xref: /illumos-gate/usr/src/cmd/zfs/zfs_main.c (revision 2ae51e795e518fd8980f736920a1a38dd17b3ad6)
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 2008 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, ":dnvF")) != -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 'v':
2452 			flags.verbose = B_TRUE;
2453 			break;
2454 		case 'F':
2455 			flags.force = B_TRUE;
2456 			break;
2457 		case ':':
2458 			(void) fprintf(stderr, gettext("missing argument for "
2459 			    "'%c' option\n"), optopt);
2460 			usage(B_FALSE);
2461 			break;
2462 		case '?':
2463 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2464 			    optopt);
2465 			usage(B_FALSE);
2466 		}
2467 	}
2468 
2469 	argc -= optind;
2470 	argv += optind;
2471 
2472 	/* check number of arguments */
2473 	if (argc < 1) {
2474 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2475 		usage(B_FALSE);
2476 	}
2477 	if (argc > 1) {
2478 		(void) fprintf(stderr, gettext("too many arguments\n"));
2479 		usage(B_FALSE);
2480 	}
2481 
2482 	if (isatty(STDIN_FILENO)) {
2483 		(void) fprintf(stderr,
2484 		    gettext("Error: Backup stream can not be read "
2485 		    "from a terminal.\n"
2486 		    "You must redirect standard input.\n"));
2487 		return (1);
2488 	}
2489 
2490 	err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2491 
2492 	return (err != 0);
2493 }
2494 
2495 typedef struct allow_cb {
2496 	int  a_permcnt;
2497 	size_t a_treeoffset;
2498 } allow_cb_t;
2499 
2500 static void
2501 zfs_print_perms(avl_tree_t *tree)
2502 {
2503 	zfs_perm_node_t *permnode;
2504 
2505 	permnode = avl_first(tree);
2506 	while (permnode != NULL) {
2507 		(void) printf("%s", permnode->z_pname);
2508 		permnode = AVL_NEXT(tree, permnode);
2509 		if (permnode)
2510 			(void) printf(",");
2511 		else
2512 			(void) printf("\n");
2513 	}
2514 }
2515 
2516 /*
2517  * Iterate over user/groups/everyone/... and the call perm_iter
2518  * function to print actual permission when tree has >0 nodes.
2519  */
2520 static void
2521 zfs_iter_perms(avl_tree_t *tree, const char *banner, allow_cb_t *cb)
2522 {
2523 	zfs_allow_node_t *item;
2524 	avl_tree_t *ptree;
2525 
2526 	item = avl_first(tree);
2527 	while (item) {
2528 		ptree = (void *)((char *)item + cb->a_treeoffset);
2529 		if (avl_numnodes(ptree)) {
2530 			if (cb->a_permcnt++ == 0)
2531 				(void) printf("%s\n", banner);
2532 			(void) printf("\t%s", item->z_key);
2533 			/*
2534 			 * Avoid an extra space being printed
2535 			 * for "everyone" which is keyed with a null
2536 			 * string
2537 			 */
2538 			if (item->z_key[0] != '\0')
2539 				(void) printf(" ");
2540 			zfs_print_perms(ptree);
2541 		}
2542 		item = AVL_NEXT(tree, item);
2543 	}
2544 }
2545 
2546 #define	LINES "-------------------------------------------------------------\n"
2547 static int
2548 zfs_print_allows(char *ds)
2549 {
2550 	zfs_allow_t *curperms, *perms;
2551 	zfs_handle_t *zhp;
2552 	allow_cb_t allowcb = { 0 };
2553 	char banner[MAXPATHLEN];
2554 
2555 	if (ds[0] == '-')
2556 		usage(B_FALSE);
2557 
2558 	if (strrchr(ds, '@')) {
2559 		(void) fprintf(stderr, gettext("Snapshots don't have 'allow'"
2560 		    " permissions\n"));
2561 		return (1);
2562 	}
2563 	if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2564 		return (1);
2565 
2566 	if (zfs_perm_get(zhp, &perms)) {
2567 		(void) fprintf(stderr,
2568 		    gettext("Failed to retrieve 'allows' on %s\n"), ds);
2569 		zfs_close(zhp);
2570 		return (1);
2571 	}
2572 
2573 	zfs_close(zhp);
2574 
2575 	if (perms != NULL)
2576 		(void) printf("%s", LINES);
2577 	for (curperms = perms; curperms; curperms = curperms->z_next) {
2578 
2579 		(void) snprintf(banner, sizeof (banner),
2580 		    gettext("Permission sets on (%s)"), curperms->z_setpoint);
2581 		allowcb.a_treeoffset =
2582 		    offsetof(zfs_allow_node_t, z_localdescend);
2583 		allowcb.a_permcnt = 0;
2584 		zfs_iter_perms(&curperms->z_sets, banner, &allowcb);
2585 
2586 		(void) snprintf(banner, sizeof (banner),
2587 		    gettext("Create time permissions on (%s)"),
2588 		    curperms->z_setpoint);
2589 		allowcb.a_treeoffset =
2590 		    offsetof(zfs_allow_node_t, z_localdescend);
2591 		allowcb.a_permcnt = 0;
2592 		zfs_iter_perms(&curperms->z_crperms, banner, &allowcb);
2593 
2594 
2595 		(void) snprintf(banner, sizeof (banner),
2596 		    gettext("Local permissions on (%s)"), curperms->z_setpoint);
2597 		allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_local);
2598 		allowcb.a_permcnt = 0;
2599 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2600 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2601 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2602 
2603 		(void) snprintf(banner, sizeof (banner),
2604 		    gettext("Descendent permissions on (%s)"),
2605 		    curperms->z_setpoint);
2606 		allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_descend);
2607 		allowcb.a_permcnt = 0;
2608 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2609 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2610 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2611 
2612 		(void) snprintf(banner, sizeof (banner),
2613 		    gettext("Local+Descendent permissions on (%s)"),
2614 		    curperms->z_setpoint);
2615 		allowcb.a_treeoffset =
2616 		    offsetof(zfs_allow_node_t, z_localdescend);
2617 		allowcb.a_permcnt = 0;
2618 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2619 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2620 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2621 
2622 		(void) printf("%s", LINES);
2623 	}
2624 	zfs_free_allows(perms);
2625 	return (0);
2626 }
2627 
2628 #define	ALLOWOPTIONS "ldcsu:g:e"
2629 #define	UNALLOWOPTIONS "ldcsu:g:er"
2630 
2631 /*
2632  * Validate options, and build necessary datastructure to display/remove/add
2633  * permissions.
2634  * Returns 0 - If permissions should be added/removed
2635  * Returns 1 - If permissions should be displayed.
2636  * Returns -1 - on failure
2637  */
2638 int
2639 parse_allow_args(int *argc, char **argv[], boolean_t unallow,
2640     char **ds, int *recurse, nvlist_t **zperms)
2641 {
2642 	int c;
2643 	char *options = unallow ? UNALLOWOPTIONS : ALLOWOPTIONS;
2644 	zfs_deleg_inherit_t deleg_type = ZFS_DELEG_NONE;
2645 	zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
2646 	char *who = NULL;
2647 	char *perms = NULL;
2648 	zfs_handle_t *zhp;
2649 
2650 	while ((c = getopt(*argc, *argv, options)) != -1) {
2651 		switch (c) {
2652 		case 'l':
2653 			if (who_type == ZFS_DELEG_CREATE ||
2654 			    who_type == ZFS_DELEG_NAMED_SET)
2655 				usage(B_FALSE);
2656 
2657 			deleg_type |= ZFS_DELEG_PERM_LOCAL;
2658 			break;
2659 		case 'd':
2660 			if (who_type == ZFS_DELEG_CREATE ||
2661 			    who_type == ZFS_DELEG_NAMED_SET)
2662 				usage(B_FALSE);
2663 
2664 			deleg_type |= ZFS_DELEG_PERM_DESCENDENT;
2665 			break;
2666 		case 'r':
2667 			*recurse = B_TRUE;
2668 			break;
2669 		case 'c':
2670 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2671 				usage(B_FALSE);
2672 			if (deleg_type)
2673 				usage(B_FALSE);
2674 			who_type = ZFS_DELEG_CREATE;
2675 			break;
2676 		case 's':
2677 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2678 				usage(B_FALSE);
2679 			if (deleg_type)
2680 				usage(B_FALSE);
2681 			who_type = ZFS_DELEG_NAMED_SET;
2682 			break;
2683 		case 'u':
2684 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2685 				usage(B_FALSE);
2686 			who_type = ZFS_DELEG_USER;
2687 			who = optarg;
2688 			break;
2689 		case 'g':
2690 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2691 				usage(B_FALSE);
2692 			who_type = ZFS_DELEG_GROUP;
2693 			who = optarg;
2694 			break;
2695 		case 'e':
2696 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2697 				usage(B_FALSE);
2698 			who_type = ZFS_DELEG_EVERYONE;
2699 			break;
2700 		default:
2701 			usage(B_FALSE);
2702 			break;
2703 		}
2704 	}
2705 
2706 	if (deleg_type == 0)
2707 		deleg_type = ZFS_DELEG_PERM_LOCALDESCENDENT;
2708 
2709 	*argc -= optind;
2710 	*argv += optind;
2711 
2712 	if (unallow == B_FALSE && *argc == 1) {
2713 		/*
2714 		 * Only print permissions if no options were processed
2715 		 */
2716 		if (optind == 1)
2717 			return (1);
2718 		else
2719 			usage(B_FALSE);
2720 	}
2721 
2722 	/*
2723 	 * initialize variables for zfs_build_perms based on number
2724 	 * of arguments.
2725 	 * 3 arguments ==>	zfs [un]allow joe perm,perm,perm <dataset> or
2726 	 *			zfs [un]allow -s @set1 perm,perm <dataset>
2727 	 * 2 arguments ==>	zfs [un]allow -c perm,perm <dataset> or
2728 	 *			zfs [un]allow -u|-g <name> perm <dataset> or
2729 	 *			zfs [un]allow -e perm,perm <dataset>
2730 	 *			zfs unallow joe <dataset>
2731 	 *			zfs unallow -s @set1 <dataset>
2732 	 * 1 argument  ==>	zfs [un]allow -e <dataset> or
2733 	 *			zfs [un]allow -c <dataset>
2734 	 */
2735 
2736 	switch (*argc) {
2737 	case 3:
2738 		perms = (*argv)[1];
2739 		who = (*argv)[0];
2740 		*ds = (*argv)[2];
2741 
2742 		/*
2743 		 * advance argc/argv for do_allow cases.
2744 		 * for do_allow case make sure who have a know who type
2745 		 * and its not a permission set.
2746 		 */
2747 		if (unallow == B_TRUE) {
2748 			*argc -= 2;
2749 			*argv += 2;
2750 		} else if (who_type != ZFS_DELEG_WHO_UNKNOWN &&
2751 		    who_type != ZFS_DELEG_NAMED_SET)
2752 			usage(B_FALSE);
2753 		break;
2754 
2755 	case 2:
2756 		if (unallow == B_TRUE && (who_type == ZFS_DELEG_EVERYONE ||
2757 		    who_type == ZFS_DELEG_CREATE || who != NULL)) {
2758 			perms = (*argv)[0];
2759 			*ds = (*argv)[1];
2760 		} else {
2761 			if (unallow == B_FALSE &&
2762 			    (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2763 			    who_type == ZFS_DELEG_NAMED_SET))
2764 				usage(B_FALSE);
2765 			else if (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2766 			    who_type == ZFS_DELEG_NAMED_SET)
2767 				who = (*argv)[0];
2768 			else if (who_type != ZFS_DELEG_NAMED_SET)
2769 				perms = (*argv)[0];
2770 			*ds = (*argv)[1];
2771 		}
2772 		if (unallow == B_TRUE) {
2773 			(*argc)--;
2774 			(*argv)++;
2775 		}
2776 		break;
2777 
2778 	case 1:
2779 		if (unallow == B_FALSE)
2780 			usage(B_FALSE);
2781 		if (who == NULL && who_type != ZFS_DELEG_CREATE &&
2782 		    who_type != ZFS_DELEG_EVERYONE)
2783 			usage(B_FALSE);
2784 		*ds = (*argv)[0];
2785 		break;
2786 
2787 	default:
2788 		usage(B_FALSE);
2789 	}
2790 
2791 	if (strrchr(*ds, '@')) {
2792 		(void) fprintf(stderr,
2793 		    gettext("Can't set or remove 'allow' permissions "
2794 		    "on snapshots.\n"));
2795 			return (-1);
2796 	}
2797 
2798 	if ((zhp = zfs_open(g_zfs, *ds, ZFS_TYPE_DATASET)) == NULL)
2799 		return (-1);
2800 
2801 	if ((zfs_build_perms(zhp, who, perms,
2802 	    who_type, deleg_type, zperms)) != 0) {
2803 		zfs_close(zhp);
2804 		return (-1);
2805 	}
2806 	zfs_close(zhp);
2807 	return (0);
2808 }
2809 
2810 static int
2811 zfs_do_allow(int argc, char **argv)
2812 {
2813 	char *ds;
2814 	nvlist_t *zperms = NULL;
2815 	zfs_handle_t *zhp;
2816 	int unused;
2817 	int ret;
2818 
2819 	if ((ret = parse_allow_args(&argc, &argv, B_FALSE, &ds,
2820 	    &unused, &zperms)) == -1)
2821 		return (1);
2822 
2823 	if (ret == 1)
2824 		return (zfs_print_allows(argv[0]));
2825 
2826 	if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2827 		return (1);
2828 
2829 	if (zfs_perm_set(zhp, zperms)) {
2830 		zfs_close(zhp);
2831 		nvlist_free(zperms);
2832 		return (1);
2833 	}
2834 	nvlist_free(zperms);
2835 	zfs_close(zhp);
2836 
2837 	return (0);
2838 }
2839 
2840 static int
2841 unallow_callback(zfs_handle_t *zhp, void *data)
2842 {
2843 	nvlist_t *nvp = (nvlist_t *)data;
2844 	int error;
2845 
2846 	error = zfs_perm_remove(zhp, nvp);
2847 	if (error) {
2848 		(void) fprintf(stderr, gettext("Failed to remove permissions "
2849 		    "on %s\n"), zfs_get_name(zhp));
2850 	}
2851 	return (error);
2852 }
2853 
2854 static int
2855 zfs_do_unallow(int argc, char **argv)
2856 {
2857 	int recurse = B_FALSE;
2858 	char *ds;
2859 	int error;
2860 	nvlist_t *zperms = NULL;
2861 	int flags = 0;
2862 
2863 	if (parse_allow_args(&argc, &argv, B_TRUE,
2864 	    &ds, &recurse, &zperms) == -1)
2865 		return (1);
2866 
2867 	if (recurse)
2868 		flags |= ZFS_ITER_RECURSE;
2869 	error = zfs_for_each(argc, argv, flags,
2870 	    ZFS_TYPE_FILESYSTEM|ZFS_TYPE_VOLUME, NULL,
2871 	    NULL, unallow_callback, (void *)zperms);
2872 
2873 	if (zperms)
2874 		nvlist_free(zperms);
2875 
2876 	return (error);
2877 }
2878 
2879 typedef struct get_all_cbdata {
2880 	zfs_handle_t	**cb_handles;
2881 	size_t		cb_alloc;
2882 	size_t		cb_used;
2883 	uint_t		cb_types;
2884 	boolean_t	cb_verbose;
2885 } get_all_cbdata_t;
2886 
2887 #define	CHECK_SPINNER 30
2888 #define	SPINNER_TIME 3		/* seconds */
2889 #define	MOUNT_TIME 5		/* seconds */
2890 
2891 static int
2892 get_one_dataset(zfs_handle_t *zhp, void *data)
2893 {
2894 	static char spin[] = { '-', '\\', '|', '/' };
2895 	static int spinval = 0;
2896 	static int spincheck = 0;
2897 	static time_t last_spin_time = (time_t)0;
2898 	get_all_cbdata_t *cbp = data;
2899 	zfs_type_t type = zfs_get_type(zhp);
2900 
2901 	if (cbp->cb_verbose) {
2902 		if (--spincheck < 0) {
2903 			time_t now = time(NULL);
2904 			if (last_spin_time + SPINNER_TIME < now) {
2905 				(void) printf("\b%c", spin[spinval++ % 4]);
2906 				(void) fflush(stdout);
2907 				last_spin_time = now;
2908 			}
2909 			spincheck = CHECK_SPINNER;
2910 		}
2911 	}
2912 
2913 	/*
2914 	 * Interate over any nested datasets.
2915 	 */
2916 	if (type == ZFS_TYPE_FILESYSTEM &&
2917 	    zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2918 		zfs_close(zhp);
2919 		return (1);
2920 	}
2921 
2922 	/*
2923 	 * Skip any datasets whose type does not match.
2924 	 */
2925 	if ((type & cbp->cb_types) == 0) {
2926 		zfs_close(zhp);
2927 		return (0);
2928 	}
2929 
2930 	if (cbp->cb_alloc == cbp->cb_used) {
2931 		zfs_handle_t **handles;
2932 
2933 		if (cbp->cb_alloc == 0)
2934 			cbp->cb_alloc = 64;
2935 		else
2936 			cbp->cb_alloc *= 2;
2937 
2938 		handles = safe_malloc(cbp->cb_alloc * sizeof (void *));
2939 
2940 		if (cbp->cb_handles) {
2941 			bcopy(cbp->cb_handles, handles,
2942 			    cbp->cb_used * sizeof (void *));
2943 			free(cbp->cb_handles);
2944 		}
2945 
2946 		cbp->cb_handles = handles;
2947 	}
2948 
2949 	cbp->cb_handles[cbp->cb_used++] = zhp;
2950 
2951 	return (0);
2952 }
2953 
2954 static void
2955 get_all_datasets(uint_t types, zfs_handle_t ***dslist, size_t *count,
2956     boolean_t verbose)
2957 {
2958 	get_all_cbdata_t cb = { 0 };
2959 	cb.cb_types = types;
2960 	cb.cb_verbose = verbose;
2961 
2962 	if (verbose) {
2963 		(void) printf("%s: *", gettext("Reading ZFS config"));
2964 		(void) fflush(stdout);
2965 	}
2966 
2967 	(void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2968 
2969 	*dslist = cb.cb_handles;
2970 	*count = cb.cb_used;
2971 
2972 	if (verbose) {
2973 		(void) printf("\b%s\n", gettext("done."));
2974 	}
2975 }
2976 
2977 static int
2978 dataset_cmp(const void *a, const void *b)
2979 {
2980 	zfs_handle_t **za = (zfs_handle_t **)a;
2981 	zfs_handle_t **zb = (zfs_handle_t **)b;
2982 	char mounta[MAXPATHLEN];
2983 	char mountb[MAXPATHLEN];
2984 	boolean_t gota, gotb;
2985 
2986 	if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
2987 		verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
2988 		    sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
2989 	if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
2990 		verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
2991 		    sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
2992 
2993 	if (gota && gotb)
2994 		return (strcmp(mounta, mountb));
2995 
2996 	if (gota)
2997 		return (-1);
2998 	if (gotb)
2999 		return (1);
3000 
3001 	return (strcmp(zfs_get_name(a), zfs_get_name(b)));
3002 }
3003 
3004 /*
3005  * Generic callback for sharing or mounting filesystems.  Because the code is so
3006  * similar, we have a common function with an extra parameter to determine which
3007  * mode we are using.
3008  */
3009 #define	OP_SHARE	0x1
3010 #define	OP_MOUNT	0x2
3011 
3012 /*
3013  * Share or mount a dataset.
3014  */
3015 static int
3016 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
3017     boolean_t explicit, const char *options)
3018 {
3019 	char mountpoint[ZFS_MAXPROPLEN];
3020 	char shareopts[ZFS_MAXPROPLEN];
3021 	char smbshareopts[ZFS_MAXPROPLEN];
3022 	const char *cmdname = op == OP_SHARE ? "share" : "mount";
3023 	struct mnttab mnt;
3024 	uint64_t zoned, canmount;
3025 	zfs_type_t type = zfs_get_type(zhp);
3026 	boolean_t shared_nfs, shared_smb;
3027 
3028 	assert(type & (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME));
3029 
3030 	if (type == ZFS_TYPE_FILESYSTEM) {
3031 		/*
3032 		 * Check to make sure we can mount/share this dataset.  If we
3033 		 * are in the global zone and the filesystem is exported to a
3034 		 * local zone, or if we are in a local zone and the
3035 		 * filesystem is not exported, then it is an error.
3036 		 */
3037 		zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3038 
3039 		if (zoned && getzoneid() == GLOBAL_ZONEID) {
3040 			if (!explicit)
3041 				return (0);
3042 
3043 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3044 			    "dataset is exported to a local zone\n"), cmdname,
3045 			    zfs_get_name(zhp));
3046 			return (1);
3047 
3048 		} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
3049 			if (!explicit)
3050 				return (0);
3051 
3052 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3053 			    "permission denied\n"), cmdname,
3054 			    zfs_get_name(zhp));
3055 			return (1);
3056 		}
3057 
3058 		/*
3059 		 * Ignore any filesystems which don't apply to us. This
3060 		 * includes those with a legacy mountpoint, or those with
3061 		 * legacy share options.
3062 		 */
3063 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3064 		    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
3065 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
3066 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3067 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
3068 		    sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
3069 
3070 		if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
3071 		    strcmp(smbshareopts, "off") == 0) {
3072 			if (!explicit)
3073 				return (0);
3074 
3075 			(void) fprintf(stderr, gettext("cannot share '%s': "
3076 			    "legacy share\n"), zfs_get_name(zhp));
3077 			(void) fprintf(stderr, gettext("use share(1M) to "
3078 			    "share this filesystem, or set "
3079 			    "sharenfs property on\n"));
3080 			return (1);
3081 		}
3082 
3083 		/*
3084 		 * We cannot share or mount legacy filesystems. If the
3085 		 * shareopts is non-legacy but the mountpoint is legacy, we
3086 		 * treat it as a legacy share.
3087 		 */
3088 		if (strcmp(mountpoint, "legacy") == 0) {
3089 			if (!explicit)
3090 				return (0);
3091 
3092 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3093 			    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3094 			(void) fprintf(stderr, gettext("use %s(1M) to "
3095 			    "%s this filesystem\n"), cmdname, cmdname);
3096 			return (1);
3097 		}
3098 
3099 		if (strcmp(mountpoint, "none") == 0) {
3100 			if (!explicit)
3101 				return (0);
3102 
3103 			(void) fprintf(stderr, gettext("cannot %s '%s': no "
3104 			    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3105 			return (1);
3106 		}
3107 
3108 		/*
3109 		 * canmount	explicit	outcome
3110 		 * on		no		pass through
3111 		 * on		yes		pass through
3112 		 * off		no		return 0
3113 		 * off		yes		display error, return 1
3114 		 * noauto	no		return 0
3115 		 * noauto	yes		pass through
3116 		 */
3117 		canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
3118 		if (canmount == ZFS_CANMOUNT_OFF) {
3119 			if (!explicit)
3120 				return (0);
3121 
3122 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3123 			    "'canmount' property is set to 'off'\n"), cmdname,
3124 			    zfs_get_name(zhp));
3125 			return (1);
3126 		} else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
3127 			return (0);
3128 		}
3129 
3130 		/*
3131 		 * At this point, we have verified that the mountpoint and/or
3132 		 * shareopts are appropriate for auto management. If the
3133 		 * filesystem is already mounted or shared, return (failing
3134 		 * for explicit requests); otherwise mount or share the
3135 		 * filesystem.
3136 		 */
3137 		switch (op) {
3138 		case OP_SHARE:
3139 
3140 			shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3141 			shared_smb = zfs_is_shared_smb(zhp, NULL);
3142 
3143 			if (shared_nfs && shared_smb ||
3144 			    (shared_nfs && strcmp(shareopts, "on") == 0 &&
3145 			    strcmp(smbshareopts, "off") == 0) ||
3146 			    (shared_smb && strcmp(smbshareopts, "on") == 0 &&
3147 			    strcmp(shareopts, "off") == 0)) {
3148 				if (!explicit)
3149 					return (0);
3150 
3151 				(void) fprintf(stderr, gettext("cannot share "
3152 				    "'%s': filesystem already shared\n"),
3153 				    zfs_get_name(zhp));
3154 				return (1);
3155 			}
3156 
3157 			if (!zfs_is_mounted(zhp, NULL) &&
3158 			    zfs_mount(zhp, NULL, 0) != 0)
3159 				return (1);
3160 
3161 			if (protocol == NULL) {
3162 				if (zfs_shareall(zhp) != 0)
3163 					return (1);
3164 			} else if (strcmp(protocol, "nfs") == 0) {
3165 				if (zfs_share_nfs(zhp))
3166 					return (1);
3167 			} else if (strcmp(protocol, "smb") == 0) {
3168 				if (zfs_share_smb(zhp))
3169 					return (1);
3170 			} else {
3171 				(void) fprintf(stderr, gettext("cannot share "
3172 				    "'%s': invalid share type '%s' "
3173 				    "specified\n"),
3174 				    zfs_get_name(zhp), protocol);
3175 				return (1);
3176 			}
3177 
3178 			break;
3179 
3180 		case OP_MOUNT:
3181 			if (options == NULL)
3182 				mnt.mnt_mntopts = "";
3183 			else
3184 				mnt.mnt_mntopts = (char *)options;
3185 
3186 			if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3187 			    zfs_is_mounted(zhp, NULL)) {
3188 				if (!explicit)
3189 					return (0);
3190 
3191 				(void) fprintf(stderr, gettext("cannot mount "
3192 				    "'%s': filesystem already mounted\n"),
3193 				    zfs_get_name(zhp));
3194 				return (1);
3195 			}
3196 
3197 			if (zfs_mount(zhp, options, flags) != 0)
3198 				return (1);
3199 			break;
3200 		}
3201 	} else {
3202 		assert(op == OP_SHARE);
3203 
3204 		/*
3205 		 * Ignore any volumes that aren't shared.
3206 		 */
3207 		verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, shareopts,
3208 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3209 
3210 		if (strcmp(shareopts, "off") == 0) {
3211 			if (!explicit)
3212 				return (0);
3213 
3214 			(void) fprintf(stderr, gettext("cannot share '%s': "
3215 			    "'shareiscsi' property not set\n"),
3216 			    zfs_get_name(zhp));
3217 			(void) fprintf(stderr, gettext("set 'shareiscsi' "
3218 			    "property or use iscsitadm(1M) to share this "
3219 			    "volume\n"));
3220 			return (1);
3221 		}
3222 
3223 		if (zfs_is_shared_iscsi(zhp)) {
3224 			if (!explicit)
3225 				return (0);
3226 
3227 			(void) fprintf(stderr, gettext("cannot share "
3228 			    "'%s': volume already shared\n"),
3229 			    zfs_get_name(zhp));
3230 			return (1);
3231 		}
3232 
3233 		if (zfs_share_iscsi(zhp) != 0)
3234 			return (1);
3235 	}
3236 
3237 	return (0);
3238 }
3239 
3240 /*
3241  * Reports progress in the form "(current/total)".  Not thread-safe.
3242  */
3243 static void
3244 report_mount_progress(int current, int total)
3245 {
3246 	static int len;
3247 	static char *reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
3248 	    "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
3249 	static time_t last_progress_time;
3250 	time_t now = time(NULL);
3251 
3252 	/* report 1..n instead of 0..n-1 */
3253 	++current;
3254 
3255 	/* display header if we're here for the first time */
3256 	if (current == 1) {
3257 		(void) printf(gettext("Mounting ZFS filesystems: "));
3258 		len = 0;
3259 	} else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3260 		/* too soon to report again */
3261 		return;
3262 	}
3263 
3264 	last_progress_time = now;
3265 
3266 	/* back up to prepare for overwriting */
3267 	if (len)
3268 		(void) printf("%*.*s", len, len, reverse);
3269 
3270 	/* We put a newline at the end if this is the last one.  */
3271 	len = printf("(%d/%d)%s", current, total, current == total ? "\n" : "");
3272 	(void) fflush(stdout);
3273 }
3274 
3275 static void
3276 append_options(char *mntopts, char *newopts)
3277 {
3278 	int len = strlen(mntopts);
3279 
3280 	/* original length plus new string to append plus 1 for the comma */
3281 	if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
3282 		(void) fprintf(stderr, gettext("the opts argument for "
3283 		    "'%c' option is too long (more than %d chars)\n"),
3284 		    "-o", MNT_LINE_MAX);
3285 		usage(B_FALSE);
3286 	}
3287 
3288 	if (*mntopts)
3289 		mntopts[len++] = ',';
3290 
3291 	(void) strcpy(&mntopts[len], newopts);
3292 }
3293 
3294 static int
3295 share_mount(int op, int argc, char **argv)
3296 {
3297 	int do_all = 0;
3298 	boolean_t verbose = B_FALSE;
3299 	int c, ret = 0;
3300 	char *options = NULL;
3301 	int types, flags = 0;
3302 
3303 	/* check options */
3304 	while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
3305 	    != -1) {
3306 		switch (c) {
3307 		case 'a':
3308 			do_all = 1;
3309 			break;
3310 		case 'v':
3311 			verbose = B_TRUE;
3312 			break;
3313 		case 'o':
3314 			if (*optarg == '\0') {
3315 				(void) fprintf(stderr, gettext("empty mount "
3316 				    "options (-o) specified\n"));
3317 				usage(B_FALSE);
3318 			}
3319 
3320 			if (options == NULL)
3321 				options = safe_malloc(MNT_LINE_MAX + 1);
3322 
3323 			/* option validation is done later */
3324 			append_options(options, optarg);
3325 			break;
3326 
3327 		case 'O':
3328 			flags |= MS_OVERLAY;
3329 			break;
3330 		case ':':
3331 			(void) fprintf(stderr, gettext("missing argument for "
3332 			    "'%c' option\n"), optopt);
3333 			usage(B_FALSE);
3334 			break;
3335 		case '?':
3336 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3337 			    optopt);
3338 			usage(B_FALSE);
3339 		}
3340 	}
3341 
3342 	argc -= optind;
3343 	argv += optind;
3344 
3345 	/* check number of arguments */
3346 	if (do_all) {
3347 		zfs_handle_t **dslist = NULL;
3348 		size_t i, count = 0;
3349 		char *protocol = NULL;
3350 
3351 		if (op == OP_MOUNT) {
3352 			types = ZFS_TYPE_FILESYSTEM;
3353 		} else if (argc > 0) {
3354 			if (strcmp(argv[0], "nfs") == 0 ||
3355 			    strcmp(argv[0], "smb") == 0) {
3356 				types = ZFS_TYPE_FILESYSTEM;
3357 			} else if (strcmp(argv[0], "iscsi") == 0) {
3358 				types = ZFS_TYPE_VOLUME;
3359 			} else {
3360 				(void) fprintf(stderr, gettext("share type "
3361 				    "must be 'nfs', 'smb' or 'iscsi'\n"));
3362 				usage(B_FALSE);
3363 			}
3364 			protocol = argv[0];
3365 			argc--;
3366 			argv++;
3367 		} else {
3368 			types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3369 		}
3370 
3371 		if (argc != 0) {
3372 			(void) fprintf(stderr, gettext("too many arguments\n"));
3373 			usage(B_FALSE);
3374 		}
3375 
3376 		get_all_datasets(types, &dslist, &count, verbose);
3377 
3378 		if (count == 0)
3379 			return (0);
3380 
3381 		qsort(dslist, count, sizeof (void *), dataset_cmp);
3382 
3383 		for (i = 0; i < count; i++) {
3384 			if (verbose)
3385 				report_mount_progress(i, count);
3386 
3387 			if (share_mount_one(dslist[i], op, flags, protocol,
3388 			    B_FALSE, options) != 0)
3389 				ret = 1;
3390 			zfs_close(dslist[i]);
3391 		}
3392 
3393 		free(dslist);
3394 	} else if (argc == 0) {
3395 		struct mnttab entry;
3396 
3397 		if ((op == OP_SHARE) || (options != NULL)) {
3398 			(void) fprintf(stderr, gettext("missing filesystem "
3399 			    "argument (specify -a for all)\n"));
3400 			usage(B_FALSE);
3401 		}
3402 
3403 		/*
3404 		 * When mount is given no arguments, go through /etc/mnttab and
3405 		 * display any active ZFS mounts.  We hide any snapshots, since
3406 		 * they are controlled automatically.
3407 		 */
3408 		rewind(mnttab_file);
3409 		while (getmntent(mnttab_file, &entry) == 0) {
3410 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3411 			    strchr(entry.mnt_special, '@') != NULL)
3412 				continue;
3413 
3414 			(void) printf("%-30s  %s\n", entry.mnt_special,
3415 			    entry.mnt_mountp);
3416 		}
3417 
3418 	} else {
3419 		zfs_handle_t *zhp;
3420 
3421 		types = ZFS_TYPE_FILESYSTEM;
3422 		if (op == OP_SHARE)
3423 			types |= ZFS_TYPE_VOLUME;
3424 
3425 		if (argc > 1) {
3426 			(void) fprintf(stderr,
3427 			    gettext("too many arguments\n"));
3428 			usage(B_FALSE);
3429 		}
3430 
3431 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL) {
3432 			ret = 1;
3433 		} else {
3434 			ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3435 			    options);
3436 			zfs_close(zhp);
3437 		}
3438 	}
3439 
3440 	return (ret);
3441 }
3442 
3443 /*
3444  * zfs mount -a [nfs | iscsi]
3445  * zfs mount filesystem
3446  *
3447  * Mount all filesystems, or mount the given filesystem.
3448  */
3449 static int
3450 zfs_do_mount(int argc, char **argv)
3451 {
3452 	return (share_mount(OP_MOUNT, argc, argv));
3453 }
3454 
3455 /*
3456  * zfs share -a [nfs | iscsi | smb]
3457  * zfs share filesystem
3458  *
3459  * Share all filesystems, or share the given filesystem.
3460  */
3461 static int
3462 zfs_do_share(int argc, char **argv)
3463 {
3464 	return (share_mount(OP_SHARE, argc, argv));
3465 }
3466 
3467 typedef struct unshare_unmount_node {
3468 	zfs_handle_t	*un_zhp;
3469 	char		*un_mountp;
3470 	uu_avl_node_t	un_avlnode;
3471 } unshare_unmount_node_t;
3472 
3473 /* ARGSUSED */
3474 static int
3475 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3476 {
3477 	const unshare_unmount_node_t *l = larg;
3478 	const unshare_unmount_node_t *r = rarg;
3479 
3480 	return (strcmp(l->un_mountp, r->un_mountp));
3481 }
3482 
3483 /*
3484  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3485  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
3486  * and unmount it appropriately.
3487  */
3488 static int
3489 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3490 {
3491 	zfs_handle_t *zhp;
3492 	int ret;
3493 	struct stat64 statbuf;
3494 	struct extmnttab entry;
3495 	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3496 	ino_t path_inode;
3497 
3498 	/*
3499 	 * Search for the path in /etc/mnttab.  Rather than looking for the
3500 	 * specific path, which can be fooled by non-standard paths (i.e. ".."
3501 	 * or "//"), we stat() the path and search for the corresponding
3502 	 * (major,minor) device pair.
3503 	 */
3504 	if (stat64(path, &statbuf) != 0) {
3505 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3506 		    cmdname, path, strerror(errno));
3507 		return (1);
3508 	}
3509 	path_inode = statbuf.st_ino;
3510 
3511 	/*
3512 	 * Search for the given (major,minor) pair in the mount table.
3513 	 */
3514 	rewind(mnttab_file);
3515 	while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3516 		if (entry.mnt_major == major(statbuf.st_dev) &&
3517 		    entry.mnt_minor == minor(statbuf.st_dev))
3518 			break;
3519 	}
3520 	if (ret != 0) {
3521 		if (op == OP_SHARE) {
3522 			(void) fprintf(stderr, gettext("cannot %s '%s': not "
3523 			    "currently mounted\n"), cmdname, path);
3524 			return (1);
3525 		}
3526 		(void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
3527 		    path);
3528 		if ((ret = umount2(path, flags)) != 0)
3529 			(void) fprintf(stderr, gettext("%s: %s\n"), path,
3530 			    strerror(errno));
3531 		return (ret != 0);
3532 	}
3533 
3534 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3535 		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3536 		    "filesystem\n"), cmdname, path);
3537 		return (1);
3538 	}
3539 
3540 	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3541 	    ZFS_TYPE_FILESYSTEM)) == NULL)
3542 		return (1);
3543 
3544 	ret = 1;
3545 	if (stat64(entry.mnt_mountp, &statbuf) != 0) {
3546 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3547 		    cmdname, path, strerror(errno));
3548 		goto out;
3549 	} else if (statbuf.st_ino != path_inode) {
3550 		(void) fprintf(stderr, gettext("cannot "
3551 		    "%s '%s': not a mountpoint\n"), cmdname, path);
3552 		goto out;
3553 	}
3554 
3555 	if (op == OP_SHARE) {
3556 		char nfs_mnt_prop[ZFS_MAXPROPLEN];
3557 		char smbshare_prop[ZFS_MAXPROPLEN];
3558 
3559 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
3560 		    sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3561 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
3562 		    sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3563 
3564 		if (strcmp(nfs_mnt_prop, "off") == 0 &&
3565 		    strcmp(smbshare_prop, "off") == 0) {
3566 			(void) fprintf(stderr, gettext("cannot unshare "
3567 			    "'%s': legacy share\n"), path);
3568 			(void) fprintf(stderr, gettext("use "
3569 			    "unshare(1M) to unshare this filesystem\n"));
3570 		} else if (!zfs_is_shared(zhp)) {
3571 			(void) fprintf(stderr, gettext("cannot unshare '%s': "
3572 			    "not currently shared\n"), path);
3573 		} else {
3574 			ret = zfs_unshareall_bypath(zhp, path);
3575 		}
3576 	} else {
3577 		char mtpt_prop[ZFS_MAXPROPLEN];
3578 
3579 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
3580 		    sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
3581 
3582 		if (is_manual) {
3583 			ret = zfs_unmount(zhp, NULL, flags);
3584 		} else if (strcmp(mtpt_prop, "legacy") == 0) {
3585 			(void) fprintf(stderr, gettext("cannot unmount "
3586 			    "'%s': legacy mountpoint\n"),
3587 			    zfs_get_name(zhp));
3588 			(void) fprintf(stderr, gettext("use umount(1M) "
3589 			    "to unmount this filesystem\n"));
3590 		} else {
3591 			ret = zfs_unmountall(zhp, flags);
3592 		}
3593 	}
3594 
3595 out:
3596 	zfs_close(zhp);
3597 
3598 	return (ret != 0);
3599 }
3600 
3601 /*
3602  * Generic callback for unsharing or unmounting a filesystem.
3603  */
3604 static int
3605 unshare_unmount(int op, int argc, char **argv)
3606 {
3607 	int do_all = 0;
3608 	int flags = 0;
3609 	int ret = 0;
3610 	int types, c;
3611 	zfs_handle_t *zhp;
3612 	char nfsiscsi_mnt_prop[ZFS_MAXPROPLEN];
3613 	char sharesmb[ZFS_MAXPROPLEN];
3614 
3615 	/* check options */
3616 	while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3617 		switch (c) {
3618 		case 'a':
3619 			do_all = 1;
3620 			break;
3621 		case 'f':
3622 			flags = MS_FORCE;
3623 			break;
3624 		case '?':
3625 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3626 			    optopt);
3627 			usage(B_FALSE);
3628 		}
3629 	}
3630 
3631 	argc -= optind;
3632 	argv += optind;
3633 
3634 	if (do_all) {
3635 		/*
3636 		 * We could make use of zfs_for_each() to walk all datasets in
3637 		 * the system, but this would be very inefficient, especially
3638 		 * since we would have to linearly search /etc/mnttab for each
3639 		 * one.  Instead, do one pass through /etc/mnttab looking for
3640 		 * zfs entries and call zfs_unmount() for each one.
3641 		 *
3642 		 * Things get a little tricky if the administrator has created
3643 		 * mountpoints beneath other ZFS filesystems.  In this case, we
3644 		 * have to unmount the deepest filesystems first.  To accomplish
3645 		 * this, we place all the mountpoints in an AVL tree sorted by
3646 		 * the special type (dataset name), and walk the result in
3647 		 * reverse to make sure to get any snapshots first.
3648 		 */
3649 		struct mnttab entry;
3650 		uu_avl_pool_t *pool;
3651 		uu_avl_t *tree;
3652 		unshare_unmount_node_t *node;
3653 		uu_avl_index_t idx;
3654 		uu_avl_walk_t *walk;
3655 
3656 		if (argc != 0) {
3657 			(void) fprintf(stderr, gettext("too many arguments\n"));
3658 			usage(B_FALSE);
3659 		}
3660 
3661 		if ((pool = uu_avl_pool_create("unmount_pool",
3662 		    sizeof (unshare_unmount_node_t),
3663 		    offsetof(unshare_unmount_node_t, un_avlnode),
3664 		    unshare_unmount_compare,
3665 		    UU_DEFAULT)) == NULL) {
3666 			(void) fprintf(stderr, gettext("internal error: "
3667 			    "out of memory\n"));
3668 			exit(1);
3669 		}
3670 
3671 		if ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL) {
3672 			(void) fprintf(stderr, gettext("internal error: "
3673 			    "out of memory\n"));
3674 			exit(1);
3675 		}
3676 
3677 		rewind(mnttab_file);
3678 		while (getmntent(mnttab_file, &entry) == 0) {
3679 
3680 			/* ignore non-ZFS entries */
3681 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3682 				continue;
3683 
3684 			/* ignore snapshots */
3685 			if (strchr(entry.mnt_special, '@') != NULL)
3686 				continue;
3687 
3688 			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3689 			    ZFS_TYPE_FILESYSTEM)) == NULL) {
3690 				ret = 1;
3691 				continue;
3692 			}
3693 
3694 			switch (op) {
3695 			case OP_SHARE:
3696 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3697 				    nfsiscsi_mnt_prop,
3698 				    sizeof (nfsiscsi_mnt_prop),
3699 				    NULL, NULL, 0, B_FALSE) == 0);
3700 				if (strcmp(nfsiscsi_mnt_prop, "off") != 0)
3701 					break;
3702 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3703 				    nfsiscsi_mnt_prop,
3704 				    sizeof (nfsiscsi_mnt_prop),
3705 				    NULL, NULL, 0, B_FALSE) == 0);
3706 				if (strcmp(nfsiscsi_mnt_prop, "off") == 0)
3707 					continue;
3708 				break;
3709 			case OP_MOUNT:
3710 				/* Ignore legacy mounts */
3711 				verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3712 				    nfsiscsi_mnt_prop,
3713 				    sizeof (nfsiscsi_mnt_prop),
3714 				    NULL, NULL, 0, B_FALSE) == 0);
3715 				if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0)
3716 					continue;
3717 				/* Ignore canmount=noauto mounts */
3718 				if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
3719 				    ZFS_CANMOUNT_NOAUTO)
3720 					continue;
3721 			default:
3722 				break;
3723 			}
3724 
3725 			node = safe_malloc(sizeof (unshare_unmount_node_t));
3726 			node->un_zhp = zhp;
3727 
3728 			if ((node->un_mountp = strdup(entry.mnt_mountp)) ==
3729 			    NULL) {
3730 				(void) fprintf(stderr, gettext("internal error:"
3731 				    " out of memory\n"));
3732 				exit(1);
3733 			}
3734 
3735 			uu_avl_node_init(node, &node->un_avlnode, pool);
3736 
3737 			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3738 				uu_avl_insert(tree, node, idx);
3739 			} else {
3740 				zfs_close(node->un_zhp);
3741 				free(node->un_mountp);
3742 				free(node);
3743 			}
3744 		}
3745 
3746 		/*
3747 		 * Walk the AVL tree in reverse, unmounting each filesystem and
3748 		 * removing it from the AVL tree in the process.
3749 		 */
3750 		if ((walk = uu_avl_walk_start(tree,
3751 		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL) {
3752 			(void) fprintf(stderr,
3753 			    gettext("internal error: out of memory"));
3754 			exit(1);
3755 		}
3756 
3757 		while ((node = uu_avl_walk_next(walk)) != NULL) {
3758 			uu_avl_remove(tree, node);
3759 
3760 			switch (op) {
3761 			case OP_SHARE:
3762 				if (zfs_unshareall_bypath(node->un_zhp,
3763 				    node->un_mountp) != 0)
3764 					ret = 1;
3765 				break;
3766 
3767 			case OP_MOUNT:
3768 				if (zfs_unmount(node->un_zhp,
3769 				    node->un_mountp, flags) != 0)
3770 					ret = 1;
3771 				break;
3772 			}
3773 
3774 			zfs_close(node->un_zhp);
3775 			free(node->un_mountp);
3776 			free(node);
3777 		}
3778 
3779 		uu_avl_walk_end(walk);
3780 		uu_avl_destroy(tree);
3781 		uu_avl_pool_destroy(pool);
3782 
3783 		if (op == OP_SHARE) {
3784 			/*
3785 			 * Finally, unshare any volumes shared via iSCSI.
3786 			 */
3787 			zfs_handle_t **dslist = NULL;
3788 			size_t i, count = 0;
3789 
3790 			get_all_datasets(ZFS_TYPE_VOLUME, &dslist, &count,
3791 			    B_FALSE);
3792 
3793 			if (count != 0) {
3794 				qsort(dslist, count, sizeof (void *),
3795 				    dataset_cmp);
3796 
3797 				for (i = 0; i < count; i++) {
3798 					if (zfs_unshare_iscsi(dslist[i]) != 0)
3799 						ret = 1;
3800 					zfs_close(dslist[i]);
3801 				}
3802 
3803 				free(dslist);
3804 			}
3805 		}
3806 	} else {
3807 		if (argc != 1) {
3808 			if (argc == 0)
3809 				(void) fprintf(stderr,
3810 				    gettext("missing filesystem argument\n"));
3811 			else
3812 				(void) fprintf(stderr,
3813 				    gettext("too many arguments\n"));
3814 			usage(B_FALSE);
3815 		}
3816 
3817 		/*
3818 		 * We have an argument, but it may be a full path or a ZFS
3819 		 * filesystem.  Pass full paths off to unmount_path() (shared by
3820 		 * manual_unmount), otherwise open the filesystem and pass to
3821 		 * zfs_unmount().
3822 		 */
3823 		if (argv[0][0] == '/')
3824 			return (unshare_unmount_path(op, argv[0],
3825 			    flags, B_FALSE));
3826 
3827 		types = ZFS_TYPE_FILESYSTEM;
3828 		if (op == OP_SHARE)
3829 			types |= ZFS_TYPE_VOLUME;
3830 
3831 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3832 			return (1);
3833 
3834 		if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
3835 			verify(zfs_prop_get(zhp, op == OP_SHARE ?
3836 			    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3837 			    nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop), NULL,
3838 			    NULL, 0, B_FALSE) == 0);
3839 
3840 			switch (op) {
3841 			case OP_SHARE:
3842 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3843 				    nfsiscsi_mnt_prop,
3844 				    sizeof (nfsiscsi_mnt_prop),
3845 				    NULL, NULL, 0, B_FALSE) == 0);
3846 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3847 				    sharesmb, sizeof (sharesmb), NULL, NULL,
3848 				    0, B_FALSE) == 0);
3849 
3850 				if (strcmp(nfsiscsi_mnt_prop, "off") == 0 &&
3851 				    strcmp(sharesmb, "off") == 0) {
3852 					(void) fprintf(stderr, gettext("cannot "
3853 					    "unshare '%s': legacy share\n"),
3854 					    zfs_get_name(zhp));
3855 					(void) fprintf(stderr, gettext("use "
3856 					    "unshare(1M) to unshare this "
3857 					    "filesystem\n"));
3858 					ret = 1;
3859 				} else if (!zfs_is_shared(zhp)) {
3860 					(void) fprintf(stderr, gettext("cannot "
3861 					    "unshare '%s': not currently "
3862 					    "shared\n"), zfs_get_name(zhp));
3863 					ret = 1;
3864 				} else if (zfs_unshareall(zhp) != 0) {
3865 					ret = 1;
3866 				}
3867 				break;
3868 
3869 			case OP_MOUNT:
3870 				if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0) {
3871 					(void) fprintf(stderr, gettext("cannot "
3872 					    "unmount '%s': legacy "
3873 					    "mountpoint\n"), zfs_get_name(zhp));
3874 					(void) fprintf(stderr, gettext("use "
3875 					    "umount(1M) to unmount this "
3876 					    "filesystem\n"));
3877 					ret = 1;
3878 				} else if (!zfs_is_mounted(zhp, NULL)) {
3879 					(void) fprintf(stderr, gettext("cannot "
3880 					    "unmount '%s': not currently "
3881 					    "mounted\n"),
3882 					    zfs_get_name(zhp));
3883 					ret = 1;
3884 				} else if (zfs_unmountall(zhp, flags) != 0) {
3885 					ret = 1;
3886 				}
3887 				break;
3888 			}
3889 		} else {
3890 			assert(op == OP_SHARE);
3891 
3892 			verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI,
3893 			    nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop),
3894 			    NULL, NULL, 0, B_FALSE) == 0);
3895 
3896 			if (strcmp(nfsiscsi_mnt_prop, "off") == 0) {
3897 				(void) fprintf(stderr, gettext("cannot unshare "
3898 				    "'%s': 'shareiscsi' property not set\n"),
3899 				    zfs_get_name(zhp));
3900 				(void) fprintf(stderr, gettext("set "
3901 				    "'shareiscsi' property or use "
3902 				    "iscsitadm(1M) to share this volume\n"));
3903 				ret = 1;
3904 			} else if (!zfs_is_shared_iscsi(zhp)) {
3905 				(void) fprintf(stderr, gettext("cannot "
3906 				    "unshare '%s': not currently shared\n"),
3907 				    zfs_get_name(zhp));
3908 				ret = 1;
3909 			} else if (zfs_unshare_iscsi(zhp) != 0) {
3910 				ret = 1;
3911 			}
3912 		}
3913 
3914 		zfs_close(zhp);
3915 	}
3916 
3917 	return (ret);
3918 }
3919 
3920 /*
3921  * zfs unmount -a
3922  * zfs unmount filesystem
3923  *
3924  * Unmount all filesystems, or a specific ZFS filesystem.
3925  */
3926 static int
3927 zfs_do_unmount(int argc, char **argv)
3928 {
3929 	return (unshare_unmount(OP_MOUNT, argc, argv));
3930 }
3931 
3932 /*
3933  * zfs unshare -a
3934  * zfs unshare filesystem
3935  *
3936  * Unshare all filesystems, or a specific ZFS filesystem.
3937  */
3938 static int
3939 zfs_do_unshare(int argc, char **argv)
3940 {
3941 	return (unshare_unmount(OP_SHARE, argc, argv));
3942 }
3943 
3944 /*
3945  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
3946  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
3947  */
3948 static int
3949 manual_mount(int argc, char **argv)
3950 {
3951 	zfs_handle_t *zhp;
3952 	char mountpoint[ZFS_MAXPROPLEN];
3953 	char mntopts[MNT_LINE_MAX] = { '\0' };
3954 	int ret;
3955 	int c;
3956 	int flags = 0;
3957 	char *dataset, *path;
3958 
3959 	/* check options */
3960 	while ((c = getopt(argc, argv, ":mo:O")) != -1) {
3961 		switch (c) {
3962 		case 'o':
3963 			(void) strlcpy(mntopts, optarg, sizeof (mntopts));
3964 			break;
3965 		case 'O':
3966 			flags |= MS_OVERLAY;
3967 			break;
3968 		case 'm':
3969 			flags |= MS_NOMNTTAB;
3970 			break;
3971 		case ':':
3972 			(void) fprintf(stderr, gettext("missing argument for "
3973 			    "'%c' option\n"), optopt);
3974 			usage(B_FALSE);
3975 			break;
3976 		case '?':
3977 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3978 			    optopt);
3979 			(void) fprintf(stderr, gettext("usage: mount [-o opts] "
3980 			    "<path>\n"));
3981 			return (2);
3982 		}
3983 	}
3984 
3985 	argc -= optind;
3986 	argv += optind;
3987 
3988 	/* check that we only have two arguments */
3989 	if (argc != 2) {
3990 		if (argc == 0)
3991 			(void) fprintf(stderr, gettext("missing dataset "
3992 			    "argument\n"));
3993 		else if (argc == 1)
3994 			(void) fprintf(stderr,
3995 			    gettext("missing mountpoint argument\n"));
3996 		else
3997 			(void) fprintf(stderr, gettext("too many arguments\n"));
3998 		(void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
3999 		return (2);
4000 	}
4001 
4002 	dataset = argv[0];
4003 	path = argv[1];
4004 
4005 	/* try to open the dataset */
4006 	if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
4007 		return (1);
4008 
4009 	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
4010 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
4011 
4012 	/* check for legacy mountpoint and complain appropriately */
4013 	ret = 0;
4014 	if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
4015 		if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
4016 		    NULL, 0, mntopts, sizeof (mntopts)) != 0) {
4017 			(void) fprintf(stderr, gettext("mount failed: %s\n"),
4018 			    strerror(errno));
4019 			ret = 1;
4020 		}
4021 	} else {
4022 		(void) fprintf(stderr, gettext("filesystem '%s' cannot be "
4023 		    "mounted using 'mount -F zfs'\n"), dataset);
4024 		(void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
4025 		    "instead.\n"), path);
4026 		(void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
4027 		    "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
4028 		(void) fprintf(stderr, gettext("See zfs(1M) for more "
4029 		    "information.\n"));
4030 		ret = 1;
4031 	}
4032 
4033 	return (ret);
4034 }
4035 
4036 /*
4037  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
4038  * unmounts of non-legacy filesystems, as this is the dominant administrative
4039  * interface.
4040  */
4041 static int
4042 manual_unmount(int argc, char **argv)
4043 {
4044 	int flags = 0;
4045 	int c;
4046 
4047 	/* check options */
4048 	while ((c = getopt(argc, argv, "f")) != -1) {
4049 		switch (c) {
4050 		case 'f':
4051 			flags = MS_FORCE;
4052 			break;
4053 		case '?':
4054 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
4055 			    optopt);
4056 			(void) fprintf(stderr, gettext("usage: unmount [-f] "
4057 			    "<path>\n"));
4058 			return (2);
4059 		}
4060 	}
4061 
4062 	argc -= optind;
4063 	argv += optind;
4064 
4065 	/* check arguments */
4066 	if (argc != 1) {
4067 		if (argc == 0)
4068 			(void) fprintf(stderr, gettext("missing path "
4069 			    "argument\n"));
4070 		else
4071 			(void) fprintf(stderr, gettext("too many arguments\n"));
4072 		(void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
4073 		return (2);
4074 	}
4075 
4076 	return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
4077 }
4078 
4079 static int
4080 volcheck(zpool_handle_t *zhp, void *data)
4081 {
4082 	boolean_t isinit = *((boolean_t *)data);
4083 
4084 	if (isinit)
4085 		return (zpool_create_zvol_links(zhp));
4086 	else
4087 		return (zpool_remove_zvol_links(zhp));
4088 }
4089 
4090 /*
4091  * Iterate over all pools in the system and either create or destroy /dev/zvol
4092  * links, depending on the value of 'isinit'.
4093  */
4094 static int
4095 do_volcheck(boolean_t isinit)
4096 {
4097 	return (zpool_iter(g_zfs, volcheck, &isinit) ? 1 : 0);
4098 }
4099 
4100 static int
4101 find_command_idx(char *command, int *idx)
4102 {
4103 	int i;
4104 
4105 	for (i = 0; i < NCOMMAND; i++) {
4106 		if (command_table[i].name == NULL)
4107 			continue;
4108 
4109 		if (strcmp(command, command_table[i].name) == 0) {
4110 			*idx = i;
4111 			return (0);
4112 		}
4113 	}
4114 	return (1);
4115 }
4116 
4117 int
4118 main(int argc, char **argv)
4119 {
4120 	int ret;
4121 	int i;
4122 	char *progname;
4123 	char *cmdname;
4124 
4125 	(void) setlocale(LC_ALL, "");
4126 	(void) textdomain(TEXT_DOMAIN);
4127 
4128 	opterr = 0;
4129 
4130 	if ((g_zfs = libzfs_init()) == NULL) {
4131 		(void) fprintf(stderr, gettext("internal error: failed to "
4132 		    "initialize ZFS library\n"));
4133 		return (1);
4134 	}
4135 
4136 	zpool_set_history_str("zfs", argc, argv, history_str);
4137 	verify(zpool_stage_history(g_zfs, history_str) == 0);
4138 
4139 	libzfs_print_on_error(g_zfs, B_TRUE);
4140 
4141 	if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
4142 		(void) fprintf(stderr, gettext("internal error: unable to "
4143 		    "open %s\n"), MNTTAB);
4144 		return (1);
4145 	}
4146 
4147 	/*
4148 	 * This command also doubles as the /etc/fs mount and unmount program.
4149 	 * Determine if we should take this behavior based on argv[0].
4150 	 */
4151 	progname = basename(argv[0]);
4152 	if (strcmp(progname, "mount") == 0) {
4153 		ret = manual_mount(argc, argv);
4154 	} else if (strcmp(progname, "umount") == 0) {
4155 		ret = manual_unmount(argc, argv);
4156 	} else {
4157 		/*
4158 		 * Make sure the user has specified some command.
4159 		 */
4160 		if (argc < 2) {
4161 			(void) fprintf(stderr, gettext("missing command\n"));
4162 			usage(B_FALSE);
4163 		}
4164 
4165 		cmdname = argv[1];
4166 
4167 		/*
4168 		 * The 'umount' command is an alias for 'unmount'
4169 		 */
4170 		if (strcmp(cmdname, "umount") == 0)
4171 			cmdname = "unmount";
4172 
4173 		/*
4174 		 * The 'recv' command is an alias for 'receive'
4175 		 */
4176 		if (strcmp(cmdname, "recv") == 0)
4177 			cmdname = "receive";
4178 
4179 		/*
4180 		 * Special case '-?'
4181 		 */
4182 		if (strcmp(cmdname, "-?") == 0)
4183 			usage(B_TRUE);
4184 
4185 		/*
4186 		 * 'volinit' and 'volfini' do not appear in the usage message,
4187 		 * so we have to special case them here.
4188 		 */
4189 		if (strcmp(cmdname, "volinit") == 0)
4190 			return (do_volcheck(B_TRUE));
4191 		else if (strcmp(cmdname, "volfini") == 0)
4192 			return (do_volcheck(B_FALSE));
4193 
4194 		/*
4195 		 * Run the appropriate command.
4196 		 */
4197 		if (find_command_idx(cmdname, &i) == 0) {
4198 			current_command = &command_table[i];
4199 			ret = command_table[i].func(argc - 1, argv + 1);
4200 		} else if (strchr(cmdname, '=') != NULL) {
4201 			verify(find_command_idx("set", &i) == 0);
4202 			current_command = &command_table[i];
4203 			ret = command_table[i].func(argc, argv);
4204 		} else {
4205 			(void) fprintf(stderr, gettext("unrecognized "
4206 			    "command '%s'\n"), cmdname);
4207 			usage(B_FALSE);
4208 		}
4209 	}
4210 
4211 	(void) fclose(mnttab_file);
4212 
4213 	libzfs_fini(g_zfs);
4214 
4215 	/*
4216 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4217 	 * for the purposes of running ::findleaks.
4218 	 */
4219 	if (getenv("ZFS_ABORT") != NULL) {
4220 		(void) printf("dumping core by request\n");
4221 		abort();
4222 	}
4223 
4224 	return (ret);
4225 }
4226