xref: /freebsd/sys/kern/init_main.c (revision fa8c1aaabcc74c6d1ab2de069f46f20d0bd1adf0)
1 /*
2  * Copyright (c) 1995 Terrence R. Lambert
3  * All rights reserved.
4  *
5  * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *	This product includes software developed by the University of
24  *	California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *	@(#)init_main.c	8.9 (Berkeley) 1/21/94
42  * $FreeBSD$
43  */
44 
45 #include "opt_init_path.h"
46 
47 #include <sys/param.h>
48 #include <sys/file.h>
49 #include <sys/filedesc.h>
50 #include <sys/kernel.h>
51 #include <sys/ktr.h>
52 #include <sys/lock.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/sysctl.h>
56 #include <sys/proc.h>
57 #include <sys/resourcevar.h>
58 #include <sys/systm.h>
59 #include <sys/signalvar.h>
60 #include <sys/vnode.h>
61 #include <sys/sysent.h>
62 #include <sys/reboot.h>
63 #include <sys/sx.h>
64 #include <sys/sysproto.h>
65 #include <sys/vmmeter.h>
66 #include <sys/unistd.h>
67 #include <sys/malloc.h>
68 #include <sys/conf.h>
69 
70 #include <machine/cpu.h>
71 #include <machine/globals.h>
72 
73 #include <vm/vm.h>
74 #include <vm/vm_param.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_map.h>
77 #include <sys/user.h>
78 #include <sys/copyright.h>
79 
80 extern struct linker_set	sysinit_set;	/* XXX */
81 
82 void mi_startup(void);				/* Should be elsewhere */
83 
84 /* Components of the first process -- never freed. */
85 static struct session session0;
86 static struct pgrp pgrp0;
87 struct	proc proc0;
88 static struct pcred cred0;
89 static struct procsig procsig0;
90 static struct filedesc0 filedesc0;
91 static struct plimit limit0;
92 static struct vmspace vmspace0;
93 struct	proc *initproc;
94 
95 int cmask = CMASK;
96 extern	struct user *proc0paddr;
97 extern int fallback_elf_brand;
98 
99 struct	vnode *rootvp;
100 int	boothowto = 0;		/* initialized so that it can be patched */
101 SYSCTL_INT(_debug, OID_AUTO, boothowto, CTLFLAG_RD, &boothowto, 0, "");
102 int	bootverbose;
103 SYSCTL_INT(_debug, OID_AUTO, bootverbose, CTLFLAG_RW, &bootverbose, 0, "");
104 
105 /*
106  * This ensures that there is at least one entry so that the sysinit_set
107  * symbol is not undefined.  A sybsystem ID of SI_SUB_DUMMY is never
108  * executed.
109  */
110 SYSINIT(placeholder, SI_SUB_DUMMY, SI_ORDER_ANY, NULL, NULL)
111 
112 /*
113  * The sysinit table itself.  Items are checked off as the are run.
114  * If we want to register new sysinit types, add them to newsysinit.
115  */
116 struct sysinit **sysinit = (struct sysinit **)sysinit_set.ls_items;
117 struct sysinit **newsysinit;
118 
119 /*
120  * Merge a new sysinit set into the current set, reallocating it if
121  * necessary.  This can only be called after malloc is running.
122  */
123 void
124 sysinit_add(struct sysinit **set)
125 {
126 	struct sysinit **newset;
127 	struct sysinit **sipp;
128 	struct sysinit **xipp;
129 	int count = 0;
130 
131 	if (newsysinit)
132 		for (sipp = newsysinit; *sipp; sipp++)
133 			count++;
134 	else
135 		for (sipp = sysinit; *sipp; sipp++)
136 			count++;
137 	for (sipp = set; *sipp; sipp++)
138 		count++;
139 	count++;		/* Trailing NULL */
140 	newset = malloc(count * sizeof(*sipp), M_TEMP, M_NOWAIT);
141 	if (newset == NULL)
142 		panic("cannot malloc for sysinit");
143 	xipp = newset;
144 	if (newsysinit)
145 		for (sipp = newsysinit; *sipp; sipp++)
146 			*xipp++ = *sipp;
147 	else
148 		for (sipp = sysinit; *sipp; sipp++)
149 			*xipp++ = *sipp;
150 	for (sipp = set; *sipp; sipp++)
151 		*xipp++ = *sipp;
152 	*xipp = NULL;
153 	if (newsysinit)
154 		free(newsysinit, M_TEMP);
155 	newsysinit = newset;
156 }
157 
158 /*
159  * System startup; initialize the world, create process 0, mount root
160  * filesystem, and fork to create init and pagedaemon.  Most of the
161  * hard work is done in the lower-level initialization routines including
162  * startup(), which does memory initialization and autoconfiguration.
163  *
164  * This allows simple addition of new kernel subsystems that require
165  * boot time initialization.  It also allows substitution of subsystem
166  * (for instance, a scheduler, kernel profiler, or VM system) by object
167  * module.  Finally, it allows for optional "kernel threads".
168  */
169 void
170 mi_startup(void)
171 {
172 
173 	register struct sysinit **sipp;		/* system initialization*/
174 	register struct sysinit **xipp;		/* interior loop of sort*/
175 	register struct sysinit *save;		/* bubble*/
176 
177 restart:
178 	/*
179 	 * Perform a bubble sort of the system initialization objects by
180 	 * their subsystem (primary key) and order (secondary key).
181 	 */
182 	for (sipp = sysinit; *sipp; sipp++) {
183 		for (xipp = sipp + 1; *xipp; xipp++) {
184 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
185 			     ((*sipp)->subsystem == (*xipp)->subsystem &&
186 			      (*sipp)->order <= (*xipp)->order))
187 				continue;	/* skip*/
188 			save = *sipp;
189 			*sipp = *xipp;
190 			*xipp = save;
191 		}
192 	}
193 
194 	/*
195 	 * Traverse the (now) ordered list of system initialization tasks.
196 	 * Perform each task, and continue on to the next task.
197 	 *
198 	 * The last item on the list is expected to be the scheduler,
199 	 * which will not return.
200 	 */
201 	for (sipp = sysinit; *sipp; sipp++) {
202 
203 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
204 			continue;	/* skip dummy task(s)*/
205 
206 		if ((*sipp)->subsystem == SI_SUB_DONE)
207 			continue;
208 
209 		/* Call function */
210 		(*((*sipp)->func))((*sipp)->udata);
211 
212 		/* Check off the one we're just done */
213 		(*sipp)->subsystem = SI_SUB_DONE;
214 
215 		/* Check if we've installed more sysinit items via KLD */
216 		if (newsysinit != NULL) {
217 			if (sysinit != (struct sysinit **)sysinit_set.ls_items)
218 				free(sysinit, M_TEMP);
219 			sysinit = newsysinit;
220 			newsysinit = NULL;
221 			goto restart;
222 		}
223 	}
224 
225 	panic("Shouldn't get here!");
226 	/* NOTREACHED*/
227 }
228 
229 
230 /*
231  ***************************************************************************
232  ****
233  **** The following SYSINIT's belong elsewhere, but have not yet
234  **** been moved.
235  ****
236  ***************************************************************************
237  */
238 static void
239 print_caddr_t(void *data __unused)
240 {
241 	printf("%s", (char *)data);
242 }
243 SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t, copyright)
244 SYSINIT(version, SI_SUB_COPYRIGHT, SI_ORDER_SECOND, print_caddr_t, version)
245 
246 static void
247 set_boot_verbose(void *data __unused)
248 {
249 
250 	if (boothowto & RB_VERBOSE)
251 		bootverbose++;
252 }
253 SYSINIT(boot_verbose, SI_SUB_TUNABLES, SI_ORDER_ANY, set_boot_verbose, NULL)
254 
255 /*
256  ***************************************************************************
257  ****
258  **** The two following SYSINT's are proc0 specific glue code.  I am not
259  **** convinced that they can not be safely combined, but their order of
260  **** operation has been maintained as the same as the original init_main.c
261  **** for right now.
262  ****
263  **** These probably belong in init_proc.c or kern_proc.c, since they
264  **** deal with proc0 (the fork template process).
265  ****
266  ***************************************************************************
267  */
268 /* ARGSUSED*/
269 static void
270 proc0_init(void *dummy __unused)
271 {
272 	register struct proc		*p;
273 	register struct filedesc0	*fdp;
274 	register unsigned i;
275 
276 	p = &proc0;
277 
278 	/*
279 	 * Initialize magic number.
280 	 */
281 	p->p_magic = P_MAGIC;
282 
283 	/*
284 	 * Initialize process and pgrp structures.
285 	 */
286 	procinit();
287 
288 	/*
289 	 * Initialize sleep queue hash table
290 	 */
291 	sleepinit();
292 
293 	/*
294 	 * additional VM structures
295 	 */
296 	vm_init2();
297 
298 	/*
299 	 * Create process 0 (the swapper).
300 	 */
301 	LIST_INSERT_HEAD(&allproc, p, p_list);
302 	LIST_INSERT_HEAD(PIDHASH(0), p, p_hash);
303 	p->p_pgrp = &pgrp0;
304 	LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
305 	LIST_INIT(&pgrp0.pg_members);
306 	LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
307 
308 	pgrp0.pg_session = &session0;
309 	session0.s_count = 1;
310 	session0.s_leader = p;
311 
312 #ifdef __ELF__
313 	p->p_sysent = &elf_freebsd_sysvec;
314 #else
315 	p->p_sysent = &aout_sysvec;
316 #endif
317 
318 	p->p_flag = P_SYSTEM;
319 	p->p_sflag = PS_INMEM;
320 	p->p_stat = SRUN;
321 	p->p_nice = NZERO;
322 	p->p_pri.pri_class = PRI_TIMESHARE;
323 	p->p_pri.pri_level = PVM;
324 	p->p_pri.pri_native = PUSER;
325 	p->p_pri.pri_user = PUSER;
326 
327 	p->p_peers = 0;
328 	p->p_leader = p;
329 
330 	bcopy("swapper", p->p_comm, sizeof ("swapper"));
331 
332 	callout_init(&p->p_itcallout, 0);
333 	callout_init(&p->p_slpcallout, 1);
334 
335 	/* Create credentials. */
336 	cred0.p_refcnt = 1;
337 	cred0.p_uidinfo = uifind(0);
338 	p->p_cred = &cred0;
339 	p->p_ucred = crget();
340 	p->p_ucred->cr_ngroups = 1;	/* group 0 */
341 	p->p_ucred->cr_uidinfo = uifind(0);
342 	p->p_ucred->cr_prison = NULL;	/* Don't jail it. */
343 
344 	/* Create procsig. */
345 	p->p_procsig = &procsig0;
346 	p->p_procsig->ps_refcnt = 1;
347 
348 	/* Initialize signal state for process 0. */
349 	siginit(&proc0);
350 
351 	/* Create the file descriptor table. */
352 	fdp = &filedesc0;
353 	p->p_fd = &fdp->fd_fd;
354 	fdp->fd_fd.fd_refcnt = 1;
355 	fdp->fd_fd.fd_cmask = cmask;
356 	fdp->fd_fd.fd_ofiles = fdp->fd_dfiles;
357 	fdp->fd_fd.fd_ofileflags = fdp->fd_dfileflags;
358 	fdp->fd_fd.fd_nfiles = NDFILE;
359 
360 	/* Create the limits structures. */
361 	p->p_limit = &limit0;
362 	for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
363 		limit0.pl_rlimit[i].rlim_cur =
364 		    limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
365 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
366 	    limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
367 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
368 	    limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
369 	i = ptoa(cnt.v_free_count);
370 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = i;
371 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = i;
372 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = i / 3;
373 	limit0.p_cpulimit = RLIM_INFINITY;
374 	limit0.p_refcnt = 1;
375 
376 	/* Allocate a prototype map so we have something to fork. */
377 	mtx_lock(&vm_mtx);
378 	pmap_pinit0(vmspace_pmap(&vmspace0));
379 	p->p_vmspace = &vmspace0;
380 	vmspace0.vm_refcnt = 1;
381 	vm_map_init(&vmspace0.vm_map, round_page(VM_MIN_ADDRESS),
382 	    trunc_page(VM_MAXUSER_ADDRESS));
383 	vmspace0.vm_map.pmap = vmspace_pmap(&vmspace0);
384 	mtx_unlock(&vm_mtx);
385 	p->p_addr = proc0paddr;				/* XXX */
386 
387 	/*
388 	 * We continue to place resource usage info and signal
389 	 * actions in the user struct so they're pageable.
390 	 */
391 	p->p_stats = &p->p_addr->u_stats;
392 	p->p_sigacts = &p->p_addr->u_sigacts;
393 
394 	/*
395 	 * Charge root for one process.
396 	 */
397 	(void)chgproccnt(cred0.p_uidinfo, 1, 0);
398 }
399 SYSINIT(p0init, SI_SUB_INTRINSIC, SI_ORDER_FIRST, proc0_init, NULL)
400 
401 /* ARGSUSED*/
402 static void
403 proc0_post(void *dummy __unused)
404 {
405 	struct timespec ts;
406 	struct proc *p;
407 
408 	/*
409 	 * Now we can look at the time, having had a chance to verify the
410 	 * time from the file system.  Pretend that proc0 started now.
411 	 */
412 	sx_slock(&allproc_lock);
413 	LIST_FOREACH(p, &allproc, p_list) {
414 		microtime(&p->p_stats->p_start);
415 		p->p_runtime = 0;
416 	}
417 	sx_sunlock(&allproc_lock);
418 	microuptime(PCPU_PTR(switchtime));
419 	PCPU_SET(switchticks, ticks);
420 
421 	/*
422 	 * Give the ``random'' number generator a thump.
423 	 */
424 	nanotime(&ts);
425 	srandom(ts.tv_sec ^ ts.tv_nsec);
426 }
427 SYSINIT(p0post, SI_SUB_INTRINSIC_POST, SI_ORDER_FIRST, proc0_post, NULL)
428 
429 /*
430  ***************************************************************************
431  ****
432  **** The following SYSINIT's and glue code should be moved to the
433  **** respective files on a per subsystem basis.
434  ****
435  ***************************************************************************
436  */
437 
438 
439 /*
440  ***************************************************************************
441  ****
442  **** The following code probably belongs in another file, like
443  **** kern/init_init.c.
444  ****
445  ***************************************************************************
446  */
447 
448 /*
449  * List of paths to try when searching for "init".
450  */
451 static char init_path[MAXPATHLEN] =
452 #ifdef	INIT_PATH
453     __XSTRING(INIT_PATH);
454 #else
455     "/sbin/init:/sbin/oinit:/sbin/init.bak:/stand/sysinstall";
456 #endif
457 SYSCTL_STRING(_kern, OID_AUTO, init_path, CTLFLAG_RD, init_path, 0, "");
458 
459 /*
460  * Start the initial user process; try exec'ing each pathname in init_path.
461  * The program is invoked with one argument containing the boot flags.
462  */
463 static void
464 start_init(void *dummy)
465 {
466 	vm_offset_t addr;
467 	struct execve_args args;
468 	int options, error;
469 	char *var, *path, *next, *s;
470 	char *ucp, **uap, *arg0, *arg1;
471 	struct proc *p;
472 
473 	mtx_lock(&Giant);
474 
475 	p = curproc;
476 
477 	/* Get the vnode for '/'.  Set p->p_fd->fd_cdir to reference it. */
478 	if (VFS_ROOT(TAILQ_FIRST(&mountlist), &rootvnode))
479 		panic("cannot find root vnode");
480 	p->p_fd->fd_cdir = rootvnode;
481 	VREF(p->p_fd->fd_cdir);
482 	p->p_fd->fd_rdir = rootvnode;
483 	VREF(p->p_fd->fd_rdir);
484 	VOP_UNLOCK(rootvnode, 0, p);
485 
486 	/*
487 	 * Need just enough stack to hold the faked-up "execve()" arguments.
488 	 */
489 	addr = trunc_page(USRSTACK - PAGE_SIZE);
490 	mtx_lock(&vm_mtx);
491 	if (vm_map_find(&p->p_vmspace->vm_map, NULL, 0, &addr, PAGE_SIZE,
492 			FALSE, VM_PROT_ALL, VM_PROT_ALL, 0) != 0)
493 		panic("init: couldn't allocate argument space");
494 	p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
495 	p->p_vmspace->vm_ssize = 1;
496 	mtx_unlock(&vm_mtx);
497 
498 	if ((var = getenv("init_path")) != NULL) {
499 		strncpy(init_path, var, sizeof init_path);
500 		init_path[sizeof init_path - 1] = 0;
501 	}
502 	if ((var = getenv("kern.fallback_elf_brand")) != NULL)
503 		fallback_elf_brand = strtol(var, NULL, 0);
504 
505 	for (path = init_path; *path != '\0'; path = next) {
506 		while (*path == ':')
507 			path++;
508 		if (*path == '\0')
509 			break;
510 		for (next = path; *next != '\0' && *next != ':'; next++)
511 			/* nothing */ ;
512 		if (bootverbose)
513 			printf("start_init: trying %.*s\n", (int)(next - path),
514 			    path);
515 
516 		/*
517 		 * Move out the boot flag argument.
518 		 */
519 		options = 0;
520 		ucp = (char *)USRSTACK;
521 		(void)subyte(--ucp, 0);		/* trailing zero */
522 		if (boothowto & RB_SINGLE) {
523 			(void)subyte(--ucp, 's');
524 			options = 1;
525 		}
526 #ifdef notyet
527                 if (boothowto & RB_FASTBOOT) {
528 			(void)subyte(--ucp, 'f');
529 			options = 1;
530 		}
531 #endif
532 
533 #ifdef BOOTCDROM
534 		(void)subyte(--ucp, 'C');
535 		options = 1;
536 #endif
537 		if (devfs_present) {
538 			(void)subyte(--ucp, 'd');
539 			options = 1;
540 		}
541 
542 		if (options == 0)
543 			(void)subyte(--ucp, '-');
544 		(void)subyte(--ucp, '-');		/* leading hyphen */
545 		arg1 = ucp;
546 
547 		/*
548 		 * Move out the file name (also arg 0).
549 		 */
550 		(void)subyte(--ucp, 0);
551 		for (s = next - 1; s >= path; s--)
552 			(void)subyte(--ucp, *s);
553 		arg0 = ucp;
554 
555 		/*
556 		 * Move out the arg pointers.
557 		 */
558 		uap = (char **)((intptr_t)ucp & ~(sizeof(intptr_t)-1));
559 		(void)suword((caddr_t)--uap, (long)0);	/* terminator */
560 		(void)suword((caddr_t)--uap, (long)(intptr_t)arg1);
561 		(void)suword((caddr_t)--uap, (long)(intptr_t)arg0);
562 
563 		/*
564 		 * Point at the arguments.
565 		 */
566 		args.fname = arg0;
567 		args.argv = uap;
568 		args.envv = NULL;
569 
570 		/*
571 		 * Now try to exec the program.  If can't for any reason
572 		 * other than it doesn't exist, complain.
573 		 *
574 		 * Otherwise, return via fork_trampoline() all the way
575 		 * to user mode as init!
576 		 */
577 		if ((error = execve(p, &args)) == 0) {
578 			mtx_unlock(&Giant);
579 			return;
580 		}
581 		if (error != ENOENT)
582 			printf("exec %.*s: error %d\n", (int)(next - path),
583 			    path, error);
584 	}
585 	printf("init: not found in path %s\n", init_path);
586 	panic("no init");
587 }
588 
589 /*
590  * Like kthread_create(), but runs in it's own address space.
591  * We do this early to reserve pid 1.
592  *
593  * Note special case - do not make it runnable yet.  Other work
594  * in progress will change this more.
595  */
596 static void
597 create_init(const void *udata __unused)
598 {
599 	int error;
600 
601 	error = fork1(&proc0, RFFDG | RFPROC | RFSTOPPED, &initproc);
602 	if (error)
603 		panic("cannot fork init: %d\n", error);
604 	PROC_LOCK(initproc);
605 	initproc->p_flag |= P_SYSTEM;
606 	PROC_UNLOCK(initproc);
607 	mtx_lock_spin(&sched_lock);
608 	initproc->p_sflag |= PS_INMEM;
609 	mtx_unlock_spin(&sched_lock);
610 	cpu_set_fork_handler(initproc, start_init, NULL);
611 }
612 SYSINIT(init, SI_SUB_CREATE_INIT, SI_ORDER_FIRST, create_init, NULL)
613 
614 /*
615  * Make it runnable now.
616  */
617 static void
618 kick_init(const void *udata __unused)
619 {
620 
621 	mtx_lock_spin(&sched_lock);
622 	initproc->p_stat = SRUN;
623 	setrunqueue(initproc);
624 	mtx_unlock_spin(&sched_lock);
625 }
626 SYSINIT(kickinit, SI_SUB_KTHREAD_INIT, SI_ORDER_FIRST, kick_init, NULL)
627