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