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