xref: /titanic_44/usr/src/cmd/zoneadmd/zoneadmd.c (revision 31979bfa048dcd2ef7f20d5f6afd58702333b725)
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 /*
28  * zoneadmd manages zones; one zoneadmd process is launched for each
29  * non-global zone on the system.  This daemon juggles four jobs:
30  *
31  * - Implement setup and teardown of the zone "virtual platform": mount and
32  *   unmount filesystems; create and destroy network interfaces; communicate
33  *   with devfsadmd to lay out devices for the zone; instantiate the zone
34  *   console device; configure process runtime attributes such as resource
35  *   controls, pool bindings, fine-grained privileges.
36  *
37  * - Launch the zone's init(1M) process.
38  *
39  * - Implement a door server; clients (like zoneadm) connect to the door
40  *   server and request zone state changes.  The kernel is also a client of
41  *   this door server.  A request to halt or reboot the zone which originates
42  *   *inside* the zone results in a door upcall from the kernel into zoneadmd.
43  *
44  *   One minor problem is that messages emitted by zoneadmd need to be passed
45  *   back to the zoneadm process making the request.  These messages need to
46  *   be rendered in the client's locale; so, this is passed in as part of the
47  *   request.  The exception is the kernel upcall to zoneadmd, in which case
48  *   messages are syslog'd.
49  *
50  *   To make all of this work, the Makefile adds -a to xgettext to extract *all*
51  *   strings, and an exclusion file (zoneadmd.xcl) is used to exclude those
52  *   strings which do not need to be translated.
53  *
54  * - Act as a console server for zlogin -C processes; see comments in zcons.c
55  *   for more information about the zone console architecture.
56  *
57  * DESIGN NOTES
58  *
59  * Restart:
60  *   A chief design constraint of zoneadmd is that it should be restartable in
61  *   the case that the administrator kills it off, or it suffers a fatal error,
62  *   without the running zone being impacted; this is akin to being able to
63  *   reboot the service processor of a server without affecting the OS instance.
64  */
65 
66 #include <sys/param.h>
67 #include <sys/mman.h>
68 #include <sys/types.h>
69 #include <sys/stat.h>
70 #include <sys/sysmacros.h>
71 
72 #include <bsm/adt.h>
73 #include <bsm/adt_event.h>
74 
75 #include <alloca.h>
76 #include <assert.h>
77 #include <errno.h>
78 #include <door.h>
79 #include <fcntl.h>
80 #include <locale.h>
81 #include <signal.h>
82 #include <stdarg.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <strings.h>
87 #include <synch.h>
88 #include <syslog.h>
89 #include <thread.h>
90 #include <unistd.h>
91 #include <wait.h>
92 #include <limits.h>
93 #include <zone.h>
94 #include <libbrand.h>
95 #include <sys/brand.h>
96 #include <libcontract.h>
97 #include <libcontract_priv.h>
98 #include <sys/contract/process.h>
99 #include <sys/ctfs.h>
100 
101 #include <libzonecfg.h>
102 #include "zoneadmd.h"
103 
104 static char *progname;
105 char *zone_name;	/* zone which we are managing */
106 char brand_name[MAXNAMELEN];
107 boolean_t zone_isnative;
108 boolean_t zone_iscluster;
109 boolean_t zone_islabeled;
110 static zoneid_t zone_id;
111 dladm_handle_t dld_handle = NULL;
112 
113 static char pre_statechg_hook[2 * MAXPATHLEN];
114 static char post_statechg_hook[2 * MAXPATHLEN];
115 char query_hook[2 * MAXPATHLEN];
116 
117 zlog_t logsys;
118 
119 mutex_t	lock = DEFAULTMUTEX;	/* to serialize stuff */
120 mutex_t	msglock = DEFAULTMUTEX;	/* for calling setlocale() */
121 
122 static sema_t scratch_sem;	/* for scratch zones */
123 
124 static char	zone_door_path[MAXPATHLEN];
125 static int	zone_door = -1;
126 
127 boolean_t in_death_throes = B_FALSE;	/* daemon is dying */
128 boolean_t bringup_failure_recovery = B_FALSE; /* ignore certain failures */
129 
130 #if !defined(TEXT_DOMAIN)		/* should be defined by cc -D */
131 #define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it wasn't */
132 #endif
133 
134 #define	DEFAULT_LOCALE	"C"
135 
136 static const char *
137 z_cmd_name(zone_cmd_t zcmd)
138 {
139 	/* This list needs to match the enum in sys/zone.h */
140 	static const char *zcmdstr[] = {
141 		"ready", "boot", "forceboot", "reboot", "halt",
142 		"note_uninstalling", "mount", "forcemount", "unmount"
143 	};
144 
145 	if (zcmd >= sizeof (zcmdstr) / sizeof (*zcmdstr))
146 		return ("unknown");
147 	else
148 		return (zcmdstr[(int)zcmd]);
149 }
150 
151 static char *
152 get_execbasename(char *execfullname)
153 {
154 	char *last_slash, *execbasename;
155 
156 	/* guard against '/' at end of command invocation */
157 	for (;;) {
158 		last_slash = strrchr(execfullname, '/');
159 		if (last_slash == NULL) {
160 			execbasename = execfullname;
161 			break;
162 		} else {
163 			execbasename = last_slash + 1;
164 			if (*execbasename == '\0') {
165 				*last_slash = '\0';
166 				continue;
167 			}
168 			break;
169 		}
170 	}
171 	return (execbasename);
172 }
173 
174 static void
175 usage(void)
176 {
177 	(void) fprintf(stderr, gettext("Usage: %s -z zonename\n"), progname);
178 	(void) fprintf(stderr,
179 	    gettext("\tNote: %s should not be run directly.\n"), progname);
180 	exit(2);
181 }
182 
183 /* ARGSUSED */
184 static void
185 sigchld(int sig)
186 {
187 }
188 
189 char *
190 localize_msg(char *locale, const char *msg)
191 {
192 	char *out;
193 
194 	(void) mutex_lock(&msglock);
195 	(void) setlocale(LC_MESSAGES, locale);
196 	out = gettext(msg);
197 	(void) setlocale(LC_MESSAGES, DEFAULT_LOCALE);
198 	(void) mutex_unlock(&msglock);
199 	return (out);
200 }
201 
202 /* PRINTFLIKE3 */
203 void
204 zerror(zlog_t *zlogp, boolean_t use_strerror, const char *fmt, ...)
205 {
206 	va_list alist;
207 	char buf[MAXPATHLEN * 2]; /* enough space for err msg with a path */
208 	char *bp;
209 	int saved_errno = errno;
210 
211 	if (zlogp == NULL)
212 		return;
213 	if (zlogp == &logsys)
214 		(void) snprintf(buf, sizeof (buf), "[zone '%s'] ",
215 		    zone_name);
216 	else
217 		buf[0] = '\0';
218 	bp = &(buf[strlen(buf)]);
219 
220 	/*
221 	 * In theory, the locale pointer should be set to either "C" or a
222 	 * char array, so it should never be NULL
223 	 */
224 	assert(zlogp->locale != NULL);
225 	/* Locale is per process, but we are multi-threaded... */
226 	fmt = localize_msg(zlogp->locale, fmt);
227 
228 	va_start(alist, fmt);
229 	(void) vsnprintf(bp, sizeof (buf) - (bp - buf), fmt, alist);
230 	va_end(alist);
231 	bp = &(buf[strlen(buf)]);
232 	if (use_strerror)
233 		(void) snprintf(bp, sizeof (buf) - (bp - buf), ": %s",
234 		    strerror(saved_errno));
235 	if (zlogp == &logsys) {
236 		(void) syslog(LOG_ERR, "%s", buf);
237 	} else if (zlogp->logfile != NULL) {
238 		(void) fprintf(zlogp->logfile, "%s\n", buf);
239 	} else {
240 		size_t buflen;
241 		size_t copylen;
242 
243 		buflen = snprintf(zlogp->log, zlogp->loglen, "%s\n", buf);
244 		copylen = MIN(buflen, zlogp->loglen);
245 		zlogp->log += copylen;
246 		zlogp->loglen -= copylen;
247 	}
248 }
249 
250 /*
251  * Emit a warning for any boot arguments which are unrecognized.  Since
252  * Solaris boot arguments are getopt(3c) compatible (see kernel(1m)), we
253  * put the arguments into an argv style array, use getopt to process them,
254  * and put the resultant argument string back into outargs.
255  *
256  * During the filtering, we pull out any arguments which are truly "boot"
257  * arguments, leaving only those which are to be passed intact to the
258  * progenitor process.  The one we support at the moment is -i, which
259  * indicates to the kernel which program should be launched as 'init'.
260  *
261  * A return of Z_INVAL indicates specifically that the arguments are
262  * not valid; this is a non-fatal error.  Except for Z_OK, all other return
263  * values are treated as fatal.
264  */
265 static int
266 filter_bootargs(zlog_t *zlogp, const char *inargs, char *outargs,
267     char *init_file, char *badarg)
268 {
269 	int argc = 0, argc_save;
270 	int i;
271 	int err;
272 	char *arg, *lasts, **argv = NULL, **argv_save;
273 	char zonecfg_args[BOOTARGS_MAX];
274 	char scratchargs[BOOTARGS_MAX], *sargs;
275 	char c;
276 
277 	bzero(outargs, BOOTARGS_MAX);
278 	bzero(badarg, BOOTARGS_MAX);
279 
280 	/*
281 	 * If the user didn't specify transient boot arguments, check
282 	 * to see if there were any specified in the zone configuration,
283 	 * and use them if applicable.
284 	 */
285 	if (inargs == NULL || inargs[0] == '\0')  {
286 		zone_dochandle_t handle;
287 		if ((handle = zonecfg_init_handle()) == NULL) {
288 			zerror(zlogp, B_TRUE,
289 			    "getting zone configuration handle");
290 			return (Z_BAD_HANDLE);
291 		}
292 		err = zonecfg_get_snapshot_handle(zone_name, handle);
293 		if (err != Z_OK) {
294 			zerror(zlogp, B_FALSE,
295 			    "invalid configuration snapshot");
296 			zonecfg_fini_handle(handle);
297 			return (Z_BAD_HANDLE);
298 		}
299 
300 		bzero(zonecfg_args, sizeof (zonecfg_args));
301 		(void) zonecfg_get_bootargs(handle, zonecfg_args,
302 		    sizeof (zonecfg_args));
303 		inargs = zonecfg_args;
304 		zonecfg_fini_handle(handle);
305 	}
306 
307 	if (strlen(inargs) >= BOOTARGS_MAX) {
308 		zerror(zlogp, B_FALSE, "boot argument string too long");
309 		return (Z_INVAL);
310 	}
311 
312 	(void) strlcpy(scratchargs, inargs, sizeof (scratchargs));
313 	sargs = scratchargs;
314 	while ((arg = strtok_r(sargs, " \t", &lasts)) != NULL) {
315 		sargs = NULL;
316 		argc++;
317 	}
318 
319 	if ((argv = calloc(argc + 1, sizeof (char *))) == NULL) {
320 		zerror(zlogp, B_FALSE, "memory allocation failed");
321 		return (Z_NOMEM);
322 	}
323 
324 	argv_save = argv;
325 	argc_save = argc;
326 
327 	(void) strlcpy(scratchargs, inargs, sizeof (scratchargs));
328 	sargs = scratchargs;
329 	i = 0;
330 	while ((arg = strtok_r(sargs, " \t", &lasts)) != NULL) {
331 		sargs = NULL;
332 		if ((argv[i] = strdup(arg)) == NULL) {
333 			err = Z_NOMEM;
334 			zerror(zlogp, B_FALSE, "memory allocation failed");
335 			goto done;
336 		}
337 		i++;
338 	}
339 
340 	/*
341 	 * We preserve compatibility with the Solaris system boot behavior,
342 	 * which allows:
343 	 *
344 	 * 	# reboot kernel/unix -s -m verbose
345 	 *
346 	 * In this example, kernel/unix tells the booter what file to
347 	 * boot.  We don't want reboot in a zone to be gratuitously different,
348 	 * so we silently ignore the boot file, if necessary.
349 	 */
350 	if (argv[0] == NULL)
351 		goto done;
352 
353 	assert(argv[0][0] != ' ');
354 	assert(argv[0][0] != '\t');
355 
356 	if (argv[0][0] != '-' && argv[0][0] != '\0') {
357 		argv = &argv[1];
358 		argc--;
359 	}
360 
361 	optind = 0;
362 	opterr = 0;
363 	err = Z_OK;
364 	while ((c = getopt(argc, argv, "fi:m:s")) != -1) {
365 		switch (c) {
366 		case 'i':
367 			/*
368 			 * -i is handled by the runtime and is not passed
369 			 * along to userland
370 			 */
371 			(void) strlcpy(init_file, optarg, MAXPATHLEN);
372 			break;
373 		case 'f':
374 			/* This has already been processed by zoneadm */
375 			break;
376 		case 'm':
377 		case 's':
378 			/* These pass through unmolested */
379 			(void) snprintf(outargs, BOOTARGS_MAX,
380 			    "%s -%c %s ", outargs, c, optarg ? optarg : "");
381 			break;
382 		case '?':
383 			/*
384 			 * We warn about unknown arguments but pass them
385 			 * along anyway-- if someone wants to develop their
386 			 * own init replacement, they can pass it whatever
387 			 * args they want.
388 			 */
389 			err = Z_INVAL;
390 			(void) snprintf(outargs, BOOTARGS_MAX,
391 			    "%s -%c", outargs, optopt);
392 			(void) snprintf(badarg, BOOTARGS_MAX,
393 			    "%s -%c", badarg, optopt);
394 			break;
395 		}
396 	}
397 
398 	/*
399 	 * For Solaris Zones we warn about and discard non-option arguments.
400 	 * Hence 'boot foo bar baz gub' --> 'boot'.  However, to be similar
401 	 * to the kernel, we concat up all the other remaining boot args.
402 	 * and warn on them as a group.
403 	 */
404 	if (optind < argc) {
405 		err = Z_INVAL;
406 		while (optind < argc) {
407 			(void) snprintf(badarg, BOOTARGS_MAX, "%s%s%s",
408 			    badarg, strlen(badarg) > 0 ? " " : "",
409 			    argv[optind]);
410 			optind++;
411 		}
412 		zerror(zlogp, B_FALSE, "WARNING: Unused or invalid boot "
413 		    "arguments `%s'.", badarg);
414 	}
415 
416 done:
417 	for (i = 0; i < argc_save; i++) {
418 		if (argv_save[i] != NULL)
419 			free(argv_save[i]);
420 	}
421 	free(argv_save);
422 	return (err);
423 }
424 
425 
426 static int
427 mkzonedir(zlog_t *zlogp)
428 {
429 	struct stat st;
430 	/*
431 	 * We must create and lock everyone but root out of ZONES_TMPDIR
432 	 * since anyone can open any UNIX domain socket, regardless of
433 	 * its file system permissions.  Sigh...
434 	 */
435 	if (mkdir(ZONES_TMPDIR, S_IRWXU) < 0 && errno != EEXIST) {
436 		zerror(zlogp, B_TRUE, "could not mkdir '%s'", ZONES_TMPDIR);
437 		return (-1);
438 	}
439 	/* paranoia */
440 	if ((stat(ZONES_TMPDIR, &st) < 0) || !S_ISDIR(st.st_mode)) {
441 		zerror(zlogp, B_TRUE, "'%s' is not a directory", ZONES_TMPDIR);
442 		return (-1);
443 	}
444 	(void) chmod(ZONES_TMPDIR, S_IRWXU);
445 	return (0);
446 }
447 
448 /*
449  * Run the brand's pre-state change callback, if it exists.
450  */
451 static int
452 brand_prestatechg(zlog_t *zlogp, int state, int cmd)
453 {
454 	char cmdbuf[2 * MAXPATHLEN];
455 
456 	if (pre_statechg_hook[0] == '\0')
457 		return (0);
458 
459 	if (snprintf(cmdbuf, sizeof (cmdbuf), "%s %d %d", pre_statechg_hook,
460 	    state, cmd) > sizeof (cmdbuf))
461 		return (-1);
462 
463 	if (do_subproc(zlogp, cmdbuf, NULL) != 0)
464 		return (-1);
465 
466 	return (0);
467 }
468 
469 /*
470  * Run the brand's post-state change callback, if it exists.
471  */
472 static int
473 brand_poststatechg(zlog_t *zlogp, int state, int cmd)
474 {
475 	char cmdbuf[2 * MAXPATHLEN];
476 
477 	if (post_statechg_hook[0] == '\0')
478 		return (0);
479 
480 	if (snprintf(cmdbuf, sizeof (cmdbuf), "%s %d %d", post_statechg_hook,
481 	    state, cmd) > sizeof (cmdbuf))
482 		return (-1);
483 
484 	if (do_subproc(zlogp, cmdbuf, NULL) != 0)
485 		return (-1);
486 
487 	return (0);
488 }
489 
490 /*
491  * Bring a zone up to the pre-boot "ready" stage.  The mount_cmd argument is
492  * 'true' if this is being invoked as part of the processing for the "mount"
493  * subcommand.
494  */
495 static int
496 zone_ready(zlog_t *zlogp, zone_mnt_t mount_cmd, int zstate)
497 {
498 	int err;
499 
500 	if (brand_prestatechg(zlogp, zstate, Z_READY) != 0)
501 		return (-1);
502 
503 	if ((err = zonecfg_create_snapshot(zone_name)) != Z_OK) {
504 		zerror(zlogp, B_FALSE, "unable to create snapshot: %s",
505 		    zonecfg_strerror(err));
506 		goto bad;
507 	}
508 
509 	if ((zone_id = vplat_create(zlogp, mount_cmd)) == -1) {
510 		if ((err = zonecfg_destroy_snapshot(zone_name)) != Z_OK)
511 			zerror(zlogp, B_FALSE, "destroying snapshot: %s",
512 			    zonecfg_strerror(err));
513 		goto bad;
514 	}
515 	if (vplat_bringup(zlogp, mount_cmd, zone_id) != 0) {
516 		bringup_failure_recovery = B_TRUE;
517 		(void) vplat_teardown(NULL, (mount_cmd != Z_MNT_BOOT), B_FALSE);
518 		if ((err = zonecfg_destroy_snapshot(zone_name)) != Z_OK)
519 			zerror(zlogp, B_FALSE, "destroying snapshot: %s",
520 			    zonecfg_strerror(err));
521 		goto bad;
522 	}
523 
524 	if (brand_poststatechg(zlogp, zstate, Z_READY) != 0)
525 		goto bad;
526 
527 	return (0);
528 
529 bad:
530 	/*
531 	 * If something goes wrong, we up the zones's state to the target
532 	 * state, READY, and then invoke the hook as if we're halting.
533 	 */
534 	(void) brand_poststatechg(zlogp, ZONE_STATE_READY, Z_HALT);
535 	return (-1);
536 }
537 
538 int
539 init_template(void)
540 {
541 	int fd;
542 	int err = 0;
543 
544 	fd = open64(CTFS_ROOT "/process/template", O_RDWR);
545 	if (fd == -1)
546 		return (-1);
547 
548 	/*
549 	 * For now, zoneadmd doesn't do anything with the contract.
550 	 * Deliver no events, don't inherit, and allow it to be orphaned.
551 	 */
552 	err |= ct_tmpl_set_critical(fd, 0);
553 	err |= ct_tmpl_set_informative(fd, 0);
554 	err |= ct_pr_tmpl_set_fatal(fd, CT_PR_EV_HWERR);
555 	err |= ct_pr_tmpl_set_param(fd, CT_PR_PGRPONLY | CT_PR_REGENT);
556 	if (err || ct_tmpl_activate(fd)) {
557 		(void) close(fd);
558 		return (-1);
559 	}
560 
561 	return (fd);
562 }
563 
564 typedef struct fs_callback {
565 	zlog_t		*zlogp;
566 	zoneid_t	zoneid;
567 	boolean_t	mount_cmd;
568 } fs_callback_t;
569 
570 static int
571 mount_early_fs(void *data, const char *spec, const char *dir,
572     const char *fstype, const char *opt)
573 {
574 	zlog_t *zlogp = ((fs_callback_t *)data)->zlogp;
575 	zoneid_t zoneid = ((fs_callback_t *)data)->zoneid;
576 	boolean_t mount_cmd = ((fs_callback_t *)data)->mount_cmd;
577 	char rootpath[MAXPATHLEN];
578 	pid_t child;
579 	int child_status;
580 	int tmpl_fd;
581 	int rv;
582 	ctid_t ct;
583 
584 	/* determine the zone rootpath */
585 	if (mount_cmd) {
586 		char zonepath[MAXPATHLEN];
587 		char luroot[MAXPATHLEN];
588 
589 		if (zone_get_zonepath(zone_name,
590 		    zonepath, sizeof (zonepath)) != Z_OK) {
591 			zerror(zlogp, B_FALSE, "unable to determine zone path");
592 			return (-1);
593 		}
594 
595 		(void) snprintf(luroot, sizeof (luroot), "%s/lu", zonepath);
596 		resolve_lofs(zlogp, luroot, sizeof (luroot));
597 		(void) strlcpy(rootpath, luroot, sizeof (rootpath));
598 	} else {
599 		if (zone_get_rootpath(zone_name,
600 		    rootpath, sizeof (rootpath)) != Z_OK) {
601 			zerror(zlogp, B_FALSE, "unable to determine zone root");
602 			return (-1);
603 		}
604 	}
605 
606 	if ((rv = valid_mount_path(zlogp, rootpath, spec, dir, fstype)) < 0) {
607 		zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
608 		    rootpath, dir);
609 		return (-1);
610 	} else if (rv > 0) {
611 		/* The mount point path doesn't exist, create it now. */
612 		if (make_one_dir(zlogp, rootpath, dir,
613 		    DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
614 		    DEFAULT_DIR_GROUP) != 0) {
615 			zerror(zlogp, B_FALSE, "failed to create mount point");
616 			return (-1);
617 		}
618 
619 		/*
620 		 * Now this might seem weird, but we need to invoke
621 		 * valid_mount_path() again.  Why?  Because it checks
622 		 * to make sure that the mount point path is canonical,
623 		 * which it can only do if the path exists, so now that
624 		 * we've created the path we have to verify it again.
625 		 */
626 		if ((rv = valid_mount_path(zlogp, rootpath, spec, dir,
627 		    fstype)) < 0) {
628 			zerror(zlogp, B_FALSE,
629 			    "%s%s is not a valid mount point", rootpath, dir);
630 			return (-1);
631 		}
632 	}
633 
634 	if ((tmpl_fd = init_template()) == -1) {
635 		zerror(zlogp, B_TRUE, "failed to create contract");
636 		return (-1);
637 	}
638 
639 	if ((child = fork()) == -1) {
640 		(void) ct_tmpl_clear(tmpl_fd);
641 		(void) close(tmpl_fd);
642 		zerror(zlogp, B_TRUE, "failed to fork");
643 		return (-1);
644 
645 	} else if (child == 0) {	/* child */
646 		char opt_buf[MAX_MNTOPT_STR];
647 		int optlen = 0;
648 		int mflag = MS_DATA;
649 
650 		(void) ct_tmpl_clear(tmpl_fd);
651 		/*
652 		 * Even though there are no procs running in the zone, we
653 		 * do this for paranoia's sake.
654 		 */
655 		(void) closefrom(0);
656 
657 		if (zone_enter(zoneid) == -1) {
658 			_exit(errno);
659 		}
660 		if (opt != NULL) {
661 			/*
662 			 * The mount() system call is incredibly annoying.
663 			 * If options are specified, we need to copy them
664 			 * into a temporary buffer since the mount() system
665 			 * call will overwrite the options string.  It will
666 			 * also fail if the new option string it wants to
667 			 * write is bigger than the one we passed in, so
668 			 * you must pass in a buffer of the maximum possible
669 			 * option string length.  sigh.
670 			 */
671 			(void) strlcpy(opt_buf, opt, sizeof (opt_buf));
672 			opt = opt_buf;
673 			optlen = MAX_MNTOPT_STR;
674 			mflag = MS_OPTIONSTR;
675 		}
676 		if (mount(spec, dir, mflag, fstype, NULL, 0, opt, optlen) != 0)
677 			_exit(errno);
678 		_exit(0);
679 	}
680 
681 	/* parent */
682 	if (contract_latest(&ct) == -1)
683 		ct = -1;
684 	(void) ct_tmpl_clear(tmpl_fd);
685 	(void) close(tmpl_fd);
686 	if (waitpid(child, &child_status, 0) != child) {
687 		/* unexpected: we must have been signalled */
688 		(void) contract_abandon_id(ct);
689 		return (-1);
690 	}
691 	(void) contract_abandon_id(ct);
692 	if (WEXITSTATUS(child_status) != 0) {
693 		errno = WEXITSTATUS(child_status);
694 		zerror(zlogp, B_TRUE, "mount of %s failed", dir);
695 		return (-1);
696 	}
697 
698 	return (0);
699 }
700 
701 /*
702  * If retstr is not NULL, the output of the subproc is returned in the str,
703  * otherwise it is output using zerror().  Any memory allocated for retstr
704  * should be freed by the caller.
705  */
706 int
707 do_subproc(zlog_t *zlogp, char *cmdbuf, char **retstr)
708 {
709 	char buf[1024];		/* arbitrary large amount */
710 	char *inbuf;
711 	FILE *file;
712 	int status;
713 	int rd_cnt;
714 
715 	if (retstr != NULL) {
716 		if ((*retstr = malloc(1024)) == NULL) {
717 			zerror(zlogp, B_FALSE, "out of memory");
718 			return (-1);
719 		}
720 		inbuf = *retstr;
721 		rd_cnt = 0;
722 	} else {
723 		inbuf = buf;
724 	}
725 
726 	file = popen(cmdbuf, "r");
727 	if (file == NULL) {
728 		zerror(zlogp, B_TRUE, "could not launch: %s", cmdbuf);
729 		return (-1);
730 	}
731 
732 	while (fgets(inbuf, 1024, file) != NULL) {
733 		if (retstr == NULL && zlogp != &logsys) {
734 			zerror(zlogp, B_FALSE, "%s", inbuf);
735 		} else {
736 			char *p;
737 
738 			rd_cnt += 1024 - 1;
739 			if ((p = realloc(*retstr, rd_cnt + 1024)) == NULL) {
740 				zerror(zlogp, B_FALSE, "out of memory");
741 				(void) pclose(file);
742 				return (-1);
743 			}
744 
745 			*retstr = p;
746 			inbuf = *retstr + rd_cnt;
747 		}
748 	}
749 	status = pclose(file);
750 
751 	if (WIFSIGNALED(status)) {
752 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
753 		    "signal %d", cmdbuf, WTERMSIG(status));
754 		return (-1);
755 	}
756 	assert(WIFEXITED(status));
757 	if (WEXITSTATUS(status) == ZEXIT_EXEC) {
758 		zerror(zlogp, B_FALSE, "failed to exec %s", cmdbuf);
759 		return (-1);
760 	}
761 	return (WEXITSTATUS(status));
762 }
763 
764 static int
765 zone_bootup(zlog_t *zlogp, const char *bootargs, int zstate)
766 {
767 	zoneid_t zoneid;
768 	struct stat st;
769 	char zpath[MAXPATHLEN], initpath[MAXPATHLEN], init_file[MAXPATHLEN];
770 	char nbootargs[BOOTARGS_MAX];
771 	char cmdbuf[MAXPATHLEN];
772 	fs_callback_t cb;
773 	brand_handle_t bh;
774 	int err;
775 
776 	if (brand_prestatechg(zlogp, zstate, Z_BOOT) != 0)
777 		return (-1);
778 
779 	if ((zoneid = getzoneidbyname(zone_name)) == -1) {
780 		zerror(zlogp, B_TRUE, "unable to get zoneid");
781 		goto bad;
782 	}
783 
784 	cb.zlogp = zlogp;
785 	cb.zoneid = zoneid;
786 	cb.mount_cmd = B_FALSE;
787 
788 	/* Get a handle to the brand info for this zone */
789 	if ((bh = brand_open(brand_name)) == NULL) {
790 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
791 		goto bad;
792 	}
793 
794 	/*
795 	 * Get the list of filesystems to mount from the brand
796 	 * configuration.  These mounts are done via a thread that will
797 	 * enter the zone, so they are done from within the context of the
798 	 * zone.
799 	 */
800 	if (brand_platform_iter_mounts(bh, mount_early_fs, &cb) != 0) {
801 		zerror(zlogp, B_FALSE, "unable to mount filesystems");
802 		brand_close(bh);
803 		goto bad;
804 	}
805 
806 	/*
807 	 * Get the brand's boot callback if it exists.
808 	 */
809 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
810 		zerror(zlogp, B_FALSE, "unable to determine zone path");
811 		brand_close(bh);
812 		goto bad;
813 	}
814 	(void) strcpy(cmdbuf, EXEC_PREFIX);
815 	if (brand_get_boot(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
816 	    sizeof (cmdbuf) - EXEC_LEN) != 0) {
817 		zerror(zlogp, B_FALSE,
818 		    "unable to determine branded zone's boot callback");
819 		brand_close(bh);
820 		goto bad;
821 	}
822 
823 	/* Get the path for this zone's init(1M) (or equivalent) process.  */
824 	if (brand_get_initname(bh, init_file, MAXPATHLEN) != 0) {
825 		zerror(zlogp, B_FALSE,
826 		    "unable to determine zone's init(1M) location");
827 		brand_close(bh);
828 		goto bad;
829 	}
830 
831 	brand_close(bh);
832 
833 	err = filter_bootargs(zlogp, bootargs, nbootargs, init_file,
834 	    bad_boot_arg);
835 	if (err == Z_INVAL)
836 		eventstream_write(Z_EVT_ZONE_BADARGS);
837 	else if (err != Z_OK)
838 		goto bad;
839 
840 	assert(init_file[0] != '\0');
841 
842 	/* Try to anticipate possible problems: Make sure init is executable. */
843 	if (zone_get_rootpath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
844 		zerror(zlogp, B_FALSE, "unable to determine zone root");
845 		goto bad;
846 	}
847 
848 	(void) snprintf(initpath, sizeof (initpath), "%s%s", zpath, init_file);
849 
850 	if (stat(initpath, &st) == -1) {
851 		zerror(zlogp, B_TRUE, "could not stat %s", initpath);
852 		goto bad;
853 	}
854 
855 	if ((st.st_mode & S_IXUSR) == 0) {
856 		zerror(zlogp, B_FALSE, "%s is not executable", initpath);
857 		goto bad;
858 	}
859 
860 	/*
861 	 * If there is a brand 'boot' callback, execute it now to give the
862 	 * brand one last chance to do any additional setup before the zone
863 	 * is booted.
864 	 */
865 	if ((strlen(cmdbuf) > EXEC_LEN) &&
866 	    (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
867 		zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
868 		goto bad;
869 	}
870 
871 	if (zone_setattr(zoneid, ZONE_ATTR_INITNAME, init_file, 0) == -1) {
872 		zerror(zlogp, B_TRUE, "could not set zone boot file");
873 		goto bad;
874 	}
875 
876 	if (zone_setattr(zoneid, ZONE_ATTR_BOOTARGS, nbootargs, 0) == -1) {
877 		zerror(zlogp, B_TRUE, "could not set zone boot arguments");
878 		goto bad;
879 	}
880 
881 	if (zone_boot(zoneid) == -1) {
882 		zerror(zlogp, B_TRUE, "unable to boot zone");
883 		goto bad;
884 	}
885 
886 	if (brand_poststatechg(zlogp, zstate, Z_BOOT) != 0)
887 		goto bad;
888 
889 	return (0);
890 
891 bad:
892 	/*
893 	 * If something goes wrong, we up the zones's state to the target
894 	 * state, RUNNING, and then invoke the hook as if we're halting.
895 	 */
896 	(void) brand_poststatechg(zlogp, ZONE_STATE_RUNNING, Z_HALT);
897 	return (-1);
898 }
899 
900 static int
901 zone_halt(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting, int zstate)
902 {
903 	int err;
904 
905 	if (brand_prestatechg(zlogp, zstate, Z_HALT) != 0)
906 		return (-1);
907 
908 	if (vplat_teardown(zlogp, unmount_cmd, rebooting) != 0) {
909 		if (!bringup_failure_recovery)
910 			zerror(zlogp, B_FALSE, "unable to destroy zone");
911 		return (-1);
912 	}
913 
914 	if ((err = zonecfg_destroy_snapshot(zone_name)) != Z_OK)
915 		zerror(zlogp, B_FALSE, "destroying snapshot: %s",
916 		    zonecfg_strerror(err));
917 
918 	if (brand_poststatechg(zlogp, zstate, Z_HALT) != 0)
919 		return (-1);
920 
921 	return (0);
922 }
923 
924 /*
925  * Generate AUE_zone_state for a command that boots a zone.
926  */
927 static void
928 audit_put_record(zlog_t *zlogp, ucred_t *uc, int return_val,
929     char *new_state)
930 {
931 	adt_session_data_t	*ah;
932 	adt_event_data_t	*event;
933 	int			pass_fail, fail_reason;
934 
935 	if (!adt_audit_enabled())
936 		return;
937 
938 	if (return_val == 0) {
939 		pass_fail = ADT_SUCCESS;
940 		fail_reason = ADT_SUCCESS;
941 	} else {
942 		pass_fail = ADT_FAILURE;
943 		fail_reason = ADT_FAIL_VALUE_PROGRAM;
944 	}
945 
946 	if (adt_start_session(&ah, NULL, 0)) {
947 		zerror(zlogp, B_TRUE, gettext("audit failure."));
948 		return;
949 	}
950 	if (adt_set_from_ucred(ah, uc, ADT_NEW)) {
951 		zerror(zlogp, B_TRUE, gettext("audit failure."));
952 		(void) adt_end_session(ah);
953 		return;
954 	}
955 
956 	event = adt_alloc_event(ah, ADT_zone_state);
957 	if (event == NULL) {
958 		zerror(zlogp, B_TRUE, gettext("audit failure."));
959 		(void) adt_end_session(ah);
960 		return;
961 	}
962 	event->adt_zone_state.zonename = zone_name;
963 	event->adt_zone_state.new_state = new_state;
964 
965 	if (adt_put_event(event, pass_fail, fail_reason))
966 		zerror(zlogp, B_TRUE, gettext("audit failure."));
967 
968 	adt_free_event(event);
969 
970 	(void) adt_end_session(ah);
971 }
972 
973 /*
974  * The main routine for the door server that deals with zone state transitions.
975  */
976 /* ARGSUSED */
977 static void
978 server(void *cookie, char *args, size_t alen, door_desc_t *dp,
979     uint_t n_desc)
980 {
981 	ucred_t *uc = NULL;
982 	const priv_set_t *eset;
983 
984 	zone_state_t zstate;
985 	zone_cmd_t cmd;
986 	zone_cmd_arg_t *zargp;
987 
988 	boolean_t kernelcall;
989 
990 	int rval = -1;
991 	uint64_t uniqid;
992 	zoneid_t zoneid = -1;
993 	zlog_t zlog;
994 	zlog_t *zlogp;
995 	zone_cmd_rval_t *rvalp;
996 	size_t rlen = getpagesize(); /* conservative */
997 	fs_callback_t cb;
998 	brand_handle_t bh;
999 
1000 	/* LINTED E_BAD_PTR_CAST_ALIGN */
1001 	zargp = (zone_cmd_arg_t *)args;
1002 
1003 	/*
1004 	 * When we get the door unref message, we've fdetach'd the door, and
1005 	 * it is time for us to shut down zoneadmd.
1006 	 */
1007 	if (zargp == DOOR_UNREF_DATA) {
1008 		/*
1009 		 * See comment at end of main() for info on the last rites.
1010 		 */
1011 		exit(0);
1012 	}
1013 
1014 	if (zargp == NULL) {
1015 		(void) door_return(NULL, 0, 0, 0);
1016 	}
1017 
1018 	rvalp = alloca(rlen);
1019 	bzero(rvalp, rlen);
1020 	zlog.logfile = NULL;
1021 	zlog.buflen = zlog.loglen = rlen - sizeof (zone_cmd_rval_t) + 1;
1022 	zlog.buf = rvalp->errbuf;
1023 	zlog.log = zlog.buf;
1024 	/* defer initialization of zlog.locale until after credential check */
1025 	zlogp = &zlog;
1026 
1027 	if (alen != sizeof (zone_cmd_arg_t)) {
1028 		/*
1029 		 * This really shouldn't be happening.
1030 		 */
1031 		zerror(&logsys, B_FALSE, "argument size (%d bytes) "
1032 		    "unexpected (expected %d bytes)", alen,
1033 		    sizeof (zone_cmd_arg_t));
1034 		goto out;
1035 	}
1036 	cmd = zargp->cmd;
1037 
1038 	if (door_ucred(&uc) != 0) {
1039 		zerror(&logsys, B_TRUE, "door_ucred");
1040 		goto out;
1041 	}
1042 	eset = ucred_getprivset(uc, PRIV_EFFECTIVE);
1043 	if (ucred_getzoneid(uc) != GLOBAL_ZONEID ||
1044 	    (eset != NULL ? !priv_ismember(eset, PRIV_SYS_CONFIG) :
1045 	    ucred_geteuid(uc) != 0)) {
1046 		zerror(&logsys, B_FALSE, "insufficient privileges");
1047 		goto out;
1048 	}
1049 
1050 	kernelcall = ucred_getpid(uc) == 0;
1051 
1052 	/*
1053 	 * This is safe because we only use a zlog_t throughout the
1054 	 * duration of a door call; i.e., by the time the pointer
1055 	 * might become invalid, the door call would be over.
1056 	 */
1057 	zlog.locale = kernelcall ? DEFAULT_LOCALE : zargp->locale;
1058 
1059 	(void) mutex_lock(&lock);
1060 
1061 	/*
1062 	 * Once we start to really die off, we don't want more connections.
1063 	 */
1064 	if (in_death_throes) {
1065 		(void) mutex_unlock(&lock);
1066 		ucred_free(uc);
1067 		(void) door_return(NULL, 0, 0, 0);
1068 		thr_exit(NULL);
1069 	}
1070 
1071 	/*
1072 	 * Check for validity of command.
1073 	 */
1074 	if (cmd != Z_READY && cmd != Z_BOOT && cmd != Z_FORCEBOOT &&
1075 	    cmd != Z_REBOOT && cmd != Z_HALT && cmd != Z_NOTE_UNINSTALLING &&
1076 	    cmd != Z_MOUNT && cmd != Z_FORCEMOUNT && cmd != Z_UNMOUNT) {
1077 		zerror(&logsys, B_FALSE, "invalid command %d", (int)cmd);
1078 		goto out;
1079 	}
1080 
1081 	if (kernelcall && (cmd != Z_HALT && cmd != Z_REBOOT)) {
1082 		/*
1083 		 * Can't happen
1084 		 */
1085 		zerror(&logsys, B_FALSE, "received unexpected kernel upcall %d",
1086 		    cmd);
1087 		goto out;
1088 	}
1089 	/*
1090 	 * We ignore the possibility of someone calling zone_create(2)
1091 	 * explicitly; all requests must come through zoneadmd.
1092 	 */
1093 	if (zone_get_state(zone_name, &zstate) != Z_OK) {
1094 		/*
1095 		 * Something terribly wrong happened
1096 		 */
1097 		zerror(&logsys, B_FALSE, "unable to determine state of zone");
1098 		goto out;
1099 	}
1100 
1101 	if (kernelcall) {
1102 		/*
1103 		 * Kernel-initiated requests may lose their validity if the
1104 		 * zone_t the kernel was referring to has gone away.
1105 		 */
1106 		if ((zoneid = getzoneidbyname(zone_name)) == -1 ||
1107 		    zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
1108 		    sizeof (uniqid)) == -1 || uniqid != zargp->uniqid) {
1109 			/*
1110 			 * We're not talking about the same zone. The request
1111 			 * must have arrived too late.  Return error.
1112 			 */
1113 			rval = -1;
1114 			goto out;
1115 		}
1116 		zlogp = &logsys;	/* Log errors to syslog */
1117 	}
1118 
1119 	/*
1120 	 * If we are being asked to forcibly mount or boot a zone, we
1121 	 * pretend that an INCOMPLETE zone is actually INSTALLED.
1122 	 */
1123 	if (zstate == ZONE_STATE_INCOMPLETE &&
1124 	    (cmd == Z_FORCEBOOT || cmd == Z_FORCEMOUNT))
1125 		zstate = ZONE_STATE_INSTALLED;
1126 
1127 	switch (zstate) {
1128 	case ZONE_STATE_CONFIGURED:
1129 	case ZONE_STATE_INCOMPLETE:
1130 		/*
1131 		 * Not our area of expertise; we just print a nice message
1132 		 * and die off.
1133 		 */
1134 		zerror(zlogp, B_FALSE,
1135 		    "%s operation is invalid for zones in state '%s'",
1136 		    z_cmd_name(cmd), zone_state_str(zstate));
1137 		break;
1138 
1139 	case ZONE_STATE_INSTALLED:
1140 		switch (cmd) {
1141 		case Z_READY:
1142 			rval = zone_ready(zlogp, Z_MNT_BOOT, zstate);
1143 			if (rval == 0)
1144 				eventstream_write(Z_EVT_ZONE_READIED);
1145 			break;
1146 		case Z_BOOT:
1147 		case Z_FORCEBOOT:
1148 			eventstream_write(Z_EVT_ZONE_BOOTING);
1149 			if ((rval = zone_ready(zlogp, Z_MNT_BOOT, zstate))
1150 			    == 0) {
1151 				rval = zone_bootup(zlogp, zargp->bootbuf,
1152 				    zstate);
1153 			}
1154 			audit_put_record(zlogp, uc, rval, "boot");
1155 			if (rval != 0) {
1156 				bringup_failure_recovery = B_TRUE;
1157 				(void) zone_halt(zlogp, B_FALSE, B_FALSE,
1158 				    zstate);
1159 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1160 			}
1161 			break;
1162 		case Z_HALT:
1163 			if (kernelcall)	/* Invalid; can't happen */
1164 				abort();
1165 			/*
1166 			 * We could have two clients racing to halt this
1167 			 * zone; the second client loses, but his request
1168 			 * doesn't fail, since the zone is now in the desired
1169 			 * state.
1170 			 */
1171 			zerror(zlogp, B_FALSE, "zone is already halted");
1172 			rval = 0;
1173 			break;
1174 		case Z_REBOOT:
1175 			if (kernelcall)	/* Invalid; can't happen */
1176 				abort();
1177 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1178 			    "for zones in state '%s'", z_cmd_name(cmd),
1179 			    zone_state_str(zstate));
1180 			rval = -1;
1181 			break;
1182 		case Z_NOTE_UNINSTALLING:
1183 			if (kernelcall)	/* Invalid; can't happen */
1184 				abort();
1185 			/*
1186 			 * Tell the console to print out a message about this.
1187 			 * Once it does, we will be in_death_throes.
1188 			 */
1189 			eventstream_write(Z_EVT_ZONE_UNINSTALLING);
1190 			break;
1191 		case Z_MOUNT:
1192 		case Z_FORCEMOUNT:
1193 			if (kernelcall)	/* Invalid; can't happen */
1194 				abort();
1195 			if (!zone_isnative && !zone_iscluster &&
1196 			    !zone_islabeled) {
1197 				/*
1198 				 * -U mounts the zone without lofs mounting
1199 				 * zone file systems back into the scratch
1200 				 * zone.  This is required when mounting
1201 				 * non-native branded zones.
1202 				 */
1203 				(void) strlcpy(zargp->bootbuf, "-U",
1204 				    BOOTARGS_MAX);
1205 			}
1206 
1207 			rval = zone_ready(zlogp,
1208 			    strcmp(zargp->bootbuf, "-U") == 0 ?
1209 			    Z_MNT_UPDATE : Z_MNT_SCRATCH, zstate);
1210 			if (rval != 0)
1211 				break;
1212 
1213 			eventstream_write(Z_EVT_ZONE_READIED);
1214 
1215 			/*
1216 			 * Get a handle to the native brand info.
1217 			 * We must always use the native brand file system
1218 			 * list when mounting the zone.
1219 			 */
1220 			if ((bh = brand_open(NATIVE_BRAND_NAME)) == NULL) {
1221 				rval = -1;
1222 				break;
1223 			}
1224 
1225 			/*
1226 			 * Get the list of filesystems to mount from
1227 			 * the brand configuration.  These mounts are done
1228 			 * via a thread that will enter the zone, so they
1229 			 * are done from within the context of the zone.
1230 			 */
1231 			cb.zlogp = zlogp;
1232 			cb.zoneid = zone_id;
1233 			cb.mount_cmd = B_TRUE;
1234 			rval = brand_platform_iter_mounts(bh,
1235 			    mount_early_fs, &cb);
1236 
1237 			brand_close(bh);
1238 
1239 			/*
1240 			 * Ordinarily, /dev/fd would be mounted inside the zone
1241 			 * by svc:/system/filesystem/usr:default, but since
1242 			 * we're not booting the zone, we need to do this
1243 			 * manually.
1244 			 */
1245 			if (rval == 0)
1246 				rval = mount_early_fs(&cb,
1247 				    "fd", "/dev/fd", "fd", NULL);
1248 			break;
1249 		case Z_UNMOUNT:
1250 			if (kernelcall)	/* Invalid; can't happen */
1251 				abort();
1252 			zerror(zlogp, B_FALSE, "zone is already unmounted");
1253 			rval = 0;
1254 			break;
1255 		}
1256 		break;
1257 
1258 	case ZONE_STATE_READY:
1259 		switch (cmd) {
1260 		case Z_READY:
1261 			/*
1262 			 * We could have two clients racing to ready this
1263 			 * zone; the second client loses, but his request
1264 			 * doesn't fail, since the zone is now in the desired
1265 			 * state.
1266 			 */
1267 			zerror(zlogp, B_FALSE, "zone is already ready");
1268 			rval = 0;
1269 			break;
1270 		case Z_BOOT:
1271 			(void) strlcpy(boot_args, zargp->bootbuf,
1272 			    sizeof (boot_args));
1273 			eventstream_write(Z_EVT_ZONE_BOOTING);
1274 			rval = zone_bootup(zlogp, zargp->bootbuf, zstate);
1275 			audit_put_record(zlogp, uc, rval, "boot");
1276 			if (rval != 0) {
1277 				bringup_failure_recovery = B_TRUE;
1278 				(void) zone_halt(zlogp, B_FALSE, B_TRUE,
1279 				    zstate);
1280 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1281 			}
1282 			boot_args[0] = '\0';
1283 			break;
1284 		case Z_HALT:
1285 			if (kernelcall)	/* Invalid; can't happen */
1286 				abort();
1287 			if ((rval = zone_halt(zlogp, B_FALSE, B_FALSE, zstate))
1288 			    != 0)
1289 				break;
1290 			eventstream_write(Z_EVT_ZONE_HALTED);
1291 			break;
1292 		case Z_REBOOT:
1293 		case Z_NOTE_UNINSTALLING:
1294 		case Z_MOUNT:
1295 		case Z_UNMOUNT:
1296 			if (kernelcall)	/* Invalid; can't happen */
1297 				abort();
1298 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1299 			    "for zones in state '%s'", z_cmd_name(cmd),
1300 			    zone_state_str(zstate));
1301 			rval = -1;
1302 			break;
1303 		}
1304 		break;
1305 
1306 	case ZONE_STATE_MOUNTED:
1307 		switch (cmd) {
1308 		case Z_UNMOUNT:
1309 			if (kernelcall)	/* Invalid; can't happen */
1310 				abort();
1311 			rval = zone_halt(zlogp, B_TRUE, B_FALSE, zstate);
1312 			if (rval == 0) {
1313 				eventstream_write(Z_EVT_ZONE_HALTED);
1314 				(void) sema_post(&scratch_sem);
1315 			}
1316 			break;
1317 		default:
1318 			if (kernelcall)	/* Invalid; can't happen */
1319 				abort();
1320 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1321 			    "for zones in state '%s'", z_cmd_name(cmd),
1322 			    zone_state_str(zstate));
1323 			rval = -1;
1324 			break;
1325 		}
1326 		break;
1327 
1328 	case ZONE_STATE_RUNNING:
1329 	case ZONE_STATE_SHUTTING_DOWN:
1330 	case ZONE_STATE_DOWN:
1331 		switch (cmd) {
1332 		case Z_READY:
1333 			if ((rval = zone_halt(zlogp, B_FALSE, B_TRUE, zstate))
1334 			    != 0)
1335 				break;
1336 			if ((rval = zone_ready(zlogp, Z_MNT_BOOT, zstate)) == 0)
1337 				eventstream_write(Z_EVT_ZONE_READIED);
1338 			else
1339 				eventstream_write(Z_EVT_ZONE_HALTED);
1340 			break;
1341 		case Z_BOOT:
1342 			/*
1343 			 * We could have two clients racing to boot this
1344 			 * zone; the second client loses, but his request
1345 			 * doesn't fail, since the zone is now in the desired
1346 			 * state.
1347 			 */
1348 			zerror(zlogp, B_FALSE, "zone is already booted");
1349 			rval = 0;
1350 			break;
1351 		case Z_HALT:
1352 			if ((rval = zone_halt(zlogp, B_FALSE, B_FALSE, zstate))
1353 			    != 0)
1354 				break;
1355 			eventstream_write(Z_EVT_ZONE_HALTED);
1356 			break;
1357 		case Z_REBOOT:
1358 			(void) strlcpy(boot_args, zargp->bootbuf,
1359 			    sizeof (boot_args));
1360 			eventstream_write(Z_EVT_ZONE_REBOOTING);
1361 			if ((rval = zone_halt(zlogp, B_FALSE, B_TRUE, zstate))
1362 			    != 0) {
1363 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1364 				boot_args[0] = '\0';
1365 				break;
1366 			}
1367 			if ((rval = zone_ready(zlogp, Z_MNT_BOOT, zstate))
1368 			    != 0) {
1369 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1370 				boot_args[0] = '\0';
1371 				break;
1372 			}
1373 			rval = zone_bootup(zlogp, zargp->bootbuf, zstate);
1374 			audit_put_record(zlogp, uc, rval, "reboot");
1375 			if (rval != 0) {
1376 				(void) zone_halt(zlogp, B_FALSE, B_TRUE,
1377 				    zstate);
1378 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1379 			}
1380 			boot_args[0] = '\0';
1381 			break;
1382 		case Z_NOTE_UNINSTALLING:
1383 		case Z_MOUNT:
1384 		case Z_UNMOUNT:
1385 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1386 			    "for zones in state '%s'", z_cmd_name(cmd),
1387 			    zone_state_str(zstate));
1388 			rval = -1;
1389 			break;
1390 		}
1391 		break;
1392 	default:
1393 		abort();
1394 	}
1395 
1396 	/*
1397 	 * Because the state of the zone may have changed, we make sure
1398 	 * to wake the console poller, which is in charge of initiating
1399 	 * the shutdown procedure as necessary.
1400 	 */
1401 	eventstream_write(Z_EVT_NULL);
1402 
1403 out:
1404 	(void) mutex_unlock(&lock);
1405 	if (kernelcall) {
1406 		rvalp = NULL;
1407 		rlen = 0;
1408 	} else {
1409 		rvalp->rval = rval;
1410 	}
1411 	if (uc != NULL)
1412 		ucred_free(uc);
1413 	(void) door_return((char *)rvalp, rlen, NULL, 0);
1414 	thr_exit(NULL);
1415 }
1416 
1417 static int
1418 setup_door(zlog_t *zlogp)
1419 {
1420 	if ((zone_door = door_create(server, NULL,
1421 	    DOOR_UNREF | DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) < 0) {
1422 		zerror(zlogp, B_TRUE, "%s failed", "door_create");
1423 		return (-1);
1424 	}
1425 	(void) fdetach(zone_door_path);
1426 
1427 	if (fattach(zone_door, zone_door_path) != 0) {
1428 		zerror(zlogp, B_TRUE, "fattach to %s failed", zone_door_path);
1429 		(void) door_revoke(zone_door);
1430 		(void) fdetach(zone_door_path);
1431 		zone_door = -1;
1432 		return (-1);
1433 	}
1434 	return (0);
1435 }
1436 
1437 /*
1438  * zoneadm(1m) will start zoneadmd if it thinks it isn't running; this
1439  * is where zoneadmd itself will check to see that another instance of
1440  * zoneadmd isn't already controlling this zone.
1441  *
1442  * The idea here is that we want to open the path to which we will
1443  * attach our door, lock it, and then make sure that no-one has beat us
1444  * to fattach(3c)ing onto it.
1445  *
1446  * fattach(3c) is really a mount, so there are actually two possible
1447  * vnodes we could be dealing with.  Our strategy is as follows:
1448  *
1449  * - If the file we opened is a regular file (common case):
1450  * 	There is no fattach(3c)ed door, so we have a chance of becoming
1451  * 	the managing zoneadmd. We attempt to lock the file: if it is
1452  * 	already locked, that means someone else raced us here, so we
1453  * 	lose and give up.  zoneadm(1m) will try to contact the zoneadmd
1454  * 	that beat us to it.
1455  *
1456  * - If the file we opened is a namefs file:
1457  * 	This means there is already an established door fattach(3c)'ed
1458  * 	to the rendezvous path.  We've lost the race, so we give up.
1459  * 	Note that in this case we also try to grab the file lock, and
1460  * 	will succeed in acquiring it since the vnode locked by the
1461  * 	"winning" zoneadmd was a regular one, and the one we locked was
1462  * 	the fattach(3c)'ed door node.  At any rate, no harm is done, and
1463  * 	we just return to zoneadm(1m) which knows to retry.
1464  */
1465 static int
1466 make_daemon_exclusive(zlog_t *zlogp)
1467 {
1468 	int doorfd = -1;
1469 	int err, ret = -1;
1470 	struct stat st;
1471 	struct flock flock;
1472 	zone_state_t zstate;
1473 
1474 top:
1475 	if ((err = zone_get_state(zone_name, &zstate)) != Z_OK) {
1476 		zerror(zlogp, B_FALSE, "failed to get zone state: %s",
1477 		    zonecfg_strerror(err));
1478 		goto out;
1479 	}
1480 	if ((doorfd = open(zone_door_path, O_CREAT|O_RDWR,
1481 	    S_IREAD|S_IWRITE)) < 0) {
1482 		zerror(zlogp, B_TRUE, "failed to open %s", zone_door_path);
1483 		goto out;
1484 	}
1485 	if (fstat(doorfd, &st) < 0) {
1486 		zerror(zlogp, B_TRUE, "failed to stat %s", zone_door_path);
1487 		goto out;
1488 	}
1489 	/*
1490 	 * Lock the file to synchronize with other zoneadmd
1491 	 */
1492 	flock.l_type = F_WRLCK;
1493 	flock.l_whence = SEEK_SET;
1494 	flock.l_start = (off_t)0;
1495 	flock.l_len = (off_t)0;
1496 	if (fcntl(doorfd, F_SETLK, &flock) < 0) {
1497 		/*
1498 		 * Someone else raced us here and grabbed the lock file
1499 		 * first.  A warning here is inappropriate since nothing
1500 		 * went wrong.
1501 		 */
1502 		goto out;
1503 	}
1504 
1505 	if (strcmp(st.st_fstype, "namefs") == 0) {
1506 		struct door_info info;
1507 
1508 		/*
1509 		 * There is already something fattach()'ed to this file.
1510 		 * Lets see what the door is up to.
1511 		 */
1512 		if (door_info(doorfd, &info) == 0 && info.di_target != -1) {
1513 			/*
1514 			 * Another zoneadmd process seems to be in
1515 			 * control of the situation and we don't need to
1516 			 * be here.  A warning here is inappropriate
1517 			 * since nothing went wrong.
1518 			 *
1519 			 * If the door has been revoked, the zoneadmd
1520 			 * process currently managing the zone is going
1521 			 * away.  We'll return control to zoneadm(1m)
1522 			 * which will try again (by which time zoneadmd
1523 			 * will hopefully have exited).
1524 			 */
1525 			goto out;
1526 		}
1527 
1528 		/*
1529 		 * If we got this far, there's a fattach(3c)'ed door
1530 		 * that belongs to a process that has exited, which can
1531 		 * happen if the previous zoneadmd died unexpectedly.
1532 		 *
1533 		 * Let user know that something is amiss, but that we can
1534 		 * recover; if the zone is in the installed state, then don't
1535 		 * message, since having a running zoneadmd isn't really
1536 		 * expected/needed.  We want to keep occurences of this message
1537 		 * limited to times when zoneadmd is picking back up from a
1538 		 * zoneadmd that died while the zone was in some non-trivial
1539 		 * state.
1540 		 */
1541 		if (zstate > ZONE_STATE_INSTALLED) {
1542 			zerror(zlogp, B_FALSE,
1543 			    "zone '%s': WARNING: zone is in state '%s', but "
1544 			    "zoneadmd does not appear to be available; "
1545 			    "restarted zoneadmd to recover.",
1546 			    zone_name, zone_state_str(zstate));
1547 		}
1548 
1549 		(void) fdetach(zone_door_path);
1550 		(void) close(doorfd);
1551 		goto top;
1552 	}
1553 	ret = 0;
1554 out:
1555 	(void) close(doorfd);
1556 	return (ret);
1557 }
1558 
1559 /*
1560  * Setup the brand's pre and post state change callbacks, as well as the
1561  * query callback, if any of these exist.
1562  */
1563 static int
1564 brand_callback_init(brand_handle_t bh, char *zone_name)
1565 {
1566 	char zpath[MAXPATHLEN];
1567 
1568 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK)
1569 		return (-1);
1570 
1571 	(void) strlcpy(pre_statechg_hook, EXEC_PREFIX,
1572 	    sizeof (pre_statechg_hook));
1573 
1574 	if (brand_get_prestatechange(bh, zone_name, zpath,
1575 	    pre_statechg_hook + EXEC_LEN,
1576 	    sizeof (pre_statechg_hook) - EXEC_LEN) != 0)
1577 		return (-1);
1578 
1579 	if (strlen(pre_statechg_hook) <= EXEC_LEN)
1580 		pre_statechg_hook[0] = '\0';
1581 
1582 	(void) strlcpy(post_statechg_hook, EXEC_PREFIX,
1583 	    sizeof (post_statechg_hook));
1584 
1585 	if (brand_get_poststatechange(bh, zone_name, zpath,
1586 	    post_statechg_hook + EXEC_LEN,
1587 	    sizeof (post_statechg_hook) - EXEC_LEN) != 0)
1588 		return (-1);
1589 
1590 	if (strlen(post_statechg_hook) <= EXEC_LEN)
1591 		post_statechg_hook[0] = '\0';
1592 
1593 	(void) strlcpy(query_hook, EXEC_PREFIX,
1594 	    sizeof (query_hook));
1595 
1596 	if (brand_get_query(bh, zone_name, zpath, query_hook + EXEC_LEN,
1597 	    sizeof (query_hook) - EXEC_LEN) != 0)
1598 		return (-1);
1599 
1600 	if (strlen(query_hook) <= EXEC_LEN)
1601 		query_hook[0] = '\0';
1602 
1603 	return (0);
1604 }
1605 
1606 int
1607 main(int argc, char *argv[])
1608 {
1609 	int opt;
1610 	zoneid_t zid;
1611 	priv_set_t *privset;
1612 	zone_state_t zstate;
1613 	char parents_locale[MAXPATHLEN];
1614 	brand_handle_t bh;
1615 	int err;
1616 
1617 	pid_t pid;
1618 	sigset_t blockset;
1619 	sigset_t block_cld;
1620 
1621 	struct {
1622 		sema_t sem;
1623 		int status;
1624 		zlog_t log;
1625 	} *shstate;
1626 	size_t shstatelen = getpagesize();
1627 
1628 	zlog_t errlog;
1629 	zlog_t *zlogp;
1630 
1631 	int ctfd;
1632 
1633 	progname = get_execbasename(argv[0]);
1634 
1635 	/*
1636 	 * Make sure stderr is unbuffered
1637 	 */
1638 	(void) setbuffer(stderr, NULL, 0);
1639 
1640 	/*
1641 	 * Get out of the way of mounted filesystems, since we will daemonize
1642 	 * soon.
1643 	 */
1644 	(void) chdir("/");
1645 
1646 	/*
1647 	 * Use the default system umask per PSARC 1998/110 rather than
1648 	 * anything that may have been set by the caller.
1649 	 */
1650 	(void) umask(CMASK);
1651 
1652 	/*
1653 	 * Initially we want to use our parent's locale.
1654 	 */
1655 	(void) setlocale(LC_ALL, "");
1656 	(void) textdomain(TEXT_DOMAIN);
1657 	(void) strlcpy(parents_locale, setlocale(LC_MESSAGES, NULL),
1658 	    sizeof (parents_locale));
1659 
1660 	/*
1661 	 * This zlog_t is used for writing to stderr
1662 	 */
1663 	errlog.logfile = stderr;
1664 	errlog.buflen = errlog.loglen = 0;
1665 	errlog.buf = errlog.log = NULL;
1666 	errlog.locale = parents_locale;
1667 
1668 	/*
1669 	 * We start off writing to stderr until we're ready to daemonize.
1670 	 */
1671 	zlogp = &errlog;
1672 
1673 	/*
1674 	 * Process options.
1675 	 */
1676 	while ((opt = getopt(argc, argv, "R:z:")) != EOF) {
1677 		switch (opt) {
1678 		case 'R':
1679 			zonecfg_set_root(optarg);
1680 			break;
1681 		case 'z':
1682 			zone_name = optarg;
1683 			break;
1684 		default:
1685 			usage();
1686 		}
1687 	}
1688 
1689 	if (zone_name == NULL)
1690 		usage();
1691 
1692 	/*
1693 	 * Because usage() prints directly to stderr, it has gettext()
1694 	 * wrapping, which depends on the locale.  But since zerror() calls
1695 	 * localize() which tweaks the locale, it is not safe to call zerror()
1696 	 * until after the last call to usage().  Fortunately, the last call
1697 	 * to usage() is just above and the first call to zerror() is just
1698 	 * below.  Don't mess this up.
1699 	 */
1700 	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0) {
1701 		zerror(zlogp, B_FALSE, "cannot manage the %s zone",
1702 		    GLOBAL_ZONENAME);
1703 		return (1);
1704 	}
1705 
1706 	if (zone_get_id(zone_name, &zid) != 0) {
1707 		zerror(zlogp, B_FALSE, "could not manage %s: %s", zone_name,
1708 		    zonecfg_strerror(Z_NO_ZONE));
1709 		return (1);
1710 	}
1711 
1712 	if ((err = zone_get_state(zone_name, &zstate)) != Z_OK) {
1713 		zerror(zlogp, B_FALSE, "failed to get zone state: %s",
1714 		    zonecfg_strerror(err));
1715 		return (1);
1716 	}
1717 	if (zstate < ZONE_STATE_INCOMPLETE) {
1718 		zerror(zlogp, B_FALSE,
1719 		    "cannot manage a zone which is in state '%s'",
1720 		    zone_state_str(zstate));
1721 		return (1);
1722 	}
1723 
1724 	/* Get a handle to the brand info for this zone */
1725 	if ((zone_get_brand(zone_name, brand_name, sizeof (brand_name))
1726 	    != Z_OK) || (bh = brand_open(brand_name)) == NULL) {
1727 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
1728 		return (1);
1729 	}
1730 	zone_isnative = brand_is_native(bh);
1731 	zone_iscluster = (strcmp(brand_name, CLUSTER_BRAND_NAME) == 0);
1732 	zone_islabeled = (strcmp(brand_name, LABELED_BRAND_NAME) == 0);
1733 
1734 	/* Get state change brand hooks. */
1735 	if (brand_callback_init(bh, zone_name) == -1) {
1736 		zerror(zlogp, B_TRUE,
1737 		    "failed to initialize brand state change hooks");
1738 		brand_close(bh);
1739 		return (1);
1740 	}
1741 
1742 	brand_close(bh);
1743 
1744 	/*
1745 	 * Check that we have all privileges.  It would be nice to pare
1746 	 * this down, but this is at least a first cut.
1747 	 */
1748 	if ((privset = priv_allocset()) == NULL) {
1749 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
1750 		return (1);
1751 	}
1752 
1753 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1754 		zerror(zlogp, B_TRUE, "%s failed", "getppriv");
1755 		priv_freeset(privset);
1756 		return (1);
1757 	}
1758 
1759 	if (priv_isfullset(privset) == B_FALSE) {
1760 		zerror(zlogp, B_FALSE, "You lack sufficient privilege to "
1761 		    "run this command (all privs required)");
1762 		priv_freeset(privset);
1763 		return (1);
1764 	}
1765 	priv_freeset(privset);
1766 
1767 	if (mkzonedir(zlogp) != 0)
1768 		return (1);
1769 
1770 	/*
1771 	 * Pre-fork: setup shared state
1772 	 */
1773 	if ((shstate = (void *)mmap(NULL, shstatelen,
1774 	    PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, (off_t)0)) ==
1775 	    MAP_FAILED) {
1776 		zerror(zlogp, B_TRUE, "%s failed", "mmap");
1777 		return (1);
1778 	}
1779 	if (sema_init(&shstate->sem, 0, USYNC_PROCESS, NULL) != 0) {
1780 		zerror(zlogp, B_TRUE, "%s failed", "sema_init()");
1781 		(void) munmap((char *)shstate, shstatelen);
1782 		return (1);
1783 	}
1784 	shstate->log.logfile = NULL;
1785 	shstate->log.buflen = shstatelen - sizeof (*shstate);
1786 	shstate->log.loglen = shstate->log.buflen;
1787 	shstate->log.buf = (char *)shstate + sizeof (*shstate);
1788 	shstate->log.log = shstate->log.buf;
1789 	shstate->log.locale = parents_locale;
1790 	shstate->status = -1;
1791 
1792 	/*
1793 	 * We need a SIGCHLD handler so the sema_wait() below will wake
1794 	 * up if the child dies without doing a sema_post().
1795 	 */
1796 	(void) sigset(SIGCHLD, sigchld);
1797 	/*
1798 	 * We must mask SIGCHLD until after we've coped with the fork
1799 	 * sufficiently to deal with it; otherwise we can race and
1800 	 * receive the signal before pid has been initialized
1801 	 * (yes, this really happens).
1802 	 */
1803 	(void) sigemptyset(&block_cld);
1804 	(void) sigaddset(&block_cld, SIGCHLD);
1805 	(void) sigprocmask(SIG_BLOCK, &block_cld, NULL);
1806 
1807 	if ((ctfd = init_template()) == -1) {
1808 		zerror(zlogp, B_TRUE, "failed to create contract");
1809 		return (1);
1810 	}
1811 
1812 	/*
1813 	 * Do not let another thread localize a message while we are forking.
1814 	 */
1815 	(void) mutex_lock(&msglock);
1816 	pid = fork();
1817 	(void) mutex_unlock(&msglock);
1818 
1819 	/*
1820 	 * In all cases (parent, child, and in the event of an error) we
1821 	 * don't want to cause creation of contracts on subsequent fork()s.
1822 	 */
1823 	(void) ct_tmpl_clear(ctfd);
1824 	(void) close(ctfd);
1825 
1826 	if (pid == -1) {
1827 		zerror(zlogp, B_TRUE, "could not fork");
1828 		return (1);
1829 
1830 	} else if (pid > 0) { /* parent */
1831 		(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
1832 		/*
1833 		 * This marks a window of vulnerability in which we receive
1834 		 * the SIGCLD before falling into sema_wait (normally we would
1835 		 * get woken up from sema_wait with EINTR upon receipt of
1836 		 * SIGCLD).  So we may need to use some other scheme like
1837 		 * sema_posting in the sigcld handler.
1838 		 * blech
1839 		 */
1840 		(void) sema_wait(&shstate->sem);
1841 		(void) sema_destroy(&shstate->sem);
1842 		if (shstate->status != 0)
1843 			(void) waitpid(pid, NULL, WNOHANG);
1844 		/*
1845 		 * It's ok if we die with SIGPIPE.  It's not like we could have
1846 		 * done anything about it.
1847 		 */
1848 		(void) fprintf(stderr, "%s", shstate->log.buf);
1849 		_exit(shstate->status == 0 ? 0 : 1);
1850 	}
1851 
1852 	/*
1853 	 * The child charges on.
1854 	 */
1855 	(void) sigset(SIGCHLD, SIG_DFL);
1856 	(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
1857 
1858 	/*
1859 	 * SIGPIPE can be delivered if we write to a socket for which the
1860 	 * peer endpoint is gone.  That can lead to too-early termination
1861 	 * of zoneadmd, and that's not good eats.
1862 	 */
1863 	(void) sigset(SIGPIPE, SIG_IGN);
1864 	/*
1865 	 * Stop using stderr
1866 	 */
1867 	zlogp = &shstate->log;
1868 
1869 	/*
1870 	 * We don't need stdout/stderr from now on.
1871 	 */
1872 	closefrom(0);
1873 
1874 	/*
1875 	 * Initialize the syslog zlog_t.  This needs to be done after
1876 	 * the call to closefrom().
1877 	 */
1878 	logsys.buf = logsys.log = NULL;
1879 	logsys.buflen = logsys.loglen = 0;
1880 	logsys.logfile = NULL;
1881 	logsys.locale = DEFAULT_LOCALE;
1882 
1883 	openlog("zoneadmd", LOG_PID, LOG_DAEMON);
1884 
1885 	/*
1886 	 * The eventstream is used to publish state changes in the zone
1887 	 * from the door threads to the console I/O poller.
1888 	 */
1889 	if (eventstream_init() == -1) {
1890 		zerror(zlogp, B_TRUE, "unable to create eventstream");
1891 		goto child_out;
1892 	}
1893 
1894 	(void) snprintf(zone_door_path, sizeof (zone_door_path),
1895 	    "%s" ZONE_DOOR_PATH, zonecfg_get_root(), zone_name);
1896 
1897 	/*
1898 	 * See if another zoneadmd is running for this zone.  If not, then we
1899 	 * can now modify system state.
1900 	 */
1901 	if (make_daemon_exclusive(zlogp) == -1)
1902 		goto child_out;
1903 
1904 
1905 	/*
1906 	 * Create/join a new session; we need to be careful of what we do with
1907 	 * the console from now on so we don't end up being the session leader
1908 	 * for the terminal we're going to be handing out.
1909 	 */
1910 	(void) setsid();
1911 
1912 	/*
1913 	 * This thread shouldn't be receiving any signals; in particular,
1914 	 * SIGCHLD should be received by the thread doing the fork().
1915 	 */
1916 	(void) sigfillset(&blockset);
1917 	(void) thr_sigsetmask(SIG_BLOCK, &blockset, NULL);
1918 
1919 	/*
1920 	 * Setup the console device and get ready to serve the console;
1921 	 * once this has completed, we're ready to let console clients
1922 	 * make an attempt to connect (they will block until
1923 	 * serve_console_sock() below gets called, and any pending
1924 	 * connection is accept()ed).
1925 	 */
1926 	if (!zonecfg_in_alt_root() && init_console(zlogp) < 0)
1927 		goto child_out;
1928 
1929 	/*
1930 	 * Take the lock now, so that when the door server gets going, we
1931 	 * are guaranteed that it won't take a request until we are sure
1932 	 * that everything is completely set up.  See the child_out: label
1933 	 * below to see why this matters.
1934 	 */
1935 	(void) mutex_lock(&lock);
1936 
1937 	/* Init semaphore for scratch zones. */
1938 	if (sema_init(&scratch_sem, 0, USYNC_THREAD, NULL) == -1) {
1939 		zerror(zlogp, B_TRUE,
1940 		    "failed to initialize semaphore for scratch zone");
1941 		goto child_out;
1942 	}
1943 
1944 	/* open the dladm handle */
1945 	if (dladm_open(&dld_handle) != DLADM_STATUS_OK) {
1946 		zerror(zlogp, B_FALSE, "failed to open dladm handle");
1947 		goto child_out;
1948 	}
1949 
1950 	/*
1951 	 * Note: door setup must occur *after* the console is setup.
1952 	 * This is so that as zlogin tests the door to see if zoneadmd
1953 	 * is ready yet, we know that the console will get serviced
1954 	 * once door_info() indicates that the door is "up".
1955 	 */
1956 	if (setup_door(zlogp) == -1)
1957 		goto child_out;
1958 
1959 	/*
1960 	 * Things seem OK so far; tell the parent process that we're done
1961 	 * with setup tasks.  This will cause the parent to exit, signalling
1962 	 * to zoneadm, zlogin, or whatever forked it that we are ready to
1963 	 * service requests.
1964 	 */
1965 	shstate->status = 0;
1966 	(void) sema_post(&shstate->sem);
1967 	(void) munmap((char *)shstate, shstatelen);
1968 	shstate = NULL;
1969 
1970 	(void) mutex_unlock(&lock);
1971 
1972 	/*
1973 	 * zlogp is now invalid, so reset it to the syslog logger.
1974 	 */
1975 	zlogp = &logsys;
1976 
1977 	/*
1978 	 * Now that we are free of any parents, switch to the default locale.
1979 	 */
1980 	(void) setlocale(LC_ALL, DEFAULT_LOCALE);
1981 
1982 	/*
1983 	 * At this point the setup portion of main() is basically done, so
1984 	 * we reuse this thread to manage the zone console.  When
1985 	 * serve_console() has returned, we are past the point of no return
1986 	 * in the life of this zoneadmd.
1987 	 */
1988 	if (zonecfg_in_alt_root()) {
1989 		/*
1990 		 * This is just awful, but mounted scratch zones don't (and
1991 		 * can't) have consoles.  We just wait for unmount instead.
1992 		 */
1993 		while (sema_wait(&scratch_sem) == EINTR)
1994 			;
1995 	} else {
1996 		serve_console(zlogp);
1997 		assert(in_death_throes);
1998 	}
1999 
2000 	/*
2001 	 * This is the next-to-last part of the exit interlock.  Upon calling
2002 	 * fdetach(), the door will go unreferenced; once any
2003 	 * outstanding requests (like the door thread doing Z_HALT) are
2004 	 * done, the door will get an UNREF notification; when it handles
2005 	 * the UNREF, the door server will cause the exit.
2006 	 */
2007 	assert(!MUTEX_HELD(&lock));
2008 	(void) fdetach(zone_door_path);
2009 
2010 	for (;;)
2011 		(void) pause();
2012 
2013 child_out:
2014 	assert(pid == 0);
2015 	if (shstate != NULL) {
2016 		shstate->status = -1;
2017 		(void) sema_post(&shstate->sem);
2018 		(void) munmap((char *)shstate, shstatelen);
2019 	}
2020 
2021 	/*
2022 	 * This might trigger an unref notification, but if so,
2023 	 * we are still holding the lock, so our call to exit will
2024 	 * ultimately win the race and will publish the right exit
2025 	 * code.
2026 	 */
2027 	if (zone_door != -1) {
2028 		assert(MUTEX_HELD(&lock));
2029 		(void) door_revoke(zone_door);
2030 		(void) fdetach(zone_door_path);
2031 	}
2032 
2033 	if (dld_handle != NULL)
2034 		dladm_close(dld_handle);
2035 
2036 	return (1); /* return from main() forcibly exits an MT process */
2037 }
2038