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