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