xref: /titanic_44/usr/src/cmd/zfs/zfs_main.c (revision b9bc7f7832704fda46b4d6b04f3f7be1227dc644)
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 2007 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 #include <assert.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <libgen.h>
33 #include <libintl.h>
34 #include <libuutil.h>
35 #include <libnvpair.h>
36 #include <locale.h>
37 #include <stddef.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <strings.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <zone.h>
44 #include <sys/mkdev.h>
45 #include <sys/mntent.h>
46 #include <sys/mnttab.h>
47 #include <sys/mount.h>
48 #include <sys/stat.h>
49 #include <sys/avl.h>
50 
51 #include <libzfs.h>
52 #include <libuutil.h>
53 
54 #include "zfs_iter.h"
55 #include "zfs_util.h"
56 
57 libzfs_handle_t *g_zfs;
58 
59 static FILE *mnttab_file;
60 static char history_str[HIS_MAX_RECORD_LEN];
61 
62 static int zfs_do_clone(int argc, char **argv);
63 static int zfs_do_create(int argc, char **argv);
64 static int zfs_do_destroy(int argc, char **argv);
65 static int zfs_do_get(int argc, char **argv);
66 static int zfs_do_inherit(int argc, char **argv);
67 static int zfs_do_list(int argc, char **argv);
68 static int zfs_do_mount(int argc, char **argv);
69 static int zfs_do_rename(int argc, char **argv);
70 static int zfs_do_rollback(int argc, char **argv);
71 static int zfs_do_set(int argc, char **argv);
72 static int zfs_do_upgrade(int argc, char **argv);
73 static int zfs_do_snapshot(int argc, char **argv);
74 static int zfs_do_unmount(int argc, char **argv);
75 static int zfs_do_share(int argc, char **argv);
76 static int zfs_do_unshare(int argc, char **argv);
77 static int zfs_do_send(int argc, char **argv);
78 static int zfs_do_receive(int argc, char **argv);
79 static int zfs_do_promote(int argc, char **argv);
80 static int zfs_do_allow(int argc, char **argv);
81 static int zfs_do_unallow(int argc, char **argv);
82 
83 /*
84  * These libumem hooks provide a reasonable set of defaults for the allocator's
85  * debugging facilities.
86  */
87 const char *
88 _umem_debug_init(void)
89 {
90 	return ("default,verbose"); /* $UMEM_DEBUG setting */
91 }
92 
93 const char *
94 _umem_logging_init(void)
95 {
96 	return ("fail,contents"); /* $UMEM_LOGGING setting */
97 }
98 
99 typedef enum {
100 	HELP_CLONE,
101 	HELP_CREATE,
102 	HELP_DESTROY,
103 	HELP_GET,
104 	HELP_INHERIT,
105 	HELP_UPGRADE,
106 	HELP_LIST,
107 	HELP_MOUNT,
108 	HELP_PROMOTE,
109 	HELP_RECEIVE,
110 	HELP_RENAME,
111 	HELP_ROLLBACK,
112 	HELP_SEND,
113 	HELP_SET,
114 	HELP_SHARE,
115 	HELP_SNAPSHOT,
116 	HELP_UNMOUNT,
117 	HELP_UNSHARE,
118 	HELP_ALLOW,
119 	HELP_UNALLOW
120 } zfs_help_t;
121 
122 typedef struct zfs_command {
123 	const char	*name;
124 	int		(*func)(int argc, char **argv);
125 	zfs_help_t	usage;
126 } zfs_command_t;
127 
128 /*
129  * Master command table.  Each ZFS command has a name, associated function, and
130  * usage message.  The usage messages need to be internationalized, so we have
131  * to have a function to return the usage message based on a command index.
132  *
133  * These commands are organized according to how they are displayed in the usage
134  * message.  An empty command (one with a NULL name) indicates an empty line in
135  * the generic usage message.
136  */
137 static zfs_command_t command_table[] = {
138 	{ "create",	zfs_do_create,		HELP_CREATE		},
139 	{ "destroy",	zfs_do_destroy,		HELP_DESTROY		},
140 	{ NULL },
141 	{ "snapshot",	zfs_do_snapshot,	HELP_SNAPSHOT		},
142 	{ "rollback",	zfs_do_rollback,	HELP_ROLLBACK		},
143 	{ "clone",	zfs_do_clone,		HELP_CLONE		},
144 	{ "promote",	zfs_do_promote,		HELP_PROMOTE		},
145 	{ "rename",	zfs_do_rename,		HELP_RENAME		},
146 	{ NULL },
147 	{ "list",	zfs_do_list,		HELP_LIST		},
148 	{ NULL },
149 	{ "set",	zfs_do_set,		HELP_SET		},
150 	{ "get", 	zfs_do_get,		HELP_GET		},
151 	{ "inherit",	zfs_do_inherit,		HELP_INHERIT		},
152 	{ "upgrade",	zfs_do_upgrade,		HELP_UPGRADE		},
153 	{ NULL },
154 	{ "mount",	zfs_do_mount,		HELP_MOUNT		},
155 	{ "unmount",	zfs_do_unmount,		HELP_UNMOUNT		},
156 	{ "share",	zfs_do_share,		HELP_SHARE		},
157 	{ "unshare",	zfs_do_unshare,		HELP_UNSHARE		},
158 	{ NULL },
159 	{ "send",	zfs_do_send,		HELP_SEND		},
160 	{ "receive",	zfs_do_receive,		HELP_RECEIVE		},
161 	{ NULL },
162 	{ "allow",	zfs_do_allow,		HELP_ALLOW		},
163 	{ NULL },
164 	{ "unallow",	zfs_do_unallow,		HELP_UNALLOW		},
165 };
166 
167 #define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
168 
169 zfs_command_t *current_command;
170 
171 static const char *
172 get_usage(zfs_help_t idx)
173 {
174 	switch (idx) {
175 	case HELP_CLONE:
176 		return (gettext("\tclone [-p] <snapshot> "
177 		    "<filesystem|volume>\n"));
178 	case HELP_CREATE:
179 		return (gettext("\tcreate [-p] [-o property=value] ... "
180 		    "<filesystem>\n"
181 		    "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
182 		    "-V <size> <volume>\n"));
183 	case HELP_DESTROY:
184 		return (gettext("\tdestroy [-rRf] "
185 		    "<filesystem|volume|snapshot>\n"));
186 	case HELP_GET:
187 		return (gettext("\tget [-rHp] [-o field[,...]] "
188 		    "[-s source[,...]]\n"
189 		    "\t    <\"all\" | property[,...]> "
190 		    "[filesystem|volume|snapshot] ...\n"));
191 	case HELP_INHERIT:
192 		return (gettext("\tinherit [-r] <property> "
193 		    "<filesystem|volume> ...\n"));
194 	case HELP_UPGRADE:
195 		return (gettext("\tupgrade [-v]\n"
196 		    "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
197 	case HELP_LIST:
198 		return (gettext("\tlist [-rH] [-o property[,...]] "
199 		    "[-t type[,...]] [-s property] ...\n"
200 		    "\t    [-S property] ... "
201 		    "[filesystem|volume|snapshot] ...\n"));
202 	case HELP_MOUNT:
203 		return (gettext("\tmount\n"
204 		    "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
205 	case HELP_PROMOTE:
206 		return (gettext("\tpromote <clone-filesystem>\n"));
207 	case HELP_RECEIVE:
208 		return (gettext("\treceive [-vnF] <filesystem|volume|"
209 		"snapshot>\n"
210 		"\treceive [-vnF] -d <filesystem>\n"));
211 	case HELP_RENAME:
212 		return (gettext("\trename <filesystem|volume|snapshot> "
213 		    "<filesystem|volume|snapshot>\n"
214 		    "\trename -p <filesystem|volume> <filesystem|volume>\n"
215 		    "\trename -r <snapshot> <snapshot>"));
216 	case HELP_ROLLBACK:
217 		return (gettext("\trollback [-rR] <snapshot>\n"));
218 	case HELP_SEND:
219 		return (gettext("\tsend [-R] [-[iI] snapshot] <snapshot>\n"));
220 	case HELP_SET:
221 		return (gettext("\tset <property=value> "
222 		    "<filesystem|volume> ...\n"));
223 	case HELP_SHARE:
224 		return (gettext("\tshare <-a | filesystem>\n"));
225 	case HELP_SNAPSHOT:
226 		return (gettext("\tsnapshot [-r] "
227 		    "<filesystem@snapname|volume@snapname>\n"));
228 	case HELP_UNMOUNT:
229 		return (gettext("\tunmount [-f] "
230 		    "<-a | filesystem|mountpoint>\n"));
231 	case HELP_UNSHARE:
232 		return (gettext("\tunshare [-f] "
233 		    "<-a | filesystem|mountpoint>\n"));
234 	case HELP_ALLOW:
235 		return (gettext("\tallow [-ldug] "
236 		    "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
237 		    "\t    <filesystem|volume>\n"
238 		    "\tallow [-ld] -e <perm|@setname>[,...] "
239 		    "<filesystem|volume>\n"
240 		    "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
241 		    "\tallow -s @setname <perm|@setname>[,...] "
242 		    "<filesystem|volume>\n"));
243 	case HELP_UNALLOW:
244 		return (gettext("\tunallow [-rldug] "
245 		    "<\"everyone\"|user|group>[,...]\n"
246 		    "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
247 		    "\tunallow [-rld] -e [<perm|@setname>[,...]] "
248 		    "<filesystem|volume>\n"
249 		    "\tunallow [-r] -c [<perm|@setname>[,...]] "
250 		    "<filesystem|volume>\n"
251 		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
252 		    "<filesystem|volume>\n"));
253 	}
254 
255 	abort();
256 	/* NOTREACHED */
257 }
258 
259 /*
260  * Utility function to guarantee malloc() success.
261  */
262 void *
263 safe_malloc(size_t size)
264 {
265 	void *data;
266 
267 	if ((data = calloc(1, size)) == NULL) {
268 		(void) fprintf(stderr, "internal error: out of memory\n");
269 		exit(1);
270 	}
271 
272 	return (data);
273 }
274 
275 /*
276  * Callback routine that will print out information for each of
277  * the properties.
278  */
279 static int
280 usage_prop_cb(int prop, void *cb)
281 {
282 	FILE *fp = cb;
283 
284 	(void) fprintf(fp, "\t%-14s ", zfs_prop_to_name(prop));
285 
286 	if (prop == ZFS_PROP_CASE)
287 		(void) fprintf(fp, "NO    ");
288 	else if (zfs_prop_readonly(prop))
289 		(void) fprintf(fp, "  NO    ");
290 	else
291 		(void) fprintf(fp, " YES    ");
292 
293 	if (zfs_prop_inheritable(prop))
294 		(void) fprintf(fp, "  YES   ");
295 	else
296 		(void) fprintf(fp, "   NO   ");
297 
298 	if (zfs_prop_values(prop) == NULL)
299 		(void) fprintf(fp, "-\n");
300 	else
301 		(void) fprintf(fp, "%s\n", zfs_prop_values(prop));
302 
303 	return (ZPROP_CONT);
304 }
305 
306 /*
307  * Display usage message.  If we're inside a command, display only the usage for
308  * that command.  Otherwise, iterate over the entire command table and display
309  * a complete usage message.
310  */
311 static void
312 usage(boolean_t requested)
313 {
314 	int i;
315 	boolean_t show_properties = B_FALSE;
316 	FILE *fp = requested ? stdout : stderr;
317 
318 	if (current_command == NULL) {
319 
320 		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
321 		(void) fprintf(fp,
322 		    gettext("where 'command' is one of the following:\n\n"));
323 
324 		for (i = 0; i < NCOMMAND; i++) {
325 			if (command_table[i].name == NULL)
326 				(void) fprintf(fp, "\n");
327 			else
328 				(void) fprintf(fp, "%s",
329 				    get_usage(command_table[i].usage));
330 		}
331 
332 		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
333 		    "pool/[dataset/]*dataset[@name]\n"));
334 	} else {
335 		(void) fprintf(fp, gettext("usage:\n"));
336 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
337 	}
338 
339 	if (current_command != NULL &&
340 	    (strcmp(current_command->name, "set") == 0 ||
341 	    strcmp(current_command->name, "get") == 0 ||
342 	    strcmp(current_command->name, "inherit") == 0 ||
343 	    strcmp(current_command->name, "list") == 0))
344 		show_properties = B_TRUE;
345 
346 	if (show_properties) {
347 
348 		(void) fprintf(fp,
349 		    gettext("\nThe following properties are supported:\n"));
350 
351 		(void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
352 		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
353 
354 		/* Iterate over all properties */
355 		(void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
356 		    ZFS_TYPE_DATASET);
357 
358 		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
359 		    "with standard units such as K, M, G, etc.\n"));
360 		(void) fprintf(fp, gettext("\n\nUser-defined properties can "
361 		    "be specified by using a name containing a colon (:).\n"));
362 	} else {
363 		/*
364 		 * TRANSLATION NOTE:
365 		 * "zfs set|get" must not be localised this is the
366 		 * command name and arguments.
367 		 */
368 		(void) fprintf(fp,
369 		    gettext("\nFor the property list, run: zfs set|get\n"));
370 	}
371 
372 	/*
373 	 * See comments at end of main().
374 	 */
375 	if (getenv("ZFS_ABORT") != NULL) {
376 		(void) printf("dumping core by request\n");
377 		abort();
378 	}
379 
380 	exit(requested ? 0 : 2);
381 }
382 
383 /*
384  * zfs clone [-p] <snap> <fs | vol>
385  *
386  * Given an existing dataset, create a writable copy whose initial contents
387  * are the same as the source.  The newly created dataset maintains a
388  * dependency on the original; the original cannot be destroyed so long as
389  * the clone exists.
390  *
391  * The '-p' flag creates all the non-existing ancestors of the target first.
392  */
393 static int
394 zfs_do_clone(int argc, char **argv)
395 {
396 	zfs_handle_t *zhp;
397 	boolean_t parents = B_FALSE;
398 	int ret;
399 	int c;
400 
401 	/* check options */
402 	while ((c = getopt(argc, argv, "p")) != -1) {
403 		switch (c) {
404 		case 'p':
405 			parents = B_TRUE;
406 			break;
407 		case '?':
408 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
409 			    optopt);
410 			usage(B_FALSE);
411 		}
412 	}
413 
414 	argc -= optind;
415 	argv += optind;
416 
417 	/* check number of arguments */
418 	if (argc < 1) {
419 		(void) fprintf(stderr, gettext("missing source dataset "
420 		    "argument\n"));
421 		usage(B_FALSE);
422 	}
423 	if (argc < 2) {
424 		(void) fprintf(stderr, gettext("missing target dataset "
425 		    "argument\n"));
426 		usage(B_FALSE);
427 	}
428 	if (argc > 2) {
429 		(void) fprintf(stderr, gettext("too many arguments\n"));
430 		usage(B_FALSE);
431 	}
432 
433 	/* open the source dataset */
434 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
435 		return (1);
436 
437 	if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
438 	    ZFS_TYPE_VOLUME)) {
439 		/*
440 		 * Now create the ancestors of the target dataset.  If the
441 		 * target already exists and '-p' option was used we should not
442 		 * complain.
443 		 */
444 		if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
445 		    ZFS_TYPE_VOLUME))
446 			return (0);
447 		if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
448 			return (1);
449 	}
450 
451 	/* pass to libzfs */
452 	ret = zfs_clone(zhp, argv[1], NULL);
453 
454 	/* create the mountpoint if necessary */
455 	if (ret == 0) {
456 		zfs_handle_t *clone;
457 
458 		clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
459 		if (clone != NULL) {
460 			if ((ret = zfs_mount(clone, NULL, 0)) == 0)
461 				ret = zfs_share(clone);
462 			zfs_close(clone);
463 		}
464 	}
465 
466 	zfs_close(zhp);
467 
468 	return (ret == 0 ? 0 : 1);
469 }
470 
471 /*
472  * zfs create [-p] [-o prop=value] ... fs
473  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
474  *
475  * Create a new dataset.  This command can be used to create filesystems
476  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
477  * For volumes, the user must specify a size to be used.
478  *
479  * The '-s' flag applies only to volumes, and indicates that we should not try
480  * to set the reservation for this volume.  By default we set a reservation
481  * equal to the size for any volume.  For pools with SPA_VERSION >=
482  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
483  *
484  * The '-p' flag creates all the non-existing ancestors of the target first.
485  */
486 static int
487 zfs_do_create(int argc, char **argv)
488 {
489 	zfs_type_t type = ZFS_TYPE_FILESYSTEM;
490 	zfs_handle_t *zhp = NULL;
491 	uint64_t volsize;
492 	int c;
493 	boolean_t noreserve = B_FALSE;
494 	boolean_t bflag = B_FALSE;
495 	boolean_t parents = B_FALSE;
496 	int ret = 1;
497 	nvlist_t *props = NULL;
498 	uint64_t intval;
499 	char *propname;
500 	char *propval = NULL;
501 	char *strval;
502 
503 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
504 		(void) fprintf(stderr, gettext("internal error: "
505 		    "out of memory\n"));
506 		return (1);
507 	}
508 
509 	/* check options */
510 	while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
511 		switch (c) {
512 		case 'V':
513 			type = ZFS_TYPE_VOLUME;
514 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
515 				(void) fprintf(stderr, gettext("bad volume "
516 				    "size '%s': %s\n"), optarg,
517 				    libzfs_error_description(g_zfs));
518 				goto error;
519 			}
520 
521 			if (nvlist_add_uint64(props,
522 			    zfs_prop_to_name(ZFS_PROP_VOLSIZE),
523 			    intval) != 0) {
524 				(void) fprintf(stderr, gettext("internal "
525 				    "error: out of memory\n"));
526 				goto error;
527 			}
528 			volsize = intval;
529 			break;
530 		case 'p':
531 			parents = B_TRUE;
532 			break;
533 		case 'b':
534 			bflag = B_TRUE;
535 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
536 				(void) fprintf(stderr, gettext("bad volume "
537 				    "block size '%s': %s\n"), optarg,
538 				    libzfs_error_description(g_zfs));
539 				goto error;
540 			}
541 
542 			if (nvlist_add_uint64(props,
543 			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
544 			    intval) != 0) {
545 				(void) fprintf(stderr, gettext("internal "
546 				    "error: out of memory\n"));
547 				goto error;
548 			}
549 			break;
550 		case 'o':
551 			propname = optarg;
552 			if ((propval = strchr(propname, '=')) == NULL) {
553 				(void) fprintf(stderr, gettext("missing "
554 				    "'=' for -o option\n"));
555 				goto error;
556 			}
557 			*propval = '\0';
558 			propval++;
559 			if (nvlist_lookup_string(props, propname,
560 			    &strval) == 0) {
561 				(void) fprintf(stderr, gettext("property '%s' "
562 				    "specified multiple times\n"), propname);
563 				goto error;
564 			}
565 			if (nvlist_add_string(props, propname, propval) != 0) {
566 				(void) fprintf(stderr, gettext("internal "
567 				    "error: out of memory\n"));
568 				goto error;
569 			}
570 			break;
571 		case 's':
572 			noreserve = B_TRUE;
573 			break;
574 		case ':':
575 			(void) fprintf(stderr, gettext("missing size "
576 			    "argument\n"));
577 			goto badusage;
578 			break;
579 		case '?':
580 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
581 			    optopt);
582 			goto badusage;
583 		}
584 	}
585 
586 	if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
587 		(void) fprintf(stderr, gettext("'-s' and '-b' can only be "
588 		    "used when creating a volume\n"));
589 		goto badusage;
590 	}
591 
592 	argc -= optind;
593 	argv += optind;
594 
595 	/* check number of arguments */
596 	if (argc == 0) {
597 		(void) fprintf(stderr, gettext("missing %s argument\n"),
598 		    zfs_type_to_name(type));
599 		goto badusage;
600 	}
601 	if (argc > 1) {
602 		(void) fprintf(stderr, gettext("too many arguments\n"));
603 		goto badusage;
604 	}
605 
606 	if (type == ZFS_TYPE_VOLUME && !noreserve) {
607 		zpool_handle_t *zpool_handle;
608 		uint64_t spa_version;
609 		char *p;
610 		zfs_prop_t resv_prop;
611 
612 		if (p = strchr(argv[0], '/'))
613 			*p = '\0';
614 		zpool_handle = zpool_open(g_zfs, argv[0]);
615 		if (p != NULL)
616 			*p = '/';
617 		if (zpool_handle == NULL)
618 			goto error;
619 		spa_version = zpool_get_prop_int(zpool_handle,
620 		    ZPOOL_PROP_VERSION, NULL);
621 		zpool_close(zpool_handle);
622 		if (spa_version >= SPA_VERSION_REFRESERVATION)
623 			resv_prop = ZFS_PROP_REFRESERVATION;
624 		else
625 			resv_prop = ZFS_PROP_RESERVATION;
626 
627 		if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
628 		    &strval) != 0) {
629 			if (nvlist_add_uint64(props,
630 			    zfs_prop_to_name(resv_prop), volsize) != 0) {
631 				(void) fprintf(stderr, gettext("internal "
632 				    "error: out of memory\n"));
633 				nvlist_free(props);
634 				return (1);
635 			}
636 		}
637 	}
638 
639 	if (parents && zfs_name_valid(argv[0], type)) {
640 		/*
641 		 * Now create the ancestors of target dataset.  If the target
642 		 * already exists and '-p' option was used we should not
643 		 * complain.
644 		 */
645 		if (zfs_dataset_exists(g_zfs, argv[0], type)) {
646 			ret = 0;
647 			goto error;
648 		}
649 		if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
650 			goto error;
651 	}
652 
653 	/* pass to libzfs */
654 	if (zfs_create(g_zfs, argv[0], type, props) != 0)
655 		goto error;
656 
657 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
658 		goto error;
659 
660 	/*
661 	 * Mount and/or share the new filesystem as appropriate.  We provide a
662 	 * verbose error message to let the user know that their filesystem was
663 	 * in fact created, even if we failed to mount or share it.
664 	 */
665 	if (zfs_mount(zhp, NULL, 0) != 0) {
666 		(void) fprintf(stderr, gettext("filesystem successfully "
667 		    "created, but not mounted\n"));
668 		ret = 1;
669 	} else if (zfs_share(zhp) != 0) {
670 		(void) fprintf(stderr, gettext("filesystem successfully "
671 		    "created, but not shared\n"));
672 		ret = 1;
673 	} else {
674 		ret = 0;
675 	}
676 
677 error:
678 	if (zhp)
679 		zfs_close(zhp);
680 	nvlist_free(props);
681 	return (ret);
682 badusage:
683 	nvlist_free(props);
684 	usage(B_FALSE);
685 	return (2);
686 }
687 
688 /*
689  * zfs destroy [-rf] <fs, snap, vol>
690  *
691  * 	-r	Recursively destroy all children
692  * 	-R	Recursively destroy all dependents, including clones
693  * 	-f	Force unmounting of any dependents
694  *
695  * Destroys the given dataset.  By default, it will unmount any filesystems,
696  * and refuse to destroy a dataset that has any dependents.  A dependent can
697  * either be a child, or a clone of a child.
698  */
699 typedef struct destroy_cbdata {
700 	boolean_t	cb_first;
701 	int		cb_force;
702 	int		cb_recurse;
703 	int		cb_error;
704 	int		cb_needforce;
705 	int		cb_doclones;
706 	boolean_t	cb_closezhp;
707 	zfs_handle_t	*cb_target;
708 	char		*cb_snapname;
709 } destroy_cbdata_t;
710 
711 /*
712  * Check for any dependents based on the '-r' or '-R' flags.
713  */
714 static int
715 destroy_check_dependent(zfs_handle_t *zhp, void *data)
716 {
717 	destroy_cbdata_t *cbp = data;
718 	const char *tname = zfs_get_name(cbp->cb_target);
719 	const char *name = zfs_get_name(zhp);
720 
721 	if (strncmp(tname, name, strlen(tname)) == 0 &&
722 	    (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
723 		/*
724 		 * This is a direct descendant, not a clone somewhere else in
725 		 * the hierarchy.
726 		 */
727 		if (cbp->cb_recurse)
728 			goto out;
729 
730 		if (cbp->cb_first) {
731 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
732 			    "%s has children\n"),
733 			    zfs_get_name(cbp->cb_target),
734 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
735 			(void) fprintf(stderr, gettext("use '-r' to destroy "
736 			    "the following datasets:\n"));
737 			cbp->cb_first = B_FALSE;
738 			cbp->cb_error = 1;
739 		}
740 
741 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
742 	} else {
743 		/*
744 		 * This is a clone.  We only want to report this if the '-r'
745 		 * wasn't specified, or the target is a snapshot.
746 		 */
747 		if (!cbp->cb_recurse &&
748 		    zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
749 			goto out;
750 
751 		if (cbp->cb_first) {
752 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
753 			    "%s has dependent clones\n"),
754 			    zfs_get_name(cbp->cb_target),
755 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
756 			(void) fprintf(stderr, gettext("use '-R' to destroy "
757 			    "the following datasets:\n"));
758 			cbp->cb_first = B_FALSE;
759 			cbp->cb_error = 1;
760 		}
761 
762 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
763 	}
764 
765 out:
766 	zfs_close(zhp);
767 	return (0);
768 }
769 
770 static int
771 destroy_callback(zfs_handle_t *zhp, void *data)
772 {
773 	destroy_cbdata_t *cbp = data;
774 
775 	/*
776 	 * Ignore pools (which we've already flagged as an error before getting
777 	 * here.
778 	 */
779 	if (strchr(zfs_get_name(zhp), '/') == NULL &&
780 	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
781 		zfs_close(zhp);
782 		return (0);
783 	}
784 
785 	/*
786 	 * Bail out on the first error.
787 	 */
788 	if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
789 	    zfs_destroy(zhp) != 0) {
790 		zfs_close(zhp);
791 		return (-1);
792 	}
793 
794 	zfs_close(zhp);
795 	return (0);
796 }
797 
798 static int
799 destroy_snap_clones(zfs_handle_t *zhp, void *arg)
800 {
801 	destroy_cbdata_t *cbp = arg;
802 	char thissnap[MAXPATHLEN];
803 	zfs_handle_t *szhp;
804 	boolean_t closezhp = cbp->cb_closezhp;
805 	int rv;
806 
807 	(void) snprintf(thissnap, sizeof (thissnap),
808 	    "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
809 
810 	libzfs_print_on_error(g_zfs, B_FALSE);
811 	szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
812 	libzfs_print_on_error(g_zfs, B_TRUE);
813 	if (szhp) {
814 		/*
815 		 * Destroy any clones of this snapshot
816 		 */
817 		if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
818 		    cbp) != 0) {
819 			zfs_close(szhp);
820 			if (closezhp)
821 				zfs_close(zhp);
822 			return (-1);
823 		}
824 		zfs_close(szhp);
825 	}
826 
827 	cbp->cb_closezhp = B_TRUE;
828 	rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
829 	if (closezhp)
830 		zfs_close(zhp);
831 	return (rv);
832 }
833 
834 static int
835 zfs_do_destroy(int argc, char **argv)
836 {
837 	destroy_cbdata_t cb = { 0 };
838 	int c;
839 	zfs_handle_t *zhp;
840 	char *cp;
841 
842 	/* check options */
843 	while ((c = getopt(argc, argv, "frR")) != -1) {
844 		switch (c) {
845 		case 'f':
846 			cb.cb_force = 1;
847 			break;
848 		case 'r':
849 			cb.cb_recurse = 1;
850 			break;
851 		case 'R':
852 			cb.cb_recurse = 1;
853 			cb.cb_doclones = 1;
854 			break;
855 		case '?':
856 		default:
857 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
858 			    optopt);
859 			usage(B_FALSE);
860 		}
861 	}
862 
863 	argc -= optind;
864 	argv += optind;
865 
866 	/* check number of arguments */
867 	if (argc == 0) {
868 		(void) fprintf(stderr, gettext("missing path argument\n"));
869 		usage(B_FALSE);
870 	}
871 	if (argc > 1) {
872 		(void) fprintf(stderr, gettext("too many arguments\n"));
873 		usage(B_FALSE);
874 	}
875 
876 	/*
877 	 * If we are doing recursive destroy of a snapshot, then the
878 	 * named snapshot may not exist.  Go straight to libzfs.
879 	 */
880 	if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
881 		int ret;
882 
883 		*cp = '\0';
884 		if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
885 			return (1);
886 		*cp = '@';
887 		cp++;
888 
889 		if (cb.cb_doclones) {
890 			cb.cb_snapname = cp;
891 			if (destroy_snap_clones(zhp, &cb) != 0) {
892 				zfs_close(zhp);
893 				return (1);
894 			}
895 		}
896 
897 		ret = zfs_destroy_snaps(zhp, cp);
898 		zfs_close(zhp);
899 		if (ret) {
900 			(void) fprintf(stderr,
901 			    gettext("no snapshots destroyed\n"));
902 		}
903 		return (ret != 0);
904 	}
905 
906 
907 	/* Open the given dataset */
908 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
909 		return (1);
910 
911 	cb.cb_target = zhp;
912 
913 	/*
914 	 * Perform an explicit check for pools before going any further.
915 	 */
916 	if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
917 	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
918 		(void) fprintf(stderr, gettext("cannot destroy '%s': "
919 		    "operation does not apply to pools\n"),
920 		    zfs_get_name(zhp));
921 		(void) fprintf(stderr, gettext("use 'zfs destroy -r "
922 		    "%s' to destroy all datasets in the pool\n"),
923 		    zfs_get_name(zhp));
924 		(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
925 		    "to destroy the pool itself\n"), zfs_get_name(zhp));
926 		zfs_close(zhp);
927 		return (1);
928 	}
929 
930 	/*
931 	 * Check for any dependents and/or clones.
932 	 */
933 	cb.cb_first = B_TRUE;
934 	if (!cb.cb_doclones &&
935 	    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
936 	    &cb) != 0) {
937 		zfs_close(zhp);
938 		return (1);
939 	}
940 
941 	if (cb.cb_error ||
942 	    zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0) {
943 		zfs_close(zhp);
944 		return (1);
945 	}
946 
947 	/*
948 	 * Do the real thing.  The callback will close the handle regardless of
949 	 * whether it succeeds or not.
950 	 */
951 
952 	if (destroy_callback(zhp, &cb) != 0)
953 		return (1);
954 
955 
956 	return (0);
957 }
958 
959 /*
960  * zfs get [-rHp] [-o field[,field]...] [-s source[,source]...]
961  * 	< all | property[,property]... > < fs | snap | vol > ...
962  *
963  *	-r	recurse over any child datasets
964  *	-H	scripted mode.  Headers are stripped, and fields are separated
965  *		by tabs instead of spaces.
966  *	-o	Set of fields to display.  One of "name,property,value,source".
967  *		Default is all four.
968  *	-s	Set of sources to allow.  One of
969  *		"local,default,inherited,temporary,none".  Default is all
970  *		five.
971  *	-p	Display values in parsable (literal) format.
972  *
973  *  Prints properties for the given datasets.  The user can control which
974  *  columns to display as well as which property types to allow.
975  */
976 
977 /*
978  * Invoked to display the properties for a single dataset.
979  */
980 static int
981 get_callback(zfs_handle_t *zhp, void *data)
982 {
983 	char buf[ZFS_MAXPROPLEN];
984 	zprop_source_t sourcetype;
985 	char source[ZFS_MAXNAMELEN];
986 	zprop_get_cbdata_t *cbp = data;
987 	nvlist_t *userprop = zfs_get_user_props(zhp);
988 	zprop_list_t *pl = cbp->cb_proplist;
989 	nvlist_t *propval;
990 	char *strval;
991 	char *sourceval;
992 
993 	for (; pl != NULL; pl = pl->pl_next) {
994 		/*
995 		 * Skip the special fake placeholder.  This will also skip over
996 		 * the name property when 'all' is specified.
997 		 */
998 		if (pl->pl_prop == ZFS_PROP_NAME &&
999 		    pl == cbp->cb_proplist)
1000 			continue;
1001 
1002 		if (pl->pl_prop != ZPROP_INVAL) {
1003 			if (zfs_prop_get(zhp, pl->pl_prop, buf,
1004 			    sizeof (buf), &sourcetype, source,
1005 			    sizeof (source),
1006 			    cbp->cb_literal) != 0) {
1007 				if (pl->pl_all)
1008 					continue;
1009 				if (!zfs_prop_valid_for_type(pl->pl_prop,
1010 				    ZFS_TYPE_DATASET)) {
1011 					(void) fprintf(stderr,
1012 					    gettext("No such property '%s'\n"),
1013 					    zfs_prop_to_name(pl->pl_prop));
1014 					continue;
1015 				}
1016 				sourcetype = ZPROP_SRC_NONE;
1017 				(void) strlcpy(buf, "-", sizeof (buf));
1018 			}
1019 
1020 			zprop_print_one_property(zfs_get_name(zhp), cbp,
1021 			    zfs_prop_to_name(pl->pl_prop),
1022 			    buf, sourcetype, source);
1023 		} else {
1024 			if (nvlist_lookup_nvlist(userprop,
1025 			    pl->pl_user_prop, &propval) != 0) {
1026 				if (pl->pl_all)
1027 					continue;
1028 				sourcetype = ZPROP_SRC_NONE;
1029 				strval = "-";
1030 			} else {
1031 				verify(nvlist_lookup_string(propval,
1032 				    ZPROP_VALUE, &strval) == 0);
1033 				verify(nvlist_lookup_string(propval,
1034 				    ZPROP_SOURCE, &sourceval) == 0);
1035 
1036 				if (strcmp(sourceval,
1037 				    zfs_get_name(zhp)) == 0) {
1038 					sourcetype = ZPROP_SRC_LOCAL;
1039 				} else {
1040 					sourcetype = ZPROP_SRC_INHERITED;
1041 					(void) strlcpy(source,
1042 					    sourceval, sizeof (source));
1043 				}
1044 			}
1045 
1046 			zprop_print_one_property(zfs_get_name(zhp), cbp,
1047 			    pl->pl_user_prop, strval, sourcetype,
1048 			    source);
1049 		}
1050 	}
1051 
1052 	return (0);
1053 }
1054 
1055 static int
1056 zfs_do_get(int argc, char **argv)
1057 {
1058 	zprop_get_cbdata_t cb = { 0 };
1059 	boolean_t recurse = B_FALSE;
1060 	int i, c;
1061 	char *value, *fields;
1062 	int ret;
1063 	zprop_list_t fake_name = { 0 };
1064 
1065 	/*
1066 	 * Set up default columns and sources.
1067 	 */
1068 	cb.cb_sources = ZPROP_SRC_ALL;
1069 	cb.cb_columns[0] = GET_COL_NAME;
1070 	cb.cb_columns[1] = GET_COL_PROPERTY;
1071 	cb.cb_columns[2] = GET_COL_VALUE;
1072 	cb.cb_columns[3] = GET_COL_SOURCE;
1073 	cb.cb_type = ZFS_TYPE_DATASET;
1074 
1075 	/* check options */
1076 	while ((c = getopt(argc, argv, ":o:s:rHp")) != -1) {
1077 		switch (c) {
1078 		case 'p':
1079 			cb.cb_literal = B_TRUE;
1080 			break;
1081 		case 'r':
1082 			recurse = B_TRUE;
1083 			break;
1084 		case 'H':
1085 			cb.cb_scripted = B_TRUE;
1086 			break;
1087 		case ':':
1088 			(void) fprintf(stderr, gettext("missing argument for "
1089 			    "'%c' option\n"), optopt);
1090 			usage(B_FALSE);
1091 			break;
1092 		case 'o':
1093 			/*
1094 			 * Process the set of columns to display.  We zero out
1095 			 * the structure to give us a blank slate.
1096 			 */
1097 			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1098 			i = 0;
1099 			while (*optarg != '\0') {
1100 				static char *col_subopts[] =
1101 				    { "name", "property", "value", "source",
1102 				    NULL };
1103 
1104 				if (i == 4) {
1105 					(void) fprintf(stderr, gettext("too "
1106 					    "many fields given to -o "
1107 					    "option\n"));
1108 					usage(B_FALSE);
1109 				}
1110 
1111 				switch (getsubopt(&optarg, col_subopts,
1112 				    &value)) {
1113 				case 0:
1114 					cb.cb_columns[i++] = GET_COL_NAME;
1115 					break;
1116 				case 1:
1117 					cb.cb_columns[i++] = GET_COL_PROPERTY;
1118 					break;
1119 				case 2:
1120 					cb.cb_columns[i++] = GET_COL_VALUE;
1121 					break;
1122 				case 3:
1123 					cb.cb_columns[i++] = GET_COL_SOURCE;
1124 					break;
1125 				default:
1126 					(void) fprintf(stderr,
1127 					    gettext("invalid column name "
1128 					    "'%s'\n"), value);
1129 					usage(B_FALSE);
1130 				}
1131 			}
1132 			break;
1133 
1134 		case 's':
1135 			cb.cb_sources = 0;
1136 			while (*optarg != '\0') {
1137 				static char *source_subopts[] = {
1138 					"local", "default", "inherited",
1139 					"temporary", "none", NULL };
1140 
1141 				switch (getsubopt(&optarg, source_subopts,
1142 				    &value)) {
1143 				case 0:
1144 					cb.cb_sources |= ZPROP_SRC_LOCAL;
1145 					break;
1146 				case 1:
1147 					cb.cb_sources |= ZPROP_SRC_DEFAULT;
1148 					break;
1149 				case 2:
1150 					cb.cb_sources |= ZPROP_SRC_INHERITED;
1151 					break;
1152 				case 3:
1153 					cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1154 					break;
1155 				case 4:
1156 					cb.cb_sources |= ZPROP_SRC_NONE;
1157 					break;
1158 				default:
1159 					(void) fprintf(stderr,
1160 					    gettext("invalid source "
1161 					    "'%s'\n"), value);
1162 					usage(B_FALSE);
1163 				}
1164 			}
1165 			break;
1166 
1167 		case '?':
1168 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1169 			    optopt);
1170 			usage(B_FALSE);
1171 		}
1172 	}
1173 
1174 	argc -= optind;
1175 	argv += optind;
1176 
1177 	if (argc < 1) {
1178 		(void) fprintf(stderr, gettext("missing property "
1179 		    "argument\n"));
1180 		usage(B_FALSE);
1181 	}
1182 
1183 	fields = argv[0];
1184 
1185 	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1186 	    != 0)
1187 		usage(B_FALSE);
1188 
1189 	argc--;
1190 	argv++;
1191 
1192 	/*
1193 	 * As part of zfs_expand_proplist(), we keep track of the maximum column
1194 	 * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1195 	 * need to know the maximum name length.  However, the user likely did
1196 	 * not specify 'name' as one of the properties to fetch, so we need to
1197 	 * make sure we always include at least this property for
1198 	 * print_get_headers() to work properly.
1199 	 */
1200 	if (cb.cb_proplist != NULL) {
1201 		fake_name.pl_prop = ZFS_PROP_NAME;
1202 		fake_name.pl_width = strlen(gettext("NAME"));
1203 		fake_name.pl_next = cb.cb_proplist;
1204 		cb.cb_proplist = &fake_name;
1205 	}
1206 
1207 	cb.cb_first = B_TRUE;
1208 
1209 	/* run for each object */
1210 	ret = zfs_for_each(argc, argv, recurse, ZFS_TYPE_DATASET, NULL,
1211 	    &cb.cb_proplist, get_callback, &cb, B_FALSE);
1212 
1213 	if (cb.cb_proplist == &fake_name)
1214 		zprop_free_list(fake_name.pl_next);
1215 	else
1216 		zprop_free_list(cb.cb_proplist);
1217 
1218 	return (ret);
1219 }
1220 
1221 /*
1222  * inherit [-r] <property> <fs|vol> ...
1223  *
1224  * 	-r	Recurse over all children
1225  *
1226  * For each dataset specified on the command line, inherit the given property
1227  * from its parent.  Inheriting a property at the pool level will cause it to
1228  * use the default value.  The '-r' flag will recurse over all children, and is
1229  * useful for setting a property on a hierarchy-wide basis, regardless of any
1230  * local modifications for each dataset.
1231  */
1232 
1233 static int
1234 inherit_callback(zfs_handle_t *zhp, void *data)
1235 {
1236 	char *propname = data;
1237 	int ret;
1238 
1239 	ret = zfs_prop_inherit(zhp, propname);
1240 	return (ret != 0);
1241 }
1242 
1243 static int
1244 zfs_do_inherit(int argc, char **argv)
1245 {
1246 	boolean_t recurse = B_FALSE;
1247 	int c;
1248 	zfs_prop_t prop;
1249 	char *propname;
1250 	int ret;
1251 
1252 	/* check options */
1253 	while ((c = getopt(argc, argv, "r")) != -1) {
1254 		switch (c) {
1255 		case 'r':
1256 			recurse = B_TRUE;
1257 			break;
1258 		case '?':
1259 		default:
1260 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1261 			    optopt);
1262 			usage(B_FALSE);
1263 		}
1264 	}
1265 
1266 	argc -= optind;
1267 	argv += optind;
1268 
1269 	/* check number of arguments */
1270 	if (argc < 1) {
1271 		(void) fprintf(stderr, gettext("missing property argument\n"));
1272 		usage(B_FALSE);
1273 	}
1274 	if (argc < 2) {
1275 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1276 		usage(B_FALSE);
1277 	}
1278 
1279 	propname = argv[0];
1280 	argc--;
1281 	argv++;
1282 
1283 	if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1284 		if (zfs_prop_readonly(prop)) {
1285 			(void) fprintf(stderr, gettext(
1286 			    "%s property is read-only\n"),
1287 			    propname);
1288 			return (1);
1289 		}
1290 		if (!zfs_prop_inheritable(prop)) {
1291 			(void) fprintf(stderr, gettext("'%s' property cannot "
1292 			    "be inherited\n"), propname);
1293 			if (prop == ZFS_PROP_QUOTA ||
1294 			    prop == ZFS_PROP_RESERVATION ||
1295 			    prop == ZFS_PROP_REFQUOTA ||
1296 			    prop == ZFS_PROP_REFRESERVATION)
1297 				(void) fprintf(stderr, gettext("use 'zfs set "
1298 				    "%s=none' to clear\n"), propname);
1299 			return (1);
1300 		}
1301 	} else if (!zfs_prop_user(propname)) {
1302 		(void) fprintf(stderr, gettext("invalid property '%s'\n"),
1303 		    propname);
1304 		usage(B_FALSE);
1305 	}
1306 
1307 	ret = zfs_for_each(argc, argv, recurse,
1308 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL,
1309 	    inherit_callback, propname, B_FALSE);
1310 
1311 	return (ret);
1312 }
1313 
1314 typedef struct upgrade_cbdata {
1315 	uint64_t cb_numupgraded;
1316 	uint64_t cb_numsamegraded;
1317 	uint64_t cb_numfailed;
1318 	uint64_t cb_version;
1319 	boolean_t cb_newer;
1320 	boolean_t cb_foundone;
1321 	char cb_lastfs[ZFS_MAXNAMELEN];
1322 } upgrade_cbdata_t;
1323 
1324 static int
1325 same_pool(zfs_handle_t *zhp, const char *name)
1326 {
1327 	int len1 = strcspn(name, "/@");
1328 	const char *zhname = zfs_get_name(zhp);
1329 	int len2 = strcspn(zhname, "/@");
1330 
1331 	if (len1 != len2)
1332 		return (B_FALSE);
1333 	return (strncmp(name, zhname, len1) == 0);
1334 }
1335 
1336 static int
1337 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1338 {
1339 	upgrade_cbdata_t *cb = data;
1340 	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1341 
1342 	/* list if it's old/new */
1343 	if ((!cb->cb_newer && version < ZPL_VERSION) ||
1344 	    (cb->cb_newer && version > ZPL_VERSION)) {
1345 		char *str;
1346 		if (cb->cb_newer) {
1347 			str = gettext("The following filesystems are "
1348 			    "formatted using a newer software version and\n"
1349 			    "cannot be accessed on the current system.\n\n");
1350 		} else {
1351 			str = gettext("The following filesystems are "
1352 			    "out of date, and can be upgraded.  After being\n"
1353 			    "upgraded, these filesystems (and any 'zfs send' "
1354 			    "streams generated from\n"
1355 			    "subsequent snapshots) will no longer be "
1356 			    "accessible by older software versions.\n\n");
1357 		}
1358 
1359 		if (!cb->cb_foundone) {
1360 			(void) puts(str);
1361 			(void) printf(gettext("VER  FILESYSTEM\n"));
1362 			(void) printf(gettext("---  ------------\n"));
1363 			cb->cb_foundone = B_TRUE;
1364 		}
1365 
1366 		(void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1367 	}
1368 
1369 	return (0);
1370 }
1371 
1372 static int
1373 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1374 {
1375 	upgrade_cbdata_t *cb = data;
1376 	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1377 
1378 	if (cb->cb_version >= ZPL_VERSION_FUID) {
1379 		char pool_name[MAXPATHLEN];
1380 		zpool_handle_t *zpool_handle;
1381 		int spa_version;
1382 		char *p;
1383 
1384 		if (zfs_prop_get(zhp, ZFS_PROP_NAME, pool_name,
1385 		    sizeof (pool_name), NULL, NULL, 0, B_FALSE) != 0)
1386 			return (-1);
1387 
1388 		if (p = strchr(pool_name, '/'))
1389 			*p = '\0';
1390 		if ((zpool_handle = zpool_open(g_zfs, pool_name)) == NULL)
1391 			return (-1);
1392 
1393 		spa_version = zpool_get_prop_int(zpool_handle,
1394 		    ZPOOL_PROP_VERSION, NULL);
1395 		zpool_close(zpool_handle);
1396 		if (spa_version < SPA_VERSION_FUID) {
1397 			/* can't upgrade */
1398 			(void) printf(gettext("%s: can not be upgraded; "
1399 			    "the pool version needs to first be upgraded\nto "
1400 			    "version %d\n\n"),
1401 			    zfs_get_name(zhp), SPA_VERSION_FUID);
1402 			cb->cb_numfailed++;
1403 			return (0);
1404 		}
1405 	}
1406 
1407 	/* upgrade */
1408 	if (version < cb->cb_version) {
1409 		char verstr[16];
1410 		(void) snprintf(verstr, sizeof (verstr),
1411 		    "%llu", cb->cb_version);
1412 		if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1413 			/*
1414 			 * If they did "zfs upgrade -a", then we could
1415 			 * be doing ioctls to different pools.  We need
1416 			 * to log this history once to each pool.
1417 			 */
1418 			verify(zpool_stage_history(g_zfs, history_str) == 0);
1419 		}
1420 		if (zfs_prop_set(zhp, "version", verstr) == 0)
1421 			cb->cb_numupgraded++;
1422 		else
1423 			cb->cb_numfailed++;
1424 		(void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1425 	} else if (version > cb->cb_version) {
1426 		/* can't downgrade */
1427 		(void) printf(gettext("%s: can not be downgraded; "
1428 		    "it is already at version %u\n"),
1429 		    zfs_get_name(zhp), version);
1430 		cb->cb_numfailed++;
1431 	} else {
1432 		cb->cb_numsamegraded++;
1433 	}
1434 	return (0);
1435 }
1436 
1437 /*
1438  * zfs upgrade
1439  * zfs upgrade -v
1440  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1441  */
1442 static int
1443 zfs_do_upgrade(int argc, char **argv)
1444 {
1445 	boolean_t recurse = B_FALSE;
1446 	boolean_t all = B_FALSE;
1447 	boolean_t showversions = B_FALSE;
1448 	int ret;
1449 	upgrade_cbdata_t cb = { 0 };
1450 	char c;
1451 
1452 	/* check options */
1453 	while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1454 		switch (c) {
1455 		case 'r':
1456 			recurse = B_TRUE;
1457 			break;
1458 		case 'v':
1459 			showversions = B_TRUE;
1460 			break;
1461 		case 'V':
1462 			if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1463 			    optarg, &cb.cb_version) != 0) {
1464 				(void) fprintf(stderr,
1465 				    gettext("invalid version %s\n"), optarg);
1466 				usage(B_FALSE);
1467 			}
1468 			break;
1469 		case 'a':
1470 			all = B_TRUE;
1471 			break;
1472 		case '?':
1473 		default:
1474 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1475 			    optopt);
1476 			usage(B_FALSE);
1477 		}
1478 	}
1479 
1480 	argc -= optind;
1481 	argv += optind;
1482 
1483 	if ((!all && !argc) && (recurse | cb.cb_version))
1484 		usage(B_FALSE);
1485 	if (showversions && (recurse || all || cb.cb_version || argc))
1486 		usage(B_FALSE);
1487 	if ((all || argc) && (showversions))
1488 		usage(B_FALSE);
1489 	if (all && argc)
1490 		usage(B_FALSE);
1491 
1492 	if (showversions) {
1493 		/* Show info on available versions. */
1494 		(void) printf(gettext("The following filesystem versions are "
1495 		    "supported:\n\n"));
1496 		(void) printf(gettext("VER  DESCRIPTION\n"));
1497 		(void) printf("---  -----------------------------------------"
1498 		    "---------------\n");
1499 		(void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1500 		(void) printf(gettext(" 2   Enhanced directory entries\n"));
1501 		(void) printf(gettext(" 3   Case insensitive and File system "
1502 		    "unique identifer (FUID)\n"));
1503 		(void) printf(gettext("\nFor more information on a particular "
1504 		    "version, including supported releases, see:\n\n"));
1505 		(void) printf("http://www.opensolaris.org/os/community/zfs/"
1506 		    "version/zpl/N\n\n");
1507 		(void) printf(gettext("Where 'N' is the version number.\n"));
1508 		ret = 0;
1509 	} else if (argc || all) {
1510 		/* Upgrade filesystems */
1511 		if (cb.cb_version == 0)
1512 			cb.cb_version = ZPL_VERSION;
1513 		ret = zfs_for_each(argc, argv, recurse, ZFS_TYPE_FILESYSTEM,
1514 		    NULL, NULL, upgrade_set_callback, &cb, B_TRUE);
1515 		(void) printf(gettext("%llu filesystems upgraded\n"),
1516 		    cb.cb_numupgraded);
1517 		if (cb.cb_numsamegraded) {
1518 			(void) printf(gettext("%llu filesystems already at "
1519 			    "this version\n"),
1520 			    cb.cb_numsamegraded);
1521 		}
1522 		if (cb.cb_numfailed != 0)
1523 			ret = 1;
1524 	} else {
1525 		/* List old-version filesytems */
1526 		boolean_t found;
1527 		(void) printf(gettext("This system is currently running "
1528 		    "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
1529 
1530 		ret = zfs_for_each(0, NULL, B_TRUE, ZFS_TYPE_FILESYSTEM,
1531 		    NULL, NULL, upgrade_list_callback, &cb, B_TRUE);
1532 
1533 		found = cb.cb_foundone;
1534 		cb.cb_foundone = B_FALSE;
1535 		cb.cb_newer = B_TRUE;
1536 
1537 		ret = zfs_for_each(0, NULL, B_TRUE, ZFS_TYPE_FILESYSTEM,
1538 		    NULL, NULL, upgrade_list_callback, &cb, B_TRUE);
1539 
1540 		if (!cb.cb_foundone && !found) {
1541 			(void) printf(gettext("All filesystems are "
1542 			    "formatted with the current version.\n"));
1543 		}
1544 	}
1545 
1546 	return (ret);
1547 }
1548 
1549 /*
1550  * list [-rH] [-o property[,property]...] [-t type[,type]...]
1551  *      [-s property [-s property]...] [-S property [-S property]...]
1552  *      <dataset> ...
1553  *
1554  * 	-r	Recurse over all children
1555  * 	-H	Scripted mode; elide headers and separate columns by tabs
1556  * 	-o	Control which fields to display.
1557  * 	-t	Control which object types to display.
1558  *	-s	Specify sort columns, descending order.
1559  *	-S	Specify sort columns, ascending order.
1560  *
1561  * When given no arguments, lists all filesystems in the system.
1562  * Otherwise, list the specified datasets, optionally recursing down them if
1563  * '-r' is specified.
1564  */
1565 typedef struct list_cbdata {
1566 	boolean_t	cb_first;
1567 	boolean_t	cb_scripted;
1568 	zprop_list_t	*cb_proplist;
1569 } list_cbdata_t;
1570 
1571 /*
1572  * Given a list of columns to display, output appropriate headers for each one.
1573  */
1574 static void
1575 print_header(zprop_list_t *pl)
1576 {
1577 	char headerbuf[ZFS_MAXPROPLEN];
1578 	const char *header;
1579 	int i;
1580 	boolean_t first = B_TRUE;
1581 	boolean_t right_justify;
1582 
1583 	for (; pl != NULL; pl = pl->pl_next) {
1584 		if (!first) {
1585 			(void) printf("  ");
1586 		} else {
1587 			first = B_FALSE;
1588 		}
1589 
1590 		right_justify = B_FALSE;
1591 		if (pl->pl_prop != ZPROP_INVAL) {
1592 			header = zfs_prop_column_name(pl->pl_prop);
1593 			right_justify = zfs_prop_align_right(pl->pl_prop);
1594 		} else {
1595 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1596 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
1597 			headerbuf[i] = '\0';
1598 			header = headerbuf;
1599 		}
1600 
1601 		if (pl->pl_next == NULL && !right_justify)
1602 			(void) printf("%s", header);
1603 		else if (right_justify)
1604 			(void) printf("%*s", pl->pl_width, header);
1605 		else
1606 			(void) printf("%-*s", pl->pl_width, header);
1607 	}
1608 
1609 	(void) printf("\n");
1610 }
1611 
1612 /*
1613  * Given a dataset and a list of fields, print out all the properties according
1614  * to the described layout.
1615  */
1616 static void
1617 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
1618 {
1619 	boolean_t first = B_TRUE;
1620 	char property[ZFS_MAXPROPLEN];
1621 	nvlist_t *userprops = zfs_get_user_props(zhp);
1622 	nvlist_t *propval;
1623 	char *propstr;
1624 	boolean_t right_justify;
1625 	int width;
1626 
1627 	for (; pl != NULL; pl = pl->pl_next) {
1628 		if (!first) {
1629 			if (scripted)
1630 				(void) printf("\t");
1631 			else
1632 				(void) printf("  ");
1633 		} else {
1634 			first = B_FALSE;
1635 		}
1636 
1637 		right_justify = B_FALSE;
1638 		if (pl->pl_prop != ZPROP_INVAL) {
1639 			if (zfs_prop_get(zhp, pl->pl_prop, property,
1640 			    sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
1641 				propstr = "-";
1642 			else
1643 				propstr = property;
1644 
1645 			right_justify = zfs_prop_align_right(pl->pl_prop);
1646 		} else {
1647 			if (nvlist_lookup_nvlist(userprops,
1648 			    pl->pl_user_prop, &propval) != 0)
1649 				propstr = "-";
1650 			else
1651 				verify(nvlist_lookup_string(propval,
1652 				    ZPROP_VALUE, &propstr) == 0);
1653 		}
1654 
1655 		width = pl->pl_width;
1656 
1657 		/*
1658 		 * If this is being called in scripted mode, or if this is the
1659 		 * last column and it is left-justified, don't include a width
1660 		 * format specifier.
1661 		 */
1662 		if (scripted || (pl->pl_next == NULL && !right_justify))
1663 			(void) printf("%s", propstr);
1664 		else if (right_justify)
1665 			(void) printf("%*s", width, propstr);
1666 		else
1667 			(void) printf("%-*s", width, propstr);
1668 	}
1669 
1670 	(void) printf("\n");
1671 }
1672 
1673 /*
1674  * Generic callback function to list a dataset or snapshot.
1675  */
1676 static int
1677 list_callback(zfs_handle_t *zhp, void *data)
1678 {
1679 	list_cbdata_t *cbp = data;
1680 
1681 	if (cbp->cb_first) {
1682 		if (!cbp->cb_scripted)
1683 			print_header(cbp->cb_proplist);
1684 		cbp->cb_first = B_FALSE;
1685 	}
1686 
1687 	print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
1688 
1689 	return (0);
1690 }
1691 
1692 static int
1693 zfs_do_list(int argc, char **argv)
1694 {
1695 	int c;
1696 	boolean_t recurse = B_FALSE;
1697 	boolean_t scripted = B_FALSE;
1698 	static char default_fields[] =
1699 	    "name,used,available,referenced,mountpoint";
1700 	int types = ZFS_TYPE_DATASET;
1701 	char *fields = NULL;
1702 	char *basic_fields = default_fields;
1703 	list_cbdata_t cb = { 0 };
1704 	char *value;
1705 	int ret;
1706 	char *type_subopts[] = { "filesystem", "volume", "snapshot", NULL };
1707 	zfs_sort_column_t *sortcol = NULL;
1708 
1709 	/* check options */
1710 	while ((c = getopt(argc, argv, ":o:rt:Hs:S:")) != -1) {
1711 		switch (c) {
1712 		case 'o':
1713 			fields = optarg;
1714 			break;
1715 		case 'r':
1716 			recurse = B_TRUE;
1717 			break;
1718 		case 'H':
1719 			scripted = B_TRUE;
1720 			break;
1721 		case 's':
1722 			if (zfs_add_sort_column(&sortcol, optarg,
1723 			    B_FALSE) != 0) {
1724 				(void) fprintf(stderr,
1725 				    gettext("invalid property '%s'\n"), optarg);
1726 				usage(B_FALSE);
1727 			}
1728 			break;
1729 		case 'S':
1730 			if (zfs_add_sort_column(&sortcol, optarg,
1731 			    B_TRUE) != 0) {
1732 				(void) fprintf(stderr,
1733 				    gettext("invalid property '%s'\n"), optarg);
1734 				usage(B_FALSE);
1735 			}
1736 			break;
1737 		case 't':
1738 			types = 0;
1739 			while (*optarg != '\0') {
1740 				switch (getsubopt(&optarg, type_subopts,
1741 				    &value)) {
1742 				case 0:
1743 					types |= ZFS_TYPE_FILESYSTEM;
1744 					break;
1745 				case 1:
1746 					types |= ZFS_TYPE_VOLUME;
1747 					break;
1748 				case 2:
1749 					types |= ZFS_TYPE_SNAPSHOT;
1750 					break;
1751 				default:
1752 					(void) fprintf(stderr,
1753 					    gettext("invalid type '%s'\n"),
1754 					    value);
1755 					usage(B_FALSE);
1756 				}
1757 			}
1758 			break;
1759 		case ':':
1760 			(void) fprintf(stderr, gettext("missing argument for "
1761 			    "'%c' option\n"), optopt);
1762 			usage(B_FALSE);
1763 			break;
1764 		case '?':
1765 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1766 			    optopt);
1767 			usage(B_FALSE);
1768 		}
1769 	}
1770 
1771 	argc -= optind;
1772 	argv += optind;
1773 
1774 	if (fields == NULL)
1775 		fields = basic_fields;
1776 
1777 	/*
1778 	 * If the user specifies '-o all', the zprop_get_list() doesn't
1779 	 * normally include the name of the dataset.  For 'zfs list', we always
1780 	 * want this property to be first.
1781 	 */
1782 	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1783 	    != 0)
1784 		usage(B_FALSE);
1785 
1786 	cb.cb_scripted = scripted;
1787 	cb.cb_first = B_TRUE;
1788 
1789 	ret = zfs_for_each(argc, argv, recurse, types, sortcol, &cb.cb_proplist,
1790 	    list_callback, &cb, B_TRUE);
1791 
1792 	zprop_free_list(cb.cb_proplist);
1793 	zfs_free_sort_columns(sortcol);
1794 
1795 	if (ret == 0 && cb.cb_first && !cb.cb_scripted)
1796 		(void) printf(gettext("no datasets available\n"));
1797 
1798 	return (ret);
1799 }
1800 
1801 /*
1802  * zfs rename <fs | snap | vol> <fs | snap | vol>
1803  * zfs rename -p <fs | vol> <fs | vol>
1804  * zfs rename -r <snap> <snap>
1805  *
1806  * Renames the given dataset to another of the same type.
1807  *
1808  * The '-p' flag creates all the non-existing ancestors of the target first.
1809  */
1810 /* ARGSUSED */
1811 static int
1812 zfs_do_rename(int argc, char **argv)
1813 {
1814 	zfs_handle_t *zhp;
1815 	int c;
1816 	int ret;
1817 	boolean_t recurse = B_FALSE;
1818 	boolean_t parents = B_FALSE;
1819 
1820 	/* check options */
1821 	while ((c = getopt(argc, argv, "pr")) != -1) {
1822 		switch (c) {
1823 		case 'p':
1824 			parents = B_TRUE;
1825 			break;
1826 		case 'r':
1827 			recurse = B_TRUE;
1828 			break;
1829 		case '?':
1830 		default:
1831 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1832 			    optopt);
1833 			usage(B_FALSE);
1834 		}
1835 	}
1836 
1837 	argc -= optind;
1838 	argv += optind;
1839 
1840 	/* check number of arguments */
1841 	if (argc < 1) {
1842 		(void) fprintf(stderr, gettext("missing source dataset "
1843 		    "argument\n"));
1844 		usage(B_FALSE);
1845 	}
1846 	if (argc < 2) {
1847 		(void) fprintf(stderr, gettext("missing target dataset "
1848 		    "argument\n"));
1849 		usage(B_FALSE);
1850 	}
1851 	if (argc > 2) {
1852 		(void) fprintf(stderr, gettext("too many arguments\n"));
1853 		usage(B_FALSE);
1854 	}
1855 
1856 	if (recurse && parents) {
1857 		(void) fprintf(stderr, gettext("-p and -r options are mutually "
1858 		    "exclusive\n"));
1859 		usage(B_FALSE);
1860 	}
1861 
1862 	if (recurse && strchr(argv[0], '@') == 0) {
1863 		(void) fprintf(stderr, gettext("source dataset for recursive "
1864 		    "rename must be a snapshot\n"));
1865 		usage(B_FALSE);
1866 	}
1867 
1868 	if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
1869 	    ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
1870 		return (1);
1871 
1872 	/* If we were asked and the name looks good, try to create ancestors. */
1873 	if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
1874 	    zfs_create_ancestors(g_zfs, argv[1]) != 0) {
1875 		zfs_close(zhp);
1876 		return (1);
1877 	}
1878 
1879 	ret = (zfs_rename(zhp, argv[1], recurse) != 0);
1880 
1881 	zfs_close(zhp);
1882 	return (ret);
1883 }
1884 
1885 /*
1886  * zfs promote <fs>
1887  *
1888  * Promotes the given clone fs to be the parent
1889  */
1890 /* ARGSUSED */
1891 static int
1892 zfs_do_promote(int argc, char **argv)
1893 {
1894 	zfs_handle_t *zhp;
1895 	int ret;
1896 
1897 	/* check options */
1898 	if (argc > 1 && argv[1][0] == '-') {
1899 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1900 		    argv[1][1]);
1901 		usage(B_FALSE);
1902 	}
1903 
1904 	/* check number of arguments */
1905 	if (argc < 2) {
1906 		(void) fprintf(stderr, gettext("missing clone filesystem"
1907 		    " argument\n"));
1908 		usage(B_FALSE);
1909 	}
1910 	if (argc > 2) {
1911 		(void) fprintf(stderr, gettext("too many arguments\n"));
1912 		usage(B_FALSE);
1913 	}
1914 
1915 	zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1916 	if (zhp == NULL)
1917 		return (1);
1918 
1919 	ret = (zfs_promote(zhp) != 0);
1920 
1921 
1922 	zfs_close(zhp);
1923 	return (ret);
1924 }
1925 
1926 /*
1927  * zfs rollback [-rR] <snapshot>
1928  *
1929  * 	-r	Delete any intervening snapshots before doing rollback
1930  * 	-R	Delete any snapshots and their clones
1931  *
1932  * Given a filesystem, rollback to a specific snapshot, discarding any changes
1933  * since then and making it the active dataset.  If more recent snapshots exist,
1934  * the command will complain unless the '-r' flag is given.
1935  */
1936 typedef struct rollback_cbdata {
1937 	uint64_t	cb_create;
1938 	boolean_t	cb_first;
1939 	int		cb_doclones;
1940 	char		*cb_target;
1941 	int		cb_error;
1942 	boolean_t	cb_recurse;
1943 	boolean_t	cb_dependent;
1944 } rollback_cbdata_t;
1945 
1946 /*
1947  * Report any snapshots more recent than the one specified.  Used when '-r' is
1948  * not specified.  We reuse this same callback for the snapshot dependents - if
1949  * 'cb_dependent' is set, then this is a dependent and we should report it
1950  * without checking the transaction group.
1951  */
1952 static int
1953 rollback_check(zfs_handle_t *zhp, void *data)
1954 {
1955 	rollback_cbdata_t *cbp = data;
1956 
1957 	if (cbp->cb_doclones) {
1958 		zfs_close(zhp);
1959 		return (0);
1960 	}
1961 
1962 	if (!cbp->cb_dependent) {
1963 		if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
1964 		    zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
1965 		    zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
1966 		    cbp->cb_create) {
1967 
1968 			if (cbp->cb_first && !cbp->cb_recurse) {
1969 				(void) fprintf(stderr, gettext("cannot "
1970 				    "rollback to '%s': more recent snapshots "
1971 				    "exist\n"),
1972 				    cbp->cb_target);
1973 				(void) fprintf(stderr, gettext("use '-r' to "
1974 				    "force deletion of the following "
1975 				    "snapshots:\n"));
1976 				cbp->cb_first = 0;
1977 				cbp->cb_error = 1;
1978 			}
1979 
1980 			if (cbp->cb_recurse) {
1981 				cbp->cb_dependent = B_TRUE;
1982 				if (zfs_iter_dependents(zhp, B_TRUE,
1983 				    rollback_check, cbp) != 0) {
1984 					zfs_close(zhp);
1985 					return (-1);
1986 				}
1987 				cbp->cb_dependent = B_FALSE;
1988 			} else {
1989 				(void) fprintf(stderr, "%s\n",
1990 				    zfs_get_name(zhp));
1991 			}
1992 		}
1993 	} else {
1994 		if (cbp->cb_first && cbp->cb_recurse) {
1995 			(void) fprintf(stderr, gettext("cannot rollback to "
1996 			    "'%s': clones of previous snapshots exist\n"),
1997 			    cbp->cb_target);
1998 			(void) fprintf(stderr, gettext("use '-R' to "
1999 			    "force deletion of the following clones and "
2000 			    "dependents:\n"));
2001 			cbp->cb_first = 0;
2002 			cbp->cb_error = 1;
2003 		}
2004 
2005 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
2006 	}
2007 
2008 	zfs_close(zhp);
2009 	return (0);
2010 }
2011 
2012 static int
2013 zfs_do_rollback(int argc, char **argv)
2014 {
2015 	int ret;
2016 	int c;
2017 	rollback_cbdata_t cb = { 0 };
2018 	zfs_handle_t *zhp, *snap;
2019 	char parentname[ZFS_MAXNAMELEN];
2020 	char *delim;
2021 
2022 	/* check options */
2023 	while ((c = getopt(argc, argv, "rR")) != -1) {
2024 		switch (c) {
2025 		case 'r':
2026 			cb.cb_recurse = 1;
2027 			break;
2028 		case 'R':
2029 			cb.cb_recurse = 1;
2030 			cb.cb_doclones = 1;
2031 			break;
2032 		case '?':
2033 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2034 			    optopt);
2035 			usage(B_FALSE);
2036 		}
2037 	}
2038 
2039 	argc -= optind;
2040 	argv += optind;
2041 
2042 	/* check number of arguments */
2043 	if (argc < 1) {
2044 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
2045 		usage(B_FALSE);
2046 	}
2047 	if (argc > 1) {
2048 		(void) fprintf(stderr, gettext("too many arguments\n"));
2049 		usage(B_FALSE);
2050 	}
2051 
2052 	/* open the snapshot */
2053 	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2054 		return (1);
2055 
2056 	/* open the parent dataset */
2057 	(void) strlcpy(parentname, argv[0], sizeof (parentname));
2058 	verify((delim = strrchr(parentname, '@')) != NULL);
2059 	*delim = '\0';
2060 	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2061 		zfs_close(snap);
2062 		return (1);
2063 	}
2064 
2065 	/*
2066 	 * Check for more recent snapshots and/or clones based on the presence
2067 	 * of '-r' and '-R'.
2068 	 */
2069 	cb.cb_target = argv[0];
2070 	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2071 	cb.cb_first = B_TRUE;
2072 	cb.cb_error = 0;
2073 	if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2074 		goto out;
2075 
2076 	if ((ret = cb.cb_error) != 0)
2077 		goto out;
2078 
2079 	/*
2080 	 * Rollback parent to the given snapshot.
2081 	 */
2082 	ret = zfs_rollback(zhp, snap);
2083 
2084 out:
2085 	zfs_close(snap);
2086 	zfs_close(zhp);
2087 
2088 	if (ret == 0)
2089 		return (0);
2090 	else
2091 		return (1);
2092 }
2093 
2094 /*
2095  * zfs set property=value { fs | snap | vol } ...
2096  *
2097  * Sets the given property for all datasets specified on the command line.
2098  */
2099 typedef struct set_cbdata {
2100 	char		*cb_propname;
2101 	char		*cb_value;
2102 } set_cbdata_t;
2103 
2104 static int
2105 set_callback(zfs_handle_t *zhp, void *data)
2106 {
2107 	set_cbdata_t *cbp = data;
2108 
2109 	if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2110 		switch (libzfs_errno(g_zfs)) {
2111 		case EZFS_MOUNTFAILED:
2112 			(void) fprintf(stderr, gettext("property may be set "
2113 			    "but unable to remount filesystem\n"));
2114 			break;
2115 		case EZFS_SHARENFSFAILED:
2116 			(void) fprintf(stderr, gettext("property may be set "
2117 			    "but unable to reshare filesystem\n"));
2118 			break;
2119 		}
2120 		return (1);
2121 	}
2122 	return (0);
2123 }
2124 
2125 static int
2126 zfs_do_set(int argc, char **argv)
2127 {
2128 	set_cbdata_t cb;
2129 	int ret;
2130 
2131 	/* check for options */
2132 	if (argc > 1 && argv[1][0] == '-') {
2133 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2134 		    argv[1][1]);
2135 		usage(B_FALSE);
2136 	}
2137 
2138 	/* check number of arguments */
2139 	if (argc < 2) {
2140 		(void) fprintf(stderr, gettext("missing property=value "
2141 		    "argument\n"));
2142 		usage(B_FALSE);
2143 	}
2144 	if (argc < 3) {
2145 		(void) fprintf(stderr, gettext("missing dataset name\n"));
2146 		usage(B_FALSE);
2147 	}
2148 
2149 	/* validate property=value argument */
2150 	cb.cb_propname = argv[1];
2151 	if ((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) {
2152 		(void) fprintf(stderr, gettext("missing value in "
2153 		    "property=value argument\n"));
2154 		usage(B_FALSE);
2155 	}
2156 
2157 	*cb.cb_value = '\0';
2158 	cb.cb_value++;
2159 
2160 	if (*cb.cb_propname == '\0') {
2161 		(void) fprintf(stderr,
2162 		    gettext("missing property in property=value argument\n"));
2163 		usage(B_FALSE);
2164 	}
2165 
2166 
2167 	ret = zfs_for_each(argc - 2, argv + 2, B_FALSE,
2168 	    ZFS_TYPE_DATASET, NULL, NULL, set_callback, &cb, B_FALSE);
2169 
2170 	return (ret);
2171 }
2172 
2173 /*
2174  * zfs snapshot [-r] <fs@snap>
2175  *
2176  * Creates a snapshot with the given name.  While functionally equivalent to
2177  * 'zfs create', it is a separate command to differentiate intent.
2178  */
2179 static int
2180 zfs_do_snapshot(int argc, char **argv)
2181 {
2182 	boolean_t recursive = B_FALSE;
2183 	int ret;
2184 	char c;
2185 
2186 	/* check options */
2187 	while ((c = getopt(argc, argv, ":r")) != -1) {
2188 		switch (c) {
2189 		case 'r':
2190 			recursive = B_TRUE;
2191 			break;
2192 		case '?':
2193 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2194 			    optopt);
2195 			usage(B_FALSE);
2196 		}
2197 	}
2198 
2199 	argc -= optind;
2200 	argv += optind;
2201 
2202 	/* check number of arguments */
2203 	if (argc < 1) {
2204 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2205 		usage(B_FALSE);
2206 	}
2207 	if (argc > 1) {
2208 		(void) fprintf(stderr, gettext("too many arguments\n"));
2209 		usage(B_FALSE);
2210 	}
2211 
2212 	ret = zfs_snapshot(g_zfs, argv[0], recursive);
2213 	if (ret && recursive)
2214 		(void) fprintf(stderr, gettext("no snapshots were created\n"));
2215 	return (ret != 0);
2216 }
2217 
2218 /*
2219  * zfs send [-v] -R [-i|-I <@snap>] <fs@snap>
2220  * zfs send [-v] [-i|-I <@snap>] <fs@snap>
2221  *
2222  * Send a backup stream to stdout.
2223  */
2224 static int
2225 zfs_do_send(int argc, char **argv)
2226 {
2227 	char *fromname = NULL;
2228 	char *toname = NULL;
2229 	char *cp;
2230 	zfs_handle_t *zhp;
2231 	boolean_t doall = B_FALSE;
2232 	boolean_t replicate = B_FALSE;
2233 	boolean_t fromorigin = B_FALSE;
2234 	boolean_t verbose = B_FALSE;
2235 	int c, err;
2236 
2237 	/* check options */
2238 	while ((c = getopt(argc, argv, ":i:I:Rv")) != -1) {
2239 		switch (c) {
2240 		case 'i':
2241 			if (fromname)
2242 				usage(B_FALSE);
2243 			fromname = optarg;
2244 			break;
2245 		case 'I':
2246 			if (fromname)
2247 				usage(B_FALSE);
2248 			fromname = optarg;
2249 			doall = B_TRUE;
2250 			break;
2251 		case 'R':
2252 			replicate = B_TRUE;
2253 			break;
2254 		case 'v':
2255 			verbose = B_TRUE;
2256 			break;
2257 		case ':':
2258 			(void) fprintf(stderr, gettext("missing argument for "
2259 			    "'%c' option\n"), optopt);
2260 			usage(B_FALSE);
2261 			break;
2262 		case '?':
2263 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2264 			    optopt);
2265 			usage(B_FALSE);
2266 		}
2267 	}
2268 
2269 	argc -= optind;
2270 	argv += optind;
2271 
2272 	/* check number of arguments */
2273 	if (argc < 1) {
2274 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2275 		usage(B_FALSE);
2276 	}
2277 	if (argc > 1) {
2278 		(void) fprintf(stderr, gettext("too many arguments\n"));
2279 		usage(B_FALSE);
2280 	}
2281 
2282 	if (isatty(STDOUT_FILENO)) {
2283 		(void) fprintf(stderr,
2284 		    gettext("Error: Stream can not be written to a terminal.\n"
2285 		    "You must redirect standard output.\n"));
2286 		return (1);
2287 	}
2288 
2289 	cp = strchr(argv[0], '@');
2290 	if (cp == NULL) {
2291 		(void) fprintf(stderr,
2292 		    gettext("argument must be a snapshot\n"));
2293 		usage(B_FALSE);
2294 	}
2295 	*cp = '\0';
2296 	toname = cp + 1;
2297 	zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2298 	if (zhp == NULL)
2299 		return (1);
2300 
2301 	/*
2302 	 * If they specified the full path to the snapshot, chop off
2303 	 * everything except the short name of the snapshot, but special
2304 	 * case if they specify the origin.
2305 	 */
2306 	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2307 		char origin[ZFS_MAXNAMELEN];
2308 		zprop_source_t src;
2309 
2310 		(void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2311 		    origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2312 
2313 		if (strcmp(origin, fromname) == 0) {
2314 			fromname = NULL;
2315 			fromorigin = B_TRUE;
2316 		} else {
2317 			*cp = '\0';
2318 			if (cp != fromname && strcmp(argv[0], fromname)) {
2319 				(void) fprintf(stderr,
2320 				    gettext("incremental source must be "
2321 				    "in same filesystem\n"));
2322 				usage(B_FALSE);
2323 			}
2324 			fromname = cp + 1;
2325 			if (strchr(fromname, '@') || strchr(fromname, '/')) {
2326 				(void) fprintf(stderr,
2327 				    gettext("invalid incremental source\n"));
2328 				usage(B_FALSE);
2329 			}
2330 		}
2331 	}
2332 
2333 	if (replicate && fromname == NULL)
2334 		doall = B_TRUE;
2335 
2336 	err = zfs_send(zhp, fromname, toname, replicate, doall, fromorigin,
2337 	    verbose, STDOUT_FILENO);
2338 	zfs_close(zhp);
2339 
2340 	return (err != 0);
2341 }
2342 
2343 /*
2344  * zfs receive [-dnvF] <fs@snap>
2345  *
2346  * Restore a backup stream from stdin.
2347  */
2348 static int
2349 zfs_do_receive(int argc, char **argv)
2350 {
2351 	int c, err;
2352 	recvflags_t flags;
2353 
2354 	bzero(&flags, sizeof (recvflags_t));
2355 	/* check options */
2356 	while ((c = getopt(argc, argv, ":dnvF")) != -1) {
2357 		switch (c) {
2358 		case 'd':
2359 			flags.isprefix = B_TRUE;
2360 			break;
2361 		case 'n':
2362 			flags.dryrun = B_TRUE;
2363 			break;
2364 		case 'v':
2365 			flags.verbose = B_TRUE;
2366 			break;
2367 		case 'F':
2368 			flags.force = B_TRUE;
2369 			break;
2370 		case ':':
2371 			(void) fprintf(stderr, gettext("missing argument for "
2372 			    "'%c' option\n"), optopt);
2373 			usage(B_FALSE);
2374 			break;
2375 		case '?':
2376 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2377 			    optopt);
2378 			usage(B_FALSE);
2379 		}
2380 	}
2381 
2382 	argc -= optind;
2383 	argv += optind;
2384 
2385 	/* check number of arguments */
2386 	if (argc < 1) {
2387 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2388 		usage(B_FALSE);
2389 	}
2390 	if (argc > 1) {
2391 		(void) fprintf(stderr, gettext("too many arguments\n"));
2392 		usage(B_FALSE);
2393 	}
2394 
2395 	if (isatty(STDIN_FILENO)) {
2396 		(void) fprintf(stderr,
2397 		    gettext("Error: Backup stream can not be read "
2398 		    "from a terminal.\n"
2399 		    "You must redirect standard input.\n"));
2400 		return (1);
2401 	}
2402 
2403 	err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2404 
2405 	return (err != 0);
2406 }
2407 
2408 typedef struct allow_cb {
2409 	int  a_permcnt;
2410 	size_t a_treeoffset;
2411 } allow_cb_t;
2412 
2413 static void
2414 zfs_print_perms(avl_tree_t *tree)
2415 {
2416 	zfs_perm_node_t *permnode;
2417 
2418 	permnode = avl_first(tree);
2419 	while (permnode != NULL) {
2420 		(void) printf("%s", permnode->z_pname);
2421 		permnode = AVL_NEXT(tree, permnode);
2422 		if (permnode)
2423 			(void) printf(",");
2424 		else
2425 			(void) printf("\n");
2426 	}
2427 }
2428 
2429 /*
2430  * Iterate over user/groups/everyone/... and the call perm_iter
2431  * function to print actual permission when tree has >0 nodes.
2432  */
2433 static void
2434 zfs_iter_perms(avl_tree_t *tree, const char *banner, allow_cb_t *cb)
2435 {
2436 	zfs_allow_node_t *item;
2437 	avl_tree_t *ptree;
2438 
2439 	item = avl_first(tree);
2440 	while (item) {
2441 		ptree = (void *)((char *)item + cb->a_treeoffset);
2442 		if (avl_numnodes(ptree)) {
2443 			if (cb->a_permcnt++ == 0)
2444 				(void) printf("%s\n", banner);
2445 			(void) printf("\t%s", item->z_key);
2446 			/*
2447 			 * Avoid an extra space being printed
2448 			 * for "everyone" which is keyed with a null
2449 			 * string
2450 			 */
2451 			if (item->z_key[0] != '\0')
2452 				(void) printf(" ");
2453 			zfs_print_perms(ptree);
2454 		}
2455 		item = AVL_NEXT(tree, item);
2456 	}
2457 }
2458 
2459 #define	LINES "-------------------------------------------------------------\n"
2460 static int
2461 zfs_print_allows(char *ds)
2462 {
2463 	zfs_allow_t *curperms, *perms;
2464 	zfs_handle_t *zhp;
2465 	allow_cb_t allowcb = { 0 };
2466 	char banner[MAXPATHLEN];
2467 
2468 	if (ds[0] == '-')
2469 		usage(B_FALSE);
2470 
2471 	if (strrchr(ds, '@')) {
2472 		(void) fprintf(stderr, gettext("Snapshots don't have 'allow'"
2473 		    " permissions\n"));
2474 		return (1);
2475 	}
2476 	if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2477 		return (1);
2478 
2479 	if (zfs_perm_get(zhp, &perms)) {
2480 		(void) fprintf(stderr,
2481 		    gettext("Failed to retrieve 'allows' on %s\n"), ds);
2482 		zfs_close(zhp);
2483 		return (1);
2484 	}
2485 
2486 	zfs_close(zhp);
2487 
2488 	if (perms != NULL)
2489 		(void) printf("%s", LINES);
2490 	for (curperms = perms; curperms; curperms = curperms->z_next) {
2491 
2492 		(void) snprintf(banner, sizeof (banner),
2493 		    "Permission sets on (%s)", curperms->z_setpoint);
2494 		allowcb.a_treeoffset =
2495 		    offsetof(zfs_allow_node_t, z_localdescend);
2496 		allowcb.a_permcnt = 0;
2497 		zfs_iter_perms(&curperms->z_sets, banner, &allowcb);
2498 
2499 		(void) snprintf(banner, sizeof (banner),
2500 		    "Create time permissions on (%s)", curperms->z_setpoint);
2501 		allowcb.a_treeoffset =
2502 		    offsetof(zfs_allow_node_t, z_localdescend);
2503 		allowcb.a_permcnt = 0;
2504 		zfs_iter_perms(&curperms->z_crperms, banner, &allowcb);
2505 
2506 
2507 		(void) snprintf(banner, sizeof (banner),
2508 		    "Local permissions on (%s)", curperms->z_setpoint);
2509 		allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_local);
2510 		allowcb.a_permcnt = 0;
2511 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2512 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2513 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2514 
2515 		(void) snprintf(banner, sizeof (banner),
2516 		    "Descendent permissions on (%s)", curperms->z_setpoint);
2517 		allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_descend);
2518 		allowcb.a_permcnt = 0;
2519 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2520 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2521 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2522 
2523 		(void) snprintf(banner, sizeof (banner),
2524 		    "Local+Descendent permissions on (%s)",
2525 		    curperms->z_setpoint);
2526 		allowcb.a_treeoffset =
2527 		    offsetof(zfs_allow_node_t, z_localdescend);
2528 		allowcb.a_permcnt = 0;
2529 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2530 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2531 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2532 
2533 		(void) printf("%s", LINES);
2534 	}
2535 	zfs_free_allows(perms);
2536 	return (0);
2537 }
2538 
2539 #define	ALLOWOPTIONS "ldcsu:g:e"
2540 #define	UNALLOWOPTIONS "ldcsu:g:er"
2541 
2542 /*
2543  * Validate options, and build necessary datastructure to display/remove/add
2544  * permissions.
2545  * Returns 0 - If permissions should be added/removed
2546  * Returns 1 - If permissions should be displayed.
2547  * Returns -1 - on failure
2548  */
2549 int
2550 parse_allow_args(int *argc, char **argv[], boolean_t unallow,
2551     char **ds, int *recurse, nvlist_t **zperms)
2552 {
2553 	int c;
2554 	char *options = unallow ? UNALLOWOPTIONS : ALLOWOPTIONS;
2555 	zfs_deleg_inherit_t deleg_type = ZFS_DELEG_NONE;
2556 	zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
2557 	char *who = NULL;
2558 	char *perms = NULL;
2559 	zfs_handle_t *zhp;
2560 
2561 	while ((c = getopt(*argc, *argv, options)) != -1) {
2562 		switch (c) {
2563 		case 'l':
2564 			if (who_type == ZFS_DELEG_CREATE ||
2565 			    who_type == ZFS_DELEG_NAMED_SET)
2566 				usage(B_FALSE);
2567 
2568 			deleg_type |= ZFS_DELEG_PERM_LOCAL;
2569 			break;
2570 		case 'd':
2571 			if (who_type == ZFS_DELEG_CREATE ||
2572 			    who_type == ZFS_DELEG_NAMED_SET)
2573 				usage(B_FALSE);
2574 
2575 			deleg_type |= ZFS_DELEG_PERM_DESCENDENT;
2576 			break;
2577 		case 'r':
2578 			*recurse = B_TRUE;
2579 			break;
2580 		case 'c':
2581 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2582 				usage(B_FALSE);
2583 			if (deleg_type)
2584 				usage(B_FALSE);
2585 			who_type = ZFS_DELEG_CREATE;
2586 			break;
2587 		case 's':
2588 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2589 				usage(B_FALSE);
2590 			if (deleg_type)
2591 				usage(B_FALSE);
2592 			who_type = ZFS_DELEG_NAMED_SET;
2593 			break;
2594 		case 'u':
2595 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2596 				usage(B_FALSE);
2597 			who_type = ZFS_DELEG_USER;
2598 			who = optarg;
2599 			break;
2600 		case 'g':
2601 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2602 				usage(B_FALSE);
2603 			who_type = ZFS_DELEG_GROUP;
2604 			who = optarg;
2605 			break;
2606 		case 'e':
2607 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2608 				usage(B_FALSE);
2609 			who_type = ZFS_DELEG_EVERYONE;
2610 			break;
2611 		default:
2612 			usage(B_FALSE);
2613 			break;
2614 		}
2615 	}
2616 
2617 	if (deleg_type == 0)
2618 		deleg_type = ZFS_DELEG_PERM_LOCALDESCENDENT;
2619 
2620 	*argc -= optind;
2621 	*argv += optind;
2622 
2623 	if (unallow == B_FALSE && *argc == 1) {
2624 		/*
2625 		 * Only print permissions if no options were processed
2626 		 */
2627 		if (optind == 1)
2628 			return (1);
2629 		else
2630 			usage(B_FALSE);
2631 	}
2632 
2633 	/*
2634 	 * initialize variables for zfs_build_perms based on number
2635 	 * of arguments.
2636 	 * 3 arguments ==>	zfs [un]allow joe perm,perm,perm <dataset> or
2637 	 *			zfs [un]allow -s @set1 perm,perm <dataset>
2638 	 * 2 arguments ==>	zfs [un]allow -c perm,perm <dataset> or
2639 	 *			zfs [un]allow -u|-g <name> perm <dataset> or
2640 	 *			zfs [un]allow -e perm,perm <dataset>
2641 	 *			zfs unallow joe <dataset>
2642 	 *			zfs unallow -s @set1 <dataset>
2643 	 * 1 argument  ==>	zfs [un]allow -e <dataset> or
2644 	 *			zfs [un]allow -c <dataset>
2645 	 */
2646 
2647 	switch (*argc) {
2648 	case 3:
2649 		perms = (*argv)[1];
2650 		who = (*argv)[0];
2651 		*ds = (*argv)[2];
2652 
2653 		/*
2654 		 * advance argc/argv for do_allow cases.
2655 		 * for do_allow case make sure who have a know who type
2656 		 * and its not a permission set.
2657 		 */
2658 		if (unallow == B_TRUE) {
2659 			*argc -= 2;
2660 			*argv += 2;
2661 		} else if (who_type != ZFS_DELEG_WHO_UNKNOWN &&
2662 		    who_type != ZFS_DELEG_NAMED_SET)
2663 			usage(B_FALSE);
2664 		break;
2665 
2666 	case 2:
2667 		if (unallow == B_TRUE && (who_type == ZFS_DELEG_EVERYONE ||
2668 		    who_type == ZFS_DELEG_CREATE || who != NULL)) {
2669 			perms = (*argv)[0];
2670 			*ds = (*argv)[1];
2671 		} else {
2672 			if (unallow == B_FALSE &&
2673 			    (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2674 			    who_type == ZFS_DELEG_NAMED_SET))
2675 				usage(B_FALSE);
2676 			else if (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2677 			    who_type == ZFS_DELEG_NAMED_SET)
2678 				who = (*argv)[0];
2679 			else if (who_type != ZFS_DELEG_NAMED_SET)
2680 				perms = (*argv)[0];
2681 			*ds = (*argv)[1];
2682 		}
2683 		if (unallow == B_TRUE) {
2684 			(*argc)--;
2685 			(*argv)++;
2686 		}
2687 		break;
2688 
2689 	case 1:
2690 		if (unallow == B_FALSE)
2691 			usage(B_FALSE);
2692 		if (who == NULL && who_type != ZFS_DELEG_CREATE &&
2693 		    who_type != ZFS_DELEG_EVERYONE)
2694 			usage(B_FALSE);
2695 		*ds = (*argv)[0];
2696 		break;
2697 
2698 	default:
2699 		usage(B_FALSE);
2700 	}
2701 
2702 	if (strrchr(*ds, '@')) {
2703 		(void) fprintf(stderr,
2704 		    gettext("Can't set or remove 'allow' permissions "
2705 		    "on snapshots.\n"));
2706 			return (-1);
2707 	}
2708 
2709 	if ((zhp = zfs_open(g_zfs, *ds, ZFS_TYPE_DATASET)) == NULL)
2710 		return (-1);
2711 
2712 	if ((zfs_build_perms(zhp, who, perms,
2713 	    who_type, deleg_type, zperms)) != 0) {
2714 		zfs_close(zhp);
2715 		return (-1);
2716 	}
2717 	zfs_close(zhp);
2718 	return (0);
2719 }
2720 
2721 static int
2722 zfs_do_allow(int argc, char **argv)
2723 {
2724 	char *ds;
2725 	nvlist_t *zperms = NULL;
2726 	zfs_handle_t *zhp;
2727 	int unused;
2728 	int ret;
2729 
2730 	if ((ret = parse_allow_args(&argc, &argv, B_FALSE, &ds,
2731 	    &unused, &zperms)) == -1)
2732 		return (1);
2733 
2734 	if (ret == 1)
2735 		return (zfs_print_allows(argv[0]));
2736 
2737 	if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2738 		return (1);
2739 
2740 	if (zfs_perm_set(zhp, zperms)) {
2741 		zfs_close(zhp);
2742 		nvlist_free(zperms);
2743 		return (1);
2744 	}
2745 	nvlist_free(zperms);
2746 	zfs_close(zhp);
2747 
2748 	return (0);
2749 }
2750 
2751 static int
2752 unallow_callback(zfs_handle_t *zhp, void *data)
2753 {
2754 	nvlist_t *nvp = (nvlist_t *)data;
2755 	int error;
2756 
2757 	error = zfs_perm_remove(zhp, nvp);
2758 	if (error) {
2759 		(void) fprintf(stderr, gettext("Failed to remove permissions "
2760 		    "on %s\n"), zfs_get_name(zhp));
2761 	}
2762 	return (error);
2763 }
2764 
2765 static int
2766 zfs_do_unallow(int argc, char **argv)
2767 {
2768 	int recurse = B_FALSE;
2769 	char *ds;
2770 	int error;
2771 	nvlist_t *zperms = NULL;
2772 
2773 	if (parse_allow_args(&argc, &argv, B_TRUE,
2774 	    &ds, &recurse, &zperms) == -1)
2775 		return (1);
2776 
2777 	error = zfs_for_each(argc, argv, recurse,
2778 	    ZFS_TYPE_FILESYSTEM|ZFS_TYPE_VOLUME, NULL,
2779 	    NULL, unallow_callback, (void *)zperms, B_FALSE);
2780 
2781 	if (zperms)
2782 		nvlist_free(zperms);
2783 
2784 	return (error);
2785 }
2786 
2787 typedef struct get_all_cbdata {
2788 	zfs_handle_t	**cb_handles;
2789 	size_t		cb_alloc;
2790 	size_t		cb_used;
2791 	uint_t		cb_types;
2792 	boolean_t	cb_verbose;
2793 } get_all_cbdata_t;
2794 
2795 #define	CHECK_SPINNER 30
2796 #define	SPINNER_TIME 3		/* seconds */
2797 #define	MOUNT_TIME 5		/* seconds */
2798 
2799 static int
2800 get_one_dataset(zfs_handle_t *zhp, void *data)
2801 {
2802 	static char spin[] = { '-', '\\', '|', '/' };
2803 	static int spinval = 0;
2804 	static int spincheck = 0;
2805 	static time_t last_spin_time = (time_t)0;
2806 	get_all_cbdata_t *cbp = data;
2807 	zfs_type_t type = zfs_get_type(zhp);
2808 
2809 	if (cbp->cb_verbose) {
2810 		if (--spincheck < 0) {
2811 			time_t now = time(NULL);
2812 			if (last_spin_time + SPINNER_TIME < now) {
2813 				(void) printf("\b%c", spin[spinval++ % 4]);
2814 				(void) fflush(stdout);
2815 				last_spin_time = now;
2816 			}
2817 			spincheck = CHECK_SPINNER;
2818 		}
2819 	}
2820 
2821 	/*
2822 	 * Interate over any nested datasets.
2823 	 */
2824 	if (type == ZFS_TYPE_FILESYSTEM &&
2825 	    zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2826 		zfs_close(zhp);
2827 		return (1);
2828 	}
2829 
2830 	/*
2831 	 * Skip any datasets whose type does not match.
2832 	 */
2833 	if ((type & cbp->cb_types) == 0) {
2834 		zfs_close(zhp);
2835 		return (0);
2836 	}
2837 
2838 	if (cbp->cb_alloc == cbp->cb_used) {
2839 		zfs_handle_t **handles;
2840 
2841 		if (cbp->cb_alloc == 0)
2842 			cbp->cb_alloc = 64;
2843 		else
2844 			cbp->cb_alloc *= 2;
2845 
2846 		handles = safe_malloc(cbp->cb_alloc * sizeof (void *));
2847 
2848 		if (cbp->cb_handles) {
2849 			bcopy(cbp->cb_handles, handles,
2850 			    cbp->cb_used * sizeof (void *));
2851 			free(cbp->cb_handles);
2852 		}
2853 
2854 		cbp->cb_handles = handles;
2855 	}
2856 
2857 	cbp->cb_handles[cbp->cb_used++] = zhp;
2858 
2859 	return (0);
2860 }
2861 
2862 static void
2863 get_all_datasets(uint_t types, zfs_handle_t ***dslist, size_t *count,
2864     boolean_t verbose)
2865 {
2866 	get_all_cbdata_t cb = { 0 };
2867 	cb.cb_types = types;
2868 	cb.cb_verbose = verbose;
2869 
2870 	if (verbose) {
2871 		(void) printf("%s: *", gettext("Reading ZFS config"));
2872 		(void) fflush(stdout);
2873 	}
2874 
2875 	(void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2876 
2877 	*dslist = cb.cb_handles;
2878 	*count = cb.cb_used;
2879 
2880 	if (verbose) {
2881 		(void) printf("\b%s\n", gettext("done."));
2882 	}
2883 }
2884 
2885 static int
2886 dataset_cmp(const void *a, const void *b)
2887 {
2888 	zfs_handle_t **za = (zfs_handle_t **)a;
2889 	zfs_handle_t **zb = (zfs_handle_t **)b;
2890 	char mounta[MAXPATHLEN];
2891 	char mountb[MAXPATHLEN];
2892 	boolean_t gota, gotb;
2893 
2894 	if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
2895 		verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
2896 		    sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
2897 	if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
2898 		verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
2899 		    sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
2900 
2901 	if (gota && gotb)
2902 		return (strcmp(mounta, mountb));
2903 
2904 	if (gota)
2905 		return (-1);
2906 	if (gotb)
2907 		return (1);
2908 
2909 	return (strcmp(zfs_get_name(a), zfs_get_name(b)));
2910 }
2911 
2912 /*
2913  * Generic callback for sharing or mounting filesystems.  Because the code is so
2914  * similar, we have a common function with an extra parameter to determine which
2915  * mode we are using.
2916  */
2917 #define	OP_SHARE	0x1
2918 #define	OP_MOUNT	0x2
2919 
2920 /*
2921  * Share or mount a dataset.
2922  */
2923 static int
2924 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
2925     boolean_t explicit, const char *options)
2926 {
2927 	char mountpoint[ZFS_MAXPROPLEN];
2928 	char shareopts[ZFS_MAXPROPLEN];
2929 	char smbshareopts[ZFS_MAXPROPLEN];
2930 	const char *cmdname = op == OP_SHARE ? "share" : "mount";
2931 	struct mnttab mnt;
2932 	uint64_t zoned, canmount;
2933 	zfs_type_t type = zfs_get_type(zhp);
2934 	boolean_t shared_nfs, shared_smb;
2935 
2936 	assert(type & (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME));
2937 
2938 	if (type == ZFS_TYPE_FILESYSTEM) {
2939 		/*
2940 		 * Check to make sure we can mount/share this dataset.  If we
2941 		 * are in the global zone and the filesystem is exported to a
2942 		 * local zone, or if we are in a local zone and the
2943 		 * filesystem is not exported, then it is an error.
2944 		 */
2945 		zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2946 
2947 		if (zoned && getzoneid() == GLOBAL_ZONEID) {
2948 			if (!explicit)
2949 				return (0);
2950 
2951 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2952 			    "dataset is exported to a local zone\n"), cmdname,
2953 			    zfs_get_name(zhp));
2954 			return (1);
2955 
2956 		} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
2957 			if (!explicit)
2958 				return (0);
2959 
2960 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2961 			    "permission denied\n"), cmdname,
2962 			    zfs_get_name(zhp));
2963 			return (1);
2964 		}
2965 
2966 		/*
2967 		 * Ignore any filesystems which don't apply to us. This
2968 		 * includes those with a legacy mountpoint, or those with
2969 		 * legacy share options.
2970 		 */
2971 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
2972 		    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
2973 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
2974 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
2975 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
2976 		    sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
2977 		canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
2978 
2979 		if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
2980 		    strcmp(smbshareopts, "off") == 0) {
2981 			if (!explicit)
2982 				return (0);
2983 
2984 			(void) fprintf(stderr, gettext("cannot share '%s': "
2985 			    "legacy share\n"), zfs_get_name(zhp));
2986 			(void) fprintf(stderr, gettext("use share(1M) to "
2987 			    "share this filesystem\n"));
2988 			return (1);
2989 		}
2990 
2991 		/*
2992 		 * We cannot share or mount legacy filesystems. If the
2993 		 * shareopts is non-legacy but the mountpoint is legacy, we
2994 		 * treat it as a legacy share.
2995 		 */
2996 		if (strcmp(mountpoint, "legacy") == 0) {
2997 			if (!explicit)
2998 				return (0);
2999 
3000 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3001 			    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3002 			(void) fprintf(stderr, gettext("use %s(1M) to "
3003 			    "%s this filesystem\n"), cmdname, cmdname);
3004 			return (1);
3005 		}
3006 
3007 		if (strcmp(mountpoint, "none") == 0) {
3008 			if (!explicit)
3009 				return (0);
3010 
3011 			(void) fprintf(stderr, gettext("cannot %s '%s': no "
3012 			    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3013 			return (1);
3014 		}
3015 
3016 		if (!canmount) {
3017 			if (!explicit)
3018 				return (0);
3019 
3020 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3021 			    "'canmount' property is set to 'off'\n"), cmdname,
3022 			    zfs_get_name(zhp));
3023 			return (1);
3024 		}
3025 
3026 		/*
3027 		 * At this point, we have verified that the mountpoint and/or
3028 		 * shareopts are appropriate for auto management. If the
3029 		 * filesystem is already mounted or shared, return (failing
3030 		 * for explicit requests); otherwise mount or share the
3031 		 * filesystem.
3032 		 */
3033 		switch (op) {
3034 		case OP_SHARE:
3035 
3036 			shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3037 			shared_smb = zfs_is_shared_smb(zhp, NULL);
3038 
3039 			if (shared_nfs && shared_smb ||
3040 			    (shared_nfs && strcmp(shareopts, "on") == 0 &&
3041 			    strcmp(smbshareopts, "off") == 0) ||
3042 			    (shared_smb && strcmp(smbshareopts, "on") == 0 &&
3043 			    strcmp(shareopts, "off") == 0)) {
3044 				if (!explicit)
3045 					return (0);
3046 
3047 				(void) fprintf(stderr, gettext("cannot share "
3048 				    "'%s': filesystem already shared\n"),
3049 				    zfs_get_name(zhp));
3050 				return (1);
3051 			}
3052 
3053 			if (!zfs_is_mounted(zhp, NULL) &&
3054 			    zfs_mount(zhp, NULL, 0) != 0)
3055 				return (1);
3056 
3057 			if (protocol == NULL) {
3058 				if (zfs_shareall(zhp) != 0)
3059 					return (1);
3060 			} else if (strcmp(protocol, "nfs") == 0) {
3061 				if (zfs_share_nfs(zhp))
3062 					return (1);
3063 			} else if (strcmp(protocol, "smb") == 0) {
3064 				if (zfs_share_smb(zhp))
3065 					return (1);
3066 			} else {
3067 				(void) fprintf(stderr, gettext("cannot share "
3068 				    "'%s': invalid share type '%s' "
3069 				    "specified\n"),
3070 				    zfs_get_name(zhp), protocol);
3071 				return (1);
3072 			}
3073 
3074 			break;
3075 
3076 		case OP_MOUNT:
3077 			if (options == NULL)
3078 				mnt.mnt_mntopts = "";
3079 			else
3080 				mnt.mnt_mntopts = (char *)options;
3081 
3082 			if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3083 			    zfs_is_mounted(zhp, NULL)) {
3084 				if (!explicit)
3085 					return (0);
3086 
3087 				(void) fprintf(stderr, gettext("cannot mount "
3088 				    "'%s': filesystem already mounted\n"),
3089 				    zfs_get_name(zhp));
3090 				return (1);
3091 			}
3092 
3093 			if (zfs_mount(zhp, options, flags) != 0)
3094 				return (1);
3095 			break;
3096 		}
3097 	} else {
3098 		assert(op == OP_SHARE);
3099 
3100 		/*
3101 		 * Ignore any volumes that aren't shared.
3102 		 */
3103 		verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, shareopts,
3104 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3105 
3106 		if (strcmp(shareopts, "off") == 0) {
3107 			if (!explicit)
3108 				return (0);
3109 
3110 			(void) fprintf(stderr, gettext("cannot share '%s': "
3111 			    "'shareiscsi' property not set\n"),
3112 			    zfs_get_name(zhp));
3113 			(void) fprintf(stderr, gettext("set 'shareiscsi' "
3114 			    "property or use iscsitadm(1M) to share this "
3115 			    "volume\n"));
3116 			return (1);
3117 		}
3118 
3119 		if (zfs_is_shared_iscsi(zhp)) {
3120 			if (!explicit)
3121 				return (0);
3122 
3123 			(void) fprintf(stderr, gettext("cannot share "
3124 			    "'%s': volume already shared\n"),
3125 			    zfs_get_name(zhp));
3126 			return (1);
3127 		}
3128 
3129 		if (zfs_share_iscsi(zhp) != 0)
3130 			return (1);
3131 	}
3132 
3133 	return (0);
3134 }
3135 
3136 /*
3137  * Reports progress in the form "(current/total)".  Not thread-safe.
3138  */
3139 static void
3140 report_mount_progress(int current, int total)
3141 {
3142 	static int len;
3143 	static char *reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
3144 	    "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
3145 	static time_t last_progress_time;
3146 	time_t now = time(NULL);
3147 
3148 	/* report 1..n instead of 0..n-1 */
3149 	++current;
3150 
3151 	/* display header if we're here for the first time */
3152 	if (current == 1) {
3153 		(void) printf(gettext("Mounting ZFS filesystems: "));
3154 		len = 0;
3155 	} else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3156 		/* too soon to report again */
3157 		return;
3158 	}
3159 
3160 	last_progress_time = now;
3161 
3162 	/* back up to prepare for overwriting */
3163 	if (len)
3164 		(void) printf("%*.*s", len, len, reverse);
3165 
3166 	/* We put a newline at the end if this is the last one.  */
3167 	len = printf("(%d/%d)%s", current, total, current == total ? "\n" : "");
3168 	(void) fflush(stdout);
3169 }
3170 
3171 static int
3172 share_mount(int op, int argc, char **argv)
3173 {
3174 	int do_all = 0;
3175 	boolean_t verbose = B_FALSE;
3176 	int c, ret = 0;
3177 	const char *options = NULL;
3178 	int types, flags = 0;
3179 
3180 	/* check options */
3181 	while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
3182 	    != -1) {
3183 		switch (c) {
3184 		case 'a':
3185 			do_all = 1;
3186 			break;
3187 		case 'v':
3188 			verbose = B_TRUE;
3189 			break;
3190 		case 'o':
3191 			if (strlen(optarg) <= MNT_LINE_MAX) {
3192 				options = optarg;
3193 				break;
3194 			}
3195 			(void) fprintf(stderr, gettext("the opts argument for "
3196 			    "'%c' option is too long (more than %d chars)\n"),
3197 			    optopt, MNT_LINE_MAX);
3198 			usage(B_FALSE);
3199 			break;
3200 
3201 		case 'O':
3202 			flags |= MS_OVERLAY;
3203 			break;
3204 		case ':':
3205 			(void) fprintf(stderr, gettext("missing argument for "
3206 			    "'%c' option\n"), optopt);
3207 			usage(B_FALSE);
3208 			break;
3209 		case '?':
3210 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3211 			    optopt);
3212 			usage(B_FALSE);
3213 		}
3214 	}
3215 
3216 	argc -= optind;
3217 	argv += optind;
3218 
3219 	/* check number of arguments */
3220 	if (do_all) {
3221 		zfs_handle_t **dslist = NULL;
3222 		size_t i, count = 0;
3223 		char *protocol = NULL;
3224 
3225 		if (op == OP_MOUNT) {
3226 			types = ZFS_TYPE_FILESYSTEM;
3227 		} else if (argc > 0) {
3228 			if (strcmp(argv[0], "nfs") == 0 ||
3229 			    strcmp(argv[0], "smb") == 0) {
3230 				types = ZFS_TYPE_FILESYSTEM;
3231 			} else if (strcmp(argv[0], "iscsi") == 0) {
3232 				types = ZFS_TYPE_VOLUME;
3233 			} else {
3234 				(void) fprintf(stderr, gettext("share type "
3235 				    "must be 'nfs', 'smb' or 'iscsi'\n"));
3236 				usage(B_FALSE);
3237 			}
3238 			protocol = argv[0];
3239 			argc--;
3240 			argv++;
3241 		} else {
3242 			types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3243 		}
3244 
3245 		if (argc != 0) {
3246 			(void) fprintf(stderr, gettext("too many arguments\n"));
3247 			usage(B_FALSE);
3248 		}
3249 
3250 		get_all_datasets(types, &dslist, &count, verbose);
3251 
3252 		if (count == 0)
3253 			return (0);
3254 
3255 		qsort(dslist, count, sizeof (void *), dataset_cmp);
3256 
3257 		for (i = 0; i < count; i++) {
3258 			if (verbose)
3259 				report_mount_progress(i, count);
3260 
3261 			if (share_mount_one(dslist[i], op, flags, protocol,
3262 			    B_FALSE, options) != 0)
3263 				ret = 1;
3264 			zfs_close(dslist[i]);
3265 		}
3266 
3267 		free(dslist);
3268 	} else if (argc == 0) {
3269 		struct mnttab entry;
3270 
3271 		if ((op == OP_SHARE) || (options != NULL)) {
3272 			(void) fprintf(stderr, gettext("missing filesystem "
3273 			    "argument (specify -a for all)\n"));
3274 			usage(B_FALSE);
3275 		}
3276 
3277 		/*
3278 		 * When mount is given no arguments, go through /etc/mnttab and
3279 		 * display any active ZFS mounts.  We hide any snapshots, since
3280 		 * they are controlled automatically.
3281 		 */
3282 		rewind(mnttab_file);
3283 		while (getmntent(mnttab_file, &entry) == 0) {
3284 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3285 			    strchr(entry.mnt_special, '@') != NULL)
3286 				continue;
3287 
3288 			(void) printf("%-30s  %s\n", entry.mnt_special,
3289 			    entry.mnt_mountp);
3290 		}
3291 
3292 	} else {
3293 		zfs_handle_t *zhp;
3294 
3295 		types = ZFS_TYPE_FILESYSTEM;
3296 		if (op == OP_SHARE)
3297 			types |= ZFS_TYPE_VOLUME;
3298 
3299 		if (argc > 1) {
3300 			(void) fprintf(stderr,
3301 			    gettext("too many arguments\n"));
3302 			usage(B_FALSE);
3303 		}
3304 
3305 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL) {
3306 			ret = 1;
3307 		} else {
3308 			ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3309 			    options);
3310 			zfs_close(zhp);
3311 		}
3312 	}
3313 
3314 	return (ret);
3315 }
3316 
3317 /*
3318  * zfs mount -a [nfs | iscsi]
3319  * zfs mount filesystem
3320  *
3321  * Mount all filesystems, or mount the given filesystem.
3322  */
3323 static int
3324 zfs_do_mount(int argc, char **argv)
3325 {
3326 	return (share_mount(OP_MOUNT, argc, argv));
3327 }
3328 
3329 /*
3330  * zfs share -a [nfs | iscsi | smb]
3331  * zfs share filesystem
3332  *
3333  * Share all filesystems, or share the given filesystem.
3334  */
3335 static int
3336 zfs_do_share(int argc, char **argv)
3337 {
3338 	return (share_mount(OP_SHARE, argc, argv));
3339 }
3340 
3341 typedef struct unshare_unmount_node {
3342 	zfs_handle_t	*un_zhp;
3343 	char		*un_mountp;
3344 	uu_avl_node_t	un_avlnode;
3345 } unshare_unmount_node_t;
3346 
3347 /* ARGSUSED */
3348 static int
3349 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3350 {
3351 	const unshare_unmount_node_t *l = larg;
3352 	const unshare_unmount_node_t *r = rarg;
3353 
3354 	return (strcmp(l->un_mountp, r->un_mountp));
3355 }
3356 
3357 /*
3358  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3359  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
3360  * and unmount it appropriately.
3361  */
3362 static int
3363 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3364 {
3365 	zfs_handle_t *zhp;
3366 	int ret;
3367 	struct stat64 statbuf;
3368 	struct extmnttab entry;
3369 	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3370 	char nfs_mnt_prop[ZFS_MAXPROPLEN];
3371 	char smbshare_prop[ZFS_MAXPROPLEN];
3372 
3373 	/*
3374 	 * Search for the path in /etc/mnttab.  Rather than looking for the
3375 	 * specific path, which can be fooled by non-standard paths (i.e. ".."
3376 	 * or "//"), we stat() the path and search for the corresponding
3377 	 * (major,minor) device pair.
3378 	 */
3379 	if (stat64(path, &statbuf) != 0) {
3380 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3381 		    cmdname, path, strerror(errno));
3382 		return (1);
3383 	}
3384 
3385 	/*
3386 	 * Search for the given (major,minor) pair in the mount table.
3387 	 */
3388 	rewind(mnttab_file);
3389 	while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3390 		if (entry.mnt_major == major(statbuf.st_dev) &&
3391 		    entry.mnt_minor == minor(statbuf.st_dev))
3392 			break;
3393 	}
3394 	if (ret != 0) {
3395 		(void) fprintf(stderr, gettext("cannot %s '%s': not "
3396 		    "currently mounted\n"), cmdname, path);
3397 		return (1);
3398 	}
3399 
3400 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3401 		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3402 		    "filesystem\n"), cmdname, path);
3403 		return (1);
3404 	}
3405 
3406 	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3407 	    ZFS_TYPE_FILESYSTEM)) == NULL)
3408 		return (1);
3409 
3410 	verify(zfs_prop_get(zhp, op == OP_SHARE ?
3411 	    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT, nfs_mnt_prop,
3412 	    sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3413 	verify(zfs_prop_get(zhp, op == OP_SHARE ?
3414 	    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT, smbshare_prop,
3415 	    sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3416 
3417 	if (op == OP_SHARE) {
3418 		if (strcmp(nfs_mnt_prop, "off") == 0 &&
3419 		    strcmp(smbshare_prop, "off") == 0) {
3420 			(void) fprintf(stderr, gettext("cannot unshare "
3421 			    "'%s': legacy share\n"), path);
3422 			(void) fprintf(stderr, gettext("use "
3423 			    "unshare(1M) to unshare this filesystem\n"));
3424 			ret = 1;
3425 		} else if (!zfs_is_shared(zhp)) {
3426 			(void) fprintf(stderr, gettext("cannot unshare '%s': "
3427 			    "not currently shared\n"), path);
3428 			ret = 1;
3429 		} else {
3430 			ret = zfs_unshareall_bypath(zhp, path);
3431 		}
3432 	} else {
3433 		if (is_manual) {
3434 			ret = zfs_unmount(zhp, NULL, flags);
3435 		} else if (strcmp(nfs_mnt_prop, "legacy") == 0) {
3436 			(void) fprintf(stderr, gettext("cannot unmount "
3437 			    "'%s': legacy mountpoint\n"),
3438 			    zfs_get_name(zhp));
3439 			(void) fprintf(stderr, gettext("use umount(1M) "
3440 			    "to unmount this filesystem\n"));
3441 			ret = 1;
3442 		} else {
3443 			ret = zfs_unmountall(zhp, flags);
3444 		}
3445 	}
3446 
3447 	zfs_close(zhp);
3448 
3449 	return (ret != 0);
3450 }
3451 
3452 /*
3453  * Generic callback for unsharing or unmounting a filesystem.
3454  */
3455 static int
3456 unshare_unmount(int op, int argc, char **argv)
3457 {
3458 	int do_all = 0;
3459 	int flags = 0;
3460 	int ret = 0;
3461 	int types, c;
3462 	zfs_handle_t *zhp;
3463 	char nfsiscsi_mnt_prop[ZFS_MAXPROPLEN];
3464 	char sharesmb[ZFS_MAXPROPLEN];
3465 
3466 	/* check options */
3467 	while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3468 		switch (c) {
3469 		case 'a':
3470 			do_all = 1;
3471 			break;
3472 		case 'f':
3473 			flags = MS_FORCE;
3474 			break;
3475 		case '?':
3476 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3477 			    optopt);
3478 			usage(B_FALSE);
3479 		}
3480 	}
3481 
3482 	argc -= optind;
3483 	argv += optind;
3484 
3485 	if (do_all) {
3486 		/*
3487 		 * We could make use of zfs_for_each() to walk all datasets in
3488 		 * the system, but this would be very inefficient, especially
3489 		 * since we would have to linearly search /etc/mnttab for each
3490 		 * one.  Instead, do one pass through /etc/mnttab looking for
3491 		 * zfs entries and call zfs_unmount() for each one.
3492 		 *
3493 		 * Things get a little tricky if the administrator has created
3494 		 * mountpoints beneath other ZFS filesystems.  In this case, we
3495 		 * have to unmount the deepest filesystems first.  To accomplish
3496 		 * this, we place all the mountpoints in an AVL tree sorted by
3497 		 * the special type (dataset name), and walk the result in
3498 		 * reverse to make sure to get any snapshots first.
3499 		 */
3500 		struct mnttab entry;
3501 		uu_avl_pool_t *pool;
3502 		uu_avl_t *tree;
3503 		unshare_unmount_node_t *node;
3504 		uu_avl_index_t idx;
3505 		uu_avl_walk_t *walk;
3506 
3507 		if (argc != 0) {
3508 			(void) fprintf(stderr, gettext("too many arguments\n"));
3509 			usage(B_FALSE);
3510 		}
3511 
3512 		if ((pool = uu_avl_pool_create("unmount_pool",
3513 		    sizeof (unshare_unmount_node_t),
3514 		    offsetof(unshare_unmount_node_t, un_avlnode),
3515 		    unshare_unmount_compare,
3516 		    UU_DEFAULT)) == NULL) {
3517 			(void) fprintf(stderr, gettext("internal error: "
3518 			    "out of memory\n"));
3519 			exit(1);
3520 		}
3521 
3522 		if ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL) {
3523 			(void) fprintf(stderr, gettext("internal error: "
3524 			    "out of memory\n"));
3525 			exit(1);
3526 		}
3527 
3528 		rewind(mnttab_file);
3529 		while (getmntent(mnttab_file, &entry) == 0) {
3530 
3531 			/* ignore non-ZFS entries */
3532 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3533 				continue;
3534 
3535 			/* ignore snapshots */
3536 			if (strchr(entry.mnt_special, '@') != NULL)
3537 				continue;
3538 
3539 			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3540 			    ZFS_TYPE_FILESYSTEM)) == NULL) {
3541 				ret = 1;
3542 				continue;
3543 			}
3544 
3545 			switch (op) {
3546 			case OP_SHARE:
3547 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3548 				    nfsiscsi_mnt_prop,
3549 				    sizeof (nfsiscsi_mnt_prop),
3550 				    NULL, NULL, 0, B_FALSE) == 0);
3551 				if (strcmp(nfsiscsi_mnt_prop, "off") != 0)
3552 					break;
3553 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3554 				    nfsiscsi_mnt_prop,
3555 				    sizeof (nfsiscsi_mnt_prop),
3556 				    NULL, NULL, 0, B_FALSE) == 0);
3557 				if (strcmp(nfsiscsi_mnt_prop, "off") == 0)
3558 					continue;
3559 				break;
3560 			case OP_MOUNT:
3561 				/* Ignore legacy mounts */
3562 				verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3563 				    nfsiscsi_mnt_prop,
3564 				    sizeof (nfsiscsi_mnt_prop),
3565 				    NULL, NULL, 0, B_FALSE) == 0);
3566 				if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0)
3567 					continue;
3568 			default:
3569 				break;
3570 			}
3571 
3572 			node = safe_malloc(sizeof (unshare_unmount_node_t));
3573 			node->un_zhp = zhp;
3574 
3575 			if ((node->un_mountp = strdup(entry.mnt_mountp)) ==
3576 			    NULL) {
3577 				(void) fprintf(stderr, gettext("internal error:"
3578 				    " out of memory\n"));
3579 				exit(1);
3580 			}
3581 
3582 			uu_avl_node_init(node, &node->un_avlnode, pool);
3583 
3584 			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3585 				uu_avl_insert(tree, node, idx);
3586 			} else {
3587 				zfs_close(node->un_zhp);
3588 				free(node->un_mountp);
3589 				free(node);
3590 			}
3591 		}
3592 
3593 		/*
3594 		 * Walk the AVL tree in reverse, unmounting each filesystem and
3595 		 * removing it from the AVL tree in the process.
3596 		 */
3597 		if ((walk = uu_avl_walk_start(tree,
3598 		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL) {
3599 			(void) fprintf(stderr,
3600 			    gettext("internal error: out of memory"));
3601 			exit(1);
3602 		}
3603 
3604 		while ((node = uu_avl_walk_next(walk)) != NULL) {
3605 			uu_avl_remove(tree, node);
3606 
3607 			switch (op) {
3608 			case OP_SHARE:
3609 				if (zfs_unshareall_bypath(node->un_zhp,
3610 				    node->un_mountp) != 0)
3611 					ret = 1;
3612 				break;
3613 
3614 			case OP_MOUNT:
3615 				if (zfs_unmount(node->un_zhp,
3616 				    node->un_mountp, flags) != 0)
3617 					ret = 1;
3618 				break;
3619 			}
3620 
3621 			zfs_close(node->un_zhp);
3622 			free(node->un_mountp);
3623 			free(node);
3624 		}
3625 
3626 		uu_avl_walk_end(walk);
3627 		uu_avl_destroy(tree);
3628 		uu_avl_pool_destroy(pool);
3629 
3630 		if (op == OP_SHARE) {
3631 			/*
3632 			 * Finally, unshare any volumes shared via iSCSI.
3633 			 */
3634 			zfs_handle_t **dslist = NULL;
3635 			size_t i, count = 0;
3636 
3637 			get_all_datasets(ZFS_TYPE_VOLUME, &dslist, &count,
3638 			    B_FALSE);
3639 
3640 			if (count != 0) {
3641 				qsort(dslist, count, sizeof (void *),
3642 				    dataset_cmp);
3643 
3644 				for (i = 0; i < count; i++) {
3645 					if (zfs_unshare_iscsi(dslist[i]) != 0)
3646 						ret = 1;
3647 					zfs_close(dslist[i]);
3648 				}
3649 
3650 				free(dslist);
3651 			}
3652 		}
3653 	} else {
3654 		if (argc != 1) {
3655 			if (argc == 0)
3656 				(void) fprintf(stderr,
3657 				    gettext("missing filesystem argument\n"));
3658 			else
3659 				(void) fprintf(stderr,
3660 				    gettext("too many arguments\n"));
3661 			usage(B_FALSE);
3662 		}
3663 
3664 		/*
3665 		 * We have an argument, but it may be a full path or a ZFS
3666 		 * filesystem.  Pass full paths off to unmount_path() (shared by
3667 		 * manual_unmount), otherwise open the filesystem and pass to
3668 		 * zfs_unmount().
3669 		 */
3670 		if (argv[0][0] == '/')
3671 			return (unshare_unmount_path(op, argv[0],
3672 			    flags, B_FALSE));
3673 
3674 		types = ZFS_TYPE_FILESYSTEM;
3675 		if (op == OP_SHARE)
3676 			types |= ZFS_TYPE_VOLUME;
3677 
3678 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3679 			return (1);
3680 
3681 		if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
3682 			verify(zfs_prop_get(zhp, op == OP_SHARE ?
3683 			    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3684 			    nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop), NULL,
3685 			    NULL, 0, B_FALSE) == 0);
3686 
3687 			switch (op) {
3688 			case OP_SHARE:
3689 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3690 				    nfsiscsi_mnt_prop,
3691 				    sizeof (nfsiscsi_mnt_prop),
3692 				    NULL, NULL, 0, B_FALSE) == 0);
3693 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3694 				    sharesmb, sizeof (sharesmb), NULL, NULL,
3695 				    0, B_FALSE) == 0);
3696 
3697 				if (strcmp(nfsiscsi_mnt_prop, "off") == 0 &&
3698 				    strcmp(sharesmb, "off") == 0) {
3699 					(void) fprintf(stderr, gettext("cannot "
3700 					    "unshare '%s': legacy share\n"),
3701 					    zfs_get_name(zhp));
3702 					(void) fprintf(stderr, gettext("use "
3703 					    "unshare(1M) to unshare this "
3704 					    "filesystem\n"));
3705 					ret = 1;
3706 				} else if (!zfs_is_shared(zhp)) {
3707 					(void) fprintf(stderr, gettext("cannot "
3708 					    "unshare '%s': not currently "
3709 					    "shared\n"), zfs_get_name(zhp));
3710 					ret = 1;
3711 				} else if (zfs_unshareall(zhp) != 0) {
3712 					ret = 1;
3713 				}
3714 				break;
3715 
3716 			case OP_MOUNT:
3717 				if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0) {
3718 					(void) fprintf(stderr, gettext("cannot "
3719 					    "unmount '%s': legacy "
3720 					    "mountpoint\n"), zfs_get_name(zhp));
3721 					(void) fprintf(stderr, gettext("use "
3722 					    "umount(1M) to unmount this "
3723 					    "filesystem\n"));
3724 					ret = 1;
3725 				} else if (!zfs_is_mounted(zhp, NULL)) {
3726 					(void) fprintf(stderr, gettext("cannot "
3727 					    "unmount '%s': not currently "
3728 					    "mounted\n"),
3729 					    zfs_get_name(zhp));
3730 					ret = 1;
3731 				} else if (zfs_unmountall(zhp, flags) != 0) {
3732 					ret = 1;
3733 				}
3734 				break;
3735 			}
3736 		} else {
3737 			assert(op == OP_SHARE);
3738 
3739 			verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI,
3740 			    nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop),
3741 			    NULL, NULL, 0, B_FALSE) == 0);
3742 
3743 			if (strcmp(nfsiscsi_mnt_prop, "off") == 0) {
3744 				(void) fprintf(stderr, gettext("cannot unshare "
3745 				    "'%s': 'shareiscsi' property not set\n"),
3746 				    zfs_get_name(zhp));
3747 				(void) fprintf(stderr, gettext("set "
3748 				    "'shareiscsi' property or use "
3749 				    "iscsitadm(1M) to share this volume\n"));
3750 				ret = 1;
3751 			} else if (!zfs_is_shared_iscsi(zhp)) {
3752 				(void) fprintf(stderr, gettext("cannot "
3753 				    "unshare '%s': not currently shared\n"),
3754 				    zfs_get_name(zhp));
3755 				ret = 1;
3756 			} else if (zfs_unshare_iscsi(zhp) != 0) {
3757 				ret = 1;
3758 			}
3759 		}
3760 
3761 		zfs_close(zhp);
3762 	}
3763 
3764 	return (ret);
3765 }
3766 
3767 /*
3768  * zfs unmount -a
3769  * zfs unmount filesystem
3770  *
3771  * Unmount all filesystems, or a specific ZFS filesystem.
3772  */
3773 static int
3774 zfs_do_unmount(int argc, char **argv)
3775 {
3776 	return (unshare_unmount(OP_MOUNT, argc, argv));
3777 }
3778 
3779 /*
3780  * zfs unshare -a
3781  * zfs unshare filesystem
3782  *
3783  * Unshare all filesystems, or a specific ZFS filesystem.
3784  */
3785 static int
3786 zfs_do_unshare(int argc, char **argv)
3787 {
3788 	return (unshare_unmount(OP_SHARE, argc, argv));
3789 }
3790 
3791 /*
3792  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
3793  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
3794  */
3795 static int
3796 manual_mount(int argc, char **argv)
3797 {
3798 	zfs_handle_t *zhp;
3799 	char mountpoint[ZFS_MAXPROPLEN];
3800 	char mntopts[MNT_LINE_MAX] = { '\0' };
3801 	int ret;
3802 	int c;
3803 	int flags = 0;
3804 	char *dataset, *path;
3805 
3806 	/* check options */
3807 	while ((c = getopt(argc, argv, ":mo:O")) != -1) {
3808 		switch (c) {
3809 		case 'o':
3810 			(void) strlcpy(mntopts, optarg, sizeof (mntopts));
3811 			break;
3812 		case 'O':
3813 			flags |= MS_OVERLAY;
3814 			break;
3815 		case 'm':
3816 			flags |= MS_NOMNTTAB;
3817 			break;
3818 		case ':':
3819 			(void) fprintf(stderr, gettext("missing argument for "
3820 			    "'%c' option\n"), optopt);
3821 			usage(B_FALSE);
3822 			break;
3823 		case '?':
3824 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3825 			    optopt);
3826 			(void) fprintf(stderr, gettext("usage: mount [-o opts] "
3827 			    "<path>\n"));
3828 			return (2);
3829 		}
3830 	}
3831 
3832 	argc -= optind;
3833 	argv += optind;
3834 
3835 	/* check that we only have two arguments */
3836 	if (argc != 2) {
3837 		if (argc == 0)
3838 			(void) fprintf(stderr, gettext("missing dataset "
3839 			    "argument\n"));
3840 		else if (argc == 1)
3841 			(void) fprintf(stderr,
3842 			    gettext("missing mountpoint argument\n"));
3843 		else
3844 			(void) fprintf(stderr, gettext("too many arguments\n"));
3845 		(void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
3846 		return (2);
3847 	}
3848 
3849 	dataset = argv[0];
3850 	path = argv[1];
3851 
3852 	/* try to open the dataset */
3853 	if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
3854 		return (1);
3855 
3856 	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3857 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
3858 
3859 	/* check for legacy mountpoint and complain appropriately */
3860 	ret = 0;
3861 	if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
3862 		if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
3863 		    NULL, 0, mntopts, sizeof (mntopts)) != 0) {
3864 			(void) fprintf(stderr, gettext("mount failed: %s\n"),
3865 			    strerror(errno));
3866 			ret = 1;
3867 		}
3868 	} else {
3869 		(void) fprintf(stderr, gettext("filesystem '%s' cannot be "
3870 		    "mounted using 'mount -F zfs'\n"), dataset);
3871 		(void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
3872 		    "instead.\n"), path);
3873 		(void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
3874 		    "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
3875 		(void) fprintf(stderr, gettext("See zfs(1M) for more "
3876 		    "information.\n"));
3877 		ret = 1;
3878 	}
3879 
3880 	return (ret);
3881 }
3882 
3883 /*
3884  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
3885  * unmounts of non-legacy filesystems, as this is the dominant administrative
3886  * interface.
3887  */
3888 static int
3889 manual_unmount(int argc, char **argv)
3890 {
3891 	int flags = 0;
3892 	int c;
3893 
3894 	/* check options */
3895 	while ((c = getopt(argc, argv, "f")) != -1) {
3896 		switch (c) {
3897 		case 'f':
3898 			flags = MS_FORCE;
3899 			break;
3900 		case '?':
3901 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3902 			    optopt);
3903 			(void) fprintf(stderr, gettext("usage: unmount [-f] "
3904 			    "<path>\n"));
3905 			return (2);
3906 		}
3907 	}
3908 
3909 	argc -= optind;
3910 	argv += optind;
3911 
3912 	/* check arguments */
3913 	if (argc != 1) {
3914 		if (argc == 0)
3915 			(void) fprintf(stderr, gettext("missing path "
3916 			    "argument\n"));
3917 		else
3918 			(void) fprintf(stderr, gettext("too many arguments\n"));
3919 		(void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
3920 		return (2);
3921 	}
3922 
3923 	return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
3924 }
3925 
3926 static int
3927 volcheck(zpool_handle_t *zhp, void *data)
3928 {
3929 	boolean_t isinit = *((boolean_t *)data);
3930 
3931 	if (isinit)
3932 		return (zpool_create_zvol_links(zhp));
3933 	else
3934 		return (zpool_remove_zvol_links(zhp));
3935 }
3936 
3937 /*
3938  * Iterate over all pools in the system and either create or destroy /dev/zvol
3939  * links, depending on the value of 'isinit'.
3940  */
3941 static int
3942 do_volcheck(boolean_t isinit)
3943 {
3944 	return (zpool_iter(g_zfs, volcheck, &isinit) ? 1 : 0);
3945 }
3946 
3947 static int
3948 find_command_idx(char *command, int *idx)
3949 {
3950 	int i;
3951 
3952 	for (i = 0; i < NCOMMAND; i++) {
3953 		if (command_table[i].name == NULL)
3954 			continue;
3955 
3956 		if (strcmp(command, command_table[i].name) == 0) {
3957 			*idx = i;
3958 			return (0);
3959 		}
3960 	}
3961 	return (1);
3962 }
3963 
3964 int
3965 main(int argc, char **argv)
3966 {
3967 	int ret;
3968 	int i;
3969 	char *progname;
3970 	char *cmdname;
3971 
3972 	(void) setlocale(LC_ALL, "");
3973 	(void) textdomain(TEXT_DOMAIN);
3974 
3975 	opterr = 0;
3976 
3977 	if ((g_zfs = libzfs_init()) == NULL) {
3978 		(void) fprintf(stderr, gettext("internal error: failed to "
3979 		    "initialize ZFS library\n"));
3980 		return (1);
3981 	}
3982 
3983 	zpool_set_history_str("zfs", argc, argv, history_str);
3984 	verify(zpool_stage_history(g_zfs, history_str) == 0);
3985 
3986 	libzfs_print_on_error(g_zfs, B_TRUE);
3987 
3988 	if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
3989 		(void) fprintf(stderr, gettext("internal error: unable to "
3990 		    "open %s\n"), MNTTAB);
3991 		return (1);
3992 	}
3993 
3994 	/*
3995 	 * This command also doubles as the /etc/fs mount and unmount program.
3996 	 * Determine if we should take this behavior based on argv[0].
3997 	 */
3998 	progname = basename(argv[0]);
3999 	if (strcmp(progname, "mount") == 0) {
4000 		ret = manual_mount(argc, argv);
4001 	} else if (strcmp(progname, "umount") == 0) {
4002 		ret = manual_unmount(argc, argv);
4003 	} else {
4004 		/*
4005 		 * Make sure the user has specified some command.
4006 		 */
4007 		if (argc < 2) {
4008 			(void) fprintf(stderr, gettext("missing command\n"));
4009 			usage(B_FALSE);
4010 		}
4011 
4012 		cmdname = argv[1];
4013 
4014 		/*
4015 		 * The 'umount' command is an alias for 'unmount'
4016 		 */
4017 		if (strcmp(cmdname, "umount") == 0)
4018 			cmdname = "unmount";
4019 
4020 		/*
4021 		 * The 'recv' command is an alias for 'receive'
4022 		 */
4023 		if (strcmp(cmdname, "recv") == 0)
4024 			cmdname = "receive";
4025 
4026 		/*
4027 		 * Special case '-?'
4028 		 */
4029 		if (strcmp(cmdname, "-?") == 0)
4030 			usage(B_TRUE);
4031 
4032 		/*
4033 		 * 'volinit' and 'volfini' do not appear in the usage message,
4034 		 * so we have to special case them here.
4035 		 */
4036 		if (strcmp(cmdname, "volinit") == 0)
4037 			return (do_volcheck(B_TRUE));
4038 		else if (strcmp(cmdname, "volfini") == 0)
4039 			return (do_volcheck(B_FALSE));
4040 
4041 		/*
4042 		 * Run the appropriate command.
4043 		 */
4044 		if (find_command_idx(cmdname, &i) == 0) {
4045 			current_command = &command_table[i];
4046 			ret = command_table[i].func(argc - 1, argv + 1);
4047 		} else if (strchr(cmdname, '=') != NULL) {
4048 			verify(find_command_idx("set", &i) == 0);
4049 			current_command = &command_table[i];
4050 			ret = command_table[i].func(argc, argv);
4051 		} else {
4052 			(void) fprintf(stderr, gettext("unrecognized "
4053 			    "command '%s'\n"), cmdname);
4054 			usage(B_FALSE);
4055 		}
4056 	}
4057 
4058 	(void) fclose(mnttab_file);
4059 
4060 	libzfs_fini(g_zfs);
4061 
4062 	/*
4063 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4064 	 * for the purposes of running ::findleaks.
4065 	 */
4066 	if (getenv("ZFS_ABORT") != NULL) {
4067 		(void) printf("dumping core by request\n");
4068 		abort();
4069 	}
4070 
4071 	return (ret);
4072 }
4073