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