xref: /openbsd-src/sys/kern/init_main.c (revision e2a1b4748ac00cfe1e64a346f850b3c670166aef)
1 /*	$OpenBSD: init_main.c,v 1.111 2004/01/21 19:03:44 tedu Exp $	*/
2 /*	$NetBSD: init_main.c,v 1.84.4.1 1996/06/02 09:08:06 mrg Exp $	*/
3 
4 /*
5  * Copyright (c) 1995 Christopher G. Demetriou.  All rights reserved.
6  * Copyright (c) 1982, 1986, 1989, 1991, 1992, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)init_main.c	8.9 (Berkeley) 1/21/94
39  */
40 
41 #include <sys/param.h>
42 #include <sys/filedesc.h>
43 #include <sys/file.h>
44 #include <sys/errno.h>
45 #include <sys/exec.h>
46 #include <sys/kernel.h>
47 #include <sys/kthread.h>
48 #include <sys/mount.h>
49 #include <sys/proc.h>
50 #include <sys/resourcevar.h>
51 #include <sys/signalvar.h>
52 #include <sys/systm.h>
53 #include <sys/namei.h>
54 #include <sys/vnode.h>
55 #include <sys/tty.h>
56 #include <sys/conf.h>
57 #include <sys/buf.h>
58 #include <sys/device.h>
59 #include <sys/socketvar.h>
60 #include <sys/lockf.h>
61 #include <sys/protosw.h>
62 #include <sys/reboot.h>
63 #include <sys/user.h>
64 #ifdef SYSVSHM
65 #include <sys/shm.h>
66 #endif
67 #ifdef SYSVSEM
68 #include <sys/sem.h>
69 #endif
70 #ifdef SYSVMSG
71 #include <sys/msg.h>
72 #endif
73 #include <sys/domain.h>
74 #include <sys/mbuf.h>
75 #include <sys/pipe.h>
76 
77 #include <sys/syscall.h>
78 #include <sys/syscallargs.h>
79 
80 #include <dev/rndvar.h>
81 
82 #include <ufs/ufs/quota.h>
83 
84 #include <machine/cpu.h>
85 
86 #include <uvm/uvm.h>
87 
88 #include <net/if.h>
89 #include <net/raw_cb.h>
90 
91 #if defined(CRYPTO)
92 #include <crypto/cryptodev.h>
93 #include <crypto/cryptosoft.h>
94 #endif
95 
96 #if defined(NFSSERVER) || defined(NFSCLIENT)
97 extern void nfs_init(void);
98 #endif
99 
100 const char	copyright[] =
101 "Copyright (c) 1982, 1986, 1989, 1991, 1993\n"
102 "\tThe Regents of the University of California.  All rights reserved.\n"
103 "Copyright (c) 1995-2004 OpenBSD. All rights reserved.  http://www.OpenBSD.org\n";
104 
105 /* Components of the first process -- never freed. */
106 struct	session session0;
107 struct	pgrp pgrp0;
108 struct	proc proc0;
109 struct	pcred cred0;
110 struct	plimit limit0;
111 struct	vmspace vmspace0;
112 struct	sigacts sigacts0;
113 #ifndef curproc
114 struct	proc *curproc;
115 #endif
116 struct	proc *initproc;
117 
118 int	cmask = CMASK;
119 extern	struct user *proc0paddr;
120 
121 void	(*md_diskconf)(void) = NULL;
122 struct	vnode *rootvp, *swapdev_vp;
123 int	boothowto;
124 struct	timeval boottime;
125 struct	timeval runtime;
126 
127 #if !defined(NO_PROPOLICE)
128 long	__guard[8];
129 #endif
130 
131 /* XXX return int so gcc -Werror won't complain */
132 int	main(void *);
133 void	check_console(struct proc *);
134 void	start_init(void *);
135 void	start_cleaner(void *);
136 void	start_update(void *);
137 void	start_reaper(void *);
138 void    start_crypto(void *);
139 void	init_exec(void);
140 
141 extern char sigcode[], esigcode[];
142 #ifdef SYSCALL_DEBUG
143 extern char *syscallnames[];
144 #endif
145 
146 struct emul emul_native = {
147 	"native",
148 	NULL,
149 	sendsig,
150 	SYS_syscall,
151 	SYS_MAXSYSCALL,
152 	sysent,
153 #ifdef SYSCALL_DEBUG
154 	syscallnames,
155 #else
156 	NULL,
157 #endif
158 	0,
159 	copyargs,
160 	setregs,
161 	NULL,
162 	sigcode,
163 	esigcode,
164 	EMUL_ENABLED | EMUL_NATIVE,
165 };
166 
167 
168 /*
169  * System startup; initialize the world, create process 0, mount root
170  * filesystem, and fork to create init and pagedaemon.  Most of the
171  * hard work is done in the lower-level initialization routines including
172  * startup(), which does memory initialization and autoconfiguration.
173  */
174 /* XXX return int, so gcc -Werror won't complain */
175 int
176 main(framep)
177 	void *framep;				/* XXX should go away */
178 {
179 	struct proc *p;
180 	struct pdevinit *pdev;
181 	struct timeval rtv;
182 	quad_t lim;
183 	int s, i;
184 	register_t rval[2];
185 	extern struct pdevinit pdevinit[];
186 	extern void scheduler_start(void);
187 	extern void disk_init(void);
188 	extern void endtsleep(void *);
189 	extern void realitexpire(void *);
190 
191 	/*
192 	 * Initialize the current process pointer (curproc) before
193 	 * any possible traps/probes to simplify trap processing.
194 	 */
195 	curproc = p = &proc0;
196 
197 	/*
198 	 * Initialize timeouts.
199 	 */
200 	timeout_startup();
201 
202 	/*
203 	 * Attempt to find console and initialize
204 	 * in case of early panic or other messages.
205 	 */
206 	config_init();		/* init autoconfiguration data structures */
207 	consinit();
208 	printf(copyright);
209 	printf("\n");
210 
211 	uvm_init();
212 	disk_init();		/* must come before autoconfiguration */
213 	tty_init();		/* initialise tty's */
214 	cpu_startup();
215 
216 	/*
217 	 * Initialize mbuf's.  Do this now because we might attempt to
218 	 * allocate mbufs or mbuf clusters during autoconfiguration.
219 	 */
220 	mbinit();
221 
222 	/* Initalize sockets. */
223 	soinit();
224 
225 	/* Initialize sysctls (must be done before any processes run) */
226 	sysctl_init();
227 
228 	/*
229 	 * Initialize process and pgrp structures.
230 	 */
231 	procinit();
232 
233 	/* Initialize file locking. */
234 	lf_init();
235 
236 	/*
237 	 * Initialize filedescriptors.
238 	 */
239 	filedesc_init();
240 
241 	/*
242 	 * Initialize pipes.
243 	 */
244 	pipe_init();
245 
246 	/*
247 	 * Create process 0 (the swapper).
248 	 */
249 	LIST_INSERT_HEAD(&allproc, p, p_list);
250 	p->p_pgrp = &pgrp0;
251 	LIST_INSERT_HEAD(PIDHASH(0), p, p_hash);
252 	LIST_INSERT_HEAD(PGRPHASH(0), &pgrp0, pg_hash);
253 	LIST_INIT(&pgrp0.pg_members);
254 	LIST_INSERT_HEAD(&pgrp0.pg_members, p, p_pglist);
255 
256 	pgrp0.pg_session = &session0;
257 	session0.s_count = 1;
258 	session0.s_leader = p;
259 
260 	p->p_flag = P_INMEM | P_SYSTEM | P_NOCLDWAIT;
261 	p->p_stat = SRUN;
262 	p->p_nice = NZERO;
263 	p->p_emul = &emul_native;
264 	bcopy("swapper", p->p_comm, sizeof ("swapper"));
265 
266 	/* Init timeouts. */
267 	timeout_set(&p->p_sleep_to, endtsleep, p);
268 	timeout_set(&p->p_realit_to, realitexpire, p);
269 
270 	/* Create credentials. */
271 	cred0.p_refcnt = 1;
272 	p->p_cred = &cred0;
273 	p->p_ucred = crget();
274 	p->p_ucred->cr_ngroups = 1;	/* group 0 */
275 
276 	/* Initialize signal state for process 0. */
277 	signal_init();
278 	p->p_sigacts = &sigacts0;
279 	siginit(p);
280 
281 	/* Create the file descriptor table. */
282 	p->p_fd = fdinit(NULL);
283 
284 	/* Create the limits structures. */
285 	p->p_limit = &limit0;
286 	for (i = 0; i < sizeof(p->p_rlimit)/sizeof(p->p_rlimit[0]); i++)
287 		limit0.pl_rlimit[i].rlim_cur =
288 		    limit0.pl_rlimit[i].rlim_max = RLIM_INFINITY;
289 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_cur = NOFILE;
290 	limit0.pl_rlimit[RLIMIT_NOFILE].rlim_max = MIN(NOFILE_MAX,
291 	    (maxfiles - NOFILE > NOFILE) ?  maxfiles - NOFILE : NOFILE);
292 	limit0.pl_rlimit[RLIMIT_NPROC].rlim_cur = MAXUPRC;
293 	lim = ptoa(uvmexp.free);
294 	limit0.pl_rlimit[RLIMIT_RSS].rlim_max = lim;
295 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_max = lim;
296 	limit0.pl_rlimit[RLIMIT_MEMLOCK].rlim_cur = lim / 3;
297 	limit0.p_refcnt = 1;
298 
299 	/* Allocate a prototype map so we have something to fork. */
300 	uvmspace_init(&vmspace0, pmap_kernel(), round_page(VM_MIN_ADDRESS),
301 	    trunc_page(VM_MAX_ADDRESS), TRUE);
302 	p->p_vmspace = &vmspace0;
303 
304 	p->p_addr = proc0paddr;				/* XXX */
305 
306 	/*
307 	 * We continue to place resource usage info in the
308 	 * user struct so they're pageable.
309 	 */
310 	p->p_stats = &p->p_addr->u_stats;
311 
312 	/*
313 	 * Charge root for one process.
314 	 */
315 	(void)chgproccnt(0, 1);
316 
317 	/* Initialize run queues */
318 	rqinit();
319 
320 	/* Configure the devices */
321 	cpu_configure();
322 
323 	/* Configure virtual memory system, set vm rlimits. */
324 	uvm_init_limits(p);
325 
326 	/* Initialize the file systems. */
327 #if defined(NFSSERVER) || defined(NFSCLIENT)
328 	nfs_init();			/* initialize server/shared data */
329 #endif
330 	vfsinit();
331 
332 	/* Start real time and statistics clocks. */
333 	initclocks();
334 
335 #ifdef SYSVSHM
336 	/* Initialize System V style shared memory. */
337 	shminit();
338 #endif
339 
340 #ifdef SYSVSEM
341 	/* Initialize System V style semaphores. */
342 	seminit();
343 #endif
344 
345 #ifdef SYSVMSG
346 	/* Initialize System V style message queues. */
347 	msginit();
348 #endif
349 
350 	/* Attach pseudo-devices. */
351 	randomattach();
352 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
353 		if (pdev->pdev_count > 0)
354 			(*pdev->pdev_attach)(pdev->pdev_count);
355 
356 #ifdef CRYPTO
357 	swcr_init();
358 #endif /* CRYPTO */
359 
360 	/*
361 	 * Initialize protocols.  Block reception of incoming packets
362 	 * until everything is ready.
363 	 */
364 	s = splimp();
365 	ifinit();
366 	domaininit();
367 	if_attachdomain();
368 	splx(s);
369 
370 #ifdef GPROF
371 	/* Initialize kernel profiling. */
372 	kmstartup();
373 #endif
374 
375 #if !defined(NO_PROPOLICE)
376 	arc4random_bytes(__guard, sizeof(__guard));
377 #endif
378 
379 	/* init exec and emul */
380 	init_exec();
381 
382 	/* Start the scheduler */
383 	scheduler_start();
384 
385 	dostartuphooks();
386 
387 	/* Configure root/swap devices */
388 	if (md_diskconf)
389 		(*md_diskconf)();
390 
391 	/* Mount the root file system. */
392 	if (vfs_mountroot())
393 		panic("cannot mount root");
394 	CIRCLEQ_FIRST(&mountlist)->mnt_flag |= MNT_ROOTFS;
395 
396 	/* Get the vnode for '/'.  Set p->p_fd->fd_cdir to reference it. */
397 	if (VFS_ROOT(mountlist.cqh_first, &rootvnode))
398 		panic("cannot find root vnode");
399 	p->p_fd->fd_cdir = rootvnode;
400 	VREF(p->p_fd->fd_cdir);
401 	VOP_UNLOCK(rootvnode, 0, p);
402 	p->p_fd->fd_rdir = NULL;
403 
404 	uvm_swap_init();
405 
406 	/*
407 	 * Now can look at time, having had a chance to verify the time
408 	 * from the file system.  Reset p->p_rtime as it may have been
409 	 * munched in mi_switch() after the time got set.
410 	 */
411 	p->p_stats->p_start = runtime = mono_time = boottime = time;
412 	p->p_rtime.tv_sec = p->p_rtime.tv_usec = 0;
413 
414 	/* Create process 1 (init(8)). */
415 	if (fork1(p, SIGCHLD, FORK_FORK, NULL, 0, start_init, NULL, rval))
416 		panic("fork init");
417 
418 	/* Create process 2, the pageout daemon kernel thread. */
419 	if (kthread_create(uvm_pageout, NULL, NULL, "pagedaemon"))
420 		panic("fork pagedaemon");
421 
422 	/* Create process 3, the reaper daemon kernel thread. */
423 	if (kthread_create(start_reaper, NULL, NULL, "reaper"))
424 		panic("fork reaper");
425 
426 	/* Create process 4, the cleaner daemon kernel thread. */
427 	if (kthread_create(start_cleaner, NULL, NULL, "cleaner"))
428 		panic("fork cleaner");
429 
430 	/* Create process 5, the update daemon kernel thread. */
431 	if (kthread_create(start_update, NULL, NULL, "update"))
432 		panic("fork update");
433 
434 	/* Create process 6, the aiodone daemon kernel thread. */
435 	if (kthread_create(uvm_aiodone_daemon, NULL, NULL, "aiodoned"))
436 		panic("fork aiodoned");
437 
438 #ifdef CRYPTO
439 	/* Create process 7, the crypto kernel thread. */
440 	if (kthread_create(start_crypto, NULL, NULL, "crypto"))
441 		panic("crypto thread");
442 #endif /* CRYPTO */
443 
444 	/* Create any other deferred kernel threads. */
445 	kthread_run_deferred_queue();
446 
447 	microtime(&rtv);
448 	srandom((u_long)(rtv.tv_sec ^ rtv.tv_usec));
449 
450 	randompid = 1;
451 	/* The scheduler is an infinite loop. */
452 	uvm_scheduler();
453 	/* NOTREACHED */
454 }
455 
456 /*
457  * List of paths to try when searching for "init".
458  */
459 static char *initpaths[] = {
460 	"/sbin/init",
461 	"/sbin/oinit",
462 	"/sbin/init.bak",
463 	NULL,
464 };
465 
466 void
467 check_console(p)
468 	struct proc *p;
469 {
470 	struct nameidata nd;
471 	int error;
472 
473 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/console", p);
474 	error = namei(&nd);
475 	if (error) {
476 		if (error == ENOENT)
477 			printf("warning: /dev/console does not exist\n");
478 		else
479 			printf("warning: /dev/console error %d\n", error);
480 	} else
481 		vrele(nd.ni_vp);
482 }
483 
484 /*
485  * Start the initial user process; try exec'ing each pathname in "initpaths".
486  * The program is invoked with one argument containing the boot flags.
487  */
488 void
489 start_init(arg)
490 	void *arg;
491 {
492 	struct proc *p = arg;
493 	vaddr_t addr;
494 	struct sys_execve_args /* {
495 		syscallarg(const char *) path;
496 		syscallarg(char *const *) argp;
497 		syscallarg(char *const *) envp;
498 	} */ args;
499 	int options, error;
500 	long i;
501 	register_t retval[2];
502 	char flags[4], *flagsp;
503 	char **pathp, *path, *ucp, **uap, *arg0, *arg1 = NULL;
504 
505 	initproc = p;
506 
507 	/*
508 	 * Now in process 1.
509 	 */
510 	check_console(p);
511 
512 	/*
513 	 * Need just enough stack to hold the faked-up "execve()" arguments.
514 	 */
515 #ifdef MACHINE_STACK_GROWS_UP
516 	addr = USRSTACK;
517 #else
518 	addr = USRSTACK - PAGE_SIZE;
519 #endif
520 	if (uvm_map(&p->p_vmspace->vm_map, &addr, PAGE_SIZE,
521 	    NULL, UVM_UNKNOWN_OFFSET, 0,
522 	    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_ALL, UVM_INH_COPY,
523 	    UVM_ADV_NORMAL, UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW)))
524 		panic("init: couldn't allocate argument space");
525 	p->p_vmspace->vm_maxsaddr = (caddr_t)addr;
526 
527 	for (pathp = &initpaths[0]; (path = *pathp) != NULL; pathp++) {
528 #ifdef MACHINE_STACK_GROWS_UP
529 		ucp = (char *)addr;
530 #else
531 		ucp = (char *)(addr + PAGE_SIZE);
532 #endif
533 		/*
534 		 * Construct the boot flag argument.
535 		 */
536 		flagsp = flags;
537 		*flagsp++ = '-';
538 		options = 0;
539 
540 		if (boothowto & RB_SINGLE) {
541 			*flagsp++ = 's';
542 			options = 1;
543 		}
544 #ifdef notyet
545 		if (boothowto & RB_FASTBOOT) {
546 			*flagsp++ = 'f';
547 			options = 1;
548 		}
549 #endif
550 
551 		/*
552 		 * Move out the flags (arg 1), if necessary.
553 		 */
554 		if (options != 0) {
555 			*flagsp++ = '\0';
556 			i = flagsp - flags;
557 #ifdef DEBUG
558 			printf("init: copying out flags `%s' %d\n", flags, i);
559 #endif
560 #ifdef MACHINE_STACK_GROWS_UP
561 			arg1 = ucp;
562 			(void)copyout((caddr_t)flags, (caddr_t)ucp, i);
563 			ucp += i;
564 #else
565 			(void)copyout((caddr_t)flags, (caddr_t)(ucp -= i), i);
566 			arg1 = ucp;
567 #endif
568 		}
569 
570 		/*
571 		 * Move out the file name (also arg 0).
572 		 */
573 		i = strlen(path) + 1;
574 #ifdef DEBUG
575 		printf("init: copying out path `%s' %d\n", path, i);
576 #endif
577 #ifdef MACHINE_STACK_GROWS_UP
578 		arg0 = ucp;
579 		(void)copyout((caddr_t)path, (caddr_t)ucp, i);
580 		ucp += i;
581 		ucp = (caddr_t)ALIGN((u_long)ucp);
582 		uap = (char **)ucp + 3;
583 #else
584 		(void)copyout((caddr_t)path, (caddr_t)(ucp -= i), i);
585 		arg0 = ucp;
586 		uap = (char **)((u_long)ucp & ~ALIGNBYTES);
587 #endif
588 
589 		/*
590 		 * Move out the arg pointers.
591 		 */
592 		i = 0;
593 		copyout(&i, (caddr_t)--uap, sizeof(register_t)); /* terminator */
594 		if (options != 0)
595 			copyout(&arg1, (caddr_t)--uap, sizeof(register_t));
596 		copyout(&arg0, (caddr_t)--uap, sizeof(register_t));
597 
598 		/*
599 		 * Point at the arguments.
600 		 */
601 		SCARG(&args, path) = arg0;
602 		SCARG(&args, argp) = uap;
603 		SCARG(&args, envp) = NULL;
604 
605 		/*
606 		 * Now try to exec the program.  If can't for any reason
607 		 * other than it doesn't exist, complain.
608 		 */
609 		if ((error = sys_execve(p, &args, retval)) == 0)
610 			return;
611 		if (error != ENOENT)
612 			printf("exec %s: error %d\n", path, error);
613 	}
614 	printf("init: not found\n");
615 	panic("no init");
616 }
617 
618 void
619 start_update(arg)
620 	void *arg;
621 {
622 	sched_sync(curproc);
623 	/* NOTREACHED */
624 }
625 
626 void
627 start_cleaner(arg)
628 	void *arg;
629 {
630 	buf_daemon(curproc);
631 	/* NOTREACHED */
632 }
633 
634 void
635 start_reaper(arg)
636 	void *arg;
637 {
638 	reaper();
639 	/* NOTREACHED */
640 }
641 
642 #ifdef CRYPTO
643 void
644 start_crypto(arg)
645 	void *arg;
646 {
647 	crypto_thread();
648 	/* NOTREACHED */
649 }
650 #endif /* CRYPTO */
651