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