xref: /titanic_44/usr/src/cmd/zoneadmd/vplat.c (revision 5c46c6a053defc1bf25f2e08df2653bc7717ed0b)
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 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * This module contains functions used to bring up and tear down the
31  * Virtual Platform: [un]mounting file-systems, [un]plumbing network
32  * interfaces, [un]configuring devices, establishing resource controls,
33  * and creating/destroying the zone in the kernel.  These actions, on
34  * the way up, ready the zone; on the way down, they halt the zone.
35  * See the much longer block comment at the beginning of zoneadmd.c
36  * for a bigger picture of how the whole program functions.
37  *
38  * This module also has primary responsibility for the layout of "scratch
39  * zones."  These are mounted, but inactive, zones that are used during
40  * operating system upgrade and potentially other administrative action.  The
41  * scratch zone environment is similar to the miniroot environment.  The zone's
42  * actual root is mounted read-write on /a, and the standard paths (/usr,
43  * /sbin, /lib) all lead to read-only copies of the running system's binaries.
44  * This allows the administrative tools to manipulate the zone using "-R /a"
45  * without relying on any binaries in the zone itself.
46  *
47  * If the scratch zone is on an alternate root (Live Upgrade [LU] boot
48  * environment), then we must resolve the lofs mounts used there to uncover
49  * writable (unshared) resources.  Shared resources, though, are always
50  * read-only.  In addition, if the "same" zone with a different root path is
51  * currently running, then "/b" inside the zone points to the running zone's
52  * root.  This allows LU to synchronize configuration files during the upgrade
53  * process.
54  *
55  * To construct this environment, this module creates a tmpfs mount on
56  * $ZONEPATH/lu.  Inside this scratch area, the miniroot-like environment as
57  * described above is constructed on the fly.  The zone is then created using
58  * $ZONEPATH/lu as the root.
59  *
60  * Note that scratch zones are inactive.  The zone's bits are not running and
61  * likely cannot be run correctly until upgrade is done.  Init is not running
62  * there, nor is SMF.  Because of this, the "mounted" state of a scratch zone
63  * is not a part of the usual halt/ready/boot state machine.
64  */
65 
66 #include <sys/param.h>
67 #include <sys/mount.h>
68 #include <sys/mntent.h>
69 #include <sys/socket.h>
70 #include <sys/utsname.h>
71 #include <sys/types.h>
72 #include <sys/stat.h>
73 #include <sys/sockio.h>
74 #include <sys/stropts.h>
75 #include <sys/conf.h>
76 
77 #include <inet/tcp.h>
78 #include <arpa/inet.h>
79 #include <netinet/in.h>
80 #include <net/route.h>
81 #include <netdb.h>
82 
83 #include <stdio.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <unistd.h>
87 #include <rctl.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <strings.h>
91 #include <wait.h>
92 #include <limits.h>
93 #include <libgen.h>
94 #include <libzfs.h>
95 #include <zone.h>
96 #include <assert.h>
97 
98 #include <sys/mntio.h>
99 #include <sys/mnttab.h>
100 #include <sys/fs/autofs.h>	/* for _autofssys() */
101 #include <sys/fs/lofs_info.h>
102 #include <sys/fs/zfs.h>
103 
104 #include <pool.h>
105 #include <sys/pool.h>
106 
107 #include <libzonecfg.h>
108 #include "zoneadmd.h"
109 #include <tsol/label.h>
110 #include <libtsnet.h>
111 #include <sys/priv.h>
112 
113 #define	V4_ADDR_LEN	32
114 #define	V6_ADDR_LEN	128
115 
116 /* 0755 is the default directory mode. */
117 #define	DEFAULT_DIR_MODE \
118 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
119 
120 #define	IPD_DEFAULT_OPTS \
121 	MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
122 
123 #define	DFSTYPES	"/etc/dfs/fstypes"
124 #define	MAXTNZLEN	2048
125 
126 /*
127  * A list of directories which should be created.
128  */
129 
130 struct dir_info {
131 	char *dir_name;
132 	mode_t dir_mode;
133 };
134 
135 /*
136  * The pathnames below are relative to the zonepath
137  */
138 static struct dir_info dev_dirs[] = {
139 	{ "/dev",	0755 },
140 	{ "/dev/dsk",	0755 },
141 	{ "/dev/fd",	0555 },
142 	{ "/dev/pts",	0755 },
143 	{ "/dev/rdsk",	0755 },
144 	{ "/dev/rmt",	0755 },
145 	{ "/dev/sad",	0755 },
146 	{ "/dev/swap",	0755 },
147 	{ "/dev/term",	0755 },
148 };
149 
150 /*
151  * A list of devices which should be symlinked to /dev/zconsole.
152  */
153 
154 struct symlink_info {
155 	char *sl_source;
156 	char *sl_target;
157 };
158 
159 /*
160  * The "source" paths are relative to the zonepath
161  */
162 static struct symlink_info dev_symlinks[] = {
163 	{ "/dev/stderr",	"./fd/2" },
164 	{ "/dev/stdin",		"./fd/0" },
165 	{ "/dev/stdout",	"./fd/1" },
166 	{ "/dev/dtremote",	"/dev/null" },
167 	{ "/dev/console",	"zconsole" },
168 	{ "/dev/syscon",	"zconsole" },
169 	{ "/dev/sysmsg",	"zconsole" },
170 	{ "/dev/systty",	"zconsole" },
171 	{ "/dev/msglog",	"zconsole" },
172 };
173 
174 /* for routing socket */
175 static int rts_seqno = 0;
176 
177 /* mangled zone name when mounting in an alternate root environment */
178 static char kernzone[ZONENAME_MAX];
179 
180 /* array of cached mount entries for resolve_lofs */
181 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
182 
183 /* for Trusted Extensions */
184 static tsol_zcent_t *get_zone_label(zlog_t *, priv_set_t *);
185 static int tsol_mounts(zlog_t *, char *, char *);
186 static void tsol_unmounts(zlog_t *, char *);
187 static m_label_t *zlabel = NULL;
188 static m_label_t *zid_label = NULL;
189 static priv_set_t *zprivs = NULL;
190 
191 /* from libsocket, not in any header file */
192 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
193 
194 /*
195  * An optimization for build_mnttable: reallocate (and potentially copy the
196  * data) only once every N times through the loop.
197  */
198 #define	MNTTAB_HUNK	32
199 
200 /*
201  * Private autofs system call
202  */
203 extern int _autofssys(int, void *);
204 
205 static int
206 autofs_cleanup(zoneid_t zoneid)
207 {
208 	/*
209 	 * Ask autofs to unmount all trigger nodes in the given zone.
210 	 */
211 	return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
212 }
213 
214 static void
215 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
216 {
217 	uint_t i;
218 
219 	if (mnt_array == NULL)
220 		return;
221 	for (i = 0; i < nelem; i++) {
222 		free(mnt_array[i].mnt_mountp);
223 		free(mnt_array[i].mnt_fstype);
224 		free(mnt_array[i].mnt_special);
225 		free(mnt_array[i].mnt_mntopts);
226 		assert(mnt_array[i].mnt_time == NULL);
227 	}
228 	free(mnt_array);
229 }
230 
231 /*
232  * Build the mount table for the zone rooted at "zroot", storing the resulting
233  * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
234  * array in "nelemp".
235  */
236 static int
237 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
238     struct mnttab **mnt_arrayp, uint_t *nelemp)
239 {
240 	struct mnttab mnt;
241 	struct mnttab *mnts;
242 	struct mnttab *mnp;
243 	uint_t nmnt;
244 
245 	rewind(mnttab);
246 	resetmnttab(mnttab);
247 	nmnt = 0;
248 	mnts = NULL;
249 	while (getmntent(mnttab, &mnt) == 0) {
250 		struct mnttab *tmp_array;
251 
252 		if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
253 			continue;
254 		if (nmnt % MNTTAB_HUNK == 0) {
255 			tmp_array = realloc(mnts,
256 			    (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
257 			if (tmp_array == NULL) {
258 				free_mnttable(mnts, nmnt);
259 				return (-1);
260 			}
261 			mnts = tmp_array;
262 		}
263 		mnp = &mnts[nmnt++];
264 
265 		/*
266 		 * Zero out any fields we're not using.
267 		 */
268 		(void) memset(mnp, 0, sizeof (*mnp));
269 
270 		if (mnt.mnt_special != NULL)
271 			mnp->mnt_special = strdup(mnt.mnt_special);
272 		if (mnt.mnt_mntopts != NULL)
273 			mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
274 		mnp->mnt_mountp = strdup(mnt.mnt_mountp);
275 		mnp->mnt_fstype = strdup(mnt.mnt_fstype);
276 		if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
277 		    (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
278 		    mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
279 			zerror(zlogp, B_TRUE, "memory allocation failed");
280 			free_mnttable(mnts, nmnt);
281 			return (-1);
282 		}
283 	}
284 	*mnt_arrayp = mnts;
285 	*nelemp = nmnt;
286 	return (0);
287 }
288 
289 /*
290  * This is an optimization.  The resolve_lofs function is used quite frequently
291  * to manipulate file paths, and on a machine with a large number of zones,
292  * there will be a huge number of mounted file systems.  Thus, we trigger a
293  * reread of the list of mount points
294  */
295 static void
296 lofs_discard_mnttab(void)
297 {
298 	free_mnttable(resolve_lofs_mnts,
299 	    resolve_lofs_mnt_max - resolve_lofs_mnts);
300 	resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
301 }
302 
303 static int
304 lofs_read_mnttab(zlog_t *zlogp)
305 {
306 	FILE *mnttab;
307 	uint_t nmnts;
308 
309 	if ((mnttab = fopen(MNTTAB, "r")) == NULL)
310 		return (-1);
311 	if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
312 	    &nmnts) == -1) {
313 		(void) fclose(mnttab);
314 		return (-1);
315 	}
316 	(void) fclose(mnttab);
317 	resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
318 	return (0);
319 }
320 
321 /*
322  * This function loops over potential loopback mounts and symlinks in a given
323  * path and resolves them all down to an absolute path.
324  */
325 static void
326 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
327 {
328 	int len, arlen;
329 	const char *altroot;
330 	char tmppath[MAXPATHLEN];
331 	boolean_t outside_altroot;
332 
333 	if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
334 		return;
335 	tmppath[len] = '\0';
336 	(void) strlcpy(path, tmppath, sizeof (tmppath));
337 
338 	/* This happens once per zoneadmd operation. */
339 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
340 		return;
341 
342 	altroot = zonecfg_get_root();
343 	arlen = strlen(altroot);
344 	outside_altroot = B_FALSE;
345 	for (;;) {
346 		struct mnttab *mnp;
347 
348 		for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
349 		    mnp++) {
350 			if (mnp->mnt_fstype == NULL ||
351 			    mnp->mnt_mountp == NULL ||
352 			    mnp->mnt_special == NULL ||
353 			    strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
354 				continue;
355 			len = strlen(mnp->mnt_mountp);
356 			if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
357 			    (path[len] == '/' || path[len] == '\0'))
358 				break;
359 		}
360 		if (mnp >= resolve_lofs_mnt_max)
361 			break;
362 		if (outside_altroot) {
363 			char *cp;
364 			int olen = sizeof (MNTOPT_RO) - 1;
365 
366 			/*
367 			 * If we run into a read-only mount outside of the
368 			 * alternate root environment, then the user doesn't
369 			 * want this path to be made read-write.
370 			 */
371 			if (mnp->mnt_mntopts != NULL &&
372 			    (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
373 			    NULL &&
374 			    (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
375 			    (cp[olen] == '\0' || cp[olen] == ',')) {
376 				break;
377 			}
378 		} else if (arlen > 0 &&
379 		    (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
380 		    (mnp->mnt_special[arlen] != '\0' &&
381 		    mnp->mnt_special[arlen] != '/'))) {
382 			outside_altroot = B_TRUE;
383 		}
384 		/* use temporary buffer because new path might be longer */
385 		(void) snprintf(tmppath, sizeof (tmppath), "%s%s",
386 		    mnp->mnt_special, path + len);
387 		if ((len = resolvepath(tmppath, path, pathlen)) == -1)
388 			break;
389 		path[len] = '\0';
390 	}
391 }
392 
393 /*
394  * For a regular mount, check if a replacement lofs mount is needed because the
395  * referenced device is already mounted somewhere.
396  */
397 static int
398 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
399 {
400 	struct mnttab *mnp;
401 	zone_fsopt_t *optptr, *onext;
402 
403 	/* This happens once per zoneadmd operation. */
404 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
405 		return (-1);
406 
407 	/*
408 	 * If this special node isn't already in use, then it's ours alone;
409 	 * no need to worry about conflicting mounts.
410 	 */
411 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
412 	    mnp++) {
413 		if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
414 			break;
415 	}
416 	if (mnp >= resolve_lofs_mnt_max)
417 		return (0);
418 
419 	/*
420 	 * Convert this duplicate mount into a lofs mount.
421 	 */
422 	(void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
423 	    sizeof (fsptr->zone_fs_special));
424 	(void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
425 	    sizeof (fsptr->zone_fs_type));
426 	fsptr->zone_fs_raw[0] = '\0';
427 
428 	/*
429 	 * Discard all but one of the original options and set that to be the
430 	 * same set of options used for inherit package directory resources.
431 	 */
432 	optptr = fsptr->zone_fs_options;
433 	if (optptr == NULL) {
434 		optptr = malloc(sizeof (*optptr));
435 		if (optptr == NULL) {
436 			zerror(zlogp, B_TRUE, "cannot mount %s",
437 			    fsptr->zone_fs_dir);
438 			return (-1);
439 		}
440 	} else {
441 		while ((onext = optptr->zone_fsopt_next) != NULL) {
442 			optptr->zone_fsopt_next = onext->zone_fsopt_next;
443 			free(onext);
444 		}
445 	}
446 	(void) strcpy(optptr->zone_fsopt_opt, IPD_DEFAULT_OPTS);
447 	optptr->zone_fsopt_next = NULL;
448 	fsptr->zone_fs_options = optptr;
449 	return (0);
450 }
451 
452 static int
453 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode)
454 {
455 	char path[MAXPATHLEN];
456 	struct stat st;
457 
458 	if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
459 	    sizeof (path)) {
460 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
461 		    subdir);
462 		return (-1);
463 	}
464 
465 	if (lstat(path, &st) == 0) {
466 		/*
467 		 * We don't check the file mode since presumably the zone
468 		 * administrator may have had good reason to change the mode,
469 		 * and we don't need to second guess him.
470 		 */
471 		if (!S_ISDIR(st.st_mode)) {
472 			if (is_system_labeled() &&
473 			    S_ISREG(st.st_mode)) {
474 				/*
475 				 * The need to mount readonly copies of
476 				 * global zone /etc/ files is unique to
477 				 * Trusted Extensions.
478 				 */
479 				if (strncmp(subdir, "/etc/",
480 				    strlen("/etc/")) != 0) {
481 					zerror(zlogp, B_FALSE,
482 					    "%s is not in /etc", path);
483 					return (-1);
484 				}
485 			} else {
486 				zerror(zlogp, B_FALSE,
487 				    "%s is not a directory", path);
488 				return (-1);
489 			}
490 		}
491 	} else if (mkdirp(path, mode) != 0) {
492 		if (errno == EROFS)
493 			zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
494 			    "a read-only file system in this local zone.\nMake "
495 			    "sure %s exists in the global zone.", path, subdir);
496 		else
497 			zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
498 		return (-1);
499 	}
500 	return (0);
501 }
502 
503 /*
504  * Make /dev and various directories underneath it.
505  */
506 static int
507 make_dev_dirs(zlog_t *zlogp, const char *zonepath)
508 {
509 	int i;
510 
511 	for (i = 0; i < sizeof (dev_dirs) / sizeof (struct dir_info); i++) {
512 		if (make_one_dir(zlogp, zonepath, dev_dirs[i].dir_name,
513 		    dev_dirs[i].dir_mode) != 0)
514 			return (-1);
515 	}
516 	return (0);
517 }
518 
519 /*
520  * Make various sym-links underneath /dev.
521  */
522 static int
523 make_dev_links(zlog_t *zlogp, char *zonepath)
524 {
525 	int i;
526 
527 	for (i = 0; i < sizeof (dev_symlinks) / sizeof (struct symlink_info);
528 	    i++) {
529 		char dev[MAXPATHLEN];
530 		struct stat st;
531 
532 		(void) snprintf(dev, sizeof (dev), "%s%s", zonepath,
533 		    dev_symlinks[i].sl_source);
534 		if (lstat(dev, &st) == 0) {
535 			/*
536 			 * Try not to call unlink(2) on directories, since that
537 			 * makes UFS unhappy.
538 			 */
539 			if (S_ISDIR(st.st_mode)) {
540 				zerror(zlogp, B_FALSE, "symlink path %s is a "
541 				    "directory", dev_symlinks[i].sl_source);
542 				return (-1);
543 			}
544 			(void) unlink(dev);
545 		}
546 		if (symlink(dev_symlinks[i].sl_target, dev) != 0) {
547 			zerror(zlogp, B_TRUE, "could not setup %s->%s symlink",
548 			    dev_symlinks[i].sl_source,
549 			    dev_symlinks[i].sl_target);
550 			return (-1);
551 		}
552 	}
553 	return (0);
554 }
555 
556 /*
557  * Create various directories and sym-links under /dev.
558  */
559 static int
560 create_dev_files(zlog_t *zlogp)
561 {
562 	char zonepath[MAXPATHLEN];
563 
564 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
565 		zerror(zlogp, B_TRUE, "unable to determine zone root");
566 		return (-1);
567 	}
568 	if (zonecfg_in_alt_root())
569 		resolve_lofs(zlogp, zonepath, sizeof (zonepath));
570 
571 	if (make_dev_dirs(zlogp, zonepath) != 0)
572 		return (-1);
573 	if (make_dev_links(zlogp, zonepath) != 0)
574 		return (-1);
575 	return (0);
576 }
577 
578 static void
579 free_remote_fstypes(char **types)
580 {
581 	uint_t i;
582 
583 	if (types == NULL)
584 		return;
585 	for (i = 0; types[i] != NULL; i++)
586 		free(types[i]);
587 	free(types);
588 }
589 
590 static char **
591 get_remote_fstypes(zlog_t *zlogp)
592 {
593 	char **types = NULL;
594 	FILE *fp;
595 	char buf[MAXPATHLEN];
596 	char fstype[MAXPATHLEN];
597 	uint_t lines = 0;
598 	uint_t i;
599 
600 	if ((fp = fopen(DFSTYPES, "r")) == NULL) {
601 		zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
602 		return (NULL);
603 	}
604 	/*
605 	 * Count the number of lines
606 	 */
607 	while (fgets(buf, sizeof (buf), fp) != NULL)
608 		lines++;
609 	if (lines == 0)	/* didn't read anything; empty file */
610 		goto out;
611 	rewind(fp);
612 	/*
613 	 * Allocate enough space for a NULL-terminated array.
614 	 */
615 	types = calloc(lines + 1, sizeof (char *));
616 	if (types == NULL) {
617 		zerror(zlogp, B_TRUE, "memory allocation failed");
618 		goto out;
619 	}
620 	i = 0;
621 	while (fgets(buf, sizeof (buf), fp) != NULL) {
622 		/* LINTED - fstype is big enough to hold buf */
623 		if (sscanf(buf, "%s", fstype) == 0) {
624 			zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
625 			free_remote_fstypes(types);
626 			types = NULL;
627 			goto out;
628 		}
629 		types[i] = strdup(fstype);
630 		if (types[i] == NULL) {
631 			zerror(zlogp, B_TRUE, "memory allocation failed");
632 			free_remote_fstypes(types);
633 			types = NULL;
634 			goto out;
635 		}
636 		i++;
637 	}
638 out:
639 	(void) fclose(fp);
640 	return (types);
641 }
642 
643 static boolean_t
644 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
645 {
646 	uint_t i;
647 
648 	if (remote_fstypes == NULL)
649 		return (B_FALSE);
650 	for (i = 0; remote_fstypes[i] != NULL; i++) {
651 		if (strcmp(remote_fstypes[i], fstype) == 0)
652 			return (B_TRUE);
653 	}
654 	return (B_FALSE);
655 }
656 
657 /*
658  * This converts a zone root path (normally of the form .../root) to a Live
659  * Upgrade scratch zone root (of the form .../lu).
660  */
661 static void
662 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
663 {
664 	if (!isresolved && zonecfg_in_alt_root())
665 		resolve_lofs(zlogp, zroot, zrootlen);
666 	(void) strcpy(strrchr(zroot, '/') + 1, "lu");
667 }
668 
669 /*
670  * The general strategy for unmounting filesystems is as follows:
671  *
672  * - Remote filesystems may be dead, and attempting to contact them as
673  * part of a regular unmount may hang forever; we want to always try to
674  * forcibly unmount such filesystems and only fall back to regular
675  * unmounts if the filesystem doesn't support forced unmounts.
676  *
677  * - We don't want to unnecessarily corrupt metadata on local
678  * filesystems (ie UFS), so we want to start off with graceful unmounts,
679  * and only escalate to doing forced unmounts if we get stuck.
680  *
681  * We start off walking backwards through the mount table.  This doesn't
682  * give us strict ordering but ensures that we try to unmount submounts
683  * first.  We thus limit the number of failed umount2(2) calls.
684  *
685  * The mechanism for determining if we're stuck is to count the number
686  * of failed unmounts each iteration through the mount table.  This
687  * gives us an upper bound on the number of filesystems which remain
688  * mounted (autofs trigger nodes are dealt with separately).  If at the
689  * end of one unmount+autofs_cleanup cycle we still have the same number
690  * of mounts that we started out with, we're stuck and try a forced
691  * unmount.  If that fails (filesystem doesn't support forced unmounts)
692  * then we bail and are unable to teardown the zone.  If it succeeds,
693  * we're no longer stuck so we continue with our policy of trying
694  * graceful mounts first.
695  *
696  * Zone must be down (ie, no processes or threads active).
697  */
698 static int
699 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
700 {
701 	int error = 0;
702 	FILE *mnttab;
703 	struct mnttab *mnts;
704 	uint_t nmnt;
705 	char zroot[MAXPATHLEN + 1];
706 	size_t zrootlen;
707 	uint_t oldcount = UINT_MAX;
708 	boolean_t stuck = B_FALSE;
709 	char **remote_fstypes = NULL;
710 
711 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
712 		zerror(zlogp, B_FALSE, "unable to determine zone root");
713 		return (-1);
714 	}
715 	if (unmount_cmd)
716 		root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
717 
718 	(void) strcat(zroot, "/");
719 	zrootlen = strlen(zroot);
720 
721 	/*
722 	 * For Trusted Extensions unmount each higher level zone's mount
723 	 * of our zone's /export/home
724 	 */
725 	if (!unmount_cmd)
726 		tsol_unmounts(zlogp, zone_name);
727 
728 	if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
729 		zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
730 		return (-1);
731 	}
732 	/*
733 	 * Use our hacky mntfs ioctl so we see everything, even mounts with
734 	 * MS_NOMNTTAB.
735 	 */
736 	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
737 		zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
738 		error++;
739 		goto out;
740 	}
741 
742 	/*
743 	 * Build the list of remote fstypes so we know which ones we
744 	 * should forcibly unmount.
745 	 */
746 	remote_fstypes = get_remote_fstypes(zlogp);
747 	for (; /* ever */; ) {
748 		uint_t newcount = 0;
749 		boolean_t unmounted;
750 		struct mnttab *mnp;
751 		char *path;
752 		uint_t i;
753 
754 		mnts = NULL;
755 		nmnt = 0;
756 		/*
757 		 * MNTTAB gives us a way to walk through mounted
758 		 * filesystems; we need to be able to walk them in
759 		 * reverse order, so we build a list of all mounted
760 		 * filesystems.
761 		 */
762 		if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
763 		    &nmnt) != 0) {
764 			error++;
765 			goto out;
766 		}
767 		for (i = 0; i < nmnt; i++) {
768 			mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
769 			path = mnp->mnt_mountp;
770 			unmounted = B_FALSE;
771 			/*
772 			 * Try forced unmount first for remote filesystems.
773 			 *
774 			 * Not all remote filesystems support forced unmounts,
775 			 * so if this fails (ENOTSUP) we'll continue on
776 			 * and try a regular unmount.
777 			 */
778 			if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
779 				if (umount2(path, MS_FORCE) == 0)
780 					unmounted = B_TRUE;
781 			}
782 			/*
783 			 * Try forced unmount if we're stuck.
784 			 */
785 			if (stuck) {
786 				if (umount2(path, MS_FORCE) == 0) {
787 					unmounted = B_TRUE;
788 					stuck = B_FALSE;
789 				} else {
790 					/*
791 					 * The first failure indicates a
792 					 * mount we won't be able to get
793 					 * rid of automatically, so we
794 					 * bail.
795 					 */
796 					error++;
797 					zerror(zlogp, B_FALSE,
798 					    "unable to unmount '%s'", path);
799 					free_mnttable(mnts, nmnt);
800 					goto out;
801 				}
802 			}
803 			/*
804 			 * Try regular unmounts for everything else.
805 			 */
806 			if (!unmounted && umount2(path, 0) != 0)
807 				newcount++;
808 		}
809 		free_mnttable(mnts, nmnt);
810 
811 		if (newcount == 0)
812 			break;
813 		if (newcount >= oldcount) {
814 			/*
815 			 * Last round didn't unmount anything; we're stuck and
816 			 * should start trying forced unmounts.
817 			 */
818 			stuck = B_TRUE;
819 		}
820 		oldcount = newcount;
821 
822 		/*
823 		 * Autofs doesn't let you unmount its trigger nodes from
824 		 * userland so we have to tell the kernel to cleanup for us.
825 		 */
826 		if (autofs_cleanup(zoneid) != 0) {
827 			zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
828 			error++;
829 			goto out;
830 		}
831 	}
832 
833 out:
834 	free_remote_fstypes(remote_fstypes);
835 	(void) fclose(mnttab);
836 	return (error ? -1 : 0);
837 }
838 
839 static int
840 fs_compare(const void *m1, const void *m2)
841 {
842 	struct zone_fstab *i = (struct zone_fstab *)m1;
843 	struct zone_fstab *j = (struct zone_fstab *)m2;
844 
845 	return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
846 }
847 
848 /*
849  * Fork and exec (and wait for) the mentioned binary with the provided
850  * arguments.  Returns (-1) if something went wrong with fork(2) or exec(2),
851  * returns the exit status otherwise.
852  *
853  * If we were unable to exec the provided pathname (for whatever
854  * reason), we return the special token ZEXIT_EXEC.  The current value
855  * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
856  * consumers of this function; any future consumers must make sure this
857  * remains the case.
858  */
859 static int
860 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
861 {
862 	pid_t child_pid;
863 	int child_status = 0;
864 
865 	/*
866 	 * Do not let another thread localize a message while we are forking.
867 	 */
868 	(void) mutex_lock(&msglock);
869 	child_pid = fork();
870 	(void) mutex_unlock(&msglock);
871 	if (child_pid == -1) {
872 		zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
873 		return (-1);
874 	} else if (child_pid == 0) {
875 		closefrom(0);
876 		/* redirect stdin, stdout & stderr to /dev/null */
877 		(void) open("/dev/null", O_RDONLY);	/* stdin */
878 		(void) open("/dev/null", O_WRONLY);	/* stdout */
879 		(void) open("/dev/null", O_WRONLY);	/* stderr */
880 		(void) execv(path, argv);
881 		/*
882 		 * Since we are in the child, there is no point calling zerror()
883 		 * since there is nobody waiting to consume it.  So exit with a
884 		 * special code that the parent will recognize and call zerror()
885 		 * accordingly.
886 		 */
887 
888 		_exit(ZEXIT_EXEC);
889 	} else {
890 		(void) waitpid(child_pid, &child_status, 0);
891 	}
892 
893 	if (WIFSIGNALED(child_status)) {
894 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
895 		    "signal %d", path, WTERMSIG(child_status));
896 		return (-1);
897 	}
898 	assert(WIFEXITED(child_status));
899 	if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
900 		zerror(zlogp, B_FALSE, "failed to exec %s", path);
901 		return (-1);
902 	}
903 	return (WEXITSTATUS(child_status));
904 }
905 
906 static int
907 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
908 {
909 	char cmdbuf[MAXPATHLEN];
910 	char *argv[4];
911 	int status;
912 
913 	/*
914 	 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
915 	 * that would cost us an extra fork/exec without buying us anything.
916 	 */
917 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
918 	    > sizeof (cmdbuf)) {
919 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
920 		return (-1);
921 	}
922 
923 	argv[0] = "fsck";
924 	argv[1] = "-m";
925 	argv[2] = (char *)rawdev;
926 	argv[3] = NULL;
927 
928 	status = forkexec(zlogp, cmdbuf, argv);
929 	if (status == 0 || status == -1)
930 		return (status);
931 	zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
932 	    "run fsck manually", rawdev, status);
933 	return (-1);
934 }
935 
936 static int
937 domount(zlog_t *zlogp, const char *fstype, const char *opts,
938     const char *special, const char *directory)
939 {
940 	char cmdbuf[MAXPATHLEN];
941 	char *argv[6];
942 	int status;
943 
944 	/*
945 	 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
946 	 * that would cost us an extra fork/exec without buying us anything.
947 	 */
948 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
949 	    > sizeof (cmdbuf)) {
950 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
951 		return (-1);
952 	}
953 	argv[0] = "mount";
954 	if (opts[0] == '\0') {
955 		argv[1] = (char *)special;
956 		argv[2] = (char *)directory;
957 		argv[3] = NULL;
958 	} else {
959 		argv[1] = "-o";
960 		argv[2] = (char *)opts;
961 		argv[3] = (char *)special;
962 		argv[4] = (char *)directory;
963 		argv[5] = NULL;
964 	}
965 
966 	status = forkexec(zlogp, cmdbuf, argv);
967 	if (status == 0 || status == -1)
968 		return (status);
969 	if (opts[0] == '\0')
970 		zerror(zlogp, B_FALSE, "\"%s %s %s\" "
971 		    "failed with exit code %d",
972 		    cmdbuf, special, directory, status);
973 	else
974 		zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
975 		    "failed with exit code %d",
976 		    cmdbuf, opts, special, directory, status);
977 	return (-1);
978 }
979 
980 /*
981  * Make sure if a given path exists, it is not a sym-link, and is a directory.
982  */
983 static int
984 check_path(zlog_t *zlogp, const char *path)
985 {
986 	struct stat statbuf;
987 	char respath[MAXPATHLEN];
988 	int res;
989 
990 	if (lstat(path, &statbuf) != 0) {
991 		if (errno == ENOENT)
992 			return (0);
993 		zerror(zlogp, B_TRUE, "can't stat %s", path);
994 		return (-1);
995 	}
996 	if (S_ISLNK(statbuf.st_mode)) {
997 		zerror(zlogp, B_FALSE, "%s is a symlink", path);
998 		return (-1);
999 	}
1000 	if (!S_ISDIR(statbuf.st_mode)) {
1001 		if (is_system_labeled() && S_ISREG(statbuf.st_mode)) {
1002 			/*
1003 			 * The need to mount readonly copies of
1004 			 * global zone /etc/ files is unique to
1005 			 * Trusted Extensions.
1006 			 * The check for /etc/ via strstr() is to
1007 			 * allow paths like $ZONEROOT/etc/passwd
1008 			 */
1009 			if (strstr(path, "/etc/") == NULL) {
1010 				zerror(zlogp, B_FALSE,
1011 				    "%s is not in /etc", path);
1012 				return (-1);
1013 			}
1014 		} else {
1015 			zerror(zlogp, B_FALSE, "%s is not a directory", path);
1016 			return (-1);
1017 		}
1018 	}
1019 	if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
1020 		zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
1021 		return (-1);
1022 	}
1023 	respath[res] = '\0';
1024 	if (strcmp(path, respath) != 0) {
1025 		/*
1026 		 * We don't like ".."s and "."s throwing us off
1027 		 */
1028 		zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
1029 		return (-1);
1030 	}
1031 	return (0);
1032 }
1033 
1034 /*
1035  * Check every component of rootpath/relpath.  If any component fails (ie,
1036  * exists but isn't the canonical path to a directory), it is returned in
1037  * badpath, which is assumed to be at least of size MAXPATHLEN.
1038  *
1039  * Relpath must begin with '/'.
1040  */
1041 static boolean_t
1042 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *relpath)
1043 {
1044 	char abspath[MAXPATHLEN], *slashp;
1045 
1046 	/*
1047 	 * Make sure abspath has at least one '/' after its rootpath
1048 	 * component, and ends with '/'.
1049 	 */
1050 	if (snprintf(abspath, sizeof (abspath), "%s%s/", rootpath, relpath) >
1051 	    sizeof (abspath)) {
1052 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", rootpath,
1053 		    relpath);
1054 		return (B_FALSE);
1055 	}
1056 
1057 	slashp = &abspath[strlen(rootpath)];
1058 	assert(*slashp == '/');
1059 	do {
1060 		*slashp = '\0';
1061 		if (check_path(zlogp, abspath) != 0)
1062 			return (B_FALSE);
1063 		*slashp = '/';
1064 		slashp++;
1065 	} while ((slashp = strchr(slashp, '/')) != NULL);
1066 	return (B_TRUE);
1067 }
1068 
1069 static int
1070 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath)
1071 {
1072 	char    path[MAXPATHLEN];
1073 	char	specpath[MAXPATHLEN];
1074 	char    optstr[MAX_MNTOPT_STR];
1075 	zone_fsopt_t *optptr;
1076 
1077 	if (!valid_mount_path(zlogp, rootpath, fsptr->zone_fs_dir)) {
1078 		zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1079 		    rootpath, fsptr->zone_fs_dir);
1080 		return (-1);
1081 	}
1082 
1083 	if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1084 	    DEFAULT_DIR_MODE) != 0)
1085 		return (-1);
1086 
1087 	(void) snprintf(path, sizeof (path), "%s%s", rootpath,
1088 	    fsptr->zone_fs_dir);
1089 
1090 	if (strlen(fsptr->zone_fs_special) == 0) {
1091 		/*
1092 		 * A zero-length special is how we distinguish IPDs from
1093 		 * general-purpose FSs.  Make sure it mounts from a place that
1094 		 * can be seen via the alternate zone's root.
1095 		 */
1096 		if (snprintf(specpath, sizeof (specpath), "%s%s",
1097 		    zonecfg_get_root(), fsptr->zone_fs_dir) >=
1098 		    sizeof (specpath)) {
1099 			zerror(zlogp, B_FALSE, "cannot mount %s: path too "
1100 			    "long in alternate root", fsptr->zone_fs_dir);
1101 			return (-1);
1102 		}
1103 		if (zonecfg_in_alt_root())
1104 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1105 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS,
1106 		    specpath, path) != 0) {
1107 			zerror(zlogp, B_TRUE, "failed to loopback mount %s",
1108 			    specpath);
1109 			return (-1);
1110 		}
1111 		return (0);
1112 	}
1113 
1114 	/*
1115 	 * In general the strategy here is to do just as much verification as
1116 	 * necessary to avoid crashing or otherwise doing something bad; if the
1117 	 * administrator initiated the operation via zoneadm(1m), he'll get
1118 	 * auto-verification which will let him know what's wrong.  If he
1119 	 * modifies the zone configuration of a running zone and doesn't attempt
1120 	 * to verify that it's OK we won't crash but won't bother trying to be
1121 	 * too helpful either.  zoneadm verify is only a couple keystrokes away.
1122 	 */
1123 	if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1124 		zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1125 		    "invalid file-system type %s", fsptr->zone_fs_special,
1126 		    fsptr->zone_fs_dir, fsptr->zone_fs_type);
1127 		return (-1);
1128 	}
1129 
1130 	/*
1131 	 * If we're looking at an alternate root environment, then construct
1132 	 * read-only loopback mounts as necessary.  For all lofs mounts, make
1133 	 * sure that the 'special' entry points inside the alternate root.  (We
1134 	 * don't do this with other mounts, as devfs isn't in the alternate
1135 	 * root, and we need to assume the device environment is roughly the
1136 	 * same.)
1137 	 */
1138 	if (zonecfg_in_alt_root()) {
1139 		struct stat64 st;
1140 
1141 		if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1142 		    S_ISBLK(st.st_mode) &&
1143 		    check_lofs_needed(zlogp, fsptr) == -1)
1144 			return (-1);
1145 		if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1146 			if (snprintf(specpath, sizeof (specpath), "%s%s",
1147 			    zonecfg_get_root(), fsptr->zone_fs_special) >=
1148 			    sizeof (specpath)) {
1149 				zerror(zlogp, B_FALSE, "cannot mount %s: path "
1150 				    "too long in alternate root",
1151 				    fsptr->zone_fs_special);
1152 				return (-1);
1153 			}
1154 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1155 			(void) strlcpy(fsptr->zone_fs_special, specpath,
1156 			    sizeof (fsptr->zone_fs_special));
1157 		}
1158 	}
1159 
1160 	/*
1161 	 * Run 'fsck -m' if there's a device to fsck.
1162 	 */
1163 	if (fsptr->zone_fs_raw[0] != '\0' &&
1164 	    dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0)
1165 		return (-1);
1166 
1167 	/*
1168 	 * Build up mount option string.
1169 	 */
1170 	optstr[0] = '\0';
1171 	if (fsptr->zone_fs_options != NULL) {
1172 		(void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1173 		    sizeof (optstr));
1174 		for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1175 		    optptr != NULL; optptr = optptr->zone_fsopt_next) {
1176 			(void) strlcat(optstr, ",", sizeof (optstr));
1177 			(void) strlcat(optstr, optptr->zone_fsopt_opt,
1178 			    sizeof (optstr));
1179 		}
1180 	}
1181 	return (domount(zlogp, fsptr->zone_fs_type, optstr,
1182 	    fsptr->zone_fs_special, path));
1183 }
1184 
1185 static void
1186 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1187 {
1188 	uint_t i;
1189 
1190 	if (fsarray == NULL)
1191 		return;
1192 	for (i = 0; i < nelem; i++)
1193 		zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1194 	free(fsarray);
1195 }
1196 
1197 /*
1198  * This function constructs the miniroot-like "scratch zone" environment.  If
1199  * it returns B_FALSE, then the error has already been logged.
1200  */
1201 static boolean_t
1202 build_mounted(zlog_t *zlogp, char *rootpath, size_t rootlen,
1203     const char *zonepath)
1204 {
1205 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1206 	char luroot[MAXPATHLEN];
1207 	const char **cpp;
1208 	static const char *mkdirs[] = {
1209 		"/system", "/system/contract", "/proc", "/dev", "/tmp",
1210 		"/a", NULL
1211 	};
1212 	static const char *localdirs[] = {
1213 		"/etc", "/var", NULL
1214 	};
1215 	static const char *loopdirs[] = {
1216 		"/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1217 		"/usr", NULL
1218 	};
1219 	static const char *tmpdirs[] = {
1220 		"/tmp", "/var/run", NULL
1221 	};
1222 	FILE *fp;
1223 	struct stat st;
1224 	char *altstr;
1225 	uuid_t uuid;
1226 
1227 	/*
1228 	 * Construct a small Solaris environment, including the zone root
1229 	 * mounted on '/a' inside that environment.
1230 	 */
1231 	resolve_lofs(zlogp, rootpath, rootlen);
1232 	(void) snprintf(luroot, sizeof (luroot), "%s/lu", zonepath);
1233 	resolve_lofs(zlogp, luroot, sizeof (luroot));
1234 	(void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1235 	(void) symlink("./usr/bin", tmp);
1236 
1237 	/*
1238 	 * These are mostly special mount points; not handled here.  (See
1239 	 * zone_mount_early.)
1240 	 */
1241 	for (cpp = mkdirs; *cpp != NULL; cpp++) {
1242 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1243 		if (mkdir(tmp, 0755) != 0) {
1244 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1245 			return (B_FALSE);
1246 		}
1247 	}
1248 
1249 	/*
1250 	 * These are mounted read-write from the zone undergoing upgrade.  We
1251 	 * must be careful not to 'leak' things from the main system into the
1252 	 * zone, and this accomplishes that goal.
1253 	 */
1254 	for (cpp = localdirs; *cpp != NULL; cpp++) {
1255 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1256 		(void) snprintf(fromdir, sizeof (fromdir), "%s%s", rootpath,
1257 		    *cpp);
1258 		if (mkdir(tmp, 0755) != 0) {
1259 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1260 			return (B_FALSE);
1261 		}
1262 		if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp) != 0) {
1263 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1264 			    *cpp);
1265 			return (B_FALSE);
1266 		}
1267 	}
1268 
1269 	/*
1270 	 * These are things mounted read-only from the running system because
1271 	 * they contain binaries that must match system.
1272 	 */
1273 	for (cpp = loopdirs; *cpp != NULL; cpp++) {
1274 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1275 		if (mkdir(tmp, 0755) != 0) {
1276 			if (errno != EEXIST) {
1277 				zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1278 				return (B_FALSE);
1279 			}
1280 			if (lstat(tmp, &st) != 0) {
1281 				zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1282 				return (B_FALSE);
1283 			}
1284 			/*
1285 			 * Ignore any non-directories encountered.  These are
1286 			 * things that have been converted into symlinks
1287 			 * (/etc/fs and /etc/lib) and no longer need a lofs
1288 			 * fixup.
1289 			 */
1290 			if (!S_ISDIR(st.st_mode))
1291 				continue;
1292 		}
1293 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, *cpp,
1294 		    tmp) != 0) {
1295 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1296 			    *cpp);
1297 			return (B_FALSE);
1298 		}
1299 	}
1300 
1301 	/*
1302 	 * These are things with tmpfs mounted inside.
1303 	 */
1304 	for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1305 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1306 		if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
1307 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1308 			return (B_FALSE);
1309 		}
1310 		if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1311 			zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1312 			return (B_FALSE);
1313 		}
1314 	}
1315 
1316 	/*
1317 	 * This is here to support lucopy.  If there's an instance of this same
1318 	 * zone on the current running system, then we mount its root up as
1319 	 * read-only inside the scratch zone.
1320 	 */
1321 	(void) zonecfg_get_uuid(zone_name, uuid);
1322 	altstr = strdup(zonecfg_get_root());
1323 	if (altstr == NULL) {
1324 		zerror(zlogp, B_TRUE, "out of memory");
1325 		return (B_FALSE);
1326 	}
1327 	zonecfg_set_root("");
1328 	(void) strlcpy(tmp, zone_name, sizeof (tmp));
1329 	(void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1330 	if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1331 	    strcmp(fromdir, rootpath) != 0) {
1332 		(void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1333 		if (mkdir(tmp, 0755) != 0) {
1334 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1335 			return (B_FALSE);
1336 		}
1337 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, fromdir,
1338 		    tmp) != 0) {
1339 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1340 			    fromdir);
1341 			return (B_FALSE);
1342 		}
1343 	}
1344 	zonecfg_set_root(altstr);
1345 	free(altstr);
1346 
1347 	if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1348 		zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1349 		return (B_FALSE);
1350 	}
1351 	(void) ftruncate(fileno(fp), 0);
1352 	if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1353 		zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1354 	}
1355 	zonecfg_close_scratch(fp);
1356 	(void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1357 	if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1358 		return (B_FALSE);
1359 	(void) strlcpy(rootpath, tmp, rootlen);
1360 	return (B_TRUE);
1361 }
1362 
1363 static int
1364 mount_filesystems(zlog_t *zlogp, boolean_t mount_cmd)
1365 {
1366 	char	rootpath[MAXPATHLEN];
1367 	char	zonepath[MAXPATHLEN];
1368 	int	num_fs = 0, i;
1369 	struct zone_fstab fstab, *fs_ptr = NULL, *tmp_ptr;
1370 	struct zone_fstab *fsp;
1371 	zone_dochandle_t handle = NULL;
1372 	zone_state_t zstate;
1373 
1374 	if (zone_get_state(zone_name, &zstate) != Z_OK ||
1375 	    (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1376 		zerror(zlogp, B_FALSE,
1377 		    "zone must be in '%s' or '%s' state to mount file-systems",
1378 		    zone_state_str(ZONE_STATE_READY),
1379 		    zone_state_str(ZONE_STATE_MOUNTED));
1380 		goto bad;
1381 	}
1382 
1383 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1384 		zerror(zlogp, B_TRUE, "unable to determine zone path");
1385 		goto bad;
1386 	}
1387 
1388 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1389 		zerror(zlogp, B_TRUE, "unable to determine zone root");
1390 		goto bad;
1391 	}
1392 
1393 	if ((handle = zonecfg_init_handle()) == NULL) {
1394 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
1395 		goto bad;
1396 	}
1397 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1398 	    zonecfg_setfsent(handle) != Z_OK) {
1399 		zerror(zlogp, B_FALSE, "invalid configuration");
1400 		goto bad;
1401 	}
1402 
1403 	/*
1404 	 * /dev in the zone is loopback'd from the external /dev repository,
1405 	 * in order to provide a largely read-only semantic.  But because
1406 	 * processes in the zone need to be able to chown, chmod, etc. zone
1407 	 * /dev files, we can't use a 'ro' lofs mount.  Instead we use a
1408 	 * special mode just for zones, "zonedevfs".
1409 	 *
1410 	 * In the future we should front /dev with a full-fledged filesystem.
1411 	 */
1412 	num_fs++;
1413 	if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1414 		zerror(zlogp, B_TRUE, "memory allocation failed");
1415 		num_fs--;
1416 		goto bad;
1417 	}
1418 	fs_ptr = tmp_ptr;
1419 	fsp = &fs_ptr[num_fs - 1];
1420 	/*
1421 	 * Note that mount_one will prepend the alternate root to
1422 	 * zone_fs_special and do the necessary resolution, so all that is
1423 	 * needed here is to strip the root added by zone_get_zonepath.
1424 	 */
1425 	(void) strlcpy(fsp->zone_fs_dir, "/dev", sizeof (fsp->zone_fs_dir));
1426 	(void) snprintf(fsp->zone_fs_special, sizeof (fsp->zone_fs_special),
1427 	    "%s/dev", zonepath + strlen(zonecfg_get_root()));
1428 	fsp->zone_fs_raw[0] = '\0';
1429 	(void) strlcpy(fsp->zone_fs_type, MNTTYPE_LOFS,
1430 	    sizeof (fsp->zone_fs_type));
1431 	fsp->zone_fs_options = NULL;
1432 	if (zonecfg_add_fs_option(fsp, MNTOPT_LOFS_ZONEDEVFS) != Z_OK) {
1433 		zerror(zlogp, B_FALSE, "error adding property");
1434 		goto bad;
1435 	}
1436 
1437 	/*
1438 	 * Iterate through the rest of the filesystems, first the IPDs, then
1439 	 * the general FSs.  Sort them all, then mount them in sorted order.
1440 	 * This is to make sure the higher level directories (e.g., /usr)
1441 	 * get mounted before any beneath them (e.g., /usr/local).
1442 	 */
1443 	if (zonecfg_setipdent(handle) != Z_OK) {
1444 		zerror(zlogp, B_FALSE, "invalid configuration");
1445 		goto bad;
1446 	}
1447 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1448 		num_fs++;
1449 		if ((tmp_ptr = realloc(fs_ptr,
1450 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1451 			zerror(zlogp, B_TRUE, "memory allocation failed");
1452 			num_fs--;
1453 			(void) zonecfg_endipdent(handle);
1454 			goto bad;
1455 		}
1456 		fs_ptr = tmp_ptr;
1457 		fsp = &fs_ptr[num_fs - 1];
1458 		/*
1459 		 * IPDs logically only have a mount point; all other properties
1460 		 * are implied.
1461 		 */
1462 		(void) strlcpy(fsp->zone_fs_dir,
1463 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1464 		fsp->zone_fs_special[0] = '\0';
1465 		fsp->zone_fs_raw[0] = '\0';
1466 		fsp->zone_fs_type[0] = '\0';
1467 		fsp->zone_fs_options = NULL;
1468 	}
1469 	(void) zonecfg_endipdent(handle);
1470 
1471 	if (zonecfg_setfsent(handle) != Z_OK) {
1472 		zerror(zlogp, B_FALSE, "invalid configuration");
1473 		goto bad;
1474 	}
1475 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1476 		/*
1477 		 * ZFS filesystems will not be accessible under an alternate
1478 		 * root, since the pool will not be known.  Ignore them in this
1479 		 * case.
1480 		 */
1481 		if (mount_cmd && strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1482 			continue;
1483 
1484 		num_fs++;
1485 		if ((tmp_ptr = realloc(fs_ptr,
1486 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1487 			zerror(zlogp, B_TRUE, "memory allocation failed");
1488 			num_fs--;
1489 			(void) zonecfg_endfsent(handle);
1490 			goto bad;
1491 		}
1492 		fs_ptr = tmp_ptr;
1493 		fsp = &fs_ptr[num_fs - 1];
1494 		(void) strlcpy(fsp->zone_fs_dir,
1495 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1496 		(void) strlcpy(fsp->zone_fs_special, fstab.zone_fs_special,
1497 		    sizeof (fsp->zone_fs_special));
1498 		(void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1499 		    sizeof (fsp->zone_fs_raw));
1500 		(void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1501 		    sizeof (fsp->zone_fs_type));
1502 		fsp->zone_fs_options = fstab.zone_fs_options;
1503 	}
1504 	(void) zonecfg_endfsent(handle);
1505 	zonecfg_fini_handle(handle);
1506 	handle = NULL;
1507 
1508 	/*
1509 	 * If we're mounting a zone for administration, then we need to set up
1510 	 * the "/a" environment inside the zone so that the commands that run
1511 	 * in there have access to both the running system's utilities and the
1512 	 * to-be-modified zone's files.
1513 	 */
1514 	if (mount_cmd &&
1515 	    !build_mounted(zlogp, rootpath, sizeof (rootpath), zonepath))
1516 		goto bad;
1517 
1518 	qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1519 	for (i = 0; i < num_fs; i++) {
1520 		if (mount_cmd && strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1521 			size_t slen = strlen(rootpath) - 2;
1522 
1523 			/* /dev is special and always goes at the top */
1524 			rootpath[slen] = '\0';
1525 			if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1526 				goto bad;
1527 			rootpath[slen] = '/';
1528 			continue;
1529 		}
1530 		if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1531 			goto bad;
1532 	}
1533 
1534 	/*
1535 	 * For Trusted Extensions cross-mount each lower level /export/home
1536 	 */
1537 	if (!mount_cmd && tsol_mounts(zlogp, zone_name, rootpath) != 0)
1538 		goto bad;
1539 
1540 	free_fs_data(fs_ptr, num_fs);
1541 
1542 	/*
1543 	 * Everything looks fine.
1544 	 */
1545 	return (0);
1546 
1547 bad:
1548 	if (handle != NULL)
1549 		zonecfg_fini_handle(handle);
1550 	free_fs_data(fs_ptr, num_fs);
1551 	return (-1);
1552 }
1553 
1554 /* caller makes sure neither parameter is NULL */
1555 static int
1556 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1557 {
1558 	int prefixlen;
1559 
1560 	prefixlen = atoi(prefixstr);
1561 	if (prefixlen < 0 || prefixlen > maxprefixlen)
1562 		return (1);
1563 	while (prefixlen > 0) {
1564 		if (prefixlen >= 8) {
1565 			*maskstr++ = 0xFF;
1566 			prefixlen -= 8;
1567 			continue;
1568 		}
1569 		*maskstr |= 1 << (8 - prefixlen);
1570 		prefixlen--;
1571 	}
1572 	return (0);
1573 }
1574 
1575 /*
1576  * Tear down all interfaces belonging to the given zone.  This should
1577  * be called with the zone in a state other than "running", so that
1578  * interfaces can't be assigned to the zone after this returns.
1579  *
1580  * If anything goes wrong, log an error message and return an error.
1581  */
1582 static int
1583 unconfigure_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1584 {
1585 	struct lifnum lifn;
1586 	struct lifconf lifc;
1587 	struct lifreq *lifrp, lifrl;
1588 	int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1589 	int num_ifs, s, i, ret_code = 0;
1590 	uint_t bufsize;
1591 	char *buf = NULL;
1592 
1593 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1594 		zerror(zlogp, B_TRUE, "could not get socket");
1595 		ret_code = -1;
1596 		goto bad;
1597 	}
1598 	lifn.lifn_family = AF_UNSPEC;
1599 	lifn.lifn_flags = (int)lifc_flags;
1600 	if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1601 		zerror(zlogp, B_TRUE,
1602 		    "could not determine number of interfaces");
1603 		ret_code = -1;
1604 		goto bad;
1605 	}
1606 	num_ifs = lifn.lifn_count;
1607 	bufsize = num_ifs * sizeof (struct lifreq);
1608 	if ((buf = malloc(bufsize)) == NULL) {
1609 		zerror(zlogp, B_TRUE, "memory allocation failed");
1610 		ret_code = -1;
1611 		goto bad;
1612 	}
1613 	lifc.lifc_family = AF_UNSPEC;
1614 	lifc.lifc_flags = (int)lifc_flags;
1615 	lifc.lifc_len = bufsize;
1616 	lifc.lifc_buf = buf;
1617 	if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1618 		zerror(zlogp, B_TRUE, "could not get configured interfaces");
1619 		ret_code = -1;
1620 		goto bad;
1621 	}
1622 	lifrp = lifc.lifc_req;
1623 	for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1624 		(void) close(s);
1625 		if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1626 		    0) {
1627 			zerror(zlogp, B_TRUE, "%s: could not get socket",
1628 			    lifrl.lifr_name);
1629 			ret_code = -1;
1630 			continue;
1631 		}
1632 		(void) memset(&lifrl, 0, sizeof (lifrl));
1633 		(void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1634 		    sizeof (lifrl.lifr_name));
1635 		if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1636 			zerror(zlogp, B_TRUE,
1637 			    "%s: could not determine zone interface belongs to",
1638 			    lifrl.lifr_name);
1639 			ret_code = -1;
1640 			continue;
1641 		}
1642 		if (lifrl.lifr_zoneid == zone_id) {
1643 			if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1644 				zerror(zlogp, B_TRUE,
1645 				    "%s: could not remove interface",
1646 				    lifrl.lifr_name);
1647 				ret_code = -1;
1648 				continue;
1649 			}
1650 		}
1651 	}
1652 bad:
1653 	if (s > 0)
1654 		(void) close(s);
1655 	if (buf)
1656 		free(buf);
1657 	return (ret_code);
1658 }
1659 
1660 static union	sockunion {
1661 	struct	sockaddr sa;
1662 	struct	sockaddr_in sin;
1663 	struct	sockaddr_dl sdl;
1664 	struct	sockaddr_in6 sin6;
1665 } so_dst, so_ifp;
1666 
1667 static struct {
1668 	struct	rt_msghdr hdr;
1669 	char	space[512];
1670 } rtmsg;
1671 
1672 static int
1673 salen(struct sockaddr *sa)
1674 {
1675 	switch (sa->sa_family) {
1676 	case AF_INET:
1677 		return (sizeof (struct sockaddr_in));
1678 	case AF_LINK:
1679 		return (sizeof (struct sockaddr_dl));
1680 	case AF_INET6:
1681 		return (sizeof (struct sockaddr_in6));
1682 	default:
1683 		return (sizeof (struct sockaddr));
1684 	}
1685 }
1686 
1687 #define	ROUNDUP_LONG(a) \
1688 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1689 
1690 /*
1691  * Look up which zone is using a given IP address.  The address in question
1692  * is expected to have been stuffed into the structure to which lifr points
1693  * via a previous SIOCGLIFADDR ioctl().
1694  *
1695  * This is done using black router socket magic.
1696  *
1697  * Return the name of the zone on success or NULL on failure.
1698  *
1699  * This is a lot of code for a simple task; a new ioctl request to take care
1700  * of this might be a useful RFE.
1701  */
1702 
1703 static char *
1704 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
1705 {
1706 	static char answer[ZONENAME_MAX];
1707 	pid_t pid;
1708 	int s, rlen, l, i;
1709 	char *cp = rtmsg.space;
1710 	struct sockaddr_dl *ifp = NULL;
1711 	struct sockaddr *sa;
1712 	char save_if_name[LIFNAMSIZ];
1713 
1714 	answer[0] = '\0';
1715 
1716 	pid = getpid();
1717 	if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1718 		zerror(zlogp, B_TRUE, "could not get routing socket");
1719 		return (NULL);
1720 	}
1721 
1722 	if (lifr->lifr_addr.ss_family == AF_INET) {
1723 		struct sockaddr_in *sin4;
1724 
1725 		so_dst.sa.sa_family = AF_INET;
1726 		sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
1727 		so_dst.sin.sin_addr = sin4->sin_addr;
1728 	} else {
1729 		struct sockaddr_in6 *sin6;
1730 
1731 		so_dst.sa.sa_family = AF_INET6;
1732 		sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
1733 		so_dst.sin6.sin6_addr = sin6->sin6_addr;
1734 	}
1735 
1736 	so_ifp.sa.sa_family = AF_LINK;
1737 
1738 	(void) memset(&rtmsg, 0, sizeof (rtmsg));
1739 	rtmsg.hdr.rtm_type = RTM_GET;
1740 	rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
1741 	rtmsg.hdr.rtm_version = RTM_VERSION;
1742 	rtmsg.hdr.rtm_seq = ++rts_seqno;
1743 	rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
1744 
1745 	l = ROUNDUP_LONG(salen(&so_dst.sa));
1746 	(void) memmove(cp, &(so_dst), l);
1747 	cp += l;
1748 	l = ROUNDUP_LONG(salen(&so_ifp.sa));
1749 	(void) memmove(cp, &(so_ifp), l);
1750 	cp += l;
1751 
1752 	rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
1753 
1754 	if ((rlen = write(s, &rtmsg, l)) < 0) {
1755 		zerror(zlogp, B_TRUE, "writing to routing socket");
1756 		return (NULL);
1757 	} else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
1758 		zerror(zlogp, B_TRUE,
1759 		    "write to routing socket got only %d for len\n", rlen);
1760 		return (NULL);
1761 	}
1762 	do {
1763 		l = read(s, &rtmsg, sizeof (rtmsg));
1764 	} while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
1765 	    rtmsg.hdr.rtm_pid != pid));
1766 	if (l < 0) {
1767 		zerror(zlogp, B_TRUE, "reading from routing socket");
1768 		return (NULL);
1769 	}
1770 
1771 	if (rtmsg.hdr.rtm_version != RTM_VERSION) {
1772 		zerror(zlogp, B_FALSE,
1773 		    "routing message version %d not understood",
1774 		    rtmsg.hdr.rtm_version);
1775 		return (NULL);
1776 	}
1777 	if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
1778 		zerror(zlogp, B_FALSE, "message length mismatch, "
1779 		    "expected %d bytes, returned %d bytes",
1780 		    rtmsg.hdr.rtm_msglen, l);
1781 		return (NULL);
1782 	}
1783 	if (rtmsg.hdr.rtm_errno != 0)  {
1784 		errno = rtmsg.hdr.rtm_errno;
1785 		zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
1786 		return (NULL);
1787 	}
1788 	if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
1789 		zerror(zlogp, B_FALSE, "interface not found");
1790 		return (NULL);
1791 	}
1792 	cp = ((char *)(&rtmsg.hdr + 1));
1793 	for (i = 1; i != 0; i <<= 1) {
1794 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1795 		sa = (struct sockaddr *)cp;
1796 		if (i != RTA_IFP) {
1797 			if ((i & rtmsg.hdr.rtm_addrs) != 0)
1798 				cp += ROUNDUP_LONG(salen(sa));
1799 			continue;
1800 		}
1801 		if (sa->sa_family == AF_LINK &&
1802 		    ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
1803 			ifp = (struct sockaddr_dl *)sa;
1804 		break;
1805 	}
1806 	if (ifp == NULL) {
1807 		zerror(zlogp, B_FALSE, "interface could not be determined");
1808 		return (NULL);
1809 	}
1810 
1811 	/*
1812 	 * We need to set the I/F name to what we got above, then do the
1813 	 * appropriate ioctl to get its zone name.  But lifr->lifr_name is
1814 	 * used by the calling function to do a REMOVEIF, so if we leave the
1815 	 * "good" zone's I/F name in place, *that* I/F will be removed instead
1816 	 * of the bad one.  So we save the old (bad) I/F name before over-
1817 	 * writing it and doing the ioctl, then restore it after the ioctl.
1818 	 */
1819 	(void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
1820 	(void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
1821 	lifr->lifr_name[ifp->sdl_nlen] = '\0';
1822 	i = ioctl(s, SIOCGLIFZONE, lifr);
1823 	(void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
1824 	if (i < 0) {
1825 		zerror(zlogp, B_TRUE,
1826 		    "%s: could not determine the zone interface belongs to",
1827 		    lifr->lifr_name);
1828 		return (NULL);
1829 	}
1830 	if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
1831 		(void) snprintf(answer, sizeof (answer), "%d",
1832 		    lifr->lifr_zoneid);
1833 
1834 	if (strlen(answer) > 0)
1835 		return (answer);
1836 	return (NULL);
1837 }
1838 
1839 typedef struct mcast_rtmsg_s {
1840 	struct rt_msghdr	m_rtm;
1841 	union {
1842 		struct {
1843 			struct sockaddr_in	m_dst;
1844 			struct sockaddr_in	m_gw;
1845 			struct sockaddr_in	m_netmask;
1846 		} m_v4;
1847 		struct {
1848 			struct sockaddr_in6	m_dst;
1849 			struct sockaddr_in6	m_gw;
1850 			struct sockaddr_in6	m_netmask;
1851 		} m_v6;
1852 	} m_u;
1853 } mcast_rtmsg_t;
1854 #define	m_dst4		m_u.m_v4.m_dst
1855 #define	m_dst6		m_u.m_v6.m_dst
1856 #define	m_gw4		m_u.m_v4.m_gw
1857 #define	m_gw6		m_u.m_v6.m_gw
1858 #define	m_netmask4	m_u.m_v4.m_netmask
1859 #define	m_netmask6	m_u.m_v6.m_netmask
1860 
1861 /*
1862  * Configures a single interface: a new virtual interface is added, based on
1863  * the physical interface nwiftabptr->zone_nwif_physical, with the address
1864  * specified in nwiftabptr->zone_nwif_address, for zone zone_id.  Note that
1865  * the "address" can be an IPv6 address (with a /prefixlength required), an
1866  * IPv4 address (with a /prefixlength optional), or a name; for the latter,
1867  * an IPv4 name-to-address resolution will be attempted.
1868  *
1869  * A default interface route for multicast is created on the first IPv4 and
1870  * IPv6 interfaces (that have the IFF_MULTICAST flag set), respectively.
1871  * This should really be done in the init scripts if we ever allow zones to
1872  * modify the routing tables.
1873  *
1874  * If anything goes wrong, we log an detailed error message, attempt to tear
1875  * down whatever we set up and return an error.
1876  */
1877 static int
1878 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
1879     struct zone_nwiftab *nwiftabptr, boolean_t *mcast_rt_v4_setp,
1880     boolean_t *mcast_rt_v6_setp)
1881 {
1882 	struct lifreq lifr;
1883 	struct sockaddr_in netmask4;
1884 	struct sockaddr_in6 netmask6;
1885 	struct in_addr in4;
1886 	struct in6_addr in6;
1887 	sa_family_t af;
1888 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
1889 	mcast_rtmsg_t mcast_rtmsg;
1890 	int s;
1891 	int rs;
1892 	int rlen;
1893 	boolean_t got_netmask = B_FALSE;
1894 	char addrstr4[INET_ADDRSTRLEN];
1895 	int res;
1896 
1897 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
1898 	if (res != Z_OK) {
1899 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
1900 		    nwiftabptr->zone_nwif_address);
1901 		return (-1);
1902 	}
1903 	af = lifr.lifr_addr.ss_family;
1904 	if (af == AF_INET)
1905 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
1906 	else
1907 		in6 = ((struct sockaddr_in6 *)(&lifr.lifr_addr))->sin6_addr;
1908 
1909 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
1910 		zerror(zlogp, B_TRUE, "could not get socket");
1911 		return (-1);
1912 	}
1913 
1914 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
1915 	    sizeof (lifr.lifr_name));
1916 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
1917 		zerror(zlogp, B_TRUE, "%s: could not add interface",
1918 		    lifr.lifr_name);
1919 		(void) close(s);
1920 		return (-1);
1921 	}
1922 
1923 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
1924 		zerror(zlogp, B_TRUE,
1925 		    "%s: could not set IP address to %s",
1926 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
1927 		goto bad;
1928 	}
1929 
1930 	/* Preserve literal IPv4 address for later potential printing. */
1931 	if (af == AF_INET)
1932 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
1933 
1934 	lifr.lifr_zoneid = zone_id;
1935 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
1936 		zerror(zlogp, B_TRUE, "%s: could not place interface into zone",
1937 		    lifr.lifr_name);
1938 		goto bad;
1939 	}
1940 
1941 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
1942 		got_netmask = B_TRUE;	/* default setting will be correct */
1943 	} else {
1944 		if (af == AF_INET) {
1945 			/*
1946 			 * The IPv4 netmask can be determined either
1947 			 * directly if a prefix length was supplied with
1948 			 * the address or via the netmasks database.  Not
1949 			 * being able to determine it is a common failure,
1950 			 * but it often is not fatal to operation of the
1951 			 * interface.  In that case, a warning will be
1952 			 * printed after the rest of the interface's
1953 			 * parameters have been configured.
1954 			 */
1955 			(void) memset(&netmask4, 0, sizeof (netmask4));
1956 			if (slashp != NULL) {
1957 				if (addr2netmask(slashp + 1, V4_ADDR_LEN,
1958 				    (uchar_t *)&netmask4.sin_addr) != 0) {
1959 					*slashp = '/';
1960 					zerror(zlogp, B_FALSE,
1961 					    "%s: invalid prefix length in %s",
1962 					    lifr.lifr_name,
1963 					    nwiftabptr->zone_nwif_address);
1964 					goto bad;
1965 				}
1966 				got_netmask = B_TRUE;
1967 			} else if (getnetmaskbyaddr(in4,
1968 			    &netmask4.sin_addr) == 0) {
1969 				got_netmask = B_TRUE;
1970 			}
1971 			if (got_netmask) {
1972 				netmask4.sin_family = af;
1973 				(void) memcpy(&lifr.lifr_addr, &netmask4,
1974 				    sizeof (netmask4));
1975 			}
1976 		} else {
1977 			(void) memset(&netmask6, 0, sizeof (netmask6));
1978 			if (addr2netmask(slashp + 1, V6_ADDR_LEN,
1979 			    (uchar_t *)&netmask6.sin6_addr) != 0) {
1980 				*slashp = '/';
1981 				zerror(zlogp, B_FALSE,
1982 				    "%s: invalid prefix length in %s",
1983 				    lifr.lifr_name,
1984 				    nwiftabptr->zone_nwif_address);
1985 				goto bad;
1986 			}
1987 			got_netmask = B_TRUE;
1988 			netmask6.sin6_family = af;
1989 			(void) memcpy(&lifr.lifr_addr, &netmask6,
1990 			    sizeof (netmask6));
1991 		}
1992 		if (got_netmask &&
1993 		    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
1994 			zerror(zlogp, B_TRUE, "%s: could not set netmask",
1995 			    lifr.lifr_name);
1996 			goto bad;
1997 		}
1998 
1999 		/*
2000 		 * This doesn't set the broadcast address at all. Rather, it
2001 		 * gets, then sets the interface's address, relying on the fact
2002 		 * that resetting the address will reset the broadcast address.
2003 		 */
2004 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2005 			zerror(zlogp, B_TRUE, "%s: could not get address",
2006 			    lifr.lifr_name);
2007 			goto bad;
2008 		}
2009 		if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2010 			zerror(zlogp, B_TRUE,
2011 			    "%s: could not reset broadcast address",
2012 			    lifr.lifr_name);
2013 			goto bad;
2014 		}
2015 	}
2016 
2017 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2018 		zerror(zlogp, B_TRUE, "%s: could not get flags",
2019 		    lifr.lifr_name);
2020 		goto bad;
2021 	}
2022 	lifr.lifr_flags |= IFF_UP;
2023 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2024 		int save_errno = errno;
2025 		char *zone_using;
2026 
2027 		/*
2028 		 * If we failed with something other than EADDRNOTAVAIL,
2029 		 * then skip to the end.  Otherwise, look up our address,
2030 		 * then call a function to determine which zone is already
2031 		 * using that address.
2032 		 */
2033 		if (errno != EADDRNOTAVAIL) {
2034 			zerror(zlogp, B_TRUE,
2035 			    "%s: could not bring interface up", lifr.lifr_name);
2036 			goto bad;
2037 		}
2038 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2039 			zerror(zlogp, B_TRUE, "%s: could not get address",
2040 			    lifr.lifr_name);
2041 			goto bad;
2042 		}
2043 		zone_using = who_is_using(zlogp, &lifr);
2044 		errno = save_errno;
2045 		if (zone_using == NULL)
2046 			zerror(zlogp, B_TRUE,
2047 			    "%s: could not bring interface up", lifr.lifr_name);
2048 		else
2049 			zerror(zlogp, B_TRUE, "%s: could not bring interface "
2050 			    "up: address in use by zone '%s'", lifr.lifr_name,
2051 			    zone_using);
2052 		goto bad;
2053 	}
2054 	if ((lifr.lifr_flags & IFF_MULTICAST) && ((af == AF_INET &&
2055 	    mcast_rt_v4_setp != NULL && *mcast_rt_v4_setp == B_FALSE) ||
2056 	    (af == AF_INET6 &&
2057 	    mcast_rt_v6_setp != NULL && *mcast_rt_v6_setp == B_FALSE))) {
2058 		rs = socket(PF_ROUTE, SOCK_RAW, 0);
2059 		if (rs < 0) {
2060 			zerror(zlogp, B_TRUE, "%s: could not create "
2061 			    "routing socket", lifr.lifr_name);
2062 			goto bad;
2063 		}
2064 		(void) shutdown(rs, 0);
2065 		(void) memset((void *)&mcast_rtmsg, 0, sizeof (mcast_rtmsg_t));
2066 		mcast_rtmsg.m_rtm.rtm_msglen =  sizeof (struct rt_msghdr) +
2067 		    3 * (af == AF_INET ? sizeof (struct sockaddr_in) :
2068 		    sizeof (struct sockaddr_in6));
2069 		mcast_rtmsg.m_rtm.rtm_version = RTM_VERSION;
2070 		mcast_rtmsg.m_rtm.rtm_type = RTM_ADD;
2071 		mcast_rtmsg.m_rtm.rtm_flags = RTF_UP;
2072 		mcast_rtmsg.m_rtm.rtm_addrs =
2073 		    RTA_DST | RTA_GATEWAY | RTA_NETMASK;
2074 		mcast_rtmsg.m_rtm.rtm_seq = ++rts_seqno;
2075 		if (af == AF_INET) {
2076 			mcast_rtmsg.m_dst4.sin_family = AF_INET;
2077 			mcast_rtmsg.m_dst4.sin_addr.s_addr =
2078 			    htonl(INADDR_UNSPEC_GROUP);
2079 			mcast_rtmsg.m_gw4.sin_family = AF_INET;
2080 			mcast_rtmsg.m_gw4.sin_addr = in4;
2081 			mcast_rtmsg.m_netmask4.sin_family = AF_INET;
2082 			mcast_rtmsg.m_netmask4.sin_addr.s_addr =
2083 			    htonl(IN_CLASSD_NET);
2084 		} else {
2085 			mcast_rtmsg.m_dst6.sin6_family = AF_INET6;
2086 			mcast_rtmsg.m_dst6.sin6_addr.s6_addr[0] = 0xffU;
2087 			mcast_rtmsg.m_gw6.sin6_family = AF_INET6;
2088 			mcast_rtmsg.m_gw6.sin6_addr = in6;
2089 			mcast_rtmsg.m_netmask6.sin6_family = AF_INET6;
2090 			mcast_rtmsg.m_netmask6.sin6_addr.s6_addr[0] = 0xffU;
2091 		}
2092 		rlen = write(rs, (char *)&mcast_rtmsg,
2093 		    mcast_rtmsg.m_rtm.rtm_msglen);
2094 		if (rlen < mcast_rtmsg.m_rtm.rtm_msglen) {
2095 			if (rlen < 0) {
2096 				zerror(zlogp, B_TRUE, "%s: could not set "
2097 				    "default interface for multicast",
2098 				    lifr.lifr_name);
2099 			} else {
2100 				zerror(zlogp, B_FALSE, "%s: write to routing "
2101 				    "socket returned %d", lifr.lifr_name, rlen);
2102 			}
2103 			(void) close(rs);
2104 			goto bad;
2105 		}
2106 		if (af == AF_INET) {
2107 			*mcast_rt_v4_setp = B_TRUE;
2108 		} else {
2109 			*mcast_rt_v6_setp = B_TRUE;
2110 		}
2111 		(void) close(rs);
2112 	}
2113 
2114 	if (!got_netmask) {
2115 		/*
2116 		 * A common, but often non-fatal problem, is that the system
2117 		 * cannot find the netmask for an interface address. This is
2118 		 * often caused by it being only in /etc/inet/netmasks, but
2119 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2120 		 * in that. This doesn't show up at boot because the netmask
2121 		 * is obtained from /etc/inet/netmasks when no network
2122 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2123 		 * available. We warn the user here that something like this
2124 		 * has happened and we're just running with a default and
2125 		 * possible incorrect netmask.
2126 		 */
2127 		char buffer[INET6_ADDRSTRLEN];
2128 		void  *addr;
2129 
2130 		if (af == AF_INET)
2131 			addr = &((struct sockaddr_in *)
2132 			    (&lifr.lifr_addr))->sin_addr;
2133 		else
2134 			addr = &((struct sockaddr_in6 *)
2135 			    (&lifr.lifr_addr))->sin6_addr;
2136 
2137 		/* Find out what netmask interface is going to be using */
2138 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2139 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL)
2140 			goto bad;
2141 		zerror(zlogp, B_FALSE,
2142 		    "WARNING: %s: no matching subnet found in netmasks(4) for "
2143 		    "%s; using default of %s.",
2144 		    lifr.lifr_name, addrstr4, buffer);
2145 	}
2146 
2147 	(void) close(s);
2148 	return (Z_OK);
2149 bad:
2150 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2151 	(void) close(s);
2152 	return (-1);
2153 }
2154 
2155 /*
2156  * Sets up network interfaces based on information from the zone configuration.
2157  * An IPv4 loopback interface is set up "for free", modeling the global system.
2158  * If any of the configuration interfaces were IPv6, then an IPv6 loopback
2159  * address is set up as well.
2160  *
2161  * If anything goes wrong, we log a general error message, attempt to tear down
2162  * whatever we set up, and return an error.
2163  */
2164 static int
2165 configure_network_interfaces(zlog_t *zlogp)
2166 {
2167 	zone_dochandle_t handle;
2168 	struct zone_nwiftab nwiftab, loopback_iftab;
2169 	boolean_t saw_v6 = B_FALSE;
2170 	boolean_t mcast_rt_v4_set = B_FALSE;
2171 	boolean_t mcast_rt_v6_set = B_FALSE;
2172 	zoneid_t zoneid;
2173 
2174 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2175 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2176 		return (-1);
2177 	}
2178 
2179 	if ((handle = zonecfg_init_handle()) == NULL) {
2180 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2181 		return (-1);
2182 	}
2183 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2184 		zerror(zlogp, B_FALSE, "invalid configuration");
2185 		zonecfg_fini_handle(handle);
2186 		return (-1);
2187 	}
2188 	if (zonecfg_setnwifent(handle) == Z_OK) {
2189 		for (;;) {
2190 			struct in6_addr in6;
2191 
2192 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2193 				break;
2194 			if (configure_one_interface(zlogp, zoneid,
2195 			    &nwiftab, &mcast_rt_v4_set, &mcast_rt_v6_set) !=
2196 			    Z_OK) {
2197 				(void) zonecfg_endnwifent(handle);
2198 				zonecfg_fini_handle(handle);
2199 				return (-1);
2200 			}
2201 			if (inet_pton(AF_INET6, nwiftab.zone_nwif_address,
2202 			    &in6) == 1)
2203 				saw_v6 = B_TRUE;
2204 		}
2205 		(void) zonecfg_endnwifent(handle);
2206 	}
2207 	zonecfg_fini_handle(handle);
2208 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2209 	    sizeof (loopback_iftab.zone_nwif_physical));
2210 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2211 	    sizeof (loopback_iftab.zone_nwif_address));
2212 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab, NULL, NULL)
2213 	    != Z_OK) {
2214 		return (-1);
2215 	}
2216 	if (saw_v6) {
2217 		(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2218 		    sizeof (loopback_iftab.zone_nwif_address));
2219 		if (configure_one_interface(zlogp, zoneid,
2220 		    &loopback_iftab, NULL, NULL) != Z_OK) {
2221 			return (-1);
2222 		}
2223 	}
2224 	return (0);
2225 }
2226 
2227 static int
2228 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2229     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2230 {
2231 	int fd;
2232 	struct strioctl ioc;
2233 	tcp_ioc_abort_conn_t conn;
2234 	int error;
2235 
2236 	conn.ac_local = *local;
2237 	conn.ac_remote = *remote;
2238 	conn.ac_start = TCPS_SYN_SENT;
2239 	conn.ac_end = TCPS_TIME_WAIT;
2240 	conn.ac_zoneid = zoneid;
2241 
2242 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2243 	ioc.ic_timout = -1; /* infinite timeout */
2244 	ioc.ic_len = sizeof (conn);
2245 	ioc.ic_dp = (char *)&conn;
2246 
2247 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2248 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2249 		return (-1);
2250 	}
2251 
2252 	error = ioctl(fd, I_STR, &ioc);
2253 	(void) close(fd);
2254 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2255 		return (0);
2256 	return (-1);
2257 }
2258 
2259 static int
2260 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2261 {
2262 	struct sockaddr_storage l, r;
2263 	struct sockaddr_in *local, *remote;
2264 	struct sockaddr_in6 *local6, *remote6;
2265 	int error;
2266 
2267 	/*
2268 	 * Abort IPv4 connections.
2269 	 */
2270 	bzero(&l, sizeof (*local));
2271 	local = (struct sockaddr_in *)&l;
2272 	local->sin_family = AF_INET;
2273 	local->sin_addr.s_addr = INADDR_ANY;
2274 	local->sin_port = 0;
2275 
2276 	bzero(&r, sizeof (*remote));
2277 	remote = (struct sockaddr_in *)&r;
2278 	remote->sin_family = AF_INET;
2279 	remote->sin_addr.s_addr = INADDR_ANY;
2280 	remote->sin_port = 0;
2281 
2282 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2283 		return (error);
2284 
2285 	/*
2286 	 * Abort IPv6 connections.
2287 	 */
2288 	bzero(&l, sizeof (*local6));
2289 	local6 = (struct sockaddr_in6 *)&l;
2290 	local6->sin6_family = AF_INET6;
2291 	local6->sin6_port = 0;
2292 	local6->sin6_addr = in6addr_any;
2293 
2294 	bzero(&r, sizeof (*remote6));
2295 	remote6 = (struct sockaddr_in6 *)&r;
2296 	remote6->sin6_family = AF_INET6;
2297 	remote6->sin6_port = 0;
2298 	remote6->sin6_addr = in6addr_any;
2299 
2300 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2301 		return (error);
2302 	return (0);
2303 }
2304 
2305 static int
2306 devfsadm_call(zlog_t *zlogp, const char *arg)
2307 {
2308 	char *argv[4];
2309 	int status;
2310 
2311 	argv[0] = DEVFSADM;
2312 	argv[1] = (char *)arg;
2313 	argv[2] = zone_name;
2314 	argv[3] = NULL;
2315 	status = forkexec(zlogp, DEVFSADM_PATH, argv);
2316 	if (status == 0 || status == -1)
2317 		return (status);
2318 	zerror(zlogp, B_FALSE, "%s call (%s %s %s) unexpectedly returned %d",
2319 	    DEVFSADM, DEVFSADM_PATH, arg, zone_name, status);
2320 	return (-1);
2321 }
2322 
2323 static int
2324 devfsadm_register(zlog_t *zlogp)
2325 {
2326 	/*
2327 	 * Ready the zone's devices.
2328 	 */
2329 	return (devfsadm_call(zlogp, "-z"));
2330 }
2331 
2332 static int
2333 devfsadm_unregister(zlog_t *zlogp)
2334 {
2335 	return (devfsadm_call(zlogp, "-Z"));
2336 }
2337 
2338 static int
2339 get_privset(zlog_t *zlogp, priv_set_t *privs, boolean_t mount_cmd)
2340 {
2341 	int error = -1;
2342 	zone_dochandle_t handle;
2343 	char *privname = NULL;
2344 
2345 	if (mount_cmd) {
2346 		if (zonecfg_default_privset(privs) == Z_OK)
2347 			return (0);
2348 		zerror(zlogp, B_FALSE,
2349 		    "failed to determine the zone's default privilege set");
2350 		return (-1);
2351 	}
2352 
2353 	if ((handle = zonecfg_init_handle()) == NULL) {
2354 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2355 		return (-1);
2356 	}
2357 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2358 		zerror(zlogp, B_FALSE, "invalid configuration");
2359 		zonecfg_fini_handle(handle);
2360 		return (-1);
2361 	}
2362 
2363 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2364 	case Z_OK:
2365 		error = 0;
2366 		break;
2367 	case Z_PRIV_PROHIBITED:
2368 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2369 		    "within the zone's privilege set", privname);
2370 		break;
2371 	case Z_PRIV_REQUIRED:
2372 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2373 		    "from the zone's privilege set", privname);
2374 		break;
2375 	case Z_PRIV_UNKNOWN:
2376 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2377 		    "in the zone's privilege set", privname);
2378 		break;
2379 	default:
2380 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2381 		    "privilege set");
2382 		break;
2383 	}
2384 
2385 	free(privname);
2386 	zonecfg_fini_handle(handle);
2387 	return (error);
2388 }
2389 
2390 static int
2391 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2392 {
2393 	nvlist_t *nvl = NULL;
2394 	char *nvl_packed = NULL;
2395 	size_t nvl_size = 0;
2396 	nvlist_t **nvlv = NULL;
2397 	int rctlcount = 0;
2398 	int error = -1;
2399 	zone_dochandle_t handle;
2400 	struct zone_rctltab rctltab;
2401 	rctlblk_t *rctlblk = NULL;
2402 
2403 	*bufp = NULL;
2404 	*bufsizep = 0;
2405 
2406 	if ((handle = zonecfg_init_handle()) == NULL) {
2407 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2408 		return (-1);
2409 	}
2410 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2411 		zerror(zlogp, B_FALSE, "invalid configuration");
2412 		zonecfg_fini_handle(handle);
2413 		return (-1);
2414 	}
2415 
2416 	rctltab.zone_rctl_valptr = NULL;
2417 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2418 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2419 		goto out;
2420 	}
2421 
2422 	if (zonecfg_setrctlent(handle) != Z_OK) {
2423 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2424 		goto out;
2425 	}
2426 
2427 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2428 		zerror(zlogp, B_TRUE, "memory allocation failed");
2429 		goto out;
2430 	}
2431 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2432 		struct zone_rctlvaltab *rctlval;
2433 		uint_t i, count;
2434 		const char *name = rctltab.zone_rctl_name;
2435 
2436 		/* zoneadm should have already warned about unknown rctls. */
2437 		if (!zonecfg_is_rctl(name)) {
2438 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2439 			rctltab.zone_rctl_valptr = NULL;
2440 			continue;
2441 		}
2442 		count = 0;
2443 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2444 		    rctlval = rctlval->zone_rctlval_next) {
2445 			count++;
2446 		}
2447 		if (count == 0) {	/* ignore */
2448 			continue;	/* Nothing to free */
2449 		}
2450 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2451 			goto out;
2452 		i = 0;
2453 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2454 		    rctlval = rctlval->zone_rctlval_next, i++) {
2455 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2456 				zerror(zlogp, B_TRUE, "%s failed",
2457 				    "nvlist_alloc");
2458 				goto out;
2459 			}
2460 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2461 			    != Z_OK) {
2462 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2463 				    "(priv=%s,limit=%s,action=%s)",
2464 				    rctlval->zone_rctlval_priv,
2465 				    rctlval->zone_rctlval_limit,
2466 				    rctlval->zone_rctlval_action);
2467 				goto out;
2468 			}
2469 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2470 				zerror(zlogp, B_FALSE,
2471 				    "(priv=%s,limit=%s,action=%s) is not a "
2472 				    "valid value for rctl '%s'",
2473 				    rctlval->zone_rctlval_priv,
2474 				    rctlval->zone_rctlval_limit,
2475 				    rctlval->zone_rctlval_action,
2476 				    name);
2477 				goto out;
2478 			}
2479 			if (nvlist_add_uint64(nvlv[i], "privilege",
2480 			    rctlblk_get_privilege(rctlblk)) != 0) {
2481 				zerror(zlogp, B_FALSE, "%s failed",
2482 				    "nvlist_add_uint64");
2483 				goto out;
2484 			}
2485 			if (nvlist_add_uint64(nvlv[i], "limit",
2486 			    rctlblk_get_value(rctlblk)) != 0) {
2487 				zerror(zlogp, B_FALSE, "%s failed",
2488 				    "nvlist_add_uint64");
2489 				goto out;
2490 			}
2491 			if (nvlist_add_uint64(nvlv[i], "action",
2492 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
2493 			    != 0) {
2494 				zerror(zlogp, B_FALSE, "%s failed",
2495 				    "nvlist_add_uint64");
2496 				goto out;
2497 			}
2498 		}
2499 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2500 		rctltab.zone_rctl_valptr = NULL;
2501 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
2502 		    != 0) {
2503 			zerror(zlogp, B_FALSE, "%s failed",
2504 			    "nvlist_add_nvlist_array");
2505 			goto out;
2506 		}
2507 		for (i = 0; i < count; i++)
2508 			nvlist_free(nvlv[i]);
2509 		free(nvlv);
2510 		nvlv = NULL;
2511 		rctlcount++;
2512 	}
2513 	(void) zonecfg_endrctlent(handle);
2514 
2515 	if (rctlcount == 0) {
2516 		error = 0;
2517 		goto out;
2518 	}
2519 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
2520 	    != 0) {
2521 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
2522 		goto out;
2523 	}
2524 
2525 	error = 0;
2526 	*bufp = nvl_packed;
2527 	*bufsizep = nvl_size;
2528 
2529 out:
2530 	free(rctlblk);
2531 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2532 	if (error && nvl_packed != NULL)
2533 		free(nvl_packed);
2534 	if (nvl != NULL)
2535 		nvlist_free(nvl);
2536 	if (nvlv != NULL)
2537 		free(nvlv);
2538 	if (handle != NULL)
2539 		zonecfg_fini_handle(handle);
2540 	return (error);
2541 }
2542 
2543 static int
2544 get_zone_pool(zlog_t *zlogp, char *poolbuf, size_t bufsz)
2545 {
2546 	zone_dochandle_t handle;
2547 	int error;
2548 
2549 	if ((handle = zonecfg_init_handle()) == NULL) {
2550 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2551 		return (Z_NOMEM);
2552 	}
2553 	error = zonecfg_get_snapshot_handle(zone_name, handle);
2554 	if (error != Z_OK) {
2555 		zerror(zlogp, B_FALSE, "invalid configuration");
2556 		zonecfg_fini_handle(handle);
2557 		return (error);
2558 	}
2559 	error = zonecfg_get_pool(handle, poolbuf, bufsz);
2560 	zonecfg_fini_handle(handle);
2561 	return (error);
2562 }
2563 
2564 static int
2565 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2566 {
2567 	zone_dochandle_t handle;
2568 	struct zone_dstab dstab;
2569 	size_t total, offset, len;
2570 	int error = -1;
2571 	char *str;
2572 
2573 	*bufp = NULL;
2574 	*bufsizep = 0;
2575 
2576 	if ((handle = zonecfg_init_handle()) == NULL) {
2577 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2578 		return (-1);
2579 	}
2580 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2581 		zerror(zlogp, B_FALSE, "invalid configuration");
2582 		zonecfg_fini_handle(handle);
2583 		return (-1);
2584 	}
2585 
2586 	if (zonecfg_setdsent(handle) != Z_OK) {
2587 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
2588 		goto out;
2589 	}
2590 
2591 	total = 0;
2592 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
2593 		total += strlen(dstab.zone_dataset_name) + 1;
2594 	(void) zonecfg_enddsent(handle);
2595 
2596 	if (total == 0) {
2597 		error = 0;
2598 		goto out;
2599 	}
2600 
2601 	if ((str = malloc(total)) == NULL) {
2602 		zerror(zlogp, B_TRUE, "memory allocation failed");
2603 		goto out;
2604 	}
2605 
2606 	if (zonecfg_setdsent(handle) != Z_OK) {
2607 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
2608 		goto out;
2609 	}
2610 	offset = 0;
2611 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2612 		len = strlen(dstab.zone_dataset_name);
2613 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
2614 		    sizeof (dstab.zone_dataset_name) - offset);
2615 		offset += len;
2616 		if (offset != total - 1)
2617 			str[offset++] = ',';
2618 	}
2619 	(void) zonecfg_enddsent(handle);
2620 
2621 	error = 0;
2622 	*bufp = str;
2623 	*bufsizep = total;
2624 
2625 out:
2626 	if (error != 0 && str != NULL)
2627 		free(str);
2628 	if (handle != NULL)
2629 		zonecfg_fini_handle(handle);
2630 
2631 	return (error);
2632 }
2633 
2634 static int
2635 validate_datasets(zlog_t *zlogp)
2636 {
2637 	zone_dochandle_t handle;
2638 	struct zone_dstab dstab;
2639 	zfs_handle_t *zhp;
2640 	libzfs_handle_t *hdl;
2641 
2642 	if ((handle = zonecfg_init_handle()) == NULL) {
2643 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2644 		return (-1);
2645 	}
2646 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2647 		zerror(zlogp, B_FALSE, "invalid configuration");
2648 		zonecfg_fini_handle(handle);
2649 		return (-1);
2650 	}
2651 
2652 	if (zonecfg_setdsent(handle) != Z_OK) {
2653 		zerror(zlogp, B_FALSE, "invalid configuration");
2654 		zonecfg_fini_handle(handle);
2655 		return (-1);
2656 	}
2657 
2658 	if ((hdl = libzfs_init()) == NULL) {
2659 		zerror(zlogp, B_FALSE, "opening ZFS library");
2660 		zonecfg_fini_handle(handle);
2661 		return (-1);
2662 	}
2663 
2664 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2665 
2666 		if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
2667 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
2668 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
2669 			    dstab.zone_dataset_name);
2670 			zonecfg_fini_handle(handle);
2671 			libzfs_fini(hdl);
2672 			return (-1);
2673 		}
2674 
2675 		/*
2676 		 * Automatically set the 'zoned' property.  We check the value
2677 		 * first because we'll get EPERM if it is already set.
2678 		 */
2679 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
2680 		    zfs_prop_set(zhp, ZFS_PROP_ZONED, "on") != 0) {
2681 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
2682 			    "property for ZFS dataset '%s'\n",
2683 			    dstab.zone_dataset_name);
2684 			zonecfg_fini_handle(handle);
2685 			zfs_close(zhp);
2686 			libzfs_fini(hdl);
2687 			return (-1);
2688 		}
2689 
2690 		zfs_close(zhp);
2691 	}
2692 	(void) zonecfg_enddsent(handle);
2693 
2694 	zonecfg_fini_handle(handle);
2695 	libzfs_fini(hdl);
2696 
2697 	return (0);
2698 }
2699 
2700 static int
2701 bind_to_pool(zlog_t *zlogp, zoneid_t zoneid)
2702 {
2703 	pool_conf_t *poolconf;
2704 	pool_t *pool;
2705 	char poolname[MAXPATHLEN];
2706 	int status;
2707 	int error;
2708 
2709 	/*
2710 	 * Find the pool mentioned in the zone configuration, and bind to it.
2711 	 */
2712 	error = get_zone_pool(zlogp, poolname, sizeof (poolname));
2713 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
2714 		/*
2715 		 * The property is not set on the zone, so the pool
2716 		 * should be bound to the default pool.  But that's
2717 		 * already done by the kernel, so we can just return.
2718 		 */
2719 		return (0);
2720 	}
2721 	if (error != Z_OK) {
2722 		/*
2723 		 * Not an error, even though it shouldn't be happening.
2724 		 */
2725 		zerror(zlogp, B_FALSE,
2726 		    "WARNING: unable to retrieve default pool.");
2727 		return (0);
2728 	}
2729 	/*
2730 	 * Don't do anything if pools aren't enabled.
2731 	 */
2732 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
2733 		zerror(zlogp, B_FALSE, "WARNING: pools facility not active; "
2734 		    "zone will not be bound to pool '%s'.", poolname);
2735 		return (0);
2736 	}
2737 	/*
2738 	 * Try to provide a sane error message if the requested pool doesn't
2739 	 * exist.
2740 	 */
2741 	if ((poolconf = pool_conf_alloc()) == NULL) {
2742 		zerror(zlogp, B_FALSE, "%s failed", "pool_conf_alloc");
2743 		return (-1);
2744 	}
2745 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
2746 	    PO_SUCCESS) {
2747 		zerror(zlogp, B_FALSE, "%s failed", "pool_conf_open");
2748 		pool_conf_free(poolconf);
2749 		return (-1);
2750 	}
2751 	pool = pool_get_pool(poolconf, poolname);
2752 	(void) pool_conf_close(poolconf);
2753 	pool_conf_free(poolconf);
2754 	if (pool == NULL) {
2755 		zerror(zlogp, B_FALSE, "WARNING: pool '%s' not found; "
2756 		    "using default pool.", poolname);
2757 		return (0);
2758 	}
2759 	/*
2760 	 * Bind the zone to the pool.
2761 	 */
2762 	if (pool_set_binding(poolname, P_ZONEID, zoneid) != PO_SUCCESS) {
2763 		zerror(zlogp, B_FALSE, "WARNING: unable to bind to pool '%s'; "
2764 		    "using default pool.", poolname);
2765 	}
2766 	return (0);
2767 }
2768 
2769 /*
2770  * Mount lower level home directories into/from current zone
2771  * Share exported directories specified in dfstab for zone
2772  */
2773 static int
2774 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
2775 {
2776 	zoneid_t *zids = NULL;
2777 	priv_set_t *zid_privs;
2778 	const priv_impl_info_t *ip = NULL;
2779 	uint_t nzents_saved;
2780 	uint_t nzents;
2781 	int i;
2782 	char readonly[] = "ro";
2783 	struct zone_fstab lower_fstab;
2784 	char *argv[4];
2785 
2786 	if (!is_system_labeled())
2787 		return (0);
2788 
2789 	if (zid_label == NULL) {
2790 		zid_label = m_label_alloc(MAC_LABEL);
2791 		if (zid_label == NULL)
2792 			return (-1);
2793 	}
2794 
2795 	/* Make sure our zone has an /export/home dir */
2796 	(void) make_one_dir(zlogp, rootpath, "/export/home",
2797 	    DEFAULT_DIR_MODE);
2798 
2799 	lower_fstab.zone_fs_raw[0] = '\0';
2800 	(void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
2801 	    sizeof (lower_fstab.zone_fs_type));
2802 	lower_fstab.zone_fs_options = NULL;
2803 	(void) zonecfg_add_fs_option(&lower_fstab, readonly);
2804 
2805 	/*
2806 	 * Get the list of zones from the kernel
2807 	 */
2808 	if (zone_list(NULL, &nzents) != 0) {
2809 		zerror(zlogp, B_TRUE, "unable to list zones");
2810 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
2811 		return (-1);
2812 	}
2813 again:
2814 	if (nzents == 0) {
2815 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
2816 		return (-1);
2817 	}
2818 
2819 	zids = malloc(nzents * sizeof (zoneid_t));
2820 	if (zids == NULL) {
2821 		zerror(zlogp, B_TRUE, "unable to allocate memory");
2822 		return (-1);
2823 	}
2824 	nzents_saved = nzents;
2825 
2826 	if (zone_list(zids, &nzents) != 0) {
2827 		zerror(zlogp, B_TRUE, "unable to list zones");
2828 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
2829 		free(zids);
2830 		return (-1);
2831 	}
2832 	if (nzents != nzents_saved) {
2833 		/* list changed, try again */
2834 		free(zids);
2835 		goto again;
2836 	}
2837 
2838 	ip = getprivimplinfo();
2839 	if ((zid_privs = priv_allocset()) == NULL) {
2840 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
2841 		zonecfg_free_fs_option_list(
2842 		    lower_fstab.zone_fs_options);
2843 		free(zids);
2844 		return (-1);
2845 	}
2846 
2847 	for (i = 0; i < nzents; i++) {
2848 		char zid_name[ZONENAME_MAX];
2849 		zone_state_t zid_state;
2850 		char zid_rpath[MAXPATHLEN];
2851 		struct stat stat_buf;
2852 
2853 		if (zids[i] == GLOBAL_ZONEID)
2854 			continue;
2855 
2856 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
2857 			continue;
2858 
2859 		/*
2860 		 * Do special setup for the zone we are booting
2861 		 */
2862 		if (strcmp(zid_name, zone_name) == 0) {
2863 			struct zone_fstab autofs_fstab;
2864 			char map_path[MAXPATHLEN];
2865 			int fd;
2866 
2867 			/*
2868 			 * Create auto_home_<zone> map for this zone
2869 			 * in the global zone. The local zone entry
2870 			 * will be created by automount when the zone
2871 			 * is booted.
2872 			 */
2873 
2874 			(void) snprintf(autofs_fstab.zone_fs_special,
2875 			    MAXPATHLEN, "auto_home_%s", zid_name);
2876 
2877 			(void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
2878 			    "/zone/%s/home", zid_name);
2879 
2880 			(void) snprintf(map_path, sizeof (map_path),
2881 			    "/etc/%s", autofs_fstab.zone_fs_special);
2882 			/*
2883 			 * If the map file doesn't exist create a template
2884 			 */
2885 			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
2886 			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
2887 				int len;
2888 				char map_rec[MAXPATHLEN];
2889 
2890 				len = snprintf(map_rec, sizeof (map_rec),
2891 				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
2892 				    autofs_fstab.zone_fs_special, rootpath);
2893 				(void) write(fd, map_rec, len);
2894 				(void) close(fd);
2895 			}
2896 
2897 			/*
2898 			 * Mount auto_home_<zone> in the global zone if absent.
2899 			 * If it's already of type autofs, then
2900 			 * don't mount it again.
2901 			 */
2902 			if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
2903 			    strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
2904 				char optstr[] = "indirect,ignore,nobrowse";
2905 
2906 				(void) make_one_dir(zlogp, "",
2907 				    autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE);
2908 
2909 				/*
2910 				 * Mount will fail if automounter has already
2911 				 * processed the auto_home_<zonename> map
2912 				 */
2913 				(void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
2914 				    autofs_fstab.zone_fs_special,
2915 				    autofs_fstab.zone_fs_dir);
2916 			}
2917 			continue;
2918 		}
2919 
2920 
2921 		if (zone_get_state(zid_name, &zid_state) != Z_OK ||
2922 		    (zid_state != ZONE_STATE_READY &&
2923 		    zid_state != ZONE_STATE_RUNNING))
2924 			/* Skip over zones without mounted filesystems */
2925 			continue;
2926 
2927 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
2928 		    sizeof (m_label_t)) < 0)
2929 			/* Skip over zones with unspecified label */
2930 			continue;
2931 
2932 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
2933 		    sizeof (zid_rpath)) == -1)
2934 			/* Skip over zones with bad path */
2935 			continue;
2936 
2937 		if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
2938 		    sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
2939 			/* Skip over zones with bad privs */
2940 			continue;
2941 
2942 		/*
2943 		 * Reading down is valid according to our label model
2944 		 * but some customers want to disable it because it
2945 		 * allows execute down and other possible attacks.
2946 		 * Therefore, we restrict this feature to zones that
2947 		 * have the NET_MAC_AWARE privilege which is required
2948 		 * for NFS read-down semantics.
2949 		 */
2950 		if ((bldominates(zlabel, zid_label)) &&
2951 		    (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
2952 			/*
2953 			 * Our zone dominates this one.
2954 			 * Create a lofs mount from lower zone's /export/home
2955 			 */
2956 			(void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
2957 			    "%s/zone/%s/export/home", rootpath, zid_name);
2958 
2959 			/*
2960 			 * If the target is already an LOFS mount
2961 			 * then don't do it again.
2962 			 */
2963 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
2964 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
2965 
2966 				if (snprintf(lower_fstab.zone_fs_special,
2967 				    MAXPATHLEN, "%s/export",
2968 				    zid_rpath) > MAXPATHLEN)
2969 					continue;
2970 
2971 				/*
2972 				 * Make sure the lower-level home exists
2973 				 */
2974 				if (make_one_dir(zlogp,
2975 				    lower_fstab.zone_fs_special,
2976 				    "/home", DEFAULT_DIR_MODE) != 0)
2977 					continue;
2978 
2979 				(void) strlcat(lower_fstab.zone_fs_special,
2980 				    "/home", MAXPATHLEN);
2981 
2982 				/*
2983 				 * Mount can fail because the lower-level
2984 				 * zone may have already done a mount up.
2985 				 */
2986 				(void) mount_one(zlogp, &lower_fstab, "");
2987 			}
2988 		} else if ((bldominates(zid_label, zlabel)) &&
2989 		    (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
2990 			/*
2991 			 * This zone dominates our zone.
2992 			 * Create a lofs mount from our zone's /export/home
2993 			 */
2994 			if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
2995 			    "%s/zone/%s/export/home", zid_rpath,
2996 			    zone_name) > MAXPATHLEN)
2997 				continue;
2998 
2999 			/*
3000 			 * If the target is already an LOFS mount
3001 			 * then don't do it again.
3002 			 */
3003 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3004 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3005 
3006 				(void) snprintf(lower_fstab.zone_fs_special,
3007 				    MAXPATHLEN, "%s/export/home", rootpath);
3008 
3009 				/*
3010 				 * Mount can fail because the higher-level
3011 				 * zone may have already done a mount down.
3012 				 */
3013 				(void) mount_one(zlogp, &lower_fstab, "");
3014 			}
3015 		}
3016 	}
3017 	zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3018 	priv_freeset(zid_privs);
3019 	free(zids);
3020 
3021 	/*
3022 	 * Now share any exported directories from this zone.
3023 	 * Each zone can have its own dfstab.
3024 	 */
3025 
3026 	argv[0] = "zoneshare";
3027 	argv[1] = "-z";
3028 	argv[2] = zone_name;
3029 	argv[3] = NULL;
3030 
3031 	(void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
3032 	/* Don't check for errors since they don't affect the zone */
3033 
3034 	return (0);
3035 }
3036 
3037 /*
3038  * Unmount lofs mounts from higher level zones
3039  * Unshare nfs exported directories
3040  */
3041 static void
3042 tsol_unmounts(zlog_t *zlogp, char *zone_name)
3043 {
3044 	zoneid_t *zids = NULL;
3045 	uint_t nzents_saved;
3046 	uint_t nzents;
3047 	int i;
3048 	char *argv[4];
3049 	char path[MAXPATHLEN];
3050 
3051 	if (!is_system_labeled())
3052 		return;
3053 
3054 	/*
3055 	 * Get the list of zones from the kernel
3056 	 */
3057 	if (zone_list(NULL, &nzents) != 0) {
3058 		return;
3059 	}
3060 
3061 	if (zid_label == NULL) {
3062 		zid_label = m_label_alloc(MAC_LABEL);
3063 		if (zid_label == NULL)
3064 			return;
3065 	}
3066 
3067 again:
3068 	if (nzents == 0)
3069 		return;
3070 
3071 	zids = malloc(nzents * sizeof (zoneid_t));
3072 	if (zids == NULL) {
3073 		zerror(zlogp, B_TRUE, "unable to allocate memory");
3074 		return;
3075 	}
3076 	nzents_saved = nzents;
3077 
3078 	if (zone_list(zids, &nzents) != 0) {
3079 		free(zids);
3080 		return;
3081 	}
3082 	if (nzents != nzents_saved) {
3083 		/* list changed, try again */
3084 		free(zids);
3085 		goto again;
3086 	}
3087 
3088 	for (i = 0; i < nzents; i++) {
3089 		char zid_name[ZONENAME_MAX];
3090 		zone_state_t zid_state;
3091 		char zid_rpath[MAXPATHLEN];
3092 
3093 		if (zids[i] == GLOBAL_ZONEID)
3094 			continue;
3095 
3096 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3097 			continue;
3098 
3099 		/*
3100 		 * Skip the zone we are halting
3101 		 */
3102 		if (strcmp(zid_name, zone_name) == 0)
3103 			continue;
3104 
3105 		if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
3106 		    sizeof (zid_state)) < 0) ||
3107 		    (zid_state < ZONE_IS_READY))
3108 			/* Skip over zones without mounted filesystems */
3109 			continue;
3110 
3111 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3112 		    sizeof (m_label_t)) < 0)
3113 			/* Skip over zones with unspecified label */
3114 			continue;
3115 
3116 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3117 		    sizeof (zid_rpath)) == -1)
3118 			/* Skip over zones with bad path */
3119 			continue;
3120 
3121 		if (zlabel != NULL && bldominates(zid_label, zlabel)) {
3122 			/*
3123 			 * This zone dominates our zone.
3124 			 * Unmount the lofs mount of our zone's /export/home
3125 			 */
3126 
3127 			if (snprintf(path, MAXPATHLEN,
3128 			    "%s/zone/%s/export/home", zid_rpath,
3129 			    zone_name) > MAXPATHLEN)
3130 				continue;
3131 
3132 			/* Skip over mount failures */
3133 			(void) umount(path);
3134 		}
3135 	}
3136 	free(zids);
3137 
3138 	/*
3139 	 * Unmount global zone autofs trigger for this zone
3140 	 */
3141 	(void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
3142 	/* Skip over mount failures */
3143 	(void) umount(path);
3144 
3145 	/*
3146 	 * Next unshare any exported directories from this zone.
3147 	 */
3148 
3149 	argv[0] = "zoneunshare";
3150 	argv[1] = "-z";
3151 	argv[2] = zone_name;
3152 	argv[3] = NULL;
3153 
3154 	(void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
3155 	/* Don't check for errors since they don't affect the zone */
3156 
3157 	/*
3158 	 * Finally, deallocate any devices in the zone.
3159 	 */
3160 
3161 	argv[0] = "deallocate";
3162 	argv[1] = "-Isz";
3163 	argv[2] = zone_name;
3164 	argv[3] = NULL;
3165 
3166 	(void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
3167 	/* Don't check for errors since they don't affect the zone */
3168 }
3169 
3170 /*
3171  * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
3172  * this zone.
3173  */
3174 static tsol_zcent_t *
3175 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
3176 {
3177 	FILE *fp;
3178 	tsol_zcent_t *zcent = NULL;
3179 	char line[MAXTNZLEN];
3180 
3181 	if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
3182 		zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
3183 		return (NULL);
3184 	}
3185 
3186 	while (fgets(line, sizeof (line), fp) != NULL) {
3187 		/*
3188 		 * Check for malformed database
3189 		 */
3190 		if (strlen(line) == MAXTNZLEN - 1)
3191 			break;
3192 		if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
3193 			continue;
3194 		if (strcmp(zcent->zc_name, zone_name) == 0)
3195 			break;
3196 		tsol_freezcent(zcent);
3197 		zcent = NULL;
3198 	}
3199 	(void) fclose(fp);
3200 
3201 	if (zcent == NULL) {
3202 		zerror(zlogp, B_FALSE, "zone requires a label assignment. "
3203 		    "See tnzonecfg(4)");
3204 	} else {
3205 		if (zlabel == NULL)
3206 			zlabel = m_label_alloc(MAC_LABEL);
3207 		/*
3208 		 * Save this zone's privileges for later read-down processing
3209 		 */
3210 		if ((zprivs = priv_allocset()) == NULL) {
3211 			zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3212 			return (NULL);
3213 		} else {
3214 			priv_copyset(privs, zprivs);
3215 		}
3216 	}
3217 	return (zcent);
3218 }
3219 
3220 /*
3221  * Add the Trusted Extensions multi-level ports for this zone.
3222  */
3223 static void
3224 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
3225 {
3226 	tsol_mlp_t *mlp;
3227 	tsol_mlpent_t tsme;
3228 
3229 	if (!is_system_labeled())
3230 		return;
3231 
3232 	tsme.tsme_zoneid = zoneid;
3233 	tsme.tsme_flags = 0;
3234 	for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
3235 		tsme.tsme_mlp = *mlp;
3236 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3237 			zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
3238 			    "on %d-%d/%d", mlp->mlp_port,
3239 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3240 		}
3241 	}
3242 
3243 	tsme.tsme_flags = TSOL_MEF_SHARED;
3244 	for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
3245 		tsme.tsme_mlp = *mlp;
3246 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3247 			zerror(zlogp, B_TRUE, "cannot set shared MLP "
3248 			    "on %d-%d/%d", mlp->mlp_port,
3249 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3250 		}
3251 	}
3252 }
3253 
3254 static void
3255 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
3256 {
3257 	tsol_mlpent_t tsme;
3258 
3259 	if (!is_system_labeled())
3260 		return;
3261 
3262 	(void) memset(&tsme, 0, sizeof (tsme));
3263 	tsme.tsme_zoneid = zoneid;
3264 	if (tnmlp(TNDB_FLUSH, &tsme) != 0)
3265 		zerror(zlogp, B_TRUE, "cannot flush MLPs");
3266 }
3267 
3268 int
3269 prtmount(const char *fs, void *x) {
3270 	zerror((zlog_t *)x, B_FALSE, "  %s", fs);
3271 	return (0);
3272 }
3273 
3274 /*
3275  * Look for zones running on the main system that are using this root (or any
3276  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
3277  * is found or if we can't tell.
3278  */
3279 static boolean_t
3280 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3281 {
3282 	zoneid_t *zids = NULL;
3283 	uint_t nzids = 0;
3284 	boolean_t retv;
3285 	int rlen, zlen;
3286 	char zroot[MAXPATHLEN];
3287 	char zonename[ZONENAME_MAX];
3288 
3289 	for (;;) {
3290 		nzids += 10;
3291 		zids = malloc(nzids * sizeof (*zids));
3292 		if (zids == NULL) {
3293 			zerror(zlogp, B_TRUE, "unable to allocate memory");
3294 			return (B_TRUE);
3295 		}
3296 		if (zone_list(zids, &nzids) == 0)
3297 			break;
3298 		free(zids);
3299 	}
3300 	retv = B_FALSE;
3301 	rlen = strlen(rootpath);
3302 	while (nzids > 0) {
3303 		/*
3304 		 * Ignore errors; they just mean that the zone has disappeared
3305 		 * while we were busy.
3306 		 */
3307 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3308 		    sizeof (zroot)) == -1)
3309 			continue;
3310 		zlen = strlen(zroot);
3311 		if (zlen > rlen)
3312 			zlen = rlen;
3313 		if (strncmp(rootpath, zroot, zlen) == 0 &&
3314 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3315 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3316 			if (getzonenamebyid(zids[nzids], zonename,
3317 			    sizeof (zonename)) == -1)
3318 				(void) snprintf(zonename, sizeof (zonename),
3319 				    "id %d", (int)zids[nzids]);
3320 			zerror(zlogp, B_FALSE,
3321 			    "zone root %s already in use by zone %s",
3322 			    rootpath, zonename);
3323 			retv = B_TRUE;
3324 			break;
3325 		}
3326 	}
3327 	free(zids);
3328 	return (retv);
3329 }
3330 
3331 /*
3332  * Search for loopback mounts that use this same source node (same device and
3333  * inode).  Return B_TRUE if there is one or if we can't tell.
3334  */
3335 static boolean_t
3336 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3337 {
3338 	struct stat64 rst, zst;
3339 	struct mnttab *mnp;
3340 
3341 	if (stat64(rootpath, &rst) == -1) {
3342 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3343 		return (B_TRUE);
3344 	}
3345 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3346 		return (B_TRUE);
3347 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3348 		if (mnp->mnt_fstype == NULL ||
3349 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3350 			continue;
3351 		/* We're looking at a loopback mount.  Stat it. */
3352 		if (mnp->mnt_special != NULL &&
3353 		    stat64(mnp->mnt_special, &zst) != -1 &&
3354 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3355 			zerror(zlogp, B_FALSE,
3356 			    "zone root %s is reachable through %s",
3357 			    rootpath, mnp->mnt_mountp);
3358 			return (B_TRUE);
3359 		}
3360 	}
3361 	return (B_FALSE);
3362 }
3363 
3364 zoneid_t
3365 vplat_create(zlog_t *zlogp, boolean_t mount_cmd)
3366 {
3367 	zoneid_t rval = -1;
3368 	priv_set_t *privs;
3369 	char rootpath[MAXPATHLEN];
3370 	char *rctlbuf = NULL;
3371 	size_t rctlbufsz = 0;
3372 	char *zfsbuf = NULL;
3373 	size_t zfsbufsz = 0;
3374 	zoneid_t zoneid = -1;
3375 	int xerr;
3376 	char *kzone;
3377 	FILE *fp = NULL;
3378 	tsol_zcent_t *zcent = NULL;
3379 	int match = 0;
3380 	int doi = 0;
3381 
3382 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
3383 		zerror(zlogp, B_TRUE, "unable to determine zone root");
3384 		return (-1);
3385 	}
3386 	if (zonecfg_in_alt_root())
3387 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
3388 
3389 	if ((privs = priv_allocset()) == NULL) {
3390 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3391 		return (-1);
3392 	}
3393 	priv_emptyset(privs);
3394 	if (get_privset(zlogp, privs, mount_cmd) != 0)
3395 		goto error;
3396 
3397 	if (!mount_cmd && get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
3398 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
3399 		goto error;
3400 	}
3401 
3402 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
3403 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
3404 		goto error;
3405 	}
3406 
3407 	if (!mount_cmd && is_system_labeled()) {
3408 		zcent = get_zone_label(zlogp, privs);
3409 		if (zcent != NULL) {
3410 			match = zcent->zc_match;
3411 			doi = zcent->zc_doi;
3412 			*zlabel = zcent->zc_label;
3413 		} else {
3414 			goto error;
3415 		}
3416 	}
3417 
3418 	kzone = zone_name;
3419 
3420 	/*
3421 	 * We must do this scan twice.  First, we look for zones running on the
3422 	 * main system that are using this root (or any subdirectory of it).
3423 	 * Next, we reduce to the shortest path and search for loopback mounts
3424 	 * that use this same source node (same device and inode).
3425 	 */
3426 	if (duplicate_zone_root(zlogp, rootpath))
3427 		goto error;
3428 	if (duplicate_reachable_path(zlogp, rootpath))
3429 		goto error;
3430 
3431 	if (mount_cmd) {
3432 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
3433 
3434 		/*
3435 		 * Forge up a special root for this zone.  When a zone is
3436 		 * mounted, we can't let the zone have its own root because the
3437 		 * tools that will be used in this "scratch zone" need access
3438 		 * to both the zone's resources and the running machine's
3439 		 * executables.
3440 		 *
3441 		 * Note that the mkdir here also catches read-only filesystems.
3442 		 */
3443 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
3444 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
3445 			goto error;
3446 		}
3447 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
3448 			goto error;
3449 	}
3450 
3451 	if (zonecfg_in_alt_root()) {
3452 		/*
3453 		 * If we are mounting up a zone in an alternate root partition,
3454 		 * then we have some additional work to do before starting the
3455 		 * zone.  First, resolve the root path down so that we're not
3456 		 * fooled by duplicates.  Then forge up an internal name for
3457 		 * the zone.
3458 		 */
3459 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
3460 			zerror(zlogp, B_TRUE, "cannot open mapfile");
3461 			goto error;
3462 		}
3463 		if (zonecfg_lock_scratch(fp) != 0) {
3464 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
3465 			goto error;
3466 		}
3467 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
3468 		    NULL, 0) == 0) {
3469 			zerror(zlogp, B_FALSE, "scratch zone already running");
3470 			goto error;
3471 		}
3472 		/* This is the preferred name */
3473 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
3474 		    zone_name);
3475 		srandom(getpid());
3476 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
3477 		    0) == 0) {
3478 			/* This is just an arbitrary name; note "." usage */
3479 			(void) snprintf(kernzone, sizeof (kernzone),
3480 			    "SUNWlu.%08lX%08lX", random(), random());
3481 		}
3482 		kzone = kernzone;
3483 	}
3484 
3485 	xerr = 0;
3486 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
3487 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel)) == -1) {
3488 		if (xerr == ZE_AREMOUNTS) {
3489 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
3490 				zerror(zlogp, B_FALSE,
3491 				    "An unknown file-system is mounted on "
3492 				    "a subdirectory of %s", rootpath);
3493 			} else {
3494 
3495 				zerror(zlogp, B_FALSE,
3496 				    "These file-systems are mounted on "
3497 				    "subdirectories of %s:", rootpath);
3498 				(void) zonecfg_find_mounts(rootpath,
3499 				    prtmount, zlogp);
3500 			}
3501 		} else if (xerr == ZE_CHROOTED) {
3502 			zerror(zlogp, B_FALSE, "%s: "
3503 			    "cannot create a zone from a chrooted "
3504 			    "environment", "zone_create");
3505 		} else {
3506 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
3507 		}
3508 		goto error;
3509 	}
3510 
3511 	if (zonecfg_in_alt_root() &&
3512 	    zonecfg_add_scratch(fp, zone_name, kernzone,
3513 	    zonecfg_get_root()) == -1) {
3514 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
3515 		goto error;
3516 	}
3517 
3518 	/*
3519 	 * The following is a warning, not an error, and is not performed when
3520 	 * merely mounting a zone for administrative use.
3521 	 */
3522 	if (!mount_cmd && bind_to_pool(zlogp, zoneid) != 0)
3523 		zerror(zlogp, B_FALSE, "WARNING: unable to bind zone to "
3524 		    "requested pool; using default pool.");
3525 	if (!mount_cmd)
3526 		set_mlps(zlogp, zoneid, zcent);
3527 	rval = zoneid;
3528 	zoneid = -1;
3529 
3530 error:
3531 	if (zoneid != -1)
3532 		(void) zone_destroy(zoneid);
3533 	if (rctlbuf != NULL)
3534 		free(rctlbuf);
3535 	priv_freeset(privs);
3536 	if (fp != NULL)
3537 		zonecfg_close_scratch(fp);
3538 	lofs_discard_mnttab();
3539 	if (zcent != NULL)
3540 		tsol_freezcent(zcent);
3541 	return (rval);
3542 }
3543 
3544 int
3545 vplat_bringup(zlog_t *zlogp, boolean_t mount_cmd)
3546 {
3547 	if (!mount_cmd && validate_datasets(zlogp) != 0) {
3548 		lofs_discard_mnttab();
3549 		return (-1);
3550 	}
3551 
3552 	if (create_dev_files(zlogp) != 0 ||
3553 	    mount_filesystems(zlogp, mount_cmd) != 0) {
3554 		lofs_discard_mnttab();
3555 		return (-1);
3556 	}
3557 	if (!mount_cmd && (devfsadm_register(zlogp) != 0 ||
3558 	    configure_network_interfaces(zlogp) != 0)) {
3559 		lofs_discard_mnttab();
3560 		return (-1);
3561 	}
3562 	lofs_discard_mnttab();
3563 	return (0);
3564 }
3565 
3566 static int
3567 lu_root_teardown(zlog_t *zlogp)
3568 {
3569 	char zroot[MAXPATHLEN];
3570 
3571 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
3572 		zerror(zlogp, B_FALSE, "unable to determine zone root");
3573 		return (-1);
3574 	}
3575 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
3576 
3577 	/*
3578 	 * At this point, the processes are gone, the filesystems (save the
3579 	 * root) are unmounted, and the zone is on death row.  But there may
3580 	 * still be creds floating about in the system that reference the
3581 	 * zone_t, and which pin down zone_rootvp causing this call to fail
3582 	 * with EBUSY.  Thus, we try for a little while before just giving up.
3583 	 * (How I wish this were not true, and umount2 just did the right
3584 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
3585 	 */
3586 	if (umount2(zroot, MS_FORCE) != 0) {
3587 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
3588 			goto unmounted;
3589 		if (errno == EBUSY) {
3590 			int tries = 10;
3591 
3592 			while (--tries >= 0) {
3593 				(void) sleep(1);
3594 				if (umount2(zroot, 0) == 0)
3595 					goto unmounted;
3596 				if (errno != EBUSY)
3597 					break;
3598 			}
3599 		}
3600 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
3601 		return (-1);
3602 	}
3603 unmounted:
3604 
3605 	/*
3606 	 * Only zones in an alternate root environment have scratch zone
3607 	 * entries.
3608 	 */
3609 	if (zonecfg_in_alt_root()) {
3610 		FILE *fp;
3611 		int retv;
3612 
3613 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
3614 			zerror(zlogp, B_TRUE, "cannot open mapfile");
3615 			return (-1);
3616 		}
3617 		retv = -1;
3618 		if (zonecfg_lock_scratch(fp) != 0)
3619 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
3620 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
3621 			zerror(zlogp, B_TRUE, "cannot delete map entry");
3622 		else
3623 			retv = 0;
3624 		zonecfg_close_scratch(fp);
3625 		return (retv);
3626 	} else {
3627 		return (0);
3628 	}
3629 }
3630 
3631 int
3632 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd)
3633 {
3634 	char *kzone;
3635 	zoneid_t zoneid;
3636 
3637 	kzone = zone_name;
3638 	if (zonecfg_in_alt_root()) {
3639 		FILE *fp;
3640 
3641 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
3642 			zerror(zlogp, B_TRUE, "unable to open map file");
3643 			goto error;
3644 		}
3645 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
3646 		    kernzone, sizeof (kernzone)) != 0) {
3647 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
3648 			zonecfg_close_scratch(fp);
3649 			goto error;
3650 		}
3651 		zonecfg_close_scratch(fp);
3652 		kzone = kernzone;
3653 	}
3654 
3655 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
3656 		if (!bringup_failure_recovery)
3657 			zerror(zlogp, B_TRUE, "unable to get zoneid");
3658 		if (unmount_cmd)
3659 			(void) lu_root_teardown(zlogp);
3660 		goto error;
3661 	}
3662 
3663 	if (zone_shutdown(zoneid) != 0) {
3664 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
3665 		goto error;
3666 	}
3667 
3668 	if (!unmount_cmd && devfsadm_unregister(zlogp) != 0)
3669 		goto error;
3670 
3671 	if (!unmount_cmd &&
3672 	    unconfigure_network_interfaces(zlogp, zoneid) != 0) {
3673 		zerror(zlogp, B_FALSE,
3674 		    "unable to unconfigure network interfaces in zone");
3675 		goto error;
3676 	}
3677 
3678 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
3679 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
3680 		goto error;
3681 	}
3682 
3683 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
3684 		zerror(zlogp, B_FALSE,
3685 		    "unable to unmount file systems in zone");
3686 		goto error;
3687 	}
3688 
3689 	remove_mlps(zlogp, zoneid);
3690 
3691 	if (zone_destroy(zoneid) != 0) {
3692 		zerror(zlogp, B_TRUE, "unable to destroy zone");
3693 		goto error;
3694 	}
3695 
3696 	/*
3697 	 * Special teardown for alternate boot environments: remove the tmpfs
3698 	 * root for the zone and then remove it from the map file.
3699 	 */
3700 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
3701 		goto error;
3702 
3703 	if (!unmount_cmd)
3704 		destroy_console_slave();
3705 
3706 	lofs_discard_mnttab();
3707 	return (0);
3708 
3709 error:
3710 	lofs_discard_mnttab();
3711 	return (-1);
3712 }
3713