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