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