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