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