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