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