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