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