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