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