init_main.c revision 1.520 1 /* $NetBSD: init_main.c,v 1.520 2020/02/15 18:12:15 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2009, 2019 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /*
30 * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 *
62 * @(#)init_main.c 8.16 (Berkeley) 5/14/95
63 */
64
65 /*
66 * Copyright (c) 1995 Christopher G. Demetriou. All rights reserved.
67 *
68 * Redistribution and use in source and binary forms, with or without
69 * modification, are permitted provided that the following conditions
70 * are met:
71 * 1. Redistributions of source code must retain the above copyright
72 * notice, this list of conditions and the following disclaimer.
73 * 2. Redistributions in binary form must reproduce the above copyright
74 * notice, this list of conditions and the following disclaimer in the
75 * documentation and/or other materials provided with the distribution.
76 * 3. All advertising materials mentioning features or use of this software
77 * must display the following acknowledgement:
78 * This product includes software developed by the University of
79 * California, Berkeley and its contributors.
80 * 4. Neither the name of the University nor the names of its contributors
81 * may be used to endorse or promote products derived from this software
82 * without specific prior written permission.
83 *
84 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
85 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
88 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
89 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
90 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
91 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
92 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
93 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
94 * SUCH DAMAGE.
95 *
96 * @(#)init_main.c 8.16 (Berkeley) 5/14/95
97 */
98
99 #include <sys/cdefs.h>
100 __KERNEL_RCSID(0, "$NetBSD: init_main.c,v 1.520 2020/02/15 18:12:15 ad Exp $");
101
102 #include "opt_ddb.h"
103 #include "opt_inet.h"
104 #include "opt_ipsec.h"
105 #include "opt_modular.h"
106 #include "opt_ntp.h"
107 #include "opt_pipe.h"
108 #include "opt_syscall_debug.h"
109 #include "opt_sysv.h"
110 #include "opt_fileassoc.h"
111 #include "opt_ktrace.h"
112 #include "opt_pax.h"
113 #include "opt_compat_netbsd.h"
114 #include "opt_wapbl.h"
115 #include "opt_ptrace.h"
116 #include "opt_rnd_printf.h"
117 #include "opt_splash.h"
118 #include "opt_kernhist.h"
119 #include "opt_gprof.h"
120
121 #if defined(SPLASHSCREEN) && defined(makeoptions_SPLASHSCREEN_IMAGE)
122 extern void *_binary_splash_image_start;
123 extern void *_binary_splash_image_end;
124 #endif
125
126 #include "ksyms.h"
127
128 #include "veriexec.h"
129
130 #include <sys/param.h>
131 #include <sys/acct.h>
132 #include <sys/filedesc.h>
133 #include <sys/file.h>
134 #include <sys/errno.h>
135 #include <sys/callout.h>
136 #include <sys/cpu.h>
137 #include <sys/cpufreq.h>
138 #include <sys/spldebug.h>
139 #include <sys/kernel.h>
140 #include <sys/mount.h>
141 #include <sys/proc.h>
142 #include <sys/kthread.h>
143 #include <sys/resourcevar.h>
144 #include <sys/signalvar.h>
145 #include <sys/systm.h>
146 #include <sys/vnode.h>
147 #include <sys/fstrans.h>
148 #include <sys/tty.h>
149 #include <sys/conf.h>
150 #include <sys/disklabel.h>
151 #include <sys/buf.h>
152 #include <sys/device.h>
153 #include <sys/exec.h>
154 #include <sys/socketvar.h>
155 #include <sys/protosw.h>
156 #include <sys/percpu.h>
157 #include <sys/pserialize.h>
158 #include <sys/pset.h>
159 #include <sys/sysctl.h>
160 #include <sys/reboot.h>
161 #include <sys/event.h>
162 #include <sys/mbuf.h>
163 #include <sys/sched.h>
164 #include <sys/sleepq.h>
165 #include <sys/ipi.h>
166 #include <sys/iostat.h>
167 #include <sys/vmem.h>
168 #include <sys/uuid.h>
169 #include <sys/extent.h>
170 #include <sys/disk.h>
171 #include <sys/msgbuf.h>
172 #include <sys/module.h>
173 #include <sys/module_hook.h>
174 #include <sys/event.h>
175 #include <sys/lockf.h>
176 #include <sys/once.h>
177 #include <sys/kcpuset.h>
178 #include <sys/ksyms.h>
179 #include <sys/uidinfo.h>
180 #include <sys/kprintf.h>
181 #include <sys/bufq.h>
182 #include <sys/threadpool.h>
183 #ifdef IPSEC
184 #include <netipsec/ipsec.h>
185 #endif
186 #include <sys/domain.h>
187 #include <sys/namei.h>
188 #include <sys/rnd.h>
189 #include <sys/pipe.h>
190 #if NVERIEXEC > 0
191 #include <sys/verified_exec.h>
192 #endif /* NVERIEXEC > 0 */
193 #ifdef KTRACE
194 #include <sys/ktrace.h>
195 #endif
196 #include <sys/kauth.h>
197 #include <net80211/ieee80211_netbsd.h>
198 #include <sys/cprng.h>
199 #include <sys/psref.h>
200 #include <sys/radixtree.h>
201
202 #include <sys/syscall.h>
203 #include <sys/syscallargs.h>
204
205 #include <sys/pax.h>
206
207 #include <dev/clock_subr.h>
208
209 #include <secmodel/secmodel.h>
210
211 #include <ufs/ufs/quota.h>
212
213 #include <miscfs/genfs/genfs.h>
214 #include <miscfs/specfs/specdev.h>
215
216 #include <sys/cpu.h>
217
218 #include <uvm/uvm.h> /* extern struct uvm uvm */
219
220 #include <dev/cons.h>
221 #include <dev/splash/splash.h>
222
223 #include <net/bpf.h>
224 #include <net/if.h>
225 #include <net/pfil.h>
226 #include <net/raw_cb.h>
227 #include <net/if_llatbl.h>
228
229 #include <prop/proplib.h>
230
231 #include <sys/userconf.h>
232
233 extern struct lwp lwp0;
234 extern time_t rootfstime;
235
236 #ifndef curlwp
237 struct lwp *curlwp = &lwp0;
238 #endif
239 struct proc *initproc;
240
241 struct vnode *rootvp, *swapdev_vp;
242 int boothowto;
243 int cold __read_mostly = 1; /* still working on startup */
244 int shutting_down __read_mostly; /* system is shutting down */
245
246 int start_init_exec; /* semaphore for start_init() */
247
248 cprng_strong_t *kern_cprng;
249
250 static void check_console(struct lwp *l);
251 static void start_init(void *);
252 static void configure(void);
253 static void configure2(void);
254 static void configure3(void);
255 void main(void);
256
257 /*
258 * System startup; initialize the world, create process 0, mount root
259 * filesystem, and fork to create init and pagedaemon. Most of the
260 * hard work is done in the lower-level initialization routines including
261 * startup(), which does memory initialization and autoconfiguration.
262 */
263 void
264 main(void)
265 {
266 struct timespec time;
267 struct lwp *l;
268 struct proc *p;
269 int s, error;
270 #ifdef NVNODE_IMPLICIT
271 int usevnodes;
272 #endif
273 CPU_INFO_ITERATOR cii;
274 struct cpu_info *ci;
275
276 #ifdef DIAGNOSTIC
277 /*
278 * Verify that CPU_INFO_FOREACH() knows about the boot CPU
279 * and only the boot CPU at this point.
280 */
281 int cpucount = 0;
282 for (CPU_INFO_FOREACH(cii, ci)) {
283 KASSERT(ci == curcpu());
284 cpucount++;
285 }
286 KASSERT(cpucount == 1);
287 #endif
288
289 l = &lwp0;
290 #ifndef LWP0_CPU_INFO
291 l->l_cpu = curcpu();
292 #endif
293 l->l_pflag |= LP_RUNNING;
294
295 /*
296 * Attempt to find console and initialize
297 * in case of early panic or other messages.
298 */
299 consinit();
300
301 kernel_lock_init();
302 once_init();
303 todr_init();
304
305 mi_cpu_init();
306 kernconfig_lock_init();
307 kthread_sysinit();
308
309 /* Initialize the device switch tables. */
310 devsw_init();
311
312 /* Initialize event counters. */
313 evcnt_init();
314
315 uvm_init();
316 ubchist_init();
317 kcpuset_sysinit();
318
319 prop_kern_init();
320
321 #if ((NKSYMS > 0) || (NDDB > 0) || (NMODULAR > 0))
322 ksyms_init();
323 #endif
324 kprintf_init();
325
326 percpu_init();
327
328 /* Initialize lock caches. */
329 mutex_obj_init();
330 rw_obj_init();
331
332 /* Initialize radix trees (used by numerous subsystems). */
333 radix_tree_init();
334
335 /* Passive serialization. */
336 pserialize_init();
337
338 /* Initialize the extent manager. */
339 extent_init();
340
341 /* Do machine-dependent initialization. */
342 cpu_startup();
343
344 /* Initialize the sysctl subsystem. */
345 sysctl_init();
346
347 /* Initialize callouts, part 1. */
348 callout_startup();
349
350 /* Initialize the kernel authorization subsystem. */
351 kauth_init();
352
353 secmodel_init();
354
355 spec_init();
356
357 /*
358 * Set BPF op vector. Can't do this in bpf attach, since
359 * network drivers attach before bpf.
360 */
361 bpf_setops();
362
363 /* Start module system. */
364 module_init();
365 module_hook_init();
366
367 /*
368 * Initialize the kernel authorization subsystem and start the
369 * default security model, if any. We need to do this early
370 * enough so that subsystems relying on any of the aforementioned
371 * can work properly. Since the security model may dictate the
372 * credential inheritance policy, it is needed at least before
373 * any process is created, specifically proc0.
374 */
375 module_init_class(MODULE_CLASS_SECMODEL);
376
377 /* Initialize the buffer cache */
378 bufinit();
379 biohist_init();
380
381 #ifdef KERNHIST
382 sysctl_kernhist_init();
383 #endif
384
385
386 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_IMAGE)
387 size_t splash_size = (&_binary_splash_image_end -
388 &_binary_splash_image_start) * sizeof(void *);
389 splash_setimage(&_binary_splash_image_start, splash_size);
390 #endif
391
392 /* Initialize sockets. */
393 soinit();
394
395 /*
396 * The following things must be done before autoconfiguration.
397 */
398 rnd_init(); /* initialize entropy pool */
399
400 cprng_init(); /* initialize cryptographic PRNG */
401
402 /* Initialize process and pgrp structures. */
403 procinit();
404 lwpinit();
405
406 /* Must be called after lwpinit (lwpinit_specificdata) */
407 psref_init();
408
409 /* Initialize signal-related data structures. */
410 signal_init();
411
412 /* Initialize resource management. */
413 resource_init();
414
415 /* Create process 0. */
416 proc0_init();
417 lwp0_init();
418
419 /* Disable preemption during boot. */
420 kpreempt_disable();
421
422 /* Initialize the threadpool system. */
423 threadpools_init();
424
425 /* Initialize the UID hash table. */
426 uid_init();
427
428 /* Charge root for one process. */
429 (void)chgproccnt(0, 1);
430
431 /* Initialize timekeeping. */
432 time_init();
433
434 /* Initialize the run queues, turnstiles and sleep queues. */
435 sched_rqinit();
436 turnstile_init();
437 sleeptab_init(&sleeptab);
438
439 sched_init();
440
441 /* Initialize processor-sets */
442 psets_init();
443
444 /* Initialize cpufreq(9) */
445 cpufreq_init();
446
447 /* MI initialization of the boot cpu */
448 error = mi_cpu_attach(curcpu());
449 KASSERT(error == 0);
450
451 /* Initialize timekeeping, part 2. */
452 time_init2();
453
454 /*
455 * Initialize mbuf's. Do this now because we might attempt to
456 * allocate mbufs or mbuf clusters during autoconfiguration.
457 */
458 mbinit();
459
460 /* Initialize I/O statistics. */
461 iostat_init();
462
463 /* Initialize the log device. */
464 loginit();
465
466 /* Second part of module system initialization. */
467 module_start_unload_thread();
468
469 /* Initialize the file systems. */
470 #ifdef NVNODE_IMPLICIT
471 /*
472 * If maximum number of vnodes in namei vnode cache is not explicitly
473 * defined in kernel config, adjust the number such as we use roughly
474 * 10% of memory for vnodes and associated data structures in the
475 * assumed worst case. Do not provide fewer than NVNODE vnodes.
476 */
477 usevnodes = calc_cache_size(vmem_size(kmem_arena, VMEM_FREE|VMEM_ALLOC),
478 10, VNODE_KMEM_MAXPCT) / VNODE_COST;
479 if (usevnodes > desiredvnodes)
480 desiredvnodes = usevnodes;
481 #endif
482
483 /* Initialize fstrans. */
484 fstrans_init();
485
486 vfsinit();
487 lf_init();
488
489 /* Initialize the file descriptor system. */
490 fd_sys_init();
491
492 /* Initialize cwd structures */
493 cwd_sys_init();
494
495 /* Initialize kqueue. */
496 kqueue_init();
497
498 inittimecounter();
499 ntp_init();
500
501 /* Initialize tty subsystem. */
502 tty_init();
503 ttyldisc_init();
504
505 /* Initialize the buffer cache, part 2. */
506 bufinit2();
507
508 /* Initialize the disk wedge subsystem. */
509 dkwedge_init();
510
511 /* Initialize the kernel strong PRNG. */
512 kern_cprng = cprng_strong_create("kernel", IPL_VM,
513 CPRNG_INIT_ANY|CPRNG_REKEY_ANY);
514
515 /* Initialize pfil */
516 pfil_init();
517
518 /* Initialize interfaces. */
519 ifinit1();
520
521 spldebug_start();
522
523 /* Initialize sockets thread(s) */
524 soinit1();
525
526 /*
527 * Initialize the bufq strategy sub-system and any built-in
528 * strategy modules - they may be needed by some devices during
529 * auto-configuration
530 */
531 bufq_init();
532 module_init_class(MODULE_CLASS_BUFQ);
533
534 /* Configure the system hardware. This will enable interrupts. */
535 configure();
536
537 /* Once all CPUs are detected, initialize the per-CPU cprng_fast. */
538 cprng_fast_init();
539
540 ssp_init();
541
542 ubc_init(); /* must be after autoconfig */
543
544 mm_init();
545
546 configure2();
547
548 ipi_sysinit();
549
550 /* Now timer is working. Enable preemption. */
551 kpreempt_enable();
552
553 /* Get the threads going and into any sleeps before continuing. */
554 yield();
555
556 /* Enable deferred processing of RNG samples */
557 rnd_init_softint();
558
559 #ifdef RND_PRINTF
560 /* Enable periodic injection of console output into entropy pool */
561 kprintf_init_callout();
562 #endif
563
564 vmem_rehash_start(); /* must be before exec_init */
565
566 /* Initialize exec structures */
567 exec_init(1); /* seminit calls exithook_establish() */
568
569 #if NVERIEXEC > 0
570 /*
571 * Initialise the Veriexec subsystem.
572 */
573 veriexec_init();
574 #endif /* NVERIEXEC > 0 */
575
576 pax_init();
577
578 #ifdef IPSEC
579 /* Attach network crypto subsystem */
580 ipsec_attach();
581 #endif
582
583 /*
584 * Initialize protocols. Block reception of incoming packets
585 * until everything is ready.
586 */
587 s = splnet();
588 ifinit();
589 #if defined(INET) || defined(INET6)
590 lltableinit();
591 #endif
592 domaininit(true);
593 ifinit_post();
594 if_attachdomain();
595 splx(s);
596
597 #ifdef GPROF
598 /* Initialize kernel profiling. */
599 kmstartup();
600 #endif
601
602 /* Initialize system accounting. */
603 acct_init();
604
605 #ifndef PIPE_SOCKETPAIR
606 /* Initialize pipes. */
607 pipe_init();
608 #endif
609
610 #ifdef KTRACE
611 /* Initialize ktrace. */
612 ktrinit();
613 #endif
614
615 machdep_init();
616
617 procinit_sysctl();
618
619 scdebug_init();
620
621 /*
622 * Create process 1 (init(8)). We do this now, as Unix has
623 * historically had init be process 1, and changing this would
624 * probably upset a lot of people.
625 *
626 * Note that process 1 won't immediately exec init(8), but will
627 * wait for us to inform it that the root file system has been
628 * mounted.
629 */
630 if (fork1(l, 0, SIGCHLD, NULL, 0, start_init, NULL, NULL))
631 panic("fork init");
632
633 /*
634 * The initproc variable cannot be initialized in start_init as there
635 * is a race between vfs_mountroot and start_init.
636 */
637 mutex_enter(proc_lock);
638 initproc = proc_find_raw(1);
639 mutex_exit(proc_lock);
640
641 /*
642 * Load any remaining builtin modules, and hand back temporary
643 * storage to the VM system. Then require force when loading any
644 * remaining un-init'ed built-in modules to avoid later surprises.
645 */
646 module_init_class(MODULE_CLASS_ANY);
647 module_builtin_require_force();
648
649 /*
650 * Finalize configuration now that all real devices have been
651 * found. This needs to be done before the root device is
652 * selected, since finalization may create the root device.
653 */
654 config_finalize();
655
656 sysctl_finalize();
657
658 /*
659 * Now that autoconfiguration has completed, we can determine
660 * the root and dump devices.
661 */
662 cpu_rootconf();
663 cpu_dumpconf();
664
665 /* Mount the root file system. */
666 do {
667 domountroothook(root_device);
668 if ((error = vfs_mountroot())) {
669 printf("cannot mount root, error = %d\n", error);
670 boothowto |= RB_ASKNAME;
671 setroot(root_device,
672 (rootdev != NODEV) ? DISKPART(rootdev) : 0);
673 }
674 } while (error != 0);
675 mountroothook_destroy();
676
677 configure3();
678
679 /*
680 * Initialise the time-of-day clock, passing the time recorded
681 * in the root filesystem (if any) for use by systems that
682 * don't have a non-volatile time-of-day device.
683 */
684 inittodr(rootfstime);
685
686 /*
687 * Now can look at time, having had a chance to verify the time
688 * from the file system. Reset l->l_rtime as it may have been
689 * munched in mi_switch() after the time got set.
690 */
691 getnanotime(&time);
692
693 mutex_enter(proc_lock);
694 LIST_FOREACH(p, &allproc, p_list) {
695 KASSERT((p->p_flag & PK_MARKER) == 0);
696 mutex_enter(p->p_lock);
697 TIMESPEC_TO_TIMEVAL(&p->p_stats->p_start, &time);
698 LIST_FOREACH(l, &p->p_lwps, l_sibling) {
699 lwp_lock(l);
700 memset(&l->l_rtime, 0, sizeof(l->l_rtime));
701 lwp_unlock(l);
702 }
703 mutex_exit(p->p_lock);
704 }
705 mutex_exit(proc_lock);
706 binuptime(&curlwp->l_stime);
707
708 for (CPU_INFO_FOREACH(cii, ci)) {
709 ci->ci_schedstate.spc_lastmod = time_second;
710 }
711
712 /* Create the pageout daemon kernel thread. */
713 uvm_swap_init();
714 if (kthread_create(PRI_PGDAEMON, KTHREAD_MPSAFE, NULL, uvm_pageout,
715 NULL, NULL, "pgdaemon"))
716 panic("fork pagedaemon");
717
718 /* Create the filesystem syncer kernel thread. */
719 if (kthread_create(PRI_IOFLUSH, KTHREAD_MPSAFE, NULL, sched_sync,
720 NULL, NULL, "ioflush"))
721 panic("fork syncer");
722
723 /* Create the aiodone daemon kernel thread. */
724 if (workqueue_create(&uvm.aiodone_queue, "aiodoned",
725 uvm_aiodone_worker, NULL, PRI_VM, IPL_NONE, WQ_MPSAFE))
726 panic("fork aiodoned");
727
728 /* Wait for final configure threads to complete. */
729 config_finalize_mountroot();
730
731 /*
732 * Okay, now we can let init(8) exec! It's off to userland!
733 */
734 mutex_enter(proc_lock);
735 start_init_exec = 1;
736 cv_broadcast(&lbolt);
737 mutex_exit(proc_lock);
738
739 /* The scheduler is an infinite loop. */
740 uvm_scheduler();
741 /* NOTREACHED */
742 }
743
744 /*
745 * Configure the system's hardware.
746 */
747 static void
748 configure(void)
749 {
750
751 /* Initialize autoconf data structures. */
752 config_init_mi();
753 /*
754 * XXX
755 * callout_setfunc() requires mutex(9) so it can't be in config_init()
756 * on amiga and atari which use config_init() and autoconf(9) fucntions
757 * to initialize console devices.
758 */
759 config_twiddle_init();
760
761 pmf_init();
762
763 /* Initialize driver modules */
764 module_init_class(MODULE_CLASS_DRIVER);
765
766 userconf_init();
767 if (boothowto & RB_USERCONF)
768 userconf_prompt();
769
770 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
771 printf_nolog("Detecting hardware...");
772 }
773
774 /*
775 * Do the machine-dependent portion of autoconfiguration. This
776 * sets the configuration machinery here in motion by "finding"
777 * the root bus. When this function returns, we expect interrupts
778 * to be enabled.
779 */
780 cpu_configure();
781 }
782
783 static void
784 configure2(void)
785 {
786 CPU_INFO_ITERATOR cii;
787 struct cpu_info *ci;
788 int s;
789
790 /* Fix up CPU topology info, which has all been collected by now. */
791 cpu_topology_init();
792
793 /*
794 * Now that we've found all the hardware, start the real time
795 * and statistics clocks.
796 */
797 initclocks();
798
799 cold = 0; /* clocks are running, we're warm now! */
800 s = splsched();
801 curcpu()->ci_schedstate.spc_flags |= SPCF_RUNNING;
802 splx(s);
803
804 /* Setup the runqueues and scheduler. */
805 runq_init();
806 synch_init();
807
808 /* Boot the secondary processors. */
809 for (CPU_INFO_FOREACH(cii, ci)) {
810 uvm_cpu_attach(ci);
811 }
812
813 /* Decide how to partition free memory. */
814 uvm_page_rebucket();
815
816 mp_online = true;
817 #if defined(MULTIPROCESSOR)
818 cpu_boot_secondary_processors();
819 #endif
820
821 /*
822 * Bus scans can make it appear as if the system has paused, so
823 * twiddle constantly while config_interrupts() jobs are running.
824 */
825 config_twiddle_fn(NULL);
826
827 /*
828 * Create threads to call back and finish configuration for
829 * devices that want interrupts enabled.
830 */
831 config_create_interruptthreads();
832 }
833
834 static void
835 configure3(void)
836 {
837
838 /*
839 * Create threads to call back and finish configuration for
840 * devices that want the mounted root file system.
841 */
842 config_create_mountrootthreads();
843
844 /* Get the threads going and into any sleeps before continuing. */
845 yield();
846 }
847
848 static void
849 rootconf_handle_wedges(void)
850 {
851 struct disklabel label;
852 struct partition *p;
853 struct vnode *vp;
854 daddr_t startblk;
855 uint64_t nblks;
856 device_t dev;
857 int error;
858
859 if (booted_nblks) {
860 /*
861 * bootloader passed geometry
862 */
863 dev = booted_device;
864 startblk = booted_startblk;
865 nblks = booted_nblks;
866
867 /*
868 * keep booted_device and booted_partition
869 * in case the kernel doesn't identify a wedge
870 */
871 } else {
872 /*
873 * bootloader passed partition number
874 *
875 * We cannot ask the partition device directly when it is
876 * covered by a wedge. Instead we look up the geometry in
877 * the disklabel.
878 */
879 vp = opendisk(booted_device);
880
881 if (vp == NULL)
882 return;
883
884 error = VOP_IOCTL(vp, DIOCGDINFO, &label, FREAD, NOCRED);
885 VOP_CLOSE(vp, FREAD, NOCRED);
886 vput(vp);
887 if (error)
888 return;
889
890 KASSERT(booted_partition >= 0
891 && booted_partition < MAXPARTITIONS);
892
893 p = &label.d_partitions[booted_partition];
894
895 dev = booted_device;
896 startblk = p->p_offset;
897 nblks = p->p_size;
898 }
899
900 dev = dkwedge_find_partition(dev, startblk, nblks);
901 if (dev != NULL) {
902 booted_device = dev;
903 booted_partition = 0;
904 }
905 }
906
907 void
908 rootconf(void)
909 {
910 if (booted_device != NULL)
911 rootconf_handle_wedges();
912
913 setroot(booted_device, booted_partition);
914 }
915
916 static void
917 check_console(struct lwp *l)
918 {
919 struct vnode *vp;
920 int error;
921
922 error = namei_simple_kernel("/dev/console",
923 NSM_FOLLOW_NOEMULROOT, &vp);
924 if (error == 0) {
925 vrele(vp);
926 } else if (error == ENOENT) {
927 if (boothowto & (AB_VERBOSE|AB_DEBUG))
928 printf("warning: no /dev/console\n");
929 } else {
930 printf("warning: lookup /dev/console: error %d\n", error);
931 }
932 }
933
934 /*
935 * List of paths to try when searching for "init".
936 */
937 static const char * const initpaths[] = {
938 "/sbin/init",
939 "/sbin/oinit",
940 "/sbin/init.bak",
941 "/rescue/init",
942 NULL,
943 };
944
945 /*
946 * Start the initial user process; try exec'ing each pathname in "initpaths".
947 * The program is invoked with one argument containing the boot flags.
948 */
949 static void
950 start_init(void *arg)
951 {
952 struct lwp *l = arg;
953 struct proc *p = l->l_proc;
954 vaddr_t addr;
955 struct sys_execve_args /* {
956 syscallarg(const char *) path;
957 syscallarg(char * const *) argp;
958 syscallarg(char * const *) envp;
959 } */ args;
960 int options, i, error;
961 register_t retval[2];
962 char flags[4], *flagsp;
963 const char *path, *slash;
964 char *ucp, **uap, *arg0, *arg1, *argv[3];
965 char ipath[129];
966 int ipx, len;
967
968 /*
969 * Now in process 1.
970 */
971 strncpy(p->p_comm, "init", MAXCOMLEN);
972
973 /*
974 * Wait for main() to tell us that it's safe to exec.
975 */
976 mutex_enter(proc_lock);
977 while (start_init_exec == 0)
978 cv_wait(&lbolt, proc_lock);
979 mutex_exit(proc_lock);
980
981 /*
982 * This is not the right way to do this. We really should
983 * hand-craft a descriptor onto /dev/console to hand to init,
984 * but that's a _lot_ more work, and the benefit from this easy
985 * hack makes up for the "good is the enemy of the best" effect.
986 */
987 check_console(l);
988
989 /*
990 * Need just enough stack to hold the faked-up "execve()" arguments.
991 */
992 addr = (vaddr_t)STACK_ALLOC(USRSTACK, PAGE_SIZE);
993 if (uvm_map(&p->p_vmspace->vm_map, &addr, PAGE_SIZE,
994 NULL, UVM_UNKNOWN_OFFSET, 0,
995 UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW, UVM_INH_COPY,
996 UVM_ADV_NORMAL,
997 UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW)) != 0)
998 panic("init: couldn't allocate argument space");
999 p->p_vmspace->vm_maxsaddr = (void *)STACK_MAX(addr, PAGE_SIZE);
1000
1001 ipx = 0;
1002 while (1) {
1003 if (boothowto & RB_ASKNAME) {
1004 printf("init path");
1005 if (initpaths[ipx])
1006 printf(" (default %s)", initpaths[ipx]);
1007 printf(": ");
1008 len = cngetsn(ipath, sizeof(ipath)-1);
1009 if (len == 4 && strcmp(ipath, "halt") == 0) {
1010 kern_reboot(RB_HALT, NULL);
1011 } else if (len == 6 && strcmp(ipath, "reboot") == 0) {
1012 kern_reboot(0, NULL);
1013 #if defined(DDB)
1014 } else if (len == 3 && strcmp(ipath, "ddb") == 0) {
1015 console_debugger();
1016 continue;
1017 #endif
1018 } else if (len > 0 && ipath[0] == '/') {
1019 ipath[len] = '\0';
1020 path = ipath;
1021 } else if (len == 0 && initpaths[ipx] != NULL) {
1022 path = initpaths[ipx++];
1023 } else {
1024 printf("use absolute path, ");
1025 #if defined(DDB)
1026 printf("\"ddb\", ");
1027 #endif
1028 printf("\"halt\", or \"reboot\"\n");
1029 continue;
1030 }
1031 } else {
1032 if ((path = initpaths[ipx++]) == NULL) {
1033 ipx = 0;
1034 boothowto |= RB_ASKNAME;
1035 continue;
1036 }
1037 }
1038
1039 ucp = (char *)USRSTACK;
1040
1041 /*
1042 * Construct the boot flag argument.
1043 */
1044 flagsp = flags;
1045 *flagsp++ = '-';
1046 options = 0;
1047
1048 if (boothowto & RB_SINGLE) {
1049 *flagsp++ = 's';
1050 options = 1;
1051 }
1052 #ifdef notyet
1053 if (boothowto & RB_FASTBOOT) {
1054 *flagsp++ = 'f';
1055 options = 1;
1056 }
1057 #endif
1058
1059 /*
1060 * Move out the flags (arg 1), if necessary.
1061 */
1062 if (options != 0) {
1063 *flagsp++ = '\0';
1064 i = flagsp - flags;
1065 #ifdef DEBUG
1066 aprint_normal("init: copying out flags `%s' %d\n", flags, i);
1067 #endif
1068 arg1 = STACK_ALLOC(ucp, i);
1069 ucp = STACK_MAX(arg1, i);
1070 if ((error = copyout((void *)flags, arg1, i)) != 0)
1071 goto copyerr;
1072 } else
1073 arg1 = NULL;
1074
1075 /*
1076 * Move out the file name (also arg 0).
1077 */
1078 i = strlen(path) + 1;
1079 #ifdef DEBUG
1080 aprint_normal("init: copying out path `%s' %d\n", path, i);
1081 #else
1082 if (boothowto & RB_ASKNAME || path != initpaths[0])
1083 printf("init: trying %s\n", path);
1084 #endif
1085 arg0 = STACK_ALLOC(ucp, i);
1086 ucp = STACK_MAX(arg0, i);
1087 if ((error = copyout(path, arg0, i)) != 0)
1088 goto copyerr;
1089
1090 /*
1091 * Move out the arg pointers.
1092 */
1093 ucp = (void *)STACK_ALIGN(ucp, STACK_ALIGNBYTES);
1094 uap = (char **)STACK_ALLOC(ucp, sizeof(argv));
1095 SCARG(&args, path) = arg0;
1096 SCARG(&args, argp) = uap;
1097 SCARG(&args, envp) = NULL;
1098 slash = strrchr(path, '/');
1099
1100 argv[0] = slash ? arg0 + (slash + 1 - path) : arg0;
1101 argv[1] = arg1;
1102 argv[2] = NULL;
1103 if ((error = copyout(argv, uap, sizeof(argv))) != 0)
1104 goto copyerr;
1105
1106 /*
1107 * Now try to exec the program. If it can't for any reason
1108 * other than it doesn't exist, complain.
1109 */
1110 error = sys_execve(l, &args, retval);
1111 if (error == 0 || error == EJUSTRETURN) {
1112 KERNEL_UNLOCK_LAST(l);
1113 return;
1114 }
1115 printf("exec %s: error %d\n", path, error);
1116 }
1117 printf("init: not found\n");
1118 panic("no init");
1119 copyerr:
1120 panic("copyout %d", error);
1121 }
1122
1123 /*
1124 * calculate cache size (in bytes) from physmem and vsize.
1125 */
1126 vaddr_t
1127 calc_cache_size(vsize_t vsize, int pct, int va_pct)
1128 {
1129 paddr_t t;
1130
1131 /* XXX should consider competing cache if any */
1132 /* XXX should consider submaps */
1133 t = (uintmax_t)physmem * pct / 100 * PAGE_SIZE;
1134 if (vsize != 0) {
1135 vsize = (uintmax_t)vsize * va_pct / 100;
1136 if (t > vsize) {
1137 t = vsize;
1138 }
1139 }
1140 return t;
1141 }
1142
1143 /*
1144 * Print the system start up banner.
1145 *
1146 * - Print a limited banner if AB_SILENT.
1147 * - Always send normal banner to the log.
1148 */
1149 #define MEM_PBUFSIZE sizeof("99999 MB")
1150
1151 void
1152 banner(void)
1153 {
1154 static char notice[] = " Notice: this software is "
1155 "protected by copyright";
1156 char pbuf[81];
1157 void (*pr)(const char *, ...) __printflike(1, 2);
1158 int i;
1159
1160 if ((boothowto & AB_SILENT) != 0) {
1161 snprintf(pbuf, sizeof(pbuf), "%s %s (%s)",
1162 ostype, osrelease, kernel_ident);
1163 printf_nolog("%s", pbuf);
1164 for (i = 80 - strlen(pbuf) - sizeof(notice); i > 0; i--)
1165 printf(" ");
1166 printf_nolog("%s\n", notice);
1167 pr = aprint_normal;
1168 } else {
1169 pr = printf;
1170 }
1171
1172 memset(pbuf, 0, sizeof(pbuf));
1173 (*pr)("%s%s", copyright, version);
1174 format_bytes(pbuf, MEM_PBUFSIZE, ctob((uint64_t)physmem));
1175 (*pr)("total memory = %s\n", pbuf);
1176 format_bytes(pbuf, MEM_PBUFSIZE, ctob((uint64_t)uvm_availmem()));
1177 (*pr)("avail memory = %s\n", pbuf);
1178 }
1179