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