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