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