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