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