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