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