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