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