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