xref: /titanic_41/usr/src/cmd/zfs/zfs_main.c (revision 13faa91230bde46da937bf33010b9accc5bdeb59)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <assert.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <libgen.h>
33 #include <libintl.h>
34 #include <libuutil.h>
35 #include <libnvpair.h>
36 #include <locale.h>
37 #include <stddef.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <strings.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <zone.h>
44 #include <sys/mkdev.h>
45 #include <sys/mntent.h>
46 #include <sys/mnttab.h>
47 #include <sys/mount.h>
48 #include <sys/stat.h>
49 #include <sys/avl.h>
50 
51 #include <libzfs.h>
52 #include <libuutil.h>
53 
54 #include "zfs_iter.h"
55 #include "zfs_util.h"
56 
57 libzfs_handle_t *g_zfs;
58 
59 static FILE *mnttab_file;
60 static char history_str[HIS_MAX_RECORD_LEN];
61 
62 static int zfs_do_clone(int argc, char **argv);
63 static int zfs_do_create(int argc, char **argv);
64 static int zfs_do_destroy(int argc, char **argv);
65 static int zfs_do_get(int argc, char **argv);
66 static int zfs_do_inherit(int argc, char **argv);
67 static int zfs_do_list(int argc, char **argv);
68 static int zfs_do_mount(int argc, char **argv);
69 static int zfs_do_rename(int argc, char **argv);
70 static int zfs_do_rollback(int argc, char **argv);
71 static int zfs_do_set(int argc, char **argv);
72 static int zfs_do_upgrade(int argc, char **argv);
73 static int zfs_do_snapshot(int argc, char **argv);
74 static int zfs_do_unmount(int argc, char **argv);
75 static int zfs_do_share(int argc, char **argv);
76 static int zfs_do_unshare(int argc, char **argv);
77 static int zfs_do_send(int argc, char **argv);
78 static int zfs_do_receive(int argc, char **argv);
79 static int zfs_do_promote(int argc, char **argv);
80 static int zfs_do_allow(int argc, char **argv);
81 static int zfs_do_unallow(int argc, char **argv);
82 
83 /*
84  * These libumem hooks provide a reasonable set of defaults for the allocator's
85  * debugging facilities.
86  */
87 const char *
88 _umem_debug_init(void)
89 {
90 	return ("default,verbose"); /* $UMEM_DEBUG setting */
91 }
92 
93 const char *
94 _umem_logging_init(void)
95 {
96 	return ("fail,contents"); /* $UMEM_LOGGING setting */
97 }
98 
99 typedef enum {
100 	HELP_CLONE,
101 	HELP_CREATE,
102 	HELP_DESTROY,
103 	HELP_GET,
104 	HELP_INHERIT,
105 	HELP_UPGRADE,
106 	HELP_LIST,
107 	HELP_MOUNT,
108 	HELP_PROMOTE,
109 	HELP_RECEIVE,
110 	HELP_RENAME,
111 	HELP_ROLLBACK,
112 	HELP_SEND,
113 	HELP_SET,
114 	HELP_SHARE,
115 	HELP_SNAPSHOT,
116 	HELP_UNMOUNT,
117 	HELP_UNSHARE,
118 	HELP_ALLOW,
119 	HELP_UNALLOW
120 } zfs_help_t;
121 
122 typedef struct zfs_command {
123 	const char	*name;
124 	int		(*func)(int argc, char **argv);
125 	zfs_help_t	usage;
126 } zfs_command_t;
127 
128 /*
129  * Master command table.  Each ZFS command has a name, associated function, and
130  * usage message.  The usage messages need to be internationalized, so we have
131  * to have a function to return the usage message based on a command index.
132  *
133  * These commands are organized according to how they are displayed in the usage
134  * message.  An empty command (one with a NULL name) indicates an empty line in
135  * the generic usage message.
136  */
137 static zfs_command_t command_table[] = {
138 	{ "create",	zfs_do_create,		HELP_CREATE		},
139 	{ "destroy",	zfs_do_destroy,		HELP_DESTROY		},
140 	{ NULL },
141 	{ "snapshot",	zfs_do_snapshot,	HELP_SNAPSHOT		},
142 	{ "rollback",	zfs_do_rollback,	HELP_ROLLBACK		},
143 	{ "clone",	zfs_do_clone,		HELP_CLONE		},
144 	{ "promote",	zfs_do_promote,		HELP_PROMOTE		},
145 	{ "rename",	zfs_do_rename,		HELP_RENAME		},
146 	{ NULL },
147 	{ "list",	zfs_do_list,		HELP_LIST		},
148 	{ NULL },
149 	{ "set",	zfs_do_set,		HELP_SET		},
150 	{ "get", 	zfs_do_get,		HELP_GET		},
151 	{ "inherit",	zfs_do_inherit,		HELP_INHERIT		},
152 	{ "upgrade",	zfs_do_upgrade,		HELP_UPGRADE		},
153 	{ NULL },
154 	{ "mount",	zfs_do_mount,		HELP_MOUNT		},
155 	{ "unmount",	zfs_do_unmount,		HELP_UNMOUNT		},
156 	{ "share",	zfs_do_share,		HELP_SHARE		},
157 	{ "unshare",	zfs_do_unshare,		HELP_UNSHARE		},
158 	{ NULL },
159 	{ "send",	zfs_do_send,		HELP_SEND		},
160 	{ "receive",	zfs_do_receive,		HELP_RECEIVE		},
161 	{ NULL },
162 	{ "allow",	zfs_do_allow,		HELP_ALLOW		},
163 	{ NULL },
164 	{ "unallow",	zfs_do_unallow,		HELP_UNALLOW		},
165 };
166 
167 #define	NCOMMAND	(sizeof (command_table) / sizeof (command_table[0]))
168 
169 zfs_command_t *current_command;
170 
171 static const char *
172 get_usage(zfs_help_t idx)
173 {
174 	switch (idx) {
175 	case HELP_CLONE:
176 		return (gettext("\tclone [-p] <snapshot> "
177 		    "<filesystem|volume>\n"));
178 	case HELP_CREATE:
179 		return (gettext("\tcreate [-p] [-o property=value] ... "
180 		    "<filesystem>\n"
181 		    "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
182 		    "-V <size> <volume>\n"));
183 	case HELP_DESTROY:
184 		return (gettext("\tdestroy [-rRf] "
185 		    "<filesystem|volume|snapshot>\n"));
186 	case HELP_GET:
187 		return (gettext("\tget [-rHp] [-o field[,...]] "
188 		    "[-s source[,...]]\n"
189 		    "\t    <\"all\" | property[,...]> "
190 		    "[filesystem|volume|snapshot] ...\n"));
191 	case HELP_INHERIT:
192 		return (gettext("\tinherit [-r] <property> "
193 		    "<filesystem|volume> ...\n"));
194 	case HELP_UPGRADE:
195 		return (gettext("\tupgrade [-v]\n"
196 		    "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
197 	case HELP_LIST:
198 		return (gettext("\tlist [-rH] [-o property[,...]] "
199 		    "[-t type[,...]] [-s property] ...\n"
200 		    "\t    [-S property] ... "
201 		    "[filesystem|volume|snapshot] ...\n"));
202 	case HELP_MOUNT:
203 		return (gettext("\tmount\n"
204 		    "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
205 	case HELP_PROMOTE:
206 		return (gettext("\tpromote <clone-filesystem>\n"));
207 	case HELP_RECEIVE:
208 		return (gettext("\treceive [-vnF] <filesystem|volume|"
209 		"snapshot>\n"
210 		"\treceive [-vnF] -d <filesystem>\n"));
211 	case HELP_RENAME:
212 		return (gettext("\trename <filesystem|volume|snapshot> "
213 		    "<filesystem|volume|snapshot>\n"
214 		    "\trename -p <filesystem|volume> <filesystem|volume>\n"
215 		    "\trename -r <snapshot> <snapshot>"));
216 	case HELP_ROLLBACK:
217 		return (gettext("\trollback [-rRf] <snapshot>\n"));
218 	case HELP_SEND:
219 		return (gettext("\tsend [-R] [-[iI] snapshot] <snapshot>\n"));
220 	case HELP_SET:
221 		return (gettext("\tset <property=value> "
222 		    "<filesystem|volume> ...\n"));
223 	case HELP_SHARE:
224 		return (gettext("\tshare <-a | filesystem>\n"));
225 	case HELP_SNAPSHOT:
226 		return (gettext("\tsnapshot [-r] "
227 		    "<filesystem@snapname|volume@snapname>\n"));
228 	case HELP_UNMOUNT:
229 		return (gettext("\tunmount [-f] "
230 		    "<-a | filesystem|mountpoint>\n"));
231 	case HELP_UNSHARE:
232 		return (gettext("\tunshare [-f] "
233 		    "<-a | filesystem|mountpoint>\n"));
234 	case HELP_ALLOW:
235 		return (gettext("\tallow [-ldug] "
236 		    "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
237 		    "\t    <filesystem|volume>\n"
238 		    "\tallow [-ld] -e <perm|@setname>[,...] "
239 		    "<filesystem|volume>\n"
240 		    "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
241 		    "\tallow -s @setname <perm|@setname>[,...] "
242 		    "<filesystem|volume>\n"));
243 	case HELP_UNALLOW:
244 		return (gettext("\tunallow [-rldug] "
245 		    "<\"everyone\"|user|group>[,...]\n"
246 		    "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
247 		    "\tunallow [-rld] -e [<perm|@setname>[,...]] "
248 		    "<filesystem|volume>\n"
249 		    "\tunallow [-r] -c [<perm|@setname>[,...]] "
250 		    "<filesystem|volume>\n"
251 		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
252 		    "<filesystem|volume>\n"));
253 	}
254 
255 	abort();
256 	/* NOTREACHED */
257 }
258 
259 /*
260  * Utility function to guarantee malloc() success.
261  */
262 void *
263 safe_malloc(size_t size)
264 {
265 	void *data;
266 
267 	if ((data = calloc(1, size)) == NULL) {
268 		(void) fprintf(stderr, "internal error: out of memory\n");
269 		exit(1);
270 	}
271 
272 	return (data);
273 }
274 
275 /*
276  * Callback routine that will print out information for each of
277  * the properties.
278  */
279 static int
280 usage_prop_cb(int prop, void *cb)
281 {
282 	FILE *fp = cb;
283 
284 	(void) fprintf(fp, "\t%-14s ", zfs_prop_to_name(prop));
285 
286 	if (prop == ZFS_PROP_CASE)
287 		(void) fprintf(fp, "NO    ");
288 	else if (zfs_prop_readonly(prop))
289 		(void) fprintf(fp, "  NO    ");
290 	else
291 		(void) fprintf(fp, " YES    ");
292 
293 	if (zfs_prop_inheritable(prop))
294 		(void) fprintf(fp, "  YES   ");
295 	else
296 		(void) fprintf(fp, "   NO   ");
297 
298 	if (zfs_prop_values(prop) == NULL)
299 		(void) fprintf(fp, "-\n");
300 	else
301 		(void) fprintf(fp, "%s\n", zfs_prop_values(prop));
302 
303 	return (ZPROP_CONT);
304 }
305 
306 /*
307  * Display usage message.  If we're inside a command, display only the usage for
308  * that command.  Otherwise, iterate over the entire command table and display
309  * a complete usage message.
310  */
311 static void
312 usage(boolean_t requested)
313 {
314 	int i;
315 	boolean_t show_properties = B_FALSE;
316 	FILE *fp = requested ? stdout : stderr;
317 
318 	if (current_command == NULL) {
319 
320 		(void) fprintf(fp, gettext("usage: zfs command args ...\n"));
321 		(void) fprintf(fp,
322 		    gettext("where 'command' is one of the following:\n\n"));
323 
324 		for (i = 0; i < NCOMMAND; i++) {
325 			if (command_table[i].name == NULL)
326 				(void) fprintf(fp, "\n");
327 			else
328 				(void) fprintf(fp, "%s",
329 				    get_usage(command_table[i].usage));
330 		}
331 
332 		(void) fprintf(fp, gettext("\nEach dataset is of the form: "
333 		    "pool/[dataset/]*dataset[@name]\n"));
334 	} else {
335 		(void) fprintf(fp, gettext("usage:\n"));
336 		(void) fprintf(fp, "%s", get_usage(current_command->usage));
337 	}
338 
339 	if (current_command != NULL &&
340 	    (strcmp(current_command->name, "set") == 0 ||
341 	    strcmp(current_command->name, "get") == 0 ||
342 	    strcmp(current_command->name, "inherit") == 0 ||
343 	    strcmp(current_command->name, "list") == 0))
344 		show_properties = B_TRUE;
345 
346 	if (show_properties) {
347 
348 		(void) fprintf(fp,
349 		    gettext("\nThe following properties are supported:\n"));
350 
351 		(void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
352 		    "PROPERTY", "EDIT", "INHERIT", "VALUES");
353 
354 		/* Iterate over all properties */
355 		(void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
356 		    ZFS_TYPE_DATASET);
357 
358 		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
359 		    "with standard units such as K, M, G, etc.\n"));
360 		(void) fprintf(fp, gettext("\n\nUser-defined properties can "
361 		    "be specified by using a name containing a colon (:).\n"));
362 	} else {
363 		/*
364 		 * TRANSLATION NOTE:
365 		 * "zfs set|get" must not be localised this is the
366 		 * command name and arguments.
367 		 */
368 		(void) fprintf(fp,
369 		    gettext("\nFor the property list, run: zfs set|get\n"));
370 	}
371 
372 	/*
373 	 * See comments at end of main().
374 	 */
375 	if (getenv("ZFS_ABORT") != NULL) {
376 		(void) printf("dumping core by request\n");
377 		abort();
378 	}
379 
380 	exit(requested ? 0 : 2);
381 }
382 
383 /*
384  * zfs clone [-p] <snap> <fs | vol>
385  *
386  * Given an existing dataset, create a writable copy whose initial contents
387  * are the same as the source.  The newly created dataset maintains a
388  * dependency on the original; the original cannot be destroyed so long as
389  * the clone exists.
390  *
391  * The '-p' flag creates all the non-existing ancestors of the target first.
392  */
393 static int
394 zfs_do_clone(int argc, char **argv)
395 {
396 	zfs_handle_t *zhp;
397 	boolean_t parents = B_FALSE;
398 	int ret;
399 	int c;
400 
401 	/* check options */
402 	while ((c = getopt(argc, argv, "p")) != -1) {
403 		switch (c) {
404 		case 'p':
405 			parents = B_TRUE;
406 			break;
407 		case '?':
408 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
409 			    optopt);
410 			usage(B_FALSE);
411 		}
412 	}
413 
414 	argc -= optind;
415 	argv += optind;
416 
417 	/* check number of arguments */
418 	if (argc < 1) {
419 		(void) fprintf(stderr, gettext("missing source dataset "
420 		    "argument\n"));
421 		usage(B_FALSE);
422 	}
423 	if (argc < 2) {
424 		(void) fprintf(stderr, gettext("missing target dataset "
425 		    "argument\n"));
426 		usage(B_FALSE);
427 	}
428 	if (argc > 2) {
429 		(void) fprintf(stderr, gettext("too many arguments\n"));
430 		usage(B_FALSE);
431 	}
432 
433 	/* open the source dataset */
434 	if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
435 		return (1);
436 
437 	if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
438 	    ZFS_TYPE_VOLUME)) {
439 		/*
440 		 * Now create the ancestors of the target dataset.  If the
441 		 * target already exists and '-p' option was used we should not
442 		 * complain.
443 		 */
444 		if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
445 		    ZFS_TYPE_VOLUME))
446 			return (0);
447 		if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
448 			return (1);
449 	}
450 
451 	/* pass to libzfs */
452 	ret = zfs_clone(zhp, argv[1], NULL);
453 
454 	/* create the mountpoint if necessary */
455 	if (ret == 0) {
456 		zfs_handle_t *clone;
457 
458 		clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
459 		if (clone != NULL) {
460 			if ((ret = zfs_mount(clone, NULL, 0)) == 0)
461 				ret = zfs_share(clone);
462 			zfs_close(clone);
463 		}
464 	}
465 
466 	zfs_close(zhp);
467 
468 	return (ret == 0 ? 0 : 1);
469 }
470 
471 /*
472  * zfs create [-p] [-o prop=value] ... fs
473  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
474  *
475  * Create a new dataset.  This command can be used to create filesystems
476  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
477  * For volumes, the user must specify a size to be used.
478  *
479  * The '-s' flag applies only to volumes, and indicates that we should not try
480  * to set the reservation for this volume.  By default we set a reservation
481  * equal to the size for any volume.
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 [-rfR] <snapshot>
1907  *
1908  * 	-r	Delete any intervening snapshots before doing rollback
1909  * 	-R	Delete any snapshots and their clones
1910  * 	-f	Force unmount filesystems, even if they are in use.
1911  *
1912  * Given a filesystem, rollback to a specific snapshot, discarding any changes
1913  * since then and making it the active dataset.  If more recent snapshots exist,
1914  * the command will complain unless the '-r' flag is given.
1915  */
1916 typedef struct rollback_cbdata {
1917 	uint64_t	cb_create;
1918 	boolean_t	cb_first;
1919 	int		cb_doclones;
1920 	char		*cb_target;
1921 	int		cb_error;
1922 	boolean_t	cb_recurse;
1923 	boolean_t	cb_dependent;
1924 } rollback_cbdata_t;
1925 
1926 /*
1927  * Report any snapshots more recent than the one specified.  Used when '-r' is
1928  * not specified.  We reuse this same callback for the snapshot dependents - if
1929  * 'cb_dependent' is set, then this is a dependent and we should report it
1930  * without checking the transaction group.
1931  */
1932 static int
1933 rollback_check(zfs_handle_t *zhp, void *data)
1934 {
1935 	rollback_cbdata_t *cbp = data;
1936 
1937 	if (cbp->cb_doclones) {
1938 		zfs_close(zhp);
1939 		return (0);
1940 	}
1941 
1942 	if (!cbp->cb_dependent) {
1943 		if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
1944 		    zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
1945 		    zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
1946 		    cbp->cb_create) {
1947 
1948 			if (cbp->cb_first && !cbp->cb_recurse) {
1949 				(void) fprintf(stderr, gettext("cannot "
1950 				    "rollback to '%s': more recent snapshots "
1951 				    "exist\n"),
1952 				    cbp->cb_target);
1953 				(void) fprintf(stderr, gettext("use '-r' to "
1954 				    "force deletion of the following "
1955 				    "snapshots:\n"));
1956 				cbp->cb_first = 0;
1957 				cbp->cb_error = 1;
1958 			}
1959 
1960 			if (cbp->cb_recurse) {
1961 				cbp->cb_dependent = B_TRUE;
1962 				if (zfs_iter_dependents(zhp, B_TRUE,
1963 				    rollback_check, cbp) != 0) {
1964 					zfs_close(zhp);
1965 					return (-1);
1966 				}
1967 				cbp->cb_dependent = B_FALSE;
1968 			} else {
1969 				(void) fprintf(stderr, "%s\n",
1970 				    zfs_get_name(zhp));
1971 			}
1972 		}
1973 	} else {
1974 		if (cbp->cb_first && cbp->cb_recurse) {
1975 			(void) fprintf(stderr, gettext("cannot rollback to "
1976 			    "'%s': clones of previous snapshots exist\n"),
1977 			    cbp->cb_target);
1978 			(void) fprintf(stderr, gettext("use '-R' to "
1979 			    "force deletion of the following clones and "
1980 			    "dependents:\n"));
1981 			cbp->cb_first = 0;
1982 			cbp->cb_error = 1;
1983 		}
1984 
1985 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
1986 	}
1987 
1988 	zfs_close(zhp);
1989 	return (0);
1990 }
1991 
1992 static int
1993 zfs_do_rollback(int argc, char **argv)
1994 {
1995 	int ret;
1996 	int c;
1997 	rollback_cbdata_t cb = { 0 };
1998 	zfs_handle_t *zhp, *snap;
1999 	char parentname[ZFS_MAXNAMELEN];
2000 	char *delim;
2001 	int force = 0;
2002 
2003 	/* check options */
2004 	while ((c = getopt(argc, argv, "rfR")) != -1) {
2005 		switch (c) {
2006 		case 'f':
2007 			force = 1;
2008 			break;
2009 		case 'r':
2010 			cb.cb_recurse = 1;
2011 			break;
2012 		case 'R':
2013 			cb.cb_recurse = 1;
2014 			cb.cb_doclones = 1;
2015 			break;
2016 		case '?':
2017 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2018 			    optopt);
2019 			usage(B_FALSE);
2020 		}
2021 	}
2022 
2023 	argc -= optind;
2024 	argv += optind;
2025 
2026 	/* check number of arguments */
2027 	if (argc < 1) {
2028 		(void) fprintf(stderr, gettext("missing dataset argument\n"));
2029 		usage(B_FALSE);
2030 	}
2031 	if (argc > 1) {
2032 		(void) fprintf(stderr, gettext("too many arguments\n"));
2033 		usage(B_FALSE);
2034 	}
2035 
2036 	/* open the snapshot */
2037 	if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2038 		return (1);
2039 
2040 	/* open the parent dataset */
2041 	(void) strlcpy(parentname, argv[0], sizeof (parentname));
2042 	verify((delim = strrchr(parentname, '@')) != NULL);
2043 	*delim = '\0';
2044 	if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2045 		zfs_close(snap);
2046 		return (1);
2047 	}
2048 
2049 	/*
2050 	 * Check for more recent snapshots and/or clones based on the presence
2051 	 * of '-r' and '-R'.
2052 	 */
2053 	cb.cb_target = argv[0];
2054 	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2055 	cb.cb_first = B_TRUE;
2056 	cb.cb_error = 0;
2057 	if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2058 		goto out;
2059 
2060 	if ((ret = cb.cb_error) != 0)
2061 		goto out;
2062 
2063 	/*
2064 	 * Rollback parent to the given snapshot.
2065 	 */
2066 	ret = zfs_rollback(zhp, snap, force);
2067 
2068 out:
2069 	zfs_close(snap);
2070 	zfs_close(zhp);
2071 
2072 	if (ret == 0)
2073 		return (0);
2074 	else
2075 		return (1);
2076 }
2077 
2078 /*
2079  * zfs set property=value { fs | snap | vol } ...
2080  *
2081  * Sets the given property for all datasets specified on the command line.
2082  */
2083 typedef struct set_cbdata {
2084 	char		*cb_propname;
2085 	char		*cb_value;
2086 } set_cbdata_t;
2087 
2088 static int
2089 set_callback(zfs_handle_t *zhp, void *data)
2090 {
2091 	set_cbdata_t *cbp = data;
2092 
2093 	if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2094 		switch (libzfs_errno(g_zfs)) {
2095 		case EZFS_MOUNTFAILED:
2096 			(void) fprintf(stderr, gettext("property may be set "
2097 			    "but unable to remount filesystem\n"));
2098 			break;
2099 		case EZFS_SHARENFSFAILED:
2100 			(void) fprintf(stderr, gettext("property may be set "
2101 			    "but unable to reshare filesystem\n"));
2102 			break;
2103 		}
2104 		return (1);
2105 	}
2106 	return (0);
2107 }
2108 
2109 static int
2110 zfs_do_set(int argc, char **argv)
2111 {
2112 	set_cbdata_t cb;
2113 	int ret;
2114 
2115 	/* check for options */
2116 	if (argc > 1 && argv[1][0] == '-') {
2117 		(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2118 		    argv[1][1]);
2119 		usage(B_FALSE);
2120 	}
2121 
2122 	/* check number of arguments */
2123 	if (argc < 2) {
2124 		(void) fprintf(stderr, gettext("missing property=value "
2125 		    "argument\n"));
2126 		usage(B_FALSE);
2127 	}
2128 	if (argc < 3) {
2129 		(void) fprintf(stderr, gettext("missing dataset name\n"));
2130 		usage(B_FALSE);
2131 	}
2132 
2133 	/* validate property=value argument */
2134 	cb.cb_propname = argv[1];
2135 	if ((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) {
2136 		(void) fprintf(stderr, gettext("missing value in "
2137 		    "property=value argument\n"));
2138 		usage(B_FALSE);
2139 	}
2140 
2141 	*cb.cb_value = '\0';
2142 	cb.cb_value++;
2143 
2144 	if (*cb.cb_propname == '\0') {
2145 		(void) fprintf(stderr,
2146 		    gettext("missing property in property=value argument\n"));
2147 		usage(B_FALSE);
2148 	}
2149 
2150 
2151 	ret = zfs_for_each(argc - 2, argv + 2, B_FALSE,
2152 	    ZFS_TYPE_DATASET, NULL, NULL, set_callback, &cb, B_FALSE);
2153 
2154 	return (ret);
2155 }
2156 
2157 /*
2158  * zfs snapshot [-r] <fs@snap>
2159  *
2160  * Creates a snapshot with the given name.  While functionally equivalent to
2161  * 'zfs create', it is a separate command to differentiate intent.
2162  */
2163 static int
2164 zfs_do_snapshot(int argc, char **argv)
2165 {
2166 	boolean_t recursive = B_FALSE;
2167 	int ret;
2168 	char c;
2169 
2170 	/* check options */
2171 	while ((c = getopt(argc, argv, ":r")) != -1) {
2172 		switch (c) {
2173 		case 'r':
2174 			recursive = B_TRUE;
2175 			break;
2176 		case '?':
2177 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2178 			    optopt);
2179 			usage(B_FALSE);
2180 		}
2181 	}
2182 
2183 	argc -= optind;
2184 	argv += optind;
2185 
2186 	/* check number of arguments */
2187 	if (argc < 1) {
2188 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2189 		usage(B_FALSE);
2190 	}
2191 	if (argc > 1) {
2192 		(void) fprintf(stderr, gettext("too many arguments\n"));
2193 		usage(B_FALSE);
2194 	}
2195 
2196 	ret = zfs_snapshot(g_zfs, argv[0], recursive);
2197 	if (ret && recursive)
2198 		(void) fprintf(stderr, gettext("no snapshots were created\n"));
2199 	return (ret != 0);
2200 }
2201 
2202 /*
2203  * zfs send [-v] -R [-i|-I <@snap>] <fs@snap>
2204  * zfs send [-v] [-i|-I <@snap>] <fs@snap>
2205  *
2206  * Send a backup stream to stdout.
2207  */
2208 static int
2209 zfs_do_send(int argc, char **argv)
2210 {
2211 	char *fromname = NULL;
2212 	char *toname = NULL;
2213 	char *cp;
2214 	zfs_handle_t *zhp;
2215 	boolean_t doall = B_FALSE;
2216 	boolean_t replicate = B_FALSE;
2217 	boolean_t fromorigin = B_FALSE;
2218 	boolean_t verbose = B_FALSE;
2219 	int c, err;
2220 
2221 	/* check options */
2222 	while ((c = getopt(argc, argv, ":i:I:Rv")) != -1) {
2223 		switch (c) {
2224 		case 'i':
2225 			if (fromname)
2226 				usage(B_FALSE);
2227 			fromname = optarg;
2228 			break;
2229 		case 'I':
2230 			if (fromname)
2231 				usage(B_FALSE);
2232 			fromname = optarg;
2233 			doall = B_TRUE;
2234 			break;
2235 		case 'R':
2236 			replicate = B_TRUE;
2237 			break;
2238 		case 'v':
2239 			verbose = B_TRUE;
2240 			break;
2241 		case ':':
2242 			(void) fprintf(stderr, gettext("missing argument for "
2243 			    "'%c' option\n"), optopt);
2244 			usage(B_FALSE);
2245 			break;
2246 		case '?':
2247 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2248 			    optopt);
2249 			usage(B_FALSE);
2250 		}
2251 	}
2252 
2253 	argc -= optind;
2254 	argv += optind;
2255 
2256 	/* check number of arguments */
2257 	if (argc < 1) {
2258 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2259 		usage(B_FALSE);
2260 	}
2261 	if (argc > 1) {
2262 		(void) fprintf(stderr, gettext("too many arguments\n"));
2263 		usage(B_FALSE);
2264 	}
2265 
2266 	if (isatty(STDOUT_FILENO)) {
2267 		(void) fprintf(stderr,
2268 		    gettext("Error: Stream can not be written to a terminal.\n"
2269 		    "You must redirect standard output.\n"));
2270 		return (1);
2271 	}
2272 
2273 	cp = strchr(argv[0], '@');
2274 	if (cp == NULL) {
2275 		(void) fprintf(stderr,
2276 		    gettext("argument must be a snapshot\n"));
2277 		usage(B_FALSE);
2278 	}
2279 	*cp = '\0';
2280 	toname = cp + 1;
2281 	zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2282 	if (zhp == NULL)
2283 		return (1);
2284 
2285 	/*
2286 	 * If they specified the full path to the snapshot, chop off
2287 	 * everything except the short name of the snapshot, but special
2288 	 * case if they specify the origin.
2289 	 */
2290 	if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2291 		char origin[ZFS_MAXNAMELEN];
2292 		zprop_source_t src;
2293 
2294 		(void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2295 		    origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2296 
2297 		if (strcmp(origin, fromname) == 0) {
2298 			fromname = NULL;
2299 			fromorigin = B_TRUE;
2300 		} else {
2301 			*cp = '\0';
2302 			if (cp != fromname && strcmp(argv[0], fromname)) {
2303 				(void) fprintf(stderr,
2304 				    gettext("incremental source must be "
2305 				    "in same filesystem\n"));
2306 				usage(B_FALSE);
2307 			}
2308 			fromname = cp + 1;
2309 			if (strchr(fromname, '@') || strchr(fromname, '/')) {
2310 				(void) fprintf(stderr,
2311 				    gettext("invalid incremental source\n"));
2312 				usage(B_FALSE);
2313 			}
2314 		}
2315 	}
2316 
2317 	if (replicate && fromname == NULL)
2318 		doall = B_TRUE;
2319 
2320 	err = zfs_send(zhp, fromname, toname, replicate, doall, fromorigin,
2321 	    verbose, STDOUT_FILENO);
2322 	zfs_close(zhp);
2323 
2324 	return (err != 0);
2325 }
2326 
2327 /*
2328  * zfs receive [-dnvF] <fs@snap>
2329  *
2330  * Restore a backup stream from stdin.
2331  */
2332 static int
2333 zfs_do_receive(int argc, char **argv)
2334 {
2335 	int c, err;
2336 	recvflags_t flags;
2337 
2338 	bzero(&flags, sizeof (recvflags_t));
2339 	/* check options */
2340 	while ((c = getopt(argc, argv, ":dnvF")) != -1) {
2341 		switch (c) {
2342 		case 'd':
2343 			flags.isprefix = B_TRUE;
2344 			break;
2345 		case 'n':
2346 			flags.dryrun = B_TRUE;
2347 			break;
2348 		case 'v':
2349 			flags.verbose = B_TRUE;
2350 			break;
2351 		case 'F':
2352 			flags.force = B_TRUE;
2353 			break;
2354 		case ':':
2355 			(void) fprintf(stderr, gettext("missing argument for "
2356 			    "'%c' option\n"), optopt);
2357 			usage(B_FALSE);
2358 			break;
2359 		case '?':
2360 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
2361 			    optopt);
2362 			usage(B_FALSE);
2363 		}
2364 	}
2365 
2366 	argc -= optind;
2367 	argv += optind;
2368 
2369 	/* check number of arguments */
2370 	if (argc < 1) {
2371 		(void) fprintf(stderr, gettext("missing snapshot argument\n"));
2372 		usage(B_FALSE);
2373 	}
2374 	if (argc > 1) {
2375 		(void) fprintf(stderr, gettext("too many arguments\n"));
2376 		usage(B_FALSE);
2377 	}
2378 
2379 	if (isatty(STDIN_FILENO)) {
2380 		(void) fprintf(stderr,
2381 		    gettext("Error: Backup stream can not be read "
2382 		    "from a terminal.\n"
2383 		    "You must redirect standard input.\n"));
2384 		return (1);
2385 	}
2386 
2387 	err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2388 
2389 	return (err != 0);
2390 }
2391 
2392 typedef struct allow_cb {
2393 	int  a_permcnt;
2394 	size_t a_treeoffset;
2395 } allow_cb_t;
2396 
2397 static void
2398 zfs_print_perms(avl_tree_t *tree)
2399 {
2400 	zfs_perm_node_t *permnode;
2401 
2402 	permnode = avl_first(tree);
2403 	while (permnode != NULL) {
2404 		(void) printf("%s", permnode->z_pname);
2405 		permnode = AVL_NEXT(tree, permnode);
2406 		if (permnode)
2407 			(void) printf(",");
2408 		else
2409 			(void) printf("\n");
2410 	}
2411 }
2412 
2413 /*
2414  * Iterate over user/groups/everyone/... and the call perm_iter
2415  * function to print actual permission when tree has >0 nodes.
2416  */
2417 static void
2418 zfs_iter_perms(avl_tree_t *tree, const char *banner, allow_cb_t *cb)
2419 {
2420 	zfs_allow_node_t *item;
2421 	avl_tree_t *ptree;
2422 
2423 	item = avl_first(tree);
2424 	while (item) {
2425 		ptree = (void *)((char *)item + cb->a_treeoffset);
2426 		if (avl_numnodes(ptree)) {
2427 			if (cb->a_permcnt++ == 0)
2428 				(void) printf("%s\n", banner);
2429 			(void) printf("\t%s", item->z_key);
2430 			/*
2431 			 * Avoid an extra space being printed
2432 			 * for "everyone" which is keyed with a null
2433 			 * string
2434 			 */
2435 			if (item->z_key[0] != '\0')
2436 				(void) printf(" ");
2437 			zfs_print_perms(ptree);
2438 		}
2439 		item = AVL_NEXT(tree, item);
2440 	}
2441 }
2442 
2443 #define	LINES "-------------------------------------------------------------\n"
2444 static int
2445 zfs_print_allows(char *ds)
2446 {
2447 	zfs_allow_t *curperms, *perms;
2448 	zfs_handle_t *zhp;
2449 	allow_cb_t allowcb = { 0 };
2450 	char banner[MAXPATHLEN];
2451 
2452 	if (ds[0] == '-')
2453 		usage(B_FALSE);
2454 
2455 	if (strrchr(ds, '@')) {
2456 		(void) fprintf(stderr, gettext("Snapshots don't have 'allow'"
2457 		    " permissions\n"));
2458 		return (1);
2459 	}
2460 	if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2461 		return (1);
2462 
2463 	if (zfs_perm_get(zhp, &perms)) {
2464 		(void) fprintf(stderr,
2465 		    gettext("Failed to retrieve 'allows' on %s\n"), ds);
2466 		zfs_close(zhp);
2467 		return (1);
2468 	}
2469 
2470 	zfs_close(zhp);
2471 
2472 	if (perms != NULL)
2473 		(void) printf("%s", LINES);
2474 	for (curperms = perms; curperms; curperms = curperms->z_next) {
2475 
2476 		(void) snprintf(banner, sizeof (banner),
2477 		    "Permission sets on (%s)", curperms->z_setpoint);
2478 		allowcb.a_treeoffset =
2479 		    offsetof(zfs_allow_node_t, z_localdescend);
2480 		allowcb.a_permcnt = 0;
2481 		zfs_iter_perms(&curperms->z_sets, banner, &allowcb);
2482 
2483 		(void) snprintf(banner, sizeof (banner),
2484 		    "Create time permissions on (%s)", curperms->z_setpoint);
2485 		allowcb.a_treeoffset =
2486 		    offsetof(zfs_allow_node_t, z_localdescend);
2487 		allowcb.a_permcnt = 0;
2488 		zfs_iter_perms(&curperms->z_crperms, banner, &allowcb);
2489 
2490 
2491 		(void) snprintf(banner, sizeof (banner),
2492 		    "Local permissions on (%s)", curperms->z_setpoint);
2493 		allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_local);
2494 		allowcb.a_permcnt = 0;
2495 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2496 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2497 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2498 
2499 		(void) snprintf(banner, sizeof (banner),
2500 		    "Descendent permissions on (%s)", curperms->z_setpoint);
2501 		allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_descend);
2502 		allowcb.a_permcnt = 0;
2503 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2504 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2505 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2506 
2507 		(void) snprintf(banner, sizeof (banner),
2508 		    "Local+Descendent permissions on (%s)",
2509 		    curperms->z_setpoint);
2510 		allowcb.a_treeoffset =
2511 		    offsetof(zfs_allow_node_t, z_localdescend);
2512 		allowcb.a_permcnt = 0;
2513 		zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2514 		zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2515 		zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2516 
2517 		(void) printf("%s", LINES);
2518 	}
2519 	zfs_free_allows(perms);
2520 	return (0);
2521 }
2522 
2523 #define	ALLOWOPTIONS "ldcsu:g:e"
2524 #define	UNALLOWOPTIONS "ldcsu:g:er"
2525 
2526 /*
2527  * Validate options, and build necessary datastructure to display/remove/add
2528  * permissions.
2529  * Returns 0 - If permissions should be added/removed
2530  * Returns 1 - If permissions should be displayed.
2531  * Returns -1 - on failure
2532  */
2533 int
2534 parse_allow_args(int *argc, char **argv[], boolean_t unallow,
2535     char **ds, int *recurse, nvlist_t **zperms)
2536 {
2537 	int c;
2538 	char *options = unallow ? UNALLOWOPTIONS : ALLOWOPTIONS;
2539 	zfs_deleg_inherit_t deleg_type = ZFS_DELEG_NONE;
2540 	zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
2541 	char *who = NULL;
2542 	char *perms = NULL;
2543 	zfs_handle_t *zhp;
2544 
2545 	while ((c = getopt(*argc, *argv, options)) != -1) {
2546 		switch (c) {
2547 		case 'l':
2548 			if (who_type == ZFS_DELEG_CREATE ||
2549 			    who_type == ZFS_DELEG_NAMED_SET)
2550 				usage(B_FALSE);
2551 
2552 			deleg_type |= ZFS_DELEG_PERM_LOCAL;
2553 			break;
2554 		case 'd':
2555 			if (who_type == ZFS_DELEG_CREATE ||
2556 			    who_type == ZFS_DELEG_NAMED_SET)
2557 				usage(B_FALSE);
2558 
2559 			deleg_type |= ZFS_DELEG_PERM_DESCENDENT;
2560 			break;
2561 		case 'r':
2562 			*recurse = B_TRUE;
2563 			break;
2564 		case 'c':
2565 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2566 				usage(B_FALSE);
2567 			if (deleg_type)
2568 				usage(B_FALSE);
2569 			who_type = ZFS_DELEG_CREATE;
2570 			break;
2571 		case 's':
2572 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2573 				usage(B_FALSE);
2574 			if (deleg_type)
2575 				usage(B_FALSE);
2576 			who_type = ZFS_DELEG_NAMED_SET;
2577 			break;
2578 		case 'u':
2579 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2580 				usage(B_FALSE);
2581 			who_type = ZFS_DELEG_USER;
2582 			who = optarg;
2583 			break;
2584 		case 'g':
2585 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2586 				usage(B_FALSE);
2587 			who_type = ZFS_DELEG_GROUP;
2588 			who = optarg;
2589 			break;
2590 		case 'e':
2591 			if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2592 				usage(B_FALSE);
2593 			who_type = ZFS_DELEG_EVERYONE;
2594 			break;
2595 		default:
2596 			usage(B_FALSE);
2597 			break;
2598 		}
2599 	}
2600 
2601 	if (deleg_type == 0)
2602 		deleg_type = ZFS_DELEG_PERM_LOCALDESCENDENT;
2603 
2604 	*argc -= optind;
2605 	*argv += optind;
2606 
2607 	if (unallow == B_FALSE && *argc == 1) {
2608 		/*
2609 		 * Only print permissions if no options were processed
2610 		 */
2611 		if (optind == 1)
2612 			return (1);
2613 		else
2614 			usage(B_FALSE);
2615 	}
2616 
2617 	/*
2618 	 * initialize variables for zfs_build_perms based on number
2619 	 * of arguments.
2620 	 * 3 arguments ==>	zfs [un]allow joe perm,perm,perm <dataset> or
2621 	 *			zfs [un]allow -s @set1 perm,perm <dataset>
2622 	 * 2 arguments ==>	zfs [un]allow -c perm,perm <dataset> or
2623 	 *			zfs [un]allow -u|-g <name> perm <dataset> or
2624 	 *			zfs [un]allow -e perm,perm <dataset>
2625 	 *			zfs unallow joe <dataset>
2626 	 *			zfs unallow -s @set1 <dataset>
2627 	 * 1 argument  ==>	zfs [un]allow -e <dataset> or
2628 	 *			zfs [un]allow -c <dataset>
2629 	 */
2630 
2631 	switch (*argc) {
2632 	case 3:
2633 		perms = (*argv)[1];
2634 		who = (*argv)[0];
2635 		*ds = (*argv)[2];
2636 
2637 		/*
2638 		 * advance argc/argv for do_allow cases.
2639 		 * for do_allow case make sure who have a know who type
2640 		 * and its not a permission set.
2641 		 */
2642 		if (unallow == B_TRUE) {
2643 			*argc -= 2;
2644 			*argv += 2;
2645 		} else if (who_type != ZFS_DELEG_WHO_UNKNOWN &&
2646 		    who_type != ZFS_DELEG_NAMED_SET)
2647 			usage(B_FALSE);
2648 		break;
2649 
2650 	case 2:
2651 		if (unallow == B_TRUE && (who_type == ZFS_DELEG_EVERYONE ||
2652 		    who_type == ZFS_DELEG_CREATE || who != NULL)) {
2653 			perms = (*argv)[0];
2654 			*ds = (*argv)[1];
2655 		} else {
2656 			if (unallow == B_FALSE &&
2657 			    (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2658 			    who_type == ZFS_DELEG_NAMED_SET))
2659 				usage(B_FALSE);
2660 			else if (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2661 			    who_type == ZFS_DELEG_NAMED_SET)
2662 				who = (*argv)[0];
2663 			else if (who_type != ZFS_DELEG_NAMED_SET)
2664 				perms = (*argv)[0];
2665 			*ds = (*argv)[1];
2666 		}
2667 		if (unallow == B_TRUE) {
2668 			(*argc)--;
2669 			(*argv)++;
2670 		}
2671 		break;
2672 
2673 	case 1:
2674 		if (unallow == B_FALSE)
2675 			usage(B_FALSE);
2676 		if (who == NULL && who_type != ZFS_DELEG_CREATE &&
2677 		    who_type != ZFS_DELEG_EVERYONE)
2678 			usage(B_FALSE);
2679 		*ds = (*argv)[0];
2680 		break;
2681 
2682 	default:
2683 		usage(B_FALSE);
2684 	}
2685 
2686 	if (strrchr(*ds, '@')) {
2687 		(void) fprintf(stderr,
2688 		    gettext("Can't set or remove 'allow' permissions "
2689 		    "on snapshots.\n"));
2690 			return (-1);
2691 	}
2692 
2693 	if ((zhp = zfs_open(g_zfs, *ds, ZFS_TYPE_DATASET)) == NULL)
2694 		return (-1);
2695 
2696 	if ((zfs_build_perms(zhp, who, perms,
2697 	    who_type, deleg_type, zperms)) != 0) {
2698 		zfs_close(zhp);
2699 		return (-1);
2700 	}
2701 	zfs_close(zhp);
2702 	return (0);
2703 }
2704 
2705 static int
2706 zfs_do_allow(int argc, char **argv)
2707 {
2708 	char *ds;
2709 	nvlist_t *zperms = NULL;
2710 	zfs_handle_t *zhp;
2711 	int unused;
2712 	int ret;
2713 
2714 	if ((ret = parse_allow_args(&argc, &argv, B_FALSE, &ds,
2715 	    &unused, &zperms)) == -1)
2716 		return (1);
2717 
2718 	if (ret == 1)
2719 		return (zfs_print_allows(argv[0]));
2720 
2721 	if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2722 		return (1);
2723 
2724 	if (zfs_perm_set(zhp, zperms)) {
2725 		zfs_close(zhp);
2726 		nvlist_free(zperms);
2727 		return (1);
2728 	}
2729 	nvlist_free(zperms);
2730 	zfs_close(zhp);
2731 
2732 	return (0);
2733 }
2734 
2735 static int
2736 unallow_callback(zfs_handle_t *zhp, void *data)
2737 {
2738 	nvlist_t *nvp = (nvlist_t *)data;
2739 	int error;
2740 
2741 	error = zfs_perm_remove(zhp, nvp);
2742 	if (error) {
2743 		(void) fprintf(stderr, gettext("Failed to remove permissions "
2744 		    "on %s\n"), zfs_get_name(zhp));
2745 	}
2746 	return (error);
2747 }
2748 
2749 static int
2750 zfs_do_unallow(int argc, char **argv)
2751 {
2752 	int recurse = B_FALSE;
2753 	char *ds;
2754 	int error;
2755 	nvlist_t *zperms = NULL;
2756 
2757 	if (parse_allow_args(&argc, &argv, B_TRUE,
2758 	    &ds, &recurse, &zperms) == -1)
2759 		return (1);
2760 
2761 	error = zfs_for_each(argc, argv, recurse,
2762 	    ZFS_TYPE_FILESYSTEM|ZFS_TYPE_VOLUME, NULL,
2763 	    NULL, unallow_callback, (void *)zperms, B_FALSE);
2764 
2765 	if (zperms)
2766 		nvlist_free(zperms);
2767 
2768 	return (error);
2769 }
2770 
2771 typedef struct get_all_cbdata {
2772 	zfs_handle_t	**cb_handles;
2773 	size_t		cb_alloc;
2774 	size_t		cb_used;
2775 	uint_t		cb_types;
2776 	boolean_t	cb_verbose;
2777 } get_all_cbdata_t;
2778 
2779 #define	CHECK_SPINNER 30
2780 #define	SPINNER_TIME 3		/* seconds */
2781 #define	MOUNT_TIME 5		/* seconds */
2782 
2783 static int
2784 get_one_dataset(zfs_handle_t *zhp, void *data)
2785 {
2786 	static char spin[] = { '-', '\\', '|', '/' };
2787 	static int spinval = 0;
2788 	static int spincheck = 0;
2789 	static time_t last_spin_time = (time_t)0;
2790 	get_all_cbdata_t *cbp = data;
2791 	zfs_type_t type = zfs_get_type(zhp);
2792 
2793 	if (cbp->cb_verbose) {
2794 		if (--spincheck < 0) {
2795 			time_t now = time(NULL);
2796 			if (last_spin_time + SPINNER_TIME < now) {
2797 				(void) printf("\b%c", spin[spinval++ % 4]);
2798 				(void) fflush(stdout);
2799 				last_spin_time = now;
2800 			}
2801 			spincheck = CHECK_SPINNER;
2802 		}
2803 	}
2804 
2805 	/*
2806 	 * Interate over any nested datasets.
2807 	 */
2808 	if (type == ZFS_TYPE_FILESYSTEM &&
2809 	    zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2810 		zfs_close(zhp);
2811 		return (1);
2812 	}
2813 
2814 	/*
2815 	 * Skip any datasets whose type does not match.
2816 	 */
2817 	if ((type & cbp->cb_types) == 0) {
2818 		zfs_close(zhp);
2819 		return (0);
2820 	}
2821 
2822 	if (cbp->cb_alloc == cbp->cb_used) {
2823 		zfs_handle_t **handles;
2824 
2825 		if (cbp->cb_alloc == 0)
2826 			cbp->cb_alloc = 64;
2827 		else
2828 			cbp->cb_alloc *= 2;
2829 
2830 		handles = safe_malloc(cbp->cb_alloc * sizeof (void *));
2831 
2832 		if (cbp->cb_handles) {
2833 			bcopy(cbp->cb_handles, handles,
2834 			    cbp->cb_used * sizeof (void *));
2835 			free(cbp->cb_handles);
2836 		}
2837 
2838 		cbp->cb_handles = handles;
2839 	}
2840 
2841 	cbp->cb_handles[cbp->cb_used++] = zhp;
2842 
2843 	return (0);
2844 }
2845 
2846 static void
2847 get_all_datasets(uint_t types, zfs_handle_t ***dslist, size_t *count,
2848     boolean_t verbose)
2849 {
2850 	get_all_cbdata_t cb = { 0 };
2851 	cb.cb_types = types;
2852 	cb.cb_verbose = verbose;
2853 
2854 	if (verbose) {
2855 		(void) printf("%s: *", gettext("Reading ZFS config"));
2856 		(void) fflush(stdout);
2857 	}
2858 
2859 	(void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2860 
2861 	*dslist = cb.cb_handles;
2862 	*count = cb.cb_used;
2863 
2864 	if (verbose) {
2865 		(void) printf("\b%s\n", gettext("done."));
2866 	}
2867 }
2868 
2869 static int
2870 dataset_cmp(const void *a, const void *b)
2871 {
2872 	zfs_handle_t **za = (zfs_handle_t **)a;
2873 	zfs_handle_t **zb = (zfs_handle_t **)b;
2874 	char mounta[MAXPATHLEN];
2875 	char mountb[MAXPATHLEN];
2876 	boolean_t gota, gotb;
2877 
2878 	if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
2879 		verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
2880 		    sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
2881 	if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
2882 		verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
2883 		    sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
2884 
2885 	if (gota && gotb)
2886 		return (strcmp(mounta, mountb));
2887 
2888 	if (gota)
2889 		return (-1);
2890 	if (gotb)
2891 		return (1);
2892 
2893 	return (strcmp(zfs_get_name(a), zfs_get_name(b)));
2894 }
2895 
2896 /*
2897  * Generic callback for sharing or mounting filesystems.  Because the code is so
2898  * similar, we have a common function with an extra parameter to determine which
2899  * mode we are using.
2900  */
2901 #define	OP_SHARE	0x1
2902 #define	OP_MOUNT	0x2
2903 
2904 /*
2905  * Share or mount a dataset.
2906  */
2907 static int
2908 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
2909     boolean_t explicit, const char *options)
2910 {
2911 	char mountpoint[ZFS_MAXPROPLEN];
2912 	char shareopts[ZFS_MAXPROPLEN];
2913 	char smbshareopts[ZFS_MAXPROPLEN];
2914 	const char *cmdname = op == OP_SHARE ? "share" : "mount";
2915 	struct mnttab mnt;
2916 	uint64_t zoned, canmount;
2917 	zfs_type_t type = zfs_get_type(zhp);
2918 	boolean_t shared_nfs, shared_smb;
2919 
2920 	assert(type & (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME));
2921 
2922 	if (type == ZFS_TYPE_FILESYSTEM) {
2923 		/*
2924 		 * Check to make sure we can mount/share this dataset.  If we
2925 		 * are in the global zone and the filesystem is exported to a
2926 		 * local zone, or if we are in a local zone and the
2927 		 * filesystem is not exported, then it is an error.
2928 		 */
2929 		zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2930 
2931 		if (zoned && getzoneid() == GLOBAL_ZONEID) {
2932 			if (!explicit)
2933 				return (0);
2934 
2935 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2936 			    "dataset is exported to a local zone\n"), cmdname,
2937 			    zfs_get_name(zhp));
2938 			return (1);
2939 
2940 		} else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
2941 			if (!explicit)
2942 				return (0);
2943 
2944 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2945 			    "permission denied\n"), cmdname,
2946 			    zfs_get_name(zhp));
2947 			return (1);
2948 		}
2949 
2950 		/*
2951 		 * Ignore any filesystems which don't apply to us. This
2952 		 * includes those with a legacy mountpoint, or those with
2953 		 * legacy share options.
2954 		 */
2955 		verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
2956 		    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
2957 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
2958 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
2959 		verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
2960 		    sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
2961 		canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
2962 
2963 		if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
2964 		    strcmp(smbshareopts, "off") == 0) {
2965 			if (!explicit)
2966 				return (0);
2967 
2968 			(void) fprintf(stderr, gettext("cannot share '%s': "
2969 			    "legacy share\n"), zfs_get_name(zhp));
2970 			(void) fprintf(stderr, gettext("use share(1M) to "
2971 			    "share this filesystem\n"));
2972 			return (1);
2973 		}
2974 
2975 		/*
2976 		 * We cannot share or mount legacy filesystems. If the
2977 		 * shareopts is non-legacy but the mountpoint is legacy, we
2978 		 * treat it as a legacy share.
2979 		 */
2980 		if (strcmp(mountpoint, "legacy") == 0) {
2981 			if (!explicit)
2982 				return (0);
2983 
2984 			(void) fprintf(stderr, gettext("cannot %s '%s': "
2985 			    "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
2986 			(void) fprintf(stderr, gettext("use %s(1M) to "
2987 			    "%s this filesystem\n"), cmdname, cmdname);
2988 			return (1);
2989 		}
2990 
2991 		if (strcmp(mountpoint, "none") == 0) {
2992 			if (!explicit)
2993 				return (0);
2994 
2995 			(void) fprintf(stderr, gettext("cannot %s '%s': no "
2996 			    "mountpoint set\n"), cmdname, zfs_get_name(zhp));
2997 			return (1);
2998 		}
2999 
3000 		if (!canmount) {
3001 			if (!explicit)
3002 				return (0);
3003 
3004 			(void) fprintf(stderr, gettext("cannot %s '%s': "
3005 			    "'canmount' property is set to 'off'\n"), cmdname,
3006 			    zfs_get_name(zhp));
3007 			return (1);
3008 		}
3009 
3010 		/*
3011 		 * At this point, we have verified that the mountpoint and/or
3012 		 * shareopts are appropriate for auto management. If the
3013 		 * filesystem is already mounted or shared, return (failing
3014 		 * for explicit requests); otherwise mount or share the
3015 		 * filesystem.
3016 		 */
3017 		switch (op) {
3018 		case OP_SHARE:
3019 
3020 			shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3021 			shared_smb = zfs_is_shared_smb(zhp, NULL);
3022 
3023 			if (shared_nfs && shared_smb ||
3024 			    (shared_nfs && strcmp(shareopts, "on") == 0 &&
3025 			    strcmp(smbshareopts, "off") == 0) ||
3026 			    (shared_smb && strcmp(smbshareopts, "on") == 0 &&
3027 			    strcmp(shareopts, "off") == 0)) {
3028 				if (!explicit)
3029 					return (0);
3030 
3031 				(void) fprintf(stderr, gettext("cannot share "
3032 				    "'%s': filesystem already shared\n"),
3033 				    zfs_get_name(zhp));
3034 				return (1);
3035 			}
3036 
3037 			if (!zfs_is_mounted(zhp, NULL) &&
3038 			    zfs_mount(zhp, NULL, 0) != 0)
3039 				return (1);
3040 
3041 			if (protocol == NULL) {
3042 				if (zfs_shareall(zhp) != 0)
3043 					return (1);
3044 			} else if (strcmp(protocol, "nfs") == 0) {
3045 				if (zfs_share_nfs(zhp))
3046 					return (1);
3047 			} else if (strcmp(protocol, "smb") == 0) {
3048 				if (zfs_share_smb(zhp))
3049 					return (1);
3050 			} else {
3051 				(void) fprintf(stderr, gettext("cannot share "
3052 				    "'%s': invalid share type '%s' "
3053 				    "specified\n"),
3054 				    zfs_get_name(zhp), protocol);
3055 				return (1);
3056 			}
3057 
3058 			break;
3059 
3060 		case OP_MOUNT:
3061 			if (options == NULL)
3062 				mnt.mnt_mntopts = "";
3063 			else
3064 				mnt.mnt_mntopts = (char *)options;
3065 
3066 			if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3067 			    zfs_is_mounted(zhp, NULL)) {
3068 				if (!explicit)
3069 					return (0);
3070 
3071 				(void) fprintf(stderr, gettext("cannot mount "
3072 				    "'%s': filesystem already mounted\n"),
3073 				    zfs_get_name(zhp));
3074 				return (1);
3075 			}
3076 
3077 			if (zfs_mount(zhp, options, flags) != 0)
3078 				return (1);
3079 			break;
3080 		}
3081 	} else {
3082 		assert(op == OP_SHARE);
3083 
3084 		/*
3085 		 * Ignore any volumes that aren't shared.
3086 		 */
3087 		verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, shareopts,
3088 		    sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3089 
3090 		if (strcmp(shareopts, "off") == 0) {
3091 			if (!explicit)
3092 				return (0);
3093 
3094 			(void) fprintf(stderr, gettext("cannot share '%s': "
3095 			    "'shareiscsi' property not set\n"),
3096 			    zfs_get_name(zhp));
3097 			(void) fprintf(stderr, gettext("set 'shareiscsi' "
3098 			    "property or use iscsitadm(1M) to share this "
3099 			    "volume\n"));
3100 			return (1);
3101 		}
3102 
3103 		if (zfs_is_shared_iscsi(zhp)) {
3104 			if (!explicit)
3105 				return (0);
3106 
3107 			(void) fprintf(stderr, gettext("cannot share "
3108 			    "'%s': volume already shared\n"),
3109 			    zfs_get_name(zhp));
3110 			return (1);
3111 		}
3112 
3113 		if (zfs_share_iscsi(zhp) != 0)
3114 			return (1);
3115 	}
3116 
3117 	return (0);
3118 }
3119 
3120 /*
3121  * Reports progress in the form "(current/total)".  Not thread-safe.
3122  */
3123 static void
3124 report_mount_progress(int current, int total)
3125 {
3126 	static int len;
3127 	static char *reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
3128 	    "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
3129 	static time_t last_progress_time;
3130 	time_t now = time(NULL);
3131 
3132 	/* report 1..n instead of 0..n-1 */
3133 	++current;
3134 
3135 	/* display header if we're here for the first time */
3136 	if (current == 1) {
3137 		(void) printf(gettext("Mounting ZFS filesystems: "));
3138 		len = 0;
3139 	} else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3140 		/* too soon to report again */
3141 		return;
3142 	}
3143 
3144 	last_progress_time = now;
3145 
3146 	/* back up to prepare for overwriting */
3147 	if (len)
3148 		(void) printf("%*.*s", len, len, reverse);
3149 
3150 	/* We put a newline at the end if this is the last one.  */
3151 	len = printf("(%d/%d)%s", current, total, current == total ? "\n" : "");
3152 	(void) fflush(stdout);
3153 }
3154 
3155 static int
3156 share_mount(int op, int argc, char **argv)
3157 {
3158 	int do_all = 0;
3159 	boolean_t verbose = B_FALSE;
3160 	int c, ret = 0;
3161 	const char *options = NULL;
3162 	int types, flags = 0;
3163 
3164 	/* check options */
3165 	while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
3166 	    != -1) {
3167 		switch (c) {
3168 		case 'a':
3169 			do_all = 1;
3170 			break;
3171 		case 'v':
3172 			verbose = B_TRUE;
3173 			break;
3174 		case 'o':
3175 			if (strlen(optarg) <= MNT_LINE_MAX) {
3176 				options = optarg;
3177 				break;
3178 			}
3179 			(void) fprintf(stderr, gettext("the opts argument for "
3180 			    "'%c' option is too long (more than %d chars)\n"),
3181 			    optopt, MNT_LINE_MAX);
3182 			usage(B_FALSE);
3183 			break;
3184 
3185 		case 'O':
3186 			flags |= MS_OVERLAY;
3187 			break;
3188 		case ':':
3189 			(void) fprintf(stderr, gettext("missing argument for "
3190 			    "'%c' option\n"), optopt);
3191 			usage(B_FALSE);
3192 			break;
3193 		case '?':
3194 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3195 			    optopt);
3196 			usage(B_FALSE);
3197 		}
3198 	}
3199 
3200 	argc -= optind;
3201 	argv += optind;
3202 
3203 	/* check number of arguments */
3204 	if (do_all) {
3205 		zfs_handle_t **dslist = NULL;
3206 		size_t i, count = 0;
3207 		char *protocol = NULL;
3208 
3209 		if (op == OP_MOUNT) {
3210 			types = ZFS_TYPE_FILESYSTEM;
3211 		} else if (argc > 0) {
3212 			if (strcmp(argv[0], "nfs") == 0 ||
3213 			    strcmp(argv[0], "smb") == 0) {
3214 				types = ZFS_TYPE_FILESYSTEM;
3215 			} else if (strcmp(argv[0], "iscsi") == 0) {
3216 				types = ZFS_TYPE_VOLUME;
3217 			} else {
3218 				(void) fprintf(stderr, gettext("share type "
3219 				    "must be 'nfs', 'smb' or 'iscsi'\n"));
3220 				usage(B_FALSE);
3221 			}
3222 			protocol = argv[0];
3223 			argc--;
3224 			argv++;
3225 		} else {
3226 			types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3227 		}
3228 
3229 		if (argc != 0) {
3230 			(void) fprintf(stderr, gettext("too many arguments\n"));
3231 			usage(B_FALSE);
3232 		}
3233 
3234 		get_all_datasets(types, &dslist, &count, verbose);
3235 
3236 		if (count == 0)
3237 			return (0);
3238 
3239 		qsort(dslist, count, sizeof (void *), dataset_cmp);
3240 
3241 		for (i = 0; i < count; i++) {
3242 			if (verbose)
3243 				report_mount_progress(i, count);
3244 
3245 			if (share_mount_one(dslist[i], op, flags, protocol,
3246 			    B_FALSE, options) != 0)
3247 				ret = 1;
3248 			zfs_close(dslist[i]);
3249 		}
3250 
3251 		free(dslist);
3252 	} else if (argc == 0) {
3253 		struct mnttab entry;
3254 
3255 		if ((op == OP_SHARE) || (options != NULL)) {
3256 			(void) fprintf(stderr, gettext("missing filesystem "
3257 			    "argument (specify -a for all)\n"));
3258 			usage(B_FALSE);
3259 		}
3260 
3261 		/*
3262 		 * When mount is given no arguments, go through /etc/mnttab and
3263 		 * display any active ZFS mounts.  We hide any snapshots, since
3264 		 * they are controlled automatically.
3265 		 */
3266 		rewind(mnttab_file);
3267 		while (getmntent(mnttab_file, &entry) == 0) {
3268 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3269 			    strchr(entry.mnt_special, '@') != NULL)
3270 				continue;
3271 
3272 			(void) printf("%-30s  %s\n", entry.mnt_special,
3273 			    entry.mnt_mountp);
3274 		}
3275 
3276 	} else {
3277 		zfs_handle_t *zhp;
3278 
3279 		types = ZFS_TYPE_FILESYSTEM;
3280 		if (op == OP_SHARE)
3281 			types |= ZFS_TYPE_VOLUME;
3282 
3283 		if (argc > 1) {
3284 			(void) fprintf(stderr,
3285 			    gettext("too many arguments\n"));
3286 			usage(B_FALSE);
3287 		}
3288 
3289 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL) {
3290 			ret = 1;
3291 		} else {
3292 			ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3293 			    options);
3294 			zfs_close(zhp);
3295 		}
3296 	}
3297 
3298 	return (ret);
3299 }
3300 
3301 /*
3302  * zfs mount -a [nfs | iscsi]
3303  * zfs mount filesystem
3304  *
3305  * Mount all filesystems, or mount the given filesystem.
3306  */
3307 static int
3308 zfs_do_mount(int argc, char **argv)
3309 {
3310 	return (share_mount(OP_MOUNT, argc, argv));
3311 }
3312 
3313 /*
3314  * zfs share -a [nfs | iscsi | smb]
3315  * zfs share filesystem
3316  *
3317  * Share all filesystems, or share the given filesystem.
3318  */
3319 static int
3320 zfs_do_share(int argc, char **argv)
3321 {
3322 	return (share_mount(OP_SHARE, argc, argv));
3323 }
3324 
3325 typedef struct unshare_unmount_node {
3326 	zfs_handle_t	*un_zhp;
3327 	char		*un_mountp;
3328 	uu_avl_node_t	un_avlnode;
3329 } unshare_unmount_node_t;
3330 
3331 /* ARGSUSED */
3332 static int
3333 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3334 {
3335 	const unshare_unmount_node_t *l = larg;
3336 	const unshare_unmount_node_t *r = rarg;
3337 
3338 	return (strcmp(l->un_mountp, r->un_mountp));
3339 }
3340 
3341 /*
3342  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3343  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
3344  * and unmount it appropriately.
3345  */
3346 static int
3347 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3348 {
3349 	zfs_handle_t *zhp;
3350 	int ret;
3351 	struct stat64 statbuf;
3352 	struct extmnttab entry;
3353 	const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3354 	char nfs_mnt_prop[ZFS_MAXPROPLEN];
3355 	char smbshare_prop[ZFS_MAXPROPLEN];
3356 
3357 	/*
3358 	 * Search for the path in /etc/mnttab.  Rather than looking for the
3359 	 * specific path, which can be fooled by non-standard paths (i.e. ".."
3360 	 * or "//"), we stat() the path and search for the corresponding
3361 	 * (major,minor) device pair.
3362 	 */
3363 	if (stat64(path, &statbuf) != 0) {
3364 		(void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3365 		    cmdname, path, strerror(errno));
3366 		return (1);
3367 	}
3368 
3369 	/*
3370 	 * Search for the given (major,minor) pair in the mount table.
3371 	 */
3372 	rewind(mnttab_file);
3373 	while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3374 		if (entry.mnt_major == major(statbuf.st_dev) &&
3375 		    entry.mnt_minor == minor(statbuf.st_dev))
3376 			break;
3377 	}
3378 	if (ret != 0) {
3379 		(void) fprintf(stderr, gettext("cannot %s '%s': not "
3380 		    "currently mounted\n"), cmdname, path);
3381 		return (1);
3382 	}
3383 
3384 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3385 		(void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3386 		    "filesystem\n"), cmdname, path);
3387 		return (1);
3388 	}
3389 
3390 	if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3391 	    ZFS_TYPE_FILESYSTEM)) == NULL)
3392 		return (1);
3393 
3394 	verify(zfs_prop_get(zhp, op == OP_SHARE ?
3395 	    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT, nfs_mnt_prop,
3396 	    sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3397 	verify(zfs_prop_get(zhp, op == OP_SHARE ?
3398 	    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT, smbshare_prop,
3399 	    sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3400 
3401 	if (op == OP_SHARE) {
3402 		if (strcmp(nfs_mnt_prop, "off") == 0 &&
3403 		    strcmp(smbshare_prop, "off") == 0) {
3404 			(void) fprintf(stderr, gettext("cannot unshare "
3405 			    "'%s': legacy share\n"), path);
3406 			(void) fprintf(stderr, gettext("use "
3407 			    "unshare(1M) to unshare this filesystem\n"));
3408 			ret = 1;
3409 		} else if (!zfs_is_shared(zhp)) {
3410 			(void) fprintf(stderr, gettext("cannot unshare '%s': "
3411 			    "not currently shared\n"), path);
3412 			ret = 1;
3413 		} else {
3414 			ret = zfs_unshareall_bypath(zhp, path);
3415 		}
3416 	} else {
3417 		if (is_manual) {
3418 			ret = zfs_unmount(zhp, NULL, flags);
3419 		} else if (strcmp(nfs_mnt_prop, "legacy") == 0) {
3420 			(void) fprintf(stderr, gettext("cannot unmount "
3421 			    "'%s': legacy mountpoint\n"),
3422 			    zfs_get_name(zhp));
3423 			(void) fprintf(stderr, gettext("use umount(1M) "
3424 			    "to unmount this filesystem\n"));
3425 			ret = 1;
3426 		} else {
3427 			ret = zfs_unmountall(zhp, flags);
3428 		}
3429 	}
3430 
3431 	zfs_close(zhp);
3432 
3433 	return (ret != 0);
3434 }
3435 
3436 /*
3437  * Generic callback for unsharing or unmounting a filesystem.
3438  */
3439 static int
3440 unshare_unmount(int op, int argc, char **argv)
3441 {
3442 	int do_all = 0;
3443 	int flags = 0;
3444 	int ret = 0;
3445 	int types, c;
3446 	zfs_handle_t *zhp;
3447 	char nfsiscsi_mnt_prop[ZFS_MAXPROPLEN];
3448 	char sharesmb[ZFS_MAXPROPLEN];
3449 
3450 	/* check options */
3451 	while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3452 		switch (c) {
3453 		case 'a':
3454 			do_all = 1;
3455 			break;
3456 		case 'f':
3457 			flags = MS_FORCE;
3458 			break;
3459 		case '?':
3460 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3461 			    optopt);
3462 			usage(B_FALSE);
3463 		}
3464 	}
3465 
3466 	argc -= optind;
3467 	argv += optind;
3468 
3469 	if (do_all) {
3470 		/*
3471 		 * We could make use of zfs_for_each() to walk all datasets in
3472 		 * the system, but this would be very inefficient, especially
3473 		 * since we would have to linearly search /etc/mnttab for each
3474 		 * one.  Instead, do one pass through /etc/mnttab looking for
3475 		 * zfs entries and call zfs_unmount() for each one.
3476 		 *
3477 		 * Things get a little tricky if the administrator has created
3478 		 * mountpoints beneath other ZFS filesystems.  In this case, we
3479 		 * have to unmount the deepest filesystems first.  To accomplish
3480 		 * this, we place all the mountpoints in an AVL tree sorted by
3481 		 * the special type (dataset name), and walk the result in
3482 		 * reverse to make sure to get any snapshots first.
3483 		 */
3484 		struct mnttab entry;
3485 		uu_avl_pool_t *pool;
3486 		uu_avl_t *tree;
3487 		unshare_unmount_node_t *node;
3488 		uu_avl_index_t idx;
3489 		uu_avl_walk_t *walk;
3490 
3491 		if (argc != 0) {
3492 			(void) fprintf(stderr, gettext("too many arguments\n"));
3493 			usage(B_FALSE);
3494 		}
3495 
3496 		if ((pool = uu_avl_pool_create("unmount_pool",
3497 		    sizeof (unshare_unmount_node_t),
3498 		    offsetof(unshare_unmount_node_t, un_avlnode),
3499 		    unshare_unmount_compare,
3500 		    UU_DEFAULT)) == NULL) {
3501 			(void) fprintf(stderr, gettext("internal error: "
3502 			    "out of memory\n"));
3503 			exit(1);
3504 		}
3505 
3506 		if ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL) {
3507 			(void) fprintf(stderr, gettext("internal error: "
3508 			    "out of memory\n"));
3509 			exit(1);
3510 		}
3511 
3512 		rewind(mnttab_file);
3513 		while (getmntent(mnttab_file, &entry) == 0) {
3514 
3515 			/* ignore non-ZFS entries */
3516 			if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3517 				continue;
3518 
3519 			/* ignore snapshots */
3520 			if (strchr(entry.mnt_special, '@') != NULL)
3521 				continue;
3522 
3523 			if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3524 			    ZFS_TYPE_FILESYSTEM)) == NULL) {
3525 				ret = 1;
3526 				continue;
3527 			}
3528 
3529 			switch (op) {
3530 			case OP_SHARE:
3531 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3532 				    nfsiscsi_mnt_prop,
3533 				    sizeof (nfsiscsi_mnt_prop),
3534 				    NULL, NULL, 0, B_FALSE) == 0);
3535 				if (strcmp(nfsiscsi_mnt_prop, "off") != 0)
3536 					break;
3537 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3538 				    nfsiscsi_mnt_prop,
3539 				    sizeof (nfsiscsi_mnt_prop),
3540 				    NULL, NULL, 0, B_FALSE) == 0);
3541 				if (strcmp(nfsiscsi_mnt_prop, "off") == 0)
3542 					continue;
3543 				break;
3544 			case OP_MOUNT:
3545 				/* Ignore legacy mounts */
3546 				verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3547 				    nfsiscsi_mnt_prop,
3548 				    sizeof (nfsiscsi_mnt_prop),
3549 				    NULL, NULL, 0, B_FALSE) == 0);
3550 				if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0)
3551 					continue;
3552 			default:
3553 				break;
3554 			}
3555 
3556 			node = safe_malloc(sizeof (unshare_unmount_node_t));
3557 			node->un_zhp = zhp;
3558 
3559 			if ((node->un_mountp = strdup(entry.mnt_mountp)) ==
3560 			    NULL) {
3561 				(void) fprintf(stderr, gettext("internal error:"
3562 				    " out of memory\n"));
3563 				exit(1);
3564 			}
3565 
3566 			uu_avl_node_init(node, &node->un_avlnode, pool);
3567 
3568 			if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3569 				uu_avl_insert(tree, node, idx);
3570 			} else {
3571 				zfs_close(node->un_zhp);
3572 				free(node->un_mountp);
3573 				free(node);
3574 			}
3575 		}
3576 
3577 		/*
3578 		 * Walk the AVL tree in reverse, unmounting each filesystem and
3579 		 * removing it from the AVL tree in the process.
3580 		 */
3581 		if ((walk = uu_avl_walk_start(tree,
3582 		    UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL) {
3583 			(void) fprintf(stderr,
3584 			    gettext("internal error: out of memory"));
3585 			exit(1);
3586 		}
3587 
3588 		while ((node = uu_avl_walk_next(walk)) != NULL) {
3589 			uu_avl_remove(tree, node);
3590 
3591 			switch (op) {
3592 			case OP_SHARE:
3593 				if (zfs_unshareall_bypath(node->un_zhp,
3594 				    node->un_mountp) != 0)
3595 					ret = 1;
3596 				break;
3597 
3598 			case OP_MOUNT:
3599 				if (zfs_unmount(node->un_zhp,
3600 				    node->un_mountp, flags) != 0)
3601 					ret = 1;
3602 				break;
3603 			}
3604 
3605 			zfs_close(node->un_zhp);
3606 			free(node->un_mountp);
3607 			free(node);
3608 		}
3609 
3610 		uu_avl_walk_end(walk);
3611 		uu_avl_destroy(tree);
3612 		uu_avl_pool_destroy(pool);
3613 
3614 		if (op == OP_SHARE) {
3615 			/*
3616 			 * Finally, unshare any volumes shared via iSCSI.
3617 			 */
3618 			zfs_handle_t **dslist = NULL;
3619 			size_t i, count = 0;
3620 
3621 			get_all_datasets(ZFS_TYPE_VOLUME, &dslist, &count,
3622 			    B_FALSE);
3623 
3624 			if (count != 0) {
3625 				qsort(dslist, count, sizeof (void *),
3626 				    dataset_cmp);
3627 
3628 				for (i = 0; i < count; i++) {
3629 					if (zfs_unshare_iscsi(dslist[i]) != 0)
3630 						ret = 1;
3631 					zfs_close(dslist[i]);
3632 				}
3633 
3634 				free(dslist);
3635 			}
3636 		}
3637 	} else {
3638 		if (argc != 1) {
3639 			if (argc == 0)
3640 				(void) fprintf(stderr,
3641 				    gettext("missing filesystem argument\n"));
3642 			else
3643 				(void) fprintf(stderr,
3644 				    gettext("too many arguments\n"));
3645 			usage(B_FALSE);
3646 		}
3647 
3648 		/*
3649 		 * We have an argument, but it may be a full path or a ZFS
3650 		 * filesystem.  Pass full paths off to unmount_path() (shared by
3651 		 * manual_unmount), otherwise open the filesystem and pass to
3652 		 * zfs_unmount().
3653 		 */
3654 		if (argv[0][0] == '/')
3655 			return (unshare_unmount_path(op, argv[0],
3656 			    flags, B_FALSE));
3657 
3658 		types = ZFS_TYPE_FILESYSTEM;
3659 		if (op == OP_SHARE)
3660 			types |= ZFS_TYPE_VOLUME;
3661 
3662 		if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3663 			return (1);
3664 
3665 		if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
3666 			verify(zfs_prop_get(zhp, op == OP_SHARE ?
3667 			    ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3668 			    nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop), NULL,
3669 			    NULL, 0, B_FALSE) == 0);
3670 
3671 			switch (op) {
3672 			case OP_SHARE:
3673 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3674 				    nfsiscsi_mnt_prop,
3675 				    sizeof (nfsiscsi_mnt_prop),
3676 				    NULL, NULL, 0, B_FALSE) == 0);
3677 				verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3678 				    sharesmb, sizeof (sharesmb), NULL, NULL,
3679 				    0, B_FALSE) == 0);
3680 
3681 				if (strcmp(nfsiscsi_mnt_prop, "off") == 0 &&
3682 				    strcmp(sharesmb, "off") == 0) {
3683 					(void) fprintf(stderr, gettext("cannot "
3684 					    "unshare '%s': legacy share\n"),
3685 					    zfs_get_name(zhp));
3686 					(void) fprintf(stderr, gettext("use "
3687 					    "unshare(1M) to unshare this "
3688 					    "filesystem\n"));
3689 					ret = 1;
3690 				} else if (!zfs_is_shared(zhp)) {
3691 					(void) fprintf(stderr, gettext("cannot "
3692 					    "unshare '%s': not currently "
3693 					    "shared\n"), zfs_get_name(zhp));
3694 					ret = 1;
3695 				} else if (zfs_unshareall(zhp) != 0) {
3696 					ret = 1;
3697 				}
3698 				break;
3699 
3700 			case OP_MOUNT:
3701 				if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0) {
3702 					(void) fprintf(stderr, gettext("cannot "
3703 					    "unmount '%s': legacy "
3704 					    "mountpoint\n"), zfs_get_name(zhp));
3705 					(void) fprintf(stderr, gettext("use "
3706 					    "umount(1M) to unmount this "
3707 					    "filesystem\n"));
3708 					ret = 1;
3709 				} else if (!zfs_is_mounted(zhp, NULL)) {
3710 					(void) fprintf(stderr, gettext("cannot "
3711 					    "unmount '%s': not currently "
3712 					    "mounted\n"),
3713 					    zfs_get_name(zhp));
3714 					ret = 1;
3715 				} else if (zfs_unmountall(zhp, flags) != 0) {
3716 					ret = 1;
3717 				}
3718 				break;
3719 			}
3720 		} else {
3721 			assert(op == OP_SHARE);
3722 
3723 			verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI,
3724 			    nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop),
3725 			    NULL, NULL, 0, B_FALSE) == 0);
3726 
3727 			if (strcmp(nfsiscsi_mnt_prop, "off") == 0) {
3728 				(void) fprintf(stderr, gettext("cannot unshare "
3729 				    "'%s': 'shareiscsi' property not set\n"),
3730 				    zfs_get_name(zhp));
3731 				(void) fprintf(stderr, gettext("set "
3732 				    "'shareiscsi' property or use "
3733 				    "iscsitadm(1M) to share this volume\n"));
3734 				ret = 1;
3735 			} else if (!zfs_is_shared_iscsi(zhp)) {
3736 				(void) fprintf(stderr, gettext("cannot "
3737 				    "unshare '%s': not currently shared\n"),
3738 				    zfs_get_name(zhp));
3739 				ret = 1;
3740 			} else if (zfs_unshare_iscsi(zhp) != 0) {
3741 				ret = 1;
3742 			}
3743 		}
3744 
3745 		zfs_close(zhp);
3746 	}
3747 
3748 	return (ret);
3749 }
3750 
3751 /*
3752  * zfs unmount -a
3753  * zfs unmount filesystem
3754  *
3755  * Unmount all filesystems, or a specific ZFS filesystem.
3756  */
3757 static int
3758 zfs_do_unmount(int argc, char **argv)
3759 {
3760 	return (unshare_unmount(OP_MOUNT, argc, argv));
3761 }
3762 
3763 /*
3764  * zfs unshare -a
3765  * zfs unshare filesystem
3766  *
3767  * Unshare all filesystems, or a specific ZFS filesystem.
3768  */
3769 static int
3770 zfs_do_unshare(int argc, char **argv)
3771 {
3772 	return (unshare_unmount(OP_SHARE, argc, argv));
3773 }
3774 
3775 /*
3776  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
3777  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
3778  */
3779 static int
3780 manual_mount(int argc, char **argv)
3781 {
3782 	zfs_handle_t *zhp;
3783 	char mountpoint[ZFS_MAXPROPLEN];
3784 	char mntopts[MNT_LINE_MAX] = { '\0' };
3785 	int ret;
3786 	int c;
3787 	int flags = 0;
3788 	char *dataset, *path;
3789 
3790 	/* check options */
3791 	while ((c = getopt(argc, argv, ":mo:O")) != -1) {
3792 		switch (c) {
3793 		case 'o':
3794 			(void) strlcpy(mntopts, optarg, sizeof (mntopts));
3795 			break;
3796 		case 'O':
3797 			flags |= MS_OVERLAY;
3798 			break;
3799 		case 'm':
3800 			flags |= MS_NOMNTTAB;
3801 			break;
3802 		case ':':
3803 			(void) fprintf(stderr, gettext("missing argument for "
3804 			    "'%c' option\n"), optopt);
3805 			usage(B_FALSE);
3806 			break;
3807 		case '?':
3808 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3809 			    optopt);
3810 			(void) fprintf(stderr, gettext("usage: mount [-o opts] "
3811 			    "<path>\n"));
3812 			return (2);
3813 		}
3814 	}
3815 
3816 	argc -= optind;
3817 	argv += optind;
3818 
3819 	/* check that we only have two arguments */
3820 	if (argc != 2) {
3821 		if (argc == 0)
3822 			(void) fprintf(stderr, gettext("missing dataset "
3823 			    "argument\n"));
3824 		else if (argc == 1)
3825 			(void) fprintf(stderr,
3826 			    gettext("missing mountpoint argument\n"));
3827 		else
3828 			(void) fprintf(stderr, gettext("too many arguments\n"));
3829 		(void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
3830 		return (2);
3831 	}
3832 
3833 	dataset = argv[0];
3834 	path = argv[1];
3835 
3836 	/* try to open the dataset */
3837 	if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
3838 		return (1);
3839 
3840 	(void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3841 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
3842 
3843 	/* check for legacy mountpoint and complain appropriately */
3844 	ret = 0;
3845 	if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
3846 		if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
3847 		    NULL, 0, mntopts, sizeof (mntopts)) != 0) {
3848 			(void) fprintf(stderr, gettext("mount failed: %s\n"),
3849 			    strerror(errno));
3850 			ret = 1;
3851 		}
3852 	} else {
3853 		(void) fprintf(stderr, gettext("filesystem '%s' cannot be "
3854 		    "mounted using 'mount -F zfs'\n"), dataset);
3855 		(void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
3856 		    "instead.\n"), path);
3857 		(void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
3858 		    "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
3859 		(void) fprintf(stderr, gettext("See zfs(1M) for more "
3860 		    "information.\n"));
3861 		ret = 1;
3862 	}
3863 
3864 	return (ret);
3865 }
3866 
3867 /*
3868  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
3869  * unmounts of non-legacy filesystems, as this is the dominant administrative
3870  * interface.
3871  */
3872 static int
3873 manual_unmount(int argc, char **argv)
3874 {
3875 	int flags = 0;
3876 	int c;
3877 
3878 	/* check options */
3879 	while ((c = getopt(argc, argv, "f")) != -1) {
3880 		switch (c) {
3881 		case 'f':
3882 			flags = MS_FORCE;
3883 			break;
3884 		case '?':
3885 			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
3886 			    optopt);
3887 			(void) fprintf(stderr, gettext("usage: unmount [-f] "
3888 			    "<path>\n"));
3889 			return (2);
3890 		}
3891 	}
3892 
3893 	argc -= optind;
3894 	argv += optind;
3895 
3896 	/* check arguments */
3897 	if (argc != 1) {
3898 		if (argc == 0)
3899 			(void) fprintf(stderr, gettext("missing path "
3900 			    "argument\n"));
3901 		else
3902 			(void) fprintf(stderr, gettext("too many arguments\n"));
3903 		(void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
3904 		return (2);
3905 	}
3906 
3907 	return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
3908 }
3909 
3910 static int
3911 volcheck(zpool_handle_t *zhp, void *data)
3912 {
3913 	boolean_t isinit = *((boolean_t *)data);
3914 
3915 	if (isinit)
3916 		return (zpool_create_zvol_links(zhp));
3917 	else
3918 		return (zpool_remove_zvol_links(zhp));
3919 }
3920 
3921 /*
3922  * Iterate over all pools in the system and either create or destroy /dev/zvol
3923  * links, depending on the value of 'isinit'.
3924  */
3925 static int
3926 do_volcheck(boolean_t isinit)
3927 {
3928 	return (zpool_iter(g_zfs, volcheck, &isinit) ? 1 : 0);
3929 }
3930 
3931 static int
3932 find_command_idx(char *command, int *idx)
3933 {
3934 	int i;
3935 
3936 	for (i = 0; i < NCOMMAND; i++) {
3937 		if (command_table[i].name == NULL)
3938 			continue;
3939 
3940 		if (strcmp(command, command_table[i].name) == 0) {
3941 			*idx = i;
3942 			return (0);
3943 		}
3944 	}
3945 	return (1);
3946 }
3947 
3948 int
3949 main(int argc, char **argv)
3950 {
3951 	int ret;
3952 	int i;
3953 	char *progname;
3954 	char *cmdname;
3955 
3956 	(void) setlocale(LC_ALL, "");
3957 	(void) textdomain(TEXT_DOMAIN);
3958 
3959 	opterr = 0;
3960 
3961 	if ((g_zfs = libzfs_init()) == NULL) {
3962 		(void) fprintf(stderr, gettext("internal error: failed to "
3963 		    "initialize ZFS library\n"));
3964 		return (1);
3965 	}
3966 
3967 	zpool_set_history_str("zfs", argc, argv, history_str);
3968 	verify(zpool_stage_history(g_zfs, history_str) == 0);
3969 
3970 	libzfs_print_on_error(g_zfs, B_TRUE);
3971 
3972 	if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
3973 		(void) fprintf(stderr, gettext("internal error: unable to "
3974 		    "open %s\n"), MNTTAB);
3975 		return (1);
3976 	}
3977 
3978 	/*
3979 	 * This command also doubles as the /etc/fs mount and unmount program.
3980 	 * Determine if we should take this behavior based on argv[0].
3981 	 */
3982 	progname = basename(argv[0]);
3983 	if (strcmp(progname, "mount") == 0) {
3984 		ret = manual_mount(argc, argv);
3985 	} else if (strcmp(progname, "umount") == 0) {
3986 		ret = manual_unmount(argc, argv);
3987 	} else {
3988 		/*
3989 		 * Make sure the user has specified some command.
3990 		 */
3991 		if (argc < 2) {
3992 			(void) fprintf(stderr, gettext("missing command\n"));
3993 			usage(B_FALSE);
3994 		}
3995 
3996 		cmdname = argv[1];
3997 
3998 		/*
3999 		 * The 'umount' command is an alias for 'unmount'
4000 		 */
4001 		if (strcmp(cmdname, "umount") == 0)
4002 			cmdname = "unmount";
4003 
4004 		/*
4005 		 * The 'recv' command is an alias for 'receive'
4006 		 */
4007 		if (strcmp(cmdname, "recv") == 0)
4008 			cmdname = "receive";
4009 
4010 		/*
4011 		 * Special case '-?'
4012 		 */
4013 		if (strcmp(cmdname, "-?") == 0)
4014 			usage(B_TRUE);
4015 
4016 		/*
4017 		 * 'volinit' and 'volfini' do not appear in the usage message,
4018 		 * so we have to special case them here.
4019 		 */
4020 		if (strcmp(cmdname, "volinit") == 0)
4021 			return (do_volcheck(B_TRUE));
4022 		else if (strcmp(cmdname, "volfini") == 0)
4023 			return (do_volcheck(B_FALSE));
4024 
4025 		/*
4026 		 * Run the appropriate command.
4027 		 */
4028 		if (find_command_idx(cmdname, &i) == 0) {
4029 			current_command = &command_table[i];
4030 			ret = command_table[i].func(argc - 1, argv + 1);
4031 		} else if (strchr(cmdname, '=') != NULL) {
4032 			verify(find_command_idx("set", &i) == 0);
4033 			current_command = &command_table[i];
4034 			ret = command_table[i].func(argc, argv);
4035 		} else {
4036 			(void) fprintf(stderr, gettext("unrecognized "
4037 			    "command '%s'\n"), cmdname);
4038 			usage(B_FALSE);
4039 		}
4040 	}
4041 
4042 	(void) fclose(mnttab_file);
4043 
4044 	libzfs_fini(g_zfs);
4045 
4046 	/*
4047 	 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4048 	 * for the purposes of running ::findleaks.
4049 	 */
4050 	if (getenv("ZFS_ABORT") != NULL) {
4051 		(void) printf("dumping core by request\n");
4052 		abort();
4053 	}
4054 
4055 	return (ret);
4056 }
4057