xref: /freebsd/sys/kern/init_main.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1995 Terrence R. Lambert
5  * All rights reserved.
6  *
7  * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
8  *	The Regents of the University of California.  All rights reserved.
9  * (c) UNIX System Laboratories, Inc.
10  * All or some portions of this file are derived from material licensed
11  * to the University of California by American Telephone and Telegraph
12  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
13  * the permission of UNIX System Laboratories, Inc.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgement:
25  *	This product includes software developed by the University of
26  *	California, Berkeley and its contributors.
27  * 4. Neither the name of the University nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  *	@(#)init_main.c	8.9 (Berkeley) 1/21/94
44  */
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include "opt_ddb.h"
50 #include "opt_init_path.h"
51 #include "opt_verbose_sysinit.h"
52 
53 #include <sys/param.h>
54 #include <sys/kernel.h>
55 #include <sys/exec.h>
56 #include <sys/file.h>
57 #include <sys/filedesc.h>
58 #include <sys/jail.h>
59 #include <sys/ktr.h>
60 #include <sys/lock.h>
61 #include <sys/loginclass.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysctl.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/resourcevar.h>
69 #include <sys/systm.h>
70 #include <sys/signalvar.h>
71 #include <sys/vnode.h>
72 #include <sys/sysent.h>
73 #include <sys/reboot.h>
74 #include <sys/sched.h>
75 #include <sys/sx.h>
76 #include <sys/sysproto.h>
77 #include <sys/vmmeter.h>
78 #include <sys/unistd.h>
79 #include <sys/malloc.h>
80 #include <sys/conf.h>
81 #include <sys/cpuset.h>
82 
83 #include <machine/cpu.h>
84 
85 #include <security/audit/audit.h>
86 #include <security/mac/mac_framework.h>
87 
88 #include <vm/vm.h>
89 #include <vm/vm_param.h>
90 #include <vm/pmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_domain.h>
93 #include <sys/copyright.h>
94 
95 #include <ddb/ddb.h>
96 #include <ddb/db_sym.h>
97 
98 void mi_startup(void);				/* Should be elsewhere */
99 
100 /* Components of the first process -- never freed. */
101 static struct session session0;
102 static struct pgrp pgrp0;
103 struct	proc proc0;
104 struct thread0_storage thread0_st __aligned(32);
105 struct	vmspace vmspace0;
106 struct	proc *initproc;
107 
108 #ifndef BOOTHOWTO
109 #define	BOOTHOWTO	0
110 #endif
111 int	boothowto = BOOTHOWTO;	/* initialized so that it can be patched */
112 SYSCTL_INT(_debug, OID_AUTO, boothowto, CTLFLAG_RD, &boothowto, 0,
113 	"Boot control flags, passed from loader");
114 
115 #ifndef BOOTVERBOSE
116 #define	BOOTVERBOSE	0
117 #endif
118 int	bootverbose = BOOTVERBOSE;
119 SYSCTL_INT(_debug, OID_AUTO, bootverbose, CTLFLAG_RW, &bootverbose, 0,
120 	"Control the output of verbose kernel messages");
121 
122 #ifdef INVARIANTS
123 FEATURE(invariants, "Kernel compiled with INVARIANTS, may affect performance");
124 #endif
125 
126 /*
127  * This ensures that there is at least one entry so that the sysinit_set
128  * symbol is not undefined.  A sybsystem ID of SI_SUB_DUMMY is never
129  * executed.
130  */
131 SYSINIT(placeholder, SI_SUB_DUMMY, SI_ORDER_ANY, NULL, NULL);
132 
133 /*
134  * The sysinit table itself.  Items are checked off as the are run.
135  * If we want to register new sysinit types, add them to newsysinit.
136  */
137 SET_DECLARE(sysinit_set, struct sysinit);
138 struct sysinit **sysinit, **sysinit_end;
139 struct sysinit **newsysinit, **newsysinit_end;
140 
141 EVENTHANDLER_LIST_DECLARE(process_init);
142 EVENTHANDLER_LIST_DECLARE(thread_init);
143 EVENTHANDLER_LIST_DECLARE(process_ctor);
144 EVENTHANDLER_LIST_DECLARE(thread_ctor);
145 
146 /*
147  * Merge a new sysinit set into the current set, reallocating it if
148  * necessary.  This can only be called after malloc is running.
149  */
150 void
151 sysinit_add(struct sysinit **set, struct sysinit **set_end)
152 {
153 	struct sysinit **newset;
154 	struct sysinit **sipp;
155 	struct sysinit **xipp;
156 	int count;
157 
158 	count = set_end - set;
159 	if (newsysinit)
160 		count += newsysinit_end - newsysinit;
161 	else
162 		count += sysinit_end - sysinit;
163 	newset = malloc(count * sizeof(*sipp), M_TEMP, M_NOWAIT);
164 	if (newset == NULL)
165 		panic("cannot malloc for sysinit");
166 	xipp = newset;
167 	if (newsysinit)
168 		for (sipp = newsysinit; sipp < newsysinit_end; sipp++)
169 			*xipp++ = *sipp;
170 	else
171 		for (sipp = sysinit; sipp < sysinit_end; sipp++)
172 			*xipp++ = *sipp;
173 	for (sipp = set; sipp < set_end; sipp++)
174 		*xipp++ = *sipp;
175 	if (newsysinit)
176 		free(newsysinit, M_TEMP);
177 	newsysinit = newset;
178 	newsysinit_end = newset + count;
179 }
180 
181 #if defined (DDB) && defined(VERBOSE_SYSINIT)
182 static const char *
183 symbol_name(vm_offset_t va, db_strategy_t strategy)
184 {
185 	const char *name;
186 	c_db_sym_t sym;
187 	db_expr_t  offset;
188 
189 	if (va == 0)
190 		return (NULL);
191 	sym = db_search_symbol(va, strategy, &offset);
192 	if (offset != 0)
193 		return (NULL);
194 	db_symbol_values(sym, &name, NULL);
195 	return (name);
196 }
197 #endif
198 
199 /*
200  * System startup; initialize the world, create process 0, mount root
201  * filesystem, and fork to create init and pagedaemon.  Most of the
202  * hard work is done in the lower-level initialization routines including
203  * startup(), which does memory initialization and autoconfiguration.
204  *
205  * This allows simple addition of new kernel subsystems that require
206  * boot time initialization.  It also allows substitution of subsystem
207  * (for instance, a scheduler, kernel profiler, or VM system) by object
208  * module.  Finally, it allows for optional "kernel threads".
209  */
210 void
211 mi_startup(void)
212 {
213 
214 	struct sysinit **sipp;	/* system initialization*/
215 	struct sysinit **xipp;	/* interior loop of sort*/
216 	struct sysinit *save;	/* bubble*/
217 
218 #if defined(VERBOSE_SYSINIT)
219 	int last;
220 	int verbose;
221 #endif
222 
223 	if (boothowto & RB_VERBOSE)
224 		bootverbose++;
225 
226 	if (sysinit == NULL) {
227 		sysinit = SET_BEGIN(sysinit_set);
228 		sysinit_end = SET_LIMIT(sysinit_set);
229 	}
230 
231 restart:
232 	/*
233 	 * Perform a bubble sort of the system initialization objects by
234 	 * their subsystem (primary key) and order (secondary key).
235 	 */
236 	for (sipp = sysinit; sipp < sysinit_end; sipp++) {
237 		for (xipp = sipp + 1; xipp < sysinit_end; xipp++) {
238 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
239 			     ((*sipp)->subsystem == (*xipp)->subsystem &&
240 			      (*sipp)->order <= (*xipp)->order))
241 				continue;	/* skip*/
242 			save = *sipp;
243 			*sipp = *xipp;
244 			*xipp = save;
245 		}
246 	}
247 
248 #if defined(VERBOSE_SYSINIT)
249 	last = SI_SUB_COPYRIGHT;
250 	verbose = 0;
251 #if !defined(DDB)
252 	printf("VERBOSE_SYSINIT: DDB not enabled, symbol lookups disabled.\n");
253 #endif
254 #endif
255 
256 	/*
257 	 * Traverse the (now) ordered list of system initialization tasks.
258 	 * Perform each task, and continue on to the next task.
259 	 */
260 	for (sipp = sysinit; sipp < sysinit_end; sipp++) {
261 
262 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
263 			continue;	/* skip dummy task(s)*/
264 
265 		if ((*sipp)->subsystem == SI_SUB_DONE)
266 			continue;
267 
268 #if defined(VERBOSE_SYSINIT)
269 		if ((*sipp)->subsystem > last) {
270 			verbose = 1;
271 			last = (*sipp)->subsystem;
272 			printf("subsystem %x\n", last);
273 		}
274 		if (verbose) {
275 #if defined(DDB)
276 			const char *func, *data;
277 
278 			func = symbol_name((vm_offset_t)(*sipp)->func,
279 			    DB_STGY_PROC);
280 			data = symbol_name((vm_offset_t)(*sipp)->udata,
281 			    DB_STGY_ANY);
282 			if (func != NULL && data != NULL)
283 				printf("   %s(&%s)... ", func, data);
284 			else if (func != NULL)
285 				printf("   %s(%p)... ", func, (*sipp)->udata);
286 			else
287 #endif
288 				printf("   %p(%p)... ", (*sipp)->func,
289 				    (*sipp)->udata);
290 		}
291 #endif
292 
293 		/* Call function */
294 		(*((*sipp)->func))((*sipp)->udata);
295 
296 #if defined(VERBOSE_SYSINIT)
297 		if (verbose)
298 			printf("done.\n");
299 #endif
300 
301 		/* Check off the one we're just done */
302 		(*sipp)->subsystem = SI_SUB_DONE;
303 
304 		/* Check if we've installed more sysinit items via KLD */
305 		if (newsysinit != NULL) {
306 			if (sysinit != SET_BEGIN(sysinit_set))
307 				free(sysinit, M_TEMP);
308 			sysinit = newsysinit;
309 			sysinit_end = newsysinit_end;
310 			newsysinit = NULL;
311 			newsysinit_end = NULL;
312 			goto restart;
313 		}
314 	}
315 
316 	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
317 	mtx_unlock(&Giant);
318 
319 	/*
320 	 * Now hand over this thread to swapper.
321 	 */
322 	swapper();
323 	/* NOTREACHED*/
324 }
325 
326 static void
327 print_caddr_t(void *data)
328 {
329 	printf("%s", (char *)data);
330 }
331 
332 static void
333 print_version(void *data __unused)
334 {
335 	int len;
336 
337 	/* Strip a trailing newline from version. */
338 	len = strlen(version);
339 	while (len > 0 && version[len - 1] == '\n')
340 		len--;
341 	printf("%.*s %s\n", len, version, machine);
342 	printf("%s\n", compiler_version);
343 }
344 
345 SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t,
346     copyright);
347 SYSINIT(trademark, SI_SUB_COPYRIGHT, SI_ORDER_SECOND, print_caddr_t,
348     trademark);
349 SYSINIT(version, SI_SUB_COPYRIGHT, SI_ORDER_THIRD, print_version, NULL);
350 
351 #ifdef WITNESS
352 static char wit_warn[] =
353      "WARNING: WITNESS option enabled, expect reduced performance.\n";
354 SYSINIT(witwarn, SI_SUB_COPYRIGHT, SI_ORDER_THIRD + 1,
355    print_caddr_t, wit_warn);
356 SYSINIT(witwarn2, SI_SUB_LAST, SI_ORDER_THIRD + 1,
357    print_caddr_t, wit_warn);
358 #endif
359 
360 #ifdef DIAGNOSTIC
361 static char diag_warn[] =
362      "WARNING: DIAGNOSTIC option enabled, expect reduced performance.\n";
363 SYSINIT(diagwarn, SI_SUB_COPYRIGHT, SI_ORDER_THIRD + 2,
364     print_caddr_t, diag_warn);
365 SYSINIT(diagwarn2, SI_SUB_LAST, SI_ORDER_THIRD + 2,
366     print_caddr_t, diag_warn);
367 #endif
368 
369 static int
370 null_fetch_syscall_args(struct thread *td __unused)
371 {
372 
373 	panic("null_fetch_syscall_args");
374 }
375 
376 static void
377 null_set_syscall_retval(struct thread *td __unused, int error __unused)
378 {
379 
380 	panic("null_set_syscall_retval");
381 }
382 
383 struct sysentvec null_sysvec = {
384 	.sv_size	= 0,
385 	.sv_table	= NULL,
386 	.sv_mask	= 0,
387 	.sv_errsize	= 0,
388 	.sv_errtbl	= NULL,
389 	.sv_transtrap	= NULL,
390 	.sv_fixup	= NULL,
391 	.sv_sendsig	= NULL,
392 	.sv_sigcode	= NULL,
393 	.sv_szsigcode	= NULL,
394 	.sv_name	= "null",
395 	.sv_coredump	= NULL,
396 	.sv_imgact_try	= NULL,
397 	.sv_minsigstksz	= 0,
398 	.sv_pagesize	= PAGE_SIZE,
399 	.sv_minuser	= VM_MIN_ADDRESS,
400 	.sv_maxuser	= VM_MAXUSER_ADDRESS,
401 	.sv_usrstack	= USRSTACK,
402 	.sv_psstrings	= PS_STRINGS,
403 	.sv_stackprot	= VM_PROT_ALL,
404 	.sv_copyout_strings	= NULL,
405 	.sv_setregs	= NULL,
406 	.sv_fixlimit	= NULL,
407 	.sv_maxssiz	= NULL,
408 	.sv_flags	= 0,
409 	.sv_set_syscall_retval = null_set_syscall_retval,
410 	.sv_fetch_syscall_args = null_fetch_syscall_args,
411 	.sv_syscallnames = NULL,
412 	.sv_schedtail	= NULL,
413 	.sv_thread_detach = NULL,
414 	.sv_trap	= NULL,
415 };
416 
417 /*
418  * The two following SYSINIT's are proc0 specific glue code.  I am not
419  * convinced that they can not be safely combined, but their order of
420  * operation has been maintained as the same as the original init_main.c
421  * for right now.
422  */
423 /* ARGSUSED*/
424 static void
425 proc0_init(void *dummy __unused)
426 {
427 	struct proc *p;
428 	struct thread *td;
429 	struct ucred *newcred;
430 	struct uidinfo tmpuinfo;
431 	struct loginclass tmplc = {
432 		.lc_name = "",
433 	};
434 	vm_paddr_t pageablemem;
435 	int i;
436 
437 	GIANT_REQUIRED;
438 	p = &proc0;
439 	td = &thread0;
440 
441 	/*
442 	 * Initialize magic number and osrel.
443 	 */
444 	p->p_magic = P_MAGIC;
445 	p->p_osrel = osreldate;
446 
447 	/*
448 	 * Initialize thread and process structures.
449 	 */
450 	procinit();	/* set up proc zone */
451 	threadinit();	/* set up UMA zones */
452 
453 	/*
454 	 * Initialise scheduler resources.
455 	 * Add scheduler specific parts to proc, thread as needed.
456 	 */
457 	schedinit();	/* scheduler gets its house in order */
458 
459 	/*
460 	 * Create process 0 (the swapper).
461 	 */
462 	LIST_INSERT_HEAD(&allproc, p, p_list);
463 	LIST_INSERT_HEAD(PIDHASH(0), p, p_hash);
464 	mtx_init(&pgrp0.pg_mtx, "process group", NULL, MTX_DEF | MTX_DUPOK);
465 	p->p_pgrp = &pgrp0;
466 	LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
467 	LIST_INIT(&pgrp0.pg_members);
468 	LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
469 
470 	pgrp0.pg_session = &session0;
471 	mtx_init(&session0.s_mtx, "session", NULL, MTX_DEF);
472 	refcount_init(&session0.s_count, 1);
473 	session0.s_leader = p;
474 
475 	p->p_sysent = &null_sysvec;
476 	p->p_flag = P_SYSTEM | P_INMEM | P_KPROC;
477 	p->p_flag2 = 0;
478 	p->p_state = PRS_NORMAL;
479 	p->p_klist = knlist_alloc(&p->p_mtx);
480 	STAILQ_INIT(&p->p_ktr);
481 	p->p_nice = NZERO;
482 	/* pid_max cannot be greater than PID_MAX */
483 	td->td_tid = PID_MAX + 1;
484 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
485 	td->td_state = TDS_RUNNING;
486 	td->td_pri_class = PRI_TIMESHARE;
487 	td->td_user_pri = PUSER;
488 	td->td_base_user_pri = PUSER;
489 	td->td_lend_user_pri = PRI_MAX;
490 	td->td_priority = PVM;
491 	td->td_base_pri = PVM;
492 	td->td_oncpu = curcpu;
493 	td->td_flags = TDF_INMEM;
494 	td->td_pflags = TDP_KTHREAD;
495 	td->td_cpuset = cpuset_thread0();
496 	vm_domain_policy_init(&td->td_vm_dom_policy);
497 	vm_domain_policy_set(&td->td_vm_dom_policy, VM_POLICY_NONE, -1);
498 	vm_domain_policy_init(&p->p_vm_dom_policy);
499 	vm_domain_policy_set(&p->p_vm_dom_policy, VM_POLICY_NONE, -1);
500 	prison0_init();
501 	p->p_peers = 0;
502 	p->p_leader = p;
503 	p->p_reaper = p;
504 	LIST_INIT(&p->p_reaplist);
505 
506 	strncpy(p->p_comm, "kernel", sizeof (p->p_comm));
507 	strncpy(td->td_name, "swapper", sizeof (td->td_name));
508 
509 	callout_init_mtx(&p->p_itcallout, &p->p_mtx, 0);
510 	callout_init_mtx(&p->p_limco, &p->p_mtx, 0);
511 	callout_init(&td->td_slpcallout, 1);
512 
513 	/* Create credentials. */
514 	newcred = crget();
515 	newcred->cr_ngroups = 1;	/* group 0 */
516 	/* A hack to prevent uifind from tripping over NULL pointers. */
517 	curthread->td_ucred = newcred;
518 	tmpuinfo.ui_uid = 1;
519 	newcred->cr_uidinfo = newcred->cr_ruidinfo = &tmpuinfo;
520 	newcred->cr_uidinfo = uifind(0);
521 	newcred->cr_ruidinfo = uifind(0);
522 	newcred->cr_loginclass = &tmplc;
523 	newcred->cr_loginclass = loginclass_find("default");
524 	/* End hack. creds get properly set later with thread_cow_get_proc */
525 	curthread->td_ucred = NULL;
526 	newcred->cr_prison = &prison0;
527 	proc_set_cred_init(p, newcred);
528 #ifdef AUDIT
529 	audit_cred_kproc0(newcred);
530 #endif
531 #ifdef MAC
532 	mac_cred_create_swapper(newcred);
533 #endif
534 	/* Create sigacts. */
535 	p->p_sigacts = sigacts_alloc();
536 
537 	/* Initialize signal state for process 0. */
538 	siginit(&proc0);
539 
540 	/* Create the file descriptor table. */
541 	p->p_fd = fdinit(NULL, false);
542 	p->p_fdtol = NULL;
543 
544 	/* Create the limits structures. */
545 	p->p_limit = lim_alloc();
546 	for (i = 0; i < RLIM_NLIMITS; i++)
547 		p->p_limit->pl_rlimit[i].rlim_cur =
548 		    p->p_limit->pl_rlimit[i].rlim_max = RLIM_INFINITY;
549 	p->p_limit->pl_rlimit[RLIMIT_NOFILE].rlim_cur =
550 	    p->p_limit->pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
551 	p->p_limit->pl_rlimit[RLIMIT_NPROC].rlim_cur =
552 	    p->p_limit->pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
553 	p->p_limit->pl_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
554 	p->p_limit->pl_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
555 	p->p_limit->pl_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
556 	p->p_limit->pl_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
557 	/* Cast to avoid overflow on i386/PAE. */
558 	pageablemem = ptoa((vm_paddr_t)vm_cnt.v_free_count);
559 	p->p_limit->pl_rlimit[RLIMIT_RSS].rlim_cur =
560 	    p->p_limit->pl_rlimit[RLIMIT_RSS].rlim_max = pageablemem;
561 	p->p_limit->pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = pageablemem / 3;
562 	p->p_limit->pl_rlimit[RLIMIT_MEMLOCK].rlim_max = pageablemem;
563 	p->p_cpulimit = RLIM_INFINITY;
564 
565 	PROC_LOCK(p);
566 	thread_cow_get_proc(td, p);
567 	PROC_UNLOCK(p);
568 
569 	/* Initialize resource accounting structures. */
570 	racct_create(&p->p_racct);
571 
572 	p->p_stats = pstats_alloc();
573 
574 	/* Allocate a prototype map so we have something to fork. */
575 	p->p_vmspace = &vmspace0;
576 	vmspace0.vm_refcnt = 1;
577 	pmap_pinit0(vmspace_pmap(&vmspace0));
578 
579 	/*
580 	 * proc0 is not expected to enter usermode, so there is no special
581 	 * handling for sv_minuser here, like is done for exec_new_vmspace().
582 	 */
583 	vm_map_init(&vmspace0.vm_map, vmspace_pmap(&vmspace0),
584 	    p->p_sysent->sv_minuser, p->p_sysent->sv_maxuser);
585 
586 	/*
587 	 * Call the init and ctor for the new thread and proc.  We wait
588 	 * to do this until all other structures are fairly sane.
589 	 */
590 	EVENTHANDLER_DIRECT_INVOKE(process_init, p);
591 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
592 	EVENTHANDLER_DIRECT_INVOKE(process_ctor, p);
593 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
594 
595 	/*
596 	 * Charge root for one process.
597 	 */
598 	(void)chgproccnt(p->p_ucred->cr_ruidinfo, 1, 0);
599 	PROC_LOCK(p);
600 	racct_add_force(p, RACCT_NPROC, 1);
601 	PROC_UNLOCK(p);
602 }
603 SYSINIT(p0init, SI_SUB_INTRINSIC, SI_ORDER_FIRST, proc0_init, NULL);
604 
605 /* ARGSUSED*/
606 static void
607 proc0_post(void *dummy __unused)
608 {
609 	struct timespec ts;
610 	struct proc *p;
611 	struct rusage ru;
612 	struct thread *td;
613 
614 	/*
615 	 * Now we can look at the time, having had a chance to verify the
616 	 * time from the filesystem.  Pretend that proc0 started now.
617 	 */
618 	sx_slock(&allproc_lock);
619 	FOREACH_PROC_IN_SYSTEM(p) {
620 		microuptime(&p->p_stats->p_start);
621 		PROC_STATLOCK(p);
622 		rufetch(p, &ru);	/* Clears thread stats */
623 		PROC_STATUNLOCK(p);
624 		p->p_rux.rux_runtime = 0;
625 		p->p_rux.rux_uticks = 0;
626 		p->p_rux.rux_sticks = 0;
627 		p->p_rux.rux_iticks = 0;
628 		FOREACH_THREAD_IN_PROC(p, td) {
629 			td->td_runtime = 0;
630 		}
631 	}
632 	sx_sunlock(&allproc_lock);
633 	PCPU_SET(switchtime, cpu_ticks());
634 	PCPU_SET(switchticks, ticks);
635 
636 	/*
637 	 * Give the ``random'' number generator a thump.
638 	 */
639 	nanotime(&ts);
640 	srandom(ts.tv_sec ^ ts.tv_nsec);
641 }
642 SYSINIT(p0post, SI_SUB_INTRINSIC_POST, SI_ORDER_FIRST, proc0_post, NULL);
643 
644 static void
645 random_init(void *dummy __unused)
646 {
647 
648 	/*
649 	 * After CPU has been started we have some randomness on most
650 	 * platforms via get_cyclecount().  For platforms that don't
651 	 * we will reseed random(9) in proc0_post() as well.
652 	 */
653 	srandom(get_cyclecount());
654 }
655 SYSINIT(random, SI_SUB_RANDOM, SI_ORDER_FIRST, random_init, NULL);
656 
657 /*
658  ***************************************************************************
659  ****
660  **** The following SYSINIT's and glue code should be moved to the
661  **** respective files on a per subsystem basis.
662  ****
663  ***************************************************************************
664  */
665 
666 /*
667  * List of paths to try when searching for "init".
668  */
669 static char init_path[MAXPATHLEN] =
670 #ifdef	INIT_PATH
671     __XSTRING(INIT_PATH);
672 #else
673     "/sbin/init:/sbin/oinit:/sbin/init.bak:/rescue/init";
674 #endif
675 SYSCTL_STRING(_kern, OID_AUTO, init_path, CTLFLAG_RD, init_path, 0,
676 	"Path used to search the init process");
677 
678 /*
679  * Shutdown timeout of init(8).
680  * Unused within kernel, but used to control init(8), hence do not remove.
681  */
682 #ifndef INIT_SHUTDOWN_TIMEOUT
683 #define INIT_SHUTDOWN_TIMEOUT 120
684 #endif
685 static int init_shutdown_timeout = INIT_SHUTDOWN_TIMEOUT;
686 SYSCTL_INT(_kern, OID_AUTO, init_shutdown_timeout,
687 	CTLFLAG_RW, &init_shutdown_timeout, 0, "Shutdown timeout of init(8). "
688 	"Unused within kernel, but used to control init(8)");
689 
690 /*
691  * Start the initial user process; try exec'ing each pathname in init_path.
692  * The program is invoked with one argument containing the boot flags.
693  */
694 static void
695 start_init(void *dummy)
696 {
697 	vm_offset_t addr;
698 	struct execve_args args;
699 	int options, error;
700 	char *var, *path, *next, *s;
701 	char *ucp, **uap, *arg0, *arg1;
702 	struct thread *td;
703 	struct proc *p;
704 
705 	mtx_lock(&Giant);
706 
707 	GIANT_REQUIRED;
708 
709 	td = curthread;
710 	p = td->td_proc;
711 
712 	vfs_mountroot();
713 
714 	/* Wipe GELI passphrase from the environment. */
715 	kern_unsetenv("kern.geom.eli.passphrase");
716 
717 	/*
718 	 * Need just enough stack to hold the faked-up "execve()" arguments.
719 	 */
720 	addr = p->p_sysent->sv_usrstack - PAGE_SIZE;
721 	if (vm_map_find(&p->p_vmspace->vm_map, NULL, 0, &addr, PAGE_SIZE, 0,
722 	    VMFS_NO_SPACE, VM_PROT_ALL, VM_PROT_ALL, 0) != 0)
723 		panic("init: couldn't allocate argument space");
724 	p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
725 	p->p_vmspace->vm_ssize = 1;
726 
727 	if ((var = kern_getenv("init_path")) != NULL) {
728 		strlcpy(init_path, var, sizeof(init_path));
729 		freeenv(var);
730 	}
731 
732 	for (path = init_path; *path != '\0'; path = next) {
733 		while (*path == ':')
734 			path++;
735 		if (*path == '\0')
736 			break;
737 		for (next = path; *next != '\0' && *next != ':'; next++)
738 			/* nothing */ ;
739 		if (bootverbose)
740 			printf("start_init: trying %.*s\n", (int)(next - path),
741 			    path);
742 
743 		/*
744 		 * Move out the boot flag argument.
745 		 */
746 		options = 0;
747 		ucp = (char *)p->p_sysent->sv_usrstack;
748 		(void)subyte(--ucp, 0);		/* trailing zero */
749 		if (boothowto & RB_SINGLE) {
750 			(void)subyte(--ucp, 's');
751 			options = 1;
752 		}
753 #ifdef notyet
754                 if (boothowto & RB_FASTBOOT) {
755 			(void)subyte(--ucp, 'f');
756 			options = 1;
757 		}
758 #endif
759 
760 #ifdef BOOTCDROM
761 		(void)subyte(--ucp, 'C');
762 		options = 1;
763 #endif
764 
765 		if (options == 0)
766 			(void)subyte(--ucp, '-');
767 		(void)subyte(--ucp, '-');		/* leading hyphen */
768 		arg1 = ucp;
769 
770 		/*
771 		 * Move out the file name (also arg 0).
772 		 */
773 		(void)subyte(--ucp, 0);
774 		for (s = next - 1; s >= path; s--)
775 			(void)subyte(--ucp, *s);
776 		arg0 = ucp;
777 
778 		/*
779 		 * Move out the arg pointers.
780 		 */
781 		uap = (char **)rounddown2((intptr_t)ucp, sizeof(intptr_t));
782 		(void)suword((caddr_t)--uap, (long)0);	/* terminator */
783 		(void)suword((caddr_t)--uap, (long)(intptr_t)arg1);
784 		(void)suword((caddr_t)--uap, (long)(intptr_t)arg0);
785 
786 		/*
787 		 * Point at the arguments.
788 		 */
789 		args.fname = arg0;
790 		args.argv = uap;
791 		args.envv = NULL;
792 
793 		/*
794 		 * Now try to exec the program.  If can't for any reason
795 		 * other than it doesn't exist, complain.
796 		 *
797 		 * Otherwise, return via fork_trampoline() all the way
798 		 * to user mode as init!
799 		 */
800 		if ((error = sys_execve(td, &args)) == EJUSTRETURN) {
801 			mtx_unlock(&Giant);
802 			return;
803 		}
804 		if (error != ENOENT)
805 			printf("exec %.*s: error %d\n", (int)(next - path),
806 			    path, error);
807 	}
808 	printf("init: not found in path %s\n", init_path);
809 	panic("no init");
810 }
811 
812 /*
813  * Like kproc_create(), but runs in its own address space.
814  * We do this early to reserve pid 1.
815  *
816  * Note special case - do not make it runnable yet.  Other work
817  * in progress will change this more.
818  */
819 static void
820 create_init(const void *udata __unused)
821 {
822 	struct fork_req fr;
823 	struct ucred *newcred, *oldcred;
824 	struct thread *td;
825 	int error;
826 
827 	bzero(&fr, sizeof(fr));
828 	fr.fr_flags = RFFDG | RFPROC | RFSTOPPED;
829 	fr.fr_procp = &initproc;
830 	error = fork1(&thread0, &fr);
831 	if (error)
832 		panic("cannot fork init: %d\n", error);
833 	KASSERT(initproc->p_pid == 1, ("create_init: initproc->p_pid != 1"));
834 	/* divorce init's credentials from the kernel's */
835 	newcred = crget();
836 	sx_xlock(&proctree_lock);
837 	PROC_LOCK(initproc);
838 	initproc->p_flag |= P_SYSTEM | P_INMEM;
839 	initproc->p_treeflag |= P_TREE_REAPER;
840 	LIST_INSERT_HEAD(&initproc->p_reaplist, &proc0, p_reapsibling);
841 	oldcred = initproc->p_ucred;
842 	crcopy(newcred, oldcred);
843 #ifdef MAC
844 	mac_cred_create_init(newcred);
845 #endif
846 #ifdef AUDIT
847 	audit_cred_proc1(newcred);
848 #endif
849 	proc_set_cred(initproc, newcred);
850 	td = FIRST_THREAD_IN_PROC(initproc);
851 	crfree(td->td_ucred);
852 	td->td_ucred = crhold(initproc->p_ucred);
853 	PROC_UNLOCK(initproc);
854 	sx_xunlock(&proctree_lock);
855 	crfree(oldcred);
856 	cpu_fork_kthread_handler(FIRST_THREAD_IN_PROC(initproc),
857 	    start_init, NULL);
858 }
859 SYSINIT(init, SI_SUB_CREATE_INIT, SI_ORDER_FIRST, create_init, NULL);
860 
861 /*
862  * Make it runnable now.
863  */
864 static void
865 kick_init(const void *udata __unused)
866 {
867 	struct thread *td;
868 
869 	td = FIRST_THREAD_IN_PROC(initproc);
870 	thread_lock(td);
871 	TD_SET_CAN_RUN(td);
872 	sched_add(td, SRQ_BORING);
873 	thread_unlock(td);
874 }
875 SYSINIT(kickinit, SI_SUB_KTHREAD_INIT, SI_ORDER_MIDDLE, kick_init, NULL);
876