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