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