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