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