1 /*
2 * Copyright (c) 2010-2014 Wind River Systems, Inc.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 /**
8 * @file
9 * @brief Kernel initialization module
10 *
11 * This module contains routines that are used to initialize the kernel.
12 */
13
14 #include <offsets_short.h>
15 #include <zephyr/kernel.h>
16 #include <zephyr/sys/printk.h>
17 #include <zephyr/debug/stack.h>
18 #include <zephyr/random/random.h>
19 #include <zephyr/linker/sections.h>
20 #include <zephyr/toolchain.h>
21 #include <zephyr/kernel_structs.h>
22 #include <zephyr/device.h>
23 #include <zephyr/init.h>
24 #include <zephyr/linker/linker-defs.h>
25 #include <ksched.h>
26 #include <string.h>
27 #include <zephyr/sys/dlist.h>
28 #include <kernel_internal.h>
29 #include <zephyr/drivers/entropy.h>
30 #include <zephyr/logging/log_ctrl.h>
31 #include <zephyr/tracing/tracing.h>
32 #include <stdbool.h>
33 #include <zephyr/debug/gcov.h>
34 #include <kswap.h>
35 #include <zephyr/timing/timing.h>
36 #include <zephyr/logging/log.h>
37 #include <zephyr/pm/device_runtime.h>
38 LOG_MODULE_REGISTER(os, CONFIG_KERNEL_LOG_LEVEL);
39
40 BUILD_ASSERT(CONFIG_MP_NUM_CPUS == CONFIG_MP_MAX_NUM_CPUS,
41 "CONFIG_MP_NUM_CPUS and CONFIG_MP_MAX_NUM_CPUS need to be set the same");
42
43 /* the only struct z_kernel instance */
44 __pinned_bss
45 struct z_kernel _kernel;
46
47 __pinned_bss
48 atomic_t _cpus_active;
49
50 /* init/main and idle threads */
51 K_THREAD_PINNED_STACK_DEFINE(z_main_stack, CONFIG_MAIN_STACK_SIZE);
52 struct k_thread z_main_thread;
53
54 #ifdef CONFIG_MULTITHREADING
55 __pinned_bss
56 struct k_thread z_idle_threads[CONFIG_MP_MAX_NUM_CPUS];
57
58 static K_KERNEL_PINNED_STACK_ARRAY_DEFINE(z_idle_stacks,
59 CONFIG_MP_MAX_NUM_CPUS,
60 CONFIG_IDLE_STACK_SIZE);
61 #endif /* CONFIG_MULTITHREADING */
62
63 extern const struct init_entry __init_start[];
64 extern const struct init_entry __init_EARLY_start[];
65 extern const struct init_entry __init_PRE_KERNEL_1_start[];
66 extern const struct init_entry __init_PRE_KERNEL_2_start[];
67 extern const struct init_entry __init_POST_KERNEL_start[];
68 extern const struct init_entry __init_APPLICATION_start[];
69 extern const struct init_entry __init_end[];
70
71 enum init_level {
72 INIT_LEVEL_EARLY = 0,
73 INIT_LEVEL_PRE_KERNEL_1,
74 INIT_LEVEL_PRE_KERNEL_2,
75 INIT_LEVEL_POST_KERNEL,
76 INIT_LEVEL_APPLICATION,
77 #ifdef CONFIG_SMP
78 INIT_LEVEL_SMP,
79 #endif
80 };
81
82 #ifdef CONFIG_SMP
83 extern const struct init_entry __init_SMP_start[];
84 #endif
85
86 /*
87 * storage space for the interrupt stack
88 *
89 * Note: This area is used as the system stack during kernel initialization,
90 * since the kernel hasn't yet set up its own stack areas. The dual purposing
91 * of this area is safe since interrupts are disabled until the kernel context
92 * switches to the init thread.
93 */
94 K_KERNEL_PINNED_STACK_ARRAY_DEFINE(z_interrupt_stacks,
95 CONFIG_MP_MAX_NUM_CPUS,
96 CONFIG_ISR_STACK_SIZE);
97
98 extern void idle(void *unused1, void *unused2, void *unused3);
99
100 #ifdef CONFIG_OBJ_CORE_SYSTEM
101 static struct k_obj_type obj_type_cpu;
102 static struct k_obj_type obj_type_kernel;
103
104 #ifdef CONFIG_OBJ_CORE_STATS_SYSTEM
105 static struct k_obj_core_stats_desc cpu_stats_desc = {
106 .raw_size = sizeof(struct k_cycle_stats),
107 .query_size = sizeof(struct k_thread_runtime_stats),
108 .raw = z_cpu_stats_raw,
109 .query = z_cpu_stats_query,
110 .reset = NULL,
111 .disable = NULL,
112 .enable = NULL,
113 };
114
115 static struct k_obj_core_stats_desc kernel_stats_desc = {
116 .raw_size = sizeof(struct k_cycle_stats) * CONFIG_MP_MAX_NUM_CPUS,
117 .query_size = sizeof(struct k_thread_runtime_stats),
118 .raw = z_kernel_stats_raw,
119 .query = z_kernel_stats_query,
120 .reset = NULL,
121 .disable = NULL,
122 .enable = NULL,
123 };
124 #endif
125 #endif
126
127 /* LCOV_EXCL_START
128 *
129 * This code is called so early in the boot process that code coverage
130 * doesn't work properly. In addition, not all arches call this code,
131 * some like x86 do this with optimized assembly
132 */
133
134 /**
135 * @brief equivalent of memset() for early boot usage
136 *
137 * Architectures that can't safely use the regular (optimized) memset very
138 * early during boot because e.g. hardware isn't yet sufficiently initialized
139 * may override this with their own safe implementation.
140 */
141 __boot_func
z_early_memset(void * dst,int c,size_t n)142 void __weak z_early_memset(void *dst, int c, size_t n)
143 {
144 (void) memset(dst, c, n);
145 }
146
147 /**
148 * @brief equivalent of memcpy() for early boot usage
149 *
150 * Architectures that can't safely use the regular (optimized) memcpy very
151 * early during boot because e.g. hardware isn't yet sufficiently initialized
152 * may override this with their own safe implementation.
153 */
154 __boot_func
z_early_memcpy(void * dst,const void * src,size_t n)155 void __weak z_early_memcpy(void *dst, const void *src, size_t n)
156 {
157 (void) memcpy(dst, src, n);
158 }
159
160 /**
161 * @brief Clear BSS
162 *
163 * This routine clears the BSS region, so all bytes are 0.
164 */
165 __boot_func
z_bss_zero(void)166 void z_bss_zero(void)
167 {
168 if (IS_ENABLED(CONFIG_SKIP_BSS_CLEAR)) {
169 return;
170 }
171
172 z_early_memset(__bss_start, 0, __bss_end - __bss_start);
173 #if DT_NODE_HAS_STATUS(DT_CHOSEN(zephyr_ccm), okay)
174 z_early_memset(&__ccm_bss_start, 0,
175 (uintptr_t) &__ccm_bss_end
176 - (uintptr_t) &__ccm_bss_start);
177 #endif
178 #if DT_NODE_HAS_STATUS(DT_CHOSEN(zephyr_dtcm), okay)
179 z_early_memset(&__dtcm_bss_start, 0,
180 (uintptr_t) &__dtcm_bss_end
181 - (uintptr_t) &__dtcm_bss_start);
182 #endif
183 #if DT_NODE_HAS_STATUS(DT_CHOSEN(zephyr_ocm), okay)
184 z_early_memset(&__ocm_bss_start, 0,
185 (uintptr_t) &__ocm_bss_end
186 - (uintptr_t) &__ocm_bss_start);
187 #endif
188 #ifdef CONFIG_CODE_DATA_RELOCATION
189 extern void bss_zeroing_relocation(void);
190
191 bss_zeroing_relocation();
192 #endif /* CONFIG_CODE_DATA_RELOCATION */
193 #ifdef CONFIG_COVERAGE_GCOV
194 z_early_memset(&__gcov_bss_start, 0,
195 ((uintptr_t) &__gcov_bss_end - (uintptr_t) &__gcov_bss_start));
196 #endif
197 }
198
199 #ifdef CONFIG_LINKER_USE_BOOT_SECTION
200 /**
201 * @brief Clear BSS within the bot region
202 *
203 * This routine clears the BSS within the boot region.
204 * This is separate from z_bss_zero() as boot region may
205 * contain symbols required for the boot process before
206 * paging is initialized.
207 */
208 __boot_func
z_bss_zero_boot(void)209 void z_bss_zero_boot(void)
210 {
211 z_early_memset(&lnkr_boot_bss_start, 0,
212 (uintptr_t)&lnkr_boot_bss_end
213 - (uintptr_t)&lnkr_boot_bss_start);
214 }
215 #endif /* CONFIG_LINKER_USE_BOOT_SECTION */
216
217 #ifdef CONFIG_LINKER_USE_PINNED_SECTION
218 /**
219 * @brief Clear BSS within the pinned region
220 *
221 * This routine clears the BSS within the pinned region.
222 * This is separate from z_bss_zero() as pinned region may
223 * contain symbols required for the boot process before
224 * paging is initialized.
225 */
226 #ifdef CONFIG_LINKER_USE_BOOT_SECTION
227 __boot_func
228 #else
229 __pinned_func
230 #endif
z_bss_zero_pinned(void)231 void z_bss_zero_pinned(void)
232 {
233 z_early_memset(&lnkr_pinned_bss_start, 0,
234 (uintptr_t)&lnkr_pinned_bss_end
235 - (uintptr_t)&lnkr_pinned_bss_start);
236 }
237 #endif /* CONFIG_LINKER_USE_PINNED_SECTION */
238
239 #ifdef CONFIG_STACK_CANARIES
240 #ifdef CONFIG_STACK_CANARIES_TLS
241 extern __thread volatile uintptr_t __stack_chk_guard;
242 #else
243 extern volatile uintptr_t __stack_chk_guard;
244 #endif
245 #endif /* CONFIG_STACK_CANARIES */
246
247 /* LCOV_EXCL_STOP */
248
249 __pinned_bss
250 bool z_sys_post_kernel;
251
252 /**
253 * @brief Execute all the init entry initialization functions at a given level
254 *
255 * @details Invokes the initialization routine for each init entry object
256 * created by the INIT_ENTRY_DEFINE() macro using the specified level.
257 * The linker script places the init entry objects in memory in the order
258 * they need to be invoked, with symbols indicating where one level leaves
259 * off and the next one begins.
260 *
261 * @param level init level to run.
262 */
z_sys_init_run_level(enum init_level level)263 static void z_sys_init_run_level(enum init_level level)
264 {
265 static const struct init_entry *levels[] = {
266 __init_EARLY_start,
267 __init_PRE_KERNEL_1_start,
268 __init_PRE_KERNEL_2_start,
269 __init_POST_KERNEL_start,
270 __init_APPLICATION_start,
271 #ifdef CONFIG_SMP
272 __init_SMP_start,
273 #endif
274 /* End marker */
275 __init_end,
276 };
277 const struct init_entry *entry;
278
279 for (entry = levels[level]; entry < levels[level+1]; entry++) {
280 const struct device *dev = entry->dev;
281
282 if (dev != NULL) {
283 int rc = 0;
284
285 if (entry->init_fn.dev != NULL) {
286 rc = entry->init_fn.dev(dev);
287 /* Mark device initialized. If initialization
288 * failed, record the error condition.
289 */
290 if (rc != 0) {
291 if (rc < 0) {
292 rc = -rc;
293 }
294 if (rc > UINT8_MAX) {
295 rc = UINT8_MAX;
296 }
297 dev->state->init_res = rc;
298 }
299 }
300
301 dev->state->initialized = true;
302
303 if (rc == 0) {
304 /* Run automatic device runtime enablement */
305 (void)pm_device_runtime_auto_enable(dev);
306 }
307 } else {
308 (void)entry->init_fn.sys();
309 }
310 }
311 }
312
313 extern void boot_banner(void);
314
315 /**
316 * @brief Mainline for kernel's background thread
317 *
318 * This routine completes kernel initialization by invoking the remaining
319 * init functions, then invokes application's main() routine.
320 */
321 __boot_func
bg_thread_main(void * unused1,void * unused2,void * unused3)322 static void bg_thread_main(void *unused1, void *unused2, void *unused3)
323 {
324 ARG_UNUSED(unused1);
325 ARG_UNUSED(unused2);
326 ARG_UNUSED(unused3);
327
328 #ifdef CONFIG_MMU
329 /* Invoked here such that backing store or eviction algorithms may
330 * initialize kernel objects, and that all POST_KERNEL and later tasks
331 * may perform memory management tasks (except for z_phys_map() which
332 * is allowed at any time)
333 */
334 z_mem_manage_init();
335 #endif /* CONFIG_MMU */
336 z_sys_post_kernel = true;
337
338 z_sys_init_run_level(INIT_LEVEL_POST_KERNEL);
339 #if CONFIG_STACK_POINTER_RANDOM
340 z_stack_adjust_initialized = 1;
341 #endif
342 boot_banner();
343
344 #if defined(CONFIG_CPP)
345 void z_cpp_init_static(void);
346 z_cpp_init_static();
347 #endif
348
349 /* Final init level before app starts */
350 z_sys_init_run_level(INIT_LEVEL_APPLICATION);
351
352 z_init_static_threads();
353
354 #ifdef CONFIG_KERNEL_COHERENCE
355 __ASSERT_NO_MSG(arch_mem_coherent(&_kernel));
356 #endif
357
358 #ifdef CONFIG_SMP
359 if (!IS_ENABLED(CONFIG_SMP_BOOT_DELAY)) {
360 z_smp_init();
361 }
362 z_sys_init_run_level(INIT_LEVEL_SMP);
363 #endif
364
365 #ifdef CONFIG_MMU
366 z_mem_manage_boot_finish();
367 #endif /* CONFIG_MMU */
368
369 extern int main(void);
370
371 (void)main();
372
373 /* Mark nonessential since main() has no more work to do */
374 z_main_thread.base.user_options &= ~K_ESSENTIAL;
375
376 #ifdef CONFIG_COVERAGE_DUMP
377 /* Dump coverage data once the main() has exited. */
378 gcov_coverage_dump();
379 #endif
380 } /* LCOV_EXCL_LINE ... because we just dumped final coverage data */
381
382 #if defined(CONFIG_MULTITHREADING)
383 __boot_func
init_idle_thread(int i)384 static void init_idle_thread(int i)
385 {
386 struct k_thread *thread = &z_idle_threads[i];
387 k_thread_stack_t *stack = z_idle_stacks[i];
388
389 #ifdef CONFIG_THREAD_NAME
390
391 #if CONFIG_MP_MAX_NUM_CPUS > 1
392 char tname[8];
393 snprintk(tname, 8, "idle %02d", i);
394 #else
395 char *tname = "idle";
396 #endif
397
398 #else
399 char *tname = NULL;
400 #endif /* CONFIG_THREAD_NAME */
401
402 z_setup_new_thread(thread, stack,
403 CONFIG_IDLE_STACK_SIZE, idle, &_kernel.cpus[i],
404 NULL, NULL, K_IDLE_PRIO, K_ESSENTIAL,
405 tname);
406 z_mark_thread_as_started(thread);
407
408 #ifdef CONFIG_SMP
409 thread->base.is_idle = 1U;
410 #endif
411 }
412
z_init_cpu(int id)413 void z_init_cpu(int id)
414 {
415 init_idle_thread(id);
416 _kernel.cpus[id].idle_thread = &z_idle_threads[id];
417 _kernel.cpus[id].id = id;
418 _kernel.cpus[id].irq_stack =
419 (Z_KERNEL_STACK_BUFFER(z_interrupt_stacks[id]) +
420 K_KERNEL_STACK_SIZEOF(z_interrupt_stacks[id]));
421 #ifdef CONFIG_SCHED_THREAD_USAGE_ALL
422 _kernel.cpus[id].usage = &_kernel.usage[id];
423 _kernel.cpus[id].usage->track_usage =
424 CONFIG_SCHED_THREAD_USAGE_AUTO_ENABLE;
425 #endif
426
427 /*
428 * Increment number of CPUs active. The pm subsystem
429 * will keep track of this from here.
430 */
431 atomic_inc(&_cpus_active);
432
433 #ifdef CONFIG_OBJ_CORE_SYSTEM
434 k_obj_core_init_and_link(K_OBJ_CORE(&_kernel.cpus[id]), &obj_type_cpu);
435 #ifdef CONFIG_OBJ_CORE_STATS_SYSTEM
436 k_obj_core_stats_register(K_OBJ_CORE(&_kernel.cpus[id]),
437 _kernel.cpus[id].usage,
438 sizeof(struct k_cycle_stats));
439 #endif
440 #endif
441 }
442
443 /**
444 *
445 * @brief Initializes kernel data structures
446 *
447 * This routine initializes various kernel data structures, including
448 * the init and idle threads and any architecture-specific initialization.
449 *
450 * Note that all fields of "_kernel" are set to zero on entry, which may
451 * be all the initialization many of them require.
452 *
453 * @return initial stack pointer for the main thread
454 */
455 __boot_func
prepare_multithreading(void)456 static char *prepare_multithreading(void)
457 {
458 char *stack_ptr;
459
460 /* _kernel.ready_q is all zeroes */
461 z_sched_init();
462
463 #ifndef CONFIG_SMP
464 /*
465 * prime the cache with the main thread since:
466 *
467 * - the cache can never be NULL
468 * - the main thread will be the one to run first
469 * - no other thread is initialized yet and thus their priority fields
470 * contain garbage, which would prevent the cache loading algorithm
471 * to work as intended
472 */
473 _kernel.ready_q.cache = &z_main_thread;
474 #endif
475 stack_ptr = z_setup_new_thread(&z_main_thread, z_main_stack,
476 CONFIG_MAIN_STACK_SIZE, bg_thread_main,
477 NULL, NULL, NULL,
478 CONFIG_MAIN_THREAD_PRIORITY,
479 K_ESSENTIAL, "main");
480 z_mark_thread_as_started(&z_main_thread);
481 z_ready_thread(&z_main_thread);
482
483 z_init_cpu(0);
484
485 return stack_ptr;
486 }
487
488 __boot_func
switch_to_main_thread(char * stack_ptr)489 static FUNC_NORETURN void switch_to_main_thread(char *stack_ptr)
490 {
491 #ifdef CONFIG_ARCH_HAS_CUSTOM_SWAP_TO_MAIN
492 arch_switch_to_main_thread(&z_main_thread, stack_ptr, bg_thread_main);
493 #else
494 ARG_UNUSED(stack_ptr);
495 /*
496 * Context switch to main task (entry function is _main()): the
497 * current fake thread is not on a wait queue or ready queue, so it
498 * will never be rescheduled in.
499 */
500 z_swap_unlocked();
501 #endif
502 CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
503 }
504 #endif /* CONFIG_MULTITHREADING */
505
506 __boot_func
z_early_rand_get(uint8_t * buf,size_t length)507 void __weak z_early_rand_get(uint8_t *buf, size_t length)
508 {
509 static uint64_t state = (uint64_t)CONFIG_TIMER_RANDOM_INITIAL_STATE;
510 int rc;
511
512 #ifdef CONFIG_ENTROPY_HAS_DRIVER
513 const struct device *const entropy = DEVICE_DT_GET_OR_NULL(DT_CHOSEN(zephyr_entropy));
514
515 if ((entropy != NULL) && device_is_ready(entropy)) {
516 /* Try to see if driver provides an ISR-specific API */
517 rc = entropy_get_entropy_isr(entropy, buf, length, ENTROPY_BUSYWAIT);
518 if (rc > 0) {
519 length -= rc;
520 buf += rc;
521 }
522 }
523 #endif
524
525 while (length > 0) {
526 uint32_t val;
527
528 state = state + k_cycle_get_32();
529 state = state * 2862933555777941757ULL + 3037000493ULL;
530 val = (uint32_t)(state >> 32);
531 rc = MIN(length, sizeof(val));
532 z_early_memcpy((void *)buf, &val, rc);
533
534 length -= rc;
535 buf += rc;
536 }
537 }
538
539 /**
540 *
541 * @brief Initialize kernel
542 *
543 * This routine is invoked when the system is ready to run C code. The
544 * processor must be running in 32-bit mode, and the BSS must have been
545 * cleared/zeroed.
546 *
547 * @return Does not return
548 */
549 __boot_func
550 FUNC_NO_STACK_PROTECTOR
z_cstart(void)551 FUNC_NORETURN void z_cstart(void)
552 {
553 /* gcov hook needed to get the coverage report.*/
554 gcov_static_init();
555
556 /* initialize early init calls */
557 z_sys_init_run_level(INIT_LEVEL_EARLY);
558
559 /* perform any architecture-specific initialization */
560 arch_kernel_init();
561
562 LOG_CORE_INIT();
563
564 #if defined(CONFIG_MULTITHREADING)
565 /* Note: The z_ready_thread() call in prepare_multithreading() requires
566 * a dummy thread even if CONFIG_ARCH_HAS_CUSTOM_SWAP_TO_MAIN=y
567 */
568 struct k_thread dummy_thread;
569
570 z_dummy_thread_init(&dummy_thread);
571 #endif
572 /* do any necessary initialization of static devices */
573 z_device_state_init();
574
575 /* perform basic hardware initialization */
576 z_sys_init_run_level(INIT_LEVEL_PRE_KERNEL_1);
577 z_sys_init_run_level(INIT_LEVEL_PRE_KERNEL_2);
578
579 #ifdef CONFIG_STACK_CANARIES
580 uintptr_t stack_guard;
581
582 z_early_rand_get((uint8_t *)&stack_guard, sizeof(stack_guard));
583 __stack_chk_guard = stack_guard;
584 __stack_chk_guard <<= 8;
585 #endif /* CONFIG_STACK_CANARIES */
586
587 #ifdef CONFIG_TIMING_FUNCTIONS_NEED_AT_BOOT
588 timing_init();
589 timing_start();
590 #endif
591
592 #ifdef CONFIG_MULTITHREADING
593 switch_to_main_thread(prepare_multithreading());
594 #else
595 #ifdef ARCH_SWITCH_TO_MAIN_NO_MULTITHREADING
596 /* Custom ARCH-specific routine to switch to main()
597 * in the case of no multi-threading.
598 */
599 ARCH_SWITCH_TO_MAIN_NO_MULTITHREADING(bg_thread_main,
600 NULL, NULL, NULL);
601 #else
602 bg_thread_main(NULL, NULL, NULL);
603
604 /* LCOV_EXCL_START
605 * We've already dumped coverage data at this point.
606 */
607 irq_lock();
608 while (true) {
609 }
610 /* LCOV_EXCL_STOP */
611 #endif
612 #endif /* CONFIG_MULTITHREADING */
613
614 /*
615 * Compiler can't tell that the above routines won't return and issues
616 * a warning unless we explicitly tell it that control never gets this
617 * far.
618 */
619
620 CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
621 }
622
623 #ifdef CONFIG_OBJ_CORE_SYSTEM
init_cpu_obj_core_list(void)624 static int init_cpu_obj_core_list(void)
625 {
626 /* Initialize CPU object type */
627
628 z_obj_type_init(&obj_type_cpu, K_OBJ_TYPE_CPU_ID,
629 offsetof(struct _cpu, obj_core));
630
631 #ifdef CONFIG_OBJ_CORE_STATS_SYSTEM
632 k_obj_type_stats_init(&obj_type_cpu, &cpu_stats_desc);
633 #endif
634
635 return 0;
636 }
637
init_kernel_obj_core_list(void)638 static int init_kernel_obj_core_list(void)
639 {
640 /* Initialize kernel object type */
641
642 z_obj_type_init(&obj_type_kernel, K_OBJ_TYPE_KERNEL_ID,
643 offsetof(struct z_kernel, obj_core));
644
645 #ifdef CONFIG_OBJ_CORE_STATS_SYSTEM
646 k_obj_type_stats_init(&obj_type_kernel, &kernel_stats_desc);
647 #endif
648
649 k_obj_core_init_and_link(K_OBJ_CORE(&_kernel), &obj_type_kernel);
650 #ifdef CONFIG_OBJ_CORE_STATS_SYSTEM
651 k_obj_core_stats_register(K_OBJ_CORE(&_kernel), _kernel.usage,
652 sizeof(_kernel.usage));
653 #endif
654
655 return 0;
656 }
657
658 SYS_INIT(init_cpu_obj_core_list, PRE_KERNEL_1,
659 CONFIG_KERNEL_INIT_PRIORITY_OBJECTS);
660
661 SYS_INIT(init_kernel_obj_core_list, PRE_KERNEL_1,
662 CONFIG_KERNEL_INIT_PRIORITY_OBJECTS);
663 #endif
664