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