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