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