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