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