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