xref: /titanic_51/usr/src/cmd/zfs/zfs_main.c (revision 52244c0958bdf281ca42932b449f644b4decfdc2)
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
25  * Copyright 2012 Milan Jurik. All rights reserved.
26  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2013 Steven Hartland.  All rights reserved.
28  * Copyright 2013 Nexenta Systems, Inc.  All rights reserved.
29  */
30 
31 #include <assert.h>
32 #include <ctype.h>
33 #include <errno.h>
34 #include <libgen.h>
35 #include <libintl.h>
36 #include <libuutil.h>
37 #include <libnvpair.h>
38 #include <locale.h>
39 #include <stddef.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <strings.h>
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <zone.h>
46 #include <grp.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <sys/list.h>
50 #include <sys/mkdev.h>
51 #include <sys/mntent.h>
52 #include <sys/mnttab.h>
53 #include <sys/mount.h>
54 #include <sys/stat.h>
55 #include <sys/fs/zfs.h>
56 #include <sys/types.h>
57 #include <time.h>
58 
59 #include <libzfs.h>
60 #include <libzfs_core.h>
61 #include <zfs_prop.h>
62 #include <zfs_deleg.h>
63 #include <libuutil.h>
64 #include <aclutils.h>
65 #include <directory.h>
66 #include <idmap.h>
67 
68 #include "zfs_iter.h"
69 #include "zfs_util.h"
70 #include "zfs_comutil.h"
71 
72 libzfs_handle_t *g_zfs;
73 
74 static FILE *mnttab_file;
75 static char history_str[HIS_MAX_RECORD_LEN];
76 static boolean_t log_history = B_TRUE;
77 
78 static int zfs_do_clone(int argc, char **argv);
79 static int zfs_do_create(int argc, char **argv);
80 static int zfs_do_destroy(int argc, char **argv);
81 static int zfs_do_get(int argc, char **argv);
82 static int zfs_do_inherit(int argc, char **argv);
83 static int zfs_do_list(int argc, char **argv);
84 static int zfs_do_mount(int argc, char **argv);
85 static int zfs_do_rename(int argc, char **argv);
86 static int zfs_do_rollback(int argc, char **argv);
87 static int zfs_do_set(int argc, char **argv);
88 static int zfs_do_upgrade(int argc, char **argv);
89 static int zfs_do_snapshot(int argc, char **argv);
90 static int zfs_do_unmount(int argc, char **argv);
91 static int zfs_do_share(int argc, char **argv);
92 static int zfs_do_unshare(int argc, char **argv);
93 static int zfs_do_send(int argc, char **argv);
94 static int zfs_do_receive(int argc, char **argv);
95 static int zfs_do_promote(int argc, char **argv);
96 static int zfs_do_userspace(int argc, char **argv);
97 static int zfs_do_allow(int argc, char **argv);
98 static int zfs_do_unallow(int argc, char **argv);
99 static int zfs_do_hold(int argc, char **argv);
100 static int zfs_do_holds(int argc, char **argv);
101 static int zfs_do_release(int argc, char **argv);
102 static int zfs_do_diff(int argc, char **argv);
103 static int zfs_do_bookmark(int argc, char **argv);
104 
105 /*
106  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
107  */
108 
109 #ifdef DEBUG
110 const char *
111 _umem_debug_init(void)
112 {
113 	return ("default,verbose"); /* $UMEM_DEBUG setting */
114 }
115 
116 const char *
117 _umem_logging_init(void)
118 {
119 	return ("fail,contents"); /* $UMEM_LOGGING setting */
120 }
121 #endif
122 
123 typedef enum {
124 	HELP_CLONE,
125 	HELP_CREATE,
126 	HELP_DESTROY,
127 	HELP_GET,
128 	HELP_INHERIT,
129 	HELP_UPGRADE,
130 	HELP_LIST,
131 	HELP_MOUNT,
132 	HELP_PROMOTE,
133 	HELP_RECEIVE,
134 	HELP_RENAME,
135 	HELP_ROLLBACK,
136 	HELP_SEND,
137 	HELP_SET,
138 	HELP_SHARE,
139 	HELP_SNAPSHOT,
140 	HELP_UNMOUNT,
141 	HELP_UNSHARE,
142 	HELP_ALLOW,
143 	HELP_UNALLOW,
144 	HELP_USERSPACE,
145 	HELP_GROUPSPACE,
146 	HELP_HOLD,
147 	HELP_HOLDS,
148 	HELP_RELEASE,
149 	HELP_DIFF,
150 	HELP_BOOKMARK,
151 } zfs_help_t;
152 
153 typedef struct zfs_command {
154 	const char	*name;
155 	int		(*func)(int argc, char **argv);
156 	zfs_help_t	usage;
157 } zfs_command_t;
158 
159 /*
160  * Master command table.  Each ZFS command has a name, associated function, and
161  * usage message.  The usage messages need to be internationalized, so we have
162  * to have a function to return the usage message based on a command index.
163  *
164  * These commands are organized according to how they are displayed in the usage
165  * message.  An empty command (one with a NULL name) indicates an empty line in
166  * the generic usage message.
167  */
168 static zfs_command_t command_table[] = {
169 	{ "create",	zfs_do_create,		HELP_CREATE		},
170 	{ "destroy",	zfs_do_destroy,		HELP_DESTROY		},
171 	{ NULL },
172 	{ "snapshot",	zfs_do_snapshot,	HELP_SNAPSHOT		},
173 	{ "rollback",	zfs_do_rollback,	HELP_ROLLBACK		},
174 	{ "clone",	zfs_do_clone,		HELP_CLONE		},
175 	{ "promote",	zfs_do_promote,		HELP_PROMOTE		},
176 	{ "rename",	zfs_do_rename,		HELP_RENAME		},
177 	{ "bookmark",	zfs_do_bookmark,	HELP_BOOKMARK		},
178 	{ NULL },
179 	{ "list",	zfs_do_list,		HELP_LIST		},
180 	{ NULL },
181 	{ "set",	zfs_do_set,		HELP_SET		},
182 	{ "get",	zfs_do_get,		HELP_GET		},
183 	{ "inherit",	zfs_do_inherit,		HELP_INHERIT		},
184 	{ "upgrade",	zfs_do_upgrade,		HELP_UPGRADE		},
185 	{ "userspace",	zfs_do_userspace,	HELP_USERSPACE		},
186 	{ "groupspace",	zfs_do_userspace,	HELP_GROUPSPACE		},
187 	{ NULL },
188 	{ "mount",	zfs_do_mount,		HELP_MOUNT		},
189 	{ "unmount",	zfs_do_unmount,		HELP_UNMOUNT		},
190 	{ "share",	zfs_do_share,		HELP_SHARE		},
191 	{ "unshare",	zfs_do_unshare,		HELP_UNSHARE		},
192 	{ NULL },
193 	{ "send",	zfs_do_send,		HELP_SEND		},
194 	{ "receive",	zfs_do_receive,		HELP_RECEIVE		},
195 	{ NULL },
196 	{ "allow",	zfs_do_allow,		HELP_ALLOW		},
197 	{ NULL },
198 	{ "unallow",	zfs_do_unallow,		HELP_UNALLOW		},
199 	{ NULL },
200 	{ "hold",	zfs_do_hold,		HELP_HOLD		},
201 	{ "holds",	zfs_do_holds,		HELP_HOLDS		},
202 	{ "release",	zfs_do_release,		HELP_RELEASE		},
203 	{ "diff",	zfs_do_diff,		HELP_DIFF		},
204 };
205 
206 #define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
207 
208 zfs_command_t *current_command;
209 
210 static const char *
211 get_usage(zfs_help_t idx)
212 {
213 	switch (idx) {
214 	case HELP_CLONE:
215 		return (gettext("\tclone [-p] [-o property=value] ... "
216 		    "<snapshot> <filesystem|volume>\n"));
217 	case HELP_CREATE:
218 		return (gettext("\tcreate [-p] [-o property=value] ... "
219 		    "<filesystem>\n"
220 		    "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
221 		    "-V <size> <volume>\n"));
222 	case HELP_DESTROY:
223 		return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
224 		    "\tdestroy [-dnpRrv] "
225 		    "<filesystem|volume>@<snap>[%<snap>][,...]\n"
226 		    "\tdestroy <filesystem|volume>#<bookmark>\n"));
227 	case HELP_GET:
228 		return (gettext("\tget [-rHp] [-d max] "
229 		    "[-o \"all\" | field[,...]]\n"
230 		    "\t    [-t type[,...]] [-s source[,...]]\n"
231 		    "\t    <\"all\" | property[,...]> "
232 		    "[filesystem|volume|snapshot] ...\n"));
233 	case HELP_INHERIT:
234 		return (gettext("\tinherit [-rS] <property> "
235 		    "<filesystem|volume|snapshot> ...\n"));
236 	case HELP_UPGRADE:
237 		return (gettext("\tupgrade [-v]\n"
238 		    "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
239 	case HELP_LIST:
240 		return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
241 		    "[-s property]...\n\t    [-S property]... [-t type[,...]] "
242 		    "[filesystem|volume|snapshot] ...\n"));
243 	case HELP_MOUNT:
244 		return (gettext("\tmount\n"
245 		    "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
246 	case HELP_PROMOTE:
247 		return (gettext("\tpromote <clone-filesystem>\n"));
248 	case HELP_RECEIVE:
249 		return (gettext("\treceive [-vnFu] <filesystem|volume|"
250 		"snapshot>\n"
251 		"\treceive [-vnFu] [-d | -e] <filesystem>\n"));
252 	case HELP_RENAME:
253 		return (gettext("\trename [-f] <filesystem|volume|snapshot> "
254 		    "<filesystem|volume|snapshot>\n"
255 		    "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
256 		    "\trename -r <snapshot> <snapshot>\n"));
257 	case HELP_ROLLBACK:
258 		return (gettext("\trollback [-rRf] <snapshot>\n"));
259 	case HELP_SEND:
260 		return (gettext("\tsend [-DnPpRvLe] [-[iI] snapshot] "
261 		    "<snapshot>\n"
262 		    "\tsend [-Le] [-i snapshot|bookmark] "
263 		    "<filesystem|volume|snapshot>\n"));
264 	case HELP_SET:
265 		return (gettext("\tset <property=value> ... "
266 		    "<filesystem|volume|snapshot> ...\n"));
267 	case HELP_SHARE:
268 		return (gettext("\tshare <-a | filesystem>\n"));
269 	case HELP_SNAPSHOT:
270 		return (gettext("\tsnapshot [-r] [-o property=value] ... "
271 		    "<filesystem|volume>@<snap> ...\n"));
272 	case HELP_UNMOUNT:
273 		return (gettext("\tunmount [-f] "
274 		    "<-a | filesystem|mountpoint>\n"));
275 	case HELP_UNSHARE:
276 		return (gettext("\tunshare "
277 		    "<-a | filesystem|mountpoint>\n"));
278 	case HELP_ALLOW:
279 		return (gettext("\tallow <filesystem|volume>\n"
280 		    "\tallow [-ldug] "
281 		    "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
282 		    "\t    <filesystem|volume>\n"
283 		    "\tallow [-ld] -e <perm|@setname>[,...] "
284 		    "<filesystem|volume>\n"
285 		    "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
286 		    "\tallow -s @setname <perm|@setname>[,...] "
287 		    "<filesystem|volume>\n"));
288 	case HELP_UNALLOW:
289 		return (gettext("\tunallow [-rldug] "
290 		    "<\"everyone\"|user|group>[,...]\n"
291 		    "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
292 		    "\tunallow [-rld] -e [<perm|@setname>[,...]] "
293 		    "<filesystem|volume>\n"
294 		    "\tunallow [-r] -c [<perm|@setname>[,...]] "
295 		    "<filesystem|volume>\n"
296 		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
297 		    "<filesystem|volume>\n"));
298 	case HELP_USERSPACE:
299 		return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
300 		    "[-s field] ...\n"
301 		    "\t    [-S field] ... [-t type[,...]] "
302 		    "<filesystem|snapshot>\n"));
303 	case HELP_GROUPSPACE:
304 		return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
305 		    "[-s field] ...\n"
306 		    "\t    [-S field] ... [-t type[,...]] "
307 		    "<filesystem|snapshot>\n"));
308 	case HELP_HOLD:
309 		return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
310 	case HELP_HOLDS:
311 		return (gettext("\tholds [-r] <snapshot> ...\n"));
312 	case HELP_RELEASE:
313 		return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
314 	case HELP_DIFF:
315 		return (gettext("\tdiff [-FHt] <snapshot> "
316 		    "[snapshot|filesystem]\n"));
317 	case HELP_BOOKMARK:
318 		return (gettext("\tbookmark <snapshot> <bookmark>\n"));
319 	}
320 
321 	abort();
322 	/* NOTREACHED */
323 }
324 
325 void
326 nomem(void)
327 {
328 	(void) fprintf(stderr, gettext("internal error: out of memory\n"));
329 	exit(1);
330 }
331 
332 /*
333  * Utility function to guarantee malloc() success.
334  */
335 
336 void *
337 safe_malloc(size_t size)
338 {
339 	void *data;
340 
341 	if ((data = calloc(1, size)) == NULL)
342 		nomem();
343 
344 	return (data);
345 }
346 
347 static char *
348 safe_strdup(char *str)
349 {
350 	char *dupstr = strdup(str);
351 
352 	if (dupstr == NULL)
353 		nomem();
354 
355 	return (dupstr);
356 }
357 
358 /*
359  * Callback routine that will print out information for each of
360  * the properties.
361  */
362 static int
363 usage_prop_cb(int prop, void *cb)
364 {
365 	FILE *fp = cb;
366 
367 	(void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
368 
369 	if (zfs_prop_readonly(prop))
370 		(void) fprintf(fp, " NO    ");
371 	else
372 		(void) fprintf(fp, "YES    ");
373 
374 	if (zfs_prop_inheritable(prop))
375 		(void) fprintf(fp, "  YES   ");
376 	else
377 		(void) fprintf(fp, "   NO   ");
378 
379 	if (zfs_prop_values(prop) == NULL)
380 		(void) fprintf(fp, "-\n");
381 	else
382 		(void) fprintf(fp, "%s\n", zfs_prop_values(prop));
383 
384 	return (ZPROP_CONT);
385 }
386 
387 /*
388  * Display usage message.  If we're inside a command, display only the usage for
389  * that command.  Otherwise, iterate over the entire command table and display
390  * a complete usage message.
391  */
392 static void
393 usage(boolean_t requested)
394 {
395 	int i;
396 	boolean_t show_properties = B_FALSE;
397 	FILE *fp = requested ? stdout : stderr;
398 
399 	if (current_command == NULL) {
400 
401 		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
402 		(void) fprintf(fp,
403 		    gettext("where 'command' is one of the following:\n\n"));
404 
405 		for (i = 0; i < NCOMMAND; i++) {
406 			if (command_table[i].name == NULL)
407 				(void) fprintf(fp, "\n");
408 			else
409 				(void) fprintf(fp, "%s",
410 				    get_usage(command_table[i].usage));
411 		}
412 
413 		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
414 		    "pool/[dataset/]*dataset[@name]\n"));
415 	} else {
416 		(void) fprintf(fp, gettext("usage:\n"));
417 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
418 	}
419 
420 	if (current_command != NULL &&
421 	    (strcmp(current_command->name, "set") == 0 ||
422 	    strcmp(current_command->name, "get") == 0 ||
423 	    strcmp(current_command->name, "inherit") == 0 ||
424 	    strcmp(current_command->name, "list") == 0))
425 		show_properties = B_TRUE;
426 
427 	if (show_properties) {
428 		(void) fprintf(fp,
429 		    gettext("\nThe following properties are supported:\n"));
430 
431 		(void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
432 		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
433 
434 		/* Iterate over all properties */
435 		(void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
436 		    ZFS_TYPE_DATASET);
437 
438 		(void) fprintf(fp, "\t%-15s ", "userused@...");
439 		(void) fprintf(fp, " NO       NO   <size>\n");
440 		(void) fprintf(fp, "\t%-15s ", "groupused@...");
441 		(void) fprintf(fp, " NO       NO   <size>\n");
442 		(void) fprintf(fp, "\t%-15s ", "userquota@...");
443 		(void) fprintf(fp, "YES       NO   <size> | none\n");
444 		(void) fprintf(fp, "\t%-15s ", "groupquota@...");
445 		(void) fprintf(fp, "YES       NO   <size> | none\n");
446 		(void) fprintf(fp, "\t%-15s ", "written@<snap>");
447 		(void) fprintf(fp, " NO       NO   <size>\n");
448 
449 		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
450 		    "with standard units such as K, M, G, etc.\n"));
451 		(void) fprintf(fp, gettext("\nUser-defined properties can "
452 		    "be specified by using a name containing a colon (:).\n"));
453 		(void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
454 		    "properties must be appended with\n"
455 		    "a user or group specifier of one of these forms:\n"
456 		    "    POSIX name      (eg: \"matt\")\n"
457 		    "    POSIX id        (eg: \"126829\")\n"
458 		    "    SMB name@domain (eg: \"matt@sun\")\n"
459 		    "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
460 	} else {
461 		(void) fprintf(fp,
462 		    gettext("\nFor the property list, run: %s\n"),
463 		    "zfs set|get");
464 		(void) fprintf(fp,
465 		    gettext("\nFor the delegated permission list, run: %s\n"),
466 		    "zfs allow|unallow");
467 	}
468 
469 	/*
470 	 * See comments at end of main().
471 	 */
472 	if (getenv("ZFS_ABORT") != NULL) {
473 		(void) printf("dumping core by request\n");
474 		abort();
475 	}
476 
477 	exit(requested ? 0 : 2);
478 }
479 
480 /*
481  * Take a property=value argument string and add it to the given nvlist.
482  * Modifies the argument inplace.
483  */
484 static int
485 parseprop(nvlist_t *props, char *propname)
486 {
487 	char *propval, *strval;
488 
489 	if ((propval = strchr(propname, '=')) == NULL) {
490 		(void) fprintf(stderr, gettext("missing "
491 		    "'=' for property=value argument\n"));
492 		return (-1);
493 	}
494 	*propval = '\0';
495 	propval++;
496 	if (nvlist_lookup_string(props, propname, &strval) == 0) {
497 		(void) fprintf(stderr, gettext("property '%s' "
498 		    "specified multiple times\n"), propname);
499 		return (-1);
500 	}
501 	if (nvlist_add_string(props, propname, propval) != 0)
502 		nomem();
503 	return (0);
504 }
505 
506 static int
507 parse_depth(char *opt, int *flags)
508 {
509 	char *tmp;
510 	int depth;
511 
512 	depth = (int)strtol(opt, &tmp, 0);
513 	if (*tmp) {
514 		(void) fprintf(stderr,
515 		    gettext("%s is not an integer\n"), optarg);
516 		usage(B_FALSE);
517 	}
518 	if (depth < 0) {
519 		(void) fprintf(stderr,
520 		    gettext("Depth can not be negative.\n"));
521 		usage(B_FALSE);
522 	}
523 	*flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
524 	return (depth);
525 }
526 
527 #define	PROGRESS_DELAY 2		/* seconds */
528 
529 static char *pt_reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
530 static time_t pt_begin;
531 static char *pt_header = NULL;
532 static boolean_t pt_shown;
533 
534 static void
535 start_progress_timer(void)
536 {
537 	pt_begin = time(NULL) + PROGRESS_DELAY;
538 	pt_shown = B_FALSE;
539 }
540 
541 static void
542 set_progress_header(char *header)
543 {
544 	assert(pt_header == NULL);
545 	pt_header = safe_strdup(header);
546 	if (pt_shown) {
547 		(void) printf("%s: ", header);
548 		(void) fflush(stdout);
549 	}
550 }
551 
552 static void
553 update_progress(char *update)
554 {
555 	if (!pt_shown && time(NULL) > pt_begin) {
556 		int len = strlen(update);
557 
558 		(void) printf("%s: %s%*.*s", pt_header, update, len, len,
559 		    pt_reverse);
560 		(void) fflush(stdout);
561 		pt_shown = B_TRUE;
562 	} else if (pt_shown) {
563 		int len = strlen(update);
564 
565 		(void) printf("%s%*.*s", update, len, len, pt_reverse);
566 		(void) fflush(stdout);
567 	}
568 }
569 
570 static void
571 finish_progress(char *done)
572 {
573 	if (pt_shown) {
574 		(void) printf("%s\n", done);
575 		(void) fflush(stdout);
576 	}
577 	free(pt_header);
578 	pt_header = NULL;
579 }
580 
581 /*
582  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
583  *
584  * Given an existing dataset, create a writable copy whose initial contents
585  * are the same as the source.  The newly created dataset maintains a
586  * dependency on the original; the original cannot be destroyed so long as
587  * the clone exists.
588  *
589  * The '-p' flag creates all the non-existing ancestors of the target first.
590  */
591 static int
592 zfs_do_clone(int argc, char **argv)
593 {
594 	zfs_handle_t *zhp = NULL;
595 	boolean_t parents = B_FALSE;
596 	nvlist_t *props;
597 	int ret = 0;
598 	int c;
599 
600 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
601 		nomem();
602 
603 	/* check options */
604 	while ((c = getopt(argc, argv, "o:p")) != -1) {
605 		switch (c) {
606 		case 'o':
607 			if (parseprop(props, optarg) != 0)
608 				return (1);
609 			break;
610 		case 'p':
611 			parents = B_TRUE;
612 			break;
613 		case '?':
614 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
615 			    optopt);
616 			goto usage;
617 		}
618 	}
619 
620 	argc -= optind;
621 	argv += optind;
622 
623 	/* check number of arguments */
624 	if (argc < 1) {
625 		(void) fprintf(stderr, gettext("missing source dataset "
626 		    "argument\n"));
627 		goto usage;
628 	}
629 	if (argc < 2) {
630 		(void) fprintf(stderr, gettext("missing target dataset "
631 		    "argument\n"));
632 		goto usage;
633 	}
634 	if (argc > 2) {
635 		(void) fprintf(stderr, gettext("too many arguments\n"));
636 		goto usage;
637 	}
638 
639 	/* open the source dataset */
640 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
641 		return (1);
642 
643 	if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
644 	    ZFS_TYPE_VOLUME)) {
645 		/*
646 		 * Now create the ancestors of the target dataset.  If the
647 		 * target already exists and '-p' option was used we should not
648 		 * complain.
649 		 */
650 		if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
651 		    ZFS_TYPE_VOLUME))
652 			return (0);
653 		if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
654 			return (1);
655 	}
656 
657 	/* pass to libzfs */
658 	ret = zfs_clone(zhp, argv[1], props);
659 
660 	/* create the mountpoint if necessary */
661 	if (ret == 0) {
662 		zfs_handle_t *clone;
663 
664 		clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
665 		if (clone != NULL) {
666 			if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
667 				if ((ret = zfs_mount(clone, NULL, 0)) == 0)
668 					ret = zfs_share(clone);
669 			zfs_close(clone);
670 		}
671 	}
672 
673 	zfs_close(zhp);
674 	nvlist_free(props);
675 
676 	return (!!ret);
677 
678 usage:
679 	if (zhp)
680 		zfs_close(zhp);
681 	nvlist_free(props);
682 	usage(B_FALSE);
683 	return (-1);
684 }
685 
686 /*
687  * zfs create [-p] [-o prop=value] ... fs
688  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
689  *
690  * Create a new dataset.  This command can be used to create filesystems
691  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
692  * For volumes, the user must specify a size to be used.
693  *
694  * The '-s' flag applies only to volumes, and indicates that we should not try
695  * to set the reservation for this volume.  By default we set a reservation
696  * equal to the size for any volume.  For pools with SPA_VERSION >=
697  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
698  *
699  * The '-p' flag creates all the non-existing ancestors of the target first.
700  */
701 static int
702 zfs_do_create(int argc, char **argv)
703 {
704 	zfs_type_t type = ZFS_TYPE_FILESYSTEM;
705 	zfs_handle_t *zhp = NULL;
706 	uint64_t volsize;
707 	int c;
708 	boolean_t noreserve = B_FALSE;
709 	boolean_t bflag = B_FALSE;
710 	boolean_t parents = B_FALSE;
711 	int ret = 1;
712 	nvlist_t *props;
713 	uint64_t intval;
714 	int canmount = ZFS_CANMOUNT_OFF;
715 
716 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
717 		nomem();
718 
719 	/* check options */
720 	while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
721 		switch (c) {
722 		case 'V':
723 			type = ZFS_TYPE_VOLUME;
724 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
725 				(void) fprintf(stderr, gettext("bad volume "
726 				    "size '%s': %s\n"), optarg,
727 				    libzfs_error_description(g_zfs));
728 				goto error;
729 			}
730 
731 			if (nvlist_add_uint64(props,
732 			    zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
733 				nomem();
734 			volsize = intval;
735 			break;
736 		case 'p':
737 			parents = B_TRUE;
738 			break;
739 		case 'b':
740 			bflag = B_TRUE;
741 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
742 				(void) fprintf(stderr, gettext("bad volume "
743 				    "block size '%s': %s\n"), optarg,
744 				    libzfs_error_description(g_zfs));
745 				goto error;
746 			}
747 
748 			if (nvlist_add_uint64(props,
749 			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
750 			    intval) != 0)
751 				nomem();
752 			break;
753 		case 'o':
754 			if (parseprop(props, optarg))
755 				goto error;
756 			break;
757 		case 's':
758 			noreserve = B_TRUE;
759 			break;
760 		case ':':
761 			(void) fprintf(stderr, gettext("missing size "
762 			    "argument\n"));
763 			goto badusage;
764 		case '?':
765 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
766 			    optopt);
767 			goto badusage;
768 		}
769 	}
770 
771 	if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
772 		(void) fprintf(stderr, gettext("'-s' and '-b' can only be "
773 		    "used when creating a volume\n"));
774 		goto badusage;
775 	}
776 
777 	argc -= optind;
778 	argv += optind;
779 
780 	/* check number of arguments */
781 	if (argc == 0) {
782 		(void) fprintf(stderr, gettext("missing %s argument\n"),
783 		    zfs_type_to_name(type));
784 		goto badusage;
785 	}
786 	if (argc > 1) {
787 		(void) fprintf(stderr, gettext("too many arguments\n"));
788 		goto badusage;
789 	}
790 
791 	if (type == ZFS_TYPE_VOLUME && !noreserve) {
792 		zpool_handle_t *zpool_handle;
793 		nvlist_t *real_props;
794 		uint64_t spa_version;
795 		char *p;
796 		zfs_prop_t resv_prop;
797 		char *strval;
798 		char msg[1024];
799 
800 		if (p = strchr(argv[0], '/'))
801 			*p = '\0';
802 		zpool_handle = zpool_open(g_zfs, argv[0]);
803 		if (p != NULL)
804 			*p = '/';
805 		if (zpool_handle == NULL)
806 			goto error;
807 		spa_version = zpool_get_prop_int(zpool_handle,
808 		    ZPOOL_PROP_VERSION, NULL);
809 		zpool_close(zpool_handle);
810 		if (spa_version >= SPA_VERSION_REFRESERVATION)
811 			resv_prop = ZFS_PROP_REFRESERVATION;
812 		else
813 			resv_prop = ZFS_PROP_RESERVATION;
814 
815 		(void) snprintf(msg, sizeof (msg),
816 		    gettext("cannot create '%s'"), argv[0]);
817 		if (props && (real_props = zfs_valid_proplist(g_zfs, type,
818 		    props, 0, NULL, msg)) == NULL)
819 			goto error;
820 
821 		volsize = zvol_volsize_to_reservation(volsize, real_props);
822 		nvlist_free(real_props);
823 
824 		if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
825 		    &strval) != 0) {
826 			if (nvlist_add_uint64(props,
827 			    zfs_prop_to_name(resv_prop), volsize) != 0) {
828 				nvlist_free(props);
829 				nomem();
830 			}
831 		}
832 	}
833 
834 	if (parents && zfs_name_valid(argv[0], type)) {
835 		/*
836 		 * Now create the ancestors of target dataset.  If the target
837 		 * already exists and '-p' option was used we should not
838 		 * complain.
839 		 */
840 		if (zfs_dataset_exists(g_zfs, argv[0], type)) {
841 			ret = 0;
842 			goto error;
843 		}
844 		if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
845 			goto error;
846 	}
847 
848 	/* pass to libzfs */
849 	if (zfs_create(g_zfs, argv[0], type, props) != 0)
850 		goto error;
851 
852 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
853 		goto error;
854 
855 	ret = 0;
856 	/*
857 	 * if the user doesn't want the dataset automatically mounted,
858 	 * then skip the mount/share step
859 	 */
860 	if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
861 		canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
862 
863 	/*
864 	 * Mount and/or share the new filesystem as appropriate.  We provide a
865 	 * verbose error message to let the user know that their filesystem was
866 	 * in fact created, even if we failed to mount or share it.
867 	 */
868 	if (canmount == ZFS_CANMOUNT_ON) {
869 		if (zfs_mount(zhp, NULL, 0) != 0) {
870 			(void) fprintf(stderr, gettext("filesystem "
871 			    "successfully created, but not mounted\n"));
872 			ret = 1;
873 		} else if (zfs_share(zhp) != 0) {
874 			(void) fprintf(stderr, gettext("filesystem "
875 			    "successfully created, but not shared\n"));
876 			ret = 1;
877 		}
878 	}
879 
880 error:
881 	if (zhp)
882 		zfs_close(zhp);
883 	nvlist_free(props);
884 	return (ret);
885 badusage:
886 	nvlist_free(props);
887 	usage(B_FALSE);
888 	return (2);
889 }
890 
891 /*
892  * zfs destroy [-rRf] <fs, vol>
893  * zfs destroy [-rRd] <snap>
894  *
895  *	-r	Recursively destroy all children
896  *	-R	Recursively destroy all dependents, including clones
897  *	-f	Force unmounting of any dependents
898  *	-d	If we can't destroy now, mark for deferred destruction
899  *
900  * Destroys the given dataset.  By default, it will unmount any filesystems,
901  * and refuse to destroy a dataset that has any dependents.  A dependent can
902  * either be a child, or a clone of a child.
903  */
904 typedef struct destroy_cbdata {
905 	boolean_t	cb_first;
906 	boolean_t	cb_force;
907 	boolean_t	cb_recurse;
908 	boolean_t	cb_error;
909 	boolean_t	cb_doclones;
910 	zfs_handle_t	*cb_target;
911 	boolean_t	cb_defer_destroy;
912 	boolean_t	cb_verbose;
913 	boolean_t	cb_parsable;
914 	boolean_t	cb_dryrun;
915 	nvlist_t	*cb_nvl;
916 	nvlist_t	*cb_batchedsnaps;
917 
918 	/* first snap in contiguous run */
919 	char		*cb_firstsnap;
920 	/* previous snap in contiguous run */
921 	char		*cb_prevsnap;
922 	int64_t		cb_snapused;
923 	char		*cb_snapspec;
924 	char		*cb_bookmark;
925 } destroy_cbdata_t;
926 
927 /*
928  * Check for any dependents based on the '-r' or '-R' flags.
929  */
930 static int
931 destroy_check_dependent(zfs_handle_t *zhp, void *data)
932 {
933 	destroy_cbdata_t *cbp = data;
934 	const char *tname = zfs_get_name(cbp->cb_target);
935 	const char *name = zfs_get_name(zhp);
936 
937 	if (strncmp(tname, name, strlen(tname)) == 0 &&
938 	    (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
939 		/*
940 		 * This is a direct descendant, not a clone somewhere else in
941 		 * the hierarchy.
942 		 */
943 		if (cbp->cb_recurse)
944 			goto out;
945 
946 		if (cbp->cb_first) {
947 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
948 			    "%s has children\n"),
949 			    zfs_get_name(cbp->cb_target),
950 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
951 			(void) fprintf(stderr, gettext("use '-r' to destroy "
952 			    "the following datasets:\n"));
953 			cbp->cb_first = B_FALSE;
954 			cbp->cb_error = B_TRUE;
955 		}
956 
957 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
958 	} else {
959 		/*
960 		 * This is a clone.  We only want to report this if the '-r'
961 		 * wasn't specified, or the target is a snapshot.
962 		 */
963 		if (!cbp->cb_recurse &&
964 		    zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
965 			goto out;
966 
967 		if (cbp->cb_first) {
968 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
969 			    "%s has dependent clones\n"),
970 			    zfs_get_name(cbp->cb_target),
971 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
972 			(void) fprintf(stderr, gettext("use '-R' to destroy "
973 			    "the following datasets:\n"));
974 			cbp->cb_first = B_FALSE;
975 			cbp->cb_error = B_TRUE;
976 			cbp->cb_dryrun = B_TRUE;
977 		}
978 
979 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
980 	}
981 
982 out:
983 	zfs_close(zhp);
984 	return (0);
985 }
986 
987 static int
988 destroy_callback(zfs_handle_t *zhp, void *data)
989 {
990 	destroy_cbdata_t *cb = data;
991 	const char *name = zfs_get_name(zhp);
992 
993 	if (cb->cb_verbose) {
994 		if (cb->cb_parsable) {
995 			(void) printf("destroy\t%s\n", name);
996 		} else if (cb->cb_dryrun) {
997 			(void) printf(gettext("would destroy %s\n"),
998 			    name);
999 		} else {
1000 			(void) printf(gettext("will destroy %s\n"),
1001 			    name);
1002 		}
1003 	}
1004 
1005 	/*
1006 	 * Ignore pools (which we've already flagged as an error before getting
1007 	 * here).
1008 	 */
1009 	if (strchr(zfs_get_name(zhp), '/') == NULL &&
1010 	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1011 		zfs_close(zhp);
1012 		return (0);
1013 	}
1014 	if (cb->cb_dryrun) {
1015 		zfs_close(zhp);
1016 		return (0);
1017 	}
1018 
1019 	/*
1020 	 * We batch up all contiguous snapshots (even of different
1021 	 * filesystems) and destroy them with one ioctl.  We can't
1022 	 * simply do all snap deletions and then all fs deletions,
1023 	 * because we must delete a clone before its origin.
1024 	 */
1025 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1026 		fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1027 	} else {
1028 		int error = zfs_destroy_snaps_nvl(g_zfs,
1029 		    cb->cb_batchedsnaps, B_FALSE);
1030 		fnvlist_free(cb->cb_batchedsnaps);
1031 		cb->cb_batchedsnaps = fnvlist_alloc();
1032 
1033 		if (error != 0 ||
1034 		    zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1035 		    zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1036 			zfs_close(zhp);
1037 			return (-1);
1038 		}
1039 	}
1040 
1041 	zfs_close(zhp);
1042 	return (0);
1043 }
1044 
1045 static int
1046 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1047 {
1048 	destroy_cbdata_t *cb = arg;
1049 	const char *name = zfs_get_name(zhp);
1050 	int err = 0;
1051 
1052 	if (nvlist_exists(cb->cb_nvl, name)) {
1053 		if (cb->cb_firstsnap == NULL)
1054 			cb->cb_firstsnap = strdup(name);
1055 		if (cb->cb_prevsnap != NULL)
1056 			free(cb->cb_prevsnap);
1057 		/* this snap continues the current range */
1058 		cb->cb_prevsnap = strdup(name);
1059 		if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1060 			nomem();
1061 		if (cb->cb_verbose) {
1062 			if (cb->cb_parsable) {
1063 				(void) printf("destroy\t%s\n", name);
1064 			} else if (cb->cb_dryrun) {
1065 				(void) printf(gettext("would destroy %s\n"),
1066 				    name);
1067 			} else {
1068 				(void) printf(gettext("will destroy %s\n"),
1069 				    name);
1070 			}
1071 		}
1072 	} else if (cb->cb_firstsnap != NULL) {
1073 		/* end of this range */
1074 		uint64_t used = 0;
1075 		err = lzc_snaprange_space(cb->cb_firstsnap,
1076 		    cb->cb_prevsnap, &used);
1077 		cb->cb_snapused += used;
1078 		free(cb->cb_firstsnap);
1079 		cb->cb_firstsnap = NULL;
1080 		free(cb->cb_prevsnap);
1081 		cb->cb_prevsnap = NULL;
1082 	}
1083 	zfs_close(zhp);
1084 	return (err);
1085 }
1086 
1087 static int
1088 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1089 {
1090 	int err = 0;
1091 	assert(cb->cb_firstsnap == NULL);
1092 	assert(cb->cb_prevsnap == NULL);
1093 	err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1094 	if (cb->cb_firstsnap != NULL) {
1095 		uint64_t used = 0;
1096 		if (err == 0) {
1097 			err = lzc_snaprange_space(cb->cb_firstsnap,
1098 			    cb->cb_prevsnap, &used);
1099 		}
1100 		cb->cb_snapused += used;
1101 		free(cb->cb_firstsnap);
1102 		cb->cb_firstsnap = NULL;
1103 		free(cb->cb_prevsnap);
1104 		cb->cb_prevsnap = NULL;
1105 	}
1106 	return (err);
1107 }
1108 
1109 static int
1110 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1111 {
1112 	destroy_cbdata_t *cb = arg;
1113 	int err = 0;
1114 
1115 	/* Check for clones. */
1116 	if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1117 		cb->cb_target = zhp;
1118 		cb->cb_first = B_TRUE;
1119 		err = zfs_iter_dependents(zhp, B_TRUE,
1120 		    destroy_check_dependent, cb);
1121 	}
1122 
1123 	if (err == 0) {
1124 		if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1125 			nomem();
1126 	}
1127 	zfs_close(zhp);
1128 	return (err);
1129 }
1130 
1131 static int
1132 gather_snapshots(zfs_handle_t *zhp, void *arg)
1133 {
1134 	destroy_cbdata_t *cb = arg;
1135 	int err = 0;
1136 
1137 	err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1138 	if (err == ENOENT)
1139 		err = 0;
1140 	if (err != 0)
1141 		goto out;
1142 
1143 	if (cb->cb_verbose) {
1144 		err = destroy_print_snapshots(zhp, cb);
1145 		if (err != 0)
1146 			goto out;
1147 	}
1148 
1149 	if (cb->cb_recurse)
1150 		err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1151 
1152 out:
1153 	zfs_close(zhp);
1154 	return (err);
1155 }
1156 
1157 static int
1158 destroy_clones(destroy_cbdata_t *cb)
1159 {
1160 	nvpair_t *pair;
1161 	for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1162 	    pair != NULL;
1163 	    pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1164 		zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1165 		    ZFS_TYPE_SNAPSHOT);
1166 		if (zhp != NULL) {
1167 			boolean_t defer = cb->cb_defer_destroy;
1168 			int err = 0;
1169 
1170 			/*
1171 			 * We can't defer destroy non-snapshots, so set it to
1172 			 * false while destroying the clones.
1173 			 */
1174 			cb->cb_defer_destroy = B_FALSE;
1175 			err = zfs_iter_dependents(zhp, B_FALSE,
1176 			    destroy_callback, cb);
1177 			cb->cb_defer_destroy = defer;
1178 			zfs_close(zhp);
1179 			if (err != 0)
1180 				return (err);
1181 		}
1182 	}
1183 	return (0);
1184 }
1185 
1186 static int
1187 zfs_do_destroy(int argc, char **argv)
1188 {
1189 	destroy_cbdata_t cb = { 0 };
1190 	int rv = 0;
1191 	int err = 0;
1192 	int c;
1193 	zfs_handle_t *zhp = NULL;
1194 	char *at, *pound;
1195 	zfs_type_t type = ZFS_TYPE_DATASET;
1196 
1197 	/* check options */
1198 	while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1199 		switch (c) {
1200 		case 'v':
1201 			cb.cb_verbose = B_TRUE;
1202 			break;
1203 		case 'p':
1204 			cb.cb_verbose = B_TRUE;
1205 			cb.cb_parsable = B_TRUE;
1206 			break;
1207 		case 'n':
1208 			cb.cb_dryrun = B_TRUE;
1209 			break;
1210 		case 'd':
1211 			cb.cb_defer_destroy = B_TRUE;
1212 			type = ZFS_TYPE_SNAPSHOT;
1213 			break;
1214 		case 'f':
1215 			cb.cb_force = B_TRUE;
1216 			break;
1217 		case 'r':
1218 			cb.cb_recurse = B_TRUE;
1219 			break;
1220 		case 'R':
1221 			cb.cb_recurse = B_TRUE;
1222 			cb.cb_doclones = B_TRUE;
1223 			break;
1224 		case '?':
1225 		default:
1226 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1227 			    optopt);
1228 			usage(B_FALSE);
1229 		}
1230 	}
1231 
1232 	argc -= optind;
1233 	argv += optind;
1234 
1235 	/* check number of arguments */
1236 	if (argc == 0) {
1237 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1238 		usage(B_FALSE);
1239 	}
1240 	if (argc > 1) {
1241 		(void) fprintf(stderr, gettext("too many arguments\n"));
1242 		usage(B_FALSE);
1243 	}
1244 
1245 	at = strchr(argv[0], '@');
1246 	pound = strchr(argv[0], '#');
1247 	if (at != NULL) {
1248 
1249 		/* Build the list of snaps to destroy in cb_nvl. */
1250 		cb.cb_nvl = fnvlist_alloc();
1251 
1252 		*at = '\0';
1253 		zhp = zfs_open(g_zfs, argv[0],
1254 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1255 		if (zhp == NULL)
1256 			return (1);
1257 
1258 		cb.cb_snapspec = at + 1;
1259 		if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1260 		    cb.cb_error) {
1261 			rv = 1;
1262 			goto out;
1263 		}
1264 
1265 		if (nvlist_empty(cb.cb_nvl)) {
1266 			(void) fprintf(stderr, gettext("could not find any "
1267 			    "snapshots to destroy; check snapshot names.\n"));
1268 			rv = 1;
1269 			goto out;
1270 		}
1271 
1272 		if (cb.cb_verbose) {
1273 			char buf[16];
1274 			zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1275 			if (cb.cb_parsable) {
1276 				(void) printf("reclaim\t%llu\n",
1277 				    cb.cb_snapused);
1278 			} else if (cb.cb_dryrun) {
1279 				(void) printf(gettext("would reclaim %s\n"),
1280 				    buf);
1281 			} else {
1282 				(void) printf(gettext("will reclaim %s\n"),
1283 				    buf);
1284 			}
1285 		}
1286 
1287 		if (!cb.cb_dryrun) {
1288 			if (cb.cb_doclones) {
1289 				cb.cb_batchedsnaps = fnvlist_alloc();
1290 				err = destroy_clones(&cb);
1291 				if (err == 0) {
1292 					err = zfs_destroy_snaps_nvl(g_zfs,
1293 					    cb.cb_batchedsnaps, B_FALSE);
1294 				}
1295 				if (err != 0) {
1296 					rv = 1;
1297 					goto out;
1298 				}
1299 			}
1300 			if (err == 0) {
1301 				err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1302 				    cb.cb_defer_destroy);
1303 			}
1304 		}
1305 
1306 		if (err != 0)
1307 			rv = 1;
1308 	} else if (pound != NULL) {
1309 		int err;
1310 		nvlist_t *nvl;
1311 
1312 		if (cb.cb_dryrun) {
1313 			(void) fprintf(stderr,
1314 			    "dryrun is not supported with bookmark\n");
1315 			return (-1);
1316 		}
1317 
1318 		if (cb.cb_defer_destroy) {
1319 			(void) fprintf(stderr,
1320 			    "defer destroy is not supported with bookmark\n");
1321 			return (-1);
1322 		}
1323 
1324 		if (cb.cb_recurse) {
1325 			(void) fprintf(stderr,
1326 			    "recursive is not supported with bookmark\n");
1327 			return (-1);
1328 		}
1329 
1330 		if (!zfs_bookmark_exists(argv[0])) {
1331 			(void) fprintf(stderr, gettext("bookmark '%s' "
1332 			    "does not exist.\n"), argv[0]);
1333 			return (1);
1334 		}
1335 
1336 		nvl = fnvlist_alloc();
1337 		fnvlist_add_boolean(nvl, argv[0]);
1338 
1339 		err = lzc_destroy_bookmarks(nvl, NULL);
1340 		if (err != 0) {
1341 			(void) zfs_standard_error(g_zfs, err,
1342 			    "cannot destroy bookmark");
1343 		}
1344 
1345 		nvlist_free(cb.cb_nvl);
1346 
1347 		return (err);
1348 	} else {
1349 		/* Open the given dataset */
1350 		if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1351 			return (1);
1352 
1353 		cb.cb_target = zhp;
1354 
1355 		/*
1356 		 * Perform an explicit check for pools before going any further.
1357 		 */
1358 		if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1359 		    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1360 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1361 			    "operation does not apply to pools\n"),
1362 			    zfs_get_name(zhp));
1363 			(void) fprintf(stderr, gettext("use 'zfs destroy -r "
1364 			    "%s' to destroy all datasets in the pool\n"),
1365 			    zfs_get_name(zhp));
1366 			(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1367 			    "to destroy the pool itself\n"), zfs_get_name(zhp));
1368 			rv = 1;
1369 			goto out;
1370 		}
1371 
1372 		/*
1373 		 * Check for any dependents and/or clones.
1374 		 */
1375 		cb.cb_first = B_TRUE;
1376 		if (!cb.cb_doclones &&
1377 		    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1378 		    &cb) != 0) {
1379 			rv = 1;
1380 			goto out;
1381 		}
1382 
1383 		if (cb.cb_error) {
1384 			rv = 1;
1385 			goto out;
1386 		}
1387 
1388 		cb.cb_batchedsnaps = fnvlist_alloc();
1389 		if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1390 		    &cb) != 0) {
1391 			rv = 1;
1392 			goto out;
1393 		}
1394 
1395 		/*
1396 		 * Do the real thing.  The callback will close the
1397 		 * handle regardless of whether it succeeds or not.
1398 		 */
1399 		err = destroy_callback(zhp, &cb);
1400 		zhp = NULL;
1401 		if (err == 0) {
1402 			err = zfs_destroy_snaps_nvl(g_zfs,
1403 			    cb.cb_batchedsnaps, cb.cb_defer_destroy);
1404 		}
1405 		if (err != 0)
1406 			rv = 1;
1407 	}
1408 
1409 out:
1410 	fnvlist_free(cb.cb_batchedsnaps);
1411 	fnvlist_free(cb.cb_nvl);
1412 	if (zhp != NULL)
1413 		zfs_close(zhp);
1414 	return (rv);
1415 }
1416 
1417 static boolean_t
1418 is_recvd_column(zprop_get_cbdata_t *cbp)
1419 {
1420 	int i;
1421 	zfs_get_column_t col;
1422 
1423 	for (i = 0; i < ZFS_GET_NCOLS &&
1424 	    (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1425 		if (col == GET_COL_RECVD)
1426 			return (B_TRUE);
1427 	return (B_FALSE);
1428 }
1429 
1430 /*
1431  * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1432  *	< all | property[,property]... > < fs | snap | vol > ...
1433  *
1434  *	-r	recurse over any child datasets
1435  *	-H	scripted mode.  Headers are stripped, and fields are separated
1436  *		by tabs instead of spaces.
1437  *	-o	Set of fields to display.  One of "name,property,value,
1438  *		received,source". Default is "name,property,value,source".
1439  *		"all" is an alias for all five.
1440  *	-s	Set of sources to allow.  One of
1441  *		"local,default,inherited,received,temporary,none".  Default is
1442  *		all six.
1443  *	-p	Display values in parsable (literal) format.
1444  *
1445  *  Prints properties for the given datasets.  The user can control which
1446  *  columns to display as well as which property types to allow.
1447  */
1448 
1449 /*
1450  * Invoked to display the properties for a single dataset.
1451  */
1452 static int
1453 get_callback(zfs_handle_t *zhp, void *data)
1454 {
1455 	char buf[ZFS_MAXPROPLEN];
1456 	char rbuf[ZFS_MAXPROPLEN];
1457 	zprop_source_t sourcetype;
1458 	char source[ZFS_MAXNAMELEN];
1459 	zprop_get_cbdata_t *cbp = data;
1460 	nvlist_t *user_props = zfs_get_user_props(zhp);
1461 	zprop_list_t *pl = cbp->cb_proplist;
1462 	nvlist_t *propval;
1463 	char *strval;
1464 	char *sourceval;
1465 	boolean_t received = is_recvd_column(cbp);
1466 
1467 	for (; pl != NULL; pl = pl->pl_next) {
1468 		char *recvdval = NULL;
1469 		/*
1470 		 * Skip the special fake placeholder.  This will also skip over
1471 		 * the name property when 'all' is specified.
1472 		 */
1473 		if (pl->pl_prop == ZFS_PROP_NAME &&
1474 		    pl == cbp->cb_proplist)
1475 			continue;
1476 
1477 		if (pl->pl_prop != ZPROP_INVAL) {
1478 			if (zfs_prop_get(zhp, pl->pl_prop, buf,
1479 			    sizeof (buf), &sourcetype, source,
1480 			    sizeof (source),
1481 			    cbp->cb_literal) != 0) {
1482 				if (pl->pl_all)
1483 					continue;
1484 				if (!zfs_prop_valid_for_type(pl->pl_prop,
1485 				    ZFS_TYPE_DATASET)) {
1486 					(void) fprintf(stderr,
1487 					    gettext("No such property '%s'\n"),
1488 					    zfs_prop_to_name(pl->pl_prop));
1489 					continue;
1490 				}
1491 				sourcetype = ZPROP_SRC_NONE;
1492 				(void) strlcpy(buf, "-", sizeof (buf));
1493 			}
1494 
1495 			if (received && (zfs_prop_get_recvd(zhp,
1496 			    zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1497 			    cbp->cb_literal) == 0))
1498 				recvdval = rbuf;
1499 
1500 			zprop_print_one_property(zfs_get_name(zhp), cbp,
1501 			    zfs_prop_to_name(pl->pl_prop),
1502 			    buf, sourcetype, source, recvdval);
1503 		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
1504 			sourcetype = ZPROP_SRC_LOCAL;
1505 
1506 			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1507 			    buf, sizeof (buf), cbp->cb_literal) != 0) {
1508 				sourcetype = ZPROP_SRC_NONE;
1509 				(void) strlcpy(buf, "-", sizeof (buf));
1510 			}
1511 
1512 			zprop_print_one_property(zfs_get_name(zhp), cbp,
1513 			    pl->pl_user_prop, buf, sourcetype, source, NULL);
1514 		} else if (zfs_prop_written(pl->pl_user_prop)) {
1515 			sourcetype = ZPROP_SRC_LOCAL;
1516 
1517 			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1518 			    buf, sizeof (buf), cbp->cb_literal) != 0) {
1519 				sourcetype = ZPROP_SRC_NONE;
1520 				(void) strlcpy(buf, "-", sizeof (buf));
1521 			}
1522 
1523 			zprop_print_one_property(zfs_get_name(zhp), cbp,
1524 			    pl->pl_user_prop, buf, sourcetype, source, NULL);
1525 		} else {
1526 			if (nvlist_lookup_nvlist(user_props,
1527 			    pl->pl_user_prop, &propval) != 0) {
1528 				if (pl->pl_all)
1529 					continue;
1530 				sourcetype = ZPROP_SRC_NONE;
1531 				strval = "-";
1532 			} else {
1533 				verify(nvlist_lookup_string(propval,
1534 				    ZPROP_VALUE, &strval) == 0);
1535 				verify(nvlist_lookup_string(propval,
1536 				    ZPROP_SOURCE, &sourceval) == 0);
1537 
1538 				if (strcmp(sourceval,
1539 				    zfs_get_name(zhp)) == 0) {
1540 					sourcetype = ZPROP_SRC_LOCAL;
1541 				} else if (strcmp(sourceval,
1542 				    ZPROP_SOURCE_VAL_RECVD) == 0) {
1543 					sourcetype = ZPROP_SRC_RECEIVED;
1544 				} else {
1545 					sourcetype = ZPROP_SRC_INHERITED;
1546 					(void) strlcpy(source,
1547 					    sourceval, sizeof (source));
1548 				}
1549 			}
1550 
1551 			if (received && (zfs_prop_get_recvd(zhp,
1552 			    pl->pl_user_prop, rbuf, sizeof (rbuf),
1553 			    cbp->cb_literal) == 0))
1554 				recvdval = rbuf;
1555 
1556 			zprop_print_one_property(zfs_get_name(zhp), cbp,
1557 			    pl->pl_user_prop, strval, sourcetype,
1558 			    source, recvdval);
1559 		}
1560 	}
1561 
1562 	return (0);
1563 }
1564 
1565 static int
1566 zfs_do_get(int argc, char **argv)
1567 {
1568 	zprop_get_cbdata_t cb = { 0 };
1569 	int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1570 	int types = ZFS_TYPE_DATASET;
1571 	char *value, *fields;
1572 	int ret = 0;
1573 	int limit = 0;
1574 	zprop_list_t fake_name = { 0 };
1575 
1576 	/*
1577 	 * Set up default columns and sources.
1578 	 */
1579 	cb.cb_sources = ZPROP_SRC_ALL;
1580 	cb.cb_columns[0] = GET_COL_NAME;
1581 	cb.cb_columns[1] = GET_COL_PROPERTY;
1582 	cb.cb_columns[2] = GET_COL_VALUE;
1583 	cb.cb_columns[3] = GET_COL_SOURCE;
1584 	cb.cb_type = ZFS_TYPE_DATASET;
1585 
1586 	/* check options */
1587 	while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1588 		switch (c) {
1589 		case 'p':
1590 			cb.cb_literal = B_TRUE;
1591 			break;
1592 		case 'd':
1593 			limit = parse_depth(optarg, &flags);
1594 			break;
1595 		case 'r':
1596 			flags |= ZFS_ITER_RECURSE;
1597 			break;
1598 		case 'H':
1599 			cb.cb_scripted = B_TRUE;
1600 			break;
1601 		case ':':
1602 			(void) fprintf(stderr, gettext("missing argument for "
1603 			    "'%c' option\n"), optopt);
1604 			usage(B_FALSE);
1605 			break;
1606 		case 'o':
1607 			/*
1608 			 * Process the set of columns to display.  We zero out
1609 			 * the structure to give us a blank slate.
1610 			 */
1611 			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1612 			i = 0;
1613 			while (*optarg != '\0') {
1614 				static char *col_subopts[] =
1615 				    { "name", "property", "value", "received",
1616 				    "source", "all", NULL };
1617 
1618 				if (i == ZFS_GET_NCOLS) {
1619 					(void) fprintf(stderr, gettext("too "
1620 					    "many fields given to -o "
1621 					    "option\n"));
1622 					usage(B_FALSE);
1623 				}
1624 
1625 				switch (getsubopt(&optarg, col_subopts,
1626 				    &value)) {
1627 				case 0:
1628 					cb.cb_columns[i++] = GET_COL_NAME;
1629 					break;
1630 				case 1:
1631 					cb.cb_columns[i++] = GET_COL_PROPERTY;
1632 					break;
1633 				case 2:
1634 					cb.cb_columns[i++] = GET_COL_VALUE;
1635 					break;
1636 				case 3:
1637 					cb.cb_columns[i++] = GET_COL_RECVD;
1638 					flags |= ZFS_ITER_RECVD_PROPS;
1639 					break;
1640 				case 4:
1641 					cb.cb_columns[i++] = GET_COL_SOURCE;
1642 					break;
1643 				case 5:
1644 					if (i > 0) {
1645 						(void) fprintf(stderr,
1646 						    gettext("\"all\" conflicts "
1647 						    "with specific fields "
1648 						    "given to -o option\n"));
1649 						usage(B_FALSE);
1650 					}
1651 					cb.cb_columns[0] = GET_COL_NAME;
1652 					cb.cb_columns[1] = GET_COL_PROPERTY;
1653 					cb.cb_columns[2] = GET_COL_VALUE;
1654 					cb.cb_columns[3] = GET_COL_RECVD;
1655 					cb.cb_columns[4] = GET_COL_SOURCE;
1656 					flags |= ZFS_ITER_RECVD_PROPS;
1657 					i = ZFS_GET_NCOLS;
1658 					break;
1659 				default:
1660 					(void) fprintf(stderr,
1661 					    gettext("invalid column name "
1662 					    "'%s'\n"), value);
1663 					usage(B_FALSE);
1664 				}
1665 			}
1666 			break;
1667 
1668 		case 's':
1669 			cb.cb_sources = 0;
1670 			while (*optarg != '\0') {
1671 				static char *source_subopts[] = {
1672 					"local", "default", "inherited",
1673 					"received", "temporary", "none",
1674 					NULL };
1675 
1676 				switch (getsubopt(&optarg, source_subopts,
1677 				    &value)) {
1678 				case 0:
1679 					cb.cb_sources |= ZPROP_SRC_LOCAL;
1680 					break;
1681 				case 1:
1682 					cb.cb_sources |= ZPROP_SRC_DEFAULT;
1683 					break;
1684 				case 2:
1685 					cb.cb_sources |= ZPROP_SRC_INHERITED;
1686 					break;
1687 				case 3:
1688 					cb.cb_sources |= ZPROP_SRC_RECEIVED;
1689 					break;
1690 				case 4:
1691 					cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1692 					break;
1693 				case 5:
1694 					cb.cb_sources |= ZPROP_SRC_NONE;
1695 					break;
1696 				default:
1697 					(void) fprintf(stderr,
1698 					    gettext("invalid source "
1699 					    "'%s'\n"), value);
1700 					usage(B_FALSE);
1701 				}
1702 			}
1703 			break;
1704 
1705 		case 't':
1706 			types = 0;
1707 			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1708 			while (*optarg != '\0') {
1709 				static char *type_subopts[] = { "filesystem",
1710 				    "volume", "snapshot", "bookmark",
1711 				    "all", NULL };
1712 
1713 				switch (getsubopt(&optarg, type_subopts,
1714 				    &value)) {
1715 				case 0:
1716 					types |= ZFS_TYPE_FILESYSTEM;
1717 					break;
1718 				case 1:
1719 					types |= ZFS_TYPE_VOLUME;
1720 					break;
1721 				case 2:
1722 					types |= ZFS_TYPE_SNAPSHOT;
1723 					break;
1724 				case 3:
1725 					types |= ZFS_TYPE_BOOKMARK;
1726 					break;
1727 				case 4:
1728 					types = ZFS_TYPE_DATASET |
1729 					    ZFS_TYPE_BOOKMARK;
1730 					break;
1731 
1732 				default:
1733 					(void) fprintf(stderr,
1734 					    gettext("invalid type '%s'\n"),
1735 					    value);
1736 					usage(B_FALSE);
1737 				}
1738 			}
1739 			break;
1740 
1741 		case '?':
1742 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1743 			    optopt);
1744 			usage(B_FALSE);
1745 		}
1746 	}
1747 
1748 	argc -= optind;
1749 	argv += optind;
1750 
1751 	if (argc < 1) {
1752 		(void) fprintf(stderr, gettext("missing property "
1753 		    "argument\n"));
1754 		usage(B_FALSE);
1755 	}
1756 
1757 	fields = argv[0];
1758 
1759 	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1760 	    != 0)
1761 		usage(B_FALSE);
1762 
1763 	argc--;
1764 	argv++;
1765 
1766 	/*
1767 	 * As part of zfs_expand_proplist(), we keep track of the maximum column
1768 	 * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1769 	 * need to know the maximum name length.  However, the user likely did
1770 	 * not specify 'name' as one of the properties to fetch, so we need to
1771 	 * make sure we always include at least this property for
1772 	 * print_get_headers() to work properly.
1773 	 */
1774 	if (cb.cb_proplist != NULL) {
1775 		fake_name.pl_prop = ZFS_PROP_NAME;
1776 		fake_name.pl_width = strlen(gettext("NAME"));
1777 		fake_name.pl_next = cb.cb_proplist;
1778 		cb.cb_proplist = &fake_name;
1779 	}
1780 
1781 	cb.cb_first = B_TRUE;
1782 
1783 	/* run for each object */
1784 	ret = zfs_for_each(argc, argv, flags, types, NULL,
1785 	    &cb.cb_proplist, limit, get_callback, &cb);
1786 
1787 	if (cb.cb_proplist == &fake_name)
1788 		zprop_free_list(fake_name.pl_next);
1789 	else
1790 		zprop_free_list(cb.cb_proplist);
1791 
1792 	return (ret);
1793 }
1794 
1795 /*
1796  * inherit [-rS] <property> <fs|vol> ...
1797  *
1798  *	-r	Recurse over all children
1799  *	-S	Revert to received value, if any
1800  *
1801  * For each dataset specified on the command line, inherit the given property
1802  * from its parent.  Inheriting a property at the pool level will cause it to
1803  * use the default value.  The '-r' flag will recurse over all children, and is
1804  * useful for setting a property on a hierarchy-wide basis, regardless of any
1805  * local modifications for each dataset.
1806  */
1807 
1808 typedef struct inherit_cbdata {
1809 	const char *cb_propname;
1810 	boolean_t cb_received;
1811 } inherit_cbdata_t;
1812 
1813 static int
1814 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1815 {
1816 	inherit_cbdata_t *cb = data;
1817 	zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1818 
1819 	/*
1820 	 * If we're doing it recursively, then ignore properties that
1821 	 * are not valid for this type of dataset.
1822 	 */
1823 	if (prop != ZPROP_INVAL &&
1824 	    !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1825 		return (0);
1826 
1827 	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1828 }
1829 
1830 static int
1831 inherit_cb(zfs_handle_t *zhp, void *data)
1832 {
1833 	inherit_cbdata_t *cb = data;
1834 
1835 	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1836 }
1837 
1838 static int
1839 zfs_do_inherit(int argc, char **argv)
1840 {
1841 	int c;
1842 	zfs_prop_t prop;
1843 	inherit_cbdata_t cb = { 0 };
1844 	char *propname;
1845 	int ret = 0;
1846 	int flags = 0;
1847 	boolean_t received = B_FALSE;
1848 
1849 	/* check options */
1850 	while ((c = getopt(argc, argv, "rS")) != -1) {
1851 		switch (c) {
1852 		case 'r':
1853 			flags |= ZFS_ITER_RECURSE;
1854 			break;
1855 		case 'S':
1856 			received = B_TRUE;
1857 			break;
1858 		case '?':
1859 		default:
1860 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1861 			    optopt);
1862 			usage(B_FALSE);
1863 		}
1864 	}
1865 
1866 	argc -= optind;
1867 	argv += optind;
1868 
1869 	/* check number of arguments */
1870 	if (argc < 1) {
1871 		(void) fprintf(stderr, gettext("missing property argument\n"));
1872 		usage(B_FALSE);
1873 	}
1874 	if (argc < 2) {
1875 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1876 		usage(B_FALSE);
1877 	}
1878 
1879 	propname = argv[0];
1880 	argc--;
1881 	argv++;
1882 
1883 	if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1884 		if (zfs_prop_readonly(prop)) {
1885 			(void) fprintf(stderr, gettext(
1886 			    "%s property is read-only\n"),
1887 			    propname);
1888 			return (1);
1889 		}
1890 		if (!zfs_prop_inheritable(prop) && !received) {
1891 			(void) fprintf(stderr, gettext("'%s' property cannot "
1892 			    "be inherited\n"), propname);
1893 			if (prop == ZFS_PROP_QUOTA ||
1894 			    prop == ZFS_PROP_RESERVATION ||
1895 			    prop == ZFS_PROP_REFQUOTA ||
1896 			    prop == ZFS_PROP_REFRESERVATION) {
1897 				(void) fprintf(stderr, gettext("use 'zfs set "
1898 				    "%s=none' to clear\n"), propname);
1899 				(void) fprintf(stderr, gettext("use 'zfs "
1900 				    "inherit -S %s' to revert to received "
1901 				    "value\n"), propname);
1902 			}
1903 			return (1);
1904 		}
1905 		if (received && (prop == ZFS_PROP_VOLSIZE ||
1906 		    prop == ZFS_PROP_VERSION)) {
1907 			(void) fprintf(stderr, gettext("'%s' property cannot "
1908 			    "be reverted to a received value\n"), propname);
1909 			return (1);
1910 		}
1911 	} else if (!zfs_prop_user(propname)) {
1912 		(void) fprintf(stderr, gettext("invalid property '%s'\n"),
1913 		    propname);
1914 		usage(B_FALSE);
1915 	}
1916 
1917 	cb.cb_propname = propname;
1918 	cb.cb_received = received;
1919 
1920 	if (flags & ZFS_ITER_RECURSE) {
1921 		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1922 		    NULL, NULL, 0, inherit_recurse_cb, &cb);
1923 	} else {
1924 		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1925 		    NULL, NULL, 0, inherit_cb, &cb);
1926 	}
1927 
1928 	return (ret);
1929 }
1930 
1931 typedef struct upgrade_cbdata {
1932 	uint64_t cb_numupgraded;
1933 	uint64_t cb_numsamegraded;
1934 	uint64_t cb_numfailed;
1935 	uint64_t cb_version;
1936 	boolean_t cb_newer;
1937 	boolean_t cb_foundone;
1938 	char cb_lastfs[ZFS_MAXNAMELEN];
1939 } upgrade_cbdata_t;
1940 
1941 static int
1942 same_pool(zfs_handle_t *zhp, const char *name)
1943 {
1944 	int len1 = strcspn(name, "/@");
1945 	const char *zhname = zfs_get_name(zhp);
1946 	int len2 = strcspn(zhname, "/@");
1947 
1948 	if (len1 != len2)
1949 		return (B_FALSE);
1950 	return (strncmp(name, zhname, len1) == 0);
1951 }
1952 
1953 static int
1954 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1955 {
1956 	upgrade_cbdata_t *cb = data;
1957 	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1958 
1959 	/* list if it's old/new */
1960 	if ((!cb->cb_newer && version < ZPL_VERSION) ||
1961 	    (cb->cb_newer && version > ZPL_VERSION)) {
1962 		char *str;
1963 		if (cb->cb_newer) {
1964 			str = gettext("The following filesystems are "
1965 			    "formatted using a newer software version and\n"
1966 			    "cannot be accessed on the current system.\n\n");
1967 		} else {
1968 			str = gettext("The following filesystems are "
1969 			    "out of date, and can be upgraded.  After being\n"
1970 			    "upgraded, these filesystems (and any 'zfs send' "
1971 			    "streams generated from\n"
1972 			    "subsequent snapshots) will no longer be "
1973 			    "accessible by older software versions.\n\n");
1974 		}
1975 
1976 		if (!cb->cb_foundone) {
1977 			(void) puts(str);
1978 			(void) printf(gettext("VER  FILESYSTEM\n"));
1979 			(void) printf(gettext("---  ------------\n"));
1980 			cb->cb_foundone = B_TRUE;
1981 		}
1982 
1983 		(void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1984 	}
1985 
1986 	return (0);
1987 }
1988 
1989 static int
1990 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1991 {
1992 	upgrade_cbdata_t *cb = data;
1993 	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1994 	int needed_spa_version;
1995 	int spa_version;
1996 
1997 	if (zfs_spa_version(zhp, &spa_version) < 0)
1998 		return (-1);
1999 
2000 	needed_spa_version = zfs_spa_version_map(cb->cb_version);
2001 
2002 	if (needed_spa_version < 0)
2003 		return (-1);
2004 
2005 	if (spa_version < needed_spa_version) {
2006 		/* can't upgrade */
2007 		(void) printf(gettext("%s: can not be "
2008 		    "upgraded; the pool version needs to first "
2009 		    "be upgraded\nto version %d\n\n"),
2010 		    zfs_get_name(zhp), needed_spa_version);
2011 		cb->cb_numfailed++;
2012 		return (0);
2013 	}
2014 
2015 	/* upgrade */
2016 	if (version < cb->cb_version) {
2017 		char verstr[16];
2018 		(void) snprintf(verstr, sizeof (verstr),
2019 		    "%llu", cb->cb_version);
2020 		if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2021 			/*
2022 			 * If they did "zfs upgrade -a", then we could
2023 			 * be doing ioctls to different pools.  We need
2024 			 * to log this history once to each pool, and bypass
2025 			 * the normal history logging that happens in main().
2026 			 */
2027 			(void) zpool_log_history(g_zfs, history_str);
2028 			log_history = B_FALSE;
2029 		}
2030 		if (zfs_prop_set(zhp, "version", verstr) == 0)
2031 			cb->cb_numupgraded++;
2032 		else
2033 			cb->cb_numfailed++;
2034 		(void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2035 	} else if (version > cb->cb_version) {
2036 		/* can't downgrade */
2037 		(void) printf(gettext("%s: can not be downgraded; "
2038 		    "it is already at version %u\n"),
2039 		    zfs_get_name(zhp), version);
2040 		cb->cb_numfailed++;
2041 	} else {
2042 		cb->cb_numsamegraded++;
2043 	}
2044 	return (0);
2045 }
2046 
2047 /*
2048  * zfs upgrade
2049  * zfs upgrade -v
2050  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2051  */
2052 static int
2053 zfs_do_upgrade(int argc, char **argv)
2054 {
2055 	boolean_t all = B_FALSE;
2056 	boolean_t showversions = B_FALSE;
2057 	int ret = 0;
2058 	upgrade_cbdata_t cb = { 0 };
2059 	char c;
2060 	int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2061 
2062 	/* check options */
2063 	while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2064 		switch (c) {
2065 		case 'r':
2066 			flags |= ZFS_ITER_RECURSE;
2067 			break;
2068 		case 'v':
2069 			showversions = B_TRUE;
2070 			break;
2071 		case 'V':
2072 			if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2073 			    optarg, &cb.cb_version) != 0) {
2074 				(void) fprintf(stderr,
2075 				    gettext("invalid version %s\n"), optarg);
2076 				usage(B_FALSE);
2077 			}
2078 			break;
2079 		case 'a':
2080 			all = B_TRUE;
2081 			break;
2082 		case '?':
2083 		default:
2084 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2085 			    optopt);
2086 			usage(B_FALSE);
2087 		}
2088 	}
2089 
2090 	argc -= optind;
2091 	argv += optind;
2092 
2093 	if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2094 		usage(B_FALSE);
2095 	if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2096 	    cb.cb_version || argc))
2097 		usage(B_FALSE);
2098 	if ((all || argc) && (showversions))
2099 		usage(B_FALSE);
2100 	if (all && argc)
2101 		usage(B_FALSE);
2102 
2103 	if (showversions) {
2104 		/* Show info on available versions. */
2105 		(void) printf(gettext("The following filesystem versions are "
2106 		    "supported:\n\n"));
2107 		(void) printf(gettext("VER  DESCRIPTION\n"));
2108 		(void) printf("---  -----------------------------------------"
2109 		    "---------------\n");
2110 		(void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
2111 		(void) printf(gettext(" 2   Enhanced directory entries\n"));
2112 		(void) printf(gettext(" 3   Case insensitive and filesystem "
2113 		    "user identifier (FUID)\n"));
2114 		(void) printf(gettext(" 4   userquota, groupquota "
2115 		    "properties\n"));
2116 		(void) printf(gettext(" 5   System attributes\n"));
2117 		(void) printf(gettext("\nFor more information on a particular "
2118 		    "version, including supported releases,\n"));
2119 		(void) printf("see the ZFS Administration Guide.\n\n");
2120 		ret = 0;
2121 	} else if (argc || all) {
2122 		/* Upgrade filesystems */
2123 		if (cb.cb_version == 0)
2124 			cb.cb_version = ZPL_VERSION;
2125 		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2126 		    NULL, NULL, 0, upgrade_set_callback, &cb);
2127 		(void) printf(gettext("%llu filesystems upgraded\n"),
2128 		    cb.cb_numupgraded);
2129 		if (cb.cb_numsamegraded) {
2130 			(void) printf(gettext("%llu filesystems already at "
2131 			    "this version\n"),
2132 			    cb.cb_numsamegraded);
2133 		}
2134 		if (cb.cb_numfailed != 0)
2135 			ret = 1;
2136 	} else {
2137 		/* List old-version filesytems */
2138 		boolean_t found;
2139 		(void) printf(gettext("This system is currently running "
2140 		    "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2141 
2142 		flags |= ZFS_ITER_RECURSE;
2143 		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2144 		    NULL, NULL, 0, upgrade_list_callback, &cb);
2145 
2146 		found = cb.cb_foundone;
2147 		cb.cb_foundone = B_FALSE;
2148 		cb.cb_newer = B_TRUE;
2149 
2150 		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2151 		    NULL, NULL, 0, upgrade_list_callback, &cb);
2152 
2153 		if (!cb.cb_foundone && !found) {
2154 			(void) printf(gettext("All filesystems are "
2155 			    "formatted with the current version.\n"));
2156 		}
2157 	}
2158 
2159 	return (ret);
2160 }
2161 
2162 /*
2163  * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2164  *               [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2165  * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2166  *                [-S field [-S field]...] [-t type[,...]] filesystem | snapshot
2167  *
2168  *	-H      Scripted mode; elide headers and separate columns by tabs.
2169  *	-i	Translate SID to POSIX ID.
2170  *	-n	Print numeric ID instead of user/group name.
2171  *	-o      Control which fields to display.
2172  *	-p	Use exact (parsable) numeric output.
2173  *	-s      Specify sort columns, descending order.
2174  *	-S      Specify sort columns, ascending order.
2175  *	-t      Control which object types to display.
2176  *
2177  *	Displays space consumed by, and quotas on, each user in the specified
2178  *	filesystem or snapshot.
2179  */
2180 
2181 /* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2182 enum us_field_types {
2183 	USFIELD_TYPE,
2184 	USFIELD_NAME,
2185 	USFIELD_USED,
2186 	USFIELD_QUOTA
2187 };
2188 static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2189 static char *us_field_names[] = { "type", "name", "used", "quota" };
2190 #define	USFIELD_LAST	(sizeof (us_field_names) / sizeof (char *))
2191 
2192 #define	USTYPE_PSX_GRP	(1 << 0)
2193 #define	USTYPE_PSX_USR	(1 << 1)
2194 #define	USTYPE_SMB_GRP	(1 << 2)
2195 #define	USTYPE_SMB_USR	(1 << 3)
2196 #define	USTYPE_ALL	\
2197 	(USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR)
2198 
2199 static int us_type_bits[] = {
2200 	USTYPE_PSX_GRP,
2201 	USTYPE_PSX_USR,
2202 	USTYPE_SMB_GRP,
2203 	USTYPE_SMB_USR,
2204 	USTYPE_ALL
2205 };
2206 static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2207 	"smbuser", "all" };
2208 
2209 typedef struct us_node {
2210 	nvlist_t	*usn_nvl;
2211 	uu_avl_node_t	usn_avlnode;
2212 	uu_list_node_t	usn_listnode;
2213 } us_node_t;
2214 
2215 typedef struct us_cbdata {
2216 	nvlist_t	**cb_nvlp;
2217 	uu_avl_pool_t	*cb_avl_pool;
2218 	uu_avl_t	*cb_avl;
2219 	boolean_t	cb_numname;
2220 	boolean_t	cb_nicenum;
2221 	boolean_t	cb_sid2posix;
2222 	zfs_userquota_prop_t cb_prop;
2223 	zfs_sort_column_t *cb_sortcol;
2224 	size_t		cb_width[USFIELD_LAST];
2225 } us_cbdata_t;
2226 
2227 static boolean_t us_populated = B_FALSE;
2228 
2229 typedef struct {
2230 	zfs_sort_column_t *si_sortcol;
2231 	boolean_t	si_numname;
2232 } us_sort_info_t;
2233 
2234 static int
2235 us_field_index(char *field)
2236 {
2237 	int i;
2238 
2239 	for (i = 0; i < USFIELD_LAST; i++) {
2240 		if (strcmp(field, us_field_names[i]) == 0)
2241 			return (i);
2242 	}
2243 
2244 	return (-1);
2245 }
2246 
2247 static int
2248 us_compare(const void *larg, const void *rarg, void *unused)
2249 {
2250 	const us_node_t *l = larg;
2251 	const us_node_t *r = rarg;
2252 	us_sort_info_t *si = (us_sort_info_t *)unused;
2253 	zfs_sort_column_t *sortcol = si->si_sortcol;
2254 	boolean_t numname = si->si_numname;
2255 	nvlist_t *lnvl = l->usn_nvl;
2256 	nvlist_t *rnvl = r->usn_nvl;
2257 	int rc = 0;
2258 	boolean_t lvb, rvb;
2259 
2260 	for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2261 		char *lvstr = "";
2262 		char *rvstr = "";
2263 		uint32_t lv32 = 0;
2264 		uint32_t rv32 = 0;
2265 		uint64_t lv64 = 0;
2266 		uint64_t rv64 = 0;
2267 		zfs_prop_t prop = sortcol->sc_prop;
2268 		const char *propname = NULL;
2269 		boolean_t reverse = sortcol->sc_reverse;
2270 
2271 		switch (prop) {
2272 		case ZFS_PROP_TYPE:
2273 			propname = "type";
2274 			(void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2275 			(void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2276 			if (rv32 != lv32)
2277 				rc = (rv32 < lv32) ? 1 : -1;
2278 			break;
2279 		case ZFS_PROP_NAME:
2280 			propname = "name";
2281 			if (numname) {
2282 				(void) nvlist_lookup_uint64(lnvl, propname,
2283 				    &lv64);
2284 				(void) nvlist_lookup_uint64(rnvl, propname,
2285 				    &rv64);
2286 				if (rv64 != lv64)
2287 					rc = (rv64 < lv64) ? 1 : -1;
2288 			} else {
2289 				(void) nvlist_lookup_string(lnvl, propname,
2290 				    &lvstr);
2291 				(void) nvlist_lookup_string(rnvl, propname,
2292 				    &rvstr);
2293 				rc = strcmp(lvstr, rvstr);
2294 			}
2295 			break;
2296 		case ZFS_PROP_USED:
2297 		case ZFS_PROP_QUOTA:
2298 			if (!us_populated)
2299 				break;
2300 			if (prop == ZFS_PROP_USED)
2301 				propname = "used";
2302 			else
2303 				propname = "quota";
2304 			(void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2305 			(void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2306 			if (rv64 != lv64)
2307 				rc = (rv64 < lv64) ? 1 : -1;
2308 			break;
2309 		}
2310 
2311 		if (rc != 0) {
2312 			if (rc < 0)
2313 				return (reverse ? 1 : -1);
2314 			else
2315 				return (reverse ? -1 : 1);
2316 		}
2317 	}
2318 
2319 	/*
2320 	 * If entries still seem to be the same, check if they are of the same
2321 	 * type (smbentity is added only if we are doing SID to POSIX ID
2322 	 * translation where we can have duplicate type/name combinations).
2323 	 */
2324 	if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2325 	    nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2326 	    lvb != rvb)
2327 		return (lvb < rvb ? -1 : 1);
2328 
2329 	return (0);
2330 }
2331 
2332 static inline const char *
2333 us_type2str(unsigned field_type)
2334 {
2335 	switch (field_type) {
2336 	case USTYPE_PSX_USR:
2337 		return ("POSIX User");
2338 	case USTYPE_PSX_GRP:
2339 		return ("POSIX Group");
2340 	case USTYPE_SMB_USR:
2341 		return ("SMB User");
2342 	case USTYPE_SMB_GRP:
2343 		return ("SMB Group");
2344 	default:
2345 		return ("Undefined");
2346 	}
2347 }
2348 
2349 static int
2350 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2351 {
2352 	us_cbdata_t *cb = (us_cbdata_t *)arg;
2353 	zfs_userquota_prop_t prop = cb->cb_prop;
2354 	char *name = NULL;
2355 	char *propname;
2356 	char sizebuf[32];
2357 	us_node_t *node;
2358 	uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2359 	uu_avl_t *avl = cb->cb_avl;
2360 	uu_avl_index_t idx;
2361 	nvlist_t *props;
2362 	us_node_t *n;
2363 	zfs_sort_column_t *sortcol = cb->cb_sortcol;
2364 	unsigned type;
2365 	const char *typestr;
2366 	size_t namelen;
2367 	size_t typelen;
2368 	size_t sizelen;
2369 	int typeidx, nameidx, sizeidx;
2370 	us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2371 	boolean_t smbentity = B_FALSE;
2372 
2373 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2374 		nomem();
2375 	node = safe_malloc(sizeof (us_node_t));
2376 	uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2377 	node->usn_nvl = props;
2378 
2379 	if (domain != NULL && domain[0] != '\0') {
2380 		/* SMB */
2381 		char sid[ZFS_MAXNAMELEN + 32];
2382 		uid_t id;
2383 		int err;
2384 		int flag = IDMAP_REQ_FLG_USE_CACHE;
2385 
2386 		smbentity = B_TRUE;
2387 
2388 		(void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2389 
2390 		if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2391 			type = USTYPE_SMB_GRP;
2392 			err = sid_to_id(sid, B_FALSE, &id);
2393 		} else {
2394 			type = USTYPE_SMB_USR;
2395 			err = sid_to_id(sid, B_TRUE, &id);
2396 		}
2397 
2398 		if (err == 0) {
2399 			rid = id;
2400 			if (!cb->cb_sid2posix) {
2401 				if (type == USTYPE_SMB_USR) {
2402 					(void) idmap_getwinnamebyuid(rid, flag,
2403 					    &name, NULL);
2404 				} else {
2405 					(void) idmap_getwinnamebygid(rid, flag,
2406 					    &name, NULL);
2407 				}
2408 				if (name == NULL)
2409 					name = sid;
2410 			}
2411 		}
2412 	}
2413 
2414 	if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2415 		/* POSIX or -i */
2416 		if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2417 			type = USTYPE_PSX_GRP;
2418 			if (!cb->cb_numname) {
2419 				struct group *g;
2420 
2421 				if ((g = getgrgid(rid)) != NULL)
2422 					name = g->gr_name;
2423 			}
2424 		} else {
2425 			type = USTYPE_PSX_USR;
2426 			if (!cb->cb_numname) {
2427 				struct passwd *p;
2428 
2429 				if ((p = getpwuid(rid)) != NULL)
2430 					name = p->pw_name;
2431 			}
2432 		}
2433 	}
2434 
2435 	/*
2436 	 * Make sure that the type/name combination is unique when doing
2437 	 * SID to POSIX ID translation (hence changing the type from SMB to
2438 	 * POSIX).
2439 	 */
2440 	if (cb->cb_sid2posix &&
2441 	    nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2442 		nomem();
2443 
2444 	/* Calculate/update width of TYPE field */
2445 	typestr = us_type2str(type);
2446 	typelen = strlen(gettext(typestr));
2447 	typeidx = us_field_index("type");
2448 	if (typelen > cb->cb_width[typeidx])
2449 		cb->cb_width[typeidx] = typelen;
2450 	if (nvlist_add_uint32(props, "type", type) != 0)
2451 		nomem();
2452 
2453 	/* Calculate/update width of NAME field */
2454 	if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2455 		if (nvlist_add_uint64(props, "name", rid) != 0)
2456 			nomem();
2457 		namelen = snprintf(NULL, 0, "%u", rid);
2458 	} else {
2459 		if (nvlist_add_string(props, "name", name) != 0)
2460 			nomem();
2461 		namelen = strlen(name);
2462 	}
2463 	nameidx = us_field_index("name");
2464 	if (namelen > cb->cb_width[nameidx])
2465 		cb->cb_width[nameidx] = namelen;
2466 
2467 	/*
2468 	 * Check if this type/name combination is in the list and update it;
2469 	 * otherwise add new node to the list.
2470 	 */
2471 	if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2472 		uu_avl_insert(avl, node, idx);
2473 	} else {
2474 		nvlist_free(props);
2475 		free(node);
2476 		node = n;
2477 		props = node->usn_nvl;
2478 	}
2479 
2480 	/* Calculate/update width of USED/QUOTA fields */
2481 	if (cb->cb_nicenum)
2482 		zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2483 	else
2484 		(void) snprintf(sizebuf, sizeof (sizebuf), "%llu", space);
2485 	sizelen = strlen(sizebuf);
2486 	if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2487 		propname = "used";
2488 		if (!nvlist_exists(props, "quota"))
2489 			(void) nvlist_add_uint64(props, "quota", 0);
2490 	} else {
2491 		propname = "quota";
2492 		if (!nvlist_exists(props, "used"))
2493 			(void) nvlist_add_uint64(props, "used", 0);
2494 	}
2495 	sizeidx = us_field_index(propname);
2496 	if (sizelen > cb->cb_width[sizeidx])
2497 		cb->cb_width[sizeidx] = sizelen;
2498 
2499 	if (nvlist_add_uint64(props, propname, space) != 0)
2500 		nomem();
2501 
2502 	return (0);
2503 }
2504 
2505 static void
2506 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2507     size_t *width, us_node_t *node)
2508 {
2509 	nvlist_t *nvl = node->usn_nvl;
2510 	char valstr[ZFS_MAXNAMELEN];
2511 	boolean_t first = B_TRUE;
2512 	int cfield = 0;
2513 	int field;
2514 	uint32_t ustype;
2515 
2516 	/* Check type */
2517 	(void) nvlist_lookup_uint32(nvl, "type", &ustype);
2518 	if (!(ustype & types))
2519 		return;
2520 
2521 	while ((field = fields[cfield]) != USFIELD_LAST) {
2522 		nvpair_t *nvp = NULL;
2523 		data_type_t type;
2524 		uint32_t val32;
2525 		uint64_t val64;
2526 		char *strval = NULL;
2527 
2528 		while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2529 			if (strcmp(nvpair_name(nvp),
2530 			    us_field_names[field]) == 0)
2531 				break;
2532 		}
2533 
2534 		type = nvpair_type(nvp);
2535 		switch (type) {
2536 		case DATA_TYPE_UINT32:
2537 			(void) nvpair_value_uint32(nvp, &val32);
2538 			break;
2539 		case DATA_TYPE_UINT64:
2540 			(void) nvpair_value_uint64(nvp, &val64);
2541 			break;
2542 		case DATA_TYPE_STRING:
2543 			(void) nvpair_value_string(nvp, &strval);
2544 			break;
2545 		default:
2546 			(void) fprintf(stderr, "invalid data type\n");
2547 		}
2548 
2549 		switch (field) {
2550 		case USFIELD_TYPE:
2551 			strval = (char *)us_type2str(val32);
2552 			break;
2553 		case USFIELD_NAME:
2554 			if (type == DATA_TYPE_UINT64) {
2555 				(void) sprintf(valstr, "%llu", val64);
2556 				strval = valstr;
2557 			}
2558 			break;
2559 		case USFIELD_USED:
2560 		case USFIELD_QUOTA:
2561 			if (type == DATA_TYPE_UINT64) {
2562 				if (parsable) {
2563 					(void) sprintf(valstr, "%llu", val64);
2564 				} else {
2565 					zfs_nicenum(val64, valstr,
2566 					    sizeof (valstr));
2567 				}
2568 				if (field == USFIELD_QUOTA &&
2569 				    strcmp(valstr, "0") == 0)
2570 					strval = "none";
2571 				else
2572 					strval = valstr;
2573 			}
2574 			break;
2575 		}
2576 
2577 		if (!first) {
2578 			if (scripted)
2579 				(void) printf("\t");
2580 			else
2581 				(void) printf("  ");
2582 		}
2583 		if (scripted)
2584 			(void) printf("%s", strval);
2585 		else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2586 			(void) printf("%-*s", width[field], strval);
2587 		else
2588 			(void) printf("%*s", width[field], strval);
2589 
2590 		first = B_FALSE;
2591 		cfield++;
2592 	}
2593 
2594 	(void) printf("\n");
2595 }
2596 
2597 static void
2598 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2599     size_t *width, boolean_t rmnode, uu_avl_t *avl)
2600 {
2601 	us_node_t *node;
2602 	const char *col;
2603 	int cfield = 0;
2604 	int field;
2605 
2606 	if (!scripted) {
2607 		boolean_t first = B_TRUE;
2608 
2609 		while ((field = fields[cfield]) != USFIELD_LAST) {
2610 			col = gettext(us_field_hdr[field]);
2611 			if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2612 				(void) printf(first ? "%-*s" : "  %-*s",
2613 				    width[field], col);
2614 			} else {
2615 				(void) printf(first ? "%*s" : "  %*s",
2616 				    width[field], col);
2617 			}
2618 			first = B_FALSE;
2619 			cfield++;
2620 		}
2621 		(void) printf("\n");
2622 	}
2623 
2624 	for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2625 		print_us_node(scripted, parsable, fields, types, width, node);
2626 		if (rmnode)
2627 			nvlist_free(node->usn_nvl);
2628 	}
2629 }
2630 
2631 static int
2632 zfs_do_userspace(int argc, char **argv)
2633 {
2634 	zfs_handle_t *zhp;
2635 	zfs_userquota_prop_t p;
2636 	uu_avl_pool_t *avl_pool;
2637 	uu_avl_t *avl_tree;
2638 	uu_avl_walk_t *walk;
2639 	char *delim;
2640 	char deffields[] = "type,name,used,quota";
2641 	char *ofield = NULL;
2642 	char *tfield = NULL;
2643 	int cfield = 0;
2644 	int fields[256];
2645 	int i;
2646 	boolean_t scripted = B_FALSE;
2647 	boolean_t prtnum = B_FALSE;
2648 	boolean_t parsable = B_FALSE;
2649 	boolean_t sid2posix = B_FALSE;
2650 	int ret = 0;
2651 	int c;
2652 	zfs_sort_column_t *sortcol = NULL;
2653 	int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2654 	us_cbdata_t cb;
2655 	us_node_t *node;
2656 	us_node_t *rmnode;
2657 	uu_list_pool_t *listpool;
2658 	uu_list_t *list;
2659 	uu_avl_index_t idx = 0;
2660 	uu_list_index_t idx2 = 0;
2661 
2662 	if (argc < 2)
2663 		usage(B_FALSE);
2664 
2665 	if (strcmp(argv[0], "groupspace") == 0)
2666 		/* Toggle default group types */
2667 		types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2668 
2669 	while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2670 		switch (c) {
2671 		case 'n':
2672 			prtnum = B_TRUE;
2673 			break;
2674 		case 'H':
2675 			scripted = B_TRUE;
2676 			break;
2677 		case 'p':
2678 			parsable = B_TRUE;
2679 			break;
2680 		case 'o':
2681 			ofield = optarg;
2682 			break;
2683 		case 's':
2684 		case 'S':
2685 			if (zfs_add_sort_column(&sortcol, optarg,
2686 			    c == 's' ? B_FALSE : B_TRUE) != 0) {
2687 				(void) fprintf(stderr,
2688 				    gettext("invalid field '%s'\n"), optarg);
2689 				usage(B_FALSE);
2690 			}
2691 			break;
2692 		case 't':
2693 			tfield = optarg;
2694 			break;
2695 		case 'i':
2696 			sid2posix = B_TRUE;
2697 			break;
2698 		case ':':
2699 			(void) fprintf(stderr, gettext("missing argument for "
2700 			    "'%c' option\n"), optopt);
2701 			usage(B_FALSE);
2702 			break;
2703 		case '?':
2704 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2705 			    optopt);
2706 			usage(B_FALSE);
2707 		}
2708 	}
2709 
2710 	argc -= optind;
2711 	argv += optind;
2712 
2713 	if (argc < 1) {
2714 		(void) fprintf(stderr, gettext("missing dataset name\n"));
2715 		usage(B_FALSE);
2716 	}
2717 	if (argc > 1) {
2718 		(void) fprintf(stderr, gettext("too many arguments\n"));
2719 		usage(B_FALSE);
2720 	}
2721 
2722 	/* Use default output fields if not specified using -o */
2723 	if (ofield == NULL)
2724 		ofield = deffields;
2725 	do {
2726 		if ((delim = strchr(ofield, ',')) != NULL)
2727 			*delim = '\0';
2728 		if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2729 			(void) fprintf(stderr, gettext("invalid type '%s' "
2730 			    "for -o option\n"), ofield);
2731 			return (-1);
2732 		}
2733 		if (delim != NULL)
2734 			ofield = delim + 1;
2735 	} while (delim != NULL);
2736 	fields[cfield] = USFIELD_LAST;
2737 
2738 	/* Override output types (-t option) */
2739 	if (tfield != NULL) {
2740 		types = 0;
2741 
2742 		do {
2743 			boolean_t found = B_FALSE;
2744 
2745 			if ((delim = strchr(tfield, ',')) != NULL)
2746 				*delim = '\0';
2747 			for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2748 			    i++) {
2749 				if (strcmp(tfield, us_type_names[i]) == 0) {
2750 					found = B_TRUE;
2751 					types |= us_type_bits[i];
2752 					break;
2753 				}
2754 			}
2755 			if (!found) {
2756 				(void) fprintf(stderr, gettext("invalid type "
2757 				    "'%s' for -t option\n"), tfield);
2758 				return (-1);
2759 			}
2760 			if (delim != NULL)
2761 				tfield = delim + 1;
2762 		} while (delim != NULL);
2763 	}
2764 
2765 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2766 		return (1);
2767 
2768 	if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2769 	    offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2770 		nomem();
2771 	if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2772 		nomem();
2773 
2774 	/* Always add default sorting columns */
2775 	(void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2776 	(void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2777 
2778 	cb.cb_sortcol = sortcol;
2779 	cb.cb_numname = prtnum;
2780 	cb.cb_nicenum = !parsable;
2781 	cb.cb_avl_pool = avl_pool;
2782 	cb.cb_avl = avl_tree;
2783 	cb.cb_sid2posix = sid2posix;
2784 
2785 	for (i = 0; i < USFIELD_LAST; i++)
2786 		cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2787 
2788 	for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2789 		if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2790 		    !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2791 		    ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2792 		    !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2793 			continue;
2794 		cb.cb_prop = p;
2795 		if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2796 			return (ret);
2797 	}
2798 
2799 	/* Sort the list */
2800 	if ((node = uu_avl_first(avl_tree)) == NULL)
2801 		return (0);
2802 
2803 	us_populated = B_TRUE;
2804 
2805 	listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2806 	    offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2807 	list = uu_list_create(listpool, NULL, UU_DEFAULT);
2808 	uu_list_node_init(node, &node->usn_listnode, listpool);
2809 
2810 	while (node != NULL) {
2811 		rmnode = node;
2812 		node = uu_avl_next(avl_tree, node);
2813 		uu_avl_remove(avl_tree, rmnode);
2814 		if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2815 			uu_list_insert(list, rmnode, idx2);
2816 	}
2817 
2818 	for (node = uu_list_first(list); node != NULL;
2819 	    node = uu_list_next(list, node)) {
2820 		us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2821 
2822 		if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2823 			uu_avl_insert(avl_tree, node, idx);
2824 	}
2825 
2826 	uu_list_destroy(list);
2827 	uu_list_pool_destroy(listpool);
2828 
2829 	/* Print and free node nvlist memory */
2830 	print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2831 	    cb.cb_avl);
2832 
2833 	zfs_free_sort_columns(sortcol);
2834 
2835 	/* Clean up the AVL tree */
2836 	if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2837 		nomem();
2838 
2839 	while ((node = uu_avl_walk_next(walk)) != NULL) {
2840 		uu_avl_remove(cb.cb_avl, node);
2841 		free(node);
2842 	}
2843 
2844 	uu_avl_walk_end(walk);
2845 	uu_avl_destroy(avl_tree);
2846 	uu_avl_pool_destroy(avl_pool);
2847 
2848 	return (ret);
2849 }
2850 
2851 /*
2852  * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2853  *      [-t type[,...]] [filesystem|volume|snapshot] ...
2854  *
2855  *	-H	Scripted mode; elide headers and separate columns by tabs.
2856  *	-p	Display values in parsable (literal) format.
2857  *	-r	Recurse over all children.
2858  *	-d	Limit recursion by depth.
2859  *	-o	Control which fields to display.
2860  *	-s	Specify sort columns, descending order.
2861  *	-S	Specify sort columns, ascending order.
2862  *	-t	Control which object types to display.
2863  *
2864  * When given no arguments, list all filesystems in the system.
2865  * Otherwise, list the specified datasets, optionally recursing down them if
2866  * '-r' is specified.
2867  */
2868 typedef struct list_cbdata {
2869 	boolean_t	cb_first;
2870 	boolean_t	cb_literal;
2871 	boolean_t	cb_scripted;
2872 	zprop_list_t	*cb_proplist;
2873 } list_cbdata_t;
2874 
2875 /*
2876  * Given a list of columns to display, output appropriate headers for each one.
2877  */
2878 static void
2879 print_header(list_cbdata_t *cb)
2880 {
2881 	zprop_list_t *pl = cb->cb_proplist;
2882 	char headerbuf[ZFS_MAXPROPLEN];
2883 	const char *header;
2884 	int i;
2885 	boolean_t first = B_TRUE;
2886 	boolean_t right_justify;
2887 
2888 	for (; pl != NULL; pl = pl->pl_next) {
2889 		if (!first) {
2890 			(void) printf("  ");
2891 		} else {
2892 			first = B_FALSE;
2893 		}
2894 
2895 		right_justify = B_FALSE;
2896 		if (pl->pl_prop != ZPROP_INVAL) {
2897 			header = zfs_prop_column_name(pl->pl_prop);
2898 			right_justify = zfs_prop_align_right(pl->pl_prop);
2899 		} else {
2900 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2901 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
2902 			headerbuf[i] = '\0';
2903 			header = headerbuf;
2904 		}
2905 
2906 		if (pl->pl_next == NULL && !right_justify)
2907 			(void) printf("%s", header);
2908 		else if (right_justify)
2909 			(void) printf("%*s", pl->pl_width, header);
2910 		else
2911 			(void) printf("%-*s", pl->pl_width, header);
2912 	}
2913 
2914 	(void) printf("\n");
2915 }
2916 
2917 /*
2918  * Given a dataset and a list of fields, print out all the properties according
2919  * to the described layout.
2920  */
2921 static void
2922 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2923 {
2924 	zprop_list_t *pl = cb->cb_proplist;
2925 	boolean_t first = B_TRUE;
2926 	char property[ZFS_MAXPROPLEN];
2927 	nvlist_t *userprops = zfs_get_user_props(zhp);
2928 	nvlist_t *propval;
2929 	char *propstr;
2930 	boolean_t right_justify;
2931 
2932 	for (; pl != NULL; pl = pl->pl_next) {
2933 		if (!first) {
2934 			if (cb->cb_scripted)
2935 				(void) printf("\t");
2936 			else
2937 				(void) printf("  ");
2938 		} else {
2939 			first = B_FALSE;
2940 		}
2941 
2942 		if (pl->pl_prop != ZPROP_INVAL) {
2943 			if (zfs_prop_get(zhp, pl->pl_prop, property,
2944 			    sizeof (property), NULL, NULL, 0,
2945 			    cb->cb_literal) != 0)
2946 				propstr = "-";
2947 			else
2948 				propstr = property;
2949 			right_justify = zfs_prop_align_right(pl->pl_prop);
2950 		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
2951 			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2952 			    property, sizeof (property), cb->cb_literal) != 0)
2953 				propstr = "-";
2954 			else
2955 				propstr = property;
2956 			right_justify = B_TRUE;
2957 		} else if (zfs_prop_written(pl->pl_user_prop)) {
2958 			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2959 			    property, sizeof (property), cb->cb_literal) != 0)
2960 				propstr = "-";
2961 			else
2962 				propstr = property;
2963 			right_justify = B_TRUE;
2964 		} else {
2965 			if (nvlist_lookup_nvlist(userprops,
2966 			    pl->pl_user_prop, &propval) != 0)
2967 				propstr = "-";
2968 			else
2969 				verify(nvlist_lookup_string(propval,
2970 				    ZPROP_VALUE, &propstr) == 0);
2971 			right_justify = B_FALSE;
2972 		}
2973 
2974 		/*
2975 		 * If this is being called in scripted mode, or if this is the
2976 		 * last column and it is left-justified, don't include a width
2977 		 * format specifier.
2978 		 */
2979 		if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
2980 			(void) printf("%s", propstr);
2981 		else if (right_justify)
2982 			(void) printf("%*s", pl->pl_width, propstr);
2983 		else
2984 			(void) printf("%-*s", pl->pl_width, propstr);
2985 	}
2986 
2987 	(void) printf("\n");
2988 }
2989 
2990 /*
2991  * Generic callback function to list a dataset or snapshot.
2992  */
2993 static int
2994 list_callback(zfs_handle_t *zhp, void *data)
2995 {
2996 	list_cbdata_t *cbp = data;
2997 
2998 	if (cbp->cb_first) {
2999 		if (!cbp->cb_scripted)
3000 			print_header(cbp);
3001 		cbp->cb_first = B_FALSE;
3002 	}
3003 
3004 	print_dataset(zhp, cbp);
3005 
3006 	return (0);
3007 }
3008 
3009 static int
3010 zfs_do_list(int argc, char **argv)
3011 {
3012 	int c;
3013 	static char default_fields[] =
3014 	    "name,used,available,referenced,mountpoint";
3015 	int types = ZFS_TYPE_DATASET;
3016 	boolean_t types_specified = B_FALSE;
3017 	char *fields = NULL;
3018 	list_cbdata_t cb = { 0 };
3019 	char *value;
3020 	int limit = 0;
3021 	int ret = 0;
3022 	zfs_sort_column_t *sortcol = NULL;
3023 	int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3024 
3025 	/* check options */
3026 	while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3027 		switch (c) {
3028 		case 'o':
3029 			fields = optarg;
3030 			break;
3031 		case 'p':
3032 			cb.cb_literal = B_TRUE;
3033 			flags |= ZFS_ITER_LITERAL_PROPS;
3034 			break;
3035 		case 'd':
3036 			limit = parse_depth(optarg, &flags);
3037 			break;
3038 		case 'r':
3039 			flags |= ZFS_ITER_RECURSE;
3040 			break;
3041 		case 'H':
3042 			cb.cb_scripted = B_TRUE;
3043 			break;
3044 		case 's':
3045 			if (zfs_add_sort_column(&sortcol, optarg,
3046 			    B_FALSE) != 0) {
3047 				(void) fprintf(stderr,
3048 				    gettext("invalid property '%s'\n"), optarg);
3049 				usage(B_FALSE);
3050 			}
3051 			break;
3052 		case 'S':
3053 			if (zfs_add_sort_column(&sortcol, optarg,
3054 			    B_TRUE) != 0) {
3055 				(void) fprintf(stderr,
3056 				    gettext("invalid property '%s'\n"), optarg);
3057 				usage(B_FALSE);
3058 			}
3059 			break;
3060 		case 't':
3061 			types = 0;
3062 			types_specified = B_TRUE;
3063 			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3064 			while (*optarg != '\0') {
3065 				static char *type_subopts[] = { "filesystem",
3066 				    "volume", "snapshot", "snap", "bookmark",
3067 				    "all", NULL };
3068 
3069 				switch (getsubopt(&optarg, type_subopts,
3070 				    &value)) {
3071 				case 0:
3072 					types |= ZFS_TYPE_FILESYSTEM;
3073 					break;
3074 				case 1:
3075 					types |= ZFS_TYPE_VOLUME;
3076 					break;
3077 				case 2:
3078 				case 3:
3079 					types |= ZFS_TYPE_SNAPSHOT;
3080 					break;
3081 				case 4:
3082 					types |= ZFS_TYPE_BOOKMARK;
3083 					break;
3084 				case 5:
3085 					types = ZFS_TYPE_DATASET |
3086 					    ZFS_TYPE_BOOKMARK;
3087 					break;
3088 				default:
3089 					(void) fprintf(stderr,
3090 					    gettext("invalid type '%s'\n"),
3091 					    value);
3092 					usage(B_FALSE);
3093 				}
3094 			}
3095 			break;
3096 		case ':':
3097 			(void) fprintf(stderr, gettext("missing argument for "
3098 			    "'%c' option\n"), optopt);
3099 			usage(B_FALSE);
3100 			break;
3101 		case '?':
3102 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3103 			    optopt);
3104 			usage(B_FALSE);
3105 		}
3106 	}
3107 
3108 	argc -= optind;
3109 	argv += optind;
3110 
3111 	if (fields == NULL)
3112 		fields = default_fields;
3113 
3114 	/*
3115 	 * If "-o space" and no types were specified, don't display snapshots.
3116 	 */
3117 	if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3118 		types &= ~ZFS_TYPE_SNAPSHOT;
3119 
3120 	/*
3121 	 * If the user specifies '-o all', the zprop_get_list() doesn't
3122 	 * normally include the name of the dataset.  For 'zfs list', we always
3123 	 * want this property to be first.
3124 	 */
3125 	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3126 	    != 0)
3127 		usage(B_FALSE);
3128 
3129 	cb.cb_first = B_TRUE;
3130 
3131 	ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3132 	    limit, list_callback, &cb);
3133 
3134 	zprop_free_list(cb.cb_proplist);
3135 	zfs_free_sort_columns(sortcol);
3136 
3137 	if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3138 		(void) printf(gettext("no datasets available\n"));
3139 
3140 	return (ret);
3141 }
3142 
3143 /*
3144  * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3145  * zfs rename [-f] -p <fs | vol> <fs | vol>
3146  * zfs rename -r <snap> <snap>
3147  *
3148  * Renames the given dataset to another of the same type.
3149  *
3150  * The '-p' flag creates all the non-existing ancestors of the target first.
3151  */
3152 /* ARGSUSED */
3153 static int
3154 zfs_do_rename(int argc, char **argv)
3155 {
3156 	zfs_handle_t *zhp;
3157 	int c;
3158 	int ret = 0;
3159 	boolean_t recurse = B_FALSE;
3160 	boolean_t parents = B_FALSE;
3161 	boolean_t force_unmount = B_FALSE;
3162 
3163 	/* check options */
3164 	while ((c = getopt(argc, argv, "prf")) != -1) {
3165 		switch (c) {
3166 		case 'p':
3167 			parents = B_TRUE;
3168 			break;
3169 		case 'r':
3170 			recurse = B_TRUE;
3171 			break;
3172 		case 'f':
3173 			force_unmount = B_TRUE;
3174 			break;
3175 		case '?':
3176 		default:
3177 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3178 			    optopt);
3179 			usage(B_FALSE);
3180 		}
3181 	}
3182 
3183 	argc -= optind;
3184 	argv += optind;
3185 
3186 	/* check number of arguments */
3187 	if (argc < 1) {
3188 		(void) fprintf(stderr, gettext("missing source dataset "
3189 		    "argument\n"));
3190 		usage(B_FALSE);
3191 	}
3192 	if (argc < 2) {
3193 		(void) fprintf(stderr, gettext("missing target dataset "
3194 		    "argument\n"));
3195 		usage(B_FALSE);
3196 	}
3197 	if (argc > 2) {
3198 		(void) fprintf(stderr, gettext("too many arguments\n"));
3199 		usage(B_FALSE);
3200 	}
3201 
3202 	if (recurse && parents) {
3203 		(void) fprintf(stderr, gettext("-p and -r options are mutually "
3204 		    "exclusive\n"));
3205 		usage(B_FALSE);
3206 	}
3207 
3208 	if (recurse && strchr(argv[0], '@') == 0) {
3209 		(void) fprintf(stderr, gettext("source dataset for recursive "
3210 		    "rename must be a snapshot\n"));
3211 		usage(B_FALSE);
3212 	}
3213 
3214 	if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3215 	    ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3216 		return (1);
3217 
3218 	/* If we were asked and the name looks good, try to create ancestors. */
3219 	if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3220 	    zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3221 		zfs_close(zhp);
3222 		return (1);
3223 	}
3224 
3225 	ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3226 
3227 	zfs_close(zhp);
3228 	return (ret);
3229 }
3230 
3231 /*
3232  * zfs promote <fs>
3233  *
3234  * Promotes the given clone fs to be the parent
3235  */
3236 /* ARGSUSED */
3237 static int
3238 zfs_do_promote(int argc, char **argv)
3239 {
3240 	zfs_handle_t *zhp;
3241 	int ret = 0;
3242 
3243 	/* check options */
3244 	if (argc > 1 && argv[1][0] == '-') {
3245 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3246 		    argv[1][1]);
3247 		usage(B_FALSE);
3248 	}
3249 
3250 	/* check number of arguments */
3251 	if (argc < 2) {
3252 		(void) fprintf(stderr, gettext("missing clone filesystem"
3253 		    " argument\n"));
3254 		usage(B_FALSE);
3255 	}
3256 	if (argc > 2) {
3257 		(void) fprintf(stderr, gettext("too many arguments\n"));
3258 		usage(B_FALSE);
3259 	}
3260 
3261 	zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3262 	if (zhp == NULL)
3263 		return (1);
3264 
3265 	ret = (zfs_promote(zhp) != 0);
3266 
3267 
3268 	zfs_close(zhp);
3269 	return (ret);
3270 }
3271 
3272 /*
3273  * zfs rollback [-rRf] <snapshot>
3274  *
3275  *	-r	Delete any intervening snapshots before doing rollback
3276  *	-R	Delete any snapshots and their clones
3277  *	-f	ignored for backwards compatability
3278  *
3279  * Given a filesystem, rollback to a specific snapshot, discarding any changes
3280  * since then and making it the active dataset.  If more recent snapshots exist,
3281  * the command will complain unless the '-r' flag is given.
3282  */
3283 typedef struct rollback_cbdata {
3284 	uint64_t	cb_create;
3285 	boolean_t	cb_first;
3286 	int		cb_doclones;
3287 	char		*cb_target;
3288 	int		cb_error;
3289 	boolean_t	cb_recurse;
3290 } rollback_cbdata_t;
3291 
3292 static int
3293 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3294 {
3295 	rollback_cbdata_t *cbp = data;
3296 
3297 	if (cbp->cb_first && cbp->cb_recurse) {
3298 		(void) fprintf(stderr, gettext("cannot rollback to "
3299 		    "'%s': clones of previous snapshots exist\n"),
3300 		    cbp->cb_target);
3301 		(void) fprintf(stderr, gettext("use '-R' to "
3302 		    "force deletion of the following clones and "
3303 		    "dependents:\n"));
3304 		cbp->cb_first = 0;
3305 		cbp->cb_error = 1;
3306 	}
3307 
3308 	(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3309 
3310 	zfs_close(zhp);
3311 	return (0);
3312 }
3313 
3314 /*
3315  * Report any snapshots more recent than the one specified.  Used when '-r' is
3316  * not specified.  We reuse this same callback for the snapshot dependents - if
3317  * 'cb_dependent' is set, then this is a dependent and we should report it
3318  * without checking the transaction group.
3319  */
3320 static int
3321 rollback_check(zfs_handle_t *zhp, void *data)
3322 {
3323 	rollback_cbdata_t *cbp = data;
3324 
3325 	if (cbp->cb_doclones) {
3326 		zfs_close(zhp);
3327 		return (0);
3328 	}
3329 
3330 	if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3331 		if (cbp->cb_first && !cbp->cb_recurse) {
3332 			(void) fprintf(stderr, gettext("cannot "
3333 			    "rollback to '%s': more recent snapshots "
3334 			    "or bookmarks exist\n"),
3335 			    cbp->cb_target);
3336 			(void) fprintf(stderr, gettext("use '-r' to "
3337 			    "force deletion of the following "
3338 			    "snapshots and bookmarks:\n"));
3339 			cbp->cb_first = 0;
3340 			cbp->cb_error = 1;
3341 		}
3342 
3343 		if (cbp->cb_recurse) {
3344 			if (zfs_iter_dependents(zhp, B_TRUE,
3345 			    rollback_check_dependent, cbp) != 0) {
3346 				zfs_close(zhp);
3347 				return (-1);
3348 			}
3349 		} else {
3350 			(void) fprintf(stderr, "%s\n",
3351 			    zfs_get_name(zhp));
3352 		}
3353 	}
3354 	zfs_close(zhp);
3355 	return (0);
3356 }
3357 
3358 static int
3359 zfs_do_rollback(int argc, char **argv)
3360 {
3361 	int ret = 0;
3362 	int c;
3363 	boolean_t force = B_FALSE;
3364 	rollback_cbdata_t cb = { 0 };
3365 	zfs_handle_t *zhp, *snap;
3366 	char parentname[ZFS_MAXNAMELEN];
3367 	char *delim;
3368 
3369 	/* check options */
3370 	while ((c = getopt(argc, argv, "rRf")) != -1) {
3371 		switch (c) {
3372 		case 'r':
3373 			cb.cb_recurse = 1;
3374 			break;
3375 		case 'R':
3376 			cb.cb_recurse = 1;
3377 			cb.cb_doclones = 1;
3378 			break;
3379 		case 'f':
3380 			force = B_TRUE;
3381 			break;
3382 		case '?':
3383 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3384 			    optopt);
3385 			usage(B_FALSE);
3386 		}
3387 	}
3388 
3389 	argc -= optind;
3390 	argv += optind;
3391 
3392 	/* check number of arguments */
3393 	if (argc < 1) {
3394 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
3395 		usage(B_FALSE);
3396 	}
3397 	if (argc > 1) {
3398 		(void) fprintf(stderr, gettext("too many arguments\n"));
3399 		usage(B_FALSE);
3400 	}
3401 
3402 	/* open the snapshot */
3403 	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3404 		return (1);
3405 
3406 	/* open the parent dataset */
3407 	(void) strlcpy(parentname, argv[0], sizeof (parentname));
3408 	verify((delim = strrchr(parentname, '@')) != NULL);
3409 	*delim = '\0';
3410 	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3411 		zfs_close(snap);
3412 		return (1);
3413 	}
3414 
3415 	/*
3416 	 * Check for more recent snapshots and/or clones based on the presence
3417 	 * of '-r' and '-R'.
3418 	 */
3419 	cb.cb_target = argv[0];
3420 	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3421 	cb.cb_first = B_TRUE;
3422 	cb.cb_error = 0;
3423 	if ((ret = zfs_iter_snapshots(zhp, rollback_check, &cb)) != 0)
3424 		goto out;
3425 	if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3426 		goto out;
3427 
3428 	if ((ret = cb.cb_error) != 0)
3429 		goto out;
3430 
3431 	/*
3432 	 * Rollback parent to the given snapshot.
3433 	 */
3434 	ret = zfs_rollback(zhp, snap, force);
3435 
3436 out:
3437 	zfs_close(snap);
3438 	zfs_close(zhp);
3439 
3440 	if (ret == 0)
3441 		return (0);
3442 	else
3443 		return (1);
3444 }
3445 
3446 /*
3447  * zfs set property=value ... { fs | snap | vol } ...
3448  *
3449  * Sets the given properties for all datasets specified on the command line.
3450  */
3451 
3452 static int
3453 set_callback(zfs_handle_t *zhp, void *data)
3454 {
3455 	nvlist_t *props = data;
3456 
3457 	if (zfs_prop_set_list(zhp, props) != 0) {
3458 		switch (libzfs_errno(g_zfs)) {
3459 		case EZFS_MOUNTFAILED:
3460 			(void) fprintf(stderr, gettext("property may be set "
3461 			    "but unable to remount filesystem\n"));
3462 			break;
3463 		case EZFS_SHARENFSFAILED:
3464 			(void) fprintf(stderr, gettext("property may be set "
3465 			    "but unable to reshare filesystem\n"));
3466 			break;
3467 		}
3468 		return (1);
3469 	}
3470 	return (0);
3471 }
3472 
3473 static int
3474 zfs_do_set(int argc, char **argv)
3475 {
3476 	nvlist_t *props = NULL;
3477 	int ds_start = -1; /* argv idx of first dataset arg */
3478 	int ret = 0;
3479 
3480 	/* check for options */
3481 	if (argc > 1 && argv[1][0] == '-') {
3482 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3483 		    argv[1][1]);
3484 		usage(B_FALSE);
3485 	}
3486 
3487 	/* check number of arguments */
3488 	if (argc < 2) {
3489 		(void) fprintf(stderr, gettext("missing arguments\n"));
3490 		usage(B_FALSE);
3491 	}
3492 	if (argc < 3) {
3493 		if (strchr(argv[1], '=') == NULL) {
3494 			(void) fprintf(stderr, gettext("missing property=value "
3495 			    "argument(s)\n"));
3496 		} else {
3497 			(void) fprintf(stderr, gettext("missing dataset "
3498 			    "name(s)\n"));
3499 		}
3500 		usage(B_FALSE);
3501 	}
3502 
3503 	/* validate argument order:  prop=val args followed by dataset args */
3504 	for (int i = 1; i < argc; i++) {
3505 		if (strchr(argv[i], '=') != NULL) {
3506 			if (ds_start > 0) {
3507 				/* out-of-order prop=val argument */
3508 				(void) fprintf(stderr, gettext("invalid "
3509 				    "argument order\n"), i);
3510 				usage(B_FALSE);
3511 			}
3512 		} else if (ds_start < 0) {
3513 			ds_start = i;
3514 		}
3515 	}
3516 	if (ds_start < 0) {
3517 		(void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3518 		usage(B_FALSE);
3519 	}
3520 
3521 	/* Populate a list of property settings */
3522 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3523 		nomem();
3524 	for (int i = 1; i < ds_start; i++) {
3525 		if ((ret = parseprop(props, argv[i])) != 0)
3526 			goto error;
3527 	}
3528 
3529 	ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3530 	    ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3531 
3532 error:
3533 	nvlist_free(props);
3534 	return (ret);
3535 }
3536 
3537 typedef struct snap_cbdata {
3538 	nvlist_t *sd_nvl;
3539 	boolean_t sd_recursive;
3540 	const char *sd_snapname;
3541 } snap_cbdata_t;
3542 
3543 static int
3544 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3545 {
3546 	snap_cbdata_t *sd = arg;
3547 	char *name;
3548 	int rv = 0;
3549 	int error;
3550 
3551 	if (sd->sd_recursive &&
3552 	    zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3553 		zfs_close(zhp);
3554 		return (0);
3555 	}
3556 
3557 	error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3558 	if (error == -1)
3559 		nomem();
3560 	fnvlist_add_boolean(sd->sd_nvl, name);
3561 	free(name);
3562 
3563 	if (sd->sd_recursive)
3564 		rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3565 	zfs_close(zhp);
3566 	return (rv);
3567 }
3568 
3569 /*
3570  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3571  *
3572  * Creates a snapshot with the given name.  While functionally equivalent to
3573  * 'zfs create', it is a separate command to differentiate intent.
3574  */
3575 static int
3576 zfs_do_snapshot(int argc, char **argv)
3577 {
3578 	int ret = 0;
3579 	char c;
3580 	nvlist_t *props;
3581 	snap_cbdata_t sd = { 0 };
3582 	boolean_t multiple_snaps = B_FALSE;
3583 
3584 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3585 		nomem();
3586 	if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3587 		nomem();
3588 
3589 	/* check options */
3590 	while ((c = getopt(argc, argv, "ro:")) != -1) {
3591 		switch (c) {
3592 		case 'o':
3593 			if (parseprop(props, optarg))
3594 				return (1);
3595 			break;
3596 		case 'r':
3597 			sd.sd_recursive = B_TRUE;
3598 			multiple_snaps = B_TRUE;
3599 			break;
3600 		case '?':
3601 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3602 			    optopt);
3603 			goto usage;
3604 		}
3605 	}
3606 
3607 	argc -= optind;
3608 	argv += optind;
3609 
3610 	/* check number of arguments */
3611 	if (argc < 1) {
3612 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
3613 		goto usage;
3614 	}
3615 
3616 	if (argc > 1)
3617 		multiple_snaps = B_TRUE;
3618 	for (; argc > 0; argc--, argv++) {
3619 		char *atp;
3620 		zfs_handle_t *zhp;
3621 
3622 		atp = strchr(argv[0], '@');
3623 		if (atp == NULL)
3624 			goto usage;
3625 		*atp = '\0';
3626 		sd.sd_snapname = atp + 1;
3627 		zhp = zfs_open(g_zfs, argv[0],
3628 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3629 		if (zhp == NULL)
3630 			goto usage;
3631 		if (zfs_snapshot_cb(zhp, &sd) != 0)
3632 			goto usage;
3633 	}
3634 
3635 	ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3636 	nvlist_free(sd.sd_nvl);
3637 	nvlist_free(props);
3638 	if (ret != 0 && multiple_snaps)
3639 		(void) fprintf(stderr, gettext("no snapshots were created\n"));
3640 	return (ret != 0);
3641 
3642 usage:
3643 	nvlist_free(sd.sd_nvl);
3644 	nvlist_free(props);
3645 	usage(B_FALSE);
3646 	return (-1);
3647 }
3648 
3649 /*
3650  * Send a backup stream to stdout.
3651  */
3652 static int
3653 zfs_do_send(int argc, char **argv)
3654 {
3655 	char *fromname = NULL;
3656 	char *toname = NULL;
3657 	char *cp;
3658 	zfs_handle_t *zhp;
3659 	sendflags_t flags = { 0 };
3660 	int c, err;
3661 	nvlist_t *dbgnv = NULL;
3662 	boolean_t extraverbose = B_FALSE;
3663 
3664 	/* check options */
3665 	while ((c = getopt(argc, argv, ":i:I:RDpvnPLe")) != -1) {
3666 		switch (c) {
3667 		case 'i':
3668 			if (fromname)
3669 				usage(B_FALSE);
3670 			fromname = optarg;
3671 			break;
3672 		case 'I':
3673 			if (fromname)
3674 				usage(B_FALSE);
3675 			fromname = optarg;
3676 			flags.doall = B_TRUE;
3677 			break;
3678 		case 'R':
3679 			flags.replicate = B_TRUE;
3680 			break;
3681 		case 'p':
3682 			flags.props = B_TRUE;
3683 			break;
3684 		case 'P':
3685 			flags.parsable = B_TRUE;
3686 			flags.verbose = B_TRUE;
3687 			break;
3688 		case 'v':
3689 			if (flags.verbose)
3690 				extraverbose = B_TRUE;
3691 			flags.verbose = B_TRUE;
3692 			flags.progress = B_TRUE;
3693 			break;
3694 		case 'D':
3695 			flags.dedup = B_TRUE;
3696 			break;
3697 		case 'n':
3698 			flags.dryrun = B_TRUE;
3699 			break;
3700 		case 'L':
3701 			flags.largeblock = B_TRUE;
3702 			break;
3703 		case 'e':
3704 			flags.embed_data = B_TRUE;
3705 			break;
3706 		case ':':
3707 			(void) fprintf(stderr, gettext("missing argument for "
3708 			    "'%c' option\n"), optopt);
3709 			usage(B_FALSE);
3710 			break;
3711 		case '?':
3712 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3713 			    optopt);
3714 			usage(B_FALSE);
3715 		}
3716 	}
3717 
3718 	argc -= optind;
3719 	argv += optind;
3720 
3721 	/* check number of arguments */
3722 	if (argc < 1) {
3723 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
3724 		usage(B_FALSE);
3725 	}
3726 	if (argc > 1) {
3727 		(void) fprintf(stderr, gettext("too many arguments\n"));
3728 		usage(B_FALSE);
3729 	}
3730 
3731 	if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3732 		(void) fprintf(stderr,
3733 		    gettext("Error: Stream can not be written to a terminal.\n"
3734 		    "You must redirect standard output.\n"));
3735 		return (1);
3736 	}
3737 
3738 	/*
3739 	 * Special case sending a filesystem, or from a bookmark.
3740 	 */
3741 	if (strchr(argv[0], '@') == NULL ||
3742 	    (fromname && strchr(fromname, '#') != NULL)) {
3743 		char frombuf[ZFS_MAXNAMELEN];
3744 		enum lzc_send_flags lzc_flags = 0;
3745 
3746 		if (flags.replicate || flags.doall || flags.props ||
3747 		    flags.dedup || flags.dryrun || flags.verbose ||
3748 		    flags.progress) {
3749 			(void) fprintf(stderr,
3750 			    gettext("Error: "
3751 			    "Unsupported flag with filesystem or bookmark.\n"));
3752 			return (1);
3753 		}
3754 
3755 		zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3756 		if (zhp == NULL)
3757 			return (1);
3758 
3759 		if (flags.largeblock)
3760 			lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3761 		if (flags.embed_data)
3762 			lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3763 
3764 		if (fromname != NULL &&
3765 		    (fromname[0] == '#' || fromname[0] == '@')) {
3766 			/*
3767 			 * Incremental source name begins with # or @.
3768 			 * Default to same fs as target.
3769 			 */
3770 			(void) strncpy(frombuf, argv[0], sizeof (frombuf));
3771 			cp = strchr(frombuf, '@');
3772 			if (cp != NULL)
3773 				*cp = '\0';
3774 			(void) strlcat(frombuf, fromname, sizeof (frombuf));
3775 			fromname = frombuf;
3776 		}
3777 		err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3778 		zfs_close(zhp);
3779 		return (err != 0);
3780 	}
3781 
3782 	cp = strchr(argv[0], '@');
3783 	*cp = '\0';
3784 	toname = cp + 1;
3785 	zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3786 	if (zhp == NULL)
3787 		return (1);
3788 
3789 	/*
3790 	 * If they specified the full path to the snapshot, chop off
3791 	 * everything except the short name of the snapshot, but special
3792 	 * case if they specify the origin.
3793 	 */
3794 	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3795 		char origin[ZFS_MAXNAMELEN];
3796 		zprop_source_t src;
3797 
3798 		(void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3799 		    origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3800 
3801 		if (strcmp(origin, fromname) == 0) {
3802 			fromname = NULL;
3803 			flags.fromorigin = B_TRUE;
3804 		} else {
3805 			*cp = '\0';
3806 			if (cp != fromname && strcmp(argv[0], fromname)) {
3807 				(void) fprintf(stderr,
3808 				    gettext("incremental source must be "
3809 				    "in same filesystem\n"));
3810 				usage(B_FALSE);
3811 			}
3812 			fromname = cp + 1;
3813 			if (strchr(fromname, '@') || strchr(fromname, '/')) {
3814 				(void) fprintf(stderr,
3815 				    gettext("invalid incremental source\n"));
3816 				usage(B_FALSE);
3817 			}
3818 		}
3819 	}
3820 
3821 	if (flags.replicate && fromname == NULL)
3822 		flags.doall = B_TRUE;
3823 
3824 	err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3825 	    extraverbose ? &dbgnv : NULL);
3826 
3827 	if (extraverbose && dbgnv != NULL) {
3828 		/*
3829 		 * dump_nvlist prints to stdout, but that's been
3830 		 * redirected to a file.  Make it print to stderr
3831 		 * instead.
3832 		 */
3833 		(void) dup2(STDERR_FILENO, STDOUT_FILENO);
3834 		dump_nvlist(dbgnv, 0);
3835 		nvlist_free(dbgnv);
3836 	}
3837 	zfs_close(zhp);
3838 
3839 	return (err != 0);
3840 }
3841 
3842 /*
3843  * zfs receive [-vnFu] [-d | -e] <fs@snap>
3844  *
3845  * Restore a backup stream from stdin.
3846  */
3847 static int
3848 zfs_do_receive(int argc, char **argv)
3849 {
3850 	int c, err;
3851 	recvflags_t flags = { 0 };
3852 
3853 	/* check options */
3854 	while ((c = getopt(argc, argv, ":denuvF")) != -1) {
3855 		switch (c) {
3856 		case 'd':
3857 			flags.isprefix = B_TRUE;
3858 			break;
3859 		case 'e':
3860 			flags.isprefix = B_TRUE;
3861 			flags.istail = B_TRUE;
3862 			break;
3863 		case 'n':
3864 			flags.dryrun = B_TRUE;
3865 			break;
3866 		case 'u':
3867 			flags.nomount = B_TRUE;
3868 			break;
3869 		case 'v':
3870 			flags.verbose = B_TRUE;
3871 			break;
3872 		case 'F':
3873 			flags.force = B_TRUE;
3874 			break;
3875 		case ':':
3876 			(void) fprintf(stderr, gettext("missing argument for "
3877 			    "'%c' option\n"), optopt);
3878 			usage(B_FALSE);
3879 			break;
3880 		case '?':
3881 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3882 			    optopt);
3883 			usage(B_FALSE);
3884 		}
3885 	}
3886 
3887 	argc -= optind;
3888 	argv += optind;
3889 
3890 	/* check number of arguments */
3891 	if (argc < 1) {
3892 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
3893 		usage(B_FALSE);
3894 	}
3895 	if (argc > 1) {
3896 		(void) fprintf(stderr, gettext("too many arguments\n"));
3897 		usage(B_FALSE);
3898 	}
3899 
3900 	if (isatty(STDIN_FILENO)) {
3901 		(void) fprintf(stderr,
3902 		    gettext("Error: Backup stream can not be read "
3903 		    "from a terminal.\n"
3904 		    "You must redirect standard input.\n"));
3905 		return (1);
3906 	}
3907 
3908 	err = zfs_receive(g_zfs, argv[0], &flags, STDIN_FILENO, NULL);
3909 
3910 	return (err != 0);
3911 }
3912 
3913 /*
3914  * allow/unallow stuff
3915  */
3916 /* copied from zfs/sys/dsl_deleg.h */
3917 #define	ZFS_DELEG_PERM_CREATE		"create"
3918 #define	ZFS_DELEG_PERM_DESTROY		"destroy"
3919 #define	ZFS_DELEG_PERM_SNAPSHOT		"snapshot"
3920 #define	ZFS_DELEG_PERM_ROLLBACK		"rollback"
3921 #define	ZFS_DELEG_PERM_CLONE		"clone"
3922 #define	ZFS_DELEG_PERM_PROMOTE		"promote"
3923 #define	ZFS_DELEG_PERM_RENAME		"rename"
3924 #define	ZFS_DELEG_PERM_MOUNT		"mount"
3925 #define	ZFS_DELEG_PERM_SHARE		"share"
3926 #define	ZFS_DELEG_PERM_SEND		"send"
3927 #define	ZFS_DELEG_PERM_RECEIVE		"receive"
3928 #define	ZFS_DELEG_PERM_ALLOW		"allow"
3929 #define	ZFS_DELEG_PERM_USERPROP		"userprop"
3930 #define	ZFS_DELEG_PERM_VSCAN		"vscan" /* ??? */
3931 #define	ZFS_DELEG_PERM_USERQUOTA	"userquota"
3932 #define	ZFS_DELEG_PERM_GROUPQUOTA	"groupquota"
3933 #define	ZFS_DELEG_PERM_USERUSED		"userused"
3934 #define	ZFS_DELEG_PERM_GROUPUSED	"groupused"
3935 #define	ZFS_DELEG_PERM_HOLD		"hold"
3936 #define	ZFS_DELEG_PERM_RELEASE		"release"
3937 #define	ZFS_DELEG_PERM_DIFF		"diff"
3938 #define	ZFS_DELEG_PERM_BOOKMARK		"bookmark"
3939 
3940 #define	ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
3941 
3942 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
3943 	{ ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
3944 	{ ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
3945 	{ ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
3946 	{ ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
3947 	{ ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
3948 	{ ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
3949 	{ ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
3950 	{ ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
3951 	{ ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
3952 	{ ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
3953 	{ ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
3954 	{ ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
3955 	{ ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
3956 	{ ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
3957 	{ ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
3958 	{ ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
3959 
3960 	{ ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
3961 	{ ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
3962 	{ ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
3963 	{ ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
3964 	{ ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
3965 	{ NULL, ZFS_DELEG_NOTE_NONE }
3966 };
3967 
3968 /* permission structure */
3969 typedef struct deleg_perm {
3970 	zfs_deleg_who_type_t	dp_who_type;
3971 	const char		*dp_name;
3972 	boolean_t		dp_local;
3973 	boolean_t		dp_descend;
3974 } deleg_perm_t;
3975 
3976 /* */
3977 typedef struct deleg_perm_node {
3978 	deleg_perm_t		dpn_perm;
3979 
3980 	uu_avl_node_t		dpn_avl_node;
3981 } deleg_perm_node_t;
3982 
3983 typedef struct fs_perm fs_perm_t;
3984 
3985 /* permissions set */
3986 typedef struct who_perm {
3987 	zfs_deleg_who_type_t	who_type;
3988 	const char		*who_name;		/* id */
3989 	char			who_ug_name[256];	/* user/group name */
3990 	fs_perm_t		*who_fsperm;		/* uplink */
3991 
3992 	uu_avl_t		*who_deleg_perm_avl;	/* permissions */
3993 } who_perm_t;
3994 
3995 /* */
3996 typedef struct who_perm_node {
3997 	who_perm_t	who_perm;
3998 	uu_avl_node_t	who_avl_node;
3999 } who_perm_node_t;
4000 
4001 typedef struct fs_perm_set fs_perm_set_t;
4002 /* fs permissions */
4003 struct fs_perm {
4004 	const char		*fsp_name;
4005 
4006 	uu_avl_t		*fsp_sc_avl;	/* sets,create */
4007 	uu_avl_t		*fsp_uge_avl;	/* user,group,everyone */
4008 
4009 	fs_perm_set_t		*fsp_set;	/* uplink */
4010 };
4011 
4012 /* */
4013 typedef struct fs_perm_node {
4014 	fs_perm_t	fspn_fsperm;
4015 	uu_avl_t	*fspn_avl;
4016 
4017 	uu_list_node_t	fspn_list_node;
4018 } fs_perm_node_t;
4019 
4020 /* top level structure */
4021 struct fs_perm_set {
4022 	uu_list_pool_t	*fsps_list_pool;
4023 	uu_list_t	*fsps_list; /* list of fs_perms */
4024 
4025 	uu_avl_pool_t	*fsps_named_set_avl_pool;
4026 	uu_avl_pool_t	*fsps_who_perm_avl_pool;
4027 	uu_avl_pool_t	*fsps_deleg_perm_avl_pool;
4028 };
4029 
4030 static inline const char *
4031 deleg_perm_type(zfs_deleg_note_t note)
4032 {
4033 	/* subcommands */
4034 	switch (note) {
4035 		/* SUBCOMMANDS */
4036 		/* OTHER */
4037 	case ZFS_DELEG_NOTE_GROUPQUOTA:
4038 	case ZFS_DELEG_NOTE_GROUPUSED:
4039 	case ZFS_DELEG_NOTE_USERPROP:
4040 	case ZFS_DELEG_NOTE_USERQUOTA:
4041 	case ZFS_DELEG_NOTE_USERUSED:
4042 		/* other */
4043 		return (gettext("other"));
4044 	default:
4045 		return (gettext("subcommand"));
4046 	}
4047 }
4048 
4049 static int inline
4050 who_type2weight(zfs_deleg_who_type_t who_type)
4051 {
4052 	int res;
4053 	switch (who_type) {
4054 		case ZFS_DELEG_NAMED_SET_SETS:
4055 		case ZFS_DELEG_NAMED_SET:
4056 			res = 0;
4057 			break;
4058 		case ZFS_DELEG_CREATE_SETS:
4059 		case ZFS_DELEG_CREATE:
4060 			res = 1;
4061 			break;
4062 		case ZFS_DELEG_USER_SETS:
4063 		case ZFS_DELEG_USER:
4064 			res = 2;
4065 			break;
4066 		case ZFS_DELEG_GROUP_SETS:
4067 		case ZFS_DELEG_GROUP:
4068 			res = 3;
4069 			break;
4070 		case ZFS_DELEG_EVERYONE_SETS:
4071 		case ZFS_DELEG_EVERYONE:
4072 			res = 4;
4073 			break;
4074 		default:
4075 			res = -1;
4076 	}
4077 
4078 	return (res);
4079 }
4080 
4081 /* ARGSUSED */
4082 static int
4083 who_perm_compare(const void *larg, const void *rarg, void *unused)
4084 {
4085 	const who_perm_node_t *l = larg;
4086 	const who_perm_node_t *r = rarg;
4087 	zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4088 	zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4089 	int lweight = who_type2weight(ltype);
4090 	int rweight = who_type2weight(rtype);
4091 	int res = lweight - rweight;
4092 	if (res == 0)
4093 		res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4094 		    ZFS_MAX_DELEG_NAME-1);
4095 
4096 	if (res == 0)
4097 		return (0);
4098 	if (res > 0)
4099 		return (1);
4100 	else
4101 		return (-1);
4102 }
4103 
4104 /* ARGSUSED */
4105 static int
4106 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4107 {
4108 	const deleg_perm_node_t *l = larg;
4109 	const deleg_perm_node_t *r = rarg;
4110 	int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4111 	    ZFS_MAX_DELEG_NAME-1);
4112 
4113 	if (res == 0)
4114 		return (0);
4115 
4116 	if (res > 0)
4117 		return (1);
4118 	else
4119 		return (-1);
4120 }
4121 
4122 static inline void
4123 fs_perm_set_init(fs_perm_set_t *fspset)
4124 {
4125 	bzero(fspset, sizeof (fs_perm_set_t));
4126 
4127 	if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4128 	    sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4129 	    NULL, UU_DEFAULT)) == NULL)
4130 		nomem();
4131 	if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4132 	    UU_DEFAULT)) == NULL)
4133 		nomem();
4134 
4135 	if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4136 	    "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4137 	    who_perm_node_t, who_avl_node), who_perm_compare,
4138 	    UU_DEFAULT)) == NULL)
4139 		nomem();
4140 
4141 	if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4142 	    "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4143 	    who_perm_node_t, who_avl_node), who_perm_compare,
4144 	    UU_DEFAULT)) == NULL)
4145 		nomem();
4146 
4147 	if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4148 	    "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4149 	    deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4150 	    == NULL)
4151 		nomem();
4152 }
4153 
4154 static inline void fs_perm_fini(fs_perm_t *);
4155 static inline void who_perm_fini(who_perm_t *);
4156 
4157 static inline void
4158 fs_perm_set_fini(fs_perm_set_t *fspset)
4159 {
4160 	fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4161 
4162 	while (node != NULL) {
4163 		fs_perm_node_t *next_node =
4164 		    uu_list_next(fspset->fsps_list, node);
4165 		fs_perm_t *fsperm = &node->fspn_fsperm;
4166 		fs_perm_fini(fsperm);
4167 		uu_list_remove(fspset->fsps_list, node);
4168 		free(node);
4169 		node = next_node;
4170 	}
4171 
4172 	uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4173 	uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4174 	uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4175 }
4176 
4177 static inline void
4178 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4179     const char *name)
4180 {
4181 	deleg_perm->dp_who_type = type;
4182 	deleg_perm->dp_name = name;
4183 }
4184 
4185 static inline void
4186 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4187     zfs_deleg_who_type_t type, const char *name)
4188 {
4189 	uu_avl_pool_t	*pool;
4190 	pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4191 
4192 	bzero(who_perm, sizeof (who_perm_t));
4193 
4194 	if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4195 	    UU_DEFAULT)) == NULL)
4196 		nomem();
4197 
4198 	who_perm->who_type = type;
4199 	who_perm->who_name = name;
4200 	who_perm->who_fsperm = fsperm;
4201 }
4202 
4203 static inline void
4204 who_perm_fini(who_perm_t *who_perm)
4205 {
4206 	deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4207 
4208 	while (node != NULL) {
4209 		deleg_perm_node_t *next_node =
4210 		    uu_avl_next(who_perm->who_deleg_perm_avl, node);
4211 
4212 		uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4213 		free(node);
4214 		node = next_node;
4215 	}
4216 
4217 	uu_avl_destroy(who_perm->who_deleg_perm_avl);
4218 }
4219 
4220 static inline void
4221 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4222 {
4223 	uu_avl_pool_t	*nset_pool = fspset->fsps_named_set_avl_pool;
4224 	uu_avl_pool_t	*who_pool = fspset->fsps_who_perm_avl_pool;
4225 
4226 	bzero(fsperm, sizeof (fs_perm_t));
4227 
4228 	if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4229 	    == NULL)
4230 		nomem();
4231 
4232 	if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4233 	    == NULL)
4234 		nomem();
4235 
4236 	fsperm->fsp_set = fspset;
4237 	fsperm->fsp_name = fsname;
4238 }
4239 
4240 static inline void
4241 fs_perm_fini(fs_perm_t *fsperm)
4242 {
4243 	who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4244 	while (node != NULL) {
4245 		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4246 		    node);
4247 		who_perm_t *who_perm = &node->who_perm;
4248 		who_perm_fini(who_perm);
4249 		uu_avl_remove(fsperm->fsp_sc_avl, node);
4250 		free(node);
4251 		node = next_node;
4252 	}
4253 
4254 	node = uu_avl_first(fsperm->fsp_uge_avl);
4255 	while (node != NULL) {
4256 		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4257 		    node);
4258 		who_perm_t *who_perm = &node->who_perm;
4259 		who_perm_fini(who_perm);
4260 		uu_avl_remove(fsperm->fsp_uge_avl, node);
4261 		free(node);
4262 		node = next_node;
4263 	}
4264 
4265 	uu_avl_destroy(fsperm->fsp_sc_avl);
4266 	uu_avl_destroy(fsperm->fsp_uge_avl);
4267 }
4268 
4269 static void inline
4270 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4271     zfs_deleg_who_type_t who_type, const char *name, char locality)
4272 {
4273 	uu_avl_index_t idx = 0;
4274 
4275 	deleg_perm_node_t *found_node = NULL;
4276 	deleg_perm_t	*deleg_perm = &node->dpn_perm;
4277 
4278 	deleg_perm_init(deleg_perm, who_type, name);
4279 
4280 	if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4281 	    == NULL)
4282 		uu_avl_insert(avl, node, idx);
4283 	else {
4284 		node = found_node;
4285 		deleg_perm = &node->dpn_perm;
4286 	}
4287 
4288 
4289 	switch (locality) {
4290 	case ZFS_DELEG_LOCAL:
4291 		deleg_perm->dp_local = B_TRUE;
4292 		break;
4293 	case ZFS_DELEG_DESCENDENT:
4294 		deleg_perm->dp_descend = B_TRUE;
4295 		break;
4296 	case ZFS_DELEG_NA:
4297 		break;
4298 	default:
4299 		assert(B_FALSE); /* invalid locality */
4300 	}
4301 }
4302 
4303 static inline int
4304 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4305 {
4306 	nvpair_t *nvp = NULL;
4307 	fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4308 	uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4309 	zfs_deleg_who_type_t who_type = who_perm->who_type;
4310 
4311 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4312 		const char *name = nvpair_name(nvp);
4313 		data_type_t type = nvpair_type(nvp);
4314 		uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4315 		deleg_perm_node_t *node =
4316 		    safe_malloc(sizeof (deleg_perm_node_t));
4317 
4318 		assert(type == DATA_TYPE_BOOLEAN);
4319 
4320 		uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4321 		set_deleg_perm_node(avl, node, who_type, name, locality);
4322 	}
4323 
4324 	return (0);
4325 }
4326 
4327 static inline int
4328 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4329 {
4330 	nvpair_t *nvp = NULL;
4331 	fs_perm_set_t *fspset = fsperm->fsp_set;
4332 
4333 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4334 		nvlist_t *nvl2 = NULL;
4335 		const char *name = nvpair_name(nvp);
4336 		uu_avl_t *avl = NULL;
4337 		uu_avl_pool_t *avl_pool;
4338 		zfs_deleg_who_type_t perm_type = name[0];
4339 		char perm_locality = name[1];
4340 		const char *perm_name = name + 3;
4341 		boolean_t is_set = B_TRUE;
4342 		who_perm_t *who_perm = NULL;
4343 
4344 		assert('$' == name[2]);
4345 
4346 		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4347 			return (-1);
4348 
4349 		switch (perm_type) {
4350 		case ZFS_DELEG_CREATE:
4351 		case ZFS_DELEG_CREATE_SETS:
4352 		case ZFS_DELEG_NAMED_SET:
4353 		case ZFS_DELEG_NAMED_SET_SETS:
4354 			avl_pool = fspset->fsps_named_set_avl_pool;
4355 			avl = fsperm->fsp_sc_avl;
4356 			break;
4357 		case ZFS_DELEG_USER:
4358 		case ZFS_DELEG_USER_SETS:
4359 		case ZFS_DELEG_GROUP:
4360 		case ZFS_DELEG_GROUP_SETS:
4361 		case ZFS_DELEG_EVERYONE:
4362 		case ZFS_DELEG_EVERYONE_SETS:
4363 			avl_pool = fspset->fsps_who_perm_avl_pool;
4364 			avl = fsperm->fsp_uge_avl;
4365 			break;
4366 		}
4367 
4368 		if (is_set) {
4369 			who_perm_node_t *found_node = NULL;
4370 			who_perm_node_t *node = safe_malloc(
4371 			    sizeof (who_perm_node_t));
4372 			who_perm = &node->who_perm;
4373 			uu_avl_index_t idx = 0;
4374 
4375 			uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4376 			who_perm_init(who_perm, fsperm, perm_type, perm_name);
4377 
4378 			if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4379 			    == NULL) {
4380 				if (avl == fsperm->fsp_uge_avl) {
4381 					uid_t rid = 0;
4382 					struct passwd *p = NULL;
4383 					struct group *g = NULL;
4384 					const char *nice_name = NULL;
4385 
4386 					switch (perm_type) {
4387 					case ZFS_DELEG_USER_SETS:
4388 					case ZFS_DELEG_USER:
4389 						rid = atoi(perm_name);
4390 						p = getpwuid(rid);
4391 						if (p)
4392 							nice_name = p->pw_name;
4393 						break;
4394 					case ZFS_DELEG_GROUP_SETS:
4395 					case ZFS_DELEG_GROUP:
4396 						rid = atoi(perm_name);
4397 						g = getgrgid(rid);
4398 						if (g)
4399 							nice_name = g->gr_name;
4400 						break;
4401 					}
4402 
4403 					if (nice_name != NULL)
4404 						(void) strlcpy(
4405 						    node->who_perm.who_ug_name,
4406 						    nice_name, 256);
4407 				}
4408 
4409 				uu_avl_insert(avl, node, idx);
4410 			} else {
4411 				node = found_node;
4412 				who_perm = &node->who_perm;
4413 			}
4414 		}
4415 
4416 		(void) parse_who_perm(who_perm, nvl2, perm_locality);
4417 	}
4418 
4419 	return (0);
4420 }
4421 
4422 static inline int
4423 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4424 {
4425 	nvpair_t *nvp = NULL;
4426 	uu_avl_index_t idx = 0;
4427 
4428 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4429 		nvlist_t *nvl2 = NULL;
4430 		const char *fsname = nvpair_name(nvp);
4431 		data_type_t type = nvpair_type(nvp);
4432 		fs_perm_t *fsperm = NULL;
4433 		fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4434 		if (node == NULL)
4435 			nomem();
4436 
4437 		fsperm = &node->fspn_fsperm;
4438 
4439 		assert(DATA_TYPE_NVLIST == type);
4440 
4441 		uu_list_node_init(node, &node->fspn_list_node,
4442 		    fspset->fsps_list_pool);
4443 
4444 		idx = uu_list_numnodes(fspset->fsps_list);
4445 		fs_perm_init(fsperm, fspset, fsname);
4446 
4447 		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4448 			return (-1);
4449 
4450 		(void) parse_fs_perm(fsperm, nvl2);
4451 
4452 		uu_list_insert(fspset->fsps_list, node, idx);
4453 	}
4454 
4455 	return (0);
4456 }
4457 
4458 static inline const char *
4459 deleg_perm_comment(zfs_deleg_note_t note)
4460 {
4461 	const char *str = "";
4462 
4463 	/* subcommands */
4464 	switch (note) {
4465 		/* SUBCOMMANDS */
4466 	case ZFS_DELEG_NOTE_ALLOW:
4467 		str = gettext("Must also have the permission that is being"
4468 		    "\n\t\t\t\tallowed");
4469 		break;
4470 	case ZFS_DELEG_NOTE_CLONE:
4471 		str = gettext("Must also have the 'create' ability and 'mount'"
4472 		    "\n\t\t\t\tability in the origin file system");
4473 		break;
4474 	case ZFS_DELEG_NOTE_CREATE:
4475 		str = gettext("Must also have the 'mount' ability");
4476 		break;
4477 	case ZFS_DELEG_NOTE_DESTROY:
4478 		str = gettext("Must also have the 'mount' ability");
4479 		break;
4480 	case ZFS_DELEG_NOTE_DIFF:
4481 		str = gettext("Allows lookup of paths within a dataset;"
4482 		    "\n\t\t\t\tgiven an object number. Ordinary users need this"
4483 		    "\n\t\t\t\tin order to use zfs diff");
4484 		break;
4485 	case ZFS_DELEG_NOTE_HOLD:
4486 		str = gettext("Allows adding a user hold to a snapshot");
4487 		break;
4488 	case ZFS_DELEG_NOTE_MOUNT:
4489 		str = gettext("Allows mount/umount of ZFS datasets");
4490 		break;
4491 	case ZFS_DELEG_NOTE_PROMOTE:
4492 		str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4493 		    " 'promote' ability in the origin file system");
4494 		break;
4495 	case ZFS_DELEG_NOTE_RECEIVE:
4496 		str = gettext("Must also have the 'mount' and 'create'"
4497 		    " ability");
4498 		break;
4499 	case ZFS_DELEG_NOTE_RELEASE:
4500 		str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4501 		    "might destroy the snapshot");
4502 		break;
4503 	case ZFS_DELEG_NOTE_RENAME:
4504 		str = gettext("Must also have the 'mount' and 'create'"
4505 		    "\n\t\t\t\tability in the new parent");
4506 		break;
4507 	case ZFS_DELEG_NOTE_ROLLBACK:
4508 		str = gettext("");
4509 		break;
4510 	case ZFS_DELEG_NOTE_SEND:
4511 		str = gettext("");
4512 		break;
4513 	case ZFS_DELEG_NOTE_SHARE:
4514 		str = gettext("Allows sharing file systems over NFS or SMB"
4515 		    "\n\t\t\t\tprotocols");
4516 		break;
4517 	case ZFS_DELEG_NOTE_SNAPSHOT:
4518 		str = gettext("");
4519 		break;
4520 /*
4521  *	case ZFS_DELEG_NOTE_VSCAN:
4522  *		str = gettext("");
4523  *		break;
4524  */
4525 		/* OTHER */
4526 	case ZFS_DELEG_NOTE_GROUPQUOTA:
4527 		str = gettext("Allows accessing any groupquota@... property");
4528 		break;
4529 	case ZFS_DELEG_NOTE_GROUPUSED:
4530 		str = gettext("Allows reading any groupused@... property");
4531 		break;
4532 	case ZFS_DELEG_NOTE_USERPROP:
4533 		str = gettext("Allows changing any user property");
4534 		break;
4535 	case ZFS_DELEG_NOTE_USERQUOTA:
4536 		str = gettext("Allows accessing any userquota@... property");
4537 		break;
4538 	case ZFS_DELEG_NOTE_USERUSED:
4539 		str = gettext("Allows reading any userused@... property");
4540 		break;
4541 		/* other */
4542 	default:
4543 		str = "";
4544 	}
4545 
4546 	return (str);
4547 }
4548 
4549 struct allow_opts {
4550 	boolean_t local;
4551 	boolean_t descend;
4552 	boolean_t user;
4553 	boolean_t group;
4554 	boolean_t everyone;
4555 	boolean_t create;
4556 	boolean_t set;
4557 	boolean_t recursive; /* unallow only */
4558 	boolean_t prt_usage;
4559 
4560 	boolean_t prt_perms;
4561 	char *who;
4562 	char *perms;
4563 	const char *dataset;
4564 };
4565 
4566 static inline int
4567 prop_cmp(const void *a, const void *b)
4568 {
4569 	const char *str1 = *(const char **)a;
4570 	const char *str2 = *(const char **)b;
4571 	return (strcmp(str1, str2));
4572 }
4573 
4574 static void
4575 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4576 {
4577 	const char *opt_desc[] = {
4578 		"-h", gettext("show this help message and exit"),
4579 		"-l", gettext("set permission locally"),
4580 		"-d", gettext("set permission for descents"),
4581 		"-u", gettext("set permission for user"),
4582 		"-g", gettext("set permission for group"),
4583 		"-e", gettext("set permission for everyone"),
4584 		"-c", gettext("set create time permission"),
4585 		"-s", gettext("define permission set"),
4586 		/* unallow only */
4587 		"-r", gettext("remove permissions recursively"),
4588 	};
4589 	size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4590 	size_t allow_size = unallow_size - 2;
4591 	const char *props[ZFS_NUM_PROPS];
4592 	int i;
4593 	size_t count = 0;
4594 	FILE *fp = requested ? stdout : stderr;
4595 	zprop_desc_t *pdtbl = zfs_prop_get_table();
4596 	const char *fmt = gettext("%-16s %-14s\t%s\n");
4597 
4598 	(void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4599 	    HELP_ALLOW));
4600 	(void) fprintf(fp, gettext("Options:\n"));
4601 	for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4602 		const char *opt = opt_desc[i++];
4603 		const char *optdsc = opt_desc[i];
4604 		(void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
4605 	}
4606 
4607 	(void) fprintf(fp, gettext("\nThe following permissions are "
4608 	    "supported:\n\n"));
4609 	(void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4610 	    gettext("NOTES"));
4611 	for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4612 		const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4613 		zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4614 		const char *perm_type = deleg_perm_type(perm_note);
4615 		const char *perm_comment = deleg_perm_comment(perm_note);
4616 		(void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4617 	}
4618 
4619 	for (i = 0; i < ZFS_NUM_PROPS; i++) {
4620 		zprop_desc_t *pd = &pdtbl[i];
4621 		if (pd->pd_visible != B_TRUE)
4622 			continue;
4623 
4624 		if (pd->pd_attr == PROP_READONLY)
4625 			continue;
4626 
4627 		props[count++] = pd->pd_name;
4628 	}
4629 	props[count] = NULL;
4630 
4631 	qsort(props, count, sizeof (char *), prop_cmp);
4632 
4633 	for (i = 0; i < count; i++)
4634 		(void) fprintf(fp, fmt, props[i], gettext("property"), "");
4635 
4636 	if (msg != NULL)
4637 		(void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4638 
4639 	exit(requested ? 0 : 2);
4640 }
4641 
4642 static inline const char *
4643 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4644     char **permsp)
4645 {
4646 	if (un && argc == expected_argc - 1)
4647 		*permsp = NULL;
4648 	else if (argc == expected_argc)
4649 		*permsp = argv[argc - 2];
4650 	else
4651 		allow_usage(un, B_FALSE,
4652 		    gettext("wrong number of parameters\n"));
4653 
4654 	return (argv[argc - 1]);
4655 }
4656 
4657 static void
4658 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4659 {
4660 	int uge_sum = opts->user + opts->group + opts->everyone;
4661 	int csuge_sum = opts->create + opts->set + uge_sum;
4662 	int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4663 	int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4664 
4665 	if (uge_sum > 1)
4666 		allow_usage(un, B_FALSE,
4667 		    gettext("-u, -g, and -e are mutually exclusive\n"));
4668 
4669 	if (opts->prt_usage)
4670 		if (argc == 0 && all_sum == 0)
4671 			allow_usage(un, B_TRUE, NULL);
4672 		else
4673 			usage(B_FALSE);
4674 
4675 	if (opts->set) {
4676 		if (csuge_sum > 1)
4677 			allow_usage(un, B_FALSE,
4678 			    gettext("invalid options combined with -s\n"));
4679 
4680 		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4681 		if (argv[0][0] != '@')
4682 			allow_usage(un, B_FALSE,
4683 			    gettext("invalid set name: missing '@' prefix\n"));
4684 		opts->who = argv[0];
4685 	} else if (opts->create) {
4686 		if (ldcsuge_sum > 1)
4687 			allow_usage(un, B_FALSE,
4688 			    gettext("invalid options combined with -c\n"));
4689 		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4690 	} else if (opts->everyone) {
4691 		if (csuge_sum > 1)
4692 			allow_usage(un, B_FALSE,
4693 			    gettext("invalid options combined with -e\n"));
4694 		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4695 	} else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4696 	    == 0) {
4697 		opts->everyone = B_TRUE;
4698 		argc--;
4699 		argv++;
4700 		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4701 	} else if (argc == 1 && !un) {
4702 		opts->prt_perms = B_TRUE;
4703 		opts->dataset = argv[argc-1];
4704 	} else {
4705 		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4706 		opts->who = argv[0];
4707 	}
4708 
4709 	if (!opts->local && !opts->descend) {
4710 		opts->local = B_TRUE;
4711 		opts->descend = B_TRUE;
4712 	}
4713 }
4714 
4715 static void
4716 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4717     const char *who, char *perms, nvlist_t *top_nvl)
4718 {
4719 	int i;
4720 	char ld[2] = { '\0', '\0' };
4721 	char who_buf[ZFS_MAXNAMELEN+32];
4722 	char base_type;
4723 	char set_type;
4724 	nvlist_t *base_nvl = NULL;
4725 	nvlist_t *set_nvl = NULL;
4726 	nvlist_t *nvl;
4727 
4728 	if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4729 		nomem();
4730 	if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
4731 		nomem();
4732 
4733 	switch (type) {
4734 	case ZFS_DELEG_NAMED_SET_SETS:
4735 	case ZFS_DELEG_NAMED_SET:
4736 		set_type = ZFS_DELEG_NAMED_SET_SETS;
4737 		base_type = ZFS_DELEG_NAMED_SET;
4738 		ld[0] = ZFS_DELEG_NA;
4739 		break;
4740 	case ZFS_DELEG_CREATE_SETS:
4741 	case ZFS_DELEG_CREATE:
4742 		set_type = ZFS_DELEG_CREATE_SETS;
4743 		base_type = ZFS_DELEG_CREATE;
4744 		ld[0] = ZFS_DELEG_NA;
4745 		break;
4746 	case ZFS_DELEG_USER_SETS:
4747 	case ZFS_DELEG_USER:
4748 		set_type = ZFS_DELEG_USER_SETS;
4749 		base_type = ZFS_DELEG_USER;
4750 		if (local)
4751 			ld[0] = ZFS_DELEG_LOCAL;
4752 		if (descend)
4753 			ld[1] = ZFS_DELEG_DESCENDENT;
4754 		break;
4755 	case ZFS_DELEG_GROUP_SETS:
4756 	case ZFS_DELEG_GROUP:
4757 		set_type = ZFS_DELEG_GROUP_SETS;
4758 		base_type = ZFS_DELEG_GROUP;
4759 		if (local)
4760 			ld[0] = ZFS_DELEG_LOCAL;
4761 		if (descend)
4762 			ld[1] = ZFS_DELEG_DESCENDENT;
4763 		break;
4764 	case ZFS_DELEG_EVERYONE_SETS:
4765 	case ZFS_DELEG_EVERYONE:
4766 		set_type = ZFS_DELEG_EVERYONE_SETS;
4767 		base_type = ZFS_DELEG_EVERYONE;
4768 		if (local)
4769 			ld[0] = ZFS_DELEG_LOCAL;
4770 		if (descend)
4771 			ld[1] = ZFS_DELEG_DESCENDENT;
4772 	}
4773 
4774 	if (perms != NULL) {
4775 		char *curr = perms;
4776 		char *end = curr + strlen(perms);
4777 
4778 		while (curr < end) {
4779 			char *delim = strchr(curr, ',');
4780 			if (delim == NULL)
4781 				delim = end;
4782 			else
4783 				*delim = '\0';
4784 
4785 			if (curr[0] == '@')
4786 				nvl = set_nvl;
4787 			else
4788 				nvl = base_nvl;
4789 
4790 			(void) nvlist_add_boolean(nvl, curr);
4791 			if (delim != end)
4792 				*delim = ',';
4793 			curr = delim + 1;
4794 		}
4795 
4796 		for (i = 0; i < 2; i++) {
4797 			char locality = ld[i];
4798 			if (locality == 0)
4799 				continue;
4800 
4801 			if (!nvlist_empty(base_nvl)) {
4802 				if (who != NULL)
4803 					(void) snprintf(who_buf,
4804 					    sizeof (who_buf), "%c%c$%s",
4805 					    base_type, locality, who);
4806 				else
4807 					(void) snprintf(who_buf,
4808 					    sizeof (who_buf), "%c%c$",
4809 					    base_type, locality);
4810 
4811 				(void) nvlist_add_nvlist(top_nvl, who_buf,
4812 				    base_nvl);
4813 			}
4814 
4815 
4816 			if (!nvlist_empty(set_nvl)) {
4817 				if (who != NULL)
4818 					(void) snprintf(who_buf,
4819 					    sizeof (who_buf), "%c%c$%s",
4820 					    set_type, locality, who);
4821 				else
4822 					(void) snprintf(who_buf,
4823 					    sizeof (who_buf), "%c%c$",
4824 					    set_type, locality);
4825 
4826 				(void) nvlist_add_nvlist(top_nvl, who_buf,
4827 				    set_nvl);
4828 			}
4829 		}
4830 	} else {
4831 		for (i = 0; i < 2; i++) {
4832 			char locality = ld[i];
4833 			if (locality == 0)
4834 				continue;
4835 
4836 			if (who != NULL)
4837 				(void) snprintf(who_buf, sizeof (who_buf),
4838 				    "%c%c$%s", base_type, locality, who);
4839 			else
4840 				(void) snprintf(who_buf, sizeof (who_buf),
4841 				    "%c%c$", base_type, locality);
4842 			(void) nvlist_add_boolean(top_nvl, who_buf);
4843 
4844 			if (who != NULL)
4845 				(void) snprintf(who_buf, sizeof (who_buf),
4846 				    "%c%c$%s", set_type, locality, who);
4847 			else
4848 				(void) snprintf(who_buf, sizeof (who_buf),
4849 				    "%c%c$", set_type, locality);
4850 			(void) nvlist_add_boolean(top_nvl, who_buf);
4851 		}
4852 	}
4853 }
4854 
4855 static int
4856 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4857 {
4858 	if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4859 		nomem();
4860 
4861 	if (opts->set) {
4862 		store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4863 		    opts->descend, opts->who, opts->perms, *nvlp);
4864 	} else if (opts->create) {
4865 		store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4866 		    opts->descend, NULL, opts->perms, *nvlp);
4867 	} else if (opts->everyone) {
4868 		store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4869 		    opts->descend, NULL, opts->perms, *nvlp);
4870 	} else {
4871 		char *curr = opts->who;
4872 		char *end = curr + strlen(curr);
4873 
4874 		while (curr < end) {
4875 			const char *who;
4876 			zfs_deleg_who_type_t who_type;
4877 			char *endch;
4878 			char *delim = strchr(curr, ',');
4879 			char errbuf[256];
4880 			char id[64];
4881 			struct passwd *p = NULL;
4882 			struct group *g = NULL;
4883 
4884 			uid_t rid;
4885 			if (delim == NULL)
4886 				delim = end;
4887 			else
4888 				*delim = '\0';
4889 
4890 			rid = (uid_t)strtol(curr, &endch, 0);
4891 			if (opts->user) {
4892 				who_type = ZFS_DELEG_USER;
4893 				if (*endch != '\0')
4894 					p = getpwnam(curr);
4895 				else
4896 					p = getpwuid(rid);
4897 
4898 				if (p != NULL)
4899 					rid = p->pw_uid;
4900 				else {
4901 					(void) snprintf(errbuf, 256, gettext(
4902 					    "invalid user %s"), curr);
4903 					allow_usage(un, B_TRUE, errbuf);
4904 				}
4905 			} else if (opts->group) {
4906 				who_type = ZFS_DELEG_GROUP;
4907 				if (*endch != '\0')
4908 					g = getgrnam(curr);
4909 				else
4910 					g = getgrgid(rid);
4911 
4912 				if (g != NULL)
4913 					rid = g->gr_gid;
4914 				else {
4915 					(void) snprintf(errbuf, 256, gettext(
4916 					    "invalid group %s"),  curr);
4917 					allow_usage(un, B_TRUE, errbuf);
4918 				}
4919 			} else {
4920 				if (*endch != '\0') {
4921 					p = getpwnam(curr);
4922 				} else {
4923 					p = getpwuid(rid);
4924 				}
4925 
4926 				if (p == NULL)
4927 					if (*endch != '\0') {
4928 						g = getgrnam(curr);
4929 					} else {
4930 						g = getgrgid(rid);
4931 					}
4932 
4933 				if (p != NULL) {
4934 					who_type = ZFS_DELEG_USER;
4935 					rid = p->pw_uid;
4936 				} else if (g != NULL) {
4937 					who_type = ZFS_DELEG_GROUP;
4938 					rid = g->gr_gid;
4939 				} else {
4940 					(void) snprintf(errbuf, 256, gettext(
4941 					    "invalid user/group %s"), curr);
4942 					allow_usage(un, B_TRUE, errbuf);
4943 				}
4944 			}
4945 
4946 			(void) sprintf(id, "%u", rid);
4947 			who = id;
4948 
4949 			store_allow_perm(who_type, opts->local,
4950 			    opts->descend, who, opts->perms, *nvlp);
4951 			curr = delim + 1;
4952 		}
4953 	}
4954 
4955 	return (0);
4956 }
4957 
4958 static void
4959 print_set_creat_perms(uu_avl_t *who_avl)
4960 {
4961 	const char *sc_title[] = {
4962 		gettext("Permission sets:\n"),
4963 		gettext("Create time permissions:\n"),
4964 		NULL
4965 	};
4966 	const char **title_ptr = sc_title;
4967 	who_perm_node_t *who_node = NULL;
4968 	int prev_weight = -1;
4969 
4970 	for (who_node = uu_avl_first(who_avl); who_node != NULL;
4971 	    who_node = uu_avl_next(who_avl, who_node)) {
4972 		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4973 		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4974 		const char *who_name = who_node->who_perm.who_name;
4975 		int weight = who_type2weight(who_type);
4976 		boolean_t first = B_TRUE;
4977 		deleg_perm_node_t *deleg_node;
4978 
4979 		if (prev_weight != weight) {
4980 			(void) printf(*title_ptr++);
4981 			prev_weight = weight;
4982 		}
4983 
4984 		if (who_name == NULL || strnlen(who_name, 1) == 0)
4985 			(void) printf("\t");
4986 		else
4987 			(void) printf("\t%s ", who_name);
4988 
4989 		for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
4990 		    deleg_node = uu_avl_next(avl, deleg_node)) {
4991 			if (first) {
4992 				(void) printf("%s",
4993 				    deleg_node->dpn_perm.dp_name);
4994 				first = B_FALSE;
4995 			} else
4996 				(void) printf(",%s",
4997 				    deleg_node->dpn_perm.dp_name);
4998 		}
4999 
5000 		(void) printf("\n");
5001 	}
5002 }
5003 
5004 static void inline
5005 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5006     const char *title)
5007 {
5008 	who_perm_node_t *who_node = NULL;
5009 	boolean_t prt_title = B_TRUE;
5010 	uu_avl_walk_t *walk;
5011 
5012 	if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5013 		nomem();
5014 
5015 	while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5016 		const char *who_name = who_node->who_perm.who_name;
5017 		const char *nice_who_name = who_node->who_perm.who_ug_name;
5018 		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5019 		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5020 		char delim = ' ';
5021 		deleg_perm_node_t *deleg_node;
5022 		boolean_t prt_who = B_TRUE;
5023 
5024 		for (deleg_node = uu_avl_first(avl);
5025 		    deleg_node != NULL;
5026 		    deleg_node = uu_avl_next(avl, deleg_node)) {
5027 			if (local != deleg_node->dpn_perm.dp_local ||
5028 			    descend != deleg_node->dpn_perm.dp_descend)
5029 				continue;
5030 
5031 			if (prt_who) {
5032 				const char *who = NULL;
5033 				if (prt_title) {
5034 					prt_title = B_FALSE;
5035 					(void) printf(title);
5036 				}
5037 
5038 				switch (who_type) {
5039 				case ZFS_DELEG_USER_SETS:
5040 				case ZFS_DELEG_USER:
5041 					who = gettext("user");
5042 					if (nice_who_name)
5043 						who_name  = nice_who_name;
5044 					break;
5045 				case ZFS_DELEG_GROUP_SETS:
5046 				case ZFS_DELEG_GROUP:
5047 					who = gettext("group");
5048 					if (nice_who_name)
5049 						who_name  = nice_who_name;
5050 					break;
5051 				case ZFS_DELEG_EVERYONE_SETS:
5052 				case ZFS_DELEG_EVERYONE:
5053 					who = gettext("everyone");
5054 					who_name = NULL;
5055 				}
5056 
5057 				prt_who = B_FALSE;
5058 				if (who_name == NULL)
5059 					(void) printf("\t%s", who);
5060 				else
5061 					(void) printf("\t%s %s", who, who_name);
5062 			}
5063 
5064 			(void) printf("%c%s", delim,
5065 			    deleg_node->dpn_perm.dp_name);
5066 			delim = ',';
5067 		}
5068 
5069 		if (!prt_who)
5070 			(void) printf("\n");
5071 	}
5072 
5073 	uu_avl_walk_end(walk);
5074 }
5075 
5076 static void
5077 print_fs_perms(fs_perm_set_t *fspset)
5078 {
5079 	fs_perm_node_t *node = NULL;
5080 	char buf[ZFS_MAXNAMELEN+32];
5081 	const char *dsname = buf;
5082 
5083 	for (node = uu_list_first(fspset->fsps_list); node != NULL;
5084 	    node = uu_list_next(fspset->fsps_list, node)) {
5085 		uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5086 		uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5087 		int left = 0;
5088 
5089 		(void) snprintf(buf, ZFS_MAXNAMELEN+32,
5090 		    gettext("---- Permissions on %s "),
5091 		    node->fspn_fsperm.fsp_name);
5092 		(void) printf(dsname);
5093 		left = 70 - strlen(buf);
5094 		while (left-- > 0)
5095 			(void) printf("-");
5096 		(void) printf("\n");
5097 
5098 		print_set_creat_perms(sc_avl);
5099 		print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5100 		    gettext("Local permissions:\n"));
5101 		print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5102 		    gettext("Descendent permissions:\n"));
5103 		print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5104 		    gettext("Local+Descendent permissions:\n"));
5105 	}
5106 }
5107 
5108 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5109 
5110 struct deleg_perms {
5111 	boolean_t un;
5112 	nvlist_t *nvl;
5113 };
5114 
5115 static int
5116 set_deleg_perms(zfs_handle_t *zhp, void *data)
5117 {
5118 	struct deleg_perms *perms = (struct deleg_perms *)data;
5119 	zfs_type_t zfs_type = zfs_get_type(zhp);
5120 
5121 	if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5122 		return (0);
5123 
5124 	return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5125 }
5126 
5127 static int
5128 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5129 {
5130 	zfs_handle_t *zhp;
5131 	nvlist_t *perm_nvl = NULL;
5132 	nvlist_t *update_perm_nvl = NULL;
5133 	int error = 1;
5134 	int c;
5135 	struct allow_opts opts = { 0 };
5136 
5137 	const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5138 
5139 	/* check opts */
5140 	while ((c = getopt(argc, argv, optstr)) != -1) {
5141 		switch (c) {
5142 		case 'l':
5143 			opts.local = B_TRUE;
5144 			break;
5145 		case 'd':
5146 			opts.descend = B_TRUE;
5147 			break;
5148 		case 'u':
5149 			opts.user = B_TRUE;
5150 			break;
5151 		case 'g':
5152 			opts.group = B_TRUE;
5153 			break;
5154 		case 'e':
5155 			opts.everyone = B_TRUE;
5156 			break;
5157 		case 's':
5158 			opts.set = B_TRUE;
5159 			break;
5160 		case 'c':
5161 			opts.create = B_TRUE;
5162 			break;
5163 		case 'r':
5164 			opts.recursive = B_TRUE;
5165 			break;
5166 		case ':':
5167 			(void) fprintf(stderr, gettext("missing argument for "
5168 			    "'%c' option\n"), optopt);
5169 			usage(B_FALSE);
5170 			break;
5171 		case 'h':
5172 			opts.prt_usage = B_TRUE;
5173 			break;
5174 		case '?':
5175 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5176 			    optopt);
5177 			usage(B_FALSE);
5178 		}
5179 	}
5180 
5181 	argc -= optind;
5182 	argv += optind;
5183 
5184 	/* check arguments */
5185 	parse_allow_args(argc, argv, un, &opts);
5186 
5187 	/* try to open the dataset */
5188 	if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5189 	    ZFS_TYPE_VOLUME)) == NULL) {
5190 		(void) fprintf(stderr, "Failed to open dataset: %s\n",
5191 		    opts.dataset);
5192 		return (-1);
5193 	}
5194 
5195 	if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5196 		goto cleanup2;
5197 
5198 	fs_perm_set_init(&fs_perm_set);
5199 	if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5200 		(void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5201 		goto cleanup1;
5202 	}
5203 
5204 	if (opts.prt_perms)
5205 		print_fs_perms(&fs_perm_set);
5206 	else {
5207 		(void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5208 		if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5209 			goto cleanup0;
5210 
5211 		if (un && opts.recursive) {
5212 			struct deleg_perms data = { un, update_perm_nvl };
5213 			if (zfs_iter_filesystems(zhp, set_deleg_perms,
5214 			    &data) != 0)
5215 				goto cleanup0;
5216 		}
5217 	}
5218 
5219 	error = 0;
5220 
5221 cleanup0:
5222 	nvlist_free(perm_nvl);
5223 	if (update_perm_nvl != NULL)
5224 		nvlist_free(update_perm_nvl);
5225 cleanup1:
5226 	fs_perm_set_fini(&fs_perm_set);
5227 cleanup2:
5228 	zfs_close(zhp);
5229 
5230 	return (error);
5231 }
5232 
5233 static int
5234 zfs_do_allow(int argc, char **argv)
5235 {
5236 	return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5237 }
5238 
5239 static int
5240 zfs_do_unallow(int argc, char **argv)
5241 {
5242 	return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5243 }
5244 
5245 static int
5246 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5247 {
5248 	int errors = 0;
5249 	int i;
5250 	const char *tag;
5251 	boolean_t recursive = B_FALSE;
5252 	const char *opts = holding ? "rt" : "r";
5253 	int c;
5254 
5255 	/* check options */
5256 	while ((c = getopt(argc, argv, opts)) != -1) {
5257 		switch (c) {
5258 		case 'r':
5259 			recursive = B_TRUE;
5260 			break;
5261 		case '?':
5262 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5263 			    optopt);
5264 			usage(B_FALSE);
5265 		}
5266 	}
5267 
5268 	argc -= optind;
5269 	argv += optind;
5270 
5271 	/* check number of arguments */
5272 	if (argc < 2)
5273 		usage(B_FALSE);
5274 
5275 	tag = argv[0];
5276 	--argc;
5277 	++argv;
5278 
5279 	if (holding && tag[0] == '.') {
5280 		/* tags starting with '.' are reserved for libzfs */
5281 		(void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5282 		usage(B_FALSE);
5283 	}
5284 
5285 	for (i = 0; i < argc; ++i) {
5286 		zfs_handle_t *zhp;
5287 		char parent[ZFS_MAXNAMELEN];
5288 		const char *delim;
5289 		char *path = argv[i];
5290 
5291 		delim = strchr(path, '@');
5292 		if (delim == NULL) {
5293 			(void) fprintf(stderr,
5294 			    gettext("'%s' is not a snapshot\n"), path);
5295 			++errors;
5296 			continue;
5297 		}
5298 		(void) strncpy(parent, path, delim - path);
5299 		parent[delim - path] = '\0';
5300 
5301 		zhp = zfs_open(g_zfs, parent,
5302 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5303 		if (zhp == NULL) {
5304 			++errors;
5305 			continue;
5306 		}
5307 		if (holding) {
5308 			if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5309 				++errors;
5310 		} else {
5311 			if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5312 				++errors;
5313 		}
5314 		zfs_close(zhp);
5315 	}
5316 
5317 	return (errors != 0);
5318 }
5319 
5320 /*
5321  * zfs hold [-r] [-t] <tag> <snap> ...
5322  *
5323  *	-r	Recursively hold
5324  *
5325  * Apply a user-hold with the given tag to the list of snapshots.
5326  */
5327 static int
5328 zfs_do_hold(int argc, char **argv)
5329 {
5330 	return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5331 }
5332 
5333 /*
5334  * zfs release [-r] <tag> <snap> ...
5335  *
5336  *	-r	Recursively release
5337  *
5338  * Release a user-hold with the given tag from the list of snapshots.
5339  */
5340 static int
5341 zfs_do_release(int argc, char **argv)
5342 {
5343 	return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5344 }
5345 
5346 typedef struct holds_cbdata {
5347 	boolean_t	cb_recursive;
5348 	const char	*cb_snapname;
5349 	nvlist_t	**cb_nvlp;
5350 	size_t		cb_max_namelen;
5351 	size_t		cb_max_taglen;
5352 } holds_cbdata_t;
5353 
5354 #define	STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5355 #define	DATETIME_BUF_LEN (32)
5356 /*
5357  *
5358  */
5359 static void
5360 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5361 {
5362 	int i;
5363 	nvpair_t *nvp = NULL;
5364 	char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5365 	const char *col;
5366 
5367 	if (!scripted) {
5368 		for (i = 0; i < 3; i++) {
5369 			col = gettext(hdr_cols[i]);
5370 			if (i < 2)
5371 				(void) printf("%-*s  ", i ? tagwidth : nwidth,
5372 				    col);
5373 			else
5374 				(void) printf("%s\n", col);
5375 		}
5376 	}
5377 
5378 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5379 		char *zname = nvpair_name(nvp);
5380 		nvlist_t *nvl2;
5381 		nvpair_t *nvp2 = NULL;
5382 		(void) nvpair_value_nvlist(nvp, &nvl2);
5383 		while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5384 			char tsbuf[DATETIME_BUF_LEN];
5385 			char *tagname = nvpair_name(nvp2);
5386 			uint64_t val = 0;
5387 			time_t time;
5388 			struct tm t;
5389 			char sep = scripted ? '\t' : ' ';
5390 			size_t sepnum = scripted ? 1 : 2;
5391 
5392 			(void) nvpair_value_uint64(nvp2, &val);
5393 			time = (time_t)val;
5394 			(void) localtime_r(&time, &t);
5395 			(void) strftime(tsbuf, DATETIME_BUF_LEN,
5396 			    gettext(STRFTIME_FMT_STR), &t);
5397 
5398 			(void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5399 			    sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5400 		}
5401 	}
5402 }
5403 
5404 /*
5405  * Generic callback function to list a dataset or snapshot.
5406  */
5407 static int
5408 holds_callback(zfs_handle_t *zhp, void *data)
5409 {
5410 	holds_cbdata_t *cbp = data;
5411 	nvlist_t *top_nvl = *cbp->cb_nvlp;
5412 	nvlist_t *nvl = NULL;
5413 	nvpair_t *nvp = NULL;
5414 	const char *zname = zfs_get_name(zhp);
5415 	size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5416 
5417 	if (cbp->cb_recursive) {
5418 		const char *snapname;
5419 		char *delim  = strchr(zname, '@');
5420 		if (delim == NULL)
5421 			return (0);
5422 
5423 		snapname = delim + 1;
5424 		if (strcmp(cbp->cb_snapname, snapname))
5425 			return (0);
5426 	}
5427 
5428 	if (zfs_get_holds(zhp, &nvl) != 0)
5429 		return (-1);
5430 
5431 	if (znamelen > cbp->cb_max_namelen)
5432 		cbp->cb_max_namelen  = znamelen;
5433 
5434 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5435 		const char *tag = nvpair_name(nvp);
5436 		size_t taglen = strnlen(tag, MAXNAMELEN);
5437 		if (taglen > cbp->cb_max_taglen)
5438 			cbp->cb_max_taglen  = taglen;
5439 	}
5440 
5441 	return (nvlist_add_nvlist(top_nvl, zname, nvl));
5442 }
5443 
5444 /*
5445  * zfs holds [-r] <snap> ...
5446  *
5447  *	-r	Recursively hold
5448  */
5449 static int
5450 zfs_do_holds(int argc, char **argv)
5451 {
5452 	int errors = 0;
5453 	int c;
5454 	int i;
5455 	boolean_t scripted = B_FALSE;
5456 	boolean_t recursive = B_FALSE;
5457 	const char *opts = "rH";
5458 	nvlist_t *nvl;
5459 
5460 	int types = ZFS_TYPE_SNAPSHOT;
5461 	holds_cbdata_t cb = { 0 };
5462 
5463 	int limit = 0;
5464 	int ret = 0;
5465 	int flags = 0;
5466 
5467 	/* check options */
5468 	while ((c = getopt(argc, argv, opts)) != -1) {
5469 		switch (c) {
5470 		case 'r':
5471 			recursive = B_TRUE;
5472 			break;
5473 		case 'H':
5474 			scripted = B_TRUE;
5475 			break;
5476 		case '?':
5477 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5478 			    optopt);
5479 			usage(B_FALSE);
5480 		}
5481 	}
5482 
5483 	if (recursive) {
5484 		types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5485 		flags |= ZFS_ITER_RECURSE;
5486 	}
5487 
5488 	argc -= optind;
5489 	argv += optind;
5490 
5491 	/* check number of arguments */
5492 	if (argc < 1)
5493 		usage(B_FALSE);
5494 
5495 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5496 		nomem();
5497 
5498 	for (i = 0; i < argc; ++i) {
5499 		char *snapshot = argv[i];
5500 		const char *delim;
5501 		const char *snapname;
5502 
5503 		delim = strchr(snapshot, '@');
5504 		if (delim == NULL) {
5505 			(void) fprintf(stderr,
5506 			    gettext("'%s' is not a snapshot\n"), snapshot);
5507 			++errors;
5508 			continue;
5509 		}
5510 		snapname = delim + 1;
5511 		if (recursive)
5512 			snapshot[delim - snapshot] = '\0';
5513 
5514 		cb.cb_recursive = recursive;
5515 		cb.cb_snapname = snapname;
5516 		cb.cb_nvlp = &nvl;
5517 
5518 		/*
5519 		 *  1. collect holds data, set format options
5520 		 */
5521 		ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5522 		    holds_callback, &cb);
5523 		if (ret != 0)
5524 			++errors;
5525 	}
5526 
5527 	/*
5528 	 *  2. print holds data
5529 	 */
5530 	print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5531 
5532 	if (nvlist_empty(nvl))
5533 		(void) printf(gettext("no datasets available\n"));
5534 
5535 	nvlist_free(nvl);
5536 
5537 	return (0 != errors);
5538 }
5539 
5540 #define	CHECK_SPINNER 30
5541 #define	SPINNER_TIME 3		/* seconds */
5542 #define	MOUNT_TIME 5		/* seconds */
5543 
5544 static int
5545 get_one_dataset(zfs_handle_t *zhp, void *data)
5546 {
5547 	static char *spin[] = { "-", "\\", "|", "/" };
5548 	static int spinval = 0;
5549 	static int spincheck = 0;
5550 	static time_t last_spin_time = (time_t)0;
5551 	get_all_cb_t *cbp = data;
5552 	zfs_type_t type = zfs_get_type(zhp);
5553 
5554 	if (cbp->cb_verbose) {
5555 		if (--spincheck < 0) {
5556 			time_t now = time(NULL);
5557 			if (last_spin_time + SPINNER_TIME < now) {
5558 				update_progress(spin[spinval++ % 4]);
5559 				last_spin_time = now;
5560 			}
5561 			spincheck = CHECK_SPINNER;
5562 		}
5563 	}
5564 
5565 	/*
5566 	 * Interate over any nested datasets.
5567 	 */
5568 	if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5569 		zfs_close(zhp);
5570 		return (1);
5571 	}
5572 
5573 	/*
5574 	 * Skip any datasets whose type does not match.
5575 	 */
5576 	if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5577 		zfs_close(zhp);
5578 		return (0);
5579 	}
5580 	libzfs_add_handle(cbp, zhp);
5581 	assert(cbp->cb_used <= cbp->cb_alloc);
5582 
5583 	return (0);
5584 }
5585 
5586 static void
5587 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5588 {
5589 	get_all_cb_t cb = { 0 };
5590 	cb.cb_verbose = verbose;
5591 	cb.cb_getone = get_one_dataset;
5592 
5593 	if (verbose)
5594 		set_progress_header(gettext("Reading ZFS config"));
5595 	(void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5596 
5597 	*dslist = cb.cb_handles;
5598 	*count = cb.cb_used;
5599 
5600 	if (verbose)
5601 		finish_progress(gettext("done."));
5602 }
5603 
5604 /*
5605  * Generic callback for sharing or mounting filesystems.  Because the code is so
5606  * similar, we have a common function with an extra parameter to determine which
5607  * mode we are using.
5608  */
5609 #define	OP_SHARE	0x1
5610 #define	OP_MOUNT	0x2
5611 
5612 /*
5613  * Share or mount a dataset.
5614  */
5615 static int
5616 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5617     boolean_t explicit, const char *options)
5618 {
5619 	char mountpoint[ZFS_MAXPROPLEN];
5620 	char shareopts[ZFS_MAXPROPLEN];
5621 	char smbshareopts[ZFS_MAXPROPLEN];
5622 	const char *cmdname = op == OP_SHARE ? "share" : "mount";
5623 	struct mnttab mnt;
5624 	uint64_t zoned, canmount;
5625 	boolean_t shared_nfs, shared_smb;
5626 
5627 	assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5628 
5629 	/*
5630 	 * Check to make sure we can mount/share this dataset.  If we
5631 	 * are in the global zone and the filesystem is exported to a
5632 	 * local zone, or if we are in a local zone and the
5633 	 * filesystem is not exported, then it is an error.
5634 	 */
5635 	zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5636 
5637 	if (zoned && getzoneid() == GLOBAL_ZONEID) {
5638 		if (!explicit)
5639 			return (0);
5640 
5641 		(void) fprintf(stderr, gettext("cannot %s '%s': "
5642 		    "dataset is exported to a local zone\n"), cmdname,
5643 		    zfs_get_name(zhp));
5644 		return (1);
5645 
5646 	} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5647 		if (!explicit)
5648 			return (0);
5649 
5650 		(void) fprintf(stderr, gettext("cannot %s '%s': "
5651 		    "permission denied\n"), cmdname,
5652 		    zfs_get_name(zhp));
5653 		return (1);
5654 	}
5655 
5656 	/*
5657 	 * Ignore any filesystems which don't apply to us. This
5658 	 * includes those with a legacy mountpoint, or those with
5659 	 * legacy share options.
5660 	 */
5661 	verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5662 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5663 	verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5664 	    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5665 	verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5666 	    sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5667 
5668 	if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5669 	    strcmp(smbshareopts, "off") == 0) {
5670 		if (!explicit)
5671 			return (0);
5672 
5673 		(void) fprintf(stderr, gettext("cannot share '%s': "
5674 		    "legacy share\n"), zfs_get_name(zhp));
5675 		(void) fprintf(stderr, gettext("use share(1M) to "
5676 		    "share this filesystem, or set "
5677 		    "sharenfs property on\n"));
5678 		return (1);
5679 	}
5680 
5681 	/*
5682 	 * We cannot share or mount legacy filesystems. If the
5683 	 * shareopts is non-legacy but the mountpoint is legacy, we
5684 	 * treat it as a legacy share.
5685 	 */
5686 	if (strcmp(mountpoint, "legacy") == 0) {
5687 		if (!explicit)
5688 			return (0);
5689 
5690 		(void) fprintf(stderr, gettext("cannot %s '%s': "
5691 		    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5692 		(void) fprintf(stderr, gettext("use %s(1M) to "
5693 		    "%s this filesystem\n"), cmdname, cmdname);
5694 		return (1);
5695 	}
5696 
5697 	if (strcmp(mountpoint, "none") == 0) {
5698 		if (!explicit)
5699 			return (0);
5700 
5701 		(void) fprintf(stderr, gettext("cannot %s '%s': no "
5702 		    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5703 		return (1);
5704 	}
5705 
5706 	/*
5707 	 * canmount	explicit	outcome
5708 	 * on		no		pass through
5709 	 * on		yes		pass through
5710 	 * off		no		return 0
5711 	 * off		yes		display error, return 1
5712 	 * noauto	no		return 0
5713 	 * noauto	yes		pass through
5714 	 */
5715 	canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5716 	if (canmount == ZFS_CANMOUNT_OFF) {
5717 		if (!explicit)
5718 			return (0);
5719 
5720 		(void) fprintf(stderr, gettext("cannot %s '%s': "
5721 		    "'canmount' property is set to 'off'\n"), cmdname,
5722 		    zfs_get_name(zhp));
5723 		return (1);
5724 	} else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5725 		return (0);
5726 	}
5727 
5728 	/*
5729 	 * At this point, we have verified that the mountpoint and/or
5730 	 * shareopts are appropriate for auto management. If the
5731 	 * filesystem is already mounted or shared, return (failing
5732 	 * for explicit requests); otherwise mount or share the
5733 	 * filesystem.
5734 	 */
5735 	switch (op) {
5736 	case OP_SHARE:
5737 
5738 		shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5739 		shared_smb = zfs_is_shared_smb(zhp, NULL);
5740 
5741 		if (shared_nfs && shared_smb ||
5742 		    (shared_nfs && strcmp(shareopts, "on") == 0 &&
5743 		    strcmp(smbshareopts, "off") == 0) ||
5744 		    (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5745 		    strcmp(shareopts, "off") == 0)) {
5746 			if (!explicit)
5747 				return (0);
5748 
5749 			(void) fprintf(stderr, gettext("cannot share "
5750 			    "'%s': filesystem already shared\n"),
5751 			    zfs_get_name(zhp));
5752 			return (1);
5753 		}
5754 
5755 		if (!zfs_is_mounted(zhp, NULL) &&
5756 		    zfs_mount(zhp, NULL, 0) != 0)
5757 			return (1);
5758 
5759 		if (protocol == NULL) {
5760 			if (zfs_shareall(zhp) != 0)
5761 				return (1);
5762 		} else if (strcmp(protocol, "nfs") == 0) {
5763 			if (zfs_share_nfs(zhp))
5764 				return (1);
5765 		} else if (strcmp(protocol, "smb") == 0) {
5766 			if (zfs_share_smb(zhp))
5767 				return (1);
5768 		} else {
5769 			(void) fprintf(stderr, gettext("cannot share "
5770 			    "'%s': invalid share type '%s' "
5771 			    "specified\n"),
5772 			    zfs_get_name(zhp), protocol);
5773 			return (1);
5774 		}
5775 
5776 		break;
5777 
5778 	case OP_MOUNT:
5779 		if (options == NULL)
5780 			mnt.mnt_mntopts = "";
5781 		else
5782 			mnt.mnt_mntopts = (char *)options;
5783 
5784 		if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5785 		    zfs_is_mounted(zhp, NULL)) {
5786 			if (!explicit)
5787 				return (0);
5788 
5789 			(void) fprintf(stderr, gettext("cannot mount "
5790 			    "'%s': filesystem already mounted\n"),
5791 			    zfs_get_name(zhp));
5792 			return (1);
5793 		}
5794 
5795 		if (zfs_mount(zhp, options, flags) != 0)
5796 			return (1);
5797 		break;
5798 	}
5799 
5800 	return (0);
5801 }
5802 
5803 /*
5804  * Reports progress in the form "(current/total)".  Not thread-safe.
5805  */
5806 static void
5807 report_mount_progress(int current, int total)
5808 {
5809 	static time_t last_progress_time = 0;
5810 	time_t now = time(NULL);
5811 	char info[32];
5812 
5813 	/* report 1..n instead of 0..n-1 */
5814 	++current;
5815 
5816 	/* display header if we're here for the first time */
5817 	if (current == 1) {
5818 		set_progress_header(gettext("Mounting ZFS filesystems"));
5819 	} else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5820 		/* too soon to report again */
5821 		return;
5822 	}
5823 
5824 	last_progress_time = now;
5825 
5826 	(void) sprintf(info, "(%d/%d)", current, total);
5827 
5828 	if (current == total)
5829 		finish_progress(info);
5830 	else
5831 		update_progress(info);
5832 }
5833 
5834 static void
5835 append_options(char *mntopts, char *newopts)
5836 {
5837 	int len = strlen(mntopts);
5838 
5839 	/* original length plus new string to append plus 1 for the comma */
5840 	if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5841 		(void) fprintf(stderr, gettext("the opts argument for "
5842 		    "'%c' option is too long (more than %d chars)\n"),
5843 		    "-o", MNT_LINE_MAX);
5844 		usage(B_FALSE);
5845 	}
5846 
5847 	if (*mntopts)
5848 		mntopts[len++] = ',';
5849 
5850 	(void) strcpy(&mntopts[len], newopts);
5851 }
5852 
5853 static int
5854 share_mount(int op, int argc, char **argv)
5855 {
5856 	int do_all = 0;
5857 	boolean_t verbose = B_FALSE;
5858 	int c, ret = 0;
5859 	char *options = NULL;
5860 	int flags = 0;
5861 
5862 	/* check options */
5863 	while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5864 	    != -1) {
5865 		switch (c) {
5866 		case 'a':
5867 			do_all = 1;
5868 			break;
5869 		case 'v':
5870 			verbose = B_TRUE;
5871 			break;
5872 		case 'o':
5873 			if (*optarg == '\0') {
5874 				(void) fprintf(stderr, gettext("empty mount "
5875 				    "options (-o) specified\n"));
5876 				usage(B_FALSE);
5877 			}
5878 
5879 			if (options == NULL)
5880 				options = safe_malloc(MNT_LINE_MAX + 1);
5881 
5882 			/* option validation is done later */
5883 			append_options(options, optarg);
5884 			break;
5885 
5886 		case 'O':
5887 			flags |= MS_OVERLAY;
5888 			break;
5889 		case ':':
5890 			(void) fprintf(stderr, gettext("missing argument for "
5891 			    "'%c' option\n"), optopt);
5892 			usage(B_FALSE);
5893 			break;
5894 		case '?':
5895 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
5896 			    optopt);
5897 			usage(B_FALSE);
5898 		}
5899 	}
5900 
5901 	argc -= optind;
5902 	argv += optind;
5903 
5904 	/* check number of arguments */
5905 	if (do_all) {
5906 		zfs_handle_t **dslist = NULL;
5907 		size_t i, count = 0;
5908 		char *protocol = NULL;
5909 
5910 		if (op == OP_SHARE && argc > 0) {
5911 			if (strcmp(argv[0], "nfs") != 0 &&
5912 			    strcmp(argv[0], "smb") != 0) {
5913 				(void) fprintf(stderr, gettext("share type "
5914 				    "must be 'nfs' or 'smb'\n"));
5915 				usage(B_FALSE);
5916 			}
5917 			protocol = argv[0];
5918 			argc--;
5919 			argv++;
5920 		}
5921 
5922 		if (argc != 0) {
5923 			(void) fprintf(stderr, gettext("too many arguments\n"));
5924 			usage(B_FALSE);
5925 		}
5926 
5927 		start_progress_timer();
5928 		get_all_datasets(&dslist, &count, verbose);
5929 
5930 		if (count == 0)
5931 			return (0);
5932 
5933 		qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
5934 
5935 		for (i = 0; i < count; i++) {
5936 			if (verbose)
5937 				report_mount_progress(i, count);
5938 
5939 			if (share_mount_one(dslist[i], op, flags, protocol,
5940 			    B_FALSE, options) != 0)
5941 				ret = 1;
5942 			zfs_close(dslist[i]);
5943 		}
5944 
5945 		free(dslist);
5946 	} else if (argc == 0) {
5947 		struct mnttab entry;
5948 
5949 		if ((op == OP_SHARE) || (options != NULL)) {
5950 			(void) fprintf(stderr, gettext("missing filesystem "
5951 			    "argument (specify -a for all)\n"));
5952 			usage(B_FALSE);
5953 		}
5954 
5955 		/*
5956 		 * When mount is given no arguments, go through /etc/mnttab and
5957 		 * display any active ZFS mounts.  We hide any snapshots, since
5958 		 * they are controlled automatically.
5959 		 */
5960 		rewind(mnttab_file);
5961 		while (getmntent(mnttab_file, &entry) == 0) {
5962 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
5963 			    strchr(entry.mnt_special, '@') != NULL)
5964 				continue;
5965 
5966 			(void) printf("%-30s  %s\n", entry.mnt_special,
5967 			    entry.mnt_mountp);
5968 		}
5969 
5970 	} else {
5971 		zfs_handle_t *zhp;
5972 
5973 		if (argc > 1) {
5974 			(void) fprintf(stderr,
5975 			    gettext("too many arguments\n"));
5976 			usage(B_FALSE);
5977 		}
5978 
5979 		if ((zhp = zfs_open(g_zfs, argv[0],
5980 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
5981 			ret = 1;
5982 		} else {
5983 			ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
5984 			    options);
5985 			zfs_close(zhp);
5986 		}
5987 	}
5988 
5989 	return (ret);
5990 }
5991 
5992 /*
5993  * zfs mount -a [nfs]
5994  * zfs mount filesystem
5995  *
5996  * Mount all filesystems, or mount the given filesystem.
5997  */
5998 static int
5999 zfs_do_mount(int argc, char **argv)
6000 {
6001 	return (share_mount(OP_MOUNT, argc, argv));
6002 }
6003 
6004 /*
6005  * zfs share -a [nfs | smb]
6006  * zfs share filesystem
6007  *
6008  * Share all filesystems, or share the given filesystem.
6009  */
6010 static int
6011 zfs_do_share(int argc, char **argv)
6012 {
6013 	return (share_mount(OP_SHARE, argc, argv));
6014 }
6015 
6016 typedef struct unshare_unmount_node {
6017 	zfs_handle_t	*un_zhp;
6018 	char		*un_mountp;
6019 	uu_avl_node_t	un_avlnode;
6020 } unshare_unmount_node_t;
6021 
6022 /* ARGSUSED */
6023 static int
6024 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6025 {
6026 	const unshare_unmount_node_t *l = larg;
6027 	const unshare_unmount_node_t *r = rarg;
6028 
6029 	return (strcmp(l->un_mountp, r->un_mountp));
6030 }
6031 
6032 /*
6033  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
6034  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
6035  * and unmount it appropriately.
6036  */
6037 static int
6038 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6039 {
6040 	zfs_handle_t *zhp;
6041 	int ret = 0;
6042 	struct stat64 statbuf;
6043 	struct extmnttab entry;
6044 	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6045 	ino_t path_inode;
6046 
6047 	/*
6048 	 * Search for the path in /etc/mnttab.  Rather than looking for the
6049 	 * specific path, which can be fooled by non-standard paths (i.e. ".."
6050 	 * or "//"), we stat() the path and search for the corresponding
6051 	 * (major,minor) device pair.
6052 	 */
6053 	if (stat64(path, &statbuf) != 0) {
6054 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6055 		    cmdname, path, strerror(errno));
6056 		return (1);
6057 	}
6058 	path_inode = statbuf.st_ino;
6059 
6060 	/*
6061 	 * Search for the given (major,minor) pair in the mount table.
6062 	 */
6063 	rewind(mnttab_file);
6064 	while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6065 		if (entry.mnt_major == major(statbuf.st_dev) &&
6066 		    entry.mnt_minor == minor(statbuf.st_dev))
6067 			break;
6068 	}
6069 	if (ret != 0) {
6070 		if (op == OP_SHARE) {
6071 			(void) fprintf(stderr, gettext("cannot %s '%s': not "
6072 			    "currently mounted\n"), cmdname, path);
6073 			return (1);
6074 		}
6075 		(void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
6076 		    path);
6077 		if ((ret = umount2(path, flags)) != 0)
6078 			(void) fprintf(stderr, gettext("%s: %s\n"), path,
6079 			    strerror(errno));
6080 		return (ret != 0);
6081 	}
6082 
6083 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6084 		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6085 		    "filesystem\n"), cmdname, path);
6086 		return (1);
6087 	}
6088 
6089 	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6090 	    ZFS_TYPE_FILESYSTEM)) == NULL)
6091 		return (1);
6092 
6093 	ret = 1;
6094 	if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6095 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6096 		    cmdname, path, strerror(errno));
6097 		goto out;
6098 	} else if (statbuf.st_ino != path_inode) {
6099 		(void) fprintf(stderr, gettext("cannot "
6100 		    "%s '%s': not a mountpoint\n"), cmdname, path);
6101 		goto out;
6102 	}
6103 
6104 	if (op == OP_SHARE) {
6105 		char nfs_mnt_prop[ZFS_MAXPROPLEN];
6106 		char smbshare_prop[ZFS_MAXPROPLEN];
6107 
6108 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6109 		    sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6110 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6111 		    sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6112 
6113 		if (strcmp(nfs_mnt_prop, "off") == 0 &&
6114 		    strcmp(smbshare_prop, "off") == 0) {
6115 			(void) fprintf(stderr, gettext("cannot unshare "
6116 			    "'%s': legacy share\n"), path);
6117 			(void) fprintf(stderr, gettext("use "
6118 			    "unshare(1M) to unshare this filesystem\n"));
6119 		} else if (!zfs_is_shared(zhp)) {
6120 			(void) fprintf(stderr, gettext("cannot unshare '%s': "
6121 			    "not currently shared\n"), path);
6122 		} else {
6123 			ret = zfs_unshareall_bypath(zhp, path);
6124 		}
6125 	} else {
6126 		char mtpt_prop[ZFS_MAXPROPLEN];
6127 
6128 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6129 		    sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6130 
6131 		if (is_manual) {
6132 			ret = zfs_unmount(zhp, NULL, flags);
6133 		} else if (strcmp(mtpt_prop, "legacy") == 0) {
6134 			(void) fprintf(stderr, gettext("cannot unmount "
6135 			    "'%s': legacy mountpoint\n"),
6136 			    zfs_get_name(zhp));
6137 			(void) fprintf(stderr, gettext("use umount(1M) "
6138 			    "to unmount this filesystem\n"));
6139 		} else {
6140 			ret = zfs_unmountall(zhp, flags);
6141 		}
6142 	}
6143 
6144 out:
6145 	zfs_close(zhp);
6146 
6147 	return (ret != 0);
6148 }
6149 
6150 /*
6151  * Generic callback for unsharing or unmounting a filesystem.
6152  */
6153 static int
6154 unshare_unmount(int op, int argc, char **argv)
6155 {
6156 	int do_all = 0;
6157 	int flags = 0;
6158 	int ret = 0;
6159 	int c;
6160 	zfs_handle_t *zhp;
6161 	char nfs_mnt_prop[ZFS_MAXPROPLEN];
6162 	char sharesmb[ZFS_MAXPROPLEN];
6163 
6164 	/* check options */
6165 	while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6166 		switch (c) {
6167 		case 'a':
6168 			do_all = 1;
6169 			break;
6170 		case 'f':
6171 			flags = MS_FORCE;
6172 			break;
6173 		case '?':
6174 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6175 			    optopt);
6176 			usage(B_FALSE);
6177 		}
6178 	}
6179 
6180 	argc -= optind;
6181 	argv += optind;
6182 
6183 	if (do_all) {
6184 		/*
6185 		 * We could make use of zfs_for_each() to walk all datasets in
6186 		 * the system, but this would be very inefficient, especially
6187 		 * since we would have to linearly search /etc/mnttab for each
6188 		 * one.  Instead, do one pass through /etc/mnttab looking for
6189 		 * zfs entries and call zfs_unmount() for each one.
6190 		 *
6191 		 * Things get a little tricky if the administrator has created
6192 		 * mountpoints beneath other ZFS filesystems.  In this case, we
6193 		 * have to unmount the deepest filesystems first.  To accomplish
6194 		 * this, we place all the mountpoints in an AVL tree sorted by
6195 		 * the special type (dataset name), and walk the result in
6196 		 * reverse to make sure to get any snapshots first.
6197 		 */
6198 		struct mnttab entry;
6199 		uu_avl_pool_t *pool;
6200 		uu_avl_t *tree;
6201 		unshare_unmount_node_t *node;
6202 		uu_avl_index_t idx;
6203 		uu_avl_walk_t *walk;
6204 
6205 		if (argc != 0) {
6206 			(void) fprintf(stderr, gettext("too many arguments\n"));
6207 			usage(B_FALSE);
6208 		}
6209 
6210 		if (((pool = uu_avl_pool_create("unmount_pool",
6211 		    sizeof (unshare_unmount_node_t),
6212 		    offsetof(unshare_unmount_node_t, un_avlnode),
6213 		    unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6214 		    ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6215 			nomem();
6216 
6217 		rewind(mnttab_file);
6218 		while (getmntent(mnttab_file, &entry) == 0) {
6219 
6220 			/* ignore non-ZFS entries */
6221 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6222 				continue;
6223 
6224 			/* ignore snapshots */
6225 			if (strchr(entry.mnt_special, '@') != NULL)
6226 				continue;
6227 
6228 			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6229 			    ZFS_TYPE_FILESYSTEM)) == NULL) {
6230 				ret = 1;
6231 				continue;
6232 			}
6233 
6234 			switch (op) {
6235 			case OP_SHARE:
6236 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6237 				    nfs_mnt_prop,
6238 				    sizeof (nfs_mnt_prop),
6239 				    NULL, NULL, 0, B_FALSE) == 0);
6240 				if (strcmp(nfs_mnt_prop, "off") != 0)
6241 					break;
6242 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6243 				    nfs_mnt_prop,
6244 				    sizeof (nfs_mnt_prop),
6245 				    NULL, NULL, 0, B_FALSE) == 0);
6246 				if (strcmp(nfs_mnt_prop, "off") == 0)
6247 					continue;
6248 				break;
6249 			case OP_MOUNT:
6250 				/* Ignore legacy mounts */
6251 				verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6252 				    nfs_mnt_prop,
6253 				    sizeof (nfs_mnt_prop),
6254 				    NULL, NULL, 0, B_FALSE) == 0);
6255 				if (strcmp(nfs_mnt_prop, "legacy") == 0)
6256 					continue;
6257 				/* Ignore canmount=noauto mounts */
6258 				if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6259 				    ZFS_CANMOUNT_NOAUTO)
6260 					continue;
6261 			default:
6262 				break;
6263 			}
6264 
6265 			node = safe_malloc(sizeof (unshare_unmount_node_t));
6266 			node->un_zhp = zhp;
6267 			node->un_mountp = safe_strdup(entry.mnt_mountp);
6268 
6269 			uu_avl_node_init(node, &node->un_avlnode, pool);
6270 
6271 			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6272 				uu_avl_insert(tree, node, idx);
6273 			} else {
6274 				zfs_close(node->un_zhp);
6275 				free(node->un_mountp);
6276 				free(node);
6277 			}
6278 		}
6279 
6280 		/*
6281 		 * Walk the AVL tree in reverse, unmounting each filesystem and
6282 		 * removing it from the AVL tree in the process.
6283 		 */
6284 		if ((walk = uu_avl_walk_start(tree,
6285 		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6286 			nomem();
6287 
6288 		while ((node = uu_avl_walk_next(walk)) != NULL) {
6289 			uu_avl_remove(tree, node);
6290 
6291 			switch (op) {
6292 			case OP_SHARE:
6293 				if (zfs_unshareall_bypath(node->un_zhp,
6294 				    node->un_mountp) != 0)
6295 					ret = 1;
6296 				break;
6297 
6298 			case OP_MOUNT:
6299 				if (zfs_unmount(node->un_zhp,
6300 				    node->un_mountp, flags) != 0)
6301 					ret = 1;
6302 				break;
6303 			}
6304 
6305 			zfs_close(node->un_zhp);
6306 			free(node->un_mountp);
6307 			free(node);
6308 		}
6309 
6310 		uu_avl_walk_end(walk);
6311 		uu_avl_destroy(tree);
6312 		uu_avl_pool_destroy(pool);
6313 
6314 	} else {
6315 		if (argc != 1) {
6316 			if (argc == 0)
6317 				(void) fprintf(stderr,
6318 				    gettext("missing filesystem argument\n"));
6319 			else
6320 				(void) fprintf(stderr,
6321 				    gettext("too many arguments\n"));
6322 			usage(B_FALSE);
6323 		}
6324 
6325 		/*
6326 		 * We have an argument, but it may be a full path or a ZFS
6327 		 * filesystem.  Pass full paths off to unmount_path() (shared by
6328 		 * manual_unmount), otherwise open the filesystem and pass to
6329 		 * zfs_unmount().
6330 		 */
6331 		if (argv[0][0] == '/')
6332 			return (unshare_unmount_path(op, argv[0],
6333 			    flags, B_FALSE));
6334 
6335 		if ((zhp = zfs_open(g_zfs, argv[0],
6336 		    ZFS_TYPE_FILESYSTEM)) == NULL)
6337 			return (1);
6338 
6339 		verify(zfs_prop_get(zhp, op == OP_SHARE ?
6340 		    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6341 		    nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6342 		    NULL, 0, B_FALSE) == 0);
6343 
6344 		switch (op) {
6345 		case OP_SHARE:
6346 			verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6347 			    nfs_mnt_prop,
6348 			    sizeof (nfs_mnt_prop),
6349 			    NULL, NULL, 0, B_FALSE) == 0);
6350 			verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6351 			    sharesmb, sizeof (sharesmb), NULL, NULL,
6352 			    0, B_FALSE) == 0);
6353 
6354 			if (strcmp(nfs_mnt_prop, "off") == 0 &&
6355 			    strcmp(sharesmb, "off") == 0) {
6356 				(void) fprintf(stderr, gettext("cannot "
6357 				    "unshare '%s': legacy share\n"),
6358 				    zfs_get_name(zhp));
6359 				(void) fprintf(stderr, gettext("use "
6360 				    "unshare(1M) to unshare this "
6361 				    "filesystem\n"));
6362 				ret = 1;
6363 			} else if (!zfs_is_shared(zhp)) {
6364 				(void) fprintf(stderr, gettext("cannot "
6365 				    "unshare '%s': not currently "
6366 				    "shared\n"), zfs_get_name(zhp));
6367 				ret = 1;
6368 			} else if (zfs_unshareall(zhp) != 0) {
6369 				ret = 1;
6370 			}
6371 			break;
6372 
6373 		case OP_MOUNT:
6374 			if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6375 				(void) fprintf(stderr, gettext("cannot "
6376 				    "unmount '%s': legacy "
6377 				    "mountpoint\n"), zfs_get_name(zhp));
6378 				(void) fprintf(stderr, gettext("use "
6379 				    "umount(1M) to unmount this "
6380 				    "filesystem\n"));
6381 				ret = 1;
6382 			} else if (!zfs_is_mounted(zhp, NULL)) {
6383 				(void) fprintf(stderr, gettext("cannot "
6384 				    "unmount '%s': not currently "
6385 				    "mounted\n"),
6386 				    zfs_get_name(zhp));
6387 				ret = 1;
6388 			} else if (zfs_unmountall(zhp, flags) != 0) {
6389 				ret = 1;
6390 			}
6391 			break;
6392 		}
6393 
6394 		zfs_close(zhp);
6395 	}
6396 
6397 	return (ret);
6398 }
6399 
6400 /*
6401  * zfs unmount -a
6402  * zfs unmount filesystem
6403  *
6404  * Unmount all filesystems, or a specific ZFS filesystem.
6405  */
6406 static int
6407 zfs_do_unmount(int argc, char **argv)
6408 {
6409 	return (unshare_unmount(OP_MOUNT, argc, argv));
6410 }
6411 
6412 /*
6413  * zfs unshare -a
6414  * zfs unshare filesystem
6415  *
6416  * Unshare all filesystems, or a specific ZFS filesystem.
6417  */
6418 static int
6419 zfs_do_unshare(int argc, char **argv)
6420 {
6421 	return (unshare_unmount(OP_SHARE, argc, argv));
6422 }
6423 
6424 /*
6425  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
6426  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
6427  */
6428 static int
6429 manual_mount(int argc, char **argv)
6430 {
6431 	zfs_handle_t *zhp;
6432 	char mountpoint[ZFS_MAXPROPLEN];
6433 	char mntopts[MNT_LINE_MAX] = { '\0' };
6434 	int ret = 0;
6435 	int c;
6436 	int flags = 0;
6437 	char *dataset, *path;
6438 
6439 	/* check options */
6440 	while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6441 		switch (c) {
6442 		case 'o':
6443 			(void) strlcpy(mntopts, optarg, sizeof (mntopts));
6444 			break;
6445 		case 'O':
6446 			flags |= MS_OVERLAY;
6447 			break;
6448 		case 'm':
6449 			flags |= MS_NOMNTTAB;
6450 			break;
6451 		case ':':
6452 			(void) fprintf(stderr, gettext("missing argument for "
6453 			    "'%c' option\n"), optopt);
6454 			usage(B_FALSE);
6455 			break;
6456 		case '?':
6457 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6458 			    optopt);
6459 			(void) fprintf(stderr, gettext("usage: mount [-o opts] "
6460 			    "<path>\n"));
6461 			return (2);
6462 		}
6463 	}
6464 
6465 	argc -= optind;
6466 	argv += optind;
6467 
6468 	/* check that we only have two arguments */
6469 	if (argc != 2) {
6470 		if (argc == 0)
6471 			(void) fprintf(stderr, gettext("missing dataset "
6472 			    "argument\n"));
6473 		else if (argc == 1)
6474 			(void) fprintf(stderr,
6475 			    gettext("missing mountpoint argument\n"));
6476 		else
6477 			(void) fprintf(stderr, gettext("too many arguments\n"));
6478 		(void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6479 		return (2);
6480 	}
6481 
6482 	dataset = argv[0];
6483 	path = argv[1];
6484 
6485 	/* try to open the dataset */
6486 	if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6487 		return (1);
6488 
6489 	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6490 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6491 
6492 	/* check for legacy mountpoint and complain appropriately */
6493 	ret = 0;
6494 	if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6495 		if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6496 		    NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6497 			(void) fprintf(stderr, gettext("mount failed: %s\n"),
6498 			    strerror(errno));
6499 			ret = 1;
6500 		}
6501 	} else {
6502 		(void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6503 		    "mounted using 'mount -F zfs'\n"), dataset);
6504 		(void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6505 		    "instead.\n"), path);
6506 		(void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6507 		    "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6508 		(void) fprintf(stderr, gettext("See zfs(1M) for more "
6509 		    "information.\n"));
6510 		ret = 1;
6511 	}
6512 
6513 	return (ret);
6514 }
6515 
6516 /*
6517  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
6518  * unmounts of non-legacy filesystems, as this is the dominant administrative
6519  * interface.
6520  */
6521 static int
6522 manual_unmount(int argc, char **argv)
6523 {
6524 	int flags = 0;
6525 	int c;
6526 
6527 	/* check options */
6528 	while ((c = getopt(argc, argv, "f")) != -1) {
6529 		switch (c) {
6530 		case 'f':
6531 			flags = MS_FORCE;
6532 			break;
6533 		case '?':
6534 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6535 			    optopt);
6536 			(void) fprintf(stderr, gettext("usage: unmount [-f] "
6537 			    "<path>\n"));
6538 			return (2);
6539 		}
6540 	}
6541 
6542 	argc -= optind;
6543 	argv += optind;
6544 
6545 	/* check arguments */
6546 	if (argc != 1) {
6547 		if (argc == 0)
6548 			(void) fprintf(stderr, gettext("missing path "
6549 			    "argument\n"));
6550 		else
6551 			(void) fprintf(stderr, gettext("too many arguments\n"));
6552 		(void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6553 		return (2);
6554 	}
6555 
6556 	return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6557 }
6558 
6559 static int
6560 find_command_idx(char *command, int *idx)
6561 {
6562 	int i;
6563 
6564 	for (i = 0; i < NCOMMAND; i++) {
6565 		if (command_table[i].name == NULL)
6566 			continue;
6567 
6568 		if (strcmp(command, command_table[i].name) == 0) {
6569 			*idx = i;
6570 			return (0);
6571 		}
6572 	}
6573 	return (1);
6574 }
6575 
6576 static int
6577 zfs_do_diff(int argc, char **argv)
6578 {
6579 	zfs_handle_t *zhp;
6580 	int flags = 0;
6581 	char *tosnap = NULL;
6582 	char *fromsnap = NULL;
6583 	char *atp, *copy;
6584 	int err = 0;
6585 	int c;
6586 
6587 	while ((c = getopt(argc, argv, "FHt")) != -1) {
6588 		switch (c) {
6589 		case 'F':
6590 			flags |= ZFS_DIFF_CLASSIFY;
6591 			break;
6592 		case 'H':
6593 			flags |= ZFS_DIFF_PARSEABLE;
6594 			break;
6595 		case 't':
6596 			flags |= ZFS_DIFF_TIMESTAMP;
6597 			break;
6598 		default:
6599 			(void) fprintf(stderr,
6600 			    gettext("invalid option '%c'\n"), optopt);
6601 			usage(B_FALSE);
6602 		}
6603 	}
6604 
6605 	argc -= optind;
6606 	argv += optind;
6607 
6608 	if (argc < 1) {
6609 		(void) fprintf(stderr,
6610 		gettext("must provide at least one snapshot name\n"));
6611 		usage(B_FALSE);
6612 	}
6613 
6614 	if (argc > 2) {
6615 		(void) fprintf(stderr, gettext("too many arguments\n"));
6616 		usage(B_FALSE);
6617 	}
6618 
6619 	fromsnap = argv[0];
6620 	tosnap = (argc == 2) ? argv[1] : NULL;
6621 
6622 	copy = NULL;
6623 	if (*fromsnap != '@')
6624 		copy = strdup(fromsnap);
6625 	else if (tosnap)
6626 		copy = strdup(tosnap);
6627 	if (copy == NULL)
6628 		usage(B_FALSE);
6629 
6630 	if (atp = strchr(copy, '@'))
6631 		*atp = '\0';
6632 
6633 	if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6634 		return (1);
6635 
6636 	free(copy);
6637 
6638 	/*
6639 	 * Ignore SIGPIPE so that the library can give us
6640 	 * information on any failure
6641 	 */
6642 	(void) sigignore(SIGPIPE);
6643 
6644 	err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6645 
6646 	zfs_close(zhp);
6647 
6648 	return (err != 0);
6649 }
6650 
6651 /*
6652  * zfs bookmark <fs@snap> <fs#bmark>
6653  *
6654  * Creates a bookmark with the given name from the given snapshot.
6655  */
6656 static int
6657 zfs_do_bookmark(int argc, char **argv)
6658 {
6659 	char snapname[ZFS_MAXNAMELEN];
6660 	zfs_handle_t *zhp;
6661 	nvlist_t *nvl;
6662 	int ret = 0;
6663 	int c;
6664 
6665 	/* check options */
6666 	while ((c = getopt(argc, argv, "")) != -1) {
6667 		switch (c) {
6668 		case '?':
6669 			(void) fprintf(stderr,
6670 			    gettext("invalid option '%c'\n"), optopt);
6671 			goto usage;
6672 		}
6673 	}
6674 
6675 	argc -= optind;
6676 	argv += optind;
6677 
6678 	/* check number of arguments */
6679 	if (argc < 1) {
6680 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
6681 		goto usage;
6682 	}
6683 	if (argc < 2) {
6684 		(void) fprintf(stderr, gettext("missing bookmark argument\n"));
6685 		goto usage;
6686 	}
6687 
6688 	if (strchr(argv[1], '#') == NULL) {
6689 		(void) fprintf(stderr,
6690 		    gettext("invalid bookmark name '%s' -- "
6691 		    "must contain a '#'\n"), argv[1]);
6692 		goto usage;
6693 	}
6694 
6695 	if (argv[0][0] == '@') {
6696 		/*
6697 		 * Snapshot name begins with @.
6698 		 * Default to same fs as bookmark.
6699 		 */
6700 		(void) strncpy(snapname, argv[1], sizeof (snapname));
6701 		*strchr(snapname, '#') = '\0';
6702 		(void) strlcat(snapname, argv[0], sizeof (snapname));
6703 	} else {
6704 		(void) strncpy(snapname, argv[0], sizeof (snapname));
6705 	}
6706 	zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
6707 	if (zhp == NULL)
6708 		goto usage;
6709 	zfs_close(zhp);
6710 
6711 
6712 	nvl = fnvlist_alloc();
6713 	fnvlist_add_string(nvl, argv[1], snapname);
6714 	ret = lzc_bookmark(nvl, NULL);
6715 	fnvlist_free(nvl);
6716 
6717 	if (ret != 0) {
6718 		const char *err_msg;
6719 		char errbuf[1024];
6720 
6721 		(void) snprintf(errbuf, sizeof (errbuf),
6722 		    dgettext(TEXT_DOMAIN,
6723 		    "cannot create bookmark '%s'"), argv[1]);
6724 
6725 		switch (ret) {
6726 		case EXDEV:
6727 			err_msg = "bookmark is in a different pool";
6728 			break;
6729 		case EEXIST:
6730 			err_msg = "bookmark exists";
6731 			break;
6732 		case EINVAL:
6733 			err_msg = "invalid argument";
6734 			break;
6735 		case ENOTSUP:
6736 			err_msg = "bookmark feature not enabled";
6737 			break;
6738 		case ENOSPC:
6739 			err_msg = "out of space";
6740 			break;
6741 		default:
6742 			err_msg = "unknown error";
6743 			break;
6744 		}
6745 		(void) fprintf(stderr, "%s: %s\n", errbuf,
6746 		    dgettext(TEXT_DOMAIN, err_msg));
6747 	}
6748 
6749 	return (ret != 0);
6750 
6751 usage:
6752 	usage(B_FALSE);
6753 	return (-1);
6754 }
6755 
6756 int
6757 main(int argc, char **argv)
6758 {
6759 	int ret = 0;
6760 	int i;
6761 	char *progname;
6762 	char *cmdname;
6763 
6764 	(void) setlocale(LC_ALL, "");
6765 	(void) textdomain(TEXT_DOMAIN);
6766 
6767 	opterr = 0;
6768 
6769 	if ((g_zfs = libzfs_init()) == NULL) {
6770 		(void) fprintf(stderr, gettext("internal error: failed to "
6771 		    "initialize ZFS library\n"));
6772 		return (1);
6773 	}
6774 
6775 	zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6776 
6777 	libzfs_print_on_error(g_zfs, B_TRUE);
6778 
6779 	if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6780 		(void) fprintf(stderr, gettext("internal error: unable to "
6781 		    "open %s\n"), MNTTAB);
6782 		return (1);
6783 	}
6784 
6785 	/*
6786 	 * This command also doubles as the /etc/fs mount and unmount program.
6787 	 * Determine if we should take this behavior based on argv[0].
6788 	 */
6789 	progname = basename(argv[0]);
6790 	if (strcmp(progname, "mount") == 0) {
6791 		ret = manual_mount(argc, argv);
6792 	} else if (strcmp(progname, "umount") == 0) {
6793 		ret = manual_unmount(argc, argv);
6794 	} else {
6795 		/*
6796 		 * Make sure the user has specified some command.
6797 		 */
6798 		if (argc < 2) {
6799 			(void) fprintf(stderr, gettext("missing command\n"));
6800 			usage(B_FALSE);
6801 		}
6802 
6803 		cmdname = argv[1];
6804 
6805 		/*
6806 		 * The 'umount' command is an alias for 'unmount'
6807 		 */
6808 		if (strcmp(cmdname, "umount") == 0)
6809 			cmdname = "unmount";
6810 
6811 		/*
6812 		 * The 'recv' command is an alias for 'receive'
6813 		 */
6814 		if (strcmp(cmdname, "recv") == 0)
6815 			cmdname = "receive";
6816 
6817 		/*
6818 		 * The 'snap' command is an alias for 'snapshot'
6819 		 */
6820 		if (strcmp(cmdname, "snap") == 0)
6821 			cmdname = "snapshot";
6822 
6823 		/*
6824 		 * Special case '-?'
6825 		 */
6826 		if (strcmp(cmdname, "-?") == 0)
6827 			usage(B_TRUE);
6828 
6829 		/*
6830 		 * Run the appropriate command.
6831 		 */
6832 		libzfs_mnttab_cache(g_zfs, B_TRUE);
6833 		if (find_command_idx(cmdname, &i) == 0) {
6834 			current_command = &command_table[i];
6835 			ret = command_table[i].func(argc - 1, argv + 1);
6836 		} else if (strchr(cmdname, '=') != NULL) {
6837 			verify(find_command_idx("set", &i) == 0);
6838 			current_command = &command_table[i];
6839 			ret = command_table[i].func(argc, argv);
6840 		} else {
6841 			(void) fprintf(stderr, gettext("unrecognized "
6842 			    "command '%s'\n"), cmdname);
6843 			usage(B_FALSE);
6844 		}
6845 		libzfs_mnttab_cache(g_zfs, B_FALSE);
6846 	}
6847 
6848 	(void) fclose(mnttab_file);
6849 
6850 	if (ret == 0 && log_history)
6851 		(void) zpool_log_history(g_zfs, history_str);
6852 
6853 	libzfs_fini(g_zfs);
6854 
6855 	/*
6856 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6857 	 * for the purposes of running ::findleaks.
6858 	 */
6859 	if (getenv("ZFS_ABORT") != NULL) {
6860 		(void) printf("dumping core by request\n");
6861 		abort();
6862 	}
6863 
6864 	return (ret);
6865 }
6866