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