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