xref: /freebsd/sys/kern/init_main.c (revision 33b77e2decd50e53798014b70bf7ca3bdc4c0c7e)
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  * $Id: init_main.c,v 1.78 1997/12/12 04:00:57 dyson Exp $
43  */
44 
45 #include "opt_devfs.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 
64 #include <machine/cpu.h>
65 
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <vm/vm_prot.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 extern void __main __P((void));
78 extern void main __P((void *framep));
79 
80 /* Components of the first process -- never freed. */
81 static struct session session0;
82 static struct pgrp pgrp0;
83 struct	proc proc0;
84 static struct pcred cred0;
85 static struct filedesc0 filedesc0;
86 static struct plimit limit0;
87 static struct vmspace vmspace0;
88 #ifndef SMP	/* per-cpu on smp */
89 struct	proc *curproc = &proc0;
90 #endif
91 struct	proc *initproc;
92 
93 int cmask = CMASK;
94 extern	struct user *proc0paddr;
95 
96 struct	vnode *rootvp;
97 int	boothowto = 0;		/* initialized so that it can be patched */
98 
99 struct	timeval boottime;
100 SYSCTL_STRUCT(_kern, KERN_BOOTTIME, boottime,
101 	CTLFLAG_RD, &boottime, timeval, "");
102 
103 static int shutdowntimeout = 120;
104 SYSCTL_INT(_kern, OID_AUTO, shutdown_timeout,
105 	CTLFLAG_RW, &shutdowntimeout, 0, "");
106 
107 #ifndef SMP	/* per-cpu on smp */
108 struct	timeval runtime;
109 #endif
110 
111 /*
112  * Promiscuous argument pass for start_init()
113  *
114  * This is a kludge because we use a return from main() rather than a call
115  * to a new routine in locore.s to kick the kernel alive from locore.s.
116  */
117 static void	*init_framep;
118 
119 
120 #if __GNUC__ >= 2
121 void __main() {}
122 #endif
123 
124 
125 /*
126  * This ensures that there is at least one entry so that the sysinit_set
127  * symbol is not undefined.  A sybsystem ID of SI_SUB_DUMMY is never
128  * executed.
129  */
130 SYSINIT(placeholder, SI_SUB_DUMMY,SI_ORDER_ANY, NULL, NULL)
131 
132 
133 /*
134  * System startup; initialize the world, create process 0, mount root
135  * filesystem, and fork to create init and pagedaemon.  Most of the
136  * hard work is done in the lower-level initialization routines including
137  * startup(), which does memory initialization and autoconfiguration.
138  *
139  * This allows simple addition of new kernel subsystems that require
140  * boot time initialization.  It also allows substitution of subsystem
141  * (for instance, a scheduler, kernel profiler, or VM system) by object
142  * module.  Finally, it allows for optional "kernel threads", like an LFS
143  * cleaner.
144  */
145 void
146 main(framep)
147 	void *framep;
148 {
149 
150 	register struct sysinit **sipp;		/* system initialization*/
151 	register struct sysinit **xipp;		/* interior loop of sort*/
152 	register struct sysinit *save;		/* bubble*/
153 
154 	/*
155 	 * Copy the locore.s frame pointer for proc0, this is forked into
156 	 * all other processes.
157 	 */
158 	init_framep = framep;
159 
160 #ifdef SMP
161 	/*
162 	 * XXX curproc is per-cpu in SMP, and exists in freshly mapped pages,
163 	 * so its value must be initialized now before it is used by various
164 	 * initialization routines.  proc0_init() isn't soon enough:
165 	 * among other things, configure() is called first, and may call
166 	 * setdumpdev(), which panics without a valid curproc.
167 	 */
168 	curproc = &proc0;
169 #endif /* SMP */
170 
171 	/*
172 	 * Perform a bubble sort of the system initialization objects by
173 	 * their subsystem (primary key) and order (secondary key).
174 	 *
175 	 * Since some things care about execution order, this is the
176 	 * operation which ensures continued function.
177 	 */
178 	for( sipp = (struct sysinit **)sysinit_set.ls_items; *sipp; sipp++) {
179 		for( xipp = sipp + 1; *xipp; xipp++) {
180 			if( (*sipp)->subsystem < (*xipp)->subsystem ||
181 			    ( (*sipp)->subsystem == (*xipp)->subsystem &&
182 			      (*sipp)->order < (*xipp)->order))
183 				continue;	/* skip*/
184 			save = *sipp;
185 			*sipp = *xipp;
186 			*xipp = save;
187 		}
188 	}
189 
190 	/*
191 	 * Traverse the (now) ordered list of system initialization tasks.
192 	 * Perform each task, and continue on to the next task.
193 	 *
194 	 * The last item on the list is expected to be the scheduler,
195 	 * which will not return.
196 	 */
197 	for( sipp = (struct sysinit **)sysinit_set.ls_items; *sipp; sipp++) {
198 
199 		if( (*sipp)->subsystem == SI_SUB_DUMMY)
200 			continue;	/* skip dummy task(s)*/
201 
202 		switch( (*sipp)->type) {
203 		case SI_TYPE_DEFAULT:
204 			/* no special processing*/
205 			(*((*sipp)->func))( (*sipp)->udata);
206 			break;
207 
208 		case SI_TYPE_KTHREAD:
209 #if !defined(SMP)
210 			/* kernel thread*/
211 			if (fork1(&proc0, RFMEM|RFFDG|RFPROC))
212 				panic("fork kernel thread");
213 			cpu_set_fork_handler(pfind(proc0.p_retval[0]),
214 			    (*sipp)->func, (*sipp)->udata);
215 			break;
216 #endif
217 
218 		case SI_TYPE_KPROCESS:
219 			if (fork1(&proc0, RFFDG|RFPROC))
220 				panic("fork kernel process");
221 			cpu_set_fork_handler(pfind(proc0.p_retval[0]),
222 			    (*sipp)->func, (*sipp)->udata);
223 			break;
224 
225 		default:
226 			panic( "init_main: unrecognized init type");
227 		}
228 	}
229 
230 	panic("Shouldn't get here!");
231 	/* NOTREACHED*/
232 }
233 
234 
235 /*
236  * Start a kernel process.  This is called after a fork() call in
237  * main() in the file kern/init_main.c.
238  *
239  * This function is used to start "internal" daemons.
240  */
241 /* ARGSUSED*/
242 void
243 kproc_start(udata)
244 	void *udata;
245 {
246 	struct kproc_desc	*kp = udata;
247 	struct proc		*p = curproc;
248 
249 #ifdef DIAGNOSTIC
250 	printf("Start pid=%d <%s>\n",p->p_pid, kp->arg0);
251 #endif
252 
253 	/* save a global descriptor, if desired*/
254 	if( kp->global_procpp != NULL)
255 		*kp->global_procpp	= p;
256 
257 	/* this is a non-swapped system process*/
258 	p->p_flag |= P_INMEM | P_SYSTEM;
259 
260 	/* set up arg0 for 'ps', et al*/
261 	strcpy( p->p_comm, kp->arg0);
262 
263 	/* call the processes' main()...*/
264 	(*kp->func)();
265 
266 	/* NOTREACHED */
267 	panic("kproc_start: %s", kp->arg0);
268 }
269 
270 
271 /*
272  ***************************************************************************
273  ****
274  **** The following SYSINIT's belong elsewhere, but have not yet
275  **** been moved.
276  ****
277  ***************************************************************************
278  */
279 #ifdef OMIT
280 /*
281  * Handled by vfs_mountroot (bad idea) at this time... should be
282  * done the same as 4.4Lite2.
283  */
284 SYSINIT(swapinit, SI_SUB_SWAP, SI_ORDER_FIRST, swapinit, NULL)
285 #endif	/* OMIT*/
286 
287 static void print_caddr_t __P((void *data));
288 static void
289 print_caddr_t(data)
290 	void *data;
291 {
292 	printf("%s", (char *)data);
293 }
294 SYSINIT(announce, SI_SUB_COPYRIGHT, SI_ORDER_FIRST, print_caddr_t, copyright)
295 
296 
297 /*
298  ***************************************************************************
299  ****
300  **** The two following SYSINT's are proc0 specific glue code.  I am not
301  **** convinced that they can not be safely combined, but their order of
302  **** operation has been maintained as the same as the original init_main.c
303  **** for right now.
304  ****
305  **** These probably belong in init_proc.c or kern_proc.c, since they
306  **** deal with proc0 (the fork template process).
307  ****
308  ***************************************************************************
309  */
310 /* ARGSUSED*/
311 static void proc0_init __P((void *dummy));
312 static void
313 proc0_init(dummy)
314 	void *dummy;
315 {
316 	register struct proc		*p;
317 	register struct filedesc0	*fdp;
318 	register unsigned i;
319 
320 	/*
321 	 * Initialize the current process pointer (curproc) before
322 	 * any possible traps/probes to simplify trap processing.
323 	 */
324 	p = &proc0;
325 	curproc = p;			/* XXX redundant*/
326 
327 	/*
328 	 * Initialize process and pgrp structures.
329 	 */
330 	procinit();
331 
332 	/*
333 	 * Initialize sleep queue hash table
334 	 */
335 	sleepinit();
336 
337 	/*
338 	 * additional VM structures
339 	 */
340 	vm_init2();
341 
342 	/*
343 	 * Create process 0 (the swapper).
344 	 */
345 	LIST_INSERT_HEAD(&allproc, p, p_list);
346 	p->p_pgrp = &pgrp0;
347 	LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
348 	LIST_INIT(&pgrp0.pg_members);
349 	LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
350 
351 	pgrp0.pg_session = &session0;
352 	session0.s_count = 1;
353 	session0.s_leader = p;
354 
355 	p->p_sysent = &aout_sysvec;
356 
357 	p->p_flag = P_INMEM | P_SYSTEM;
358 	p->p_stat = SRUN;
359 	p->p_nice = NZERO;
360 	p->p_rtprio.type = RTP_PRIO_NORMAL;
361 	p->p_rtprio.prio = 0;
362 
363 /*
364  * Link for kernel based threads
365  */
366 	p->p_peers = 0;
367 	p->p_leader = p;
368 
369 	bcopy("swapper", p->p_comm, sizeof ("swapper"));
370 
371 	/* Create credentials. */
372 	cred0.p_refcnt = 1;
373 	p->p_cred = &cred0;
374 	p->p_ucred = crget();
375 	p->p_ucred->cr_ngroups = 1;	/* group 0 */
376 
377 	/* Create the file descriptor table. */
378 	fdp = &filedesc0;
379 	p->p_fd = &fdp->fd_fd;
380 	fdp->fd_fd.fd_refcnt = 1;
381 	fdp->fd_fd.fd_cmask = cmask;
382 	fdp->fd_fd.fd_ofiles = fdp->fd_dfiles;
383 	fdp->fd_fd.fd_ofileflags = fdp->fd_dfileflags;
384 	fdp->fd_fd.fd_nfiles = NDFILE;
385 
386 	/* Create the limits structures. */
387 	p->p_limit = &limit0;
388 	for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
389 		limit0.pl_rlimit[i].rlim_cur =
390 		    limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
391 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur =
392 	    limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = maxfiles;
393 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur =
394 	    limit0.pl_rlimit[RLIMIT_NPROC].rlim_max = maxproc;
395 	i = ptoa(cnt.v_free_count);
396 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = i;
397 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = i;
398 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = i / 3;
399 	limit0.p_refcnt = 1;
400 
401 	/* Allocate a prototype map so we have something to fork. */
402 	p->p_vmspace = &vmspace0;
403 	vmspace0.vm_refcnt = 1;
404 	pmap_pinit0(&vmspace0.vm_pmap);
405 	vm_map_init(&vmspace0.vm_map, round_page(VM_MIN_ADDRESS),
406 	    trunc_page(VM_MAXUSER_ADDRESS), TRUE);
407 	vmspace0.vm_map.pmap = &vmspace0.vm_pmap;
408 	p->p_addr = proc0paddr;				/* XXX */
409 
410 #define INCOMPAT_LITES2
411 #ifdef INCOMPAT_LITES2
412 	/*
413 	 * proc0 needs to have a coherent frame base in it's stack.
414 	 */
415 	cpu_set_init_frame(p, init_framep);			/* XXX! */
416 #endif	/* INCOMPAT_LITES2*/
417 
418 	/*
419 	 * We continue to place resource usage info and signal
420 	 * actions in the user struct so they're pageable.
421 	 */
422 	p->p_stats = &p->p_addr->u_stats;
423 	p->p_sigacts = &p->p_addr->u_sigacts;
424 
425 	/*
426 	 * Charge root for one process.
427 	 */
428 	(void)chgproccnt(0, 1);
429 
430 	/*
431 	 * Initialize the procfs flags (to 0, of course)
432 	 */
433 	p->p_stops = p->p_stype = p->p_step = 0;
434 
435 }
436 SYSINIT(p0init, SI_SUB_INTRINSIC, SI_ORDER_FIRST, proc0_init, NULL)
437 
438 /* ARGSUSED*/
439 static void proc0_post __P((void *dummy));
440 static void
441 proc0_post(dummy)
442 	void *dummy;
443 {
444 	struct timeval tv;
445 
446 	/*
447 	 * Now can look at time, having had a chance to verify the time
448 	 * from the file system.  Reset p->p_rtime as it may have been
449 	 * munched in mi_switch() after the time got set.
450 	 */
451 	gettime(&boottime);
452 	proc0.p_stats->p_start = runtime = mono_time = boottime;
453 	proc0.p_rtime.tv_sec = proc0.p_rtime.tv_usec = 0;
454 
455 	/*
456 	 * Give the ``random'' number generator a thump.
457 	 */
458 	microtime(&tv);
459 	srandom(tv.tv_sec ^ tv.tv_usec);
460 
461 	/* Initialize signal state for process 0. */
462 	siginit(&proc0);
463 }
464 SYSINIT(p0post, SI_SUB_INTRINSIC_POST, SI_ORDER_FIRST, proc0_post, NULL)
465 
466 
467 
468 
469 /*
470  ***************************************************************************
471  ****
472  **** The following SYSINIT's and glue code should be moved to the
473  **** respective files on a per subsystem basis.
474  ****
475  ***************************************************************************
476  */
477 
478 /* ARGSUSED */
479 static void root_conf __P((void *dummy));
480 static void
481 root_conf(dummy)
482 	void *dummy;
483 {
484 	cpu_rootconf();
485 }
486 SYSINIT(root_conf, SI_SUB_ROOT_CONF, SI_ORDER_FIRST, root_conf, NULL)
487 
488 /* ARGSUSED*/
489 static void xxx_vfs_root_fdtab __P((void *dummy));
490 static void
491 xxx_vfs_root_fdtab(dummy)
492 	void *dummy;
493 {
494 	register struct filedesc0	*fdp = &filedesc0;
495 
496 	/* Get the vnode for '/'.  Set fdp->fd_fd.fd_cdir to reference it. */
497 	if (VFS_ROOT(mountlist.cqh_first, &rootvnode))
498 		panic("cannot find root vnode");
499 	fdp->fd_fd.fd_cdir = rootvnode;
500 	VREF(fdp->fd_fd.fd_cdir);
501 	VOP_UNLOCK(rootvnode, 0, &proc0);
502 	fdp->fd_fd.fd_rdir = NULL;
503 }
504 SYSINIT(retrofit, SI_SUB_ROOT_FDTAB, SI_ORDER_FIRST, xxx_vfs_root_fdtab, NULL)
505 
506 
507 /*
508  ***************************************************************************
509  ****
510  **** The following code probably belongs in another file, like
511  **** kern/init_init.c.  It is here for two reasons only:
512  ****
513  ****	1)	This code returns to startup the system; this is
514  ****		abnormal for a kernel thread.
515  ****	2)	This code promiscuously uses init_frame
516  ****
517  ***************************************************************************
518  */
519 
520 static void kthread_init __P((void *dummy));
521 SYSINIT_KP(init,SI_SUB_KTHREAD_INIT, SI_ORDER_FIRST, kthread_init, NULL)
522 
523 
524 extern void prepare_usermode __P((void));
525 static void start_init __P((struct proc *p));
526 
527 /* ARGSUSED*/
528 static void
529 kthread_init(dummy)
530 	void *dummy;
531 {
532 	/* Create process 1 (init(8)). */
533 	start_init(curproc);
534 
535 	prepare_usermode();
536 
537 	/*
538 	 * This returns to the fork trampoline, then to user mode.
539 	 */
540 	return;
541 }
542 
543 
544 /*
545  * List of paths to try when searching for "init".
546  */
547 static char *initpaths[] = {
548 	"/sbin/init",
549 	"/sbin/oinit",
550 	"/sbin/init.bak",
551 	"/stand/sysinstall",
552 	NULL,
553 };
554 
555 /*
556  * Start the initial user process; try exec'ing each pathname in "initpaths".
557  * The program is invoked with one argument containing the boot flags.
558  */
559 static void
560 start_init(p)
561 	struct proc *p;
562 {
563 	vm_offset_t addr;
564 	struct execve_args args;
565 	int options, i, error;
566 	char **pathp, *path, *ucp, **uap, *arg0, *arg1;
567 
568 	initproc = p;
569 
570 	/*
571 	 * Need just enough stack to hold the faked-up "execve()" arguments.
572 	 */
573 	addr = trunc_page(VM_MAXUSER_ADDRESS - PAGE_SIZE);
574 	if (vm_map_find(&p->p_vmspace->vm_map, NULL, 0, &addr, PAGE_SIZE, FALSE, VM_PROT_ALL, VM_PROT_ALL, 0) != 0)
575 		panic("init: couldn't allocate argument space");
576 	p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
577 	p->p_vmspace->vm_ssize = 1;
578 
579 	for (pathp = &initpaths[0]; (path = *pathp) != NULL; pathp++) {
580 		/*
581 		 * Move out the boot flag argument.
582 		 */
583 		options = 0;
584 		ucp = (char *)USRSTACK;
585 		(void)subyte(--ucp, 0);		/* trailing zero */
586 		if (boothowto & RB_SINGLE) {
587 			(void)subyte(--ucp, 's');
588 			options = 1;
589 		}
590 #ifdef notyet
591                 if (boothowto & RB_FASTBOOT) {
592 			(void)subyte(--ucp, 'f');
593 			options = 1;
594 		}
595 #endif
596 
597 #ifdef BOOTCDROM
598 		(void)subyte(--ucp, 'C');
599 		options = 1;
600 #endif
601 
602 #if defined(DEVFS) && defined(DEVFS_ROOT)
603 		(void)subyte(--ucp, 'd');
604 		options = 1;
605 #endif
606 		if (options == 0)
607 			(void)subyte(--ucp, '-');
608 		(void)subyte(--ucp, '-');		/* leading hyphen */
609 		arg1 = ucp;
610 
611 		/*
612 		 * Move out the file name (also arg 0).
613 		 */
614 		for (i = strlen(path) + 1; i >= 0; i--)
615 			(void)subyte(--ucp, path[i]);
616 		arg0 = ucp;
617 
618 		/*
619 		 * Move out the arg pointers.
620 		 */
621 		uap = (char **)((int)ucp & ~(NBPW-1));
622 		(void)suword((caddr_t)--uap, 0);	/* terminator */
623 		(void)suword((caddr_t)--uap, (int)arg1);
624 		(void)suword((caddr_t)--uap, (int)arg0);
625 
626 		/*
627 		 * Point at the arguments.
628 		 */
629 		args.fname = arg0;
630 		args.argv = uap;
631 		args.envv = NULL;
632 
633 		/*
634 		 * Now try to exec the program.  If can't for any reason
635 		 * other than it doesn't exist, complain.
636 		 *
637 		 * Otherwise return to main() which returns to btext
638 		 * which completes the system startup.
639 		 */
640 		if ((error = execve(p, &args)) == 0)
641 			return;
642 		if (error != ENOENT)
643 			printf("exec %s: error %d\n", path, error);
644 	}
645 	printf("init: not found\n");
646 	panic("no init");
647 }
648