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