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