xref: /titanic_51/usr/src/cmd/zoneadmd/vplat.c (revision 78cca7e25deead6e03a496fee27183f7d9c04242)
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 int
1041 vplat_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 (vplat_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 sockaddr_storage laddr;
2215 	struct in_addr in4;
2216 	sa_family_t af;
2217 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2218 	int s;
2219 	boolean_t got_netmask = B_FALSE;
2220 	boolean_t is_loopback = B_FALSE;
2221 	char addrstr4[INET_ADDRSTRLEN];
2222 	int res;
2223 
2224 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2225 	if (res != Z_OK) {
2226 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2227 		    nwiftabptr->zone_nwif_address);
2228 		return (-1);
2229 	}
2230 	af = lifr.lifr_addr.ss_family;
2231 	if (af == AF_INET)
2232 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2233 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2234 		zerror(zlogp, B_TRUE, "could not get socket");
2235 		return (-1);
2236 	}
2237 
2238 	/*
2239 	 * This is a similar kind of "hack" like in addif() to get around
2240 	 * the problem of SIOCLIFADDIF.  The problem is that this ioctl
2241 	 * does not include the netmask when adding a logical interface.
2242 	 * To get around this problem, we first add the logical interface
2243 	 * with a 0 address.  After that, we set the netmask if provided.
2244 	 * Finally we set the interface address.
2245 	 */
2246 	laddr = lifr.lifr_addr;
2247 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2248 	    sizeof (lifr.lifr_name));
2249 	(void) memset(&lifr.lifr_addr, 0, sizeof (lifr.lifr_addr));
2250 
2251 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2252 		/*
2253 		 * Here, we know that the interface can't be brought up.
2254 		 * A similar warning message was already printed out to
2255 		 * the console by zoneadm(1M) so instead we log the
2256 		 * message to syslog and continue.
2257 		 */
2258 		zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2259 		    "'%s' which may not be present/plumbed in the "
2260 		    "global zone.", lifr.lifr_name);
2261 		(void) close(s);
2262 		return (Z_OK);
2263 	}
2264 
2265 	/* Preserve literal IPv4 address for later potential printing. */
2266 	if (af == AF_INET)
2267 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2268 
2269 	lifr.lifr_zoneid = zone_id;
2270 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2271 		zerror(zlogp, B_TRUE, "%s: could not place network interface "
2272 		    "into zone", lifr.lifr_name);
2273 		goto bad;
2274 	}
2275 
2276 	/*
2277 	 * Loopback interface will use the default netmask assigned, if no
2278 	 * netmask is found.
2279 	 */
2280 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2281 		is_loopback = B_TRUE;
2282 	}
2283 	if (af == AF_INET) {
2284 		/*
2285 		 * The IPv4 netmask can be determined either
2286 		 * directly if a prefix length was supplied with
2287 		 * the address or via the netmasks database.  Not
2288 		 * being able to determine it is a common failure,
2289 		 * but it often is not fatal to operation of the
2290 		 * interface.  In that case, a warning will be
2291 		 * printed after the rest of the interface's
2292 		 * parameters have been configured.
2293 		 */
2294 		(void) memset(&netmask4, 0, sizeof (netmask4));
2295 		if (slashp != NULL) {
2296 			if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2297 			    (uchar_t *)&netmask4.sin_addr) != 0) {
2298 				*slashp = '/';
2299 				zerror(zlogp, B_FALSE,
2300 				    "%s: invalid prefix length in %s",
2301 				    lifr.lifr_name,
2302 				    nwiftabptr->zone_nwif_address);
2303 				goto bad;
2304 			}
2305 			got_netmask = B_TRUE;
2306 		} else if (getnetmaskbyaddr(in4,
2307 		    &netmask4.sin_addr) == 0) {
2308 			got_netmask = B_TRUE;
2309 		}
2310 		if (got_netmask) {
2311 			netmask4.sin_family = af;
2312 			(void) memcpy(&lifr.lifr_addr, &netmask4,
2313 			    sizeof (netmask4));
2314 		}
2315 	} else {
2316 		(void) memset(&netmask6, 0, sizeof (netmask6));
2317 		if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2318 		    (uchar_t *)&netmask6.sin6_addr) != 0) {
2319 			*slashp = '/';
2320 			zerror(zlogp, B_FALSE,
2321 			    "%s: invalid prefix length in %s",
2322 			    lifr.lifr_name,
2323 			    nwiftabptr->zone_nwif_address);
2324 			goto bad;
2325 		}
2326 		got_netmask = B_TRUE;
2327 		netmask6.sin6_family = af;
2328 		(void) memcpy(&lifr.lifr_addr, &netmask6,
2329 		    sizeof (netmask6));
2330 	}
2331 	if (got_netmask &&
2332 	    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2333 		zerror(zlogp, B_TRUE, "%s: could not set netmask",
2334 		    lifr.lifr_name);
2335 		goto bad;
2336 	}
2337 
2338 	/* Set the interface address */
2339 	lifr.lifr_addr = laddr;
2340 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2341 		zerror(zlogp, B_TRUE,
2342 		    "%s: could not set IP address to %s",
2343 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
2344 		goto bad;
2345 	}
2346 
2347 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2348 		zerror(zlogp, B_TRUE, "%s: could not get flags",
2349 		    lifr.lifr_name);
2350 		goto bad;
2351 	}
2352 	lifr.lifr_flags |= IFF_UP;
2353 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2354 		int save_errno = errno;
2355 		char *zone_using;
2356 
2357 		/*
2358 		 * If we failed with something other than EADDRNOTAVAIL,
2359 		 * then skip to the end.  Otherwise, look up our address,
2360 		 * then call a function to determine which zone is already
2361 		 * using that address.
2362 		 */
2363 		if (errno != EADDRNOTAVAIL) {
2364 			zerror(zlogp, B_TRUE,
2365 			    "%s: could not bring network interface up",
2366 			    lifr.lifr_name);
2367 			goto bad;
2368 		}
2369 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2370 			zerror(zlogp, B_TRUE, "%s: could not get address",
2371 			    lifr.lifr_name);
2372 			goto bad;
2373 		}
2374 		zone_using = who_is_using(zlogp, &lifr);
2375 		errno = save_errno;
2376 		if (zone_using == NULL)
2377 			zerror(zlogp, B_TRUE,
2378 			    "%s: could not bring network interface up",
2379 			    lifr.lifr_name);
2380 		else
2381 			zerror(zlogp, B_TRUE, "%s: could not bring network "
2382 			    "interface up: address in use by zone '%s'",
2383 			    lifr.lifr_name, zone_using);
2384 		goto bad;
2385 	}
2386 
2387 	if (!got_netmask && !is_loopback) {
2388 		/*
2389 		 * A common, but often non-fatal problem, is that the system
2390 		 * cannot find the netmask for an interface address. This is
2391 		 * often caused by it being only in /etc/inet/netmasks, but
2392 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2393 		 * in that. This doesn't show up at boot because the netmask
2394 		 * is obtained from /etc/inet/netmasks when no network
2395 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2396 		 * available. We warn the user here that something like this
2397 		 * has happened and we're just running with a default and
2398 		 * possible incorrect netmask.
2399 		 */
2400 		char buffer[INET6_ADDRSTRLEN];
2401 		void  *addr;
2402 		const char *nomatch = "no matching subnet found in netmasks(4)";
2403 
2404 		if (af == AF_INET)
2405 			addr = &((struct sockaddr_in *)
2406 			    (&lifr.lifr_addr))->sin_addr;
2407 		else
2408 			addr = &((struct sockaddr_in6 *)
2409 			    (&lifr.lifr_addr))->sin6_addr;
2410 
2411 		/*
2412 		 * Find out what netmask the interface is going to be using.
2413 		 * If we just brought up an IPMP data address on an underlying
2414 		 * interface above, the address will have already migrated, so
2415 		 * the SIOCGLIFNETMASK won't be able to find it (but we need
2416 		 * to bring the address up to get the actual netmask).  Just
2417 		 * omit printing the actual netmask in this corner-case.
2418 		 */
2419 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2420 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL) {
2421 			zerror(zlogp, B_FALSE, "WARNING: %s; using default.",
2422 			    nomatch);
2423 		} else {
2424 			zerror(zlogp, B_FALSE,
2425 			    "WARNING: %s: %s: %s; using default of %s.",
2426 			    lifr.lifr_name, nomatch, addrstr4, buffer);
2427 		}
2428 	}
2429 
2430 	/*
2431 	 * If a default router was specified for this interface
2432 	 * set the route now. Ignore if already set.
2433 	 */
2434 	if (strlen(nwiftabptr->zone_nwif_defrouter) > 0) {
2435 		int status;
2436 		char *argv[7];
2437 
2438 		argv[0] = "route";
2439 		argv[1] = "add";
2440 		argv[2] = "-ifp";
2441 		argv[3] = nwiftabptr->zone_nwif_physical;
2442 		argv[4] = "default";
2443 		argv[5] = nwiftabptr->zone_nwif_defrouter;
2444 		argv[6] = NULL;
2445 
2446 		status = forkexec(zlogp, "/usr/sbin/route", argv);
2447 		if (status != 0 && status != EEXIST)
2448 			zerror(zlogp, B_FALSE, "Unable to set route for "
2449 			    "interface %s to %s\n",
2450 			    nwiftabptr->zone_nwif_physical,
2451 			    nwiftabptr->zone_nwif_defrouter);
2452 	}
2453 
2454 	(void) close(s);
2455 	return (Z_OK);
2456 bad:
2457 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2458 	(void) close(s);
2459 	return (-1);
2460 }
2461 
2462 /*
2463  * Sets up network interfaces based on information from the zone configuration.
2464  * IPv4 and IPv6 loopback interfaces are set up "for free", modeling the global
2465  * system.
2466  *
2467  * If anything goes wrong, we log a general error message, attempt to tear down
2468  * whatever we set up, and return an error.
2469  */
2470 static int
2471 configure_shared_network_interfaces(zlog_t *zlogp)
2472 {
2473 	zone_dochandle_t handle;
2474 	struct zone_nwiftab nwiftab, loopback_iftab;
2475 	zoneid_t zoneid;
2476 
2477 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2478 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2479 		return (-1);
2480 	}
2481 
2482 	if ((handle = zonecfg_init_handle()) == NULL) {
2483 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2484 		return (-1);
2485 	}
2486 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2487 		zerror(zlogp, B_FALSE, "invalid configuration");
2488 		zonecfg_fini_handle(handle);
2489 		return (-1);
2490 	}
2491 	if (zonecfg_setnwifent(handle) == Z_OK) {
2492 		for (;;) {
2493 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2494 				break;
2495 			if (configure_one_interface(zlogp, zoneid, &nwiftab) !=
2496 			    Z_OK) {
2497 				(void) zonecfg_endnwifent(handle);
2498 				zonecfg_fini_handle(handle);
2499 				return (-1);
2500 			}
2501 		}
2502 		(void) zonecfg_endnwifent(handle);
2503 	}
2504 	zonecfg_fini_handle(handle);
2505 	if (is_system_labeled()) {
2506 		/*
2507 		 * Labeled zones share the loopback interface
2508 		 * so it is not plumbed for shared stack instances.
2509 		 */
2510 		return (0);
2511 	}
2512 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2513 	    sizeof (loopback_iftab.zone_nwif_physical));
2514 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2515 	    sizeof (loopback_iftab.zone_nwif_address));
2516 	loopback_iftab.zone_nwif_defrouter[0] = '\0';
2517 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2518 		return (-1);
2519 
2520 	/* Always plumb up the IPv6 loopback interface. */
2521 	(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2522 	    sizeof (loopback_iftab.zone_nwif_address));
2523 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2524 		return (-1);
2525 	return (0);
2526 }
2527 
2528 static void
2529 zdlerror(zlog_t *zlogp, dladm_status_t err, const char *dlname, const char *str)
2530 {
2531 	char errmsg[DLADM_STRSIZE];
2532 
2533 	(void) dladm_status2str(err, errmsg);
2534 	zerror(zlogp, B_FALSE, "%s '%s': %s", str, dlname, errmsg);
2535 }
2536 
2537 static int
2538 add_datalink(zlog_t *zlogp, char *zone_name, datalink_id_t linkid, char *dlname)
2539 {
2540 	dladm_status_t err;
2541 
2542 	/* First check if it's in use by global zone. */
2543 	if (zonecfg_ifname_exists(AF_INET, dlname) ||
2544 	    zonecfg_ifname_exists(AF_INET6, dlname)) {
2545 		zerror(zlogp, B_FALSE, "WARNING: skipping network interface "
2546 		    "'%s' which is used in the global zone", dlname);
2547 		return (-1);
2548 	}
2549 
2550 	/* Set zoneid of this link. */
2551 	err = dladm_set_linkprop(dld_handle, linkid, "zone", &zone_name, 1,
2552 	    DLADM_OPT_ACTIVE);
2553 	if (err != DLADM_STATUS_OK) {
2554 		zdlerror(zlogp, err, dlname,
2555 		    "WARNING: unable to add network interface");
2556 		return (-1);
2557 	}
2558 	return (0);
2559 }
2560 
2561 /*
2562  * Add the kernel access control information for the interface names.
2563  * If anything goes wrong, we log a general error message, attempt to tear down
2564  * whatever we set up, and return an error.
2565  */
2566 static int
2567 configure_exclusive_network_interfaces(zlog_t *zlogp)
2568 {
2569 	zone_dochandle_t handle;
2570 	struct zone_nwiftab nwiftab;
2571 	char rootpath[MAXPATHLEN];
2572 	char path[MAXPATHLEN];
2573 	datalink_id_t linkid;
2574 	di_prof_t prof = NULL;
2575 	boolean_t added = B_FALSE;
2576 
2577 	if ((handle = zonecfg_init_handle()) == NULL) {
2578 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2579 		return (-1);
2580 	}
2581 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2582 		zerror(zlogp, B_FALSE, "invalid configuration");
2583 		zonecfg_fini_handle(handle);
2584 		return (-1);
2585 	}
2586 
2587 	if (zonecfg_setnwifent(handle) != Z_OK) {
2588 		zonecfg_fini_handle(handle);
2589 		return (0);
2590 	}
2591 
2592 	for (;;) {
2593 		if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2594 			break;
2595 
2596 		if (prof == NULL) {
2597 			if (zone_get_devroot(zone_name, rootpath,
2598 			    sizeof (rootpath)) != Z_OK) {
2599 				(void) zonecfg_endnwifent(handle);
2600 				zonecfg_fini_handle(handle);
2601 				zerror(zlogp, B_TRUE,
2602 				    "unable to determine dev root");
2603 				return (-1);
2604 			}
2605 			(void) snprintf(path, sizeof (path), "%s%s", rootpath,
2606 			    "/dev");
2607 			if (di_prof_init(path, &prof) != 0) {
2608 				(void) zonecfg_endnwifent(handle);
2609 				zonecfg_fini_handle(handle);
2610 				zerror(zlogp, B_TRUE,
2611 				    "failed to initialize profile");
2612 				return (-1);
2613 			}
2614 		}
2615 
2616 		/*
2617 		 * Create the /dev entry for backward compatibility.
2618 		 * Only create the /dev entry if it's not in use.
2619 		 * Note that the zone still boots when the assigned
2620 		 * interface is inaccessible, used by others, etc.
2621 		 * Also, when vanity naming is used, some interface do
2622 		 * do not have corresponding /dev node names (for example,
2623 		 * vanity named aggregations).  The /dev entry is not
2624 		 * created in that case.  The /dev/net entry is always
2625 		 * accessible.
2626 		 */
2627 		if (dladm_name2info(dld_handle, nwiftab.zone_nwif_physical,
2628 		    &linkid, NULL, NULL, NULL) == DLADM_STATUS_OK &&
2629 		    add_datalink(zlogp, zone_name, linkid,
2630 		    nwiftab.zone_nwif_physical) == 0) {
2631 			added = B_TRUE;
2632 		} else {
2633 			(void) zonecfg_endnwifent(handle);
2634 			zonecfg_fini_handle(handle);
2635 			zerror(zlogp, B_TRUE, "failed to add network device");
2636 			return (-1);
2637 		}
2638 	}
2639 	(void) zonecfg_endnwifent(handle);
2640 	zonecfg_fini_handle(handle);
2641 
2642 	if (prof != NULL && added) {
2643 		if (di_prof_commit(prof) != 0) {
2644 			zerror(zlogp, B_TRUE, "failed to commit profile");
2645 			return (-1);
2646 		}
2647 	}
2648 	if (prof != NULL)
2649 		di_prof_fini(prof);
2650 
2651 	return (0);
2652 }
2653 
2654 static int
2655 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2656 {
2657 	int dlnum = 0;
2658 
2659 	/*
2660 	 * The kernel shutdown callback for the dls module should have removed
2661 	 * all datalinks from this zone.  If any remain, then there's a
2662 	 * problem.
2663 	 */
2664 	if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2665 		zerror(zlogp, B_TRUE, "unable to list network interfaces");
2666 		return (-1);
2667 	}
2668 	if (dlnum != 0) {
2669 		zerror(zlogp, B_FALSE,
2670 		    "datalinks remain in zone after shutdown");
2671 		return (-1);
2672 	}
2673 	return (0);
2674 }
2675 
2676 static int
2677 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2678     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2679 {
2680 	int fd;
2681 	struct strioctl ioc;
2682 	tcp_ioc_abort_conn_t conn;
2683 	int error;
2684 
2685 	conn.ac_local = *local;
2686 	conn.ac_remote = *remote;
2687 	conn.ac_start = TCPS_SYN_SENT;
2688 	conn.ac_end = TCPS_TIME_WAIT;
2689 	conn.ac_zoneid = zoneid;
2690 
2691 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2692 	ioc.ic_timout = -1; /* infinite timeout */
2693 	ioc.ic_len = sizeof (conn);
2694 	ioc.ic_dp = (char *)&conn;
2695 
2696 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2697 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2698 		return (-1);
2699 	}
2700 
2701 	error = ioctl(fd, I_STR, &ioc);
2702 	(void) close(fd);
2703 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2704 		return (0);
2705 	return (-1);
2706 }
2707 
2708 static int
2709 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2710 {
2711 	struct sockaddr_storage l, r;
2712 	struct sockaddr_in *local, *remote;
2713 	struct sockaddr_in6 *local6, *remote6;
2714 	int error;
2715 
2716 	/*
2717 	 * Abort IPv4 connections.
2718 	 */
2719 	bzero(&l, sizeof (*local));
2720 	local = (struct sockaddr_in *)&l;
2721 	local->sin_family = AF_INET;
2722 	local->sin_addr.s_addr = INADDR_ANY;
2723 	local->sin_port = 0;
2724 
2725 	bzero(&r, sizeof (*remote));
2726 	remote = (struct sockaddr_in *)&r;
2727 	remote->sin_family = AF_INET;
2728 	remote->sin_addr.s_addr = INADDR_ANY;
2729 	remote->sin_port = 0;
2730 
2731 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2732 		return (error);
2733 
2734 	/*
2735 	 * Abort IPv6 connections.
2736 	 */
2737 	bzero(&l, sizeof (*local6));
2738 	local6 = (struct sockaddr_in6 *)&l;
2739 	local6->sin6_family = AF_INET6;
2740 	local6->sin6_port = 0;
2741 	local6->sin6_addr = in6addr_any;
2742 
2743 	bzero(&r, sizeof (*remote6));
2744 	remote6 = (struct sockaddr_in6 *)&r;
2745 	remote6->sin6_family = AF_INET6;
2746 	remote6->sin6_port = 0;
2747 	remote6->sin6_addr = in6addr_any;
2748 
2749 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2750 		return (error);
2751 	return (0);
2752 }
2753 
2754 static int
2755 get_privset(zlog_t *zlogp, priv_set_t *privs, zone_mnt_t mount_cmd)
2756 {
2757 	int error = -1;
2758 	zone_dochandle_t handle;
2759 	char *privname = NULL;
2760 
2761 	if ((handle = zonecfg_init_handle()) == NULL) {
2762 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2763 		return (-1);
2764 	}
2765 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2766 		zerror(zlogp, B_FALSE, "invalid configuration");
2767 		zonecfg_fini_handle(handle);
2768 		return (-1);
2769 	}
2770 
2771 	if (ALT_MOUNT(mount_cmd)) {
2772 		zone_iptype_t	iptype;
2773 		const char	*curr_iptype;
2774 
2775 		if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
2776 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
2777 			zonecfg_fini_handle(handle);
2778 			return (-1);
2779 		}
2780 
2781 		switch (iptype) {
2782 		case ZS_SHARED:
2783 			curr_iptype = "shared";
2784 			break;
2785 		case ZS_EXCLUSIVE:
2786 			curr_iptype = "exclusive";
2787 			break;
2788 		}
2789 
2790 		if (zonecfg_default_privset(privs, curr_iptype) == Z_OK) {
2791 			zonecfg_fini_handle(handle);
2792 			return (0);
2793 		}
2794 		zerror(zlogp, B_FALSE,
2795 		    "failed to determine the zone's default privilege set");
2796 		zonecfg_fini_handle(handle);
2797 		return (-1);
2798 	}
2799 
2800 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2801 	case Z_OK:
2802 		error = 0;
2803 		break;
2804 	case Z_PRIV_PROHIBITED:
2805 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2806 		    "within the zone's privilege set", privname);
2807 		break;
2808 	case Z_PRIV_REQUIRED:
2809 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2810 		    "from the zone's privilege set", privname);
2811 		break;
2812 	case Z_PRIV_UNKNOWN:
2813 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2814 		    "in the zone's privilege set", privname);
2815 		break;
2816 	default:
2817 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2818 		    "privilege set");
2819 		break;
2820 	}
2821 
2822 	free(privname);
2823 	zonecfg_fini_handle(handle);
2824 	return (error);
2825 }
2826 
2827 static int
2828 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2829 {
2830 	nvlist_t *nvl = NULL;
2831 	char *nvl_packed = NULL;
2832 	size_t nvl_size = 0;
2833 	nvlist_t **nvlv = NULL;
2834 	int rctlcount = 0;
2835 	int error = -1;
2836 	zone_dochandle_t handle;
2837 	struct zone_rctltab rctltab;
2838 	rctlblk_t *rctlblk = NULL;
2839 
2840 	*bufp = NULL;
2841 	*bufsizep = 0;
2842 
2843 	if ((handle = zonecfg_init_handle()) == NULL) {
2844 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2845 		return (-1);
2846 	}
2847 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2848 		zerror(zlogp, B_FALSE, "invalid configuration");
2849 		zonecfg_fini_handle(handle);
2850 		return (-1);
2851 	}
2852 
2853 	rctltab.zone_rctl_valptr = NULL;
2854 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2855 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2856 		goto out;
2857 	}
2858 
2859 	if (zonecfg_setrctlent(handle) != Z_OK) {
2860 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2861 		goto out;
2862 	}
2863 
2864 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2865 		zerror(zlogp, B_TRUE, "memory allocation failed");
2866 		goto out;
2867 	}
2868 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2869 		struct zone_rctlvaltab *rctlval;
2870 		uint_t i, count;
2871 		const char *name = rctltab.zone_rctl_name;
2872 
2873 		/* zoneadm should have already warned about unknown rctls. */
2874 		if (!zonecfg_is_rctl(name)) {
2875 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2876 			rctltab.zone_rctl_valptr = NULL;
2877 			continue;
2878 		}
2879 		count = 0;
2880 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2881 		    rctlval = rctlval->zone_rctlval_next) {
2882 			count++;
2883 		}
2884 		if (count == 0) {	/* ignore */
2885 			continue;	/* Nothing to free */
2886 		}
2887 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2888 			goto out;
2889 		i = 0;
2890 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2891 		    rctlval = rctlval->zone_rctlval_next, i++) {
2892 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2893 				zerror(zlogp, B_TRUE, "%s failed",
2894 				    "nvlist_alloc");
2895 				goto out;
2896 			}
2897 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2898 			    != Z_OK) {
2899 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2900 				    "(priv=%s,limit=%s,action=%s)",
2901 				    rctlval->zone_rctlval_priv,
2902 				    rctlval->zone_rctlval_limit,
2903 				    rctlval->zone_rctlval_action);
2904 				goto out;
2905 			}
2906 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2907 				zerror(zlogp, B_FALSE,
2908 				    "(priv=%s,limit=%s,action=%s) is not a "
2909 				    "valid value for rctl '%s'",
2910 				    rctlval->zone_rctlval_priv,
2911 				    rctlval->zone_rctlval_limit,
2912 				    rctlval->zone_rctlval_action,
2913 				    name);
2914 				goto out;
2915 			}
2916 			if (nvlist_add_uint64(nvlv[i], "privilege",
2917 			    rctlblk_get_privilege(rctlblk)) != 0) {
2918 				zerror(zlogp, B_FALSE, "%s failed",
2919 				    "nvlist_add_uint64");
2920 				goto out;
2921 			}
2922 			if (nvlist_add_uint64(nvlv[i], "limit",
2923 			    rctlblk_get_value(rctlblk)) != 0) {
2924 				zerror(zlogp, B_FALSE, "%s failed",
2925 				    "nvlist_add_uint64");
2926 				goto out;
2927 			}
2928 			if (nvlist_add_uint64(nvlv[i], "action",
2929 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
2930 			    != 0) {
2931 				zerror(zlogp, B_FALSE, "%s failed",
2932 				    "nvlist_add_uint64");
2933 				goto out;
2934 			}
2935 		}
2936 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2937 		rctltab.zone_rctl_valptr = NULL;
2938 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
2939 		    != 0) {
2940 			zerror(zlogp, B_FALSE, "%s failed",
2941 			    "nvlist_add_nvlist_array");
2942 			goto out;
2943 		}
2944 		for (i = 0; i < count; i++)
2945 			nvlist_free(nvlv[i]);
2946 		free(nvlv);
2947 		nvlv = NULL;
2948 		rctlcount++;
2949 	}
2950 	(void) zonecfg_endrctlent(handle);
2951 
2952 	if (rctlcount == 0) {
2953 		error = 0;
2954 		goto out;
2955 	}
2956 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
2957 	    != 0) {
2958 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
2959 		goto out;
2960 	}
2961 
2962 	error = 0;
2963 	*bufp = nvl_packed;
2964 	*bufsizep = nvl_size;
2965 
2966 out:
2967 	free(rctlblk);
2968 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2969 	if (error && nvl_packed != NULL)
2970 		free(nvl_packed);
2971 	if (nvl != NULL)
2972 		nvlist_free(nvl);
2973 	if (nvlv != NULL)
2974 		free(nvlv);
2975 	if (handle != NULL)
2976 		zonecfg_fini_handle(handle);
2977 	return (error);
2978 }
2979 
2980 static int
2981 get_implicit_datasets(zlog_t *zlogp, char **retstr)
2982 {
2983 	char cmdbuf[2 * MAXPATHLEN];
2984 
2985 	if (query_hook[0] == '\0')
2986 		return (0);
2987 
2988 	if (snprintf(cmdbuf, sizeof (cmdbuf), "%s datasets", query_hook)
2989 	    > sizeof (cmdbuf))
2990 		return (-1);
2991 
2992 	if (do_subproc(zlogp, cmdbuf, retstr) != 0)
2993 		return (-1);
2994 
2995 	return (0);
2996 }
2997 
2998 static int
2999 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3000 {
3001 	zone_dochandle_t handle;
3002 	struct zone_dstab dstab;
3003 	size_t total, offset, len;
3004 	int error = -1;
3005 	char *str = NULL;
3006 	char *implicit_datasets = NULL;
3007 	int implicit_len = 0;
3008 
3009 	*bufp = NULL;
3010 	*bufsizep = 0;
3011 
3012 	if ((handle = zonecfg_init_handle()) == NULL) {
3013 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3014 		return (-1);
3015 	}
3016 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3017 		zerror(zlogp, B_FALSE, "invalid configuration");
3018 		zonecfg_fini_handle(handle);
3019 		return (-1);
3020 	}
3021 
3022 	if (get_implicit_datasets(zlogp, &implicit_datasets) != 0) {
3023 		zerror(zlogp, B_FALSE, "getting implicit datasets failed");
3024 		goto out;
3025 	}
3026 
3027 	if (zonecfg_setdsent(handle) != Z_OK) {
3028 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3029 		goto out;
3030 	}
3031 
3032 	total = 0;
3033 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3034 		total += strlen(dstab.zone_dataset_name) + 1;
3035 	(void) zonecfg_enddsent(handle);
3036 
3037 	if (implicit_datasets != NULL)
3038 		implicit_len = strlen(implicit_datasets);
3039 	if (implicit_len > 0)
3040 		total += implicit_len + 1;
3041 
3042 	if (total == 0) {
3043 		error = 0;
3044 		goto out;
3045 	}
3046 
3047 	if ((str = malloc(total)) == NULL) {
3048 		zerror(zlogp, B_TRUE, "memory allocation failed");
3049 		goto out;
3050 	}
3051 
3052 	if (zonecfg_setdsent(handle) != Z_OK) {
3053 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3054 		goto out;
3055 	}
3056 	offset = 0;
3057 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3058 		len = strlen(dstab.zone_dataset_name);
3059 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
3060 		    total - offset);
3061 		offset += len;
3062 		if (offset < total - 1)
3063 			str[offset++] = ',';
3064 	}
3065 	(void) zonecfg_enddsent(handle);
3066 
3067 	if (implicit_len > 0)
3068 		(void) strlcpy(str + offset, implicit_datasets, total - offset);
3069 
3070 	error = 0;
3071 	*bufp = str;
3072 	*bufsizep = total;
3073 
3074 out:
3075 	if (error != 0 && str != NULL)
3076 		free(str);
3077 	if (handle != NULL)
3078 		zonecfg_fini_handle(handle);
3079 	if (implicit_datasets != NULL)
3080 		free(implicit_datasets);
3081 
3082 	return (error);
3083 }
3084 
3085 static int
3086 validate_datasets(zlog_t *zlogp)
3087 {
3088 	zone_dochandle_t handle;
3089 	struct zone_dstab dstab;
3090 	zfs_handle_t *zhp;
3091 	libzfs_handle_t *hdl;
3092 
3093 	if ((handle = zonecfg_init_handle()) == NULL) {
3094 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3095 		return (-1);
3096 	}
3097 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3098 		zerror(zlogp, B_FALSE, "invalid configuration");
3099 		zonecfg_fini_handle(handle);
3100 		return (-1);
3101 	}
3102 
3103 	if (zonecfg_setdsent(handle) != Z_OK) {
3104 		zerror(zlogp, B_FALSE, "invalid configuration");
3105 		zonecfg_fini_handle(handle);
3106 		return (-1);
3107 	}
3108 
3109 	if ((hdl = libzfs_init()) == NULL) {
3110 		zerror(zlogp, B_FALSE, "opening ZFS library");
3111 		zonecfg_fini_handle(handle);
3112 		return (-1);
3113 	}
3114 
3115 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3116 
3117 		if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3118 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
3119 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3120 			    dstab.zone_dataset_name);
3121 			zonecfg_fini_handle(handle);
3122 			libzfs_fini(hdl);
3123 			return (-1);
3124 		}
3125 
3126 		/*
3127 		 * Automatically set the 'zoned' property.  We check the value
3128 		 * first because we'll get EPERM if it is already set.
3129 		 */
3130 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3131 		    zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3132 		    "on") != 0) {
3133 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3134 			    "property for ZFS dataset '%s'\n",
3135 			    dstab.zone_dataset_name);
3136 			zonecfg_fini_handle(handle);
3137 			zfs_close(zhp);
3138 			libzfs_fini(hdl);
3139 			return (-1);
3140 		}
3141 
3142 		zfs_close(zhp);
3143 	}
3144 	(void) zonecfg_enddsent(handle);
3145 
3146 	zonecfg_fini_handle(handle);
3147 	libzfs_fini(hdl);
3148 
3149 	return (0);
3150 }
3151 
3152 /*
3153  * Mount lower level home directories into/from current zone
3154  * Share exported directories specified in dfstab for zone
3155  */
3156 static int
3157 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
3158 {
3159 	zoneid_t *zids = NULL;
3160 	priv_set_t *zid_privs;
3161 	const priv_impl_info_t *ip = NULL;
3162 	uint_t nzents_saved;
3163 	uint_t nzents;
3164 	int i;
3165 	char readonly[] = "ro";
3166 	struct zone_fstab lower_fstab;
3167 	char *argv[4];
3168 
3169 	if (!is_system_labeled())
3170 		return (0);
3171 
3172 	if (zid_label == NULL) {
3173 		zid_label = m_label_alloc(MAC_LABEL);
3174 		if (zid_label == NULL)
3175 			return (-1);
3176 	}
3177 
3178 	/* Make sure our zone has an /export/home dir */
3179 	(void) make_one_dir(zlogp, rootpath, "/export/home",
3180 	    DEFAULT_DIR_MODE, DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3181 
3182 	lower_fstab.zone_fs_raw[0] = '\0';
3183 	(void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
3184 	    sizeof (lower_fstab.zone_fs_type));
3185 	lower_fstab.zone_fs_options = NULL;
3186 	(void) zonecfg_add_fs_option(&lower_fstab, readonly);
3187 
3188 	/*
3189 	 * Get the list of zones from the kernel
3190 	 */
3191 	if (zone_list(NULL, &nzents) != 0) {
3192 		zerror(zlogp, B_TRUE, "unable to list zones");
3193 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3194 		return (-1);
3195 	}
3196 again:
3197 	if (nzents == 0) {
3198 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3199 		return (-1);
3200 	}
3201 
3202 	zids = malloc(nzents * sizeof (zoneid_t));
3203 	if (zids == NULL) {
3204 		zerror(zlogp, B_TRUE, "memory allocation failed");
3205 		return (-1);
3206 	}
3207 	nzents_saved = nzents;
3208 
3209 	if (zone_list(zids, &nzents) != 0) {
3210 		zerror(zlogp, B_TRUE, "unable to list zones");
3211 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3212 		free(zids);
3213 		return (-1);
3214 	}
3215 	if (nzents != nzents_saved) {
3216 		/* list changed, try again */
3217 		free(zids);
3218 		goto again;
3219 	}
3220 
3221 	ip = getprivimplinfo();
3222 	if ((zid_privs = priv_allocset()) == NULL) {
3223 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3224 		zonecfg_free_fs_option_list(
3225 		    lower_fstab.zone_fs_options);
3226 		free(zids);
3227 		return (-1);
3228 	}
3229 
3230 	for (i = 0; i < nzents; i++) {
3231 		char zid_name[ZONENAME_MAX];
3232 		zone_state_t zid_state;
3233 		char zid_rpath[MAXPATHLEN];
3234 		struct stat stat_buf;
3235 
3236 		if (zids[i] == GLOBAL_ZONEID)
3237 			continue;
3238 
3239 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3240 			continue;
3241 
3242 		/*
3243 		 * Do special setup for the zone we are booting
3244 		 */
3245 		if (strcmp(zid_name, zone_name) == 0) {
3246 			struct zone_fstab autofs_fstab;
3247 			char map_path[MAXPATHLEN];
3248 			int fd;
3249 
3250 			/*
3251 			 * Create auto_home_<zone> map for this zone
3252 			 * in the global zone. The non-global zone entry
3253 			 * will be created by automount when the zone
3254 			 * is booted.
3255 			 */
3256 
3257 			(void) snprintf(autofs_fstab.zone_fs_special,
3258 			    MAXPATHLEN, "auto_home_%s", zid_name);
3259 
3260 			(void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
3261 			    "/zone/%s/home", zid_name);
3262 
3263 			(void) snprintf(map_path, sizeof (map_path),
3264 			    "/etc/%s", autofs_fstab.zone_fs_special);
3265 			/*
3266 			 * If the map file doesn't exist create a template
3267 			 */
3268 			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
3269 			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
3270 				int len;
3271 				char map_rec[MAXPATHLEN];
3272 
3273 				len = snprintf(map_rec, sizeof (map_rec),
3274 				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
3275 				    autofs_fstab.zone_fs_special, rootpath);
3276 				(void) write(fd, map_rec, len);
3277 				(void) close(fd);
3278 			}
3279 
3280 			/*
3281 			 * Mount auto_home_<zone> in the global zone if absent.
3282 			 * If it's already of type autofs, then
3283 			 * don't mount it again.
3284 			 */
3285 			if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
3286 			    strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
3287 				char optstr[] = "indirect,ignore,nobrowse";
3288 
3289 				(void) make_one_dir(zlogp, "",
3290 				    autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE,
3291 				    DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3292 
3293 				/*
3294 				 * Mount will fail if automounter has already
3295 				 * processed the auto_home_<zonename> map
3296 				 */
3297 				(void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
3298 				    autofs_fstab.zone_fs_special,
3299 				    autofs_fstab.zone_fs_dir);
3300 			}
3301 			continue;
3302 		}
3303 
3304 
3305 		if (zone_get_state(zid_name, &zid_state) != Z_OK ||
3306 		    (zid_state != ZONE_STATE_READY &&
3307 		    zid_state != ZONE_STATE_RUNNING))
3308 			/* Skip over zones without mounted filesystems */
3309 			continue;
3310 
3311 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3312 		    sizeof (m_label_t)) < 0)
3313 			/* Skip over zones with unspecified label */
3314 			continue;
3315 
3316 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3317 		    sizeof (zid_rpath)) == -1)
3318 			/* Skip over zones with bad path */
3319 			continue;
3320 
3321 		if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
3322 		    sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
3323 			/* Skip over zones with bad privs */
3324 			continue;
3325 
3326 		/*
3327 		 * Reading down is valid according to our label model
3328 		 * but some customers want to disable it because it
3329 		 * allows execute down and other possible attacks.
3330 		 * Therefore, we restrict this feature to zones that
3331 		 * have the NET_MAC_AWARE privilege which is required
3332 		 * for NFS read-down semantics.
3333 		 */
3334 		if ((bldominates(zlabel, zid_label)) &&
3335 		    (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
3336 			/*
3337 			 * Our zone dominates this one.
3338 			 * Create a lofs mount from lower zone's /export/home
3339 			 */
3340 			(void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3341 			    "%s/zone/%s/export/home", rootpath, zid_name);
3342 
3343 			/*
3344 			 * If the target is already an LOFS mount
3345 			 * then don't do it again.
3346 			 */
3347 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3348 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3349 
3350 				if (snprintf(lower_fstab.zone_fs_special,
3351 				    MAXPATHLEN, "%s/export",
3352 				    zid_rpath) > MAXPATHLEN)
3353 					continue;
3354 
3355 				/*
3356 				 * Make sure the lower-level home exists
3357 				 */
3358 				if (make_one_dir(zlogp,
3359 				    lower_fstab.zone_fs_special, "/home",
3360 				    DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
3361 				    DEFAULT_DIR_GROUP) != 0)
3362 					continue;
3363 
3364 				(void) strlcat(lower_fstab.zone_fs_special,
3365 				    "/home", MAXPATHLEN);
3366 
3367 				/*
3368 				 * Mount can fail because the lower-level
3369 				 * zone may have already done a mount up.
3370 				 */
3371 				(void) mount_one(zlogp, &lower_fstab, "",
3372 				    Z_MNT_BOOT);
3373 			}
3374 		} else if ((bldominates(zid_label, zlabel)) &&
3375 		    (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
3376 			/*
3377 			 * This zone dominates our zone.
3378 			 * Create a lofs mount from our zone's /export/home
3379 			 */
3380 			if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3381 			    "%s/zone/%s/export/home", zid_rpath,
3382 			    zone_name) > MAXPATHLEN)
3383 				continue;
3384 
3385 			/*
3386 			 * If the target is already an LOFS mount
3387 			 * then don't do it again.
3388 			 */
3389 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3390 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3391 
3392 				(void) snprintf(lower_fstab.zone_fs_special,
3393 				    MAXPATHLEN, "%s/export/home", rootpath);
3394 
3395 				/*
3396 				 * Mount can fail because the higher-level
3397 				 * zone may have already done a mount down.
3398 				 */
3399 				(void) mount_one(zlogp, &lower_fstab, "",
3400 				    Z_MNT_BOOT);
3401 			}
3402 		}
3403 	}
3404 	zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3405 	priv_freeset(zid_privs);
3406 	free(zids);
3407 
3408 	/*
3409 	 * Now share any exported directories from this zone.
3410 	 * Each zone can have its own dfstab.
3411 	 */
3412 
3413 	argv[0] = "zoneshare";
3414 	argv[1] = "-z";
3415 	argv[2] = zone_name;
3416 	argv[3] = NULL;
3417 
3418 	(void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
3419 	/* Don't check for errors since they don't affect the zone */
3420 
3421 	return (0);
3422 }
3423 
3424 /*
3425  * Unmount lofs mounts from higher level zones
3426  * Unshare nfs exported directories
3427  */
3428 static void
3429 tsol_unmounts(zlog_t *zlogp, char *zone_name)
3430 {
3431 	zoneid_t *zids = NULL;
3432 	uint_t nzents_saved;
3433 	uint_t nzents;
3434 	int i;
3435 	char *argv[4];
3436 	char path[MAXPATHLEN];
3437 
3438 	if (!is_system_labeled())
3439 		return;
3440 
3441 	/*
3442 	 * Get the list of zones from the kernel
3443 	 */
3444 	if (zone_list(NULL, &nzents) != 0) {
3445 		return;
3446 	}
3447 
3448 	if (zid_label == NULL) {
3449 		zid_label = m_label_alloc(MAC_LABEL);
3450 		if (zid_label == NULL)
3451 			return;
3452 	}
3453 
3454 again:
3455 	if (nzents == 0)
3456 		return;
3457 
3458 	zids = malloc(nzents * sizeof (zoneid_t));
3459 	if (zids == NULL) {
3460 		zerror(zlogp, B_TRUE, "memory allocation failed");
3461 		return;
3462 	}
3463 	nzents_saved = nzents;
3464 
3465 	if (zone_list(zids, &nzents) != 0) {
3466 		free(zids);
3467 		return;
3468 	}
3469 	if (nzents != nzents_saved) {
3470 		/* list changed, try again */
3471 		free(zids);
3472 		goto again;
3473 	}
3474 
3475 	for (i = 0; i < nzents; i++) {
3476 		char zid_name[ZONENAME_MAX];
3477 		zone_state_t zid_state;
3478 		char zid_rpath[MAXPATHLEN];
3479 
3480 		if (zids[i] == GLOBAL_ZONEID)
3481 			continue;
3482 
3483 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3484 			continue;
3485 
3486 		/*
3487 		 * Skip the zone we are halting
3488 		 */
3489 		if (strcmp(zid_name, zone_name) == 0)
3490 			continue;
3491 
3492 		if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
3493 		    sizeof (zid_state)) < 0) ||
3494 		    (zid_state < ZONE_IS_READY))
3495 			/* Skip over zones without mounted filesystems */
3496 			continue;
3497 
3498 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3499 		    sizeof (m_label_t)) < 0)
3500 			/* Skip over zones with unspecified label */
3501 			continue;
3502 
3503 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3504 		    sizeof (zid_rpath)) == -1)
3505 			/* Skip over zones with bad path */
3506 			continue;
3507 
3508 		if (zlabel != NULL && bldominates(zid_label, zlabel)) {
3509 			/*
3510 			 * This zone dominates our zone.
3511 			 * Unmount the lofs mount of our zone's /export/home
3512 			 */
3513 
3514 			if (snprintf(path, MAXPATHLEN,
3515 			    "%s/zone/%s/export/home", zid_rpath,
3516 			    zone_name) > MAXPATHLEN)
3517 				continue;
3518 
3519 			/* Skip over mount failures */
3520 			(void) umount(path);
3521 		}
3522 	}
3523 	free(zids);
3524 
3525 	/*
3526 	 * Unmount global zone autofs trigger for this zone
3527 	 */
3528 	(void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
3529 	/* Skip over mount failures */
3530 	(void) umount(path);
3531 
3532 	/*
3533 	 * Next unshare any exported directories from this zone.
3534 	 */
3535 
3536 	argv[0] = "zoneunshare";
3537 	argv[1] = "-z";
3538 	argv[2] = zone_name;
3539 	argv[3] = NULL;
3540 
3541 	(void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
3542 	/* Don't check for errors since they don't affect the zone */
3543 
3544 	/*
3545 	 * Finally, deallocate any devices in the zone.
3546 	 */
3547 
3548 	argv[0] = "deallocate";
3549 	argv[1] = "-Isz";
3550 	argv[2] = zone_name;
3551 	argv[3] = NULL;
3552 
3553 	(void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
3554 	/* Don't check for errors since they don't affect the zone */
3555 }
3556 
3557 /*
3558  * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
3559  * this zone.
3560  */
3561 static tsol_zcent_t *
3562 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
3563 {
3564 	FILE *fp;
3565 	tsol_zcent_t *zcent = NULL;
3566 	char line[MAXTNZLEN];
3567 
3568 	if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
3569 		zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
3570 		return (NULL);
3571 	}
3572 
3573 	while (fgets(line, sizeof (line), fp) != NULL) {
3574 		/*
3575 		 * Check for malformed database
3576 		 */
3577 		if (strlen(line) == MAXTNZLEN - 1)
3578 			break;
3579 		if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
3580 			continue;
3581 		if (strcmp(zcent->zc_name, zone_name) == 0)
3582 			break;
3583 		tsol_freezcent(zcent);
3584 		zcent = NULL;
3585 	}
3586 	(void) fclose(fp);
3587 
3588 	if (zcent == NULL) {
3589 		zerror(zlogp, B_FALSE, "zone requires a label assignment. "
3590 		    "See tnzonecfg(4)");
3591 	} else {
3592 		if (zlabel == NULL)
3593 			zlabel = m_label_alloc(MAC_LABEL);
3594 		/*
3595 		 * Save this zone's privileges for later read-down processing
3596 		 */
3597 		if ((zprivs = priv_allocset()) == NULL) {
3598 			zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3599 			return (NULL);
3600 		} else {
3601 			priv_copyset(privs, zprivs);
3602 		}
3603 	}
3604 	return (zcent);
3605 }
3606 
3607 /*
3608  * Add the Trusted Extensions multi-level ports for this zone.
3609  */
3610 static void
3611 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
3612 {
3613 	tsol_mlp_t *mlp;
3614 	tsol_mlpent_t tsme;
3615 
3616 	if (!is_system_labeled())
3617 		return;
3618 
3619 	tsme.tsme_zoneid = zoneid;
3620 	tsme.tsme_flags = 0;
3621 	for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
3622 		tsme.tsme_mlp = *mlp;
3623 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3624 			zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
3625 			    "on %d-%d/%d", mlp->mlp_port,
3626 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3627 		}
3628 	}
3629 
3630 	tsme.tsme_flags = TSOL_MEF_SHARED;
3631 	for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
3632 		tsme.tsme_mlp = *mlp;
3633 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3634 			zerror(zlogp, B_TRUE, "cannot set shared MLP "
3635 			    "on %d-%d/%d", mlp->mlp_port,
3636 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3637 		}
3638 	}
3639 }
3640 
3641 static void
3642 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
3643 {
3644 	tsol_mlpent_t tsme;
3645 
3646 	if (!is_system_labeled())
3647 		return;
3648 
3649 	(void) memset(&tsme, 0, sizeof (tsme));
3650 	tsme.tsme_zoneid = zoneid;
3651 	if (tnmlp(TNDB_FLUSH, &tsme) != 0)
3652 		zerror(zlogp, B_TRUE, "cannot flush MLPs");
3653 }
3654 
3655 int
3656 prtmount(const char *fs, void *x) {
3657 	zerror((zlog_t *)x, B_FALSE, "  %s", fs);
3658 	return (0);
3659 }
3660 
3661 /*
3662  * Look for zones running on the main system that are using this root (or any
3663  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
3664  * is found or if we can't tell.
3665  */
3666 static boolean_t
3667 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3668 {
3669 	zoneid_t *zids = NULL;
3670 	uint_t nzids = 0;
3671 	boolean_t retv;
3672 	int rlen, zlen;
3673 	char zroot[MAXPATHLEN];
3674 	char zonename[ZONENAME_MAX];
3675 
3676 	for (;;) {
3677 		nzids += 10;
3678 		zids = malloc(nzids * sizeof (*zids));
3679 		if (zids == NULL) {
3680 			zerror(zlogp, B_TRUE, "memory allocation failed");
3681 			return (B_TRUE);
3682 		}
3683 		if (zone_list(zids, &nzids) == 0)
3684 			break;
3685 		free(zids);
3686 	}
3687 	retv = B_FALSE;
3688 	rlen = strlen(rootpath);
3689 	while (nzids > 0) {
3690 		/*
3691 		 * Ignore errors; they just mean that the zone has disappeared
3692 		 * while we were busy.
3693 		 */
3694 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3695 		    sizeof (zroot)) == -1)
3696 			continue;
3697 		zlen = strlen(zroot);
3698 		if (zlen > rlen)
3699 			zlen = rlen;
3700 		if (strncmp(rootpath, zroot, zlen) == 0 &&
3701 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3702 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3703 			if (getzonenamebyid(zids[nzids], zonename,
3704 			    sizeof (zonename)) == -1)
3705 				(void) snprintf(zonename, sizeof (zonename),
3706 				    "id %d", (int)zids[nzids]);
3707 			zerror(zlogp, B_FALSE,
3708 			    "zone root %s already in use by zone %s",
3709 			    rootpath, zonename);
3710 			retv = B_TRUE;
3711 			break;
3712 		}
3713 	}
3714 	free(zids);
3715 	return (retv);
3716 }
3717 
3718 /*
3719  * Search for loopback mounts that use this same source node (same device and
3720  * inode).  Return B_TRUE if there is one or if we can't tell.
3721  */
3722 static boolean_t
3723 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3724 {
3725 	struct stat64 rst, zst;
3726 	struct mnttab *mnp;
3727 
3728 	if (stat64(rootpath, &rst) == -1) {
3729 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3730 		return (B_TRUE);
3731 	}
3732 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3733 		return (B_TRUE);
3734 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3735 		if (mnp->mnt_fstype == NULL ||
3736 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3737 			continue;
3738 		/* We're looking at a loopback mount.  Stat it. */
3739 		if (mnp->mnt_special != NULL &&
3740 		    stat64(mnp->mnt_special, &zst) != -1 &&
3741 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3742 			zerror(zlogp, B_FALSE,
3743 			    "zone root %s is reachable through %s",
3744 			    rootpath, mnp->mnt_mountp);
3745 			return (B_TRUE);
3746 		}
3747 	}
3748 	return (B_FALSE);
3749 }
3750 
3751 /*
3752  * Set memory cap and pool info for the zone's resource management
3753  * configuration.
3754  */
3755 static int
3756 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
3757 {
3758 	int res;
3759 	uint64_t tmp;
3760 	struct zone_mcaptab mcap;
3761 	char sched[MAXNAMELEN];
3762 	zone_dochandle_t handle = NULL;
3763 	char pool_err[128];
3764 
3765 	if ((handle = zonecfg_init_handle()) == NULL) {
3766 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3767 		return (Z_BAD_HANDLE);
3768 	}
3769 
3770 	if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
3771 		zerror(zlogp, B_FALSE, "invalid configuration");
3772 		zonecfg_fini_handle(handle);
3773 		return (res);
3774 	}
3775 
3776 	/*
3777 	 * If a memory cap is configured, set the cap in the kernel using
3778 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
3779 	 */
3780 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
3781 		uint64_t num;
3782 		char smf_err[128];
3783 
3784 		num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
3785 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
3786 			zerror(zlogp, B_TRUE, "could not set zone memory cap");
3787 			zonecfg_fini_handle(handle);
3788 			return (Z_INVAL);
3789 		}
3790 
3791 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
3792 			zerror(zlogp, B_FALSE, "enabling system/rcap service "
3793 			    "failed: %s", smf_err);
3794 			zonecfg_fini_handle(handle);
3795 			return (Z_INVAL);
3796 		}
3797 	}
3798 
3799 	/* Get the scheduling class set in the zone configuration. */
3800 	if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
3801 	    strlen(sched) > 0) {
3802 		if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
3803 		    strlen(sched)) == -1)
3804 			zerror(zlogp, B_TRUE, "WARNING: unable to set the "
3805 			    "default scheduling class");
3806 
3807 	} else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
3808 	    == Z_OK) {
3809 		/*
3810 		 * If the zone has the zone.cpu-shares rctl set then we want to
3811 		 * use the Fair Share Scheduler (FSS) for processes in the
3812 		 * zone.  Check what scheduling class the zone would be running
3813 		 * in by default so we can print a warning and modify the class
3814 		 * if we wouldn't be using FSS.
3815 		 */
3816 		char class_name[PC_CLNMSZ];
3817 
3818 		if (zonecfg_get_dflt_sched_class(handle, class_name,
3819 		    sizeof (class_name)) != Z_OK) {
3820 			zerror(zlogp, B_FALSE, "WARNING: unable to determine "
3821 			    "the zone's scheduling class");
3822 
3823 		} else if (strcmp("FSS", class_name) != 0) {
3824 			zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
3825 			    "rctl is set but\nFSS is not the default "
3826 			    "scheduling class for\nthis zone.  FSS will be "
3827 			    "used for processes\nin the zone but to get the "
3828 			    "full benefit of FSS,\nit should be the default "
3829 			    "scheduling class.\nSee dispadmin(1M) for more "
3830 			    "details.");
3831 
3832 			if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
3833 			    strlen("FSS")) == -1)
3834 				zerror(zlogp, B_TRUE, "WARNING: unable to set "
3835 				    "zone scheduling class to FSS");
3836 		}
3837 	}
3838 
3839 	/*
3840 	 * The next few blocks of code attempt to set up temporary pools as
3841 	 * well as persistent pools.  In all cases we call the functions
3842 	 * unconditionally.  Within each funtion the code will check if the
3843 	 * zone is actually configured for a temporary pool or persistent pool
3844 	 * and just return if there is nothing to do.
3845 	 *
3846 	 * If we are rebooting we want to attempt to reuse any temporary pool
3847 	 * that was previously set up.  zonecfg_bind_tmp_pool() will do the
3848 	 * right thing in all cases (reuse or create) based on the current
3849 	 * zonecfg.
3850 	 */
3851 	if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
3852 	    sizeof (pool_err))) != Z_OK) {
3853 		if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
3854 			zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
3855 			    "cannot be instantiated", zonecfg_strerror(res),
3856 			    pool_err);
3857 		else
3858 			zerror(zlogp, B_FALSE, "could not bind zone to "
3859 			    "temporary pool: %s", zonecfg_strerror(res));
3860 		zonecfg_fini_handle(handle);
3861 		return (Z_POOL_BIND);
3862 	}
3863 
3864 	/*
3865 	 * Check if we need to warn about poold not being enabled.
3866 	 */
3867 	if (zonecfg_warn_poold(handle)) {
3868 		zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
3869 		    "been specified\nbut the dynamic pool service is not "
3870 		    "enabled.\nThe system will not dynamically adjust the\n"
3871 		    "processor allocation within the specified range\n"
3872 		    "until svc:/system/pools/dynamic is enabled.\n"
3873 		    "See poold(1M).");
3874 	}
3875 
3876 	/* The following is a warning, not an error. */
3877 	if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
3878 	    sizeof (pool_err))) != Z_OK) {
3879 		if (res == Z_POOL_BIND)
3880 			zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
3881 			    "pool '%s'; using default pool.", pool_err);
3882 		else if (res == Z_POOL)
3883 			zerror(zlogp, B_FALSE, "WARNING: %s: %s",
3884 			    zonecfg_strerror(res), pool_err);
3885 		else
3886 			zerror(zlogp, B_FALSE, "WARNING: %s",
3887 			    zonecfg_strerror(res));
3888 	}
3889 
3890 	zonecfg_fini_handle(handle);
3891 	return (Z_OK);
3892 }
3893 
3894 /*
3895  * Sets the hostid of the new zone based on its configured value.  The zone's
3896  * zone_t structure must already exist in kernel memory.  'zlogp' refers to the
3897  * log used to report errors and warnings and must be non-NULL.  'zone_namep'
3898  * is the name of the new zone and must be non-NULL.  'zoneid' is the numeric
3899  * ID of the new zone.
3900  *
3901  * This function returns zero on success and a nonzero error code on failure.
3902  */
3903 static int
3904 setup_zone_hostid(zlog_t *zlogp, char *zone_namep, zoneid_t zoneid)
3905 {
3906 	int res;
3907 	zone_dochandle_t handle;
3908 	char hostidp[HW_HOSTID_LEN];
3909 	unsigned int hostid;
3910 
3911 	if ((handle = zonecfg_init_handle()) == NULL) {
3912 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3913 		return (Z_BAD_HANDLE);
3914 	}
3915 	if ((res = zonecfg_get_snapshot_handle(zone_namep, handle)) != Z_OK) {
3916 		zerror(zlogp, B_FALSE, "invalid configuration");
3917 		zonecfg_fini_handle(handle);
3918 		return (res);
3919 	}
3920 
3921 	if ((res = zonecfg_get_hostid(handle, hostidp, sizeof (hostidp))) ==
3922 	    Z_OK) {
3923 		if (zonecfg_valid_hostid(hostidp) != Z_OK) {
3924 			zerror(zlogp, B_FALSE,
3925 			    "zone hostid is not valid: %s", hostidp);
3926 			zonecfg_fini_handle(handle);
3927 			return (Z_HOSTID_FUBAR);
3928 		}
3929 		hostid = (unsigned int)strtoul(hostidp, NULL, 16);
3930 		if (zone_setattr(zoneid, ZONE_ATTR_HOSTID, &hostid,
3931 		    sizeof (hostid)) != 0) {
3932 			zerror(zlogp, B_TRUE,
3933 			    "zone hostid is not valid: %s", hostidp);
3934 			zonecfg_fini_handle(handle);
3935 			return (Z_SYSTEM);
3936 		}
3937 	} else if (res != Z_BAD_PROPERTY) {
3938 		/*
3939 		 * Z_BAD_PROPERTY is an acceptable error value (from
3940 		 * zonecfg_get_hostid()) because it indicates that the zone
3941 		 * doesn't have a hostid.
3942 		 */
3943 		if (res == Z_TOO_BIG)
3944 			zerror(zlogp, B_FALSE, "hostid string in zone "
3945 			    "configuration is too large.");
3946 		else
3947 			zerror(zlogp, B_TRUE, "fetching zone hostid from "
3948 			    "configuration");
3949 		zonecfg_fini_handle(handle);
3950 		return (res);
3951 	}
3952 
3953 	zonecfg_fini_handle(handle);
3954 	return (Z_OK);
3955 }
3956 
3957 zoneid_t
3958 vplat_create(zlog_t *zlogp, zone_mnt_t mount_cmd)
3959 {
3960 	zoneid_t rval = -1;
3961 	priv_set_t *privs;
3962 	char rootpath[MAXPATHLEN];
3963 	char *rctlbuf = NULL;
3964 	size_t rctlbufsz = 0;
3965 	char *zfsbuf = NULL;
3966 	size_t zfsbufsz = 0;
3967 	zoneid_t zoneid = -1;
3968 	int xerr;
3969 	char *kzone;
3970 	FILE *fp = NULL;
3971 	tsol_zcent_t *zcent = NULL;
3972 	int match = 0;
3973 	int doi = 0;
3974 	int flags;
3975 	zone_iptype_t iptype;
3976 
3977 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
3978 		zerror(zlogp, B_TRUE, "unable to determine zone root");
3979 		return (-1);
3980 	}
3981 	if (zonecfg_in_alt_root())
3982 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
3983 
3984 	if (vplat_get_iptype(zlogp, &iptype) < 0) {
3985 		zerror(zlogp, B_TRUE, "unable to determine ip-type");
3986 		return (-1);
3987 	}
3988 	switch (iptype) {
3989 	case ZS_SHARED:
3990 		flags = 0;
3991 		break;
3992 	case ZS_EXCLUSIVE:
3993 		flags = ZCF_NET_EXCL;
3994 		break;
3995 	}
3996 
3997 	if ((privs = priv_allocset()) == NULL) {
3998 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3999 		return (-1);
4000 	}
4001 	priv_emptyset(privs);
4002 	if (get_privset(zlogp, privs, mount_cmd) != 0)
4003 		goto error;
4004 
4005 	if (mount_cmd == Z_MNT_BOOT &&
4006 	    get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
4007 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
4008 		goto error;
4009 	}
4010 
4011 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
4012 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
4013 		goto error;
4014 	}
4015 
4016 	if (mount_cmd == Z_MNT_BOOT && is_system_labeled()) {
4017 		zcent = get_zone_label(zlogp, privs);
4018 		if (zcent != NULL) {
4019 			match = zcent->zc_match;
4020 			doi = zcent->zc_doi;
4021 			*zlabel = zcent->zc_label;
4022 		} else {
4023 			goto error;
4024 		}
4025 	}
4026 
4027 	kzone = zone_name;
4028 
4029 	/*
4030 	 * We must do this scan twice.  First, we look for zones running on the
4031 	 * main system that are using this root (or any subdirectory of it).
4032 	 * Next, we reduce to the shortest path and search for loopback mounts
4033 	 * that use this same source node (same device and inode).
4034 	 */
4035 	if (duplicate_zone_root(zlogp, rootpath))
4036 		goto error;
4037 	if (duplicate_reachable_path(zlogp, rootpath))
4038 		goto error;
4039 
4040 	if (ALT_MOUNT(mount_cmd)) {
4041 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
4042 
4043 		/*
4044 		 * Forge up a special root for this zone.  When a zone is
4045 		 * mounted, we can't let the zone have its own root because the
4046 		 * tools that will be used in this "scratch zone" need access
4047 		 * to both the zone's resources and the running machine's
4048 		 * executables.
4049 		 *
4050 		 * Note that the mkdir here also catches read-only filesystems.
4051 		 */
4052 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
4053 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
4054 			goto error;
4055 		}
4056 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
4057 			goto error;
4058 	}
4059 
4060 	if (zonecfg_in_alt_root()) {
4061 		/*
4062 		 * If we are mounting up a zone in an alternate root partition,
4063 		 * then we have some additional work to do before starting the
4064 		 * zone.  First, resolve the root path down so that we're not
4065 		 * fooled by duplicates.  Then forge up an internal name for
4066 		 * the zone.
4067 		 */
4068 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4069 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4070 			goto error;
4071 		}
4072 		if (zonecfg_lock_scratch(fp) != 0) {
4073 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4074 			goto error;
4075 		}
4076 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4077 		    NULL, 0) == 0) {
4078 			zerror(zlogp, B_FALSE, "scratch zone already running");
4079 			goto error;
4080 		}
4081 		/* This is the preferred name */
4082 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4083 		    zone_name);
4084 		srandom(getpid());
4085 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4086 		    0) == 0) {
4087 			/* This is just an arbitrary name; note "." usage */
4088 			(void) snprintf(kernzone, sizeof (kernzone),
4089 			    "SUNWlu.%08lX%08lX", random(), random());
4090 		}
4091 		kzone = kernzone;
4092 	}
4093 
4094 	xerr = 0;
4095 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4096 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel,
4097 	    flags)) == -1) {
4098 		if (xerr == ZE_AREMOUNTS) {
4099 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4100 				zerror(zlogp, B_FALSE,
4101 				    "An unknown file-system is mounted on "
4102 				    "a subdirectory of %s", rootpath);
4103 			} else {
4104 
4105 				zerror(zlogp, B_FALSE,
4106 				    "These file-systems are mounted on "
4107 				    "subdirectories of %s:", rootpath);
4108 				(void) zonecfg_find_mounts(rootpath,
4109 				    prtmount, zlogp);
4110 			}
4111 		} else if (xerr == ZE_CHROOTED) {
4112 			zerror(zlogp, B_FALSE, "%s: "
4113 			    "cannot create a zone from a chrooted "
4114 			    "environment", "zone_create");
4115 		} else if (xerr == ZE_LABELINUSE) {
4116 			char zonename[ZONENAME_MAX];
4117 			(void) getzonenamebyid(getzoneidbylabel(zlabel),
4118 			    zonename, ZONENAME_MAX);
4119 			zerror(zlogp, B_FALSE, "The zone label is already "
4120 			    "used by the zone '%s'.", zonename);
4121 		} else {
4122 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4123 		}
4124 		goto error;
4125 	}
4126 
4127 	if (zonecfg_in_alt_root() &&
4128 	    zonecfg_add_scratch(fp, zone_name, kernzone,
4129 	    zonecfg_get_root()) == -1) {
4130 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4131 		goto error;
4132 	}
4133 
4134 	/*
4135 	 * The following actions are not performed when merely mounting a zone
4136 	 * for administrative use.
4137 	 */
4138 	if (mount_cmd == Z_MNT_BOOT) {
4139 		brand_handle_t bh;
4140 		struct brand_attr attr;
4141 		char modname[MAXPATHLEN];
4142 
4143 		if (setup_zone_hostid(zlogp, zone_name, zoneid) != Z_OK)
4144 			goto error;
4145 
4146 		if ((zone_get_brand(zone_name, attr.ba_brandname,
4147 		    MAXNAMELEN) != Z_OK) ||
4148 		    (bh = brand_open(attr.ba_brandname)) == NULL) {
4149 			zerror(zlogp, B_FALSE,
4150 			    "unable to determine brand name");
4151 			goto error;
4152 		}
4153 
4154 		if (!is_system_labeled() &&
4155 		    (strcmp(attr.ba_brandname, LABELED_BRAND_NAME) == 0)) {
4156 			brand_close(bh);
4157 			zerror(zlogp, B_FALSE,
4158 			    "cannot boot labeled zone on unlabeled system");
4159 			goto error;
4160 		}
4161 
4162 		/*
4163 		 * If this brand requires any kernel support, now is the time to
4164 		 * get it loaded and initialized.
4165 		 */
4166 		if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4167 			brand_close(bh);
4168 			zerror(zlogp, B_FALSE,
4169 			    "unable to determine brand kernel module");
4170 			goto error;
4171 		}
4172 		brand_close(bh);
4173 
4174 		if (strlen(modname) > 0) {
4175 			(void) strlcpy(attr.ba_modname, modname, MAXPATHLEN);
4176 			if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4177 			    sizeof (attr) != 0)) {
4178 				zerror(zlogp, B_TRUE,
4179 				    "could not set zone brand attribute.");
4180 				goto error;
4181 			}
4182 		}
4183 
4184 		if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK)
4185 			goto error;
4186 
4187 		set_mlps(zlogp, zoneid, zcent);
4188 	}
4189 
4190 	rval = zoneid;
4191 	zoneid = -1;
4192 
4193 error:
4194 	if (zoneid != -1) {
4195 		(void) zone_shutdown(zoneid);
4196 		(void) zone_destroy(zoneid);
4197 	}
4198 	if (rctlbuf != NULL)
4199 		free(rctlbuf);
4200 	priv_freeset(privs);
4201 	if (fp != NULL)
4202 		zonecfg_close_scratch(fp);
4203 	lofs_discard_mnttab();
4204 	if (zcent != NULL)
4205 		tsol_freezcent(zcent);
4206 	return (rval);
4207 }
4208 
4209 /*
4210  * Enter the zone and write a /etc/zones/index file there.  This allows
4211  * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
4212  * details from inside the zone.
4213  */
4214 static void
4215 write_index_file(zoneid_t zoneid)
4216 {
4217 	FILE *zef;
4218 	FILE *zet;
4219 	struct zoneent *zep;
4220 	pid_t child;
4221 	int tmpl_fd;
4222 	ctid_t ct;
4223 	int fd;
4224 	char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
4225 
4226 	/* Locate the zone entry in the global zone's index file */
4227 	if ((zef = setzoneent()) == NULL)
4228 		return;
4229 	while ((zep = getzoneent_private(zef)) != NULL) {
4230 		if (strcmp(zep->zone_name, zone_name) == 0)
4231 			break;
4232 		free(zep);
4233 	}
4234 	endzoneent(zef);
4235 	if (zep == NULL)
4236 		return;
4237 
4238 	if ((tmpl_fd = init_template()) == -1) {
4239 		free(zep);
4240 		return;
4241 	}
4242 
4243 	if ((child = fork()) == -1) {
4244 		(void) ct_tmpl_clear(tmpl_fd);
4245 		(void) close(tmpl_fd);
4246 		free(zep);
4247 		return;
4248 	}
4249 
4250 	/* parent waits for child to finish */
4251 	if (child != 0) {
4252 		free(zep);
4253 		if (contract_latest(&ct) == -1)
4254 			ct = -1;
4255 		(void) ct_tmpl_clear(tmpl_fd);
4256 		(void) close(tmpl_fd);
4257 		(void) waitpid(child, NULL, 0);
4258 		(void) contract_abandon_id(ct);
4259 		return;
4260 	}
4261 
4262 	/* child enters zone and sets up index file */
4263 	(void) ct_tmpl_clear(tmpl_fd);
4264 	if (zone_enter(zoneid) != -1) {
4265 		(void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
4266 		(void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
4267 		    ZONE_CONFIG_GID);
4268 		fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
4269 		    ZONE_INDEX_MODE);
4270 		if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
4271 			(void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
4272 			if (uuid_is_null(zep->zone_uuid))
4273 				uuidstr[0] = '\0';
4274 			else
4275 				uuid_unparse(zep->zone_uuid, uuidstr);
4276 			(void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
4277 			    zone_state_str(zep->zone_state),
4278 			    uuidstr);
4279 			(void) fclose(zet);
4280 		}
4281 	}
4282 	_exit(0);
4283 }
4284 
4285 int
4286 vplat_bringup(zlog_t *zlogp, zone_mnt_t mount_cmd, zoneid_t zoneid)
4287 {
4288 	char zonepath[MAXPATHLEN];
4289 
4290 	if (mount_cmd == Z_MNT_BOOT && validate_datasets(zlogp) != 0) {
4291 		lofs_discard_mnttab();
4292 		return (-1);
4293 	}
4294 
4295 	/*
4296 	 * Before we try to mount filesystems we need to create the
4297 	 * attribute backing store for /dev
4298 	 */
4299 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
4300 		lofs_discard_mnttab();
4301 		return (-1);
4302 	}
4303 	resolve_lofs(zlogp, zonepath, sizeof (zonepath));
4304 
4305 	/* Make /dev directory owned by root, grouped sys */
4306 	if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE,
4307 	    0, 3) != 0) {
4308 		lofs_discard_mnttab();
4309 		return (-1);
4310 	}
4311 
4312 	if (mount_filesystems(zlogp, mount_cmd) != 0) {
4313 		lofs_discard_mnttab();
4314 		return (-1);
4315 	}
4316 
4317 	if (mount_cmd == Z_MNT_BOOT) {
4318 		zone_iptype_t iptype;
4319 
4320 		if (vplat_get_iptype(zlogp, &iptype) < 0) {
4321 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
4322 			lofs_discard_mnttab();
4323 			return (-1);
4324 		}
4325 
4326 		switch (iptype) {
4327 		case ZS_SHARED:
4328 			/* Always do this to make lo0 get configured */
4329 			if (configure_shared_network_interfaces(zlogp) != 0) {
4330 				lofs_discard_mnttab();
4331 				return (-1);
4332 			}
4333 			break;
4334 		case ZS_EXCLUSIVE:
4335 			if (configure_exclusive_network_interfaces(zlogp) !=
4336 			    0) {
4337 				lofs_discard_mnttab();
4338 				return (-1);
4339 			}
4340 			break;
4341 		}
4342 	}
4343 
4344 	write_index_file(zoneid);
4345 
4346 	lofs_discard_mnttab();
4347 	return (0);
4348 }
4349 
4350 static int
4351 lu_root_teardown(zlog_t *zlogp)
4352 {
4353 	char zroot[MAXPATHLEN];
4354 
4355 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4356 		zerror(zlogp, B_FALSE, "unable to determine zone root");
4357 		return (-1);
4358 	}
4359 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
4360 
4361 	/*
4362 	 * At this point, the processes are gone, the filesystems (save the
4363 	 * root) are unmounted, and the zone is on death row.  But there may
4364 	 * still be creds floating about in the system that reference the
4365 	 * zone_t, and which pin down zone_rootvp causing this call to fail
4366 	 * with EBUSY.  Thus, we try for a little while before just giving up.
4367 	 * (How I wish this were not true, and umount2 just did the right
4368 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
4369 	 */
4370 	if (umount2(zroot, MS_FORCE) != 0) {
4371 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
4372 			goto unmounted;
4373 		if (errno == EBUSY) {
4374 			int tries = 10;
4375 
4376 			while (--tries >= 0) {
4377 				(void) sleep(1);
4378 				if (umount2(zroot, 0) == 0)
4379 					goto unmounted;
4380 				if (errno != EBUSY)
4381 					break;
4382 			}
4383 		}
4384 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
4385 		return (-1);
4386 	}
4387 unmounted:
4388 
4389 	/*
4390 	 * Only zones in an alternate root environment have scratch zone
4391 	 * entries.
4392 	 */
4393 	if (zonecfg_in_alt_root()) {
4394 		FILE *fp;
4395 		int retv;
4396 
4397 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4398 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4399 			return (-1);
4400 		}
4401 		retv = -1;
4402 		if (zonecfg_lock_scratch(fp) != 0)
4403 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4404 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
4405 			zerror(zlogp, B_TRUE, "cannot delete map entry");
4406 		else
4407 			retv = 0;
4408 		zonecfg_close_scratch(fp);
4409 		return (retv);
4410 	} else {
4411 		return (0);
4412 	}
4413 }
4414 
4415 int
4416 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
4417 {
4418 	char *kzone;
4419 	zoneid_t zoneid;
4420 	int res;
4421 	char pool_err[128];
4422 	char zpath[MAXPATHLEN];
4423 	char cmdbuf[MAXPATHLEN];
4424 	char brand[MAXNAMELEN];
4425 	brand_handle_t bh = NULL;
4426 	dladm_status_t status;
4427 	char errmsg[DLADM_STRSIZE];
4428 	ushort_t flags;
4429 
4430 	kzone = zone_name;
4431 	if (zonecfg_in_alt_root()) {
4432 		FILE *fp;
4433 
4434 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4435 			zerror(zlogp, B_TRUE, "unable to open map file");
4436 			goto error;
4437 		}
4438 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4439 		    kernzone, sizeof (kernzone)) != 0) {
4440 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
4441 			zonecfg_close_scratch(fp);
4442 			goto error;
4443 		}
4444 		zonecfg_close_scratch(fp);
4445 		kzone = kernzone;
4446 	}
4447 
4448 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
4449 		if (!bringup_failure_recovery)
4450 			zerror(zlogp, B_TRUE, "unable to get zoneid");
4451 		if (unmount_cmd)
4452 			(void) lu_root_teardown(zlogp);
4453 		goto error;
4454 	}
4455 
4456 	if (zone_shutdown(zoneid) != 0) {
4457 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
4458 		goto error;
4459 	}
4460 
4461 	/* Get the zonepath of this zone */
4462 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
4463 		zerror(zlogp, B_FALSE, "unable to determine zone path");
4464 		goto error;
4465 	}
4466 
4467 	/* Get a handle to the brand info for this zone */
4468 	if ((zone_get_brand(zone_name, brand, sizeof (brand)) != Z_OK) ||
4469 	    (bh = brand_open(brand)) == NULL) {
4470 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
4471 		return (-1);
4472 	}
4473 	/*
4474 	 * If there is a brand 'halt' callback, execute it now to give the
4475 	 * brand a chance to cleanup any custom configuration.
4476 	 */
4477 	(void) strcpy(cmdbuf, EXEC_PREFIX);
4478 	if (brand_get_halt(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
4479 	    sizeof (cmdbuf) - EXEC_LEN) < 0) {
4480 		brand_close(bh);
4481 		zerror(zlogp, B_FALSE, "unable to determine branded zone's "
4482 		    "halt callback.");
4483 		goto error;
4484 	}
4485 	brand_close(bh);
4486 
4487 	if ((strlen(cmdbuf) > EXEC_LEN) &&
4488 	    (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
4489 		zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
4490 		goto error;
4491 	}
4492 
4493 	if (!unmount_cmd) {
4494 		zone_iptype_t iptype;
4495 
4496 		if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
4497 		    sizeof (flags)) < 0) {
4498 			if (vplat_get_iptype(zlogp, &iptype) < 0) {
4499 				zerror(zlogp, B_TRUE, "unable to determine "
4500 				    "ip-type");
4501 				goto error;
4502 			}
4503 		} else {
4504 			if (flags & ZF_NET_EXCL)
4505 				iptype = ZS_EXCLUSIVE;
4506 			else
4507 				iptype = ZS_SHARED;
4508 		}
4509 
4510 		switch (iptype) {
4511 		case ZS_SHARED:
4512 			if (unconfigure_shared_network_interfaces(zlogp,
4513 			    zoneid) != 0) {
4514 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4515 				    "network interfaces in zone");
4516 				goto error;
4517 			}
4518 			break;
4519 		case ZS_EXCLUSIVE:
4520 			if (unconfigure_exclusive_network_interfaces(zlogp,
4521 			    zoneid) != 0) {
4522 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4523 				    "network interfaces in zone");
4524 				goto error;
4525 			}
4526 			status = dladm_zone_halt(dld_handle, zoneid);
4527 			if (status != DLADM_STATUS_OK) {
4528 				zerror(zlogp, B_FALSE, "unable to notify "
4529 				    "dlmgmtd of zone halt: %s",
4530 				    dladm_status2str(status, errmsg));
4531 			}
4532 			break;
4533 		}
4534 	}
4535 
4536 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
4537 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
4538 		goto error;
4539 	}
4540 
4541 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
4542 		zerror(zlogp, B_FALSE,
4543 		    "unable to unmount file systems in zone");
4544 		goto error;
4545 	}
4546 
4547 	/*
4548 	 * If we are rebooting then we normally don't want to destroy an
4549 	 * existing temporary pool at this point so that we can just reuse it
4550 	 * when the zone boots back up.  However, it is also possible we were
4551 	 * running with a temporary pool and the zone configuration has been
4552 	 * modified to no longer use a temporary pool.  In that case we need
4553 	 * to destroy the temporary pool now.  This case looks like the case
4554 	 * where we never had a temporary pool configured but
4555 	 * zonecfg_destroy_tmp_pool will do the right thing either way.
4556 	 */
4557 	if (!unmount_cmd) {
4558 		boolean_t destroy_tmp_pool = B_TRUE;
4559 
4560 		if (rebooting) {
4561 			struct zone_psettab pset_tab;
4562 			zone_dochandle_t handle;
4563 
4564 			if ((handle = zonecfg_init_handle()) != NULL &&
4565 			    zonecfg_get_handle(zone_name, handle) == Z_OK &&
4566 			    zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
4567 				destroy_tmp_pool = B_FALSE;
4568 
4569 			zonecfg_fini_handle(handle);
4570 		}
4571 
4572 		if (destroy_tmp_pool) {
4573 			if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
4574 			    sizeof (pool_err))) != Z_OK) {
4575 				if (res == Z_POOL)
4576 					zerror(zlogp, B_FALSE, pool_err);
4577 			}
4578 		}
4579 	}
4580 
4581 	remove_mlps(zlogp, zoneid);
4582 
4583 	if (zone_destroy(zoneid) != 0) {
4584 		zerror(zlogp, B_TRUE, "unable to destroy zone");
4585 		goto error;
4586 	}
4587 
4588 	/*
4589 	 * Special teardown for alternate boot environments: remove the tmpfs
4590 	 * root for the zone and then remove it from the map file.
4591 	 */
4592 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
4593 		goto error;
4594 
4595 	lofs_discard_mnttab();
4596 	return (0);
4597 
4598 error:
4599 	lofs_discard_mnttab();
4600 	return (-1);
4601 }
4602