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