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