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