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