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
86libzfs_handle_t *g_zfs;
87
88static FILE *mnttab_file;
89static char history_str[HIS_MAX_RECORD_LEN];
90static boolean_t log_history = B_TRUE;
91
92static int zfs_do_clone(int argc, char **argv);
93static int zfs_do_create(int argc, char **argv);
94static int zfs_do_destroy(int argc, char **argv);
95static int zfs_do_get(int argc, char **argv);
96static int zfs_do_inherit(int argc, char **argv);
97static int zfs_do_list(int argc, char **argv);
98static int zfs_do_mount(int argc, char **argv);
99static int zfs_do_rename(int argc, char **argv);
100static int zfs_do_rollback(int argc, char **argv);
101static int zfs_do_set(int argc, char **argv);
102static int zfs_do_upgrade(int argc, char **argv);
103static int zfs_do_snapshot(int argc, char **argv);
104static int zfs_do_unmount(int argc, char **argv);
105static int zfs_do_share(int argc, char **argv);
106static int zfs_do_unshare(int argc, char **argv);
107static int zfs_do_send(int argc, char **argv);
108static int zfs_do_receive(int argc, char **argv);
109static int zfs_do_promote(int argc, char **argv);
110static int zfs_do_userspace(int argc, char **argv);
111static int zfs_do_allow(int argc, char **argv);
112static int zfs_do_unallow(int argc, char **argv);
113static int zfs_do_hold(int argc, char **argv);
114static int zfs_do_holds(int argc, char **argv);
115static int zfs_do_release(int argc, char **argv);
116static int zfs_do_diff(int argc, char **argv);
117static int zfs_do_bookmark(int argc, char **argv);
118static int zfs_do_channel_program(int argc, char **argv);
119static int zfs_do_load_key(int argc, char **argv);
120static int zfs_do_unload_key(int argc, char **argv);
121static int zfs_do_change_key(int argc, char **argv);
122static int zfs_do_project(int argc, char **argv);
123static int zfs_do_version(int argc, char **argv);
124static int zfs_do_redact(int argc, char **argv);
125static int zfs_do_wait(int argc, char **argv);
126
127#ifdef __FreeBSD__
128static int zfs_do_jail(int argc, char **argv);
129static 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
137const char *
138_umem_debug_init(void)
139{
140	return ("default,verbose"); /* $UMEM_DEBUG setting */
141}
142
143const char *
144_umem_logging_init(void)
145{
146	return ("fail,contents"); /* $UMEM_LOGGING setting */
147}
148#endif
149
150typedef 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
191typedef 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 */
206static 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
263zfs_command_t *current_command;
264
265static const char *
266get_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 -p [-f] <filesystem|volume> <filesystem|volume>\n"
315		    "\trename -u [-f] <filesystem> <filesystem>\n"
316		    "\trename -r <snapshot> <snapshot>\n"));
317	case HELP_ROLLBACK:
318		return (gettext("\trollback [-rRf] <snapshot>\n"));
319	case HELP_SEND:
320		return (gettext("\tsend [-DnPpRvLecwhb] [-[i|I] snapshot] "
321		    "<snapshot>\n"
322		    "\tsend [-nvPLecw] [-i snapshot|bookmark] "
323		    "<filesystem|volume|snapshot>\n"
324		    "\tsend [-DnPpvLec] [-i bookmark|snapshot] "
325		    "--redact <bookmark> <snapshot>\n"
326		    "\tsend [-nvPe] -t <receive_resume_token>\n"
327		    "\tsend [-Pnv] --saved filesystem\n"));
328	case HELP_SET:
329		return (gettext("\tset <property=value> ... "
330		    "<filesystem|volume|snapshot> ...\n"));
331	case HELP_SHARE:
332		return (gettext("\tshare [-l] <-a [nfs|smb] | filesystem>\n"));
333	case HELP_SNAPSHOT:
334		return (gettext("\tsnapshot [-r] [-o property=value] ... "
335		    "<filesystem|volume>@<snap> ...\n"));
336	case HELP_UNMOUNT:
337		return (gettext("\tunmount [-fu] "
338		    "<-a | filesystem|mountpoint>\n"));
339	case HELP_UNSHARE:
340		return (gettext("\tunshare "
341		    "<-a [nfs|smb] | filesystem|mountpoint>\n"));
342	case HELP_ALLOW:
343		return (gettext("\tallow <filesystem|volume>\n"
344		    "\tallow [-ldug] "
345		    "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
346		    "\t    <filesystem|volume>\n"
347		    "\tallow [-ld] -e <perm|@setname>[,...] "
348		    "<filesystem|volume>\n"
349		    "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
350		    "\tallow -s @setname <perm|@setname>[,...] "
351		    "<filesystem|volume>\n"));
352	case HELP_UNALLOW:
353		return (gettext("\tunallow [-rldug] "
354		    "<\"everyone\"|user|group>[,...]\n"
355		    "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
356		    "\tunallow [-rld] -e [<perm|@setname>[,...]] "
357		    "<filesystem|volume>\n"
358		    "\tunallow [-r] -c [<perm|@setname>[,...]] "
359		    "<filesystem|volume>\n"
360		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
361		    "<filesystem|volume>\n"));
362	case HELP_USERSPACE:
363		return (gettext("\tuserspace [-Hinp] [-o field[,...]] "
364		    "[-s field] ...\n"
365		    "\t    [-S field] ... [-t type[,...]] "
366		    "<filesystem|snapshot|path>\n"));
367	case HELP_GROUPSPACE:
368		return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
369		    "[-s field] ...\n"
370		    "\t    [-S field] ... [-t type[,...]] "
371		    "<filesystem|snapshot|path>\n"));
372	case HELP_PROJECTSPACE:
373		return (gettext("\tprojectspace [-Hp] [-o field[,...]] "
374		    "[-s field] ... \n"
375		    "\t    [-S field] ... <filesystem|snapshot|path>\n"));
376	case HELP_PROJECT:
377		return (gettext("\tproject [-d|-r] <directory|file ...>\n"
378		    "\tproject -c [-0] [-d|-r] [-p id] <directory|file ...>\n"
379		    "\tproject -C [-k] [-r] <directory ...>\n"
380		    "\tproject [-p id] [-r] [-s] <directory ...>\n"));
381	case HELP_HOLD:
382		return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
383	case HELP_HOLDS:
384		return (gettext("\tholds [-rH] <snapshot> ...\n"));
385	case HELP_RELEASE:
386		return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
387	case HELP_DIFF:
388		return (gettext("\tdiff [-FHt] <snapshot> "
389		    "[snapshot|filesystem]\n"));
390	case HELP_BOOKMARK:
391		return (gettext("\tbookmark <snapshot|bookmark> "
392		    "<newbookmark>\n"));
393	case HELP_CHANNEL_PROGRAM:
394		return (gettext("\tprogram [-jn] [-t <instruction limit>] "
395		    "[-m <memory limit (b)>]\n"
396		    "\t    <pool> <program file> [lua args...]\n"));
397	case HELP_LOAD_KEY:
398		return (gettext("\tload-key [-rn] [-L <keylocation>] "
399		    "<-a | filesystem|volume>\n"));
400	case HELP_UNLOAD_KEY:
401		return (gettext("\tunload-key [-r] "
402		    "<-a | filesystem|volume>\n"));
403	case HELP_CHANGE_KEY:
404		return (gettext("\tchange-key [-l] [-o keyformat=<value>]\n"
405		    "\t    [-o keylocation=<value>] [-o pbkdf2iters=<value>]\n"
406		    "\t    <filesystem|volume>\n"
407		    "\tchange-key -i [-l] <filesystem|volume>\n"));
408	case HELP_VERSION:
409		return (gettext("\tversion\n"));
410	case HELP_REDACT:
411		return (gettext("\tredact <snapshot> <bookmark> "
412		    "<redaction_snapshot> ...\n"));
413	case HELP_JAIL:
414		return (gettext("\tjail <jailid|jailname> <filesystem>\n"));
415	case HELP_UNJAIL:
416		return (gettext("\tunjail <jailid|jailname> <filesystem>\n"));
417	case HELP_WAIT:
418		return (gettext("\twait [-t <activity>] <filesystem>\n"));
419	}
420
421	abort();
422	/* NOTREACHED */
423}
424
425void
426nomem(void)
427{
428	(void) fprintf(stderr, gettext("internal error: out of memory\n"));
429	exit(1);
430}
431
432/*
433 * Utility function to guarantee malloc() success.
434 */
435
436void *
437safe_malloc(size_t size)
438{
439	void *data;
440
441	if ((data = calloc(1, size)) == NULL)
442		nomem();
443
444	return (data);
445}
446
447static void *
448safe_realloc(void *data, size_t size)
449{
450	void *newp;
451	if ((newp = realloc(data, size)) == NULL) {
452		free(data);
453		nomem();
454	}
455
456	return (newp);
457}
458
459static char *
460safe_strdup(char *str)
461{
462	char *dupstr = strdup(str);
463
464	if (dupstr == NULL)
465		nomem();
466
467	return (dupstr);
468}
469
470/*
471 * Callback routine that will print out information for each of
472 * the properties.
473 */
474static int
475usage_prop_cb(int prop, void *cb)
476{
477	FILE *fp = cb;
478
479	(void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
480
481	if (zfs_prop_readonly(prop))
482		(void) fprintf(fp, " NO    ");
483	else
484		(void) fprintf(fp, "YES    ");
485
486	if (zfs_prop_inheritable(prop))
487		(void) fprintf(fp, "  YES   ");
488	else
489		(void) fprintf(fp, "   NO   ");
490
491	if (zfs_prop_values(prop) == NULL)
492		(void) fprintf(fp, "-\n");
493	else
494		(void) fprintf(fp, "%s\n", zfs_prop_values(prop));
495
496	return (ZPROP_CONT);
497}
498
499/*
500 * Display usage message.  If we're inside a command, display only the usage for
501 * that command.  Otherwise, iterate over the entire command table and display
502 * a complete usage message.
503 */
504static void
505usage(boolean_t requested)
506{
507	int i;
508	boolean_t show_properties = B_FALSE;
509	FILE *fp = requested ? stdout : stderr;
510
511	if (current_command == NULL) {
512
513		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
514		(void) fprintf(fp,
515		    gettext("where 'command' is one of the following:\n\n"));
516
517		for (i = 0; i < NCOMMAND; i++) {
518			if (command_table[i].name == NULL)
519				(void) fprintf(fp, "\n");
520			else
521				(void) fprintf(fp, "%s",
522				    get_usage(command_table[i].usage));
523		}
524
525		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
526		    "pool/[dataset/]*dataset[@name]\n"));
527	} else {
528		(void) fprintf(fp, gettext("usage:\n"));
529		(void) fprintf(fp, "%s", get_usage(current_command->usage));
530	}
531
532	if (current_command != NULL &&
533	    (strcmp(current_command->name, "set") == 0 ||
534	    strcmp(current_command->name, "get") == 0 ||
535	    strcmp(current_command->name, "inherit") == 0 ||
536	    strcmp(current_command->name, "list") == 0))
537		show_properties = B_TRUE;
538
539	if (show_properties) {
540		(void) fprintf(fp,
541		    gettext("\nThe following properties are supported:\n"));
542
543		(void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
544		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
545
546		/* Iterate over all properties */
547		(void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
548		    ZFS_TYPE_DATASET);
549
550		(void) fprintf(fp, "\t%-15s ", "userused@...");
551		(void) fprintf(fp, " NO       NO   <size>\n");
552		(void) fprintf(fp, "\t%-15s ", "groupused@...");
553		(void) fprintf(fp, " NO       NO   <size>\n");
554		(void) fprintf(fp, "\t%-15s ", "projectused@...");
555		(void) fprintf(fp, " NO       NO   <size>\n");
556		(void) fprintf(fp, "\t%-15s ", "userobjused@...");
557		(void) fprintf(fp, " NO       NO   <size>\n");
558		(void) fprintf(fp, "\t%-15s ", "groupobjused@...");
559		(void) fprintf(fp, " NO       NO   <size>\n");
560		(void) fprintf(fp, "\t%-15s ", "projectobjused@...");
561		(void) fprintf(fp, " NO       NO   <size>\n");
562		(void) fprintf(fp, "\t%-15s ", "userquota@...");
563		(void) fprintf(fp, "YES       NO   <size> | none\n");
564		(void) fprintf(fp, "\t%-15s ", "groupquota@...");
565		(void) fprintf(fp, "YES       NO   <size> | none\n");
566		(void) fprintf(fp, "\t%-15s ", "projectquota@...");
567		(void) fprintf(fp, "YES       NO   <size> | none\n");
568		(void) fprintf(fp, "\t%-15s ", "userobjquota@...");
569		(void) fprintf(fp, "YES       NO   <size> | none\n");
570		(void) fprintf(fp, "\t%-15s ", "groupobjquota@...");
571		(void) fprintf(fp, "YES       NO   <size> | none\n");
572		(void) fprintf(fp, "\t%-15s ", "projectobjquota@...");
573		(void) fprintf(fp, "YES       NO   <size> | none\n");
574		(void) fprintf(fp, "\t%-15s ", "written@<snap>");
575		(void) fprintf(fp, " NO       NO   <size>\n");
576		(void) fprintf(fp, "\t%-15s ", "written#<bookmark>");
577		(void) fprintf(fp, " NO       NO   <size>\n");
578
579		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
580		    "with standard units such as K, M, G, etc.\n"));
581		(void) fprintf(fp, gettext("\nUser-defined properties can "
582		    "be specified by using a name containing a colon (:).\n"));
583		(void) fprintf(fp, gettext("\nThe {user|group|project}"
584		    "[obj]{used|quota}@ properties must be appended with\n"
585		    "a user|group|project specifier of one of these forms:\n"
586		    "    POSIX name      (eg: \"matt\")\n"
587		    "    POSIX id        (eg: \"126829\")\n"
588		    "    SMB name@domain (eg: \"matt@sun\")\n"
589		    "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
590	} else {
591		(void) fprintf(fp,
592		    gettext("\nFor the property list, run: %s\n"),
593		    "zfs set|get");
594		(void) fprintf(fp,
595		    gettext("\nFor the delegated permission list, run: %s\n"),
596		    "zfs allow|unallow");
597	}
598
599	/*
600	 * See comments at end of main().
601	 */
602	if (getenv("ZFS_ABORT") != NULL) {
603		(void) printf("dumping core by request\n");
604		abort();
605	}
606
607	exit(requested ? 0 : 2);
608}
609
610/*
611 * Take a property=value argument string and add it to the given nvlist.
612 * Modifies the argument inplace.
613 */
614static boolean_t
615parseprop(nvlist_t *props, char *propname)
616{
617	char *propval;
618
619	if ((propval = strchr(propname, '=')) == NULL) {
620		(void) fprintf(stderr, gettext("missing "
621		    "'=' for property=value argument\n"));
622		return (B_FALSE);
623	}
624	*propval = '\0';
625	propval++;
626	if (nvlist_exists(props, propname)) {
627		(void) fprintf(stderr, gettext("property '%s' "
628		    "specified multiple times\n"), propname);
629		return (B_FALSE);
630	}
631	if (nvlist_add_string(props, propname, propval) != 0)
632		nomem();
633	return (B_TRUE);
634}
635
636/*
637 * Take a property name argument and add it to the given nvlist.
638 * Modifies the argument inplace.
639 */
640static boolean_t
641parsepropname(nvlist_t *props, char *propname)
642{
643	if (strchr(propname, '=') != NULL) {
644		(void) fprintf(stderr, gettext("invalid character "
645		    "'=' in property argument\n"));
646		return (B_FALSE);
647	}
648	if (nvlist_exists(props, propname)) {
649		(void) fprintf(stderr, gettext("property '%s' "
650		    "specified multiple times\n"), propname);
651		return (B_FALSE);
652	}
653	if (nvlist_add_boolean(props, propname) != 0)
654		nomem();
655	return (B_TRUE);
656}
657
658static int
659parse_depth(char *opt, int *flags)
660{
661	char *tmp;
662	int depth;
663
664	depth = (int)strtol(opt, &tmp, 0);
665	if (*tmp) {
666		(void) fprintf(stderr,
667		    gettext("%s is not an integer\n"), optarg);
668		usage(B_FALSE);
669	}
670	if (depth < 0) {
671		(void) fprintf(stderr,
672		    gettext("Depth can not be negative.\n"));
673		usage(B_FALSE);
674	}
675	*flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
676	return (depth);
677}
678
679#define	PROGRESS_DELAY 2		/* seconds */
680
681static 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";
682static time_t pt_begin;
683static char *pt_header = NULL;
684static boolean_t pt_shown;
685
686static void
687start_progress_timer(void)
688{
689	pt_begin = time(NULL) + PROGRESS_DELAY;
690	pt_shown = B_FALSE;
691}
692
693static void
694set_progress_header(char *header)
695{
696	assert(pt_header == NULL);
697	pt_header = safe_strdup(header);
698	if (pt_shown) {
699		(void) printf("%s: ", header);
700		(void) fflush(stdout);
701	}
702}
703
704static void
705update_progress(char *update)
706{
707	if (!pt_shown && time(NULL) > pt_begin) {
708		int len = strlen(update);
709
710		(void) printf("%s: %s%*.*s", pt_header, update, len, len,
711		    pt_reverse);
712		(void) fflush(stdout);
713		pt_shown = B_TRUE;
714	} else if (pt_shown) {
715		int len = strlen(update);
716
717		(void) printf("%s%*.*s", update, len, len, pt_reverse);
718		(void) fflush(stdout);
719	}
720}
721
722static void
723finish_progress(char *done)
724{
725	if (pt_shown) {
726		(void) printf("%s\n", done);
727		(void) fflush(stdout);
728	}
729	free(pt_header);
730	pt_header = NULL;
731}
732
733static int
734zfs_mount_and_share(libzfs_handle_t *hdl, const char *dataset, zfs_type_t type)
735{
736	zfs_handle_t *zhp = NULL;
737	int ret = 0;
738
739	zhp = zfs_open(hdl, dataset, type);
740	if (zhp == NULL)
741		return (1);
742
743	/*
744	 * Volumes may neither be mounted or shared.  Potentially in the
745	 * future filesystems detected on these volumes could be mounted.
746	 */
747	if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
748		zfs_close(zhp);
749		return (0);
750	}
751
752	/*
753	 * Mount and/or share the new filesystem as appropriate.  We provide a
754	 * verbose error message to let the user know that their filesystem was
755	 * in fact created, even if we failed to mount or share it.
756	 *
757	 * If the user doesn't want the dataset automatically mounted, then
758	 * skip the mount/share step
759	 */
760	if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type, B_FALSE) &&
761	    zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_ON) {
762		if (zfs_mount_delegation_check()) {
763			(void) fprintf(stderr, gettext("filesystem "
764			    "successfully created, but it may only be "
765			    "mounted by root\n"));
766			ret = 1;
767		} else if (zfs_mount(zhp, NULL, 0) != 0) {
768			(void) fprintf(stderr, gettext("filesystem "
769			    "successfully created, but not mounted\n"));
770			ret = 1;
771		} else if (zfs_share(zhp) != 0) {
772			(void) fprintf(stderr, gettext("filesystem "
773			    "successfully created, but not shared\n"));
774			ret = 1;
775		}
776		zfs_commit_all_shares();
777	}
778
779	zfs_close(zhp);
780
781	return (ret);
782}
783
784/*
785 * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
786 *
787 * Given an existing dataset, create a writable copy whose initial contents
788 * are the same as the source.  The newly created dataset maintains a
789 * dependency on the original; the original cannot be destroyed so long as
790 * the clone exists.
791 *
792 * The '-p' flag creates all the non-existing ancestors of the target first.
793 */
794static int
795zfs_do_clone(int argc, char **argv)
796{
797	zfs_handle_t *zhp = NULL;
798	boolean_t parents = B_FALSE;
799	nvlist_t *props;
800	int ret = 0;
801	int c;
802
803	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
804		nomem();
805
806	/* check options */
807	while ((c = getopt(argc, argv, "o:p")) != -1) {
808		switch (c) {
809		case 'o':
810			if (!parseprop(props, optarg)) {
811				nvlist_free(props);
812				return (1);
813			}
814			break;
815		case 'p':
816			parents = B_TRUE;
817			break;
818		case '?':
819			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
820			    optopt);
821			goto usage;
822		}
823	}
824
825	argc -= optind;
826	argv += optind;
827
828	/* check number of arguments */
829	if (argc < 1) {
830		(void) fprintf(stderr, gettext("missing source dataset "
831		    "argument\n"));
832		goto usage;
833	}
834	if (argc < 2) {
835		(void) fprintf(stderr, gettext("missing target dataset "
836		    "argument\n"));
837		goto usage;
838	}
839	if (argc > 2) {
840		(void) fprintf(stderr, gettext("too many arguments\n"));
841		goto usage;
842	}
843
844	/* open the source dataset */
845	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL) {
846		nvlist_free(props);
847		return (1);
848	}
849
850	if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
851	    ZFS_TYPE_VOLUME)) {
852		/*
853		 * Now create the ancestors of the target dataset.  If the
854		 * target already exists and '-p' option was used we should not
855		 * complain.
856		 */
857		if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
858		    ZFS_TYPE_VOLUME)) {
859			zfs_close(zhp);
860			nvlist_free(props);
861			return (0);
862		}
863		if (zfs_create_ancestors(g_zfs, argv[1]) != 0) {
864			zfs_close(zhp);
865			nvlist_free(props);
866			return (1);
867		}
868	}
869
870	/* pass to libzfs */
871	ret = zfs_clone(zhp, argv[1], props);
872
873	/* create the mountpoint if necessary */
874	if (ret == 0) {
875		if (log_history) {
876			(void) zpool_log_history(g_zfs, history_str);
877			log_history = B_FALSE;
878		}
879
880		ret = zfs_mount_and_share(g_zfs, argv[1], ZFS_TYPE_DATASET);
881	}
882
883	zfs_close(zhp);
884	nvlist_free(props);
885
886	return (!!ret);
887
888usage:
889	ASSERT3P(zhp, ==, NULL);
890	nvlist_free(props);
891	usage(B_FALSE);
892	return (-1);
893}
894
895/*
896 * zfs create [-Pnpv] [-o prop=value] ... fs
897 * zfs create [-Pnpsv] [-b blocksize] [-o prop=value] ... -V vol size
898 *
899 * Create a new dataset.  This command can be used to create filesystems
900 * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
901 * For volumes, the user must specify a size to be used.
902 *
903 * The '-s' flag applies only to volumes, and indicates that we should not try
904 * to set the reservation for this volume.  By default we set a reservation
905 * equal to the size for any volume.  For pools with SPA_VERSION >=
906 * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
907 *
908 * The '-p' flag creates all the non-existing ancestors of the target first.
909 *
910 * The '-n' flag is no-op (dry run) mode.  This will perform a user-space sanity
911 * check of arguments and properties, but does not check for permissions,
912 * available space, etc.
913 *
914 * The '-v' flag is for verbose output.
915 *
916 * The '-P' flag is used for parseable output.  It implies '-v'.
917 */
918static int
919zfs_do_create(int argc, char **argv)
920{
921	zfs_type_t type = ZFS_TYPE_FILESYSTEM;
922	zpool_handle_t *zpool_handle = NULL;
923	nvlist_t *real_props = NULL;
924	uint64_t volsize = 0;
925	int c;
926	boolean_t noreserve = B_FALSE;
927	boolean_t bflag = B_FALSE;
928	boolean_t parents = B_FALSE;
929	boolean_t dryrun = B_FALSE;
930	boolean_t verbose = B_FALSE;
931	boolean_t parseable = B_FALSE;
932	int ret = 1;
933	nvlist_t *props;
934	uint64_t intval;
935
936	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
937		nomem();
938
939	/* check options */
940	while ((c = getopt(argc, argv, ":PV:b:nso:pv")) != -1) {
941		switch (c) {
942		case 'V':
943			type = ZFS_TYPE_VOLUME;
944			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
945				(void) fprintf(stderr, gettext("bad volume "
946				    "size '%s': %s\n"), optarg,
947				    libzfs_error_description(g_zfs));
948				goto error;
949			}
950
951			if (nvlist_add_uint64(props,
952			    zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
953				nomem();
954			volsize = intval;
955			break;
956		case 'P':
957			verbose = B_TRUE;
958			parseable = B_TRUE;
959			break;
960		case 'p':
961			parents = B_TRUE;
962			break;
963		case 'b':
964			bflag = B_TRUE;
965			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
966				(void) fprintf(stderr, gettext("bad volume "
967				    "block size '%s': %s\n"), optarg,
968				    libzfs_error_description(g_zfs));
969				goto error;
970			}
971
972			if (nvlist_add_uint64(props,
973			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
974			    intval) != 0)
975				nomem();
976			break;
977		case 'n':
978			dryrun = B_TRUE;
979			break;
980		case 'o':
981			if (!parseprop(props, optarg))
982				goto error;
983			break;
984		case 's':
985			noreserve = B_TRUE;
986			break;
987		case 'v':
988			verbose = B_TRUE;
989			break;
990		case ':':
991			(void) fprintf(stderr, gettext("missing size "
992			    "argument\n"));
993			goto badusage;
994		case '?':
995			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
996			    optopt);
997			goto badusage;
998		}
999	}
1000
1001	if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
1002		(void) fprintf(stderr, gettext("'-s' and '-b' can only be "
1003		    "used when creating a volume\n"));
1004		goto badusage;
1005	}
1006
1007	argc -= optind;
1008	argv += optind;
1009
1010	/* check number of arguments */
1011	if (argc == 0) {
1012		(void) fprintf(stderr, gettext("missing %s argument\n"),
1013		    zfs_type_to_name(type));
1014		goto badusage;
1015	}
1016	if (argc > 1) {
1017		(void) fprintf(stderr, gettext("too many arguments\n"));
1018		goto badusage;
1019	}
1020
1021	if (dryrun || (type == ZFS_TYPE_VOLUME && !noreserve)) {
1022		char msg[ZFS_MAX_DATASET_NAME_LEN * 2];
1023		char *p;
1024
1025		if ((p = strchr(argv[0], '/')) != NULL)
1026			*p = '\0';
1027		zpool_handle = zpool_open(g_zfs, argv[0]);
1028		if (p != NULL)
1029			*p = '/';
1030		if (zpool_handle == NULL)
1031			goto error;
1032
1033		(void) snprintf(msg, sizeof (msg),
1034		    dryrun ? gettext("cannot verify '%s'") :
1035		    gettext("cannot create '%s'"), argv[0]);
1036		if (props && (real_props = zfs_valid_proplist(g_zfs, type,
1037		    props, 0, NULL, zpool_handle, B_TRUE, msg)) == NULL) {
1038			zpool_close(zpool_handle);
1039			goto error;
1040		}
1041	}
1042
1043	/*
1044	 * if volsize is not a multiple of volblocksize, round it up to the
1045	 * nearest multiple of the volblocksize
1046	 */
1047	if (type == ZFS_TYPE_VOLUME) {
1048		uint64_t volblocksize;
1049
1050		if (nvlist_lookup_uint64(props,
1051		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1052		    &volblocksize) != 0)
1053			volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
1054
1055		if (volsize % volblocksize) {
1056			volsize = P2ROUNDUP_TYPED(volsize, volblocksize,
1057			    uint64_t);
1058
1059			if (nvlist_add_uint64(props,
1060			    zfs_prop_to_name(ZFS_PROP_VOLSIZE), volsize) != 0) {
1061				nvlist_free(props);
1062				nomem();
1063			}
1064		}
1065	}
1066
1067
1068	if (type == ZFS_TYPE_VOLUME && !noreserve) {
1069		uint64_t spa_version;
1070		zfs_prop_t resv_prop;
1071		char *strval;
1072
1073		spa_version = zpool_get_prop_int(zpool_handle,
1074		    ZPOOL_PROP_VERSION, NULL);
1075		if (spa_version >= SPA_VERSION_REFRESERVATION)
1076			resv_prop = ZFS_PROP_REFRESERVATION;
1077		else
1078			resv_prop = ZFS_PROP_RESERVATION;
1079
1080		volsize = zvol_volsize_to_reservation(zpool_handle, volsize,
1081		    real_props);
1082
1083		if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
1084		    &strval) != 0) {
1085			if (nvlist_add_uint64(props,
1086			    zfs_prop_to_name(resv_prop), volsize) != 0) {
1087				nvlist_free(props);
1088				nomem();
1089			}
1090		}
1091	}
1092	if (zpool_handle != NULL) {
1093		zpool_close(zpool_handle);
1094		nvlist_free(real_props);
1095	}
1096
1097	if (parents && zfs_name_valid(argv[0], type)) {
1098		/*
1099		 * Now create the ancestors of target dataset.  If the target
1100		 * already exists and '-p' option was used we should not
1101		 * complain.
1102		 */
1103		if (zfs_dataset_exists(g_zfs, argv[0], type)) {
1104			ret = 0;
1105			goto error;
1106		}
1107		if (verbose) {
1108			(void) printf(parseable ? "create_ancestors\t%s\n" :
1109			    dryrun ?  "would create ancestors of %s\n" :
1110			    "create ancestors of %s\n", argv[0]);
1111		}
1112		if (!dryrun) {
1113			if (zfs_create_ancestors(g_zfs, argv[0]) != 0) {
1114				goto error;
1115			}
1116		}
1117	}
1118
1119	if (verbose) {
1120		nvpair_t *nvp = NULL;
1121		(void) printf(parseable ? "create\t%s\n" :
1122		    dryrun ? "would create %s\n" : "create %s\n", argv[0]);
1123		while ((nvp = nvlist_next_nvpair(props, nvp)) != NULL) {
1124			uint64_t uval;
1125			char *sval;
1126
1127			switch (nvpair_type(nvp)) {
1128			case DATA_TYPE_UINT64:
1129				VERIFY0(nvpair_value_uint64(nvp, &uval));
1130				(void) printf(parseable ?
1131				    "property\t%s\t%llu\n" : "\t%s=%llu\n",
1132				    nvpair_name(nvp), (u_longlong_t)uval);
1133				break;
1134			case DATA_TYPE_STRING:
1135				VERIFY0(nvpair_value_string(nvp, &sval));
1136				(void) printf(parseable ?
1137				    "property\t%s\t%s\n" : "\t%s=%s\n",
1138				    nvpair_name(nvp), sval);
1139				break;
1140			default:
1141				(void) fprintf(stderr, "property '%s' "
1142				    "has illegal type %d\n",
1143				    nvpair_name(nvp), nvpair_type(nvp));
1144				abort();
1145			}
1146		}
1147	}
1148	if (dryrun) {
1149		ret = 0;
1150		goto error;
1151	}
1152
1153	/* pass to libzfs */
1154	if (zfs_create(g_zfs, argv[0], type, props) != 0)
1155		goto error;
1156
1157	if (log_history) {
1158		(void) zpool_log_history(g_zfs, history_str);
1159		log_history = B_FALSE;
1160	}
1161
1162	ret = zfs_mount_and_share(g_zfs, argv[0], ZFS_TYPE_DATASET);
1163error:
1164	nvlist_free(props);
1165	return (ret);
1166badusage:
1167	nvlist_free(props);
1168	usage(B_FALSE);
1169	return (2);
1170}
1171
1172/*
1173 * zfs destroy [-rRf] <fs, vol>
1174 * zfs destroy [-rRd] <snap>
1175 *
1176 *	-r	Recursively destroy all children
1177 *	-R	Recursively destroy all dependents, including clones
1178 *	-f	Force unmounting of any dependents
1179 *	-d	If we can't destroy now, mark for deferred destruction
1180 *
1181 * Destroys the given dataset.  By default, it will unmount any filesystems,
1182 * and refuse to destroy a dataset that has any dependents.  A dependent can
1183 * either be a child, or a clone of a child.
1184 */
1185typedef struct destroy_cbdata {
1186	boolean_t	cb_first;
1187	boolean_t	cb_force;
1188	boolean_t	cb_recurse;
1189	boolean_t	cb_error;
1190	boolean_t	cb_doclones;
1191	zfs_handle_t	*cb_target;
1192	boolean_t	cb_defer_destroy;
1193	boolean_t	cb_verbose;
1194	boolean_t	cb_parsable;
1195	boolean_t	cb_dryrun;
1196	nvlist_t	*cb_nvl;
1197	nvlist_t	*cb_batchedsnaps;
1198
1199	/* first snap in contiguous run */
1200	char		*cb_firstsnap;
1201	/* previous snap in contiguous run */
1202	char		*cb_prevsnap;
1203	int64_t		cb_snapused;
1204	char		*cb_snapspec;
1205	char		*cb_bookmark;
1206	uint64_t	cb_snap_count;
1207} destroy_cbdata_t;
1208
1209/*
1210 * Check for any dependents based on the '-r' or '-R' flags.
1211 */
1212static int
1213destroy_check_dependent(zfs_handle_t *zhp, void *data)
1214{
1215	destroy_cbdata_t *cbp = data;
1216	const char *tname = zfs_get_name(cbp->cb_target);
1217	const char *name = zfs_get_name(zhp);
1218
1219	if (strncmp(tname, name, strlen(tname)) == 0 &&
1220	    (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
1221		/*
1222		 * This is a direct descendant, not a clone somewhere else in
1223		 * the hierarchy.
1224		 */
1225		if (cbp->cb_recurse)
1226			goto out;
1227
1228		if (cbp->cb_first) {
1229			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1230			    "%s has children\n"),
1231			    zfs_get_name(cbp->cb_target),
1232			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1233			(void) fprintf(stderr, gettext("use '-r' to destroy "
1234			    "the following datasets:\n"));
1235			cbp->cb_first = B_FALSE;
1236			cbp->cb_error = B_TRUE;
1237		}
1238
1239		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1240	} else {
1241		/*
1242		 * This is a clone.  We only want to report this if the '-r'
1243		 * wasn't specified, or the target is a snapshot.
1244		 */
1245		if (!cbp->cb_recurse &&
1246		    zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
1247			goto out;
1248
1249		if (cbp->cb_first) {
1250			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1251			    "%s has dependent clones\n"),
1252			    zfs_get_name(cbp->cb_target),
1253			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
1254			(void) fprintf(stderr, gettext("use '-R' to destroy "
1255			    "the following datasets:\n"));
1256			cbp->cb_first = B_FALSE;
1257			cbp->cb_error = B_TRUE;
1258			cbp->cb_dryrun = B_TRUE;
1259		}
1260
1261		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1262	}
1263
1264out:
1265	zfs_close(zhp);
1266	return (0);
1267}
1268
1269static int
1270destroy_batched(destroy_cbdata_t *cb)
1271{
1272	int error = zfs_destroy_snaps_nvl(g_zfs,
1273	    cb->cb_batchedsnaps, B_FALSE);
1274	fnvlist_free(cb->cb_batchedsnaps);
1275	cb->cb_batchedsnaps = fnvlist_alloc();
1276	return (error);
1277}
1278
1279static int
1280destroy_callback(zfs_handle_t *zhp, void *data)
1281{
1282	destroy_cbdata_t *cb = data;
1283	const char *name = zfs_get_name(zhp);
1284	int error;
1285
1286	if (cb->cb_verbose) {
1287		if (cb->cb_parsable) {
1288			(void) printf("destroy\t%s\n", name);
1289		} else if (cb->cb_dryrun) {
1290			(void) printf(gettext("would destroy %s\n"),
1291			    name);
1292		} else {
1293			(void) printf(gettext("will destroy %s\n"),
1294			    name);
1295		}
1296	}
1297
1298	/*
1299	 * Ignore pools (which we've already flagged as an error before getting
1300	 * here).
1301	 */
1302	if (strchr(zfs_get_name(zhp), '/') == NULL &&
1303	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1304		zfs_close(zhp);
1305		return (0);
1306	}
1307	if (cb->cb_dryrun) {
1308		zfs_close(zhp);
1309		return (0);
1310	}
1311
1312	/*
1313	 * We batch up all contiguous snapshots (even of different
1314	 * filesystems) and destroy them with one ioctl.  We can't
1315	 * simply do all snap deletions and then all fs deletions,
1316	 * because we must delete a clone before its origin.
1317	 */
1318	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT) {
1319		cb->cb_snap_count++;
1320		fnvlist_add_boolean(cb->cb_batchedsnaps, name);
1321		if (cb->cb_snap_count % 10 == 0 && cb->cb_defer_destroy)
1322			error = destroy_batched(cb);
1323	} else {
1324		error = destroy_batched(cb);
1325		if (error != 0 ||
1326		    zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
1327		    zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
1328			zfs_close(zhp);
1329			/*
1330			 * When performing a recursive destroy we ignore errors
1331			 * so that the recursive destroy could continue
1332			 * destroying past problem datasets
1333			 */
1334			if (cb->cb_recurse) {
1335				cb->cb_error = B_TRUE;
1336				return (0);
1337			}
1338			return (-1);
1339		}
1340	}
1341
1342	zfs_close(zhp);
1343	return (0);
1344}
1345
1346static int
1347destroy_print_cb(zfs_handle_t *zhp, void *arg)
1348{
1349	destroy_cbdata_t *cb = arg;
1350	const char *name = zfs_get_name(zhp);
1351	int err = 0;
1352
1353	if (nvlist_exists(cb->cb_nvl, name)) {
1354		if (cb->cb_firstsnap == NULL)
1355			cb->cb_firstsnap = strdup(name);
1356		if (cb->cb_prevsnap != NULL)
1357			free(cb->cb_prevsnap);
1358		/* this snap continues the current range */
1359		cb->cb_prevsnap = strdup(name);
1360		if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1361			nomem();
1362		if (cb->cb_verbose) {
1363			if (cb->cb_parsable) {
1364				(void) printf("destroy\t%s\n", name);
1365			} else if (cb->cb_dryrun) {
1366				(void) printf(gettext("would destroy %s\n"),
1367				    name);
1368			} else {
1369				(void) printf(gettext("will destroy %s\n"),
1370				    name);
1371			}
1372		}
1373	} else if (cb->cb_firstsnap != NULL) {
1374		/* end of this range */
1375		uint64_t used = 0;
1376		err = lzc_snaprange_space(cb->cb_firstsnap,
1377		    cb->cb_prevsnap, &used);
1378		cb->cb_snapused += used;
1379		free(cb->cb_firstsnap);
1380		cb->cb_firstsnap = NULL;
1381		free(cb->cb_prevsnap);
1382		cb->cb_prevsnap = NULL;
1383	}
1384	zfs_close(zhp);
1385	return (err);
1386}
1387
1388static int
1389destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1390{
1391	int err;
1392	assert(cb->cb_firstsnap == NULL);
1393	assert(cb->cb_prevsnap == NULL);
1394	err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb, 0, 0);
1395	if (cb->cb_firstsnap != NULL) {
1396		uint64_t used = 0;
1397		if (err == 0) {
1398			err = lzc_snaprange_space(cb->cb_firstsnap,
1399			    cb->cb_prevsnap, &used);
1400		}
1401		cb->cb_snapused += used;
1402		free(cb->cb_firstsnap);
1403		cb->cb_firstsnap = NULL;
1404		free(cb->cb_prevsnap);
1405		cb->cb_prevsnap = NULL;
1406	}
1407	return (err);
1408}
1409
1410static int
1411snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1412{
1413	destroy_cbdata_t *cb = arg;
1414	int err = 0;
1415
1416	/* Check for clones. */
1417	if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1418		cb->cb_target = zhp;
1419		cb->cb_first = B_TRUE;
1420		err = zfs_iter_dependents(zhp, B_TRUE,
1421		    destroy_check_dependent, cb);
1422	}
1423
1424	if (err == 0) {
1425		if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1426			nomem();
1427	}
1428	zfs_close(zhp);
1429	return (err);
1430}
1431
1432static int
1433gather_snapshots(zfs_handle_t *zhp, void *arg)
1434{
1435	destroy_cbdata_t *cb = arg;
1436	int err = 0;
1437
1438	err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1439	if (err == ENOENT)
1440		err = 0;
1441	if (err != 0)
1442		goto out;
1443
1444	if (cb->cb_verbose) {
1445		err = destroy_print_snapshots(zhp, cb);
1446		if (err != 0)
1447			goto out;
1448	}
1449
1450	if (cb->cb_recurse)
1451		err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1452
1453out:
1454	zfs_close(zhp);
1455	return (err);
1456}
1457
1458static int
1459destroy_clones(destroy_cbdata_t *cb)
1460{
1461	nvpair_t *pair;
1462	for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1463	    pair != NULL;
1464	    pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1465		zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1466		    ZFS_TYPE_SNAPSHOT);
1467		if (zhp != NULL) {
1468			boolean_t defer = cb->cb_defer_destroy;
1469			int err;
1470
1471			/*
1472			 * We can't defer destroy non-snapshots, so set it to
1473			 * false while destroying the clones.
1474			 */
1475			cb->cb_defer_destroy = B_FALSE;
1476			err = zfs_iter_dependents(zhp, B_FALSE,
1477			    destroy_callback, cb);
1478			cb->cb_defer_destroy = defer;
1479			zfs_close(zhp);
1480			if (err != 0)
1481				return (err);
1482		}
1483	}
1484	return (0);
1485}
1486
1487static int
1488zfs_do_destroy(int argc, char **argv)
1489{
1490	destroy_cbdata_t cb = { 0 };
1491	int rv = 0;
1492	int err = 0;
1493	int c;
1494	zfs_handle_t *zhp = NULL;
1495	char *at, *pound;
1496	zfs_type_t type = ZFS_TYPE_DATASET;
1497
1498	/* check options */
1499	while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1500		switch (c) {
1501		case 'v':
1502			cb.cb_verbose = B_TRUE;
1503			break;
1504		case 'p':
1505			cb.cb_verbose = B_TRUE;
1506			cb.cb_parsable = B_TRUE;
1507			break;
1508		case 'n':
1509			cb.cb_dryrun = B_TRUE;
1510			break;
1511		case 'd':
1512			cb.cb_defer_destroy = B_TRUE;
1513			type = ZFS_TYPE_SNAPSHOT;
1514			break;
1515		case 'f':
1516			cb.cb_force = B_TRUE;
1517			break;
1518		case 'r':
1519			cb.cb_recurse = B_TRUE;
1520			break;
1521		case 'R':
1522			cb.cb_recurse = B_TRUE;
1523			cb.cb_doclones = B_TRUE;
1524			break;
1525		case '?':
1526		default:
1527			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1528			    optopt);
1529			usage(B_FALSE);
1530		}
1531	}
1532
1533	argc -= optind;
1534	argv += optind;
1535
1536	/* check number of arguments */
1537	if (argc == 0) {
1538		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1539		usage(B_FALSE);
1540	}
1541	if (argc > 1) {
1542		(void) fprintf(stderr, gettext("too many arguments\n"));
1543		usage(B_FALSE);
1544	}
1545
1546	at = strchr(argv[0], '@');
1547	pound = strchr(argv[0], '#');
1548	if (at != NULL) {
1549
1550		/* Build the list of snaps to destroy in cb_nvl. */
1551		cb.cb_nvl = fnvlist_alloc();
1552
1553		*at = '\0';
1554		zhp = zfs_open(g_zfs, argv[0],
1555		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1556		if (zhp == NULL) {
1557			nvlist_free(cb.cb_nvl);
1558			return (1);
1559		}
1560
1561		cb.cb_snapspec = at + 1;
1562		if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1563		    cb.cb_error) {
1564			rv = 1;
1565			goto out;
1566		}
1567
1568		if (nvlist_empty(cb.cb_nvl)) {
1569			(void) fprintf(stderr, gettext("could not find any "
1570			    "snapshots to destroy; check snapshot names.\n"));
1571			rv = 1;
1572			goto out;
1573		}
1574
1575		if (cb.cb_verbose) {
1576			char buf[16];
1577			zfs_nicebytes(cb.cb_snapused, buf, sizeof (buf));
1578			if (cb.cb_parsable) {
1579				(void) printf("reclaim\t%llu\n",
1580				    (u_longlong_t)cb.cb_snapused);
1581			} else if (cb.cb_dryrun) {
1582				(void) printf(gettext("would reclaim %s\n"),
1583				    buf);
1584			} else {
1585				(void) printf(gettext("will reclaim %s\n"),
1586				    buf);
1587			}
1588		}
1589
1590		if (!cb.cb_dryrun) {
1591			if (cb.cb_doclones) {
1592				cb.cb_batchedsnaps = fnvlist_alloc();
1593				err = destroy_clones(&cb);
1594				if (err == 0) {
1595					err = zfs_destroy_snaps_nvl(g_zfs,
1596					    cb.cb_batchedsnaps, B_FALSE);
1597				}
1598				if (err != 0) {
1599					rv = 1;
1600					goto out;
1601				}
1602			}
1603			if (err == 0) {
1604				err = zfs_destroy_snaps_nvl(g_zfs, cb.cb_nvl,
1605				    cb.cb_defer_destroy);
1606			}
1607		}
1608
1609		if (err != 0)
1610			rv = 1;
1611	} else if (pound != NULL) {
1612		int err;
1613		nvlist_t *nvl;
1614
1615		if (cb.cb_dryrun) {
1616			(void) fprintf(stderr,
1617			    "dryrun is not supported with bookmark\n");
1618			return (-1);
1619		}
1620
1621		if (cb.cb_defer_destroy) {
1622			(void) fprintf(stderr,
1623			    "defer destroy is not supported with bookmark\n");
1624			return (-1);
1625		}
1626
1627		if (cb.cb_recurse) {
1628			(void) fprintf(stderr,
1629			    "recursive is not supported with bookmark\n");
1630			return (-1);
1631		}
1632
1633		/*
1634		 * Unfortunately, zfs_bookmark() doesn't honor the
1635		 * casesensitivity setting.  However, we can't simply
1636		 * remove this check, because lzc_destroy_bookmarks()
1637		 * ignores non-existent bookmarks, so this is necessary
1638		 * to get a proper error message.
1639		 */
1640		if (!zfs_bookmark_exists(argv[0])) {
1641			(void) fprintf(stderr, gettext("bookmark '%s' "
1642			    "does not exist.\n"), argv[0]);
1643			return (1);
1644		}
1645
1646		nvl = fnvlist_alloc();
1647		fnvlist_add_boolean(nvl, argv[0]);
1648
1649		err = lzc_destroy_bookmarks(nvl, NULL);
1650		if (err != 0) {
1651			(void) zfs_standard_error(g_zfs, err,
1652			    "cannot destroy bookmark");
1653		}
1654
1655		nvlist_free(nvl);
1656
1657		return (err);
1658	} else {
1659		/* Open the given dataset */
1660		if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1661			return (1);
1662
1663		cb.cb_target = zhp;
1664
1665		/*
1666		 * Perform an explicit check for pools before going any further.
1667		 */
1668		if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1669		    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1670			(void) fprintf(stderr, gettext("cannot destroy '%s': "
1671			    "operation does not apply to pools\n"),
1672			    zfs_get_name(zhp));
1673			(void) fprintf(stderr, gettext("use 'zfs destroy -r "
1674			    "%s' to destroy all datasets in the pool\n"),
1675			    zfs_get_name(zhp));
1676			(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1677			    "to destroy the pool itself\n"), zfs_get_name(zhp));
1678			rv = 1;
1679			goto out;
1680		}
1681
1682		/*
1683		 * Check for any dependents and/or clones.
1684		 */
1685		cb.cb_first = B_TRUE;
1686		if (!cb.cb_doclones &&
1687		    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1688		    &cb) != 0) {
1689			rv = 1;
1690			goto out;
1691		}
1692
1693		if (cb.cb_error) {
1694			rv = 1;
1695			goto out;
1696		}
1697		cb.cb_batchedsnaps = fnvlist_alloc();
1698		if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1699		    &cb) != 0) {
1700			rv = 1;
1701			goto out;
1702		}
1703
1704		/*
1705		 * Do the real thing.  The callback will close the
1706		 * handle regardless of whether it succeeds or not.
1707		 */
1708		err = destroy_callback(zhp, &cb);
1709		zhp = NULL;
1710		if (err == 0) {
1711			err = zfs_destroy_snaps_nvl(g_zfs,
1712			    cb.cb_batchedsnaps, cb.cb_defer_destroy);
1713		}
1714		if (err != 0 || cb.cb_error == B_TRUE)
1715			rv = 1;
1716	}
1717
1718out:
1719	fnvlist_free(cb.cb_batchedsnaps);
1720	fnvlist_free(cb.cb_nvl);
1721	if (zhp != NULL)
1722		zfs_close(zhp);
1723	return (rv);
1724}
1725
1726static boolean_t
1727is_recvd_column(zprop_get_cbdata_t *cbp)
1728{
1729	int i;
1730	zfs_get_column_t col;
1731
1732	for (i = 0; i < ZFS_GET_NCOLS &&
1733	    (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1734		if (col == GET_COL_RECVD)
1735			return (B_TRUE);
1736	return (B_FALSE);
1737}
1738
1739/*
1740 * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1741 *	< all | property[,property]... > < fs | snap | vol > ...
1742 *
1743 *	-r	recurse over any child datasets
1744 *	-H	scripted mode.  Headers are stripped, and fields are separated
1745 *		by tabs instead of spaces.
1746 *	-o	Set of fields to display.  One of "name,property,value,
1747 *		received,source". Default is "name,property,value,source".
1748 *		"all" is an alias for all five.
1749 *	-s	Set of sources to allow.  One of
1750 *		"local,default,inherited,received,temporary,none".  Default is
1751 *		all six.
1752 *	-p	Display values in parsable (literal) format.
1753 *
1754 *  Prints properties for the given datasets.  The user can control which
1755 *  columns to display as well as which property types to allow.
1756 */
1757
1758/*
1759 * Invoked to display the properties for a single dataset.
1760 */
1761static int
1762get_callback(zfs_handle_t *zhp, void *data)
1763{
1764	char buf[ZFS_MAXPROPLEN];
1765	char rbuf[ZFS_MAXPROPLEN];
1766	zprop_source_t sourcetype;
1767	char source[ZFS_MAX_DATASET_NAME_LEN];
1768	zprop_get_cbdata_t *cbp = data;
1769	nvlist_t *user_props = zfs_get_user_props(zhp);
1770	zprop_list_t *pl = cbp->cb_proplist;
1771	nvlist_t *propval;
1772	char *strval;
1773	char *sourceval;
1774	boolean_t received = is_recvd_column(cbp);
1775
1776	for (; pl != NULL; pl = pl->pl_next) {
1777		char *recvdval = NULL;
1778		/*
1779		 * Skip the special fake placeholder.  This will also skip over
1780		 * the name property when 'all' is specified.
1781		 */
1782		if (pl->pl_prop == ZFS_PROP_NAME &&
1783		    pl == cbp->cb_proplist)
1784			continue;
1785
1786		if (pl->pl_prop != ZPROP_INVAL) {
1787			if (zfs_prop_get(zhp, pl->pl_prop, buf,
1788			    sizeof (buf), &sourcetype, source,
1789			    sizeof (source),
1790			    cbp->cb_literal) != 0) {
1791				if (pl->pl_all)
1792					continue;
1793				if (!zfs_prop_valid_for_type(pl->pl_prop,
1794				    ZFS_TYPE_DATASET, B_FALSE)) {
1795					(void) fprintf(stderr,
1796					    gettext("No such property '%s'\n"),
1797					    zfs_prop_to_name(pl->pl_prop));
1798					continue;
1799				}
1800				sourcetype = ZPROP_SRC_NONE;
1801				(void) strlcpy(buf, "-", sizeof (buf));
1802			}
1803
1804			if (received && (zfs_prop_get_recvd(zhp,
1805			    zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1806			    cbp->cb_literal) == 0))
1807				recvdval = rbuf;
1808
1809			zprop_print_one_property(zfs_get_name(zhp), cbp,
1810			    zfs_prop_to_name(pl->pl_prop),
1811			    buf, sourcetype, source, recvdval);
1812		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
1813			sourcetype = ZPROP_SRC_LOCAL;
1814
1815			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1816			    buf, sizeof (buf), cbp->cb_literal) != 0) {
1817				sourcetype = ZPROP_SRC_NONE;
1818				(void) strlcpy(buf, "-", sizeof (buf));
1819			}
1820
1821			zprop_print_one_property(zfs_get_name(zhp), cbp,
1822			    pl->pl_user_prop, buf, sourcetype, source, NULL);
1823		} else if (zfs_prop_written(pl->pl_user_prop)) {
1824			sourcetype = ZPROP_SRC_LOCAL;
1825
1826			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1827			    buf, sizeof (buf), cbp->cb_literal) != 0) {
1828				sourcetype = ZPROP_SRC_NONE;
1829				(void) strlcpy(buf, "-", sizeof (buf));
1830			}
1831
1832			zprop_print_one_property(zfs_get_name(zhp), cbp,
1833			    pl->pl_user_prop, buf, sourcetype, source, NULL);
1834		} else {
1835			if (nvlist_lookup_nvlist(user_props,
1836			    pl->pl_user_prop, &propval) != 0) {
1837				if (pl->pl_all)
1838					continue;
1839				sourcetype = ZPROP_SRC_NONE;
1840				strval = "-";
1841			} else {
1842				verify(nvlist_lookup_string(propval,
1843				    ZPROP_VALUE, &strval) == 0);
1844				verify(nvlist_lookup_string(propval,
1845				    ZPROP_SOURCE, &sourceval) == 0);
1846
1847				if (strcmp(sourceval,
1848				    zfs_get_name(zhp)) == 0) {
1849					sourcetype = ZPROP_SRC_LOCAL;
1850				} else if (strcmp(sourceval,
1851				    ZPROP_SOURCE_VAL_RECVD) == 0) {
1852					sourcetype = ZPROP_SRC_RECEIVED;
1853				} else {
1854					sourcetype = ZPROP_SRC_INHERITED;
1855					(void) strlcpy(source,
1856					    sourceval, sizeof (source));
1857				}
1858			}
1859
1860			if (received && (zfs_prop_get_recvd(zhp,
1861			    pl->pl_user_prop, rbuf, sizeof (rbuf),
1862			    cbp->cb_literal) == 0))
1863				recvdval = rbuf;
1864
1865			zprop_print_one_property(zfs_get_name(zhp), cbp,
1866			    pl->pl_user_prop, strval, sourcetype,
1867			    source, recvdval);
1868		}
1869	}
1870
1871	return (0);
1872}
1873
1874static int
1875zfs_do_get(int argc, char **argv)
1876{
1877	zprop_get_cbdata_t cb = { 0 };
1878	int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1879	int types = ZFS_TYPE_DATASET | ZFS_TYPE_BOOKMARK;
1880	char *value, *fields;
1881	int ret = 0;
1882	int limit = 0;
1883	zprop_list_t fake_name = { 0 };
1884
1885	/*
1886	 * Set up default columns and sources.
1887	 */
1888	cb.cb_sources = ZPROP_SRC_ALL;
1889	cb.cb_columns[0] = GET_COL_NAME;
1890	cb.cb_columns[1] = GET_COL_PROPERTY;
1891	cb.cb_columns[2] = GET_COL_VALUE;
1892	cb.cb_columns[3] = GET_COL_SOURCE;
1893	cb.cb_type = ZFS_TYPE_DATASET;
1894
1895	/* check options */
1896	while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1897		switch (c) {
1898		case 'p':
1899			cb.cb_literal = B_TRUE;
1900			break;
1901		case 'd':
1902			limit = parse_depth(optarg, &flags);
1903			break;
1904		case 'r':
1905			flags |= ZFS_ITER_RECURSE;
1906			break;
1907		case 'H':
1908			cb.cb_scripted = B_TRUE;
1909			break;
1910		case ':':
1911			(void) fprintf(stderr, gettext("missing argument for "
1912			    "'%c' option\n"), optopt);
1913			usage(B_FALSE);
1914			break;
1915		case 'o':
1916			/*
1917			 * Process the set of columns to display.  We zero out
1918			 * the structure to give us a blank slate.
1919			 */
1920			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1921			i = 0;
1922			while (*optarg != '\0') {
1923				static char *col_subopts[] =
1924				    { "name", "property", "value", "received",
1925				    "source", "all", NULL };
1926
1927				if (i == ZFS_GET_NCOLS) {
1928					(void) fprintf(stderr, gettext("too "
1929					    "many fields given to -o "
1930					    "option\n"));
1931					usage(B_FALSE);
1932				}
1933
1934				switch (getsubopt(&optarg, col_subopts,
1935				    &value)) {
1936				case 0:
1937					cb.cb_columns[i++] = GET_COL_NAME;
1938					break;
1939				case 1:
1940					cb.cb_columns[i++] = GET_COL_PROPERTY;
1941					break;
1942				case 2:
1943					cb.cb_columns[i++] = GET_COL_VALUE;
1944					break;
1945				case 3:
1946					cb.cb_columns[i++] = GET_COL_RECVD;
1947					flags |= ZFS_ITER_RECVD_PROPS;
1948					break;
1949				case 4:
1950					cb.cb_columns[i++] = GET_COL_SOURCE;
1951					break;
1952				case 5:
1953					if (i > 0) {
1954						(void) fprintf(stderr,
1955						    gettext("\"all\" conflicts "
1956						    "with specific fields "
1957						    "given to -o option\n"));
1958						usage(B_FALSE);
1959					}
1960					cb.cb_columns[0] = GET_COL_NAME;
1961					cb.cb_columns[1] = GET_COL_PROPERTY;
1962					cb.cb_columns[2] = GET_COL_VALUE;
1963					cb.cb_columns[3] = GET_COL_RECVD;
1964					cb.cb_columns[4] = GET_COL_SOURCE;
1965					flags |= ZFS_ITER_RECVD_PROPS;
1966					i = ZFS_GET_NCOLS;
1967					break;
1968				default:
1969					(void) fprintf(stderr,
1970					    gettext("invalid column name "
1971					    "'%s'\n"), value);
1972					usage(B_FALSE);
1973				}
1974			}
1975			break;
1976
1977		case 's':
1978			cb.cb_sources = 0;
1979			while (*optarg != '\0') {
1980				static char *source_subopts[] = {
1981					"local", "default", "inherited",
1982					"received", "temporary", "none",
1983					NULL };
1984
1985				switch (getsubopt(&optarg, source_subopts,
1986				    &value)) {
1987				case 0:
1988					cb.cb_sources |= ZPROP_SRC_LOCAL;
1989					break;
1990				case 1:
1991					cb.cb_sources |= ZPROP_SRC_DEFAULT;
1992					break;
1993				case 2:
1994					cb.cb_sources |= ZPROP_SRC_INHERITED;
1995					break;
1996				case 3:
1997					cb.cb_sources |= ZPROP_SRC_RECEIVED;
1998					break;
1999				case 4:
2000					cb.cb_sources |= ZPROP_SRC_TEMPORARY;
2001					break;
2002				case 5:
2003					cb.cb_sources |= ZPROP_SRC_NONE;
2004					break;
2005				default:
2006					(void) fprintf(stderr,
2007					    gettext("invalid source "
2008					    "'%s'\n"), value);
2009					usage(B_FALSE);
2010				}
2011			}
2012			break;
2013
2014		case 't':
2015			types = 0;
2016			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2017			while (*optarg != '\0') {
2018				static char *type_subopts[] = { "filesystem",
2019				    "volume", "snapshot", "snap", "bookmark",
2020				    "all", NULL };
2021
2022				switch (getsubopt(&optarg, type_subopts,
2023				    &value)) {
2024				case 0:
2025					types |= ZFS_TYPE_FILESYSTEM;
2026					break;
2027				case 1:
2028					types |= ZFS_TYPE_VOLUME;
2029					break;
2030				case 2:
2031				case 3:
2032					types |= ZFS_TYPE_SNAPSHOT;
2033					break;
2034				case 4:
2035					types |= ZFS_TYPE_BOOKMARK;
2036					break;
2037				case 5:
2038					types = ZFS_TYPE_DATASET |
2039					    ZFS_TYPE_BOOKMARK;
2040					break;
2041
2042				default:
2043					(void) fprintf(stderr,
2044					    gettext("invalid type '%s'\n"),
2045					    value);
2046					usage(B_FALSE);
2047				}
2048			}
2049			break;
2050
2051		case '?':
2052			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2053			    optopt);
2054			usage(B_FALSE);
2055		}
2056	}
2057
2058	argc -= optind;
2059	argv += optind;
2060
2061	if (argc < 1) {
2062		(void) fprintf(stderr, gettext("missing property "
2063		    "argument\n"));
2064		usage(B_FALSE);
2065	}
2066
2067	fields = argv[0];
2068
2069	/*
2070	 * Handle users who want to get all snapshots or bookmarks
2071	 * of a dataset (ex. 'zfs get -t snapshot refer <dataset>').
2072	 */
2073	if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
2074	    argc > 1 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
2075		flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
2076		limit = 1;
2077	}
2078
2079	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
2080	    != 0)
2081		usage(B_FALSE);
2082
2083	argc--;
2084	argv++;
2085
2086	/*
2087	 * As part of zfs_expand_proplist(), we keep track of the maximum column
2088	 * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
2089	 * need to know the maximum name length.  However, the user likely did
2090	 * not specify 'name' as one of the properties to fetch, so we need to
2091	 * make sure we always include at least this property for
2092	 * print_get_headers() to work properly.
2093	 */
2094	if (cb.cb_proplist != NULL) {
2095		fake_name.pl_prop = ZFS_PROP_NAME;
2096		fake_name.pl_width = strlen(gettext("NAME"));
2097		fake_name.pl_next = cb.cb_proplist;
2098		cb.cb_proplist = &fake_name;
2099	}
2100
2101	cb.cb_first = B_TRUE;
2102
2103	/* run for each object */
2104	ret = zfs_for_each(argc, argv, flags, types, NULL,
2105	    &cb.cb_proplist, limit, get_callback, &cb);
2106
2107	if (cb.cb_proplist == &fake_name)
2108		zprop_free_list(fake_name.pl_next);
2109	else
2110		zprop_free_list(cb.cb_proplist);
2111
2112	return (ret);
2113}
2114
2115/*
2116 * inherit [-rS] <property> <fs|vol> ...
2117 *
2118 *	-r	Recurse over all children
2119 *	-S	Revert to received value, if any
2120 *
2121 * For each dataset specified on the command line, inherit the given property
2122 * from its parent.  Inheriting a property at the pool level will cause it to
2123 * use the default value.  The '-r' flag will recurse over all children, and is
2124 * useful for setting a property on a hierarchy-wide basis, regardless of any
2125 * local modifications for each dataset.
2126 */
2127
2128typedef struct inherit_cbdata {
2129	const char *cb_propname;
2130	boolean_t cb_received;
2131} inherit_cbdata_t;
2132
2133static int
2134inherit_recurse_cb(zfs_handle_t *zhp, void *data)
2135{
2136	inherit_cbdata_t *cb = data;
2137	zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
2138
2139	/*
2140	 * If we're doing it recursively, then ignore properties that
2141	 * are not valid for this type of dataset.
2142	 */
2143	if (prop != ZPROP_INVAL &&
2144	    !zfs_prop_valid_for_type(prop, zfs_get_type(zhp), B_FALSE))
2145		return (0);
2146
2147	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2148}
2149
2150static int
2151inherit_cb(zfs_handle_t *zhp, void *data)
2152{
2153	inherit_cbdata_t *cb = data;
2154
2155	return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
2156}
2157
2158static int
2159zfs_do_inherit(int argc, char **argv)
2160{
2161	int c;
2162	zfs_prop_t prop;
2163	inherit_cbdata_t cb = { 0 };
2164	char *propname;
2165	int ret = 0;
2166	int flags = 0;
2167	boolean_t received = B_FALSE;
2168
2169	/* check options */
2170	while ((c = getopt(argc, argv, "rS")) != -1) {
2171		switch (c) {
2172		case 'r':
2173			flags |= ZFS_ITER_RECURSE;
2174			break;
2175		case 'S':
2176			received = B_TRUE;
2177			break;
2178		case '?':
2179		default:
2180			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2181			    optopt);
2182			usage(B_FALSE);
2183		}
2184	}
2185
2186	argc -= optind;
2187	argv += optind;
2188
2189	/* check number of arguments */
2190	if (argc < 1) {
2191		(void) fprintf(stderr, gettext("missing property argument\n"));
2192		usage(B_FALSE);
2193	}
2194	if (argc < 2) {
2195		(void) fprintf(stderr, gettext("missing dataset argument\n"));
2196		usage(B_FALSE);
2197	}
2198
2199	propname = argv[0];
2200	argc--;
2201	argv++;
2202
2203	if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
2204		if (zfs_prop_readonly(prop)) {
2205			(void) fprintf(stderr, gettext(
2206			    "%s property is read-only\n"),
2207			    propname);
2208			return (1);
2209		}
2210		if (!zfs_prop_inheritable(prop) && !received) {
2211			(void) fprintf(stderr, gettext("'%s' property cannot "
2212			    "be inherited\n"), propname);
2213			if (prop == ZFS_PROP_QUOTA ||
2214			    prop == ZFS_PROP_RESERVATION ||
2215			    prop == ZFS_PROP_REFQUOTA ||
2216			    prop == ZFS_PROP_REFRESERVATION) {
2217				(void) fprintf(stderr, gettext("use 'zfs set "
2218				    "%s=none' to clear\n"), propname);
2219				(void) fprintf(stderr, gettext("use 'zfs "
2220				    "inherit -S %s' to revert to received "
2221				    "value\n"), propname);
2222			}
2223			return (1);
2224		}
2225		if (received && (prop == ZFS_PROP_VOLSIZE ||
2226		    prop == ZFS_PROP_VERSION)) {
2227			(void) fprintf(stderr, gettext("'%s' property cannot "
2228			    "be reverted to a received value\n"), propname);
2229			return (1);
2230		}
2231	} else if (!zfs_prop_user(propname)) {
2232		(void) fprintf(stderr, gettext("invalid property '%s'\n"),
2233		    propname);
2234		usage(B_FALSE);
2235	}
2236
2237	cb.cb_propname = propname;
2238	cb.cb_received = received;
2239
2240	if (flags & ZFS_ITER_RECURSE) {
2241		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2242		    NULL, NULL, 0, inherit_recurse_cb, &cb);
2243	} else {
2244		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
2245		    NULL, NULL, 0, inherit_cb, &cb);
2246	}
2247
2248	return (ret);
2249}
2250
2251typedef struct upgrade_cbdata {
2252	uint64_t cb_numupgraded;
2253	uint64_t cb_numsamegraded;
2254	uint64_t cb_numfailed;
2255	uint64_t cb_version;
2256	boolean_t cb_newer;
2257	boolean_t cb_foundone;
2258	char cb_lastfs[ZFS_MAX_DATASET_NAME_LEN];
2259} upgrade_cbdata_t;
2260
2261static int
2262same_pool(zfs_handle_t *zhp, const char *name)
2263{
2264	int len1 = strcspn(name, "/@");
2265	const char *zhname = zfs_get_name(zhp);
2266	int len2 = strcspn(zhname, "/@");
2267
2268	if (len1 != len2)
2269		return (B_FALSE);
2270	return (strncmp(name, zhname, len1) == 0);
2271}
2272
2273static int
2274upgrade_list_callback(zfs_handle_t *zhp, void *data)
2275{
2276	upgrade_cbdata_t *cb = data;
2277	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2278
2279	/* list if it's old/new */
2280	if ((!cb->cb_newer && version < ZPL_VERSION) ||
2281	    (cb->cb_newer && version > ZPL_VERSION)) {
2282		char *str;
2283		if (cb->cb_newer) {
2284			str = gettext("The following filesystems are "
2285			    "formatted using a newer software version and\n"
2286			    "cannot be accessed on the current system.\n\n");
2287		} else {
2288			str = gettext("The following filesystems are "
2289			    "out of date, and can be upgraded.  After being\n"
2290			    "upgraded, these filesystems (and any 'zfs send' "
2291			    "streams generated from\n"
2292			    "subsequent snapshots) will no longer be "
2293			    "accessible by older software versions.\n\n");
2294		}
2295
2296		if (!cb->cb_foundone) {
2297			(void) puts(str);
2298			(void) printf(gettext("VER  FILESYSTEM\n"));
2299			(void) printf(gettext("---  ------------\n"));
2300			cb->cb_foundone = B_TRUE;
2301		}
2302
2303		(void) printf("%2u   %s\n", version, zfs_get_name(zhp));
2304	}
2305
2306	return (0);
2307}
2308
2309static int
2310upgrade_set_callback(zfs_handle_t *zhp, void *data)
2311{
2312	upgrade_cbdata_t *cb = data;
2313	int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
2314	int needed_spa_version;
2315	int spa_version;
2316
2317	if (zfs_spa_version(zhp, &spa_version) < 0)
2318		return (-1);
2319
2320	needed_spa_version = zfs_spa_version_map(cb->cb_version);
2321
2322	if (needed_spa_version < 0)
2323		return (-1);
2324
2325	if (spa_version < needed_spa_version) {
2326		/* can't upgrade */
2327		(void) printf(gettext("%s: can not be "
2328		    "upgraded; the pool version needs to first "
2329		    "be upgraded\nto version %d\n\n"),
2330		    zfs_get_name(zhp), needed_spa_version);
2331		cb->cb_numfailed++;
2332		return (0);
2333	}
2334
2335	/* upgrade */
2336	if (version < cb->cb_version) {
2337		char verstr[16];
2338		(void) snprintf(verstr, sizeof (verstr),
2339		    "%llu", (u_longlong_t)cb->cb_version);
2340		if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
2341			/*
2342			 * If they did "zfs upgrade -a", then we could
2343			 * be doing ioctls to different pools.  We need
2344			 * to log this history once to each pool, and bypass
2345			 * the normal history logging that happens in main().
2346			 */
2347			(void) zpool_log_history(g_zfs, history_str);
2348			log_history = B_FALSE;
2349		}
2350		if (zfs_prop_set(zhp, "version", verstr) == 0)
2351			cb->cb_numupgraded++;
2352		else
2353			cb->cb_numfailed++;
2354		(void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
2355	} else if (version > cb->cb_version) {
2356		/* can't downgrade */
2357		(void) printf(gettext("%s: can not be downgraded; "
2358		    "it is already at version %u\n"),
2359		    zfs_get_name(zhp), version);
2360		cb->cb_numfailed++;
2361	} else {
2362		cb->cb_numsamegraded++;
2363	}
2364	return (0);
2365}
2366
2367/*
2368 * zfs upgrade
2369 * zfs upgrade -v
2370 * zfs upgrade [-r] [-V <version>] <-a | filesystem>
2371 */
2372static int
2373zfs_do_upgrade(int argc, char **argv)
2374{
2375	boolean_t all = B_FALSE;
2376	boolean_t showversions = B_FALSE;
2377	int ret = 0;
2378	upgrade_cbdata_t cb = { 0 };
2379	int c;
2380	int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
2381
2382	/* check options */
2383	while ((c = getopt(argc, argv, "rvV:a")) != -1) {
2384		switch (c) {
2385		case 'r':
2386			flags |= ZFS_ITER_RECURSE;
2387			break;
2388		case 'v':
2389			showversions = B_TRUE;
2390			break;
2391		case 'V':
2392			if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
2393			    optarg, &cb.cb_version) != 0) {
2394				(void) fprintf(stderr,
2395				    gettext("invalid version %s\n"), optarg);
2396				usage(B_FALSE);
2397			}
2398			break;
2399		case 'a':
2400			all = B_TRUE;
2401			break;
2402		case '?':
2403		default:
2404			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2405			    optopt);
2406			usage(B_FALSE);
2407		}
2408	}
2409
2410	argc -= optind;
2411	argv += optind;
2412
2413	if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
2414		usage(B_FALSE);
2415	if (showversions && (flags & ZFS_ITER_RECURSE || all ||
2416	    cb.cb_version || argc))
2417		usage(B_FALSE);
2418	if ((all || argc) && (showversions))
2419		usage(B_FALSE);
2420	if (all && argc)
2421		usage(B_FALSE);
2422
2423	if (showversions) {
2424		/* Show info on available versions. */
2425		(void) printf(gettext("The following filesystem versions are "
2426		    "supported:\n\n"));
2427		(void) printf(gettext("VER  DESCRIPTION\n"));
2428		(void) printf("---  -----------------------------------------"
2429		    "---------------\n");
2430		(void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
2431		(void) printf(gettext(" 2   Enhanced directory entries\n"));
2432		(void) printf(gettext(" 3   Case insensitive and filesystem "
2433		    "user identifier (FUID)\n"));
2434		(void) printf(gettext(" 4   userquota, groupquota "
2435		    "properties\n"));
2436		(void) printf(gettext(" 5   System attributes\n"));
2437		(void) printf(gettext("\nFor more information on a particular "
2438		    "version, including supported releases,\n"));
2439		(void) printf("see the ZFS Administration Guide.\n\n");
2440		ret = 0;
2441	} else if (argc || all) {
2442		/* Upgrade filesystems */
2443		if (cb.cb_version == 0)
2444			cb.cb_version = ZPL_VERSION;
2445		ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2446		    NULL, NULL, 0, upgrade_set_callback, &cb);
2447		(void) printf(gettext("%llu filesystems upgraded\n"),
2448		    (u_longlong_t)cb.cb_numupgraded);
2449		if (cb.cb_numsamegraded) {
2450			(void) printf(gettext("%llu filesystems already at "
2451			    "this version\n"),
2452			    (u_longlong_t)cb.cb_numsamegraded);
2453		}
2454		if (cb.cb_numfailed != 0)
2455			ret = 1;
2456	} else {
2457		/* List old-version filesystems */
2458		boolean_t found;
2459		(void) printf(gettext("This system is currently running "
2460		    "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2461
2462		flags |= ZFS_ITER_RECURSE;
2463		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2464		    NULL, NULL, 0, upgrade_list_callback, &cb);
2465
2466		found = cb.cb_foundone;
2467		cb.cb_foundone = B_FALSE;
2468		cb.cb_newer = B_TRUE;
2469
2470		ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2471		    NULL, NULL, 0, upgrade_list_callback, &cb);
2472
2473		if (!cb.cb_foundone && !found) {
2474			(void) printf(gettext("All filesystems are "
2475			    "formatted with the current version.\n"));
2476		}
2477	}
2478
2479	return (ret);
2480}
2481
2482/*
2483 * zfs userspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2484 *               [-S field [-S field]...] [-t type[,...]]
2485 *               filesystem | snapshot | path
2486 * zfs groupspace [-Hinp] [-o field[,...]] [-s field [-s field]...]
2487 *                [-S field [-S field]...] [-t type[,...]]
2488 *                filesystem | snapshot | path
2489 * zfs projectspace [-Hp] [-o field[,...]] [-s field [-s field]...]
2490 *                [-S field [-S field]...] filesystem | snapshot | path
2491 *
2492 *	-H      Scripted mode; elide headers and separate columns by tabs.
2493 *	-i	Translate SID to POSIX ID.
2494 *	-n	Print numeric ID instead of user/group name.
2495 *	-o      Control which fields to display.
2496 *	-p	Use exact (parsable) numeric output.
2497 *	-s      Specify sort columns, descending order.
2498 *	-S      Specify sort columns, ascending order.
2499 *	-t      Control which object types to display.
2500 *
2501 *	Displays space consumed by, and quotas on, each user in the specified
2502 *	filesystem or snapshot.
2503 */
2504
2505/* us_field_types, us_field_hdr and us_field_names should be kept in sync */
2506enum us_field_types {
2507	USFIELD_TYPE,
2508	USFIELD_NAME,
2509	USFIELD_USED,
2510	USFIELD_QUOTA,
2511	USFIELD_OBJUSED,
2512	USFIELD_OBJQUOTA
2513};
2514static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA",
2515				    "OBJUSED", "OBJQUOTA" };
2516static char *us_field_names[] = { "type", "name", "used", "quota",
2517				    "objused", "objquota" };
2518#define	USFIELD_LAST	(sizeof (us_field_names) / sizeof (char *))
2519
2520#define	USTYPE_PSX_GRP	(1 << 0)
2521#define	USTYPE_PSX_USR	(1 << 1)
2522#define	USTYPE_SMB_GRP	(1 << 2)
2523#define	USTYPE_SMB_USR	(1 << 3)
2524#define	USTYPE_PROJ	(1 << 4)
2525#define	USTYPE_ALL	\
2526	(USTYPE_PSX_GRP | USTYPE_PSX_USR | USTYPE_SMB_GRP | USTYPE_SMB_USR | \
2527	    USTYPE_PROJ)
2528
2529static int us_type_bits[] = {
2530	USTYPE_PSX_GRP,
2531	USTYPE_PSX_USR,
2532	USTYPE_SMB_GRP,
2533	USTYPE_SMB_USR,
2534	USTYPE_ALL
2535};
2536static char *us_type_names[] = { "posixgroup", "posixuser", "smbgroup",
2537	"smbuser", "all" };
2538
2539typedef struct us_node {
2540	nvlist_t	*usn_nvl;
2541	uu_avl_node_t	usn_avlnode;
2542	uu_list_node_t	usn_listnode;
2543} us_node_t;
2544
2545typedef struct us_cbdata {
2546	nvlist_t	**cb_nvlp;
2547	uu_avl_pool_t	*cb_avl_pool;
2548	uu_avl_t	*cb_avl;
2549	boolean_t	cb_numname;
2550	boolean_t	cb_nicenum;
2551	boolean_t	cb_sid2posix;
2552	zfs_userquota_prop_t cb_prop;
2553	zfs_sort_column_t *cb_sortcol;
2554	size_t		cb_width[USFIELD_LAST];
2555} us_cbdata_t;
2556
2557static boolean_t us_populated = B_FALSE;
2558
2559typedef struct {
2560	zfs_sort_column_t *si_sortcol;
2561	boolean_t	si_numname;
2562} us_sort_info_t;
2563
2564static int
2565us_field_index(char *field)
2566{
2567	int i;
2568
2569	for (i = 0; i < USFIELD_LAST; i++) {
2570		if (strcmp(field, us_field_names[i]) == 0)
2571			return (i);
2572	}
2573
2574	return (-1);
2575}
2576
2577static int
2578us_compare(const void *larg, const void *rarg, void *unused)
2579{
2580	const us_node_t *l = larg;
2581	const us_node_t *r = rarg;
2582	us_sort_info_t *si = (us_sort_info_t *)unused;
2583	zfs_sort_column_t *sortcol = si->si_sortcol;
2584	boolean_t numname = si->si_numname;
2585	nvlist_t *lnvl = l->usn_nvl;
2586	nvlist_t *rnvl = r->usn_nvl;
2587	int rc = 0;
2588	boolean_t lvb, rvb;
2589
2590	for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2591		char *lvstr = "";
2592		char *rvstr = "";
2593		uint32_t lv32 = 0;
2594		uint32_t rv32 = 0;
2595		uint64_t lv64 = 0;
2596		uint64_t rv64 = 0;
2597		zfs_prop_t prop = sortcol->sc_prop;
2598		const char *propname = NULL;
2599		boolean_t reverse = sortcol->sc_reverse;
2600
2601		switch (prop) {
2602		case ZFS_PROP_TYPE:
2603			propname = "type";
2604			(void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2605			(void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2606			if (rv32 != lv32)
2607				rc = (rv32 < lv32) ? 1 : -1;
2608			break;
2609		case ZFS_PROP_NAME:
2610			propname = "name";
2611			if (numname) {
2612compare_nums:
2613				(void) nvlist_lookup_uint64(lnvl, propname,
2614				    &lv64);
2615				(void) nvlist_lookup_uint64(rnvl, propname,
2616				    &rv64);
2617				if (rv64 != lv64)
2618					rc = (rv64 < lv64) ? 1 : -1;
2619			} else {
2620				if ((nvlist_lookup_string(lnvl, propname,
2621				    &lvstr) == ENOENT) ||
2622				    (nvlist_lookup_string(rnvl, propname,
2623				    &rvstr) == ENOENT)) {
2624					goto compare_nums;
2625				}
2626				rc = strcmp(lvstr, rvstr);
2627			}
2628			break;
2629		case ZFS_PROP_USED:
2630		case ZFS_PROP_QUOTA:
2631			if (!us_populated)
2632				break;
2633			if (prop == ZFS_PROP_USED)
2634				propname = "used";
2635			else
2636				propname = "quota";
2637			(void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2638			(void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2639			if (rv64 != lv64)
2640				rc = (rv64 < lv64) ? 1 : -1;
2641			break;
2642
2643		default:
2644			break;
2645		}
2646
2647		if (rc != 0) {
2648			if (rc < 0)
2649				return (reverse ? 1 : -1);
2650			else
2651				return (reverse ? -1 : 1);
2652		}
2653	}
2654
2655	/*
2656	 * If entries still seem to be the same, check if they are of the same
2657	 * type (smbentity is added only if we are doing SID to POSIX ID
2658	 * translation where we can have duplicate type/name combinations).
2659	 */
2660	if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2661	    nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2662	    lvb != rvb)
2663		return (lvb < rvb ? -1 : 1);
2664
2665	return (0);
2666}
2667
2668static boolean_t
2669zfs_prop_is_user(unsigned p)
2670{
2671	return (p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA ||
2672	    p == ZFS_PROP_USEROBJUSED || p == ZFS_PROP_USEROBJQUOTA);
2673}
2674
2675static boolean_t
2676zfs_prop_is_group(unsigned p)
2677{
2678	return (p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA ||
2679	    p == ZFS_PROP_GROUPOBJUSED || p == ZFS_PROP_GROUPOBJQUOTA);
2680}
2681
2682static boolean_t
2683zfs_prop_is_project(unsigned p)
2684{
2685	return (p == ZFS_PROP_PROJECTUSED || p == ZFS_PROP_PROJECTQUOTA ||
2686	    p == ZFS_PROP_PROJECTOBJUSED || p == ZFS_PROP_PROJECTOBJQUOTA);
2687}
2688
2689static inline const char *
2690us_type2str(unsigned field_type)
2691{
2692	switch (field_type) {
2693	case USTYPE_PSX_USR:
2694		return ("POSIX User");
2695	case USTYPE_PSX_GRP:
2696		return ("POSIX Group");
2697	case USTYPE_SMB_USR:
2698		return ("SMB User");
2699	case USTYPE_SMB_GRP:
2700		return ("SMB Group");
2701	case USTYPE_PROJ:
2702		return ("Project");
2703	default:
2704		return ("Undefined");
2705	}
2706}
2707
2708static int
2709userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2710{
2711	us_cbdata_t *cb = (us_cbdata_t *)arg;
2712	zfs_userquota_prop_t prop = cb->cb_prop;
2713	char *name = NULL;
2714	char *propname;
2715	char sizebuf[32];
2716	us_node_t *node;
2717	uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2718	uu_avl_t *avl = cb->cb_avl;
2719	uu_avl_index_t idx;
2720	nvlist_t *props;
2721	us_node_t *n;
2722	zfs_sort_column_t *sortcol = cb->cb_sortcol;
2723	unsigned type = 0;
2724	const char *typestr;
2725	size_t namelen;
2726	size_t typelen;
2727	size_t sizelen;
2728	int typeidx, nameidx, sizeidx;
2729	us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2730	boolean_t smbentity = B_FALSE;
2731
2732	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2733		nomem();
2734	node = safe_malloc(sizeof (us_node_t));
2735	uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2736	node->usn_nvl = props;
2737
2738	if (domain != NULL && domain[0] != '\0') {
2739#ifdef HAVE_IDMAP
2740		/* SMB */
2741		char sid[MAXNAMELEN + 32];
2742		uid_t id;
2743		uint64_t classes;
2744		int err;
2745		directory_error_t e;
2746
2747		smbentity = B_TRUE;
2748
2749		(void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2750
2751		if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2752			type = USTYPE_SMB_GRP;
2753			err = sid_to_id(sid, B_FALSE, &id);
2754		} else {
2755			type = USTYPE_SMB_USR;
2756			err = sid_to_id(sid, B_TRUE, &id);
2757		}
2758
2759		if (err == 0) {
2760			rid = id;
2761			if (!cb->cb_sid2posix) {
2762				e = directory_name_from_sid(NULL, sid, &name,
2763				    &classes);
2764				if (e != NULL)
2765					directory_error_free(e);
2766				if (name == NULL)
2767					name = sid;
2768			}
2769		}
2770#else
2771		nvlist_free(props);
2772		free(node);
2773
2774		return (-1);
2775#endif /* HAVE_IDMAP */
2776	}
2777
2778	if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2779		/* POSIX or -i */
2780		if (zfs_prop_is_group(prop)) {
2781			type = USTYPE_PSX_GRP;
2782			if (!cb->cb_numname) {
2783				struct group *g;
2784
2785				if ((g = getgrgid(rid)) != NULL)
2786					name = g->gr_name;
2787			}
2788		} else if (zfs_prop_is_user(prop)) {
2789			type = USTYPE_PSX_USR;
2790			if (!cb->cb_numname) {
2791				struct passwd *p;
2792
2793				if ((p = getpwuid(rid)) != NULL)
2794					name = p->pw_name;
2795			}
2796		} else {
2797			type = USTYPE_PROJ;
2798		}
2799	}
2800
2801	/*
2802	 * Make sure that the type/name combination is unique when doing
2803	 * SID to POSIX ID translation (hence changing the type from SMB to
2804	 * POSIX).
2805	 */
2806	if (cb->cb_sid2posix &&
2807	    nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2808		nomem();
2809
2810	/* Calculate/update width of TYPE field */
2811	typestr = us_type2str(type);
2812	typelen = strlen(gettext(typestr));
2813	typeidx = us_field_index("type");
2814	if (typelen > cb->cb_width[typeidx])
2815		cb->cb_width[typeidx] = typelen;
2816	if (nvlist_add_uint32(props, "type", type) != 0)
2817		nomem();
2818
2819	/* Calculate/update width of NAME field */
2820	if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2821		if (nvlist_add_uint64(props, "name", rid) != 0)
2822			nomem();
2823		namelen = snprintf(NULL, 0, "%u", rid);
2824	} else {
2825		if (nvlist_add_string(props, "name", name) != 0)
2826			nomem();
2827		namelen = strlen(name);
2828	}
2829	nameidx = us_field_index("name");
2830	if (nameidx >= 0 && namelen > cb->cb_width[nameidx])
2831		cb->cb_width[nameidx] = namelen;
2832
2833	/*
2834	 * Check if this type/name combination is in the list and update it;
2835	 * otherwise add new node to the list.
2836	 */
2837	if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2838		uu_avl_insert(avl, node, idx);
2839	} else {
2840		nvlist_free(props);
2841		free(node);
2842		node = n;
2843		props = node->usn_nvl;
2844	}
2845
2846	/* Calculate/update width of USED/QUOTA fields */
2847	if (cb->cb_nicenum) {
2848		if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
2849		    prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
2850		    prop == ZFS_PROP_PROJECTUSED ||
2851		    prop == ZFS_PROP_PROJECTQUOTA) {
2852			zfs_nicebytes(space, sizebuf, sizeof (sizebuf));
2853		} else {
2854			zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2855		}
2856	} else {
2857		(void) snprintf(sizebuf, sizeof (sizebuf), "%llu",
2858		    (u_longlong_t)space);
2859	}
2860	sizelen = strlen(sizebuf);
2861	if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED ||
2862	    prop == ZFS_PROP_PROJECTUSED) {
2863		propname = "used";
2864		if (!nvlist_exists(props, "quota"))
2865			(void) nvlist_add_uint64(props, "quota", 0);
2866	} else if (prop == ZFS_PROP_USERQUOTA || prop == ZFS_PROP_GROUPQUOTA ||
2867	    prop == ZFS_PROP_PROJECTQUOTA) {
2868		propname = "quota";
2869		if (!nvlist_exists(props, "used"))
2870			(void) nvlist_add_uint64(props, "used", 0);
2871	} else if (prop == ZFS_PROP_USEROBJUSED ||
2872	    prop == ZFS_PROP_GROUPOBJUSED || prop == ZFS_PROP_PROJECTOBJUSED) {
2873		propname = "objused";
2874		if (!nvlist_exists(props, "objquota"))
2875			(void) nvlist_add_uint64(props, "objquota", 0);
2876	} else if (prop == ZFS_PROP_USEROBJQUOTA ||
2877	    prop == ZFS_PROP_GROUPOBJQUOTA ||
2878	    prop == ZFS_PROP_PROJECTOBJQUOTA) {
2879		propname = "objquota";
2880		if (!nvlist_exists(props, "objused"))
2881			(void) nvlist_add_uint64(props, "objused", 0);
2882	} else {
2883		return (-1);
2884	}
2885	sizeidx = us_field_index(propname);
2886	if (sizeidx >= 0 && sizelen > cb->cb_width[sizeidx])
2887		cb->cb_width[sizeidx] = sizelen;
2888
2889	if (nvlist_add_uint64(props, propname, space) != 0)
2890		nomem();
2891
2892	return (0);
2893}
2894
2895static void
2896print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2897    size_t *width, us_node_t *node)
2898{
2899	nvlist_t *nvl = node->usn_nvl;
2900	char valstr[MAXNAMELEN];
2901	boolean_t first = B_TRUE;
2902	int cfield = 0;
2903	int field;
2904	uint32_t ustype;
2905
2906	/* Check type */
2907	(void) nvlist_lookup_uint32(nvl, "type", &ustype);
2908	if (!(ustype & types))
2909		return;
2910
2911	while ((field = fields[cfield]) != USFIELD_LAST) {
2912		nvpair_t *nvp = NULL;
2913		data_type_t type;
2914		uint32_t val32;
2915		uint64_t val64;
2916		char *strval = "-";
2917
2918		while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2919			if (strcmp(nvpair_name(nvp),
2920			    us_field_names[field]) == 0)
2921				break;
2922		}
2923
2924		type = nvp == NULL ? DATA_TYPE_UNKNOWN : nvpair_type(nvp);
2925		switch (type) {
2926		case DATA_TYPE_UINT32:
2927			(void) nvpair_value_uint32(nvp, &val32);
2928			break;
2929		case DATA_TYPE_UINT64:
2930			(void) nvpair_value_uint64(nvp, &val64);
2931			break;
2932		case DATA_TYPE_STRING:
2933			(void) nvpair_value_string(nvp, &strval);
2934			break;
2935		case DATA_TYPE_UNKNOWN:
2936			break;
2937		default:
2938			(void) fprintf(stderr, "invalid data type\n");
2939		}
2940
2941		switch (field) {
2942		case USFIELD_TYPE:
2943			if (type == DATA_TYPE_UINT32)
2944				strval = (char *)us_type2str(val32);
2945			break;
2946		case USFIELD_NAME:
2947			if (type == DATA_TYPE_UINT64) {
2948				(void) sprintf(valstr, "%llu",
2949				    (u_longlong_t)val64);
2950				strval = valstr;
2951			}
2952			break;
2953		case USFIELD_USED:
2954		case USFIELD_QUOTA:
2955			if (type == DATA_TYPE_UINT64) {
2956				if (parsable) {
2957					(void) sprintf(valstr, "%llu",
2958					    (u_longlong_t)val64);
2959					strval = valstr;
2960				} else if (field == USFIELD_QUOTA &&
2961				    val64 == 0) {
2962					strval = "none";
2963				} else {
2964					zfs_nicebytes(val64, valstr,
2965					    sizeof (valstr));
2966					strval = valstr;
2967				}
2968			}
2969			break;
2970		case USFIELD_OBJUSED:
2971		case USFIELD_OBJQUOTA:
2972			if (type == DATA_TYPE_UINT64) {
2973				if (parsable) {
2974					(void) sprintf(valstr, "%llu",
2975					    (u_longlong_t)val64);
2976					strval = valstr;
2977				} else if (field == USFIELD_OBJQUOTA &&
2978				    val64 == 0) {
2979					strval = "none";
2980				} else {
2981					zfs_nicenum(val64, valstr,
2982					    sizeof (valstr));
2983					strval = valstr;
2984				}
2985			}
2986			break;
2987		}
2988
2989		if (!first) {
2990			if (scripted)
2991				(void) printf("\t");
2992			else
2993				(void) printf("  ");
2994		}
2995		if (scripted)
2996			(void) printf("%s", strval);
2997		else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2998			(void) printf("%-*s", (int)width[field], strval);
2999		else
3000			(void) printf("%*s", (int)width[field], strval);
3001
3002		first = B_FALSE;
3003		cfield++;
3004	}
3005
3006	(void) printf("\n");
3007}
3008
3009static void
3010print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
3011    size_t *width, boolean_t rmnode, uu_avl_t *avl)
3012{
3013	us_node_t *node;
3014	const char *col;
3015	int cfield = 0;
3016	int field;
3017
3018	if (!scripted) {
3019		boolean_t first = B_TRUE;
3020
3021		while ((field = fields[cfield]) != USFIELD_LAST) {
3022			col = gettext(us_field_hdr[field]);
3023			if (field == USFIELD_TYPE || field == USFIELD_NAME) {
3024				(void) printf(first ? "%-*s" : "  %-*s",
3025				    (int)width[field], col);
3026			} else {
3027				(void) printf(first ? "%*s" : "  %*s",
3028				    (int)width[field], col);
3029			}
3030			first = B_FALSE;
3031			cfield++;
3032		}
3033		(void) printf("\n");
3034	}
3035
3036	for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
3037		print_us_node(scripted, parsable, fields, types, width, node);
3038		if (rmnode)
3039			nvlist_free(node->usn_nvl);
3040	}
3041}
3042
3043static int
3044zfs_do_userspace(int argc, char **argv)
3045{
3046	zfs_handle_t *zhp;
3047	zfs_userquota_prop_t p;
3048	uu_avl_pool_t *avl_pool;
3049	uu_avl_t *avl_tree;
3050	uu_avl_walk_t *walk;
3051	char *delim;
3052	char deffields[] = "type,name,used,quota,objused,objquota";
3053	char *ofield = NULL;
3054	char *tfield = NULL;
3055	int cfield = 0;
3056	int fields[256];
3057	int i;
3058	boolean_t scripted = B_FALSE;
3059	boolean_t prtnum = B_FALSE;
3060	boolean_t parsable = B_FALSE;
3061	boolean_t sid2posix = B_FALSE;
3062	int ret = 0;
3063	int c;
3064	zfs_sort_column_t *sortcol = NULL;
3065	int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
3066	us_cbdata_t cb;
3067	us_node_t *node;
3068	us_node_t *rmnode;
3069	uu_list_pool_t *listpool;
3070	uu_list_t *list;
3071	uu_avl_index_t idx = 0;
3072	uu_list_index_t idx2 = 0;
3073
3074	if (argc < 2)
3075		usage(B_FALSE);
3076
3077	if (strcmp(argv[0], "groupspace") == 0) {
3078		/* Toggle default group types */
3079		types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
3080	} else if (strcmp(argv[0], "projectspace") == 0) {
3081		types = USTYPE_PROJ;
3082		prtnum = B_TRUE;
3083	}
3084
3085	while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
3086		switch (c) {
3087		case 'n':
3088			if (types == USTYPE_PROJ) {
3089				(void) fprintf(stderr,
3090				    gettext("invalid option 'n'\n"));
3091				usage(B_FALSE);
3092			}
3093			prtnum = B_TRUE;
3094			break;
3095		case 'H':
3096			scripted = B_TRUE;
3097			break;
3098		case 'p':
3099			parsable = B_TRUE;
3100			break;
3101		case 'o':
3102			ofield = optarg;
3103			break;
3104		case 's':
3105		case 'S':
3106			if (zfs_add_sort_column(&sortcol, optarg,
3107			    c == 's' ? B_FALSE : B_TRUE) != 0) {
3108				(void) fprintf(stderr,
3109				    gettext("invalid field '%s'\n"), optarg);
3110				usage(B_FALSE);
3111			}
3112			break;
3113		case 't':
3114			if (types == USTYPE_PROJ) {
3115				(void) fprintf(stderr,
3116				    gettext("invalid option 't'\n"));
3117				usage(B_FALSE);
3118			}
3119			tfield = optarg;
3120			break;
3121		case 'i':
3122			if (types == USTYPE_PROJ) {
3123				(void) fprintf(stderr,
3124				    gettext("invalid option 'i'\n"));
3125				usage(B_FALSE);
3126			}
3127			sid2posix = B_TRUE;
3128			break;
3129		case ':':
3130			(void) fprintf(stderr, gettext("missing argument for "
3131			    "'%c' option\n"), optopt);
3132			usage(B_FALSE);
3133			break;
3134		case '?':
3135			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3136			    optopt);
3137			usage(B_FALSE);
3138		}
3139	}
3140
3141	argc -= optind;
3142	argv += optind;
3143
3144	if (argc < 1) {
3145		(void) fprintf(stderr, gettext("missing dataset name\n"));
3146		usage(B_FALSE);
3147	}
3148	if (argc > 1) {
3149		(void) fprintf(stderr, gettext("too many arguments\n"));
3150		usage(B_FALSE);
3151	}
3152
3153	/* Use default output fields if not specified using -o */
3154	if (ofield == NULL)
3155		ofield = deffields;
3156	do {
3157		if ((delim = strchr(ofield, ',')) != NULL)
3158			*delim = '\0';
3159		if ((fields[cfield++] = us_field_index(ofield)) == -1) {
3160			(void) fprintf(stderr, gettext("invalid type '%s' "
3161			    "for -o option\n"), ofield);
3162			return (-1);
3163		}
3164		if (delim != NULL)
3165			ofield = delim + 1;
3166	} while (delim != NULL);
3167	fields[cfield] = USFIELD_LAST;
3168
3169	/* Override output types (-t option) */
3170	if (tfield != NULL) {
3171		types = 0;
3172
3173		do {
3174			boolean_t found = B_FALSE;
3175
3176			if ((delim = strchr(tfield, ',')) != NULL)
3177				*delim = '\0';
3178			for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
3179			    i++) {
3180				if (strcmp(tfield, us_type_names[i]) == 0) {
3181					found = B_TRUE;
3182					types |= us_type_bits[i];
3183					break;
3184				}
3185			}
3186			if (!found) {
3187				(void) fprintf(stderr, gettext("invalid type "
3188				    "'%s' for -t option\n"), tfield);
3189				return (-1);
3190			}
3191			if (delim != NULL)
3192				tfield = delim + 1;
3193		} while (delim != NULL);
3194	}
3195
3196	if ((zhp = zfs_path_to_zhandle(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM |
3197	    ZFS_TYPE_SNAPSHOT)) == NULL)
3198		return (1);
3199	if (zhp->zfs_head_type != ZFS_TYPE_FILESYSTEM) {
3200		(void) fprintf(stderr, gettext("operation is only applicable "
3201		    "to filesystems and their snapshots\n"));
3202		zfs_close(zhp);
3203		return (1);
3204	}
3205
3206	if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
3207	    offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
3208		nomem();
3209	if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
3210		nomem();
3211
3212	/* Always add default sorting columns */
3213	(void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
3214	(void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
3215
3216	cb.cb_sortcol = sortcol;
3217	cb.cb_numname = prtnum;
3218	cb.cb_nicenum = !parsable;
3219	cb.cb_avl_pool = avl_pool;
3220	cb.cb_avl = avl_tree;
3221	cb.cb_sid2posix = sid2posix;
3222
3223	for (i = 0; i < USFIELD_LAST; i++)
3224		cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
3225
3226	for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
3227		if ((zfs_prop_is_user(p) &&
3228		    !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
3229		    (zfs_prop_is_group(p) &&
3230		    !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))) ||
3231		    (zfs_prop_is_project(p) && types != USTYPE_PROJ))
3232			continue;
3233
3234		cb.cb_prop = p;
3235		if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0) {
3236			zfs_close(zhp);
3237			return (ret);
3238		}
3239	}
3240	zfs_close(zhp);
3241
3242	/* Sort the list */
3243	if ((node = uu_avl_first(avl_tree)) == NULL)
3244		return (0);
3245
3246	us_populated = B_TRUE;
3247
3248	listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
3249	    offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
3250	list = uu_list_create(listpool, NULL, UU_DEFAULT);
3251	uu_list_node_init(node, &node->usn_listnode, listpool);
3252
3253	while (node != NULL) {
3254		rmnode = node;
3255		node = uu_avl_next(avl_tree, node);
3256		uu_avl_remove(avl_tree, rmnode);
3257		if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
3258			uu_list_insert(list, rmnode, idx2);
3259	}
3260
3261	for (node = uu_list_first(list); node != NULL;
3262	    node = uu_list_next(list, node)) {
3263		us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
3264
3265		if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
3266			uu_avl_insert(avl_tree, node, idx);
3267	}
3268
3269	uu_list_destroy(list);
3270	uu_list_pool_destroy(listpool);
3271
3272	/* Print and free node nvlist memory */
3273	print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
3274	    cb.cb_avl);
3275
3276	zfs_free_sort_columns(sortcol);
3277
3278	/* Clean up the AVL tree */
3279	if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
3280		nomem();
3281
3282	while ((node = uu_avl_walk_next(walk)) != NULL) {
3283		uu_avl_remove(cb.cb_avl, node);
3284		free(node);
3285	}
3286
3287	uu_avl_walk_end(walk);
3288	uu_avl_destroy(avl_tree);
3289	uu_avl_pool_destroy(avl_pool);
3290
3291	return (ret);
3292}
3293
3294/*
3295 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property]
3296 *      [-t type[,...]] [filesystem|volume|snapshot] ...
3297 *
3298 *	-H	Scripted mode; elide headers and separate columns by tabs
3299 *	-p	Display values in parsable (literal) format.
3300 *	-r	Recurse over all children
3301 *	-d	Limit recursion by depth.
3302 *	-o	Control which fields to display.
3303 *	-s	Specify sort columns, descending order.
3304 *	-S	Specify sort columns, ascending order.
3305 *	-t	Control which object types to display.
3306 *
3307 * When given no arguments, list all filesystems in the system.
3308 * Otherwise, list the specified datasets, optionally recursing down them if
3309 * '-r' is specified.
3310 */
3311typedef struct list_cbdata {
3312	boolean_t	cb_first;
3313	boolean_t	cb_literal;
3314	boolean_t	cb_scripted;
3315	zprop_list_t	*cb_proplist;
3316} list_cbdata_t;
3317
3318/*
3319 * Given a list of columns to display, output appropriate headers for each one.
3320 */
3321static void
3322print_header(list_cbdata_t *cb)
3323{
3324	zprop_list_t *pl = cb->cb_proplist;
3325	char headerbuf[ZFS_MAXPROPLEN];
3326	const char *header;
3327	int i;
3328	boolean_t first = B_TRUE;
3329	boolean_t right_justify;
3330
3331	for (; pl != NULL; pl = pl->pl_next) {
3332		if (!first) {
3333			(void) printf("  ");
3334		} else {
3335			first = B_FALSE;
3336		}
3337
3338		right_justify = B_FALSE;
3339		if (pl->pl_prop != ZPROP_INVAL) {
3340			header = zfs_prop_column_name(pl->pl_prop);
3341			right_justify = zfs_prop_align_right(pl->pl_prop);
3342		} else {
3343			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
3344				headerbuf[i] = toupper(pl->pl_user_prop[i]);
3345			headerbuf[i] = '\0';
3346			header = headerbuf;
3347		}
3348
3349		if (pl->pl_next == NULL && !right_justify)
3350			(void) printf("%s", header);
3351		else if (right_justify)
3352			(void) printf("%*s", (int)pl->pl_width, header);
3353		else
3354			(void) printf("%-*s", (int)pl->pl_width, header);
3355	}
3356
3357	(void) printf("\n");
3358}
3359
3360/*
3361 * Given a dataset and a list of fields, print out all the properties according
3362 * to the described layout.
3363 */
3364static void
3365print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
3366{
3367	zprop_list_t *pl = cb->cb_proplist;
3368	boolean_t first = B_TRUE;
3369	char property[ZFS_MAXPROPLEN];
3370	nvlist_t *userprops = zfs_get_user_props(zhp);
3371	nvlist_t *propval;
3372	char *propstr;
3373	boolean_t right_justify;
3374
3375	for (; pl != NULL; pl = pl->pl_next) {
3376		if (!first) {
3377			if (cb->cb_scripted)
3378				(void) printf("\t");
3379			else
3380				(void) printf("  ");
3381		} else {
3382			first = B_FALSE;
3383		}
3384
3385		if (pl->pl_prop == ZFS_PROP_NAME) {
3386			(void) strlcpy(property, zfs_get_name(zhp),
3387			    sizeof (property));
3388			propstr = property;
3389			right_justify = zfs_prop_align_right(pl->pl_prop);
3390		} else if (pl->pl_prop != ZPROP_INVAL) {
3391			if (zfs_prop_get(zhp, pl->pl_prop, property,
3392			    sizeof (property), NULL, NULL, 0,
3393			    cb->cb_literal) != 0)
3394				propstr = "-";
3395			else
3396				propstr = property;
3397			right_justify = zfs_prop_align_right(pl->pl_prop);
3398		} else if (zfs_prop_userquota(pl->pl_user_prop)) {
3399			if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
3400			    property, sizeof (property), cb->cb_literal) != 0)
3401				propstr = "-";
3402			else
3403				propstr = property;
3404			right_justify = B_TRUE;
3405		} else if (zfs_prop_written(pl->pl_user_prop)) {
3406			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
3407			    property, sizeof (property), cb->cb_literal) != 0)
3408				propstr = "-";
3409			else
3410				propstr = property;
3411			right_justify = B_TRUE;
3412		} else {
3413			if (nvlist_lookup_nvlist(userprops,
3414			    pl->pl_user_prop, &propval) != 0)
3415				propstr = "-";
3416			else
3417				verify(nvlist_lookup_string(propval,
3418				    ZPROP_VALUE, &propstr) == 0);
3419			right_justify = B_FALSE;
3420		}
3421
3422		/*
3423		 * If this is being called in scripted mode, or if this is the
3424		 * last column and it is left-justified, don't include a width
3425		 * format specifier.
3426		 */
3427		if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3428			(void) printf("%s", propstr);
3429		else if (right_justify)
3430			(void) printf("%*s", (int)pl->pl_width, propstr);
3431		else
3432			(void) printf("%-*s", (int)pl->pl_width, propstr);
3433	}
3434
3435	(void) printf("\n");
3436}
3437
3438/*
3439 * Generic callback function to list a dataset or snapshot.
3440 */
3441static int
3442list_callback(zfs_handle_t *zhp, void *data)
3443{
3444	list_cbdata_t *cbp = data;
3445
3446	if (cbp->cb_first) {
3447		if (!cbp->cb_scripted)
3448			print_header(cbp);
3449		cbp->cb_first = B_FALSE;
3450	}
3451
3452	print_dataset(zhp, cbp);
3453
3454	return (0);
3455}
3456
3457static int
3458zfs_do_list(int argc, char **argv)
3459{
3460	int c;
3461	static char default_fields[] =
3462	    "name,used,available,referenced,mountpoint";
3463	int types = ZFS_TYPE_DATASET;
3464	boolean_t types_specified = B_FALSE;
3465	char *fields = NULL;
3466	list_cbdata_t cb = { 0 };
3467	char *value;
3468	int limit = 0;
3469	int ret = 0;
3470	zfs_sort_column_t *sortcol = NULL;
3471	int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3472
3473	/* check options */
3474	while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3475		switch (c) {
3476		case 'o':
3477			fields = optarg;
3478			break;
3479		case 'p':
3480			cb.cb_literal = B_TRUE;
3481			flags |= ZFS_ITER_LITERAL_PROPS;
3482			break;
3483		case 'd':
3484			limit = parse_depth(optarg, &flags);
3485			break;
3486		case 'r':
3487			flags |= ZFS_ITER_RECURSE;
3488			break;
3489		case 'H':
3490			cb.cb_scripted = B_TRUE;
3491			break;
3492		case 's':
3493			if (zfs_add_sort_column(&sortcol, optarg,
3494			    B_FALSE) != 0) {
3495				(void) fprintf(stderr,
3496				    gettext("invalid property '%s'\n"), optarg);
3497				usage(B_FALSE);
3498			}
3499			break;
3500		case 'S':
3501			if (zfs_add_sort_column(&sortcol, optarg,
3502			    B_TRUE) != 0) {
3503				(void) fprintf(stderr,
3504				    gettext("invalid property '%s'\n"), optarg);
3505				usage(B_FALSE);
3506			}
3507			break;
3508		case 't':
3509			types = 0;
3510			types_specified = B_TRUE;
3511			flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3512			while (*optarg != '\0') {
3513				static char *type_subopts[] = { "filesystem",
3514				    "volume", "snapshot", "snap", "bookmark",
3515				    "all", NULL };
3516
3517				switch (getsubopt(&optarg, type_subopts,
3518				    &value)) {
3519				case 0:
3520					types |= ZFS_TYPE_FILESYSTEM;
3521					break;
3522				case 1:
3523					types |= ZFS_TYPE_VOLUME;
3524					break;
3525				case 2:
3526				case 3:
3527					types |= ZFS_TYPE_SNAPSHOT;
3528					break;
3529				case 4:
3530					types |= ZFS_TYPE_BOOKMARK;
3531					break;
3532				case 5:
3533					types = ZFS_TYPE_DATASET |
3534					    ZFS_TYPE_BOOKMARK;
3535					break;
3536				default:
3537					(void) fprintf(stderr,
3538					    gettext("invalid type '%s'\n"),
3539					    value);
3540					usage(B_FALSE);
3541				}
3542			}
3543			break;
3544		case ':':
3545			(void) fprintf(stderr, gettext("missing argument for "
3546			    "'%c' option\n"), optopt);
3547			usage(B_FALSE);
3548			break;
3549		case '?':
3550			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3551			    optopt);
3552			usage(B_FALSE);
3553		}
3554	}
3555
3556	argc -= optind;
3557	argv += optind;
3558
3559	if (fields == NULL)
3560		fields = default_fields;
3561
3562	/*
3563	 * If we are only going to list snapshot names and sort by name,
3564	 * then we can use faster version.
3565	 */
3566	if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3567		flags |= ZFS_ITER_SIMPLE;
3568
3569	/*
3570	 * If "-o space" and no types were specified, don't display snapshots.
3571	 */
3572	if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3573		types &= ~ZFS_TYPE_SNAPSHOT;
3574
3575	/*
3576	 * Handle users who want to list all snapshots or bookmarks
3577	 * of the current dataset (ex. 'zfs list -t snapshot <dataset>').
3578	 */
3579	if ((types == ZFS_TYPE_SNAPSHOT || types == ZFS_TYPE_BOOKMARK) &&
3580	    argc > 0 && (flags & ZFS_ITER_RECURSE) == 0 && limit == 0) {
3581		flags |= (ZFS_ITER_DEPTH_LIMIT | ZFS_ITER_RECURSE);
3582		limit = 1;
3583	}
3584
3585	/*
3586	 * If the user specifies '-o all', the zprop_get_list() doesn't
3587	 * normally include the name of the dataset.  For 'zfs list', we always
3588	 * want this property to be first.
3589	 */
3590	if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3591	    != 0)
3592		usage(B_FALSE);
3593
3594	cb.cb_first = B_TRUE;
3595
3596	ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3597	    limit, list_callback, &cb);
3598
3599	zprop_free_list(cb.cb_proplist);
3600	zfs_free_sort_columns(sortcol);
3601
3602	if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3603		(void) fprintf(stderr, gettext("no datasets available\n"));
3604
3605	return (ret);
3606}
3607
3608/*
3609 * zfs rename [-fu] <fs | snap | vol> <fs | snap | vol>
3610 * zfs rename [-f] -p <fs | vol> <fs | vol>
3611 * zfs rename [-u] -r <snap> <snap>
3612 *
3613 * Renames the given dataset to another of the same type.
3614 *
3615 * The '-p' flag creates all the non-existing ancestors of the target first.
3616 * The '-u' flag prevents file systems from being remounted during rename.
3617 */
3618/* ARGSUSED */
3619static int
3620zfs_do_rename(int argc, char **argv)
3621{
3622	zfs_handle_t *zhp;
3623	renameflags_t flags = { 0 };
3624	int c;
3625	int ret = 0;
3626	int types;
3627	boolean_t parents = B_FALSE;
3628
3629	/* check options */
3630	while ((c = getopt(argc, argv, "pruf")) != -1) {
3631		switch (c) {
3632		case 'p':
3633			parents = B_TRUE;
3634			break;
3635		case 'r':
3636			flags.recursive = B_TRUE;
3637			break;
3638		case 'u':
3639			flags.nounmount = B_TRUE;
3640			break;
3641		case 'f':
3642			flags.forceunmount = B_TRUE;
3643			break;
3644		case '?':
3645		default:
3646			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3647			    optopt);
3648			usage(B_FALSE);
3649		}
3650	}
3651
3652	argc -= optind;
3653	argv += optind;
3654
3655	/* check number of arguments */
3656	if (argc < 1) {
3657		(void) fprintf(stderr, gettext("missing source dataset "
3658		    "argument\n"));
3659		usage(B_FALSE);
3660	}
3661	if (argc < 2) {
3662		(void) fprintf(stderr, gettext("missing target dataset "
3663		    "argument\n"));
3664		usage(B_FALSE);
3665	}
3666	if (argc > 2) {
3667		(void) fprintf(stderr, gettext("too many arguments\n"));
3668		usage(B_FALSE);
3669	}
3670
3671	if (flags.recursive && parents) {
3672		(void) fprintf(stderr, gettext("-p and -r options are mutually "
3673		    "exclusive\n"));
3674		usage(B_FALSE);
3675	}
3676
3677	if (flags.nounmount && parents) {
3678		(void) fprintf(stderr, gettext("-u and -p options are mutually "
3679		    "exclusive\n"));
3680		usage(B_FALSE);
3681	}
3682
3683	if (flags.recursive && strchr(argv[0], '@') == 0) {
3684		(void) fprintf(stderr, gettext("source dataset for recursive "
3685		    "rename must be a snapshot\n"));
3686		usage(B_FALSE);
3687	}
3688
3689	if (flags.nounmount)
3690		types = ZFS_TYPE_FILESYSTEM;
3691	else if (parents)
3692		types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3693	else
3694		types = ZFS_TYPE_DATASET;
3695
3696	if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3697		return (1);
3698
3699	/* If we were asked and the name looks good, try to create ancestors. */
3700	if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3701	    zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3702		zfs_close(zhp);
3703		return (1);
3704	}
3705
3706	ret = (zfs_rename(zhp, argv[1], flags) != 0);
3707
3708	zfs_close(zhp);
3709	return (ret);
3710}
3711
3712/*
3713 * zfs promote <fs>
3714 *
3715 * Promotes the given clone fs to be the parent
3716 */
3717/* ARGSUSED */
3718static int
3719zfs_do_promote(int argc, char **argv)
3720{
3721	zfs_handle_t *zhp;
3722	int ret = 0;
3723
3724	/* check options */
3725	if (argc > 1 && argv[1][0] == '-') {
3726		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3727		    argv[1][1]);
3728		usage(B_FALSE);
3729	}
3730
3731	/* check number of arguments */
3732	if (argc < 2) {
3733		(void) fprintf(stderr, gettext("missing clone filesystem"
3734		    " argument\n"));
3735		usage(B_FALSE);
3736	}
3737	if (argc > 2) {
3738		(void) fprintf(stderr, gettext("too many arguments\n"));
3739		usage(B_FALSE);
3740	}
3741
3742	zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3743	if (zhp == NULL)
3744		return (1);
3745
3746	ret = (zfs_promote(zhp) != 0);
3747
3748
3749	zfs_close(zhp);
3750	return (ret);
3751}
3752
3753static int
3754zfs_do_redact(int argc, char **argv)
3755{
3756	char *snap = NULL;
3757	char *bookname = NULL;
3758	char **rsnaps = NULL;
3759	int numrsnaps = 0;
3760	argv++;
3761	argc--;
3762	if (argc < 3) {
3763		(void) fprintf(stderr, gettext("too few arguments\n"));
3764		usage(B_FALSE);
3765	}
3766
3767	snap = argv[0];
3768	bookname = argv[1];
3769	rsnaps = argv + 2;
3770	numrsnaps = argc - 2;
3771
3772	nvlist_t *rsnapnv = fnvlist_alloc();
3773
3774	for (int i = 0; i < numrsnaps; i++) {
3775		fnvlist_add_boolean(rsnapnv, rsnaps[i]);
3776	}
3777
3778	int err = lzc_redact(snap, bookname, rsnapnv);
3779	fnvlist_free(rsnapnv);
3780
3781	switch (err) {
3782	case 0:
3783		break;
3784	case ENOENT:
3785		(void) fprintf(stderr,
3786		    gettext("provided snapshot %s does not exist\n"), snap);
3787		break;
3788	case EEXIST:
3789		(void) fprintf(stderr, gettext("specified redaction bookmark "
3790		    "(%s) provided already exists\n"), bookname);
3791		break;
3792	case ENAMETOOLONG:
3793		(void) fprintf(stderr, gettext("provided bookmark name cannot "
3794		    "be used, final name would be too long\n"));
3795		break;
3796	case E2BIG:
3797		(void) fprintf(stderr, gettext("too many redaction snapshots "
3798		    "specified\n"));
3799		break;
3800	case EINVAL:
3801		if (strchr(bookname, '#') != NULL)
3802			(void) fprintf(stderr, gettext(
3803			    "redaction bookmark name must not contain '#'\n"));
3804		else
3805			(void) fprintf(stderr, gettext(
3806			    "redaction snapshot must be descendent of "
3807			    "snapshot being redacted\n"));
3808		break;
3809	case EALREADY:
3810		(void) fprintf(stderr, gettext("attempted to redact redacted "
3811		    "dataset or with respect to redacted dataset\n"));
3812		break;
3813	case ENOTSUP:
3814		(void) fprintf(stderr, gettext("redaction bookmarks feature "
3815		    "not enabled\n"));
3816		break;
3817	case EXDEV:
3818		(void) fprintf(stderr, gettext("potentially invalid redaction "
3819		    "snapshot; full dataset names required\n"));
3820		break;
3821	default:
3822		(void) fprintf(stderr, gettext("internal error: %s\n"),
3823		    strerror(errno));
3824	}
3825
3826	return (err);
3827}
3828
3829/*
3830 * zfs rollback [-rRf] <snapshot>
3831 *
3832 *	-r	Delete any intervening snapshots before doing rollback
3833 *	-R	Delete any snapshots and their clones
3834 *	-f	ignored for backwards compatibility
3835 *
3836 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3837 * since then and making it the active dataset.  If more recent snapshots exist,
3838 * the command will complain unless the '-r' flag is given.
3839 */
3840typedef struct rollback_cbdata {
3841	uint64_t	cb_create;
3842	uint8_t		cb_younger_ds_printed;
3843	boolean_t	cb_first;
3844	int		cb_doclones;
3845	char		*cb_target;
3846	int		cb_error;
3847	boolean_t	cb_recurse;
3848} rollback_cbdata_t;
3849
3850static int
3851rollback_check_dependent(zfs_handle_t *zhp, void *data)
3852{
3853	rollback_cbdata_t *cbp = data;
3854
3855	if (cbp->cb_first && cbp->cb_recurse) {
3856		(void) fprintf(stderr, gettext("cannot rollback to "
3857		    "'%s': clones of previous snapshots exist\n"),
3858		    cbp->cb_target);
3859		(void) fprintf(stderr, gettext("use '-R' to "
3860		    "force deletion of the following clones and "
3861		    "dependents:\n"));
3862		cbp->cb_first = 0;
3863		cbp->cb_error = 1;
3864	}
3865
3866	(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3867
3868	zfs_close(zhp);
3869	return (0);
3870}
3871
3872
3873/*
3874 * Report some snapshots/bookmarks more recent than the one specified.
3875 * Used when '-r' is not specified. We reuse this same callback for the
3876 * snapshot dependents - if 'cb_dependent' is set, then this is a
3877 * dependent and we should report it without checking the transaction group.
3878 */
3879static int
3880rollback_check(zfs_handle_t *zhp, void *data)
3881{
3882	rollback_cbdata_t *cbp = data;
3883	/*
3884	 * Max number of younger snapshots and/or bookmarks to display before
3885	 * we stop the iteration.
3886	 */
3887	const uint8_t max_younger = 32;
3888
3889	if (cbp->cb_doclones) {
3890		zfs_close(zhp);
3891		return (0);
3892	}
3893
3894	if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3895		if (cbp->cb_first && !cbp->cb_recurse) {
3896			(void) fprintf(stderr, gettext("cannot "
3897			    "rollback to '%s': more recent snapshots "
3898			    "or bookmarks exist\n"),
3899			    cbp->cb_target);
3900			(void) fprintf(stderr, gettext("use '-r' to "
3901			    "force deletion of the following "
3902			    "snapshots and bookmarks:\n"));
3903			cbp->cb_first = 0;
3904			cbp->cb_error = 1;
3905		}
3906
3907		if (cbp->cb_recurse) {
3908			if (zfs_iter_dependents(zhp, B_TRUE,
3909			    rollback_check_dependent, cbp) != 0) {
3910				zfs_close(zhp);
3911				return (-1);
3912			}
3913		} else {
3914			(void) fprintf(stderr, "%s\n",
3915			    zfs_get_name(zhp));
3916			cbp->cb_younger_ds_printed++;
3917		}
3918	}
3919	zfs_close(zhp);
3920
3921	if (cbp->cb_younger_ds_printed == max_younger) {
3922		/*
3923		 * This non-recursive rollback is going to fail due to the
3924		 * presence of snapshots and/or bookmarks that are younger than
3925		 * the rollback target.
3926		 * We printed some of the offending objects, now we stop
3927		 * zfs_iter_snapshot/bookmark iteration so we can fail fast and
3928		 * avoid iterating over the rest of the younger objects
3929		 */
3930		(void) fprintf(stderr, gettext("Output limited to %d "
3931		    "snapshots/bookmarks\n"), max_younger);
3932		return (-1);
3933	}
3934	return (0);
3935}
3936
3937static int
3938zfs_do_rollback(int argc, char **argv)
3939{
3940	int ret = 0;
3941	int c;
3942	boolean_t force = B_FALSE;
3943	rollback_cbdata_t cb = { 0 };
3944	zfs_handle_t *zhp, *snap;
3945	char parentname[ZFS_MAX_DATASET_NAME_LEN];
3946	char *delim;
3947	uint64_t min_txg = 0;
3948
3949	/* check options */
3950	while ((c = getopt(argc, argv, "rRf")) != -1) {
3951		switch (c) {
3952		case 'r':
3953			cb.cb_recurse = 1;
3954			break;
3955		case 'R':
3956			cb.cb_recurse = 1;
3957			cb.cb_doclones = 1;
3958			break;
3959		case 'f':
3960			force = B_TRUE;
3961			break;
3962		case '?':
3963			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3964			    optopt);
3965			usage(B_FALSE);
3966		}
3967	}
3968
3969	argc -= optind;
3970	argv += optind;
3971
3972	/* check number of arguments */
3973	if (argc < 1) {
3974		(void) fprintf(stderr, gettext("missing dataset argument\n"));
3975		usage(B_FALSE);
3976	}
3977	if (argc > 1) {
3978		(void) fprintf(stderr, gettext("too many arguments\n"));
3979		usage(B_FALSE);
3980	}
3981
3982	/* open the snapshot */
3983	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3984		return (1);
3985
3986	/* open the parent dataset */
3987	(void) strlcpy(parentname, argv[0], sizeof (parentname));
3988	verify((delim = strrchr(parentname, '@')) != NULL);
3989	*delim = '\0';
3990	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3991		zfs_close(snap);
3992		return (1);
3993	}
3994
3995	/*
3996	 * Check for more recent snapshots and/or clones based on the presence
3997	 * of '-r' and '-R'.
3998	 */
3999	cb.cb_target = argv[0];
4000	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
4001	cb.cb_first = B_TRUE;
4002	cb.cb_error = 0;
4003
4004	if (cb.cb_create > 0)
4005		min_txg = cb.cb_create;
4006
4007	if ((ret = zfs_iter_snapshots(zhp, B_FALSE, rollback_check, &cb,
4008	    min_txg, 0)) != 0)
4009		goto out;
4010	if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
4011		goto out;
4012
4013	if ((ret = cb.cb_error) != 0)
4014		goto out;
4015
4016	/*
4017	 * Rollback parent to the given snapshot.
4018	 */
4019	ret = zfs_rollback(zhp, snap, force);
4020
4021out:
4022	zfs_close(snap);
4023	zfs_close(zhp);
4024
4025	if (ret == 0)
4026		return (0);
4027	else
4028		return (1);
4029}
4030
4031/*
4032 * zfs set property=value ... { fs | snap | vol } ...
4033 *
4034 * Sets the given properties for all datasets specified on the command line.
4035 */
4036
4037static int
4038set_callback(zfs_handle_t *zhp, void *data)
4039{
4040	nvlist_t *props = data;
4041
4042	if (zfs_prop_set_list(zhp, props) != 0) {
4043		switch (libzfs_errno(g_zfs)) {
4044		case EZFS_MOUNTFAILED:
4045			(void) fprintf(stderr, gettext("property may be set "
4046			    "but unable to remount filesystem\n"));
4047			break;
4048		case EZFS_SHARENFSFAILED:
4049			(void) fprintf(stderr, gettext("property may be set "
4050			    "but unable to reshare filesystem\n"));
4051			break;
4052		}
4053		return (1);
4054	}
4055	return (0);
4056}
4057
4058static int
4059zfs_do_set(int argc, char **argv)
4060{
4061	nvlist_t *props = NULL;
4062	int ds_start = -1; /* argv idx of first dataset arg */
4063	int ret = 0;
4064	int i;
4065
4066	/* check for options */
4067	if (argc > 1 && argv[1][0] == '-') {
4068		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4069		    argv[1][1]);
4070		usage(B_FALSE);
4071	}
4072
4073	/* check number of arguments */
4074	if (argc < 2) {
4075		(void) fprintf(stderr, gettext("missing arguments\n"));
4076		usage(B_FALSE);
4077	}
4078	if (argc < 3) {
4079		if (strchr(argv[1], '=') == NULL) {
4080			(void) fprintf(stderr, gettext("missing property=value "
4081			    "argument(s)\n"));
4082		} else {
4083			(void) fprintf(stderr, gettext("missing dataset "
4084			    "name(s)\n"));
4085		}
4086		usage(B_FALSE);
4087	}
4088
4089	/* validate argument order:  prop=val args followed by dataset args */
4090	for (i = 1; i < argc; i++) {
4091		if (strchr(argv[i], '=') != NULL) {
4092			if (ds_start > 0) {
4093				/* out-of-order prop=val argument */
4094				(void) fprintf(stderr, gettext("invalid "
4095				    "argument order\n"));
4096				usage(B_FALSE);
4097			}
4098		} else if (ds_start < 0) {
4099			ds_start = i;
4100		}
4101	}
4102	if (ds_start < 0) {
4103		(void) fprintf(stderr, gettext("missing dataset name(s)\n"));
4104		usage(B_FALSE);
4105	}
4106
4107	/* Populate a list of property settings */
4108	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4109		nomem();
4110	for (i = 1; i < ds_start; i++) {
4111		if (!parseprop(props, argv[i])) {
4112			ret = -1;
4113			goto error;
4114		}
4115	}
4116
4117	ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
4118	    ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
4119
4120error:
4121	nvlist_free(props);
4122	return (ret);
4123}
4124
4125typedef struct snap_cbdata {
4126	nvlist_t *sd_nvl;
4127	boolean_t sd_recursive;
4128	const char *sd_snapname;
4129} snap_cbdata_t;
4130
4131static int
4132zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
4133{
4134	snap_cbdata_t *sd = arg;
4135	char *name;
4136	int rv = 0;
4137	int error;
4138
4139	if (sd->sd_recursive &&
4140	    zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
4141		zfs_close(zhp);
4142		return (0);
4143	}
4144
4145	error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
4146	if (error == -1)
4147		nomem();
4148	fnvlist_add_boolean(sd->sd_nvl, name);
4149	free(name);
4150
4151	if (sd->sd_recursive)
4152		rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
4153	zfs_close(zhp);
4154	return (rv);
4155}
4156
4157/*
4158 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
4159 *
4160 * Creates a snapshot with the given name.  While functionally equivalent to
4161 * 'zfs create', it is a separate command to differentiate intent.
4162 */
4163static int
4164zfs_do_snapshot(int argc, char **argv)
4165{
4166	int ret = 0;
4167	int c;
4168	nvlist_t *props;
4169	snap_cbdata_t sd = { 0 };
4170	boolean_t multiple_snaps = B_FALSE;
4171
4172	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4173		nomem();
4174	if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
4175		nomem();
4176
4177	/* check options */
4178	while ((c = getopt(argc, argv, "ro:")) != -1) {
4179		switch (c) {
4180		case 'o':
4181			if (!parseprop(props, optarg)) {
4182				nvlist_free(sd.sd_nvl);
4183				nvlist_free(props);
4184				return (1);
4185			}
4186			break;
4187		case 'r':
4188			sd.sd_recursive = B_TRUE;
4189			multiple_snaps = B_TRUE;
4190			break;
4191		case '?':
4192			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4193			    optopt);
4194			goto usage;
4195		}
4196	}
4197
4198	argc -= optind;
4199	argv += optind;
4200
4201	/* check number of arguments */
4202	if (argc < 1) {
4203		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
4204		goto usage;
4205	}
4206
4207	if (argc > 1)
4208		multiple_snaps = B_TRUE;
4209	for (; argc > 0; argc--, argv++) {
4210		char *atp;
4211		zfs_handle_t *zhp;
4212
4213		atp = strchr(argv[0], '@');
4214		if (atp == NULL)
4215			goto usage;
4216		*atp = '\0';
4217		sd.sd_snapname = atp + 1;
4218		zhp = zfs_open(g_zfs, argv[0],
4219		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4220		if (zhp == NULL)
4221			goto usage;
4222		if (zfs_snapshot_cb(zhp, &sd) != 0)
4223			goto usage;
4224	}
4225
4226	ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
4227	nvlist_free(sd.sd_nvl);
4228	nvlist_free(props);
4229	if (ret != 0 && multiple_snaps)
4230		(void) fprintf(stderr, gettext("no snapshots were created\n"));
4231	return (ret != 0);
4232
4233usage:
4234	nvlist_free(sd.sd_nvl);
4235	nvlist_free(props);
4236	usage(B_FALSE);
4237	return (-1);
4238}
4239
4240
4241/*
4242 * Send a backup stream to stdout.
4243 */
4244static int
4245zfs_do_send(int argc, char **argv)
4246{
4247	char *fromname = NULL;
4248	char *toname = NULL;
4249	char *resume_token = NULL;
4250	char *cp;
4251	zfs_handle_t *zhp;
4252	sendflags_t flags = { 0 };
4253	int c, err;
4254	nvlist_t *dbgnv = NULL;
4255	char *redactbook = NULL;
4256
4257	struct option long_options[] = {
4258		{"replicate",	no_argument,		NULL, 'R'},
4259		{"redact",	required_argument,	NULL, 'd'},
4260		{"props",	no_argument,		NULL, 'p'},
4261		{"parsable",	no_argument,		NULL, 'P'},
4262		{"dedup",	no_argument,		NULL, 'D'},
4263		{"verbose",	no_argument,		NULL, 'v'},
4264		{"dryrun",	no_argument,		NULL, 'n'},
4265		{"large-block",	no_argument,		NULL, 'L'},
4266		{"embed",	no_argument,		NULL, 'e'},
4267		{"resume",	required_argument,	NULL, 't'},
4268		{"compressed",	no_argument,		NULL, 'c'},
4269		{"raw",		no_argument,		NULL, 'w'},
4270		{"backup",	no_argument,		NULL, 'b'},
4271		{"holds",	no_argument,		NULL, 'h'},
4272		{"saved",	no_argument,		NULL, 'S'},
4273		{0, 0, 0, 0}
4274	};
4275
4276	/* check options */
4277	while ((c = getopt_long(argc, argv, ":i:I:RDpvnPLeht:cwbd:S",
4278	    long_options, NULL)) != -1) {
4279		switch (c) {
4280		case 'i':
4281			if (fromname)
4282				usage(B_FALSE);
4283			fromname = optarg;
4284			break;
4285		case 'I':
4286			if (fromname)
4287				usage(B_FALSE);
4288			fromname = optarg;
4289			flags.doall = B_TRUE;
4290			break;
4291		case 'R':
4292			flags.replicate = B_TRUE;
4293			break;
4294		case 'd':
4295			redactbook = optarg;
4296			break;
4297		case 'p':
4298			flags.props = B_TRUE;
4299			break;
4300		case 'b':
4301			flags.backup = B_TRUE;
4302			break;
4303		case 'h':
4304			flags.holds = B_TRUE;
4305			break;
4306		case 'P':
4307			flags.parsable = B_TRUE;
4308			break;
4309		case 'v':
4310			flags.verbosity++;
4311			flags.progress = B_TRUE;
4312			break;
4313		case 'D':
4314			(void) fprintf(stderr,
4315			    gettext("WARNING: deduplicated send is no "
4316			    "longer supported.  A regular,\n"
4317			    "non-deduplicated stream will be generated.\n\n"));
4318			break;
4319		case 'n':
4320			flags.dryrun = B_TRUE;
4321			break;
4322		case 'L':
4323			flags.largeblock = B_TRUE;
4324			break;
4325		case 'e':
4326			flags.embed_data = B_TRUE;
4327			break;
4328		case 't':
4329			resume_token = optarg;
4330			break;
4331		case 'c':
4332			flags.compress = B_TRUE;
4333			break;
4334		case 'w':
4335			flags.raw = B_TRUE;
4336			flags.compress = B_TRUE;
4337			flags.embed_data = B_TRUE;
4338			flags.largeblock = B_TRUE;
4339			break;
4340		case 'S':
4341			flags.saved = B_TRUE;
4342			break;
4343		case ':':
4344			/*
4345			 * If a parameter was not passed, optopt contains the
4346			 * value that would normally lead us into the
4347			 * appropriate case statement.  If it's > 256, then this
4348			 * must be a longopt and we should look at argv to get
4349			 * the string.  Otherwise it's just the character, so we
4350			 * should use it directly.
4351			 */
4352			if (optopt <= UINT8_MAX) {
4353				(void) fprintf(stderr,
4354				    gettext("missing argument for '%c' "
4355				    "option\n"), optopt);
4356			} else {
4357				(void) fprintf(stderr,
4358				    gettext("missing argument for '%s' "
4359				    "option\n"), argv[optind - 1]);
4360			}
4361			usage(B_FALSE);
4362			break;
4363		case '?':
4364			/*FALLTHROUGH*/
4365		default:
4366			/*
4367			 * If an invalid flag was passed, optopt contains the
4368			 * character if it was a short flag, or 0 if it was a
4369			 * longopt.
4370			 */
4371			if (optopt != 0) {
4372				(void) fprintf(stderr,
4373				    gettext("invalid option '%c'\n"), optopt);
4374			} else {
4375				(void) fprintf(stderr,
4376				    gettext("invalid option '%s'\n"),
4377				    argv[optind - 1]);
4378
4379			}
4380			usage(B_FALSE);
4381		}
4382	}
4383
4384	if (flags.parsable && flags.verbosity == 0)
4385		flags.verbosity = 1;
4386
4387	argc -= optind;
4388	argv += optind;
4389
4390	if (resume_token != NULL) {
4391		if (fromname != NULL || flags.replicate || flags.props ||
4392		    flags.backup || flags.holds ||
4393		    flags.saved || redactbook != NULL) {
4394			(void) fprintf(stderr,
4395			    gettext("invalid flags combined with -t\n"));
4396			usage(B_FALSE);
4397		}
4398		if (argc > 0) {
4399			(void) fprintf(stderr, gettext("too many arguments\n"));
4400			usage(B_FALSE);
4401		}
4402	} else {
4403		if (argc < 1) {
4404			(void) fprintf(stderr,
4405			    gettext("missing snapshot argument\n"));
4406			usage(B_FALSE);
4407		}
4408		if (argc > 1) {
4409			(void) fprintf(stderr, gettext("too many arguments\n"));
4410			usage(B_FALSE);
4411		}
4412	}
4413
4414	if (flags.saved) {
4415		if (fromname != NULL || flags.replicate || flags.props ||
4416		    flags.doall || flags.backup ||
4417		    flags.holds || flags.largeblock || flags.embed_data ||
4418		    flags.compress || flags.raw || redactbook != NULL) {
4419			(void) fprintf(stderr, gettext("incompatible flags "
4420			    "combined with saved send flag\n"));
4421			usage(B_FALSE);
4422		}
4423		if (strchr(argv[0], '@') != NULL) {
4424			(void) fprintf(stderr, gettext("saved send must "
4425			    "specify the dataset with partially-received "
4426			    "state\n"));
4427			usage(B_FALSE);
4428		}
4429	}
4430
4431	if (flags.raw && redactbook != NULL) {
4432		(void) fprintf(stderr,
4433		    gettext("Error: raw sends may not be redacted.\n"));
4434		return (1);
4435	}
4436
4437	if (!flags.dryrun && isatty(STDOUT_FILENO)) {
4438		(void) fprintf(stderr,
4439		    gettext("Error: Stream can not be written to a terminal.\n"
4440		    "You must redirect standard output.\n"));
4441		return (1);
4442	}
4443
4444	if (flags.saved) {
4445		zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4446		if (zhp == NULL)
4447			return (1);
4448
4449		err = zfs_send_saved(zhp, &flags, STDOUT_FILENO,
4450		    resume_token);
4451		zfs_close(zhp);
4452		return (err != 0);
4453	} else if (resume_token != NULL) {
4454		return (zfs_send_resume(g_zfs, &flags, STDOUT_FILENO,
4455		    resume_token));
4456	}
4457
4458	/*
4459	 * For everything except -R and -I, use the new, cleaner code path.
4460	 */
4461	if (!(flags.replicate || flags.doall)) {
4462		char frombuf[ZFS_MAX_DATASET_NAME_LEN];
4463
4464		if (fromname != NULL && (strchr(fromname, '#') == NULL &&
4465		    strchr(fromname, '@') == NULL)) {
4466			/*
4467			 * Neither bookmark or snapshot was specified.  Print a
4468			 * warning, and assume snapshot.
4469			 */
4470			(void) fprintf(stderr, "Warning: incremental source "
4471			    "didn't specify type, assuming snapshot. Use '@' "
4472			    "or '#' prefix to avoid ambiguity.\n");
4473			(void) snprintf(frombuf, sizeof (frombuf), "@%s",
4474			    fromname);
4475			fromname = frombuf;
4476		}
4477		if (fromname != NULL &&
4478		    (fromname[0] == '#' || fromname[0] == '@')) {
4479			/*
4480			 * Incremental source name begins with # or @.
4481			 * Default to same fs as target.
4482			 */
4483			char tmpbuf[ZFS_MAX_DATASET_NAME_LEN];
4484			(void) strlcpy(tmpbuf, fromname, sizeof (tmpbuf));
4485			(void) strlcpy(frombuf, argv[0], sizeof (frombuf));
4486			cp = strchr(frombuf, '@');
4487			if (cp != NULL)
4488				*cp = '\0';
4489			(void) strlcat(frombuf, tmpbuf, sizeof (frombuf));
4490			fromname = frombuf;
4491		}
4492
4493		zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
4494		if (zhp == NULL)
4495			return (1);
4496		err = zfs_send_one(zhp, fromname, STDOUT_FILENO, &flags,
4497		    redactbook);
4498		zfs_close(zhp);
4499		return (err != 0);
4500	}
4501
4502	if (fromname != NULL && strchr(fromname, '#')) {
4503		(void) fprintf(stderr,
4504		    gettext("Error: multiple snapshots cannot be "
4505		    "sent from a bookmark.\n"));
4506		return (1);
4507	}
4508
4509	if (redactbook != NULL) {
4510		(void) fprintf(stderr, gettext("Error: multiple snapshots "
4511		    "cannot be sent redacted.\n"));
4512		return (1);
4513	}
4514
4515	if ((cp = strchr(argv[0], '@')) == NULL) {
4516		(void) fprintf(stderr, gettext("Error: "
4517		    "Unsupported flag with filesystem or bookmark.\n"));
4518		return (1);
4519	}
4520	*cp = '\0';
4521	toname = cp + 1;
4522	zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4523	if (zhp == NULL)
4524		return (1);
4525
4526	/*
4527	 * If they specified the full path to the snapshot, chop off
4528	 * everything except the short name of the snapshot, but special
4529	 * case if they specify the origin.
4530	 */
4531	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
4532		char origin[ZFS_MAX_DATASET_NAME_LEN];
4533		zprop_source_t src;
4534
4535		(void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
4536		    origin, sizeof (origin), &src, NULL, 0, B_FALSE);
4537
4538		if (strcmp(origin, fromname) == 0) {
4539			fromname = NULL;
4540			flags.fromorigin = B_TRUE;
4541		} else {
4542			*cp = '\0';
4543			if (cp != fromname && strcmp(argv[0], fromname)) {
4544				(void) fprintf(stderr,
4545				    gettext("incremental source must be "
4546				    "in same filesystem\n"));
4547				usage(B_FALSE);
4548			}
4549			fromname = cp + 1;
4550			if (strchr(fromname, '@') || strchr(fromname, '/')) {
4551				(void) fprintf(stderr,
4552				    gettext("invalid incremental source\n"));
4553				usage(B_FALSE);
4554			}
4555		}
4556	}
4557
4558	if (flags.replicate && fromname == NULL)
4559		flags.doall = B_TRUE;
4560
4561	err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
4562	    flags.verbosity >= 3 ? &dbgnv : NULL);
4563
4564	if (flags.verbosity >= 3 && dbgnv != NULL) {
4565		/*
4566		 * dump_nvlist prints to stdout, but that's been
4567		 * redirected to a file.  Make it print to stderr
4568		 * instead.
4569		 */
4570		(void) dup2(STDERR_FILENO, STDOUT_FILENO);
4571		dump_nvlist(dbgnv, 0);
4572		nvlist_free(dbgnv);
4573	}
4574	zfs_close(zhp);
4575
4576	return (err != 0);
4577}
4578
4579/*
4580 * Restore a backup stream from stdin.
4581 */
4582static int
4583zfs_do_receive(int argc, char **argv)
4584{
4585	int c, err = 0;
4586	recvflags_t flags = { 0 };
4587	boolean_t abort_resumable = B_FALSE;
4588	nvlist_t *props;
4589
4590	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
4591		nomem();
4592
4593	/* check options */
4594	while ((c = getopt(argc, argv, ":o:x:dehMnuvFsA")) != -1) {
4595		switch (c) {
4596		case 'o':
4597			if (!parseprop(props, optarg)) {
4598				nvlist_free(props);
4599				usage(B_FALSE);
4600			}
4601			break;
4602		case 'x':
4603			if (!parsepropname(props, optarg)) {
4604				nvlist_free(props);
4605				usage(B_FALSE);
4606			}
4607			break;
4608		case 'd':
4609			if (flags.istail) {
4610				(void) fprintf(stderr, gettext("invalid option "
4611				    "combination: -d and -e are mutually "
4612				    "exclusive\n"));
4613				usage(B_FALSE);
4614			}
4615			flags.isprefix = B_TRUE;
4616			break;
4617		case 'e':
4618			if (flags.isprefix) {
4619				(void) fprintf(stderr, gettext("invalid option "
4620				    "combination: -d and -e are mutually "
4621				    "exclusive\n"));
4622				usage(B_FALSE);
4623			}
4624			flags.istail = B_TRUE;
4625			break;
4626		case 'h':
4627			flags.skipholds = B_TRUE;
4628			break;
4629		case 'M':
4630			flags.forceunmount = B_TRUE;
4631			break;
4632		case 'n':
4633			flags.dryrun = B_TRUE;
4634			break;
4635		case 'u':
4636			flags.nomount = B_TRUE;
4637			break;
4638		case 'v':
4639			flags.verbose = B_TRUE;
4640			break;
4641		case 's':
4642			flags.resumable = B_TRUE;
4643			break;
4644		case 'F':
4645			flags.force = B_TRUE;
4646			break;
4647		case 'A':
4648			abort_resumable = B_TRUE;
4649			break;
4650		case ':':
4651			(void) fprintf(stderr, gettext("missing argument for "
4652			    "'%c' option\n"), optopt);
4653			usage(B_FALSE);
4654			break;
4655		case '?':
4656			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4657			    optopt);
4658			usage(B_FALSE);
4659		}
4660	}
4661
4662	argc -= optind;
4663	argv += optind;
4664
4665	/* zfs recv -e (use "tail" name) implies -d (remove dataset "head") */
4666	if (flags.istail)
4667		flags.isprefix = B_TRUE;
4668
4669	/* check number of arguments */
4670	if (argc < 1) {
4671		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
4672		usage(B_FALSE);
4673	}
4674	if (argc > 1) {
4675		(void) fprintf(stderr, gettext("too many arguments\n"));
4676		usage(B_FALSE);
4677	}
4678
4679	if (abort_resumable) {
4680		if (flags.isprefix || flags.istail || flags.dryrun ||
4681		    flags.resumable || flags.nomount) {
4682			(void) fprintf(stderr, gettext("invalid option\n"));
4683			usage(B_FALSE);
4684		}
4685
4686		char namebuf[ZFS_MAX_DATASET_NAME_LEN];
4687		(void) snprintf(namebuf, sizeof (namebuf),
4688		    "%s/%%recv", argv[0]);
4689
4690		if (zfs_dataset_exists(g_zfs, namebuf,
4691		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) {
4692			zfs_handle_t *zhp = zfs_open(g_zfs,
4693			    namebuf, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4694			if (zhp == NULL) {
4695				nvlist_free(props);
4696				return (1);
4697			}
4698			err = zfs_destroy(zhp, B_FALSE);
4699			zfs_close(zhp);
4700		} else {
4701			zfs_handle_t *zhp = zfs_open(g_zfs,
4702			    argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
4703			if (zhp == NULL)
4704				usage(B_FALSE);
4705			if (!zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) ||
4706			    zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
4707			    NULL, 0, NULL, NULL, 0, B_TRUE) == -1) {
4708				(void) fprintf(stderr,
4709				    gettext("'%s' does not have any "
4710				    "resumable receive state to abort\n"),
4711				    argv[0]);
4712				nvlist_free(props);
4713				zfs_close(zhp);
4714				return (1);
4715			}
4716			err = zfs_destroy(zhp, B_FALSE);
4717			zfs_close(zhp);
4718		}
4719		nvlist_free(props);
4720		return (err != 0);
4721	}
4722
4723	if (isatty(STDIN_FILENO)) {
4724		(void) fprintf(stderr,
4725		    gettext("Error: Backup stream can not be read "
4726		    "from a terminal.\n"
4727		    "You must redirect standard input.\n"));
4728		nvlist_free(props);
4729		return (1);
4730	}
4731	err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
4732	nvlist_free(props);
4733
4734	return (err != 0);
4735}
4736
4737/*
4738 * allow/unallow stuff
4739 */
4740/* copied from zfs/sys/dsl_deleg.h */
4741#define	ZFS_DELEG_PERM_CREATE		"create"
4742#define	ZFS_DELEG_PERM_DESTROY		"destroy"
4743#define	ZFS_DELEG_PERM_SNAPSHOT		"snapshot"
4744#define	ZFS_DELEG_PERM_ROLLBACK		"rollback"
4745#define	ZFS_DELEG_PERM_CLONE		"clone"
4746#define	ZFS_DELEG_PERM_PROMOTE		"promote"
4747#define	ZFS_DELEG_PERM_RENAME		"rename"
4748#define	ZFS_DELEG_PERM_MOUNT		"mount"
4749#define	ZFS_DELEG_PERM_SHARE		"share"
4750#define	ZFS_DELEG_PERM_SEND		"send"
4751#define	ZFS_DELEG_PERM_RECEIVE		"receive"
4752#define	ZFS_DELEG_PERM_ALLOW		"allow"
4753#define	ZFS_DELEG_PERM_USERPROP		"userprop"
4754#define	ZFS_DELEG_PERM_VSCAN		"vscan" /* ??? */
4755#define	ZFS_DELEG_PERM_USERQUOTA	"userquota"
4756#define	ZFS_DELEG_PERM_GROUPQUOTA	"groupquota"
4757#define	ZFS_DELEG_PERM_USERUSED		"userused"
4758#define	ZFS_DELEG_PERM_GROUPUSED	"groupused"
4759#define	ZFS_DELEG_PERM_USEROBJQUOTA	"userobjquota"
4760#define	ZFS_DELEG_PERM_GROUPOBJQUOTA	"groupobjquota"
4761#define	ZFS_DELEG_PERM_USEROBJUSED	"userobjused"
4762#define	ZFS_DELEG_PERM_GROUPOBJUSED	"groupobjused"
4763
4764#define	ZFS_DELEG_PERM_HOLD		"hold"
4765#define	ZFS_DELEG_PERM_RELEASE		"release"
4766#define	ZFS_DELEG_PERM_DIFF		"diff"
4767#define	ZFS_DELEG_PERM_BOOKMARK		"bookmark"
4768#define	ZFS_DELEG_PERM_LOAD_KEY		"load-key"
4769#define	ZFS_DELEG_PERM_CHANGE_KEY	"change-key"
4770
4771#define	ZFS_DELEG_PERM_PROJECTUSED	"projectused"
4772#define	ZFS_DELEG_PERM_PROJECTQUOTA	"projectquota"
4773#define	ZFS_DELEG_PERM_PROJECTOBJUSED	"projectobjused"
4774#define	ZFS_DELEG_PERM_PROJECTOBJQUOTA	"projectobjquota"
4775
4776#define	ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4777
4778static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4779	{ ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4780	{ ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4781	{ ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4782	{ ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4783	{ ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4784	{ ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4785	{ ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4786	{ ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4787	{ ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4788	{ ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4789	{ ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4790	{ ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4791	{ ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4792	{ ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4793	{ ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4794	{ ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4795	{ ZFS_DELEG_PERM_LOAD_KEY, ZFS_DELEG_NOTE_LOAD_KEY },
4796	{ ZFS_DELEG_PERM_CHANGE_KEY, ZFS_DELEG_NOTE_CHANGE_KEY },
4797
4798	{ ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4799	{ ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4800	{ ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4801	{ ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4802	{ ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4803	{ ZFS_DELEG_PERM_USEROBJQUOTA, ZFS_DELEG_NOTE_USEROBJQUOTA },
4804	{ ZFS_DELEG_PERM_USEROBJUSED, ZFS_DELEG_NOTE_USEROBJUSED },
4805	{ ZFS_DELEG_PERM_GROUPOBJQUOTA, ZFS_DELEG_NOTE_GROUPOBJQUOTA },
4806	{ ZFS_DELEG_PERM_GROUPOBJUSED, ZFS_DELEG_NOTE_GROUPOBJUSED },
4807	{ ZFS_DELEG_PERM_PROJECTUSED, ZFS_DELEG_NOTE_PROJECTUSED },
4808	{ ZFS_DELEG_PERM_PROJECTQUOTA, ZFS_DELEG_NOTE_PROJECTQUOTA },
4809	{ ZFS_DELEG_PERM_PROJECTOBJUSED, ZFS_DELEG_NOTE_PROJECTOBJUSED },
4810	{ ZFS_DELEG_PERM_PROJECTOBJQUOTA, ZFS_DELEG_NOTE_PROJECTOBJQUOTA },
4811	{ NULL, ZFS_DELEG_NOTE_NONE }
4812};
4813
4814/* permission structure */
4815typedef struct deleg_perm {
4816	zfs_deleg_who_type_t	dp_who_type;
4817	const char		*dp_name;
4818	boolean_t		dp_local;
4819	boolean_t		dp_descend;
4820} deleg_perm_t;
4821
4822/* */
4823typedef struct deleg_perm_node {
4824	deleg_perm_t		dpn_perm;
4825
4826	uu_avl_node_t		dpn_avl_node;
4827} deleg_perm_node_t;
4828
4829typedef struct fs_perm fs_perm_t;
4830
4831/* permissions set */
4832typedef struct who_perm {
4833	zfs_deleg_who_type_t	who_type;
4834	const char		*who_name;		/* id */
4835	char			who_ug_name[256];	/* user/group name */
4836	fs_perm_t		*who_fsperm;		/* uplink */
4837
4838	uu_avl_t		*who_deleg_perm_avl;	/* permissions */
4839} who_perm_t;
4840
4841/* */
4842typedef struct who_perm_node {
4843	who_perm_t	who_perm;
4844	uu_avl_node_t	who_avl_node;
4845} who_perm_node_t;
4846
4847typedef struct fs_perm_set fs_perm_set_t;
4848/* fs permissions */
4849struct fs_perm {
4850	const char		*fsp_name;
4851
4852	uu_avl_t		*fsp_sc_avl;	/* sets,create */
4853	uu_avl_t		*fsp_uge_avl;	/* user,group,everyone */
4854
4855	fs_perm_set_t		*fsp_set;	/* uplink */
4856};
4857
4858/* */
4859typedef struct fs_perm_node {
4860	fs_perm_t	fspn_fsperm;
4861	uu_avl_t	*fspn_avl;
4862
4863	uu_list_node_t	fspn_list_node;
4864} fs_perm_node_t;
4865
4866/* top level structure */
4867struct fs_perm_set {
4868	uu_list_pool_t	*fsps_list_pool;
4869	uu_list_t	*fsps_list; /* list of fs_perms */
4870
4871	uu_avl_pool_t	*fsps_named_set_avl_pool;
4872	uu_avl_pool_t	*fsps_who_perm_avl_pool;
4873	uu_avl_pool_t	*fsps_deleg_perm_avl_pool;
4874};
4875
4876static inline const char *
4877deleg_perm_type(zfs_deleg_note_t note)
4878{
4879	/* subcommands */
4880	switch (note) {
4881		/* SUBCOMMANDS */
4882		/* OTHER */
4883	case ZFS_DELEG_NOTE_GROUPQUOTA:
4884	case ZFS_DELEG_NOTE_GROUPUSED:
4885	case ZFS_DELEG_NOTE_USERPROP:
4886	case ZFS_DELEG_NOTE_USERQUOTA:
4887	case ZFS_DELEG_NOTE_USERUSED:
4888	case ZFS_DELEG_NOTE_USEROBJQUOTA:
4889	case ZFS_DELEG_NOTE_USEROBJUSED:
4890	case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
4891	case ZFS_DELEG_NOTE_GROUPOBJUSED:
4892	case ZFS_DELEG_NOTE_PROJECTUSED:
4893	case ZFS_DELEG_NOTE_PROJECTQUOTA:
4894	case ZFS_DELEG_NOTE_PROJECTOBJUSED:
4895	case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
4896		/* other */
4897		return (gettext("other"));
4898	default:
4899		return (gettext("subcommand"));
4900	}
4901}
4902
4903static int
4904who_type2weight(zfs_deleg_who_type_t who_type)
4905{
4906	int res;
4907	switch (who_type) {
4908		case ZFS_DELEG_NAMED_SET_SETS:
4909		case ZFS_DELEG_NAMED_SET:
4910			res = 0;
4911			break;
4912		case ZFS_DELEG_CREATE_SETS:
4913		case ZFS_DELEG_CREATE:
4914			res = 1;
4915			break;
4916		case ZFS_DELEG_USER_SETS:
4917		case ZFS_DELEG_USER:
4918			res = 2;
4919			break;
4920		case ZFS_DELEG_GROUP_SETS:
4921		case ZFS_DELEG_GROUP:
4922			res = 3;
4923			break;
4924		case ZFS_DELEG_EVERYONE_SETS:
4925		case ZFS_DELEG_EVERYONE:
4926			res = 4;
4927			break;
4928		default:
4929			res = -1;
4930	}
4931
4932	return (res);
4933}
4934
4935/* ARGSUSED */
4936static int
4937who_perm_compare(const void *larg, const void *rarg, void *unused)
4938{
4939	const who_perm_node_t *l = larg;
4940	const who_perm_node_t *r = rarg;
4941	zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4942	zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4943	int lweight = who_type2weight(ltype);
4944	int rweight = who_type2weight(rtype);
4945	int res = lweight - rweight;
4946	if (res == 0)
4947		res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4948		    ZFS_MAX_DELEG_NAME-1);
4949
4950	if (res == 0)
4951		return (0);
4952	if (res > 0)
4953		return (1);
4954	else
4955		return (-1);
4956}
4957
4958/* ARGSUSED */
4959static int
4960deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4961{
4962	const deleg_perm_node_t *l = larg;
4963	const deleg_perm_node_t *r = rarg;
4964	int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4965	    ZFS_MAX_DELEG_NAME-1);
4966
4967	if (res == 0)
4968		return (0);
4969
4970	if (res > 0)
4971		return (1);
4972	else
4973		return (-1);
4974}
4975
4976static inline void
4977fs_perm_set_init(fs_perm_set_t *fspset)
4978{
4979	bzero(fspset, sizeof (fs_perm_set_t));
4980
4981	if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4982	    sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4983	    NULL, UU_DEFAULT)) == NULL)
4984		nomem();
4985	if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4986	    UU_DEFAULT)) == NULL)
4987		nomem();
4988
4989	if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4990	    "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4991	    who_perm_node_t, who_avl_node), who_perm_compare,
4992	    UU_DEFAULT)) == NULL)
4993		nomem();
4994
4995	if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4996	    "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4997	    who_perm_node_t, who_avl_node), who_perm_compare,
4998	    UU_DEFAULT)) == NULL)
4999		nomem();
5000
5001	if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
5002	    "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
5003	    deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
5004	    == NULL)
5005		nomem();
5006}
5007
5008static inline void fs_perm_fini(fs_perm_t *);
5009static inline void who_perm_fini(who_perm_t *);
5010
5011static inline void
5012fs_perm_set_fini(fs_perm_set_t *fspset)
5013{
5014	fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
5015
5016	while (node != NULL) {
5017		fs_perm_node_t *next_node =
5018		    uu_list_next(fspset->fsps_list, node);
5019		fs_perm_t *fsperm = &node->fspn_fsperm;
5020		fs_perm_fini(fsperm);
5021		uu_list_remove(fspset->fsps_list, node);
5022		free(node);
5023		node = next_node;
5024	}
5025
5026	uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
5027	uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
5028	uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
5029}
5030
5031static inline void
5032deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
5033    const char *name)
5034{
5035	deleg_perm->dp_who_type = type;
5036	deleg_perm->dp_name = name;
5037}
5038
5039static inline void
5040who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
5041    zfs_deleg_who_type_t type, const char *name)
5042{
5043	uu_avl_pool_t	*pool;
5044	pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
5045
5046	bzero(who_perm, sizeof (who_perm_t));
5047
5048	if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
5049	    UU_DEFAULT)) == NULL)
5050		nomem();
5051
5052	who_perm->who_type = type;
5053	who_perm->who_name = name;
5054	who_perm->who_fsperm = fsperm;
5055}
5056
5057static inline void
5058who_perm_fini(who_perm_t *who_perm)
5059{
5060	deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
5061
5062	while (node != NULL) {
5063		deleg_perm_node_t *next_node =
5064		    uu_avl_next(who_perm->who_deleg_perm_avl, node);
5065
5066		uu_avl_remove(who_perm->who_deleg_perm_avl, node);
5067		free(node);
5068		node = next_node;
5069	}
5070
5071	uu_avl_destroy(who_perm->who_deleg_perm_avl);
5072}
5073
5074static inline void
5075fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
5076{
5077	uu_avl_pool_t	*nset_pool = fspset->fsps_named_set_avl_pool;
5078	uu_avl_pool_t	*who_pool = fspset->fsps_who_perm_avl_pool;
5079
5080	bzero(fsperm, sizeof (fs_perm_t));
5081
5082	if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
5083	    == NULL)
5084		nomem();
5085
5086	if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
5087	    == NULL)
5088		nomem();
5089
5090	fsperm->fsp_set = fspset;
5091	fsperm->fsp_name = fsname;
5092}
5093
5094static inline void
5095fs_perm_fini(fs_perm_t *fsperm)
5096{
5097	who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
5098	while (node != NULL) {
5099		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
5100		    node);
5101		who_perm_t *who_perm = &node->who_perm;
5102		who_perm_fini(who_perm);
5103		uu_avl_remove(fsperm->fsp_sc_avl, node);
5104		free(node);
5105		node = next_node;
5106	}
5107
5108	node = uu_avl_first(fsperm->fsp_uge_avl);
5109	while (node != NULL) {
5110		who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
5111		    node);
5112		who_perm_t *who_perm = &node->who_perm;
5113		who_perm_fini(who_perm);
5114		uu_avl_remove(fsperm->fsp_uge_avl, node);
5115		free(node);
5116		node = next_node;
5117	}
5118
5119	uu_avl_destroy(fsperm->fsp_sc_avl);
5120	uu_avl_destroy(fsperm->fsp_uge_avl);
5121}
5122
5123static void
5124set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
5125    zfs_deleg_who_type_t who_type, const char *name, char locality)
5126{
5127	uu_avl_index_t idx = 0;
5128
5129	deleg_perm_node_t *found_node = NULL;
5130	deleg_perm_t	*deleg_perm = &node->dpn_perm;
5131
5132	deleg_perm_init(deleg_perm, who_type, name);
5133
5134	if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5135	    == NULL)
5136		uu_avl_insert(avl, node, idx);
5137	else {
5138		node = found_node;
5139		deleg_perm = &node->dpn_perm;
5140	}
5141
5142
5143	switch (locality) {
5144	case ZFS_DELEG_LOCAL:
5145		deleg_perm->dp_local = B_TRUE;
5146		break;
5147	case ZFS_DELEG_DESCENDENT:
5148		deleg_perm->dp_descend = B_TRUE;
5149		break;
5150	case ZFS_DELEG_NA:
5151		break;
5152	default:
5153		assert(B_FALSE); /* invalid locality */
5154	}
5155}
5156
5157static inline int
5158parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
5159{
5160	nvpair_t *nvp = NULL;
5161	fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
5162	uu_avl_t *avl = who_perm->who_deleg_perm_avl;
5163	zfs_deleg_who_type_t who_type = who_perm->who_type;
5164
5165	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5166		const char *name = nvpair_name(nvp);
5167		data_type_t type = nvpair_type(nvp);
5168		uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
5169		deleg_perm_node_t *node =
5170		    safe_malloc(sizeof (deleg_perm_node_t));
5171
5172		VERIFY(type == DATA_TYPE_BOOLEAN);
5173
5174		uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
5175		set_deleg_perm_node(avl, node, who_type, name, locality);
5176	}
5177
5178	return (0);
5179}
5180
5181static inline int
5182parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
5183{
5184	nvpair_t *nvp = NULL;
5185	fs_perm_set_t *fspset = fsperm->fsp_set;
5186
5187	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5188		nvlist_t *nvl2 = NULL;
5189		const char *name = nvpair_name(nvp);
5190		uu_avl_t *avl = NULL;
5191		uu_avl_pool_t *avl_pool = NULL;
5192		zfs_deleg_who_type_t perm_type = name[0];
5193		char perm_locality = name[1];
5194		const char *perm_name = name + 3;
5195		who_perm_t *who_perm = NULL;
5196
5197		assert('$' == name[2]);
5198
5199		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5200			return (-1);
5201
5202		switch (perm_type) {
5203		case ZFS_DELEG_CREATE:
5204		case ZFS_DELEG_CREATE_SETS:
5205		case ZFS_DELEG_NAMED_SET:
5206		case ZFS_DELEG_NAMED_SET_SETS:
5207			avl_pool = fspset->fsps_named_set_avl_pool;
5208			avl = fsperm->fsp_sc_avl;
5209			break;
5210		case ZFS_DELEG_USER:
5211		case ZFS_DELEG_USER_SETS:
5212		case ZFS_DELEG_GROUP:
5213		case ZFS_DELEG_GROUP_SETS:
5214		case ZFS_DELEG_EVERYONE:
5215		case ZFS_DELEG_EVERYONE_SETS:
5216			avl_pool = fspset->fsps_who_perm_avl_pool;
5217			avl = fsperm->fsp_uge_avl;
5218			break;
5219
5220		default:
5221			assert(!"unhandled zfs_deleg_who_type_t");
5222		}
5223
5224		who_perm_node_t *found_node = NULL;
5225		who_perm_node_t *node = safe_malloc(
5226		    sizeof (who_perm_node_t));
5227		who_perm = &node->who_perm;
5228		uu_avl_index_t idx = 0;
5229
5230		uu_avl_node_init(node, &node->who_avl_node, avl_pool);
5231		who_perm_init(who_perm, fsperm, perm_type, perm_name);
5232
5233		if ((found_node = uu_avl_find(avl, node, NULL, &idx))
5234		    == NULL) {
5235			if (avl == fsperm->fsp_uge_avl) {
5236				uid_t rid = 0;
5237				struct passwd *p = NULL;
5238				struct group *g = NULL;
5239				const char *nice_name = NULL;
5240
5241				switch (perm_type) {
5242				case ZFS_DELEG_USER_SETS:
5243				case ZFS_DELEG_USER:
5244					rid = atoi(perm_name);
5245					p = getpwuid(rid);
5246					if (p)
5247						nice_name = p->pw_name;
5248					break;
5249				case ZFS_DELEG_GROUP_SETS:
5250				case ZFS_DELEG_GROUP:
5251					rid = atoi(perm_name);
5252					g = getgrgid(rid);
5253					if (g)
5254						nice_name = g->gr_name;
5255					break;
5256
5257				default:
5258					break;
5259				}
5260
5261				if (nice_name != NULL) {
5262					(void) strlcpy(
5263					    node->who_perm.who_ug_name,
5264					    nice_name, 256);
5265				} else {
5266					/* User or group unknown */
5267					(void) snprintf(
5268					    node->who_perm.who_ug_name,
5269					    sizeof (node->who_perm.who_ug_name),
5270					    "(unknown: %d)", rid);
5271				}
5272			}
5273
5274			uu_avl_insert(avl, node, idx);
5275		} else {
5276			node = found_node;
5277			who_perm = &node->who_perm;
5278		}
5279
5280		assert(who_perm != NULL);
5281		(void) parse_who_perm(who_perm, nvl2, perm_locality);
5282	}
5283
5284	return (0);
5285}
5286
5287static inline int
5288parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
5289{
5290	nvpair_t *nvp = NULL;
5291	uu_avl_index_t idx = 0;
5292
5293	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5294		nvlist_t *nvl2 = NULL;
5295		const char *fsname = nvpair_name(nvp);
5296		data_type_t type = nvpair_type(nvp);
5297		fs_perm_t *fsperm = NULL;
5298		fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
5299		if (node == NULL)
5300			nomem();
5301
5302		fsperm = &node->fspn_fsperm;
5303
5304		VERIFY(DATA_TYPE_NVLIST == type);
5305
5306		uu_list_node_init(node, &node->fspn_list_node,
5307		    fspset->fsps_list_pool);
5308
5309		idx = uu_list_numnodes(fspset->fsps_list);
5310		fs_perm_init(fsperm, fspset, fsname);
5311
5312		if (nvpair_value_nvlist(nvp, &nvl2) != 0)
5313			return (-1);
5314
5315		(void) parse_fs_perm(fsperm, nvl2);
5316
5317		uu_list_insert(fspset->fsps_list, node, idx);
5318	}
5319
5320	return (0);
5321}
5322
5323static inline const char *
5324deleg_perm_comment(zfs_deleg_note_t note)
5325{
5326	const char *str = "";
5327
5328	/* subcommands */
5329	switch (note) {
5330		/* SUBCOMMANDS */
5331	case ZFS_DELEG_NOTE_ALLOW:
5332		str = gettext("Must also have the permission that is being"
5333		    "\n\t\t\t\tallowed");
5334		break;
5335	case ZFS_DELEG_NOTE_CLONE:
5336		str = gettext("Must also have the 'create' ability and 'mount'"
5337		    "\n\t\t\t\tability in the origin file system");
5338		break;
5339	case ZFS_DELEG_NOTE_CREATE:
5340		str = gettext("Must also have the 'mount' ability");
5341		break;
5342	case ZFS_DELEG_NOTE_DESTROY:
5343		str = gettext("Must also have the 'mount' ability");
5344		break;
5345	case ZFS_DELEG_NOTE_DIFF:
5346		str = gettext("Allows lookup of paths within a dataset;"
5347		    "\n\t\t\t\tgiven an object number. Ordinary users need this"
5348		    "\n\t\t\t\tin order to use zfs diff");
5349		break;
5350	case ZFS_DELEG_NOTE_HOLD:
5351		str = gettext("Allows adding a user hold to a snapshot");
5352		break;
5353	case ZFS_DELEG_NOTE_MOUNT:
5354		str = gettext("Allows mount/umount of ZFS datasets");
5355		break;
5356	case ZFS_DELEG_NOTE_PROMOTE:
5357		str = gettext("Must also have the 'mount'\n\t\t\t\tand"
5358		    " 'promote' ability in the origin file system");
5359		break;
5360	case ZFS_DELEG_NOTE_RECEIVE:
5361		str = gettext("Must also have the 'mount' and 'create'"
5362		    " ability");
5363		break;
5364	case ZFS_DELEG_NOTE_RELEASE:
5365		str = gettext("Allows releasing a user hold which\n\t\t\t\t"
5366		    "might destroy the snapshot");
5367		break;
5368	case ZFS_DELEG_NOTE_RENAME:
5369		str = gettext("Must also have the 'mount' and 'create'"
5370		    "\n\t\t\t\tability in the new parent");
5371		break;
5372	case ZFS_DELEG_NOTE_ROLLBACK:
5373		str = gettext("");
5374		break;
5375	case ZFS_DELEG_NOTE_SEND:
5376		str = gettext("");
5377		break;
5378	case ZFS_DELEG_NOTE_SHARE:
5379		str = gettext("Allows sharing file systems over NFS or SMB"
5380		    "\n\t\t\t\tprotocols");
5381		break;
5382	case ZFS_DELEG_NOTE_SNAPSHOT:
5383		str = gettext("");
5384		break;
5385	case ZFS_DELEG_NOTE_LOAD_KEY:
5386		str = gettext("Allows loading or unloading an encryption key");
5387		break;
5388	case ZFS_DELEG_NOTE_CHANGE_KEY:
5389		str = gettext("Allows changing or adding an encryption key");
5390		break;
5391/*
5392 *	case ZFS_DELEG_NOTE_VSCAN:
5393 *		str = gettext("");
5394 *		break;
5395 */
5396		/* OTHER */
5397	case ZFS_DELEG_NOTE_GROUPQUOTA:
5398		str = gettext("Allows accessing any groupquota@... property");
5399		break;
5400	case ZFS_DELEG_NOTE_GROUPUSED:
5401		str = gettext("Allows reading any groupused@... property");
5402		break;
5403	case ZFS_DELEG_NOTE_USERPROP:
5404		str = gettext("Allows changing any user property");
5405		break;
5406	case ZFS_DELEG_NOTE_USERQUOTA:
5407		str = gettext("Allows accessing any userquota@... property");
5408		break;
5409	case ZFS_DELEG_NOTE_USERUSED:
5410		str = gettext("Allows reading any userused@... property");
5411		break;
5412	case ZFS_DELEG_NOTE_USEROBJQUOTA:
5413		str = gettext("Allows accessing any userobjquota@... property");
5414		break;
5415	case ZFS_DELEG_NOTE_GROUPOBJQUOTA:
5416		str = gettext("Allows accessing any \n\t\t\t\t"
5417		    "groupobjquota@... property");
5418		break;
5419	case ZFS_DELEG_NOTE_GROUPOBJUSED:
5420		str = gettext("Allows reading any groupobjused@... property");
5421		break;
5422	case ZFS_DELEG_NOTE_USEROBJUSED:
5423		str = gettext("Allows reading any userobjused@... property");
5424		break;
5425	case ZFS_DELEG_NOTE_PROJECTQUOTA:
5426		str = gettext("Allows accessing any projectquota@... property");
5427		break;
5428	case ZFS_DELEG_NOTE_PROJECTOBJQUOTA:
5429		str = gettext("Allows accessing any \n\t\t\t\t"
5430		    "projectobjquota@... property");
5431		break;
5432	case ZFS_DELEG_NOTE_PROJECTUSED:
5433		str = gettext("Allows reading any projectused@... property");
5434		break;
5435	case ZFS_DELEG_NOTE_PROJECTOBJUSED:
5436		str = gettext("Allows accessing any \n\t\t\t\t"
5437		    "projectobjused@... property");
5438		break;
5439		/* other */
5440	default:
5441		str = "";
5442	}
5443
5444	return (str);
5445}
5446
5447struct allow_opts {
5448	boolean_t local;
5449	boolean_t descend;
5450	boolean_t user;
5451	boolean_t group;
5452	boolean_t everyone;
5453	boolean_t create;
5454	boolean_t set;
5455	boolean_t recursive; /* unallow only */
5456	boolean_t prt_usage;
5457
5458	boolean_t prt_perms;
5459	char *who;
5460	char *perms;
5461	const char *dataset;
5462};
5463
5464static inline int
5465prop_cmp(const void *a, const void *b)
5466{
5467	const char *str1 = *(const char **)a;
5468	const char *str2 = *(const char **)b;
5469	return (strcmp(str1, str2));
5470}
5471
5472static void
5473allow_usage(boolean_t un, boolean_t requested, const char *msg)
5474{
5475	const char *opt_desc[] = {
5476		"-h", gettext("show this help message and exit"),
5477		"-l", gettext("set permission locally"),
5478		"-d", gettext("set permission for descents"),
5479		"-u", gettext("set permission for user"),
5480		"-g", gettext("set permission for group"),
5481		"-e", gettext("set permission for everyone"),
5482		"-c", gettext("set create time permission"),
5483		"-s", gettext("define permission set"),
5484		/* unallow only */
5485		"-r", gettext("remove permissions recursively"),
5486	};
5487	size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
5488	size_t allow_size = unallow_size - 2;
5489	const char *props[ZFS_NUM_PROPS];
5490	int i;
5491	size_t count = 0;
5492	FILE *fp = requested ? stdout : stderr;
5493	zprop_desc_t *pdtbl = zfs_prop_get_table();
5494	const char *fmt = gettext("%-16s %-14s\t%s\n");
5495
5496	(void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
5497	    HELP_ALLOW));
5498	(void) fprintf(fp, gettext("Options:\n"));
5499	for (i = 0; i < (un ? unallow_size : allow_size); i += 2) {
5500		const char *opt = opt_desc[i];
5501		const char *optdsc = opt_desc[i + 1];
5502		(void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
5503	}
5504
5505	(void) fprintf(fp, gettext("\nThe following permissions are "
5506	    "supported:\n\n"));
5507	(void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
5508	    gettext("NOTES"));
5509	for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
5510		const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
5511		zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
5512		const char *perm_type = deleg_perm_type(perm_note);
5513		const char *perm_comment = deleg_perm_comment(perm_note);
5514		(void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
5515	}
5516
5517	for (i = 0; i < ZFS_NUM_PROPS; i++) {
5518		zprop_desc_t *pd = &pdtbl[i];
5519		if (pd->pd_visible != B_TRUE)
5520			continue;
5521
5522		if (pd->pd_attr == PROP_READONLY)
5523			continue;
5524
5525		props[count++] = pd->pd_name;
5526	}
5527	props[count] = NULL;
5528
5529	qsort(props, count, sizeof (char *), prop_cmp);
5530
5531	for (i = 0; i < count; i++)
5532		(void) fprintf(fp, fmt, props[i], gettext("property"), "");
5533
5534	if (msg != NULL)
5535		(void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
5536
5537	exit(requested ? 0 : 2);
5538}
5539
5540static inline const char *
5541munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
5542    char **permsp)
5543{
5544	if (un && argc == expected_argc - 1)
5545		*permsp = NULL;
5546	else if (argc == expected_argc)
5547		*permsp = argv[argc - 2];
5548	else
5549		allow_usage(un, B_FALSE,
5550		    gettext("wrong number of parameters\n"));
5551
5552	return (argv[argc - 1]);
5553}
5554
5555static void
5556parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
5557{
5558	int uge_sum = opts->user + opts->group + opts->everyone;
5559	int csuge_sum = opts->create + opts->set + uge_sum;
5560	int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
5561	int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
5562
5563	if (uge_sum > 1)
5564		allow_usage(un, B_FALSE,
5565		    gettext("-u, -g, and -e are mutually exclusive\n"));
5566
5567	if (opts->prt_usage) {
5568		if (argc == 0 && all_sum == 0)
5569			allow_usage(un, B_TRUE, NULL);
5570		else
5571			usage(B_FALSE);
5572	}
5573
5574	if (opts->set) {
5575		if (csuge_sum > 1)
5576			allow_usage(un, B_FALSE,
5577			    gettext("invalid options combined with -s\n"));
5578
5579		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
5580		if (argv[0][0] != '@')
5581			allow_usage(un, B_FALSE,
5582			    gettext("invalid set name: missing '@' prefix\n"));
5583		opts->who = argv[0];
5584	} else if (opts->create) {
5585		if (ldcsuge_sum > 1)
5586			allow_usage(un, B_FALSE,
5587			    gettext("invalid options combined with -c\n"));
5588		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
5589	} else if (opts->everyone) {
5590		if (csuge_sum > 1)
5591			allow_usage(un, B_FALSE,
5592			    gettext("invalid options combined with -e\n"));
5593		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
5594	} else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
5595	    == 0) {
5596		opts->everyone = B_TRUE;
5597		argc--;
5598		argv++;
5599		opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
5600	} else if (argc == 1 && !un) {
5601		opts->prt_perms = B_TRUE;
5602		opts->dataset = argv[argc-1];
5603	} else {
5604		opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
5605		opts->who = argv[0];
5606	}
5607
5608	if (!opts->local && !opts->descend) {
5609		opts->local = B_TRUE;
5610		opts->descend = B_TRUE;
5611	}
5612}
5613
5614static void
5615store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
5616    const char *who, char *perms, nvlist_t *top_nvl)
5617{
5618	int i;
5619	char ld[2] = { '\0', '\0' };
5620	char who_buf[MAXNAMELEN + 32];
5621	char base_type = '\0';
5622	char set_type = '\0';
5623	nvlist_t *base_nvl = NULL;
5624	nvlist_t *set_nvl = NULL;
5625	nvlist_t *nvl;
5626
5627	if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
5628		nomem();
5629	if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
5630		nomem();
5631
5632	switch (type) {
5633	case ZFS_DELEG_NAMED_SET_SETS:
5634	case ZFS_DELEG_NAMED_SET:
5635		set_type = ZFS_DELEG_NAMED_SET_SETS;
5636		base_type = ZFS_DELEG_NAMED_SET;
5637		ld[0] = ZFS_DELEG_NA;
5638		break;
5639	case ZFS_DELEG_CREATE_SETS:
5640	case ZFS_DELEG_CREATE:
5641		set_type = ZFS_DELEG_CREATE_SETS;
5642		base_type = ZFS_DELEG_CREATE;
5643		ld[0] = ZFS_DELEG_NA;
5644		break;
5645	case ZFS_DELEG_USER_SETS:
5646	case ZFS_DELEG_USER:
5647		set_type = ZFS_DELEG_USER_SETS;
5648		base_type = ZFS_DELEG_USER;
5649		if (local)
5650			ld[0] = ZFS_DELEG_LOCAL;
5651		if (descend)
5652			ld[1] = ZFS_DELEG_DESCENDENT;
5653		break;
5654	case ZFS_DELEG_GROUP_SETS:
5655	case ZFS_DELEG_GROUP:
5656		set_type = ZFS_DELEG_GROUP_SETS;
5657		base_type = ZFS_DELEG_GROUP;
5658		if (local)
5659			ld[0] = ZFS_DELEG_LOCAL;
5660		if (descend)
5661			ld[1] = ZFS_DELEG_DESCENDENT;
5662		break;
5663	case ZFS_DELEG_EVERYONE_SETS:
5664	case ZFS_DELEG_EVERYONE:
5665		set_type = ZFS_DELEG_EVERYONE_SETS;
5666		base_type = ZFS_DELEG_EVERYONE;
5667		if (local)
5668			ld[0] = ZFS_DELEG_LOCAL;
5669		if (descend)
5670			ld[1] = ZFS_DELEG_DESCENDENT;
5671		break;
5672
5673	default:
5674		assert(set_type != '\0' && base_type != '\0');
5675	}
5676
5677	if (perms != NULL) {
5678		char *curr = perms;
5679		char *end = curr + strlen(perms);
5680
5681		while (curr < end) {
5682			char *delim = strchr(curr, ',');
5683			if (delim == NULL)
5684				delim = end;
5685			else
5686				*delim = '\0';
5687
5688			if (curr[0] == '@')
5689				nvl = set_nvl;
5690			else
5691				nvl = base_nvl;
5692
5693			(void) nvlist_add_boolean(nvl, curr);
5694			if (delim != end)
5695				*delim = ',';
5696			curr = delim + 1;
5697		}
5698
5699		for (i = 0; i < 2; i++) {
5700			char locality = ld[i];
5701			if (locality == 0)
5702				continue;
5703
5704			if (!nvlist_empty(base_nvl)) {
5705				if (who != NULL)
5706					(void) snprintf(who_buf,
5707					    sizeof (who_buf), "%c%c$%s",
5708					    base_type, locality, who);
5709				else
5710					(void) snprintf(who_buf,
5711					    sizeof (who_buf), "%c%c$",
5712					    base_type, locality);
5713
5714				(void) nvlist_add_nvlist(top_nvl, who_buf,
5715				    base_nvl);
5716			}
5717
5718
5719			if (!nvlist_empty(set_nvl)) {
5720				if (who != NULL)
5721					(void) snprintf(who_buf,
5722					    sizeof (who_buf), "%c%c$%s",
5723					    set_type, locality, who);
5724				else
5725					(void) snprintf(who_buf,
5726					    sizeof (who_buf), "%c%c$",
5727					    set_type, locality);
5728
5729				(void) nvlist_add_nvlist(top_nvl, who_buf,
5730				    set_nvl);
5731			}
5732		}
5733	} else {
5734		for (i = 0; i < 2; i++) {
5735			char locality = ld[i];
5736			if (locality == 0)
5737				continue;
5738
5739			if (who != NULL)
5740				(void) snprintf(who_buf, sizeof (who_buf),
5741				    "%c%c$%s", base_type, locality, who);
5742			else
5743				(void) snprintf(who_buf, sizeof (who_buf),
5744				    "%c%c$", base_type, locality);
5745			(void) nvlist_add_boolean(top_nvl, who_buf);
5746
5747			if (who != NULL)
5748				(void) snprintf(who_buf, sizeof (who_buf),
5749				    "%c%c$%s", set_type, locality, who);
5750			else
5751				(void) snprintf(who_buf, sizeof (who_buf),
5752				    "%c%c$", set_type, locality);
5753			(void) nvlist_add_boolean(top_nvl, who_buf);
5754		}
5755	}
5756}
5757
5758static int
5759construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
5760{
5761	if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
5762		nomem();
5763
5764	if (opts->set) {
5765		store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
5766		    opts->descend, opts->who, opts->perms, *nvlp);
5767	} else if (opts->create) {
5768		store_allow_perm(ZFS_DELEG_CREATE, opts->local,
5769		    opts->descend, NULL, opts->perms, *nvlp);
5770	} else if (opts->everyone) {
5771		store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
5772		    opts->descend, NULL, opts->perms, *nvlp);
5773	} else {
5774		char *curr = opts->who;
5775		char *end = curr + strlen(curr);
5776
5777		while (curr < end) {
5778			const char *who;
5779			zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
5780			char *endch;
5781			char *delim = strchr(curr, ',');
5782			char errbuf[256];
5783			char id[64];
5784			struct passwd *p = NULL;
5785			struct group *g = NULL;
5786
5787			uid_t rid;
5788			if (delim == NULL)
5789				delim = end;
5790			else
5791				*delim = '\0';
5792
5793			rid = (uid_t)strtol(curr, &endch, 0);
5794			if (opts->user) {
5795				who_type = ZFS_DELEG_USER;
5796				if (*endch != '\0')
5797					p = getpwnam(curr);
5798				else
5799					p = getpwuid(rid);
5800
5801				if (p != NULL)
5802					rid = p->pw_uid;
5803				else if (*endch != '\0') {
5804					(void) snprintf(errbuf, 256, gettext(
5805					    "invalid user %s\n"), curr);
5806					allow_usage(un, B_TRUE, errbuf);
5807				}
5808			} else if (opts->group) {
5809				who_type = ZFS_DELEG_GROUP;
5810				if (*endch != '\0')
5811					g = getgrnam(curr);
5812				else
5813					g = getgrgid(rid);
5814
5815				if (g != NULL)
5816					rid = g->gr_gid;
5817				else if (*endch != '\0') {
5818					(void) snprintf(errbuf, 256, gettext(
5819					    "invalid group %s\n"),  curr);
5820					allow_usage(un, B_TRUE, errbuf);
5821				}
5822			} else {
5823				if (*endch != '\0') {
5824					p = getpwnam(curr);
5825				} else {
5826					p = getpwuid(rid);
5827				}
5828
5829				if (p == NULL) {
5830					if (*endch != '\0') {
5831						g = getgrnam(curr);
5832					} else {
5833						g = getgrgid(rid);
5834					}
5835				}
5836
5837				if (p != NULL) {
5838					who_type = ZFS_DELEG_USER;
5839					rid = p->pw_uid;
5840				} else if (g != NULL) {
5841					who_type = ZFS_DELEG_GROUP;
5842					rid = g->gr_gid;
5843				} else {
5844					(void) snprintf(errbuf, 256, gettext(
5845					    "invalid user/group %s\n"), curr);
5846					allow_usage(un, B_TRUE, errbuf);
5847				}
5848			}
5849
5850			(void) sprintf(id, "%u", rid);
5851			who = id;
5852
5853			store_allow_perm(who_type, opts->local,
5854			    opts->descend, who, opts->perms, *nvlp);
5855			curr = delim + 1;
5856		}
5857	}
5858
5859	return (0);
5860}
5861
5862static void
5863print_set_creat_perms(uu_avl_t *who_avl)
5864{
5865	const char *sc_title[] = {
5866		gettext("Permission sets:\n"),
5867		gettext("Create time permissions:\n"),
5868		NULL
5869	};
5870	who_perm_node_t *who_node = NULL;
5871	int prev_weight = -1;
5872
5873	for (who_node = uu_avl_first(who_avl); who_node != NULL;
5874	    who_node = uu_avl_next(who_avl, who_node)) {
5875		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5876		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5877		const char *who_name = who_node->who_perm.who_name;
5878		int weight = who_type2weight(who_type);
5879		boolean_t first = B_TRUE;
5880		deleg_perm_node_t *deleg_node;
5881
5882		if (prev_weight != weight) {
5883			(void) printf("%s", sc_title[weight]);
5884			prev_weight = weight;
5885		}
5886
5887		if (who_name == NULL || strnlen(who_name, 1) == 0)
5888			(void) printf("\t");
5889		else
5890			(void) printf("\t%s ", who_name);
5891
5892		for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5893		    deleg_node = uu_avl_next(avl, deleg_node)) {
5894			if (first) {
5895				(void) printf("%s",
5896				    deleg_node->dpn_perm.dp_name);
5897				first = B_FALSE;
5898			} else
5899				(void) printf(",%s",
5900				    deleg_node->dpn_perm.dp_name);
5901		}
5902
5903		(void) printf("\n");
5904	}
5905}
5906
5907static void
5908print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5909    const char *title)
5910{
5911	who_perm_node_t *who_node = NULL;
5912	boolean_t prt_title = B_TRUE;
5913	uu_avl_walk_t *walk;
5914
5915	if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5916		nomem();
5917
5918	while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5919		const char *who_name = who_node->who_perm.who_name;
5920		const char *nice_who_name = who_node->who_perm.who_ug_name;
5921		uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5922		zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5923		char delim = ' ';
5924		deleg_perm_node_t *deleg_node;
5925		boolean_t prt_who = B_TRUE;
5926
5927		for (deleg_node = uu_avl_first(avl);
5928		    deleg_node != NULL;
5929		    deleg_node = uu_avl_next(avl, deleg_node)) {
5930			if (local != deleg_node->dpn_perm.dp_local ||
5931			    descend != deleg_node->dpn_perm.dp_descend)
5932				continue;
5933
5934			if (prt_who) {
5935				const char *who = NULL;
5936				if (prt_title) {
5937					prt_title = B_FALSE;
5938					(void) printf("%s", title);
5939				}
5940
5941				switch (who_type) {
5942				case ZFS_DELEG_USER_SETS:
5943				case ZFS_DELEG_USER:
5944					who = gettext("user");
5945					if (nice_who_name)
5946						who_name  = nice_who_name;
5947					break;
5948				case ZFS_DELEG_GROUP_SETS:
5949				case ZFS_DELEG_GROUP:
5950					who = gettext("group");
5951					if (nice_who_name)
5952						who_name  = nice_who_name;
5953					break;
5954				case ZFS_DELEG_EVERYONE_SETS:
5955				case ZFS_DELEG_EVERYONE:
5956					who = gettext("everyone");
5957					who_name = NULL;
5958					break;
5959
5960				default:
5961					assert(who != NULL);
5962				}
5963
5964				prt_who = B_FALSE;
5965				if (who_name == NULL)
5966					(void) printf("\t%s", who);
5967				else
5968					(void) printf("\t%s %s", who, who_name);
5969			}
5970
5971			(void) printf("%c%s", delim,
5972			    deleg_node->dpn_perm.dp_name);
5973			delim = ',';
5974		}
5975
5976		if (!prt_who)
5977			(void) printf("\n");
5978	}
5979
5980	uu_avl_walk_end(walk);
5981}
5982
5983static void
5984print_fs_perms(fs_perm_set_t *fspset)
5985{
5986	fs_perm_node_t *node = NULL;
5987	char buf[MAXNAMELEN + 32];
5988	const char *dsname = buf;
5989
5990	for (node = uu_list_first(fspset->fsps_list); node != NULL;
5991	    node = uu_list_next(fspset->fsps_list, node)) {
5992		uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5993		uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5994		int left = 0;
5995
5996		(void) snprintf(buf, sizeof (buf),
5997		    gettext("---- Permissions on %s "),
5998		    node->fspn_fsperm.fsp_name);
5999		(void) printf("%s", dsname);
6000		left = 70 - strlen(buf);
6001		while (left-- > 0)
6002			(void) printf("-");
6003		(void) printf("\n");
6004
6005		print_set_creat_perms(sc_avl);
6006		print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
6007		    gettext("Local permissions:\n"));
6008		print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
6009		    gettext("Descendent permissions:\n"));
6010		print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
6011		    gettext("Local+Descendent permissions:\n"));
6012	}
6013}
6014
6015static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
6016
6017struct deleg_perms {
6018	boolean_t un;
6019	nvlist_t *nvl;
6020};
6021
6022static int
6023set_deleg_perms(zfs_handle_t *zhp, void *data)
6024{
6025	struct deleg_perms *perms = (struct deleg_perms *)data;
6026	zfs_type_t zfs_type = zfs_get_type(zhp);
6027
6028	if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
6029		return (0);
6030
6031	return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
6032}
6033
6034static int
6035zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
6036{
6037	zfs_handle_t *zhp;
6038	nvlist_t *perm_nvl = NULL;
6039	nvlist_t *update_perm_nvl = NULL;
6040	int error = 1;
6041	int c;
6042	struct allow_opts opts = { 0 };
6043
6044	const char *optstr = un ? "ldugecsrh" : "ldugecsh";
6045
6046	/* check opts */
6047	while ((c = getopt(argc, argv, optstr)) != -1) {
6048		switch (c) {
6049		case 'l':
6050			opts.local = B_TRUE;
6051			break;
6052		case 'd':
6053			opts.descend = B_TRUE;
6054			break;
6055		case 'u':
6056			opts.user = B_TRUE;
6057			break;
6058		case 'g':
6059			opts.group = B_TRUE;
6060			break;
6061		case 'e':
6062			opts.everyone = B_TRUE;
6063			break;
6064		case 's':
6065			opts.set = B_TRUE;
6066			break;
6067		case 'c':
6068			opts.create = B_TRUE;
6069			break;
6070		case 'r':
6071			opts.recursive = B_TRUE;
6072			break;
6073		case ':':
6074			(void) fprintf(stderr, gettext("missing argument for "
6075			    "'%c' option\n"), optopt);
6076			usage(B_FALSE);
6077			break;
6078		case 'h':
6079			opts.prt_usage = B_TRUE;
6080			break;
6081		case '?':
6082			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6083			    optopt);
6084			usage(B_FALSE);
6085		}
6086	}
6087
6088	argc -= optind;
6089	argv += optind;
6090
6091	/* check arguments */
6092	parse_allow_args(argc, argv, un, &opts);
6093
6094	/* try to open the dataset */
6095	if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
6096	    ZFS_TYPE_VOLUME)) == NULL) {
6097		(void) fprintf(stderr, "Failed to open dataset: %s\n",
6098		    opts.dataset);
6099		return (-1);
6100	}
6101
6102	if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
6103		goto cleanup2;
6104
6105	fs_perm_set_init(&fs_perm_set);
6106	if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
6107		(void) fprintf(stderr, "Failed to parse fsacl permissions\n");
6108		goto cleanup1;
6109	}
6110
6111	if (opts.prt_perms)
6112		print_fs_perms(&fs_perm_set);
6113	else {
6114		(void) construct_fsacl_list(un, &opts, &update_perm_nvl);
6115		if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
6116			goto cleanup0;
6117
6118		if (un && opts.recursive) {
6119			struct deleg_perms data = { un, update_perm_nvl };
6120			if (zfs_iter_filesystems(zhp, set_deleg_perms,
6121			    &data) != 0)
6122				goto cleanup0;
6123		}
6124	}
6125
6126	error = 0;
6127
6128cleanup0:
6129	nvlist_free(perm_nvl);
6130	nvlist_free(update_perm_nvl);
6131cleanup1:
6132	fs_perm_set_fini(&fs_perm_set);
6133cleanup2:
6134	zfs_close(zhp);
6135
6136	return (error);
6137}
6138
6139static int
6140zfs_do_allow(int argc, char **argv)
6141{
6142	return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
6143}
6144
6145static int
6146zfs_do_unallow(int argc, char **argv)
6147{
6148	return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
6149}
6150
6151static int
6152zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
6153{
6154	int errors = 0;
6155	int i;
6156	const char *tag;
6157	boolean_t recursive = B_FALSE;
6158	const char *opts = holding ? "rt" : "r";
6159	int c;
6160
6161	/* check options */
6162	while ((c = getopt(argc, argv, opts)) != -1) {
6163		switch (c) {
6164		case 'r':
6165			recursive = B_TRUE;
6166			break;
6167		case '?':
6168			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6169			    optopt);
6170			usage(B_FALSE);
6171		}
6172	}
6173
6174	argc -= optind;
6175	argv += optind;
6176
6177	/* check number of arguments */
6178	if (argc < 2)
6179		usage(B_FALSE);
6180
6181	tag = argv[0];
6182	--argc;
6183	++argv;
6184
6185	if (holding && tag[0] == '.') {
6186		/* tags starting with '.' are reserved for libzfs */
6187		(void) fprintf(stderr, gettext("tag may not start with '.'\n"));
6188		usage(B_FALSE);
6189	}
6190
6191	for (i = 0; i < argc; ++i) {
6192		zfs_handle_t *zhp;
6193		char parent[ZFS_MAX_DATASET_NAME_LEN];
6194		const char *delim;
6195		char *path = argv[i];
6196
6197		delim = strchr(path, '@');
6198		if (delim == NULL) {
6199			(void) fprintf(stderr,
6200			    gettext("'%s' is not a snapshot\n"), path);
6201			++errors;
6202			continue;
6203		}
6204		(void) strncpy(parent, path, delim - path);
6205		parent[delim - path] = '\0';
6206
6207		zhp = zfs_open(g_zfs, parent,
6208		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
6209		if (zhp == NULL) {
6210			++errors;
6211			continue;
6212		}
6213		if (holding) {
6214			if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
6215				++errors;
6216		} else {
6217			if (zfs_release(zhp, delim+1, tag, recursive) != 0)
6218				++errors;
6219		}
6220		zfs_close(zhp);
6221	}
6222
6223	return (errors != 0);
6224}
6225
6226/*
6227 * zfs hold [-r] [-t] <tag> <snap> ...
6228 *
6229 *	-r	Recursively hold
6230 *
6231 * Apply a user-hold with the given tag to the list of snapshots.
6232 */
6233static int
6234zfs_do_hold(int argc, char **argv)
6235{
6236	return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
6237}
6238
6239/*
6240 * zfs release [-r] <tag> <snap> ...
6241 *
6242 *	-r	Recursively release
6243 *
6244 * Release a user-hold with the given tag from the list of snapshots.
6245 */
6246static int
6247zfs_do_release(int argc, char **argv)
6248{
6249	return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
6250}
6251
6252typedef struct holds_cbdata {
6253	boolean_t	cb_recursive;
6254	const char	*cb_snapname;
6255	nvlist_t	**cb_nvlp;
6256	size_t		cb_max_namelen;
6257	size_t		cb_max_taglen;
6258} holds_cbdata_t;
6259
6260#define	STRFTIME_FMT_STR "%a %b %e %H:%M %Y"
6261#define	DATETIME_BUF_LEN (32)
6262/*
6263 *
6264 */
6265static void
6266print_holds(boolean_t scripted, int nwidth, int tagwidth, nvlist_t *nvl)
6267{
6268	int i;
6269	nvpair_t *nvp = NULL;
6270	char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
6271	const char *col;
6272
6273	if (!scripted) {
6274		for (i = 0; i < 3; i++) {
6275			col = gettext(hdr_cols[i]);
6276			if (i < 2)
6277				(void) printf("%-*s  ", i ? tagwidth : nwidth,
6278				    col);
6279			else
6280				(void) printf("%s\n", col);
6281		}
6282	}
6283
6284	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6285		char *zname = nvpair_name(nvp);
6286		nvlist_t *nvl2;
6287		nvpair_t *nvp2 = NULL;
6288		(void) nvpair_value_nvlist(nvp, &nvl2);
6289		while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
6290			char tsbuf[DATETIME_BUF_LEN];
6291			char *tagname = nvpair_name(nvp2);
6292			uint64_t val = 0;
6293			time_t time;
6294			struct tm t;
6295
6296			(void) nvpair_value_uint64(nvp2, &val);
6297			time = (time_t)val;
6298			(void) localtime_r(&time, &t);
6299			(void) strftime(tsbuf, DATETIME_BUF_LEN,
6300			    gettext(STRFTIME_FMT_STR), &t);
6301
6302			if (scripted) {
6303				(void) printf("%s\t%s\t%s\n", zname,
6304				    tagname, tsbuf);
6305			} else {
6306				(void) printf("%-*s  %-*s  %s\n", nwidth,
6307				    zname, tagwidth, tagname, tsbuf);
6308			}
6309		}
6310	}
6311}
6312
6313/*
6314 * Generic callback function to list a dataset or snapshot.
6315 */
6316static int
6317holds_callback(zfs_handle_t *zhp, void *data)
6318{
6319	holds_cbdata_t *cbp = data;
6320	nvlist_t *top_nvl = *cbp->cb_nvlp;
6321	nvlist_t *nvl = NULL;
6322	nvpair_t *nvp = NULL;
6323	const char *zname = zfs_get_name(zhp);
6324	size_t znamelen = strlen(zname);
6325
6326	if (cbp->cb_recursive) {
6327		const char *snapname;
6328		char *delim  = strchr(zname, '@');
6329		if (delim == NULL)
6330			return (0);
6331
6332		snapname = delim + 1;
6333		if (strcmp(cbp->cb_snapname, snapname))
6334			return (0);
6335	}
6336
6337	if (zfs_get_holds(zhp, &nvl) != 0)
6338		return (-1);
6339
6340	if (znamelen > cbp->cb_max_namelen)
6341		cbp->cb_max_namelen  = znamelen;
6342
6343	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
6344		const char *tag = nvpair_name(nvp);
6345		size_t taglen = strlen(tag);
6346		if (taglen > cbp->cb_max_taglen)
6347			cbp->cb_max_taglen  = taglen;
6348	}
6349
6350	return (nvlist_add_nvlist(top_nvl, zname, nvl));
6351}
6352
6353/*
6354 * zfs holds [-rH] <snap> ...
6355 *
6356 *	-r	Lists holds that are set on the named snapshots recursively.
6357 *	-H	Scripted mode; elide headers and separate columns by tabs.
6358 */
6359static int
6360zfs_do_holds(int argc, char **argv)
6361{
6362	int errors = 0;
6363	int c;
6364	int i;
6365	boolean_t scripted = B_FALSE;
6366	boolean_t recursive = B_FALSE;
6367	const char *opts = "rH";
6368	nvlist_t *nvl;
6369
6370	int types = ZFS_TYPE_SNAPSHOT;
6371	holds_cbdata_t cb = { 0 };
6372
6373	int limit = 0;
6374	int ret = 0;
6375	int flags = 0;
6376
6377	/* check options */
6378	while ((c = getopt(argc, argv, opts)) != -1) {
6379		switch (c) {
6380		case 'r':
6381			recursive = B_TRUE;
6382			break;
6383		case 'H':
6384			scripted = B_TRUE;
6385			break;
6386		case '?':
6387			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
6388			    optopt);
6389			usage(B_FALSE);
6390		}
6391	}
6392
6393	if (recursive) {
6394		types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
6395		flags |= ZFS_ITER_RECURSE;
6396	}
6397
6398	argc -= optind;
6399	argv += optind;
6400
6401	/* check number of arguments */
6402	if (argc < 1)
6403		usage(B_FALSE);
6404
6405	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
6406		nomem();
6407
6408	for (i = 0; i < argc; ++i) {
6409		char *snapshot = argv[i];
6410		const char *delim;
6411		const char *snapname;
6412
6413		delim =