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