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