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