Merge tag 'v5.5-rc4' into locking/kcsan, to resolve conflicts
[sfrench/cifs-2.6.git] / init / main.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/init/main.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  *
7  *  GK 2/5/95  -  Changed to support mounting root fs via NFS
8  *  Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96
9  *  Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96
10  *  Simplified starting of init:  Michael A. Griffith <grif@acm.org>
11  */
12
13 #define DEBUG           /* Enable initcall_debug */
14
15 #include <linux/types.h>
16 #include <linux/extable.h>
17 #include <linux/module.h>
18 #include <linux/proc_fs.h>
19 #include <linux/binfmts.h>
20 #include <linux/kernel.h>
21 #include <linux/syscalls.h>
22 #include <linux/stackprotector.h>
23 #include <linux/string.h>
24 #include <linux/ctype.h>
25 #include <linux/delay.h>
26 #include <linux/ioport.h>
27 #include <linux/init.h>
28 #include <linux/initrd.h>
29 #include <linux/memblock.h>
30 #include <linux/acpi.h>
31 #include <linux/console.h>
32 #include <linux/nmi.h>
33 #include <linux/percpu.h>
34 #include <linux/kmod.h>
35 #include <linux/vmalloc.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/start_kernel.h>
38 #include <linux/security.h>
39 #include <linux/smp.h>
40 #include <linux/profile.h>
41 #include <linux/rcupdate.h>
42 #include <linux/moduleparam.h>
43 #include <linux/kallsyms.h>
44 #include <linux/writeback.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/cgroup.h>
48 #include <linux/efi.h>
49 #include <linux/tick.h>
50 #include <linux/sched/isolation.h>
51 #include <linux/interrupt.h>
52 #include <linux/taskstats_kern.h>
53 #include <linux/delayacct.h>
54 #include <linux/unistd.h>
55 #include <linux/utsname.h>
56 #include <linux/rmap.h>
57 #include <linux/mempolicy.h>
58 #include <linux/key.h>
59 #include <linux/buffer_head.h>
60 #include <linux/page_ext.h>
61 #include <linux/debug_locks.h>
62 #include <linux/debugobjects.h>
63 #include <linux/lockdep.h>
64 #include <linux/kmemleak.h>
65 #include <linux/pid_namespace.h>
66 #include <linux/device.h>
67 #include <linux/kthread.h>
68 #include <linux/sched.h>
69 #include <linux/sched/init.h>
70 #include <linux/signal.h>
71 #include <linux/idr.h>
72 #include <linux/kgdb.h>
73 #include <linux/ftrace.h>
74 #include <linux/async.h>
75 #include <linux/sfi.h>
76 #include <linux/shmem_fs.h>
77 #include <linux/slab.h>
78 #include <linux/perf_event.h>
79 #include <linux/ptrace.h>
80 #include <linux/pti.h>
81 #include <linux/blkdev.h>
82 #include <linux/elevator.h>
83 #include <linux/sched/clock.h>
84 #include <linux/sched/task.h>
85 #include <linux/sched/task_stack.h>
86 #include <linux/context_tracking.h>
87 #include <linux/random.h>
88 #include <linux/list.h>
89 #include <linux/integrity.h>
90 #include <linux/proc_ns.h>
91 #include <linux/io.h>
92 #include <linux/cache.h>
93 #include <linux/rodata_test.h>
94 #include <linux/jump_label.h>
95 #include <linux/mem_encrypt.h>
96 #include <linux/file.h>
97 #include <linux/kcsan.h>
98
99 #include <asm/io.h>
100 #include <asm/bugs.h>
101 #include <asm/setup.h>
102 #include <asm/sections.h>
103 #include <asm/cacheflush.h>
104
105 #define CREATE_TRACE_POINTS
106 #include <trace/events/initcall.h>
107
108 static int kernel_init(void *);
109
110 extern void init_IRQ(void);
111 extern void radix_tree_init(void);
112
113 /*
114  * Debug helper: via this flag we know that we are in 'early bootup code'
115  * where only the boot processor is running with IRQ disabled.  This means
116  * two things - IRQ must not be enabled before the flag is cleared and some
117  * operations which are not allowed with IRQ disabled are allowed while the
118  * flag is set.
119  */
120 bool early_boot_irqs_disabled __read_mostly;
121
122 enum system_states system_state __read_mostly;
123 EXPORT_SYMBOL(system_state);
124
125 /*
126  * Boot command-line arguments
127  */
128 #define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT
129 #define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT
130
131 extern void time_init(void);
132 /* Default late time init is NULL. archs can override this later. */
133 void (*__initdata late_time_init)(void);
134
135 /* Untouched command line saved by arch-specific code. */
136 char __initdata boot_command_line[COMMAND_LINE_SIZE];
137 /* Untouched saved command line (eg. for /proc) */
138 char *saved_command_line;
139 /* Command line for parameter parsing */
140 static char *static_command_line;
141 /* Command line for per-initcall parameter parsing */
142 static char *initcall_command_line;
143
144 static char *execute_command;
145 static char *ramdisk_execute_command;
146
147 /*
148  * Used to generate warnings if static_key manipulation functions are used
149  * before jump_label_init is called.
150  */
151 bool static_key_initialized __read_mostly;
152 EXPORT_SYMBOL_GPL(static_key_initialized);
153
154 /*
155  * If set, this is an indication to the drivers that reset the underlying
156  * device before going ahead with the initialization otherwise driver might
157  * rely on the BIOS and skip the reset operation.
158  *
159  * This is useful if kernel is booting in an unreliable environment.
160  * For ex. kdump situation where previous kernel has crashed, BIOS has been
161  * skipped and devices will be in unknown state.
162  */
163 unsigned int reset_devices;
164 EXPORT_SYMBOL(reset_devices);
165
166 static int __init set_reset_devices(char *str)
167 {
168         reset_devices = 1;
169         return 1;
170 }
171
172 __setup("reset_devices", set_reset_devices);
173
174 static const char *argv_init[MAX_INIT_ARGS+2] = { "init", NULL, };
175 const char *envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, };
176 static const char *panic_later, *panic_param;
177
178 extern const struct obs_kernel_param __setup_start[], __setup_end[];
179
180 static bool __init obsolete_checksetup(char *line)
181 {
182         const struct obs_kernel_param *p;
183         bool had_early_param = false;
184
185         p = __setup_start;
186         do {
187                 int n = strlen(p->str);
188                 if (parameqn(line, p->str, n)) {
189                         if (p->early) {
190                                 /* Already done in parse_early_param?
191                                  * (Needs exact match on param part).
192                                  * Keep iterating, as we can have early
193                                  * params and __setups of same names 8( */
194                                 if (line[n] == '\0' || line[n] == '=')
195                                         had_early_param = true;
196                         } else if (!p->setup_func) {
197                                 pr_warn("Parameter %s is obsolete, ignored\n",
198                                         p->str);
199                                 return true;
200                         } else if (p->setup_func(line + n))
201                                 return true;
202                 }
203                 p++;
204         } while (p < __setup_end);
205
206         return had_early_param;
207 }
208
209 /*
210  * This should be approx 2 Bo*oMips to start (note initial shift), and will
211  * still work even if initially too large, it will just take slightly longer
212  */
213 unsigned long loops_per_jiffy = (1<<12);
214 EXPORT_SYMBOL(loops_per_jiffy);
215
216 static int __init debug_kernel(char *str)
217 {
218         console_loglevel = CONSOLE_LOGLEVEL_DEBUG;
219         return 0;
220 }
221
222 static int __init quiet_kernel(char *str)
223 {
224         console_loglevel = CONSOLE_LOGLEVEL_QUIET;
225         return 0;
226 }
227
228 early_param("debug", debug_kernel);
229 early_param("quiet", quiet_kernel);
230
231 static int __init loglevel(char *str)
232 {
233         int newlevel;
234
235         /*
236          * Only update loglevel value when a correct setting was passed,
237          * to prevent blind crashes (when loglevel being set to 0) that
238          * are quite hard to debug
239          */
240         if (get_option(&str, &newlevel)) {
241                 console_loglevel = newlevel;
242                 return 0;
243         }
244
245         return -EINVAL;
246 }
247
248 early_param("loglevel", loglevel);
249
250 /* Change NUL term back to "=", to make "param" the whole string. */
251 static int __init repair_env_string(char *param, char *val,
252                                     const char *unused, void *arg)
253 {
254         if (val) {
255                 /* param=val or param="val"? */
256                 if (val == param+strlen(param)+1)
257                         val[-1] = '=';
258                 else if (val == param+strlen(param)+2) {
259                         val[-2] = '=';
260                         memmove(val-1, val, strlen(val)+1);
261                         val--;
262                 } else
263                         BUG();
264         }
265         return 0;
266 }
267
268 /* Anything after -- gets handed straight to init. */
269 static int __init set_init_arg(char *param, char *val,
270                                const char *unused, void *arg)
271 {
272         unsigned int i;
273
274         if (panic_later)
275                 return 0;
276
277         repair_env_string(param, val, unused, NULL);
278
279         for (i = 0; argv_init[i]; i++) {
280                 if (i == MAX_INIT_ARGS) {
281                         panic_later = "init";
282                         panic_param = param;
283                         return 0;
284                 }
285         }
286         argv_init[i] = param;
287         return 0;
288 }
289
290 /*
291  * Unknown boot options get handed to init, unless they look like
292  * unused parameters (modprobe will find them in /proc/cmdline).
293  */
294 static int __init unknown_bootoption(char *param, char *val,
295                                      const char *unused, void *arg)
296 {
297         repair_env_string(param, val, unused, NULL);
298
299         /* Handle obsolete-style parameters */
300         if (obsolete_checksetup(param))
301                 return 0;
302
303         /* Unused module parameter. */
304         if (strchr(param, '.') && (!val || strchr(param, '.') < val))
305                 return 0;
306
307         if (panic_later)
308                 return 0;
309
310         if (val) {
311                 /* Environment option */
312                 unsigned int i;
313                 for (i = 0; envp_init[i]; i++) {
314                         if (i == MAX_INIT_ENVS) {
315                                 panic_later = "env";
316                                 panic_param = param;
317                         }
318                         if (!strncmp(param, envp_init[i], val - param))
319                                 break;
320                 }
321                 envp_init[i] = param;
322         } else {
323                 /* Command line option */
324                 unsigned int i;
325                 for (i = 0; argv_init[i]; i++) {
326                         if (i == MAX_INIT_ARGS) {
327                                 panic_later = "init";
328                                 panic_param = param;
329                         }
330                 }
331                 argv_init[i] = param;
332         }
333         return 0;
334 }
335
336 static int __init init_setup(char *str)
337 {
338         unsigned int i;
339
340         execute_command = str;
341         /*
342          * In case LILO is going to boot us with default command line,
343          * it prepends "auto" before the whole cmdline which makes
344          * the shell think it should execute a script with such name.
345          * So we ignore all arguments entered _before_ init=... [MJ]
346          */
347         for (i = 1; i < MAX_INIT_ARGS; i++)
348                 argv_init[i] = NULL;
349         return 1;
350 }
351 __setup("init=", init_setup);
352
353 static int __init rdinit_setup(char *str)
354 {
355         unsigned int i;
356
357         ramdisk_execute_command = str;
358         /* See "auto" comment in init_setup */
359         for (i = 1; i < MAX_INIT_ARGS; i++)
360                 argv_init[i] = NULL;
361         return 1;
362 }
363 __setup("rdinit=", rdinit_setup);
364
365 #ifndef CONFIG_SMP
366 static const unsigned int setup_max_cpus = NR_CPUS;
367 static inline void setup_nr_cpu_ids(void) { }
368 static inline void smp_prepare_cpus(unsigned int maxcpus) { }
369 #endif
370
371 /*
372  * We need to store the untouched command line for future reference.
373  * We also need to store the touched command line since the parameter
374  * parsing is performed in place, and we should allow a component to
375  * store reference of name/value for future reference.
376  */
377 static void __init setup_command_line(char *command_line)
378 {
379         size_t len = strlen(boot_command_line) + 1;
380
381         saved_command_line = memblock_alloc(len, SMP_CACHE_BYTES);
382         if (!saved_command_line)
383                 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
384
385         initcall_command_line = memblock_alloc(len, SMP_CACHE_BYTES);
386         if (!initcall_command_line)
387                 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
388
389         static_command_line = memblock_alloc(len, SMP_CACHE_BYTES);
390         if (!static_command_line)
391                 panic("%s: Failed to allocate %zu bytes\n", __func__, len);
392
393         strcpy(saved_command_line, boot_command_line);
394         strcpy(static_command_line, command_line);
395 }
396
397 /*
398  * We need to finalize in a non-__init function or else race conditions
399  * between the root thread and the init thread may cause start_kernel to
400  * be reaped by free_initmem before the root thread has proceeded to
401  * cpu_idle.
402  *
403  * gcc-3.4 accidentally inlines this function, so use noinline.
404  */
405
406 static __initdata DECLARE_COMPLETION(kthreadd_done);
407
408 noinline void __ref rest_init(void)
409 {
410         struct task_struct *tsk;
411         int pid;
412
413         rcu_scheduler_starting();
414         /*
415          * We need to spawn init first so that it obtains pid 1, however
416          * the init task will end up wanting to create kthreads, which, if
417          * we schedule it before we create kthreadd, will OOPS.
418          */
419         pid = kernel_thread(kernel_init, NULL, CLONE_FS);
420         /*
421          * Pin init on the boot CPU. Task migration is not properly working
422          * until sched_init_smp() has been run. It will set the allowed
423          * CPUs for init to the non isolated CPUs.
424          */
425         rcu_read_lock();
426         tsk = find_task_by_pid_ns(pid, &init_pid_ns);
427         set_cpus_allowed_ptr(tsk, cpumask_of(smp_processor_id()));
428         rcu_read_unlock();
429
430         numa_default_policy();
431         pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES);
432         rcu_read_lock();
433         kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns);
434         rcu_read_unlock();
435
436         /*
437          * Enable might_sleep() and smp_processor_id() checks.
438          * They cannot be enabled earlier because with CONFIG_PREEMPTION=y
439          * kernel_thread() would trigger might_sleep() splats. With
440          * CONFIG_PREEMPT_VOLUNTARY=y the init task might have scheduled
441          * already, but it's stuck on the kthreadd_done completion.
442          */
443         system_state = SYSTEM_SCHEDULING;
444
445         complete(&kthreadd_done);
446
447         /*
448          * The boot idle thread must execute schedule()
449          * at least once to get things moving:
450          */
451         schedule_preempt_disabled();
452         /* Call into cpu_idle with preempt disabled */
453         cpu_startup_entry(CPUHP_ONLINE);
454 }
455
456 /* Check for early params. */
457 static int __init do_early_param(char *param, char *val,
458                                  const char *unused, void *arg)
459 {
460         const struct obs_kernel_param *p;
461
462         for (p = __setup_start; p < __setup_end; p++) {
463                 if ((p->early && parameq(param, p->str)) ||
464                     (strcmp(param, "console") == 0 &&
465                      strcmp(p->str, "earlycon") == 0)
466                 ) {
467                         if (p->setup_func(val) != 0)
468                                 pr_warn("Malformed early option '%s'\n", param);
469                 }
470         }
471         /* We accept everything at this stage. */
472         return 0;
473 }
474
475 void __init parse_early_options(char *cmdline)
476 {
477         parse_args("early options", cmdline, NULL, 0, 0, 0, NULL,
478                    do_early_param);
479 }
480
481 /* Arch code calls this early on, or if not, just before other parsing. */
482 void __init parse_early_param(void)
483 {
484         static int done __initdata;
485         static char tmp_cmdline[COMMAND_LINE_SIZE] __initdata;
486
487         if (done)
488                 return;
489
490         /* All fall through to do_early_param. */
491         strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE);
492         parse_early_options(tmp_cmdline);
493         done = 1;
494 }
495
496 void __init __weak arch_post_acpi_subsys_init(void) { }
497
498 void __init __weak smp_setup_processor_id(void)
499 {
500 }
501
502 # if THREAD_SIZE >= PAGE_SIZE
503 void __init __weak thread_stack_cache_init(void)
504 {
505 }
506 #endif
507
508 void __init __weak mem_encrypt_init(void) { }
509
510 void __init __weak poking_init(void) { }
511
512 void __init __weak pgtable_cache_init(void) { }
513
514 bool initcall_debug;
515 core_param(initcall_debug, initcall_debug, bool, 0644);
516
517 #ifdef TRACEPOINTS_ENABLED
518 static void __init initcall_debug_enable(void);
519 #else
520 static inline void initcall_debug_enable(void)
521 {
522 }
523 #endif
524
525 /* Report memory auto-initialization states for this boot. */
526 static void __init report_meminit(void)
527 {
528         const char *stack;
529
530         if (IS_ENABLED(CONFIG_INIT_STACK_ALL))
531                 stack = "all";
532         else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL))
533                 stack = "byref_all";
534         else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF))
535                 stack = "byref";
536         else if (IS_ENABLED(CONFIG_GCC_PLUGIN_STRUCTLEAK_USER))
537                 stack = "__user";
538         else
539                 stack = "off";
540
541         pr_info("mem auto-init: stack:%s, heap alloc:%s, heap free:%s\n",
542                 stack, want_init_on_alloc(GFP_KERNEL) ? "on" : "off",
543                 want_init_on_free() ? "on" : "off");
544         if (want_init_on_free())
545                 pr_info("mem auto-init: clearing system memory may take some time...\n");
546 }
547
548 /*
549  * Set up kernel memory allocators
550  */
551 static void __init mm_init(void)
552 {
553         /*
554          * page_ext requires contiguous pages,
555          * bigger than MAX_ORDER unless SPARSEMEM.
556          */
557         page_ext_init_flatmem();
558         report_meminit();
559         mem_init();
560         kmem_cache_init();
561         kmemleak_init();
562         pgtable_init();
563         debug_objects_mem_init();
564         vmalloc_init();
565         ioremap_huge_init();
566         /* Should be run before the first non-init thread is created */
567         init_espfix_bsp();
568         /* Should be run after espfix64 is set up. */
569         pti_init();
570 }
571
572 void __init __weak arch_call_rest_init(void)
573 {
574         rest_init();
575 }
576
577 asmlinkage __visible void __init start_kernel(void)
578 {
579         char *command_line;
580         char *after_dashes;
581
582         set_task_stack_end_magic(&init_task);
583         smp_setup_processor_id();
584         debug_objects_early_init();
585
586         cgroup_init_early();
587
588         local_irq_disable();
589         early_boot_irqs_disabled = true;
590
591         /*
592          * Interrupts are still disabled. Do necessary setups, then
593          * enable them.
594          */
595         boot_cpu_init();
596         page_address_init();
597         pr_notice("%s", linux_banner);
598         early_security_init();
599         setup_arch(&command_line);
600         setup_command_line(command_line);
601         setup_nr_cpu_ids();
602         setup_per_cpu_areas();
603         smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */
604         boot_cpu_hotplug_init();
605
606         build_all_zonelists(NULL);
607         page_alloc_init();
608
609         pr_notice("Kernel command line: %s\n", boot_command_line);
610         /* parameters may set static keys */
611         jump_label_init();
612         parse_early_param();
613         after_dashes = parse_args("Booting kernel",
614                                   static_command_line, __start___param,
615                                   __stop___param - __start___param,
616                                   -1, -1, NULL, &unknown_bootoption);
617         if (!IS_ERR_OR_NULL(after_dashes))
618                 parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
619                            NULL, set_init_arg);
620
621         /*
622          * These use large bootmem allocations and must precede
623          * kmem_cache_init()
624          */
625         setup_log_buf(0);
626         vfs_caches_init_early();
627         sort_main_extable();
628         trap_init();
629         mm_init();
630
631         ftrace_init();
632
633         /* trace_printk can be enabled here */
634         early_trace_init();
635
636         /*
637          * Set up the scheduler prior starting any interrupts (such as the
638          * timer interrupt). Full topology setup happens at smp_init()
639          * time - but meanwhile we still have a functioning scheduler.
640          */
641         sched_init();
642         /*
643          * Disable preemption - early bootup scheduling is extremely
644          * fragile until we cpu_idle() for the first time.
645          */
646         preempt_disable();
647         if (WARN(!irqs_disabled(),
648                  "Interrupts were enabled *very* early, fixing it\n"))
649                 local_irq_disable();
650         radix_tree_init();
651
652         /*
653          * Set up housekeeping before setting up workqueues to allow the unbound
654          * workqueue to take non-housekeeping into account.
655          */
656         housekeeping_init();
657
658         /*
659          * Allow workqueue creation and work item queueing/cancelling
660          * early.  Work item execution depends on kthreads and starts after
661          * workqueue_init().
662          */
663         workqueue_init_early();
664
665         rcu_init();
666
667         /* Trace events are available after this */
668         trace_init();
669
670         if (initcall_debug)
671                 initcall_debug_enable();
672
673         context_tracking_init();
674         /* init some links before init_ISA_irqs() */
675         early_irq_init();
676         init_IRQ();
677         tick_init();
678         rcu_init_nohz();
679         init_timers();
680         hrtimers_init();
681         softirq_init();
682         timekeeping_init();
683
684         /*
685          * For best initial stack canary entropy, prepare it after:
686          * - setup_arch() for any UEFI RNG entropy and boot cmdline access
687          * - timekeeping_init() for ktime entropy used in rand_initialize()
688          * - rand_initialize() to get any arch-specific entropy like RDRAND
689          * - add_latent_entropy() to get any latent entropy
690          * - adding command line entropy
691          */
692         rand_initialize();
693         add_latent_entropy();
694         add_device_randomness(command_line, strlen(command_line));
695         boot_init_stack_canary();
696
697         time_init();
698         printk_safe_init();
699         perf_event_init();
700         profile_init();
701         call_function_init();
702         WARN(!irqs_disabled(), "Interrupts were enabled early\n");
703
704         early_boot_irqs_disabled = false;
705         local_irq_enable();
706
707         kmem_cache_init_late();
708
709         /*
710          * HACK ALERT! This is early. We're enabling the console before
711          * we've done PCI setups etc, and console_init() must be aware of
712          * this. But we do want output early, in case something goes wrong.
713          */
714         console_init();
715         if (panic_later)
716                 panic("Too many boot %s vars at `%s'", panic_later,
717                       panic_param);
718
719         lockdep_init();
720
721         /*
722          * Need to run this when irqs are enabled, because it wants
723          * to self-test [hard/soft]-irqs on/off lock inversion bugs
724          * too:
725          */
726         locking_selftest();
727
728         /*
729          * This needs to be called before any devices perform DMA
730          * operations that might use the SWIOTLB bounce buffers. It will
731          * mark the bounce buffers as decrypted so that their usage will
732          * not cause "plain-text" data to be decrypted when accessed.
733          */
734         mem_encrypt_init();
735
736 #ifdef CONFIG_BLK_DEV_INITRD
737         if (initrd_start && !initrd_below_start_ok &&
738             page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) {
739                 pr_crit("initrd overwritten (0x%08lx < 0x%08lx) - disabling it.\n",
740                     page_to_pfn(virt_to_page((void *)initrd_start)),
741                     min_low_pfn);
742                 initrd_start = 0;
743         }
744 #endif
745         setup_per_cpu_pageset();
746         numa_policy_init();
747         acpi_early_init();
748         if (late_time_init)
749                 late_time_init();
750         sched_clock_init();
751         calibrate_delay();
752         pid_idr_init();
753         anon_vma_init();
754 #ifdef CONFIG_X86
755         if (efi_enabled(EFI_RUNTIME_SERVICES))
756                 efi_enter_virtual_mode();
757 #endif
758         thread_stack_cache_init();
759         cred_init();
760         fork_init();
761         proc_caches_init();
762         uts_ns_init();
763         buffer_init();
764         key_init();
765         security_init();
766         dbg_late_init();
767         vfs_caches_init();
768         pagecache_init();
769         signals_init();
770         seq_file_init();
771         proc_root_init();
772         nsfs_init();
773         cpuset_init();
774         cgroup_init();
775         taskstats_init_early();
776         delayacct_init();
777
778         poking_init();
779         check_bugs();
780
781         acpi_subsystem_init();
782         arch_post_acpi_subsys_init();
783         sfi_init_late();
784         kcsan_init();
785
786         /* Do the rest non-__init'ed, we're now alive */
787         arch_call_rest_init();
788 }
789
790 /* Call all constructor functions linked into the kernel. */
791 static void __init do_ctors(void)
792 {
793 #ifdef CONFIG_CONSTRUCTORS
794         ctor_fn_t *fn = (ctor_fn_t *) __ctors_start;
795
796         for (; fn < (ctor_fn_t *) __ctors_end; fn++)
797                 (*fn)();
798 #endif
799 }
800
801 #ifdef CONFIG_KALLSYMS
802 struct blacklist_entry {
803         struct list_head next;
804         char *buf;
805 };
806
807 static __initdata_or_module LIST_HEAD(blacklisted_initcalls);
808
809 static int __init initcall_blacklist(char *str)
810 {
811         char *str_entry;
812         struct blacklist_entry *entry;
813
814         /* str argument is a comma-separated list of functions */
815         do {
816                 str_entry = strsep(&str, ",");
817                 if (str_entry) {
818                         pr_debug("blacklisting initcall %s\n", str_entry);
819                         entry = memblock_alloc(sizeof(*entry),
820                                                SMP_CACHE_BYTES);
821                         if (!entry)
822                                 panic("%s: Failed to allocate %zu bytes\n",
823                                       __func__, sizeof(*entry));
824                         entry->buf = memblock_alloc(strlen(str_entry) + 1,
825                                                     SMP_CACHE_BYTES);
826                         if (!entry->buf)
827                                 panic("%s: Failed to allocate %zu bytes\n",
828                                       __func__, strlen(str_entry) + 1);
829                         strcpy(entry->buf, str_entry);
830                         list_add(&entry->next, &blacklisted_initcalls);
831                 }
832         } while (str_entry);
833
834         return 0;
835 }
836
837 static bool __init_or_module initcall_blacklisted(initcall_t fn)
838 {
839         struct blacklist_entry *entry;
840         char fn_name[KSYM_SYMBOL_LEN];
841         unsigned long addr;
842
843         if (list_empty(&blacklisted_initcalls))
844                 return false;
845
846         addr = (unsigned long) dereference_function_descriptor(fn);
847         sprint_symbol_no_offset(fn_name, addr);
848
849         /*
850          * fn will be "function_name [module_name]" where [module_name] is not
851          * displayed for built-in init functions.  Strip off the [module_name].
852          */
853         strreplace(fn_name, ' ', '\0');
854
855         list_for_each_entry(entry, &blacklisted_initcalls, next) {
856                 if (!strcmp(fn_name, entry->buf)) {
857                         pr_debug("initcall %s blacklisted\n", fn_name);
858                         return true;
859                 }
860         }
861
862         return false;
863 }
864 #else
865 static int __init initcall_blacklist(char *str)
866 {
867         pr_warn("initcall_blacklist requires CONFIG_KALLSYMS\n");
868         return 0;
869 }
870
871 static bool __init_or_module initcall_blacklisted(initcall_t fn)
872 {
873         return false;
874 }
875 #endif
876 __setup("initcall_blacklist=", initcall_blacklist);
877
878 static __init_or_module void
879 trace_initcall_start_cb(void *data, initcall_t fn)
880 {
881         ktime_t *calltime = (ktime_t *)data;
882
883         printk(KERN_DEBUG "calling  %pS @ %i\n", fn, task_pid_nr(current));
884         *calltime = ktime_get();
885 }
886
887 static __init_or_module void
888 trace_initcall_finish_cb(void *data, initcall_t fn, int ret)
889 {
890         ktime_t *calltime = (ktime_t *)data;
891         ktime_t delta, rettime;
892         unsigned long long duration;
893
894         rettime = ktime_get();
895         delta = ktime_sub(rettime, *calltime);
896         duration = (unsigned long long) ktime_to_ns(delta) >> 10;
897         printk(KERN_DEBUG "initcall %pS returned %d after %lld usecs\n",
898                  fn, ret, duration);
899 }
900
901 static ktime_t initcall_calltime;
902
903 #ifdef TRACEPOINTS_ENABLED
904 static void __init initcall_debug_enable(void)
905 {
906         int ret;
907
908         ret = register_trace_initcall_start(trace_initcall_start_cb,
909                                             &initcall_calltime);
910         ret |= register_trace_initcall_finish(trace_initcall_finish_cb,
911                                               &initcall_calltime);
912         WARN(ret, "Failed to register initcall tracepoints\n");
913 }
914 # define do_trace_initcall_start        trace_initcall_start
915 # define do_trace_initcall_finish       trace_initcall_finish
916 #else
917 static inline void do_trace_initcall_start(initcall_t fn)
918 {
919         if (!initcall_debug)
920                 return;
921         trace_initcall_start_cb(&initcall_calltime, fn);
922 }
923 static inline void do_trace_initcall_finish(initcall_t fn, int ret)
924 {
925         if (!initcall_debug)
926                 return;
927         trace_initcall_finish_cb(&initcall_calltime, fn, ret);
928 }
929 #endif /* !TRACEPOINTS_ENABLED */
930
931 int __init_or_module do_one_initcall(initcall_t fn)
932 {
933         int count = preempt_count();
934         char msgbuf[64];
935         int ret;
936
937         if (initcall_blacklisted(fn))
938                 return -EPERM;
939
940         do_trace_initcall_start(fn);
941         ret = fn();
942         do_trace_initcall_finish(fn, ret);
943
944         msgbuf[0] = 0;
945
946         if (preempt_count() != count) {
947                 sprintf(msgbuf, "preemption imbalance ");
948                 preempt_count_set(count);
949         }
950         if (irqs_disabled()) {
951                 strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
952                 local_irq_enable();
953         }
954         WARN(msgbuf[0], "initcall %pS returned with %s\n", fn, msgbuf);
955
956         add_latent_entropy();
957         return ret;
958 }
959
960
961 extern initcall_entry_t __initcall_start[];
962 extern initcall_entry_t __initcall0_start[];
963 extern initcall_entry_t __initcall1_start[];
964 extern initcall_entry_t __initcall2_start[];
965 extern initcall_entry_t __initcall3_start[];
966 extern initcall_entry_t __initcall4_start[];
967 extern initcall_entry_t __initcall5_start[];
968 extern initcall_entry_t __initcall6_start[];
969 extern initcall_entry_t __initcall7_start[];
970 extern initcall_entry_t __initcall_end[];
971
972 static initcall_entry_t *initcall_levels[] __initdata = {
973         __initcall0_start,
974         __initcall1_start,
975         __initcall2_start,
976         __initcall3_start,
977         __initcall4_start,
978         __initcall5_start,
979         __initcall6_start,
980         __initcall7_start,
981         __initcall_end,
982 };
983
984 /* Keep these in sync with initcalls in include/linux/init.h */
985 static const char *initcall_level_names[] __initdata = {
986         "pure",
987         "core",
988         "postcore",
989         "arch",
990         "subsys",
991         "fs",
992         "device",
993         "late",
994 };
995
996 static void __init do_initcall_level(int level)
997 {
998         initcall_entry_t *fn;
999
1000         strcpy(initcall_command_line, saved_command_line);
1001         parse_args(initcall_level_names[level],
1002                    initcall_command_line, __start___param,
1003                    __stop___param - __start___param,
1004                    level, level,
1005                    NULL, &repair_env_string);
1006
1007         trace_initcall_level(initcall_level_names[level]);
1008         for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++)
1009                 do_one_initcall(initcall_from_entry(fn));
1010 }
1011
1012 static void __init do_initcalls(void)
1013 {
1014         int level;
1015
1016         for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++)
1017                 do_initcall_level(level);
1018 }
1019
1020 /*
1021  * Ok, the machine is now initialized. None of the devices
1022  * have been touched yet, but the CPU subsystem is up and
1023  * running, and memory and process management works.
1024  *
1025  * Now we can finally start doing some real work..
1026  */
1027 static void __init do_basic_setup(void)
1028 {
1029         cpuset_init_smp();
1030         driver_init();
1031         init_irq_proc();
1032         do_ctors();
1033         usermodehelper_enable();
1034         do_initcalls();
1035 }
1036
1037 static void __init do_pre_smp_initcalls(void)
1038 {
1039         initcall_entry_t *fn;
1040
1041         trace_initcall_level("early");
1042         for (fn = __initcall_start; fn < __initcall0_start; fn++)
1043                 do_one_initcall(initcall_from_entry(fn));
1044 }
1045
1046 static int run_init_process(const char *init_filename)
1047 {
1048         argv_init[0] = init_filename;
1049         pr_info("Run %s as init process\n", init_filename);
1050         return do_execve(getname_kernel(init_filename),
1051                 (const char __user *const __user *)argv_init,
1052                 (const char __user *const __user *)envp_init);
1053 }
1054
1055 static int try_to_run_init_process(const char *init_filename)
1056 {
1057         int ret;
1058
1059         ret = run_init_process(init_filename);
1060
1061         if (ret && ret != -ENOENT) {
1062                 pr_err("Starting init: %s exists but couldn't execute it (error %d)\n",
1063                        init_filename, ret);
1064         }
1065
1066         return ret;
1067 }
1068
1069 static noinline void __init kernel_init_freeable(void);
1070
1071 #if defined(CONFIG_STRICT_KERNEL_RWX) || defined(CONFIG_STRICT_MODULE_RWX)
1072 bool rodata_enabled __ro_after_init = true;
1073 static int __init set_debug_rodata(char *str)
1074 {
1075         return strtobool(str, &rodata_enabled);
1076 }
1077 __setup("rodata=", set_debug_rodata);
1078 #endif
1079
1080 #ifdef CONFIG_STRICT_KERNEL_RWX
1081 static void mark_readonly(void)
1082 {
1083         if (rodata_enabled) {
1084                 /*
1085                  * load_module() results in W+X mappings, which are cleaned
1086                  * up with call_rcu().  Let's make sure that queued work is
1087                  * flushed so that we don't hit false positives looking for
1088                  * insecure pages which are W+X.
1089                  */
1090                 rcu_barrier();
1091                 mark_rodata_ro();
1092                 rodata_test();
1093         } else
1094                 pr_info("Kernel memory protection disabled.\n");
1095 }
1096 #else
1097 static inline void mark_readonly(void)
1098 {
1099         pr_warn("This architecture does not have kernel memory protection.\n");
1100 }
1101 #endif
1102
1103 void __weak free_initmem(void)
1104 {
1105         free_initmem_default(POISON_FREE_INITMEM);
1106 }
1107
1108 static int __ref kernel_init(void *unused)
1109 {
1110         int ret;
1111
1112         kernel_init_freeable();
1113         /* need to finish all async __init code before freeing the memory */
1114         async_synchronize_full();
1115         ftrace_free_init_mem();
1116         free_initmem();
1117         mark_readonly();
1118
1119         /*
1120          * Kernel mappings are now finalized - update the userspace page-table
1121          * to finalize PTI.
1122          */
1123         pti_finalize();
1124
1125         system_state = SYSTEM_RUNNING;
1126         numa_default_policy();
1127
1128         rcu_end_inkernel_boot();
1129
1130         if (ramdisk_execute_command) {
1131                 ret = run_init_process(ramdisk_execute_command);
1132                 if (!ret)
1133                         return 0;
1134                 pr_err("Failed to execute %s (error %d)\n",
1135                        ramdisk_execute_command, ret);
1136         }
1137
1138         /*
1139          * We try each of these until one succeeds.
1140          *
1141          * The Bourne shell can be used instead of init if we are
1142          * trying to recover a really broken machine.
1143          */
1144         if (execute_command) {
1145                 ret = run_init_process(execute_command);
1146                 if (!ret)
1147                         return 0;
1148                 panic("Requested init %s failed (error %d).",
1149                       execute_command, ret);
1150         }
1151         if (!try_to_run_init_process("/sbin/init") ||
1152             !try_to_run_init_process("/etc/init") ||
1153             !try_to_run_init_process("/bin/init") ||
1154             !try_to_run_init_process("/bin/sh"))
1155                 return 0;
1156
1157         panic("No working init found.  Try passing init= option to kernel. "
1158               "See Linux Documentation/admin-guide/init.rst for guidance.");
1159 }
1160
1161 void console_on_rootfs(void)
1162 {
1163         struct file *file;
1164         unsigned int i;
1165
1166         /* Open /dev/console in kernelspace, this should never fail */
1167         file = filp_open("/dev/console", O_RDWR, 0);
1168         if (IS_ERR(file))
1169                 goto err_out;
1170
1171         /* create stdin/stdout/stderr, this should never fail */
1172         for (i = 0; i < 3; i++) {
1173                 if (f_dupfd(i, file, 0) != i)
1174                         goto err_out;
1175         }
1176
1177         return;
1178
1179 err_out:
1180         /* no panic -- this might not be fatal */
1181         pr_err("Warning: unable to open an initial console.\n");
1182         return;
1183 }
1184
1185 static noinline void __init kernel_init_freeable(void)
1186 {
1187         /*
1188          * Wait until kthreadd is all set-up.
1189          */
1190         wait_for_completion(&kthreadd_done);
1191
1192         /* Now the scheduler is fully set up and can do blocking allocations */
1193         gfp_allowed_mask = __GFP_BITS_MASK;
1194
1195         /*
1196          * init can allocate pages on any node
1197          */
1198         set_mems_allowed(node_states[N_MEMORY]);
1199
1200         cad_pid = task_pid(current);
1201
1202         smp_prepare_cpus(setup_max_cpus);
1203
1204         workqueue_init();
1205
1206         init_mm_internals();
1207
1208         do_pre_smp_initcalls();
1209         lockup_detector_init();
1210
1211         smp_init();
1212         sched_init_smp();
1213
1214         page_alloc_init_late();
1215         /* Initialize page ext after all struct pages are initialized. */
1216         page_ext_init();
1217
1218         do_basic_setup();
1219
1220         console_on_rootfs();
1221
1222         /*
1223          * check if there is an early userspace init.  If yes, let it do all
1224          * the work
1225          */
1226
1227         if (!ramdisk_execute_command)
1228                 ramdisk_execute_command = "/init";
1229
1230         if (ksys_access((const char __user *)
1231                         ramdisk_execute_command, 0) != 0) {
1232                 ramdisk_execute_command = NULL;
1233                 prepare_namespace();
1234         }
1235
1236         /*
1237          * Ok, we have completed the initial bootup, and
1238          * we're essentially up and running. Get rid of the
1239          * initmem segments and start the user-mode stuff..
1240          *
1241          * rootfs is available now, try loading the public keys
1242          * and default modules
1243          */
1244
1245         integrity_load_keys();
1246 }