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