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