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