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