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