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