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