1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/init/main.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 *
7 * GK 2/5/95 - Changed to support mounting root fs via NFS
8 * Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96
9 * Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96
10 * Simplified starting of init: Michael A. Griffith <grif@acm.org>
11 */
12
13 #define DEBUG /* Enable initcall_debug */
14
15 #include <linux/types.h>
16 #include <linux/extable.h>
17 #include <linux/module.h>
18 #include <linux/proc_fs.h>
19 #include <linux/binfmts.h>
20 #include <linux/kernel.h>
21 #include <linux/syscalls.h>
22 #include <linux/stackprotector.h>
23 #include <linux/string.h>
24 #include <linux/ctype.h>
25 #include <linux/delay.h>
26 #include <linux/ioport.h>
27 #include <linux/init.h>
28 #include <linux/initrd.h>
29 #include <linux/memblock.h>
30 #include <linux/acpi.h>
31 #include <linux/bootconfig.h>
32 #include <linux/console.h>
33 #include <linux/nmi.h>
34 #include <linux/percpu.h>
35 #include <linux/kmod.h>
36 #include <linux/kprobes.h>
37 #include <linux/vmalloc.h>
38 #include <linux/kernel_stat.h>
39 #include <linux/start_kernel.h>
40 #include <linux/security.h>
41 #include <linux/smp.h>
42 #include <linux/profile.h>
43 #include <linux/kfence.h>
44 #include <linux/rcupdate.h>
45 #include <linux/moduleparam.h>
46 #include <linux/kallsyms.h>
47 #include <linux/writeback.h>
48 #include <linux/cpu.h>
49 #include <linux/cpuset.h>
50 #include <linux/cgroup.h>
51 #include <linux/efi.h>
52 #include <linux/tick.h>
53 #include <linux/sched/isolation.h>
54 #include <linux/interrupt.h>
55 #include <linux/taskstats_kern.h>
56 #include <linux/delayacct.h>
57 #include <linux/unistd.h>
58 #include <linux/utsname.h>
59 #include <linux/rmap.h>
60 #include <linux/mempolicy.h>
61 #include <linux/key.h>
62 #include <linux/buffer_head.h>
63 #include <linux/page_ext.h>
64 #include <linux/debug_locks.h>
65 #include <linux/debugobjects.h>
66 #include <linux/lockdep.h>
67 #include <linux/kmemleak.h>
68 #include <linux/padata.h>
69 #include <linux/pid_namespace.h>
70 #include <linux/device/driver.h>
71 #include <linux/kthread.h>
72 #include <linux/sched.h>
73 #include <linux/sched/init.h>
74 #include <linux/signal.h>
75 #include <linux/idr.h>
76 #include <linux/kgdb.h>
77 #include <linux/ftrace.h>
78 #include <linux/async.h>
79 #include <linux/sfi.h>
80 #include <linux/shmem_fs.h>
81 #include <linux/slab.h>
82 #include <linux/perf_event.h>
83 #include <linux/ptrace.h>
84 #include <linux/pti.h>
85 #include <linux/blkdev.h>
86 #include <linux/elevator.h>
87 #include <linux/sched/clock.h>
88 #include <linux/sched/task.h>
89 #include <linux/sched/task_stack.h>
90 #include <linux/context_tracking.h>
91 #include <linux/random.h>
92 #include <linux/list.h>
93 #include <linux/integrity.h>
94 #include <linux/proc_ns.h>
95 #include <linux/io.h>
96 #include <linux/cache.h>
97 #include <linux/rodata_test.h>
98 #include <linux/jump_label.h>
99 #include <linux/mem_encrypt.h>
100 #include <linux/kcsan.h>
101 #include <linux/init_syscalls.h>
102 #include <linux/stackdepot.h>
103
104 #include <asm/io.h>
105 #include <asm/bugs.h>
106 #include <asm/setup.h>
107 #include <asm/sections.h>
108 #include <asm/cacheflush.h>
109
110 #define CREATE_TRACE_POINTS
111 #include <trace/events/initcall.h>
112
113 #include <kunit/test.h>
114
115 static int kernel_init(void *);
116
117 extern void init_IRQ(void);
118 extern void radix_tree_init(void);
119
120 /*
121 * Debug helper: via this flag we know that we are in 'early bootup code'
122 * where only the boot processor is running with IRQ disabled. This means
123 * two things - IRQ must not be enabled before the flag is cleared and some
124 * operations which are not allowed with IRQ disabled are allowed while the
125 * flag is set.
126 */
127 bool early_boot_irqs_disabled __read_mostly;
128
129 enum system_states system_state __read_mostly;
130 EXPORT_SYMBOL(system_state);
131
132 /*
133 * Boot command-line arguments
134 */
135 #define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT
136 #define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT
137
138 extern void time_init(void);
139 /* Default late time init is NULL. archs can override this later. */
140 void (*__initdata late_time_init)(void);
141
142 /* Untouched command line saved by arch-specific code. */
143 char __initdata boot_command_line[COMMAND_LINE_SIZE];
144 /* Untouched saved command line (eg. for /proc) */
145 char *saved_command_line;
146 /* Command line for parameter parsing */
147 static char *static_command_line;
148 /* Untouched extra command line */
149 static char *extra_command_line;
150 /* Extra init arguments */
151 static char *extra_init_args;
152
153 #ifdef CONFIG_BOOT_CONFIG
154 /* Is bootconfig on command line? */
155 static bool bootconfig_found;
156 static bool initargs_found;
157 #else
158 # define bootconfig_found false
159 # define initargs_found false
160 #endif
161
162 static char *execute_command;
163 static char *ramdisk_execute_command = "/init";
164
165 /*
166 * Used to generate warnings if static_key manipulation functions are used
167 * before jump_label_init is called.
168 */
169 bool static_key_initialized __read_mostly;
170 EXPORT_SYMBOL_GPL(static_key_initialized);
171
172 /*
173 * If set, this is an indication to the drivers that reset the underlying
174 * device before going ahead with the initialization otherwise driver might
175 * rely on the BIOS and skip the reset operation.
176 *
177 * This is useful if kernel is booting in an unreliable environment.
178 * For ex. kdump situation where previous kernel has crashed, BIOS has been
179 * skipped and devices will be in unknown state.
180 */
181 unsigned int reset_devices;
182 EXPORT_SYMBOL(reset_devices);
183
set_reset_devices(char * str)184 static int __init set_reset_devices(char *str)
185 {
186 reset_devices = 1;
187 return 1;
188 }
189
190 __setup("reset_devices", set_reset_devices);
191
192 static const char *argv_init[MAX_INIT_ARGS+2] = { "init", NULL, };
193 const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
194 static const char *panic_later, *panic_param;
195
196 extern const struct obs_kernel_param __setup_start[], __setup_end[];
197
obsolete_checksetup(char * line)198 static bool __init obsolete_checksetup(char *line)
199 {
200 const struct obs_kernel_param *p;
201 bool had_early_param = false;
202
203 p = __setup_start;
204 do {
205 int n = strlen(p->str);
206 if (parameqn(line, p->str, n)) {
207 if (p->early) {
208 /* Already done in parse_early_param?
209 * (Needs exact match on param part).
210 * Keep iterating, as we can have early
211 * params and __setups of same names 8( */
212 if (line[n] == '\0' || line[n] == '=')
213 had_early_param = true;
214 } else if (!p->setup_func) {
215 pr_warn("Parameter %s is obsolete, ignored\n",
216 p->str);
217 return true;
218 } else if (p->setup_func(line + n))
219 return true;
220 }
221 p++;
222 } while (p < __setup_end);
223
224 return had_early_param;
225 }
226
227 /*
228 * This should be approx 2 Bo*oMips to start (note initial shift), and will
229 * still work even if initially too large, it will just take slightly longer
230 */
231 unsigned long loops_per_jiffy = (1<<12);
232 EXPORT_SYMBOL(loops_per_jiffy);
233
debug_kernel(char * str)234 static int __init debug_kernel(char *str)
235 {
236 console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
237 return 0;
238 }
239
quiet_kernel(char * str)240 static int __init quiet_kernel(char *str)
241 {
242 console_loglevel = CONSOLE_LOGLEVEL_QUIET;
243 return 0;
244 }
245
246 early_param("debug", debug_kernel);
247 early_param("quiet", quiet_kernel);
248
loglevel(char * str)249 static int __init loglevel(char *str)
250 {
251 int newlevel;
252
253 /*
254 * Only update loglevel value when a correct setting was passed,
255 * to prevent blind crashes (when loglevel being set to 0) that
256 * are quite hard to debug
257 */
258 if (get_option(&str, &newlevel)) {
259 console_loglevel = newlevel;
260 return 0;
261 }
262
263 return -EINVAL;
264 }
265
266 early_param("loglevel", loglevel);
267
268 #ifdef CONFIG_BLK_DEV_INITRD
get_boot_config_from_initrd(u32 * _size,u32 * _csum)269 static void * __init get_boot_config_from_initrd(u32 *_size, u32 *_csum)
270 {
271 u32 size, csum;
272 char *data;
273 u32 *hdr;
274 int i;
275
276 if (!initrd_end)
277 return NULL;
278
279 data = (char *)initrd_end - BOOTCONFIG_MAGIC_LEN;
280 /*
281 * Since Grub may align the size of initrd to 4, we must
282 * check the preceding 3 bytes as well.
283 */
284 for (i = 0; i < 4; i++) {
285 if (!memcmp(data, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN))
286 goto found;
287 data--;
288 }
289 return NULL;
290
291 found:
292 hdr = (u32 *)(data - 8);
293 size = le32_to_cpu(hdr[0]);
294 csum = le32_to_cpu(hdr[1]);
295
296 data = ((void *)hdr) - size;
297 if ((unsigned long)data < initrd_start) {
298 pr_err("bootconfig size %d is greater than initrd size %ld\n",
299 size, initrd_end - initrd_start);
300 return NULL;
301 }
302
303 /* Remove bootconfig from initramfs/initrd */
304 initrd_end = (unsigned long)data;
305 if (_size)
306 *_size = size;
307 if (_csum)
308 *_csum = csum;
309
310 return data;
311 }
312 #else
get_boot_config_from_initrd(u32 * _size,u32 * _csum)313 static void * __init get_boot_config_from_initrd(u32 *_size, u32 *_csum)
314 {
315 return NULL;
316 }
317 #endif
318
319 #ifdef CONFIG_BOOT_CONFIG
320
321 static char xbc_namebuf[XBC_KEYLEN_MAX] __initdata;
322
323 #define rest(dst, end) ((end) > (dst) ? (end) - (dst) : 0)
324
xbc_snprint_cmdline(char * buf,size_t size,struct xbc_node * root)325 static int __init xbc_snprint_cmdline(char *buf, size_t size,
326 struct xbc_node *root)
327 {
328 struct xbc_node *knode, *vnode;
329 char *end = buf + size;
330 const char *val;
331 int ret;
332
333 xbc_node_for_each_key_value(root, knode, val) {
334 ret = xbc_node_compose_key_after(root, knode,
335 xbc_namebuf, XBC_KEYLEN_MAX);
336 if (ret < 0)
337 return ret;
338
339 vnode = xbc_node_get_child(knode);
340 if (!vnode) {
341 ret = snprintf(buf, rest(buf, end), "%s ", xbc_namebuf);
342 if (ret < 0)
343 return ret;
344 buf += ret;
345 continue;
346 }
347 xbc_array_for_each_value(vnode, val) {
348 ret = snprintf(buf, rest(buf, end), "%s=\"%s\" ",
349 xbc_namebuf, val);
350 if (ret < 0)
351 return ret;
352 buf += ret;
353 }
354 }
355
356 return buf - (end - size);
357 }
358 #undef rest
359
360 /* Make an extra command line under given key word */
xbc_make_cmdline(const char * key)361 static char * __init xbc_make_cmdline(const char *key)
362 {
363 struct xbc_node *root;
364 char *new_cmdline;
365 int ret, len = 0;
366
367 root = xbc_find_node(key);
368 if (!root)
369 return NULL;
370
371 /* Count required buffer size */
372 len = xbc_snprint_cmdline(NULL, 0, root);
373 if (len <= 0)
374 return NULL;
375
376 new_cmdline = memblock_alloc(len + 1, SMP_CACHE_BYTES);
377 if (!new_cmdline) {
378 pr_err("Failed to allocate memory for extra kernel cmdline.\n");
379 return NULL;
380 }
381
382 ret = xbc_snprint_cmdline(new_cmdline, len + 1, root);
383 if (ret < 0 || ret > len) {
384 pr_err("Failed to print extra kernel cmdline.\n");
385 memblock_free(__pa(new_cmdline), len + 1);
386 return NULL;
387 }
388
389 return new_cmdline;
390 }
391
bootconfig_params(char * param,char * val,const char * unused,void * arg)392 static int __init bootconfig_params(char *param, char *val,
393 const char *unused, void *arg)
394 {
395 if (strcmp(param, "bootconfig") == 0) {
396 bootconfig_found = true;
397 }
398 return 0;
399 }
400
setup_boot_config(const char * cmdline)401 static void __init setup_boot_config(const char *cmdline)
402 {
403 static char tmp_cmdline[COMMAND_LINE_SIZE] __initdata;
404 const char *msg;
405 int pos;
406 u32 size, csum;
407 char *data, *copy, *err;
408 int ret;
409
410 /* Cut out the bootconfig data even if we have no bootconfig option */
411 data = get_boot_config_from_initrd(&size, &csum);
412
413 strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
414 err = parse_args("bootconfig", tmp_cmdline, NULL, 0, 0, 0, NULL,
415 bootconfig_params);
416
417 if (IS_ERR(err) || !bootconfig_found)
418 return;
419
420 /* parse_args() stops at '--' and returns an address */
421 if (err)
422 initargs_found = true;
423
424 if (!data) {
425 pr_err("'bootconfig' found on command line, but no bootconfig found\n");
426 return;
427 }
428
429 if (size >= XBC_DATA_MAX) {
430 pr_err("bootconfig size %d greater than max size %d\n",
431 size, XBC_DATA_MAX);
432 return;
433 }
434
435 if (xbc_calc_checksum(data, size) != csum) {
436 pr_err("bootconfig checksum failed\n");
437 return;
438 }
439
440 copy = memblock_alloc(size + 1, SMP_CACHE_BYTES);
441 if (!copy) {
442 pr_err("Failed to allocate memory for bootconfig\n");
443 return;
444 }
445
446 memcpy(copy, data, size);
447 copy[size] = '\0';
448
449 ret = xbc_init(copy, &msg, &pos);
450 if (ret < 0) {
451 if (pos < 0)
452 pr_err("Failed to init bootconfig: %s.\n", msg);
453 else
454 pr_err("Failed to parse bootconfig: %s at %d.\n",
455 msg, pos);
456 } else {
457 pr_info("Load bootconfig: %d bytes %d nodes\n", size, ret);
458 /* keys starting with "kernel." are passed via cmdline */
459 extra_command_line = xbc_make_cmdline("kernel");
460 /* Also, "init." keys are init arguments */
461 extra_init_args = xbc_make_cmdline("init");
462 }
463 return;
464 }
465
466 #else
467
setup_boot_config(const char * cmdline)468 static void __init setup_boot_config(const char *cmdline)
469 {
470 /* Remove bootconfig data from initrd */
471 get_boot_config_from_initrd(NULL, NULL);
472 }
473
warn_bootconfig(char * str)474 static int __init warn_bootconfig(char *str)
475 {
476 pr_warn("WARNING: 'bootconfig' found on the kernel command line but CONFIG_BOOT_CONFIG is not set.\n");
477 return 0;
478 }
479 early_param("bootconfig", warn_bootconfig);
480
481 #endif
482
483 /* Change NUL term back to "=", to make "param" the whole string. */
repair_env_string(char * param,char * val)484 static void __init repair_env_string(char *param, char *val)
485 {
486 if (val) {
487 /* param=val or param="val"? */
488 if (val == param+strlen(param)+1)
489 val[-1] = '=';
490 else if (val == param+strlen(param)+2) {
491 val[-2] = '=';
492 memmove(val-1, val, strlen(val)+1);
493 } else
494 BUG();
495 }
496 }
497
498 /* Anything after -- gets handed straight to init. */
set_init_arg(char * param,char * val,const char * unused,void * arg)499 static int __init set_init_arg(char *param, char *val,
500 const char *unused, void *arg)
501 {
502 unsigned int i;
503
504 if (panic_later)
505 return 0;
506
507 repair_env_string(param, val);
508
509 for (i = 0; argv_init[i]; i++) {
510 if (i == MAX_INIT_ARGS) {
511 panic_later = "init";
512 panic_param = param;
513 return 0;
514 }
515 }
516 argv_init[i] = param;
517 return 0;
518 }
519
520 /*
521 * Unknown boot options get handed to init, unless they look like
522 * unused parameters (modprobe will find them in /proc/cmdline).
523 */
unknown_bootoption(char * param,char * val,const char * unused,void * arg)524 static int __init unknown_bootoption(char *param, char *val,
525 const char *unused, void *arg)
526 {
527 size_t len = strlen(param);
528
529 repair_env_string(param, val);
530
531 /* Handle obsolete-style parameters */
532 if (obsolete_checksetup(param))
533 return 0;
534
535 /* Unused module parameter. */
536 if (strnchr(param, len, '.'))
537 return 0;
538
539 if (panic_later)
540 return 0;
541
542 if (val) {
543 /* Environment option */
544 unsigned int i;
545 for (i = 0; envp_init[i]; i++) {
546 if (i == MAX_INIT_ENVS) {
547 panic_later = "env";
548 panic_param = param;
549 }
550 if (!strncmp(param, envp_init[i], len+1))
551 break;
552 }
553 envp_init[i] = param;
554 } else {
555 /* Command line option */
556 unsigned int i;
557 for (i = 0; argv_init[i]; i++) {
558 if (i == MAX_INIT_ARGS) {
559 panic_later = "init";
560 panic_param = param;
561 }
562 }
563 argv_init[i] = param;
564 }
565 return 0;
566 }
567
init_setup(char * str)568 static int __init init_setup(char *str)
569 {
570 unsigned int i;
571
572 execute_command = str;
573 /*
574 * In case LILO is going to boot us with default command line,
575 * it prepends "auto" before the whole cmdline which makes
576 * the shell think it should execute a script with such name.
577 * So we ignore all arguments entered _before_ init=... [MJ]
578 */
579 for (i = 1; i < MAX_INIT_ARGS; i++)
580 argv_init[i] = NULL;
581 return 1;
582 }
583 __setup("init=", init_setup);
584
rdinit_setup(char * str)585 static int __init rdinit_setup(char *str)
586 {
587 unsigned int i;
588
589 ramdisk_execute_command = str;
590 /* See "auto" comment in init_setup */
591 for (i = 1; i < MAX_INIT_ARGS; i++)
592 argv_init[i] = NULL;
593 return 1;
594 }
595 __setup("rdinit=", rdinit_setup);
596
597 #ifndef CONFIG_SMP
598 static const unsigned int setup_max_cpus = NR_CPUS;
setup_nr_cpu_ids(void)599 static inline void setup_nr_cpu_ids(void) { }
smp_prepare_cpus(unsigned int maxcpus)600 static inline void smp_prepare_cpus(unsigned int maxcpus) { }
601 #endif
602
603 /*
604 * We need to store the untouched command line for future reference.
605 * We also need to store the touched command line since the parameter
606 * parsing is performed in place, and we should allow a component to
607 * store reference of name/value for future reference.
608 */
setup_command_line(char * command_line)609 static void __init setup_command_line(char *command_line)
610 {
611 size_t len, xlen = 0, ilen = 0;
612
613 if (extra_command_line)
614 xlen = strlen(extra_command_line);
615 if (extra_init_args)
616 ilen = strlen(extra_init_args) + 4; /* for " -- " */
617
618 len = xlen + strlen(boot_command_line) + 1;
619
620 saved_command_line = memblock_alloc(len + ilen, SMP_CACHE_BYTES);
621 if (!saved_command_line)
622 panic("%s: Failed to allocate %zu bytes\n", __func__, len + ilen);
623
624 static_command_line = memblock_alloc(len, SMP_CACHE_BYTES);
625 if (!static_command_line)
626 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
627
628 if (xlen) {
629 /*
630 * We have to put extra_command_line before boot command
631 * lines because there could be dashes (separator of init
632 * command line) in the command lines.
633 */
634 strcpy(saved_command_line, extra_command_line);
635 strcpy(static_command_line, extra_command_line);
636 }
637 strcpy(saved_command_line + xlen, boot_command_line);
638 strcpy(static_command_line + xlen, command_line);
639
640 if (ilen) {
641 /*
642 * Append supplemental init boot args to saved_command_line
643 * so that user can check what command line options passed
644 * to init.
645 */
646 len = strlen(saved_command_line);
647 if (initargs_found) {
648 saved_command_line[len++] = ' ';
649 } else {
650 strcpy(saved_command_line + len, " -- ");
651 len += 4;
652 }
653
654 strcpy(saved_command_line + len, extra_init_args);
655 }
656 }
657
658 /*
659 * We need to finalize in a non-__init function or else race conditions
660 * between the root thread and the init thread may cause start_kernel to
661 * be reaped by free_initmem before the root thread has proceeded to
662 * cpu_idle.
663 *
664 * gcc-3.4 accidentally inlines this function, so use noinline.
665 */
666
667 static __initdata DECLARE_COMPLETION(kthreadd_done);
668
rest_init(void)669 noinline void __ref rest_init(void)
670 {
671 struct task_struct *tsk;
672 int pid;
673
674 rcu_scheduler_starting();
675 /*
676 * We need to spawn init first so that it obtains pid 1, however
677 * the init task will end up wanting to create kthreads, which, if
678 * we schedule it before we create kthreadd, will OOPS.
679 */
680 pid = kernel_thread(kernel_init, NULL, CLONE_FS);
681 /*
682 * Pin init on the boot CPU. Task migration is not properly working
683 * until sched_init_smp() has been run. It will set the allowed
684 * CPUs for init to the non isolated CPUs.
685 */
686 rcu_read_lock();
687 tsk = find_task_by_pid_ns(pid, &init_pid_ns);
688 set_cpus_allowed_ptr(tsk, cpumask_of(smp_processor_id()));
689 rcu_read_unlock();
690
691 numa_default_policy();
692 pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
693 rcu_read_lock();
694 kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
695 rcu_read_unlock();
696
697 /*
698 * Enable might_sleep() and smp_processor_id() checks.
699 * They cannot be enabled earlier because with CONFIG_PREEMPTION=y
700 * kernel_thread() would trigger might_sleep() splats. With
701 * CONFIG_PREEMPT_VOLUNTARY=y the init task might have scheduled
702 * already, but it's stuck on the kthreadd_done completion.
703 */
704 system_state = SYSTEM_SCHEDULING;
705
706 complete(&kthreadd_done);
707
708 /*
709 * The boot idle thread must execute schedule()
710 * at least once to get things moving:
711 */
712 schedule_preempt_disabled();
713 /* Call into cpu_idle with preempt disabled */
714 cpu_startup_entry(CPUHP_ONLINE);
715 }
716
717 /* Check for early params. */
do_early_param(char * param,char * val,const char * unused,void * arg)718 static int __init do_early_param(char *param, char *val,
719 const char *unused, void *arg)
720 {
721 const struct obs_kernel_param *p;
722
723 for (p = __setup_start; p < __setup_end; p++) {
724 if ((p->early && parameq(param, p->str)) ||
725 (strcmp(param, "console") == 0 &&
726 strcmp(p->str, "earlycon") == 0)
727 ) {
728 if (p->setup_func(val) != 0)
729 pr_warn("Malformed early option '%s'\n", param);
730 }
731 }
732 /* We accept everything at this stage. */
733 return 0;
734 }
735
parse_early_options(char * cmdline)736 void __init parse_early_options(char *cmdline)
737 {
738 parse_args("early options", cmdline, NULL, 0, 0, 0, NULL,
739 do_early_param);
740 }
741
742 /* Arch code calls this early on, or if not, just before other parsing. */
parse_early_param(void)743 void __init parse_early_param(void)
744 {
745 static int done __initdata;
746 static char tmp_cmdline[COMMAND_LINE_SIZE] __initdata;
747
748 if (done)
749 return;
750
751 /* All fall through to do_early_param. */
752 strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
753 parse_early_options(tmp_cmdline);
754 done = 1;
755 }
756
arch_post_acpi_subsys_init(void)757 void __init __weak arch_post_acpi_subsys_init(void) { }
758
smp_setup_processor_id(void)759 void __init __weak smp_setup_processor_id(void)
760 {
761 }
762
763 # if THREAD_SIZE >= PAGE_SIZE
thread_stack_cache_init(void)764 void __init __weak thread_stack_cache_init(void)
765 {
766 }
767 #endif
768
mem_encrypt_init(void)769 void __init __weak mem_encrypt_init(void) { }
770
poking_init(void)771 void __init __weak poking_init(void) { }
772
pgtable_cache_init(void)773 void __init __weak pgtable_cache_init(void) { }
774
775 bool initcall_debug;
776 core_param(initcall_debug, initcall_debug, bool, 0644);
777
778 #ifdef TRACEPOINTS_ENABLED
779 static void __init initcall_debug_enable(void);
780 #else
initcall_debug_enable(void)781 static inline void initcall_debug_enable(void)
782 {
783 }
784 #endif
785
786 /* Report memory auto-initialization states for this boot. */
report_meminit(void)787 static void __init report_meminit(void)
788 {
789 const char *stack;
790
791 if (IS_ENABLED(CONFIG_INIT_STACK_ALL_PATTERN))
792 stack = "all(pattern)";
793 else if (IS_ENABLED(CONFIG_INIT_STACK_ALL_ZERO))
794 stack = "all(zero)";
795 else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL))
796 stack = "byref_all(zero)";
797 else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF))
798 stack = "byref(zero)";
799 else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_USER))
800 stack = "__user(zero)";
801 else
802 stack = "off";
803
804 pr_info("mem auto-init: stack:%s, heap alloc:%s, heap free:%s\n",
805 stack, want_init_on_alloc(GFP_KERNEL) ? "on" : "off",
806 want_init_on_free() ? "on" : "off");
807 if (want_init_on_free())
808 pr_info("mem auto-init: clearing system memory may take some time...\n");
809 }
810
811 /*
812 * Set up kernel memory allocators
813 */
mm_init(void)814 static void __init mm_init(void)
815 {
816 /*
817 * page_ext requires contiguous pages,
818 * bigger than MAX_ORDER unless SPARSEMEM.
819 */
820 page_ext_init_flatmem();
821 init_mem_debugging_and_hardening();
822 kfence_alloc_pool();
823 report_meminit();
824 stack_depot_init();
825 mem_init();
826 /* page_owner must be initialized after buddy is ready */
827 page_ext_init_flatmem_late();
828 kmem_cache_init();
829 kmemleak_init();
830 pgtable_init();
831 debug_objects_mem_init();
832 vmalloc_init();
833 ioremap_huge_init();
834 /* Should be run before the first non-init thread is created */
835 init_espfix_bsp();
836 /* Should be run after espfix64 is set up. */
837 pti_init();
838 }
839
arch_call_rest_init(void)840 void __init __weak arch_call_rest_init(void)
841 {
842 rest_init();
843 }
844
start_kernel(void)845 asmlinkage __visible void __init __no_sanitize_address start_kernel(void)
846 {
847 char *command_line;
848 char *after_dashes;
849
850 set_task_stack_end_magic(&init_task);
851 smp_setup_processor_id();
852 debug_objects_early_init();
853
854 cgroup_init_early();
855
856 local_irq_disable();
857 early_boot_irqs_disabled = true;
858
859 /*
860 * Interrupts are still disabled. Do necessary setups, then
861 * enable them.
862 */
863 boot_cpu_init();
864 page_address_init();
865 pr_notice("%s", linux_banner);
866 early_security_init();
867 setup_arch(&command_line);
868 setup_boot_config(command_line);
869 setup_command_line(command_line);
870 setup_nr_cpu_ids();
871 setup_per_cpu_areas();
872 smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */
873 boot_cpu_hotplug_init();
874
875 build_all_zonelists(NULL);
876 page_alloc_init();
877
878 #ifdef CONFIG_ARCH_ROCKCHIP
879 {
880 const char *s = saved_command_line;
881 const char *e = &saved_command_line[strlen(saved_command_line)];
882 int n =
883 pr_notice("Kernel command line: %s\n", saved_command_line);
884 n -= strlen("Kernel command line: ");
885 s += n;
886 /* command line maybe too long to print one time */
887 while (n > 0 && s < e) {
888 n = pr_cont("%s\n", s);
889 s += n;
890 }
891 }
892 #else
893 pr_notice("Kernel command line: %s\n", saved_command_line);
894 #endif
895 /* parameters may set static keys */
896 jump_label_init();
897 parse_early_param();
898 after_dashes = parse_args("Booting kernel",
899 static_command_line, __start___param,
900 __stop___param - __start___param,
901 -1, -1, NULL, &unknown_bootoption);
902 if (!IS_ERR_OR_NULL(after_dashes))
903 parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
904 NULL, set_init_arg);
905 if (extra_init_args)
906 parse_args("Setting extra init args", extra_init_args,
907 NULL, 0, -1, -1, NULL, set_init_arg);
908
909 /*
910 * These use large bootmem allocations and must precede
911 * kmem_cache_init()
912 */
913 setup_log_buf(0);
914 vfs_caches_init_early();
915 sort_main_extable();
916 trap_init();
917 mm_init();
918
919 ftrace_init();
920
921 /* trace_printk can be enabled here */
922 early_trace_init();
923
924 /*
925 * Set up the scheduler prior starting any interrupts (such as the
926 * timer interrupt). Full topology setup happens at smp_init()
927 * time - but meanwhile we still have a functioning scheduler.
928 */
929 sched_init();
930
931 if (WARN(!irqs_disabled(),
932 "Interrupts were enabled *very* early, fixing it\n"))
933 local_irq_disable();
934 radix_tree_init();
935
936 /*
937 * Set up housekeeping before setting up workqueues to allow the unbound
938 * workqueue to take non-housekeeping into account.
939 */
940 housekeeping_init();
941
942 /*
943 * Allow workqueue creation and work item queueing/cancelling
944 * early. Work item execution depends on kthreads and starts after
945 * workqueue_init().
946 */
947 workqueue_init_early();
948
949 rcu_init();
950
951 /* Trace events are available after this */
952 trace_init();
953
954 if (initcall_debug)
955 initcall_debug_enable();
956
957 context_tracking_init();
958 /* init some links before init_ISA_irqs() */
959 early_irq_init();
960 init_IRQ();
961 tick_init();
962 rcu_init_nohz();
963 init_timers();
964 hrtimers_init();
965 softirq_init();
966 timekeeping_init();
967 kfence_init();
968 time_init();
969
970 /*
971 * For best initial stack canary entropy, prepare it after:
972 * - setup_arch() for any UEFI RNG entropy and boot cmdline access
973 * - timekeeping_init() for ktime entropy used in random_init()
974 * - time_init() for making random_get_entropy() work on some platforms
975 * - random_init() to initialize the RNG from from early entropy sources
976 */
977 random_init(command_line);
978 boot_init_stack_canary();
979
980 perf_event_init();
981 profile_init();
982 call_function_init();
983 WARN(!irqs_disabled(), "Interrupts were enabled early\n");
984
985 early_boot_irqs_disabled = false;
986 local_irq_enable();
987
988 kmem_cache_init_late();
989
990 /*
991 * HACK ALERT! This is early. We're enabling the console before
992 * we've done PCI setups etc, and console_init() must be aware of
993 * this. But we do want output early, in case something goes wrong.
994 */
995 console_init();
996 if (panic_later)
997 panic("Too many boot %s vars at `%s'", panic_later,
998 panic_param);
999
1000 lockdep_init();
1001
1002 /*
1003 * Need to run this when irqs are enabled, because it wants
1004 * to self-test [hard/soft]-irqs on/off lock inversion bugs
1005 * too:
1006 */
1007 locking_selftest();
1008
1009 /*
1010 * This needs to be called before any devices perform DMA
1011 * operations that might use the SWIOTLB bounce buffers. It will
1012 * mark the bounce buffers as decrypted so that their usage will
1013 * not cause "plain-text" data to be decrypted when accessed.
1014 */
1015 mem_encrypt_init();
1016
1017 #ifdef CONFIG_BLK_DEV_INITRD
1018 if (initrd_start && !initrd_below_start_ok &&
1019 page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
1020 pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n",
1021 page_to_pfn(virt_to_page((void *)initrd_start)),
1022 min_low_pfn);
1023 initrd_start = 0;
1024 }
1025 #endif
1026 setup_per_cpu_pageset();
1027 numa_policy_init();
1028 acpi_early_init();
1029 if (late_time_init)
1030 late_time_init();
1031 sched_clock_init();
1032 calibrate_delay();
1033 pid_idr_init();
1034 anon_vma_init();
1035 #ifdef CONFIG_X86
1036 if (efi_enabled(EFI_RUNTIME_SERVICES))
1037 efi_enter_virtual_mode();
1038 #endif
1039 thread_stack_cache_init();
1040 cred_init();
1041 fork_init();
1042 proc_caches_init();
1043 uts_ns_init();
1044 buffer_init();
1045 key_init();
1046 security_init();
1047 dbg_late_init();
1048 vfs_caches_init();
1049 pagecache_init();
1050 signals_init();
1051 seq_file_init();
1052 proc_root_init();
1053 nsfs_init();
1054 cpuset_init();
1055 cgroup_init();
1056 taskstats_init_early();
1057 delayacct_init();
1058
1059 poking_init();
1060 check_bugs();
1061
1062 acpi_subsystem_init();
1063 arch_post_acpi_subsys_init();
1064 sfi_init_late();
1065 kcsan_init();
1066
1067 /* Do the rest non-__init'ed, we're now alive */
1068 arch_call_rest_init();
1069
1070 prevent_tail_call_optimization();
1071 }
1072
1073 /* Call all constructor functions linked into the kernel. */
do_ctors(void)1074 static void __init do_ctors(void)
1075 {
1076 #ifdef CONFIG_CONSTRUCTORS
1077 ctor_fn_t *fn = (ctor_fn_t *) __ctors_start;
1078
1079 for (; fn < (ctor_fn_t *) __ctors_end; fn++)
1080 (*fn)();
1081 #endif
1082 }
1083
1084 #ifdef CONFIG_KALLSYMS
1085 struct blacklist_entry {
1086 struct list_head next;
1087 char *buf;
1088 };
1089
1090 static __initdata_or_module LIST_HEAD(blacklisted_initcalls);
1091
initcall_blacklist(char * str)1092 static int __init initcall_blacklist(char *str)
1093 {
1094 char *str_entry;
1095 struct blacklist_entry *entry;
1096
1097 /* str argument is a comma-separated list of functions */
1098 do {
1099 str_entry = strsep(&str, ",");
1100 if (str_entry) {
1101 pr_debug("blacklisting initcall %s\n", str_entry);
1102 entry = memblock_alloc(sizeof(*entry),
1103 SMP_CACHE_BYTES);
1104 if (!entry)
1105 panic("%s: Failed to allocate %zu bytes\n",
1106 __func__, sizeof(*entry));
1107 entry->buf = memblock_alloc(strlen(str_entry) + 1,
1108 SMP_CACHE_BYTES);
1109 if (!entry->buf)
1110 panic("%s: Failed to allocate %zu bytes\n",
1111 __func__, strlen(str_entry) + 1);
1112 strcpy(entry->buf, str_entry);
1113 list_add(&entry->next, &blacklisted_initcalls);
1114 }
1115 } while (str_entry);
1116
1117 return 1;
1118 }
1119
initcall_blacklisted(initcall_t fn)1120 static bool __init_or_module initcall_blacklisted(initcall_t fn)
1121 {
1122 struct blacklist_entry *entry;
1123 char fn_name[KSYM_SYMBOL_LEN];
1124 unsigned long addr;
1125
1126 if (list_empty(&blacklisted_initcalls))
1127 return false;
1128
1129 addr = (unsigned long) dereference_function_descriptor(fn);
1130 sprint_symbol_no_offset(fn_name, addr);
1131
1132 /*
1133 * fn will be "function_name [module_name]" where [module_name] is not
1134 * displayed for built-in init functions. Strip off the [module_name].
1135 */
1136 strreplace(fn_name, ' ', '\0');
1137
1138 list_for_each_entry(entry, &blacklisted_initcalls, next) {
1139 if (!strcmp(fn_name, entry->buf)) {
1140 pr_debug("initcall %s blacklisted\n", fn_name);
1141 return true;
1142 }
1143 }
1144
1145 return false;
1146 }
1147 #else
initcall_blacklist(char * str)1148 static int __init initcall_blacklist(char *str)
1149 {
1150 pr_warn("initcall_blacklist requires CONFIG_KALLSYMS\n");
1151 return 0;
1152 }
1153
initcall_blacklisted(initcall_t fn)1154 static bool __init_or_module initcall_blacklisted(initcall_t fn)
1155 {
1156 return false;
1157 }
1158 #endif
1159 __setup("initcall_blacklist=", initcall_blacklist);
1160
1161 static __init_or_module void
trace_initcall_start_cb(void * data,initcall_t fn)1162 trace_initcall_start_cb(void *data, initcall_t fn)
1163 {
1164 ktime_t *calltime = (ktime_t *)data;
1165
1166 printk(KERN_DEBUG "calling %pS @ %i\n", fn, task_pid_nr(current));
1167 *calltime = ktime_get();
1168 }
1169
1170 static __init_or_module void
trace_initcall_finish_cb(void * data,initcall_t fn,int ret)1171 trace_initcall_finish_cb(void *data, initcall_t fn, int ret)
1172 {
1173 ktime_t *calltime = (ktime_t *)data;
1174 ktime_t delta, rettime;
1175 unsigned long long duration;
1176
1177 rettime = ktime_get();
1178 delta = ktime_sub(rettime, *calltime);
1179 duration = (unsigned long long) ktime_to_ns(delta) >> 10;
1180 printk(KERN_DEBUG "initcall %pS returned %d after %lld usecs\n",
1181 fn, ret, duration);
1182 }
1183
1184 static ktime_t initcall_calltime;
1185
1186 #ifdef TRACEPOINTS_ENABLED
initcall_debug_enable(void)1187 static void __init initcall_debug_enable(void)
1188 {
1189 int ret;
1190
1191 ret = register_trace_initcall_start(trace_initcall_start_cb,
1192 &initcall_calltime);
1193 ret |= register_trace_initcall_finish(trace_initcall_finish_cb,
1194 &initcall_calltime);
1195 WARN(ret, "Failed to register initcall tracepoints\n");
1196 }
1197 # define do_trace_initcall_start trace_initcall_start
1198 # define do_trace_initcall_finish trace_initcall_finish
1199 #else
do_trace_initcall_start(initcall_t fn)1200 static inline void do_trace_initcall_start(initcall_t fn)
1201 {
1202 if (!initcall_debug)
1203 return;
1204 trace_initcall_start_cb(&initcall_calltime, fn);
1205 }
do_trace_initcall_finish(initcall_t fn,int ret)1206 static inline void do_trace_initcall_finish(initcall_t fn, int ret)
1207 {
1208 if (!initcall_debug)
1209 return;
1210 trace_initcall_finish_cb(&initcall_calltime, fn, ret);
1211 }
1212 #endif /* !TRACEPOINTS_ENABLED */
1213
do_one_initcall(initcall_t fn)1214 int __init_or_module do_one_initcall(initcall_t fn)
1215 {
1216 int count = preempt_count();
1217 char msgbuf[64];
1218 int ret;
1219
1220 if (initcall_blacklisted(fn))
1221 return -EPERM;
1222
1223 do_trace_initcall_start(fn);
1224 ret = fn();
1225 do_trace_initcall_finish(fn, ret);
1226
1227 msgbuf[0] = 0;
1228
1229 if (preempt_count() != count) {
1230 sprintf(msgbuf, "preemption imbalance ");
1231 preempt_count_set(count);
1232 }
1233 if (irqs_disabled()) {
1234 strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
1235 local_irq_enable();
1236 }
1237 WARN(msgbuf[0], "initcall %pS returned with %s\n", fn, msgbuf);
1238
1239 add_latent_entropy();
1240 return ret;
1241 }
1242
1243
1244 extern initcall_entry_t __initcall_start[];
1245 extern initcall_entry_t __initcall0_start[];
1246 extern initcall_entry_t __initcall1_start[];
1247 extern initcall_entry_t __initcall2_start[];
1248 extern initcall_entry_t __initcall3_start[];
1249 extern initcall_entry_t __initcall4_start[];
1250 extern initcall_entry_t __initcall5_start[];
1251 extern initcall_entry_t __initcall6_start[];
1252 extern initcall_entry_t __initcall7_start[];
1253 extern initcall_entry_t __initcall_end[];
1254
1255 static initcall_entry_t *initcall_levels[] __initdata = {
1256 __initcall0_start,
1257 __initcall1_start,
1258 __initcall2_start,
1259 __initcall3_start,
1260 __initcall4_start,
1261 __initcall5_start,
1262 __initcall6_start,
1263 __initcall7_start,
1264 __initcall_end,
1265 };
1266
1267 /* Keep these in sync with initcalls in include/linux/init.h */
1268 static const char *initcall_level_names[] __initdata = {
1269 "pure",
1270 "core",
1271 "postcore",
1272 "arch",
1273 "subsys",
1274 "fs",
1275 "device",
1276 "late",
1277 };
1278
ignore_unknown_bootoption(char * param,char * val,const char * unused,void * arg)1279 static int __init ignore_unknown_bootoption(char *param, char *val,
1280 const char *unused, void *arg)
1281 {
1282 return 0;
1283 }
1284
1285 #ifdef CONFIG_INITCALL_ASYNC
1286 extern initcall_entry_t __initcall0s_start[];
1287 extern initcall_entry_t __initcall1s_start[];
1288 extern initcall_entry_t __initcall2s_start[];
1289 extern initcall_entry_t __initcall3s_start[];
1290 extern initcall_entry_t __initcall4s_start[];
1291 extern initcall_entry_t __initcall5s_start[];
1292 extern initcall_entry_t __initcall6s_start[];
1293 extern initcall_entry_t __initcall7s_start[];
1294
1295 static initcall_entry_t *initcall_sync_levels[] __initdata = {
1296 __initcall0s_start,
1297 __initcall1s_start,
1298 __initcall2s_start,
1299 __initcall3s_start,
1300 __initcall4s_start,
1301 __initcall5s_start,
1302 __initcall6s_start,
1303 __initcall7s_start,
1304 __initcall_end,
1305 };
1306
1307 struct initcall_work {
1308 struct kthread_work work;
1309 initcall_t call;
1310 };
1311
1312 struct initcall_worker {
1313 struct kthread_worker *worker;
1314 bool queued;
1315 };
1316
1317 static struct initcall_worker *initcall_workers;
1318 static int initcall_nr_workers;
1319
setup_initcall_nr_threads(char * str)1320 static int __init setup_initcall_nr_threads(char *str)
1321 {
1322 get_option(&str, &initcall_nr_workers);
1323
1324 return 1;
1325 }
1326 __setup("initcall_nr_threads=", setup_initcall_nr_threads);
1327
initcall_work_func(struct kthread_work * work)1328 static void __init initcall_work_func(struct kthread_work *work)
1329 {
1330 struct initcall_work *iwork =
1331 container_of(work, struct initcall_work, work);
1332
1333 do_one_initcall(iwork->call);
1334 }
1335
initcall_queue_work(struct initcall_worker * iworker,struct initcall_work * iwork)1336 static void __init initcall_queue_work(struct initcall_worker *iworker,
1337 struct initcall_work *iwork)
1338 {
1339 kthread_queue_work(iworker->worker, &iwork->work);
1340 iworker->queued = true;
1341 }
1342
initcall_flush_worker(int level,bool sync)1343 static void __init initcall_flush_worker(int level, bool sync)
1344 {
1345 int i;
1346 struct initcall_worker *iworker;
1347
1348 for (i = 0; i < initcall_nr_workers; i++) {
1349 iworker = &initcall_workers[i];
1350 if (iworker->queued) {
1351 kthread_flush_worker(iworker->worker);
1352 iworker->queued = false;
1353 }
1354 }
1355 }
1356
do_initcall_level_threaded(int level)1357 static int __init do_initcall_level_threaded(int level)
1358 {
1359 initcall_entry_t *fn;
1360 size_t i = 0, w = 0;
1361 size_t n = initcall_levels[level + 1] - initcall_levels[level];
1362 struct initcall_work *iwork, *iworks;
1363 ktime_t start = 0, end;
1364
1365 if (!n)
1366 return 0;
1367
1368 iworks = kmalloc_array(n, sizeof(*iworks), GFP_KERNEL);
1369 if (!iworks)
1370 return -ENOMEM;
1371
1372 if (initcall_debug)
1373 start = ktime_get();
1374
1375 for (fn = initcall_levels[level]; fn < initcall_sync_levels[level];
1376 fn++, i++) {
1377 iwork = &iworks[i];
1378 iwork->call = initcall_from_entry(fn);
1379 kthread_init_work(&iwork->work, initcall_work_func);
1380 initcall_queue_work(&initcall_workers[w], iwork);
1381 if (++w >= initcall_nr_workers)
1382 w = 0;
1383 }
1384 if (initcall_sync_levels[level] > initcall_levels[level]) {
1385 initcall_flush_worker(level, false);
1386
1387 if (initcall_debug) {
1388 end = ktime_get();
1389 printk(KERN_DEBUG "initcall level %s %lld usecs\n",
1390 initcall_level_names[level],
1391 ktime_us_delta(end, start));
1392 start = end;
1393 }
1394 }
1395
1396 for (fn = initcall_sync_levels[level]; fn < initcall_levels[level + 1];
1397 fn++, i++) {
1398 iwork = &iworks[i];
1399 iwork->call = initcall_from_entry(fn);
1400 kthread_init_work(&iwork->work, initcall_work_func);
1401 initcall_queue_work(&initcall_workers[w], iwork);
1402 if (++w >= initcall_nr_workers)
1403 w = 0;
1404 }
1405 if (initcall_levels[level + 1] > initcall_sync_levels[level]) {
1406 initcall_flush_worker(level, true);
1407
1408 if (initcall_debug) {
1409 end = ktime_get();
1410 printk(KERN_DEBUG "initcall level %s_sync %lld usecs\n",
1411 initcall_level_names[level],
1412 ktime_us_delta(end, start));
1413 }
1414 }
1415
1416 kfree(iworks);
1417
1418 return 0;
1419 }
1420
initcall_init_workers(void)1421 static void __init initcall_init_workers(void)
1422 {
1423 int i;
1424
1425 if (initcall_nr_workers < 0)
1426 initcall_nr_workers = num_online_cpus() * 2;
1427
1428 if (!initcall_nr_workers)
1429 return;
1430
1431 initcall_workers =
1432 kcalloc(initcall_nr_workers, sizeof(*initcall_workers),
1433 GFP_KERNEL);
1434 if (!initcall_workers)
1435 initcall_nr_workers = 0;
1436
1437 for (i = 0; i < initcall_nr_workers; i++) {
1438 struct kthread_worker *worker;
1439
1440 worker = kthread_create_worker(0, "init/%d", i);
1441 if (IS_ERR(worker)) {
1442 i--;
1443 initcall_nr_workers = (i >= 0 ? i : 0);
1444 break;
1445 }
1446 initcall_workers[i].worker = worker;
1447 }
1448 }
1449
initcall_free_works(void)1450 static void __init initcall_free_works(void)
1451 {
1452 int i;
1453
1454 for (i = 0; i < initcall_nr_workers; i++)
1455 if (initcall_workers[i].worker)
1456 kthread_destroy_worker(initcall_workers[i].worker);
1457
1458 kfree(initcall_workers);
1459 }
1460 #endif /* CONFIG_INITCALL_ASYNC */
1461
do_initcall_level(int level,char * command_line)1462 static void __init do_initcall_level(int level, char *command_line)
1463 {
1464 initcall_entry_t *fn;
1465
1466 parse_args(initcall_level_names[level],
1467 command_line, __start___param,
1468 __stop___param - __start___param,
1469 level, level,
1470 NULL, ignore_unknown_bootoption);
1471
1472 trace_initcall_level(initcall_level_names[level]);
1473
1474 #ifdef CONFIG_INITCALL_ASYNC
1475 if (initcall_nr_workers)
1476 if (do_initcall_level_threaded(level) == 0)
1477 return;
1478 #endif
1479
1480 for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++)
1481 do_one_initcall(initcall_from_entry(fn));
1482 }
1483
do_initcalls(void)1484 static void __init do_initcalls(void)
1485 {
1486 int level;
1487 size_t len = strlen(saved_command_line) + 1;
1488 char *command_line;
1489
1490 #ifdef CONFIG_INITCALL_ASYNC
1491 initcall_init_workers();
1492 #endif
1493
1494 command_line = kzalloc(len, GFP_KERNEL);
1495 if (!command_line)
1496 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
1497
1498 for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++) {
1499 /* Parser modifies command_line, restore it each time */
1500 strcpy(command_line, saved_command_line);
1501 do_initcall_level(level, command_line);
1502 }
1503
1504 kfree(command_line);
1505
1506 #ifdef CONFIG_INITCALL_ASYNC
1507 initcall_free_works();
1508 #endif
1509 }
1510
1511 /*
1512 * Ok, the machine is now initialized. None of the devices
1513 * have been touched yet, but the CPU subsystem is up and
1514 * running, and memory and process management works.
1515 *
1516 * Now we can finally start doing some real work..
1517 */
do_basic_setup(void)1518 static void __init do_basic_setup(void)
1519 {
1520 cpuset_init_smp();
1521 driver_init();
1522 init_irq_proc();
1523 do_ctors();
1524 usermodehelper_enable();
1525 do_initcalls();
1526 }
1527
do_pre_smp_initcalls(void)1528 static void __init do_pre_smp_initcalls(void)
1529 {
1530 initcall_entry_t *fn;
1531
1532 trace_initcall_level("early");
1533 for (fn = __initcall_start; fn < __initcall0_start; fn++)
1534 do_one_initcall(initcall_from_entry(fn));
1535 }
1536
run_init_process(const char * init_filename)1537 static int run_init_process(const char *init_filename)
1538 {
1539 const char *const *p;
1540
1541 argv_init[0] = init_filename;
1542 pr_info("Run %s as init process\n", init_filename);
1543 pr_debug(" with arguments:\n");
1544 for (p = argv_init; *p; p++)
1545 pr_debug(" %s\n", *p);
1546 pr_debug(" with environment:\n");
1547 for (p = envp_init; *p; p++)
1548 pr_debug(" %s\n", *p);
1549 return kernel_execve(init_filename, argv_init, envp_init);
1550 }
1551
try_to_run_init_process(const char * init_filename)1552 static int try_to_run_init_process(const char *init_filename)
1553 {
1554 int ret;
1555
1556 ret = run_init_process(init_filename);
1557
1558 if (ret && ret != -ENOENT) {
1559 pr_err("Starting init: %s exists but couldn't execute it (error %d)\n",
1560 init_filename, ret);
1561 }
1562
1563 return ret;
1564 }
1565
1566 static noinline void __init kernel_init_freeable(void);
1567
1568 #if defined(CONFIG_STRICT_KERNEL_RWX) || defined(CONFIG_STRICT_MODULE_RWX)
1569 bool rodata_enabled __ro_after_init = true;
set_debug_rodata(char * str)1570 static int __init set_debug_rodata(char *str)
1571 {
1572 if (strtobool(str, &rodata_enabled))
1573 pr_warn("Invalid option string for rodata: '%s'\n", str);
1574 return 1;
1575 }
1576 __setup("rodata=", set_debug_rodata);
1577 #endif
1578
1579 #ifdef CONFIG_STRICT_KERNEL_RWX
mark_readonly(void)1580 static void mark_readonly(void)
1581 {
1582 if (rodata_enabled) {
1583 /*
1584 * load_module() results in W+X mappings, which are cleaned
1585 * up with call_rcu(). Let's make sure that queued work is
1586 * flushed so that we don't hit false positives looking for
1587 * insecure pages which are W+X.
1588 */
1589 rcu_barrier();
1590 mark_rodata_ro();
1591 rodata_test();
1592 } else
1593 pr_info("Kernel memory protection disabled.\n");
1594 }
1595 #elif defined(CONFIG_ARCH_HAS_STRICT_KERNEL_RWX)
mark_readonly(void)1596 static inline void mark_readonly(void)
1597 {
1598 pr_warn("Kernel memory protection not selected by kernel config.\n");
1599 }
1600 #else
mark_readonly(void)1601 static inline void mark_readonly(void)
1602 {
1603 pr_warn("This architecture does not have kernel memory protection.\n");
1604 }
1605 #endif
1606
free_initmem(void)1607 void __weak free_initmem(void)
1608 {
1609 free_initmem_default(POISON_FREE_INITMEM);
1610 }
1611
kernel_init(void * unused)1612 static int __ref kernel_init(void *unused)
1613 {
1614 int ret;
1615
1616 kernel_init_freeable();
1617 /* need to finish all async __init code before freeing the memory */
1618 async_synchronize_full();
1619 kprobe_free_init_mem();
1620 ftrace_free_init_mem();
1621 kgdb_free_init_mem();
1622 free_initmem();
1623 mark_readonly();
1624
1625 /*
1626 * Kernel mappings are now finalized - update the userspace page-table
1627 * to finalize PTI.
1628 */
1629 pti_finalize();
1630
1631 system_state = SYSTEM_RUNNING;
1632 numa_default_policy();
1633
1634 rcu_end_inkernel_boot();
1635
1636 do_sysctl_args();
1637
1638 if (ramdisk_execute_command) {
1639 ret = run_init_process(ramdisk_execute_command);
1640 if (!ret)
1641 return 0;
1642 pr_err("Failed to execute %s (error %d)\n",
1643 ramdisk_execute_command, ret);
1644 }
1645
1646 /*
1647 * We try each of these until one succeeds.
1648 *
1649 * The Bourne shell can be used instead of init if we are
1650 * trying to recover a really broken machine.
1651 */
1652 if (execute_command) {
1653 ret = run_init_process(execute_command);
1654 if (!ret)
1655 return 0;
1656 panic("Requested init %s failed (error %d).",
1657 execute_command, ret);
1658 }
1659
1660 if (CONFIG_DEFAULT_INIT[0] != '\0') {
1661 ret = run_init_process(CONFIG_DEFAULT_INIT);
1662 if (ret)
1663 pr_err("Default init %s failed (error %d)\n",
1664 CONFIG_DEFAULT_INIT, ret);
1665 else
1666 return 0;
1667 }
1668
1669 if (!try_to_run_init_process("/sbin/init") ||
1670 !try_to_run_init_process("/etc/init") ||
1671 !try_to_run_init_process("/bin/init") ||
1672 !try_to_run_init_process("/bin/sh"))
1673 return 0;
1674
1675 panic("No working init found. Try passing init= option to kernel. "
1676 "See Linux Documentation/admin-guide/init.rst for guidance.");
1677 }
1678
1679 /* Open /dev/console, for stdin/stdout/stderr, this should never fail */
console_on_rootfs(void)1680 void __init console_on_rootfs(void)
1681 {
1682 struct file *file = filp_open("/dev/console", O_RDWR, 0);
1683
1684 if (IS_ERR(file)) {
1685 pr_err("Warning: unable to open an initial console.\n");
1686 return;
1687 }
1688 init_dup(file);
1689 init_dup(file);
1690 init_dup(file);
1691 fput(file);
1692 }
1693
kernel_init_freeable(void)1694 static noinline void __init kernel_init_freeable(void)
1695 {
1696 /*
1697 * Wait until kthreadd is all set-up.
1698 */
1699 wait_for_completion(&kthreadd_done);
1700
1701 /* Now the scheduler is fully set up and can do blocking allocations */
1702 gfp_allowed_mask = __GFP_BITS_MASK;
1703
1704 /*
1705 * init can allocate pages on any node
1706 */
1707 set_mems_allowed(node_states[N_MEMORY]);
1708
1709 cad_pid = get_pid(task_pid(current));
1710
1711 smp_prepare_cpus(setup_max_cpus);
1712
1713 workqueue_init();
1714
1715 init_mm_internals();
1716
1717 rcu_init_tasks_generic();
1718 do_pre_smp_initcalls();
1719 lockup_detector_init();
1720
1721 smp_init();
1722 sched_init_smp();
1723
1724 #if defined(CONFIG_ROCKCHIP_THUNDER_BOOT) && defined(CONFIG_SMP)
1725 kthread_run(defer_free_memblock, NULL, "defer_mem");
1726 #endif
1727
1728 padata_init();
1729 page_alloc_init_late();
1730 /* Initialize page ext after all struct pages are initialized. */
1731 page_ext_init();
1732
1733 do_basic_setup();
1734
1735 kunit_run_all_tests();
1736
1737 #if IS_BUILTIN(CONFIG_INITRD_ASYNC)
1738 async_synchronize_full();
1739 #endif
1740
1741 console_on_rootfs();
1742
1743 /*
1744 * check if there is an early userspace init. If yes, let it do all
1745 * the work
1746 */
1747 if (init_eaccess(ramdisk_execute_command) != 0) {
1748 ramdisk_execute_command = NULL;
1749 prepare_namespace();
1750 }
1751
1752 /*
1753 * Ok, we have completed the initial bootup, and
1754 * we're essentially up and running. Get rid of the
1755 * initmem segments and start the user-mode stuff..
1756 *
1757 * rootfs is available now, try loading the public keys
1758 * and default modules
1759 */
1760
1761 integrity_load_keys();
1762 }
1763