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