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