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