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