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