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