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