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