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