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