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