xref: /titanic_41/usr/src/cmd/zoneadmd/vplat.c (revision c39526b769298791ff5b0b6c5e761f49aabaeb4e)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * This module contains functions used to bring up and tear down the
29  * Virtual Platform: [un]mounting file-systems, [un]plumbing network
30  * interfaces, [un]configuring devices, establishing resource controls,
31  * and creating/destroying the zone in the kernel.  These actions, on
32  * the way up, ready the zone; on the way down, they halt the zone.
33  * See the much longer block comment at the beginning of zoneadmd.c
34  * for a bigger picture of how the whole program functions.
35  *
36  * This module also has primary responsibility for the layout of "scratch
37  * zones."  These are mounted, but inactive, zones that are used during
38  * operating system upgrade and potentially other administrative action.  The
39  * scratch zone environment is similar to the miniroot environment.  The zone's
40  * actual root is mounted read-write on /a, and the standard paths (/usr,
41  * /sbin, /lib) all lead to read-only copies of the running system's binaries.
42  * This allows the administrative tools to manipulate the zone using "-R /a"
43  * without relying on any binaries in the zone itself.
44  *
45  * If the scratch zone is on an alternate root (Live Upgrade [LU] boot
46  * environment), then we must resolve the lofs mounts used there to uncover
47  * writable (unshared) resources.  Shared resources, though, are always
48  * read-only.  In addition, if the "same" zone with a different root path is
49  * currently running, then "/b" inside the zone points to the running zone's
50  * root.  This allows LU to synchronize configuration files during the upgrade
51  * process.
52  *
53  * To construct this environment, this module creates a tmpfs mount on
54  * $ZONEPATH/lu.  Inside this scratch area, the miniroot-like environment as
55  * described above is constructed on the fly.  The zone is then created using
56  * $ZONEPATH/lu as the root.
57  *
58  * Note that scratch zones are inactive.  The zone's bits are not running and
59  * likely cannot be run correctly until upgrade is done.  Init is not running
60  * there, nor is SMF.  Because of this, the "mounted" state of a scratch zone
61  * is not a part of the usual halt/ready/boot state machine.
62  */
63 
64 #include <sys/param.h>
65 #include <sys/mount.h>
66 #include <sys/mntent.h>
67 #include <sys/socket.h>
68 #include <sys/utsname.h>
69 #include <sys/types.h>
70 #include <sys/stat.h>
71 #include <sys/sockio.h>
72 #include <sys/stropts.h>
73 #include <sys/conf.h>
74 #include <sys/systeminfo.h>
75 
76 #include <libdlpi.h>
77 #include <libdllink.h>
78 #include <libdlvlan.h>
79 
80 #include <inet/tcp.h>
81 #include <arpa/inet.h>
82 #include <netinet/in.h>
83 #include <net/route.h>
84 
85 #include <stdio.h>
86 #include <errno.h>
87 #include <fcntl.h>
88 #include <unistd.h>
89 #include <rctl.h>
90 #include <stdlib.h>
91 #include <string.h>
92 #include <strings.h>
93 #include <wait.h>
94 #include <limits.h>
95 #include <libgen.h>
96 #include <libzfs.h>
97 #include <libdevinfo.h>
98 #include <zone.h>
99 #include <assert.h>
100 #include <libcontract.h>
101 #include <libcontract_priv.h>
102 #include <uuid/uuid.h>
103 
104 #include <sys/mntio.h>
105 #include <sys/mnttab.h>
106 #include <sys/fs/autofs.h>	/* for _autofssys() */
107 #include <sys/fs/lofs_info.h>
108 #include <sys/fs/zfs.h>
109 
110 #include <pool.h>
111 #include <sys/pool.h>
112 #include <sys/priocntl.h>
113 
114 #include <libbrand.h>
115 #include <sys/brand.h>
116 #include <libzonecfg.h>
117 #include <synch.h>
118 
119 #include "zoneadmd.h"
120 #include <tsol/label.h>
121 #include <libtsnet.h>
122 #include <sys/priv.h>
123 
124 #define	V4_ADDR_LEN	32
125 #define	V6_ADDR_LEN	128
126 
127 #define	IPD_DEFAULT_OPTS \
128 	MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
129 
130 #define	DFSTYPES	"/etc/dfs/fstypes"
131 #define	MAXTNZLEN	2048
132 
133 #define	ALT_MOUNT(mount_cmd) 	((mount_cmd) != Z_MNT_BOOT)
134 
135 /* for routing socket */
136 static int rts_seqno = 0;
137 
138 /* mangled zone name when mounting in an alternate root environment */
139 static char kernzone[ZONENAME_MAX];
140 
141 /* array of cached mount entries for resolve_lofs */
142 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
143 
144 /* for Trusted Extensions */
145 static tsol_zcent_t *get_zone_label(zlog_t *, priv_set_t *);
146 static int tsol_mounts(zlog_t *, char *, char *);
147 static void tsol_unmounts(zlog_t *, char *);
148 
149 static m_label_t *zlabel = NULL;
150 static m_label_t *zid_label = NULL;
151 static priv_set_t *zprivs = NULL;
152 
153 /* from libsocket, not in any header file */
154 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
155 
156 /* from zoneadmd */
157 extern char query_hook[];
158 
159 /*
160  * An optimization for build_mnttable: reallocate (and potentially copy the
161  * data) only once every N times through the loop.
162  */
163 #define	MNTTAB_HUNK	32
164 
165 /*
166  * Private autofs system call
167  */
168 extern int _autofssys(int, void *);
169 
170 static int
171 autofs_cleanup(zoneid_t zoneid)
172 {
173 	/*
174 	 * Ask autofs to unmount all trigger nodes in the given zone.
175 	 */
176 	return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
177 }
178 
179 static void
180 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
181 {
182 	uint_t i;
183 
184 	if (mnt_array == NULL)
185 		return;
186 	for (i = 0; i < nelem; i++) {
187 		free(mnt_array[i].mnt_mountp);
188 		free(mnt_array[i].mnt_fstype);
189 		free(mnt_array[i].mnt_special);
190 		free(mnt_array[i].mnt_mntopts);
191 		assert(mnt_array[i].mnt_time == NULL);
192 	}
193 	free(mnt_array);
194 }
195 
196 /*
197  * Build the mount table for the zone rooted at "zroot", storing the resulting
198  * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
199  * array in "nelemp".
200  */
201 static int
202 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
203     struct mnttab **mnt_arrayp, uint_t *nelemp)
204 {
205 	struct mnttab mnt;
206 	struct mnttab *mnts;
207 	struct mnttab *mnp;
208 	uint_t nmnt;
209 
210 	rewind(mnttab);
211 	resetmnttab(mnttab);
212 	nmnt = 0;
213 	mnts = NULL;
214 	while (getmntent(mnttab, &mnt) == 0) {
215 		struct mnttab *tmp_array;
216 
217 		if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
218 			continue;
219 		if (nmnt % MNTTAB_HUNK == 0) {
220 			tmp_array = realloc(mnts,
221 			    (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
222 			if (tmp_array == NULL) {
223 				free_mnttable(mnts, nmnt);
224 				return (-1);
225 			}
226 			mnts = tmp_array;
227 		}
228 		mnp = &mnts[nmnt++];
229 
230 		/*
231 		 * Zero out any fields we're not using.
232 		 */
233 		(void) memset(mnp, 0, sizeof (*mnp));
234 
235 		if (mnt.mnt_special != NULL)
236 			mnp->mnt_special = strdup(mnt.mnt_special);
237 		if (mnt.mnt_mntopts != NULL)
238 			mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
239 		mnp->mnt_mountp = strdup(mnt.mnt_mountp);
240 		mnp->mnt_fstype = strdup(mnt.mnt_fstype);
241 		if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
242 		    (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
243 		    mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
244 			zerror(zlogp, B_TRUE, "memory allocation failed");
245 			free_mnttable(mnts, nmnt);
246 			return (-1);
247 		}
248 	}
249 	*mnt_arrayp = mnts;
250 	*nelemp = nmnt;
251 	return (0);
252 }
253 
254 /*
255  * This is an optimization.  The resolve_lofs function is used quite frequently
256  * to manipulate file paths, and on a machine with a large number of zones,
257  * there will be a huge number of mounted file systems.  Thus, we trigger a
258  * reread of the list of mount points
259  */
260 static void
261 lofs_discard_mnttab(void)
262 {
263 	free_mnttable(resolve_lofs_mnts,
264 	    resolve_lofs_mnt_max - resolve_lofs_mnts);
265 	resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
266 }
267 
268 static int
269 lofs_read_mnttab(zlog_t *zlogp)
270 {
271 	FILE *mnttab;
272 	uint_t nmnts;
273 
274 	if ((mnttab = fopen(MNTTAB, "r")) == NULL)
275 		return (-1);
276 	if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
277 	    &nmnts) == -1) {
278 		(void) fclose(mnttab);
279 		return (-1);
280 	}
281 	(void) fclose(mnttab);
282 	resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
283 	return (0);
284 }
285 
286 /*
287  * This function loops over potential loopback mounts and symlinks in a given
288  * path and resolves them all down to an absolute path.
289  */
290 void
291 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
292 {
293 	int len, arlen;
294 	const char *altroot;
295 	char tmppath[MAXPATHLEN];
296 	boolean_t outside_altroot;
297 
298 	if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
299 		return;
300 	tmppath[len] = '\0';
301 	(void) strlcpy(path, tmppath, sizeof (tmppath));
302 
303 	/* This happens once per zoneadmd operation. */
304 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
305 		return;
306 
307 	altroot = zonecfg_get_root();
308 	arlen = strlen(altroot);
309 	outside_altroot = B_FALSE;
310 	for (;;) {
311 		struct mnttab *mnp;
312 
313 		/* Search in reverse order to find longest match */
314 		for (mnp = resolve_lofs_mnt_max - 1; mnp >= resolve_lofs_mnts;
315 		    mnp--) {
316 			if (mnp->mnt_fstype == NULL ||
317 			    mnp->mnt_mountp == NULL ||
318 			    mnp->mnt_special == NULL)
319 				continue;
320 			len = strlen(mnp->mnt_mountp);
321 			if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
322 			    (path[len] == '/' || path[len] == '\0'))
323 				break;
324 		}
325 		if (mnp < resolve_lofs_mnts)
326 			break;
327 		/* If it's not a lofs then we're done */
328 		if (strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
329 			break;
330 		if (outside_altroot) {
331 			char *cp;
332 			int olen = sizeof (MNTOPT_RO) - 1;
333 
334 			/*
335 			 * If we run into a read-only mount outside of the
336 			 * alternate root environment, then the user doesn't
337 			 * want this path to be made read-write.
338 			 */
339 			if (mnp->mnt_mntopts != NULL &&
340 			    (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
341 			    NULL &&
342 			    (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
343 			    (cp[olen] == '\0' || cp[olen] == ',')) {
344 				break;
345 			}
346 		} else if (arlen > 0 &&
347 		    (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
348 		    (mnp->mnt_special[arlen] != '\0' &&
349 		    mnp->mnt_special[arlen] != '/'))) {
350 			outside_altroot = B_TRUE;
351 		}
352 		/* use temporary buffer because new path might be longer */
353 		(void) snprintf(tmppath, sizeof (tmppath), "%s%s",
354 		    mnp->mnt_special, path + len);
355 		if ((len = resolvepath(tmppath, path, pathlen)) == -1)
356 			break;
357 		path[len] = '\0';
358 	}
359 }
360 
361 /*
362  * For a regular mount, check if a replacement lofs mount is needed because the
363  * referenced device is already mounted somewhere.
364  */
365 static int
366 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
367 {
368 	struct mnttab *mnp;
369 	zone_fsopt_t *optptr, *onext;
370 
371 	/* This happens once per zoneadmd operation. */
372 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
373 		return (-1);
374 
375 	/*
376 	 * If this special node isn't already in use, then it's ours alone;
377 	 * no need to worry about conflicting mounts.
378 	 */
379 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
380 	    mnp++) {
381 		if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
382 			break;
383 	}
384 	if (mnp >= resolve_lofs_mnt_max)
385 		return (0);
386 
387 	/*
388 	 * Convert this duplicate mount into a lofs mount.
389 	 */
390 	(void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
391 	    sizeof (fsptr->zone_fs_special));
392 	(void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
393 	    sizeof (fsptr->zone_fs_type));
394 	fsptr->zone_fs_raw[0] = '\0';
395 
396 	/*
397 	 * Discard all but one of the original options and set that to be the
398 	 * same set of options used for inherit package directory resources.
399 	 */
400 	optptr = fsptr->zone_fs_options;
401 	if (optptr == NULL) {
402 		optptr = malloc(sizeof (*optptr));
403 		if (optptr == NULL) {
404 			zerror(zlogp, B_TRUE, "cannot mount %s",
405 			    fsptr->zone_fs_dir);
406 			return (-1);
407 		}
408 	} else {
409 		while ((onext = optptr->zone_fsopt_next) != NULL) {
410 			optptr->zone_fsopt_next = onext->zone_fsopt_next;
411 			free(onext);
412 		}
413 	}
414 	(void) strcpy(optptr->zone_fsopt_opt, IPD_DEFAULT_OPTS);
415 	optptr->zone_fsopt_next = NULL;
416 	fsptr->zone_fs_options = optptr;
417 	return (0);
418 }
419 
420 int
421 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode,
422     uid_t userid, gid_t groupid)
423 {
424 	char path[MAXPATHLEN];
425 	struct stat st;
426 
427 	if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
428 	    sizeof (path)) {
429 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
430 		    subdir);
431 		return (-1);
432 	}
433 
434 	if (lstat(path, &st) == 0) {
435 		/*
436 		 * We don't check the file mode since presumably the zone
437 		 * administrator may have had good reason to change the mode,
438 		 * and we don't need to second guess him.
439 		 */
440 		if (!S_ISDIR(st.st_mode)) {
441 			if (S_ISREG(st.st_mode)) {
442 				/*
443 				 * Allow readonly mounts of /etc/ files; this
444 				 * is needed most by Trusted Extensions.
445 				 */
446 				if (strncmp(subdir, "/etc/",
447 				    strlen("/etc/")) != 0) {
448 					zerror(zlogp, B_FALSE,
449 					    "%s is not in /etc", path);
450 					return (-1);
451 				}
452 			} else {
453 				zerror(zlogp, B_FALSE,
454 				    "%s is not a directory", path);
455 				return (-1);
456 			}
457 		}
458 		return (0);
459 	}
460 
461 	if (mkdirp(path, mode) != 0) {
462 		if (errno == EROFS)
463 			zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
464 			    "a read-only file system in this local zone.\nMake "
465 			    "sure %s exists in the global zone.", path, subdir);
466 		else
467 			zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
468 		return (-1);
469 	}
470 
471 	(void) chown(path, userid, groupid);
472 	return (0);
473 }
474 
475 static void
476 free_remote_fstypes(char **types)
477 {
478 	uint_t i;
479 
480 	if (types == NULL)
481 		return;
482 	for (i = 0; types[i] != NULL; i++)
483 		free(types[i]);
484 	free(types);
485 }
486 
487 static char **
488 get_remote_fstypes(zlog_t *zlogp)
489 {
490 	char **types = NULL;
491 	FILE *fp;
492 	char buf[MAXPATHLEN];
493 	char fstype[MAXPATHLEN];
494 	uint_t lines = 0;
495 	uint_t i;
496 
497 	if ((fp = fopen(DFSTYPES, "r")) == NULL) {
498 		zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
499 		return (NULL);
500 	}
501 	/*
502 	 * Count the number of lines
503 	 */
504 	while (fgets(buf, sizeof (buf), fp) != NULL)
505 		lines++;
506 	if (lines == 0)	/* didn't read anything; empty file */
507 		goto out;
508 	rewind(fp);
509 	/*
510 	 * Allocate enough space for a NULL-terminated array.
511 	 */
512 	types = calloc(lines + 1, sizeof (char *));
513 	if (types == NULL) {
514 		zerror(zlogp, B_TRUE, "memory allocation failed");
515 		goto out;
516 	}
517 	i = 0;
518 	while (fgets(buf, sizeof (buf), fp) != NULL) {
519 		/* LINTED - fstype is big enough to hold buf */
520 		if (sscanf(buf, "%s", fstype) == 0) {
521 			zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
522 			free_remote_fstypes(types);
523 			types = NULL;
524 			goto out;
525 		}
526 		types[i] = strdup(fstype);
527 		if (types[i] == NULL) {
528 			zerror(zlogp, B_TRUE, "memory allocation failed");
529 			free_remote_fstypes(types);
530 			types = NULL;
531 			goto out;
532 		}
533 		i++;
534 	}
535 out:
536 	(void) fclose(fp);
537 	return (types);
538 }
539 
540 static boolean_t
541 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
542 {
543 	uint_t i;
544 
545 	if (remote_fstypes == NULL)
546 		return (B_FALSE);
547 	for (i = 0; remote_fstypes[i] != NULL; i++) {
548 		if (strcmp(remote_fstypes[i], fstype) == 0)
549 			return (B_TRUE);
550 	}
551 	return (B_FALSE);
552 }
553 
554 /*
555  * This converts a zone root path (normally of the form .../root) to a Live
556  * Upgrade scratch zone root (of the form .../lu).
557  */
558 static void
559 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
560 {
561 	if (!isresolved && zonecfg_in_alt_root())
562 		resolve_lofs(zlogp, zroot, zrootlen);
563 	(void) strcpy(strrchr(zroot, '/') + 1, "lu");
564 }
565 
566 /*
567  * The general strategy for unmounting filesystems is as follows:
568  *
569  * - Remote filesystems may be dead, and attempting to contact them as
570  * part of a regular unmount may hang forever; we want to always try to
571  * forcibly unmount such filesystems and only fall back to regular
572  * unmounts if the filesystem doesn't support forced unmounts.
573  *
574  * - We don't want to unnecessarily corrupt metadata on local
575  * filesystems (ie UFS), so we want to start off with graceful unmounts,
576  * and only escalate to doing forced unmounts if we get stuck.
577  *
578  * We start off walking backwards through the mount table.  This doesn't
579  * give us strict ordering but ensures that we try to unmount submounts
580  * first.  We thus limit the number of failed umount2(2) calls.
581  *
582  * The mechanism for determining if we're stuck is to count the number
583  * of failed unmounts each iteration through the mount table.  This
584  * gives us an upper bound on the number of filesystems which remain
585  * mounted (autofs trigger nodes are dealt with separately).  If at the
586  * end of one unmount+autofs_cleanup cycle we still have the same number
587  * of mounts that we started out with, we're stuck and try a forced
588  * unmount.  If that fails (filesystem doesn't support forced unmounts)
589  * then we bail and are unable to teardown the zone.  If it succeeds,
590  * we're no longer stuck so we continue with our policy of trying
591  * graceful mounts first.
592  *
593  * Zone must be down (ie, no processes or threads active).
594  */
595 static int
596 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
597 {
598 	int error = 0;
599 	FILE *mnttab;
600 	struct mnttab *mnts;
601 	uint_t nmnt;
602 	char zroot[MAXPATHLEN + 1];
603 	size_t zrootlen;
604 	uint_t oldcount = UINT_MAX;
605 	boolean_t stuck = B_FALSE;
606 	char **remote_fstypes = NULL;
607 
608 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
609 		zerror(zlogp, B_FALSE, "unable to determine zone root");
610 		return (-1);
611 	}
612 	if (unmount_cmd)
613 		root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
614 
615 	(void) strcat(zroot, "/");
616 	zrootlen = strlen(zroot);
617 
618 	/*
619 	 * For Trusted Extensions unmount each higher level zone's mount
620 	 * of our zone's /export/home
621 	 */
622 	if (!unmount_cmd)
623 		tsol_unmounts(zlogp, zone_name);
624 
625 	if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
626 		zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
627 		return (-1);
628 	}
629 	/*
630 	 * Use our hacky mntfs ioctl so we see everything, even mounts with
631 	 * MS_NOMNTTAB.
632 	 */
633 	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
634 		zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
635 		error++;
636 		goto out;
637 	}
638 
639 	/*
640 	 * Build the list of remote fstypes so we know which ones we
641 	 * should forcibly unmount.
642 	 */
643 	remote_fstypes = get_remote_fstypes(zlogp);
644 	for (; /* ever */; ) {
645 		uint_t newcount = 0;
646 		boolean_t unmounted;
647 		struct mnttab *mnp;
648 		char *path;
649 		uint_t i;
650 
651 		mnts = NULL;
652 		nmnt = 0;
653 		/*
654 		 * MNTTAB gives us a way to walk through mounted
655 		 * filesystems; we need to be able to walk them in
656 		 * reverse order, so we build a list of all mounted
657 		 * filesystems.
658 		 */
659 		if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
660 		    &nmnt) != 0) {
661 			error++;
662 			goto out;
663 		}
664 		for (i = 0; i < nmnt; i++) {
665 			mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
666 			path = mnp->mnt_mountp;
667 			unmounted = B_FALSE;
668 			/*
669 			 * Try forced unmount first for remote filesystems.
670 			 *
671 			 * Not all remote filesystems support forced unmounts,
672 			 * so if this fails (ENOTSUP) we'll continue on
673 			 * and try a regular unmount.
674 			 */
675 			if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
676 				if (umount2(path, MS_FORCE) == 0)
677 					unmounted = B_TRUE;
678 			}
679 			/*
680 			 * Try forced unmount if we're stuck.
681 			 */
682 			if (stuck) {
683 				if (umount2(path, MS_FORCE) == 0) {
684 					unmounted = B_TRUE;
685 					stuck = B_FALSE;
686 				} else {
687 					/*
688 					 * The first failure indicates a
689 					 * mount we won't be able to get
690 					 * rid of automatically, so we
691 					 * bail.
692 					 */
693 					error++;
694 					zerror(zlogp, B_FALSE,
695 					    "unable to unmount '%s'", path);
696 					free_mnttable(mnts, nmnt);
697 					goto out;
698 				}
699 			}
700 			/*
701 			 * Try regular unmounts for everything else.
702 			 */
703 			if (!unmounted && umount2(path, 0) != 0)
704 				newcount++;
705 		}
706 		free_mnttable(mnts, nmnt);
707 
708 		if (newcount == 0)
709 			break;
710 		if (newcount >= oldcount) {
711 			/*
712 			 * Last round didn't unmount anything; we're stuck and
713 			 * should start trying forced unmounts.
714 			 */
715 			stuck = B_TRUE;
716 		}
717 		oldcount = newcount;
718 
719 		/*
720 		 * Autofs doesn't let you unmount its trigger nodes from
721 		 * userland so we have to tell the kernel to cleanup for us.
722 		 */
723 		if (autofs_cleanup(zoneid) != 0) {
724 			zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
725 			error++;
726 			goto out;
727 		}
728 	}
729 
730 out:
731 	free_remote_fstypes(remote_fstypes);
732 	(void) fclose(mnttab);
733 	return (error ? -1 : 0);
734 }
735 
736 static int
737 fs_compare(const void *m1, const void *m2)
738 {
739 	struct zone_fstab *i = (struct zone_fstab *)m1;
740 	struct zone_fstab *j = (struct zone_fstab *)m2;
741 
742 	return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
743 }
744 
745 /*
746  * Fork and exec (and wait for) the mentioned binary with the provided
747  * arguments.  Returns (-1) if something went wrong with fork(2) or exec(2),
748  * returns the exit status otherwise.
749  *
750  * If we were unable to exec the provided pathname (for whatever
751  * reason), we return the special token ZEXIT_EXEC.  The current value
752  * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
753  * consumers of this function; any future consumers must make sure this
754  * remains the case.
755  */
756 static int
757 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
758 {
759 	pid_t child_pid;
760 	int child_status = 0;
761 
762 	/*
763 	 * Do not let another thread localize a message while we are forking.
764 	 */
765 	(void) mutex_lock(&msglock);
766 	child_pid = fork();
767 	(void) mutex_unlock(&msglock);
768 	if (child_pid == -1) {
769 		zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
770 		return (-1);
771 	} else if (child_pid == 0) {
772 		closefrom(0);
773 		/* redirect stdin, stdout & stderr to /dev/null */
774 		(void) open("/dev/null", O_RDONLY);	/* stdin */
775 		(void) open("/dev/null", O_WRONLY);	/* stdout */
776 		(void) open("/dev/null", O_WRONLY);	/* stderr */
777 		(void) execv(path, argv);
778 		/*
779 		 * Since we are in the child, there is no point calling zerror()
780 		 * since there is nobody waiting to consume it.  So exit with a
781 		 * special code that the parent will recognize and call zerror()
782 		 * accordingly.
783 		 */
784 
785 		_exit(ZEXIT_EXEC);
786 	} else {
787 		(void) waitpid(child_pid, &child_status, 0);
788 	}
789 
790 	if (WIFSIGNALED(child_status)) {
791 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
792 		    "signal %d", path, WTERMSIG(child_status));
793 		return (-1);
794 	}
795 	assert(WIFEXITED(child_status));
796 	if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
797 		zerror(zlogp, B_FALSE, "failed to exec %s", path);
798 		return (-1);
799 	}
800 	return (WEXITSTATUS(child_status));
801 }
802 
803 static int
804 isregfile(const char *path)
805 {
806 	struct stat64 st;
807 
808 	if (stat64(path, &st) == -1)
809 		return (-1);
810 
811 	return (S_ISREG(st.st_mode));
812 }
813 
814 static int
815 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
816 {
817 	char cmdbuf[MAXPATHLEN];
818 	char *argv[5];
819 	int status;
820 
821 	/*
822 	 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
823 	 * that would cost us an extra fork/exec without buying us anything.
824 	 */
825 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
826 	    >= sizeof (cmdbuf)) {
827 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
828 		return (-1);
829 	}
830 
831 	/*
832 	 * If it doesn't exist, that's OK: we verified this previously
833 	 * in zoneadm.
834 	 */
835 	if (isregfile(cmdbuf) == -1)
836 		return (0);
837 
838 	argv[0] = "fsck";
839 	argv[1] = "-o";
840 	argv[2] = "p";
841 	argv[3] = (char *)rawdev;
842 	argv[4] = NULL;
843 
844 	status = forkexec(zlogp, cmdbuf, argv);
845 	if (status == 0 || status == -1)
846 		return (status);
847 	zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
848 	    "run fsck manually", rawdev, status);
849 	return (-1);
850 }
851 
852 static int
853 domount(zlog_t *zlogp, const char *fstype, const char *opts,
854     const char *special, const char *directory)
855 {
856 	char cmdbuf[MAXPATHLEN];
857 	char *argv[6];
858 	int status;
859 
860 	/*
861 	 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
862 	 * that would cost us an extra fork/exec without buying us anything.
863 	 */
864 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
865 	    >= sizeof (cmdbuf)) {
866 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
867 		return (-1);
868 	}
869 	argv[0] = "mount";
870 	if (opts[0] == '\0') {
871 		argv[1] = (char *)special;
872 		argv[2] = (char *)directory;
873 		argv[3] = NULL;
874 	} else {
875 		argv[1] = "-o";
876 		argv[2] = (char *)opts;
877 		argv[3] = (char *)special;
878 		argv[4] = (char *)directory;
879 		argv[5] = NULL;
880 	}
881 
882 	status = forkexec(zlogp, cmdbuf, argv);
883 	if (status == 0 || status == -1)
884 		return (status);
885 	if (opts[0] == '\0')
886 		zerror(zlogp, B_FALSE, "\"%s %s %s\" "
887 		    "failed with exit code %d",
888 		    cmdbuf, special, directory, status);
889 	else
890 		zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
891 		    "failed with exit code %d",
892 		    cmdbuf, opts, special, directory, status);
893 	return (-1);
894 }
895 
896 /*
897  * Check if a given mount point path exists.
898  * If it does, make sure it doesn't contain any symlinks.
899  * Note that if "leaf" is false we're checking an intermediate
900  * component of the mount point path, so it must be a directory.
901  * If "leaf" is true, then we're checking the entire mount point
902  * path, so the mount point itself can be anything aside from a
903  * symbolic link.
904  *
905  * If the path is invalid then a negative value is returned.  If the
906  * path exists and is a valid mount point path then 0 is returned.
907  * If the path doesn't exist return a positive value.
908  */
909 static int
910 valid_mount_point(zlog_t *zlogp, const char *path, const boolean_t leaf)
911 {
912 	struct stat statbuf;
913 	char respath[MAXPATHLEN];
914 	int res;
915 
916 	if (lstat(path, &statbuf) != 0) {
917 		if (errno == ENOENT)
918 			return (1);
919 		zerror(zlogp, B_TRUE, "can't stat %s", path);
920 		return (-1);
921 	}
922 	if (S_ISLNK(statbuf.st_mode)) {
923 		zerror(zlogp, B_FALSE, "%s is a symlink", path);
924 		return (-1);
925 	}
926 	if (!leaf && !S_ISDIR(statbuf.st_mode)) {
927 		zerror(zlogp, B_FALSE, "%s is not a directory", path);
928 		return (-1);
929 	}
930 	if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
931 		zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
932 		return (-1);
933 	}
934 	respath[res] = '\0';
935 	if (strcmp(path, respath) != 0) {
936 		/*
937 		 * We don't like ".."s, "."s, or "//"s throwing us off
938 		 */
939 		zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
940 		return (-1);
941 	}
942 	return (0);
943 }
944 
945 /*
946  * Validate a mount point path.  A valid mount point path is an
947  * absolute path that either doesn't exist, or, if it does exists it
948  * must be an absolute canonical path that doesn't have any symbolic
949  * links in it.  The target of a mount point path can be any filesystem
950  * object.  (Different filesystems can support different mount points,
951  * for example "lofs" and "mntfs" both support files and directories
952  * while "ufs" just supports directories.)
953  *
954  * If the path is invalid then a negative value is returned.  If the
955  * path exists and is a valid mount point path then 0 is returned.
956  * If the path doesn't exist return a positive value.
957  */
958 int
959 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *spec,
960     const char *dir, const char *fstype)
961 {
962 	char abspath[MAXPATHLEN], *slashp, *slashp_next;
963 	int rv;
964 
965 	/*
966 	 * Sanity check the target mount point path.
967 	 * It must be a non-null string that starts with a '/'.
968 	 */
969 	if (dir[0] != '/') {
970 		if (spec[0] == '\0') {
971 			/*
972 			 * This must be an invalid ipd entry (see comments
973 			 * in mount_filesystems_ipdent()).
974 			 */
975 			zerror(zlogp, B_FALSE,
976 			    "invalid inherit-pkg-dir entry: \"%s\"", dir);
977 		} else {
978 			/* Something went wrong. */
979 			zerror(zlogp, B_FALSE, "invalid mount directory, "
980 			    "type: \"%s\", special: \"%s\", dir: \"%s\"",
981 			    fstype, spec, dir);
982 		}
983 		return (-1);
984 	}
985 
986 	/*
987 	 * Join rootpath and dir.  Make sure abspath ends with '/', this
988 	 * is added to all paths (even non-directory paths) to allow us
989 	 * to detect the end of paths below.  If the path already ends
990 	 * in a '/', then that's ok too (although we'll fail the
991 	 * cannonical path check in valid_mount_point()).
992 	 */
993 	if (snprintf(abspath, sizeof (abspath),
994 	    "%s%s/", rootpath, dir) >= sizeof (abspath)) {
995 		zerror(zlogp, B_FALSE, "pathname %s%s is too long",
996 		    rootpath, dir);
997 		return (-1);
998 	}
999 
1000 	/*
1001 	 * Starting with rootpath, verify the mount path one component
1002 	 * at a time.  Continue until we've evaluated all of abspath.
1003 	 */
1004 	slashp = &abspath[strlen(rootpath)];
1005 	assert(*slashp == '/');
1006 	do {
1007 		slashp_next = strchr(slashp + 1, '/');
1008 		*slashp = '\0';
1009 		if (slashp_next != NULL) {
1010 			/* This is an intermediary mount path component. */
1011 			rv = valid_mount_point(zlogp, abspath, B_FALSE);
1012 		} else {
1013 			/* This is the last component of the mount path. */
1014 			rv = valid_mount_point(zlogp, abspath, B_TRUE);
1015 		}
1016 		if (rv < 0)
1017 			return (rv);
1018 		*slashp = '/';
1019 	} while ((slashp = slashp_next) != NULL);
1020 	return (rv);
1021 }
1022 
1023 static int
1024 mount_one_dev_device_cb(void *arg, const char *match, const char *name)
1025 {
1026 	di_prof_t prof = arg;
1027 
1028 	if (name == NULL)
1029 		return (di_prof_add_dev(prof, match));
1030 	return (di_prof_add_map(prof, match, name));
1031 }
1032 
1033 static int
1034 mount_one_dev_symlink_cb(void *arg, const char *source, const char *target)
1035 {
1036 	di_prof_t prof = arg;
1037 
1038 	return (di_prof_add_symlink(prof, source, target));
1039 }
1040 
1041 int
1042 vplat_get_iptype(zlog_t *zlogp, zone_iptype_t *iptypep)
1043 {
1044 	zone_dochandle_t handle;
1045 
1046 	if ((handle = zonecfg_init_handle()) == NULL) {
1047 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
1048 		return (-1);
1049 	}
1050 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
1051 		zerror(zlogp, B_FALSE, "invalid configuration");
1052 		zonecfg_fini_handle(handle);
1053 		return (-1);
1054 	}
1055 	if (zonecfg_get_iptype(handle, iptypep) != Z_OK) {
1056 		zerror(zlogp, B_FALSE, "invalid ip-type configuration");
1057 		zonecfg_fini_handle(handle);
1058 		return (-1);
1059 	}
1060 	zonecfg_fini_handle(handle);
1061 	return (0);
1062 }
1063 
1064 /*
1065  * Apply the standard lists of devices/symlinks/mappings and the user-specified
1066  * list of devices (via zonecfg) to the /dev filesystem.  The filesystem will
1067  * use these as a profile/filter to determine what exists in /dev.
1068  */
1069 static int
1070 mount_one_dev(zlog_t *zlogp, char *devpath, zone_mnt_t mount_cmd)
1071 {
1072 	char			brand[MAXNAMELEN];
1073 	zone_dochandle_t	handle = NULL;
1074 	brand_handle_t		bh = NULL;
1075 	struct zone_devtab	ztab;
1076 	di_prof_t		prof = NULL;
1077 	int			err;
1078 	int			retval = -1;
1079 	zone_iptype_t		iptype;
1080 	const char 		*curr_iptype;
1081 
1082 	if (di_prof_init(devpath, &prof)) {
1083 		zerror(zlogp, B_TRUE, "failed to initialize profile");
1084 		goto cleanup;
1085 	}
1086 
1087 	/*
1088 	 * Get a handle to the brand info for this zone.
1089 	 * If we are mounting the zone, then we must always use the default
1090 	 * brand device mounts.
1091 	 */
1092 	if (ALT_MOUNT(mount_cmd)) {
1093 		(void) strlcpy(brand, default_brand, sizeof (brand));
1094 	} else {
1095 		(void) strlcpy(brand, brand_name, sizeof (brand));
1096 	}
1097 
1098 	if ((bh = brand_open(brand)) == NULL) {
1099 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
1100 		goto cleanup;
1101 	}
1102 
1103 	if (vplat_get_iptype(zlogp, &iptype) < 0) {
1104 		zerror(zlogp, B_TRUE, "unable to determine ip-type");
1105 		goto cleanup;
1106 	}
1107 	switch (iptype) {
1108 	case ZS_SHARED:
1109 		curr_iptype = "shared";
1110 		break;
1111 	case ZS_EXCLUSIVE:
1112 		curr_iptype = "exclusive";
1113 		break;
1114 	}
1115 
1116 	if (brand_platform_iter_devices(bh, zone_name,
1117 	    mount_one_dev_device_cb, prof, curr_iptype) != 0) {
1118 		zerror(zlogp, B_TRUE, "failed to add standard device");
1119 		goto cleanup;
1120 	}
1121 
1122 	if (brand_platform_iter_link(bh,
1123 	    mount_one_dev_symlink_cb, prof) != 0) {
1124 		zerror(zlogp, B_TRUE, "failed to add standard symlink");
1125 		goto cleanup;
1126 	}
1127 
1128 	/* Add user-specified devices and directories */
1129 	if ((handle = zonecfg_init_handle()) == NULL) {
1130 		zerror(zlogp, B_FALSE, "can't initialize zone handle");
1131 		goto cleanup;
1132 	}
1133 	if (err = zonecfg_get_handle(zone_name, handle)) {
1134 		zerror(zlogp, B_FALSE, "can't get handle for zone "
1135 		    "%s: %s", zone_name, zonecfg_strerror(err));
1136 		goto cleanup;
1137 	}
1138 	if (err = zonecfg_setdevent(handle)) {
1139 		zerror(zlogp, B_FALSE, "%s: %s", zone_name,
1140 		    zonecfg_strerror(err));
1141 		goto cleanup;
1142 	}
1143 	while (zonecfg_getdevent(handle, &ztab) == Z_OK) {
1144 		if (di_prof_add_dev(prof, ztab.zone_dev_match)) {
1145 			zerror(zlogp, B_TRUE, "failed to add "
1146 			    "user-specified device");
1147 			goto cleanup;
1148 		}
1149 	}
1150 	(void) zonecfg_enddevent(handle);
1151 
1152 	/* Send profile to kernel */
1153 	if (di_prof_commit(prof)) {
1154 		zerror(zlogp, B_TRUE, "failed to commit profile");
1155 		goto cleanup;
1156 	}
1157 
1158 	retval = 0;
1159 
1160 cleanup:
1161 	if (bh != NULL)
1162 		brand_close(bh);
1163 	if (handle != NULL)
1164 		zonecfg_fini_handle(handle);
1165 	if (prof)
1166 		di_prof_fini(prof);
1167 	return (retval);
1168 }
1169 
1170 static int
1171 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath,
1172     zone_mnt_t mount_cmd)
1173 {
1174 	char path[MAXPATHLEN];
1175 	char specpath[MAXPATHLEN];
1176 	char optstr[MAX_MNTOPT_STR];
1177 	zone_fsopt_t *optptr;
1178 	int rv;
1179 
1180 	if ((rv = valid_mount_path(zlogp, rootpath, fsptr->zone_fs_special,
1181 	    fsptr->zone_fs_dir, fsptr->zone_fs_type)) < 0) {
1182 		zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1183 		    rootpath, fsptr->zone_fs_dir);
1184 		return (-1);
1185 	} else if (rv > 0) {
1186 		/* The mount point path doesn't exist, create it now. */
1187 		if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1188 		    DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
1189 		    DEFAULT_DIR_GROUP) != 0) {
1190 			zerror(zlogp, B_FALSE, "failed to create mount point");
1191 			return (-1);
1192 		}
1193 
1194 		/*
1195 		 * Now this might seem weird, but we need to invoke
1196 		 * valid_mount_path() again.  Why?  Because it checks
1197 		 * to make sure that the mount point path is canonical,
1198 		 * which it can only do if the path exists, so now that
1199 		 * we've created the path we have to verify it again.
1200 		 */
1201 		if ((rv = valid_mount_path(zlogp, rootpath,
1202 		    fsptr->zone_fs_special, fsptr->zone_fs_dir,
1203 		    fsptr->zone_fs_type)) < 0) {
1204 			zerror(zlogp, B_FALSE,
1205 			    "%s%s is not a valid mount point",
1206 			    rootpath, fsptr->zone_fs_dir);
1207 			return (-1);
1208 		}
1209 	}
1210 
1211 	(void) snprintf(path, sizeof (path), "%s%s", rootpath,
1212 	    fsptr->zone_fs_dir);
1213 
1214 	if (strlen(fsptr->zone_fs_special) == 0) {
1215 		/*
1216 		 * A zero-length special is how we distinguish IPDs from
1217 		 * general-purpose FSs.  Make sure it mounts from a place that
1218 		 * can be seen via the alternate zone's root.
1219 		 */
1220 		if (snprintf(specpath, sizeof (specpath), "%s%s",
1221 		    zonecfg_get_root(), fsptr->zone_fs_dir) >=
1222 		    sizeof (specpath)) {
1223 			zerror(zlogp, B_FALSE, "cannot mount %s: path too "
1224 			    "long in alternate root", fsptr->zone_fs_dir);
1225 			return (-1);
1226 		}
1227 		if (zonecfg_in_alt_root())
1228 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1229 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS,
1230 		    specpath, path) != 0) {
1231 			zerror(zlogp, B_TRUE, "failed to loopback mount %s",
1232 			    specpath);
1233 			return (-1);
1234 		}
1235 		return (0);
1236 	}
1237 
1238 	/*
1239 	 * In general the strategy here is to do just as much verification as
1240 	 * necessary to avoid crashing or otherwise doing something bad; if the
1241 	 * administrator initiated the operation via zoneadm(1m), he'll get
1242 	 * auto-verification which will let him know what's wrong.  If he
1243 	 * modifies the zone configuration of a running zone and doesn't attempt
1244 	 * to verify that it's OK we won't crash but won't bother trying to be
1245 	 * too helpful either.  zoneadm verify is only a couple keystrokes away.
1246 	 */
1247 	if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1248 		zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1249 		    "invalid file-system type %s", fsptr->zone_fs_special,
1250 		    fsptr->zone_fs_dir, fsptr->zone_fs_type);
1251 		return (-1);
1252 	}
1253 
1254 	/*
1255 	 * If we're looking at an alternate root environment, then construct
1256 	 * read-only loopback mounts as necessary.  Note that any special
1257 	 * paths for lofs zone mounts in an alternate root must have
1258 	 * already been pre-pended with any alternate root path by the
1259 	 * time we get here.
1260 	 */
1261 	if (zonecfg_in_alt_root()) {
1262 		struct stat64 st;
1263 
1264 		if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1265 		    S_ISBLK(st.st_mode)) {
1266 			/*
1267 			 * If we're going to mount a block device we need
1268 			 * to check if that device is already mounted
1269 			 * somewhere else, and if so, do a lofs mount
1270 			 * of the device instead of a direct mount
1271 			 */
1272 			if (check_lofs_needed(zlogp, fsptr) == -1)
1273 				return (-1);
1274 		} else if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1275 			/*
1276 			 * For lofs mounts, the special node is inside the
1277 			 * alternate root.  We need lofs resolution for
1278 			 * this case in order to get at the underlying
1279 			 * read-write path.
1280 			 */
1281 			resolve_lofs(zlogp, fsptr->zone_fs_special,
1282 			    sizeof (fsptr->zone_fs_special));
1283 		}
1284 	}
1285 
1286 	/*
1287 	 * Run 'fsck -m' if there's a device to fsck.
1288 	 */
1289 	if (fsptr->zone_fs_raw[0] != '\0' &&
1290 	    dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0) {
1291 		return (-1);
1292 	} else if (isregfile(fsptr->zone_fs_special) == 1 &&
1293 	    dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_special) != 0) {
1294 		return (-1);
1295 	}
1296 
1297 	/*
1298 	 * Build up mount option string.
1299 	 */
1300 	optstr[0] = '\0';
1301 	if (fsptr->zone_fs_options != NULL) {
1302 		(void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1303 		    sizeof (optstr));
1304 		for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1305 		    optptr != NULL; optptr = optptr->zone_fsopt_next) {
1306 			(void) strlcat(optstr, ",", sizeof (optstr));
1307 			(void) strlcat(optstr, optptr->zone_fsopt_opt,
1308 			    sizeof (optstr));
1309 		}
1310 	}
1311 
1312 	if ((rv = domount(zlogp, fsptr->zone_fs_type, optstr,
1313 	    fsptr->zone_fs_special, path)) != 0)
1314 		return (rv);
1315 
1316 	/*
1317 	 * The mount succeeded.  If this was not a mount of /dev then
1318 	 * we're done.
1319 	 */
1320 	if (strcmp(fsptr->zone_fs_type, MNTTYPE_DEV) != 0)
1321 		return (0);
1322 
1323 	/*
1324 	 * We just mounted an instance of a /dev filesystem, so now we
1325 	 * need to configure it.
1326 	 */
1327 	return (mount_one_dev(zlogp, path, mount_cmd));
1328 }
1329 
1330 static void
1331 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1332 {
1333 	uint_t i;
1334 
1335 	if (fsarray == NULL)
1336 		return;
1337 	for (i = 0; i < nelem; i++)
1338 		zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1339 	free(fsarray);
1340 }
1341 
1342 /*
1343  * This function initiates the creation of a small Solaris Environment for
1344  * scratch zone. The Environment creation process is split up into two
1345  * functions(build_mounted_pre_var() and build_mounted_post_var()). It
1346  * is done this way because:
1347  * 	We need to have both /etc and /var in the root of the scratchzone.
1348  * 	We loopback mount zone's own /etc and /var into the root of the
1349  * 	scratch zone. Unlike /etc, /var can be a seperate filesystem. So we
1350  * 	need to delay the mount of /var till the zone's root gets populated.
1351  *	So mounting of localdirs[](/etc and /var) have been moved to the
1352  * 	build_mounted_post_var() which gets called only after the zone
1353  * 	specific filesystems are mounted.
1354  *
1355  * Note that the scratch zone we set up for updating the zone (Z_MNT_UPDATE)
1356  * does not loopback mount the zone's own /etc and /var into the root of the
1357  * scratch zone.
1358  */
1359 static boolean_t
1360 build_mounted_pre_var(zlog_t *zlogp, char *rootpath,
1361     size_t rootlen, const char *zonepath, char *luroot, size_t lurootlen)
1362 {
1363 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1364 	const char **cpp;
1365 	static const char *mkdirs[] = {
1366 		"/system", "/system/contract", "/system/object", "/proc",
1367 		"/dev", "/tmp", "/a", NULL
1368 	};
1369 	char *altstr;
1370 	FILE *fp;
1371 	uuid_t uuid;
1372 
1373 	resolve_lofs(zlogp, rootpath, rootlen);
1374 	(void) snprintf(luroot, lurootlen, "%s/lu", zonepath);
1375 	resolve_lofs(zlogp, luroot, lurootlen);
1376 	(void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1377 	(void) symlink("./usr/bin", tmp);
1378 
1379 	/*
1380 	 * These are mostly special mount points; not handled here.  (See
1381 	 * zone_mount_early.)
1382 	 */
1383 	for (cpp = mkdirs; *cpp != NULL; cpp++) {
1384 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1385 		if (mkdir(tmp, 0755) != 0) {
1386 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1387 			return (B_FALSE);
1388 		}
1389 	}
1390 	/*
1391 	 * This is here to support lucopy.  If there's an instance of this same
1392 	 * zone on the current running system, then we mount its root up as
1393 	 * read-only inside the scratch zone.
1394 	 */
1395 	(void) zonecfg_get_uuid(zone_name, uuid);
1396 	altstr = strdup(zonecfg_get_root());
1397 	if (altstr == NULL) {
1398 		zerror(zlogp, B_TRUE, "memory allocation failed");
1399 		return (B_FALSE);
1400 	}
1401 	zonecfg_set_root("");
1402 	(void) strlcpy(tmp, zone_name, sizeof (tmp));
1403 	(void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1404 	if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1405 	    strcmp(fromdir, rootpath) != 0) {
1406 		(void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1407 		if (mkdir(tmp, 0755) != 0) {
1408 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1409 			return (B_FALSE);
1410 		}
1411 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, fromdir,
1412 		    tmp) != 0) {
1413 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1414 			    fromdir);
1415 			return (B_FALSE);
1416 		}
1417 	}
1418 	zonecfg_set_root(altstr);
1419 	free(altstr);
1420 
1421 	if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1422 		zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1423 		return (B_FALSE);
1424 	}
1425 	(void) ftruncate(fileno(fp), 0);
1426 	if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1427 		zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1428 	}
1429 	zonecfg_close_scratch(fp);
1430 	(void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1431 	if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1432 		return (B_FALSE);
1433 	(void) strlcpy(rootpath, tmp, rootlen);
1434 	return (B_TRUE);
1435 }
1436 
1437 
1438 static boolean_t
1439 build_mounted_post_var(zlog_t *zlogp, zone_mnt_t mount_cmd, char *rootpath,
1440     const char *luroot)
1441 {
1442 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1443 	const char **cpp;
1444 	const char **loopdirs;
1445 	const char **tmpdirs;
1446 	static const char *localdirs[] = {
1447 		"/etc", "/var", NULL
1448 	};
1449 	static const char *scr_loopdirs[] = {
1450 		"/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1451 		"/usr", NULL
1452 	};
1453 	static const char *upd_loopdirs[] = {
1454 		"/etc", "/kernel", "/lib", "/opt", "/platform", "/sbin",
1455 		"/usr", "/var", NULL
1456 	};
1457 	static const char *scr_tmpdirs[] = {
1458 		"/tmp", "/var/run", NULL
1459 	};
1460 	static const char *upd_tmpdirs[] = {
1461 		"/tmp", "/var/run", "/var/tmp", NULL
1462 	};
1463 	struct stat st;
1464 
1465 	if (mount_cmd == Z_MNT_SCRATCH) {
1466 		/*
1467 		 * These are mounted read-write from the zone undergoing
1468 		 * upgrade.  We must be careful not to 'leak' things from the
1469 		 * main system into the zone, and this accomplishes that goal.
1470 		 */
1471 		for (cpp = localdirs; *cpp != NULL; cpp++) {
1472 			(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot,
1473 			    *cpp);
1474 			(void) snprintf(fromdir, sizeof (fromdir), "%s%s",
1475 			    rootpath, *cpp);
1476 			if (mkdir(tmp, 0755) != 0) {
1477 				zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1478 				return (B_FALSE);
1479 			}
1480 			if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp)
1481 			    != 0) {
1482 				zerror(zlogp, B_TRUE, "cannot mount %s on %s",
1483 				    tmp, *cpp);
1484 				return (B_FALSE);
1485 			}
1486 		}
1487 	}
1488 
1489 	if (mount_cmd == Z_MNT_UPDATE)
1490 		loopdirs = upd_loopdirs;
1491 	else
1492 		loopdirs = scr_loopdirs;
1493 
1494 	/*
1495 	 * These are things mounted read-only from the running system because
1496 	 * they contain binaries that must match system.
1497 	 */
1498 	for (cpp = loopdirs; *cpp != NULL; cpp++) {
1499 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1500 		if (mkdir(tmp, 0755) != 0) {
1501 			if (errno != EEXIST) {
1502 				zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1503 				return (B_FALSE);
1504 			}
1505 			if (lstat(tmp, &st) != 0) {
1506 				zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1507 				return (B_FALSE);
1508 			}
1509 			/*
1510 			 * Ignore any non-directories encountered.  These are
1511 			 * things that have been converted into symlinks
1512 			 * (/etc/fs and /etc/lib) and no longer need a lofs
1513 			 * fixup.
1514 			 */
1515 			if (!S_ISDIR(st.st_mode))
1516 				continue;
1517 		}
1518 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, *cpp,
1519 		    tmp) != 0) {
1520 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1521 			    *cpp);
1522 			return (B_FALSE);
1523 		}
1524 	}
1525 
1526 	if (mount_cmd == Z_MNT_UPDATE)
1527 		tmpdirs = upd_tmpdirs;
1528 	else
1529 		tmpdirs = scr_tmpdirs;
1530 
1531 	/*
1532 	 * These are things with tmpfs mounted inside.
1533 	 */
1534 	for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1535 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1536 		if (mount_cmd == Z_MNT_SCRATCH && mkdir(tmp, 0755) != 0 &&
1537 		    errno != EEXIST) {
1538 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1539 			return (B_FALSE);
1540 		}
1541 
1542 		/*
1543 		 * We could set the mode for /tmp when we do the mkdir but
1544 		 * since that can be modified by the umask we will just set
1545 		 * the correct mode for /tmp now.
1546 		 */
1547 		if (strcmp(*cpp, "/tmp") == 0 && chmod(tmp, 01777) != 0) {
1548 			zerror(zlogp, B_TRUE, "cannot chmod %s", tmp);
1549 			return (B_FALSE);
1550 		}
1551 
1552 		if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1553 			zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1554 			return (B_FALSE);
1555 		}
1556 	}
1557 	return (B_TRUE);
1558 }
1559 
1560 typedef struct plat_gmount_cb_data {
1561 	zlog_t			*pgcd_zlogp;
1562 	struct zone_fstab	**pgcd_fs_tab;
1563 	int			*pgcd_num_fs;
1564 } plat_gmount_cb_data_t;
1565 
1566 /*
1567  * plat_gmount_cb() is a callback function invoked by libbrand to iterate
1568  * through all global brand platform mounts.
1569  */
1570 int
1571 plat_gmount_cb(void *data, const char *spec, const char *dir,
1572     const char *fstype, const char *opt)
1573 {
1574 	plat_gmount_cb_data_t	*cp = data;
1575 	zlog_t			*zlogp = cp->pgcd_zlogp;
1576 	struct zone_fstab	*fs_ptr = *cp->pgcd_fs_tab;
1577 	int			num_fs = *cp->pgcd_num_fs;
1578 	struct zone_fstab	*fsp, *tmp_ptr;
1579 
1580 	num_fs++;
1581 	if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1582 		zerror(zlogp, B_TRUE, "memory allocation failed");
1583 		return (-1);
1584 	}
1585 
1586 	fs_ptr = tmp_ptr;
1587 	fsp = &fs_ptr[num_fs - 1];
1588 
1589 	/* update the callback struct passed in */
1590 	*cp->pgcd_fs_tab = fs_ptr;
1591 	*cp->pgcd_num_fs = num_fs;
1592 
1593 	fsp->zone_fs_raw[0] = '\0';
1594 	(void) strlcpy(fsp->zone_fs_special, spec,
1595 	    sizeof (fsp->zone_fs_special));
1596 	(void) strlcpy(fsp->zone_fs_dir, dir, sizeof (fsp->zone_fs_dir));
1597 	(void) strlcpy(fsp->zone_fs_type, fstype, sizeof (fsp->zone_fs_type));
1598 	fsp->zone_fs_options = NULL;
1599 	if ((opt != NULL) &&
1600 	    (zonecfg_add_fs_option(fsp, (char *)opt) != Z_OK)) {
1601 		zerror(zlogp, B_FALSE, "error adding property");
1602 		return (-1);
1603 	}
1604 
1605 	return (0);
1606 }
1607 
1608 static int
1609 mount_filesystems_ipdent(zone_dochandle_t handle, zlog_t *zlogp,
1610     struct zone_fstab **fs_tabp, int *num_fsp)
1611 {
1612 	struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1613 	int num_fs;
1614 
1615 	num_fs = *num_fsp;
1616 	fs_ptr = *fs_tabp;
1617 
1618 	if (zonecfg_setipdent(handle) != Z_OK) {
1619 		zerror(zlogp, B_FALSE, "invalid configuration");
1620 		return (-1);
1621 	}
1622 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1623 		num_fs++;
1624 		if ((tmp_ptr = realloc(fs_ptr,
1625 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1626 			zerror(zlogp, B_TRUE, "memory allocation failed");
1627 			(void) zonecfg_endipdent(handle);
1628 			return (-1);
1629 		}
1630 
1631 		/* update the pointers passed in */
1632 		*fs_tabp = tmp_ptr;
1633 		*num_fsp = num_fs;
1634 
1635 		/*
1636 		 * IPDs logically only have a mount point; all other properties
1637 		 * are implied.
1638 		 */
1639 		fs_ptr = tmp_ptr;
1640 		fsp = &fs_ptr[num_fs - 1];
1641 		(void) strlcpy(fsp->zone_fs_dir,
1642 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1643 		fsp->zone_fs_special[0] = '\0';
1644 		fsp->zone_fs_raw[0] = '\0';
1645 		fsp->zone_fs_type[0] = '\0';
1646 		fsp->zone_fs_options = NULL;
1647 	}
1648 	(void) zonecfg_endipdent(handle);
1649 	return (0);
1650 }
1651 
1652 static int
1653 mount_filesystems_fsent(zone_dochandle_t handle, zlog_t *zlogp,
1654     struct zone_fstab **fs_tabp, int *num_fsp, zone_mnt_t mount_cmd)
1655 {
1656 	struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1657 	int num_fs;
1658 
1659 	num_fs = *num_fsp;
1660 	fs_ptr = *fs_tabp;
1661 
1662 	if (zonecfg_setfsent(handle) != Z_OK) {
1663 		zerror(zlogp, B_FALSE, "invalid configuration");
1664 		return (-1);
1665 	}
1666 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1667 		/*
1668 		 * ZFS filesystems will not be accessible under an alternate
1669 		 * root, since the pool will not be known.  Ignore them in this
1670 		 * case.
1671 		 */
1672 		if (ALT_MOUNT(mount_cmd) &&
1673 		    strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1674 			continue;
1675 
1676 		num_fs++;
1677 		if ((tmp_ptr = realloc(fs_ptr,
1678 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1679 			zerror(zlogp, B_TRUE, "memory allocation failed");
1680 			(void) zonecfg_endfsent(handle);
1681 			return (-1);
1682 		}
1683 		/* update the pointers passed in */
1684 		*fs_tabp = tmp_ptr;
1685 		*num_fsp = num_fs;
1686 
1687 		fs_ptr = tmp_ptr;
1688 		fsp = &fs_ptr[num_fs - 1];
1689 		(void) strlcpy(fsp->zone_fs_dir,
1690 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1691 		(void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1692 		    sizeof (fsp->zone_fs_raw));
1693 		(void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1694 		    sizeof (fsp->zone_fs_type));
1695 		fsp->zone_fs_options = fstab.zone_fs_options;
1696 
1697 		/*
1698 		 * For all lofs mounts, make sure that the 'special'
1699 		 * entry points inside the alternate root.  The
1700 		 * source path for a lofs mount in a given zone needs
1701 		 * to be relative to the root of the boot environment
1702 		 * that contains the zone.  Note that we don't do this
1703 		 * for non-lofs mounts since they will have a device
1704 		 * as a backing store and device paths must always be
1705 		 * specified relative to the current boot environment.
1706 		 */
1707 		fsp->zone_fs_special[0] = '\0';
1708 		if (strcmp(fsp->zone_fs_type, MNTTYPE_LOFS) == 0) {
1709 			(void) strlcat(fsp->zone_fs_special, zonecfg_get_root(),
1710 			    sizeof (fsp->zone_fs_special));
1711 		}
1712 		(void) strlcat(fsp->zone_fs_special, fstab.zone_fs_special,
1713 		    sizeof (fsp->zone_fs_special));
1714 	}
1715 	(void) zonecfg_endfsent(handle);
1716 	return (0);
1717 }
1718 
1719 static int
1720 mount_filesystems(zlog_t *zlogp, zone_mnt_t mount_cmd)
1721 {
1722 	char rootpath[MAXPATHLEN];
1723 	char zonepath[MAXPATHLEN];
1724 	char brand[MAXNAMELEN];
1725 	char luroot[MAXPATHLEN];
1726 	int i, num_fs = 0;
1727 	struct zone_fstab *fs_ptr = NULL;
1728 	zone_dochandle_t handle = NULL;
1729 	zone_state_t zstate;
1730 	brand_handle_t bh;
1731 	plat_gmount_cb_data_t cb;
1732 
1733 	if (zone_get_state(zone_name, &zstate) != Z_OK ||
1734 	    (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1735 		zerror(zlogp, B_FALSE,
1736 		    "zone must be in '%s' or '%s' state to mount file-systems",
1737 		    zone_state_str(ZONE_STATE_READY),
1738 		    zone_state_str(ZONE_STATE_MOUNTED));
1739 		goto bad;
1740 	}
1741 
1742 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1743 		zerror(zlogp, B_TRUE, "unable to determine zone path");
1744 		goto bad;
1745 	}
1746 
1747 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1748 		zerror(zlogp, B_TRUE, "unable to determine zone root");
1749 		goto bad;
1750 	}
1751 
1752 	if ((handle = zonecfg_init_handle()) == NULL) {
1753 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
1754 		goto bad;
1755 	}
1756 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1757 	    zonecfg_setfsent(handle) != Z_OK) {
1758 		zerror(zlogp, B_FALSE, "invalid configuration");
1759 		goto bad;
1760 	}
1761 
1762 	/*
1763 	 * If we are mounting the zone, then we must always use the default
1764 	 * brand global mounts.
1765 	 */
1766 	if (ALT_MOUNT(mount_cmd)) {
1767 		(void) strlcpy(brand, default_brand, sizeof (brand));
1768 	} else {
1769 		(void) strlcpy(brand, brand_name, sizeof (brand));
1770 	}
1771 
1772 	/* Get a handle to the brand info for this zone */
1773 	if ((bh = brand_open(brand)) == NULL) {
1774 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
1775 		zonecfg_fini_handle(handle);
1776 		return (-1);
1777 	}
1778 
1779 	/*
1780 	 * Get the list of global filesystems to mount from the brand
1781 	 * configuration.
1782 	 */
1783 	cb.pgcd_zlogp = zlogp;
1784 	cb.pgcd_fs_tab = &fs_ptr;
1785 	cb.pgcd_num_fs = &num_fs;
1786 	if (brand_platform_iter_gmounts(bh, zonepath,
1787 	    plat_gmount_cb, &cb) != 0) {
1788 		zerror(zlogp, B_FALSE, "unable to mount filesystems");
1789 		brand_close(bh);
1790 		zonecfg_fini_handle(handle);
1791 		return (-1);
1792 	}
1793 	brand_close(bh);
1794 
1795 	/*
1796 	 * Iterate through the rest of the filesystems, first the IPDs, then
1797 	 * the general FSs.  Sort them all, then mount them in sorted order.
1798 	 * This is to make sure the higher level directories (e.g., /usr)
1799 	 * get mounted before any beneath them (e.g., /usr/local).
1800 	 */
1801 	if (mount_filesystems_ipdent(handle, zlogp, &fs_ptr, &num_fs) != 0)
1802 		goto bad;
1803 
1804 	if (mount_filesystems_fsent(handle, zlogp, &fs_ptr, &num_fs,
1805 	    mount_cmd) != 0)
1806 		goto bad;
1807 
1808 	zonecfg_fini_handle(handle);
1809 	handle = NULL;
1810 
1811 	/*
1812 	 * Normally when we mount a zone all the zone filesystems
1813 	 * get mounted relative to rootpath, which is usually
1814 	 * <zonepath>/root.  But when mounting a zone for administration
1815 	 * purposes via the zone "mount" state, build_mounted_pre_var()
1816 	 * updates rootpath to be <zonepath>/lu/a so we'll mount all
1817 	 * the zones filesystems there instead.
1818 	 *
1819 	 * build_mounted_pre_var() and build_mounted_post_var() will
1820 	 * also do some extra work to create directories and lofs mount
1821 	 * a bunch of global zone file system paths into <zonepath>/lu.
1822 	 *
1823 	 * This allows us to be able to enter the zone (now rooted at
1824 	 * <zonepath>/lu) and run the upgrade/patch tools that are in the
1825 	 * global zone and have them upgrade the to-be-modified zone's
1826 	 * files mounted on /a.  (Which mirrors the existing standard
1827 	 * upgrade environment.)
1828 	 *
1829 	 * There is of course one catch.  When doing the upgrade
1830 	 * we need <zoneroot>/lu/dev to be the /dev filesystem
1831 	 * for the zone and we don't want to have any /dev filesystem
1832 	 * mounted at <zoneroot>/lu/a/dev.  Since /dev is specified
1833 	 * as a normal zone filesystem by default we'll try to mount
1834 	 * it at <zoneroot>/lu/a/dev, so we have to detect this
1835 	 * case and instead mount it at <zoneroot>/lu/dev.
1836 	 *
1837 	 * All this work is done in three phases:
1838 	 *   1) Create and populate lu directory (build_mounted_pre_var()).
1839 	 *   2) Mount the required filesystems as per the zone configuration.
1840 	 *   3) Set up the rest of the scratch zone environment
1841 	 *	(build_mounted_post_var()).
1842 	 */
1843 	if (ALT_MOUNT(mount_cmd) && !build_mounted_pre_var(zlogp,
1844 	    rootpath, sizeof (rootpath), zonepath, luroot, sizeof (luroot)))
1845 		goto bad;
1846 
1847 	qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1848 
1849 	for (i = 0; i < num_fs; i++) {
1850 		if (ALT_MOUNT(mount_cmd) &&
1851 		    strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1852 			size_t slen = strlen(rootpath) - 2;
1853 
1854 			/*
1855 			 * By default we'll try to mount /dev as /a/dev
1856 			 * but /dev is special and always goes at the top
1857 			 * so strip the trailing '/a' from the rootpath.
1858 			 */
1859 			assert(strcmp(&rootpath[slen], "/a") == 0);
1860 			rootpath[slen] = '\0';
1861 			if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd)
1862 			    != 0)
1863 				goto bad;
1864 			rootpath[slen] = '/';
1865 			continue;
1866 		}
1867 		if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd) != 0)
1868 			goto bad;
1869 	}
1870 	if (ALT_MOUNT(mount_cmd) &&
1871 	    !build_mounted_post_var(zlogp, mount_cmd, rootpath, luroot))
1872 		goto bad;
1873 
1874 	/*
1875 	 * For Trusted Extensions cross-mount each lower level /export/home
1876 	 */
1877 	if (mount_cmd == Z_MNT_BOOT &&
1878 	    tsol_mounts(zlogp, zone_name, rootpath) != 0)
1879 		goto bad;
1880 
1881 	free_fs_data(fs_ptr, num_fs);
1882 
1883 	/*
1884 	 * Everything looks fine.
1885 	 */
1886 	return (0);
1887 
1888 bad:
1889 	if (handle != NULL)
1890 		zonecfg_fini_handle(handle);
1891 	free_fs_data(fs_ptr, num_fs);
1892 	return (-1);
1893 }
1894 
1895 /* caller makes sure neither parameter is NULL */
1896 static int
1897 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1898 {
1899 	int prefixlen;
1900 
1901 	prefixlen = atoi(prefixstr);
1902 	if (prefixlen < 0 || prefixlen > maxprefixlen)
1903 		return (1);
1904 	while (prefixlen > 0) {
1905 		if (prefixlen >= 8) {
1906 			*maskstr++ = 0xFF;
1907 			prefixlen -= 8;
1908 			continue;
1909 		}
1910 		*maskstr |= 1 << (8 - prefixlen);
1911 		prefixlen--;
1912 	}
1913 	return (0);
1914 }
1915 
1916 /*
1917  * Tear down all interfaces belonging to the given zone.  This should
1918  * be called with the zone in a state other than "running", so that
1919  * interfaces can't be assigned to the zone after this returns.
1920  *
1921  * If anything goes wrong, log an error message and return an error.
1922  */
1923 static int
1924 unconfigure_shared_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1925 {
1926 	struct lifnum lifn;
1927 	struct lifconf lifc;
1928 	struct lifreq *lifrp, lifrl;
1929 	int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1930 	int num_ifs, s, i, ret_code = 0;
1931 	uint_t bufsize;
1932 	char *buf = NULL;
1933 
1934 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1935 		zerror(zlogp, B_TRUE, "could not get socket");
1936 		ret_code = -1;
1937 		goto bad;
1938 	}
1939 	lifn.lifn_family = AF_UNSPEC;
1940 	lifn.lifn_flags = (int)lifc_flags;
1941 	if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1942 		zerror(zlogp, B_TRUE,
1943 		    "could not determine number of network interfaces");
1944 		ret_code = -1;
1945 		goto bad;
1946 	}
1947 	num_ifs = lifn.lifn_count;
1948 	bufsize = num_ifs * sizeof (struct lifreq);
1949 	if ((buf = malloc(bufsize)) == NULL) {
1950 		zerror(zlogp, B_TRUE, "memory allocation failed");
1951 		ret_code = -1;
1952 		goto bad;
1953 	}
1954 	lifc.lifc_family = AF_UNSPEC;
1955 	lifc.lifc_flags = (int)lifc_flags;
1956 	lifc.lifc_len = bufsize;
1957 	lifc.lifc_buf = buf;
1958 	if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1959 		zerror(zlogp, B_TRUE, "could not get configured network "
1960 		    "interfaces");
1961 		ret_code = -1;
1962 		goto bad;
1963 	}
1964 	lifrp = lifc.lifc_req;
1965 	for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1966 		(void) close(s);
1967 		if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1968 		    0) {
1969 			zerror(zlogp, B_TRUE, "%s: could not get socket",
1970 			    lifrl.lifr_name);
1971 			ret_code = -1;
1972 			continue;
1973 		}
1974 		(void) memset(&lifrl, 0, sizeof (lifrl));
1975 		(void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1976 		    sizeof (lifrl.lifr_name));
1977 		if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1978 			if (errno == ENXIO)
1979 				/*
1980 				 * Interface may have been removed by admin or
1981 				 * another zone halting.
1982 				 */
1983 				continue;
1984 			zerror(zlogp, B_TRUE,
1985 			    "%s: could not determine the zone to which this "
1986 			    "network interface is bound", lifrl.lifr_name);
1987 			ret_code = -1;
1988 			continue;
1989 		}
1990 		if (lifrl.lifr_zoneid == zone_id) {
1991 			if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1992 				zerror(zlogp, B_TRUE,
1993 				    "%s: could not remove network interface",
1994 				    lifrl.lifr_name);
1995 				ret_code = -1;
1996 				continue;
1997 			}
1998 		}
1999 	}
2000 bad:
2001 	if (s > 0)
2002 		(void) close(s);
2003 	if (buf)
2004 		free(buf);
2005 	return (ret_code);
2006 }
2007 
2008 static union	sockunion {
2009 	struct	sockaddr sa;
2010 	struct	sockaddr_in sin;
2011 	struct	sockaddr_dl sdl;
2012 	struct	sockaddr_in6 sin6;
2013 } so_dst, so_ifp;
2014 
2015 static struct {
2016 	struct	rt_msghdr hdr;
2017 	char	space[512];
2018 } rtmsg;
2019 
2020 static int
2021 salen(struct sockaddr *sa)
2022 {
2023 	switch (sa->sa_family) {
2024 	case AF_INET:
2025 		return (sizeof (struct sockaddr_in));
2026 	case AF_LINK:
2027 		return (sizeof (struct sockaddr_dl));
2028 	case AF_INET6:
2029 		return (sizeof (struct sockaddr_in6));
2030 	default:
2031 		return (sizeof (struct sockaddr));
2032 	}
2033 }
2034 
2035 #define	ROUNDUP_LONG(a) \
2036 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
2037 
2038 /*
2039  * Look up which zone is using a given IP address.  The address in question
2040  * is expected to have been stuffed into the structure to which lifr points
2041  * via a previous SIOCGLIFADDR ioctl().
2042  *
2043  * This is done using black router socket magic.
2044  *
2045  * Return the name of the zone on success or NULL on failure.
2046  *
2047  * This is a lot of code for a simple task; a new ioctl request to take care
2048  * of this might be a useful RFE.
2049  */
2050 
2051 static char *
2052 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
2053 {
2054 	static char answer[ZONENAME_MAX];
2055 	pid_t pid;
2056 	int s, rlen, l, i;
2057 	char *cp = rtmsg.space;
2058 	struct sockaddr_dl *ifp = NULL;
2059 	struct sockaddr *sa;
2060 	char save_if_name[LIFNAMSIZ];
2061 
2062 	answer[0] = '\0';
2063 
2064 	pid = getpid();
2065 	if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
2066 		zerror(zlogp, B_TRUE, "could not get routing socket");
2067 		return (NULL);
2068 	}
2069 
2070 	if (lifr->lifr_addr.ss_family == AF_INET) {
2071 		struct sockaddr_in *sin4;
2072 
2073 		so_dst.sa.sa_family = AF_INET;
2074 		sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
2075 		so_dst.sin.sin_addr = sin4->sin_addr;
2076 	} else {
2077 		struct sockaddr_in6 *sin6;
2078 
2079 		so_dst.sa.sa_family = AF_INET6;
2080 		sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
2081 		so_dst.sin6.sin6_addr = sin6->sin6_addr;
2082 	}
2083 
2084 	so_ifp.sa.sa_family = AF_LINK;
2085 
2086 	(void) memset(&rtmsg, 0, sizeof (rtmsg));
2087 	rtmsg.hdr.rtm_type = RTM_GET;
2088 	rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
2089 	rtmsg.hdr.rtm_version = RTM_VERSION;
2090 	rtmsg.hdr.rtm_seq = ++rts_seqno;
2091 	rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
2092 
2093 	l = ROUNDUP_LONG(salen(&so_dst.sa));
2094 	(void) memmove(cp, &(so_dst), l);
2095 	cp += l;
2096 	l = ROUNDUP_LONG(salen(&so_ifp.sa));
2097 	(void) memmove(cp, &(so_ifp), l);
2098 	cp += l;
2099 
2100 	rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
2101 
2102 	if ((rlen = write(s, &rtmsg, l)) < 0) {
2103 		zerror(zlogp, B_TRUE, "writing to routing socket");
2104 		return (NULL);
2105 	} else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
2106 		zerror(zlogp, B_TRUE,
2107 		    "write to routing socket got only %d for len\n", rlen);
2108 		return (NULL);
2109 	}
2110 	do {
2111 		l = read(s, &rtmsg, sizeof (rtmsg));
2112 	} while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
2113 	    rtmsg.hdr.rtm_pid != pid));
2114 	if (l < 0) {
2115 		zerror(zlogp, B_TRUE, "reading from routing socket");
2116 		return (NULL);
2117 	}
2118 
2119 	if (rtmsg.hdr.rtm_version != RTM_VERSION) {
2120 		zerror(zlogp, B_FALSE,
2121 		    "routing message version %d not understood",
2122 		    rtmsg.hdr.rtm_version);
2123 		return (NULL);
2124 	}
2125 	if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
2126 		zerror(zlogp, B_FALSE, "message length mismatch, "
2127 		    "expected %d bytes, returned %d bytes",
2128 		    rtmsg.hdr.rtm_msglen, l);
2129 		return (NULL);
2130 	}
2131 	if (rtmsg.hdr.rtm_errno != 0)  {
2132 		errno = rtmsg.hdr.rtm_errno;
2133 		zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
2134 		return (NULL);
2135 	}
2136 	if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
2137 		zerror(zlogp, B_FALSE, "network interface not found");
2138 		return (NULL);
2139 	}
2140 	cp = ((char *)(&rtmsg.hdr + 1));
2141 	for (i = 1; i != 0; i <<= 1) {
2142 		/* LINTED E_BAD_PTR_CAST_ALIGN */
2143 		sa = (struct sockaddr *)cp;
2144 		if (i != RTA_IFP) {
2145 			if ((i & rtmsg.hdr.rtm_addrs) != 0)
2146 				cp += ROUNDUP_LONG(salen(sa));
2147 			continue;
2148 		}
2149 		if (sa->sa_family == AF_LINK &&
2150 		    ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
2151 			ifp = (struct sockaddr_dl *)sa;
2152 		break;
2153 	}
2154 	if (ifp == NULL) {
2155 		zerror(zlogp, B_FALSE, "network interface could not be "
2156 		    "determined");
2157 		return (NULL);
2158 	}
2159 
2160 	/*
2161 	 * We need to set the I/F name to what we got above, then do the
2162 	 * appropriate ioctl to get its zone name.  But lifr->lifr_name is
2163 	 * used by the calling function to do a REMOVEIF, so if we leave the
2164 	 * "good" zone's I/F name in place, *that* I/F will be removed instead
2165 	 * of the bad one.  So we save the old (bad) I/F name before over-
2166 	 * writing it and doing the ioctl, then restore it after the ioctl.
2167 	 */
2168 	(void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
2169 	(void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
2170 	lifr->lifr_name[ifp->sdl_nlen] = '\0';
2171 	i = ioctl(s, SIOCGLIFZONE, lifr);
2172 	(void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
2173 	if (i < 0) {
2174 		zerror(zlogp, B_TRUE,
2175 		    "%s: could not determine the zone network interface "
2176 		    "belongs to", lifr->lifr_name);
2177 		return (NULL);
2178 	}
2179 	if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
2180 		(void) snprintf(answer, sizeof (answer), "%d",
2181 		    lifr->lifr_zoneid);
2182 
2183 	if (strlen(answer) > 0)
2184 		return (answer);
2185 	return (NULL);
2186 }
2187 
2188 /*
2189  * Configures a single interface: a new virtual interface is added, based on
2190  * the physical interface nwiftabptr->zone_nwif_physical, with the address
2191  * specified in nwiftabptr->zone_nwif_address, for zone zone_id.  Note that
2192  * the "address" can be an IPv6 address (with a /prefixlength required), an
2193  * IPv4 address (with a /prefixlength optional), or a name; for the latter,
2194  * an IPv4 name-to-address resolution will be attempted.
2195  *
2196  * If anything goes wrong, we log an detailed error message, attempt to tear
2197  * down whatever we set up and return an error.
2198  */
2199 static int
2200 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
2201     struct zone_nwiftab *nwiftabptr)
2202 {
2203 	struct lifreq lifr;
2204 	struct sockaddr_in netmask4;
2205 	struct sockaddr_in6 netmask6;
2206 	struct sockaddr_storage laddr;
2207 	struct in_addr in4;
2208 	sa_family_t af;
2209 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2210 	int s;
2211 	boolean_t got_netmask = B_FALSE;
2212 	boolean_t is_loopback = B_FALSE;
2213 	char addrstr4[INET_ADDRSTRLEN];
2214 	int res;
2215 
2216 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2217 	if (res != Z_OK) {
2218 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2219 		    nwiftabptr->zone_nwif_address);
2220 		return (-1);
2221 	}
2222 	af = lifr.lifr_addr.ss_family;
2223 	if (af == AF_INET)
2224 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2225 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2226 		zerror(zlogp, B_TRUE, "could not get socket");
2227 		return (-1);
2228 	}
2229 
2230 	/*
2231 	 * This is a similar kind of "hack" like in addif() to get around
2232 	 * the problem of SIOCLIFADDIF.  The problem is that this ioctl
2233 	 * does not include the netmask when adding a logical interface.
2234 	 * To get around this problem, we first add the logical interface
2235 	 * with a 0 address.  After that, we set the netmask if provided.
2236 	 * Finally we set the interface address.
2237 	 */
2238 	laddr = lifr.lifr_addr;
2239 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2240 	    sizeof (lifr.lifr_name));
2241 	(void) memset(&lifr.lifr_addr, 0, sizeof (lifr.lifr_addr));
2242 
2243 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2244 		/*
2245 		 * Here, we know that the interface can't be brought up.
2246 		 * A similar warning message was already printed out to
2247 		 * the console by zoneadm(1M) so instead we log the
2248 		 * message to syslog and continue.
2249 		 */
2250 		zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2251 		    "'%s' which may not be present/plumbed in the "
2252 		    "global zone.", lifr.lifr_name);
2253 		(void) close(s);
2254 		return (Z_OK);
2255 	}
2256 
2257 	/* Preserve literal IPv4 address for later potential printing. */
2258 	if (af == AF_INET)
2259 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2260 
2261 	lifr.lifr_zoneid = zone_id;
2262 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2263 		zerror(zlogp, B_TRUE, "%s: could not place network interface "
2264 		    "into zone", lifr.lifr_name);
2265 		goto bad;
2266 	}
2267 
2268 	/*
2269 	 * Loopback interface will use the default netmask assigned, if no
2270 	 * netmask is found.
2271 	 */
2272 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2273 		is_loopback = B_TRUE;
2274 	}
2275 	if (af == AF_INET) {
2276 		/*
2277 		 * The IPv4 netmask can be determined either
2278 		 * directly if a prefix length was supplied with
2279 		 * the address or via the netmasks database.  Not
2280 		 * being able to determine it is a common failure,
2281 		 * but it often is not fatal to operation of the
2282 		 * interface.  In that case, a warning will be
2283 		 * printed after the rest of the interface's
2284 		 * parameters have been configured.
2285 		 */
2286 		(void) memset(&netmask4, 0, sizeof (netmask4));
2287 		if (slashp != NULL) {
2288 			if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2289 			    (uchar_t *)&netmask4.sin_addr) != 0) {
2290 				*slashp = '/';
2291 				zerror(zlogp, B_FALSE,
2292 				    "%s: invalid prefix length in %s",
2293 				    lifr.lifr_name,
2294 				    nwiftabptr->zone_nwif_address);
2295 				goto bad;
2296 			}
2297 			got_netmask = B_TRUE;
2298 		} else if (getnetmaskbyaddr(in4,
2299 		    &netmask4.sin_addr) == 0) {
2300 			got_netmask = B_TRUE;
2301 		}
2302 		if (got_netmask) {
2303 			netmask4.sin_family = af;
2304 			(void) memcpy(&lifr.lifr_addr, &netmask4,
2305 			    sizeof (netmask4));
2306 		}
2307 	} else {
2308 		(void) memset(&netmask6, 0, sizeof (netmask6));
2309 		if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2310 		    (uchar_t *)&netmask6.sin6_addr) != 0) {
2311 			*slashp = '/';
2312 			zerror(zlogp, B_FALSE,
2313 			    "%s: invalid prefix length in %s",
2314 			    lifr.lifr_name,
2315 			    nwiftabptr->zone_nwif_address);
2316 			goto bad;
2317 		}
2318 		got_netmask = B_TRUE;
2319 		netmask6.sin6_family = af;
2320 		(void) memcpy(&lifr.lifr_addr, &netmask6,
2321 		    sizeof (netmask6));
2322 	}
2323 	if (got_netmask &&
2324 	    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2325 		zerror(zlogp, B_TRUE, "%s: could not set netmask",
2326 		    lifr.lifr_name);
2327 		goto bad;
2328 	}
2329 
2330 	/* Set the interface address */
2331 	lifr.lifr_addr = laddr;
2332 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2333 		zerror(zlogp, B_TRUE,
2334 		    "%s: could not set IP address to %s",
2335 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
2336 		goto bad;
2337 	}
2338 
2339 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2340 		zerror(zlogp, B_TRUE, "%s: could not get flags",
2341 		    lifr.lifr_name);
2342 		goto bad;
2343 	}
2344 	lifr.lifr_flags |= IFF_UP;
2345 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2346 		int save_errno = errno;
2347 		char *zone_using;
2348 
2349 		/*
2350 		 * If we failed with something other than EADDRNOTAVAIL,
2351 		 * then skip to the end.  Otherwise, look up our address,
2352 		 * then call a function to determine which zone is already
2353 		 * using that address.
2354 		 */
2355 		if (errno != EADDRNOTAVAIL) {
2356 			zerror(zlogp, B_TRUE,
2357 			    "%s: could not bring network interface up",
2358 			    lifr.lifr_name);
2359 			goto bad;
2360 		}
2361 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2362 			zerror(zlogp, B_TRUE, "%s: could not get address",
2363 			    lifr.lifr_name);
2364 			goto bad;
2365 		}
2366 		zone_using = who_is_using(zlogp, &lifr);
2367 		errno = save_errno;
2368 		if (zone_using == NULL)
2369 			zerror(zlogp, B_TRUE,
2370 			    "%s: could not bring network interface up",
2371 			    lifr.lifr_name);
2372 		else
2373 			zerror(zlogp, B_TRUE, "%s: could not bring network "
2374 			    "interface up: address in use by zone '%s'",
2375 			    lifr.lifr_name, zone_using);
2376 		goto bad;
2377 	}
2378 
2379 	if (!got_netmask && !is_loopback) {
2380 		/*
2381 		 * A common, but often non-fatal problem, is that the system
2382 		 * cannot find the netmask for an interface address. This is
2383 		 * often caused by it being only in /etc/inet/netmasks, but
2384 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2385 		 * in that. This doesn't show up at boot because the netmask
2386 		 * is obtained from /etc/inet/netmasks when no network
2387 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2388 		 * available. We warn the user here that something like this
2389 		 * has happened and we're just running with a default and
2390 		 * possible incorrect netmask.
2391 		 */
2392 		char buffer[INET6_ADDRSTRLEN];
2393 		void  *addr;
2394 		const char *nomatch = "no matching subnet found in netmasks(4)";
2395 
2396 		if (af == AF_INET)
2397 			addr = &((struct sockaddr_in *)
2398 			    (&lifr.lifr_addr))->sin_addr;
2399 		else
2400 			addr = &((struct sockaddr_in6 *)
2401 			    (&lifr.lifr_addr))->sin6_addr;
2402 
2403 		/*
2404 		 * Find out what netmask the interface is going to be using.
2405 		 * If we just brought up an IPMP data address on an underlying
2406 		 * interface above, the address will have already migrated, so
2407 		 * the SIOCGLIFNETMASK won't be able to find it (but we need
2408 		 * to bring the address up to get the actual netmask).  Just
2409 		 * omit printing the actual netmask in this corner-case.
2410 		 */
2411 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2412 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL) {
2413 			zerror(zlogp, B_FALSE, "WARNING: %s; using default.",
2414 			    nomatch);
2415 		} else {
2416 			zerror(zlogp, B_FALSE,
2417 			    "WARNING: %s: %s: %s; using default of %s.",
2418 			    lifr.lifr_name, nomatch, addrstr4, buffer);
2419 		}
2420 	}
2421 
2422 	/*
2423 	 * If a default router was specified for this interface
2424 	 * set the route now. Ignore if already set.
2425 	 */
2426 	if (strlen(nwiftabptr->zone_nwif_defrouter) > 0) {
2427 		int status;
2428 		char *argv[7];
2429 
2430 		argv[0] = "route";
2431 		argv[1] = "add";
2432 		argv[2] = "-ifp";
2433 		argv[3] = nwiftabptr->zone_nwif_physical;
2434 		argv[4] = "default";
2435 		argv[5] = nwiftabptr->zone_nwif_defrouter;
2436 		argv[6] = NULL;
2437 
2438 		status = forkexec(zlogp, "/usr/sbin/route", argv);
2439 		if (status != 0 && status != EEXIST)
2440 			zerror(zlogp, B_FALSE, "Unable to set route for "
2441 			    "interface %s to %s\n",
2442 			    nwiftabptr->zone_nwif_physical,
2443 			    nwiftabptr->zone_nwif_defrouter);
2444 	}
2445 
2446 	(void) close(s);
2447 	return (Z_OK);
2448 bad:
2449 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2450 	(void) close(s);
2451 	return (-1);
2452 }
2453 
2454 /*
2455  * Sets up network interfaces based on information from the zone configuration.
2456  * IPv4 and IPv6 loopback interfaces are set up "for free", modeling the global
2457  * system.
2458  *
2459  * If anything goes wrong, we log a general error message, attempt to tear down
2460  * whatever we set up, and return an error.
2461  */
2462 static int
2463 configure_shared_network_interfaces(zlog_t *zlogp)
2464 {
2465 	zone_dochandle_t handle;
2466 	struct zone_nwiftab nwiftab, loopback_iftab;
2467 	zoneid_t zoneid;
2468 
2469 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2470 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2471 		return (-1);
2472 	}
2473 
2474 	if ((handle = zonecfg_init_handle()) == NULL) {
2475 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2476 		return (-1);
2477 	}
2478 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2479 		zerror(zlogp, B_FALSE, "invalid configuration");
2480 		zonecfg_fini_handle(handle);
2481 		return (-1);
2482 	}
2483 	if (zonecfg_setnwifent(handle) == Z_OK) {
2484 		for (;;) {
2485 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2486 				break;
2487 			if (configure_one_interface(zlogp, zoneid, &nwiftab) !=
2488 			    Z_OK) {
2489 				(void) zonecfg_endnwifent(handle);
2490 				zonecfg_fini_handle(handle);
2491 				return (-1);
2492 			}
2493 		}
2494 		(void) zonecfg_endnwifent(handle);
2495 	}
2496 	zonecfg_fini_handle(handle);
2497 	if (is_system_labeled()) {
2498 		/*
2499 		 * Labeled zones share the loopback interface
2500 		 * so it is not plumbed for shared stack instances.
2501 		 */
2502 		return (0);
2503 	}
2504 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2505 	    sizeof (loopback_iftab.zone_nwif_physical));
2506 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2507 	    sizeof (loopback_iftab.zone_nwif_address));
2508 	loopback_iftab.zone_nwif_defrouter[0] = '\0';
2509 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2510 		return (-1);
2511 
2512 	/* Always plumb up the IPv6 loopback interface. */
2513 	(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2514 	    sizeof (loopback_iftab.zone_nwif_address));
2515 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2516 		return (-1);
2517 	return (0);
2518 }
2519 
2520 static void
2521 zdlerror(zlog_t *zlogp, dladm_status_t err, const char *dlname, const char *str)
2522 {
2523 	char errmsg[DLADM_STRSIZE];
2524 
2525 	(void) dladm_status2str(err, errmsg);
2526 	zerror(zlogp, B_FALSE, "%s '%s': %s", str, dlname, errmsg);
2527 }
2528 
2529 static int
2530 add_datalink(zlog_t *zlogp, char *zone_name, datalink_id_t linkid, char *dlname)
2531 {
2532 	dladm_status_t err;
2533 	boolean_t cpuset, poolset;
2534 
2535 	/* First check if it's in use by global zone. */
2536 	if (zonecfg_ifname_exists(AF_INET, dlname) ||
2537 	    zonecfg_ifname_exists(AF_INET6, dlname)) {
2538 		zerror(zlogp, B_FALSE, "WARNING: skipping network interface "
2539 		    "'%s' which is used in the global zone", dlname);
2540 		return (-1);
2541 	}
2542 
2543 	/* Set zoneid of this link. */
2544 	err = dladm_set_linkprop(dld_handle, linkid, "zone", &zone_name, 1,
2545 	    DLADM_OPT_ACTIVE);
2546 	if (err != DLADM_STATUS_OK) {
2547 		zdlerror(zlogp, err, dlname,
2548 		    "WARNING: unable to add network interface");
2549 		return (-1);
2550 	}
2551 
2552 	/*
2553 	 * Set the pool of this link if the zone has a pool and
2554 	 * neither the cpus nor the pool datalink property is
2555 	 * already set.
2556 	 */
2557 	err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2558 	    "cpus", &cpuset);
2559 	if (err != DLADM_STATUS_OK) {
2560 		zdlerror(zlogp, err, dlname,
2561 		    "WARNING: unable to check if cpus link property is set");
2562 	}
2563 	err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2564 	    "pool", &poolset);
2565 	if (err != DLADM_STATUS_OK) {
2566 		zdlerror(zlogp, err, dlname,
2567 		    "WARNING: unable to check if pool link property is set");
2568 	}
2569 
2570 	if ((strlen(pool_name) != 0) && !cpuset && !poolset) {
2571 		err = dladm_set_linkprop(dld_handle, linkid, "pool",
2572 		    &pool_name, 1, DLADM_OPT_ACTIVE);
2573 		if (err != DLADM_STATUS_OK) {
2574 			zerror(zlogp, B_FALSE, "WARNING: unable to set "
2575 			    "pool %s to datalink %s", pool_name, dlname);
2576 			bzero(pool_name, MAXPATHLEN);
2577 		}
2578 	} else {
2579 		bzero(pool_name, MAXPATHLEN);
2580 	}
2581 	return (0);
2582 }
2583 
2584 /*
2585  * Add the kernel access control information for the interface names.
2586  * If anything goes wrong, we log a general error message, attempt to tear down
2587  * whatever we set up, and return an error.
2588  */
2589 static int
2590 configure_exclusive_network_interfaces(zlog_t *zlogp)
2591 {
2592 	zone_dochandle_t handle;
2593 	struct zone_nwiftab nwiftab;
2594 	char rootpath[MAXPATHLEN];
2595 	char path[MAXPATHLEN];
2596 	datalink_id_t linkid;
2597 	di_prof_t prof = NULL;
2598 	boolean_t added = B_FALSE;
2599 
2600 	if ((handle = zonecfg_init_handle()) == NULL) {
2601 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2602 		return (-1);
2603 	}
2604 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2605 		zerror(zlogp, B_FALSE, "invalid configuration");
2606 		zonecfg_fini_handle(handle);
2607 		return (-1);
2608 	}
2609 
2610 	if (zonecfg_setnwifent(handle) != Z_OK) {
2611 		zonecfg_fini_handle(handle);
2612 		return (0);
2613 	}
2614 
2615 	for (;;) {
2616 		if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2617 			break;
2618 
2619 		if (prof == NULL) {
2620 			if (zone_get_devroot(zone_name, rootpath,
2621 			    sizeof (rootpath)) != Z_OK) {
2622 				(void) zonecfg_endnwifent(handle);
2623 				zonecfg_fini_handle(handle);
2624 				zerror(zlogp, B_TRUE,
2625 				    "unable to determine dev root");
2626 				return (-1);
2627 			}
2628 			(void) snprintf(path, sizeof (path), "%s%s", rootpath,
2629 			    "/dev");
2630 			if (di_prof_init(path, &prof) != 0) {
2631 				(void) zonecfg_endnwifent(handle);
2632 				zonecfg_fini_handle(handle);
2633 				zerror(zlogp, B_TRUE,
2634 				    "failed to initialize profile");
2635 				return (-1);
2636 			}
2637 		}
2638 
2639 		/*
2640 		 * Create the /dev entry for backward compatibility.
2641 		 * Only create the /dev entry if it's not in use.
2642 		 * Note that the zone still boots when the assigned
2643 		 * interface is inaccessible, used by others, etc.
2644 		 * Also, when vanity naming is used, some interface do
2645 		 * do not have corresponding /dev node names (for example,
2646 		 * vanity named aggregations).  The /dev entry is not
2647 		 * created in that case.  The /dev/net entry is always
2648 		 * accessible.
2649 		 */
2650 		if (dladm_name2info(dld_handle, nwiftab.zone_nwif_physical,
2651 		    &linkid, NULL, NULL, NULL) == DLADM_STATUS_OK &&
2652 		    add_datalink(zlogp, zone_name, linkid,
2653 		    nwiftab.zone_nwif_physical) == 0) {
2654 			added = B_TRUE;
2655 		} else {
2656 			(void) zonecfg_endnwifent(handle);
2657 			zonecfg_fini_handle(handle);
2658 			zerror(zlogp, B_TRUE, "failed to add network device");
2659 			return (-1);
2660 		}
2661 	}
2662 	(void) zonecfg_endnwifent(handle);
2663 	zonecfg_fini_handle(handle);
2664 
2665 	if (prof != NULL && added) {
2666 		if (di_prof_commit(prof) != 0) {
2667 			zerror(zlogp, B_TRUE, "failed to commit profile");
2668 			return (-1);
2669 		}
2670 	}
2671 	if (prof != NULL)
2672 		di_prof_fini(prof);
2673 
2674 	return (0);
2675 }
2676 
2677 static int
2678 remove_datalink_pool(zlog_t *zlogp, zoneid_t zoneid)
2679 {
2680 	ushort_t flags;
2681 	zone_iptype_t iptype;
2682 	int i, dlnum = 0;
2683 	datalink_id_t *dllink, *dllinks = NULL;
2684 	dladm_status_t err;
2685 
2686 	if (strlen(pool_name) == 0)
2687 		return (0);
2688 
2689 	if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
2690 	    sizeof (flags)) < 0) {
2691 		if (vplat_get_iptype(zlogp, &iptype) < 0) {
2692 			zerror(zlogp, B_TRUE, "unable to determine "
2693 			    "ip-type");
2694 			return (-1);
2695 		}
2696 	} else {
2697 		if (flags & ZF_NET_EXCL)
2698 			iptype = ZS_EXCLUSIVE;
2699 		else
2700 			iptype = ZS_SHARED;
2701 	}
2702 
2703 	if (iptype == ZS_EXCLUSIVE) {
2704 		/*
2705 		 * Get the datalink count and for each datalink,
2706 		 * attempt to clear the pool property and clear
2707 		 * the pool_name.
2708 		 */
2709 		if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2710 			zerror(zlogp, B_TRUE, "unable to count network "
2711 			    "interfaces");
2712 			return (-1);
2713 		}
2714 
2715 		if (dlnum == 0)
2716 			return (0);
2717 
2718 		if ((dllinks = malloc(dlnum * sizeof (datalink_id_t)))
2719 		    == NULL) {
2720 			zerror(zlogp, B_TRUE, "memory allocation failed");
2721 			return (-1);
2722 		}
2723 		if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
2724 			zerror(zlogp, B_TRUE, "unable to list network "
2725 			    "interfaces");
2726 			return (-1);
2727 		}
2728 
2729 		bzero(pool_name, MAXPATHLEN);
2730 		for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
2731 			err = dladm_set_linkprop(dld_handle, *dllink, "pool",
2732 			    NULL, 0, DLADM_OPT_ACTIVE);
2733 			if (err != DLADM_STATUS_OK) {
2734 				zerror(zlogp, B_TRUE,
2735 				    "WARNING: unable to clear pool");
2736 			}
2737 		}
2738 		free(dllinks);
2739 	}
2740 	return (0);
2741 }
2742 
2743 static int
2744 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2745 {
2746 	int dlnum = 0;
2747 
2748 	/*
2749 	 * The kernel shutdown callback for the dls module should have removed
2750 	 * all datalinks from this zone.  If any remain, then there's a
2751 	 * problem.
2752 	 */
2753 	if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2754 		zerror(zlogp, B_TRUE, "unable to list network interfaces");
2755 		return (-1);
2756 	}
2757 	if (dlnum != 0) {
2758 		zerror(zlogp, B_FALSE,
2759 		    "datalinks remain in zone after shutdown");
2760 		return (-1);
2761 	}
2762 	return (0);
2763 }
2764 
2765 static int
2766 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2767     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2768 {
2769 	int fd;
2770 	struct strioctl ioc;
2771 	tcp_ioc_abort_conn_t conn;
2772 	int error;
2773 
2774 	conn.ac_local = *local;
2775 	conn.ac_remote = *remote;
2776 	conn.ac_start = TCPS_SYN_SENT;
2777 	conn.ac_end = TCPS_TIME_WAIT;
2778 	conn.ac_zoneid = zoneid;
2779 
2780 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2781 	ioc.ic_timout = -1; /* infinite timeout */
2782 	ioc.ic_len = sizeof (conn);
2783 	ioc.ic_dp = (char *)&conn;
2784 
2785 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2786 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2787 		return (-1);
2788 	}
2789 
2790 	error = ioctl(fd, I_STR, &ioc);
2791 	(void) close(fd);
2792 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2793 		return (0);
2794 	return (-1);
2795 }
2796 
2797 static int
2798 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2799 {
2800 	struct sockaddr_storage l, r;
2801 	struct sockaddr_in *local, *remote;
2802 	struct sockaddr_in6 *local6, *remote6;
2803 	int error;
2804 
2805 	/*
2806 	 * Abort IPv4 connections.
2807 	 */
2808 	bzero(&l, sizeof (*local));
2809 	local = (struct sockaddr_in *)&l;
2810 	local->sin_family = AF_INET;
2811 	local->sin_addr.s_addr = INADDR_ANY;
2812 	local->sin_port = 0;
2813 
2814 	bzero(&r, sizeof (*remote));
2815 	remote = (struct sockaddr_in *)&r;
2816 	remote->sin_family = AF_INET;
2817 	remote->sin_addr.s_addr = INADDR_ANY;
2818 	remote->sin_port = 0;
2819 
2820 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2821 		return (error);
2822 
2823 	/*
2824 	 * Abort IPv6 connections.
2825 	 */
2826 	bzero(&l, sizeof (*local6));
2827 	local6 = (struct sockaddr_in6 *)&l;
2828 	local6->sin6_family = AF_INET6;
2829 	local6->sin6_port = 0;
2830 	local6->sin6_addr = in6addr_any;
2831 
2832 	bzero(&r, sizeof (*remote6));
2833 	remote6 = (struct sockaddr_in6 *)&r;
2834 	remote6->sin6_family = AF_INET6;
2835 	remote6->sin6_port = 0;
2836 	remote6->sin6_addr = in6addr_any;
2837 
2838 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2839 		return (error);
2840 	return (0);
2841 }
2842 
2843 static int
2844 get_privset(zlog_t *zlogp, priv_set_t *privs, zone_mnt_t mount_cmd)
2845 {
2846 	int error = -1;
2847 	zone_dochandle_t handle;
2848 	char *privname = NULL;
2849 
2850 	if ((handle = zonecfg_init_handle()) == NULL) {
2851 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2852 		return (-1);
2853 	}
2854 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2855 		zerror(zlogp, B_FALSE, "invalid configuration");
2856 		zonecfg_fini_handle(handle);
2857 		return (-1);
2858 	}
2859 
2860 	if (ALT_MOUNT(mount_cmd)) {
2861 		zone_iptype_t	iptype;
2862 		const char	*curr_iptype;
2863 
2864 		if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
2865 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
2866 			zonecfg_fini_handle(handle);
2867 			return (-1);
2868 		}
2869 
2870 		switch (iptype) {
2871 		case ZS_SHARED:
2872 			curr_iptype = "shared";
2873 			break;
2874 		case ZS_EXCLUSIVE:
2875 			curr_iptype = "exclusive";
2876 			break;
2877 		}
2878 
2879 		if (zonecfg_default_privset(privs, curr_iptype) == Z_OK) {
2880 			zonecfg_fini_handle(handle);
2881 			return (0);
2882 		}
2883 		zerror(zlogp, B_FALSE,
2884 		    "failed to determine the zone's default privilege set");
2885 		zonecfg_fini_handle(handle);
2886 		return (-1);
2887 	}
2888 
2889 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2890 	case Z_OK:
2891 		error = 0;
2892 		break;
2893 	case Z_PRIV_PROHIBITED:
2894 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2895 		    "within the zone's privilege set", privname);
2896 		break;
2897 	case Z_PRIV_REQUIRED:
2898 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2899 		    "from the zone's privilege set", privname);
2900 		break;
2901 	case Z_PRIV_UNKNOWN:
2902 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2903 		    "in the zone's privilege set", privname);
2904 		break;
2905 	default:
2906 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2907 		    "privilege set");
2908 		break;
2909 	}
2910 
2911 	free(privname);
2912 	zonecfg_fini_handle(handle);
2913 	return (error);
2914 }
2915 
2916 static int
2917 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2918 {
2919 	nvlist_t *nvl = NULL;
2920 	char *nvl_packed = NULL;
2921 	size_t nvl_size = 0;
2922 	nvlist_t **nvlv = NULL;
2923 	int rctlcount = 0;
2924 	int error = -1;
2925 	zone_dochandle_t handle;
2926 	struct zone_rctltab rctltab;
2927 	rctlblk_t *rctlblk = NULL;
2928 
2929 	*bufp = NULL;
2930 	*bufsizep = 0;
2931 
2932 	if ((handle = zonecfg_init_handle()) == NULL) {
2933 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2934 		return (-1);
2935 	}
2936 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2937 		zerror(zlogp, B_FALSE, "invalid configuration");
2938 		zonecfg_fini_handle(handle);
2939 		return (-1);
2940 	}
2941 
2942 	rctltab.zone_rctl_valptr = NULL;
2943 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2944 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2945 		goto out;
2946 	}
2947 
2948 	if (zonecfg_setrctlent(handle) != Z_OK) {
2949 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2950 		goto out;
2951 	}
2952 
2953 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2954 		zerror(zlogp, B_TRUE, "memory allocation failed");
2955 		goto out;
2956 	}
2957 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2958 		struct zone_rctlvaltab *rctlval;
2959 		uint_t i, count;
2960 		const char *name = rctltab.zone_rctl_name;
2961 
2962 		/* zoneadm should have already warned about unknown rctls. */
2963 		if (!zonecfg_is_rctl(name)) {
2964 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2965 			rctltab.zone_rctl_valptr = NULL;
2966 			continue;
2967 		}
2968 		count = 0;
2969 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2970 		    rctlval = rctlval->zone_rctlval_next) {
2971 			count++;
2972 		}
2973 		if (count == 0) {	/* ignore */
2974 			continue;	/* Nothing to free */
2975 		}
2976 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2977 			goto out;
2978 		i = 0;
2979 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2980 		    rctlval = rctlval->zone_rctlval_next, i++) {
2981 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2982 				zerror(zlogp, B_TRUE, "%s failed",
2983 				    "nvlist_alloc");
2984 				goto out;
2985 			}
2986 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2987 			    != Z_OK) {
2988 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2989 				    "(priv=%s,limit=%s,action=%s)",
2990 				    rctlval->zone_rctlval_priv,
2991 				    rctlval->zone_rctlval_limit,
2992 				    rctlval->zone_rctlval_action);
2993 				goto out;
2994 			}
2995 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2996 				zerror(zlogp, B_FALSE,
2997 				    "(priv=%s,limit=%s,action=%s) is not a "
2998 				    "valid value for rctl '%s'",
2999 				    rctlval->zone_rctlval_priv,
3000 				    rctlval->zone_rctlval_limit,
3001 				    rctlval->zone_rctlval_action,
3002 				    name);
3003 				goto out;
3004 			}
3005 			if (nvlist_add_uint64(nvlv[i], "privilege",
3006 			    rctlblk_get_privilege(rctlblk)) != 0) {
3007 				zerror(zlogp, B_FALSE, "%s failed",
3008 				    "nvlist_add_uint64");
3009 				goto out;
3010 			}
3011 			if (nvlist_add_uint64(nvlv[i], "limit",
3012 			    rctlblk_get_value(rctlblk)) != 0) {
3013 				zerror(zlogp, B_FALSE, "%s failed",
3014 				    "nvlist_add_uint64");
3015 				goto out;
3016 			}
3017 			if (nvlist_add_uint64(nvlv[i], "action",
3018 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
3019 			    != 0) {
3020 				zerror(zlogp, B_FALSE, "%s failed",
3021 				    "nvlist_add_uint64");
3022 				goto out;
3023 			}
3024 		}
3025 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3026 		rctltab.zone_rctl_valptr = NULL;
3027 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
3028 		    != 0) {
3029 			zerror(zlogp, B_FALSE, "%s failed",
3030 			    "nvlist_add_nvlist_array");
3031 			goto out;
3032 		}
3033 		for (i = 0; i < count; i++)
3034 			nvlist_free(nvlv[i]);
3035 		free(nvlv);
3036 		nvlv = NULL;
3037 		rctlcount++;
3038 	}
3039 	(void) zonecfg_endrctlent(handle);
3040 
3041 	if (rctlcount == 0) {
3042 		error = 0;
3043 		goto out;
3044 	}
3045 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
3046 	    != 0) {
3047 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
3048 		goto out;
3049 	}
3050 
3051 	error = 0;
3052 	*bufp = nvl_packed;
3053 	*bufsizep = nvl_size;
3054 
3055 out:
3056 	free(rctlblk);
3057 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3058 	if (error && nvl_packed != NULL)
3059 		free(nvl_packed);
3060 	if (nvl != NULL)
3061 		nvlist_free(nvl);
3062 	if (nvlv != NULL)
3063 		free(nvlv);
3064 	if (handle != NULL)
3065 		zonecfg_fini_handle(handle);
3066 	return (error);
3067 }
3068 
3069 static int
3070 get_implicit_datasets(zlog_t *zlogp, char **retstr)
3071 {
3072 	char cmdbuf[2 * MAXPATHLEN];
3073 
3074 	if (query_hook[0] == '\0')
3075 		return (0);
3076 
3077 	if (snprintf(cmdbuf, sizeof (cmdbuf), "%s datasets", query_hook)
3078 	    > sizeof (cmdbuf))
3079 		return (-1);
3080 
3081 	if (do_subproc(zlogp, cmdbuf, retstr) != 0)
3082 		return (-1);
3083 
3084 	return (0);
3085 }
3086 
3087 static int
3088 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3089 {
3090 	zone_dochandle_t handle;
3091 	struct zone_dstab dstab;
3092 	size_t total, offset, len;
3093 	int error = -1;
3094 	char *str = NULL;
3095 	char *implicit_datasets = NULL;
3096 	int implicit_len = 0;
3097 
3098 	*bufp = NULL;
3099 	*bufsizep = 0;
3100 
3101 	if ((handle = zonecfg_init_handle()) == NULL) {
3102 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3103 		return (-1);
3104 	}
3105 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3106 		zerror(zlogp, B_FALSE, "invalid configuration");
3107 		zonecfg_fini_handle(handle);
3108 		return (-1);
3109 	}
3110 
3111 	if (get_implicit_datasets(zlogp, &implicit_datasets) != 0) {
3112 		zerror(zlogp, B_FALSE, "getting implicit datasets failed");
3113 		goto out;
3114 	}
3115 
3116 	if (zonecfg_setdsent(handle) != Z_OK) {
3117 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3118 		goto out;
3119 	}
3120 
3121 	total = 0;
3122 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3123 		total += strlen(dstab.zone_dataset_name) + 1;
3124 	(void) zonecfg_enddsent(handle);
3125 
3126 	if (implicit_datasets != NULL)
3127 		implicit_len = strlen(implicit_datasets);
3128 	if (implicit_len > 0)
3129 		total += implicit_len + 1;
3130 
3131 	if (total == 0) {
3132 		error = 0;
3133 		goto out;
3134 	}
3135 
3136 	if ((str = malloc(total)) == NULL) {
3137 		zerror(zlogp, B_TRUE, "memory allocation failed");
3138 		goto out;
3139 	}
3140 
3141 	if (zonecfg_setdsent(handle) != Z_OK) {
3142 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3143 		goto out;
3144 	}
3145 	offset = 0;
3146 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3147 		len = strlen(dstab.zone_dataset_name);
3148 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
3149 		    total - offset);
3150 		offset += len;
3151 		if (offset < total - 1)
3152 			str[offset++] = ',';
3153 	}
3154 	(void) zonecfg_enddsent(handle);
3155 
3156 	if (implicit_len > 0)
3157 		(void) strlcpy(str + offset, implicit_datasets, total - offset);
3158 
3159 	error = 0;
3160 	*bufp = str;
3161 	*bufsizep = total;
3162 
3163 out:
3164 	if (error != 0 && str != NULL)
3165 		free(str);
3166 	if (handle != NULL)
3167 		zonecfg_fini_handle(handle);
3168 	if (implicit_datasets != NULL)
3169 		free(implicit_datasets);
3170 
3171 	return (error);
3172 }
3173 
3174 static int
3175 validate_datasets(zlog_t *zlogp)
3176 {
3177 	zone_dochandle_t handle;
3178 	struct zone_dstab dstab;
3179 	zfs_handle_t *zhp;
3180 	libzfs_handle_t *hdl;
3181 
3182 	if ((handle = zonecfg_init_handle()) == NULL) {
3183 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3184 		return (-1);
3185 	}
3186 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3187 		zerror(zlogp, B_FALSE, "invalid configuration");
3188 		zonecfg_fini_handle(handle);
3189 		return (-1);
3190 	}
3191 
3192 	if (zonecfg_setdsent(handle) != Z_OK) {
3193 		zerror(zlogp, B_FALSE, "invalid configuration");
3194 		zonecfg_fini_handle(handle);
3195 		return (-1);
3196 	}
3197 
3198 	if ((hdl = libzfs_init()) == NULL) {
3199 		zerror(zlogp, B_FALSE, "opening ZFS library");
3200 		zonecfg_fini_handle(handle);
3201 		return (-1);
3202 	}
3203 
3204 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3205 
3206 		if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3207 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
3208 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3209 			    dstab.zone_dataset_name);
3210 			zonecfg_fini_handle(handle);
3211 			libzfs_fini(hdl);
3212 			return (-1);
3213 		}
3214 
3215 		/*
3216 		 * Automatically set the 'zoned' property.  We check the value
3217 		 * first because we'll get EPERM if it is already set.
3218 		 */
3219 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3220 		    zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3221 		    "on") != 0) {
3222 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3223 			    "property for ZFS dataset '%s'\n",
3224 			    dstab.zone_dataset_name);
3225 			zonecfg_fini_handle(handle);
3226 			zfs_close(zhp);
3227 			libzfs_fini(hdl);
3228 			return (-1);
3229 		}
3230 
3231 		zfs_close(zhp);
3232 	}
3233 	(void) zonecfg_enddsent(handle);
3234 
3235 	zonecfg_fini_handle(handle);
3236 	libzfs_fini(hdl);
3237 
3238 	return (0);
3239 }
3240 
3241 /*
3242  * Return true if the path is its own zfs file system.  We determine this
3243  * by stat-ing the path to see if it is zfs and stat-ing the parent to see
3244  * if it is a different fs.
3245  */
3246 boolean_t
3247 is_zonepath_zfs(char *zonepath)
3248 {
3249 	int res;
3250 	char *path;
3251 	char *parent;
3252 	struct statvfs64 buf1, buf2;
3253 
3254 	if (statvfs64(zonepath, &buf1) != 0)
3255 		return (B_FALSE);
3256 
3257 	if (strcmp(buf1.f_basetype, "zfs") != 0)
3258 		return (B_FALSE);
3259 
3260 	if ((path = strdup(zonepath)) == NULL)
3261 		return (B_FALSE);
3262 
3263 	parent = dirname(path);
3264 	res = statvfs64(parent, &buf2);
3265 	free(path);
3266 
3267 	if (res != 0)
3268 		return (B_FALSE);
3269 
3270 	if (buf1.f_fsid == buf2.f_fsid)
3271 		return (B_FALSE);
3272 
3273 	return (B_TRUE);
3274 }
3275 
3276 /*
3277  * Verify the MAC label in the root dataset for the zone.
3278  * If the label exists, it must match the label configured for the zone.
3279  * Otherwise if there's no label on the dataset, create one here.
3280  */
3281 
3282 static int
3283 validate_rootds_label(zlog_t *zlogp, char *rootpath, m_label_t *zone_sl)
3284 {
3285 	int		error = -1;
3286 	zfs_handle_t	*zhp;
3287 	libzfs_handle_t	*hdl;
3288 	m_label_t	ds_sl;
3289 	char		zonepath[MAXPATHLEN];
3290 	char		ds_hexsl[MAXNAMELEN];
3291 
3292 	if (!is_system_labeled())
3293 		return (0);
3294 
3295 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
3296 		zerror(zlogp, B_TRUE, "unable to determine zone path");
3297 		return (-1);
3298 	}
3299 
3300 	if (!is_zonepath_zfs(zonepath))
3301 		return (0);
3302 
3303 	if ((hdl = libzfs_init()) == NULL) {
3304 		zerror(zlogp, B_FALSE, "opening ZFS library");
3305 		return (-1);
3306 	}
3307 
3308 	if ((zhp = zfs_path_to_zhandle(hdl, rootpath,
3309 	    ZFS_TYPE_FILESYSTEM)) == NULL) {
3310 		zerror(zlogp, B_FALSE, "cannot open ZFS dataset for path '%s'",
3311 		    rootpath);
3312 		libzfs_fini(hdl);
3313 		return (-1);
3314 	}
3315 
3316 	/* Get the mlslabel property if it exists. */
3317 	if ((zfs_prop_get(zhp, ZFS_PROP_MLSLABEL, ds_hexsl, MAXNAMELEN,
3318 	    NULL, NULL, 0, B_TRUE) != 0) ||
3319 	    (strcmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0)) {
3320 		char		*str2 = NULL;
3321 
3322 		/*
3323 		 * No label on the dataset (or default only); create one.
3324 		 * (Only do this automatic labeling for the labeled brand.)
3325 		 */
3326 		if (strcmp(brand_name, LABELED_BRAND_NAME) != 0) {
3327 			error = 0;
3328 			goto out;
3329 		}
3330 
3331 		error = l_to_str_internal(zone_sl, &str2);
3332 		if (error)
3333 			goto out;
3334 		if (str2 == NULL) {
3335 			error = -1;
3336 			goto out;
3337 		}
3338 		if ((error = zfs_prop_set(zhp,
3339 		    zfs_prop_to_name(ZFS_PROP_MLSLABEL), str2)) != 0) {
3340 			zerror(zlogp, B_FALSE, "cannot set 'mlslabel' "
3341 			    "property for root dataset at '%s'\n", rootpath);
3342 		}
3343 		free(str2);
3344 		goto out;
3345 	}
3346 
3347 	/* Convert the retrieved dataset label to binary form. */
3348 	error = hexstr_to_label(ds_hexsl, &ds_sl);
3349 	if (error) {
3350 		zerror(zlogp, B_FALSE, "invalid 'mlslabel' "
3351 		    "property on root dataset at '%s'\n", rootpath);
3352 		goto out;			/* exit with error */
3353 	}
3354 
3355 	/*
3356 	 * Perform a MAC check by comparing the zone label with the
3357 	 * dataset label.
3358 	 */
3359 	error = (!blequal(zone_sl, &ds_sl));
3360 	if (error)
3361 		zerror(zlogp, B_FALSE, "Rootpath dataset has mismatched label");
3362 out:
3363 	zfs_close(zhp);
3364 	libzfs_fini(hdl);
3365 
3366 	return (error);
3367 }
3368 
3369 /*
3370  * Mount lower level home directories into/from current zone
3371  * Share exported directories specified in dfstab for zone
3372  */
3373 static int
3374 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
3375 {
3376 	zoneid_t *zids = NULL;
3377 	priv_set_t *zid_privs;
3378 	const priv_impl_info_t *ip = NULL;
3379 	uint_t nzents_saved;
3380 	uint_t nzents;
3381 	int i;
3382 	char readonly[] = "ro";
3383 	struct zone_fstab lower_fstab;
3384 	char *argv[4];
3385 
3386 	if (!is_system_labeled())
3387 		return (0);
3388 
3389 	if (zid_label == NULL) {
3390 		zid_label = m_label_alloc(MAC_LABEL);
3391 		if (zid_label == NULL)
3392 			return (-1);
3393 	}
3394 
3395 	/* Make sure our zone has an /export/home dir */
3396 	(void) make_one_dir(zlogp, rootpath, "/export/home",
3397 	    DEFAULT_DIR_MODE, DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3398 
3399 	lower_fstab.zone_fs_raw[0] = '\0';
3400 	(void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
3401 	    sizeof (lower_fstab.zone_fs_type));
3402 	lower_fstab.zone_fs_options = NULL;
3403 	(void) zonecfg_add_fs_option(&lower_fstab, readonly);
3404 
3405 	/*
3406 	 * Get the list of zones from the kernel
3407 	 */
3408 	if (zone_list(NULL, &nzents) != 0) {
3409 		zerror(zlogp, B_TRUE, "unable to list zones");
3410 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3411 		return (-1);
3412 	}
3413 again:
3414 	if (nzents == 0) {
3415 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3416 		return (-1);
3417 	}
3418 
3419 	zids = malloc(nzents * sizeof (zoneid_t));
3420 	if (zids == NULL) {
3421 		zerror(zlogp, B_TRUE, "memory allocation failed");
3422 		return (-1);
3423 	}
3424 	nzents_saved = nzents;
3425 
3426 	if (zone_list(zids, &nzents) != 0) {
3427 		zerror(zlogp, B_TRUE, "unable to list zones");
3428 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3429 		free(zids);
3430 		return (-1);
3431 	}
3432 	if (nzents != nzents_saved) {
3433 		/* list changed, try again */
3434 		free(zids);
3435 		goto again;
3436 	}
3437 
3438 	ip = getprivimplinfo();
3439 	if ((zid_privs = priv_allocset()) == NULL) {
3440 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3441 		zonecfg_free_fs_option_list(
3442 		    lower_fstab.zone_fs_options);
3443 		free(zids);
3444 		return (-1);
3445 	}
3446 
3447 	for (i = 0; i < nzents; i++) {
3448 		char zid_name[ZONENAME_MAX];
3449 		zone_state_t zid_state;
3450 		char zid_rpath[MAXPATHLEN];
3451 		struct stat stat_buf;
3452 
3453 		if (zids[i] == GLOBAL_ZONEID)
3454 			continue;
3455 
3456 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3457 			continue;
3458 
3459 		/*
3460 		 * Do special setup for the zone we are booting
3461 		 */
3462 		if (strcmp(zid_name, zone_name) == 0) {
3463 			struct zone_fstab autofs_fstab;
3464 			char map_path[MAXPATHLEN];
3465 			int fd;
3466 
3467 			/*
3468 			 * Create auto_home_<zone> map for this zone
3469 			 * in the global zone. The non-global zone entry
3470 			 * will be created by automount when the zone
3471 			 * is booted.
3472 			 */
3473 
3474 			(void) snprintf(autofs_fstab.zone_fs_special,
3475 			    MAXPATHLEN, "auto_home_%s", zid_name);
3476 
3477 			(void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
3478 			    "/zone/%s/home", zid_name);
3479 
3480 			(void) snprintf(map_path, sizeof (map_path),
3481 			    "/etc/%s", autofs_fstab.zone_fs_special);
3482 			/*
3483 			 * If the map file doesn't exist create a template
3484 			 */
3485 			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
3486 			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
3487 				int len;
3488 				char map_rec[MAXPATHLEN];
3489 
3490 				len = snprintf(map_rec, sizeof (map_rec),
3491 				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
3492 				    autofs_fstab.zone_fs_special, rootpath);
3493 				(void) write(fd, map_rec, len);
3494 				(void) close(fd);
3495 			}
3496 
3497 			/*
3498 			 * Mount auto_home_<zone> in the global zone if absent.
3499 			 * If it's already of type autofs, then
3500 			 * don't mount it again.
3501 			 */
3502 			if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
3503 			    strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
3504 				char optstr[] = "indirect,ignore,nobrowse";
3505 
3506 				(void) make_one_dir(zlogp, "",
3507 				    autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE,
3508 				    DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3509 
3510 				/*
3511 				 * Mount will fail if automounter has already
3512 				 * processed the auto_home_<zonename> map
3513 				 */
3514 				(void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
3515 				    autofs_fstab.zone_fs_special,
3516 				    autofs_fstab.zone_fs_dir);
3517 			}
3518 			continue;
3519 		}
3520 
3521 
3522 		if (zone_get_state(zid_name, &zid_state) != Z_OK ||
3523 		    (zid_state != ZONE_STATE_READY &&
3524 		    zid_state != ZONE_STATE_RUNNING))
3525 			/* Skip over zones without mounted filesystems */
3526 			continue;
3527 
3528 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3529 		    sizeof (m_label_t)) < 0)
3530 			/* Skip over zones with unspecified label */
3531 			continue;
3532 
3533 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3534 		    sizeof (zid_rpath)) == -1)
3535 			/* Skip over zones with bad path */
3536 			continue;
3537 
3538 		if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
3539 		    sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
3540 			/* Skip over zones with bad privs */
3541 			continue;
3542 
3543 		/*
3544 		 * Reading down is valid according to our label model
3545 		 * but some customers want to disable it because it
3546 		 * allows execute down and other possible attacks.
3547 		 * Therefore, we restrict this feature to zones that
3548 		 * have the NET_MAC_AWARE privilege which is required
3549 		 * for NFS read-down semantics.
3550 		 */
3551 		if ((bldominates(zlabel, zid_label)) &&
3552 		    (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
3553 			/*
3554 			 * Our zone dominates this one.
3555 			 * Create a lofs mount from lower zone's /export/home
3556 			 */
3557 			(void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3558 			    "%s/zone/%s/export/home", rootpath, zid_name);
3559 
3560 			/*
3561 			 * If the target is already an LOFS mount
3562 			 * then don't do it again.
3563 			 */
3564 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3565 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3566 
3567 				if (snprintf(lower_fstab.zone_fs_special,
3568 				    MAXPATHLEN, "%s/export",
3569 				    zid_rpath) > MAXPATHLEN)
3570 					continue;
3571 
3572 				/*
3573 				 * Make sure the lower-level home exists
3574 				 */
3575 				if (make_one_dir(zlogp,
3576 				    lower_fstab.zone_fs_special, "/home",
3577 				    DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
3578 				    DEFAULT_DIR_GROUP) != 0)
3579 					continue;
3580 
3581 				(void) strlcat(lower_fstab.zone_fs_special,
3582 				    "/home", MAXPATHLEN);
3583 
3584 				/*
3585 				 * Mount can fail because the lower-level
3586 				 * zone may have already done a mount up.
3587 				 */
3588 				(void) mount_one(zlogp, &lower_fstab, "",
3589 				    Z_MNT_BOOT);
3590 			}
3591 		} else if ((bldominates(zid_label, zlabel)) &&
3592 		    (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
3593 			/*
3594 			 * This zone dominates our zone.
3595 			 * Create a lofs mount from our zone's /export/home
3596 			 */
3597 			if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3598 			    "%s/zone/%s/export/home", zid_rpath,
3599 			    zone_name) > MAXPATHLEN)
3600 				continue;
3601 
3602 			/*
3603 			 * If the target is already an LOFS mount
3604 			 * then don't do it again.
3605 			 */
3606 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3607 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3608 
3609 				(void) snprintf(lower_fstab.zone_fs_special,
3610 				    MAXPATHLEN, "%s/export/home", rootpath);
3611 
3612 				/*
3613 				 * Mount can fail because the higher-level
3614 				 * zone may have already done a mount down.
3615 				 */
3616 				(void) mount_one(zlogp, &lower_fstab, "",
3617 				    Z_MNT_BOOT);
3618 			}
3619 		}
3620 	}
3621 	zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3622 	priv_freeset(zid_privs);
3623 	free(zids);
3624 
3625 	/*
3626 	 * Now share any exported directories from this zone.
3627 	 * Each zone can have its own dfstab.
3628 	 */
3629 
3630 	argv[0] = "zoneshare";
3631 	argv[1] = "-z";
3632 	argv[2] = zone_name;
3633 	argv[3] = NULL;
3634 
3635 	(void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
3636 	/* Don't check for errors since they don't affect the zone */
3637 
3638 	return (0);
3639 }
3640 
3641 /*
3642  * Unmount lofs mounts from higher level zones
3643  * Unshare nfs exported directories
3644  */
3645 static void
3646 tsol_unmounts(zlog_t *zlogp, char *zone_name)
3647 {
3648 	zoneid_t *zids = NULL;
3649 	uint_t nzents_saved;
3650 	uint_t nzents;
3651 	int i;
3652 	char *argv[4];
3653 	char path[MAXPATHLEN];
3654 
3655 	if (!is_system_labeled())
3656 		return;
3657 
3658 	/*
3659 	 * Get the list of zones from the kernel
3660 	 */
3661 	if (zone_list(NULL, &nzents) != 0) {
3662 		return;
3663 	}
3664 
3665 	if (zid_label == NULL) {
3666 		zid_label = m_label_alloc(MAC_LABEL);
3667 		if (zid_label == NULL)
3668 			return;
3669 	}
3670 
3671 again:
3672 	if (nzents == 0)
3673 		return;
3674 
3675 	zids = malloc(nzents * sizeof (zoneid_t));
3676 	if (zids == NULL) {
3677 		zerror(zlogp, B_TRUE, "memory allocation failed");
3678 		return;
3679 	}
3680 	nzents_saved = nzents;
3681 
3682 	if (zone_list(zids, &nzents) != 0) {
3683 		free(zids);
3684 		return;
3685 	}
3686 	if (nzents != nzents_saved) {
3687 		/* list changed, try again */
3688 		free(zids);
3689 		goto again;
3690 	}
3691 
3692 	for (i = 0; i < nzents; i++) {
3693 		char zid_name[ZONENAME_MAX];
3694 		zone_state_t zid_state;
3695 		char zid_rpath[MAXPATHLEN];
3696 
3697 		if (zids[i] == GLOBAL_ZONEID)
3698 			continue;
3699 
3700 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3701 			continue;
3702 
3703 		/*
3704 		 * Skip the zone we are halting
3705 		 */
3706 		if (strcmp(zid_name, zone_name) == 0)
3707 			continue;
3708 
3709 		if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
3710 		    sizeof (zid_state)) < 0) ||
3711 		    (zid_state < ZONE_IS_READY))
3712 			/* Skip over zones without mounted filesystems */
3713 			continue;
3714 
3715 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3716 		    sizeof (m_label_t)) < 0)
3717 			/* Skip over zones with unspecified label */
3718 			continue;
3719 
3720 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3721 		    sizeof (zid_rpath)) == -1)
3722 			/* Skip over zones with bad path */
3723 			continue;
3724 
3725 		if (zlabel != NULL && bldominates(zid_label, zlabel)) {
3726 			/*
3727 			 * This zone dominates our zone.
3728 			 * Unmount the lofs mount of our zone's /export/home
3729 			 */
3730 
3731 			if (snprintf(path, MAXPATHLEN,
3732 			    "%s/zone/%s/export/home", zid_rpath,
3733 			    zone_name) > MAXPATHLEN)
3734 				continue;
3735 
3736 			/* Skip over mount failures */
3737 			(void) umount(path);
3738 		}
3739 	}
3740 	free(zids);
3741 
3742 	/*
3743 	 * Unmount global zone autofs trigger for this zone
3744 	 */
3745 	(void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
3746 	/* Skip over mount failures */
3747 	(void) umount(path);
3748 
3749 	/*
3750 	 * Next unshare any exported directories from this zone.
3751 	 */
3752 
3753 	argv[0] = "zoneunshare";
3754 	argv[1] = "-z";
3755 	argv[2] = zone_name;
3756 	argv[3] = NULL;
3757 
3758 	(void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
3759 	/* Don't check for errors since they don't affect the zone */
3760 
3761 	/*
3762 	 * Finally, deallocate any devices in the zone.
3763 	 */
3764 
3765 	argv[0] = "deallocate";
3766 	argv[1] = "-Isz";
3767 	argv[2] = zone_name;
3768 	argv[3] = NULL;
3769 
3770 	(void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
3771 	/* Don't check for errors since they don't affect the zone */
3772 }
3773 
3774 /*
3775  * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
3776  * this zone.
3777  */
3778 static tsol_zcent_t *
3779 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
3780 {
3781 	FILE *fp;
3782 	tsol_zcent_t *zcent = NULL;
3783 	char line[MAXTNZLEN];
3784 
3785 	if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
3786 		zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
3787 		return (NULL);
3788 	}
3789 
3790 	while (fgets(line, sizeof (line), fp) != NULL) {
3791 		/*
3792 		 * Check for malformed database
3793 		 */
3794 		if (strlen(line) == MAXTNZLEN - 1)
3795 			break;
3796 		if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
3797 			continue;
3798 		if (strcmp(zcent->zc_name, zone_name) == 0)
3799 			break;
3800 		tsol_freezcent(zcent);
3801 		zcent = NULL;
3802 	}
3803 	(void) fclose(fp);
3804 
3805 	if (zcent == NULL) {
3806 		zerror(zlogp, B_FALSE, "zone requires a label assignment. "
3807 		    "See tnzonecfg(4)");
3808 	} else {
3809 		if (zlabel == NULL)
3810 			zlabel = m_label_alloc(MAC_LABEL);
3811 		/*
3812 		 * Save this zone's privileges for later read-down processing
3813 		 */
3814 		if ((zprivs = priv_allocset()) == NULL) {
3815 			zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3816 			return (NULL);
3817 		} else {
3818 			priv_copyset(privs, zprivs);
3819 		}
3820 	}
3821 	return (zcent);
3822 }
3823 
3824 /*
3825  * Add the Trusted Extensions multi-level ports for this zone.
3826  */
3827 static void
3828 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
3829 {
3830 	tsol_mlp_t *mlp;
3831 	tsol_mlpent_t tsme;
3832 
3833 	if (!is_system_labeled())
3834 		return;
3835 
3836 	tsme.tsme_zoneid = zoneid;
3837 	tsme.tsme_flags = 0;
3838 	for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
3839 		tsme.tsme_mlp = *mlp;
3840 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3841 			zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
3842 			    "on %d-%d/%d", mlp->mlp_port,
3843 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3844 		}
3845 	}
3846 
3847 	tsme.tsme_flags = TSOL_MEF_SHARED;
3848 	for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
3849 		tsme.tsme_mlp = *mlp;
3850 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3851 			zerror(zlogp, B_TRUE, "cannot set shared MLP "
3852 			    "on %d-%d/%d", mlp->mlp_port,
3853 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3854 		}
3855 	}
3856 }
3857 
3858 static void
3859 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
3860 {
3861 	tsol_mlpent_t tsme;
3862 
3863 	if (!is_system_labeled())
3864 		return;
3865 
3866 	(void) memset(&tsme, 0, sizeof (tsme));
3867 	tsme.tsme_zoneid = zoneid;
3868 	if (tnmlp(TNDB_FLUSH, &tsme) != 0)
3869 		zerror(zlogp, B_TRUE, "cannot flush MLPs");
3870 }
3871 
3872 int
3873 prtmount(const struct mnttab *fs, void *x) {
3874 	zerror((zlog_t *)x, B_FALSE, "  %s", fs->mnt_mountp);
3875 	return (0);
3876 }
3877 
3878 /*
3879  * Look for zones running on the main system that are using this root (or any
3880  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
3881  * is found or if we can't tell.
3882  */
3883 static boolean_t
3884 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3885 {
3886 	zoneid_t *zids = NULL;
3887 	uint_t nzids = 0;
3888 	boolean_t retv;
3889 	int rlen, zlen;
3890 	char zroot[MAXPATHLEN];
3891 	char zonename[ZONENAME_MAX];
3892 
3893 	for (;;) {
3894 		nzids += 10;
3895 		zids = malloc(nzids * sizeof (*zids));
3896 		if (zids == NULL) {
3897 			zerror(zlogp, B_TRUE, "memory allocation failed");
3898 			return (B_TRUE);
3899 		}
3900 		if (zone_list(zids, &nzids) == 0)
3901 			break;
3902 		free(zids);
3903 	}
3904 	retv = B_FALSE;
3905 	rlen = strlen(rootpath);
3906 	while (nzids > 0) {
3907 		/*
3908 		 * Ignore errors; they just mean that the zone has disappeared
3909 		 * while we were busy.
3910 		 */
3911 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3912 		    sizeof (zroot)) == -1)
3913 			continue;
3914 		zlen = strlen(zroot);
3915 		if (zlen > rlen)
3916 			zlen = rlen;
3917 		if (strncmp(rootpath, zroot, zlen) == 0 &&
3918 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3919 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3920 			if (getzonenamebyid(zids[nzids], zonename,
3921 			    sizeof (zonename)) == -1)
3922 				(void) snprintf(zonename, sizeof (zonename),
3923 				    "id %d", (int)zids[nzids]);
3924 			zerror(zlogp, B_FALSE,
3925 			    "zone root %s already in use by zone %s",
3926 			    rootpath, zonename);
3927 			retv = B_TRUE;
3928 			break;
3929 		}
3930 	}
3931 	free(zids);
3932 	return (retv);
3933 }
3934 
3935 /*
3936  * Search for loopback mounts that use this same source node (same device and
3937  * inode).  Return B_TRUE if there is one or if we can't tell.
3938  */
3939 static boolean_t
3940 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3941 {
3942 	struct stat64 rst, zst;
3943 	struct mnttab *mnp;
3944 
3945 	if (stat64(rootpath, &rst) == -1) {
3946 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3947 		return (B_TRUE);
3948 	}
3949 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3950 		return (B_TRUE);
3951 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3952 		if (mnp->mnt_fstype == NULL ||
3953 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3954 			continue;
3955 		/* We're looking at a loopback mount.  Stat it. */
3956 		if (mnp->mnt_special != NULL &&
3957 		    stat64(mnp->mnt_special, &zst) != -1 &&
3958 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3959 			zerror(zlogp, B_FALSE,
3960 			    "zone root %s is reachable through %s",
3961 			    rootpath, mnp->mnt_mountp);
3962 			return (B_TRUE);
3963 		}
3964 	}
3965 	return (B_FALSE);
3966 }
3967 
3968 /*
3969  * Set memory cap and pool info for the zone's resource management
3970  * configuration.
3971  */
3972 static int
3973 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
3974 {
3975 	int res;
3976 	uint64_t tmp;
3977 	struct zone_mcaptab mcap;
3978 	char sched[MAXNAMELEN];
3979 	zone_dochandle_t handle = NULL;
3980 	char pool_err[128];
3981 
3982 	if ((handle = zonecfg_init_handle()) == NULL) {
3983 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3984 		return (Z_BAD_HANDLE);
3985 	}
3986 
3987 	if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
3988 		zerror(zlogp, B_FALSE, "invalid configuration");
3989 		zonecfg_fini_handle(handle);
3990 		return (res);
3991 	}
3992 
3993 	/*
3994 	 * If a memory cap is configured, set the cap in the kernel using
3995 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
3996 	 */
3997 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
3998 		uint64_t num;
3999 		char smf_err[128];
4000 
4001 		num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
4002 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
4003 			zerror(zlogp, B_TRUE, "could not set zone memory cap");
4004 			zonecfg_fini_handle(handle);
4005 			return (Z_INVAL);
4006 		}
4007 
4008 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
4009 			zerror(zlogp, B_FALSE, "enabling system/rcap service "
4010 			    "failed: %s", smf_err);
4011 			zonecfg_fini_handle(handle);
4012 			return (Z_INVAL);
4013 		}
4014 	}
4015 
4016 	/* Get the scheduling class set in the zone configuration. */
4017 	if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
4018 	    strlen(sched) > 0) {
4019 		if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
4020 		    strlen(sched)) == -1)
4021 			zerror(zlogp, B_TRUE, "WARNING: unable to set the "
4022 			    "default scheduling class");
4023 
4024 	} else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
4025 	    == Z_OK) {
4026 		/*
4027 		 * If the zone has the zone.cpu-shares rctl set then we want to
4028 		 * use the Fair Share Scheduler (FSS) for processes in the
4029 		 * zone.  Check what scheduling class the zone would be running
4030 		 * in by default so we can print a warning and modify the class
4031 		 * if we wouldn't be using FSS.
4032 		 */
4033 		char class_name[PC_CLNMSZ];
4034 
4035 		if (zonecfg_get_dflt_sched_class(handle, class_name,
4036 		    sizeof (class_name)) != Z_OK) {
4037 			zerror(zlogp, B_FALSE, "WARNING: unable to determine "
4038 			    "the zone's scheduling class");
4039 
4040 		} else if (strcmp("FSS", class_name) != 0) {
4041 			zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
4042 			    "rctl is set but\nFSS is not the default "
4043 			    "scheduling class for\nthis zone.  FSS will be "
4044 			    "used for processes\nin the zone but to get the "
4045 			    "full benefit of FSS,\nit should be the default "
4046 			    "scheduling class.\nSee dispadmin(1M) for more "
4047 			    "details.");
4048 
4049 			if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
4050 			    strlen("FSS")) == -1)
4051 				zerror(zlogp, B_TRUE, "WARNING: unable to set "
4052 				    "zone scheduling class to FSS");
4053 		}
4054 	}
4055 
4056 	/*
4057 	 * The next few blocks of code attempt to set up temporary pools as
4058 	 * well as persistent pools.  In all cases we call the functions
4059 	 * unconditionally.  Within each funtion the code will check if the
4060 	 * zone is actually configured for a temporary pool or persistent pool
4061 	 * and just return if there is nothing to do.
4062 	 *
4063 	 * If we are rebooting we want to attempt to reuse any temporary pool
4064 	 * that was previously set up.  zonecfg_bind_tmp_pool() will do the
4065 	 * right thing in all cases (reuse or create) based on the current
4066 	 * zonecfg.
4067 	 */
4068 	if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
4069 	    sizeof (pool_err))) != Z_OK) {
4070 		if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
4071 			zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
4072 			    "cannot be instantiated", zonecfg_strerror(res),
4073 			    pool_err);
4074 		else
4075 			zerror(zlogp, B_FALSE, "could not bind zone to "
4076 			    "temporary pool: %s", zonecfg_strerror(res));
4077 		zonecfg_fini_handle(handle);
4078 		return (Z_POOL_BIND);
4079 	}
4080 
4081 	/*
4082 	 * Check if we need to warn about poold not being enabled.
4083 	 */
4084 	if (zonecfg_warn_poold(handle)) {
4085 		zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
4086 		    "been specified\nbut the dynamic pool service is not "
4087 		    "enabled.\nThe system will not dynamically adjust the\n"
4088 		    "processor allocation within the specified range\n"
4089 		    "until svc:/system/pools/dynamic is enabled.\n"
4090 		    "See poold(1M).");
4091 	}
4092 
4093 	/* The following is a warning, not an error. */
4094 	if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
4095 	    sizeof (pool_err))) != Z_OK) {
4096 		if (res == Z_POOL_BIND)
4097 			zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
4098 			    "pool '%s'; using default pool.", pool_err);
4099 		else if (res == Z_POOL)
4100 			zerror(zlogp, B_FALSE, "WARNING: %s: %s",
4101 			    zonecfg_strerror(res), pool_err);
4102 		else
4103 			zerror(zlogp, B_FALSE, "WARNING: %s",
4104 			    zonecfg_strerror(res));
4105 	}
4106 	(void) zonecfg_get_poolname(handle, zone_name, pool_name, MAXPATHLEN);
4107 
4108 	zonecfg_fini_handle(handle);
4109 	return (Z_OK);
4110 }
4111 
4112 /*
4113  * Sets the hostid of the new zone based on its configured value.  The zone's
4114  * zone_t structure must already exist in kernel memory.  'zlogp' refers to the
4115  * log used to report errors and warnings and must be non-NULL.  'zone_namep'
4116  * is the name of the new zone and must be non-NULL.  'zoneid' is the numeric
4117  * ID of the new zone.
4118  *
4119  * This function returns zero on success and a nonzero error code on failure.
4120  */
4121 static int
4122 setup_zone_hostid(zlog_t *zlogp, char *zone_namep, zoneid_t zoneid)
4123 {
4124 	int res;
4125 	zone_dochandle_t handle;
4126 	char hostidp[HW_HOSTID_LEN];
4127 	unsigned int hostid;
4128 
4129 	if ((handle = zonecfg_init_handle()) == NULL) {
4130 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
4131 		return (Z_BAD_HANDLE);
4132 	}
4133 	if ((res = zonecfg_get_snapshot_handle(zone_namep, handle)) != Z_OK) {
4134 		zerror(zlogp, B_FALSE, "invalid configuration");
4135 		zonecfg_fini_handle(handle);
4136 		return (res);
4137 	}
4138 
4139 	if ((res = zonecfg_get_hostid(handle, hostidp, sizeof (hostidp))) ==
4140 	    Z_OK) {
4141 		if (zonecfg_valid_hostid(hostidp) != Z_OK) {
4142 			zerror(zlogp, B_FALSE,
4143 			    "zone hostid is not valid: %s", hostidp);
4144 			zonecfg_fini_handle(handle);
4145 			return (Z_HOSTID_FUBAR);
4146 		}
4147 		hostid = (unsigned int)strtoul(hostidp, NULL, 16);
4148 		if (zone_setattr(zoneid, ZONE_ATTR_HOSTID, &hostid,
4149 		    sizeof (hostid)) != 0) {
4150 			zerror(zlogp, B_TRUE,
4151 			    "zone hostid is not valid: %s", hostidp);
4152 			zonecfg_fini_handle(handle);
4153 			return (Z_SYSTEM);
4154 		}
4155 	} else if (res != Z_BAD_PROPERTY) {
4156 		/*
4157 		 * Z_BAD_PROPERTY is an acceptable error value (from
4158 		 * zonecfg_get_hostid()) because it indicates that the zone
4159 		 * doesn't have a hostid.
4160 		 */
4161 		if (res == Z_TOO_BIG)
4162 			zerror(zlogp, B_FALSE, "hostid string in zone "
4163 			    "configuration is too large.");
4164 		else
4165 			zerror(zlogp, B_TRUE, "fetching zone hostid from "
4166 			    "configuration");
4167 		zonecfg_fini_handle(handle);
4168 		return (res);
4169 	}
4170 
4171 	zonecfg_fini_handle(handle);
4172 	return (Z_OK);
4173 }
4174 
4175 zoneid_t
4176 vplat_create(zlog_t *zlogp, zone_mnt_t mount_cmd)
4177 {
4178 	zoneid_t rval = -1;
4179 	priv_set_t *privs;
4180 	char rootpath[MAXPATHLEN];
4181 	char *rctlbuf = NULL;
4182 	size_t rctlbufsz = 0;
4183 	char *zfsbuf = NULL;
4184 	size_t zfsbufsz = 0;
4185 	zoneid_t zoneid = -1;
4186 	int xerr;
4187 	char *kzone;
4188 	FILE *fp = NULL;
4189 	tsol_zcent_t *zcent = NULL;
4190 	int match = 0;
4191 	int doi = 0;
4192 	int flags;
4193 	zone_iptype_t iptype;
4194 
4195 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
4196 		zerror(zlogp, B_TRUE, "unable to determine zone root");
4197 		return (-1);
4198 	}
4199 	if (zonecfg_in_alt_root())
4200 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
4201 
4202 	if (vplat_get_iptype(zlogp, &iptype) < 0) {
4203 		zerror(zlogp, B_TRUE, "unable to determine ip-type");
4204 		return (-1);
4205 	}
4206 	switch (iptype) {
4207 	case ZS_SHARED:
4208 		flags = 0;
4209 		break;
4210 	case ZS_EXCLUSIVE:
4211 		flags = ZCF_NET_EXCL;
4212 		break;
4213 	}
4214 
4215 	if ((privs = priv_allocset()) == NULL) {
4216 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
4217 		return (-1);
4218 	}
4219 	priv_emptyset(privs);
4220 	if (get_privset(zlogp, privs, mount_cmd) != 0)
4221 		goto error;
4222 
4223 	if (mount_cmd == Z_MNT_BOOT &&
4224 	    get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
4225 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
4226 		goto error;
4227 	}
4228 
4229 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
4230 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
4231 		goto error;
4232 	}
4233 
4234 	if (mount_cmd == Z_MNT_BOOT && is_system_labeled()) {
4235 		zcent = get_zone_label(zlogp, privs);
4236 		if (zcent != NULL) {
4237 			match = zcent->zc_match;
4238 			doi = zcent->zc_doi;
4239 			*zlabel = zcent->zc_label;
4240 		} else {
4241 			goto error;
4242 		}
4243 		if (validate_rootds_label(zlogp, rootpath, zlabel) != 0)
4244 			goto error;
4245 	}
4246 
4247 	kzone = zone_name;
4248 
4249 	/*
4250 	 * We must do this scan twice.  First, we look for zones running on the
4251 	 * main system that are using this root (or any subdirectory of it).
4252 	 * Next, we reduce to the shortest path and search for loopback mounts
4253 	 * that use this same source node (same device and inode).
4254 	 */
4255 	if (duplicate_zone_root(zlogp, rootpath))
4256 		goto error;
4257 	if (duplicate_reachable_path(zlogp, rootpath))
4258 		goto error;
4259 
4260 	if (ALT_MOUNT(mount_cmd)) {
4261 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
4262 
4263 		/*
4264 		 * Forge up a special root for this zone.  When a zone is
4265 		 * mounted, we can't let the zone have its own root because the
4266 		 * tools that will be used in this "scratch zone" need access
4267 		 * to both the zone's resources and the running machine's
4268 		 * executables.
4269 		 *
4270 		 * Note that the mkdir here also catches read-only filesystems.
4271 		 */
4272 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
4273 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
4274 			goto error;
4275 		}
4276 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
4277 			goto error;
4278 	}
4279 
4280 	if (zonecfg_in_alt_root()) {
4281 		/*
4282 		 * If we are mounting up a zone in an alternate root partition,
4283 		 * then we have some additional work to do before starting the
4284 		 * zone.  First, resolve the root path down so that we're not
4285 		 * fooled by duplicates.  Then forge up an internal name for
4286 		 * the zone.
4287 		 */
4288 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4289 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4290 			goto error;
4291 		}
4292 		if (zonecfg_lock_scratch(fp) != 0) {
4293 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4294 			goto error;
4295 		}
4296 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4297 		    NULL, 0) == 0) {
4298 			zerror(zlogp, B_FALSE, "scratch zone already running");
4299 			goto error;
4300 		}
4301 		/* This is the preferred name */
4302 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4303 		    zone_name);
4304 		srandom(getpid());
4305 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4306 		    0) == 0) {
4307 			/* This is just an arbitrary name; note "." usage */
4308 			(void) snprintf(kernzone, sizeof (kernzone),
4309 			    "SUNWlu.%08lX%08lX", random(), random());
4310 		}
4311 		kzone = kernzone;
4312 	}
4313 
4314 	xerr = 0;
4315 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4316 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel,
4317 	    flags)) == -1) {
4318 		if (xerr == ZE_AREMOUNTS) {
4319 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4320 				zerror(zlogp, B_FALSE,
4321 				    "An unknown file-system is mounted on "
4322 				    "a subdirectory of %s", rootpath);
4323 			} else {
4324 
4325 				zerror(zlogp, B_FALSE,
4326 				    "These file-systems are mounted on "
4327 				    "subdirectories of %s:", rootpath);
4328 				(void) zonecfg_find_mounts(rootpath,
4329 				    prtmount, zlogp);
4330 			}
4331 		} else if (xerr == ZE_CHROOTED) {
4332 			zerror(zlogp, B_FALSE, "%s: "
4333 			    "cannot create a zone from a chrooted "
4334 			    "environment", "zone_create");
4335 		} else if (xerr == ZE_LABELINUSE) {
4336 			char zonename[ZONENAME_MAX];
4337 			(void) getzonenamebyid(getzoneidbylabel(zlabel),
4338 			    zonename, ZONENAME_MAX);
4339 			zerror(zlogp, B_FALSE, "The zone label is already "
4340 			    "used by the zone '%s'.", zonename);
4341 		} else {
4342 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4343 		}
4344 		goto error;
4345 	}
4346 
4347 	if (zonecfg_in_alt_root() &&
4348 	    zonecfg_add_scratch(fp, zone_name, kernzone,
4349 	    zonecfg_get_root()) == -1) {
4350 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4351 		goto error;
4352 	}
4353 
4354 	if ((pool_name = malloc(MAXPATHLEN)) == NULL) {
4355 		zerror(zlogp, B_TRUE, "memory allocation failed");
4356 		return (Z_NOMEM);
4357 	}
4358 	bzero(pool_name, MAXPATHLEN);
4359 
4360 	/*
4361 	 * The following actions are not performed when merely mounting a zone
4362 	 * for administrative use.
4363 	 */
4364 	if (mount_cmd == Z_MNT_BOOT) {
4365 		brand_handle_t bh;
4366 		struct brand_attr attr;
4367 		char modname[MAXPATHLEN];
4368 
4369 		if (setup_zone_hostid(zlogp, zone_name, zoneid) != Z_OK)
4370 			goto error;
4371 
4372 		if ((bh = brand_open(brand_name)) == NULL) {
4373 			zerror(zlogp, B_FALSE,
4374 			    "unable to determine brand name");
4375 			goto error;
4376 		}
4377 
4378 		if (!is_system_labeled() &&
4379 		    (strcmp(brand_name, LABELED_BRAND_NAME) == 0)) {
4380 			brand_close(bh);
4381 			zerror(zlogp, B_FALSE,
4382 			    "cannot boot labeled zone on unlabeled system");
4383 			goto error;
4384 		}
4385 
4386 		/*
4387 		 * If this brand requires any kernel support, now is the time to
4388 		 * get it loaded and initialized.
4389 		 */
4390 		if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4391 			brand_close(bh);
4392 			zerror(zlogp, B_FALSE,
4393 			    "unable to determine brand kernel module");
4394 			goto error;
4395 		}
4396 		brand_close(bh);
4397 
4398 		if (strlen(modname) > 0) {
4399 			(void) strlcpy(attr.ba_brandname, brand_name,
4400 			    sizeof (attr.ba_brandname));
4401 			(void) strlcpy(attr.ba_modname, modname,
4402 			    sizeof (attr.ba_modname));
4403 			if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4404 			    sizeof (attr) != 0)) {
4405 				zerror(zlogp, B_TRUE,
4406 				    "could not set zone brand attribute.");
4407 				goto error;
4408 			}
4409 		}
4410 
4411 		if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK)
4412 			goto error;
4413 
4414 		set_mlps(zlogp, zoneid, zcent);
4415 	}
4416 
4417 	rval = zoneid;
4418 	zoneid = -1;
4419 
4420 error:
4421 	if (zoneid != -1) {
4422 		(void) zone_shutdown(zoneid);
4423 		(void) zone_destroy(zoneid);
4424 	}
4425 	if (rctlbuf != NULL)
4426 		free(rctlbuf);
4427 	priv_freeset(privs);
4428 	if (fp != NULL)
4429 		zonecfg_close_scratch(fp);
4430 	lofs_discard_mnttab();
4431 	if (zcent != NULL)
4432 		tsol_freezcent(zcent);
4433 	return (rval);
4434 }
4435 
4436 /*
4437  * Enter the zone and write a /etc/zones/index file there.  This allows
4438  * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
4439  * details from inside the zone.
4440  */
4441 static void
4442 write_index_file(zoneid_t zoneid)
4443 {
4444 	FILE *zef;
4445 	FILE *zet;
4446 	struct zoneent *zep;
4447 	pid_t child;
4448 	int tmpl_fd;
4449 	ctid_t ct;
4450 	int fd;
4451 	char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
4452 
4453 	/* Locate the zone entry in the global zone's index file */
4454 	if ((zef = setzoneent()) == NULL)
4455 		return;
4456 	while ((zep = getzoneent_private(zef)) != NULL) {
4457 		if (strcmp(zep->zone_name, zone_name) == 0)
4458 			break;
4459 		free(zep);
4460 	}
4461 	endzoneent(zef);
4462 	if (zep == NULL)
4463 		return;
4464 
4465 	if ((tmpl_fd = init_template()) == -1) {
4466 		free(zep);
4467 		return;
4468 	}
4469 
4470 	if ((child = fork()) == -1) {
4471 		(void) ct_tmpl_clear(tmpl_fd);
4472 		(void) close(tmpl_fd);
4473 		free(zep);
4474 		return;
4475 	}
4476 
4477 	/* parent waits for child to finish */
4478 	if (child != 0) {
4479 		free(zep);
4480 		if (contract_latest(&ct) == -1)
4481 			ct = -1;
4482 		(void) ct_tmpl_clear(tmpl_fd);
4483 		(void) close(tmpl_fd);
4484 		(void) waitpid(child, NULL, 0);
4485 		(void) contract_abandon_id(ct);
4486 		return;
4487 	}
4488 
4489 	/* child enters zone and sets up index file */
4490 	(void) ct_tmpl_clear(tmpl_fd);
4491 	if (zone_enter(zoneid) != -1) {
4492 		(void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
4493 		(void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
4494 		    ZONE_CONFIG_GID);
4495 		fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
4496 		    ZONE_INDEX_MODE);
4497 		if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
4498 			(void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
4499 			if (uuid_is_null(zep->zone_uuid))
4500 				uuidstr[0] = '\0';
4501 			else
4502 				uuid_unparse(zep->zone_uuid, uuidstr);
4503 			(void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
4504 			    zone_state_str(zep->zone_state),
4505 			    uuidstr);
4506 			(void) fclose(zet);
4507 		}
4508 	}
4509 	_exit(0);
4510 }
4511 
4512 int
4513 vplat_bringup(zlog_t *zlogp, zone_mnt_t mount_cmd, zoneid_t zoneid)
4514 {
4515 	char zonepath[MAXPATHLEN];
4516 
4517 	if (mount_cmd == Z_MNT_BOOT && validate_datasets(zlogp) != 0) {
4518 		lofs_discard_mnttab();
4519 		return (-1);
4520 	}
4521 
4522 	/*
4523 	 * Before we try to mount filesystems we need to create the
4524 	 * attribute backing store for /dev
4525 	 */
4526 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
4527 		lofs_discard_mnttab();
4528 		return (-1);
4529 	}
4530 	resolve_lofs(zlogp, zonepath, sizeof (zonepath));
4531 
4532 	/* Make /dev directory owned by root, grouped sys */
4533 	if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE,
4534 	    0, 3) != 0) {
4535 		lofs_discard_mnttab();
4536 		return (-1);
4537 	}
4538 
4539 	if (mount_filesystems(zlogp, mount_cmd) != 0) {
4540 		lofs_discard_mnttab();
4541 		return (-1);
4542 	}
4543 
4544 	if (mount_cmd == Z_MNT_BOOT) {
4545 		zone_iptype_t iptype;
4546 
4547 		if (vplat_get_iptype(zlogp, &iptype) < 0) {
4548 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
4549 			lofs_discard_mnttab();
4550 			return (-1);
4551 		}
4552 
4553 		switch (iptype) {
4554 		case ZS_SHARED:
4555 			/* Always do this to make lo0 get configured */
4556 			if (configure_shared_network_interfaces(zlogp) != 0) {
4557 				lofs_discard_mnttab();
4558 				return (-1);
4559 			}
4560 			break;
4561 		case ZS_EXCLUSIVE:
4562 			if (configure_exclusive_network_interfaces(zlogp) !=
4563 			    0) {
4564 				lofs_discard_mnttab();
4565 				return (-1);
4566 			}
4567 			break;
4568 		}
4569 	}
4570 
4571 	write_index_file(zoneid);
4572 
4573 	lofs_discard_mnttab();
4574 	return (0);
4575 }
4576 
4577 static int
4578 lu_root_teardown(zlog_t *zlogp)
4579 {
4580 	char zroot[MAXPATHLEN];
4581 
4582 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4583 		zerror(zlogp, B_FALSE, "unable to determine zone root");
4584 		return (-1);
4585 	}
4586 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
4587 
4588 	/*
4589 	 * At this point, the processes are gone, the filesystems (save the
4590 	 * root) are unmounted, and the zone is on death row.  But there may
4591 	 * still be creds floating about in the system that reference the
4592 	 * zone_t, and which pin down zone_rootvp causing this call to fail
4593 	 * with EBUSY.  Thus, we try for a little while before just giving up.
4594 	 * (How I wish this were not true, and umount2 just did the right
4595 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
4596 	 */
4597 	if (umount2(zroot, MS_FORCE) != 0) {
4598 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
4599 			goto unmounted;
4600 		if (errno == EBUSY) {
4601 			int tries = 10;
4602 
4603 			while (--tries >= 0) {
4604 				(void) sleep(1);
4605 				if (umount2(zroot, 0) == 0)
4606 					goto unmounted;
4607 				if (errno != EBUSY)
4608 					break;
4609 			}
4610 		}
4611 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
4612 		return (-1);
4613 	}
4614 unmounted:
4615 
4616 	/*
4617 	 * Only zones in an alternate root environment have scratch zone
4618 	 * entries.
4619 	 */
4620 	if (zonecfg_in_alt_root()) {
4621 		FILE *fp;
4622 		int retv;
4623 
4624 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4625 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4626 			return (-1);
4627 		}
4628 		retv = -1;
4629 		if (zonecfg_lock_scratch(fp) != 0)
4630 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4631 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
4632 			zerror(zlogp, B_TRUE, "cannot delete map entry");
4633 		else
4634 			retv = 0;
4635 		zonecfg_close_scratch(fp);
4636 		return (retv);
4637 	} else {
4638 		return (0);
4639 	}
4640 }
4641 
4642 int
4643 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
4644 {
4645 	char *kzone;
4646 	zoneid_t zoneid;
4647 	int res;
4648 	char pool_err[128];
4649 	char zpath[MAXPATHLEN];
4650 	char cmdbuf[MAXPATHLEN];
4651 	brand_handle_t bh = NULL;
4652 	dladm_status_t status;
4653 	char errmsg[DLADM_STRSIZE];
4654 	ushort_t flags;
4655 
4656 	kzone = zone_name;
4657 	if (zonecfg_in_alt_root()) {
4658 		FILE *fp;
4659 
4660 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4661 			zerror(zlogp, B_TRUE, "unable to open map file");
4662 			goto error;
4663 		}
4664 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4665 		    kernzone, sizeof (kernzone)) != 0) {
4666 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
4667 			zonecfg_close_scratch(fp);
4668 			goto error;
4669 		}
4670 		zonecfg_close_scratch(fp);
4671 		kzone = kernzone;
4672 	}
4673 
4674 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
4675 		if (!bringup_failure_recovery)
4676 			zerror(zlogp, B_TRUE, "unable to get zoneid");
4677 		if (unmount_cmd)
4678 			(void) lu_root_teardown(zlogp);
4679 		goto error;
4680 	}
4681 
4682 	if (remove_datalink_pool(zlogp, zoneid) != 0) {
4683 		zerror(zlogp, B_FALSE, "unable clear datalink pool property");
4684 		goto error;
4685 	}
4686 
4687 	if (zone_shutdown(zoneid) != 0) {
4688 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
4689 		goto error;
4690 	}
4691 
4692 	/* Get the zonepath of this zone */
4693 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
4694 		zerror(zlogp, B_FALSE, "unable to determine zone path");
4695 		goto error;
4696 	}
4697 
4698 	/* Get a handle to the brand info for this zone */
4699 	if ((bh = brand_open(brand_name)) == NULL) {
4700 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
4701 		return (-1);
4702 	}
4703 	/*
4704 	 * If there is a brand 'halt' callback, execute it now to give the
4705 	 * brand a chance to cleanup any custom configuration.
4706 	 */
4707 	(void) strcpy(cmdbuf, EXEC_PREFIX);
4708 	if (brand_get_halt(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
4709 	    sizeof (cmdbuf) - EXEC_LEN) < 0) {
4710 		brand_close(bh);
4711 		zerror(zlogp, B_FALSE, "unable to determine branded zone's "
4712 		    "halt callback.");
4713 		goto error;
4714 	}
4715 	brand_close(bh);
4716 
4717 	if ((strlen(cmdbuf) > EXEC_LEN) &&
4718 	    (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
4719 		zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
4720 		goto error;
4721 	}
4722 
4723 	if (!unmount_cmd) {
4724 		zone_iptype_t iptype;
4725 
4726 		if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
4727 		    sizeof (flags)) < 0) {
4728 			if (vplat_get_iptype(zlogp, &iptype) < 0) {
4729 				zerror(zlogp, B_TRUE, "unable to determine "
4730 				    "ip-type");
4731 				goto error;
4732 			}
4733 		} else {
4734 			if (flags & ZF_NET_EXCL)
4735 				iptype = ZS_EXCLUSIVE;
4736 			else
4737 				iptype = ZS_SHARED;
4738 		}
4739 
4740 		switch (iptype) {
4741 		case ZS_SHARED:
4742 			if (unconfigure_shared_network_interfaces(zlogp,
4743 			    zoneid) != 0) {
4744 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4745 				    "network interfaces in zone");
4746 				goto error;
4747 			}
4748 			break;
4749 		case ZS_EXCLUSIVE:
4750 			if (unconfigure_exclusive_network_interfaces(zlogp,
4751 			    zoneid) != 0) {
4752 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4753 				    "network interfaces in zone");
4754 				goto error;
4755 			}
4756 			status = dladm_zone_halt(dld_handle, zoneid);
4757 			if (status != DLADM_STATUS_OK) {
4758 				zerror(zlogp, B_FALSE, "unable to notify "
4759 				    "dlmgmtd of zone halt: %s",
4760 				    dladm_status2str(status, errmsg));
4761 			}
4762 			break;
4763 		}
4764 	}
4765 
4766 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
4767 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
4768 		goto error;
4769 	}
4770 
4771 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
4772 		zerror(zlogp, B_FALSE,
4773 		    "unable to unmount file systems in zone");
4774 		goto error;
4775 	}
4776 
4777 	/*
4778 	 * If we are rebooting then we normally don't want to destroy an
4779 	 * existing temporary pool at this point so that we can just reuse it
4780 	 * when the zone boots back up.  However, it is also possible we were
4781 	 * running with a temporary pool and the zone configuration has been
4782 	 * modified to no longer use a temporary pool.  In that case we need
4783 	 * to destroy the temporary pool now.  This case looks like the case
4784 	 * where we never had a temporary pool configured but
4785 	 * zonecfg_destroy_tmp_pool will do the right thing either way.
4786 	 */
4787 	if (!unmount_cmd) {
4788 		boolean_t destroy_tmp_pool = B_TRUE;
4789 
4790 		if (rebooting) {
4791 			struct zone_psettab pset_tab;
4792 			zone_dochandle_t handle;
4793 
4794 			if ((handle = zonecfg_init_handle()) != NULL &&
4795 			    zonecfg_get_handle(zone_name, handle) == Z_OK &&
4796 			    zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
4797 				destroy_tmp_pool = B_FALSE;
4798 
4799 			zonecfg_fini_handle(handle);
4800 		}
4801 
4802 		if (destroy_tmp_pool) {
4803 			if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
4804 			    sizeof (pool_err))) != Z_OK) {
4805 				if (res == Z_POOL)
4806 					zerror(zlogp, B_FALSE, pool_err);
4807 			}
4808 		}
4809 	}
4810 
4811 	free(pool_name);
4812 
4813 	remove_mlps(zlogp, zoneid);
4814 
4815 	if (zone_destroy(zoneid) != 0) {
4816 		zerror(zlogp, B_TRUE, "unable to destroy zone");
4817 		goto error;
4818 	}
4819 
4820 	/*
4821 	 * Special teardown for alternate boot environments: remove the tmpfs
4822 	 * root for the zone and then remove it from the map file.
4823 	 */
4824 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
4825 		goto error;
4826 
4827 	lofs_discard_mnttab();
4828 	return (0);
4829 
4830 error:
4831 	lofs_discard_mnttab();
4832 	return (-1);
4833 }
4834