xref: /freebsd/sys/kern/init_main.c (revision 37b087a645354d60200c774d51b305b268e41c83)
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/mount.h>
52 #include <sys/sysctl.h>
53 #include <sys/proc.h>
54 #include <sys/resourcevar.h>
55 #include <sys/signalvar.h>
56 #include <sys/systm.h>
57 #include <sys/vnode.h>
58 #include <sys/sysent.h>
59 #include <sys/reboot.h>
60 #include <sys/sysproto.h>
61 #include <sys/vmmeter.h>
62 #include <sys/unistd.h>
63 #include <sys/malloc.h>
64 
65 #include <machine/cpu.h>
66 
67 #include <vm/vm.h>
68 #include <vm/vm_param.h>
69 #include <sys/lock.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_map.h>
72 #include <sys/user.h>
73 #include <sys/copyright.h>
74 
75 extern struct linker_set	sysinit_set;	/* XXX */
76 
77 void mi_startup(void);				/* Should be elsewhere */
78 
79 /* Components of the first process -- never freed. */
80 static struct session session0;
81 static struct pgrp pgrp0;
82 struct	proc proc0;
83 static struct pcred cred0;
84 static struct procsig procsig0;
85 static struct filedesc0 filedesc0;
86 static struct plimit limit0;
87 static struct vmspace vmspace0;
88 struct	proc *initproc;
89 
90 int cmask = CMASK;
91 extern	struct user *proc0paddr;
92 
93 struct	vnode *rootvp;
94 int	boothowto = 0;		/* initialized so that it can be patched */
95 SYSCTL_INT(_debug, OID_AUTO, boothowto, CTLFLAG_RD, &boothowto, 0, "");
96 
97 /*
98  * This ensures that there is at least one entry so that the sysinit_set
99  * symbol is not undefined.  A sybsystem ID of SI_SUB_DUMMY is never
100  * executed.
101  */
102 SYSINIT(placeholder, SI_SUB_DUMMY, SI_ORDER_ANY, NULL, NULL)
103 
104 /*
105  * The sysinit table itself.  Items are checked off as the are run.
106  * If we want to register new sysinit types, add them to newsysinit.
107  */
108 struct sysinit **sysinit = (struct sysinit **)sysinit_set.ls_items;
109 struct sysinit **newsysinit;
110 
111 /*
112  * Merge a new sysinit set into the current set, reallocating it if
113  * necessary.  This can only be called after malloc is running.
114  */
115 void
116 sysinit_add(struct sysinit **set)
117 {
118 	struct sysinit **newset;
119 	struct sysinit **sipp;
120 	struct sysinit **xipp;
121 	int count = 0;
122 
123 	if (newsysinit)
124 		for (sipp = newsysinit; *sipp; sipp++)
125 			count++;
126 	else
127 		for (sipp = sysinit; *sipp; sipp++)
128 			count++;
129 	for (sipp = set; *sipp; sipp++)
130 		count++;
131 	count++;		/* Trailing NULL */
132 	newset = malloc(count * sizeof(*sipp), M_TEMP, M_NOWAIT);
133 	if (newset == NULL)
134 		panic("cannot malloc for sysinit");
135 	xipp = newset;
136 	if (newsysinit)
137 		for (sipp = newsysinit; *sipp; sipp++)
138 			*xipp++ = *sipp;
139 	else
140 		for (sipp = sysinit; *sipp; sipp++)
141 			*xipp++ = *sipp;
142 	for (sipp = set; *sipp; sipp++)
143 		*xipp++ = *sipp;
144 	*xipp = NULL;
145 	if (newsysinit)
146 		free(newsysinit, M_TEMP);
147 	newsysinit = newset;
148 }
149 
150 /*
151  * System startup; initialize the world, create process 0, mount root
152  * filesystem, and fork to create init and pagedaemon.  Most of the
153  * hard work is done in the lower-level initialization routines including
154  * startup(), which does memory initialization and autoconfiguration.
155  *
156  * This allows simple addition of new kernel subsystems that require
157  * boot time initialization.  It also allows substitution of subsystem
158  * (for instance, a scheduler, kernel profiler, or VM system) by object
159  * module.  Finally, it allows for optional "kernel threads".
160  */
161 void
162 mi_startup(void)
163 {
164 
165 	register struct sysinit **sipp;		/* system initialization*/
166 	register struct sysinit **xipp;		/* interior loop of sort*/
167 	register struct sysinit *save;		/* bubble*/
168 
169 restart:
170 	/*
171 	 * Perform a bubble sort of the system initialization objects by
172 	 * their subsystem (primary key) and order (secondary key).
173 	 */
174 	for (sipp = sysinit; *sipp; sipp++) {
175 		for (xipp = sipp + 1; *xipp; xipp++) {
176 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
177 			     ((*sipp)->subsystem == (*xipp)->subsystem &&
178 			      (*sipp)->order <= (*xipp)->order))
179 				continue;	/* skip*/
180 			save = *sipp;
181 			*sipp = *xipp;
182 			*xipp = save;
183 		}
184 	}
185 
186 	/*
187 	 * Traverse the (now) ordered list of system initialization tasks.
188 	 * Perform each task, and continue on to the next task.
189 	 *
190 	 * The last item on the list is expected to be the scheduler,
191 	 * which will not return.
192 	 */
193 	for (sipp = sysinit; *sipp; sipp++) {
194 
195 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
196 			continue;	/* skip dummy task(s)*/
197 
198 		if ((*sipp)->subsystem == SI_SUB_DONE)
199 			continue;
200 
201 		/* Call function */
202 		(*((*sipp)->func))((*sipp)->udata);
203 
204 		/* Check off the one we're just done */
205 		(*sipp)->subsystem = SI_SUB_DONE;
206 
207 		/* Check if we've installed more sysinit items via KLD */
208 		if (newsysinit != NULL) {
209 			if (sysinit != (struct sysinit **)sysinit_set.ls_items)
210 				free(sysinit, M_TEMP);
211 			sysinit = newsysinit;
212 			newsysinit = NULL;
213 			goto restart;
214 		}
215 	}
216 
217 	panic("Shouldn't get here!");
218 	/* NOTREACHED*/
219 }
220 
221 
222 /*
223  ***************************************************************************
224  ****
225  **** The following SYSINIT's belong elsewhere, but have not yet
226  **** been moved.
227  ****
228  ***************************************************************************
229  */
230 static void
231 print_caddr_t(void *data __unused)
232 {
233 	printf("%s", (char *)data);
234 }
235 SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t, copyright)
236 
237 
238 /*
239  ***************************************************************************
240  ****
241  **** The two following SYSINT's are proc0 specific glue code.  I am not
242  **** convinced that they can not be safely combined, but their order of
243  **** operation has been maintained as the same as the original init_main.c
244  **** for right now.
245  ****
246  **** These probably belong in init_proc.c or kern_proc.c, since they
247  **** deal with proc0 (the fork template process).
248  ****
249  ***************************************************************************
250  */
251 /* ARGSUSED*/
252 static void
253 proc0_init(void *dummy __unused)
254 {
255 	register struct proc		*p;
256 	register struct filedesc0	*fdp;
257 	register unsigned i;
258 
259 	p = &proc0;
260 
261 	/*
262 	 * Initialize process and pgrp structures.
263 	 */
264 	procinit();
265 
266 	/*
267 	 * Initialize sleep queue hash table
268 	 */
269 	sleepinit();
270 
271 	/*
272 	 * additional VM structures
273 	 */
274 	vm_init2();
275 
276 	/*
277 	 * Create process 0 (the swapper).
278 	 */
279 	LIST_INSERT_HEAD(&allproc, p, p_list);
280 	p->p_pgrp = &pgrp0;
281 	LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
282 	LIST_INIT(&pgrp0.pg_members);
283 	LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
284 
285 	pgrp0.pg_session = &session0;
286 	session0.s_count = 1;
287 	session0.s_leader = p;
288 
289 	p->p_sysent = &aout_sysvec;
290 
291 	p->p_flag = P_INMEM | P_SYSTEM;
292 	p->p_stat = SRUN;
293 	p->p_nice = NZERO;
294 	p->p_rtprio.type = RTP_PRIO_NORMAL;
295 	p->p_rtprio.prio = 0;
296 
297 	p->p_peers = 0;
298 	p->p_leader = p;
299 
300 	bcopy("swapper", p->p_comm, sizeof ("swapper"));
301 
302 	/* Create credentials. */
303 	cred0.p_refcnt = 1;
304 	p->p_cred = &cred0;
305 	p->p_ucred = crget();
306 	p->p_ucred->cr_ngroups = 1;	/* group 0 */
307 
308 	/* Don't jail it */
309 	p->p_prison = 0;
310 
311 	/* Create procsig. */
312 	p->p_procsig = &procsig0;
313 	p->p_procsig->ps_refcnt = 1;
314 
315 	/* Initialize signal state for process 0. */
316 	siginit(&proc0);
317 
318 	/* Create the file descriptor table. */
319 	fdp = &filedesc0;
320 	p->p_fd = &fdp->fd_fd;
321 	fdp->fd_fd.fd_refcnt = 1;
322 	fdp->fd_fd.fd_cmask = cmask;
323 	fdp->fd_fd.fd_ofiles = fdp->fd_dfiles;
324 	fdp->fd_fd.fd_ofileflags = fdp->fd_dfileflags;
325 	fdp->fd_fd.fd_nfiles = NDFILE;
326 
327 	/* Create the limits structures. */
328 	p->p_limit = &limit0;
329 	for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
330 		limit0.pl_rlimit[i].rlim_cur =
331 		    limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
332 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
333 	    limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
334 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
335 	    limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
336 	i = ptoa(cnt.v_free_count);
337 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = i;
338 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = i;
339 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = i / 3;
340 	limit0.p_cpulimit = RLIM_INFINITY;
341 	limit0.p_refcnt = 1;
342 
343 	/* Allocate a prototype map so we have something to fork. */
344 	pmap_pinit0(vmspace_pmap(&vmspace0));
345 	p->p_vmspace = &vmspace0;
346 	vmspace0.vm_refcnt = 1;
347 	vm_map_init(&vmspace0.vm_map, round_page(VM_MIN_ADDRESS),
348 	    trunc_page(VM_MAXUSER_ADDRESS));
349 	vmspace0.vm_map.pmap = vmspace_pmap(&vmspace0);
350 	p->p_addr = proc0paddr;				/* XXX */
351 
352 	/*
353 	 * We continue to place resource usage info and signal
354 	 * actions in the user struct so they're pageable.
355 	 */
356 	p->p_stats = &p->p_addr->u_stats;
357 	p->p_sigacts = &p->p_addr->u_sigacts;
358 
359 	/*
360 	 * Charge root for one process.
361 	 */
362 	(void)chgproccnt(0, 1, 0);
363 
364 	/*
365 	 * Initialize the current process pointer (curproc) before
366 	 * any possible traps/probes to simplify trap processing.
367 	 */
368 	SET_CURPROC(p);
369 
370 }
371 SYSINIT(p0init, SI_SUB_INTRINSIC, SI_ORDER_FIRST, proc0_init, NULL)
372 
373 /* ARGSUSED*/
374 static void
375 proc0_post(void *dummy __unused)
376 {
377 	struct timespec ts;
378 	struct proc *p;
379 
380 	/*
381 	 * Now we can look at the time, having had a chance to verify the
382 	 * time from the file system.  Pretend that proc0 started now.
383 	 */
384 	LIST_FOREACH(p, &allproc, p_list) {
385 		microtime(&p->p_stats->p_start);
386 		p->p_runtime = 0;
387 	}
388 	microuptime(&switchtime);
389 	switchticks = ticks;
390 
391 	/*
392 	 * Give the ``random'' number generator a thump.
393 	 */
394 	nanotime(&ts);
395 	srandom(ts.tv_sec ^ ts.tv_nsec);
396 }
397 SYSINIT(p0post, SI_SUB_INTRINSIC_POST, SI_ORDER_FIRST, proc0_post, NULL)
398 
399 /*
400  ***************************************************************************
401  ****
402  **** The following SYSINIT's and glue code should be moved to the
403  **** respective files on a per subsystem basis.
404  ****
405  ***************************************************************************
406  */
407 
408 
409 /*
410  ***************************************************************************
411  ****
412  **** The following code probably belongs in another file, like
413  **** kern/init_init.c.
414  ****
415  ***************************************************************************
416  */
417 
418 
419 /*
420  * List of paths to try when searching for "init".
421  */
422 static char init_path[MAXPATHLEN] =
423 #ifdef	INIT_PATH
424     __XSTRING(INIT_PATH);
425 #else
426     "/sbin/init:/sbin/oinit:/sbin/init.bak:/stand/sysinstall";
427 #endif
428 SYSCTL_STRING(_kern, OID_AUTO, init_path, CTLFLAG_RD, init_path, 0, "");
429 
430 /*
431  * Start the initial user process; try exec'ing each pathname in init_path.
432  * The program is invoked with one argument containing the boot flags.
433  */
434 static void
435 start_init(void *dummy)
436 {
437 	vm_offset_t addr;
438 	struct execve_args args;
439 	int options, error;
440 	char *var, *path, *next, *s;
441 	char *ucp, **uap, *arg0, *arg1;
442 	struct proc *p;
443 
444 	p = curproc;
445 
446 	/* Get the vnode for '/'.  Set p->p_fd->fd_cdir to reference it. */
447 	if (VFS_ROOT(TAILQ_FIRST(&mountlist), &rootvnode))
448 		panic("cannot find root vnode");
449 	p->p_fd->fd_cdir = rootvnode;
450 	VREF(p->p_fd->fd_cdir);
451 	p->p_fd->fd_rdir = rootvnode;
452 	VOP_UNLOCK(rootvnode, 0, p);
453 
454 	/*
455 	 * Need just enough stack to hold the faked-up "execve()" arguments.
456 	 */
457 	addr = trunc_page(USRSTACK - PAGE_SIZE);
458 	if (vm_map_find(&p->p_vmspace->vm_map, NULL, 0, &addr, PAGE_SIZE,
459 			FALSE, VM_PROT_ALL, VM_PROT_ALL, 0) != 0)
460 		panic("init: couldn't allocate argument space");
461 	p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
462 	p->p_vmspace->vm_ssize = 1;
463 
464 	if ((var = getenv("init_path")) != NULL) {
465 		strncpy(init_path, var, sizeof init_path);
466 		init_path[sizeof init_path - 1] = 0;
467 	}
468 
469 	for (path = init_path; *path != '\0'; path = next) {
470 		while (*path == ':')
471 			path++;
472 		if (*path == '\0')
473 			break;
474 		for (next = path; *next != '\0' && *next != ':'; next++)
475 			/* nothing */ ;
476 		if (bootverbose)
477 			printf("start_init: trying %.*s\n", (int)(next - path),
478 			    path);
479 
480 		/*
481 		 * Move out the boot flag argument.
482 		 */
483 		options = 0;
484 		ucp = (char *)USRSTACK;
485 		(void)subyte(--ucp, 0);		/* trailing zero */
486 		if (boothowto & RB_SINGLE) {
487 			(void)subyte(--ucp, 's');
488 			options = 1;
489 		}
490 #ifdef notyet
491                 if (boothowto & RB_FASTBOOT) {
492 			(void)subyte(--ucp, 'f');
493 			options = 1;
494 		}
495 #endif
496 
497 #ifdef BOOTCDROM
498 		(void)subyte(--ucp, 'C');
499 		options = 1;
500 #endif
501 		if (options == 0)
502 			(void)subyte(--ucp, '-');
503 		(void)subyte(--ucp, '-');		/* leading hyphen */
504 		arg1 = ucp;
505 
506 		/*
507 		 * Move out the file name (also arg 0).
508 		 */
509 		(void)subyte(--ucp, 0);
510 		for (s = next - 1; s >= path; s--)
511 			(void)subyte(--ucp, *s);
512 		arg0 = ucp;
513 
514 		/*
515 		 * Move out the arg pointers.
516 		 */
517 		uap = (char **)((intptr_t)ucp & ~(sizeof(intptr_t)-1));
518 		(void)suword((caddr_t)--uap, (long)0);	/* terminator */
519 		(void)suword((caddr_t)--uap, (long)(intptr_t)arg1);
520 		(void)suword((caddr_t)--uap, (long)(intptr_t)arg0);
521 
522 		/*
523 		 * Point at the arguments.
524 		 */
525 		args.fname = arg0;
526 		args.argv = uap;
527 		args.envv = NULL;
528 
529 		/*
530 		 * Now try to exec the program.  If can't for any reason
531 		 * other than it doesn't exist, complain.
532 		 *
533 		 * Otherwise, return via fork_trampoline() all the way
534 		 * to user mode as init!
535 		 */
536 		if ((error = execve(p, &args)) == 0)
537 			return;
538 		if (error != ENOENT)
539 			printf("exec %.*s: error %d\n", (int)(next - path),
540 			    path, error);
541 	}
542 	printf("init: not found in path %s\n", init_path);
543 	panic("no init");
544 }
545 
546 /*
547  * Like kthread_create(), but runs in it's own address space.
548  * We do this early to reserve pid 1.
549  *
550  * Note special case - do not make it runnable yet.  Other work
551  * in progress will change this more.
552  */
553 static void
554 create_init(const void *udata __unused)
555 {
556 	int error;
557 	int s;
558 
559 	s = splhigh();
560 	error = fork1(&proc0, RFFDG | RFPROC, &initproc);
561 	if (error)
562 		panic("cannot fork init: %d\n", error);
563 	initproc->p_flag |= P_INMEM | P_SYSTEM;
564 	cpu_set_fork_handler(initproc, start_init, NULL);
565 	remrunqueue(initproc);
566 	splx(s);
567 }
568 SYSINIT(init,SI_SUB_CREATE_INIT, SI_ORDER_FIRST, create_init, NULL)
569 
570 /*
571  * Make it runnable now.
572  */
573 static void
574 kick_init(const void *udata __unused)
575 {
576 	setrunqueue(initproc);
577 }
578 SYSINIT(kickinit,SI_SUB_KTHREAD_INIT, SI_ORDER_FIRST, kick_init, NULL)
579