xref: /titanic_44/usr/src/cmd/zoneadmd/vplat.c (revision ffbafc5382b8d46def826aec8c419ad31dff8ebd)
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 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * This module contains functions used to bring up and tear down the
31  * Virtual Platform: [un]mounting file-systems, [un]plumbing network
32  * interfaces, [un]configuring devices, establishing resource controls,
33  * and creating/destroying the zone in the kernel.  These actions, on
34  * the way up, ready the zone; on the way down, they halt the zone.
35  * See the much longer block comment at the beginning of zoneadmd.c
36  * for a bigger picture of how the whole program functions.
37  *
38  * This module also has primary responsibility for the layout of "scratch
39  * zones."  These are mounted, but inactive, zones that are used during
40  * operating system upgrade and potentially other administrative action.  The
41  * scratch zone environment is similar to the miniroot environment.  The zone's
42  * actual root is mounted read-write on /a, and the standard paths (/usr,
43  * /sbin, /lib) all lead to read-only copies of the running system's binaries.
44  * This allows the administrative tools to manipulate the zone using "-R /a"
45  * without relying on any binaries in the zone itself.
46  *
47  * If the scratch zone is on an alternate root (Live Upgrade [LU] boot
48  * environment), then we must resolve the lofs mounts used there to uncover
49  * writable (unshared) resources.  Shared resources, though, are always
50  * read-only.  In addition, if the "same" zone with a different root path is
51  * currently running, then "/b" inside the zone points to the running zone's
52  * root.  This allows LU to synchronize configuration files during the upgrade
53  * process.
54  *
55  * To construct this environment, this module creates a tmpfs mount on
56  * $ZONEPATH/lu.  Inside this scratch area, the miniroot-like environment as
57  * described above is constructed on the fly.  The zone is then created using
58  * $ZONEPATH/lu as the root.
59  *
60  * Note that scratch zones are inactive.  The zone's bits are not running and
61  * likely cannot be run correctly until upgrade is done.  Init is not running
62  * there, nor is SMF.  Because of this, the "mounted" state of a scratch zone
63  * is not a part of the usual halt/ready/boot state machine.
64  */
65 
66 #include <sys/param.h>
67 #include <sys/mount.h>
68 #include <sys/mntent.h>
69 #include <sys/socket.h>
70 #include <sys/utsname.h>
71 #include <sys/types.h>
72 #include <sys/stat.h>
73 #include <sys/sockio.h>
74 #include <sys/stropts.h>
75 #include <sys/conf.h>
76 
77 #include <inet/tcp.h>
78 #include <arpa/inet.h>
79 #include <netinet/in.h>
80 #include <net/route.h>
81 #include <netdb.h>
82 
83 #include <stdio.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <unistd.h>
87 #include <rctl.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <strings.h>
91 #include <wait.h>
92 #include <limits.h>
93 #include <libgen.h>
94 #include <libzfs.h>
95 #include <zone.h>
96 #include <assert.h>
97 
98 #include <sys/mntio.h>
99 #include <sys/mnttab.h>
100 #include <sys/fs/autofs.h>	/* for _autofssys() */
101 #include <sys/fs/lofs_info.h>
102 #include <sys/fs/zfs.h>
103 
104 #include <pool.h>
105 #include <sys/pool.h>
106 
107 #include <libzonecfg.h>
108 #include "zoneadmd.h"
109 
110 #define	V4_ADDR_LEN	32
111 #define	V6_ADDR_LEN	128
112 
113 /* 0755 is the default directory mode. */
114 #define	DEFAULT_DIR_MODE \
115 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
116 
117 #define	IPD_DEFAULT_OPTS \
118 	MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
119 
120 #define	DFSTYPES	"/etc/dfs/fstypes"
121 
122 /*
123  * A list of directories which should be created.
124  */
125 
126 struct dir_info {
127 	char *dir_name;
128 	mode_t dir_mode;
129 };
130 
131 /*
132  * The pathnames below are relative to the zonepath
133  */
134 static struct dir_info dev_dirs[] = {
135 	{ "/dev",	0755 },
136 	{ "/dev/dsk",	0755 },
137 	{ "/dev/fd",	0555 },
138 	{ "/dev/pts",	0755 },
139 	{ "/dev/rdsk",	0755 },
140 	{ "/dev/rmt",	0755 },
141 	{ "/dev/sad",	0755 },
142 	{ "/dev/swap",	0755 },
143 	{ "/dev/term",	0755 },
144 };
145 
146 /*
147  * A list of devices which should be symlinked to /dev/zconsole.
148  */
149 
150 struct symlink_info {
151 	char *sl_source;
152 	char *sl_target;
153 };
154 
155 /*
156  * The "source" paths are relative to the zonepath
157  */
158 static struct symlink_info dev_symlinks[] = {
159 	{ "/dev/stderr",	"./fd/2" },
160 	{ "/dev/stdin",		"./fd/0" },
161 	{ "/dev/stdout",	"./fd/1" },
162 	{ "/dev/dtremote",	"/dev/null" },
163 	{ "/dev/console",	"zconsole" },
164 	{ "/dev/syscon",	"zconsole" },
165 	{ "/dev/sysmsg",	"zconsole" },
166 	{ "/dev/systty",	"zconsole" },
167 	{ "/dev/msglog",	"zconsole" },
168 };
169 
170 /* for routing socket */
171 static int rts_seqno = 0;
172 
173 /* mangled zone name when mounting in an alternate root environment */
174 static char kernzone[ZONENAME_MAX];
175 
176 /* array of cached mount entries for resolve_lofs */
177 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
178 
179 /* from libsocket, not in any header file */
180 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
181 
182 /*
183  * An optimization for build_mnttable: reallocate (and potentially copy the
184  * data) only once every N times through the loop.
185  */
186 #define	MNTTAB_HUNK	32
187 
188 /*
189  * Private autofs system call
190  */
191 extern int _autofssys(int, void *);
192 
193 static int
194 autofs_cleanup(zoneid_t zoneid)
195 {
196 	/*
197 	 * Ask autofs to unmount all trigger nodes in the given zone.
198 	 */
199 	return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
200 }
201 
202 static void
203 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
204 {
205 	uint_t i;
206 
207 	if (mnt_array == NULL)
208 		return;
209 	for (i = 0; i < nelem; i++) {
210 		free(mnt_array[i].mnt_mountp);
211 		free(mnt_array[i].mnt_fstype);
212 		free(mnt_array[i].mnt_special);
213 		free(mnt_array[i].mnt_mntopts);
214 		assert(mnt_array[i].mnt_time == NULL);
215 	}
216 	free(mnt_array);
217 }
218 
219 /*
220  * Build the mount table for the zone rooted at "zroot", storing the resulting
221  * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
222  * array in "nelemp".
223  */
224 static int
225 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
226     struct mnttab **mnt_arrayp, uint_t *nelemp)
227 {
228 	struct mnttab mnt;
229 	struct mnttab *mnts;
230 	struct mnttab *mnp;
231 	uint_t nmnt;
232 
233 	rewind(mnttab);
234 	resetmnttab(mnttab);
235 	nmnt = 0;
236 	mnts = NULL;
237 	while (getmntent(mnttab, &mnt) == 0) {
238 		struct mnttab *tmp_array;
239 
240 		if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
241 			continue;
242 		if (nmnt % MNTTAB_HUNK == 0) {
243 			tmp_array = realloc(mnts,
244 			    (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
245 			if (tmp_array == NULL) {
246 				free_mnttable(mnts, nmnt);
247 				return (-1);
248 			}
249 			mnts = tmp_array;
250 		}
251 		mnp = &mnts[nmnt++];
252 
253 		/*
254 		 * Zero out any fields we're not using.
255 		 */
256 		(void) memset(mnp, 0, sizeof (*mnp));
257 
258 		if (mnt.mnt_special != NULL)
259 			mnp->mnt_special = strdup(mnt.mnt_special);
260 		if (mnt.mnt_mntopts != NULL)
261 			mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
262 		mnp->mnt_mountp = strdup(mnt.mnt_mountp);
263 		mnp->mnt_fstype = strdup(mnt.mnt_fstype);
264 		if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
265 		    (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
266 		    mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
267 			zerror(zlogp, B_TRUE, "memory allocation failed");
268 			free_mnttable(mnts, nmnt);
269 			return (-1);
270 		}
271 	}
272 	*mnt_arrayp = mnts;
273 	*nelemp = nmnt;
274 	return (0);
275 }
276 
277 /*
278  * This is an optimization.  The resolve_lofs function is used quite frequently
279  * to manipulate file paths, and on a machine with a large number of zones,
280  * there will be a huge number of mounted file systems.  Thus, we trigger a
281  * reread of the list of mount points
282  */
283 static void
284 lofs_discard_mnttab(void)
285 {
286 	free_mnttable(resolve_lofs_mnts,
287 	    resolve_lofs_mnt_max - resolve_lofs_mnts);
288 	resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
289 }
290 
291 static int
292 lofs_read_mnttab(zlog_t *zlogp)
293 {
294 	FILE *mnttab;
295 	uint_t nmnts;
296 
297 	if ((mnttab = fopen(MNTTAB, "r")) == NULL)
298 		return (-1);
299 	if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
300 	    &nmnts) == -1) {
301 		(void) fclose(mnttab);
302 		return (-1);
303 	}
304 	(void) fclose(mnttab);
305 	resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
306 	return (0);
307 }
308 
309 /*
310  * This function loops over potential loopback mounts and symlinks in a given
311  * path and resolves them all down to an absolute path.
312  */
313 static void
314 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
315 {
316 	int len, arlen;
317 	const char *altroot;
318 	char tmppath[MAXPATHLEN];
319 	boolean_t outside_altroot;
320 
321 	if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
322 		return;
323 	tmppath[len] = '\0';
324 	(void) strlcpy(path, tmppath, sizeof (tmppath));
325 
326 	/* This happens once per zoneadmd operation. */
327 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
328 		return;
329 
330 	altroot = zonecfg_get_root();
331 	arlen = strlen(altroot);
332 	outside_altroot = B_FALSE;
333 	for (;;) {
334 		struct mnttab *mnp;
335 
336 		for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
337 		    mnp++) {
338 			if (mnp->mnt_fstype == NULL ||
339 			    mnp->mnt_mountp == NULL ||
340 			    mnp->mnt_special == NULL ||
341 			    strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
342 				continue;
343 			len = strlen(mnp->mnt_mountp);
344 			if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
345 			    (path[len] == '/' || path[len] == '\0'))
346 				break;
347 		}
348 		if (mnp >= resolve_lofs_mnt_max)
349 			break;
350 		if (outside_altroot) {
351 			char *cp;
352 			int olen = sizeof (MNTOPT_RO) - 1;
353 
354 			/*
355 			 * If we run into a read-only mount outside of the
356 			 * alternate root environment, then the user doesn't
357 			 * want this path to be made read-write.
358 			 */
359 			if (mnp->mnt_mntopts != NULL &&
360 			    (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
361 			    NULL &&
362 			    (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
363 			    (cp[olen] == '\0' || cp[olen] == ',')) {
364 				break;
365 			}
366 		} else if (arlen > 0 &&
367 		    (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
368 		    (mnp->mnt_special[arlen] != '\0' &&
369 		    mnp->mnt_special[arlen] != '/'))) {
370 			outside_altroot = B_TRUE;
371 		}
372 		/* use temporary buffer because new path might be longer */
373 		(void) snprintf(tmppath, sizeof (tmppath), "%s%s",
374 		    mnp->mnt_special, path + len);
375 		if ((len = resolvepath(tmppath, path, pathlen)) == -1)
376 			break;
377 		path[len] = '\0';
378 	}
379 }
380 
381 /*
382  * For a regular mount, check if a replacement lofs mount is needed because the
383  * referenced device is already mounted somewhere.
384  */
385 static int
386 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
387 {
388 	struct mnttab *mnp;
389 	zone_fsopt_t *optptr, *onext;
390 
391 	/* This happens once per zoneadmd operation. */
392 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
393 		return (-1);
394 
395 	/*
396 	 * If this special node isn't already in use, then it's ours alone;
397 	 * no need to worry about conflicting mounts.
398 	 */
399 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
400 	    mnp++) {
401 		if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
402 			break;
403 	}
404 	if (mnp >= resolve_lofs_mnt_max)
405 		return (0);
406 
407 	/*
408 	 * Convert this duplicate mount into a lofs mount.
409 	 */
410 	(void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
411 	    sizeof (fsptr->zone_fs_special));
412 	(void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
413 	    sizeof (fsptr->zone_fs_type));
414 	fsptr->zone_fs_raw[0] = '\0';
415 
416 	/*
417 	 * Discard all but one of the original options and set that to be the
418 	 * same set of options used for inherit package directory resources.
419 	 */
420 	optptr = fsptr->zone_fs_options;
421 	if (optptr == NULL) {
422 		optptr = malloc(sizeof (*optptr));
423 		if (optptr == NULL) {
424 			zerror(zlogp, B_TRUE, "cannot mount %s",
425 			    fsptr->zone_fs_dir);
426 			return (-1);
427 		}
428 	} else {
429 		while ((onext = optptr->zone_fsopt_next) != NULL) {
430 			optptr->zone_fsopt_next = onext->zone_fsopt_next;
431 			free(onext);
432 		}
433 	}
434 	(void) strcpy(optptr->zone_fsopt_opt, IPD_DEFAULT_OPTS);
435 	optptr->zone_fsopt_next = NULL;
436 	fsptr->zone_fs_options = optptr;
437 	return (0);
438 }
439 
440 static int
441 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode)
442 {
443 	char path[MAXPATHLEN];
444 	struct stat st;
445 
446 	if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
447 	    sizeof (path)) {
448 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
449 		    subdir);
450 		return (-1);
451 	}
452 
453 	if (lstat(path, &st) == 0) {
454 		/*
455 		 * We don't check the file mode since presumably the zone
456 		 * administrator may have had good reason to change the mode,
457 		 * and we don't need to second guess him.
458 		 */
459 		if (!S_ISDIR(st.st_mode)) {
460 			zerror(zlogp, B_FALSE, "%s is not a directory", path);
461 			return (-1);
462 		}
463 	} else if (mkdirp(path, mode) != 0) {
464 		if (errno == EROFS)
465 			zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
466 			    "a read-only file system in this local zone.\nMake "
467 			    "sure %s exists in the global zone.", path, subdir);
468 		else
469 			zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
470 		return (-1);
471 	}
472 	return (0);
473 }
474 
475 /*
476  * Make /dev and various directories underneath it.
477  */
478 static int
479 make_dev_dirs(zlog_t *zlogp, const char *zonepath)
480 {
481 	int i;
482 
483 	for (i = 0; i < sizeof (dev_dirs) / sizeof (struct dir_info); i++) {
484 		if (make_one_dir(zlogp, zonepath, dev_dirs[i].dir_name,
485 		    dev_dirs[i].dir_mode) != 0)
486 			return (-1);
487 	}
488 	return (0);
489 }
490 
491 /*
492  * Make various sym-links underneath /dev.
493  */
494 static int
495 make_dev_links(zlog_t *zlogp, char *zonepath)
496 {
497 	int i;
498 
499 	for (i = 0; i < sizeof (dev_symlinks) / sizeof (struct symlink_info);
500 	    i++) {
501 		char dev[MAXPATHLEN];
502 		struct stat st;
503 
504 		(void) snprintf(dev, sizeof (dev), "%s%s", zonepath,
505 		    dev_symlinks[i].sl_source);
506 		if (lstat(dev, &st) == 0) {
507 			/*
508 			 * Try not to call unlink(2) on directories, since that
509 			 * makes UFS unhappy.
510 			 */
511 			if (S_ISDIR(st.st_mode)) {
512 				zerror(zlogp, B_FALSE, "symlink path %s is a "
513 				    "directory", dev_symlinks[i].sl_source);
514 				return (-1);
515 			}
516 			(void) unlink(dev);
517 		}
518 		if (symlink(dev_symlinks[i].sl_target, dev) != 0) {
519 			zerror(zlogp, B_TRUE, "could not setup %s->%s symlink",
520 			    dev_symlinks[i].sl_source,
521 			    dev_symlinks[i].sl_target);
522 			return (-1);
523 		}
524 	}
525 	return (0);
526 }
527 
528 /*
529  * Create various directories and sym-links under /dev.
530  */
531 static int
532 create_dev_files(zlog_t *zlogp)
533 {
534 	char zonepath[MAXPATHLEN];
535 
536 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
537 		zerror(zlogp, B_TRUE, "unable to determine zone root");
538 		return (-1);
539 	}
540 	if (zonecfg_in_alt_root())
541 		resolve_lofs(zlogp, zonepath, sizeof (zonepath));
542 
543 	if (make_dev_dirs(zlogp, zonepath) != 0)
544 		return (-1);
545 	if (make_dev_links(zlogp, zonepath) != 0)
546 		return (-1);
547 	return (0);
548 }
549 
550 static void
551 free_remote_fstypes(char **types)
552 {
553 	uint_t i;
554 
555 	if (types == NULL)
556 		return;
557 	for (i = 0; types[i] != NULL; i++)
558 		free(types[i]);
559 	free(types);
560 }
561 
562 static char **
563 get_remote_fstypes(zlog_t *zlogp)
564 {
565 	char **types = NULL;
566 	FILE *fp;
567 	char buf[MAXPATHLEN];
568 	char fstype[MAXPATHLEN];
569 	uint_t lines = 0;
570 	uint_t i;
571 
572 	if ((fp = fopen(DFSTYPES, "r")) == NULL) {
573 		zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
574 		return (NULL);
575 	}
576 	/*
577 	 * Count the number of lines
578 	 */
579 	while (fgets(buf, sizeof (buf), fp) != NULL)
580 		lines++;
581 	if (lines == 0)	/* didn't read anything; empty file */
582 		goto out;
583 	rewind(fp);
584 	/*
585 	 * Allocate enough space for a NULL-terminated array.
586 	 */
587 	types = calloc(lines + 1, sizeof (char *));
588 	if (types == NULL) {
589 		zerror(zlogp, B_TRUE, "memory allocation failed");
590 		goto out;
591 	}
592 	i = 0;
593 	while (fgets(buf, sizeof (buf), fp) != NULL) {
594 		/* LINTED - fstype is big enough to hold buf */
595 		if (sscanf(buf, "%s", fstype) == 0) {
596 			zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
597 			free_remote_fstypes(types);
598 			types = NULL;
599 			goto out;
600 		}
601 		types[i] = strdup(fstype);
602 		if (types[i] == NULL) {
603 			zerror(zlogp, B_TRUE, "memory allocation failed");
604 			free_remote_fstypes(types);
605 			types = NULL;
606 			goto out;
607 		}
608 		i++;
609 	}
610 out:
611 	(void) fclose(fp);
612 	return (types);
613 }
614 
615 static boolean_t
616 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
617 {
618 	uint_t i;
619 
620 	if (remote_fstypes == NULL)
621 		return (B_FALSE);
622 	for (i = 0; remote_fstypes[i] != NULL; i++) {
623 		if (strcmp(remote_fstypes[i], fstype) == 0)
624 			return (B_TRUE);
625 	}
626 	return (B_FALSE);
627 }
628 
629 /*
630  * This converts a zone root path (normally of the form .../root) to a Live
631  * Upgrade scratch zone root (of the form .../lu).
632  */
633 static void
634 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
635 {
636 	if (!isresolved && zonecfg_in_alt_root())
637 		resolve_lofs(zlogp, zroot, zrootlen);
638 	(void) strcpy(strrchr(zroot, '/') + 1, "lu");
639 }
640 
641 /*
642  * The general strategy for unmounting filesystems is as follows:
643  *
644  * - Remote filesystems may be dead, and attempting to contact them as
645  * part of a regular unmount may hang forever; we want to always try to
646  * forcibly unmount such filesystems and only fall back to regular
647  * unmounts if the filesystem doesn't support forced unmounts.
648  *
649  * - We don't want to unnecessarily corrupt metadata on local
650  * filesystems (ie UFS), so we want to start off with graceful unmounts,
651  * and only escalate to doing forced unmounts if we get stuck.
652  *
653  * We start off walking backwards through the mount table.  This doesn't
654  * give us strict ordering but ensures that we try to unmount submounts
655  * first.  We thus limit the number of failed umount2(2) calls.
656  *
657  * The mechanism for determining if we're stuck is to count the number
658  * of failed unmounts each iteration through the mount table.  This
659  * gives us an upper bound on the number of filesystems which remain
660  * mounted (autofs trigger nodes are dealt with separately).  If at the
661  * end of one unmount+autofs_cleanup cycle we still have the same number
662  * of mounts that we started out with, we're stuck and try a forced
663  * unmount.  If that fails (filesystem doesn't support forced unmounts)
664  * then we bail and are unable to teardown the zone.  If it succeeds,
665  * we're no longer stuck so we continue with our policy of trying
666  * graceful mounts first.
667  *
668  * Zone must be down (ie, no processes or threads active).
669  */
670 static int
671 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
672 {
673 	int error = 0;
674 	FILE *mnttab;
675 	struct mnttab *mnts;
676 	uint_t nmnt;
677 	char zroot[MAXPATHLEN + 1];
678 	size_t zrootlen;
679 	uint_t oldcount = UINT_MAX;
680 	boolean_t stuck = B_FALSE;
681 	char **remote_fstypes = NULL;
682 
683 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
684 		zerror(zlogp, B_FALSE, "unable to determine zone root");
685 		return (-1);
686 	}
687 	if (unmount_cmd)
688 		root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
689 
690 	(void) strcat(zroot, "/");
691 	zrootlen = strlen(zroot);
692 
693 	if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
694 		zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
695 		return (-1);
696 	}
697 	/*
698 	 * Use our hacky mntfs ioctl so we see everything, even mounts with
699 	 * MS_NOMNTTAB.
700 	 */
701 	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
702 		zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
703 		error++;
704 		goto out;
705 	}
706 
707 	/*
708 	 * Build the list of remote fstypes so we know which ones we
709 	 * should forcibly unmount.
710 	 */
711 	remote_fstypes = get_remote_fstypes(zlogp);
712 	for (; /* ever */; ) {
713 		uint_t newcount = 0;
714 		boolean_t unmounted;
715 		struct mnttab *mnp;
716 		char *path;
717 		uint_t i;
718 
719 		mnts = NULL;
720 		nmnt = 0;
721 		/*
722 		 * MNTTAB gives us a way to walk through mounted
723 		 * filesystems; we need to be able to walk them in
724 		 * reverse order, so we build a list of all mounted
725 		 * filesystems.
726 		 */
727 		if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
728 		    &nmnt) != 0) {
729 			error++;
730 			goto out;
731 		}
732 		for (i = 0; i < nmnt; i++) {
733 			mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
734 			path = mnp->mnt_mountp;
735 			unmounted = B_FALSE;
736 			/*
737 			 * Try forced unmount first for remote filesystems.
738 			 *
739 			 * Not all remote filesystems support forced unmounts,
740 			 * so if this fails (ENOTSUP) we'll continue on
741 			 * and try a regular unmount.
742 			 */
743 			if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
744 				if (umount2(path, MS_FORCE) == 0)
745 					unmounted = B_TRUE;
746 			}
747 			/*
748 			 * Try forced unmount if we're stuck.
749 			 */
750 			if (stuck) {
751 				if (umount2(path, MS_FORCE) == 0) {
752 					unmounted = B_TRUE;
753 					stuck = B_FALSE;
754 				} else {
755 					/*
756 					 * The first failure indicates a
757 					 * mount we won't be able to get
758 					 * rid of automatically, so we
759 					 * bail.
760 					 */
761 					error++;
762 					zerror(zlogp, B_FALSE,
763 					    "unable to unmount '%s'", path);
764 					free_mnttable(mnts, nmnt);
765 					goto out;
766 				}
767 			}
768 			/*
769 			 * Try regular unmounts for everything else.
770 			 */
771 			if (!unmounted && umount2(path, 0) != 0)
772 				newcount++;
773 		}
774 		free_mnttable(mnts, nmnt);
775 
776 		if (newcount == 0)
777 			break;
778 		if (newcount >= oldcount) {
779 			/*
780 			 * Last round didn't unmount anything; we're stuck and
781 			 * should start trying forced unmounts.
782 			 */
783 			stuck = B_TRUE;
784 		}
785 		oldcount = newcount;
786 
787 		/*
788 		 * Autofs doesn't let you unmount its trigger nodes from
789 		 * userland so we have to tell the kernel to cleanup for us.
790 		 */
791 		if (autofs_cleanup(zoneid) != 0) {
792 			zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
793 			error++;
794 			goto out;
795 		}
796 	}
797 
798 out:
799 	free_remote_fstypes(remote_fstypes);
800 	(void) fclose(mnttab);
801 	return (error ? -1 : 0);
802 }
803 
804 static int
805 fs_compare(const void *m1, const void *m2)
806 {
807 	struct zone_fstab *i = (struct zone_fstab *)m1;
808 	struct zone_fstab *j = (struct zone_fstab *)m2;
809 
810 	return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
811 }
812 
813 /*
814  * Fork and exec (and wait for) the mentioned binary with the provided
815  * arguments.  Returns (-1) if something went wrong with fork(2) or exec(2),
816  * returns the exit status otherwise.
817  *
818  * If we were unable to exec the provided pathname (for whatever
819  * reason), we return the special token ZEXIT_EXEC.  The current value
820  * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
821  * consumers of this function; any future consumers must make sure this
822  * remains the case.
823  */
824 static int
825 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
826 {
827 	pid_t child_pid;
828 	int child_status = 0;
829 
830 	/*
831 	 * Do not let another thread localize a message while we are forking.
832 	 */
833 	(void) mutex_lock(&msglock);
834 	child_pid = fork();
835 	(void) mutex_unlock(&msglock);
836 	if (child_pid == -1) {
837 		zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
838 		return (-1);
839 	} else if (child_pid == 0) {
840 		closefrom(0);
841 		(void) execv(path, argv);
842 		/*
843 		 * Since we are in the child, there is no point calling zerror()
844 		 * since there is nobody waiting to consume it.  So exit with a
845 		 * special code that the parent will recognize and call zerror()
846 		 * accordingly.
847 		 */
848 
849 		_exit(ZEXIT_EXEC);
850 	} else {
851 		(void) waitpid(child_pid, &child_status, 0);
852 	}
853 
854 	if (WIFSIGNALED(child_status)) {
855 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
856 		    "signal %d", path, WTERMSIG(child_status));
857 		return (-1);
858 	}
859 	assert(WIFEXITED(child_status));
860 	if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
861 		zerror(zlogp, B_FALSE, "failed to exec %s", path);
862 		return (-1);
863 	}
864 	return (WEXITSTATUS(child_status));
865 }
866 
867 static int
868 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
869 {
870 	char cmdbuf[MAXPATHLEN];
871 	char *argv[4];
872 	int status;
873 
874 	/*
875 	 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
876 	 * that would cost us an extra fork/exec without buying us anything.
877 	 */
878 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
879 	    > sizeof (cmdbuf)) {
880 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
881 		return (-1);
882 	}
883 
884 	argv[0] = "fsck";
885 	argv[1] = "-m";
886 	argv[2] = (char *)rawdev;
887 	argv[3] = NULL;
888 
889 	status = forkexec(zlogp, cmdbuf, argv);
890 	if (status == 0 || status == -1)
891 		return (status);
892 	zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
893 	    "run fsck manually", rawdev, status);
894 	return (-1);
895 }
896 
897 static int
898 domount(zlog_t *zlogp, const char *fstype, const char *opts,
899     const char *special, const char *directory)
900 {
901 	char cmdbuf[MAXPATHLEN];
902 	char *argv[6];
903 	int status;
904 
905 	/*
906 	 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
907 	 * that would cost us an extra fork/exec without buying us anything.
908 	 */
909 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
910 	    > sizeof (cmdbuf)) {
911 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
912 		return (-1);
913 	}
914 	argv[0] = "mount";
915 	if (opts[0] == '\0') {
916 		argv[1] = (char *)special;
917 		argv[2] = (char *)directory;
918 		argv[3] = NULL;
919 	} else {
920 		argv[1] = "-o";
921 		argv[2] = (char *)opts;
922 		argv[3] = (char *)special;
923 		argv[4] = (char *)directory;
924 		argv[5] = NULL;
925 	}
926 
927 	status = forkexec(zlogp, cmdbuf, argv);
928 	if (status == 0 || status == -1)
929 		return (status);
930 	if (opts[0] == '\0')
931 		zerror(zlogp, B_FALSE, "\"%s %s %s\" "
932 		    "failed with exit code %d",
933 		    cmdbuf, special, directory, status);
934 	else
935 		zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
936 		    "failed with exit code %d",
937 		    cmdbuf, opts, special, directory, status);
938 	return (-1);
939 }
940 
941 /*
942  * Make sure if a given path exists, it is not a sym-link, and is a directory.
943  */
944 static int
945 check_path(zlog_t *zlogp, const char *path)
946 {
947 	struct stat statbuf;
948 	char respath[MAXPATHLEN];
949 	int res;
950 
951 	if (lstat(path, &statbuf) != 0) {
952 		if (errno == ENOENT)
953 			return (0);
954 		zerror(zlogp, B_TRUE, "can't stat %s", path);
955 		return (-1);
956 	}
957 	if (S_ISLNK(statbuf.st_mode)) {
958 		zerror(zlogp, B_FALSE, "%s is a symlink", path);
959 		return (-1);
960 	}
961 	if (!S_ISDIR(statbuf.st_mode)) {
962 		zerror(zlogp, B_FALSE, "%s is not a directory", path);
963 		return (-1);
964 	}
965 	if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
966 		zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
967 		return (-1);
968 	}
969 	respath[res] = '\0';
970 	if (strcmp(path, respath) != 0) {
971 		/*
972 		 * We don't like ".."s and "."s throwing us off
973 		 */
974 		zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
975 		return (-1);
976 	}
977 	return (0);
978 }
979 
980 /*
981  * Check every component of rootpath/relpath.  If any component fails (ie,
982  * exists but isn't the canonical path to a directory), it is returned in
983  * badpath, which is assumed to be at least of size MAXPATHLEN.
984  *
985  * Relpath must begin with '/'.
986  */
987 static boolean_t
988 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *relpath)
989 {
990 	char abspath[MAXPATHLEN], *slashp;
991 
992 	/*
993 	 * Make sure abspath has at least one '/' after its rootpath
994 	 * component, and ends with '/'.
995 	 */
996 	if (snprintf(abspath, sizeof (abspath), "%s%s/", rootpath, relpath) >
997 	    sizeof (abspath)) {
998 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", rootpath,
999 		    relpath);
1000 		return (B_FALSE);
1001 	}
1002 
1003 	slashp = &abspath[strlen(rootpath)];
1004 	assert(*slashp == '/');
1005 	do {
1006 		*slashp = '\0';
1007 		if (check_path(zlogp, abspath) != 0)
1008 			return (B_FALSE);
1009 		*slashp = '/';
1010 		slashp++;
1011 	} while ((slashp = strchr(slashp, '/')) != NULL);
1012 	return (B_TRUE);
1013 }
1014 
1015 static int
1016 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath)
1017 {
1018 	char    path[MAXPATHLEN];
1019 	char	specpath[MAXPATHLEN];
1020 	char    optstr[MAX_MNTOPT_STR];
1021 	zone_fsopt_t *optptr;
1022 
1023 	if (!valid_mount_path(zlogp, rootpath, fsptr->zone_fs_dir)) {
1024 		zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1025 		    rootpath, fsptr->zone_fs_dir);
1026 		return (-1);
1027 	}
1028 
1029 	if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1030 	    DEFAULT_DIR_MODE) != 0)
1031 		return (-1);
1032 
1033 	(void) snprintf(path, sizeof (path), "%s%s", rootpath,
1034 	    fsptr->zone_fs_dir);
1035 
1036 	if (strlen(fsptr->zone_fs_special) == 0) {
1037 		/*
1038 		 * A zero-length special is how we distinguish IPDs from
1039 		 * general-purpose FSs.  Make sure it mounts from a place that
1040 		 * can be seen via the alternate zone's root.
1041 		 */
1042 		if (snprintf(specpath, sizeof (specpath), "%s%s",
1043 		    zonecfg_get_root(), fsptr->zone_fs_dir) >=
1044 		    sizeof (specpath)) {
1045 			zerror(zlogp, B_FALSE, "cannot mount %s: path too "
1046 			    "long in alternate root", fsptr->zone_fs_dir);
1047 			return (-1);
1048 		}
1049 		if (zonecfg_in_alt_root())
1050 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1051 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS,
1052 		    specpath, path) != 0) {
1053 			zerror(zlogp, B_TRUE, "failed to loopback mount %s",
1054 			    specpath);
1055 			return (-1);
1056 		}
1057 		return (0);
1058 	}
1059 
1060 	/*
1061 	 * In general the strategy here is to do just as much verification as
1062 	 * necessary to avoid crashing or otherwise doing something bad; if the
1063 	 * administrator initiated the operation via zoneadm(1m), he'll get
1064 	 * auto-verification which will let him know what's wrong.  If he
1065 	 * modifies the zone configuration of a running zone and doesn't attempt
1066 	 * to verify that it's OK we won't crash but won't bother trying to be
1067 	 * too helpful either.  zoneadm verify is only a couple keystrokes away.
1068 	 */
1069 	if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1070 		zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1071 		    "invalid file-system type %s", fsptr->zone_fs_special,
1072 		    fsptr->zone_fs_dir, fsptr->zone_fs_type);
1073 		return (-1);
1074 	}
1075 
1076 	/*
1077 	 * If we're looking at an alternate root environment, then construct
1078 	 * read-only loopback mounts as necessary.  For all lofs mounts, make
1079 	 * sure that the 'special' entry points inside the alternate root.  (We
1080 	 * don't do this with other mounts, as devfs isn't in the alternate
1081 	 * root, and we need to assume the device environment is roughly the
1082 	 * same.)
1083 	 */
1084 	if (zonecfg_in_alt_root()) {
1085 		struct stat64 st;
1086 
1087 		if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1088 		    S_ISBLK(st.st_mode) &&
1089 		    check_lofs_needed(zlogp, fsptr) == -1)
1090 			return (-1);
1091 		if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1092 			if (snprintf(specpath, sizeof (specpath), "%s%s",
1093 			    zonecfg_get_root(), fsptr->zone_fs_special) >=
1094 			    sizeof (specpath)) {
1095 				zerror(zlogp, B_FALSE, "cannot mount %s: path "
1096 				    "too long in alternate root",
1097 				    fsptr->zone_fs_special);
1098 				return (-1);
1099 			}
1100 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1101 			(void) strlcpy(fsptr->zone_fs_special, specpath,
1102 			    sizeof (fsptr->zone_fs_special));
1103 		}
1104 	}
1105 
1106 	/*
1107 	 * Run 'fsck -m' if there's a device to fsck.
1108 	 */
1109 	if (fsptr->zone_fs_raw[0] != '\0' &&
1110 	    dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0)
1111 		return (-1);
1112 
1113 	/*
1114 	 * Build up mount option string.
1115 	 */
1116 	optstr[0] = '\0';
1117 	if (fsptr->zone_fs_options != NULL) {
1118 		(void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1119 		    sizeof (optstr));
1120 		for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1121 		    optptr != NULL; optptr = optptr->zone_fsopt_next) {
1122 			(void) strlcat(optstr, ",", sizeof (optstr));
1123 			(void) strlcat(optstr, optptr->zone_fsopt_opt,
1124 			    sizeof (optstr));
1125 		}
1126 	}
1127 	return (domount(zlogp, fsptr->zone_fs_type, optstr,
1128 	    fsptr->zone_fs_special, path));
1129 }
1130 
1131 static void
1132 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1133 {
1134 	uint_t i;
1135 
1136 	if (fsarray == NULL)
1137 		return;
1138 	for (i = 0; i < nelem; i++)
1139 		zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1140 	free(fsarray);
1141 }
1142 
1143 /*
1144  * This function constructs the miniroot-like "scratch zone" environment.  If
1145  * it returns B_FALSE, then the error has already been logged.
1146  */
1147 static boolean_t
1148 build_mounted(zlog_t *zlogp, char *rootpath, size_t rootlen,
1149     const char *zonepath)
1150 {
1151 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1152 	char luroot[MAXPATHLEN];
1153 	const char **cpp;
1154 	static const char *mkdirs[] = {
1155 		"/system", "/system/contract", "/proc", "/dev", "/tmp",
1156 		"/a", NULL
1157 	};
1158 	static const char *localdirs[] = {
1159 		"/etc", "/var", NULL
1160 	};
1161 	static const char *loopdirs[] = {
1162 		"/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1163 		"/usr", NULL
1164 	};
1165 	static const char *tmpdirs[] = {
1166 		"/tmp", "/var/run", NULL
1167 	};
1168 	FILE *fp;
1169 	struct stat st;
1170 	char *altstr;
1171 	uuid_t uuid;
1172 
1173 	/*
1174 	 * Construct a small Solaris environment, including the zone root
1175 	 * mounted on '/a' inside that environment.
1176 	 */
1177 	resolve_lofs(zlogp, rootpath, rootlen);
1178 	(void) snprintf(luroot, sizeof (luroot), "%s/lu", zonepath);
1179 	resolve_lofs(zlogp, luroot, sizeof (luroot));
1180 	(void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1181 	(void) symlink("./usr/bin", tmp);
1182 
1183 	/*
1184 	 * These are mostly special mount points; not handled here.  (See
1185 	 * zone_mount_early.)
1186 	 */
1187 	for (cpp = mkdirs; *cpp != NULL; cpp++) {
1188 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1189 		if (mkdir(tmp, 0755) != 0) {
1190 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1191 			return (B_FALSE);
1192 		}
1193 	}
1194 
1195 	/*
1196 	 * These are mounted read-write from the zone undergoing upgrade.  We
1197 	 * must be careful not to 'leak' things from the main system into the
1198 	 * zone, and this accomplishes that goal.
1199 	 */
1200 	for (cpp = localdirs; *cpp != NULL; cpp++) {
1201 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1202 		(void) snprintf(fromdir, sizeof (fromdir), "%s%s", rootpath,
1203 		    *cpp);
1204 		if (mkdir(tmp, 0755) != 0) {
1205 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1206 			return (B_FALSE);
1207 		}
1208 		if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp) != 0) {
1209 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1210 			    *cpp);
1211 			return (B_FALSE);
1212 		}
1213 	}
1214 
1215 	/*
1216 	 * These are things mounted read-only from the running system because
1217 	 * they contain binaries that must match system.
1218 	 */
1219 	for (cpp = loopdirs; *cpp != NULL; cpp++) {
1220 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1221 		if (mkdir(tmp, 0755) != 0) {
1222 			if (errno != EEXIST) {
1223 				zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1224 				return (B_FALSE);
1225 			}
1226 			if (lstat(tmp, &st) != 0) {
1227 				zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1228 				return (B_FALSE);
1229 			}
1230 			/*
1231 			 * Ignore any non-directories encountered.  These are
1232 			 * things that have been converted into symlinks
1233 			 * (/etc/fs and /etc/lib) and no longer need a lofs
1234 			 * fixup.
1235 			 */
1236 			if (!S_ISDIR(st.st_mode))
1237 				continue;
1238 		}
1239 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, *cpp,
1240 		    tmp) != 0) {
1241 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1242 			    *cpp);
1243 			return (B_FALSE);
1244 		}
1245 	}
1246 
1247 	/*
1248 	 * These are things with tmpfs mounted inside.
1249 	 */
1250 	for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1251 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1252 		if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
1253 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1254 			return (B_FALSE);
1255 		}
1256 		if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1257 			zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1258 			return (B_FALSE);
1259 		}
1260 	}
1261 
1262 	/*
1263 	 * This is here to support lucopy.  If there's an instance of this same
1264 	 * zone on the current running system, then we mount its root up as
1265 	 * read-only inside the scratch zone.
1266 	 */
1267 	(void) zonecfg_get_uuid(zone_name, uuid);
1268 	altstr = strdup(zonecfg_get_root());
1269 	if (altstr == NULL) {
1270 		zerror(zlogp, B_TRUE, "out of memory");
1271 		return (B_FALSE);
1272 	}
1273 	zonecfg_set_root("");
1274 	(void) strlcpy(tmp, zone_name, sizeof (tmp));
1275 	(void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1276 	if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1277 	    strcmp(fromdir, rootpath) != 0) {
1278 		(void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1279 		if (mkdir(tmp, 0755) != 0) {
1280 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1281 			return (B_FALSE);
1282 		}
1283 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, fromdir,
1284 		    tmp) != 0) {
1285 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1286 			    fromdir);
1287 			return (B_FALSE);
1288 		}
1289 	}
1290 	zonecfg_set_root(altstr);
1291 	free(altstr);
1292 
1293 	if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1294 		zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1295 		return (B_FALSE);
1296 	}
1297 	(void) ftruncate(fileno(fp), 0);
1298 	if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1299 		zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1300 	}
1301 	zonecfg_close_scratch(fp);
1302 	(void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1303 	if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1304 		return (B_FALSE);
1305 	(void) strlcpy(rootpath, tmp, rootlen);
1306 	return (B_TRUE);
1307 }
1308 
1309 static int
1310 mount_filesystems(zlog_t *zlogp, boolean_t mount_cmd)
1311 {
1312 	char	rootpath[MAXPATHLEN];
1313 	char	zonepath[MAXPATHLEN];
1314 	int	num_fs = 0, i;
1315 	struct zone_fstab fstab, *fs_ptr = NULL, *tmp_ptr;
1316 	struct zone_fstab *fsp;
1317 	zone_dochandle_t handle = NULL;
1318 	zone_state_t zstate;
1319 
1320 	if (zone_get_state(zone_name, &zstate) != Z_OK ||
1321 	    (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1322 		zerror(zlogp, B_FALSE,
1323 		    "zone must be in '%s' or '%s' state to mount file-systems",
1324 		    zone_state_str(ZONE_STATE_READY),
1325 		    zone_state_str(ZONE_STATE_MOUNTED));
1326 		goto bad;
1327 	}
1328 
1329 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1330 		zerror(zlogp, B_TRUE, "unable to determine zone path");
1331 		goto bad;
1332 	}
1333 
1334 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1335 		zerror(zlogp, B_TRUE, "unable to determine zone root");
1336 		goto bad;
1337 	}
1338 
1339 	if ((handle = zonecfg_init_handle()) == NULL) {
1340 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
1341 		goto bad;
1342 	}
1343 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1344 	    zonecfg_setfsent(handle) != Z_OK) {
1345 		zerror(zlogp, B_FALSE, "invalid configuration");
1346 		goto bad;
1347 	}
1348 
1349 	/*
1350 	 * /dev in the zone is loopback'd from the external /dev repository,
1351 	 * in order to provide a largely read-only semantic.  But because
1352 	 * processes in the zone need to be able to chown, chmod, etc. zone
1353 	 * /dev files, we can't use a 'ro' lofs mount.  Instead we use a
1354 	 * special mode just for zones, "zonedevfs".
1355 	 *
1356 	 * In the future we should front /dev with a full-fledged filesystem.
1357 	 */
1358 	num_fs++;
1359 	if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1360 		zerror(zlogp, B_TRUE, "memory allocation failed");
1361 		num_fs--;
1362 		goto bad;
1363 	}
1364 	fs_ptr = tmp_ptr;
1365 	fsp = &fs_ptr[num_fs - 1];
1366 	/*
1367 	 * Note that mount_one will prepend the alternate root to
1368 	 * zone_fs_special and do the necessary resolution, so all that is
1369 	 * needed here is to strip the root added by zone_get_zonepath.
1370 	 */
1371 	(void) strlcpy(fsp->zone_fs_dir, "/dev", sizeof (fsp->zone_fs_dir));
1372 	(void) snprintf(fsp->zone_fs_special, sizeof (fsp->zone_fs_special),
1373 	    "%s/dev", zonepath + strlen(zonecfg_get_root()));
1374 	fsp->zone_fs_raw[0] = '\0';
1375 	(void) strlcpy(fsp->zone_fs_type, MNTTYPE_LOFS,
1376 	    sizeof (fsp->zone_fs_type));
1377 	fsp->zone_fs_options = NULL;
1378 	if (zonecfg_add_fs_option(fsp, MNTOPT_LOFS_ZONEDEVFS) != Z_OK) {
1379 		zerror(zlogp, B_FALSE, "error adding property");
1380 		goto bad;
1381 	}
1382 
1383 	/*
1384 	 * Iterate through the rest of the filesystems, first the IPDs, then
1385 	 * the general FSs.  Sort them all, then mount them in sorted order.
1386 	 * This is to make sure the higher level directories (e.g., /usr)
1387 	 * get mounted before any beneath them (e.g., /usr/local).
1388 	 */
1389 	if (zonecfg_setipdent(handle) != Z_OK) {
1390 		zerror(zlogp, B_FALSE, "invalid configuration");
1391 		goto bad;
1392 	}
1393 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1394 		num_fs++;
1395 		if ((tmp_ptr = realloc(fs_ptr,
1396 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1397 			zerror(zlogp, B_TRUE, "memory allocation failed");
1398 			num_fs--;
1399 			(void) zonecfg_endipdent(handle);
1400 			goto bad;
1401 		}
1402 		fs_ptr = tmp_ptr;
1403 		fsp = &fs_ptr[num_fs - 1];
1404 		/*
1405 		 * IPDs logically only have a mount point; all other properties
1406 		 * are implied.
1407 		 */
1408 		(void) strlcpy(fsp->zone_fs_dir,
1409 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1410 		fsp->zone_fs_special[0] = '\0';
1411 		fsp->zone_fs_raw[0] = '\0';
1412 		fsp->zone_fs_type[0] = '\0';
1413 		fsp->zone_fs_options = NULL;
1414 	}
1415 	(void) zonecfg_endipdent(handle);
1416 
1417 	if (zonecfg_setfsent(handle) != Z_OK) {
1418 		zerror(zlogp, B_FALSE, "invalid configuration");
1419 		goto bad;
1420 	}
1421 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1422 		/*
1423 		 * ZFS filesystems will not be accessible under an alternate
1424 		 * root, since the pool will not be known.  Ignore them in this
1425 		 * case.
1426 		 */
1427 		if (mount_cmd && strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1428 			continue;
1429 
1430 		num_fs++;
1431 		if ((tmp_ptr = realloc(fs_ptr,
1432 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1433 			zerror(zlogp, B_TRUE, "memory allocation failed");
1434 			num_fs--;
1435 			(void) zonecfg_endfsent(handle);
1436 			goto bad;
1437 		}
1438 		fs_ptr = tmp_ptr;
1439 		fsp = &fs_ptr[num_fs - 1];
1440 		(void) strlcpy(fsp->zone_fs_dir,
1441 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1442 		(void) strlcpy(fsp->zone_fs_special, fstab.zone_fs_special,
1443 		    sizeof (fsp->zone_fs_special));
1444 		(void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1445 		    sizeof (fsp->zone_fs_raw));
1446 		(void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1447 		    sizeof (fsp->zone_fs_type));
1448 		fsp->zone_fs_options = fstab.zone_fs_options;
1449 	}
1450 	(void) zonecfg_endfsent(handle);
1451 	zonecfg_fini_handle(handle);
1452 	handle = NULL;
1453 
1454 	/*
1455 	 * If we're mounting a zone for administration, then we need to set up
1456 	 * the "/a" environment inside the zone so that the commands that run
1457 	 * in there have access to both the running system's utilities and the
1458 	 * to-be-modified zone's files.
1459 	 */
1460 	if (mount_cmd &&
1461 	    !build_mounted(zlogp, rootpath, sizeof (rootpath), zonepath))
1462 		goto bad;
1463 
1464 	qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1465 	for (i = 0; i < num_fs; i++) {
1466 		if (mount_cmd && strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1467 			size_t slen = strlen(rootpath) - 2;
1468 
1469 			/* /dev is special and always goes at the top */
1470 			rootpath[slen] = '\0';
1471 			if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1472 				goto bad;
1473 			rootpath[slen] = '/';
1474 			continue;
1475 		}
1476 		if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1477 			goto bad;
1478 	}
1479 	free_fs_data(fs_ptr, num_fs);
1480 
1481 	/*
1482 	 * Everything looks fine.
1483 	 */
1484 	return (0);
1485 
1486 bad:
1487 	if (handle != NULL)
1488 		zonecfg_fini_handle(handle);
1489 	free_fs_data(fs_ptr, num_fs);
1490 	return (-1);
1491 }
1492 
1493 /* caller makes sure neither parameter is NULL */
1494 static int
1495 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1496 {
1497 	int prefixlen;
1498 
1499 	prefixlen = atoi(prefixstr);
1500 	if (prefixlen < 0 || prefixlen > maxprefixlen)
1501 		return (1);
1502 	while (prefixlen > 0) {
1503 		if (prefixlen >= 8) {
1504 			*maskstr++ = 0xFF;
1505 			prefixlen -= 8;
1506 			continue;
1507 		}
1508 		*maskstr |= 1 << (8 - prefixlen);
1509 		prefixlen--;
1510 	}
1511 	return (0);
1512 }
1513 
1514 /*
1515  * Tear down all interfaces belonging to the given zone.  This should
1516  * be called with the zone in a state other than "running", so that
1517  * interfaces can't be assigned to the zone after this returns.
1518  *
1519  * If anything goes wrong, log an error message and return an error.
1520  */
1521 static int
1522 unconfigure_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1523 {
1524 	struct lifnum lifn;
1525 	struct lifconf lifc;
1526 	struct lifreq *lifrp, lifrl;
1527 	int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1528 	int num_ifs, s, i, ret_code = 0;
1529 	uint_t bufsize;
1530 	char *buf = NULL;
1531 
1532 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1533 		zerror(zlogp, B_TRUE, "could not get socket");
1534 		ret_code = -1;
1535 		goto bad;
1536 	}
1537 	lifn.lifn_family = AF_UNSPEC;
1538 	lifn.lifn_flags = (int)lifc_flags;
1539 	if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1540 		zerror(zlogp, B_TRUE,
1541 		    "could not determine number of interfaces");
1542 		ret_code = -1;
1543 		goto bad;
1544 	}
1545 	num_ifs = lifn.lifn_count;
1546 	bufsize = num_ifs * sizeof (struct lifreq);
1547 	if ((buf = malloc(bufsize)) == NULL) {
1548 		zerror(zlogp, B_TRUE, "memory allocation failed");
1549 		ret_code = -1;
1550 		goto bad;
1551 	}
1552 	lifc.lifc_family = AF_UNSPEC;
1553 	lifc.lifc_flags = (int)lifc_flags;
1554 	lifc.lifc_len = bufsize;
1555 	lifc.lifc_buf = buf;
1556 	if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1557 		zerror(zlogp, B_TRUE, "could not get configured interfaces");
1558 		ret_code = -1;
1559 		goto bad;
1560 	}
1561 	lifrp = lifc.lifc_req;
1562 	for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1563 		(void) close(s);
1564 		if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1565 		    0) {
1566 			zerror(zlogp, B_TRUE, "%s: could not get socket",
1567 			    lifrl.lifr_name);
1568 			ret_code = -1;
1569 			continue;
1570 		}
1571 		(void) memset(&lifrl, 0, sizeof (lifrl));
1572 		(void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1573 		    sizeof (lifrl.lifr_name));
1574 		if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1575 			zerror(zlogp, B_TRUE,
1576 			    "%s: could not determine zone interface belongs to",
1577 			    lifrl.lifr_name);
1578 			ret_code = -1;
1579 			continue;
1580 		}
1581 		if (lifrl.lifr_zoneid == zone_id) {
1582 			if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1583 				zerror(zlogp, B_TRUE,
1584 				    "%s: could not remove interface",
1585 				    lifrl.lifr_name);
1586 				ret_code = -1;
1587 				continue;
1588 			}
1589 		}
1590 	}
1591 bad:
1592 	if (s > 0)
1593 		(void) close(s);
1594 	if (buf)
1595 		free(buf);
1596 	return (ret_code);
1597 }
1598 
1599 static union	sockunion {
1600 	struct	sockaddr sa;
1601 	struct	sockaddr_in sin;
1602 	struct	sockaddr_dl sdl;
1603 	struct	sockaddr_in6 sin6;
1604 } so_dst, so_ifp;
1605 
1606 static struct {
1607 	struct	rt_msghdr hdr;
1608 	char	space[512];
1609 } rtmsg;
1610 
1611 static int
1612 salen(struct sockaddr *sa)
1613 {
1614 	switch (sa->sa_family) {
1615 	case AF_INET:
1616 		return (sizeof (struct sockaddr_in));
1617 	case AF_LINK:
1618 		return (sizeof (struct sockaddr_dl));
1619 	case AF_INET6:
1620 		return (sizeof (struct sockaddr_in6));
1621 	default:
1622 		return (sizeof (struct sockaddr));
1623 	}
1624 }
1625 
1626 #define	ROUNDUP_LONG(a) \
1627 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1628 
1629 /*
1630  * Look up which zone is using a given IP address.  The address in question
1631  * is expected to have been stuffed into the structure to which lifr points
1632  * via a previous SIOCGLIFADDR ioctl().
1633  *
1634  * This is done using black router socket magic.
1635  *
1636  * Return the name of the zone on success or NULL on failure.
1637  *
1638  * This is a lot of code for a simple task; a new ioctl request to take care
1639  * of this might be a useful RFE.
1640  */
1641 
1642 static char *
1643 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
1644 {
1645 	static char answer[ZONENAME_MAX];
1646 	pid_t pid;
1647 	int s, rlen, l, i;
1648 	char *cp = rtmsg.space;
1649 	struct sockaddr_dl *ifp = NULL;
1650 	struct sockaddr *sa;
1651 	char save_if_name[LIFNAMSIZ];
1652 
1653 	answer[0] = '\0';
1654 
1655 	pid = getpid();
1656 	if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1657 		zerror(zlogp, B_TRUE, "could not get routing socket");
1658 		return (NULL);
1659 	}
1660 
1661 	if (lifr->lifr_addr.ss_family == AF_INET) {
1662 		struct sockaddr_in *sin4;
1663 
1664 		so_dst.sa.sa_family = AF_INET;
1665 		sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
1666 		so_dst.sin.sin_addr = sin4->sin_addr;
1667 	} else {
1668 		struct sockaddr_in6 *sin6;
1669 
1670 		so_dst.sa.sa_family = AF_INET6;
1671 		sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
1672 		so_dst.sin6.sin6_addr = sin6->sin6_addr;
1673 	}
1674 
1675 	so_ifp.sa.sa_family = AF_LINK;
1676 
1677 	(void) memset(&rtmsg, 0, sizeof (rtmsg));
1678 	rtmsg.hdr.rtm_type = RTM_GET;
1679 	rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
1680 	rtmsg.hdr.rtm_version = RTM_VERSION;
1681 	rtmsg.hdr.rtm_seq = ++rts_seqno;
1682 	rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
1683 
1684 	l = ROUNDUP_LONG(salen(&so_dst.sa));
1685 	(void) memmove(cp, &(so_dst), l);
1686 	cp += l;
1687 	l = ROUNDUP_LONG(salen(&so_ifp.sa));
1688 	(void) memmove(cp, &(so_ifp), l);
1689 	cp += l;
1690 
1691 	rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
1692 
1693 	if ((rlen = write(s, &rtmsg, l)) < 0) {
1694 		zerror(zlogp, B_TRUE, "writing to routing socket");
1695 		return (NULL);
1696 	} else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
1697 		zerror(zlogp, B_TRUE,
1698 		    "write to routing socket got only %d for len\n", rlen);
1699 		return (NULL);
1700 	}
1701 	do {
1702 		l = read(s, &rtmsg, sizeof (rtmsg));
1703 	} while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
1704 	    rtmsg.hdr.rtm_pid != pid));
1705 	if (l < 0) {
1706 		zerror(zlogp, B_TRUE, "reading from routing socket");
1707 		return (NULL);
1708 	}
1709 
1710 	if (rtmsg.hdr.rtm_version != RTM_VERSION) {
1711 		zerror(zlogp, B_FALSE,
1712 		    "routing message version %d not understood",
1713 		    rtmsg.hdr.rtm_version);
1714 		return (NULL);
1715 	}
1716 	if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
1717 		zerror(zlogp, B_FALSE, "message length mismatch, "
1718 		    "expected %d bytes, returned %d bytes",
1719 		    rtmsg.hdr.rtm_msglen, l);
1720 		return (NULL);
1721 	}
1722 	if (rtmsg.hdr.rtm_errno != 0)  {
1723 		errno = rtmsg.hdr.rtm_errno;
1724 		zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
1725 		return (NULL);
1726 	}
1727 	if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
1728 		zerror(zlogp, B_FALSE, "interface not found");
1729 		return (NULL);
1730 	}
1731 	cp = ((char *)(&rtmsg.hdr + 1));
1732 	for (i = 1; i != 0; i <<= 1) {
1733 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1734 		sa = (struct sockaddr *)cp;
1735 		if (i != RTA_IFP) {
1736 			if ((i & rtmsg.hdr.rtm_addrs) != 0)
1737 				cp += ROUNDUP_LONG(salen(sa));
1738 			continue;
1739 		}
1740 		if (sa->sa_family == AF_LINK &&
1741 		    ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
1742 			ifp = (struct sockaddr_dl *)sa;
1743 		break;
1744 	}
1745 	if (ifp == NULL) {
1746 		zerror(zlogp, B_FALSE, "interface could not be determined");
1747 		return (NULL);
1748 	}
1749 
1750 	/*
1751 	 * We need to set the I/F name to what we got above, then do the
1752 	 * appropriate ioctl to get its zone name.  But lifr->lifr_name is
1753 	 * used by the calling function to do a REMOVEIF, so if we leave the
1754 	 * "good" zone's I/F name in place, *that* I/F will be removed instead
1755 	 * of the bad one.  So we save the old (bad) I/F name before over-
1756 	 * writing it and doing the ioctl, then restore it after the ioctl.
1757 	 */
1758 	(void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
1759 	(void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
1760 	lifr->lifr_name[ifp->sdl_nlen] = '\0';
1761 	i = ioctl(s, SIOCGLIFZONE, lifr);
1762 	(void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
1763 	if (i < 0) {
1764 		zerror(zlogp, B_TRUE,
1765 		    "%s: could not determine the zone interface belongs to",
1766 		    lifr->lifr_name);
1767 		return (NULL);
1768 	}
1769 	if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
1770 		(void) snprintf(answer, sizeof (answer), "%d",
1771 		    lifr->lifr_zoneid);
1772 
1773 	if (strlen(answer) > 0)
1774 		return (answer);
1775 	return (NULL);
1776 }
1777 
1778 typedef struct mcast_rtmsg_s {
1779 	struct rt_msghdr	m_rtm;
1780 	union {
1781 		struct {
1782 			struct sockaddr_in	m_dst;
1783 			struct sockaddr_in	m_gw;
1784 			struct sockaddr_in	m_netmask;
1785 		} m_v4;
1786 		struct {
1787 			struct sockaddr_in6	m_dst;
1788 			struct sockaddr_in6	m_gw;
1789 			struct sockaddr_in6	m_netmask;
1790 		} m_v6;
1791 	} m_u;
1792 } mcast_rtmsg_t;
1793 #define	m_dst4		m_u.m_v4.m_dst
1794 #define	m_dst6		m_u.m_v6.m_dst
1795 #define	m_gw4		m_u.m_v4.m_gw
1796 #define	m_gw6		m_u.m_v6.m_gw
1797 #define	m_netmask4	m_u.m_v4.m_netmask
1798 #define	m_netmask6	m_u.m_v6.m_netmask
1799 
1800 /*
1801  * Configures a single interface: a new virtual interface is added, based on
1802  * the physical interface nwiftabptr->zone_nwif_physical, with the address
1803  * specified in nwiftabptr->zone_nwif_address, for zone zone_id.  Note that
1804  * the "address" can be an IPv6 address (with a /prefixlength required), an
1805  * IPv4 address (with a /prefixlength optional), or a name; for the latter,
1806  * an IPv4 name-to-address resolution will be attempted.
1807  *
1808  * A default interface route for multicast is created on the first IPv4 and
1809  * IPv6 interfaces (that have the IFF_MULTICAST flag set), respectively.
1810  * This should really be done in the init scripts if we ever allow zones to
1811  * modify the routing tables.
1812  *
1813  * If anything goes wrong, we log an detailed error message, attempt to tear
1814  * down whatever we set up and return an error.
1815  */
1816 static int
1817 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
1818     struct zone_nwiftab *nwiftabptr, boolean_t *mcast_rt_v4_setp,
1819     boolean_t *mcast_rt_v6_setp)
1820 {
1821 	struct lifreq lifr;
1822 	struct sockaddr_in netmask4;
1823 	struct sockaddr_in6 netmask6;
1824 	struct in_addr in4;
1825 	struct in6_addr in6;
1826 	sa_family_t af;
1827 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
1828 	mcast_rtmsg_t mcast_rtmsg;
1829 	int s;
1830 	int rs;
1831 	int rlen;
1832 	boolean_t got_netmask = B_FALSE;
1833 	char addrstr4[INET_ADDRSTRLEN];
1834 	int res;
1835 
1836 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
1837 	if (res != Z_OK) {
1838 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
1839 		    nwiftabptr->zone_nwif_address);
1840 		return (-1);
1841 	}
1842 	af = lifr.lifr_addr.ss_family;
1843 	if (af == AF_INET)
1844 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
1845 	else
1846 		in6 = ((struct sockaddr_in6 *)(&lifr.lifr_addr))->sin6_addr;
1847 
1848 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
1849 		zerror(zlogp, B_TRUE, "could not get socket");
1850 		return (-1);
1851 	}
1852 
1853 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
1854 	    sizeof (lifr.lifr_name));
1855 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
1856 		zerror(zlogp, B_TRUE, "%s: could not add interface",
1857 		    lifr.lifr_name);
1858 		(void) close(s);
1859 		return (-1);
1860 	}
1861 
1862 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
1863 		zerror(zlogp, B_TRUE,
1864 		    "%s: could not set IP address to %s",
1865 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
1866 		goto bad;
1867 	}
1868 
1869 	/* Preserve literal IPv4 address for later potential printing. */
1870 	if (af == AF_INET)
1871 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
1872 
1873 	lifr.lifr_zoneid = zone_id;
1874 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
1875 		zerror(zlogp, B_TRUE, "%s: could not place interface into zone",
1876 		    lifr.lifr_name);
1877 		goto bad;
1878 	}
1879 
1880 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
1881 		got_netmask = B_TRUE;	/* default setting will be correct */
1882 	} else {
1883 		if (af == AF_INET) {
1884 			/*
1885 			 * The IPv4 netmask can be determined either
1886 			 * directly if a prefix length was supplied with
1887 			 * the address or via the netmasks database.  Not
1888 			 * being able to determine it is a common failure,
1889 			 * but it often is not fatal to operation of the
1890 			 * interface.  In that case, a warning will be
1891 			 * printed after the rest of the interface's
1892 			 * parameters have been configured.
1893 			 */
1894 			(void) memset(&netmask4, 0, sizeof (netmask4));
1895 			if (slashp != NULL) {
1896 				if (addr2netmask(slashp + 1, V4_ADDR_LEN,
1897 				    (uchar_t *)&netmask4.sin_addr) != 0) {
1898 					*slashp = '/';
1899 					zerror(zlogp, B_FALSE,
1900 					    "%s: invalid prefix length in %s",
1901 					    lifr.lifr_name,
1902 					    nwiftabptr->zone_nwif_address);
1903 					goto bad;
1904 				}
1905 				got_netmask = B_TRUE;
1906 			} else if (getnetmaskbyaddr(in4,
1907 			    &netmask4.sin_addr) == 0) {
1908 				got_netmask = B_TRUE;
1909 			}
1910 			if (got_netmask) {
1911 				netmask4.sin_family = af;
1912 				(void) memcpy(&lifr.lifr_addr, &netmask4,
1913 				    sizeof (netmask4));
1914 			}
1915 		} else {
1916 			(void) memset(&netmask6, 0, sizeof (netmask6));
1917 			if (addr2netmask(slashp + 1, V6_ADDR_LEN,
1918 			    (uchar_t *)&netmask6.sin6_addr) != 0) {
1919 				*slashp = '/';
1920 				zerror(zlogp, B_FALSE,
1921 				    "%s: invalid prefix length in %s",
1922 				    lifr.lifr_name,
1923 				    nwiftabptr->zone_nwif_address);
1924 				goto bad;
1925 			}
1926 			got_netmask = B_TRUE;
1927 			netmask6.sin6_family = af;
1928 			(void) memcpy(&lifr.lifr_addr, &netmask6,
1929 			    sizeof (netmask6));
1930 		}
1931 		if (got_netmask &&
1932 		    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
1933 			zerror(zlogp, B_TRUE, "%s: could not set netmask",
1934 			    lifr.lifr_name);
1935 			goto bad;
1936 		}
1937 
1938 		/*
1939 		 * This doesn't set the broadcast address at all. Rather, it
1940 		 * gets, then sets the interface's address, relying on the fact
1941 		 * that resetting the address will reset the broadcast address.
1942 		 */
1943 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
1944 			zerror(zlogp, B_TRUE, "%s: could not get address",
1945 			    lifr.lifr_name);
1946 			goto bad;
1947 		}
1948 		if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
1949 			zerror(zlogp, B_TRUE,
1950 			    "%s: could not reset broadcast address",
1951 			    lifr.lifr_name);
1952 			goto bad;
1953 		}
1954 	}
1955 
1956 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
1957 		zerror(zlogp, B_TRUE, "%s: could not get flags",
1958 		    lifr.lifr_name);
1959 		goto bad;
1960 	}
1961 	lifr.lifr_flags |= IFF_UP;
1962 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
1963 		int save_errno = errno;
1964 		char *zone_using;
1965 
1966 		/*
1967 		 * If we failed with something other than EADDRNOTAVAIL,
1968 		 * then skip to the end.  Otherwise, look up our address,
1969 		 * then call a function to determine which zone is already
1970 		 * using that address.
1971 		 */
1972 		if (errno != EADDRNOTAVAIL) {
1973 			zerror(zlogp, B_TRUE,
1974 			    "%s: could not bring interface up", lifr.lifr_name);
1975 			goto bad;
1976 		}
1977 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
1978 			zerror(zlogp, B_TRUE, "%s: could not get address",
1979 			    lifr.lifr_name);
1980 			goto bad;
1981 		}
1982 		zone_using = who_is_using(zlogp, &lifr);
1983 		errno = save_errno;
1984 		if (zone_using == NULL)
1985 			zerror(zlogp, B_TRUE,
1986 			    "%s: could not bring interface up", lifr.lifr_name);
1987 		else
1988 			zerror(zlogp, B_TRUE, "%s: could not bring interface "
1989 			    "up: address in use by zone '%s'", lifr.lifr_name,
1990 			    zone_using);
1991 		goto bad;
1992 	}
1993 	if ((lifr.lifr_flags & IFF_MULTICAST) && ((af == AF_INET &&
1994 	    mcast_rt_v4_setp != NULL && *mcast_rt_v4_setp == B_FALSE) ||
1995 	    (af == AF_INET6 &&
1996 	    mcast_rt_v6_setp != NULL && *mcast_rt_v6_setp == B_FALSE))) {
1997 		rs = socket(PF_ROUTE, SOCK_RAW, 0);
1998 		if (rs < 0) {
1999 			zerror(zlogp, B_TRUE, "%s: could not create "
2000 			    "routing socket", lifr.lifr_name);
2001 			goto bad;
2002 		}
2003 		(void) shutdown(rs, 0);
2004 		(void) memset((void *)&mcast_rtmsg, 0, sizeof (mcast_rtmsg_t));
2005 		mcast_rtmsg.m_rtm.rtm_msglen =  sizeof (struct rt_msghdr) +
2006 		    3 * (af == AF_INET ? sizeof (struct sockaddr_in) :
2007 		    sizeof (struct sockaddr_in6));
2008 		mcast_rtmsg.m_rtm.rtm_version = RTM_VERSION;
2009 		mcast_rtmsg.m_rtm.rtm_type = RTM_ADD;
2010 		mcast_rtmsg.m_rtm.rtm_flags = RTF_UP;
2011 		mcast_rtmsg.m_rtm.rtm_addrs =
2012 		    RTA_DST | RTA_GATEWAY | RTA_NETMASK;
2013 		mcast_rtmsg.m_rtm.rtm_seq = ++rts_seqno;
2014 		if (af == AF_INET) {
2015 			mcast_rtmsg.m_dst4.sin_family = AF_INET;
2016 			mcast_rtmsg.m_dst4.sin_addr.s_addr =
2017 			    htonl(INADDR_UNSPEC_GROUP);
2018 			mcast_rtmsg.m_gw4.sin_family = AF_INET;
2019 			mcast_rtmsg.m_gw4.sin_addr = in4;
2020 			mcast_rtmsg.m_netmask4.sin_family = AF_INET;
2021 			mcast_rtmsg.m_netmask4.sin_addr.s_addr =
2022 			    htonl(IN_CLASSD_NET);
2023 		} else {
2024 			mcast_rtmsg.m_dst6.sin6_family = AF_INET6;
2025 			mcast_rtmsg.m_dst6.sin6_addr.s6_addr[0] = 0xffU;
2026 			mcast_rtmsg.m_gw6.sin6_family = AF_INET6;
2027 			mcast_rtmsg.m_gw6.sin6_addr = in6;
2028 			mcast_rtmsg.m_netmask6.sin6_family = AF_INET6;
2029 			mcast_rtmsg.m_netmask6.sin6_addr.s6_addr[0] = 0xffU;
2030 		}
2031 		rlen = write(rs, (char *)&mcast_rtmsg,
2032 		    mcast_rtmsg.m_rtm.rtm_msglen);
2033 		if (rlen < mcast_rtmsg.m_rtm.rtm_msglen) {
2034 			if (rlen < 0) {
2035 				zerror(zlogp, B_TRUE, "%s: could not set "
2036 				    "default interface for multicast",
2037 				    lifr.lifr_name);
2038 			} else {
2039 				zerror(zlogp, B_FALSE, "%s: write to routing "
2040 				    "socket returned %d", lifr.lifr_name, rlen);
2041 			}
2042 			(void) close(rs);
2043 			goto bad;
2044 		}
2045 		if (af == AF_INET) {
2046 			*mcast_rt_v4_setp = B_TRUE;
2047 		} else {
2048 			*mcast_rt_v6_setp = B_TRUE;
2049 		}
2050 		(void) close(rs);
2051 	}
2052 
2053 	if (!got_netmask) {
2054 		/*
2055 		 * A common, but often non-fatal problem, is that the system
2056 		 * cannot find the netmask for an interface address. This is
2057 		 * often caused by it being only in /etc/inet/netmasks, but
2058 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2059 		 * in that. This doesn't show up at boot because the netmask
2060 		 * is obtained from /etc/inet/netmasks when no network
2061 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2062 		 * available. We warn the user here that something like this
2063 		 * has happened and we're just running with a default and
2064 		 * possible incorrect netmask.
2065 		 */
2066 		char buffer[INET6_ADDRSTRLEN];
2067 		void  *addr;
2068 
2069 		if (af == AF_INET)
2070 			addr = &((struct sockaddr_in *)
2071 			    (&lifr.lifr_addr))->sin_addr;
2072 		else
2073 			addr = &((struct sockaddr_in6 *)
2074 			    (&lifr.lifr_addr))->sin6_addr;
2075 
2076 		/* Find out what netmask interface is going to be using */
2077 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2078 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL)
2079 			goto bad;
2080 		zerror(zlogp, B_FALSE,
2081 		    "WARNING: %s: no matching subnet found in netmasks(4) for "
2082 		    "%s; using default of %s.",
2083 		    lifr.lifr_name, addrstr4, buffer);
2084 	}
2085 
2086 	(void) close(s);
2087 	return (Z_OK);
2088 bad:
2089 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2090 	(void) close(s);
2091 	return (-1);
2092 }
2093 
2094 /*
2095  * Sets up network interfaces based on information from the zone configuration.
2096  * An IPv4 loopback interface is set up "for free", modeling the global system.
2097  * If any of the configuration interfaces were IPv6, then an IPv6 loopback
2098  * address is set up as well.
2099  *
2100  * If anything goes wrong, we log a general error message, attempt to tear down
2101  * whatever we set up, and return an error.
2102  */
2103 static int
2104 configure_network_interfaces(zlog_t *zlogp)
2105 {
2106 	zone_dochandle_t handle;
2107 	struct zone_nwiftab nwiftab, loopback_iftab;
2108 	boolean_t saw_v6 = B_FALSE;
2109 	boolean_t mcast_rt_v4_set = B_FALSE;
2110 	boolean_t mcast_rt_v6_set = B_FALSE;
2111 	zoneid_t zoneid;
2112 
2113 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2114 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2115 		return (-1);
2116 	}
2117 
2118 	if ((handle = zonecfg_init_handle()) == NULL) {
2119 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2120 		return (-1);
2121 	}
2122 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2123 		zerror(zlogp, B_FALSE, "invalid configuration");
2124 		zonecfg_fini_handle(handle);
2125 		return (-1);
2126 	}
2127 	if (zonecfg_setnwifent(handle) == Z_OK) {
2128 		for (;;) {
2129 			struct in6_addr in6;
2130 
2131 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2132 				break;
2133 			if (configure_one_interface(zlogp, zoneid,
2134 			    &nwiftab, &mcast_rt_v4_set, &mcast_rt_v6_set) !=
2135 			    Z_OK) {
2136 				(void) zonecfg_endnwifent(handle);
2137 				zonecfg_fini_handle(handle);
2138 				return (-1);
2139 			}
2140 			if (inet_pton(AF_INET6, nwiftab.zone_nwif_address,
2141 			    &in6) == 1)
2142 				saw_v6 = B_TRUE;
2143 		}
2144 		(void) zonecfg_endnwifent(handle);
2145 	}
2146 	zonecfg_fini_handle(handle);
2147 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2148 	    sizeof (loopback_iftab.zone_nwif_physical));
2149 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2150 	    sizeof (loopback_iftab.zone_nwif_address));
2151 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab, NULL, NULL)
2152 	    != Z_OK) {
2153 		return (-1);
2154 	}
2155 	if (saw_v6) {
2156 		(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2157 		    sizeof (loopback_iftab.zone_nwif_address));
2158 		if (configure_one_interface(zlogp, zoneid,
2159 		    &loopback_iftab, NULL, NULL) != Z_OK) {
2160 			return (-1);
2161 		}
2162 	}
2163 	return (0);
2164 }
2165 
2166 static int
2167 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2168     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2169 {
2170 	int fd;
2171 	struct strioctl ioc;
2172 	tcp_ioc_abort_conn_t conn;
2173 	int error;
2174 
2175 	conn.ac_local = *local;
2176 	conn.ac_remote = *remote;
2177 	conn.ac_start = TCPS_SYN_SENT;
2178 	conn.ac_end = TCPS_TIME_WAIT;
2179 	conn.ac_zoneid = zoneid;
2180 
2181 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2182 	ioc.ic_timout = -1; /* infinite timeout */
2183 	ioc.ic_len = sizeof (conn);
2184 	ioc.ic_dp = (char *)&conn;
2185 
2186 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2187 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2188 		return (-1);
2189 	}
2190 
2191 	error = ioctl(fd, I_STR, &ioc);
2192 	(void) close(fd);
2193 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2194 		return (0);
2195 	return (-1);
2196 }
2197 
2198 static int
2199 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2200 {
2201 	struct sockaddr_storage l, r;
2202 	struct sockaddr_in *local, *remote;
2203 	struct sockaddr_in6 *local6, *remote6;
2204 	int error;
2205 
2206 	/*
2207 	 * Abort IPv4 connections.
2208 	 */
2209 	bzero(&l, sizeof (*local));
2210 	local = (struct sockaddr_in *)&l;
2211 	local->sin_family = AF_INET;
2212 	local->sin_addr.s_addr = INADDR_ANY;
2213 	local->sin_port = 0;
2214 
2215 	bzero(&r, sizeof (*remote));
2216 	remote = (struct sockaddr_in *)&r;
2217 	remote->sin_family = AF_INET;
2218 	remote->sin_addr.s_addr = INADDR_ANY;
2219 	remote->sin_port = 0;
2220 
2221 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2222 		return (error);
2223 
2224 	/*
2225 	 * Abort IPv6 connections.
2226 	 */
2227 	bzero(&l, sizeof (*local6));
2228 	local6 = (struct sockaddr_in6 *)&l;
2229 	local6->sin6_family = AF_INET6;
2230 	local6->sin6_port = 0;
2231 	local6->sin6_addr = in6addr_any;
2232 
2233 	bzero(&r, sizeof (*remote6));
2234 	remote6 = (struct sockaddr_in6 *)&r;
2235 	remote6->sin6_family = AF_INET6;
2236 	remote6->sin6_port = 0;
2237 	remote6->sin6_addr = in6addr_any;
2238 
2239 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2240 		return (error);
2241 	return (0);
2242 }
2243 
2244 static int
2245 devfsadm_call(zlog_t *zlogp, const char *arg)
2246 {
2247 	char *argv[4];
2248 	int status;
2249 
2250 	argv[0] = DEVFSADM;
2251 	argv[1] = (char *)arg;
2252 	argv[2] = zone_name;
2253 	argv[3] = NULL;
2254 	status = forkexec(zlogp, DEVFSADM_PATH, argv);
2255 	if (status == 0 || status == -1)
2256 		return (status);
2257 	zerror(zlogp, B_FALSE, "%s call (%s %s %s) unexpectedly returned %d",
2258 	    DEVFSADM, DEVFSADM_PATH, arg, zone_name, status);
2259 	return (-1);
2260 }
2261 
2262 static int
2263 devfsadm_register(zlog_t *zlogp)
2264 {
2265 	/*
2266 	 * Ready the zone's devices.
2267 	 */
2268 	return (devfsadm_call(zlogp, "-z"));
2269 }
2270 
2271 static int
2272 devfsadm_unregister(zlog_t *zlogp)
2273 {
2274 	return (devfsadm_call(zlogp, "-Z"));
2275 }
2276 
2277 static int
2278 get_privset(zlog_t *zlogp, priv_set_t *privs, boolean_t mount_cmd)
2279 {
2280 	int error = -1;
2281 	zone_dochandle_t handle;
2282 	char *privname = NULL;
2283 
2284 	if (mount_cmd) {
2285 		if (zonecfg_default_privset(privs) == Z_OK)
2286 			return (0);
2287 		zerror(zlogp, B_FALSE,
2288 		    "failed to determine the zone's default privilege set");
2289 		return (-1);
2290 	}
2291 
2292 	if ((handle = zonecfg_init_handle()) == NULL) {
2293 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2294 		return (-1);
2295 	}
2296 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2297 		zerror(zlogp, B_FALSE, "invalid configuration");
2298 		zonecfg_fini_handle(handle);
2299 		return (-1);
2300 	}
2301 
2302 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2303 	case Z_OK:
2304 		error = 0;
2305 		break;
2306 	case Z_PRIV_PROHIBITED:
2307 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2308 		    "within the zone's privilege set", privname);
2309 		break;
2310 	case Z_PRIV_REQUIRED:
2311 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2312 		    "from the zone's privilege set", privname);
2313 		break;
2314 	case Z_PRIV_UNKNOWN:
2315 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2316 		    "in the zone's privilege set", privname);
2317 		break;
2318 	default:
2319 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2320 		    "privilege set");
2321 		break;
2322 	}
2323 
2324 	free(privname);
2325 	zonecfg_fini_handle(handle);
2326 	return (error);
2327 }
2328 
2329 static int
2330 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2331 {
2332 	nvlist_t *nvl = NULL;
2333 	char *nvl_packed = NULL;
2334 	size_t nvl_size = 0;
2335 	nvlist_t **nvlv = NULL;
2336 	int rctlcount = 0;
2337 	int error = -1;
2338 	zone_dochandle_t handle;
2339 	struct zone_rctltab rctltab;
2340 	rctlblk_t *rctlblk = NULL;
2341 
2342 	*bufp = NULL;
2343 	*bufsizep = 0;
2344 
2345 	if ((handle = zonecfg_init_handle()) == NULL) {
2346 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2347 		return (-1);
2348 	}
2349 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2350 		zerror(zlogp, B_FALSE, "invalid configuration");
2351 		zonecfg_fini_handle(handle);
2352 		return (-1);
2353 	}
2354 
2355 	rctltab.zone_rctl_valptr = NULL;
2356 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2357 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2358 		goto out;
2359 	}
2360 
2361 	if (zonecfg_setrctlent(handle) != Z_OK) {
2362 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2363 		goto out;
2364 	}
2365 
2366 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2367 		zerror(zlogp, B_TRUE, "memory allocation failed");
2368 		goto out;
2369 	}
2370 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2371 		struct zone_rctlvaltab *rctlval;
2372 		uint_t i, count;
2373 		const char *name = rctltab.zone_rctl_name;
2374 
2375 		/* zoneadm should have already warned about unknown rctls. */
2376 		if (!zonecfg_is_rctl(name)) {
2377 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2378 			rctltab.zone_rctl_valptr = NULL;
2379 			continue;
2380 		}
2381 		count = 0;
2382 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2383 		    rctlval = rctlval->zone_rctlval_next) {
2384 			count++;
2385 		}
2386 		if (count == 0) {	/* ignore */
2387 			continue;	/* Nothing to free */
2388 		}
2389 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2390 			goto out;
2391 		i = 0;
2392 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2393 		    rctlval = rctlval->zone_rctlval_next, i++) {
2394 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2395 				zerror(zlogp, B_TRUE, "%s failed",
2396 				    "nvlist_alloc");
2397 				goto out;
2398 			}
2399 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2400 			    != Z_OK) {
2401 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2402 				    "(priv=%s,limit=%s,action=%s)",
2403 				    rctlval->zone_rctlval_priv,
2404 				    rctlval->zone_rctlval_limit,
2405 				    rctlval->zone_rctlval_action);
2406 				goto out;
2407 			}
2408 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2409 				zerror(zlogp, B_FALSE,
2410 				    "(priv=%s,limit=%s,action=%s) is not a "
2411 				    "valid value for rctl '%s'",
2412 				    rctlval->zone_rctlval_priv,
2413 				    rctlval->zone_rctlval_limit,
2414 				    rctlval->zone_rctlval_action,
2415 				    name);
2416 				goto out;
2417 			}
2418 			if (nvlist_add_uint64(nvlv[i], "privilege",
2419 			    rctlblk_get_privilege(rctlblk)) != 0) {
2420 				zerror(zlogp, B_FALSE, "%s failed",
2421 				    "nvlist_add_uint64");
2422 				goto out;
2423 			}
2424 			if (nvlist_add_uint64(nvlv[i], "limit",
2425 			    rctlblk_get_value(rctlblk)) != 0) {
2426 				zerror(zlogp, B_FALSE, "%s failed",
2427 				    "nvlist_add_uint64");
2428 				goto out;
2429 			}
2430 			if (nvlist_add_uint64(nvlv[i], "action",
2431 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
2432 			    != 0) {
2433 				zerror(zlogp, B_FALSE, "%s failed",
2434 				    "nvlist_add_uint64");
2435 				goto out;
2436 			}
2437 		}
2438 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2439 		rctltab.zone_rctl_valptr = NULL;
2440 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
2441 		    != 0) {
2442 			zerror(zlogp, B_FALSE, "%s failed",
2443 			    "nvlist_add_nvlist_array");
2444 			goto out;
2445 		}
2446 		for (i = 0; i < count; i++)
2447 			nvlist_free(nvlv[i]);
2448 		free(nvlv);
2449 		nvlv = NULL;
2450 		rctlcount++;
2451 	}
2452 	(void) zonecfg_endrctlent(handle);
2453 
2454 	if (rctlcount == 0) {
2455 		error = 0;
2456 		goto out;
2457 	}
2458 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
2459 	    != 0) {
2460 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
2461 		goto out;
2462 	}
2463 
2464 	error = 0;
2465 	*bufp = nvl_packed;
2466 	*bufsizep = nvl_size;
2467 
2468 out:
2469 	free(rctlblk);
2470 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2471 	if (error && nvl_packed != NULL)
2472 		free(nvl_packed);
2473 	if (nvl != NULL)
2474 		nvlist_free(nvl);
2475 	if (nvlv != NULL)
2476 		free(nvlv);
2477 	if (handle != NULL)
2478 		zonecfg_fini_handle(handle);
2479 	return (error);
2480 }
2481 
2482 static int
2483 get_zone_pool(zlog_t *zlogp, char *poolbuf, size_t bufsz)
2484 {
2485 	zone_dochandle_t handle;
2486 	int error;
2487 
2488 	if ((handle = zonecfg_init_handle()) == NULL) {
2489 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2490 		return (Z_NOMEM);
2491 	}
2492 	error = zonecfg_get_snapshot_handle(zone_name, handle);
2493 	if (error != Z_OK) {
2494 		zerror(zlogp, B_FALSE, "invalid configuration");
2495 		zonecfg_fini_handle(handle);
2496 		return (error);
2497 	}
2498 	error = zonecfg_get_pool(handle, poolbuf, bufsz);
2499 	zonecfg_fini_handle(handle);
2500 	return (error);
2501 }
2502 
2503 static int
2504 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2505 {
2506 	zone_dochandle_t handle;
2507 	struct zone_dstab dstab;
2508 	size_t total, offset, len;
2509 	int error = -1;
2510 	char *str;
2511 
2512 	*bufp = NULL;
2513 	*bufsizep = 0;
2514 
2515 	if ((handle = zonecfg_init_handle()) == NULL) {
2516 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2517 		return (-1);
2518 	}
2519 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2520 		zerror(zlogp, B_FALSE, "invalid configuration");
2521 		zonecfg_fini_handle(handle);
2522 		return (-1);
2523 	}
2524 
2525 	if (zonecfg_setdsent(handle) != Z_OK) {
2526 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
2527 		goto out;
2528 	}
2529 
2530 	total = 0;
2531 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
2532 		total += strlen(dstab.zone_dataset_name) + 1;
2533 	(void) zonecfg_enddsent(handle);
2534 
2535 	if (total == 0) {
2536 		error = 0;
2537 		goto out;
2538 	}
2539 
2540 	if ((str = malloc(total)) == NULL) {
2541 		zerror(zlogp, B_TRUE, "memory allocation failed");
2542 		goto out;
2543 	}
2544 
2545 	if (zonecfg_setdsent(handle) != Z_OK) {
2546 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
2547 		goto out;
2548 	}
2549 	offset = 0;
2550 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2551 		len = strlen(dstab.zone_dataset_name);
2552 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
2553 		    sizeof (dstab.zone_dataset_name) - offset);
2554 		offset += len;
2555 		if (offset != total - 1)
2556 			str[offset++] = ',';
2557 	}
2558 	(void) zonecfg_enddsent(handle);
2559 
2560 	error = 0;
2561 	*bufp = str;
2562 	*bufsizep = total;
2563 
2564 out:
2565 	if (error != 0 && str != NULL)
2566 		free(str);
2567 	if (handle != NULL)
2568 		zonecfg_fini_handle(handle);
2569 
2570 	return (error);
2571 }
2572 
2573 /* ARGSUSED */
2574 static void
2575 zfs_error_handler(const char *fmt, va_list ap)
2576 {
2577 	/*
2578 	 * Do nothing - we interpret the failures from each libzfs call below.
2579 	 */
2580 }
2581 
2582 static int
2583 validate_datasets(zlog_t *zlogp)
2584 {
2585 	zone_dochandle_t handle;
2586 	struct zone_dstab dstab;
2587 	zfs_handle_t *zhp;
2588 
2589 	if ((handle = zonecfg_init_handle()) == NULL) {
2590 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2591 		return (-1);
2592 	}
2593 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2594 		zerror(zlogp, B_FALSE, "invalid configuration");
2595 		zonecfg_fini_handle(handle);
2596 		return (-1);
2597 	}
2598 
2599 	if (zonecfg_setdsent(handle) != Z_OK) {
2600 		zerror(zlogp, B_FALSE, "invalid configuration");
2601 		zonecfg_fini_handle(handle);
2602 		return (-1);
2603 	}
2604 
2605 	zfs_set_error_handler(zfs_error_handler);
2606 
2607 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2608 
2609 		if ((zhp = zfs_open(dstab.zone_dataset_name,
2610 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
2611 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
2612 			    dstab.zone_dataset_name);
2613 			zonecfg_fini_handle(handle);
2614 			return (-1);
2615 		}
2616 
2617 		/*
2618 		 * Automatically set the 'zoned' property.  We check the value
2619 		 * first because we'll get EPERM if it is already set.
2620 		 */
2621 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
2622 		    zfs_prop_set(zhp, ZFS_PROP_ZONED, "on") != 0) {
2623 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
2624 			    "property for ZFS dataset '%s'\n",
2625 			    dstab.zone_dataset_name);
2626 			zonecfg_fini_handle(handle);
2627 			zfs_close(zhp);
2628 			return (-1);
2629 		}
2630 
2631 		zfs_close(zhp);
2632 	}
2633 	(void) zonecfg_enddsent(handle);
2634 
2635 	zonecfg_fini_handle(handle);
2636 
2637 	return (0);
2638 }
2639 
2640 static int
2641 bind_to_pool(zlog_t *zlogp, zoneid_t zoneid)
2642 {
2643 	pool_conf_t *poolconf;
2644 	pool_t *pool;
2645 	char poolname[MAXPATHLEN];
2646 	int status;
2647 	int error;
2648 
2649 	/*
2650 	 * Find the pool mentioned in the zone configuration, and bind to it.
2651 	 */
2652 	error = get_zone_pool(zlogp, poolname, sizeof (poolname));
2653 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
2654 		/*
2655 		 * The property is not set on the zone, so the pool
2656 		 * should be bound to the default pool.  But that's
2657 		 * already done by the kernel, so we can just return.
2658 		 */
2659 		return (0);
2660 	}
2661 	if (error != Z_OK) {
2662 		/*
2663 		 * Not an error, even though it shouldn't be happening.
2664 		 */
2665 		zerror(zlogp, B_FALSE,
2666 		    "WARNING: unable to retrieve default pool.");
2667 		return (0);
2668 	}
2669 	/*
2670 	 * Don't do anything if pools aren't enabled.
2671 	 */
2672 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
2673 		zerror(zlogp, B_FALSE, "WARNING: pools facility not active; "
2674 		    "zone will not be bound to pool '%s'.", poolname);
2675 		return (0);
2676 	}
2677 	/*
2678 	 * Try to provide a sane error message if the requested pool doesn't
2679 	 * exist.
2680 	 */
2681 	if ((poolconf = pool_conf_alloc()) == NULL) {
2682 		zerror(zlogp, B_FALSE, "%s failed", "pool_conf_alloc");
2683 		return (-1);
2684 	}
2685 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
2686 	    PO_SUCCESS) {
2687 		zerror(zlogp, B_FALSE, "%s failed", "pool_conf_open");
2688 		pool_conf_free(poolconf);
2689 		return (-1);
2690 	}
2691 	pool = pool_get_pool(poolconf, poolname);
2692 	(void) pool_conf_close(poolconf);
2693 	pool_conf_free(poolconf);
2694 	if (pool == NULL) {
2695 		zerror(zlogp, B_FALSE, "WARNING: pool '%s' not found; "
2696 		    "using default pool.", poolname);
2697 		return (0);
2698 	}
2699 	/*
2700 	 * Bind the zone to the pool.
2701 	 */
2702 	if (pool_set_binding(poolname, P_ZONEID, zoneid) != PO_SUCCESS) {
2703 		zerror(zlogp, B_FALSE, "WARNING: unable to bind to pool '%s'; "
2704 		    "using default pool.", poolname);
2705 	}
2706 	return (0);
2707 }
2708 
2709 int
2710 prtmount(const char *fs, void *x) {
2711 	zerror((zlog_t *)x, B_FALSE, "  %s", fs);
2712 	return (0);
2713 }
2714 
2715 /*
2716  * Look for zones running on the main system that are using this root (or any
2717  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
2718  * is found or if we can't tell.
2719  */
2720 static boolean_t
2721 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
2722 {
2723 	zoneid_t *zids = NULL;
2724 	uint_t nzids = 0;
2725 	boolean_t retv;
2726 	int rlen, zlen;
2727 	char zroot[MAXPATHLEN];
2728 	char zonename[ZONENAME_MAX];
2729 
2730 	for (;;) {
2731 		nzids += 10;
2732 		zids = malloc(nzids * sizeof (*zids));
2733 		if (zids == NULL) {
2734 			zerror(zlogp, B_TRUE, "unable to allocate memory");
2735 			return (B_TRUE);
2736 		}
2737 		if (zone_list(zids, &nzids) == 0)
2738 			break;
2739 		free(zids);
2740 	}
2741 	retv = B_FALSE;
2742 	rlen = strlen(rootpath);
2743 	while (nzids > 0) {
2744 		/*
2745 		 * Ignore errors; they just mean that the zone has disappeared
2746 		 * while we were busy.
2747 		 */
2748 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
2749 		    sizeof (zroot)) == -1)
2750 			continue;
2751 		zlen = strlen(zroot);
2752 		if (zlen > rlen)
2753 			zlen = rlen;
2754 		if (strncmp(rootpath, zroot, zlen) == 0 &&
2755 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
2756 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
2757 			if (getzonenamebyid(zids[nzids], zonename,
2758 			    sizeof (zonename)) == -1)
2759 				(void) snprintf(zonename, sizeof (zonename),
2760 				    "id %d", (int)zids[nzids]);
2761 			zerror(zlogp, B_FALSE,
2762 			    "zone root %s already in use by zone %s",
2763 			    rootpath, zonename);
2764 			retv = B_TRUE;
2765 			break;
2766 		}
2767 	}
2768 	free(zids);
2769 	return (retv);
2770 }
2771 
2772 /*
2773  * Search for loopback mounts that use this same source node (same device and
2774  * inode).  Return B_TRUE if there is one or if we can't tell.
2775  */
2776 static boolean_t
2777 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
2778 {
2779 	struct stat64 rst, zst;
2780 	struct mnttab *mnp;
2781 
2782 	if (stat64(rootpath, &rst) == -1) {
2783 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
2784 		return (B_TRUE);
2785 	}
2786 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
2787 		return (B_TRUE);
2788 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
2789 		if (mnp->mnt_fstype == NULL ||
2790 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
2791 			continue;
2792 		/* We're looking at a loopback mount.  Stat it. */
2793 		if (mnp->mnt_special != NULL &&
2794 		    stat64(mnp->mnt_special, &zst) != -1 &&
2795 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
2796 			zerror(zlogp, B_FALSE,
2797 			    "zone root %s is reachable through %s",
2798 			    rootpath, mnp->mnt_mountp);
2799 			return (B_TRUE);
2800 		}
2801 	}
2802 	return (B_FALSE);
2803 }
2804 
2805 zoneid_t
2806 vplat_create(zlog_t *zlogp, boolean_t mount_cmd)
2807 {
2808 	zoneid_t rval = -1;
2809 	priv_set_t *privs;
2810 	char rootpath[MAXPATHLEN];
2811 	char *rctlbuf = NULL;
2812 	size_t rctlbufsz = 0;
2813 	char *zfsbuf = NULL;
2814 	size_t zfsbufsz = 0;
2815 	zoneid_t zoneid = -1;
2816 	int xerr;
2817 	char *kzone;
2818 	FILE *fp = NULL;
2819 
2820 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
2821 		zerror(zlogp, B_TRUE, "unable to determine zone root");
2822 		return (-1);
2823 	}
2824 	if (zonecfg_in_alt_root())
2825 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
2826 
2827 	if ((privs = priv_allocset()) == NULL) {
2828 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
2829 		return (-1);
2830 	}
2831 	priv_emptyset(privs);
2832 	if (get_privset(zlogp, privs, mount_cmd) != 0)
2833 		goto error;
2834 
2835 	if (!mount_cmd && get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
2836 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
2837 		goto error;
2838 	}
2839 
2840 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
2841 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
2842 		goto error;
2843 	}
2844 
2845 	kzone = zone_name;
2846 
2847 	/*
2848 	 * We must do this scan twice.  First, we look for zones running on the
2849 	 * main system that are using this root (or any subdirectory of it).
2850 	 * Next, we reduce to the shortest path and search for loopback mounts
2851 	 * that use this same source node (same device and inode).
2852 	 */
2853 	if (duplicate_zone_root(zlogp, rootpath))
2854 		goto error;
2855 	if (duplicate_reachable_path(zlogp, rootpath))
2856 		goto error;
2857 
2858 	if (mount_cmd) {
2859 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
2860 
2861 		/*
2862 		 * Forge up a special root for this zone.  When a zone is
2863 		 * mounted, we can't let the zone have its own root because the
2864 		 * tools that will be used in this "scratch zone" need access
2865 		 * to both the zone's resources and the running machine's
2866 		 * executables.
2867 		 *
2868 		 * Note that the mkdir here also catches read-only filesystems.
2869 		 */
2870 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
2871 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
2872 			goto error;
2873 		}
2874 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
2875 			goto error;
2876 	}
2877 
2878 	if (zonecfg_in_alt_root()) {
2879 		/*
2880 		 * If we are mounting up a zone in an alternate root partition,
2881 		 * then we have some additional work to do before starting the
2882 		 * zone.  First, resolve the root path down so that we're not
2883 		 * fooled by duplicates.  Then forge up an internal name for
2884 		 * the zone.
2885 		 */
2886 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
2887 			zerror(zlogp, B_TRUE, "cannot open mapfile");
2888 			goto error;
2889 		}
2890 		if (zonecfg_lock_scratch(fp) != 0) {
2891 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
2892 			goto error;
2893 		}
2894 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
2895 		    NULL, 0) == 0) {
2896 			zerror(zlogp, B_FALSE, "scratch zone already running");
2897 			goto error;
2898 		}
2899 		/* This is the preferred name */
2900 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
2901 		    zone_name);
2902 		srandom(getpid());
2903 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
2904 		    0) == 0) {
2905 			/* This is just an arbitrary name; note "." usage */
2906 			(void) snprintf(kernzone, sizeof (kernzone),
2907 			    "SUNWlu.%08lX%08lX", random(), random());
2908 		}
2909 		kzone = kernzone;
2910 	}
2911 
2912 	xerr = 0;
2913 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
2914 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr)) == -1) {
2915 		if (xerr == ZE_AREMOUNTS) {
2916 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
2917 				zerror(zlogp, B_FALSE,
2918 				    "An unknown file-system is mounted on "
2919 				    "a subdirectory of %s", rootpath);
2920 			} else {
2921 
2922 				zerror(zlogp, B_FALSE,
2923 				    "These file-systems are mounted on "
2924 				    "subdirectories of %s:", rootpath);
2925 				(void) zonecfg_find_mounts(rootpath,
2926 				    prtmount, zlogp);
2927 			}
2928 		} else if (xerr == ZE_CHROOTED) {
2929 			zerror(zlogp, B_FALSE, "%s: "
2930 			    "cannot create a zone from a chrooted "
2931 			    "environment", "zone_create");
2932 		} else {
2933 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
2934 		}
2935 		goto error;
2936 	}
2937 
2938 	if (zonecfg_in_alt_root() &&
2939 	    zonecfg_add_scratch(fp, zone_name, kernzone,
2940 	    zonecfg_get_root()) == -1) {
2941 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
2942 		goto error;
2943 	}
2944 
2945 	/*
2946 	 * The following is a warning, not an error, and is not performed when
2947 	 * merely mounting a zone for administrative use.
2948 	 */
2949 	if (!mount_cmd && bind_to_pool(zlogp, zoneid) != 0)
2950 		zerror(zlogp, B_FALSE, "WARNING: unable to bind zone to "
2951 		    "requested pool; using default pool.");
2952 	rval = zoneid;
2953 	zoneid = -1;
2954 
2955 error:
2956 	if (zoneid != -1)
2957 		(void) zone_destroy(zoneid);
2958 	if (rctlbuf != NULL)
2959 		free(rctlbuf);
2960 	priv_freeset(privs);
2961 	if (fp != NULL)
2962 		zonecfg_close_scratch(fp);
2963 	lofs_discard_mnttab();
2964 	return (rval);
2965 }
2966 
2967 int
2968 vplat_bringup(zlog_t *zlogp, boolean_t mount_cmd)
2969 {
2970 	if (!mount_cmd && validate_datasets(zlogp) != 0) {
2971 		lofs_discard_mnttab();
2972 		return (-1);
2973 	}
2974 
2975 	if (create_dev_files(zlogp) != 0 ||
2976 	    mount_filesystems(zlogp, mount_cmd) != 0) {
2977 		lofs_discard_mnttab();
2978 		return (-1);
2979 	}
2980 	if (!mount_cmd && (devfsadm_register(zlogp) != 0 ||
2981 	    configure_network_interfaces(zlogp) != 0)) {
2982 		lofs_discard_mnttab();
2983 		return (-1);
2984 	}
2985 	lofs_discard_mnttab();
2986 	return (0);
2987 }
2988 
2989 static int
2990 lu_root_teardown(zlog_t *zlogp)
2991 {
2992 	char zroot[MAXPATHLEN];
2993 
2994 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
2995 		zerror(zlogp, B_FALSE, "unable to determine zone root");
2996 		return (-1);
2997 	}
2998 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
2999 
3000 	/*
3001 	 * At this point, the processes are gone, the filesystems (save the
3002 	 * root) are unmounted, and the zone is on death row.  But there may
3003 	 * still be creds floating about in the system that reference the
3004 	 * zone_t, and which pin down zone_rootvp causing this call to fail
3005 	 * with EBUSY.  Thus, we try for a little while before just giving up.
3006 	 * (How I wish this were not true, and umount2 just did the right
3007 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
3008 	 */
3009 	if (umount2(zroot, MS_FORCE) != 0) {
3010 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
3011 			goto unmounted;
3012 		if (errno == EBUSY) {
3013 			int tries = 10;
3014 
3015 			while (--tries >= 0) {
3016 				(void) sleep(1);
3017 				if (umount2(zroot, 0) == 0)
3018 					goto unmounted;
3019 				if (errno != EBUSY)
3020 					break;
3021 			}
3022 		}
3023 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
3024 		return (-1);
3025 	}
3026 unmounted:
3027 
3028 	/*
3029 	 * Only zones in an alternate root environment have scratch zone
3030 	 * entries.
3031 	 */
3032 	if (zonecfg_in_alt_root()) {
3033 		FILE *fp;
3034 		int retv;
3035 
3036 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
3037 			zerror(zlogp, B_TRUE, "cannot open mapfile");
3038 			return (-1);
3039 		}
3040 		retv = -1;
3041 		if (zonecfg_lock_scratch(fp) != 0)
3042 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
3043 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
3044 			zerror(zlogp, B_TRUE, "cannot delete map entry");
3045 		else
3046 			retv = 0;
3047 		zonecfg_close_scratch(fp);
3048 		return (retv);
3049 	} else {
3050 		return (0);
3051 	}
3052 }
3053 
3054 int
3055 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd)
3056 {
3057 	char *kzone;
3058 	zoneid_t zoneid;
3059 
3060 	kzone = zone_name;
3061 	if (zonecfg_in_alt_root()) {
3062 		FILE *fp;
3063 
3064 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
3065 			zerror(zlogp, B_TRUE, "unable to open map file");
3066 			goto error;
3067 		}
3068 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
3069 		    kernzone, sizeof (kernzone)) != 0) {
3070 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
3071 			zonecfg_close_scratch(fp);
3072 			goto error;
3073 		}
3074 		zonecfg_close_scratch(fp);
3075 		kzone = kernzone;
3076 	}
3077 
3078 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
3079 		if (!bringup_failure_recovery)
3080 			zerror(zlogp, B_TRUE, "unable to get zoneid");
3081 		if (unmount_cmd)
3082 			(void) lu_root_teardown(zlogp);
3083 		goto error;
3084 	}
3085 
3086 	if (zone_shutdown(zoneid) != 0) {
3087 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
3088 		goto error;
3089 	}
3090 
3091 	if (!unmount_cmd && devfsadm_unregister(zlogp) != 0)
3092 		goto error;
3093 
3094 	if (!unmount_cmd &&
3095 	    unconfigure_network_interfaces(zlogp, zoneid) != 0) {
3096 		zerror(zlogp, B_FALSE,
3097 		    "unable to unconfigure network interfaces in zone");
3098 		goto error;
3099 	}
3100 
3101 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
3102 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
3103 		goto error;
3104 	}
3105 
3106 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
3107 		zerror(zlogp, B_FALSE,
3108 		    "unable to unmount file systems in zone");
3109 		goto error;
3110 	}
3111 
3112 	if (zone_destroy(zoneid) != 0) {
3113 		zerror(zlogp, B_TRUE, "unable to destroy zone");
3114 		goto error;
3115 	}
3116 
3117 	/*
3118 	 * Special teardown for alternate boot environments: remove the tmpfs
3119 	 * root for the zone and then remove it from the map file.
3120 	 */
3121 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
3122 		goto error;
3123 
3124 	if (!unmount_cmd)
3125 		destroy_console_slave();
3126 
3127 	lofs_discard_mnttab();
3128 	return (0);
3129 
3130 error:
3131 	lofs_discard_mnttab();
3132 	return (-1);
3133 }
3134