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