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