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