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