xref: /titanic_41/usr/src/cmd/zfs/zfs_main.c (revision f4da9be01648d6afa604495d9b9956dddeb92a8c)
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 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <assert.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <libgen.h>
33 #include <libintl.h>
34 #include <libuutil.h>
35 #include <locale.h>
36 #include <stddef.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42 #include <zone.h>
43 #include <sys/mkdev.h>
44 #include <sys/mntent.h>
45 #include <sys/mnttab.h>
46 #include <sys/mount.h>
47 #include <sys/stat.h>
48 
49 #include <libzfs.h>
50 
51 #include "zfs_iter.h"
52 #include "zfs_util.h"
53 
54 libzfs_handle_t *g_zfs;
55 
56 static FILE *mnttab_file;
57 
58 static int zfs_do_clone(int argc, char **argv);
59 static int zfs_do_create(int argc, char **argv);
60 static int zfs_do_destroy(int argc, char **argv);
61 static int zfs_do_get(int argc, char **argv);
62 static int zfs_do_inherit(int argc, char **argv);
63 static int zfs_do_list(int argc, char **argv);
64 static int zfs_do_mount(int argc, char **argv);
65 static int zfs_do_rename(int argc, char **argv);
66 static int zfs_do_rollback(int argc, char **argv);
67 static int zfs_do_set(int argc, char **argv);
68 static int zfs_do_snapshot(int argc, char **argv);
69 static int zfs_do_unmount(int argc, char **argv);
70 static int zfs_do_share(int argc, char **argv);
71 static int zfs_do_unshare(int argc, char **argv);
72 static int zfs_do_send(int argc, char **argv);
73 static int zfs_do_receive(int argc, char **argv);
74 static int zfs_do_promote(int argc, char **argv);
75 
76 /*
77  * These libumem hooks provide a reasonable set of defaults for the allocator's
78  * debugging facilities.
79  */
80 const char *
81 _umem_debug_init(void)
82 {
83 	return ("default,verbose"); /* $UMEM_DEBUG setting */
84 }
85 
86 const char *
87 _umem_logging_init(void)
88 {
89 	return ("fail,contents"); /* $UMEM_LOGGING setting */
90 }
91 
92 typedef enum {
93 	HELP_CLONE,
94 	HELP_CREATE,
95 	HELP_DESTROY,
96 	HELP_GET,
97 	HELP_INHERIT,
98 	HELP_LIST,
99 	HELP_MOUNT,
100 	HELP_PROMOTE,
101 	HELP_RECEIVE,
102 	HELP_RENAME,
103 	HELP_ROLLBACK,
104 	HELP_SEND,
105 	HELP_SET,
106 	HELP_SHARE,
107 	HELP_SNAPSHOT,
108 	HELP_UNMOUNT,
109 	HELP_UNSHARE
110 } zfs_help_t;
111 
112 typedef struct zfs_command {
113 	const char	*name;
114 	int		(*func)(int argc, char **argv);
115 	zfs_help_t	usage;
116 } zfs_command_t;
117 
118 /*
119  * Master command table.  Each ZFS command has a name, associated function, and
120  * usage message.  The usage messages need to be internationalized, so we have
121  * to have a function to return the usage message based on a command index.
122  *
123  * These commands are organized according to how they are displayed in the usage
124  * message.  An empty command (one with a NULL name) indicates an empty line in
125  * the generic usage message.
126  */
127 static zfs_command_t command_table[] = {
128 	{ "create",	zfs_do_create,		HELP_CREATE		},
129 	{ "destroy",	zfs_do_destroy,		HELP_DESTROY		},
130 	{ NULL },
131 	{ "snapshot",	zfs_do_snapshot,	HELP_SNAPSHOT		},
132 	{ "rollback",	zfs_do_rollback,	HELP_ROLLBACK		},
133 	{ "clone",	zfs_do_clone,		HELP_CLONE		},
134 	{ "promote",	zfs_do_promote,		HELP_PROMOTE		},
135 	{ "rename",	zfs_do_rename,		HELP_RENAME		},
136 	{ NULL },
137 	{ "list",	zfs_do_list,		HELP_LIST		},
138 	{ NULL },
139 	{ "set",	zfs_do_set,		HELP_SET		},
140 	{ "get", 	zfs_do_get,		HELP_GET		},
141 	{ "inherit",	zfs_do_inherit,		HELP_INHERIT		},
142 	{ NULL },
143 	{ "mount",	zfs_do_mount,		HELP_MOUNT		},
144 	{ NULL },
145 	{ "unmount",	zfs_do_unmount,		HELP_UNMOUNT		},
146 	{ NULL },
147 	{ "share",	zfs_do_share,		HELP_SHARE		},
148 	{ NULL },
149 	{ "unshare",	zfs_do_unshare,		HELP_UNSHARE		},
150 	{ NULL },
151 	{ "send",	zfs_do_send,		HELP_SEND		},
152 	{ "receive",	zfs_do_receive,		HELP_RECEIVE		},
153 };
154 
155 #define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
156 
157 zfs_command_t *current_command;
158 
159 static const char *
160 get_usage(zfs_help_t idx)
161 {
162 	switch (idx) {
163 	case HELP_CLONE:
164 		return (gettext("\tclone <snapshot> <filesystem|volume>\n"));
165 	case HELP_CREATE:
166 		return (gettext("\tcreate [[-o property=value] ... ] "
167 		    "<filesystem>\n"
168 		    "\tcreate [-s] [-b blocksize] [[-o property=value] ...]\n"
169 		    "\t    -V <size> <volume>\n"));
170 	case HELP_DESTROY:
171 		return (gettext("\tdestroy [-rRf] "
172 		    "<filesystem|volume|snapshot>\n"));
173 	case HELP_GET:
174 		return (gettext("\tget [-rHp] [-o field[,field]...] "
175 		    "[-s source[,source]...]\n"
176 		    "\t    <all | property[,property]...> "
177 		    "[filesystem|volume|snapshot] ...\n"));
178 	case HELP_INHERIT:
179 		return (gettext("\tinherit [-r] <property> "
180 		    "<filesystem|volume> ...\n"));
181 	case HELP_LIST:
182 		return (gettext("\tlist [-rH] [-o property[,property]...] "
183 		    "[-t type[,type]...]\n"
184 		    "\t    [-s property [-s property]...]"
185 		    " [-S property [-S property]...]\n"
186 		    "\t    [filesystem|volume|snapshot] ...\n"));
187 	case HELP_MOUNT:
188 		return (gettext("\tmount\n"
189 		    "\tmount [-o opts] [-O] -a\n"
190 		    "\tmount [-o opts] [-O] <filesystem>\n"));
191 	case HELP_PROMOTE:
192 		return (gettext("\tpromote <clone filesystem>\n"));
193 	case HELP_RECEIVE:
194 		return (gettext("\treceive [-vnF] <filesystem|volume|"
195 		"snapshot>\n"
196 		"\treceive [-vnF] -d <filesystem>\n"));
197 	case HELP_RENAME:
198 		return (gettext("\trename <filesystem|volume|snapshot> "
199 		    "<filesystem|volume|snapshot>\n"
200 		    "\trename -r <snapshot> <snapshot>"));
201 	case HELP_ROLLBACK:
202 		return (gettext("\trollback [-rRf] <snapshot>\n"));
203 	case HELP_SEND:
204 		return (gettext("\tsend [-i <snapshot>] <snapshot>\n"));
205 	case HELP_SET:
206 		return (gettext("\tset <property=value> "
207 		    "<filesystem|volume> ...\n"));
208 	case HELP_SHARE:
209 		return (gettext("\tshare -a\n"
210 		    "\tshare <filesystem>\n"));
211 	case HELP_SNAPSHOT:
212 		return (gettext("\tsnapshot [-r] "
213 		    "<filesystem@name|volume@name>\n"));
214 	case HELP_UNMOUNT:
215 		return (gettext("\tunmount [-f] -a\n"
216 		    "\tunmount [-f] <filesystem|mountpoint>\n"));
217 	case HELP_UNSHARE:
218 		return (gettext("\tunshare [-f] -a\n"
219 		    "\tunshare [-f] <filesystem|mountpoint>\n"));
220 	}
221 
222 	abort();
223 	/* NOTREACHED */
224 }
225 
226 /*
227  * Utility function to guarantee malloc() success.
228  */
229 void *
230 safe_malloc(size_t size)
231 {
232 	void *data;
233 
234 	if ((data = calloc(1, size)) == NULL) {
235 		(void) fprintf(stderr, "internal error: out of memory\n");
236 		exit(1);
237 	}
238 
239 	return (data);
240 }
241 
242 /*
243  * Callback routinue that will print out information for each of the
244  * the properties.
245  */
246 static zfs_prop_t
247 usage_prop_cb(zfs_prop_t prop, void *cb)
248 {
249 	FILE *fp = cb;
250 
251 	(void) fprintf(fp, "\t%-13s  ", zfs_prop_to_name(prop));
252 
253 	if (zfs_prop_readonly(prop))
254 		(void) fprintf(fp, "  NO    ");
255 	else
256 		(void) fprintf(fp, " YES    ");
257 
258 	if (zfs_prop_inheritable(prop))
259 		(void) fprintf(fp, "  YES   ");
260 	else
261 		(void) fprintf(fp, "   NO   ");
262 
263 	if (zfs_prop_values(prop) == NULL)
264 		(void) fprintf(fp, "-\n");
265 	else
266 		(void) fprintf(fp, "%s\n", zfs_prop_values(prop));
267 
268 	return (ZFS_PROP_CONT);
269 }
270 
271 /*
272  * Display usage message.  If we're inside a command, display only the usage for
273  * that command.  Otherwise, iterate over the entire command table and display
274  * a complete usage message.
275  */
276 static void
277 usage(boolean_t requested)
278 {
279 	int i;
280 	boolean_t show_properties = B_FALSE;
281 	FILE *fp = requested ? stdout : stderr;
282 
283 	if (current_command == NULL) {
284 
285 		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
286 		(void) fprintf(fp,
287 		    gettext("where 'command' is one of the following:\n\n"));
288 
289 		for (i = 0; i < NCOMMAND; i++) {
290 			if (command_table[i].name == NULL)
291 				(void) fprintf(fp, "\n");
292 			else
293 				(void) fprintf(fp, "%s",
294 				    get_usage(command_table[i].usage));
295 		}
296 
297 		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
298 		    "pool/[dataset/]*dataset[@name]\n"));
299 	} else {
300 		(void) fprintf(fp, gettext("usage:\n"));
301 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
302 	}
303 
304 	if (current_command != NULL &&
305 	    (strcmp(current_command->name, "set") == 0 ||
306 	    strcmp(current_command->name, "get") == 0 ||
307 	    strcmp(current_command->name, "inherit") == 0 ||
308 	    strcmp(current_command->name, "list") == 0))
309 		show_properties = B_TRUE;
310 
311 	if (show_properties) {
312 
313 		(void) fprintf(fp,
314 		    gettext("\nThe following properties are supported:\n"));
315 
316 		(void) fprintf(fp, "\n\t%-13s  %s  %s   %s\n\n",
317 		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
318 
319 		/* Iterate over all properties */
320 		(void) zfs_prop_iter(usage_prop_cb, fp, B_FALSE);
321 
322 		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
323 		    "with standard units such as K, M, G, etc.\n"));
324 		(void) fprintf(fp, gettext("\n\nUser-defined properties can "
325 		    "be specified by using a name containing a colon (:).\n"));
326 	} else {
327 		/*
328 		 * TRANSLATION NOTE:
329 		 * "zfs set|get" must not be localised this is the
330 		 * command name and arguments.
331 		 */
332 		(void) fprintf(fp,
333 		    gettext("\nFor the property list, run: zfs set|get\n"));
334 	}
335 
336 	/*
337 	 * See comments at end of main().
338 	 */
339 	if (getenv("ZFS_ABORT") != NULL) {
340 		(void) printf("dumping core by request\n");
341 		abort();
342 	}
343 
344 	exit(requested ? 0 : 2);
345 }
346 
347 /*
348  * zfs clone <fs, snap, vol> fs
349  *
350  * Given an existing dataset, create a writable copy whose initial contents
351  * are the same as the source.  The newly created dataset maintains a
352  * dependency on the original; the original cannot be destroyed so long as
353  * the clone exists.
354  */
355 static int
356 zfs_do_clone(int argc, char **argv)
357 {
358 	zfs_handle_t *zhp;
359 	int ret;
360 
361 	/* check options */
362 	if (argc > 1 && argv[1][0] == '-') {
363 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
364 		    argv[1][1]);
365 		usage(B_FALSE);
366 	}
367 
368 	/* check number of arguments */
369 	if (argc < 2) {
370 		(void) fprintf(stderr, gettext("missing source dataset "
371 		    "argument\n"));
372 		usage(B_FALSE);
373 	}
374 	if (argc < 3) {
375 		(void) fprintf(stderr, gettext("missing target dataset "
376 		    "argument\n"));
377 		usage(B_FALSE);
378 	}
379 	if (argc > 3) {
380 		(void) fprintf(stderr, gettext("too many arguments\n"));
381 		usage(B_FALSE);
382 	}
383 
384 	/* open the source dataset */
385 	if ((zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_SNAPSHOT)) == NULL)
386 		return (1);
387 
388 	/* pass to libzfs */
389 	ret = zfs_clone(zhp, argv[2], NULL);
390 
391 	/* create the mountpoint if necessary */
392 	if (ret == 0) {
393 		zfs_handle_t *clone = zfs_open(g_zfs, argv[2], ZFS_TYPE_ANY);
394 		if (clone != NULL) {
395 			if ((ret = zfs_mount(clone, NULL, 0)) == 0)
396 				ret = zfs_share(clone);
397 			zfs_close(clone);
398 		}
399 		zpool_log_history(g_zfs, argc, argv, argv[2], B_FALSE, B_FALSE);
400 	}
401 
402 	zfs_close(zhp);
403 
404 	return (ret == 0 ? 0 : 1);
405 }
406 
407 /*
408  * zfs create [-o prop=value] ... fs
409  * zfs create [-s] [-b blocksize] [-o prop=value] ... -V vol size
410  *
411  * Create a new dataset.  This command can be used to create filesystems
412  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
413  * For volumes, the user must specify a size to be used.
414  *
415  * The '-s' flag applies only to volumes, and indicates that we should not try
416  * to set the reservation for this volume.  By default we set a reservation
417  * equal to the size for any volume.
418  */
419 static int
420 zfs_do_create(int argc, char **argv)
421 {
422 	zfs_type_t type = ZFS_TYPE_FILESYSTEM;
423 	zfs_handle_t *zhp = NULL;
424 	uint64_t volsize;
425 	int c;
426 	boolean_t noreserve = B_FALSE;
427 	int ret = 1;
428 	nvlist_t *props = NULL;
429 	uint64_t intval;
430 	char *propname;
431 	char *propval = NULL;
432 	char *strval;
433 
434 	if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
435 		(void) fprintf(stderr, gettext("internal error: "
436 		    "out of memory\n"));
437 		return (1);
438 	}
439 
440 	/* check options */
441 	while ((c = getopt(argc, argv, ":V:b:so:")) != -1) {
442 		switch (c) {
443 		case 'V':
444 			type = ZFS_TYPE_VOLUME;
445 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
446 				(void) fprintf(stderr, gettext("bad volume "
447 				    "size '%s': %s\n"), optarg,
448 				    libzfs_error_description(g_zfs));
449 				goto error;
450 			}
451 
452 			if (nvlist_add_uint64(props,
453 			    zfs_prop_to_name(ZFS_PROP_VOLSIZE),
454 			    intval) != 0) {
455 				(void) fprintf(stderr, gettext("internal "
456 				    "error: out of memory\n"));
457 				goto error;
458 			}
459 			volsize = intval;
460 			break;
461 		case 'b':
462 			if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
463 				(void) fprintf(stderr, gettext("bad volume "
464 				    "block size '%s': %s\n"), optarg,
465 				    libzfs_error_description(g_zfs));
466 				goto error;
467 			}
468 
469 			if (nvlist_add_uint64(props,
470 			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
471 			    intval) != 0) {
472 				(void) fprintf(stderr, gettext("internal "
473 				    "error: out of memory\n"));
474 				goto error;
475 			}
476 			break;
477 		case 'o':
478 			propname = optarg;
479 			if ((propval = strchr(propname, '=')) == NULL) {
480 				(void) fprintf(stderr, gettext("missing "
481 				    "'=' for -o option\n"));
482 				goto error;
483 			}
484 			*propval = '\0';
485 			propval++;
486 			if (nvlist_lookup_string(props, propname,
487 			    &strval) == 0) {
488 				(void) fprintf(stderr, gettext("property '%s' "
489 				    "specified multiple times\n"), propname);
490 				goto error;
491 			}
492 			if (nvlist_add_string(props, propname, propval) != 0) {
493 				(void) fprintf(stderr, gettext("internal "
494 				    "error: out of memory\n"));
495 				goto error;
496 			}
497 			break;
498 		case 's':
499 			noreserve = B_TRUE;
500 			break;
501 		case ':':
502 			(void) fprintf(stderr, gettext("missing size "
503 			    "argument\n"));
504 			goto badusage;
505 			break;
506 		case '?':
507 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
508 			    optopt);
509 			goto badusage;
510 		}
511 	}
512 
513 	if (noreserve && type != ZFS_TYPE_VOLUME) {
514 		(void) fprintf(stderr, gettext("'-s' can only be used when "
515 		    "creating a volume\n"));
516 		goto badusage;
517 	}
518 
519 	argc -= optind;
520 	argv += optind;
521 
522 	/* check number of arguments */
523 	if (argc == 0) {
524 		(void) fprintf(stderr, gettext("missing %s argument\n"),
525 		    zfs_type_to_name(type));
526 		goto badusage;
527 	}
528 	if (argc > 1) {
529 		(void) fprintf(stderr, gettext("too many arguments\n"));
530 		goto badusage;
531 	}
532 
533 	if (type == ZFS_TYPE_VOLUME && !noreserve &&
534 	    nvlist_lookup_string(props, zfs_prop_to_name(ZFS_PROP_RESERVATION),
535 	    &strval) != 0) {
536 		if (nvlist_add_uint64(props,
537 		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
538 		    volsize) != 0) {
539 			(void) fprintf(stderr, gettext("internal "
540 			    "error: out of memory\n"));
541 			nvlist_free(props);
542 			return (1);
543 		}
544 	}
545 
546 	/* pass to libzfs */
547 	if (zfs_create(g_zfs, argv[0], type, props) != 0)
548 		goto error;
549 
550 	if (propval != NULL)
551 		*(propval - 1) = '=';
552 	zpool_log_history(g_zfs, argc + optind, argv - optind, argv[0],
553 	    B_FALSE, B_FALSE);
554 
555 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_ANY)) == NULL)
556 		goto error;
557 
558 	/*
559 	 * Mount and/or share the new filesystem as appropriate.  We provide a
560 	 * verbose error message to let the user know that their filesystem was
561 	 * in fact created, even if we failed to mount or share it.
562 	 */
563 	if (zfs_mount(zhp, NULL, 0) != 0) {
564 		(void) fprintf(stderr, gettext("filesystem successfully "
565 		    "created, but not mounted\n"));
566 		ret = 1;
567 	} else if (zfs_share(zhp) != 0) {
568 		(void) fprintf(stderr, gettext("filesystem successfully "
569 		    "created, but not shared\n"));
570 		ret = 1;
571 	} else {
572 		ret = 0;
573 	}
574 
575 error:
576 	if (zhp)
577 		zfs_close(zhp);
578 	nvlist_free(props);
579 	return (ret);
580 badusage:
581 	nvlist_free(props);
582 	usage(B_FALSE);
583 	return (2);
584 }
585 
586 /*
587  * zfs destroy [-rf] <fs, snap, vol>
588  *
589  * 	-r	Recursively destroy all children
590  * 	-R	Recursively destroy all dependents, including clones
591  * 	-f	Force unmounting of any dependents
592  *
593  * Destroys the given dataset.  By default, it will unmount any filesystems,
594  * and refuse to destroy a dataset that has any dependents.  A dependent can
595  * either be a child, or a clone of a child.
596  */
597 typedef struct destroy_cbdata {
598 	boolean_t	cb_first;
599 	int		cb_force;
600 	int		cb_recurse;
601 	int		cb_error;
602 	int		cb_needforce;
603 	int		cb_doclones;
604 	boolean_t	cb_closezhp;
605 	zfs_handle_t	*cb_target;
606 	char		*cb_snapname;
607 } destroy_cbdata_t;
608 
609 /*
610  * Check for any dependents based on the '-r' or '-R' flags.
611  */
612 static int
613 destroy_check_dependent(zfs_handle_t *zhp, void *data)
614 {
615 	destroy_cbdata_t *cbp = data;
616 	const char *tname = zfs_get_name(cbp->cb_target);
617 	const char *name = zfs_get_name(zhp);
618 
619 	if (strncmp(tname, name, strlen(tname)) == 0 &&
620 	    (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
621 		/*
622 		 * This is a direct descendant, not a clone somewhere else in
623 		 * the hierarchy.
624 		 */
625 		if (cbp->cb_recurse)
626 			goto out;
627 
628 		if (cbp->cb_first) {
629 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
630 			    "%s has children\n"),
631 			    zfs_get_name(cbp->cb_target),
632 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
633 			(void) fprintf(stderr, gettext("use '-r' to destroy "
634 			    "the following datasets:\n"));
635 			cbp->cb_first = B_FALSE;
636 			cbp->cb_error = 1;
637 		}
638 
639 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
640 	} else {
641 		/*
642 		 * This is a clone.  We only want to report this if the '-r'
643 		 * wasn't specified, or the target is a snapshot.
644 		 */
645 		if (!cbp->cb_recurse &&
646 		    zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
647 			goto out;
648 
649 		if (cbp->cb_first) {
650 			(void) fprintf(stderr, gettext("cannot destroy '%s': "
651 			    "%s has dependent clones\n"),
652 			    zfs_get_name(cbp->cb_target),
653 			    zfs_type_to_name(zfs_get_type(cbp->cb_target)));
654 			(void) fprintf(stderr, gettext("use '-R' to destroy "
655 			    "the following datasets:\n"));
656 			cbp->cb_first = B_FALSE;
657 			cbp->cb_error = 1;
658 		}
659 
660 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
661 	}
662 
663 out:
664 	zfs_close(zhp);
665 	return (0);
666 }
667 
668 static int
669 destroy_callback(zfs_handle_t *zhp, void *data)
670 {
671 	destroy_cbdata_t *cbp = data;
672 
673 	/*
674 	 * Ignore pools (which we've already flagged as an error before getting
675 	 * here.
676 	 */
677 	if (strchr(zfs_get_name(zhp), '/') == NULL &&
678 	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
679 		zfs_close(zhp);
680 		return (0);
681 	}
682 
683 	/*
684 	 * Bail out on the first error.
685 	 */
686 	if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
687 	    zfs_destroy(zhp) != 0) {
688 		zfs_close(zhp);
689 		return (-1);
690 	}
691 
692 	zfs_close(zhp);
693 	return (0);
694 }
695 
696 static int
697 destroy_snap_clones(zfs_handle_t *zhp, void *arg)
698 {
699 	destroy_cbdata_t *cbp = arg;
700 	char thissnap[MAXPATHLEN];
701 	zfs_handle_t *szhp;
702 	boolean_t closezhp = cbp->cb_closezhp;
703 	int rv;
704 
705 	(void) snprintf(thissnap, sizeof (thissnap),
706 	    "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
707 
708 	libzfs_print_on_error(g_zfs, B_FALSE);
709 	szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
710 	libzfs_print_on_error(g_zfs, B_TRUE);
711 	if (szhp) {
712 		/*
713 		 * Destroy any clones of this snapshot
714 		 */
715 		if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
716 		    cbp) != 0) {
717 			zfs_close(szhp);
718 			if (closezhp)
719 				zfs_close(zhp);
720 			return (-1);
721 		}
722 		zfs_close(szhp);
723 	}
724 
725 	cbp->cb_closezhp = B_TRUE;
726 	rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
727 	if (closezhp)
728 		zfs_close(zhp);
729 	return (rv);
730 }
731 
732 static int
733 zfs_do_destroy(int argc, char **argv)
734 {
735 	destroy_cbdata_t cb = { 0 };
736 	int c;
737 	zfs_handle_t *zhp;
738 	char *cp;
739 
740 	/* check options */
741 	while ((c = getopt(argc, argv, "frR")) != -1) {
742 		switch (c) {
743 		case 'f':
744 			cb.cb_force = 1;
745 			break;
746 		case 'r':
747 			cb.cb_recurse = 1;
748 			break;
749 		case 'R':
750 			cb.cb_recurse = 1;
751 			cb.cb_doclones = 1;
752 			break;
753 		case '?':
754 		default:
755 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
756 			    optopt);
757 			usage(B_FALSE);
758 		}
759 	}
760 
761 	argc -= optind;
762 	argv += optind;
763 
764 	/* check number of arguments */
765 	if (argc == 0) {
766 		(void) fprintf(stderr, gettext("missing path argument\n"));
767 		usage(B_FALSE);
768 	}
769 	if (argc > 1) {
770 		(void) fprintf(stderr, gettext("too many arguments\n"));
771 		usage(B_FALSE);
772 	}
773 
774 	/*
775 	 * If we are doing recursive destroy of a snapshot, then the
776 	 * named snapshot may not exist.  Go straight to libzfs.
777 	 */
778 	if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
779 		int ret;
780 
781 		*cp = '\0';
782 		if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_ANY)) == NULL)
783 			return (1);
784 		*cp = '@';
785 		cp++;
786 
787 		if (cb.cb_doclones) {
788 			cb.cb_snapname = cp;
789 			if (destroy_snap_clones(zhp, &cb) != 0) {
790 				zfs_close(zhp);
791 				return (1);
792 			}
793 		}
794 
795 		ret = zfs_destroy_snaps(zhp, cp);
796 		zfs_close(zhp);
797 		if (ret) {
798 			(void) fprintf(stderr,
799 			    gettext("no snapshots destroyed\n"));
800 		} else {
801 			zpool_log_history(g_zfs, argc + optind, argv - optind,
802 			    argv[0], B_FALSE, B_FALSE);
803 		}
804 		return (ret != 0);
805 	}
806 
807 
808 	/* Open the given dataset */
809 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_ANY)) == NULL)
810 		return (1);
811 
812 	cb.cb_target = zhp;
813 
814 	/*
815 	 * Perform an explicit check for pools before going any further.
816 	 */
817 	if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
818 	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
819 		(void) fprintf(stderr, gettext("cannot destroy '%s': "
820 		    "operation does not apply to pools\n"),
821 		    zfs_get_name(zhp));
822 		(void) fprintf(stderr, gettext("use 'zfs destroy -r "
823 		    "%s' to destroy all datasets in the pool\n"),
824 		    zfs_get_name(zhp));
825 		(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
826 		    "to destroy the pool itself\n"), zfs_get_name(zhp));
827 		zfs_close(zhp);
828 		return (1);
829 	}
830 
831 	/*
832 	 * Check for any dependents and/or clones.
833 	 */
834 	cb.cb_first = B_TRUE;
835 	if (!cb.cb_doclones &&
836 	    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
837 	    &cb) != 0) {
838 		zfs_close(zhp);
839 		return (1);
840 	}
841 
842 
843 	if (cb.cb_error ||
844 	    zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0) {
845 		zfs_close(zhp);
846 		return (1);
847 	}
848 
849 	/*
850 	 * Do the real thing.  The callback will close the handle regardless of
851 	 * whether it succeeds or not.
852 	 */
853 	if (destroy_callback(zhp, &cb) != 0)
854 		return (1);
855 
856 	zpool_log_history(g_zfs, argc + optind, argv - optind, argv[0],
857 	    B_FALSE, B_FALSE);
858 
859 	return (0);
860 }
861 
862 /*
863  * zfs get [-rHp] [-o field[,field]...] [-s source[,source]...]
864  * 	< all | property[,property]... > < fs | snap | vol > ...
865  *
866  *	-r	recurse over any child datasets
867  *	-H	scripted mode.  Headers are stripped, and fields are separated
868  *		by tabs instead of spaces.
869  *	-o	Set of fields to display.  One of "name,property,value,source".
870  *		Default is all four.
871  *	-s	Set of sources to allow.  One of
872  *		"local,default,inherited,temporary,none".  Default is all
873  *		five.
874  *	-p	Display values in parsable (literal) format.
875  *
876  *  Prints properties for the given datasets.  The user can control which
877  *  columns to display as well as which property types to allow.
878  */
879 
880 /*
881  * Invoked to display the properties for a single dataset.
882  */
883 static int
884 get_callback(zfs_handle_t *zhp, void *data)
885 {
886 	char buf[ZFS_MAXPROPLEN];
887 	zfs_source_t sourcetype;
888 	char source[ZFS_MAXNAMELEN];
889 	libzfs_get_cbdata_t *cbp = data;
890 	nvlist_t *userprop = zfs_get_user_props(zhp);
891 	zfs_proplist_t *pl = cbp->cb_proplist;
892 	nvlist_t *propval;
893 	char *strval;
894 	char *sourceval;
895 
896 	for (; pl != NULL; pl = pl->pl_next) {
897 		/*
898 		 * Skip the special fake placeholder.  This will also skip over
899 		 * the name property when 'all' is specified.
900 		 */
901 		if (pl->pl_prop == ZFS_PROP_NAME &&
902 		    pl == cbp->cb_proplist)
903 			continue;
904 
905 		if (pl->pl_prop != ZFS_PROP_INVAL) {
906 			if (zfs_prop_get(zhp, pl->pl_prop, buf,
907 			    sizeof (buf), &sourcetype, source,
908 			    sizeof (source),
909 			    cbp->cb_literal) != 0) {
910 				if (pl->pl_all)
911 					continue;
912 				if (!zfs_prop_valid_for_type(pl->pl_prop,
913 				    ZFS_TYPE_ANY)) {
914 					(void) fprintf(stderr,
915 					    gettext("No such property '%s'\n"),
916 					    zfs_prop_to_name(pl->pl_prop));
917 					continue;
918 				}
919 				sourcetype = ZFS_SRC_NONE;
920 				(void) strlcpy(buf, "-", sizeof (buf));
921 			}
922 
923 			libzfs_print_one_property(zfs_get_name(zhp), cbp,
924 			    zfs_prop_to_name(pl->pl_prop),
925 			    buf, sourcetype, source);
926 		} else {
927 			if (nvlist_lookup_nvlist(userprop,
928 			    pl->pl_user_prop, &propval) != 0) {
929 				if (pl->pl_all)
930 					continue;
931 				sourcetype = ZFS_SRC_NONE;
932 				strval = "-";
933 			} else {
934 				verify(nvlist_lookup_string(propval,
935 				    ZFS_PROP_VALUE, &strval) == 0);
936 				verify(nvlist_lookup_string(propval,
937 				    ZFS_PROP_SOURCE, &sourceval) == 0);
938 
939 				if (strcmp(sourceval,
940 				    zfs_get_name(zhp)) == 0) {
941 					sourcetype = ZFS_SRC_LOCAL;
942 				} else {
943 					sourcetype = ZFS_SRC_INHERITED;
944 					(void) strlcpy(source,
945 					    sourceval, sizeof (source));
946 				}
947 			}
948 
949 			libzfs_print_one_property(zfs_get_name(zhp), cbp,
950 			    pl->pl_user_prop, strval, sourcetype,
951 			    source);
952 		}
953 	}
954 
955 	return (0);
956 }
957 
958 static int
959 zfs_do_get(int argc, char **argv)
960 {
961 	libzfs_get_cbdata_t cb = { 0 };
962 	boolean_t recurse = B_FALSE;
963 	int i, c;
964 	char *value, *fields;
965 	int ret;
966 	zfs_proplist_t fake_name = { 0 };
967 
968 	/*
969 	 * Set up default columns and sources.
970 	 */
971 	cb.cb_sources = ZFS_SRC_ALL;
972 	cb.cb_columns[0] = GET_COL_NAME;
973 	cb.cb_columns[1] = GET_COL_PROPERTY;
974 	cb.cb_columns[2] = GET_COL_VALUE;
975 	cb.cb_columns[3] = GET_COL_SOURCE;
976 
977 	/* check options */
978 	while ((c = getopt(argc, argv, ":o:s:rHp")) != -1) {
979 		switch (c) {
980 		case 'p':
981 			cb.cb_literal = B_TRUE;
982 			break;
983 		case 'r':
984 			recurse = B_TRUE;
985 			break;
986 		case 'H':
987 			cb.cb_scripted = B_TRUE;
988 			break;
989 		case ':':
990 			(void) fprintf(stderr, gettext("missing argument for "
991 			    "'%c' option\n"), optopt);
992 			usage(B_FALSE);
993 			break;
994 		case 'o':
995 			/*
996 			 * Process the set of columns to display.  We zero out
997 			 * the structure to give us a blank slate.
998 			 */
999 			bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1000 			i = 0;
1001 			while (*optarg != '\0') {
1002 				static char *col_subopts[] =
1003 				    { "name", "property", "value", "source",
1004 				    NULL };
1005 
1006 				if (i == 4) {
1007 					(void) fprintf(stderr, gettext("too "
1008 					    "many fields given to -o "
1009 					    "option\n"));
1010 					usage(B_FALSE);
1011 				}
1012 
1013 				switch (getsubopt(&optarg, col_subopts,
1014 				    &value)) {
1015 				case 0:
1016 					cb.cb_columns[i++] = GET_COL_NAME;
1017 					break;
1018 				case 1:
1019 					cb.cb_columns[i++] = GET_COL_PROPERTY;
1020 					break;
1021 				case 2:
1022 					cb.cb_columns[i++] = GET_COL_VALUE;
1023 					break;
1024 				case 3:
1025 					cb.cb_columns[i++] = GET_COL_SOURCE;
1026 					break;
1027 				default:
1028 					(void) fprintf(stderr,
1029 					    gettext("invalid column name "
1030 					    "'%s'\n"), value);
1031 					usage(B_FALSE);
1032 				}
1033 			}
1034 			break;
1035 
1036 		case 's':
1037 			cb.cb_sources = 0;
1038 			while (*optarg != '\0') {
1039 				static char *source_subopts[] = {
1040 					"local", "default", "inherited",
1041 					"temporary", "none", NULL };
1042 
1043 				switch (getsubopt(&optarg, source_subopts,
1044 				    &value)) {
1045 				case 0:
1046 					cb.cb_sources |= ZFS_SRC_LOCAL;
1047 					break;
1048 				case 1:
1049 					cb.cb_sources |= ZFS_SRC_DEFAULT;
1050 					break;
1051 				case 2:
1052 					cb.cb_sources |= ZFS_SRC_INHERITED;
1053 					break;
1054 				case 3:
1055 					cb.cb_sources |= ZFS_SRC_TEMPORARY;
1056 					break;
1057 				case 4:
1058 					cb.cb_sources |= ZFS_SRC_NONE;
1059 					break;
1060 				default:
1061 					(void) fprintf(stderr,
1062 					    gettext("invalid source "
1063 					    "'%s'\n"), value);
1064 					usage(B_FALSE);
1065 				}
1066 			}
1067 			break;
1068 
1069 		case '?':
1070 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1071 			    optopt);
1072 			usage(B_FALSE);
1073 		}
1074 	}
1075 
1076 	argc -= optind;
1077 	argv += optind;
1078 
1079 	if (argc < 1) {
1080 		(void) fprintf(stderr, gettext("missing property "
1081 		    "argument\n"));
1082 		usage(B_FALSE);
1083 	}
1084 
1085 	fields = argv[0];
1086 
1087 	if (zfs_get_proplist(g_zfs, fields, &cb.cb_proplist) != 0)
1088 		usage(B_FALSE);
1089 
1090 	argc--;
1091 	argv++;
1092 
1093 	/*
1094 	 * As part of zfs_expand_proplist(), we keep track of the maximum column
1095 	 * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1096 	 * need to know the maximum name length.  However, the user likely did
1097 	 * not specify 'name' as one of the properties to fetch, so we need to
1098 	 * make sure we always include at least this property for
1099 	 * print_get_headers() to work properly.
1100 	 */
1101 	if (cb.cb_proplist != NULL) {
1102 		fake_name.pl_prop = ZFS_PROP_NAME;
1103 		fake_name.pl_width = strlen(gettext("NAME"));
1104 		fake_name.pl_next = cb.cb_proplist;
1105 		cb.cb_proplist = &fake_name;
1106 	}
1107 
1108 	cb.cb_first = B_TRUE;
1109 
1110 	/* run for each object */
1111 	ret = zfs_for_each(argc, argv, recurse, ZFS_TYPE_ANY, NULL,
1112 	    &cb.cb_proplist, get_callback, &cb, B_FALSE);
1113 
1114 	if (cb.cb_proplist == &fake_name)
1115 		zfs_free_proplist(fake_name.pl_next);
1116 	else
1117 		zfs_free_proplist(cb.cb_proplist);
1118 
1119 	return (ret);
1120 }
1121 
1122 /*
1123  * inherit [-r] <property> <fs|vol> ...
1124  *
1125  * 	-r	Recurse over all children
1126  *
1127  * For each dataset specified on the command line, inherit the given property
1128  * from its parent.  Inheriting a property at the pool level will cause it to
1129  * use the default value.  The '-r' flag will recurse over all children, and is
1130  * useful for setting a property on a hierarchy-wide basis, regardless of any
1131  * local modifications for each dataset.
1132  */
1133 typedef struct inherit_cbdata {
1134 	char		*cb_propname;
1135 	boolean_t	cb_any_successful;
1136 } inherit_cbdata_t;
1137 
1138 static int
1139 inherit_callback(zfs_handle_t *zhp, void *data)
1140 {
1141 	inherit_cbdata_t *cbp = data;
1142 	int ret;
1143 
1144 	ret = zfs_prop_inherit(zhp, cbp->cb_propname);
1145 	if (ret == 0)
1146 		cbp->cb_any_successful = B_TRUE;
1147 	return (ret != 0);
1148 }
1149 
1150 static int
1151 zfs_do_inherit(int argc, char **argv)
1152 {
1153 	boolean_t recurse = B_FALSE;
1154 	int c;
1155 	zfs_prop_t prop;
1156 	inherit_cbdata_t cb;
1157 	int ret;
1158 
1159 	/* check options */
1160 	while ((c = getopt(argc, argv, "r")) != -1) {
1161 		switch (c) {
1162 		case 'r':
1163 			recurse = B_TRUE;
1164 			break;
1165 		case '?':
1166 		default:
1167 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1168 			    optopt);
1169 			usage(B_FALSE);
1170 		}
1171 	}
1172 
1173 	argc -= optind;
1174 	argv += optind;
1175 
1176 	/* check number of arguments */
1177 	if (argc < 1) {
1178 		(void) fprintf(stderr, gettext("missing property argument\n"));
1179 		usage(B_FALSE);
1180 	}
1181 	if (argc < 2) {
1182 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1183 		usage(B_FALSE);
1184 	}
1185 
1186 	cb.cb_propname = argv[0];
1187 	argc--;
1188 	argv++;
1189 
1190 	if ((prop = zfs_name_to_prop(cb.cb_propname)) != ZFS_PROP_INVAL) {
1191 		if (zfs_prop_readonly(prop)) {
1192 			(void) fprintf(stderr, gettext(
1193 			    "%s property is read-only\n"),
1194 			    cb.cb_propname);
1195 			return (1);
1196 		}
1197 		if (!zfs_prop_inheritable(prop)) {
1198 			(void) fprintf(stderr, gettext("'%s' property cannot "
1199 			    "be inherited\n"), cb.cb_propname);
1200 			if (prop == ZFS_PROP_QUOTA ||
1201 			    prop == ZFS_PROP_RESERVATION)
1202 				(void) fprintf(stderr, gettext("use 'zfs set "
1203 				    "%s=none' to clear\n"), cb.cb_propname);
1204 			return (1);
1205 		}
1206 	} else if (!zfs_prop_user(cb.cb_propname)) {
1207 		(void) fprintf(stderr, gettext(
1208 		    "invalid property '%s'\n"),
1209 		    cb.cb_propname);
1210 		usage(B_FALSE);
1211 	}
1212 
1213 	cb.cb_any_successful = B_FALSE;
1214 
1215 	ret = zfs_for_each(argc, argv, recurse,
1216 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, NULL, NULL,
1217 	    inherit_callback, &cb, B_FALSE);
1218 
1219 	if (cb.cb_any_successful) {
1220 		zpool_log_history(g_zfs, argc + optind + 1, argv - optind - 1,
1221 		    argv[0], B_FALSE, B_FALSE);
1222 	}
1223 
1224 	return (ret);
1225 }
1226 
1227 /*
1228  * list [-rH] [-o property[,property]...] [-t type[,type]...]
1229  *      [-s property [-s property]...] [-S property [-S property]...]
1230  *      <dataset> ...
1231  *
1232  * 	-r	Recurse over all children
1233  * 	-H	Scripted mode; elide headers and separate colums by tabs
1234  * 	-o	Control which fields to display.
1235  * 	-t	Control which object types to display.
1236  *	-s	Specify sort columns, descending order.
1237  *	-S	Specify sort columns, ascending order.
1238  *
1239  * When given no arguments, lists all filesystems in the system.
1240  * Otherwise, list the specified datasets, optionally recursing down them if
1241  * '-r' is specified.
1242  */
1243 typedef struct list_cbdata {
1244 	boolean_t	cb_first;
1245 	boolean_t	cb_scripted;
1246 	zfs_proplist_t	*cb_proplist;
1247 } list_cbdata_t;
1248 
1249 /*
1250  * Given a list of columns to display, output appropriate headers for each one.
1251  */
1252 static void
1253 print_header(zfs_proplist_t *pl)
1254 {
1255 	char headerbuf[ZFS_MAXPROPLEN];
1256 	const char *header;
1257 	int i;
1258 	boolean_t first = B_TRUE;
1259 	boolean_t right_justify;
1260 
1261 	for (; pl != NULL; pl = pl->pl_next) {
1262 		if (!first) {
1263 			(void) printf("  ");
1264 		} else {
1265 			first = B_FALSE;
1266 		}
1267 
1268 		right_justify = B_FALSE;
1269 		if (pl->pl_prop != ZFS_PROP_INVAL) {
1270 			header = zfs_prop_column_name(pl->pl_prop);
1271 			right_justify = zfs_prop_align_right(pl->pl_prop);
1272 		} else {
1273 			for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1274 				headerbuf[i] = toupper(pl->pl_user_prop[i]);
1275 			headerbuf[i] = '\0';
1276 			header = headerbuf;
1277 		}
1278 
1279 		if (pl->pl_next == NULL && !right_justify)
1280 			(void) printf("%s", header);
1281 		else if (right_justify)
1282 			(void) printf("%*s", pl->pl_width, header);
1283 		else
1284 			(void) printf("%-*s", pl->pl_width, header);
1285 	}
1286 
1287 	(void) printf("\n");
1288 }
1289 
1290 /*
1291  * Given a dataset and a list of fields, print out all the properties according
1292  * to the described layout.
1293  */
1294 static void
1295 print_dataset(zfs_handle_t *zhp, zfs_proplist_t *pl, int scripted)
1296 {
1297 	boolean_t first = B_TRUE;
1298 	char property[ZFS_MAXPROPLEN];
1299 	nvlist_t *userprops = zfs_get_user_props(zhp);
1300 	nvlist_t *propval;
1301 	char *propstr;
1302 	boolean_t right_justify;
1303 	int width;
1304 
1305 	for (; pl != NULL; pl = pl->pl_next) {
1306 		if (!first) {
1307 			if (scripted)
1308 				(void) printf("\t");
1309 			else
1310 				(void) printf("  ");
1311 		} else {
1312 			first = B_FALSE;
1313 		}
1314 
1315 		right_justify = B_FALSE;
1316 		if (pl->pl_prop != ZFS_PROP_INVAL) {
1317 			if (zfs_prop_get(zhp, pl->pl_prop, property,
1318 			    sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
1319 				propstr = "-";
1320 			else
1321 				propstr = property;
1322 
1323 			right_justify = zfs_prop_align_right(pl->pl_prop);
1324 		} else {
1325 			if (nvlist_lookup_nvlist(userprops,
1326 			    pl->pl_user_prop, &propval) != 0)
1327 				propstr = "-";
1328 			else
1329 				verify(nvlist_lookup_string(propval,
1330 				    ZFS_PROP_VALUE, &propstr) == 0);
1331 		}
1332 
1333 		width = pl->pl_width;
1334 
1335 		/*
1336 		 * If this is being called in scripted mode, or if this is the
1337 		 * last column and it is left-justified, don't include a width
1338 		 * format specifier.
1339 		 */
1340 		if (scripted || (pl->pl_next == NULL && !right_justify))
1341 			(void) printf("%s", propstr);
1342 		else if (right_justify)
1343 			(void) printf("%*s", width, propstr);
1344 		else
1345 			(void) printf("%-*s", width, propstr);
1346 	}
1347 
1348 	(void) printf("\n");
1349 }
1350 
1351 /*
1352  * Generic callback function to list a dataset or snapshot.
1353  */
1354 static int
1355 list_callback(zfs_handle_t *zhp, void *data)
1356 {
1357 	list_cbdata_t *cbp = data;
1358 
1359 	if (cbp->cb_first) {
1360 		if (!cbp->cb_scripted)
1361 			print_header(cbp->cb_proplist);
1362 		cbp->cb_first = B_FALSE;
1363 	}
1364 
1365 	print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
1366 
1367 	return (0);
1368 }
1369 
1370 static int
1371 zfs_do_list(int argc, char **argv)
1372 {
1373 	int c;
1374 	boolean_t recurse = B_FALSE;
1375 	boolean_t scripted = B_FALSE;
1376 	static char default_fields[] =
1377 	    "name,used,available,referenced,mountpoint";
1378 	int types = ZFS_TYPE_ANY;
1379 	char *fields = NULL;
1380 	char *basic_fields = default_fields;
1381 	list_cbdata_t cb = { 0 };
1382 	char *value;
1383 	int ret;
1384 	char *type_subopts[] = { "filesystem", "volume", "snapshot", NULL };
1385 	zfs_sort_column_t *sortcol = NULL;
1386 
1387 	/* check options */
1388 	while ((c = getopt(argc, argv, ":o:rt:Hs:S:")) != -1) {
1389 		switch (c) {
1390 		case 'o':
1391 			fields = optarg;
1392 			break;
1393 		case 'r':
1394 			recurse = B_TRUE;
1395 			break;
1396 		case 'H':
1397 			scripted = B_TRUE;
1398 			break;
1399 		case 's':
1400 			if (zfs_add_sort_column(&sortcol, optarg,
1401 			    B_FALSE) != 0) {
1402 				(void) fprintf(stderr,
1403 				    gettext("invalid property '%s'\n"), optarg);
1404 				usage(B_FALSE);
1405 			}
1406 			break;
1407 		case 'S':
1408 			if (zfs_add_sort_column(&sortcol, optarg,
1409 			    B_TRUE) != 0) {
1410 				(void) fprintf(stderr,
1411 				    gettext("invalid property '%s'\n"), optarg);
1412 				usage(B_FALSE);
1413 			}
1414 			break;
1415 		case 't':
1416 			types = 0;
1417 			while (*optarg != '\0') {
1418 				switch (getsubopt(&optarg, type_subopts,
1419 				    &value)) {
1420 				case 0:
1421 					types |= ZFS_TYPE_FILESYSTEM;
1422 					break;
1423 				case 1:
1424 					types |= ZFS_TYPE_VOLUME;
1425 					break;
1426 				case 2:
1427 					types |= ZFS_TYPE_SNAPSHOT;
1428 					break;
1429 				default:
1430 					(void) fprintf(stderr,
1431 					    gettext("invalid type '%s'\n"),
1432 					    value);
1433 					usage(B_FALSE);
1434 				}
1435 			}
1436 			break;
1437 		case ':':
1438 			(void) fprintf(stderr, gettext("missing argument for "
1439 			    "'%c' option\n"), optopt);
1440 			usage(B_FALSE);
1441 			break;
1442 		case '?':
1443 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1444 			    optopt);
1445 			usage(B_FALSE);
1446 		}
1447 	}
1448 
1449 	argc -= optind;
1450 	argv += optind;
1451 
1452 	if (fields == NULL)
1453 		fields = basic_fields;
1454 
1455 	/*
1456 	 * If the user specifies '-o all', the zfs_get_proplist() doesn't
1457 	 * normally include the name of the dataset.  For 'zfs list', we always
1458 	 * want this property to be first.
1459 	 */
1460 	if (zfs_get_proplist(g_zfs, fields, &cb.cb_proplist) != 0)
1461 		usage(B_FALSE);
1462 
1463 	cb.cb_scripted = scripted;
1464 	cb.cb_first = B_TRUE;
1465 
1466 	ret = zfs_for_each(argc, argv, recurse, types, sortcol, &cb.cb_proplist,
1467 	    list_callback, &cb, B_TRUE);
1468 
1469 	zfs_free_proplist(cb.cb_proplist);
1470 	zfs_free_sort_columns(sortcol);
1471 
1472 	if (ret == 0 && cb.cb_first)
1473 		(void) printf(gettext("no datasets available\n"));
1474 
1475 	return (ret);
1476 }
1477 
1478 /*
1479  * zfs rename [-r] <fs | snap | vol> <fs | snap | vol>
1480  *
1481  * Renames the given dataset to another of the same type.
1482  */
1483 /* ARGSUSED */
1484 static int
1485 zfs_do_rename(int argc, char **argv)
1486 {
1487 	zfs_handle_t *zhp;
1488 	int c;
1489 	int ret;
1490 	int recurse = 0;
1491 
1492 	/* check options */
1493 	while ((c = getopt(argc, argv, "r")) != -1) {
1494 		switch (c) {
1495 		case 'r':
1496 			recurse = 1;
1497 			break;
1498 		case '?':
1499 		default:
1500 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1501 			    optopt);
1502 			usage(B_FALSE);
1503 		}
1504 	}
1505 
1506 	argc -= optind;
1507 	argv += optind;
1508 
1509 	/* check number of arguments */
1510 	if (argc < 1) {
1511 		(void) fprintf(stderr, gettext("missing source dataset "
1512 		    "argument\n"));
1513 		usage(B_FALSE);
1514 	}
1515 	if (argc < 2) {
1516 		(void) fprintf(stderr, gettext("missing target dataset "
1517 		    "argument\n"));
1518 		usage(B_FALSE);
1519 	}
1520 	if (argc > 2) {
1521 		(void) fprintf(stderr, gettext("too many arguments\n"));
1522 		usage(B_FALSE);
1523 	}
1524 
1525 	if (recurse && strchr(argv[0], '@') == 0) {
1526 		(void) fprintf(stderr, gettext("source dataset for recursive "
1527 		    "rename must be a snapshot\n"));
1528 		usage(B_FALSE);
1529 	}
1530 
1531 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_ANY)) == NULL)
1532 		return (1);
1533 
1534 	ret = (zfs_rename(zhp, argv[1], recurse) != 0);
1535 
1536 	if (!ret)
1537 		zpool_log_history(g_zfs, argc + optind, argv - optind, argv[1],
1538 		    B_FALSE, B_FALSE);
1539 
1540 	zfs_close(zhp);
1541 	return (ret);
1542 }
1543 
1544 /*
1545  * zfs promote <fs>
1546  *
1547  * Promotes the given clone fs to be the parent
1548  */
1549 /* ARGSUSED */
1550 static int
1551 zfs_do_promote(int argc, char **argv)
1552 {
1553 	zfs_handle_t *zhp;
1554 	int ret;
1555 
1556 	/* check options */
1557 	if (argc > 1 && argv[1][0] == '-') {
1558 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1559 		    argv[1][1]);
1560 		usage(B_FALSE);
1561 	}
1562 
1563 	/* check number of arguments */
1564 	if (argc < 2) {
1565 		(void) fprintf(stderr, gettext("missing clone filesystem"
1566 		    " argument\n"));
1567 		usage(B_FALSE);
1568 	}
1569 	if (argc > 2) {
1570 		(void) fprintf(stderr, gettext("too many arguments\n"));
1571 		usage(B_FALSE);
1572 	}
1573 
1574 	zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1575 	if (zhp == NULL)
1576 		return (1);
1577 
1578 	ret = (zfs_promote(zhp) != 0);
1579 
1580 	if (!ret)
1581 		zpool_log_history(g_zfs, argc, argv, argv[1], B_FALSE, B_FALSE);
1582 
1583 	zfs_close(zhp);
1584 	return (ret);
1585 }
1586 
1587 /*
1588  * zfs rollback [-rfR] <snapshot>
1589  *
1590  * 	-r	Delete any intervening snapshots before doing rollback
1591  * 	-R	Delete any snapshots and their clones
1592  * 	-f	Force unmount filesystems, even if they are in use.
1593  *
1594  * Given a filesystem, rollback to a specific snapshot, discarding any changes
1595  * since then and making it the active dataset.  If more recent snapshots exist,
1596  * the command will complain unless the '-r' flag is given.
1597  */
1598 typedef struct rollback_cbdata {
1599 	uint64_t	cb_create;
1600 	boolean_t	cb_first;
1601 	int		cb_doclones;
1602 	char		*cb_target;
1603 	int		cb_error;
1604 	boolean_t	cb_recurse;
1605 	boolean_t	cb_dependent;
1606 } rollback_cbdata_t;
1607 
1608 /*
1609  * Report any snapshots more recent than the one specified.  Used when '-r' is
1610  * not specified.  We reuse this same callback for the snapshot dependents - if
1611  * 'cb_dependent' is set, then this is a dependent and we should report it
1612  * without checking the transaction group.
1613  */
1614 static int
1615 rollback_check(zfs_handle_t *zhp, void *data)
1616 {
1617 	rollback_cbdata_t *cbp = data;
1618 
1619 	if (cbp->cb_doclones) {
1620 		zfs_close(zhp);
1621 		return (0);
1622 	}
1623 
1624 	if (!cbp->cb_dependent) {
1625 		if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
1626 		    zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
1627 		    zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
1628 		    cbp->cb_create) {
1629 
1630 			if (cbp->cb_first && !cbp->cb_recurse) {
1631 				(void) fprintf(stderr, gettext("cannot "
1632 				    "rollback to '%s': more recent snapshots "
1633 				    "exist\n"),
1634 				    cbp->cb_target);
1635 				(void) fprintf(stderr, gettext("use '-r' to "
1636 				    "force deletion of the following "
1637 				    "snapshots:\n"));
1638 				cbp->cb_first = 0;
1639 				cbp->cb_error = 1;
1640 			}
1641 
1642 			if (cbp->cb_recurse) {
1643 				cbp->cb_dependent = B_TRUE;
1644 				if (zfs_iter_dependents(zhp, B_TRUE,
1645 				    rollback_check, cbp) != 0) {
1646 					zfs_close(zhp);
1647 					return (-1);
1648 				}
1649 				cbp->cb_dependent = B_FALSE;
1650 			} else {
1651 				(void) fprintf(stderr, "%s\n",
1652 				    zfs_get_name(zhp));
1653 			}
1654 		}
1655 	} else {
1656 		if (cbp->cb_first && cbp->cb_recurse) {
1657 			(void) fprintf(stderr, gettext("cannot rollback to "
1658 			    "'%s': clones of previous snapshots exist\n"),
1659 			    cbp->cb_target);
1660 			(void) fprintf(stderr, gettext("use '-R' to "
1661 			    "force deletion of the following clones and "
1662 			    "dependents:\n"));
1663 			cbp->cb_first = 0;
1664 			cbp->cb_error = 1;
1665 		}
1666 
1667 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1668 	}
1669 
1670 	zfs_close(zhp);
1671 	return (0);
1672 }
1673 
1674 static int
1675 zfs_do_rollback(int argc, char **argv)
1676 {
1677 	int ret;
1678 	int c;
1679 	rollback_cbdata_t cb = { 0 };
1680 	zfs_handle_t *zhp, *snap;
1681 	char parentname[ZFS_MAXNAMELEN];
1682 	char *delim;
1683 	int force = 0;
1684 
1685 	/* check options */
1686 	while ((c = getopt(argc, argv, "rfR")) != -1) {
1687 		switch (c) {
1688 		case 'f':
1689 			force = 1;
1690 			break;
1691 		case 'r':
1692 			cb.cb_recurse = 1;
1693 			break;
1694 		case 'R':
1695 			cb.cb_recurse = 1;
1696 			cb.cb_doclones = 1;
1697 			break;
1698 		case '?':
1699 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1700 			    optopt);
1701 			usage(B_FALSE);
1702 		}
1703 	}
1704 
1705 	argc -= optind;
1706 	argv += optind;
1707 
1708 	/* check number of arguments */
1709 	if (argc < 1) {
1710 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
1711 		usage(B_FALSE);
1712 	}
1713 	if (argc > 1) {
1714 		(void) fprintf(stderr, gettext("too many arguments\n"));
1715 		usage(B_FALSE);
1716 	}
1717 
1718 	/* open the snapshot */
1719 	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
1720 		return (1);
1721 
1722 	/* open the parent dataset */
1723 	(void) strlcpy(parentname, argv[0], sizeof (parentname));
1724 	verify((delim = strrchr(parentname, '@')) != NULL);
1725 	*delim = '\0';
1726 	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_ANY)) == NULL) {
1727 		zfs_close(snap);
1728 		return (1);
1729 	}
1730 
1731 	/*
1732 	 * Check for more recent snapshots and/or clones based on the presence
1733 	 * of '-r' and '-R'.
1734 	 */
1735 	cb.cb_target = argv[0];
1736 	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
1737 	cb.cb_first = B_TRUE;
1738 	cb.cb_error = 0;
1739 	if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
1740 		goto out;
1741 
1742 	if ((ret = cb.cb_error) != 0)
1743 		goto out;
1744 
1745 	/*
1746 	 * Rollback parent to the given snapshot.
1747 	 */
1748 	ret = zfs_rollback(zhp, snap, force);
1749 
1750 	if (!ret) {
1751 		zpool_log_history(g_zfs, argc + optind, argv - optind, argv[0],
1752 		    B_FALSE, B_FALSE);
1753 	}
1754 
1755 out:
1756 	zfs_close(snap);
1757 	zfs_close(zhp);
1758 
1759 	if (ret == 0)
1760 		return (0);
1761 	else
1762 		return (1);
1763 }
1764 
1765 /*
1766  * zfs set property=value { fs | snap | vol } ...
1767  *
1768  * Sets the given property for all datasets specified on the command line.
1769  */
1770 typedef struct set_cbdata {
1771 	char		*cb_propname;
1772 	char		*cb_value;
1773 	boolean_t	cb_any_successful;
1774 } set_cbdata_t;
1775 
1776 static int
1777 set_callback(zfs_handle_t *zhp, void *data)
1778 {
1779 	set_cbdata_t *cbp = data;
1780 
1781 	if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
1782 		switch (libzfs_errno(g_zfs)) {
1783 		case EZFS_MOUNTFAILED:
1784 			(void) fprintf(stderr, gettext("property may be set "
1785 			    "but unable to remount filesystem\n"));
1786 			break;
1787 		case EZFS_SHARENFSFAILED:
1788 			(void) fprintf(stderr, gettext("property may be set "
1789 			    "but unable to reshare filesystem\n"));
1790 			break;
1791 		}
1792 		return (1);
1793 	}
1794 	cbp->cb_any_successful = B_TRUE;
1795 	return (0);
1796 }
1797 
1798 static int
1799 zfs_do_set(int argc, char **argv)
1800 {
1801 	set_cbdata_t cb;
1802 	int ret;
1803 
1804 	/* check for options */
1805 	if (argc > 1 && argv[1][0] == '-') {
1806 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1807 		    argv[1][1]);
1808 		usage(B_FALSE);
1809 	}
1810 
1811 	/* check number of arguments */
1812 	if (argc < 2) {
1813 		(void) fprintf(stderr, gettext("missing property=value "
1814 		    "argument\n"));
1815 		usage(B_FALSE);
1816 	}
1817 	if (argc < 3) {
1818 		(void) fprintf(stderr, gettext("missing dataset name\n"));
1819 		usage(B_FALSE);
1820 	}
1821 
1822 	/* validate property=value argument */
1823 	cb.cb_propname = argv[1];
1824 	if ((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) {
1825 		(void) fprintf(stderr, gettext("missing value in "
1826 		    "property=value argument\n"));
1827 		usage(B_FALSE);
1828 	}
1829 
1830 	*cb.cb_value = '\0';
1831 	cb.cb_value++;
1832 	cb.cb_any_successful = B_FALSE;
1833 
1834 	if (*cb.cb_propname == '\0') {
1835 		(void) fprintf(stderr,
1836 		    gettext("missing property in property=value argument\n"));
1837 		usage(B_FALSE);
1838 	}
1839 
1840 	ret = zfs_for_each(argc - 2, argv + 2, B_FALSE,
1841 	    ZFS_TYPE_ANY, NULL, NULL, set_callback, &cb, B_FALSE);
1842 
1843 	if (cb.cb_any_successful) {
1844 		*(cb.cb_value - 1) = '=';
1845 		zpool_log_history(g_zfs, argc, argv, argv[2], B_FALSE, B_FALSE);
1846 	}
1847 
1848 	return (ret);
1849 }
1850 
1851 /*
1852  * zfs snapshot [-r] <fs@snap>
1853  *
1854  * Creates a snapshot with the given name.  While functionally equivalent to
1855  * 'zfs create', it is a separate command to diffferentiate intent.
1856  */
1857 static int
1858 zfs_do_snapshot(int argc, char **argv)
1859 {
1860 	int recursive = B_FALSE;
1861 	int ret;
1862 	char c;
1863 
1864 	/* check options */
1865 	while ((c = getopt(argc, argv, ":r")) != -1) {
1866 		switch (c) {
1867 		case 'r':
1868 			recursive = B_TRUE;
1869 			break;
1870 		case '?':
1871 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1872 			    optopt);
1873 			usage(B_FALSE);
1874 		}
1875 	}
1876 
1877 	argc -= optind;
1878 	argv += optind;
1879 
1880 	/* check number of arguments */
1881 	if (argc < 1) {
1882 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
1883 		usage(B_FALSE);
1884 	}
1885 	if (argc > 1) {
1886 		(void) fprintf(stderr, gettext("too many arguments\n"));
1887 		usage(B_FALSE);
1888 	}
1889 
1890 	ret = zfs_snapshot(g_zfs, argv[0], recursive);
1891 	if (ret && recursive)
1892 		(void) fprintf(stderr, gettext("no snapshots were created\n"));
1893 	if (!ret) {
1894 		zpool_log_history(g_zfs, argc + optind, argv - optind, argv[0],
1895 		    B_FALSE, B_FALSE);
1896 	}
1897 	return (ret != 0);
1898 }
1899 
1900 /*
1901  * zfs send [-i <@snap>] <fs@snap>
1902  *
1903  * Send a backup stream to stdout.
1904  */
1905 static int
1906 zfs_do_send(int argc, char **argv)
1907 {
1908 	char *fromname = NULL;
1909 	char *cp;
1910 	zfs_handle_t *zhp;
1911 	int c, err;
1912 
1913 	/* check options */
1914 	while ((c = getopt(argc, argv, ":i:")) != -1) {
1915 		switch (c) {
1916 		case 'i':
1917 			if (fromname)
1918 				usage(B_FALSE);
1919 			fromname = optarg;
1920 			break;
1921 		case ':':
1922 			(void) fprintf(stderr, gettext("missing argument for "
1923 			    "'%c' option\n"), optopt);
1924 			usage(B_FALSE);
1925 			break;
1926 		case '?':
1927 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
1928 			    optopt);
1929 			usage(B_FALSE);
1930 		}
1931 	}
1932 
1933 	argc -= optind;
1934 	argv += optind;
1935 
1936 	/* check number of arguments */
1937 	if (argc < 1) {
1938 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
1939 		usage(B_FALSE);
1940 	}
1941 	if (argc > 1) {
1942 		(void) fprintf(stderr, gettext("too many arguments\n"));
1943 		usage(B_FALSE);
1944 	}
1945 
1946 	if (isatty(STDOUT_FILENO)) {
1947 		(void) fprintf(stderr,
1948 		    gettext("Error: Stream can not be written to a terminal.\n"
1949 		    "You must redirect standard output.\n"));
1950 		return (1);
1951 	}
1952 
1953 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
1954 		return (1);
1955 
1956 	/*
1957 	 * If they specified the full path to the snapshot, chop off
1958 	 * everything except the short name of the snapshot.
1959 	 */
1960 	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
1961 		if (cp != fromname &&
1962 		    strncmp(argv[0], fromname, cp - fromname + 1)) {
1963 			(void) fprintf(stderr,
1964 			    gettext("incremental source must be "
1965 			    "in same filesystem\n"));
1966 			usage(B_FALSE);
1967 		}
1968 		fromname = cp + 1;
1969 		if (strchr(fromname, '@') || strchr(fromname, '/')) {
1970 			(void) fprintf(stderr,
1971 			    gettext("invalid incremental source\n"));
1972 			usage(B_FALSE);
1973 		}
1974 	}
1975 
1976 	err = zfs_send(zhp, fromname, STDOUT_FILENO);
1977 	zfs_close(zhp);
1978 
1979 	return (err != 0);
1980 }
1981 
1982 /*
1983  * zfs receive <fs@snap>
1984  *
1985  * Restore a backup stream from stdin.
1986  */
1987 static int
1988 zfs_do_receive(int argc, char **argv)
1989 {
1990 	int c, err;
1991 	boolean_t isprefix = B_FALSE;
1992 	boolean_t dryrun = B_FALSE;
1993 	boolean_t verbose = B_FALSE;
1994 	boolean_t force = B_FALSE;
1995 
1996 	/* check options */
1997 	while ((c = getopt(argc, argv, ":dnvF")) != -1) {
1998 		switch (c) {
1999 		case 'd':
2000 			isprefix = B_TRUE;
2001 			break;
2002 		case 'n':
2003 			dryrun = B_TRUE;
2004 			break;
2005 		case 'v':
2006 			verbose = B_TRUE;
2007 			break;
2008 		case 'F':
2009 			force = B_TRUE;
2010 			break;
2011 		case ':':
2012 			(void) fprintf(stderr, gettext("missing argument for "
2013 			    "'%c' option\n"), optopt);
2014 			usage(B_FALSE);
2015 			break;
2016 		case '?':
2017 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2018 			    optopt);
2019 			usage(B_FALSE);
2020 		}
2021 	}
2022 
2023 	argc -= optind;
2024 	argv += optind;
2025 
2026 	/* check number of arguments */
2027 	if (argc < 1) {
2028 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2029 		usage(B_FALSE);
2030 	}
2031 	if (argc > 1) {
2032 		(void) fprintf(stderr, gettext("too many arguments\n"));
2033 		usage(B_FALSE);
2034 	}
2035 
2036 	if (isatty(STDIN_FILENO)) {
2037 		(void) fprintf(stderr,
2038 		    gettext("Error: Backup stream can not be read "
2039 		    "from a terminal.\n"
2040 		    "You must redirect standard input.\n"));
2041 		return (1);
2042 	}
2043 
2044 	err = zfs_receive(g_zfs, argv[0], isprefix, verbose, dryrun, force,
2045 	    STDIN_FILENO);
2046 
2047 	if (!err) {
2048 		zpool_log_history(g_zfs, argc + optind, argv - optind, argv[0],
2049 		    B_FALSE, B_FALSE);
2050 	}
2051 
2052 	return (err != 0);
2053 }
2054 
2055 typedef struct get_all_cbdata {
2056 	zfs_handle_t	**cb_handles;
2057 	size_t		cb_alloc;
2058 	size_t		cb_used;
2059 	uint_t		cb_types;
2060 } get_all_cbdata_t;
2061 
2062 static int
2063 get_one_dataset(zfs_handle_t *zhp, void *data)
2064 {
2065 	get_all_cbdata_t *cbp = data;
2066 	zfs_type_t type = zfs_get_type(zhp);
2067 
2068 	/*
2069 	 * Interate over any nested datasets.
2070 	 */
2071 	if (type == ZFS_TYPE_FILESYSTEM &&
2072 	    zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2073 		zfs_close(zhp);
2074 		return (1);
2075 	}
2076 
2077 	/*
2078 	 * Skip any datasets whose type does not match.
2079 	 */
2080 	if ((type & cbp->cb_types) == 0) {
2081 		zfs_close(zhp);
2082 		return (0);
2083 	}
2084 
2085 	if (cbp->cb_alloc == cbp->cb_used) {
2086 		zfs_handle_t **handles;
2087 
2088 		if (cbp->cb_alloc == 0)
2089 			cbp->cb_alloc = 64;
2090 		else
2091 			cbp->cb_alloc *= 2;
2092 
2093 		handles = safe_malloc(cbp->cb_alloc * sizeof (void *));
2094 
2095 		if (cbp->cb_handles) {
2096 			bcopy(cbp->cb_handles, handles,
2097 			    cbp->cb_used * sizeof (void *));
2098 			free(cbp->cb_handles);
2099 		}
2100 
2101 		cbp->cb_handles = handles;
2102 	}
2103 
2104 	cbp->cb_handles[cbp->cb_used++] = zhp;
2105 
2106 	return (0);
2107 }
2108 
2109 static void
2110 get_all_datasets(uint_t types, zfs_handle_t ***dslist, size_t *count)
2111 {
2112 	get_all_cbdata_t cb = { 0 };
2113 	cb.cb_types = types;
2114 
2115 	(void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2116 
2117 	*dslist = cb.cb_handles;
2118 	*count = cb.cb_used;
2119 }
2120 
2121 static int
2122 dataset_cmp(const void *a, const void *b)
2123 {
2124 	zfs_handle_t **za = (zfs_handle_t **)a;
2125 	zfs_handle_t **zb = (zfs_handle_t **)b;
2126 	char mounta[MAXPATHLEN];
2127 	char mountb[MAXPATHLEN];
2128 	boolean_t gota, gotb;
2129 
2130 	if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
2131 		verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
2132 		    sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
2133 	if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
2134 		verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
2135 		    sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
2136 
2137 	if (gota && gotb)
2138 		return (strcmp(mounta, mountb));
2139 
2140 	if (gota)
2141 		return (-1);
2142 	if (gotb)
2143 		return (1);
2144 
2145 	return (strcmp(zfs_get_name(a), zfs_get_name(b)));
2146 }
2147 
2148 /*
2149  * Generic callback for sharing or mounting filesystems.  Because the code is so
2150  * similar, we have a common function with an extra parameter to determine which
2151  * mode we are using.
2152  */
2153 #define	OP_SHARE	0x1
2154 #define	OP_MOUNT	0x2
2155 
2156 /*
2157  * Share or mount a dataset.
2158  */
2159 static int
2160 share_mount_one(zfs_handle_t *zhp, int op, int flags, boolean_t explicit,
2161     const char *options)
2162 {
2163 	char mountpoint[ZFS_MAXPROPLEN];
2164 	char shareopts[ZFS_MAXPROPLEN];
2165 	const char *cmdname = op == OP_SHARE ? "share" : "mount";
2166 	struct mnttab mnt;
2167 	uint64_t zoned, canmount;
2168 	zfs_type_t type = zfs_get_type(zhp);
2169 
2170 	assert(type & (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME));
2171 
2172 	if (type == ZFS_TYPE_FILESYSTEM) {
2173 		/*
2174 		 * Check to make sure we can mount/share this dataset.  If we
2175 		 * are in the global zone and the filesystem is exported to a
2176 		 * local zone, or if we are in a local zone and the
2177 		 * filesystem is not exported, then it is an error.
2178 		 */
2179 		zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2180 
2181 		if (zoned && getzoneid() == GLOBAL_ZONEID) {
2182 			if (!explicit)
2183 				return (0);
2184 
2185 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2186 			    "dataset is exported to a local zone\n"), cmdname,
2187 			    zfs_get_name(zhp));
2188 			return (1);
2189 
2190 		} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
2191 			if (!explicit)
2192 				return (0);
2193 
2194 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2195 			    "permission denied\n"), cmdname,
2196 			    zfs_get_name(zhp));
2197 			return (1);
2198 		}
2199 
2200 		/*
2201 		 * Ignore any filesystems which don't apply to us. This
2202 		 * includes those with a legacy mountpoint, or those with
2203 		 * legacy share options.
2204 		 */
2205 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
2206 		    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
2207 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
2208 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
2209 		canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
2210 
2211 		if (op == OP_SHARE && strcmp(shareopts, "off") == 0) {
2212 			if (!explicit)
2213 				return (0);
2214 
2215 			(void) fprintf(stderr, gettext("cannot share '%s': "
2216 			    "legacy share\n"), zfs_get_name(zhp));
2217 			(void) fprintf(stderr, gettext("use share(1M) to "
2218 			    "share this filesystem\n"));
2219 			return (1);
2220 		}
2221 
2222 		/*
2223 		 * We cannot share or mount legacy filesystems. If the
2224 		 * shareopts is non-legacy but the mountpoint is legacy, we
2225 		 * treat it as a legacy share.
2226 		 */
2227 		if (strcmp(mountpoint, "legacy") == 0) {
2228 			if (!explicit)
2229 				return (0);
2230 
2231 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2232 			    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
2233 			(void) fprintf(stderr, gettext("use %s to "
2234 			    "%s this filesystem\n"), op == OP_SHARE ?
2235 			    "share(1M)" : "mount(1M)", cmdname);
2236 			return (1);
2237 		}
2238 
2239 		if (strcmp(mountpoint, "none") == 0) {
2240 			if (!explicit)
2241 				return (0);
2242 
2243 			(void) fprintf(stderr, gettext("cannot %s '%s': no "
2244 			    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
2245 			return (1);
2246 		}
2247 
2248 		if (!canmount) {
2249 			if (!explicit)
2250 				return (0);
2251 
2252 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2253 			    "'canmount' property is set to 'off'\n"), cmdname,
2254 			    zfs_get_name(zhp));
2255 			return (1);
2256 		}
2257 
2258 		/*
2259 		 * At this point, we have verified that the mountpoint and/or
2260 		 * shareopts are appropriate for auto management. If the
2261 		 * filesystem is already mounted or shared, return (failing
2262 		 * for explicit requests); otherwise mount or share the
2263 		 * filesystem.
2264 		 */
2265 		switch (op) {
2266 		case OP_SHARE:
2267 			if (zfs_is_shared_nfs(zhp, NULL)) {
2268 				if (!explicit)
2269 					return (0);
2270 
2271 				(void) fprintf(stderr, gettext("cannot share "
2272 				    "'%s': filesystem already shared\n"),
2273 				    zfs_get_name(zhp));
2274 				return (1);
2275 			}
2276 
2277 			if (!zfs_is_mounted(zhp, NULL) &&
2278 			    zfs_mount(zhp, NULL, 0) != 0)
2279 				return (1);
2280 
2281 			if (zfs_share_nfs(zhp) != 0)
2282 				return (1);
2283 			break;
2284 
2285 		case OP_MOUNT:
2286 			if (options == NULL)
2287 				mnt.mnt_mntopts = "";
2288 			else
2289 				mnt.mnt_mntopts = (char *)options;
2290 
2291 			if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
2292 			    zfs_is_mounted(zhp, NULL)) {
2293 				if (!explicit)
2294 					return (0);
2295 
2296 				(void) fprintf(stderr, gettext("cannot mount "
2297 				    "'%s': filesystem already mounted\n"),
2298 				    zfs_get_name(zhp));
2299 				return (1);
2300 			}
2301 
2302 			if (zfs_mount(zhp, options, flags) != 0)
2303 				return (1);
2304 			break;
2305 		}
2306 	} else {
2307 		assert(op == OP_SHARE);
2308 
2309 		/*
2310 		 * Ignore any volumes that aren't shared.
2311 		 */
2312 		verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, shareopts,
2313 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
2314 
2315 		if (strcmp(shareopts, "off") == 0) {
2316 			if (!explicit)
2317 				return (0);
2318 
2319 			(void) fprintf(stderr, gettext("cannot share '%s': "
2320 			    "'shareiscsi' property not set\n"),
2321 			    zfs_get_name(zhp));
2322 			(void) fprintf(stderr, gettext("set 'shareiscsi' "
2323 			    "property or use iscsitadm(1M) to share this "
2324 			    "volume\n"));
2325 			return (1);
2326 		}
2327 
2328 		if (zfs_is_shared_iscsi(zhp)) {
2329 			if (!explicit)
2330 				return (0);
2331 
2332 			(void) fprintf(stderr, gettext("cannot share "
2333 			    "'%s': volume already shared\n"),
2334 			    zfs_get_name(zhp));
2335 			return (1);
2336 		}
2337 
2338 		if (zfs_share_iscsi(zhp) != 0)
2339 			return (1);
2340 	}
2341 
2342 	return (0);
2343 }
2344 
2345 static int
2346 share_mount(int op, int argc, char **argv)
2347 {
2348 	int do_all = 0;
2349 	int c, ret = 0;
2350 	const char *options = NULL;
2351 	int types, flags = 0;
2352 
2353 	/* check options */
2354 	while ((c = getopt(argc, argv, op == OP_MOUNT ? ":ao:O" : "a"))
2355 	    != -1) {
2356 		switch (c) {
2357 		case 'a':
2358 			do_all = 1;
2359 			break;
2360 		case 'o':
2361 			options = optarg;
2362 			break;
2363 		case 'O':
2364 			flags |= MS_OVERLAY;
2365 			break;
2366 		case ':':
2367 			(void) fprintf(stderr, gettext("missing argument for "
2368 			    "'%c' option\n"), optopt);
2369 			usage(B_FALSE);
2370 			break;
2371 		case '?':
2372 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2373 			    optopt);
2374 			usage(B_FALSE);
2375 		}
2376 	}
2377 
2378 	argc -= optind;
2379 	argv += optind;
2380 
2381 	/* check number of arguments */
2382 	if (do_all) {
2383 		zfs_handle_t **dslist = NULL;
2384 		size_t i, count = 0;
2385 
2386 		if (op == OP_MOUNT) {
2387 			types = ZFS_TYPE_FILESYSTEM;
2388 		} else if (argc > 0) {
2389 			if (strcmp(argv[0], "nfs") == 0) {
2390 				types = ZFS_TYPE_FILESYSTEM;
2391 			} else if (strcmp(argv[0], "iscsi") == 0) {
2392 				types = ZFS_TYPE_VOLUME;
2393 			} else {
2394 				(void) fprintf(stderr, gettext("share type "
2395 				    "must be 'nfs' or 'iscsi'\n"));
2396 				usage(B_FALSE);
2397 			}
2398 
2399 			argc--;
2400 			argv++;
2401 		} else {
2402 			types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
2403 		}
2404 
2405 		if (argc != 0) {
2406 			(void) fprintf(stderr, gettext("too many arguments\n"));
2407 			usage(B_FALSE);
2408 		}
2409 
2410 		get_all_datasets(types, &dslist, &count);
2411 
2412 		if (count == 0)
2413 			return (0);
2414 
2415 		qsort(dslist, count, sizeof (void *), dataset_cmp);
2416 
2417 		for (i = 0; i < count; i++) {
2418 			if (share_mount_one(dslist[i], op, flags, B_FALSE,
2419 			    options) != 0)
2420 				ret = 1;
2421 			zfs_close(dslist[i]);
2422 		}
2423 
2424 		free(dslist);
2425 	} else if (argc == 0) {
2426 		struct mnttab entry;
2427 
2428 		if (op == OP_SHARE) {
2429 			(void) fprintf(stderr, gettext("missing filesystem "
2430 			    "argument\n"));
2431 			usage(B_FALSE);
2432 		}
2433 
2434 		/*
2435 		 * When mount is given no arguments, go through /etc/mnttab and
2436 		 * display any active ZFS mounts.  We hide any snapshots, since
2437 		 * they are controlled automatically.
2438 		 */
2439 		rewind(mnttab_file);
2440 		while (getmntent(mnttab_file, &entry) == 0) {
2441 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
2442 			    strchr(entry.mnt_special, '@') != NULL)
2443 				continue;
2444 
2445 			(void) printf("%-30s  %s\n", entry.mnt_special,
2446 			    entry.mnt_mountp);
2447 		}
2448 
2449 	} else {
2450 		zfs_handle_t *zhp;
2451 
2452 		types = ZFS_TYPE_FILESYSTEM;
2453 		if (op == OP_SHARE)
2454 			types |= ZFS_TYPE_VOLUME;
2455 
2456 		if (argc > 1) {
2457 			(void) fprintf(stderr,
2458 			    gettext("too many arguments\n"));
2459 			usage(B_FALSE);
2460 		}
2461 
2462 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL) {
2463 			ret = 1;
2464 		} else {
2465 			ret = share_mount_one(zhp, op, flags, B_TRUE,
2466 			    options);
2467 			zfs_close(zhp);
2468 		}
2469 	}
2470 
2471 	return (ret);
2472 }
2473 
2474 /*
2475  * zfs mount -a [nfs | iscsi]
2476  * zfs mount filesystem
2477  *
2478  * Mount all filesystems, or mount the given filesystem.
2479  */
2480 static int
2481 zfs_do_mount(int argc, char **argv)
2482 {
2483 	return (share_mount(OP_MOUNT, argc, argv));
2484 }
2485 
2486 /*
2487  * zfs share -a [nfs | iscsi]
2488  * zfs share filesystem
2489  *
2490  * Share all filesystems, or share the given filesystem.
2491  */
2492 static int
2493 zfs_do_share(int argc, char **argv)
2494 {
2495 	return (share_mount(OP_SHARE, argc, argv));
2496 }
2497 
2498 typedef struct unshare_unmount_node {
2499 	zfs_handle_t	*un_zhp;
2500 	char		*un_mountp;
2501 	uu_avl_node_t	un_avlnode;
2502 } unshare_unmount_node_t;
2503 
2504 /* ARGSUSED */
2505 static int
2506 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
2507 {
2508 	const unshare_unmount_node_t *l = larg;
2509 	const unshare_unmount_node_t *r = rarg;
2510 
2511 	return (strcmp(l->un_mountp, r->un_mountp));
2512 }
2513 
2514 /*
2515  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
2516  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
2517  * and unmount it appropriately.
2518  */
2519 static int
2520 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
2521 {
2522 	zfs_handle_t *zhp;
2523 	int ret;
2524 	struct stat64 statbuf;
2525 	struct extmnttab entry;
2526 	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
2527 	char property[ZFS_MAXPROPLEN];
2528 
2529 	/*
2530 	 * Search for the path in /etc/mnttab.  Rather than looking for the
2531 	 * specific path, which can be fooled by non-standard paths (i.e. ".."
2532 	 * or "//"), we stat() the path and search for the corresponding
2533 	 * (major,minor) device pair.
2534 	 */
2535 	if (stat64(path, &statbuf) != 0) {
2536 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
2537 		    cmdname, path, strerror(errno));
2538 		return (1);
2539 	}
2540 
2541 	/*
2542 	 * Search for the given (major,minor) pair in the mount table.
2543 	 */
2544 	rewind(mnttab_file);
2545 	while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
2546 		if (entry.mnt_major == major(statbuf.st_dev) &&
2547 		    entry.mnt_minor == minor(statbuf.st_dev))
2548 			break;
2549 	}
2550 	if (ret != 0) {
2551 		(void) fprintf(stderr, gettext("cannot %s '%s': not "
2552 		    "currently mounted\n"), cmdname, path);
2553 		return (1);
2554 	}
2555 
2556 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
2557 		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
2558 		    "filesystem\n"), cmdname, path);
2559 		return (1);
2560 	}
2561 
2562 	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
2563 	    ZFS_TYPE_FILESYSTEM)) == NULL)
2564 		return (1);
2565 
2566 	verify(zfs_prop_get(zhp, op == OP_SHARE ?
2567 	    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT, property,
2568 	    sizeof (property), NULL, NULL, 0, B_FALSE) == 0);
2569 
2570 	if (op == OP_SHARE) {
2571 		if (strcmp(property, "off") == 0) {
2572 			(void) fprintf(stderr, gettext("cannot unshare "
2573 			    "'%s': legacy share\n"), path);
2574 			(void) fprintf(stderr, gettext("use "
2575 			    "unshare(1M) to unshare this filesystem\n"));
2576 			ret = 1;
2577 		} else if (!zfs_is_shared_nfs(zhp, NULL)) {
2578 			(void) fprintf(stderr, gettext("cannot unshare '%s': "
2579 			    "not currently shared\n"), path);
2580 			ret = 1;
2581 		} else {
2582 			ret = zfs_unshareall_nfs(zhp);
2583 		}
2584 	} else {
2585 		if (is_manual) {
2586 			ret = zfs_unmount(zhp, NULL, flags);
2587 		} else if (strcmp(property, "legacy") == 0) {
2588 			(void) fprintf(stderr, gettext("cannot unmount "
2589 			    "'%s': legacy mountpoint\n"),
2590 			    zfs_get_name(zhp));
2591 			(void) fprintf(stderr, gettext("use umount(1M) "
2592 			    "to unmount this filesystem\n"));
2593 			ret = 1;
2594 		} else {
2595 			ret = zfs_unmountall(zhp, flags);
2596 		}
2597 	}
2598 
2599 	zfs_close(zhp);
2600 
2601 	return (ret != 0);
2602 }
2603 
2604 /*
2605  * Generic callback for unsharing or unmounting a filesystem.
2606  */
2607 static int
2608 unshare_unmount(int op, int argc, char **argv)
2609 {
2610 	int do_all = 0;
2611 	int flags = 0;
2612 	int ret = 0;
2613 	int types, c;
2614 	zfs_handle_t *zhp;
2615 	char property[ZFS_MAXPROPLEN];
2616 
2617 	/* check options */
2618 	while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
2619 		switch (c) {
2620 		case 'a':
2621 			do_all = 1;
2622 			break;
2623 		case 'f':
2624 			flags = MS_FORCE;
2625 			break;
2626 		case '?':
2627 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2628 			    optopt);
2629 			usage(B_FALSE);
2630 		}
2631 	}
2632 
2633 	argc -= optind;
2634 	argv += optind;
2635 
2636 	if (do_all) {
2637 		/*
2638 		 * We could make use of zfs_for_each() to walk all datasets in
2639 		 * the system, but this would be very inefficient, especially
2640 		 * since we would have to linearly search /etc/mnttab for each
2641 		 * one.  Instead, do one pass through /etc/mnttab looking for
2642 		 * zfs entries and call zfs_unmount() for each one.
2643 		 *
2644 		 * Things get a little tricky if the administrator has created
2645 		 * mountpoints beneath other ZFS filesystems.  In this case, we
2646 		 * have to unmount the deepest filesystems first.  To accomplish
2647 		 * this, we place all the mountpoints in an AVL tree sorted by
2648 		 * the special type (dataset name), and walk the result in
2649 		 * reverse to make sure to get any snapshots first.
2650 		 */
2651 		struct mnttab entry;
2652 		uu_avl_pool_t *pool;
2653 		uu_avl_t *tree;
2654 		unshare_unmount_node_t *node;
2655 		uu_avl_index_t idx;
2656 		uu_avl_walk_t *walk;
2657 
2658 		if (argc != 0) {
2659 			(void) fprintf(stderr, gettext("too many arguments\n"));
2660 			usage(B_FALSE);
2661 		}
2662 
2663 		if ((pool = uu_avl_pool_create("unmount_pool",
2664 		    sizeof (unshare_unmount_node_t),
2665 		    offsetof(unshare_unmount_node_t, un_avlnode),
2666 		    unshare_unmount_compare,
2667 		    UU_DEFAULT)) == NULL) {
2668 			(void) fprintf(stderr, gettext("internal error: "
2669 			    "out of memory\n"));
2670 			exit(1);
2671 		}
2672 
2673 		if ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL) {
2674 			(void) fprintf(stderr, gettext("internal error: "
2675 			    "out of memory\n"));
2676 			exit(1);
2677 		}
2678 
2679 		rewind(mnttab_file);
2680 		while (getmntent(mnttab_file, &entry) == 0) {
2681 
2682 			/* ignore non-ZFS entries */
2683 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
2684 				continue;
2685 
2686 			/* ignore snapshots */
2687 			if (strchr(entry.mnt_special, '@') != NULL)
2688 				continue;
2689 
2690 			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
2691 			    ZFS_TYPE_FILESYSTEM)) == NULL) {
2692 				ret = 1;
2693 				continue;
2694 			}
2695 
2696 			verify(zfs_prop_get(zhp, op == OP_SHARE ?
2697 			    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
2698 			    property, sizeof (property), NULL, NULL,
2699 			    0, B_FALSE) == 0);
2700 
2701 			/* Ignore legacy mounts and shares */
2702 			if ((op == OP_SHARE &&
2703 			    strcmp(property, "off") == 0) ||
2704 			    (op == OP_MOUNT &&
2705 			    strcmp(property, "legacy") == 0)) {
2706 				zfs_close(zhp);
2707 				continue;
2708 			}
2709 
2710 			node = safe_malloc(sizeof (unshare_unmount_node_t));
2711 			node->un_zhp = zhp;
2712 
2713 			if ((node->un_mountp = strdup(entry.mnt_mountp)) ==
2714 			    NULL) {
2715 				(void) fprintf(stderr, gettext("internal error:"
2716 				    " out of memory\n"));
2717 				exit(1);
2718 			}
2719 
2720 			uu_avl_node_init(node, &node->un_avlnode, pool);
2721 
2722 			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
2723 				uu_avl_insert(tree, node, idx);
2724 			} else {
2725 				zfs_close(node->un_zhp);
2726 				free(node->un_mountp);
2727 				free(node);
2728 			}
2729 		}
2730 
2731 		/*
2732 		 * Walk the AVL tree in reverse, unmounting each filesystem and
2733 		 * removing it from the AVL tree in the process.
2734 		 */
2735 		if ((walk = uu_avl_walk_start(tree,
2736 		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL) {
2737 			(void) fprintf(stderr,
2738 			    gettext("internal error: out of memory"));
2739 			exit(1);
2740 		}
2741 
2742 		while ((node = uu_avl_walk_next(walk)) != NULL) {
2743 			uu_avl_remove(tree, node);
2744 
2745 			switch (op) {
2746 			case OP_SHARE:
2747 				if (zfs_unshare_nfs(node->un_zhp,
2748 				    node->un_mountp) != 0)
2749 					ret = 1;
2750 				break;
2751 
2752 			case OP_MOUNT:
2753 				if (zfs_unmount(node->un_zhp,
2754 				    node->un_mountp, flags) != 0)
2755 					ret = 1;
2756 				break;
2757 			}
2758 
2759 			zfs_close(node->un_zhp);
2760 			free(node->un_mountp);
2761 			free(node);
2762 		}
2763 
2764 		uu_avl_walk_end(walk);
2765 		uu_avl_destroy(tree);
2766 		uu_avl_pool_destroy(pool);
2767 
2768 		if (op == OP_SHARE) {
2769 			/*
2770 			 * Finally, unshare any volumes shared via iSCSI.
2771 			 */
2772 			zfs_handle_t **dslist = NULL;
2773 			size_t i, count = 0;
2774 
2775 			get_all_datasets(ZFS_TYPE_VOLUME, &dslist, &count);
2776 
2777 			if (count != 0) {
2778 				qsort(dslist, count, sizeof (void *),
2779 				    dataset_cmp);
2780 
2781 				for (i = 0; i < count; i++) {
2782 					if (zfs_unshare_iscsi(dslist[i]) != 0)
2783 						ret = 1;
2784 					zfs_close(dslist[i]);
2785 				}
2786 
2787 				free(dslist);
2788 			}
2789 		}
2790 	} else {
2791 		if (argc != 1) {
2792 			if (argc == 0)
2793 				(void) fprintf(stderr,
2794 				    gettext("missing filesystem argument\n"));
2795 			else
2796 				(void) fprintf(stderr,
2797 				    gettext("too many arguments\n"));
2798 			usage(B_FALSE);
2799 		}
2800 
2801 		/*
2802 		 * We have an argument, but it may be a full path or a ZFS
2803 		 * filesystem.  Pass full paths off to unmount_path() (shared by
2804 		 * manual_unmount), otherwise open the filesystem and pass to
2805 		 * zfs_unmount().
2806 		 */
2807 		if (argv[0][0] == '/')
2808 			return (unshare_unmount_path(op, argv[0],
2809 			    flags, B_FALSE));
2810 
2811 		types = ZFS_TYPE_FILESYSTEM;
2812 		if (op == OP_SHARE)
2813 			types |= ZFS_TYPE_VOLUME;
2814 
2815 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
2816 			return (1);
2817 
2818 		if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
2819 			verify(zfs_prop_get(zhp, op == OP_SHARE ?
2820 			    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT, property,
2821 			    sizeof (property), NULL, NULL, 0, B_FALSE) == 0);
2822 
2823 			switch (op) {
2824 			case OP_SHARE:
2825 				if (strcmp(property, "off") == 0) {
2826 					(void) fprintf(stderr, gettext("cannot "
2827 					    "unshare '%s': legacy share\n"),
2828 					    zfs_get_name(zhp));
2829 					(void) fprintf(stderr, gettext("use "
2830 					    "unshare(1M) to unshare this "
2831 					    "filesystem\n"));
2832 					ret = 1;
2833 				} else if (!zfs_is_shared_nfs(zhp, NULL)) {
2834 					(void) fprintf(stderr, gettext("cannot "
2835 					    "unshare '%s': not currently "
2836 					    "shared\n"), zfs_get_name(zhp));
2837 					ret = 1;
2838 				} else if (zfs_unshareall_nfs(zhp) != 0) {
2839 					ret = 1;
2840 				}
2841 				break;
2842 
2843 			case OP_MOUNT:
2844 				if (strcmp(property, "legacy") == 0) {
2845 					(void) fprintf(stderr, gettext("cannot "
2846 					    "unmount '%s': legacy "
2847 					    "mountpoint\n"), zfs_get_name(zhp));
2848 					(void) fprintf(stderr, gettext("use "
2849 					    "umount(1M) to unmount this "
2850 					    "filesystem\n"));
2851 					ret = 1;
2852 				} else if (!zfs_is_mounted(zhp, NULL)) {
2853 					(void) fprintf(stderr, gettext("cannot "
2854 					    "unmount '%s': not currently "
2855 					    "mounted\n"),
2856 					    zfs_get_name(zhp));
2857 					ret = 1;
2858 				} else if (zfs_unmountall(zhp, flags) != 0) {
2859 					ret = 1;
2860 				}
2861 				break;
2862 			}
2863 		} else {
2864 			assert(op == OP_SHARE);
2865 
2866 			verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, property,
2867 			    sizeof (property), NULL, NULL, 0, B_FALSE) == 0);
2868 
2869 			if (strcmp(property, "off") == 0) {
2870 				(void) fprintf(stderr, gettext("cannot unshare "
2871 				    "'%s': 'shareiscsi' property not set\n"),
2872 				    zfs_get_name(zhp));
2873 				(void) fprintf(stderr, gettext("set "
2874 				    "'shareiscsi' property or use "
2875 				    "iscsitadm(1M) to share this volume\n"));
2876 				ret = 1;
2877 			} else if (!zfs_is_shared_iscsi(zhp)) {
2878 				(void) fprintf(stderr, gettext("cannot "
2879 				    "unshare '%s': not currently shared\n"),
2880 				    zfs_get_name(zhp));
2881 				ret = 1;
2882 			} else if (zfs_unshare_iscsi(zhp) != 0) {
2883 				ret = 1;
2884 			}
2885 		}
2886 
2887 		zfs_close(zhp);
2888 	}
2889 
2890 	return (ret);
2891 }
2892 
2893 /*
2894  * zfs unmount -a
2895  * zfs unmount filesystem
2896  *
2897  * Unmount all filesystems, or a specific ZFS filesystem.
2898  */
2899 static int
2900 zfs_do_unmount(int argc, char **argv)
2901 {
2902 	return (unshare_unmount(OP_MOUNT, argc, argv));
2903 }
2904 
2905 /*
2906  * zfs unshare -a
2907  * zfs unshare filesystem
2908  *
2909  * Unshare all filesystems, or a specific ZFS filesystem.
2910  */
2911 static int
2912 zfs_do_unshare(int argc, char **argv)
2913 {
2914 	return (unshare_unmount(OP_SHARE, argc, argv));
2915 }
2916 
2917 /*
2918  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
2919  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
2920  */
2921 static int
2922 manual_mount(int argc, char **argv)
2923 {
2924 	zfs_handle_t *zhp;
2925 	char mountpoint[ZFS_MAXPROPLEN];
2926 	char mntopts[MNT_LINE_MAX] = { '\0' };
2927 	int ret;
2928 	int c;
2929 	int flags = 0;
2930 	char *dataset, *path;
2931 
2932 	/* check options */
2933 	while ((c = getopt(argc, argv, ":mo:O")) != -1) {
2934 		switch (c) {
2935 		case 'o':
2936 			(void) strlcpy(mntopts, optarg, sizeof (mntopts));
2937 			break;
2938 		case 'O':
2939 			flags |= MS_OVERLAY;
2940 			break;
2941 		case 'm':
2942 			flags |= MS_NOMNTTAB;
2943 			break;
2944 		case ':':
2945 			(void) fprintf(stderr, gettext("missing argument for "
2946 			    "'%c' option\n"), optopt);
2947 			usage(B_FALSE);
2948 			break;
2949 		case '?':
2950 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2951 			    optopt);
2952 			(void) fprintf(stderr, gettext("usage: mount [-o opts] "
2953 			    "<path>\n"));
2954 			return (2);
2955 		}
2956 	}
2957 
2958 	argc -= optind;
2959 	argv += optind;
2960 
2961 	/* check that we only have two arguments */
2962 	if (argc != 2) {
2963 		if (argc == 0)
2964 			(void) fprintf(stderr, gettext("missing dataset "
2965 			    "argument\n"));
2966 		else if (argc == 1)
2967 			(void) fprintf(stderr,
2968 			    gettext("missing mountpoint argument\n"));
2969 		else
2970 			(void) fprintf(stderr, gettext("too many arguments\n"));
2971 		(void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
2972 		return (2);
2973 	}
2974 
2975 	dataset = argv[0];
2976 	path = argv[1];
2977 
2978 	/* try to open the dataset */
2979 	if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
2980 		return (1);
2981 
2982 	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
2983 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
2984 
2985 	/* check for legacy mountpoint and complain appropriately */
2986 	ret = 0;
2987 	if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
2988 		if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
2989 		    NULL, 0, mntopts, sizeof (mntopts)) != 0) {
2990 			(void) fprintf(stderr, gettext("mount failed: %s\n"),
2991 			    strerror(errno));
2992 			ret = 1;
2993 		}
2994 	} else {
2995 		(void) fprintf(stderr, gettext("filesystem '%s' cannot be "
2996 		    "mounted using 'mount -F zfs'\n"), dataset);
2997 		(void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
2998 		    "instead.\n"), path);
2999 		(void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
3000 		    "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
3001 		(void) fprintf(stderr, gettext("See zfs(1M) for more "
3002 		    "information.\n"));
3003 		ret = 1;
3004 	}
3005 
3006 	return (ret);
3007 }
3008 
3009 /*
3010  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
3011  * unmounts of non-legacy filesystems, as this is the dominant administrative
3012  * interface.
3013  */
3014 static int
3015 manual_unmount(int argc, char **argv)
3016 {
3017 	int flags = 0;
3018 	int c;
3019 
3020 	/* check options */
3021 	while ((c = getopt(argc, argv, "f")) != -1) {
3022 		switch (c) {
3023 		case 'f':
3024 			flags = MS_FORCE;
3025 			break;
3026 		case '?':
3027 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3028 			    optopt);
3029 			(void) fprintf(stderr, gettext("usage: unmount [-f] "
3030 			    "<path>\n"));
3031 			return (2);
3032 		}
3033 	}
3034 
3035 	argc -= optind;
3036 	argv += optind;
3037 
3038 	/* check arguments */
3039 	if (argc != 1) {
3040 		if (argc == 0)
3041 			(void) fprintf(stderr, gettext("missing path "
3042 			    "argument\n"));
3043 		else
3044 			(void) fprintf(stderr, gettext("too many arguments\n"));
3045 		(void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
3046 		return (2);
3047 	}
3048 
3049 	return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
3050 }
3051 
3052 static int
3053 volcheck(zpool_handle_t *zhp, void *data)
3054 {
3055 	boolean_t isinit = *((boolean_t *)data);
3056 
3057 	if (isinit)
3058 		return (zpool_create_zvol_links(zhp));
3059 	else
3060 		return (zpool_remove_zvol_links(zhp));
3061 }
3062 
3063 /*
3064  * Iterate over all pools in the system and either create or destroy /dev/zvol
3065  * links, depending on the value of 'isinit'.
3066  */
3067 static int
3068 do_volcheck(boolean_t isinit)
3069 {
3070 	return (zpool_iter(g_zfs, volcheck, &isinit) ? 1 : 0);
3071 }
3072 
3073 int
3074 main(int argc, char **argv)
3075 {
3076 	int ret;
3077 	int i;
3078 	char *progname;
3079 	char *cmdname;
3080 
3081 	(void) setlocale(LC_ALL, "");
3082 	(void) textdomain(TEXT_DOMAIN);
3083 
3084 	opterr = 0;
3085 
3086 	if ((g_zfs = libzfs_init()) == NULL) {
3087 		(void) fprintf(stderr, gettext("internal error: failed to "
3088 		    "initialize ZFS library\n"));
3089 		return (1);
3090 	}
3091 
3092 	libzfs_print_on_error(g_zfs, B_TRUE);
3093 
3094 	if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
3095 		(void) fprintf(stderr, gettext("internal error: unable to "
3096 		    "open %s\n"), MNTTAB);
3097 		return (1);
3098 	}
3099 
3100 	/*
3101 	 * This command also doubles as the /etc/fs mount and unmount program.
3102 	 * Determine if we should take this behavior based on argv[0].
3103 	 */
3104 	progname = basename(argv[0]);
3105 	if (strcmp(progname, "mount") == 0) {
3106 		ret = manual_mount(argc, argv);
3107 	} else if (strcmp(progname, "umount") == 0) {
3108 		ret = manual_unmount(argc, argv);
3109 	} else {
3110 		/*
3111 		 * Make sure the user has specified some command.
3112 		 */
3113 		if (argc < 2) {
3114 			(void) fprintf(stderr, gettext("missing command\n"));
3115 			usage(B_FALSE);
3116 		}
3117 
3118 		cmdname = argv[1];
3119 
3120 		/*
3121 		 * The 'umount' command is an alias for 'unmount'
3122 		 */
3123 		if (strcmp(cmdname, "umount") == 0)
3124 			cmdname = "unmount";
3125 
3126 		/*
3127 		 * The 'recv' command is an alias for 'receive'
3128 		 */
3129 		if (strcmp(cmdname, "recv") == 0)
3130 			cmdname = "receive";
3131 
3132 		/*
3133 		 * Special case '-?'
3134 		 */
3135 		if (strcmp(cmdname, "-?") == 0)
3136 			usage(B_TRUE);
3137 
3138 		/*
3139 		 * 'volinit' and 'volfini' do not appear in the usage message,
3140 		 * so we have to special case them here.
3141 		 */
3142 		if (strcmp(cmdname, "volinit") == 0)
3143 			return (do_volcheck(B_TRUE));
3144 		else if (strcmp(cmdname, "volfini") == 0)
3145 			return (do_volcheck(B_FALSE));
3146 
3147 		/*
3148 		 * Run the appropriate command.
3149 		 */
3150 		for (i = 0; i < NCOMMAND; i++) {
3151 			if (command_table[i].name == NULL)
3152 				continue;
3153 
3154 			if (strcmp(cmdname, command_table[i].name) == 0) {
3155 				current_command = &command_table[i];
3156 				ret = command_table[i].func(argc - 1, argv + 1);
3157 				break;
3158 			}
3159 		}
3160 
3161 		if (i == NCOMMAND) {
3162 			(void) fprintf(stderr, gettext("unrecognized "
3163 			    "command '%s'\n"), cmdname);
3164 			usage(B_FALSE);
3165 		}
3166 	}
3167 
3168 	(void) fclose(mnttab_file);
3169 
3170 	libzfs_fini(g_zfs);
3171 
3172 	/*
3173 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
3174 	 * for the purposes of running ::findleaks.
3175 	 */
3176 	if (getenv("ZFS_ABORT") != NULL) {
3177 		(void) printf("dumping core by request\n");
3178 		abort();
3179 	}
3180 
3181 	return (ret);
3182 }
3183