xref: /illumos-gate/usr/src/uts/common/os/main.c (revision e8921a52c53ee69f7b65f054d9b2e886139daa59)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 /*	Copyright (c) 1988 AT&T	*/
27 /*	  All Rights Reserved		*/
28 
29 /*
30  * Copyright 2018, Joyent, Inc.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/sysmacros.h>
36 #include <sys/pcb.h>
37 #include <sys/systm.h>
38 #include <sys/signal.h>
39 #include <sys/cred.h>
40 #include <sys/user.h>
41 #include <sys/vfs.h>
42 #include <sys/vnode.h>
43 #include <sys/proc.h>
44 #include <sys/time.h>
45 #include <sys/file.h>
46 #include <sys/priocntl.h>
47 #include <sys/procset.h>
48 #include <sys/disp.h>
49 #include <sys/callo.h>
50 #include <sys/callb.h>
51 #include <sys/debug.h>
52 #include <sys/conf.h>
53 #include <sys/bootconf.h>
54 #include <sys/utsname.h>
55 #include <sys/cmn_err.h>
56 #include <sys/vmparam.h>
57 #include <sys/modctl.h>
58 #include <sys/vm.h>
59 #include <sys/callb.h>
60 #include <sys/ddi_periodic.h>
61 #include <sys/kmem.h>
62 #include <sys/vmem.h>
63 #include <sys/cpuvar.h>
64 #include <sys/cladm.h>
65 #include <sys/corectl.h>
66 #include <sys/exec.h>
67 #include <sys/syscall.h>
68 #include <sys/reboot.h>
69 #include <sys/task.h>
70 #include <sys/exacct.h>
71 #include <sys/autoconf.h>
72 #include <sys/errorq.h>
73 #include <sys/class.h>
74 #include <sys/stack.h>
75 #include <sys/brand.h>
76 #include <sys/mmapobj.h>
77 
78 #include <vm/as.h>
79 #include <vm/seg_kmem.h>
80 #include <sys/dc_ki.h>
81 
82 #include <c2/audit.h>
83 #include <sys/bootprops.h>
84 
85 /* well known processes */
86 proc_t *proc_sched;		/* memory scheduler */
87 proc_t *proc_init;		/* init */
88 proc_t *proc_pageout;		/* pageout daemon */
89 proc_t *proc_fsflush;		/* fsflush daemon */
90 
91 pgcnt_t	maxmem;		/* Maximum available memory in pages.	*/
92 pgcnt_t	freemem;	/* Current available memory in pages.	*/
93 int	interrupts_unleashed;	/* set when we do the first spl0() */
94 
95 kmem_cache_t *process_cache;	/* kmem cache for proc structures */
96 
97 /*
98  * Indicates whether the auditing module (c2audit) is loaded. Possible
99  * values are:
100  * 0 - c2audit module is excluded in /etc/system and cannot be loaded
101  * 1 - c2audit module is not loaded but can be anytime
102  * 2 - c2audit module is loaded
103  */
104 int audit_active = C2AUDIT_DISABLED;
105 
106 /*
107  * Process 0's lwp directory and lwpid hash table.
108  */
109 lwpdir_t p0_lwpdir[2];
110 tidhash_t p0_tidhash[2];
111 lwpent_t p0_lep;
112 
113 /*
114  * Machine-independent initialization code
115  * Called from cold start routine as
116  * soon as a stack and segmentation
117  * have been established.
118  * Functions:
119  *	clear and free user core
120  *	turn on clock
121  *	hand craft 0th process
122  *	call all initialization routines
123  *	fork	- process 0 to schedule
124  *		- process 1 execute bootstrap
125  *		- process 2 to page out
126  *	create system threads
127  */
128 
129 int cluster_bootflags = 0;
130 
131 void
132 cluster_wrapper(void)
133 {
134 	cluster();
135 	panic("cluster()  returned");
136 }
137 
138 char initname[INITNAME_SZ] = "/sbin/init";	/* also referenced by zone0 */
139 char initargs[BOOTARGS_MAX] = "";		/* also referenced by zone0 */
140 
141 /*
142  * Construct a stack for init containing the arguments to it, then
143  * pass control to exec_common.
144  */
145 int
146 exec_init(const char *initpath, const char *args)
147 {
148 	uintptr_t ucp;
149 	uintptr_t uap;
150 	uintptr_t *argv;
151 	uintptr_t exec_fnamep;
152 	char *scratchargs;
153 	int i, sarg;
154 	size_t argvlen, alen;
155 	size_t wlen = sizeof (uintptr_t);
156 	boolean_t in_arg;
157 	int argc = 0;
158 	int error = 0, count = 0;
159 	proc_t *p = ttoproc(curthread);
160 	klwp_t *lwp = ttolwp(curthread);
161 	int brand_action;
162 
163 	if (args == NULL)
164 		args = "";
165 
166 	alen = strlen(initpath) + 1 + strlen(args) + 1;
167 	scratchargs = kmem_alloc(alen, KM_SLEEP);
168 	(void) snprintf(scratchargs, alen, "%s %s", initpath, args);
169 
170 	/*
171 	 * We do a quick two state parse of the string to sort out how big
172 	 * argc should be.
173 	 */
174 	in_arg = B_FALSE;
175 	for (i = 0; i < strlen(scratchargs); i++) {
176 		if (scratchargs[i] == ' ' || scratchargs[i] == '\0') {
177 			if (in_arg) {
178 				in_arg = B_FALSE;
179 				argc++;
180 			}
181 		} else {
182 			in_arg = B_TRUE;
183 		}
184 	}
185 	argvlen = sizeof (uintptr_t) * (argc + 1);
186 	argv = kmem_zalloc(argvlen, KM_SLEEP);
187 
188 	/*
189 	 * We pull off a bit of a hack here.  We work our way through the
190 	 * args string, putting nulls at the ends of space delimited tokens
191 	 * (boot args don't support quoting at this time).  Then we just
192 	 * copy the whole mess to userland in one go.  In other words, we
193 	 * transform this: "init -s -r\0" into this on the stack:
194 	 *
195 	 *	-0x00 \0
196 	 *	-0x01 r
197 	 *	-0x02 -  <--------.
198 	 *	-0x03 \0	  |
199 	 *	-0x04 s		  |
200 	 *	-0x05 -  <------. |
201 	 *	-0x06 \0	| |
202 	 *	-0x07 t		| |
203 	 *	-0x08 i		| |
204 	 *	-0x09 n		| |
205 	 *	-0x0a i  <---.  | |
206 	 *	-0x10 NULL   |  | |	(argv[3])
207 	 *	-0x14   -----|--|-'	(argv[2])
208 	 *	-0x18  ------|--'	(argv[1])
209 	 *	-0x1c -------'		(argv[0])
210 	 *
211 	 * Since we know the value of ucp at the beginning of this process,
212 	 * we can trivially compute the argv[] array which we also need to
213 	 * place in userland: argv[i] = ucp - sarg(i), where ucp is the
214 	 * stack ptr, and sarg is the string index of the start of the
215 	 * argument.
216 	 */
217 	ucp = (uintptr_t)p->p_usrstack;
218 
219 	argc = 0;
220 	in_arg = B_FALSE;
221 	sarg = 0;
222 
223 	for (i = 0; i < alen; i++) {
224 		if (scratchargs[i] == ' ' || scratchargs[i] == '\0') {
225 			if (in_arg == B_TRUE) {
226 				in_arg = B_FALSE;
227 				scratchargs[i] = '\0';
228 				argv[argc++] = ucp - (alen - sarg);
229 			}
230 		} else if (in_arg == B_FALSE) {
231 			in_arg = B_TRUE;
232 			sarg = i;
233 		}
234 	}
235 
236 	exec_fnamep = argv[0];
237 
238 	ucp -= alen;
239 	error |= copyout(scratchargs, (caddr_t)ucp, alen);
240 
241 	if (p->p_model == DATAMODEL_ILP32) {
242 		uintptr32_t *argv32;
243 
244 		argv32 = kmem_zalloc(argvlen / 2, KM_SLEEP);
245 
246 		for (i = 0; i < argc; i++)
247 			argv32[i] = (uintptr32_t)argv[i];
248 
249 		kmem_free(argv, argvlen);
250 		argv = (uintptr_t *)argv32;
251 		argvlen /= 2;
252 
253 		wlen = sizeof (uintptr32_t);
254 	}
255 
256 	uap = P2ALIGN(ucp, wlen);
257 	/* advance to be below the word we're in */
258 	uap -= wlen;
259 	/* advance argc words down, plus one for NULL */
260 	uap -= (argc + 1) * wlen;
261 	error |= copyout(argv, (caddr_t)uap, argvlen);
262 
263 	if (error != 0) {
264 		zcmn_err(p->p_zone->zone_id, CE_WARN,
265 		    "Could not construct stack for init.\n");
266 		kmem_free(argv, argvlen);
267 		kmem_free(scratchargs, alen);
268 		return (EFAULT);
269 	}
270 
271 	kmem_free(argv, argvlen);
272 	kmem_free(scratchargs, alen);
273 
274 	/*
275 	 * Point at the arguments.
276 	 */
277 	lwp->lwp_ap = lwp->lwp_arg;
278 	lwp->lwp_arg[0] = exec_fnamep;
279 	lwp->lwp_arg[1] = uap;
280 	lwp->lwp_arg[2] = NULL;
281 	curthread->t_post_sys = 1;
282 	curthread->t_sysnum = SYS_execve;
283 
284 	/*
285 	 * If we are executing init from zsched, we may have inherited its
286 	 * parent process's signal mask.  Clear it now so that we behave in
287 	 * the same way as when started from the global zone.
288 	 */
289 	sigemptyset(&curthread->t_hold);
290 
291 	brand_action = ZONE_IS_BRANDED(p->p_zone) ? EBA_BRAND : EBA_NONE;
292 again:
293 	error = exec_common((const char *)exec_fnamep,
294 	    (const char **)uap, NULL, brand_action);
295 
296 	/*
297 	 * Normally we would just set lwp_argsaved and t_post_sys and
298 	 * let post_syscall reset lwp_ap for us.  Unfortunately,
299 	 * exec_init isn't always called from a system call.  Instead
300 	 * of making a mess of trap_cleanup, we just reset the args
301 	 * pointer here.
302 	 */
303 	reset_syscall_args();
304 
305 	switch (error) {
306 	case 0:
307 		return (0);
308 
309 	case ENOENT:
310 		zcmn_err(p->p_zone->zone_id, CE_WARN,
311 		    "exec(%s) failed (file not found).\n", initpath);
312 		return (ENOENT);
313 
314 	case EAGAIN:
315 	case EINTR:
316 		++count;
317 		if (count < 5) {
318 			zcmn_err(p->p_zone->zone_id, CE_WARN,
319 			    "exec(%s) failed with errno %d.  Retrying...\n",
320 			    initpath, error);
321 			goto again;
322 		}
323 	}
324 
325 	zcmn_err(p->p_zone->zone_id, CE_WARN,
326 	    "exec(%s) failed with errno %d.", initpath, error);
327 	return (error);
328 }
329 
330 /*
331  * This routine does all of the common setup for invoking init; global
332  * and non-global zones employ this routine for the functionality which is
333  * in common.
334  *
335  * This program (init, presumably) must be a 32-bit process.
336  */
337 int
338 start_init_common()
339 {
340 	proc_t *p = curproc;
341 	ASSERT_STACK_ALIGNED();
342 	p->p_zone->zone_proc_initpid = p->p_pid;
343 
344 	p->p_cstime = p->p_stime = p->p_cutime = p->p_utime = 0;
345 	p->p_usrstack = (caddr_t)USRSTACK32;
346 	p->p_model = DATAMODEL_ILP32;
347 	p->p_stkprot = PROT_ZFOD & ~PROT_EXEC;
348 	p->p_datprot = PROT_ZFOD & ~PROT_EXEC;
349 	p->p_stk_ctl = INT32_MAX;
350 
351 	p->p_as = as_alloc();
352 	p->p_as->a_proc = p;
353 	p->p_as->a_userlimit = (caddr_t)USERLIMIT32;
354 	(void) hat_setup(p->p_as->a_hat, HAT_INIT);
355 
356 	init_core();
357 
358 	init_mstate(curthread, LMS_SYSTEM);
359 	return (exec_init(p->p_zone->zone_initname, p->p_zone->zone_bootargs));
360 }
361 
362 /*
363  * Start the initial user process for the global zone; once running, if
364  * init should subsequently fail, it will be automatically be caught in the
365  * exit(2) path, and restarted by restart_init().
366  */
367 static void
368 start_init(void)
369 {
370 	proc_init = curproc;
371 
372 	ASSERT(curproc->p_zone->zone_initname != NULL);
373 
374 	if (start_init_common() != 0)
375 		halt("unix: Could not start init");
376 	lwp_rtt();
377 }
378 
379 void
380 main(void)
381 {
382 	proc_t		*p = ttoproc(curthread);	/* &p0 */
383 	int		(**initptr)();
384 	extern void	sched();
385 	extern void	fsflush();
386 	extern int	(*init_tbl[])();
387 	extern int	(*mp_init_tbl[])();
388 	extern id_t	syscid, defaultcid;
389 	extern int	swaploaded;
390 	extern int	netboot;
391 	extern ib_boot_prop_t *iscsiboot_prop;
392 	extern void	vm_init(void);
393 	extern void	cbe_init_pre(void);
394 	extern void	cbe_init(void);
395 	extern void	clock_tick_init_pre(void);
396 	extern void	clock_tick_init_post(void);
397 	extern void	clock_init(void);
398 	extern void	physio_bufs_init(void);
399 	extern void	pm_cfb_setup_intr(void);
400 	extern int	pm_adjust_timestamps(dev_info_t *, void *);
401 	extern void	start_other_cpus(int);
402 	extern void	sysevent_evc_thrinit();
403 	extern kmutex_t	ualock;
404 #if defined(__x86)
405 	extern void	fastboot_post_startup(void);
406 	extern void	progressbar_start(void);
407 #endif
408 	/*
409 	 * In the horrible world of x86 in-lines, you can't get symbolic
410 	 * structure offsets a la genassym.  This assertion is here so
411 	 * that the next poor slob who innocently changes the offset of
412 	 * cpu_thread doesn't waste as much time as I just did finding
413 	 * out that it's hard-coded in i86/ml/i86.il.  Similarly for
414 	 * curcpup.  You're welcome.
415 	 */
416 	ASSERT(CPU == CPU->cpu_self);
417 	ASSERT(curthread == CPU->cpu_thread);
418 	ASSERT_STACK_ALIGNED();
419 
420 	/*
421 	 * We take the ualock until we have completed the startup
422 	 * to prevent kadmin() from disrupting this work. In particular,
423 	 * we don't want kadmin() to bring the system down while we are
424 	 * trying to start it up.
425 	 */
426 	mutex_enter(&ualock);
427 
428 	/*
429 	 * Setup root lgroup and leaf lgroup for CPU 0
430 	 */
431 	lgrp_init(LGRP_INIT_STAGE2);
432 
433 	/*
434 	 * Once 'startup()' completes, the thread_reaper() daemon would be
435 	 * created(in thread_init()). After that, it is safe to create threads
436 	 * that could exit. These exited threads will get reaped.
437 	 */
438 	startup();
439 	segkmem_gc();
440 	callb_init();
441 	cbe_init_pre();	/* x86 must initialize gethrtimef before timer_init */
442 	ddi_periodic_init();
443 	cbe_init();
444 	callout_init();	/* callout table MUST be init'd after cyclics */
445 	clock_tick_init_pre();
446 	clock_init();
447 
448 #if defined(__x86)
449 	/*
450 	 * The progressbar thread uses cv_reltimedwait() and hence needs to be
451 	 * started after the callout mechanism has been initialized.
452 	 */
453 	progressbar_start();
454 #endif
455 	/*
456 	 * On some platforms, clkinitf() changes the timing source that
457 	 * gethrtime_unscaled() uses to generate timestamps.  cbe_init() calls
458 	 * clkinitf(), so re-initialize the microstate counters after the
459 	 * timesource has been chosen.
460 	 */
461 	init_mstate(&t0, LMS_SYSTEM);
462 	init_cpu_mstate(CPU, CMS_SYSTEM);
463 
464 	/*
465 	 * May need to probe to determine latencies from CPU 0 after
466 	 * gethrtime() comes alive in cbe_init() and before enabling interrupts
467 	 * and copy and release any temporary memory allocated with BOP_ALLOC()
468 	 * before release_bootstrap() frees boot memory
469 	 */
470 	lgrp_init(LGRP_INIT_STAGE3);
471 
472 	/*
473 	 * Call all system initialization functions.
474 	 */
475 	for (initptr = &init_tbl[0]; *initptr; initptr++)
476 		(**initptr)();
477 	/*
478 	 * Load iSCSI boot properties
479 	 */
480 	ld_ib_prop();
481 	/*
482 	 * initialize vm related stuff.
483 	 */
484 	vm_init();
485 
486 	/*
487 	 * initialize buffer pool for raw I/O requests
488 	 */
489 	physio_bufs_init();
490 
491 	ttolwp(curthread)->lwp_error = 0; /* XXX kludge for SCSI driver */
492 
493 	/*
494 	 * Drop the interrupt level and allow interrupts.  At this point
495 	 * the DDI guarantees that interrupts are enabled.
496 	 */
497 	(void) spl0();
498 	interrupts_unleashed = 1;
499 
500 	/*
501 	 * Create kmem cache for proc structures
502 	 */
503 	process_cache = kmem_cache_create("process_cache", sizeof (proc_t),
504 	    0, NULL, NULL, NULL, NULL, NULL, 0);
505 
506 	vfs_mountroot();	/* Mount the root file system */
507 	errorq_init();		/* after vfs_mountroot() so DDI root is ready */
508 	cpu_kstat_init(CPU);	/* after vfs_mountroot() so TOD is valid */
509 	ddi_walk_devs(ddi_root_node(), pm_adjust_timestamps, NULL);
510 				/* after vfs_mountroot() so hrestime is valid */
511 
512 	post_startup();
513 	swaploaded = 1;
514 
515 	/*
516 	 * Initialize Solaris Audit Subsystem
517 	 */
518 	audit_init();
519 
520 	/*
521 	 * Plumb the protocol modules and drivers only if we are not
522 	 * networked booted, in this case we already did it in rootconf().
523 	 */
524 	if (netboot == 0 && iscsiboot_prop == NULL)
525 		(void) strplumb();
526 
527 	gethrestime(&PTOU(curproc)->u_start);
528 	curthread->t_start = PTOU(curproc)->u_start.tv_sec;
529 	p->p_mstart = gethrtime();
530 
531 	/*
532 	 * Perform setup functions that can only be done after root
533 	 * and swap have been set up.
534 	 */
535 	consconfig();
536 #ifndef	__sparc
537 	release_bootstrap();
538 #endif
539 
540 	/*
541 	 * attach drivers with ddi-forceattach prop
542 	 * It must be done early enough to load hotplug drivers (e.g.
543 	 * pcmcia nexus) so that devices enumerated via hotplug is
544 	 * available before I/O subsystem is fully initialized.
545 	 */
546 	i_ddi_forceattach_drivers();
547 
548 	/*
549 	 * Set the scan rate and other parameters of the paging subsystem.
550 	 */
551 	setupclock(0);
552 
553 	/*
554 	 * Initialize process 0's lwp directory and lwpid hash table.
555 	 */
556 	p->p_lwpdir = p->p_lwpfree = p0_lwpdir;
557 	p->p_lwpdir->ld_next = p->p_lwpdir + 1;
558 	p->p_lwpdir_sz = 2;
559 	p->p_tidhash = p0_tidhash;
560 	p->p_tidhash_sz = 2;
561 	p0_lep.le_thread = curthread;
562 	p0_lep.le_lwpid = curthread->t_tid;
563 	p0_lep.le_start = curthread->t_start;
564 	lwp_hash_in(p, &p0_lep, p0_tidhash, 2, 0);
565 
566 	/*
567 	 * Initialize extended accounting.
568 	 */
569 	exacct_init();
570 
571 	/*
572 	 * Initialize threads of sysevent event channels
573 	 */
574 	sysevent_evc_thrinit();
575 
576 	/*
577 	 * This must be done after post_startup() but before
578 	 * start_other_cpus()
579 	 */
580 	lgrp_init(LGRP_INIT_STAGE4);
581 
582 	/*
583 	 * Perform MP initialization, if any.
584 	 */
585 	start_other_cpus(0);
586 
587 #ifdef	__sparc
588 	/*
589 	 * Release bootstrap here since PROM interfaces are
590 	 * used to start other CPUs above.
591 	 */
592 	release_bootstrap();
593 #endif
594 
595 	/*
596 	 * Finish lgrp initialization after all CPUS are brought online.
597 	 */
598 	lgrp_init(LGRP_INIT_STAGE5);
599 
600 	/*
601 	 * After mp_init(), number of cpus are known (this is
602 	 * true for the time being, when there are actually
603 	 * hot pluggable cpus then this scheme  would not do).
604 	 * Any per cpu initialization is done here.
605 	 */
606 	kmem_mp_init();
607 	vmem_update(NULL);
608 
609 	clock_tick_init_post();
610 
611 	for (initptr = &mp_init_tbl[0]; *initptr; initptr++)
612 		(**initptr)();
613 
614 	/*
615 	 * These must be called after start_other_cpus
616 	 */
617 	pm_cfb_setup_intr();
618 #if defined(__x86)
619 	fastboot_post_startup();
620 #endif
621 
622 	/*
623 	 * Make init process; enter scheduling loop with system process.
624 	 *
625 	 * Note that we manually assign the pids for these processes, for
626 	 * historical reasons.  If more pre-assigned pids are needed,
627 	 * FAMOUS_PIDS will have to be updated.
628 	 */
629 
630 	/* create init process */
631 	if (newproc(start_init, NULL, defaultcid, 59, NULL,
632 	    FAMOUS_PID_INIT))
633 		panic("main: unable to fork init.");
634 
635 	/* create pageout daemon */
636 	if (newproc(pageout, NULL, syscid, maxclsyspri - 1, NULL,
637 	    FAMOUS_PID_PAGEOUT))
638 		panic("main: unable to fork pageout()");
639 
640 	/* create fsflush daemon */
641 	if (newproc(fsflush, NULL, syscid, minclsyspri, NULL,
642 	    FAMOUS_PID_FSFLUSH))
643 		panic("main: unable to fork fsflush()");
644 
645 	/* create cluster process if we're a member of one */
646 	if (cluster_bootflags & CLUSTER_BOOTED) {
647 		if (newproc(cluster_wrapper, NULL, syscid, minclsyspri,
648 		    NULL, 0)) {
649 			panic("main: unable to fork cluster()");
650 		}
651 	}
652 
653 	/*
654 	 * Create system threads (threads are associated with p0)
655 	 */
656 
657 	/* create module uninstall daemon */
658 	/* BugID 1132273. If swapping over NFS need a bigger stack */
659 	(void) thread_create(NULL, 0, (void (*)())mod_uninstall_daemon,
660 	    NULL, 0, &p0, TS_RUN, minclsyspri);
661 
662 	(void) thread_create(NULL, 0, seg_pasync_thread,
663 	    NULL, 0, &p0, TS_RUN, minclsyspri);
664 
665 	pid_setmin();
666 
667 	/* system is now ready */
668 	mutex_exit(&ualock);
669 
670 	bcopy("sched", PTOU(curproc)->u_psargs, 6);
671 	bcopy("sched", PTOU(curproc)->u_comm, 5);
672 	sched();
673 	/* NOTREACHED */
674 }
675