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