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