xref: /illumos-gate/usr/src/cmd/init/init.c (revision 48847494)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 /*
31  * University Copyright- Copyright (c) 1982, 1986, 1988
32  * The Regents of the University of California
33  * All Rights Reserved
34  *
35  * University Acknowledgment- Portions of this document are derived from
36  * software developed by the University of California, Berkeley, and its
37  * contributors.
38  */
39 
40 /*
41  * init(1M) is the general process spawning program.  Its primary job is to
42  * start and restart svc.startd for smf(5).  For backwards-compatibility it also
43  * spawns and respawns processes according to /etc/inittab and the current
44  * run-level.  It reads /etc/default/inittab for general configuration.
45  *
46  * To change run-levels the system administrator runs init from the command
47  * line with a level name.  init signals svc.startd via libscf and directs the
48  * zone's init (pid 1 in the global zone) what to do by sending it a signal;
49  * these signal numbers are commonly refered to in the code as 'states'.  Valid
50  * run-levels are [sS0123456].  Additionally, init can be given directives
51  * [qQabc], which indicate actions to be taken pertaining to /etc/inittab.
52  *
53  * When init processes inittab entries, it finds processes that are to be
54  * spawned at various run-levels.  inittab contains the set of the levels for
55  * which each inittab entry is valid.
56  *
57  * State File and Restartability
58  *   Premature exit by init(1M) is handled as a special case by the kernel:
59  *   init(1M) will be immediately re-executed, retaining its original PID.  (PID
60  *   1 in the global zone.)  To track the processes it has previously spawned,
61  *   as well as other mutable state, init(1M) regularly updates a state file
62  *   such that its subsequent invocations have knowledge of its various
63  *   dependent processes and duties.
64  *
65  * Process Contracts
66  *   We start svc.startd(1M) in a contract and transfer inherited contracts when
67  *   restarting it.  Everything else is started using the legacy contract
68  *   template, and the created contracts are abandoned when they become empty.
69  *
70  * utmpx Entry Handling
71  *   Because init(1M) no longer governs the startup process, its knowledge of
72  *   when utmpx becomes writable is indirect.  However, spawned processes
73  *   expect to be constructed with valid utmpx entries.  As a result, attempts
74  *   to write normal entries will be retried until successful.
75  *
76  * Maintenance Mode
77  *   In certain failure scenarios, init(1M) will enter a maintenance mode, in
78  *   which it invokes sulogin(1M) to allow the operator an opportunity to
79  *   repair the system.  Normally, this operation is performed as a
80  *   fork(2)-exec(2)-waitpid(3C) sequence with the parent waiting for repair or
81  *   diagnosis to be completed.  In the cases that fork(2) requests themselves
82  *   fail, init(1M) will directly execute sulogin(1M), and allow the kernel to
83  *   restart init(1M) on exit from the operator session.
84  *
85  *   One scenario where init(1M) enters its maintenance mode is when
86  *   svc.startd(1M) begins to fail rapidly, defined as when the average time
87  *   between recent failures drops below a given threshold.
88  */
89 
90 #include <sys/contract/process.h>
91 #include <sys/ctfs.h>
92 #include <sys/stat.h>
93 #include <sys/statvfs.h>
94 #include <sys/stropts.h>
95 #include <sys/systeminfo.h>
96 #include <sys/time.h>
97 #include <sys/termios.h>
98 #include <sys/tty.h>
99 #include <sys/types.h>
100 #include <sys/utsname.h>
101 
102 #include <bsm/adt_event.h>
103 #include <bsm/libbsm.h>
104 #include <security/pam_appl.h>
105 
106 #include <assert.h>
107 #include <ctype.h>
108 #include <dirent.h>
109 #include <errno.h>
110 #include <fcntl.h>
111 #include <libcontract.h>
112 #include <libcontract_priv.h>
113 #include <libintl.h>
114 #include <libscf.h>
115 #include <libscf_priv.h>
116 #include <poll.h>
117 #include <procfs.h>
118 #include <signal.h>
119 #include <stdarg.h>
120 #include <stdio.h>
121 #include <stdio_ext.h>
122 #include <stdlib.h>
123 #include <string.h>
124 #include <strings.h>
125 #include <syslog.h>
126 #include <time.h>
127 #include <ulimit.h>
128 #include <unistd.h>
129 #include <utmpx.h>
130 #include <wait.h>
131 #include <zone.h>
132 #include <ucontext.h>
133 
134 #undef	sleep
135 
136 #define	fioctl(p, sptr, cmd)	ioctl(fileno(p), sptr, cmd)
137 #define	min(a, b)		(((a) < (b)) ? (a) : (b))
138 
139 #define	TRUE	1
140 #define	FALSE	0
141 #define	FAILURE	-1
142 
143 #define	UT_LINE_SZ	32	/* Size of a utmpx ut_line field */
144 
145 /*
146  * SLEEPTIME	The number of seconds "init" sleeps between wakeups if
147  *		nothing else requires this "init" wakeup.
148  */
149 #define	SLEEPTIME	(5 * 60)
150 
151 /*
152  * MAXCMDL	The maximum length of a command string in inittab.
153  */
154 #define	MAXCMDL	512
155 
156 /*
157  * EXEC		The length of the prefix string added to all comamnds
158  *		found in inittab.
159  */
160 #define	EXEC	(sizeof ("exec ") - 1)
161 
162 /*
163  * TWARN	The amount of time between warning signal, SIGTERM,
164  *		and the fatal kill signal, SIGKILL.
165  */
166 #define	TWARN	5
167 
168 #define	id_eq(x, y)	((x[0] == y[0] && x[1] == y[1] && x[2] == y[2] &&\
169 			x[3] == y[3]) ? TRUE : FALSE)
170 
171 /*
172  * The kernel's default umask is 022 these days; since some processes inherit
173  * their umask from init, init will set it from CMASK in /etc/default/init.
174  * init gets the default umask from the kernel, it sets it to 022 whenever
175  * it wants to create a file and reverts to CMASK afterwards.
176  */
177 
178 static int cmask;
179 
180 /*
181  * The following definitions, concluding with the 'lvls' array, provide a
182  * common mapping between level-name (like 'S'), signal number (state),
183  * run-level mask, and specific properties associated with a run-level.
184  * This array should be accessed using the routines lvlname_to_state(),
185  * lvlname_to_mask(), state_to_mask(), and state_to_flags().
186  */
187 
188 /*
189  * Correspondence of signals to init actions.
190  */
191 #define	LVLQ		SIGHUP
192 #define	LVL0		SIGINT
193 #define	LVL1		SIGQUIT
194 #define	LVL2		SIGILL
195 #define	LVL3		SIGTRAP
196 #define	LVL4		SIGIOT
197 #define	LVL5		SIGEMT
198 #define	LVL6		SIGFPE
199 #define	SINGLE_USER	SIGBUS
200 #define	LVLa		SIGSEGV
201 #define	LVLb		SIGSYS
202 #define	LVLc		SIGPIPE
203 
204 /*
205  * Bit Mask for each level.  Used to determine legal levels.
206  */
207 #define	MASK0	0x0001
208 #define	MASK1	0x0002
209 #define	MASK2	0x0004
210 #define	MASK3	0x0008
211 #define	MASK4	0x0010
212 #define	MASK5	0x0020
213 #define	MASK6	0x0040
214 #define	MASKSU	0x0080
215 #define	MASKa	0x0100
216 #define	MASKb	0x0200
217 #define	MASKc	0x0400
218 
219 #define	MASK_NUMERIC (MASK0 | MASK1 | MASK2 | MASK3 | MASK4 | MASK5 | MASK6)
220 #define	MASK_abc (MASKa | MASKb | MASKc)
221 
222 /*
223  * Flags to indicate properties of various states.
224  */
225 #define	LSEL_RUNLEVEL	0x0001	/* runlevels you can transition to */
226 
227 typedef struct lvl {
228 	int	lvl_state;
229 	int	lvl_mask;
230 	char	lvl_name;
231 	int	lvl_flags;
232 } lvl_t;
233 
234 static lvl_t lvls[] = {
235 	{ LVLQ,		0,	'Q', 0					},
236 	{ LVLQ,		0,	'q', 0					},
237 	{ LVL0,		MASK0,	'0', LSEL_RUNLEVEL			},
238 	{ LVL1, 	MASK1,	'1', LSEL_RUNLEVEL			},
239 	{ LVL2, 	MASK2,	'2', LSEL_RUNLEVEL			},
240 	{ LVL3, 	MASK3,	'3', LSEL_RUNLEVEL			},
241 	{ LVL4, 	MASK4,	'4', LSEL_RUNLEVEL			},
242 	{ LVL5, 	MASK5,	'5', LSEL_RUNLEVEL			},
243 	{ LVL6, 	MASK6, 	'6', LSEL_RUNLEVEL			},
244 	{ SINGLE_USER, 	MASKSU, 'S', LSEL_RUNLEVEL			},
245 	{ SINGLE_USER, 	MASKSU, 's', LSEL_RUNLEVEL			},
246 	{ LVLa,		MASKa,	'a', 0					},
247 	{ LVLb,		MASKb,	'b', 0					},
248 	{ LVLc,		MASKc,	'c', 0					}
249 };
250 
251 #define	LVL_NELEMS (sizeof (lvls) / sizeof (lvl_t))
252 
253 /*
254  * Legal action field values.
255  */
256 #define	OFF		0	/* Kill process if on, else ignore */
257 #define	RESPAWN		1	/* Continuously restart process when it dies */
258 #define	ONDEMAND	RESPAWN	/* Respawn for a, b, c type processes */
259 #define	ONCE		2	/* Start process, do not respawn when dead */
260 #define	WAIT		3	/* Perform once and wait to complete */
261 #define	BOOT		4	/* Start at boot time only */
262 #define	BOOTWAIT	5	/* Start at boot time and wait to complete */
263 #define	POWERFAIL	6	/* Start on powerfail */
264 #define	POWERWAIT	7	/* Start and wait for complete on powerfail */
265 #define	INITDEFAULT	8	/* Default level "init" should start at */
266 #define	SYSINIT		9	/* Actions performed before init speaks */
267 
268 #define	M_OFF		0001
269 #define	M_RESPAWN	0002
270 #define	M_ONDEMAND	M_RESPAWN
271 #define	M_ONCE		0004
272 #define	M_WAIT		0010
273 #define	M_BOOT		0020
274 #define	M_BOOTWAIT	0040
275 #define	M_PF		0100
276 #define	M_PWAIT		0200
277 #define	M_INITDEFAULT	0400
278 #define	M_SYSINIT	01000
279 
280 /* States for the inittab parser in getcmd(). */
281 #define	ID	1
282 #define	LEVELS	2
283 #define	ACTION	3
284 #define	COMMAND	4
285 #define	COMMENT	5
286 
287 /*
288  * inittab entry id constants
289  */
290 #define	INITTAB_ENTRY_ID_SIZE 4
291 #define	INITTAB_ENTRY_ID_STR_FORMAT "%.4s"	/* if INITTAB_ENTRY_ID_SIZE */
292 						/* changes, this should */
293 						/* change accordingly */
294 
295 /*
296  * Init can be in any of three main states, "normal" mode where it is
297  * processing entries for the lines file in a normal fashion, "boot" mode,
298  * where it is only interested in the boot actions, and "powerfail" mode,
299  * where it is only interested in powerfail related actions. The following
300  * masks declare the legal actions for each mode.
301  */
302 #define	NORMAL_MODES	(M_OFF | M_RESPAWN | M_ONCE | M_WAIT)
303 #define	BOOT_MODES	(M_BOOT | M_BOOTWAIT)
304 #define	PF_MODES	(M_PF | M_PWAIT)
305 
306 struct PROC_TABLE {
307 	char	p_id[INITTAB_ENTRY_ID_SIZE];	/* Four letter unique id of */
308 						/* process */
309 	pid_t	p_pid;		/* Process id */
310 	short	p_count;	/* How many respawns of this command in */
311 				/*   the current series */
312 	long	p_time;		/* Start time for a series of respawns */
313 	short	p_flags;
314 	short	p_exit;		/* Exit status of a process which died */
315 };
316 
317 /*
318  * Flags for the "p_flags" word of a PROC_TABLE entry:
319  *
320  *	OCCUPIED	This slot in init's proc table is in use.
321  *
322  *	LIVING		Process is alive.
323  *
324  *	NOCLEANUP	efork() is not allowed to cleanup this entry even
325  *			if process is dead.
326  *
327  *	NAMED		This process has a name, i.e. came from inittab.
328  *
329  *	DEMANDREQUEST	Process started by a "telinit [abc]" command.  Processes
330  *			formed this way are respawnable and immune to level
331  *			changes as long as their entry exists in inittab.
332  *
333  *	TOUCHED		Flag used by remv() to determine whether it has looked
334  *			at an entry while checking for processes to be killed.
335  *
336  *	WARNED		Flag used by remv() to mark processes that have been
337  *			sent the SIGTERM signal.  If they don't die in 5
338  *			seconds, they are sent the SIGKILL signal.
339  *
340  *	KILLED		Flag used by remv() to mark procs that have been sent
341  *			the SIGTERM and SIGKILL signals.
342  *
343  *	PF_MASK		Bitwise or of legal flags, for sanity checking.
344  */
345 #define	OCCUPIED	01
346 #define	LIVING		02
347 #define	NOCLEANUP	04
348 #define	NAMED		010
349 #define	DEMANDREQUEST	020
350 #define	TOUCHED		040
351 #define	WARNED		0100
352 #define	KILLED		0200
353 #define	PF_MASK		0377
354 
355 /*
356  * Respawn limits for processes that are to be respawned:
357  *
358  *	SPAWN_INTERVAL	The number of seconds over which "init" will try to
359  *			respawn a process SPAWN_LIMIT times before it gets mad.
360  *
361  *	SPAWN_LIMIT	The number of respawns "init" will attempt in
362  *			SPAWN_INTERVAL seconds before it generates an
363  *			error message and inhibits further tries for
364  *			INHIBIT seconds.
365  *
366  *	INHIBIT		The number of seconds "init" ignores an entry it had
367  *			trouble spawning unless a "telinit Q" is received.
368  */
369 
370 #define	SPAWN_INTERVAL	(2*60)
371 #define	SPAWN_LIMIT	10
372 #define	INHIBIT		(5*60)
373 
374 /*
375  * The maximum number of decimal digits for an id_t.  (ceil(log10 (max_id)))
376  */
377 #define	ID_MAX_STR_LEN	10
378 
379 #define	NULLPROC	((struct PROC_TABLE *)(0))
380 #define	NO_ROOM		((struct PROC_TABLE *)(FAILURE))
381 
382 struct CMD_LINE {
383 	char c_id[INITTAB_ENTRY_ID_SIZE];	/* Four letter unique id of */
384 						/* process to be affected by */
385 						/* action */
386 	short c_levels;	/* Mask of legal levels for process */
387 	short c_action;	/* Mask for type of action required */
388 	char *c_command; /* Pointer to init command */
389 };
390 
391 struct	pidrec {
392 	int	pd_type;	/* Command type */
393 	pid_t	pd_pid;		/* pid to add or remove */
394 };
395 
396 /*
397  * pd_type's
398  */
399 #define	ADDPID	1
400 #define	REMPID	2
401 
402 static struct	pidlist {
403 	pid_t	pl_pid;		/* pid to watch for */
404 	int	pl_dflag;	/* Flag indicating SIGCLD from this pid */
405 	short	pl_exit;	/* Exit status of proc */
406 	struct	pidlist	*pl_next; /* Next in list */
407 } *Plhead, *Plfree;
408 
409 /*
410  * The following structure contains a set of modes for /dev/syscon
411  * and should match the default contents of /etc/ioctl.syscon.
412  */
413 static struct termios	dflt_termios = {
414 	BRKINT|ICRNL|IXON|IMAXBEL,			/* iflag */
415 	OPOST|ONLCR|TAB3,				/* oflag */
416 	CS8|CREAD|B9600,				/* cflag */
417 	ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN, /* lflag */
418 	CINTR, CQUIT, CERASE, CKILL, CEOF, 0, 0, 0,
419 	0, 0, 0, 0, 0, 0, 0, 0,
420 	0, 0, 0
421 };
422 
423 static struct termios	stored_syscon_termios;
424 static int		write_ioctl = 0;	/* Rewrite /etc/ioctl.syscon */
425 
426 static union WAKEUP {
427 	struct WAKEFLAGS {
428 		unsigned w_usersignal : 1;	/* User sent signal to "init" */
429 		unsigned w_childdeath : 1;	/* An "init" child died */
430 		unsigned w_powerhit : 1;	/* OS experienced powerfail */
431 	}	w_flags;
432 	int w_mask;
433 } wakeup;
434 
435 
436 struct init_state {
437 	int			ist_runlevel;
438 	int			ist_num_proc;
439 	int			ist_utmpx_ok;
440 	struct PROC_TABLE	ist_proc_table[1];
441 };
442 
443 #define	cur_state	(g_state->ist_runlevel)
444 #define	num_proc	(g_state->ist_num_proc)
445 #define	proc_table	(g_state->ist_proc_table)
446 #define	utmpx_ok	(g_state->ist_utmpx_ok)
447 
448 /* Contract cookies. */
449 #define	ORDINARY_COOKIE		0
450 #define	STARTD_COOKIE		1
451 
452 
453 #ifndef NDEBUG
454 #define	bad_error(func, err)	{					\
455 	(void) fprintf(stderr, "%s:%d: %s() failed with unexpected "	\
456 	    "error %d.  Aborting.\n", __FILE__, __LINE__, (func), (err)); \
457 	abort();							\
458 }
459 #else
460 #define	bad_error(func, err)	abort()
461 #endif
462 
463 
464 /*
465  * Useful file and device names.
466  */
467 static char *CONSOLE	  = "/dev/console";	/* Real system console */
468 static char *INITPIPE_DIR = "/var/run";
469 static char *INITPIPE	  = "/var/run/initpipe";
470 
471 #define	INIT_STATE_DIR "/etc/svc/volatile"
472 static const char * const init_state_file = INIT_STATE_DIR "/init.state";
473 static const char * const init_next_state_file =
474 	INIT_STATE_DIR "/init-next.state";
475 
476 static const int init_num_proc = 20;	/* Initial size of process table. */
477 
478 static char *UTMPX	 = UTMPX_FILE;		/* Snapshot record file */
479 static char *WTMPX	 = WTMPX_FILE;		/* Long term record file */
480 static char *INITTAB	 = "/etc/inittab";	/* Script file for "init" */
481 static char *SYSTTY	 = "/dev/systty";	/* System Console */
482 static char *SYSCON	 = "/dev/syscon";	/* Virtual System console */
483 static char *IOCTLSYSCON = "/etc/ioctl.syscon";	/* Last syscon modes */
484 static char *ENVFILE	 = "/etc/default/init";	/* Default env. */
485 static char *SU	= "/etc/sulogin";	/* Super-user program for single user */
486 static char *SH	= "/sbin/sh";		/* Standard shell */
487 
488 /*
489  * Default Path.  /sbin is included in path only during sysinit phase
490  */
491 #define	DEF_PATH	"PATH=/usr/sbin:/usr/bin"
492 #define	INIT_PATH	"PATH=/sbin:/usr/sbin:/usr/bin"
493 
494 static int	prior_state;
495 static int	prev_state;	/* State "init" was in last time it woke */
496 static int	new_state;	/* State user wants "init" to go to. */
497 static int	lvlq_received;	/* Explicit request to examine state */
498 static int	op_modes = BOOT_MODES; /* Current state of "init" */
499 static int	Gchild = 0;	/* Flag to indicate "godchild" died, set in */
500 				/*   childeath() and cleared in cleanaux() */
501 static int	Pfd = -1;	/* fd to receive pids thru */
502 static unsigned int	spawncnt, pausecnt;
503 static int	rsflag;		/* Set if a respawn has taken place */
504 static volatile int time_up;	/* Flag set to TRUE by the alarm interrupt */
505 				/* routine each time an alarm interrupt */
506 				/* takes place. */
507 static int	sflg = 0;	/* Set if we were booted -s to single user */
508 static int	rflg = 0;	/* Set if booted -r, reconfigure devices */
509 static int	bflg = 0;	/* Set if booted -b, don't run rc scripts */
510 static pid_t	init_pid;	/* PID of "one true" init for current zone */
511 
512 static struct init_state *g_state = NULL;
513 static size_t	g_state_sz;
514 static int	booting = 1;	/* Set while we're booting. */
515 
516 /*
517  * Array for default global environment.
518  */
519 #define	MAXENVENT	24	/* Max number of default env variables + 1 */
520 				/* init can use three itself, so this leaves */
521 				/* 20 for the administrator in ENVFILE. */
522 static char	*glob_envp[MAXENVENT];	/* Array of environment strings */
523 static int	glob_envn;		/* Number of environment strings */
524 
525 
526 static struct pollfd	poll_fds[1];
527 static int		poll_nfds = 0;	/* poll_fds is uninitialized */
528 
529 /*
530  * Contracts constants
531  */
532 #define	SVC_INIT_PREFIX "init:/"
533 #define	SVC_AUX_SIZE (INITTAB_ENTRY_ID_SIZE + 1)
534 #define	SVC_FMRI_SIZE (sizeof (SVC_INIT_PREFIX) + INITTAB_ENTRY_ID_SIZE)
535 
536 static int	legacy_tmpl = -1;	/* fd for legacy contract template */
537 static int	startd_tmpl = -1;	/* fd for svc.startd's template */
538 static char	startd_svc_aux[SVC_AUX_SIZE];
539 
540 static char	startd_cline[256] = "";	/* svc.startd's command line */
541 static int	do_restart_startd = 1;	/* Whether to restart svc.startd. */
542 static char	*smf_options = NULL;	/* Options to give to startd. */
543 static int	smf_debug = 0;		/* Messages for debugging smf(5) */
544 static time_t	init_boot_time;		/* Substitute for kernel boot time. */
545 
546 #define	NSTARTD_FAILURE_TIMES	3		/* trigger after 3 failures */
547 #define	STARTD_FAILURE_RATE_NS	5000000000LL	/* 1 failure/5 seconds */
548 
549 static hrtime_t	startd_failure_time[NSTARTD_FAILURE_TIMES];
550 static uint_t	startd_failure_index;
551 
552 
553 static char	*prog_name(char *);
554 static int	state_to_mask(int);
555 static int	lvlname_to_mask(char, int *);
556 static void	lscf_set_runlevel(char);
557 static int	state_to_flags(int);
558 static char	state_to_name(int);
559 static int	lvlname_to_state(char);
560 static int	getcmd(struct CMD_LINE *, char *);
561 static int	realcon();
562 static int	spawn_processes();
563 static int	get_ioctl_syscon();
564 static int	account(short, struct PROC_TABLE *, char *);
565 static void	alarmclk();
566 static void	childeath(int);
567 static void	cleanaux();
568 static void	clearent(pid_t, short);
569 static void	console(boolean_t, char *, ...);
570 static void	init_signals(void);
571 static void	setup_pipe();
572 static void	killproc(pid_t);
573 static void	init_env();
574 static void	boot_init();
575 static void	powerfail();
576 static void	remv();
577 static void	write_ioctl_syscon();
578 static void	spawn(struct PROC_TABLE *, struct CMD_LINE *);
579 static void	setimer(int);
580 static void	siglvl(int, siginfo_t *, ucontext_t *);
581 static void	sigpoll(int);
582 static void	enter_maintenance(void);
583 static void	timer(int);
584 static void	userinit(int, char **);
585 static void	notify_pam_dead(struct utmpx *);
586 static long	waitproc(struct PROC_TABLE *);
587 static struct PROC_TABLE *efork(int, struct PROC_TABLE *, int);
588 static struct PROC_TABLE *findpslot(struct CMD_LINE *);
589 static void	increase_proc_table_size();
590 static void	st_init();
591 static void	st_write();
592 static void	contracts_init();
593 static void	contract_event(struct pollfd *);
594 static int	startd_run(const char *, int, ctid_t);
595 static void	startd_record_failure();
596 static int	startd_failure_rate_critical();
597 static char	*audit_boot_msg();
598 static int	audit_put_record(int, int, char *);
599 static void	update_boot_archive(int new_state);
600 
601 int
602 main(int argc, char *argv[])
603 {
604 	int	chg_lvl_flag = FALSE, print_banner = FALSE;
605 	int	may_need_audit = 1;
606 	int	c;
607 	char	*msg;
608 
609 	/* Get a timestamp for use as boot time, if needed. */
610 	(void) time(&init_boot_time);
611 
612 	/* Get the default umask */
613 	cmask = umask(022);
614 	(void) umask(cmask);
615 
616 	/* Parse the arguments to init. Check for single user */
617 	opterr = 0;
618 	while ((c = getopt(argc, argv, "brsm:")) != EOF) {
619 		switch (c) {
620 		case 'b':
621 			rflg = 0;
622 			bflg = 1;
623 			if (!sflg)
624 				sflg++;
625 			break;
626 		case 'r':
627 			bflg = 0;
628 			rflg++;
629 			break;
630 		case 's':
631 			if (!bflg)
632 				sflg++;
633 			break;
634 		case 'm':
635 			smf_options = optarg;
636 			smf_debug = (strstr(smf_options, "debug") != NULL);
637 			break;
638 		}
639 	}
640 
641 	/*
642 	 * Determine if we are the main init, or a user invoked init, whose job
643 	 * it is to inform init to change levels or perform some other action.
644 	 */
645 	if (zone_getattr(getzoneid(), ZONE_ATTR_INITPID, &init_pid,
646 	    sizeof (init_pid)) != sizeof (init_pid)) {
647 		(void) fprintf(stderr, "could not get pid for init\n");
648 		return (1);
649 	}
650 
651 	/*
652 	 * If this PID is not the same as the "true" init for the zone, then we
653 	 * must be in 'user' mode.
654 	 */
655 	if (getpid() != init_pid) {
656 		userinit(argc, argv);
657 	}
658 
659 	if (getzoneid() != GLOBAL_ZONEID) {
660 		print_banner = TRUE;
661 	}
662 
663 	/*
664 	 * Initialize state (and set "booting").
665 	 */
666 	st_init();
667 
668 	if (booting && print_banner) {
669 		struct utsname un;
670 		char buf[BUFSIZ], *isa;
671 		long ret;
672 		int bits = 32;
673 
674 		/*
675 		 * We want to print the boot banner as soon as
676 		 * possible.  In the global zone, the kernel does it,
677 		 * but we do not have that luxury in non-global zones,
678 		 * so we will print it here.
679 		 */
680 		(void) uname(&un);
681 		ret = sysinfo(SI_ISALIST, buf, sizeof (buf));
682 		if (ret != -1L && ret <= sizeof (buf)) {
683 			for (isa = strtok(buf, " "); isa;
684 			    isa = strtok(NULL, " ")) {
685 				if (strcmp(isa, "sparcv9") == 0 ||
686 				    strcmp(isa, "amd64") == 0) {
687 					bits = 64;
688 					break;
689 				}
690 			}
691 		}
692 
693 		console(B_FALSE,
694 		    "\n\n%s Release %s Version %s %d-bit\r\n",
695 		    un.sysname, un.release, un.version, bits);
696 		console(B_FALSE,
697 		    "Copyright 1983-2009 Sun Microsystems, Inc. "
698 		    " All rights reserved.\r\n");
699 		console(B_FALSE,
700 		    "Use is subject to license terms.\r\n");
701 	}
702 
703 	/*
704 	 * Get the ioctl settings for /dev/syscon from /etc/ioctl.syscon
705 	 * so that it can be brought up in the state it was in when the
706 	 * system went down; or set to defaults if ioctl.syscon isn't
707 	 * valid.
708 	 *
709 	 * This needs to be done even if we're restarting so reset_modes()
710 	 * will work in case we need to go down to single user mode.
711 	 */
712 	write_ioctl = get_ioctl_syscon();
713 
714 	/*
715 	 * Set up all signals to be caught or ignored as appropriate.
716 	 */
717 	init_signals();
718 
719 	/* Load glob_envp from ENVFILE. */
720 	init_env();
721 
722 	contracts_init();
723 
724 	if (!booting) {
725 		/* cur_state should have been read in. */
726 
727 		op_modes = NORMAL_MODES;
728 
729 		/* Rewrite the ioctl file if it was bad. */
730 		if (write_ioctl)
731 			write_ioctl_syscon();
732 	} else {
733 		/*
734 		 * It's fine to boot up with state as zero, because
735 		 * startd will later tell us the real state.
736 		 */
737 		cur_state = 0;
738 		op_modes = BOOT_MODES;
739 
740 		boot_init();
741 	}
742 
743 	prev_state = prior_state = cur_state;
744 
745 	setup_pipe();
746 
747 	/*
748 	 * Here is the beginning of the main process loop.
749 	 */
750 	for (;;) {
751 		if (lvlq_received) {
752 			setup_pipe();
753 			lvlq_received = B_FALSE;
754 		}
755 
756 		/*
757 		 * Clean up any accounting records for dead "godchildren".
758 		 */
759 		if (Gchild)
760 			cleanaux();
761 
762 		/*
763 		 * If in "normal" mode, check all living processes and initiate
764 		 * kill sequence on those that should not be there anymore.
765 		 */
766 		if (op_modes == NORMAL_MODES && cur_state != LVLa &&
767 		    cur_state != LVLb && cur_state != LVLc)
768 			remv();
769 
770 		/*
771 		 * If a change in run levels is the reason we awoke, now do
772 		 * the accounting to report the change in the utmp file.
773 		 * Also report the change on the system console.
774 		 */
775 		if (chg_lvl_flag) {
776 			chg_lvl_flag = FALSE;
777 
778 			if (state_to_flags(cur_state) & LSEL_RUNLEVEL) {
779 				char rl = state_to_name(cur_state);
780 
781 				if (rl != -1)
782 					lscf_set_runlevel(rl);
783 			}
784 
785 			may_need_audit = 1;
786 		}
787 
788 		/*
789 		 * Scan the inittab file and spawn and respawn processes that
790 		 * should be alive in the current state. If inittab does not
791 		 * exist default to  single user mode.
792 		 */
793 		if (spawn_processes() == FAILURE) {
794 			prior_state = prev_state;
795 			cur_state = SINGLE_USER;
796 		}
797 
798 		/* If any respawns occurred, take note. */
799 		if (rsflag) {
800 			rsflag = 0;
801 			spawncnt++;
802 		}
803 
804 		/*
805 		 * If a powerfail signal was received during the last
806 		 * sequence, set mode to powerfail.  When spawn_processes() is
807 		 * entered the first thing it does is to check "powerhit".  If
808 		 * it is in PF_MODES then it clears "powerhit" and does
809 		 * a powerfail sequence.  If it is not in PF_MODES, then it
810 		 * puts itself in PF_MODES and then clears "powerhit".  Should
811 		 * "powerhit" get set again while spawn_processes() is working
812 		 * on a powerfail sequence, the following code  will see that
813 		 * spawn_processes() tries to execute the powerfail sequence
814 		 * again.  This guarantees that the powerfail sequence will be
815 		 * successfully completed before further processing takes
816 		 * place.
817 		 */
818 		if (wakeup.w_flags.w_powerhit) {
819 			op_modes = PF_MODES;
820 			/*
821 			 * Make sure that cur_state != prev_state so that
822 			 * ONCE and WAIT types work.
823 			 */
824 			prev_state = 0;
825 		} else if (op_modes != NORMAL_MODES) {
826 			/*
827 			 * If spawn_processes() was not just called while in
828 			 * normal mode, we set the mode to normal and it will
829 			 * be called again to check normal modes.  If we have
830 			 * just finished a powerfail sequence with prev_state
831 			 * equal to zero, we set prev_state equal to cur_state
832 			 * before the next pass through.
833 			 */
834 			if (op_modes == PF_MODES)
835 				prev_state = cur_state;
836 			op_modes = NORMAL_MODES;
837 		} else if (cur_state == LVLa || cur_state == LVLb ||
838 		    cur_state == LVLc) {
839 			/*
840 			 * If it was a change of levels that awakened us and the
841 			 * new level is one of the demand levels then reset
842 			 * cur_state to the previous state and do another scan
843 			 * to take care of the usual respawn actions.
844 			 */
845 			cur_state = prior_state;
846 			prior_state = prev_state;
847 			prev_state = cur_state;
848 		} else {
849 			prev_state = cur_state;
850 
851 			if (wakeup.w_mask == 0) {
852 				int ret;
853 
854 				if (may_need_audit && (cur_state == LVL3)) {
855 					msg = audit_boot_msg();
856 
857 					may_need_audit = 0;
858 					(void) audit_put_record(ADT_SUCCESS,
859 					    ADT_SUCCESS, msg);
860 					free(msg);
861 				}
862 
863 				/*
864 				 * "init" is finished with all actions for
865 				 * the current wakeup.
866 				 */
867 				ret = poll(poll_fds, poll_nfds,
868 				    SLEEPTIME * MILLISEC);
869 				pausecnt++;
870 				if (ret > 0)
871 					contract_event(&poll_fds[0]);
872 				else if (ret < 0 && errno != EINTR)
873 					console(B_TRUE, "poll() error: %s\n",
874 					    strerror(errno));
875 			}
876 
877 			if (wakeup.w_flags.w_usersignal) {
878 				/*
879 				 * Install the new level.  This could be a real
880 				 * change in levels  or a telinit [Q|a|b|c] or
881 				 * just a telinit to the same level at which
882 				 * we are running.
883 				 */
884 				if (new_state != cur_state) {
885 					if (new_state == LVLa ||
886 					    new_state == LVLb ||
887 					    new_state == LVLc) {
888 						prev_state = prior_state;
889 						prior_state = cur_state;
890 						cur_state = new_state;
891 					} else {
892 						prev_state = cur_state;
893 						if (cur_state >= 0)
894 							prior_state = cur_state;
895 						cur_state = new_state;
896 						chg_lvl_flag = TRUE;
897 					}
898 				}
899 
900 				new_state = 0;
901 			}
902 
903 			if (wakeup.w_flags.w_powerhit)
904 				op_modes = PF_MODES;
905 
906 			/*
907 			 * Clear all wakeup reasons.
908 			 */
909 			wakeup.w_mask = 0;
910 		}
911 	}
912 
913 	/*NOTREACHED*/
914 }
915 
916 static void
917 update_boot_archive(int new_state)
918 {
919 	if (new_state != LVL0 && new_state != LVL5 && new_state != LVL6)
920 		return;
921 
922 	if (getzoneid() != GLOBAL_ZONEID)
923 		return;
924 
925 	(void) system("/sbin/bootadm -ea update_all");
926 }
927 
928 /*
929  * void enter_maintenance()
930  *   A simple invocation of sulogin(1M), with no baggage, in the case that we
931  *   are unable to activate svc.startd(1M).  We fork; the child runs sulogin;
932  *   we wait for it to exit.
933  */
934 static void
935 enter_maintenance()
936 {
937 	struct PROC_TABLE	*su_process;
938 
939 	console(B_FALSE, "Requesting maintenance mode\n"
940 	    "(See /lib/svc/share/README for additional information.)\n");
941 	(void) sigset(SIGCLD, SIG_DFL);
942 	while ((su_process = efork(M_OFF, NULLPROC, NOCLEANUP)) == NO_ROOM)
943 		(void) pause();
944 	(void) sigset(SIGCLD, childeath);
945 	if (su_process == NULLPROC) {
946 		int fd;
947 
948 		(void) fclose(stdin);
949 		(void) fclose(stdout);
950 		(void) fclose(stderr);
951 		closefrom(0);
952 
953 		fd = open(SYSCON, O_RDWR | O_NOCTTY);
954 		if (fd >= 0) {
955 			(void) dup2(fd, 1);
956 			(void) dup2(fd, 2);
957 		} else {
958 			/*
959 			 * Need to issue an error message somewhere.
960 			 */
961 			syslog(LOG_CRIT, "init[%d]: cannot open %s; %s\n",
962 			    getpid(), SYSCON, strerror(errno));
963 		}
964 
965 		/*
966 		 * Execute the "su" program.
967 		 */
968 		(void) execle(SU, SU, "-", (char *)0, glob_envp);
969 		console(B_TRUE, "execle of %s failed: %s\n", SU,
970 		    strerror(errno));
971 		timer(5);
972 		exit(1);
973 	}
974 
975 	/*
976 	 * If we are the parent, wait around for the child to die
977 	 * or for "init" to be signaled to change levels.
978 	 */
979 	while (waitproc(su_process) == FAILURE) {
980 		/*
981 		 * All other reasons for waking are ignored when in
982 		 * single-user mode.  The only child we are interested
983 		 * in is being waited for explicitly by waitproc().
984 		 */
985 		wakeup.w_mask = 0;
986 	}
987 }
988 
989 /*
990  * remv() scans through "proc_table" and performs cleanup.  If
991  * there is a process in the table, which shouldn't be here at
992  * the current run level, then remv() kills the process.
993  */
994 static void
995 remv()
996 {
997 	struct PROC_TABLE	*process;
998 	struct CMD_LINE		cmd;
999 	char			cmd_string[MAXCMDL];
1000 	int			change_level;
1001 
1002 	change_level = (cur_state != prev_state ? TRUE : FALSE);
1003 
1004 	/*
1005 	 * Clear the TOUCHED flag on all entries so that when we have
1006 	 * finished scanning inittab, we will be able to tell if we
1007 	 * have any processes for which there is no entry in inittab.
1008 	 */
1009 	for (process = proc_table;
1010 	    (process < proc_table + num_proc); process++) {
1011 		process->p_flags &= ~TOUCHED;
1012 	}
1013 
1014 	/*
1015 	 * Scan all inittab entries.
1016 	 */
1017 	while (getcmd(&cmd, &cmd_string[0]) == TRUE) {
1018 		/* Scan for process which goes with this entry in inittab. */
1019 		for (process = proc_table;
1020 		    (process < proc_table + num_proc); process++) {
1021 			if ((process->p_flags & OCCUPIED) == 0 ||
1022 			    !id_eq(process->p_id, cmd.c_id))
1023 				continue;
1024 
1025 			/*
1026 			 * This slot contains the process we are looking for.
1027 			 */
1028 
1029 			/*
1030 			 * Is the cur_state SINGLE_USER or is this process
1031 			 * marked as "off" or was this proc started by some
1032 			 * mechanism other than LVL{a|b|c} and the current level
1033 			 * does not support this process?
1034 			 */
1035 			if (cur_state == SINGLE_USER ||
1036 			    cmd.c_action == M_OFF ||
1037 			    ((cmd.c_levels & state_to_mask(cur_state)) == 0 &&
1038 			    (process->p_flags & DEMANDREQUEST) == 0)) {
1039 				if (process->p_flags & LIVING) {
1040 					/*
1041 					 * Touch this entry so we know we have
1042 					 * treated it.  Note that procs which
1043 					 * are already dead at this point and
1044 					 * should not be restarted are left
1045 					 * untouched.  This causes their slot to
1046 					 * be freed later after dead accounting
1047 					 * is done.
1048 					 */
1049 					process->p_flags |= TOUCHED;
1050 
1051 					if ((process->p_flags & KILLED) == 0) {
1052 						if (change_level) {
1053 							process->p_flags
1054 							    |= WARNED;
1055 							(void) kill(
1056 							    process->p_pid,
1057 							    SIGTERM);
1058 						} else {
1059 							/*
1060 							 * Fork a killing proc
1061 							 * so "init" can
1062 							 * continue without
1063 							 * having to pause for
1064 							 * TWARN seconds.
1065 							 */
1066 							killproc(
1067 							    process->p_pid);
1068 						}
1069 						process->p_flags |= KILLED;
1070 					}
1071 				}
1072 			} else {
1073 				/*
1074 				 * Process can exist at current level.  If it is
1075 				 * still alive or a DEMANDREQUEST we touch it so
1076 				 * it will be left alone.  Otherwise we leave it
1077 				 * untouched so it will be accounted for and
1078 				 * cleaned up later in remv().  Dead
1079 				 * DEMANDREQUESTs will be accounted but not
1080 				 * freed.
1081 				 */
1082 				if (process->p_flags &
1083 				    (LIVING|NOCLEANUP|DEMANDREQUEST))
1084 					process->p_flags |= TOUCHED;
1085 			}
1086 
1087 			break;
1088 		}
1089 	}
1090 
1091 	st_write();
1092 
1093 	/*
1094 	 * If this was a change of levels call, scan through the
1095 	 * process table for processes that were warned to die.  If any
1096 	 * are found that haven't left yet, sleep for TWARN seconds and
1097 	 * then send final terminations to any that haven't died yet.
1098 	 */
1099 	if (change_level) {
1100 
1101 		/*
1102 		 * Set the alarm for TWARN seconds on the assumption
1103 		 * that there will be some that need to be waited for.
1104 		 * This won't harm anything except we are guaranteed to
1105 		 * wakeup in TWARN seconds whether we need to or not.
1106 		 */
1107 		setimer(TWARN);
1108 
1109 		/*
1110 		 * Scan for processes which should be dying.  We hope they
1111 		 * will die without having to be sent a SIGKILL signal.
1112 		 */
1113 		for (process = proc_table;
1114 		    (process < proc_table + num_proc); process++) {
1115 			/*
1116 			 * If this process should die, hasn't yet, and the
1117 			 * TWARN time hasn't expired yet, wait for process
1118 			 * to die or for timer to expire.
1119 			 */
1120 			while (time_up == FALSE &&
1121 			    (process->p_flags & (WARNED|LIVING|OCCUPIED)) ==
1122 			    (WARNED|LIVING|OCCUPIED))
1123 				(void) pause();
1124 
1125 			if (time_up == TRUE)
1126 				break;
1127 		}
1128 
1129 		/*
1130 		 * If we reached the end of the table without the timer
1131 		 * expiring, then there are no procs which will have to be
1132 		 * sent the SIGKILL signal.  If the timer has expired, then
1133 		 * it is necessary to scan the table again and send signals
1134 		 * to all processes which aren't going away nicely.
1135 		 */
1136 		if (time_up == TRUE) {
1137 			for (process = proc_table;
1138 			    (process < proc_table + num_proc); process++) {
1139 				if ((process->p_flags &
1140 				    (WARNED|LIVING|OCCUPIED)) ==
1141 				    (WARNED|LIVING|OCCUPIED))
1142 					(void) kill(process->p_pid, SIGKILL);
1143 			}
1144 		}
1145 		setimer(0);
1146 	}
1147 
1148 	/*
1149 	 * Rescan the proc_table for two kinds of entry, those marked LIVING,
1150 	 * NAMED, which don't have an entry in inittab (haven't been TOUCHED
1151 	 * by the above scanning), and haven't been sent kill signals, and
1152 	 * those entries marked not LIVING, NAMED.  The former procs are killed.
1153 	 * The latter have DEAD_PROCESS accounting done and the slot cleared.
1154 	 */
1155 	for (process = proc_table;
1156 	    (process < proc_table + num_proc); process++) {
1157 		if ((process->p_flags & (LIVING|NAMED|TOUCHED|KILLED|OCCUPIED))
1158 		    == (LIVING|NAMED|OCCUPIED)) {
1159 			killproc(process->p_pid);
1160 			process->p_flags |= KILLED;
1161 		} else if ((process->p_flags & (LIVING|NAMED|OCCUPIED)) ==
1162 		    (NAMED|OCCUPIED)) {
1163 			(void) account(DEAD_PROCESS, process, NULL);
1164 			/*
1165 			 * If this named proc hasn't been TOUCHED, then free the
1166 			 * space. It has either died of it's own accord, but
1167 			 * isn't respawnable or it was killed because it
1168 			 * shouldn't exist at this level.
1169 			 */
1170 			if ((process->p_flags & TOUCHED) == 0)
1171 				process->p_flags = 0;
1172 		}
1173 	}
1174 
1175 	st_write();
1176 }
1177 
1178 /*
1179  * Extract the svc.startd command line and whether to restart it from its
1180  * inittab entry.
1181  */
1182 /*ARGSUSED*/
1183 static void
1184 process_startd_line(struct CMD_LINE *cmd, char *cmd_string)
1185 {
1186 	size_t sz;
1187 
1188 	/* Save the command line. */
1189 	if (sflg || rflg) {
1190 		/* Also append -r or -s. */
1191 		(void) strlcpy(startd_cline, cmd_string, sizeof (startd_cline));
1192 		(void) strlcat(startd_cline, " -", sizeof (startd_cline));
1193 		if (sflg)
1194 			sz = strlcat(startd_cline, "s", sizeof (startd_cline));
1195 		if (rflg)
1196 			sz = strlcat(startd_cline, "r", sizeof (startd_cline));
1197 	} else {
1198 		sz = strlcpy(startd_cline, cmd_string, sizeof (startd_cline));
1199 	}
1200 
1201 	if (sz >= sizeof (startd_cline)) {
1202 		console(B_TRUE,
1203 		    "svc.startd command line too long.  Ignoring.\n");
1204 		startd_cline[0] = '\0';
1205 		return;
1206 	}
1207 }
1208 
1209 /*
1210  * spawn_processes() scans inittab for entries which should be run at this
1211  * mode.  Processes which should be running but are not, are started.
1212  */
1213 static int
1214 spawn_processes()
1215 {
1216 	struct PROC_TABLE		*pp;
1217 	struct CMD_LINE			cmd;
1218 	char				cmd_string[MAXCMDL];
1219 	short				lvl_mask;
1220 	int				status;
1221 
1222 	/*
1223 	 * First check the "powerhit" flag.  If it is set, make sure the modes
1224 	 * are PF_MODES and clear the "powerhit" flag.  Avoid the possible race
1225 	 * on the "powerhit" flag by disallowing a new powerfail interrupt
1226 	 * between the test of the powerhit flag and the clearing of it.
1227 	 */
1228 	if (wakeup.w_flags.w_powerhit) {
1229 		wakeup.w_flags.w_powerhit = 0;
1230 		op_modes = PF_MODES;
1231 	}
1232 	lvl_mask = state_to_mask(cur_state);
1233 
1234 	/*
1235 	 * Scan through all the entries in inittab.
1236 	 */
1237 	while ((status = getcmd(&cmd, &cmd_string[0])) == TRUE) {
1238 		if (id_eq(cmd.c_id, "smf")) {
1239 			process_startd_line(&cmd, cmd_string);
1240 			continue;
1241 		}
1242 
1243 retry_for_proc_slot:
1244 
1245 		/*
1246 		 * Find out if there is a process slot for this entry already.
1247 		 */
1248 		if ((pp = findpslot(&cmd)) == NULLPROC) {
1249 			/*
1250 			 * we've run out of proc table entries
1251 			 * increase proc_table.
1252 			 */
1253 			increase_proc_table_size();
1254 
1255 			/*
1256 			 * Retry now as we have an empty proc slot.
1257 			 * In case increase_proc_table_size() fails,
1258 			 * we will keep retrying.
1259 			 */
1260 			goto retry_for_proc_slot;
1261 		}
1262 
1263 		/*
1264 		 * If there is an entry, and it is marked as DEMANDREQUEST,
1265 		 * one of the levels a, b, or c is in its levels mask, and
1266 		 * the action field is ONDEMAND and ONDEMAND is a permissable
1267 		 * mode, and the process is dead, then respawn it.
1268 		 */
1269 		if (((pp->p_flags & (LIVING|DEMANDREQUEST)) == DEMANDREQUEST) &&
1270 		    (cmd.c_levels & MASK_abc) &&
1271 		    (cmd.c_action & op_modes) == M_ONDEMAND) {
1272 			spawn(pp, &cmd);
1273 			continue;
1274 		}
1275 
1276 		/*
1277 		 * If the action is not an action we are interested in,
1278 		 * skip the entry.
1279 		 */
1280 		if ((cmd.c_action & op_modes) == 0 || pp->p_flags & LIVING ||
1281 		    (cmd.c_levels & lvl_mask) == 0)
1282 			continue;
1283 
1284 		/*
1285 		 * If the modes are the normal modes (ONCE, WAIT, RESPAWN, OFF,
1286 		 * ONDEMAND) and the action field is either OFF or the action
1287 		 * field is ONCE or WAIT and the current level is the same as
1288 		 * the last level, then skip this entry.  ONCE and WAIT only
1289 		 * get run when the level changes.
1290 		 */
1291 		if (op_modes == NORMAL_MODES &&
1292 		    (cmd.c_action == M_OFF ||
1293 		    (cmd.c_action & (M_ONCE|M_WAIT)) &&
1294 		    cur_state == prev_state))
1295 			continue;
1296 
1297 		/*
1298 		 * At this point we are interested in performing the action for
1299 		 * this entry.  Actions fall into two categories, spinning off
1300 		 * a process and not waiting, and spinning off a process and
1301 		 * waiting for it to die.  If the action is ONCE, RESPAWN,
1302 		 * ONDEMAND, POWERFAIL, or BOOT we don't wait for the process
1303 		 * to die, for all other actions we do wait.
1304 		 */
1305 		if (cmd.c_action & (M_ONCE | M_RESPAWN | M_PF | M_BOOT)) {
1306 			spawn(pp, &cmd);
1307 
1308 		} else {
1309 			spawn(pp, &cmd);
1310 			while (waitproc(pp) == FAILURE)
1311 				;
1312 			(void) account(DEAD_PROCESS, pp, NULL);
1313 			pp->p_flags = 0;
1314 		}
1315 	}
1316 	return (status);
1317 }
1318 
1319 /*
1320  * spawn() spawns a shell, inserts the information about the process
1321  * process into the proc_table, and does the startup accounting.
1322  */
1323 static void
1324 spawn(struct PROC_TABLE *process, struct CMD_LINE *cmd)
1325 {
1326 	int		i;
1327 	int		modes, maxfiles;
1328 	time_t		now;
1329 	struct PROC_TABLE tmproc, *oprocess;
1330 
1331 	/*
1332 	 * The modes to be sent to efork() are 0 unless we are
1333 	 * spawning a LVLa, LVLb, or LVLc entry or we will be
1334 	 * waiting for the death of the child before continuing.
1335 	 */
1336 	modes = NAMED;
1337 	if (process->p_flags & DEMANDREQUEST || cur_state == LVLa ||
1338 	    cur_state == LVLb || cur_state == LVLc)
1339 		modes |= DEMANDREQUEST;
1340 	if ((cmd->c_action & (M_SYSINIT | M_WAIT | M_BOOTWAIT | M_PWAIT)) != 0)
1341 		modes |= NOCLEANUP;
1342 
1343 	/*
1344 	 * If this is a respawnable process, check the threshold
1345 	 * information to avoid excessive respawns.
1346 	 */
1347 	if (cmd->c_action & M_RESPAWN) {
1348 		/*
1349 		 * Add NOCLEANUP to all respawnable commands so that the
1350 		 * information about the frequency of respawns isn't lost.
1351 		 */
1352 		modes |= NOCLEANUP;
1353 		(void) time(&now);
1354 
1355 		/*
1356 		 * If no time is assigned, then this is the first time
1357 		 * this command is being processed in this series.  Assign
1358 		 * the current time.
1359 		 */
1360 		if (process->p_time == 0L)
1361 			process->p_time = now;
1362 
1363 		if (process->p_count++ == SPAWN_LIMIT) {
1364 
1365 			if ((now - process->p_time) < SPAWN_INTERVAL) {
1366 				/*
1367 				 * Process is respawning too rapidly.  Print
1368 				 * message and refuse to respawn it for now.
1369 				 */
1370 				console(B_TRUE, "Command is respawning too "
1371 				    "rapidly. Check for possible errors.\n"
1372 				    "id:%4s \"%s\"\n",
1373 				    &cmd->c_id[0], &cmd->c_command[EXEC]);
1374 				return;
1375 			}
1376 			process->p_time = now;
1377 			process->p_count = 0;
1378 
1379 		} else if (process->p_count > SPAWN_LIMIT) {
1380 			/*
1381 			 * If process has been respawning too rapidly and
1382 			 * the inhibit time limit hasn't expired yet, we
1383 			 * refuse to respawn.
1384 			 */
1385 			if (now - process->p_time < SPAWN_INTERVAL + INHIBIT)
1386 				return;
1387 			process->p_time = now;
1388 			process->p_count = 0;
1389 		}
1390 		rsflag = TRUE;
1391 	}
1392 
1393 	/*
1394 	 * Spawn a child process to execute this command.
1395 	 */
1396 	(void) sigset(SIGCLD, SIG_DFL);
1397 	oprocess = process;
1398 	while ((process = efork(cmd->c_action, oprocess, modes)) == NO_ROOM)
1399 		(void) pause();
1400 
1401 	if (process == NULLPROC) {
1402 
1403 		/*
1404 		 * We are the child.  We must make sure we get a different
1405 		 * file pointer for our references to utmpx.  Otherwise our
1406 		 * seeks and reads will compete with those of the parent.
1407 		 */
1408 		endutxent();
1409 
1410 		/*
1411 		 * Perform the accounting for the beginning of a process.
1412 		 * Note that all processes are initially "INIT_PROCESS"es.
1413 		 */
1414 		tmproc.p_id[0] = cmd->c_id[0];
1415 		tmproc.p_id[1] = cmd->c_id[1];
1416 		tmproc.p_id[2] = cmd->c_id[2];
1417 		tmproc.p_id[3] = cmd->c_id[3];
1418 		tmproc.p_pid = getpid();
1419 		tmproc.p_exit = 0;
1420 		(void) account(INIT_PROCESS, &tmproc,
1421 		    prog_name(&cmd->c_command[EXEC]));
1422 		maxfiles = ulimit(UL_GDESLIM, 0);
1423 		for (i = 0; i < maxfiles; i++)
1424 			(void) fcntl(i, F_SETFD, FD_CLOEXEC);
1425 
1426 		/*
1427 		 * Now exec a shell with the -c option and the command
1428 		 * from inittab.
1429 		 */
1430 		(void) execle(SH, "INITSH", "-c", cmd->c_command, (char *)0,
1431 		    glob_envp);
1432 		console(B_TRUE, "Command\n\"%s\"\n failed to execute.  errno "
1433 		    "= %d (exec of shell failed)\n", cmd->c_command, errno);
1434 
1435 		/*
1436 		 * Don't come back so quickly that "init" doesn't have a
1437 		 * chance to finish putting this child in "proc_table".
1438 		 */
1439 		timer(20);
1440 		exit(1);
1441 
1442 	}
1443 
1444 	/*
1445 	 * We are the parent.  Insert the necessary
1446 	 * information in the proc_table.
1447 	 */
1448 	process->p_id[0] = cmd->c_id[0];
1449 	process->p_id[1] = cmd->c_id[1];
1450 	process->p_id[2] = cmd->c_id[2];
1451 	process->p_id[3] = cmd->c_id[3];
1452 
1453 	st_write();
1454 
1455 	(void) sigset(SIGCLD, childeath);
1456 }
1457 
1458 /*
1459  * findpslot() finds the old slot in the process table for the
1460  * command with the same id, or it finds an empty slot.
1461  */
1462 static struct PROC_TABLE *
1463 findpslot(struct CMD_LINE *cmd)
1464 {
1465 	struct PROC_TABLE	*process;
1466 	struct PROC_TABLE	*empty = NULLPROC;
1467 
1468 	for (process = proc_table;
1469 	    (process < proc_table + num_proc); process++) {
1470 		if (process->p_flags & OCCUPIED &&
1471 		    id_eq(process->p_id, cmd->c_id))
1472 			break;
1473 
1474 		/*
1475 		 * If the entry is totally empty and "empty" is still 0,
1476 		 * remember where this hole is and make sure the slot is
1477 		 * zeroed out.
1478 		 */
1479 		if (empty == NULLPROC && (process->p_flags & OCCUPIED) == 0) {
1480 			empty = process;
1481 			process->p_id[0] = '\0';
1482 			process->p_id[1] = '\0';
1483 			process->p_id[2] = '\0';
1484 			process->p_id[3] = '\0';
1485 			process->p_pid = 0;
1486 			process->p_time = 0L;
1487 			process->p_count = 0;
1488 			process->p_flags = 0;
1489 			process->p_exit = 0;
1490 		}
1491 	}
1492 
1493 	/*
1494 	 * If there is no entry for this slot, then there should be an
1495 	 * empty slot.  If there is no empty slot, then we've run out
1496 	 * of proc_table space.  If the latter is true, empty will be
1497 	 * NULL and the caller will have to complain.
1498 	 */
1499 	if (process == (proc_table + num_proc))
1500 		process = empty;
1501 
1502 	return (process);
1503 }
1504 
1505 /*
1506  * getcmd() parses lines from inittab.  Each time it finds a command line
1507  * it will return TRUE as well as fill the passed CMD_LINE structure and
1508  * the shell command string.  When the end of inittab is reached, FALSE
1509  * is returned inittab is automatically opened if it is not currently open
1510  * and is closed when the end of the file is reached.
1511  */
1512 static FILE *fp_inittab = NULL;
1513 
1514 static int
1515 getcmd(struct CMD_LINE *cmd, char *shcmd)
1516 {
1517 	char	*ptr;
1518 	int	c, lastc, state;
1519 	char 	*ptr1;
1520 	int	answer, i, proceed;
1521 	struct	stat	sbuf;
1522 	static char *actions[] = {
1523 		"off", "respawn", "ondemand", "once", "wait", "boot",
1524 		"bootwait", "powerfail", "powerwait", "initdefault",
1525 		"sysinit",
1526 	};
1527 	static short act_masks[] = {
1528 		M_OFF, M_RESPAWN, M_ONDEMAND, M_ONCE, M_WAIT, M_BOOT,
1529 		M_BOOTWAIT, M_PF, M_PWAIT, M_INITDEFAULT, M_SYSINIT,
1530 	};
1531 	/*
1532 	 * Only these actions will be allowed for entries which
1533 	 * are specified for single-user mode.
1534 	 */
1535 	short su_acts = M_INITDEFAULT | M_PF | M_PWAIT | M_WAIT;
1536 
1537 	if (fp_inittab == NULL) {
1538 		/*
1539 		 * Before attempting to open inittab we stat it to make
1540 		 * sure it currently exists and is not empty.  We try
1541 		 * several times because someone may have temporarily
1542 		 * unlinked or truncated the file.
1543 		 */
1544 		for (i = 0; i < 3; i++) {
1545 			if (stat(INITTAB, &sbuf) == -1) {
1546 				if (i == 2) {
1547 					console(B_TRUE,
1548 					    "Cannot stat %s, errno: %d\n",
1549 					    INITTAB, errno);
1550 					return (FAILURE);
1551 				} else {
1552 					timer(3);
1553 				}
1554 			} else if (sbuf.st_size < 10) {
1555 				if (i == 2) {
1556 					console(B_TRUE,
1557 					    "%s truncated or corrupted\n",
1558 					    INITTAB);
1559 					return (FAILURE);
1560 				} else {
1561 					timer(3);
1562 				}
1563 			} else {
1564 				break;
1565 			}
1566 		}
1567 
1568 		/*
1569 		 * If unable to open inittab, print error message and
1570 		 * return FAILURE to caller.
1571 		 */
1572 		if ((fp_inittab = fopen(INITTAB, "r")) == NULL) {
1573 			console(B_TRUE, "Cannot open %s errno: %d\n", INITTAB,
1574 			    errno);
1575 			return (FAILURE);
1576 		}
1577 	}
1578 
1579 	/*
1580 	 * Keep getting commands from inittab until you find a
1581 	 * good one or run out of file.
1582 	 */
1583 	for (answer = FALSE; answer == FALSE; ) {
1584 		/*
1585 		 * Zero out the cmd itself before trying next line.
1586 		 */
1587 		bzero(cmd, sizeof (struct CMD_LINE));
1588 
1589 		/*
1590 		 * Read in lines of inittab, parsing at colons, until a line is
1591 		 * read in which doesn't end with a backslash.  Do not start if
1592 		 * the first character read is an EOF.  Note that this means
1593 		 * that lines which don't end in a newline are still processed,
1594 		 * since the "for" will terminate normally once started,
1595 		 * regardless of whether line terminates with a newline or EOF.
1596 		 */
1597 		state = FAILURE;
1598 		if ((c = fgetc(fp_inittab)) == EOF) {
1599 			answer = FALSE;
1600 			(void) fclose(fp_inittab);
1601 			fp_inittab = NULL;
1602 			break;
1603 		}
1604 
1605 		for (proceed = TRUE, ptr = shcmd, state = ID, lastc = '\0';
1606 		    proceed && c != EOF;
1607 		    lastc = c, c = fgetc(fp_inittab)) {
1608 		    /* If we're not in the FAILURE state and haven't	*/
1609 		    /* yet reached the shell command field, process	*/
1610 		    /* the line, otherwise just look for a real end	*/
1611 		    /* of line.						*/
1612 		    if (state != FAILURE && state != COMMAND) {
1613 			/*
1614 			 * Squeeze out spaces and tabs.
1615 			 */
1616 			if (c == ' ' || c == '\t')
1617 				continue;
1618 
1619 			/*
1620 			 * Ignore characters in a comment, except for the \n.
1621 			 */
1622 			if (state == COMMENT) {
1623 				if (c == '\n') {
1624 					lastc = ' ';
1625 					break;
1626 				} else {
1627 					continue;
1628 				}
1629 			}
1630 
1631 			/*
1632 			 * Detect comments (lines whose first non-whitespace
1633 			 * character is '#') by checking that we're at the
1634 			 * beginning of a line, have seen a '#', and haven't
1635 			 * yet accumulated any characters.
1636 			 */
1637 			if (state == ID && c == '#' && ptr == shcmd) {
1638 				state = COMMENT;
1639 				continue;
1640 			}
1641 
1642 			/*
1643 			 * If the character is a ':', then check the
1644 			 * previous field for correctness and advance
1645 			 * to the next field.
1646 			 */
1647 			if (c == ':') {
1648 			    switch (state) {
1649 
1650 			    case ID :
1651 				/*
1652 				 * Check to see that there are only
1653 				 * 1 to 4 characters for the id.
1654 				 */
1655 				if ((i = ptr - shcmd) < 1 || i > 4) {
1656 					state = FAILURE;
1657 				} else {
1658 					bcopy(shcmd, &cmd->c_id[0], i);
1659 					ptr = shcmd;
1660 					state = LEVELS;
1661 				}
1662 				break;
1663 
1664 			    case LEVELS :
1665 				/*
1666 				 * Build a mask for all the levels for
1667 				 * which this command will be legal.
1668 				 */
1669 				for (cmd->c_levels = 0, ptr1 = shcmd;
1670 				    ptr1 < ptr; ptr1++) {
1671 					int mask;
1672 					if (lvlname_to_mask(*ptr1,
1673 					    &mask) == -1) {
1674 						state = FAILURE;
1675 						break;
1676 					}
1677 					cmd->c_levels |= mask;
1678 				}
1679 				if (state != FAILURE) {
1680 					state = ACTION;
1681 					ptr = shcmd;	/* Reset the buffer */
1682 				}
1683 				break;
1684 
1685 			    case ACTION :
1686 				/*
1687 				 * Null terminate the string in shcmd buffer and
1688 				 * then try to match against legal actions.  If
1689 				 * the field is of length 0, then the default of
1690 				 * "RESPAWN" is used if the id is numeric,
1691 				 * otherwise the default is "OFF".
1692 				 */
1693 				if (ptr == shcmd) {
1694 					if (isdigit(cmd->c_id[0]) &&
1695 					    (cmd->c_id[1] == '\0' ||
1696 						isdigit(cmd->c_id[1])) &&
1697 					    (cmd->c_id[2] == '\0' ||
1698 						isdigit(cmd->c_id[2])) &&
1699 					    (cmd->c_id[3] == '\0' ||
1700 						isdigit(cmd->c_id[3])))
1701 						    cmd->c_action = M_RESPAWN;
1702 					else
1703 						    cmd->c_action = M_OFF;
1704 				} else {
1705 				    for (cmd->c_action = 0, i = 0, *ptr = '\0';
1706 				    i < sizeof (actions)/sizeof (char *);
1707 				    i++) {
1708 					if (strcmp(shcmd, actions[i]) == 0) {
1709 					    if ((cmd->c_levels & MASKSU) &&
1710 						!(act_masks[i] & su_acts))
1711 						    cmd->c_action = 0;
1712 					    else
1713 						cmd->c_action = act_masks[i];
1714 					    break;
1715 					}
1716 				    }
1717 				}
1718 
1719 				/*
1720 				 * If the action didn't match any legal action,
1721 				 * set state to FAILURE.
1722 				 */
1723 				if (cmd->c_action == 0) {
1724 					state = FAILURE;
1725 				} else {
1726 					state = COMMAND;
1727 					(void) strcpy(shcmd, "exec ");
1728 				}
1729 				ptr = shcmd + EXEC;
1730 				break;
1731 			    }
1732 			    continue;
1733 			}
1734 		    }
1735 
1736 		    /* If the character is a '\n', then this is the end of a */
1737 		    /* line.  If the '\n' wasn't preceded by a backslash, */
1738 		    /* it is also the end of an inittab command.  If it was */
1739 		    /* preceded by a backslash then the next line is a */
1740 		    /* continuation.  Note that the continuation '\n' falls */
1741 		    /* through and is treated like other characters and is */
1742 		    /* stored in the shell command line. */
1743 		    if (c == '\n' && lastc != '\\') {
1744 				proceed = FALSE;
1745 				*ptr = '\0';
1746 				break;
1747 		    }
1748 
1749 		    /* For all other characters just stuff them into the */
1750 		    /* command as long as there aren't too many of them. */
1751 		    /* Make sure there is room for a terminating '\0' also. */
1752 		    if (ptr >= shcmd + MAXCMDL - 1)
1753 			state = FAILURE;
1754 		    else
1755 			*ptr++ = (char)c;
1756 
1757 		    /* If the character we just stored was a quoted	*/
1758 		    /* backslash, then change "c" to '\0', so that this	*/
1759 		    /* backslash will not cause a subsequent '\n' to appear */
1760 		    /* quoted.  In otherwords '\' '\' '\n' is the real end */
1761 		    /* of a command, while '\' '\n' is a continuation. */
1762 		    if (c == '\\' && lastc == '\\')
1763 			c = '\0';
1764 		}
1765 
1766 		/*
1767 		 * Make sure all the fields are properly specified
1768 		 * for a good command line.
1769 		 */
1770 		if (state == COMMAND) {
1771 			answer = TRUE;
1772 			cmd->c_command = shcmd;
1773 
1774 			/*
1775 			 * If no default level was supplied, insert
1776 			 * all numerical levels.
1777 			 */
1778 			if (cmd->c_levels == 0)
1779 				cmd->c_levels = MASK_NUMERIC;
1780 
1781 			/*
1782 			 * If no action has been supplied, declare this
1783 			 * entry to be OFF.
1784 			 */
1785 			if (cmd->c_action == 0)
1786 				cmd->c_action = M_OFF;
1787 
1788 			/*
1789 			 * If no shell command has been supplied, make sure
1790 			 * there is a null string in the command field.
1791 			 */
1792 			if (ptr == shcmd + EXEC)
1793 				*shcmd = '\0';
1794 		} else
1795 			answer = FALSE;
1796 
1797 		/*
1798 		 * If we have reached the end of inittab, then close it
1799 		 * and quit trying to find a good command line.
1800 		 */
1801 		if (c == EOF) {
1802 			(void) fclose(fp_inittab);
1803 			fp_inittab = NULL;
1804 			break;
1805 		}
1806 	}
1807 	return (answer);
1808 }
1809 
1810 /*
1811  * lvlname_to_state(): convert the character name of a state to its level
1812  * (its corresponding signal number).
1813  */
1814 static int
1815 lvlname_to_state(char name)
1816 {
1817 	int i;
1818 	for (i = 0; i < LVL_NELEMS; i++) {
1819 		if (lvls[i].lvl_name == name)
1820 			return (lvls[i].lvl_state);
1821 	}
1822 	return (-1);
1823 }
1824 
1825 /*
1826  * state_to_name(): convert the level to the character name.
1827  */
1828 static char
1829 state_to_name(int state)
1830 {
1831 	int i;
1832 	for (i = 0; i < LVL_NELEMS; i++) {
1833 		if (lvls[i].lvl_state == state)
1834 			return (lvls[i].lvl_name);
1835 	}
1836 	return (-1);
1837 }
1838 
1839 /*
1840  * state_to_mask(): return the mask corresponding to a signal number
1841  */
1842 static int
1843 state_to_mask(int state)
1844 {
1845 	int i;
1846 	for (i = 0; i < LVL_NELEMS; i++) {
1847 		if (lvls[i].lvl_state == state)
1848 			return (lvls[i].lvl_mask);
1849 	}
1850 	return (0);	/* return 0, since that represents an empty mask */
1851 }
1852 
1853 /*
1854  * lvlname_to_mask(): return the mask corresponding to a levels character name
1855  */
1856 static int
1857 lvlname_to_mask(char name, int *mask)
1858 {
1859 	int i;
1860 	for (i = 0; i < LVL_NELEMS; i++) {
1861 		if (lvls[i].lvl_name == name) {
1862 			*mask = lvls[i].lvl_mask;
1863 			return (0);
1864 		}
1865 	}
1866 	return (-1);
1867 }
1868 
1869 /*
1870  * state_to_flags(): return the flags corresponding to a runlevel.  These
1871  * indicate properties of that runlevel.
1872  */
1873 static int
1874 state_to_flags(int state)
1875 {
1876 	int i;
1877 	for (i = 0; i < LVL_NELEMS; i++) {
1878 		if (lvls[i].lvl_state == state)
1879 			return (lvls[i].lvl_flags);
1880 	}
1881 	return (0);
1882 }
1883 
1884 /*
1885  * killproc() creates a child which kills the process specified by pid.
1886  */
1887 void
1888 killproc(pid_t pid)
1889 {
1890 	struct PROC_TABLE	*process;
1891 
1892 	(void) sigset(SIGCLD, SIG_DFL);
1893 	while ((process = efork(M_OFF, NULLPROC, 0)) == NO_ROOM)
1894 		(void) pause();
1895 	(void) sigset(SIGCLD, childeath);
1896 
1897 	if (process == NULLPROC) {
1898 		/*
1899 		 * efork() sets all signal handlers to the default, so reset
1900 		 * the ALRM handler to make timer() work as expected.
1901 		 */
1902 		(void) sigset(SIGALRM, alarmclk);
1903 
1904 		/*
1905 		 * We are the child.  Try to terminate the process nicely
1906 		 * first using SIGTERM and if it refuses to die in TWARN
1907 		 * seconds kill it with SIGKILL.
1908 		 */
1909 		(void) kill(pid, SIGTERM);
1910 		(void) timer(TWARN);
1911 		(void) kill(pid, SIGKILL);
1912 		(void) exit(0);
1913 	}
1914 }
1915 
1916 /*
1917  * Set up the default environment for all procs to be forked from init.
1918  * Read the values from the /etc/default/init file, except for PATH.  If
1919  * there's not enough room in the environment array, the environment
1920  * lines that don't fit are silently discarded.
1921  */
1922 void
1923 init_env()
1924 {
1925 	char	line[MAXCMDL];
1926 	FILE	*fp;
1927 	int	inquotes, length, wslength;
1928 	char	*tokp, *cp1, *cp2;
1929 
1930 	glob_envp[0] = malloc((unsigned)(strlen(DEF_PATH)+2));
1931 	(void) strcpy(glob_envp[0], DEF_PATH);
1932 	glob_envn = 1;
1933 
1934 	if (rflg) {
1935 		glob_envp[1] =
1936 		    malloc((unsigned)(strlen("_DVFS_RECONFIG=YES")+2));
1937 		(void) strcpy(glob_envp[1], "_DVFS_RECONFIG=YES");
1938 		++glob_envn;
1939 	} else if (bflg == 1) {
1940 		glob_envp[1] =
1941 		    malloc((unsigned)(strlen("RB_NOBOOTRC=YES")+2));
1942 		(void) strcpy(glob_envp[1], "RB_NOBOOTRC=YES");
1943 		++glob_envn;
1944 	}
1945 
1946 	if ((fp = fopen(ENVFILE, "r")) == NULL) {
1947 		console(B_TRUE,
1948 		    "Cannot open %s. Environment not initialized.\n",
1949 		    ENVFILE);
1950 	} else {
1951 		while (fgets(line, MAXCMDL - 1, fp) != NULL &&
1952 		    glob_envn < MAXENVENT - 2) {
1953 			/*
1954 			 * Toss newline
1955 			 */
1956 			length = strlen(line);
1957 			if (line[length - 1] == '\n')
1958 				line[length - 1] = '\0';
1959 
1960 			/*
1961 			 * Ignore blank or comment lines.
1962 			 */
1963 			if (line[0] == '#' || line[0] == '\0' ||
1964 			    (wslength = strspn(line, " \t\n")) ==
1965 			    strlen(line) ||
1966 			    strchr(line, '#') == line + wslength)
1967 				continue;
1968 
1969 			/*
1970 			 * First make a pass through the line and change
1971 			 * any non-quoted semi-colons to blanks so they
1972 			 * will be treated as token separators below.
1973 			 */
1974 			inquotes = 0;
1975 			for (cp1 = line; *cp1 != '\0'; cp1++) {
1976 				if (*cp1 == '"') {
1977 					if (inquotes == 0)
1978 						inquotes = 1;
1979 					else
1980 						inquotes = 0;
1981 				} else if (*cp1 == ';') {
1982 					if (inquotes == 0)
1983 						*cp1 = ' ';
1984 				}
1985 			}
1986 
1987 			/*
1988 			 * Tokens within the line are separated by blanks
1989 			 *  and tabs.  For each token in the line which
1990 			 * contains a '=' we strip out any quotes and then
1991 			 * stick the token in the environment array.
1992 			 */
1993 			if ((tokp = strtok(line, " \t")) == NULL)
1994 				continue;
1995 			do {
1996 				if (strchr(tokp, '=') == NULL)
1997 					continue;
1998 				length = strlen(tokp);
1999 				while ((cp1 = strpbrk(tokp, "\"\'")) != NULL) {
2000 					for (cp2 = cp1;
2001 					    cp2 < &tokp[length]; cp2++)
2002 						*cp2 = *(cp2 + 1);
2003 					length--;
2004 				}
2005 
2006 				if (strncmp(tokp, "CMASK=",
2007 				    sizeof ("CMASK=") - 1) == 0) {
2008 					long t;
2009 
2010 					/* We know there's an = */
2011 					t = strtol(strchr(tokp, '=') + 1, NULL,
2012 					    8);
2013 
2014 					/* Sanity */
2015 					if (t <= 077 && t >= 0)
2016 						cmask = (int)t;
2017 					(void) umask(cmask);
2018 					continue;
2019 				}
2020 				glob_envp[glob_envn] =
2021 				    malloc((unsigned)(length + 1));
2022 				(void) strcpy(glob_envp[glob_envn], tokp);
2023 				if (++glob_envn >= MAXENVENT - 1)
2024 					break;
2025 			} while ((tokp = strtok(NULL, " \t")) != NULL);
2026 		}
2027 
2028 		/*
2029 		 * Append a null pointer to the environment array
2030 		 * to mark its end.
2031 		 */
2032 		glob_envp[glob_envn] = NULL;
2033 		(void) fclose(fp);
2034 	}
2035 }
2036 
2037 /*
2038  * boot_init(): Do initialization things that should be done at boot.
2039  */
2040 void
2041 boot_init()
2042 {
2043 	int i;
2044 	struct PROC_TABLE *process, *oprocess;
2045 	struct CMD_LINE	cmd;
2046 	char	line[MAXCMDL];
2047 	char	svc_aux[SVC_AUX_SIZE];
2048 	char	init_svc_fmri[SVC_FMRI_SIZE];
2049 	char *old_path;
2050 	int maxfiles;
2051 
2052 	/* Use INIT_PATH for sysinit cmds */
2053 	old_path = glob_envp[0];
2054 	glob_envp[0] = malloc((unsigned)(strlen(INIT_PATH)+2));
2055 	(void) strcpy(glob_envp[0], INIT_PATH);
2056 
2057 	/*
2058 	 * Scan inittab(4) and process the special svc.startd entry, initdefault
2059 	 * and sysinit entries.
2060 	 */
2061 	while (getcmd(&cmd, &line[0]) == TRUE) {
2062 		if (startd_tmpl >= 0 && id_eq(cmd.c_id, "smf")) {
2063 			process_startd_line(&cmd, line);
2064 			(void) snprintf(startd_svc_aux, SVC_AUX_SIZE,
2065 			    INITTAB_ENTRY_ID_STR_FORMAT, cmd.c_id);
2066 		} else if (cmd.c_action == M_INITDEFAULT) {
2067 			/*
2068 			 * initdefault is no longer meaningful, as the SMF
2069 			 * milestone controls what (legacy) run level we
2070 			 * boot to.
2071 			 */
2072 			console(B_TRUE,
2073 			    "Ignoring legacy \"initdefault\" entry.\n");
2074 		} else if (cmd.c_action == M_SYSINIT) {
2075 			/*
2076 			 * Execute the "sysinit" entry and wait for it to
2077 			 * complete.  No bookkeeping is performed on these
2078 			 * entries because we avoid writing to the file system
2079 			 * until after there has been an chance to check it.
2080 			 */
2081 			if (process = findpslot(&cmd)) {
2082 				(void) sigset(SIGCLD, SIG_DFL);
2083 				(void) snprintf(svc_aux, SVC_AUX_SIZE,
2084 				    INITTAB_ENTRY_ID_STR_FORMAT, cmd.c_id);
2085 				(void) snprintf(init_svc_fmri, SVC_FMRI_SIZE,
2086 				    SVC_INIT_PREFIX INITTAB_ENTRY_ID_STR_FORMAT,
2087 				    cmd.c_id);
2088 				if (legacy_tmpl >= 0) {
2089 					(void) ct_pr_tmpl_set_svc_fmri(
2090 					    legacy_tmpl, init_svc_fmri);
2091 					(void) ct_pr_tmpl_set_svc_aux(
2092 					    legacy_tmpl, svc_aux);
2093 				}
2094 
2095 				for (oprocess = process;
2096 				    (process = efork(M_OFF, oprocess,
2097 				    (NAMED|NOCLEANUP))) == NO_ROOM;
2098 				    /* CSTYLED */)
2099 					;
2100 				(void) sigset(SIGCLD, childeath);
2101 
2102 				if (process == NULLPROC) {
2103 					maxfiles = ulimit(UL_GDESLIM, 0);
2104 
2105 					for (i = 0; i < maxfiles; i++)
2106 						(void) fcntl(i, F_SETFD,
2107 						    FD_CLOEXEC);
2108 					(void) execle(SH, "INITSH", "-c",
2109 					    cmd.c_command,
2110 					    (char *)0, glob_envp);
2111 					console(B_TRUE,
2112 "Command\n\"%s\"\n failed to execute.  errno = %d (exec of shell failed)\n",
2113 					    cmd.c_command, errno);
2114 					exit(1);
2115 				} else while (waitproc(process) == FAILURE);
2116 				process->p_flags = 0;
2117 				st_write();
2118 			}
2119 		}
2120 	}
2121 
2122 	/* Restore the path. */
2123 	free(glob_envp[0]);
2124 	glob_envp[0] = old_path;
2125 
2126 	/*
2127 	 * This will enable st_write() to complain about init_state_file.
2128 	 */
2129 	booting = 0;
2130 
2131 	/*
2132 	 * If the /etc/ioctl.syscon didn't exist or had invalid contents write
2133 	 * out a correct version.
2134 	 */
2135 	if (write_ioctl)
2136 		write_ioctl_syscon();
2137 
2138 	/*
2139 	 * Start svc.startd(1M), which does most of the work.
2140 	 */
2141 	if (startd_cline[0] != '\0' && startd_tmpl >= 0) {
2142 		/* Start svc.startd. */
2143 		if (startd_run(startd_cline, startd_tmpl, 0) == -1)
2144 			cur_state = SINGLE_USER;
2145 	} else {
2146 		console(B_TRUE, "Absent svc.startd entry or bad "
2147 		    "contract template.  Not starting svc.startd.\n");
2148 		enter_maintenance();
2149 	}
2150 }
2151 
2152 /*
2153  * init_signals(): Initialize all signals to either be caught or ignored.
2154  */
2155 void
2156 init_signals(void)
2157 {
2158 	struct sigaction act;
2159 	int i;
2160 
2161 	/*
2162 	 * Start by ignoring all signals, then selectively re-enable some.
2163 	 * The SIG_IGN disposition will only affect asynchronous signals:
2164 	 * any signal that we trigger synchronously that doesn't end up
2165 	 * being handled by siglvl() will be forcibly delivered by the kernel.
2166 	 */
2167 	for (i = SIGHUP; i <= SIGRTMAX; i++)
2168 		(void) sigset(i, SIG_IGN);
2169 
2170 	/*
2171 	 * Handle all level-changing signals using siglvl() and set sa_mask so
2172 	 * that all level-changing signals are blocked while in siglvl().
2173 	 */
2174 	act.sa_handler = siglvl;
2175 	act.sa_flags = SA_SIGINFO;
2176 	(void) sigemptyset(&act.sa_mask);
2177 
2178 	(void) sigaddset(&act.sa_mask, LVLQ);
2179 	(void) sigaddset(&act.sa_mask, LVL0);
2180 	(void) sigaddset(&act.sa_mask, LVL1);
2181 	(void) sigaddset(&act.sa_mask, LVL2);
2182 	(void) sigaddset(&act.sa_mask, LVL3);
2183 	(void) sigaddset(&act.sa_mask, LVL4);
2184 	(void) sigaddset(&act.sa_mask, LVL5);
2185 	(void) sigaddset(&act.sa_mask, LVL6);
2186 	(void) sigaddset(&act.sa_mask, SINGLE_USER);
2187 	(void) sigaddset(&act.sa_mask, LVLa);
2188 	(void) sigaddset(&act.sa_mask, LVLb);
2189 	(void) sigaddset(&act.sa_mask, LVLc);
2190 
2191 	(void) sigaction(LVLQ, &act, NULL);
2192 	(void) sigaction(LVL0, &act, NULL);
2193 	(void) sigaction(LVL1, &act, NULL);
2194 	(void) sigaction(LVL2, &act, NULL);
2195 	(void) sigaction(LVL3, &act, NULL);
2196 	(void) sigaction(LVL4, &act, NULL);
2197 	(void) sigaction(LVL5, &act, NULL);
2198 	(void) sigaction(LVL6, &act, NULL);
2199 	(void) sigaction(SINGLE_USER, &act, NULL);
2200 	(void) sigaction(LVLa, &act, NULL);
2201 	(void) sigaction(LVLb, &act, NULL);
2202 	(void) sigaction(LVLc, &act, NULL);
2203 
2204 	(void) sigset(SIGALRM, alarmclk);
2205 	alarmclk();
2206 
2207 	(void) sigset(SIGCLD, childeath);
2208 	(void) sigset(SIGPWR, powerfail);
2209 }
2210 
2211 /*
2212  * Set up pipe for "godchildren". If the file exists and is a pipe just open
2213  * it. Else, if the file system is r/w create it.  Otherwise, defer its
2214  * creation and open until after /var/run has been mounted.  This function is
2215  * only called on startup and when explicitly requested via LVLQ.
2216  */
2217 void
2218 setup_pipe()
2219 {
2220 	struct stat stat_buf;
2221 	struct statvfs statvfs_buf;
2222 	struct sigaction act;
2223 
2224 	/*
2225 	 * Always close the previous pipe descriptor as the mounted filesystems
2226 	 * may have changed.
2227 	 */
2228 	if (Pfd >= 0)
2229 		(void) close(Pfd);
2230 
2231 	if ((stat(INITPIPE, &stat_buf) == 0) &&
2232 	    ((stat_buf.st_mode & (S_IFMT|S_IRUSR)) == (S_IFIFO|S_IRUSR)))
2233 		Pfd = open(INITPIPE, O_RDWR | O_NDELAY);
2234 	else
2235 		if ((statvfs(INITPIPE_DIR, &statvfs_buf) == 0) &&
2236 		    ((statvfs_buf.f_flag & ST_RDONLY) == 0)) {
2237 			(void) unlink(INITPIPE);
2238 			(void) mknod(INITPIPE, S_IFIFO | 0600, 0);
2239 			Pfd = open(INITPIPE, O_RDWR | O_NDELAY);
2240 		}
2241 
2242 	if (Pfd >= 0) {
2243 		(void) ioctl(Pfd, I_SETSIG, S_INPUT);
2244 		/*
2245 		 * Read pipe in message discard mode.
2246 		 */
2247 		(void) ioctl(Pfd, I_SRDOPT, RMSGD);
2248 
2249 		act.sa_handler = sigpoll;
2250 		act.sa_flags = 0;
2251 		(void) sigemptyset(&act.sa_mask);
2252 		(void) sigaddset(&act.sa_mask, SIGCLD);
2253 		(void) sigaction(SIGPOLL, &act, NULL);
2254 	}
2255 }
2256 
2257 /*
2258  * siglvl - handle an asynchronous signal from init(1M) telling us that we
2259  * should change the current run level.  We set new_state accordingly.
2260  */
2261 void
2262 siglvl(int sig, siginfo_t *sip, ucontext_t *ucp)
2263 {
2264 	struct PROC_TABLE *process;
2265 	struct sigaction act;
2266 
2267 	/*
2268 	 * If the signal was from the kernel (rather than init(1M)) then init
2269 	 * itself tripped the signal.  That is, we might have a bug and tripped
2270 	 * a real SIGSEGV instead of receiving it as an alias for SIGLVLa.  In
2271 	 * such a case we reset the disposition to SIG_DFL, block all signals
2272 	 * in uc_mask but the current one, and return to the interrupted ucp
2273 	 * to effect an appropriate death.  The kernel will then restart us.
2274 	 *
2275 	 * The one exception to SI_FROMKERNEL() is SIGFPE (a.k.a. LVL6), which
2276 	 * the kernel can send us when it wants to effect an orderly reboot.
2277 	 * For this case we must also verify si_code is zero, rather than a
2278 	 * code such as FPE_INTDIV which a bug might have triggered.
2279 	 */
2280 	if (sip != NULL && SI_FROMKERNEL(sip) &&
2281 	    (sig != SIGFPE || sip->si_code == 0)) {
2282 
2283 		(void) sigemptyset(&act.sa_mask);
2284 		act.sa_handler = SIG_DFL;
2285 		act.sa_flags = 0;
2286 		(void) sigaction(sig, &act, NULL);
2287 
2288 		(void) sigfillset(&ucp->uc_sigmask);
2289 		(void) sigdelset(&ucp->uc_sigmask, sig);
2290 		ucp->uc_flags |= UC_SIGMASK;
2291 
2292 		(void) setcontext(ucp);
2293 	}
2294 
2295 	/*
2296 	 * If the signal received is a LVLQ signal, do not really
2297 	 * change levels, just restate the current level.  If the
2298 	 * signal is not a LVLQ, set the new level to the signal
2299 	 * received.
2300 	 */
2301 	if (sig == LVLQ) {
2302 		new_state = cur_state;
2303 		lvlq_received = B_TRUE;
2304 	} else {
2305 		new_state = sig;
2306 	}
2307 
2308 	/*
2309 	 * Clear all times and repeat counts in the process table
2310 	 * since either the level is changing or the user has editted
2311 	 * the inittab file and wants us to look at it again.
2312 	 * If the user has fixed a typo, we don't want residual timing
2313 	 * data preventing the fixed command line from executing.
2314 	 */
2315 	for (process = proc_table;
2316 	    (process < proc_table + num_proc); process++) {
2317 		process->p_time = 0L;
2318 		process->p_count = 0;
2319 	}
2320 
2321 	/*
2322 	 * Set the flag to indicate that a "user signal" was received.
2323 	 */
2324 	wakeup.w_flags.w_usersignal = 1;
2325 }
2326 
2327 
2328 /*
2329  * alarmclk
2330  */
2331 static void
2332 alarmclk()
2333 {
2334 	time_up = TRUE;
2335 }
2336 
2337 /*
2338  * childeath_single():
2339  *
2340  * This used to be the SIGCLD handler and it was set with signal()
2341  * (as opposed to sigset()).  When a child exited we'd come to the
2342  * handler, wait for the child, and reenable the handler with
2343  * signal() just before returning.  The implementation of signal()
2344  * checks with waitid() for waitable children and sends a SIGCLD
2345  * if there are some.  If children are exiting faster than the
2346  * handler can run we keep sending signals and the handler never
2347  * gets to return and eventually the stack runs out and init dies.
2348  * To prevent that we set the handler with sigset() so the handler
2349  * doesn't need to be reset, and in childeath() (see below) we
2350  * call childeath_single() as long as there are children to be
2351  * waited for.  If a child exits while init is in the handler a
2352  * SIGCLD will be pending and delivered on return from the handler.
2353  * If the child was already waited for the handler will have nothing
2354  * to do and return, otherwise the child will be waited for.
2355  */
2356 static void
2357 childeath_single()
2358 {
2359 	struct PROC_TABLE	*process;
2360 	struct pidlist		*pp;
2361 	pid_t			pid;
2362 	int			status;
2363 
2364 	/*
2365 	 * Perform wait to get the process id of the child that died and
2366 	 * then scan the process table to see if we are interested in
2367 	 * this process. NOTE: if a super-user sends the SIGCLD signal
2368 	 * to init, the following wait will not immediately return and
2369 	 * init will be inoperative until one of its child really does die.
2370 	 */
2371 	pid = wait(&status);
2372 
2373 	for (process = proc_table;
2374 	    (process < proc_table + num_proc); process++) {
2375 		if ((process->p_flags & (LIVING|OCCUPIED)) ==
2376 		    (LIVING|OCCUPIED) && process->p_pid == pid) {
2377 
2378 			/*
2379 			 * Mark this process as having died and store the exit
2380 			 * status.  Also set the wakeup flag for a dead child
2381 			 * and break out of the loop.
2382 			 */
2383 			process->p_flags &= ~LIVING;
2384 			process->p_exit = (short)status;
2385 			wakeup.w_flags.w_childdeath = 1;
2386 
2387 			return;
2388 		}
2389 	}
2390 
2391 	/*
2392 	 * No process was found above, look through auxiliary list.
2393 	 */
2394 	(void) sighold(SIGPOLL);
2395 	pp = Plhead;
2396 	while (pp) {
2397 		if (pid > pp->pl_pid) {
2398 			/*
2399 			 * Keep on looking.
2400 			 */
2401 			pp = pp->pl_next;
2402 			continue;
2403 		} else if (pid < pp->pl_pid) {
2404 			/*
2405 			 * Not in the list.
2406 			 */
2407 			break;
2408 		} else {
2409 			/*
2410 			 * This is a dead "godchild".
2411 			 */
2412 			pp->pl_dflag = 1;
2413 			pp->pl_exit = (short)status;
2414 			wakeup.w_flags.w_childdeath = 1;
2415 			Gchild = 1;	/* Notice to call cleanaux(). */
2416 			break;
2417 		}
2418 	}
2419 
2420 	(void) sigrelse(SIGPOLL);
2421 }
2422 
2423 /* ARGSUSED */
2424 static void
2425 childeath(int signo)
2426 {
2427 	siginfo_t info;
2428 
2429 	while ((waitid(P_ALL, (id_t)0, &info, WEXITED|WNOHANG|WNOWAIT) == 0) &&
2430 	    info.si_pid != 0)
2431 		childeath_single();
2432 }
2433 
2434 static void
2435 powerfail()
2436 {
2437 	(void) nice(-19);
2438 	wakeup.w_flags.w_powerhit = 1;
2439 }
2440 
2441 /*
2442  * efork() forks a child and the parent inserts the process in its table
2443  * of processes that are directly a result of forks that it has performed.
2444  * The child just changes the "global" with the process id for this process
2445  * to it's new value.
2446  * If efork() is called with a pointer into the proc_table it uses that slot,
2447  * otherwise it searches for a free slot.  Regardless of how it was called,
2448  * it returns the pointer to the proc_table entry
2449  *
2450  * The SIGCLD handler is set to default (SIG_DFL) before calling efork().
2451  * This relies on the somewhat obscure SVR2 SIGCLD/SIG_DFL semantic
2452  * implied by the use of signal(3c).  While the meaning of SIG_DFL for
2453  * SIGCLD is nominally to ignore the signal, once the signal disposition
2454  * is set to childeath(), the kernel will post a SIGCLD if a child
2455  * exited during the period the disposition was SIG_DFL.  It acts more
2456  * like a signal block.
2457  *
2458  * Ideally, this should be rewritten to use modern signal semantics.
2459  */
2460 static struct PROC_TABLE *
2461 efork(int action, struct PROC_TABLE *process, int modes)
2462 {
2463 	pid_t	childpid;
2464 	struct PROC_TABLE *proc;
2465 	int		i;
2466 	void (*oldroutine)();
2467 	/*
2468 	 * Freshen up the proc_table, removing any entries for dead processes
2469 	 * that don't have NOCLEANUP set.  Perform the necessary accounting.
2470 	 */
2471 	for (proc = proc_table; (proc < proc_table + num_proc); proc++) {
2472 		if ((proc->p_flags & (OCCUPIED|LIVING|NOCLEANUP)) ==
2473 		    (OCCUPIED)) {
2474 			/*
2475 			 * Is this a named process?
2476 			 * If so, do the necessary bookkeeping.
2477 			 */
2478 			if (proc->p_flags & NAMED)
2479 				(void) account(DEAD_PROCESS, proc, NULL);
2480 
2481 			/*
2482 			 * Free this entry for new usage.
2483 			 */
2484 			proc->p_flags = 0;
2485 		}
2486 	}
2487 
2488 	while ((childpid = fork()) == FAILURE) {
2489 		/*
2490 		 * Shorten the alarm timer in case someone else's child dies
2491 		 * and free up a slot in the process table.
2492 		 */
2493 		setimer(5);
2494 
2495 		/*
2496 		 * Wait for some children to die.  Since efork() is normally
2497 		 * called with SIGCLD in the default state, reset it to catch
2498 		 * so that child death signals can come in.
2499 		 */
2500 		oldroutine = sigset(SIGCLD, childeath);
2501 		(void) pause();
2502 		(void) sigset(SIGCLD, oldroutine);
2503 		setimer(0);
2504 	}
2505 
2506 	if (childpid != 0) {
2507 
2508 		if (process == NULLPROC) {
2509 			/*
2510 			 * No proc table pointer specified so search
2511 			 * for a free slot.
2512 			 */
2513 			for (process = proc_table;  process->p_flags != 0 &&
2514 			    (process < proc_table + num_proc); process++)
2515 					;
2516 
2517 			if (process == (proc_table + num_proc)) {
2518 				int old_proc_table_size = num_proc;
2519 
2520 				/* Increase the process table size */
2521 				increase_proc_table_size();
2522 				if (old_proc_table_size == num_proc) {
2523 					/* didn't grow: memory failure */
2524 					return (NO_ROOM);
2525 				} else {
2526 					process =
2527 					    proc_table + old_proc_table_size;
2528 				}
2529 			}
2530 
2531 			process->p_time = 0L;
2532 			process->p_count = 0;
2533 		}
2534 		process->p_id[0] = '\0';
2535 		process->p_id[1] = '\0';
2536 		process->p_id[2] = '\0';
2537 		process->p_id[3] = '\0';
2538 		process->p_pid = childpid;
2539 		process->p_flags = (LIVING | OCCUPIED | modes);
2540 		process->p_exit = 0;
2541 
2542 		st_write();
2543 	} else {
2544 		if ((action & (M_WAIT | M_BOOTWAIT)) == 0)
2545 			(void) setpgrp();
2546 
2547 		process = NULLPROC;
2548 
2549 		/*
2550 		 * Reset all signals to the system defaults.
2551 		 */
2552 		for (i = SIGHUP; i <= SIGRTMAX; i++)
2553 			(void) sigset(i, SIG_DFL);
2554 
2555 		/*
2556 		 * POSIX B.2.2.2 advises that init should set SIGTTOU,
2557 		 * SIGTTIN, and SIGTSTP to SIG_IGN.
2558 		 *
2559 		 * Make sure that SIGXCPU and SIGXFSZ also remain ignored,
2560 		 * for backward compatibility.
2561 		 */
2562 		(void) sigset(SIGTTIN, SIG_IGN);
2563 		(void) sigset(SIGTTOU, SIG_IGN);
2564 		(void) sigset(SIGTSTP, SIG_IGN);
2565 		(void) sigset(SIGXCPU, SIG_IGN);
2566 		(void) sigset(SIGXFSZ, SIG_IGN);
2567 	}
2568 	return (process);
2569 }
2570 
2571 
2572 /*
2573  * waitproc() waits for a specified process to die.  For this function to
2574  * work, the specified process must already in the proc_table.  waitproc()
2575  * returns the exit status of the specified process when it dies.
2576  */
2577 static long
2578 waitproc(struct PROC_TABLE *process)
2579 {
2580 	int		answer;
2581 	sigset_t	oldmask, newmask, zeromask;
2582 
2583 	(void) sigemptyset(&zeromask);
2584 	(void) sigemptyset(&newmask);
2585 
2586 	(void) sigaddset(&newmask, SIGCLD);
2587 
2588 	/* Block SIGCLD and save the current signal mask */
2589 	if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
2590 		perror("SIG_BLOCK error");
2591 
2592 	/*
2593 	 * Wait around until the process dies.
2594 	 */
2595 	if (process->p_flags & LIVING)
2596 		(void) sigsuspend(&zeromask);
2597 
2598 	/* Reset signal mask to unblock SIGCLD */
2599 	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
2600 		perror("SIG_SETMASK error");
2601 
2602 	if (process->p_flags & LIVING)
2603 		return (FAILURE);
2604 
2605 	/*
2606 	 * Make sure to only return 16 bits so that answer will always
2607 	 * be positive whenever the process of interest really died.
2608 	 */
2609 	answer = (process->p_exit & 0xffff);
2610 
2611 	/*
2612 	 * Free the slot in the proc_table.
2613 	 */
2614 	process->p_flags = 0;
2615 	return (answer);
2616 }
2617 
2618 /*
2619  * notify_pam_dead(): calls into the PAM framework to close the given session.
2620  */
2621 static void
2622 notify_pam_dead(struct utmpx *up)
2623 {
2624 	pam_handle_t *pamh;
2625 	char user[sizeof (up->ut_user) + 1];
2626 	char ttyn[sizeof (up->ut_line) + 1];
2627 	char host[sizeof (up->ut_host) + 1];
2628 
2629 	/*
2630 	 * PAM does not take care of updating utmpx/wtmpx.
2631 	 */
2632 	(void) snprintf(user, sizeof (user), "%s", up->ut_user);
2633 	(void) snprintf(ttyn, sizeof (ttyn), "%s", up->ut_line);
2634 	(void) snprintf(host, sizeof (host), "%s", up->ut_host);
2635 
2636 	if (pam_start("init", user, NULL, &pamh) == PAM_SUCCESS)  {
2637 		(void) pam_set_item(pamh, PAM_TTY, ttyn);
2638 		(void) pam_set_item(pamh, PAM_RHOST, host);
2639 		(void) pam_close_session(pamh, 0);
2640 		(void) pam_end(pamh, PAM_SUCCESS);
2641 	}
2642 }
2643 
2644 /*
2645  * Check you can access utmpx (As / may be read-only and
2646  * /var may not be mounted yet).
2647  */
2648 static int
2649 access_utmpx(void)
2650 {
2651 	do {
2652 		utmpx_ok = (access(UTMPX, R_OK|W_OK) == 0);
2653 	} while (!utmpx_ok && errno == EINTR);
2654 
2655 	return (utmpx_ok);
2656 }
2657 
2658 /*
2659  * account() updates entries in utmpx and appends new entries to the end of
2660  * wtmpx (assuming they exist).  The program argument indicates the name of
2661  * program if INIT_PROCESS, otherwise should be NULL.
2662  *
2663  * account() only blocks for INIT_PROCESS requests.
2664  *
2665  * Returns non-zero if write failed.
2666  */
2667 static int
2668 account(short state, struct PROC_TABLE *process, char *program)
2669 {
2670 	struct utmpx utmpbuf, *u, *oldu;
2671 	int tmplen;
2672 	char fail_buf[UT_LINE_SZ];
2673 	sigset_t block, unblock;
2674 
2675 	if (!utmpx_ok && !access_utmpx()) {
2676 		return (-1);
2677 	}
2678 
2679 	/*
2680 	 * Set up the prototype for the utmp structure we want to write.
2681 	 */
2682 	u = &utmpbuf;
2683 	(void) memset(u, 0, sizeof (struct utmpx));
2684 
2685 	/*
2686 	 * Fill in the various fields of the utmp structure.
2687 	 */
2688 	u->ut_id[0] = process->p_id[0];
2689 	u->ut_id[1] = process->p_id[1];
2690 	u->ut_id[2] = process->p_id[2];
2691 	u->ut_id[3] = process->p_id[3];
2692 	u->ut_pid = process->p_pid;
2693 
2694 	/*
2695 	 * Fill the "ut_exit" structure.
2696 	 */
2697 	u->ut_exit.e_termination = WTERMSIG(process->p_exit);
2698 	u->ut_exit.e_exit = WEXITSTATUS(process->p_exit);
2699 	u->ut_type = state;
2700 
2701 	(void) time(&u->ut_tv.tv_sec);
2702 
2703 	/*
2704 	 * Block signals for utmp update.
2705 	 */
2706 	(void) sigfillset(&block);
2707 	(void) sigprocmask(SIG_BLOCK, &block, &unblock);
2708 
2709 	/*
2710 	 * See if there already is such an entry in the "utmpx" file.
2711 	 */
2712 	setutxent();	/* Start at beginning of utmpx file. */
2713 
2714 	if ((oldu = getutxid(u)) != NULL) {
2715 		/*
2716 		 * Copy in the old "user", "line" and "host" fields
2717 		 * to our new structure.
2718 		 */
2719 		bcopy(oldu->ut_user, u->ut_user, sizeof (u->ut_user));
2720 		bcopy(oldu->ut_line, u->ut_line, sizeof (u->ut_line));
2721 		bcopy(oldu->ut_host, u->ut_host, sizeof (u->ut_host));
2722 		u->ut_syslen = (tmplen = strlen(u->ut_host)) ?
2723 		    min(tmplen + 1, sizeof (u->ut_host)) : 0;
2724 
2725 		if (oldu->ut_type == USER_PROCESS && state == DEAD_PROCESS) {
2726 			notify_pam_dead(oldu);
2727 		}
2728 	}
2729 
2730 	/*
2731 	 * Perform special accounting. Insert the special string into the
2732 	 * ut_line array. For INIT_PROCESSes put in the name of the
2733 	 * program in the "ut_user" field.
2734 	 */
2735 	switch (state) {
2736 	case INIT_PROCESS:
2737 		(void) strncpy(u->ut_user, program, sizeof (u->ut_user));
2738 		(void) strcpy(fail_buf, "INIT_PROCESS");
2739 		break;
2740 
2741 	default:
2742 		(void) strlcpy(fail_buf, u->ut_id, sizeof (u->ut_id) + 1);
2743 		break;
2744 	}
2745 
2746 	/*
2747 	 * Write out the updated entry to utmpx file.
2748 	 */
2749 	if (pututxline(u) == NULL) {
2750 		console(B_TRUE, "Failed write of utmpx entry: \"%s\": %s\n",
2751 		    fail_buf, strerror(errno));
2752 		endutxent();
2753 		(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2754 		return (-1);
2755 	}
2756 
2757 	/*
2758 	 * If we're able to write to utmpx, then attempt to add to the
2759 	 * end of the wtmpx file.
2760 	 */
2761 	updwtmpx(WTMPX, u);
2762 
2763 	endutxent();
2764 
2765 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2766 
2767 	return (0);
2768 }
2769 
2770 static void
2771 clearent(pid_t pid, short status)
2772 {
2773 	struct utmpx *up;
2774 	sigset_t block, unblock;
2775 
2776 	/*
2777 	 * Block signals for utmp update.
2778 	 */
2779 	(void) sigfillset(&block);
2780 	(void) sigprocmask(SIG_BLOCK, &block, &unblock);
2781 
2782 	/*
2783 	 * No error checking for now.
2784 	 */
2785 
2786 	setutxent();
2787 	while (up = getutxent()) {
2788 		if (up->ut_pid == pid) {
2789 			if (up->ut_type == DEAD_PROCESS) {
2790 				/*
2791 				 * Cleaned up elsewhere.
2792 				 */
2793 				continue;
2794 			}
2795 
2796 			notify_pam_dead(up);
2797 
2798 			up->ut_type = DEAD_PROCESS;
2799 			up->ut_exit.e_termination = WTERMSIG(status);
2800 			up->ut_exit.e_exit = WEXITSTATUS(status);
2801 			(void) time(&up->ut_tv.tv_sec);
2802 
2803 			(void) pututxline(up);
2804 			/*
2805 			 * Now attempt to add to the end of the
2806 			 * wtmp and wtmpx files.  Do not create
2807 			 * if they don't already exist.
2808 			 */
2809 			updwtmpx(WTMPX, up);
2810 
2811 			break;
2812 		}
2813 	}
2814 
2815 	endutxent();
2816 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2817 }
2818 
2819 /*
2820  * prog_name() searches for the word or unix path name and
2821  * returns a pointer to the last element of the pathname.
2822  */
2823 static char *
2824 prog_name(char *string)
2825 {
2826 	char	*ptr, *ptr2;
2827 	/* XXX - utmp - fix name length */
2828 	static char word[_POSIX_LOGIN_NAME_MAX];
2829 
2830 	/*
2831 	 * Search for the first word skipping leading spaces and tabs.
2832 	 */
2833 	while (*string == ' ' || *string == '\t')
2834 		string++;
2835 
2836 	/*
2837 	 * If the first non-space non-tab character is not one allowed in
2838 	 * a word, return a pointer to a null string, otherwise parse the
2839 	 * pathname.
2840 	 */
2841 	if (*string != '.' && *string != '/' && *string != '_' &&
2842 	    (*string < 'a' || *string > 'z') &&
2843 	    (*string < 'A' || * string > 'Z') &&
2844 	    (*string < '0' || *string > '9'))
2845 		return ("");
2846 
2847 	/*
2848 	 * Parse the pathname looking forward for '/', ' ', '\t', '\n' or
2849 	 * '\0'.  Each time a '/' is found, move "ptr" to one past the
2850 	 * '/', thus when a ' ', '\t', '\n', or '\0' is found, "ptr" will
2851 	 * point to the last element of the pathname.
2852 	 */
2853 	for (ptr = string; *string != ' ' && *string != '\t' &&
2854 	    *string != '\n' && *string != '\0'; string++) {
2855 		if (*string == '/')
2856 			ptr = string+1;
2857 	}
2858 
2859 	/*
2860 	 * Copy out up to the size of the "ut_user" array into "word",
2861 	 * null terminate it and return a pointer to it.
2862 	 */
2863 	/* XXX - utmp - fix name length */
2864 	for (ptr2 = &word[0]; ptr2 < &word[_POSIX_LOGIN_NAME_MAX - 1] &&
2865 	    ptr < string; /* CSTYLED */)
2866 		*ptr2++ = *ptr++;
2867 
2868 	*ptr2 = '\0';
2869 	return (&word[0]);
2870 }
2871 
2872 
2873 /*
2874  * realcon() returns a nonzero value if there is a character device
2875  * associated with SYSCON that has the same device number as CONSOLE.
2876  */
2877 static int
2878 realcon()
2879 {
2880 	struct stat sconbuf, conbuf;
2881 
2882 	if (stat(SYSCON, &sconbuf) != -1 &&
2883 	    stat(CONSOLE, &conbuf) != -1 &&
2884 	    S_ISCHR(sconbuf.st_mode) &&
2885 	    S_ISCHR(conbuf.st_mode) &&
2886 	    sconbuf.st_rdev == conbuf.st_rdev) {
2887 		return (1);
2888 	} else {
2889 		return (0);
2890 	}
2891 }
2892 
2893 
2894 /*
2895  * get_ioctl_syscon() retrieves the SYSCON settings from the IOCTLSYSCON file.
2896  * Returns true if the IOCTLSYSCON file needs to be written (with
2897  * write_ioctl_syscon() below)
2898  */
2899 static int
2900 get_ioctl_syscon()
2901 {
2902 	FILE	*fp;
2903 	unsigned int	iflags, oflags, cflags, lflags, ldisc, cc[18];
2904 	int		i, valid_format = 0;
2905 
2906 	/*
2907 	 * Read in the previous modes for SYSCON from IOCTLSYSCON.
2908 	 */
2909 	if ((fp = fopen(IOCTLSYSCON, "r")) == NULL) {
2910 		stored_syscon_termios = dflt_termios;
2911 		console(B_TRUE,
2912 		    "warning:%s does not exist, default settings assumed\n",
2913 		    IOCTLSYSCON);
2914 	} else {
2915 
2916 	    i = fscanf(fp,
2917 	    "%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x",
2918 		&iflags, &oflags, &cflags, &lflags,
2919 		&cc[0], &cc[1], &cc[2], &cc[3], &cc[4], &cc[5], &cc[6],
2920 		&cc[7], &cc[8], &cc[9], &cc[10], &cc[11], &cc[12], &cc[13],
2921 		&cc[14], &cc[15], &cc[16], &cc[17]);
2922 
2923 	    if (i == 22) {
2924 		stored_syscon_termios.c_iflag = iflags;
2925 		stored_syscon_termios.c_oflag = oflags;
2926 		stored_syscon_termios.c_cflag = cflags;
2927 		stored_syscon_termios.c_lflag = lflags;
2928 		for (i = 0; i < 18; i++)
2929 			stored_syscon_termios.c_cc[i] = (char)cc[i];
2930 		valid_format = 1;
2931 	    } else if (i == 13) {
2932 		rewind(fp);
2933 		i = fscanf(fp, "%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x",
2934 		    &iflags, &oflags, &cflags, &lflags, &ldisc, &cc[0], &cc[1],
2935 		    &cc[2], &cc[3], &cc[4], &cc[5], &cc[6], &cc[7]);
2936 
2937 		/*
2938 		 * If the file is formatted properly, use the values to
2939 		 * initialize the console terminal condition.
2940 		 */
2941 		stored_syscon_termios.c_iflag = (ushort_t)iflags;
2942 		stored_syscon_termios.c_oflag = (ushort_t)oflags;
2943 		stored_syscon_termios.c_cflag = (ushort_t)cflags;
2944 		stored_syscon_termios.c_lflag = (ushort_t)lflags;
2945 		for (i = 0; i < 8; i++)
2946 			stored_syscon_termios.c_cc[i] = (char)cc[i];
2947 		valid_format = 1;
2948 	    }
2949 	    (void) fclose(fp);
2950 
2951 	    /* If the file is badly formatted, use the default settings. */
2952 	    if (!valid_format)
2953 		stored_syscon_termios = dflt_termios;
2954 	}
2955 
2956 	/* If the file had a bad format, rewrite it later. */
2957 	return (!valid_format);
2958 }
2959 
2960 
2961 static void
2962 write_ioctl_syscon()
2963 {
2964 	FILE *fp;
2965 	int i;
2966 
2967 	(void) unlink(SYSCON);
2968 	(void) link(SYSTTY, SYSCON);
2969 	(void) umask(022);
2970 	fp = fopen(IOCTLSYSCON, "w");
2971 
2972 	(void) fprintf(fp, "%x:%x:%x:%x:0", stored_syscon_termios.c_iflag,
2973 	    stored_syscon_termios.c_oflag, stored_syscon_termios.c_cflag,
2974 	    stored_syscon_termios.c_lflag);
2975 	for (i = 0; i < 8; ++i)
2976 		(void) fprintf(fp, ":%x", stored_syscon_termios.c_cc[i]);
2977 	(void) putc('\n', fp);
2978 
2979 	(void) fflush(fp);
2980 	(void) fsync(fileno(fp));
2981 	(void) fclose(fp);
2982 	(void) umask(cmask);
2983 }
2984 
2985 
2986 /*
2987  * void console(boolean_t, char *, ...)
2988  *   Outputs the requested message to the system console.  Note that the number
2989  *   of arguments passed to console() should be determined by the print format.
2990  *
2991  *   The "prefix" parameter indicates whether or not "INIT: " should precede the
2992  *   message.
2993  *
2994  *   To make sure we write to the console in a sane fashion, we use the modes
2995  *   we keep in stored_syscon_termios (which we read out of /etc/ioctl.syscon).
2996  *   Afterwards we restore whatever modes were already there.
2997  */
2998 /* PRINTFLIKE2 */
2999 static void
3000 console(boolean_t prefix, char *format, ...)
3001 {
3002 	char	outbuf[BUFSIZ];
3003 	va_list	args;
3004 	int fd, getret;
3005 	struct termios old_syscon_termios;
3006 	FILE *f;
3007 
3008 	/*
3009 	 * We open SYSCON anew each time in case it has changed (see
3010 	 * userinit()).
3011 	 */
3012 	if ((fd = open(SYSCON, O_RDWR | O_NOCTTY)) < 0 ||
3013 	    (f = fdopen(fd, "r+")) == NULL) {
3014 		if (prefix)
3015 			syslog(LOG_WARNING, "INIT: ");
3016 		va_start(args, format);
3017 		vsyslog(LOG_WARNING, format, args);
3018 		va_end(args);
3019 		if (fd >= 0)
3020 			(void) close(fd);
3021 		return;
3022 	}
3023 	setbuf(f, &outbuf[0]);
3024 
3025 	getret = tcgetattr(fd, &old_syscon_termios);
3026 	old_syscon_termios.c_cflag &= ~HUPCL;
3027 	if (realcon())
3028 		/* Don't overwrite cflag of real console. */
3029 		stored_syscon_termios.c_cflag = old_syscon_termios.c_cflag;
3030 
3031 	stored_syscon_termios.c_cflag &= ~HUPCL;
3032 
3033 	(void) tcsetattr(fd, TCSANOW, &stored_syscon_termios);
3034 
3035 	if (prefix)
3036 		(void) fprintf(f, "\nINIT: ");
3037 	va_start(args, format);
3038 	(void) vfprintf(f, format, args);
3039 	va_end(args);
3040 
3041 	if (getret == 0)
3042 		(void) tcsetattr(fd, TCSADRAIN, &old_syscon_termios);
3043 
3044 	(void) fclose(f);
3045 }
3046 
3047 /*
3048  * timer() is a substitute for sleep() which uses alarm() and pause().
3049  */
3050 static void
3051 timer(int waitime)
3052 {
3053 	setimer(waitime);
3054 	while (time_up == FALSE)
3055 		(void) pause();
3056 }
3057 
3058 static void
3059 setimer(int timelimit)
3060 {
3061 	alarmclk();
3062 	(void) alarm(timelimit);
3063 	time_up = (timelimit ? FALSE : TRUE);
3064 }
3065 
3066 /*
3067  * Fails with
3068  *   ENOMEM - out of memory
3069  *   ECONNABORTED - repository connection broken
3070  *   EPERM - permission denied
3071  *   EACCES - backend access denied
3072  *   EROFS - backend readonly
3073  */
3074 static int
3075 get_or_add_startd(scf_instance_t *inst)
3076 {
3077 	scf_handle_t *h;
3078 	scf_scope_t *scope = NULL;
3079 	scf_service_t *svc = NULL;
3080 	int ret = 0;
3081 
3082 	h = scf_instance_handle(inst);
3083 
3084 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL, inst,
3085 	    NULL, NULL, SCF_DECODE_FMRI_EXACT) == 0)
3086 		return (0);
3087 
3088 	switch (scf_error()) {
3089 	case SCF_ERROR_CONNECTION_BROKEN:
3090 		return (ECONNABORTED);
3091 
3092 	case SCF_ERROR_NOT_FOUND:
3093 		break;
3094 
3095 	case SCF_ERROR_HANDLE_MISMATCH:
3096 	case SCF_ERROR_INVALID_ARGUMENT:
3097 	case SCF_ERROR_CONSTRAINT_VIOLATED:
3098 	default:
3099 		bad_error("scf_handle_decode_fmri", scf_error());
3100 	}
3101 
3102 	/* Make sure we're right, since we're adding piece-by-piece. */
3103 	assert(strcmp(SCF_SERVICE_STARTD,
3104 	    "svc:/system/svc/restarter:default") == 0);
3105 
3106 	if ((scope = scf_scope_create(h)) == NULL ||
3107 	    (svc = scf_service_create(h)) == NULL) {
3108 		ret = ENOMEM;
3109 		goto out;
3110 	}
3111 
3112 get_scope:
3113 	if (scf_handle_get_scope(h, SCF_SCOPE_LOCAL, scope) != 0) {
3114 		switch (scf_error()) {
3115 		case SCF_ERROR_CONNECTION_BROKEN:
3116 			ret = ECONNABORTED;
3117 			goto out;
3118 
3119 		case SCF_ERROR_NOT_FOUND:
3120 			(void) fputs(gettext(
3121 			    "smf(5) repository missing local scope.\n"),
3122 			    stderr);
3123 			exit(1);
3124 			/* NOTREACHED */
3125 
3126 		case SCF_ERROR_HANDLE_MISMATCH:
3127 		case SCF_ERROR_INVALID_ARGUMENT:
3128 		default:
3129 			bad_error("scf_handle_get_scope", scf_error());
3130 		}
3131 	}
3132 
3133 get_svc:
3134 	if (scf_scope_get_service(scope, "system/svc/restarter", svc) != 0) {
3135 		switch (scf_error()) {
3136 		case SCF_ERROR_CONNECTION_BROKEN:
3137 			ret = ECONNABORTED;
3138 			goto out;
3139 
3140 		case SCF_ERROR_DELETED:
3141 			goto get_scope;
3142 
3143 		case SCF_ERROR_NOT_FOUND:
3144 			break;
3145 
3146 		case SCF_ERROR_HANDLE_MISMATCH:
3147 		case SCF_ERROR_INVALID_ARGUMENT:
3148 		case SCF_ERROR_NOT_SET:
3149 		default:
3150 			bad_error("scf_scope_get_service", scf_error());
3151 		}
3152 
3153 add_svc:
3154 		if (scf_scope_add_service(scope, "system/svc/restarter", svc) !=
3155 		    0) {
3156 			switch (scf_error()) {
3157 			case SCF_ERROR_CONNECTION_BROKEN:
3158 				ret = ECONNABORTED;
3159 				goto out;
3160 
3161 			case SCF_ERROR_EXISTS:
3162 				goto get_svc;
3163 
3164 			case SCF_ERROR_PERMISSION_DENIED:
3165 				ret = EPERM;
3166 				goto out;
3167 
3168 			case SCF_ERROR_BACKEND_ACCESS:
3169 				ret = EACCES;
3170 				goto out;
3171 
3172 			case SCF_ERROR_BACKEND_READONLY:
3173 				ret = EROFS;
3174 				goto out;
3175 
3176 			case SCF_ERROR_HANDLE_MISMATCH:
3177 			case SCF_ERROR_INVALID_ARGUMENT:
3178 			case SCF_ERROR_NOT_SET:
3179 			default:
3180 				bad_error("scf_scope_add_service", scf_error());
3181 			}
3182 		}
3183 	}
3184 
3185 get_inst:
3186 	if (scf_service_get_instance(svc, "default", inst) != 0) {
3187 		switch (scf_error()) {
3188 		case SCF_ERROR_CONNECTION_BROKEN:
3189 			ret = ECONNABORTED;
3190 			goto out;
3191 
3192 		case SCF_ERROR_DELETED:
3193 			goto add_svc;
3194 
3195 		case SCF_ERROR_NOT_FOUND:
3196 			break;
3197 
3198 		case SCF_ERROR_HANDLE_MISMATCH:
3199 		case SCF_ERROR_INVALID_ARGUMENT:
3200 		case SCF_ERROR_NOT_SET:
3201 		default:
3202 			bad_error("scf_service_get_instance", scf_error());
3203 		}
3204 
3205 		if (scf_service_add_instance(svc, "default", inst) !=
3206 		    0) {
3207 			switch (scf_error()) {
3208 			case SCF_ERROR_CONNECTION_BROKEN:
3209 				ret = ECONNABORTED;
3210 				goto out;
3211 
3212 			case SCF_ERROR_DELETED:
3213 				goto add_svc;
3214 
3215 			case SCF_ERROR_EXISTS:
3216 				goto get_inst;
3217 
3218 			case SCF_ERROR_PERMISSION_DENIED:
3219 				ret = EPERM;
3220 				goto out;
3221 
3222 			case SCF_ERROR_BACKEND_ACCESS:
3223 				ret = EACCES;
3224 				goto out;
3225 
3226 			case SCF_ERROR_BACKEND_READONLY:
3227 				ret = EROFS;
3228 				goto out;
3229 
3230 			case SCF_ERROR_HANDLE_MISMATCH:
3231 			case SCF_ERROR_INVALID_ARGUMENT:
3232 			case SCF_ERROR_NOT_SET:
3233 			default:
3234 				bad_error("scf_service_add_instance",
3235 				    scf_error());
3236 			}
3237 		}
3238 	}
3239 
3240 	ret = 0;
3241 
3242 out:
3243 	scf_service_destroy(svc);
3244 	scf_scope_destroy(scope);
3245 	return (ret);
3246 }
3247 
3248 /*
3249  * Fails with
3250  *   ECONNABORTED - repository connection broken
3251  *   ECANCELED - the transaction's property group was deleted
3252  */
3253 static int
3254 transaction_add_set(scf_transaction_t *tx, scf_transaction_entry_t *ent,
3255     const char *pname, scf_type_t type)
3256 {
3257 change_type:
3258 	if (scf_transaction_property_change_type(tx, ent, pname, type) == 0)
3259 		return (0);
3260 
3261 	switch (scf_error()) {
3262 	case SCF_ERROR_CONNECTION_BROKEN:
3263 		return (ECONNABORTED);
3264 
3265 	case SCF_ERROR_DELETED:
3266 		return (ECANCELED);
3267 
3268 	case SCF_ERROR_NOT_FOUND:
3269 		goto new;
3270 
3271 	case SCF_ERROR_HANDLE_MISMATCH:
3272 	case SCF_ERROR_INVALID_ARGUMENT:
3273 	case SCF_ERROR_NOT_BOUND:
3274 	case SCF_ERROR_NOT_SET:
3275 	default:
3276 		bad_error("scf_transaction_property_change_type", scf_error());
3277 	}
3278 
3279 new:
3280 	if (scf_transaction_property_new(tx, ent, pname, type) == 0)
3281 		return (0);
3282 
3283 	switch (scf_error()) {
3284 	case SCF_ERROR_CONNECTION_BROKEN:
3285 		return (ECONNABORTED);
3286 
3287 	case SCF_ERROR_DELETED:
3288 		return (ECANCELED);
3289 
3290 	case SCF_ERROR_EXISTS:
3291 		goto change_type;
3292 
3293 	case SCF_ERROR_HANDLE_MISMATCH:
3294 	case SCF_ERROR_INVALID_ARGUMENT:
3295 	case SCF_ERROR_NOT_BOUND:
3296 	case SCF_ERROR_NOT_SET:
3297 	default:
3298 		bad_error("scf_transaction_property_new", scf_error());
3299 		/* NOTREACHED */
3300 	}
3301 }
3302 
3303 static void
3304 scferr(void)
3305 {
3306 	switch (scf_error()) {
3307 	case SCF_ERROR_NO_MEMORY:
3308 		console(B_TRUE, gettext("Out of memory.\n"));
3309 		break;
3310 
3311 	case SCF_ERROR_CONNECTION_BROKEN:
3312 		console(B_TRUE, gettext(
3313 		    "Connection to smf(5) repository server broken.\n"));
3314 		break;
3315 
3316 	case SCF_ERROR_NO_RESOURCES:
3317 		console(B_TRUE, gettext(
3318 		    "smf(5) repository server is out of memory.\n"));
3319 		break;
3320 
3321 	case SCF_ERROR_PERMISSION_DENIED:
3322 		console(B_TRUE, gettext("Insufficient privileges.\n"));
3323 		break;
3324 
3325 	default:
3326 		console(B_TRUE, gettext("libscf error: %s\n"),
3327 		    scf_strerror(scf_error()));
3328 	}
3329 }
3330 
3331 static void
3332 lscf_set_runlevel(char rl)
3333 {
3334 	scf_handle_t *h;
3335 	scf_instance_t *inst = NULL;
3336 	scf_propertygroup_t *pg = NULL;
3337 	scf_transaction_t *tx = NULL;
3338 	scf_transaction_entry_t *ent = NULL;
3339 	scf_value_t *val = NULL;
3340 	char buf[2];
3341 	int r;
3342 
3343 	h = scf_handle_create(SCF_VERSION);
3344 	if (h == NULL) {
3345 		scferr();
3346 		return;
3347 	}
3348 
3349 	if (scf_handle_bind(h) != 0) {
3350 		switch (scf_error()) {
3351 		case SCF_ERROR_NO_SERVER:
3352 			console(B_TRUE,
3353 			    gettext("smf(5) repository server not running.\n"));
3354 			goto bail;
3355 
3356 		default:
3357 			scferr();
3358 			goto bail;
3359 		}
3360 	}
3361 
3362 	if ((inst = scf_instance_create(h)) == NULL ||
3363 	    (pg = scf_pg_create(h)) == NULL ||
3364 	    (val = scf_value_create(h)) == NULL ||
3365 	    (tx = scf_transaction_create(h)) == NULL ||
3366 	    (ent = scf_entry_create(h)) == NULL) {
3367 		scferr();
3368 		goto bail;
3369 	}
3370 
3371 get_inst:
3372 	r = get_or_add_startd(inst);
3373 	switch (r) {
3374 	case 0:
3375 		break;
3376 
3377 	case ENOMEM:
3378 	case ECONNABORTED:
3379 	case EPERM:
3380 	case EACCES:
3381 	case EROFS:
3382 		scferr();
3383 		goto bail;
3384 	default:
3385 		bad_error("get_or_add_startd", r);
3386 	}
3387 
3388 get_pg:
3389 	if (scf_instance_get_pg(inst, SCF_PG_OPTIONS_OVR, pg) != 0) {
3390 		switch (scf_error()) {
3391 		case SCF_ERROR_CONNECTION_BROKEN:
3392 			scferr();
3393 			goto bail;
3394 
3395 		case SCF_ERROR_DELETED:
3396 			goto get_inst;
3397 
3398 		case SCF_ERROR_NOT_FOUND:
3399 			break;
3400 
3401 		case SCF_ERROR_HANDLE_MISMATCH:
3402 		case SCF_ERROR_INVALID_ARGUMENT:
3403 		case SCF_ERROR_NOT_SET:
3404 		default:
3405 			bad_error("scf_instance_get_pg", scf_error());
3406 		}
3407 
3408 add_pg:
3409 		if (scf_instance_add_pg(inst, SCF_PG_OPTIONS_OVR,
3410 		    SCF_PG_OPTIONS_OVR_TYPE, SCF_PG_OPTIONS_OVR_FLAGS, pg) !=
3411 		    0) {
3412 			switch (scf_error()) {
3413 			case SCF_ERROR_CONNECTION_BROKEN:
3414 			case SCF_ERROR_PERMISSION_DENIED:
3415 			case SCF_ERROR_BACKEND_ACCESS:
3416 				scferr();
3417 				goto bail;
3418 
3419 			case SCF_ERROR_DELETED:
3420 				goto get_inst;
3421 
3422 			case SCF_ERROR_EXISTS:
3423 				goto get_pg;
3424 
3425 			case SCF_ERROR_HANDLE_MISMATCH:
3426 			case SCF_ERROR_INVALID_ARGUMENT:
3427 			case SCF_ERROR_NOT_SET:
3428 			default:
3429 				bad_error("scf_instance_add_pg", scf_error());
3430 			}
3431 		}
3432 	}
3433 
3434 	buf[0] = rl;
3435 	buf[1] = '\0';
3436 	r = scf_value_set_astring(val, buf);
3437 	assert(r == 0);
3438 
3439 	for (;;) {
3440 		if (scf_transaction_start(tx, pg) != 0) {
3441 			switch (scf_error()) {
3442 			case SCF_ERROR_CONNECTION_BROKEN:
3443 			case SCF_ERROR_PERMISSION_DENIED:
3444 			case SCF_ERROR_BACKEND_ACCESS:
3445 				scferr();
3446 				goto bail;
3447 
3448 			case SCF_ERROR_DELETED:
3449 				goto add_pg;
3450 
3451 			case SCF_ERROR_HANDLE_MISMATCH:
3452 			case SCF_ERROR_NOT_BOUND:
3453 			case SCF_ERROR_IN_USE:
3454 			case SCF_ERROR_NOT_SET:
3455 			default:
3456 				bad_error("scf_transaction_start", scf_error());
3457 			}
3458 		}
3459 
3460 		r = transaction_add_set(tx, ent, "runlevel", SCF_TYPE_ASTRING);
3461 		switch (r) {
3462 		case 0:
3463 			break;
3464 
3465 		case ECONNABORTED:
3466 			scferr();
3467 			goto bail;
3468 
3469 		case ECANCELED:
3470 			scf_transaction_reset(tx);
3471 			goto add_pg;
3472 
3473 		default:
3474 			bad_error("transaction_add_set", r);
3475 		}
3476 
3477 		r = scf_entry_add_value(ent, val);
3478 		assert(r == 0);
3479 
3480 		r = scf_transaction_commit(tx);
3481 		if (r == 1)
3482 			break;
3483 
3484 		if (r != 0) {
3485 			switch (scf_error()) {
3486 			case SCF_ERROR_CONNECTION_BROKEN:
3487 			case SCF_ERROR_PERMISSION_DENIED:
3488 			case SCF_ERROR_BACKEND_ACCESS:
3489 			case SCF_ERROR_BACKEND_READONLY:
3490 				scferr();
3491 				goto bail;
3492 
3493 			case SCF_ERROR_DELETED:
3494 				scf_transaction_reset(tx);
3495 				goto add_pg;
3496 
3497 			case SCF_ERROR_INVALID_ARGUMENT:
3498 			case SCF_ERROR_NOT_BOUND:
3499 			case SCF_ERROR_NOT_SET:
3500 			default:
3501 				bad_error("scf_transaction_commit",
3502 				    scf_error());
3503 			}
3504 		}
3505 
3506 		scf_transaction_reset(tx);
3507 		(void) scf_pg_update(pg);
3508 	}
3509 
3510 bail:
3511 	scf_transaction_destroy(tx);
3512 	scf_entry_destroy(ent);
3513 	scf_value_destroy(val);
3514 	scf_pg_destroy(pg);
3515 	scf_instance_destroy(inst);
3516 
3517 	(void) scf_handle_unbind(h);
3518 	scf_handle_destroy(h);
3519 }
3520 
3521 /*
3522  * Function to handle requests from users to main init running as process 1.
3523  */
3524 static void
3525 userinit(int argc, char **argv)
3526 {
3527 	FILE	*fp;
3528 	char	*ln;
3529 	int	init_signal;
3530 	struct stat	sconbuf, conbuf;
3531 	const char *usage_msg = "Usage: init [0123456SsQqabc]\n";
3532 
3533 	/*
3534 	 * We are a user invoked init.  Is there an argument and is it
3535 	 * a single character?  If not, print usage message and quit.
3536 	 */
3537 	if (argc != 2 || argv[1][1] != '\0') {
3538 		(void) fprintf(stderr, usage_msg);
3539 		exit(0);
3540 	}
3541 
3542 	if ((init_signal = lvlname_to_state((char)argv[1][0])) == -1) {
3543 		(void) fprintf(stderr, usage_msg);
3544 		(void) audit_put_record(ADT_FAILURE, ADT_FAIL_VALUE_BAD_CMD,
3545 		    argv[1]);
3546 		exit(1);
3547 	}
3548 
3549 	if (init_signal == SINGLE_USER) {
3550 		/*
3551 		 * Make sure this process is talking to a legal tty line
3552 		 * and that /dev/syscon is linked to this line.
3553 		 */
3554 		ln = ttyname(0);	/* Get the name of tty */
3555 		if (ln == NULL) {
3556 			(void) fprintf(stderr,
3557 			    "Standard input not a tty line\n");
3558 			(void) audit_put_record(ADT_FAILURE,
3559 			    ADT_FAIL_VALUE_BAD_TTY, argv[1]);
3560 			exit(1);
3561 		}
3562 
3563 		if ((stat(ln, &sconbuf) != -1) &&
3564 		    (stat(SYSCON, &conbuf) == -1 ||
3565 		    sconbuf.st_rdev != conbuf.st_rdev)) {
3566 			/*
3567 			 * /dev/syscon needs to change.
3568 			 * Unlink /dev/syscon and relink it to the current line.
3569 			 */
3570 			if (lstat(SYSCON, &conbuf) != -1 &&
3571 			    unlink(SYSCON) == FAILURE) {
3572 				perror("Can't unlink /dev/syscon");
3573 				(void) fprintf(stderr,
3574 				    "Run command on the system console.\n");
3575 				(void) audit_put_record(ADT_FAILURE,
3576 				    ADT_FAIL_VALUE_PROGRAM, argv[1]);
3577 				exit(1);
3578 			}
3579 			if (symlink(ln, SYSCON) == FAILURE) {
3580 				(void) fprintf(stderr,
3581 				    "Can't symlink /dev/syscon to %s: %s", ln,
3582 				    strerror(errno));
3583 
3584 				/* Try to leave a syscon */
3585 				(void) link(SYSTTY, SYSCON);
3586 				(void) audit_put_record(ADT_FAILURE,
3587 				    ADT_FAIL_VALUE_PROGRAM, argv[1]);
3588 				exit(1);
3589 			}
3590 
3591 			/*
3592 			 * Try to leave a message on system console saying where
3593 			 * /dev/syscon is currently connected.
3594 			 */
3595 			if ((fp = fopen(SYSTTY, "r+")) != NULL) {
3596 				(void) fprintf(fp,
3597 				    "\n****	SYSCON CHANGED TO %s	****\n",
3598 				    ln);
3599 				(void) fclose(fp);
3600 			}
3601 		}
3602 	}
3603 
3604 	update_boot_archive(init_signal);
3605 
3606 	(void) audit_put_record(ADT_SUCCESS, ADT_SUCCESS, argv[1]);
3607 
3608 	/*
3609 	 * Signal init; init will take care of telling svc.startd.
3610 	 */
3611 	if (kill(init_pid, init_signal) == FAILURE) {
3612 		(void) fprintf(stderr, "Must be super-user\n");
3613 		(void) audit_put_record(ADT_FAILURE,
3614 		    ADT_FAIL_VALUE_AUTH, argv[1]);
3615 		exit(1);
3616 	}
3617 
3618 	exit(0);
3619 }
3620 
3621 
3622 #define	DELTA	25	/* Number of pidlist elements to allocate at a time */
3623 
3624 /* ARGSUSED */
3625 void
3626 sigpoll(int n)
3627 {
3628 	struct pidrec prec;
3629 	struct pidrec *p = &prec;
3630 	struct pidlist *plp;
3631 	struct pidlist *tp, *savetp;
3632 	int i;
3633 
3634 	if (Pfd < 0) {
3635 		return;
3636 	}
3637 
3638 	for (;;) {
3639 		/*
3640 		 * Important Note: Either read will really fail (in which case
3641 		 * return is all we can do) or will get EAGAIN (Pfd was opened
3642 		 * O_NDELAY), in which case we also want to return.
3643 		 * Always return from here!
3644 		 */
3645 		if (read(Pfd, p, sizeof (struct pidrec)) !=
3646 						sizeof (struct pidrec)) {
3647 			return;
3648 		}
3649 		switch (p->pd_type) {
3650 
3651 		case ADDPID:
3652 			/*
3653 			 * New "godchild", add to list.
3654 			 */
3655 			if (Plfree == NULL) {
3656 				plp = (struct pidlist *)calloc(DELTA,
3657 				    sizeof (struct pidlist));
3658 				if (plp == NULL) {
3659 					/* Can't save pid */
3660 					break;
3661 				}
3662 				/*
3663 				 * Point at 2nd record allocated, we'll use plp.
3664 				 */
3665 				tp = plp + 1;
3666 				/*
3667 				 * Link them into a chain.
3668 				 */
3669 				Plfree = tp;
3670 				for (i = 0; i < DELTA - 2; i++) {
3671 					tp->pl_next = tp + 1;
3672 					tp++;
3673 				}
3674 			} else {
3675 				plp = Plfree;
3676 				Plfree = plp->pl_next;
3677 			}
3678 			plp->pl_pid = p->pd_pid;
3679 			plp->pl_dflag = 0;
3680 			plp->pl_next = NULL;
3681 			/*
3682 			 * Note - pid list is kept in increasing order of pids.
3683 			 */
3684 			if (Plhead == NULL) {
3685 				Plhead = plp;
3686 				/* Back up to read next record */
3687 				break;
3688 			} else {
3689 				savetp = tp = Plhead;
3690 				while (tp) {
3691 					if (plp->pl_pid > tp->pl_pid) {
3692 						savetp = tp;
3693 						tp = tp->pl_next;
3694 						continue;
3695 					} else if (plp->pl_pid < tp->pl_pid) {
3696 						if (tp == Plhead) {
3697 							plp->pl_next = Plhead;
3698 							Plhead = plp;
3699 						} else {
3700 							plp->pl_next =
3701 							    savetp->pl_next;
3702 							savetp->pl_next = plp;
3703 						}
3704 						break;
3705 					} else {
3706 						/* Already in list! */
3707 						plp->pl_next = Plfree;
3708 						Plfree = plp;
3709 						break;
3710 					}
3711 				}
3712 				if (tp == NULL) {
3713 					/* Add to end of list */
3714 					savetp->pl_next = plp;
3715 				}
3716 			}
3717 			/* Back up to read next record. */
3718 			break;
3719 
3720 		case REMPID:
3721 			/*
3722 			 * This one was handled by someone else,
3723 			 * purge it from the list.
3724 			 */
3725 			if (Plhead == NULL) {
3726 				/* Back up to read next record. */
3727 				break;
3728 			}
3729 			savetp = tp = Plhead;
3730 			while (tp) {
3731 				if (p->pd_pid > tp->pl_pid) {
3732 					/* Keep on looking. */
3733 					savetp = tp;
3734 					tp = tp->pl_next;
3735 					continue;
3736 				} else if (p->pd_pid < tp->pl_pid) {
3737 					/* Not in list. */
3738 					break;
3739 				} else {
3740 					/* Found it. */
3741 					if (tp == Plhead)
3742 						Plhead = tp->pl_next;
3743 					else
3744 						savetp->pl_next = tp->pl_next;
3745 					tp->pl_next = Plfree;
3746 					Plfree = tp;
3747 					break;
3748 				}
3749 			}
3750 			/* Back up to read next record. */
3751 			break;
3752 		default:
3753 			console(B_TRUE, "Bad message on initpipe\n");
3754 			break;
3755 		}
3756 	}
3757 }
3758 
3759 
3760 static void
3761 cleanaux()
3762 {
3763 	struct pidlist *savep, *p;
3764 	pid_t	pid;
3765 	short	status;
3766 
3767 	(void) sigset(SIGCLD, SIG_DFL);
3768 	Gchild = 0;	/* Note - Safe to do this here since no SIGCLDs */
3769 	(void) sighold(SIGPOLL);
3770 	savep = p = Plhead;
3771 	while (p) {
3772 		if (p->pl_dflag) {
3773 			/*
3774 			 * Found an entry to delete,
3775 			 * remove it from list first.
3776 			 */
3777 			pid = p->pl_pid;
3778 			status = p->pl_exit;
3779 			if (p == Plhead) {
3780 				Plhead = p->pl_next;
3781 				p->pl_next = Plfree;
3782 				Plfree = p;
3783 				savep = p = Plhead;
3784 			} else {
3785 				savep->pl_next = p->pl_next;
3786 				p->pl_next = Plfree;
3787 				Plfree = p;
3788 				p = savep->pl_next;
3789 			}
3790 			clearent(pid, status);
3791 			continue;
3792 		}
3793 		savep = p;
3794 		p = p->pl_next;
3795 	}
3796 	(void) sigrelse(SIGPOLL);
3797 	(void) sigset(SIGCLD, childeath);
3798 }
3799 
3800 
3801 /*
3802  * /etc/inittab has more entries and we have run out of room in the proc_table
3803  * array. Double the size of proc_table to accomodate the extra entries.
3804  */
3805 static void
3806 increase_proc_table_size()
3807 {
3808 	sigset_t block, unblock;
3809 	void *ptr;
3810 	size_t delta = num_proc * sizeof (struct PROC_TABLE);
3811 
3812 
3813 	/*
3814 	 * Block signals for realloc.
3815 	 */
3816 	(void) sigfillset(&block);
3817 	(void) sigprocmask(SIG_BLOCK, &block, &unblock);
3818 
3819 
3820 	/*
3821 	 * On failure we just return because callers of this function check
3822 	 * for failure.
3823 	 */
3824 	do
3825 		ptr = realloc(g_state, g_state_sz + delta);
3826 	while (ptr == NULL && errno == EAGAIN);
3827 
3828 	if (ptr != NULL) {
3829 		/* ensure that the new part is initialized to zero */
3830 		bzero((caddr_t)ptr + g_state_sz, delta);
3831 
3832 		g_state = ptr;
3833 		g_state_sz += delta;
3834 		num_proc <<= 1;
3835 	}
3836 
3837 
3838 	/* unblock our signals before returning */
3839 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
3840 }
3841 
3842 
3843 
3844 /*
3845  * Sanity check g_state.
3846  */
3847 static int
3848 st_sane()
3849 {
3850 	int i;
3851 	struct PROC_TABLE *ptp;
3852 
3853 
3854 	/* Note: cur_state is encoded as a signal number */
3855 	if (cur_state < 1 || cur_state == 9 || cur_state > 13)
3856 		return (0);
3857 
3858 	/* Check num_proc */
3859 	if (g_state_sz != sizeof (struct init_state) + (num_proc - 1) *
3860 	    sizeof (struct PROC_TABLE))
3861 		return (0);
3862 
3863 	/* Check proc_table */
3864 	for (i = 0, ptp = proc_table; i < num_proc; ++i, ++ptp) {
3865 		/* skip unoccupied entries */
3866 		if (!(ptp->p_flags & OCCUPIED))
3867 			continue;
3868 
3869 		/* p_flags has no bits outside of PF_MASK */
3870 		if (ptp->p_flags & ~(PF_MASK))
3871 			return (0);
3872 
3873 		/* 5 <= pid <= MAXPID */
3874 		if (ptp->p_pid < 5 || ptp->p_pid > MAXPID)
3875 			return (0);
3876 
3877 		/* p_count >= 0 */
3878 		if (ptp->p_count < 0)
3879 			return (0);
3880 
3881 		/* p_time >= 0 */
3882 		if (ptp->p_time < 0)
3883 			return (0);
3884 	}
3885 
3886 	return (1);
3887 }
3888 
3889 /*
3890  * Initialize our state.
3891  *
3892  * If the system just booted, then init_state_file, which is located on an
3893  * everpresent tmpfs filesystem, should not exist.
3894  *
3895  * If we were restarted, then init_state_file should exist, in
3896  * which case we'll read it in, sanity check it, and use it.
3897  *
3898  * Note: You can't call console() until proc_table is ready.
3899  */
3900 void
3901 st_init()
3902 {
3903 	struct stat stb;
3904 	int ret, st_fd, insane = 0;
3905 	size_t to_be_read;
3906 	char *ptr;
3907 
3908 
3909 	booting = 1;
3910 
3911 	do {
3912 		/*
3913 		 * If we can exclusively create the file, then we're the
3914 		 * initial invocation of init(1M).
3915 		 */
3916 		st_fd = open(init_state_file, O_RDWR | O_CREAT | O_EXCL,
3917 		    S_IRUSR | S_IWUSR);
3918 	} while (st_fd == -1 && errno == EINTR);
3919 	if (st_fd != -1)
3920 		goto new_state;
3921 
3922 	booting = 0;
3923 
3924 	do {
3925 		st_fd = open(init_state_file, O_RDWR, S_IRUSR | S_IWUSR);
3926 	} while (st_fd == -1 && errno == EINTR);
3927 	if (st_fd == -1)
3928 		goto new_state;
3929 
3930 	/* Get the size of the file. */
3931 	do
3932 		ret = fstat(st_fd, &stb);
3933 	while (ret == -1 && errno == EINTR);
3934 	if (ret == -1)
3935 		goto new_state;
3936 
3937 	do
3938 		g_state = malloc(stb.st_size);
3939 	while (g_state == NULL && errno == EAGAIN);
3940 	if (g_state == NULL)
3941 		goto new_state;
3942 
3943 	to_be_read = stb.st_size;
3944 	ptr = (char *)g_state;
3945 	while (to_be_read > 0) {
3946 		ssize_t read_ret;
3947 
3948 		read_ret = read(st_fd, ptr, to_be_read);
3949 		if (read_ret < 0) {
3950 			if (errno == EINTR)
3951 				continue;
3952 
3953 			goto new_state;
3954 		}
3955 
3956 		to_be_read -= read_ret;
3957 		ptr += read_ret;
3958 	}
3959 
3960 	(void) close(st_fd);
3961 
3962 	g_state_sz = stb.st_size;
3963 
3964 	if (st_sane()) {
3965 		console(B_TRUE, "Restarting.\n");
3966 		return;
3967 	}
3968 
3969 	insane = 1;
3970 
3971 new_state:
3972 	if (st_fd >= 0)
3973 		(void) close(st_fd);
3974 	else
3975 		(void) unlink(init_state_file);
3976 
3977 	if (g_state != NULL)
3978 		free(g_state);
3979 
3980 	/* Something went wrong, so allocate new state. */
3981 	g_state_sz = sizeof (struct init_state) +
3982 	    ((init_num_proc - 1) * sizeof (struct PROC_TABLE));
3983 	do
3984 		g_state = calloc(1, g_state_sz);
3985 	while (g_state == NULL && errno == EAGAIN);
3986 	if (g_state == NULL) {
3987 		/* Fatal error! */
3988 		exit(errno);
3989 	}
3990 
3991 	g_state->ist_runlevel = -1;
3992 	num_proc = init_num_proc;
3993 
3994 	if (!booting) {
3995 		console(B_TRUE, "Restarting.\n");
3996 
3997 		/* Overwrite the bad state file. */
3998 		st_write();
3999 
4000 		if (!insane) {
4001 			console(B_TRUE,
4002 			    "Error accessing persistent state file `%s'.  "
4003 			    "Ignored.\n", init_state_file);
4004 		} else {
4005 			console(B_TRUE,
4006 			    "Persistent state file `%s' is invalid and was "
4007 			    "ignored.\n", init_state_file);
4008 		}
4009 	}
4010 }
4011 
4012 /*
4013  * Write g_state out to the state file.
4014  */
4015 void
4016 st_write()
4017 {
4018 	static int complained = 0;
4019 
4020 	int st_fd;
4021 	char *cp;
4022 	size_t sz;
4023 	ssize_t ret;
4024 
4025 
4026 	do {
4027 		st_fd = open(init_next_state_file,
4028 		    O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
4029 	} while (st_fd < 0 && errno == EINTR);
4030 	if (st_fd < 0)
4031 		goto err;
4032 
4033 	cp = (char *)g_state;
4034 	sz = g_state_sz;
4035 	while (sz > 0) {
4036 		ret = write(st_fd, cp, sz);
4037 		if (ret < 0) {
4038 			if (errno == EINTR)
4039 				continue;
4040 
4041 			goto err;
4042 		}
4043 
4044 		sz -= ret;
4045 		cp += ret;
4046 	}
4047 
4048 	(void) close(st_fd);
4049 	st_fd = -1;
4050 	if (rename(init_next_state_file, init_state_file)) {
4051 		(void) unlink(init_next_state_file);
4052 		goto err;
4053 	}
4054 	complained = 0;
4055 
4056 	return;
4057 
4058 err:
4059 	if (st_fd >= 0)
4060 		(void) close(st_fd);
4061 
4062 	if (!booting && !complained) {
4063 		/*
4064 		 * Only complain after the filesystem should have come up.
4065 		 * And only do it once so we don't loop between console()
4066 		 * & efork().
4067 		 */
4068 		complained = 1;
4069 		if (st_fd)
4070 			console(B_TRUE, "Couldn't write persistent state "
4071 			    "file `%s'.\n", init_state_file);
4072 		else
4073 			console(B_TRUE, "Couldn't move persistent state "
4074 			    "file `%s' to `%s'.\n", init_next_state_file,
4075 			    init_state_file);
4076 	}
4077 }
4078 
4079 /*
4080  * Create a contract with these parameters.
4081  */
4082 static int
4083 contract_make_template(uint_t info, uint_t critical, uint_t fatal,
4084     uint64_t cookie)
4085 {
4086 	int fd, err;
4087 
4088 	char *ioctl_tset_emsg =
4089 	    "Couldn't set \"%s\" contract template parameter: %s.\n";
4090 
4091 	do
4092 		fd = open64(CTFS_ROOT "/process/template", O_RDWR);
4093 	while (fd < 0 && errno == EINTR);
4094 	if (fd < 0) {
4095 		console(B_TRUE, "Couldn't create process template: %s.\n",
4096 		    strerror(errno));
4097 		return (-1);
4098 	}
4099 
4100 	if (err = ct_pr_tmpl_set_param(fd, CT_PR_INHERIT | CT_PR_REGENT))
4101 		console(B_TRUE, "Contract set template inherit, regent "
4102 		    "failed: %s.\n", strerror(err));
4103 
4104 	/*
4105 	 * These errors result in a misconfigured template, which is better
4106 	 * than no template at all, so warn but don't abort.
4107 	 */
4108 	if (err = ct_tmpl_set_informative(fd, info))
4109 		console(B_TRUE, ioctl_tset_emsg, "informative", strerror(err));
4110 
4111 	if (err = ct_tmpl_set_critical(fd, critical))
4112 		console(B_TRUE, ioctl_tset_emsg, "critical", strerror(err));
4113 
4114 	if (err = ct_pr_tmpl_set_fatal(fd, fatal))
4115 		console(B_TRUE, ioctl_tset_emsg, "fatal", strerror(err));
4116 
4117 	if (err = ct_tmpl_set_cookie(fd,