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