blob: c1171e1fa0b086b3a1502c150bd2c06c5852bf0b [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// 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/pid_namespace.h>
69#include <linux/device.h>
70#include <linux/kthread.h>
71#include <linux/sched.h>
72#include <linux/sched/init.h>
73#include <linux/signal.h>
74#include <linux/idr.h>
75#include <linux/kgdb.h>
76#include <linux/ftrace.h>
77#include <linux/async.h>
78#include <linux/sfi.h>
79#include <linux/shmem_fs.h>
80#include <linux/slab.h>
81#include <linux/perf_event.h>
82#include <linux/ptrace.h>
83#include <linux/pti.h>
84#include <linux/blkdev.h>
85#include <linux/elevator.h>
86#include <linux/sched/clock.h>
87#include <linux/sched/task.h>
88#include <linux/sched/task_stack.h>
89#include <linux/context_tracking.h>
90#include <linux/random.h>
91#include <linux/list.h>
92#include <linux/integrity.h>
93#include <linux/proc_ns.h>
94#include <linux/io.h>
95#include <linux/cache.h>
96#include <linux/rodata_test.h>
97#include <linux/jump_label.h>
98
99#include <asm/io.h>
100#include <asm/setup.h>
101#include <asm/sections.h>
102#include <asm/cacheflush.h>
103
104#define CREATE_TRACE_POINTS
105#include <trace/events/initcall.h>
106
107static int kernel_init(void *);
108
109extern void init_IRQ(void);
110extern void radix_tree_init(void);
111
112/*
113 * Debug helper: via this flag we know that we are in 'early bootup code'
114 * where only the boot processor is running with IRQ disabled. This means
115 * two things - IRQ must not be enabled before the flag is cleared and some
116 * operations which are not allowed with IRQ disabled are allowed while the
117 * flag is set.
118 */
119bool early_boot_irqs_disabled __read_mostly;
120
121enum system_states system_state __read_mostly;
122EXPORT_SYMBOL(system_state);
123
124/*
125 * Boot command-line arguments
126 */
127#define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT
128#define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT
129
130extern void time_init(void);
131/* Default late time init is NULL. archs can override this later. */
132void (*__initdata late_time_init)(void);
133
134/* Untouched command line saved by arch-specific code. */
135char __initdata boot_command_line[COMMAND_LINE_SIZE];
136/* Untouched saved command line (eg. for /proc) */
137char *saved_command_line;
138/* Command line for parameter parsing */
139static char *static_command_line;
140/* Untouched extra command line */
141static char *extra_command_line;
142/* Extra init arguments */
143static char *extra_init_args;
144
145#ifdef CONFIG_BOOT_CONFIG
146/* Is bootconfig on command line? */
147static bool bootconfig_found;
148static bool initargs_found;
149#else
150# define bootconfig_found false
151# define initargs_found false
152#endif
153
154static char *execute_command;
155static char *ramdisk_execute_command;
156
157/*
158 * Used to generate warnings if static_key manipulation functions are used
159 * before jump_label_init is called.
160 */
161bool static_key_initialized __read_mostly;
162EXPORT_SYMBOL_GPL(static_key_initialized);
163
164/*
165 * If set, this is an indication to the drivers that reset the underlying
166 * device before going ahead with the initialization otherwise driver might
167 * rely on the BIOS and skip the reset operation.
168 *
169 * This is useful if kernel is booting in an unreliable environment.
170 * For ex. kdump situation where previous kernel has crashed, BIOS has been
171 * skipped and devices will be in unknown state.
172 */
173unsigned int reset_devices;
174EXPORT_SYMBOL(reset_devices);
175
176static int __init set_reset_devices(char *str)
177{
178 reset_devices = 1;
179 return 1;
180}
181
182__setup("reset_devices", set_reset_devices);
183
184static const char *argv_init[MAX_INIT_ARGS+2] = { "init", NULL, };
185const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
186static const char *panic_later, *panic_param;
187
188extern const struct obs_kernel_param __setup_start[], __setup_end[];
189
190static bool __init obsolete_checksetup(char *line)
191{
192 const struct obs_kernel_param *p;
193 bool had_early_param = false;
194
195 p = __setup_start;
196 do {
197 int n = strlen(p->str);
198 if (parameqn(line, p->str, n)) {
199 if (p->early) {
200 /* Already done in parse_early_param?
201 * (Needs exact match on param part).
202 * Keep iterating, as we can have early
203 * params and __setups of same names 8( */
204 if (line[n] == '\0' || line[n] == '=')
205 had_early_param = true;
206 } else if (!p->setup_func) {
207 pr_warn("Parameter %s is obsolete, ignored\n",
208 p->str);
209 return true;
210 } else if (p->setup_func(line + n))
211 return true;
212 }
213 p++;
214 } while (p < __setup_end);
215
216 return had_early_param;
217}
218
219/*
220 * This should be approx 2 Bo*oMips to start (note initial shift), and will
221 * still work even if initially too large, it will just take slightly longer
222 */
223unsigned long loops_per_jiffy = (1<<12);
224EXPORT_SYMBOL(loops_per_jiffy);
225
226static int __init debug_kernel(char *str)
227{
228 console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
229 return 0;
230}
231
232static int __init quiet_kernel(char *str)
233{
234 console_loglevel = CONSOLE_LOGLEVEL_QUIET;
235 return 0;
236}
237
238early_param("debug", debug_kernel);
239early_param("quiet", quiet_kernel);
240
241static int __init loglevel(char *str)
242{
243 int newlevel;
244
245 /*
246 * Only update loglevel value when a correct setting was passed,
247 * to prevent blind crashes (when loglevel being set to 0) that
248 * are quite hard to debug
249 */
250 if (get_option(&str, &newlevel)) {
251 console_loglevel = newlevel;
252 return 0;
253 }
254
255 return -EINVAL;
256}
257
258early_param("loglevel", loglevel);
259
260#ifdef CONFIG_BLK_DEV_INITRD
261static void * __init get_boot_config_from_initrd(u32 *_size, u32 *_csum)
262{
263 u32 size, csum;
264 char *data;
265 u32 *hdr;
266 int i;
267
268 if (!initrd_end)
269 return NULL;
270
271 data = (char *)initrd_end - BOOTCONFIG_MAGIC_LEN;
272 /*
273 * Since Grub may align the size of initrd to 4, we must
274 * check the preceding 3 bytes as well.
275 */
276 for (i = 0; i < 4; i++) {
277 if (!memcmp(data, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN))
278 goto found;
279 data--;
280 }
281 return NULL;
282
283found:
284 hdr = (u32 *)(data - 8);
285 size = hdr[0];
286 csum = hdr[1];
287
288 data = ((void *)hdr) - size;
289 if ((unsigned long)data < initrd_start) {
290 pr_err("bootconfig size %d is greater than initrd size %ld\n",
291 size, initrd_end - initrd_start);
292 return NULL;
293 }
294
295 /* Remove bootconfig from initramfs/initrd */
296 initrd_end = (unsigned long)data;
297 if (_size)
298 *_size = size;
299 if (_csum)
300 *_csum = csum;
301
302 return data;
303}
304#else
305static void * __init get_boot_config_from_initrd(u32 *_size, u32 *_csum)
306{
307 return NULL;
308}
309#endif
310
311#ifdef CONFIG_BOOT_CONFIG
312
313char xbc_namebuf[XBC_KEYLEN_MAX] __initdata;
314
315#define rest(dst, end) ((end) > (dst) ? (end) - (dst) : 0)
316
317static int __init xbc_snprint_cmdline(char *buf, size_t size,
318 struct xbc_node *root)
319{
320 struct xbc_node *knode, *vnode;
321 char *end = buf + size;
322 const char *val;
323 int ret;
324
325 xbc_node_for_each_key_value(root, knode, val) {
326 ret = xbc_node_compose_key_after(root, knode,
327 xbc_namebuf, XBC_KEYLEN_MAX);
328 if (ret < 0)
329 return ret;
330
331 vnode = xbc_node_get_child(knode);
332 if (!vnode) {
333 ret = snprintf(buf, rest(buf, end), "%s ", xbc_namebuf);
334 if (ret < 0)
335 return ret;
336 buf += ret;
337 continue;
338 }
339 xbc_array_for_each_value(vnode, val) {
340 ret = snprintf(buf, rest(buf, end), "%s=\"%s\" ",
341 xbc_namebuf, val);
342 if (ret < 0)
343 return ret;
344 buf += ret;
345 }
346 }
347
348 return buf - (end - size);
349}
350#undef rest
351
352/* Make an extra command line under given key word */
353static char * __init xbc_make_cmdline(const char *key)
354{
355 struct xbc_node *root;
356 char *new_cmdline;
357 int ret, len = 0;
358
359 root = xbc_find_node(key);
360 if (!root)
361 return NULL;
362
363 /* Count required buffer size */
364 len = xbc_snprint_cmdline(NULL, 0, root);
365 if (len <= 0)
366 return NULL;
367
368 new_cmdline = memblock_alloc(len + 1, SMP_CACHE_BYTES);
369 if (!new_cmdline) {
370 pr_err("Failed to allocate memory for extra kernel cmdline.\n");
371 return NULL;
372 }
373
374 ret = xbc_snprint_cmdline(new_cmdline, len + 1, root);
375 if (ret < 0 || ret > len) {
376 pr_err("Failed to print extra kernel cmdline.\n");
377 return NULL;
378 }
379
380 return new_cmdline;
381}
382
383static int __init bootconfig_params(char *param, char *val,
384 const char *unused, void *arg)
385{
386 if (strcmp(param, "bootconfig") == 0) {
387 bootconfig_found = true;
388 }
389 return 0;
390}
391
392static void __init setup_boot_config(const char *cmdline)
393{
394 static char tmp_cmdline[COMMAND_LINE_SIZE] __initdata;
395 const char *msg;
396 int pos;
397 u32 size, csum;
398 char *data, *copy, *err;
399 int ret;
400
401 /* Cut out the bootconfig data even if we have no bootconfig option */
402 data = get_boot_config_from_initrd(&size, &csum);
403
404 strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
405 err = parse_args("bootconfig", tmp_cmdline, NULL, 0, 0, 0, NULL,
406 bootconfig_params);
407
408 if (IS_ERR(err) || !bootconfig_found)
409 return;
410
411 /* parse_args() stops at '--' and returns an address */
412 if (err)
413 initargs_found = true;
414
415 if (!data) {
416 pr_err("'bootconfig' found on command line, but no bootconfig found\n");
417 return;
418 }
419
420 if (size >= XBC_DATA_MAX) {
421 pr_err("bootconfig size %d greater than max size %d\n",
422 size, XBC_DATA_MAX);
423 return;
424 }
425
426 if (xbc_calc_checksum(data, size) != csum) {
427 pr_err("bootconfig checksum failed\n");
428 return;
429 }
430
431 copy = memblock_alloc(size + 1, SMP_CACHE_BYTES);
432 if (!copy) {
433 pr_err("Failed to allocate memory for bootconfig\n");
434 return;
435 }
436
437 memcpy(copy, data, size);
438 copy[size] = '\0';
439
440 ret = xbc_init(copy, &msg, &pos);
441 if (ret < 0) {
442 if (pos < 0)
443 pr_err("Failed to init bootconfig: %s.\n", msg);
444 else
445 pr_err("Failed to parse bootconfig: %s at %d.\n",
446 msg, pos);
447 } else {
448 pr_info("Load bootconfig: %d bytes %d nodes\n", size, ret);
449 /* keys starting with "kernel." are passed via cmdline */
450 extra_command_line = xbc_make_cmdline("kernel");
451 /* Also, "init." keys are init arguments */
452 extra_init_args = xbc_make_cmdline("init");
453 }
454 return;
455}
456
457#else
458
459static void __init setup_boot_config(const char *cmdline)
460{
461 /* Remove bootconfig data from initrd */
462 get_boot_config_from_initrd(NULL, NULL);
463}
464
465static int __init warn_bootconfig(char *str)
466{
467 pr_warn("WARNING: 'bootconfig' found on the kernel command line but CONFIG_BOOTCONFIG is not set.\n");
468 return 0;
469}
470early_param("bootconfig", warn_bootconfig);
471
472#endif
473
474/* Change NUL term back to "=", to make "param" the whole string. */
475static int __init repair_env_string(char *param, char *val,
476 const char *unused, void *arg)
477{
478 if (val) {
479 /* param=val or param="val"? */
480 if (val == param+strlen(param)+1)
481 val[-1] = '=';
482 else if (val == param+strlen(param)+2) {
483 val[-2] = '=';
484 memmove(val-1, val, strlen(val)+1);
485 val--;
486 } else
487 BUG();
488 }
489 return 0;
490}
491
492/* Anything after -- gets handed straight to init. */
493static int __init set_init_arg(char *param, char *val,
494 const char *unused, void *arg)
495{
496 unsigned int i;
497
498 if (panic_later)
499 return 0;
500
501 repair_env_string(param, val, unused, NULL);
502
503 for (i = 0; argv_init[i]; i++) {
504 if (i == MAX_INIT_ARGS) {
505 panic_later = "init";
506 panic_param = param;
507 return 0;
508 }
509 }
510 argv_init[i] = param;
511 return 0;
512}
513
514/*
515 * Unknown boot options get handed to init, unless they look like
516 * unused parameters (modprobe will find them in /proc/cmdline).
517 */
518static int __init unknown_bootoption(char *param, char *val,
519 const char *unused, void *arg)
520{
521 repair_env_string(param, val, unused, NULL);
522
523 /* Handle obsolete-style parameters */
524 if (obsolete_checksetup(param))
525 return 0;
526
527 /* Unused module parameter. */
528 if (strchr(param, '.') && (!val || strchr(param, '.') < val))
529 return 0;
530
531 if (panic_later)
532 return 0;
533
534 if (val) {
535 /* Environment option */
536 unsigned int i;
537 for (i = 0; envp_init[i]; i++) {
538 if (i == MAX_INIT_ENVS) {
539 panic_later = "env";
540 panic_param = param;
541 }
542 if (!strncmp(param, envp_init[i], val - param))
543 break;
544 }
545 envp_init[i] = param;
546 } else {
547 /* Command line option */
548 unsigned int i;
549 for (i = 0; argv_init[i]; i++) {
550 if (i == MAX_INIT_ARGS) {
551 panic_later = "init";
552 panic_param = param;
553 }
554 }
555 argv_init[i] = param;
556 }
557 return 0;
558}
559
560static int __init init_setup(char *str)
561{
562 unsigned int i;
563
564 execute_command = str;
565 /*
566 * In case LILO is going to boot us with default command line,
567 * it prepends "auto" before the whole cmdline which makes
568 * the shell think it should execute a script with such name.
569 * So we ignore all arguments entered _before_ init=... [MJ]
570 */
571 for (i = 1; i < MAX_INIT_ARGS; i++)
572 argv_init[i] = NULL;
573 return 1;
574}
575__setup("init=", init_setup);
576
577static int __init rdinit_setup(char *str)
578{
579 unsigned int i;
580
581 ramdisk_execute_command = str;
582 /* See "auto" comment in init_setup */
583 for (i = 1; i < MAX_INIT_ARGS; i++)
584 argv_init[i] = NULL;
585 return 1;
586}
587__setup("rdinit=", rdinit_setup);
588
589#ifndef CONFIG_SMP
590static const unsigned int setup_max_cpus = NR_CPUS;
591static inline void setup_nr_cpu_ids(void) { }
592static inline void smp_prepare_cpus(unsigned int maxcpus) { }
593#endif
594
595#ifdef CONFIG_MANGLE_BOOTARGS
596static void __init mangle_bootargs(char *command_line)
597{
598 char *rootdev;
599 char *rootfs;
600
601 rootdev = strstr(command_line, "root=/dev/mtdblock");
602
603 if (rootdev)
604 strncpy(rootdev, "mangled_rootblock=", 18);
605
606 rootfs = strstr(command_line, "rootfstype");
607
608 if (rootfs)
609 strncpy(rootfs, "mangled_fs", 10);
610
611}
612#else
613static void __init mangle_bootargs(char *command_line)
614{
615}
616#endif
617
618/*
619 * We need to store the untouched command line for future reference.
620 * We also need to store the touched command line since the parameter
621 * parsing is performed in place, and we should allow a component to
622 * store reference of name/value for future reference.
623 */
624static void __init setup_command_line(char *command_line)
625{
626 size_t len, xlen = 0, ilen = 0;
627
628 if (extra_command_line)
629 xlen = strlen(extra_command_line);
630 if (extra_init_args)
631 ilen = strlen(extra_init_args) + 4; /* for " -- " */
632
633 len = xlen + strlen(boot_command_line) + 1;
634
635 saved_command_line = memblock_alloc(len + ilen, SMP_CACHE_BYTES);
636 if (!saved_command_line)
637 panic("%s: Failed to allocate %zu bytes\n", __func__, len + ilen);
638
639 static_command_line = memblock_alloc(len, SMP_CACHE_BYTES);
640 if (!static_command_line)
641 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
642
643 if (xlen) {
644 /*
645 * We have to put extra_command_line before boot command
646 * lines because there could be dashes (separator of init
647 * command line) in the command lines.
648 */
649 strcpy(saved_command_line, extra_command_line);
650 strcpy(static_command_line, extra_command_line);
651 }
652 strcpy(saved_command_line + xlen, boot_command_line);
653 strcpy(static_command_line + xlen, command_line);
654
655 if (ilen) {
656 /*
657 * Append supplemental init boot args to saved_command_line
658 * so that user can check what command line options passed
659 * to init.
660 */
661 len = strlen(saved_command_line);
662 if (initargs_found) {
663 saved_command_line[len++] = ' ';
664 } else {
665 strcpy(saved_command_line + len, " -- ");
666 len += 4;
667 }
668
669 strcpy(saved_command_line + len, extra_init_args);
670 }
671}
672
673/*
674 * We need to finalize in a non-__init function or else race conditions
675 * between the root thread and the init thread may cause start_kernel to
676 * be reaped by free_initmem before the root thread has proceeded to
677 * cpu_idle.
678 *
679 * gcc-3.4 accidentally inlines this function, so use noinline.
680 */
681
682static __initdata DECLARE_COMPLETION(kthreadd_done);
683
684noinline void __ref rest_init(void)
685{
686 struct task_struct *tsk;
687 int pid;
688
689 rcu_scheduler_starting();
690 /*
691 * We need to spawn init first so that it obtains pid 1, however
692 * the init task will end up wanting to create kthreads, which, if
693 * we schedule it before we create kthreadd, will OOPS.
694 */
695 pid = kernel_thread(kernel_init, NULL, CLONE_FS);
696 /*
697 * Pin init on the boot CPU. Task migration is not properly working
698 * until sched_init_smp() has been run. It will set the allowed
699 * CPUs for init to the non isolated CPUs.
700 */
701 rcu_read_lock();
702 tsk = find_task_by_pid_ns(pid, &init_pid_ns);
703 set_cpus_allowed_ptr(tsk, cpumask_of(smp_processor_id()));
704 rcu_read_unlock();
705
706 numa_default_policy();
707 pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
708 rcu_read_lock();
709 kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
710 rcu_read_unlock();
711
712 /*
713 * Enable might_sleep() and smp_processor_id() checks.
714 * They cannot be enabled earlier because with CONFIG_PREEMPTION=y
715 * kernel_thread() would trigger might_sleep() splats. With
716 * CONFIG_PREEMPT_VOLUNTARY=y the init task might have scheduled
717 * already, but it's stuck on the kthreadd_done completion.
718 */
719 system_state = SYSTEM_SCHEDULING;
720
721 complete(&kthreadd_done);
722
723 /*
724 * The boot idle thread must execute schedule()
725 * at least once to get things moving:
726 */
727 schedule_preempt_disabled();
728 /* Call into cpu_idle with preempt disabled */
729 cpu_startup_entry(CPUHP_ONLINE);
730}
731
732/* Check for early params. */
733static int __init do_early_param(char *param, char *val,
734 const char *unused, void *arg)
735{
736 const struct obs_kernel_param *p;
737
738 for (p = __setup_start; p < __setup_end; p++) {
739 if ((p->early && parameq(param, p->str)) ||
740 (strcmp(param, "console") == 0 &&
741 strcmp(p->str, "earlycon") == 0)
742 ) {
743 if (p->setup_func(val) != 0)
744 pr_warn("Malformed early option '%s'\n", param);
745 }
746 }
747 /* We accept everything at this stage. */
748 return 0;
749}
750
751void __init parse_early_options(char *cmdline)
752{
753 parse_args("early options", cmdline, NULL, 0, 0, 0, NULL,
754 do_early_param);
755}
756
757/* Arch code calls this early on, or if not, just before other parsing. */
758void __init parse_early_param(void)
759{
760 static int done __initdata;
761 static char tmp_cmdline[COMMAND_LINE_SIZE] __initdata;
762
763 if (done)
764 return;
765
766 /* All fall through to do_early_param. */
767 strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
768 parse_early_options(tmp_cmdline);
769 done = 1;
770}
771
772void __init __weak arch_post_acpi_subsys_init(void) { }
773
774void __init __weak smp_setup_processor_id(void)
775{
776}
777
778# if THREAD_SIZE >= PAGE_SIZE
779void __init __weak thread_stack_cache_init(void)
780{
781}
782#endif
783
784void __init __weak poking_init(void) { }
785
786void __init __weak pgtable_cache_init(void) { }
787
788bool initcall_debug;
789core_param(initcall_debug, initcall_debug, bool, 0644);
790
791#ifdef TRACEPOINTS_ENABLED
792static void __init initcall_debug_enable(void);
793#else
794static inline void initcall_debug_enable(void)
795{
796}
797#endif
798
799/* Report memory auto-initialization states for this boot. */
800static void __init report_meminit(void)
801{
802 const char *stack;
803
804 if (IS_ENABLED(CONFIG_INIT_STACK_ALL_PATTERN))
805 stack = "all(pattern)";
806 else if (IS_ENABLED(CONFIG_INIT_STACK_ALL_ZERO))
807 stack = "all(zero)";
808 else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL))
809 stack = "byref_all(zero)";
810 else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF))
811 stack = "byref(zero)";
812 else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_USER))
813 stack = "__user(zero)";
814 else
815 stack = "off";
816
817 pr_info("mem auto-init: stack:%s, heap alloc:%s, heap free:%s\n",
818 stack, want_init_on_alloc(GFP_KERNEL) ? "on" : "off",
819 want_init_on_free() ? "on" : "off");
820 if (want_init_on_free())
821 pr_info("mem auto-init: clearing system memory may take some time...\n");
822}
823
824/*
825 * Set up kernel memory allocators
826 */
827static void __init mm_init(void)
828{
829 /*
830 * page_ext requires contiguous pages,
831 * bigger than MAX_ORDER unless SPARSEMEM.
832 */
833 page_ext_init_flatmem();
834 init_debug_pagealloc();
835 kfence_alloc_pool();
836 report_meminit();
837 mem_init();
838 kmem_cache_init();
839 kmemleak_init();
840 pgtable_init();
841 debug_objects_mem_init();
842 vmalloc_init();
843 ioremap_huge_init();
844 /* Should be run before the first non-init thread is created */
845 init_espfix_bsp();
846 /* Should be run after espfix64 is set up. */
847 pti_init();
848 mm_cache_init();
849}
850
851void __init __weak arch_call_rest_init(void)
852{
853 rest_init();
854}
855
856asmlinkage __visible void __init start_kernel(void)
857{
858 char *command_line;
859 char *after_dashes;
860
861 set_task_stack_end_magic(&init_task);
862 smp_setup_processor_id();
863 debug_objects_early_init();
864
865 cgroup_init_early();
866
867 local_irq_disable();
868 early_boot_irqs_disabled = true;
869
870 /*
871 * Interrupts are still disabled. Do necessary setups, then
872 * enable them.
873 */
874 boot_cpu_init();
875 page_address_init();
876 pr_notice("%s", linux_banner);
877 early_security_init();
878 setup_arch(&command_line);
879 mangle_bootargs(command_line);
880 setup_boot_config(command_line);
881 setup_command_line(command_line);
882 setup_nr_cpu_ids();
883 setup_per_cpu_areas();
884 smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */
885 boot_cpu_hotplug_init();
886
887 build_all_zonelists(NULL);
888 page_alloc_init();
889
890 pr_notice("Kernel command line: %s\n", saved_command_line);
891 /* parameters may set static keys */
892 jump_label_init();
893 parse_early_param();
894 after_dashes = parse_args("Booting kernel",
895 static_command_line, __start___param,
896 __stop___param - __start___param,
897 -1, -1, NULL, &unknown_bootoption);
898 if (!IS_ERR_OR_NULL(after_dashes))
899 parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
900 NULL, set_init_arg);
901 if (extra_init_args)
902 parse_args("Setting extra init args", extra_init_args,
903 NULL, 0, -1, -1, NULL, set_init_arg);
904
905 /*
906 * These use large bootmem allocations and must precede
907 * kmem_cache_init()
908 */
909 setup_log_buf(0);
910 vfs_caches_init_early();
911 sort_main_extable();
912 trap_init();
913 mm_init();
914 poking_init();
915 ftrace_init();
916
917 /* trace_printk can be enabled here */
918 early_trace_init();
919
920 /*
921 * Set up the scheduler prior starting any interrupts (such as the
922 * timer interrupt). Full topology setup happens at smp_init()
923 * time - but meanwhile we still have a functioning scheduler.
924 */
925 sched_init();
926 /*
927 * Disable preemption - early bootup scheduling is extremely
928 * fragile until we cpu_idle() for the first time.
929 */
930 preempt_disable();
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#ifdef CONFIG_BLK_DEV_INITRD
1010 if (initrd_start && !initrd_below_start_ok &&
1011 page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
1012 pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n",
1013 page_to_pfn(virt_to_page((void *)initrd_start)),
1014 min_low_pfn);
1015 initrd_start = 0;
1016 }
1017#endif
1018 setup_per_cpu_pageset();
1019 numa_policy_init();
1020 acpi_early_init();
1021 if (late_time_init)
1022 late_time_init();
1023 sched_clock_init();
1024 calibrate_delay();
1025
1026 arch_cpu_finalize_init();
1027
1028 pid_idr_init();
1029 anon_vma_init();
1030#ifdef CONFIG_X86
1031 if (efi_enabled(EFI_RUNTIME_SERVICES))
1032 efi_enter_virtual_mode();
1033#endif
1034 thread_stack_cache_init();
1035 cred_init();
1036 fork_init();
1037 proc_caches_init();
1038 uts_ns_init();
1039 buffer_init();
1040 key_init();
1041 security_init();
1042 dbg_late_init();
1043 vfs_caches_init();
1044 pagecache_init();
1045 signals_init();
1046 seq_file_init();
1047 proc_root_init();
1048 nsfs_init();
1049 cpuset_init();
1050 cgroup_init();
1051 taskstats_init_early();
1052 delayacct_init();
1053
1054 acpi_subsystem_init();
1055 arch_post_acpi_subsys_init();
1056 sfi_init_late();
1057
1058 /* Do the rest non-__init'ed, we're now alive */
1059 arch_call_rest_init();
1060
1061 prevent_tail_call_optimization();
1062}
1063
1064/* Call all constructor functions linked into the kernel. */
1065static void __init do_ctors(void)
1066{
1067#ifdef CONFIG_CONSTRUCTORS
1068 ctor_fn_t *fn = (ctor_fn_t *) __ctors_start;
1069
1070 for (; fn < (ctor_fn_t *) __ctors_end; fn++)
1071 (*fn)();
1072#endif
1073}
1074
1075#ifdef CONFIG_KALLSYMS
1076struct blacklist_entry {
1077 struct list_head next;
1078 char *buf;
1079};
1080
1081static __initdata_or_module LIST_HEAD(blacklisted_initcalls);
1082
1083static int __init initcall_blacklist(char *str)
1084{
1085 char *str_entry;
1086 struct blacklist_entry *entry;
1087
1088 /* str argument is a comma-separated list of functions */
1089 do {
1090 str_entry = strsep(&str, ",");
1091 if (str_entry) {
1092 pr_debug("blacklisting initcall %s\n", str_entry);
1093 entry = memblock_alloc(sizeof(*entry),
1094 SMP_CACHE_BYTES);
1095 if (!entry)
1096 panic("%s: Failed to allocate %zu bytes\n",
1097 __func__, sizeof(*entry));
1098 entry->buf = memblock_alloc(strlen(str_entry) + 1,
1099 SMP_CACHE_BYTES);
1100 if (!entry->buf)
1101 panic("%s: Failed to allocate %zu bytes\n",
1102 __func__, strlen(str_entry) + 1);
1103 strcpy(entry->buf, str_entry);
1104 list_add(&entry->next, &blacklisted_initcalls);
1105 }
1106 } while (str_entry);
1107
1108 return 1;
1109}
1110
1111static bool __init_or_module initcall_blacklisted(initcall_t fn)
1112{
1113 struct blacklist_entry *entry;
1114 char fn_name[KSYM_SYMBOL_LEN];
1115 unsigned long addr;
1116
1117 if (list_empty(&blacklisted_initcalls))
1118 return false;
1119
1120 addr = (unsigned long) dereference_function_descriptor(fn);
1121 sprint_symbol_no_offset(fn_name, addr);
1122
1123 /*
1124 * fn will be "function_name [module_name]" where [module_name] is not
1125 * displayed for built-in init functions. Strip off the [module_name].
1126 */
1127 strreplace(fn_name, ' ', '\0');
1128
1129 list_for_each_entry(entry, &blacklisted_initcalls, next) {
1130 if (!strcmp(fn_name, entry->buf)) {
1131 pr_debug("initcall %s blacklisted\n", fn_name);
1132 return true;
1133 }
1134 }
1135
1136 return false;
1137}
1138#else
1139static int __init initcall_blacklist(char *str)
1140{
1141 pr_warn("initcall_blacklist requires CONFIG_KALLSYMS\n");
1142 return 0;
1143}
1144
1145static bool __init_or_module initcall_blacklisted(initcall_t fn)
1146{
1147 return false;
1148}
1149#endif
1150__setup("initcall_blacklist=", initcall_blacklist);
1151
1152static __init_or_module void
1153trace_initcall_start_cb(void *data, initcall_t fn)
1154{
1155 ktime_t *calltime = (ktime_t *)data;
1156
1157 printk(KERN_DEBUG "calling %pS @ %i\n", fn, task_pid_nr(current));
1158 *calltime = ktime_get();
1159}
1160
1161static __init_or_module void
1162trace_initcall_finish_cb(void *data, initcall_t fn, int ret)
1163{
1164 ktime_t *calltime = (ktime_t *)data;
1165 ktime_t delta, rettime;
1166 unsigned long long duration;
1167
1168 rettime = ktime_get();
1169 delta = ktime_sub(rettime, *calltime);
1170 duration = (unsigned long long) ktime_to_ns(delta) >> 10;
1171 printk(KERN_DEBUG "initcall %pS returned %d after %lld usecs\n",
1172 fn, ret, duration);
1173}
1174
1175static ktime_t initcall_calltime;
1176
1177#ifdef TRACEPOINTS_ENABLED
1178static void __init initcall_debug_enable(void)
1179{
1180 int ret;
1181
1182 ret = register_trace_initcall_start(trace_initcall_start_cb,
1183 &initcall_calltime);
1184 ret |= register_trace_initcall_finish(trace_initcall_finish_cb,
1185 &initcall_calltime);
1186 WARN(ret, "Failed to register initcall tracepoints\n");
1187}
1188# define do_trace_initcall_start trace_initcall_start
1189# define do_trace_initcall_finish trace_initcall_finish
1190#else
1191static inline void do_trace_initcall_start(initcall_t fn)
1192{
1193 if (!initcall_debug)
1194 return;
1195 trace_initcall_start_cb(&initcall_calltime, fn);
1196}
1197static inline void do_trace_initcall_finish(initcall_t fn, int ret)
1198{
1199 if (!initcall_debug)
1200 return;
1201 trace_initcall_finish_cb(&initcall_calltime, fn, ret);
1202}
1203#endif /* !TRACEPOINTS_ENABLED */
1204
1205int __init_or_module do_one_initcall(initcall_t fn)
1206{
1207 int count = preempt_count();
1208 char msgbuf[64];
1209 int ret;
1210
1211 if (initcall_blacklisted(fn))
1212 return -EPERM;
1213
1214 do_trace_initcall_start(fn);
1215 ret = fn();
1216 do_trace_initcall_finish(fn, ret);
1217
1218 msgbuf[0] = 0;
1219
1220 if (preempt_count() != count) {
1221 sprintf(msgbuf, "preemption imbalance ");
1222 preempt_count_set(count);
1223 }
1224 if (irqs_disabled()) {
1225 strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
1226 local_irq_enable();
1227 }
1228 WARN(msgbuf[0], "initcall %pS returned with %s\n", fn, msgbuf);
1229
1230 add_latent_entropy();
1231 return ret;
1232}
1233
1234
1235extern initcall_entry_t __initcall_start[];
1236extern initcall_entry_t __initcall0_start[];
1237extern initcall_entry_t __initcall1_start[];
1238extern initcall_entry_t __initcall2_start[];
1239extern initcall_entry_t __initcall3_start[];
1240extern initcall_entry_t __initcall4_start[];
1241extern initcall_entry_t __initcall5_start[];
1242extern initcall_entry_t __initcall6_start[];
1243extern initcall_entry_t __initcall7_start[];
1244extern initcall_entry_t __initcall_end[];
1245
1246static initcall_entry_t *initcall_levels[] __initdata = {
1247 __initcall0_start,
1248 __initcall1_start,
1249 __initcall2_start,
1250 __initcall3_start,
1251 __initcall4_start,
1252 __initcall5_start,
1253 __initcall6_start,
1254 __initcall7_start,
1255 __initcall_end,
1256};
1257
1258/* Keep these in sync with initcalls in include/linux/init.h */
1259static const char *initcall_level_names[] __initdata = {
1260 "pure",
1261 "core",
1262 "postcore",
1263 "arch",
1264 "subsys",
1265 "fs",
1266 "device",
1267 "late",
1268};
1269
1270static void __init do_initcall_level(int level, char *command_line)
1271{
1272 initcall_entry_t *fn;
1273
1274 parse_args(initcall_level_names[level],
1275 command_line, __start___param,
1276 __stop___param - __start___param,
1277 level, level,
1278 NULL, &repair_env_string);
1279
1280 trace_initcall_level(initcall_level_names[level]);
1281 for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++)
1282 do_one_initcall(initcall_from_entry(fn));
1283}
1284
1285static void __init do_initcalls(void)
1286{
1287 int level;
1288 size_t len = strlen(saved_command_line) + 1;
1289 char *command_line;
1290
1291 command_line = kzalloc(len, GFP_KERNEL);
1292 if (!command_line)
1293 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
1294
1295 for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++) {
1296 /* Parser modifies command_line, restore it each time */
1297 strcpy(command_line, saved_command_line);
1298 do_initcall_level(level, command_line);
1299 }
1300
1301 kfree(command_line);
1302}
1303
1304/*
1305 * Ok, the machine is now initialized. None of the devices
1306 * have been touched yet, but the CPU subsystem is up and
1307 * running, and memory and process management works.
1308 *
1309 * Now we can finally start doing some real work..
1310 */
1311static void __init do_basic_setup(void)
1312{
1313 cpuset_init_smp();
1314 driver_init();
1315 init_irq_proc();
1316 do_ctors();
1317 usermodehelper_enable();
1318 do_initcalls();
1319}
1320
1321static void __init do_pre_smp_initcalls(void)
1322{
1323 initcall_entry_t *fn;
1324
1325 trace_initcall_level("early");
1326 for (fn = __initcall_start; fn < __initcall0_start; fn++)
1327 do_one_initcall(initcall_from_entry(fn));
1328}
1329
1330static int run_init_process(const char *init_filename)
1331{
1332 argv_init[0] = init_filename;
1333 pr_info("Run %s as init process\n", init_filename);
1334 return do_execve(getname_kernel(init_filename),
1335 (const char __user *const __user *)argv_init,
1336 (const char __user *const __user *)envp_init);
1337}
1338
1339static int try_to_run_init_process(const char *init_filename)
1340{
1341 int ret;
1342
1343 ret = run_init_process(init_filename);
1344
1345 if (ret && ret != -ENOENT) {
1346 pr_err("Starting init: %s exists but couldn't execute it (error %d)\n",
1347 init_filename, ret);
1348 }
1349
1350 return ret;
1351}
1352
1353static noinline void __init kernel_init_freeable(void);
1354
1355#if defined(CONFIG_STRICT_KERNEL_RWX) || defined(CONFIG_STRICT_MODULE_RWX)
1356bool rodata_enabled __ro_after_init = true;
1357static int __init set_debug_rodata(char *str)
1358{
1359 if (strtobool(str, &rodata_enabled))
1360 pr_warn("Invalid option string for rodata: '%s'\n", str);
1361 return 1;
1362}
1363__setup("rodata=", set_debug_rodata);
1364#endif
1365
1366#ifdef CONFIG_STRICT_KERNEL_RWX
1367static void mark_readonly(void)
1368{
1369 if (rodata_enabled) {
1370 /*
1371 * load_module() results in W+X mappings, which are cleaned
1372 * up with call_rcu(). Let's make sure that queued work is
1373 * flushed so that we don't hit false positives looking for
1374 * insecure pages which are W+X.
1375 */
1376 rcu_barrier();
1377 mark_rodata_ro();
1378 rodata_test();
1379 } else
1380 pr_info("Kernel memory protection disabled.\n");
1381}
1382#else
1383static inline void mark_readonly(void)
1384{
1385 pr_warn("This architecture does not have kernel memory protection.\n");
1386}
1387#endif
1388
1389void __weak free_initmem(void)
1390{
1391 free_initmem_default(POISON_FREE_INITMEM);
1392}
1393
1394static int __ref kernel_init(void *unused)
1395{
1396 int ret;
1397
1398 kernel_init_freeable();
1399 /* need to finish all async __init code before freeing the memory */
1400 async_synchronize_full();
1401 kprobe_free_init_mem();
1402 ftrace_free_init_mem();
1403 free_initmem();
1404 mark_readonly();
1405
1406 /*
1407 * Kernel mappings are now finalized - update the userspace page-table
1408 * to finalize PTI.
1409 */
1410 pti_finalize();
1411
1412 system_state = SYSTEM_RUNNING;
1413 numa_default_policy();
1414
1415 rcu_end_inkernel_boot();
1416
1417 if (ramdisk_execute_command) {
1418 ret = run_init_process(ramdisk_execute_command);
1419 if (!ret)
1420 return 0;
1421 pr_err("Failed to execute %s (error %d)\n",
1422 ramdisk_execute_command, ret);
1423 }
1424
1425 /*
1426 * We try each of these until one succeeds.
1427 *
1428 * The Bourne shell can be used instead of init if we are
1429 * trying to recover a really broken machine.
1430 */
1431 if (execute_command) {
1432 ret = run_init_process(execute_command);
1433 if (!ret)
1434 return 0;
1435 panic("Requested init %s failed (error %d).",
1436 execute_command, ret);
1437 }
1438 if (!try_to_run_init_process("/sbin/init") ||
1439 !try_to_run_init_process("/etc/init") ||
1440 !try_to_run_init_process("/bin/init") ||
1441 !try_to_run_init_process("/bin/sh"))
1442 return 0;
1443
1444 panic("No working init found. Try passing init= option to kernel. "
1445 "See Linux Documentation/admin-guide/init.rst for guidance.");
1446}
1447
1448static noinline void __init kernel_init_freeable(void)
1449{
1450 /*
1451 * Wait until kthreadd is all set-up.
1452 */
1453 wait_for_completion(&kthreadd_done);
1454
1455 /* Now the scheduler is fully set up and can do blocking allocations */
1456 gfp_allowed_mask = __GFP_BITS_MASK;
1457
1458 /*
1459 * init can allocate pages on any node
1460 */
1461 set_mems_allowed(node_states[N_MEMORY]);
1462
1463 cad_pid = get_pid(task_pid(current));
1464
1465 smp_prepare_cpus(setup_max_cpus);
1466
1467 workqueue_init();
1468
1469 init_mm_internals();
1470
1471 do_pre_smp_initcalls();
1472 lockup_detector_init();
1473
1474 smp_init();
1475 sched_init_smp();
1476
1477 page_alloc_init_late();
1478 /* Initialize page ext after all struct pages are initialized. */
1479 page_ext_init();
1480
1481 do_basic_setup();
1482
1483 /* Open the /dev/console on the rootfs, this should never fail */
1484 if (ksys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0)
1485 pr_err("Warning: unable to open an initial console.\n");
1486
1487 (void) ksys_dup(0);
1488 (void) ksys_dup(0);
1489 /*
1490 * check if there is an early userspace init. If yes, let it do all
1491 * the work
1492 */
1493
1494 if (!ramdisk_execute_command)
1495 ramdisk_execute_command = "/init";
1496
1497 if (ksys_access((const char __user *)
1498 ramdisk_execute_command, 0) != 0) {
1499 ramdisk_execute_command = NULL;
1500 prepare_namespace();
1501 }
1502
1503 /*
1504 * Ok, we have completed the initial bootup, and
1505 * we're essentially up and running. Get rid of the
1506 * initmem segments and start the user-mode stuff..
1507 *
1508 * rootfs is available now, try loading the public keys
1509 * and default modules
1510 */
1511
1512 integrity_load_keys();
1513}