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