Home | History | Annotate | Line # | Download | only in kern
init_main.c revision 1.309
      1 /*	$NetBSD: init_main.c,v 1.309 2007/07/21 19:51:49 ad Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * (c) UNIX System Laboratories, Inc.
      7  * All or some portions of this file are derived from material licensed
      8  * to the University of California by American Telephone and Telegraph
      9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     10  * the permission of UNIX System Laboratories, Inc.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)init_main.c	8.16 (Berkeley) 5/14/95
     37  */
     38 
     39 /*
     40  * Copyright (c) 1995 Christopher G. Demetriou.  All rights reserved.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  *
     70  *	@(#)init_main.c	8.16 (Berkeley) 5/14/95
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 __KERNEL_RCSID(0, "$NetBSD: init_main.c,v 1.309 2007/07/21 19:51:49 ad Exp $");
     75 
     76 #include "opt_ipsec.h"
     77 #include "opt_multiprocessor.h"
     78 #include "opt_ntp.h"
     79 #include "opt_pipe.h"
     80 #include "opt_posix.h"
     81 #include "opt_syscall_debug.h"
     82 #include "opt_sysv.h"
     83 #include "opt_systrace.h"
     84 #include "opt_fileassoc.h"
     85 #include "opt_ktrace.h"
     86 #include "opt_pax.h"
     87 
     88 #include "rnd.h"
     89 #include "sysmon_envsys.h"
     90 #include "sysmon_power.h"
     91 #include "veriexec.h"
     92 
     93 #include <sys/param.h>
     94 #include <sys/acct.h>
     95 #include <sys/filedesc.h>
     96 #include <sys/file.h>
     97 #include <sys/errno.h>
     98 #include <sys/callout.h>
     99 #include <sys/cpu.h>
    100 #include <sys/kernel.h>
    101 #include <sys/kmem.h>
    102 #include <sys/mount.h>
    103 #include <sys/proc.h>
    104 #include <sys/kthread.h>
    105 #include <sys/resourcevar.h>
    106 #include <sys/signalvar.h>
    107 #include <sys/systm.h>
    108 #include <sys/vnode.h>
    109 #include <sys/fstrans.h>
    110 #include <sys/tty.h>
    111 #include <sys/conf.h>
    112 #include <sys/disklabel.h>
    113 #include <sys/buf.h>
    114 #include <sys/device.h>
    115 #include <sys/exec.h>
    116 #include <sys/socketvar.h>
    117 #include <sys/protosw.h>
    118 #include <sys/reboot.h>
    119 #include <sys/user.h>
    120 #include <sys/sysctl.h>
    121 #include <sys/event.h>
    122 #include <sys/mbuf.h>
    123 #include <sys/sched.h>
    124 #include <sys/sleepq.h>
    125 #include <sys/iostat.h>
    126 #include <sys/vmem.h>
    127 #include <sys/uuid.h>
    128 #include <sys/extent.h>
    129 #include <sys/disk.h>
    130 #ifdef FAST_IPSEC
    131 #include <netipsec/ipsec.h>
    132 #endif
    133 #ifdef SYSVSHM
    134 #include <sys/shm.h>
    135 #endif
    136 #ifdef SYSVSEM
    137 #include <sys/sem.h>
    138 #endif
    139 #ifdef SYSVMSG
    140 #include <sys/msg.h>
    141 #endif
    142 #ifdef SYSTRACE
    143 #include <sys/systrace.h>
    144 #endif
    145 #ifdef P1003_1B_SEMAPHORE
    146 #include <sys/ksem.h>
    147 #endif
    148 #include <sys/domain.h>
    149 #include <sys/namei.h>
    150 #if NRND > 0
    151 #include <sys/rnd.h>
    152 #endif
    153 #include <sys/pipe.h>
    154 #ifdef LKM
    155 #include <sys/lkm.h>
    156 #endif
    157 #if NVERIEXEC > 0
    158 #include <sys/verified_exec.h>
    159 #endif /* NVERIEXEC > 0 */
    160 #ifdef KTRACE
    161 #include <sys/ktrace.h>
    162 #endif
    163 #include <sys/debug.h>
    164 #include <sys/kauth.h>
    165 #include <net80211/ieee80211_netbsd.h>
    166 
    167 #include <sys/syscall.h>
    168 #include <sys/syscallargs.h>
    169 
    170 #if defined(PAX_MPROTECT) || defined(PAX_SEGVGUARD)
    171 #include <sys/pax.h>
    172 #endif /* PAX_MPROTECT || PAX_SEGVGUARD */
    173 #include <ufs/ufs/quota.h>
    174 
    175 #include <miscfs/genfs/genfs.h>
    176 #include <miscfs/syncfs/syncfs.h>
    177 
    178 #include <machine/cpu.h>
    179 
    180 #include <uvm/uvm.h>
    181 
    182 #include <dev/cons.h>
    183 #if NSYSMON_ENVSYS > 0 || NSYSMON_POWER > 0
    184 #include <dev/sysmon/sysmonvar.h>
    185 #endif
    186 
    187 #include <net/if.h>
    188 #include <net/raw_cb.h>
    189 
    190 #include <secmodel/secmodel.h>
    191 
    192 extern struct proc proc0;
    193 extern struct lwp lwp0;
    194 extern struct cwdinfo cwdi0;
    195 
    196 #ifndef curlwp
    197 struct	lwp *curlwp = &lwp0;
    198 #endif
    199 struct	proc *initproc;
    200 
    201 struct	vnode *rootvp, *swapdev_vp;
    202 int	boothowto;
    203 int	cold = 1;			/* still working on startup */
    204 struct timeval boottime;	        /* time at system startup - will only follow settime deltas */
    205 time_t	rootfstime;			/* recorded root fs time, if known */
    206 int	ncpu = 0;			/* number of CPUs configured, assume 1 */
    207 
    208 volatile int start_init_exec;		/* semaphore for start_init() */
    209 
    210 static void check_console(struct lwp *l);
    211 static void start_init(void *);
    212 void main(void);
    213 
    214 #if defined(__SSP__) || defined(__SSP_ALL__)
    215 long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    216 void __stack_chk_fail(void);
    217 
    218 void
    219 __stack_chk_fail(void)
    220 {
    221 	panic("stack overflow detected; terminated");
    222 }
    223 #endif
    224 
    225 void __secmodel_none(void);
    226 __weak_alias(secmodel_start,__secmodel_none);
    227 void
    228 __secmodel_none(void)
    229 {
    230 	return;
    231 }
    232 
    233 /*
    234  * System startup; initialize the world, create process 0, mount root
    235  * filesystem, and fork to create init and pagedaemon.  Most of the
    236  * hard work is done in the lower-level initialization routines including
    237  * startup(), which does memory initialization and autoconfiguration.
    238  */
    239 void
    240 main(void)
    241 {
    242 #ifdef __HAVE_TIMECOUNTER
    243 	struct timeval time;
    244 #endif
    245 	struct lwp *l;
    246 	struct proc *p;
    247 	struct pdevinit *pdev;
    248 	int s, error;
    249 	extern struct pdevinit pdevinit[];
    250 #ifdef NVNODE_IMPLICIT
    251 	int usevnodes;
    252 #endif
    253 
    254 	/*
    255 	 * Initialize the current LWP pointer (curlwp) before
    256 	 * any possible traps/probes to simplify trap processing.
    257 	 */
    258 	l = &lwp0;
    259 	curlwp = l;
    260 	l->l_cpu = curcpu();
    261 	l->l_proc = &proc0;
    262 	l->l_lid = 1;
    263 
    264 	/*
    265 	 * Attempt to find console and initialize
    266 	 * in case of early panic or other messages.
    267 	 */
    268 	consinit();
    269 
    270 	KERNEL_LOCK_INIT();
    271 
    272 	uvm_init();
    273 
    274 #ifdef DEBUG
    275 	debug_init();
    276 #endif
    277 
    278 	kmem_init();
    279 
    280 	/* Initialize the extent manager. */
    281 	extent_init();
    282 
    283 	/* Do machine-dependent initialization. */
    284 	cpu_startup();
    285 
    286 	/* Initialize callouts, part 1. */
    287 	callout_startup();
    288 
    289 	/*
    290 	 * Initialize the kernel authorization subsystem and start the
    291 	 * default security model, if any. We need to do this early
    292 	 * enough so that subsystems relying on any of the aforementioned
    293 	 * can work properly. Since the security model may dictate the
    294 	 * credential inheritance policy, it is needed at least before
    295 	 * any process is created, specifically proc0.
    296 	 */
    297 	kauth_init();
    298 	secmodel_start();
    299 
    300 	/* Initialize the buffer cache */
    301 	bufinit();
    302 
    303 	/*
    304 	 * Initialize mbuf's.  Do this now because we might attempt to
    305 	 * allocate mbufs or mbuf clusters during autoconfiguration.
    306 	 */
    307 	mbinit();
    308 
    309 	/* Initialize sockets. */
    310 	soinit();
    311 
    312 	/*
    313 	 * The following things must be done before autoconfiguration.
    314 	 */
    315 	evcnt_init();		/* initialize event counters */
    316 #if NRND > 0
    317 	rnd_init();		/* initialize RNG */
    318 #endif
    319 
    320 	/* Initialize process and pgrp structures. */
    321 	procinit();
    322 	lwpinit();
    323 
    324 	/* Initialize signal-related data structures. */
    325 	signal_init();
    326 
    327 	/* Create process 0 (the swapper). */
    328 	proc0_init();
    329 
    330 	/* Initialize the UID hash table. */
    331 	uid_init();
    332 
    333 	/* Charge root for one process. */
    334 	(void)chgproccnt(0, 1);
    335 
    336 	/* Initialize the run queues, turnstiles and sleep queues. */
    337 	sched_rqinit();
    338 	turnstile_init();
    339 	sleeptab_init(&sleeptab);
    340 
    341 	/* MI initialization of the boot cpu */
    342 	error = mi_cpu_attach(curcpu());
    343 	KASSERT(error == 0);
    344 
    345 	/* Initialize the sysctl subsystem. */
    346 	sysctl_init();
    347 
    348 	/* Initialize I/O statistics. */
    349 	iostat_init();
    350 
    351 	/* Initialize the file systems. */
    352 #ifdef NVNODE_IMPLICIT
    353 	/*
    354 	 * If maximum number of vnodes in namei vnode cache is not explicitly
    355 	 * defined in kernel config, adjust the number such as we use roughly
    356 	 * 1.0% of memory for vnode cache (but not less than NVNODE vnodes).
    357 	 */
    358 	usevnodes = (ptoa((unsigned)physmem) / 100) / sizeof(struct vnode);
    359 	if (usevnodes > desiredvnodes)
    360 		desiredvnodes = usevnodes;
    361 #endif
    362 	vfsinit();
    363 
    364 	/* Initialize fstrans. */
    365 	fstrans_init();
    366 
    367 	/* Initialize the select()/poll() system calls. */
    368 	selsysinit();
    369 
    370 	/* Initialize asynchronous I/O. */
    371 	aio_sysinit();
    372 
    373 #if NSYSMON_ENVSYS > 0
    374 	sysmon_envsys_init();
    375 #endif
    376 #if NSYSMON_POWER > 0
    377 	sysmon_power_init();
    378 #endif
    379 #ifdef __HAVE_TIMECOUNTER
    380 	inittimecounter();
    381 	ntp_init();
    382 #endif /* __HAVE_TIMECOUNTER */
    383 
    384 	/* Initialize the device switch tables. */
    385 	devsw_init();
    386 
    387 	/* Initialize the disk wedge subsystem. */
    388 	dkwedge_init();
    389 
    390 	/* Configure the system hardware.  This will enable interrupts. */
    391 	configure();
    392 
    393 #if defined(__SSP__) || defined(__SSP_ALL__)
    394 	{
    395 #ifdef DIAGNOSTIC
    396 		printf("Initializing SSP:");
    397 #endif
    398 		/*
    399 		 * We initialize ssp here carefully:
    400 		 *	1. after we got some entropy
    401 		 *	2. without calling a function
    402 		 */
    403 		size_t i;
    404 		long guard[__arraycount(__stack_chk_guard)];
    405 
    406 		arc4randbytes(guard, sizeof(guard));
    407 		for (i = 0; i < __arraycount(guard); i++)
    408 			__stack_chk_guard[i] = guard[i];
    409 #ifdef DIAGNOSTIC
    410 		for (i = 0; i < __arraycount(guard); i++)
    411 			printf("%lx ", guard[i]);
    412 		printf("\n");
    413 #endif
    414 	}
    415 #endif
    416 	ubc_init();		/* must be after autoconfig */
    417 
    418 	/* Lock the kernel on behalf of proc0. */
    419 	KERNEL_LOCK(1, l);
    420 
    421 #ifdef SYSTRACE
    422 	systrace_init();
    423 #endif
    424 
    425 #ifdef SYSVSHM
    426 	/* Initialize System V style shared memory. */
    427 	shminit();
    428 #endif
    429 
    430 #ifdef SYSVSEM
    431 	/* Initialize System V style semaphores. */
    432 	seminit();
    433 #endif
    434 
    435 #ifdef SYSVMSG
    436 	/* Initialize System V style message queues. */
    437 	msginit();
    438 #endif
    439 
    440 #ifdef P1003_1B_SEMAPHORE
    441 	/* Initialize posix semaphores */
    442 	ksem_init();
    443 #endif
    444 
    445 #if NVERIEXEC > 0
    446 	/*
    447 	 * Initialise the Veriexec subsystem.
    448 	 */
    449 	veriexec_init();
    450 #endif /* NVERIEXEC > 0 */
    451 
    452 #if defined(PAX_MPROTECT) || defined(PAX_SEGVGUARD)
    453 	pax_init();
    454 #endif /* PAX_MPROTECT || PAX_SEGVGUARD */
    455 
    456 	/* Attach pseudo-devices. */
    457 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
    458 		(*pdev->pdev_attach)(pdev->pdev_count);
    459 
    460 #ifdef	FAST_IPSEC
    461 	/* Attach network crypto subsystem */
    462 	ipsec_attach();
    463 #endif
    464 
    465 	/*
    466 	 * Initialize protocols.  Block reception of incoming packets
    467 	 * until everything is ready.
    468 	 */
    469 	s = splnet();
    470 	ifinit();
    471 	domaininit();
    472 	if_attachdomain();
    473 	splx(s);
    474 
    475 #ifdef GPROF
    476 	/* Initialize kernel profiling. */
    477 	kmstartup();
    478 #endif
    479 
    480 	/* Initialize system accouting. */
    481 	acct_init();
    482 
    483 #ifndef PIPE_SOCKETPAIR
    484 	/* Initialize pipes. */
    485 	pipe_init();
    486 #endif
    487 
    488 	/* Setup the scheduler */
    489 	sched_init();
    490 
    491 #ifdef KTRACE
    492 	/* Initialize ktrace. */
    493 	ktrinit();
    494 #endif
    495 
    496 	/* Initialize the UUID system calls. */
    497 	uuid_init();
    498 
    499 	/*
    500 	 * Create process 1 (init(8)).  We do this now, as Unix has
    501 	 * historically had init be process 1, and changing this would
    502 	 * probably upset a lot of people.
    503 	 *
    504 	 * Note that process 1 won't immediately exec init(8), but will
    505 	 * wait for us to inform it that the root file system has been
    506 	 * mounted.
    507 	 */
    508 	if (fork1(l, 0, SIGCHLD, NULL, 0, start_init, NULL, NULL, &initproc))
    509 		panic("fork init");
    510 
    511 	/*
    512 	 * Now that device driver threads have been created, wait for
    513 	 * them to finish any deferred autoconfiguration.  Note we don't
    514 	 * need to lock this semaphore, since we haven't booted any
    515 	 * secondary processors, yet.
    516 	 */
    517 	while (config_pending)
    518 		(void) tsleep(&config_pending, PWAIT, "cfpend", 0);
    519 
    520 	/*
    521 	 * Finalize configuration now that all real devices have been
    522 	 * found.  This needs to be done before the root device is
    523 	 * selected, since finalization may create the root device.
    524 	 */
    525 	config_finalize();
    526 
    527 	/*
    528 	 * Now that autoconfiguration has completed, we can determine
    529 	 * the root and dump devices.
    530 	 */
    531 	cpu_rootconf();
    532 	cpu_dumpconf();
    533 
    534 	/* Mount the root file system. */
    535 	do {
    536 		domountroothook();
    537 		if ((error = vfs_mountroot())) {
    538 			printf("cannot mount root, error = %d\n", error);
    539 			boothowto |= RB_ASKNAME;
    540 			setroot(root_device,
    541 			    (rootdev != NODEV) ? DISKPART(rootdev) : 0);
    542 		}
    543 	} while (error != 0);
    544 	mountroothook_destroy();
    545 
    546 	/*
    547 	 * Initialise the time-of-day clock, passing the time recorded
    548 	 * in the root filesystem (if any) for use by systems that
    549 	 * don't have a non-volatile time-of-day device.
    550 	 */
    551 	inittodr(rootfstime);
    552 
    553 	CIRCLEQ_FIRST(&mountlist)->mnt_flag |= MNT_ROOTFS;
    554 	CIRCLEQ_FIRST(&mountlist)->mnt_op->vfs_refcount++;
    555 
    556 	/*
    557 	 * Get the vnode for '/'.  Set filedesc0.fd_fd.fd_cdir to
    558 	 * reference it.
    559 	 */
    560 	error = VFS_ROOT(CIRCLEQ_FIRST(&mountlist), &rootvnode);
    561 	if (error)
    562 		panic("cannot find root vnode, error=%d", error);
    563 	cwdi0.cwdi_cdir = rootvnode;
    564 	VREF(cwdi0.cwdi_cdir);
    565 	VOP_UNLOCK(rootvnode, 0);
    566 	cwdi0.cwdi_rdir = NULL;
    567 
    568 	/*
    569 	 * Now that root is mounted, we can fixup initproc's CWD
    570 	 * info.  All other processes are kthreads, which merely
    571 	 * share proc0's CWD info.
    572 	 */
    573 	initproc->p_cwdi->cwdi_cdir = rootvnode;
    574 	VREF(initproc->p_cwdi->cwdi_cdir);
    575 	initproc->p_cwdi->cwdi_rdir = NULL;
    576 
    577 	/*
    578 	 * Now can look at time, having had a chance to verify the time
    579 	 * from the file system.  Reset l->l_rtime as it may have been
    580 	 * munched in mi_switch() after the time got set.
    581 	 */
    582 #ifdef __HAVE_TIMECOUNTER
    583 	getmicrotime(&time);
    584 #else
    585 	mono_time = time;
    586 #endif
    587 	boottime = time;
    588 	mutex_enter(&proclist_lock);
    589 	LIST_FOREACH(p, &allproc, p_list) {
    590 		KASSERT((p->p_flag & PK_MARKER) == 0);
    591 		mutex_enter(&p->p_smutex);
    592 		p->p_stats->p_start = time;
    593 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    594 			lwp_lock(l);
    595 			l->l_cpu->ci_schedstate.spc_runtime = time;
    596 			l->l_rtime.tv_sec = l->l_rtime.tv_usec = 0;
    597 			lwp_unlock(l);
    598 		}
    599 		mutex_exit(&p->p_smutex);
    600 	}
    601 	mutex_exit(&proclist_lock);
    602 
    603 	/* Create the pageout daemon kernel thread. */
    604 	uvm_swap_init();
    605 	if (kthread_create(PVM, 0, NULL, uvm_pageout,
    606 	    NULL, NULL, "pgdaemon"))
    607 		panic("fork pagedaemon");
    608 
    609 	/* Create the filesystem syncer kernel thread. */
    610 	if (kthread_create(PINOD, 0, NULL, sched_sync, NULL, NULL, "ioflush"))
    611 		panic("fork syncer");
    612 
    613 	/* Create the aiodone daemon kernel thread. */
    614 	if (workqueue_create(&uvm.aiodone_queue, "aiodoned",
    615 	    uvm_aiodone_worker, NULL, PVM, IPL_BIO, 0))
    616 		panic("fork aiodoned");
    617 
    618 	vmem_rehash_start();
    619 
    620 #if defined(MULTIPROCESSOR)
    621 	/* Boot the secondary processors. */
    622 	cpu_boot_secondary_processors();
    623 #endif
    624 
    625 	/* Initialize exec structures */
    626 	exec_init(1);
    627 
    628 	/*
    629 	 * Okay, now we can let init(8) exec!  It's off to userland!
    630 	 */
    631 	start_init_exec = 1;
    632 	wakeup(&start_init_exec);
    633 
    634 	/* The scheduler is an infinite loop. */
    635 	uvm_scheduler();
    636 	/* NOTREACHED */
    637 }
    638 
    639 void
    640 setrootfstime(time_t t)
    641 {
    642 	rootfstime = t;
    643 }
    644 
    645 static void
    646 check_console(struct lwp *l)
    647 {
    648 	struct nameidata nd;
    649 	int error;
    650 
    651 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/console", l);
    652 	error = namei(&nd);
    653 	if (error == 0)
    654 		vrele(nd.ni_vp);
    655 	else if (error == ENOENT)
    656 		printf("warning: no /dev/console\n");
    657 	else
    658 		printf("warning: lookup /dev/console: error %d\n", error);
    659 }
    660 
    661 /*
    662  * List of paths to try when searching for "init".
    663  */
    664 static const char *initpaths[] = {
    665 	"/sbin/init",
    666 	"/sbin/oinit",
    667 	"/sbin/init.bak",
    668 	NULL,
    669 };
    670 
    671 /*
    672  * Start the initial user process; try exec'ing each pathname in "initpaths".
    673  * The program is invoked with one argument containing the boot flags.
    674  */
    675 static void
    676 start_init(void *arg)
    677 {
    678 	struct lwp *l = arg;
    679 	struct proc *p = l->l_proc;
    680 	vaddr_t addr;
    681 	struct sys_execve_args /* {
    682 		syscallarg(const char *) path;
    683 		syscallarg(char * const *) argp;
    684 		syscallarg(char * const *) envp;
    685 	} */ args;
    686 	int options, i, error;
    687 	register_t retval[2];
    688 	char flags[4], *flagsp;
    689 	const char *path, *slash;
    690 	char *ucp, **uap, *arg0, *arg1 = NULL;
    691 	char ipath[129];
    692 	int ipx, len;
    693 
    694 	/*
    695 	 * Now in process 1.
    696 	 */
    697 	strncpy(p->p_comm, "init", MAXCOMLEN);
    698 
    699 	/*
    700 	 * Wait for main() to tell us that it's safe to exec.
    701 	 */
    702 	while (start_init_exec == 0)
    703 		(void) tsleep(&start_init_exec, PWAIT, "initexec", 0);
    704 
    705 	/*
    706 	 * This is not the right way to do this.  We really should
    707 	 * hand-craft a descriptor onto /dev/console to hand to init,
    708 	 * but that's a _lot_ more work, and the benefit from this easy
    709 	 * hack makes up for the "good is the enemy of the best" effect.
    710 	 */
    711 	check_console(l);
    712 
    713 	/*
    714 	 * Need just enough stack to hold the faked-up "execve()" arguments.
    715 	 */
    716 	addr = (vaddr_t)STACK_ALLOC(USRSTACK, PAGE_SIZE);
    717 	if (uvm_map(&p->p_vmspace->vm_map, &addr, PAGE_SIZE,
    718                     NULL, UVM_UNKNOWN_OFFSET, 0,
    719                     UVM_MAPFLAG(UVM_PROT_ALL, UVM_PROT_ALL, UVM_INH_COPY,
    720 		    UVM_ADV_NORMAL,
    721                     UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW)) != 0)
    722 		panic("init: couldn't allocate argument space");
    723 	p->p_vmspace->vm_maxsaddr = (void *)STACK_MAX(addr, PAGE_SIZE);
    724 
    725 	ipx = 0;
    726 	while (1) {
    727 		if (boothowto & RB_ASKNAME) {
    728 			printf("init path");
    729 			if (initpaths[ipx])
    730 				printf(" (default %s)", initpaths[ipx]);
    731 			printf(": ");
    732 			len = cngetsn(ipath, sizeof(ipath)-1);
    733 			if (len == 0) {
    734 				if (initpaths[ipx])
    735 					path = initpaths[ipx++];
    736 				else
    737 					continue;
    738 			} else {
    739 				ipath[len] = '\0';
    740 				path = ipath;
    741 			}
    742 		} else {
    743 			if ((path = initpaths[ipx++]) == NULL)
    744 				break;
    745 		}
    746 
    747 		ucp = (char *)USRSTACK;
    748 
    749 		/*
    750 		 * Construct the boot flag argument.
    751 		 */
    752 		flagsp = flags;
    753 		*flagsp++ = '-';
    754 		options = 0;
    755 
    756 		if (boothowto & RB_SINGLE) {
    757 			*flagsp++ = 's';
    758 			options = 1;
    759 		}
    760 #ifdef notyet
    761 		if (boothowto & RB_FASTBOOT) {
    762 			*flagsp++ = 'f';
    763 			options = 1;
    764 		}
    765 #endif
    766 
    767 		/*
    768 		 * Move out the flags (arg 1), if necessary.
    769 		 */
    770 		if (options != 0) {
    771 			*flagsp++ = '\0';
    772 			i = flagsp - flags;
    773 #ifdef DEBUG
    774 			printf("init: copying out flags `%s' %d\n", flags, i);
    775 #endif
    776 			arg1 = STACK_ALLOC(ucp, i);
    777 			ucp = STACK_MAX(arg1, i);
    778 			(void)copyout((void *)flags, arg1, i);
    779 		}
    780 
    781 		/*
    782 		 * Move out the file name (also arg 0).
    783 		 */
    784 		i = strlen(path) + 1;
    785 #ifdef DEBUG
    786 		printf("init: copying out path `%s' %d\n", path, i);
    787 #else
    788 		if (boothowto & RB_ASKNAME || path != initpaths[0])
    789 			printf("init: trying %s\n", path);
    790 #endif
    791 		arg0 = STACK_ALLOC(ucp, i);
    792 		ucp = STACK_MAX(arg0, i);
    793 		(void)copyout(path, arg0, i);
    794 
    795 		/*
    796 		 * Move out the arg pointers.
    797 		 */
    798 		ucp = (void *)STACK_ALIGN(ucp, ALIGNBYTES);
    799 		uap = (char **)STACK_ALLOC(ucp, sizeof(char *) * 3);
    800 		SCARG(&args, path) = arg0;
    801 		SCARG(&args, argp) = uap;
    802 		SCARG(&args, envp) = NULL;
    803 		slash = strrchr(path, '/');
    804 		if (slash)
    805 			(void)suword((void *)uap++,
    806 			    (long)arg0 + (slash + 1 - path));
    807 		else
    808 			(void)suword((void *)uap++, (long)arg0);
    809 		if (options != 0)
    810 			(void)suword((void *)uap++, (long)arg1);
    811 		(void)suword((void *)uap++, 0);	/* terminator */
    812 
    813 		/*
    814 		 * Now try to exec the program.  If can't for any reason
    815 		 * other than it doesn't exist, complain.
    816 		 */
    817 		error = sys_execve(l, &args, retval);
    818 		if (error == 0 || error == EJUSTRETURN) {
    819 			KERNEL_UNLOCK_LAST(l);
    820 			return;
    821 		}
    822 		printf("exec %s: error %d\n", path, error);
    823 	}
    824 	printf("init: not found\n");
    825 	panic("no init");
    826 }
    827