libzfs_dataset.c revision 239774
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2011 by Delphix. All rights reserved.
26 * Copyright (c) 2012 DEY Storage Systems, Inc.  All rights reserved.
27 * Copyright (c) 2011-2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
28 * All rights reserved.
29 * Copyright (c) 2012 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
30 */
31
32#include <ctype.h>
33#include <errno.h>
34#include <libintl.h>
35#include <math.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <strings.h>
39#include <unistd.h>
40#include <stddef.h>
41#include <zone.h>
42#include <fcntl.h>
43#include <sys/mntent.h>
44#include <sys/mount.h>
45#include <priv.h>
46#include <pwd.h>
47#include <grp.h>
48#include <stddef.h>
49#include <idmap.h>
50
51#include <sys/dnode.h>
52#include <sys/spa.h>
53#include <sys/zap.h>
54#include <sys/misc.h>
55#include <libzfs.h>
56
57#include "zfs_namecheck.h"
58#include "zfs_prop.h"
59#include "libzfs_impl.h"
60#include "zfs_deleg.h"
61
62static int userquota_propname_decode(const char *propname, boolean_t zoned,
63    zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp);
64
65/*
66 * Given a single type (not a mask of types), return the type in a human
67 * readable form.
68 */
69const char *
70zfs_type_to_name(zfs_type_t type)
71{
72	switch (type) {
73	case ZFS_TYPE_FILESYSTEM:
74		return (dgettext(TEXT_DOMAIN, "filesystem"));
75	case ZFS_TYPE_SNAPSHOT:
76		return (dgettext(TEXT_DOMAIN, "snapshot"));
77	case ZFS_TYPE_VOLUME:
78		return (dgettext(TEXT_DOMAIN, "volume"));
79	}
80
81	return (NULL);
82}
83
84/*
85 * Given a path and mask of ZFS types, return a string describing this dataset.
86 * This is used when we fail to open a dataset and we cannot get an exact type.
87 * We guess what the type would have been based on the path and the mask of
88 * acceptable types.
89 */
90static const char *
91path_to_str(const char *path, int types)
92{
93	/*
94	 * When given a single type, always report the exact type.
95	 */
96	if (types == ZFS_TYPE_SNAPSHOT)
97		return (dgettext(TEXT_DOMAIN, "snapshot"));
98	if (types == ZFS_TYPE_FILESYSTEM)
99		return (dgettext(TEXT_DOMAIN, "filesystem"));
100	if (types == ZFS_TYPE_VOLUME)
101		return (dgettext(TEXT_DOMAIN, "volume"));
102
103	/*
104	 * The user is requesting more than one type of dataset.  If this is the
105	 * case, consult the path itself.  If we're looking for a snapshot, and
106	 * a '@' is found, then report it as "snapshot".  Otherwise, remove the
107	 * snapshot attribute and try again.
108	 */
109	if (types & ZFS_TYPE_SNAPSHOT) {
110		if (strchr(path, '@') != NULL)
111			return (dgettext(TEXT_DOMAIN, "snapshot"));
112		return (path_to_str(path, types & ~ZFS_TYPE_SNAPSHOT));
113	}
114
115	/*
116	 * The user has requested either filesystems or volumes.
117	 * We have no way of knowing a priori what type this would be, so always
118	 * report it as "filesystem" or "volume", our two primitive types.
119	 */
120	if (types & ZFS_TYPE_FILESYSTEM)
121		return (dgettext(TEXT_DOMAIN, "filesystem"));
122
123	assert(types & ZFS_TYPE_VOLUME);
124	return (dgettext(TEXT_DOMAIN, "volume"));
125}
126
127/*
128 * Validate a ZFS path.  This is used even before trying to open the dataset, to
129 * provide a more meaningful error message.  We call zfs_error_aux() to
130 * explain exactly why the name was not valid.
131 */
132int
133zfs_validate_name(libzfs_handle_t *hdl, const char *path, int type,
134    boolean_t modifying)
135{
136	namecheck_err_t why;
137	char what;
138
139	(void) zfs_prop_get_table();
140	if (dataset_namecheck(path, &why, &what) != 0) {
141		if (hdl != NULL) {
142			switch (why) {
143			case NAME_ERR_TOOLONG:
144				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
145				    "name is too long"));
146				break;
147
148			case NAME_ERR_LEADING_SLASH:
149				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
150				    "leading slash in name"));
151				break;
152
153			case NAME_ERR_EMPTY_COMPONENT:
154				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
155				    "empty component in name"));
156				break;
157
158			case NAME_ERR_TRAILING_SLASH:
159				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
160				    "trailing slash in name"));
161				break;
162
163			case NAME_ERR_INVALCHAR:
164				zfs_error_aux(hdl,
165				    dgettext(TEXT_DOMAIN, "invalid character "
166				    "'%c' in name"), what);
167				break;
168
169			case NAME_ERR_MULTIPLE_AT:
170				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
171				    "multiple '@' delimiters in name"));
172				break;
173
174			case NAME_ERR_NOLETTER:
175				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
176				    "pool doesn't begin with a letter"));
177				break;
178
179			case NAME_ERR_RESERVED:
180				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
181				    "name is reserved"));
182				break;
183
184			case NAME_ERR_DISKLIKE:
185				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
186				    "reserved disk name"));
187				break;
188			}
189		}
190
191		return (0);
192	}
193
194	if (!(type & ZFS_TYPE_SNAPSHOT) && strchr(path, '@') != NULL) {
195		if (hdl != NULL)
196			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
197			    "snapshot delimiter '@' in filesystem name"));
198		return (0);
199	}
200
201	if (type == ZFS_TYPE_SNAPSHOT && strchr(path, '@') == NULL) {
202		if (hdl != NULL)
203			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
204			    "missing '@' delimiter in snapshot name"));
205		return (0);
206	}
207
208	if (modifying && strchr(path, '%') != NULL) {
209		if (hdl != NULL)
210			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
211			    "invalid character %c in name"), '%');
212		return (0);
213	}
214
215	return (-1);
216}
217
218int
219zfs_name_valid(const char *name, zfs_type_t type)
220{
221	if (type == ZFS_TYPE_POOL)
222		return (zpool_name_valid(NULL, B_FALSE, name));
223	return (zfs_validate_name(NULL, name, type, B_FALSE));
224}
225
226/*
227 * This function takes the raw DSL properties, and filters out the user-defined
228 * properties into a separate nvlist.
229 */
230static nvlist_t *
231process_user_props(zfs_handle_t *zhp, nvlist_t *props)
232{
233	libzfs_handle_t *hdl = zhp->zfs_hdl;
234	nvpair_t *elem;
235	nvlist_t *propval;
236	nvlist_t *nvl;
237
238	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
239		(void) no_memory(hdl);
240		return (NULL);
241	}
242
243	elem = NULL;
244	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
245		if (!zfs_prop_user(nvpair_name(elem)))
246			continue;
247
248		verify(nvpair_value_nvlist(elem, &propval) == 0);
249		if (nvlist_add_nvlist(nvl, nvpair_name(elem), propval) != 0) {
250			nvlist_free(nvl);
251			(void) no_memory(hdl);
252			return (NULL);
253		}
254	}
255
256	return (nvl);
257}
258
259static zpool_handle_t *
260zpool_add_handle(zfs_handle_t *zhp, const char *pool_name)
261{
262	libzfs_handle_t *hdl = zhp->zfs_hdl;
263	zpool_handle_t *zph;
264
265	if ((zph = zpool_open_canfail(hdl, pool_name)) != NULL) {
266		if (hdl->libzfs_pool_handles != NULL)
267			zph->zpool_next = hdl->libzfs_pool_handles;
268		hdl->libzfs_pool_handles = zph;
269	}
270	return (zph);
271}
272
273static zpool_handle_t *
274zpool_find_handle(zfs_handle_t *zhp, const char *pool_name, int len)
275{
276	libzfs_handle_t *hdl = zhp->zfs_hdl;
277	zpool_handle_t *zph = hdl->libzfs_pool_handles;
278
279	while ((zph != NULL) &&
280	    (strncmp(pool_name, zpool_get_name(zph), len) != 0))
281		zph = zph->zpool_next;
282	return (zph);
283}
284
285/*
286 * Returns a handle to the pool that contains the provided dataset.
287 * If a handle to that pool already exists then that handle is returned.
288 * Otherwise, a new handle is created and added to the list of handles.
289 */
290static zpool_handle_t *
291zpool_handle(zfs_handle_t *zhp)
292{
293	char *pool_name;
294	int len;
295	zpool_handle_t *zph;
296
297	len = strcspn(zhp->zfs_name, "/@") + 1;
298	pool_name = zfs_alloc(zhp->zfs_hdl, len);
299	(void) strlcpy(pool_name, zhp->zfs_name, len);
300
301	zph = zpool_find_handle(zhp, pool_name, len);
302	if (zph == NULL)
303		zph = zpool_add_handle(zhp, pool_name);
304
305	free(pool_name);
306	return (zph);
307}
308
309void
310zpool_free_handles(libzfs_handle_t *hdl)
311{
312	zpool_handle_t *next, *zph = hdl->libzfs_pool_handles;
313
314	while (zph != NULL) {
315		next = zph->zpool_next;
316		zpool_close(zph);
317		zph = next;
318	}
319	hdl->libzfs_pool_handles = NULL;
320}
321
322/*
323 * Utility function to gather stats (objset and zpl) for the given object.
324 */
325static int
326get_stats_ioctl(zfs_handle_t *zhp, zfs_cmd_t *zc)
327{
328	libzfs_handle_t *hdl = zhp->zfs_hdl;
329
330	(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
331
332	while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, zc) != 0) {
333		if (errno == ENOMEM) {
334			if (zcmd_expand_dst_nvlist(hdl, zc) != 0) {
335				return (-1);
336			}
337		} else {
338			return (-1);
339		}
340	}
341	return (0);
342}
343
344/*
345 * Utility function to get the received properties of the given object.
346 */
347static int
348get_recvd_props_ioctl(zfs_handle_t *zhp)
349{
350	libzfs_handle_t *hdl = zhp->zfs_hdl;
351	nvlist_t *recvdprops;
352	zfs_cmd_t zc = { 0 };
353	int err;
354
355	if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0)
356		return (-1);
357
358	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
359
360	while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_RECVD_PROPS, &zc) != 0) {
361		if (errno == ENOMEM) {
362			if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
363				return (-1);
364			}
365		} else {
366			zcmd_free_nvlists(&zc);
367			return (-1);
368		}
369	}
370
371	err = zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &recvdprops);
372	zcmd_free_nvlists(&zc);
373	if (err != 0)
374		return (-1);
375
376	nvlist_free(zhp->zfs_recvd_props);
377	zhp->zfs_recvd_props = recvdprops;
378
379	return (0);
380}
381
382static int
383put_stats_zhdl(zfs_handle_t *zhp, zfs_cmd_t *zc)
384{
385	nvlist_t *allprops, *userprops;
386
387	zhp->zfs_dmustats = zc->zc_objset_stats; /* structure assignment */
388
389	if (zcmd_read_dst_nvlist(zhp->zfs_hdl, zc, &allprops) != 0) {
390		return (-1);
391	}
392
393	/*
394	 * XXX Why do we store the user props separately, in addition to
395	 * storing them in zfs_props?
396	 */
397	if ((userprops = process_user_props(zhp, allprops)) == NULL) {
398		nvlist_free(allprops);
399		return (-1);
400	}
401
402	nvlist_free(zhp->zfs_props);
403	nvlist_free(zhp->zfs_user_props);
404
405	zhp->zfs_props = allprops;
406	zhp->zfs_user_props = userprops;
407
408	return (0);
409}
410
411static int
412get_stats(zfs_handle_t *zhp)
413{
414	int rc = 0;
415	zfs_cmd_t zc = { 0 };
416
417	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
418		return (-1);
419	if (get_stats_ioctl(zhp, &zc) != 0)
420		rc = -1;
421	else if (put_stats_zhdl(zhp, &zc) != 0)
422		rc = -1;
423	zcmd_free_nvlists(&zc);
424	return (rc);
425}
426
427/*
428 * Refresh the properties currently stored in the handle.
429 */
430void
431zfs_refresh_properties(zfs_handle_t *zhp)
432{
433	(void) get_stats(zhp);
434}
435
436/*
437 * Makes a handle from the given dataset name.  Used by zfs_open() and
438 * zfs_iter_* to create child handles on the fly.
439 */
440static int
441make_dataset_handle_common(zfs_handle_t *zhp, zfs_cmd_t *zc)
442{
443	if (put_stats_zhdl(zhp, zc) != 0)
444		return (-1);
445
446	/*
447	 * We've managed to open the dataset and gather statistics.  Determine
448	 * the high-level type.
449	 */
450	if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
451		zhp->zfs_head_type = ZFS_TYPE_VOLUME;
452	else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
453		zhp->zfs_head_type = ZFS_TYPE_FILESYSTEM;
454	else
455		abort();
456
457	if (zhp->zfs_dmustats.dds_is_snapshot)
458		zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
459	else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
460		zhp->zfs_type = ZFS_TYPE_VOLUME;
461	else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
462		zhp->zfs_type = ZFS_TYPE_FILESYSTEM;
463	else
464		abort();	/* we should never see any other types */
465
466	if ((zhp->zpool_hdl = zpool_handle(zhp)) == NULL)
467		return (-1);
468
469	return (0);
470}
471
472zfs_handle_t *
473make_dataset_handle(libzfs_handle_t *hdl, const char *path)
474{
475	zfs_cmd_t zc = { 0 };
476
477	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
478
479	if (zhp == NULL)
480		return (NULL);
481
482	zhp->zfs_hdl = hdl;
483	(void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
484	if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0) {
485		free(zhp);
486		return (NULL);
487	}
488	if (get_stats_ioctl(zhp, &zc) == -1) {
489		zcmd_free_nvlists(&zc);
490		free(zhp);
491		return (NULL);
492	}
493	if (make_dataset_handle_common(zhp, &zc) == -1) {
494		free(zhp);
495		zhp = NULL;
496	}
497	zcmd_free_nvlists(&zc);
498	return (zhp);
499}
500
501zfs_handle_t *
502make_dataset_handle_zc(libzfs_handle_t *hdl, zfs_cmd_t *zc)
503{
504	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
505
506	if (zhp == NULL)
507		return (NULL);
508
509	zhp->zfs_hdl = hdl;
510	(void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
511	if (make_dataset_handle_common(zhp, zc) == -1) {
512		free(zhp);
513		return (NULL);
514	}
515	return (zhp);
516}
517
518zfs_handle_t *
519make_dataset_simple_handle_zc(zfs_handle_t *pzhp, zfs_cmd_t *zc)
520{
521	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
522
523	if (zhp == NULL)
524		return (NULL);
525
526	zhp->zfs_hdl = pzhp->zfs_hdl;
527	(void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
528	zhp->zfs_head_type = pzhp->zfs_type;
529	zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
530	zhp->zpool_hdl = zpool_handle(zhp);
531	return (zhp);
532}
533
534zfs_handle_t *
535zfs_handle_dup(zfs_handle_t *zhp_orig)
536{
537	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
538
539	if (zhp == NULL)
540		return (NULL);
541
542	zhp->zfs_hdl = zhp_orig->zfs_hdl;
543	zhp->zpool_hdl = zhp_orig->zpool_hdl;
544	(void) strlcpy(zhp->zfs_name, zhp_orig->zfs_name,
545	    sizeof (zhp->zfs_name));
546	zhp->zfs_type = zhp_orig->zfs_type;
547	zhp->zfs_head_type = zhp_orig->zfs_head_type;
548	zhp->zfs_dmustats = zhp_orig->zfs_dmustats;
549	if (zhp_orig->zfs_props != NULL) {
550		if (nvlist_dup(zhp_orig->zfs_props, &zhp->zfs_props, 0) != 0) {
551			(void) no_memory(zhp->zfs_hdl);
552			zfs_close(zhp);
553			return (NULL);
554		}
555	}
556	if (zhp_orig->zfs_user_props != NULL) {
557		if (nvlist_dup(zhp_orig->zfs_user_props,
558		    &zhp->zfs_user_props, 0) != 0) {
559			(void) no_memory(zhp->zfs_hdl);
560			zfs_close(zhp);
561			return (NULL);
562		}
563	}
564	if (zhp_orig->zfs_recvd_props != NULL) {
565		if (nvlist_dup(zhp_orig->zfs_recvd_props,
566		    &zhp->zfs_recvd_props, 0)) {
567			(void) no_memory(zhp->zfs_hdl);
568			zfs_close(zhp);
569			return (NULL);
570		}
571	}
572	zhp->zfs_mntcheck = zhp_orig->zfs_mntcheck;
573	if (zhp_orig->zfs_mntopts != NULL) {
574		zhp->zfs_mntopts = zfs_strdup(zhp_orig->zfs_hdl,
575		    zhp_orig->zfs_mntopts);
576	}
577	zhp->zfs_props_table = zhp_orig->zfs_props_table;
578	return (zhp);
579}
580
581/*
582 * Opens the given snapshot, filesystem, or volume.   The 'types'
583 * argument is a mask of acceptable types.  The function will print an
584 * appropriate error message and return NULL if it can't be opened.
585 */
586zfs_handle_t *
587zfs_open(libzfs_handle_t *hdl, const char *path, int types)
588{
589	zfs_handle_t *zhp;
590	char errbuf[1024];
591
592	(void) snprintf(errbuf, sizeof (errbuf),
593	    dgettext(TEXT_DOMAIN, "cannot open '%s'"), path);
594
595	/*
596	 * Validate the name before we even try to open it.
597	 */
598	if (!zfs_validate_name(hdl, path, ZFS_TYPE_DATASET, B_FALSE)) {
599		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
600		    "invalid dataset name"));
601		(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
602		return (NULL);
603	}
604
605	/*
606	 * Try to get stats for the dataset, which will tell us if it exists.
607	 */
608	errno = 0;
609	if ((zhp = make_dataset_handle(hdl, path)) == NULL) {
610		(void) zfs_standard_error(hdl, errno, errbuf);
611		return (NULL);
612	}
613
614	if (!(types & zhp->zfs_type)) {
615		(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
616		zfs_close(zhp);
617		return (NULL);
618	}
619
620	return (zhp);
621}
622
623/*
624 * Release a ZFS handle.  Nothing to do but free the associated memory.
625 */
626void
627zfs_close(zfs_handle_t *zhp)
628{
629	if (zhp->zfs_mntopts)
630		free(zhp->zfs_mntopts);
631	nvlist_free(zhp->zfs_props);
632	nvlist_free(zhp->zfs_user_props);
633	nvlist_free(zhp->zfs_recvd_props);
634	free(zhp);
635}
636
637typedef struct mnttab_node {
638	struct mnttab mtn_mt;
639	avl_node_t mtn_node;
640} mnttab_node_t;
641
642static int
643libzfs_mnttab_cache_compare(const void *arg1, const void *arg2)
644{
645	const mnttab_node_t *mtn1 = arg1;
646	const mnttab_node_t *mtn2 = arg2;
647	int rv;
648
649	rv = strcmp(mtn1->mtn_mt.mnt_special, mtn2->mtn_mt.mnt_special);
650
651	if (rv == 0)
652		return (0);
653	return (rv > 0 ? 1 : -1);
654}
655
656void
657libzfs_mnttab_init(libzfs_handle_t *hdl)
658{
659	assert(avl_numnodes(&hdl->libzfs_mnttab_cache) == 0);
660	avl_create(&hdl->libzfs_mnttab_cache, libzfs_mnttab_cache_compare,
661	    sizeof (mnttab_node_t), offsetof(mnttab_node_t, mtn_node));
662}
663
664void
665libzfs_mnttab_update(libzfs_handle_t *hdl)
666{
667	struct mnttab entry;
668
669	rewind(hdl->libzfs_mnttab);
670	while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
671		mnttab_node_t *mtn;
672
673		if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
674			continue;
675		mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
676		mtn->mtn_mt.mnt_special = zfs_strdup(hdl, entry.mnt_special);
677		mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, entry.mnt_mountp);
678		mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, entry.mnt_fstype);
679		mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, entry.mnt_mntopts);
680		avl_add(&hdl->libzfs_mnttab_cache, mtn);
681	}
682}
683
684void
685libzfs_mnttab_fini(libzfs_handle_t *hdl)
686{
687	void *cookie = NULL;
688	mnttab_node_t *mtn;
689
690	while (mtn = avl_destroy_nodes(&hdl->libzfs_mnttab_cache, &cookie)) {
691		free(mtn->mtn_mt.mnt_special);
692		free(mtn->mtn_mt.mnt_mountp);
693		free(mtn->mtn_mt.mnt_fstype);
694		free(mtn->mtn_mt.mnt_mntopts);
695		free(mtn);
696	}
697	avl_destroy(&hdl->libzfs_mnttab_cache);
698}
699
700void
701libzfs_mnttab_cache(libzfs_handle_t *hdl, boolean_t enable)
702{
703	hdl->libzfs_mnttab_enable = enable;
704}
705
706int
707libzfs_mnttab_find(libzfs_handle_t *hdl, const char *fsname,
708    struct mnttab *entry)
709{
710	mnttab_node_t find;
711	mnttab_node_t *mtn;
712
713	if (!hdl->libzfs_mnttab_enable) {
714		struct mnttab srch = { 0 };
715
716		if (avl_numnodes(&hdl->libzfs_mnttab_cache))
717			libzfs_mnttab_fini(hdl);
718		rewind(hdl->libzfs_mnttab);
719		srch.mnt_special = (char *)fsname;
720		srch.mnt_fstype = MNTTYPE_ZFS;
721		if (getmntany(hdl->libzfs_mnttab, entry, &srch) == 0)
722			return (0);
723		else
724			return (ENOENT);
725	}
726
727	if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
728		libzfs_mnttab_update(hdl);
729
730	find.mtn_mt.mnt_special = (char *)fsname;
731	mtn = avl_find(&hdl->libzfs_mnttab_cache, &find, NULL);
732	if (mtn) {
733		*entry = mtn->mtn_mt;
734		return (0);
735	}
736	return (ENOENT);
737}
738
739void
740libzfs_mnttab_add(libzfs_handle_t *hdl, const char *special,
741    const char *mountp, const char *mntopts)
742{
743	mnttab_node_t *mtn;
744
745	if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
746		return;
747	mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
748	mtn->mtn_mt.mnt_special = zfs_strdup(hdl, special);
749	mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, mountp);
750	mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, MNTTYPE_ZFS);
751	mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, mntopts);
752	avl_add(&hdl->libzfs_mnttab_cache, mtn);
753}
754
755void
756libzfs_mnttab_remove(libzfs_handle_t *hdl, const char *fsname)
757{
758	mnttab_node_t find;
759	mnttab_node_t *ret;
760
761	find.mtn_mt.mnt_special = (char *)fsname;
762	if (ret = avl_find(&hdl->libzfs_mnttab_cache, (void *)&find, NULL)) {
763		avl_remove(&hdl->libzfs_mnttab_cache, ret);
764		free(ret->mtn_mt.mnt_special);
765		free(ret->mtn_mt.mnt_mountp);
766		free(ret->mtn_mt.mnt_fstype);
767		free(ret->mtn_mt.mnt_mntopts);
768		free(ret);
769	}
770}
771
772int
773zfs_spa_version(zfs_handle_t *zhp, int *spa_version)
774{
775	zpool_handle_t *zpool_handle = zhp->zpool_hdl;
776
777	if (zpool_handle == NULL)
778		return (-1);
779
780	*spa_version = zpool_get_prop_int(zpool_handle,
781	    ZPOOL_PROP_VERSION, NULL);
782	return (0);
783}
784
785/*
786 * The choice of reservation property depends on the SPA version.
787 */
788static int
789zfs_which_resv_prop(zfs_handle_t *zhp, zfs_prop_t *resv_prop)
790{
791	int spa_version;
792
793	if (zfs_spa_version(zhp, &spa_version) < 0)
794		return (-1);
795
796	if (spa_version >= SPA_VERSION_REFRESERVATION)
797		*resv_prop = ZFS_PROP_REFRESERVATION;
798	else
799		*resv_prop = ZFS_PROP_RESERVATION;
800
801	return (0);
802}
803
804/*
805 * Given an nvlist of properties to set, validates that they are correct, and
806 * parses any numeric properties (index, boolean, etc) if they are specified as
807 * strings.
808 */
809nvlist_t *
810zfs_valid_proplist(libzfs_handle_t *hdl, zfs_type_t type, nvlist_t *nvl,
811    uint64_t zoned, zfs_handle_t *zhp, const char *errbuf)
812{
813	nvpair_t *elem;
814	uint64_t intval;
815	char *strval;
816	zfs_prop_t prop;
817	nvlist_t *ret;
818	int chosen_normal = -1;
819	int chosen_utf = -1;
820
821	if (nvlist_alloc(&ret, NV_UNIQUE_NAME, 0) != 0) {
822		(void) no_memory(hdl);
823		return (NULL);
824	}
825
826	/*
827	 * Make sure this property is valid and applies to this type.
828	 */
829
830	elem = NULL;
831	while ((elem = nvlist_next_nvpair(nvl, elem)) != NULL) {
832		const char *propname = nvpair_name(elem);
833
834		prop = zfs_name_to_prop(propname);
835		if (prop == ZPROP_INVAL && zfs_prop_user(propname)) {
836			/*
837			 * This is a user property: make sure it's a
838			 * string, and that it's less than ZAP_MAXNAMELEN.
839			 */
840			if (nvpair_type(elem) != DATA_TYPE_STRING) {
841				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
842				    "'%s' must be a string"), propname);
843				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
844				goto error;
845			}
846
847			if (strlen(nvpair_name(elem)) >= ZAP_MAXNAMELEN) {
848				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
849				    "property name '%s' is too long"),
850				    propname);
851				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
852				goto error;
853			}
854
855			(void) nvpair_value_string(elem, &strval);
856			if (nvlist_add_string(ret, propname, strval) != 0) {
857				(void) no_memory(hdl);
858				goto error;
859			}
860			continue;
861		}
862
863		/*
864		 * Currently, only user properties can be modified on
865		 * snapshots.
866		 */
867		if (type == ZFS_TYPE_SNAPSHOT) {
868			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
869			    "this property can not be modified for snapshots"));
870			(void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
871			goto error;
872		}
873
874		if (prop == ZPROP_INVAL && zfs_prop_userquota(propname)) {
875			zfs_userquota_prop_t uqtype;
876			char newpropname[128];
877			char domain[128];
878			uint64_t rid;
879			uint64_t valary[3];
880
881			if (userquota_propname_decode(propname, zoned,
882			    &uqtype, domain, sizeof (domain), &rid) != 0) {
883				zfs_error_aux(hdl,
884				    dgettext(TEXT_DOMAIN,
885				    "'%s' has an invalid user/group name"),
886				    propname);
887				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
888				goto error;
889			}
890
891			if (uqtype != ZFS_PROP_USERQUOTA &&
892			    uqtype != ZFS_PROP_GROUPQUOTA) {
893				zfs_error_aux(hdl,
894				    dgettext(TEXT_DOMAIN, "'%s' is readonly"),
895				    propname);
896				(void) zfs_error(hdl, EZFS_PROPREADONLY,
897				    errbuf);
898				goto error;
899			}
900
901			if (nvpair_type(elem) == DATA_TYPE_STRING) {
902				(void) nvpair_value_string(elem, &strval);
903				if (strcmp(strval, "none") == 0) {
904					intval = 0;
905				} else if (zfs_nicestrtonum(hdl,
906				    strval, &intval) != 0) {
907					(void) zfs_error(hdl,
908					    EZFS_BADPROP, errbuf);
909					goto error;
910				}
911			} else if (nvpair_type(elem) ==
912			    DATA_TYPE_UINT64) {
913				(void) nvpair_value_uint64(elem, &intval);
914				if (intval == 0) {
915					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
916					    "use 'none' to disable "
917					    "userquota/groupquota"));
918					goto error;
919				}
920			} else {
921				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
922				    "'%s' must be a number"), propname);
923				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
924				goto error;
925			}
926
927			/*
928			 * Encode the prop name as
929			 * userquota@<hex-rid>-domain, to make it easy
930			 * for the kernel to decode.
931			 */
932			(void) snprintf(newpropname, sizeof (newpropname),
933			    "%s%llx-%s", zfs_userquota_prop_prefixes[uqtype],
934			    (longlong_t)rid, domain);
935			valary[0] = uqtype;
936			valary[1] = rid;
937			valary[2] = intval;
938			if (nvlist_add_uint64_array(ret, newpropname,
939			    valary, 3) != 0) {
940				(void) no_memory(hdl);
941				goto error;
942			}
943			continue;
944		} else if (prop == ZPROP_INVAL && zfs_prop_written(propname)) {
945			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
946			    "'%s' is readonly"),
947			    propname);
948			(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
949			goto error;
950		}
951
952		if (prop == ZPROP_INVAL) {
953			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
954			    "invalid property '%s'"), propname);
955			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
956			goto error;
957		}
958
959		if (!zfs_prop_valid_for_type(prop, type)) {
960			zfs_error_aux(hdl,
961			    dgettext(TEXT_DOMAIN, "'%s' does not "
962			    "apply to datasets of this type"), propname);
963			(void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
964			goto error;
965		}
966
967		if (zfs_prop_readonly(prop) &&
968		    (!zfs_prop_setonce(prop) || zhp != NULL)) {
969			zfs_error_aux(hdl,
970			    dgettext(TEXT_DOMAIN, "'%s' is readonly"),
971			    propname);
972			(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
973			goto error;
974		}
975
976		if (zprop_parse_value(hdl, elem, prop, type, ret,
977		    &strval, &intval, errbuf) != 0)
978			goto error;
979
980		/*
981		 * Perform some additional checks for specific properties.
982		 */
983		switch (prop) {
984		case ZFS_PROP_VERSION:
985		{
986			int version;
987
988			if (zhp == NULL)
989				break;
990			version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
991			if (intval < version) {
992				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
993				    "Can not downgrade; already at version %u"),
994				    version);
995				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
996				goto error;
997			}
998			break;
999		}
1000
1001		case ZFS_PROP_RECORDSIZE:
1002		case ZFS_PROP_VOLBLOCKSIZE:
1003			/* must be power of two within SPA_{MIN,MAX}BLOCKSIZE */
1004			if (intval < SPA_MINBLOCKSIZE ||
1005			    intval > SPA_MAXBLOCKSIZE || !ISP2(intval)) {
1006				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1007				    "'%s' must be power of 2 from %u "
1008				    "to %uk"), propname,
1009				    (uint_t)SPA_MINBLOCKSIZE,
1010				    (uint_t)SPA_MAXBLOCKSIZE >> 10);
1011				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1012				goto error;
1013			}
1014			break;
1015
1016		case ZFS_PROP_MLSLABEL:
1017		{
1018#ifdef sun
1019			/*
1020			 * Verify the mlslabel string and convert to
1021			 * internal hex label string.
1022			 */
1023
1024			m_label_t *new_sl;
1025			char *hex = NULL;	/* internal label string */
1026
1027			/* Default value is already OK. */
1028			if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
1029				break;
1030
1031			/* Verify the label can be converted to binary form */
1032			if (((new_sl = m_label_alloc(MAC_LABEL)) == NULL) ||
1033			    (str_to_label(strval, &new_sl, MAC_LABEL,
1034			    L_NO_CORRECTION, NULL) == -1)) {
1035				goto badlabel;
1036			}
1037
1038			/* Now translate to hex internal label string */
1039			if (label_to_str(new_sl, &hex, M_INTERNAL,
1040			    DEF_NAMES) != 0) {
1041				if (hex)
1042					free(hex);
1043				goto badlabel;
1044			}
1045			m_label_free(new_sl);
1046
1047			/* If string is already in internal form, we're done. */
1048			if (strcmp(strval, hex) == 0) {
1049				free(hex);
1050				break;
1051			}
1052
1053			/* Replace the label string with the internal form. */
1054			(void) nvlist_remove(ret, zfs_prop_to_name(prop),
1055			    DATA_TYPE_STRING);
1056			verify(nvlist_add_string(ret, zfs_prop_to_name(prop),
1057			    hex) == 0);
1058			free(hex);
1059
1060			break;
1061
1062badlabel:
1063			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1064			    "invalid mlslabel '%s'"), strval);
1065			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1066			m_label_free(new_sl);	/* OK if null */
1067#else	/* !sun */
1068			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1069			    "mlslabel is not supported on FreeBSD"));
1070			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1071#endif	/* !sun */
1072			goto error;
1073
1074		}
1075
1076		case ZFS_PROP_MOUNTPOINT:
1077		{
1078			namecheck_err_t why;
1079
1080			if (strcmp(strval, ZFS_MOUNTPOINT_NONE) == 0 ||
1081			    strcmp(strval, ZFS_MOUNTPOINT_LEGACY) == 0)
1082				break;
1083
1084			if (mountpoint_namecheck(strval, &why)) {
1085				switch (why) {
1086				case NAME_ERR_LEADING_SLASH:
1087					zfs_error_aux(hdl,
1088					    dgettext(TEXT_DOMAIN,
1089					    "'%s' must be an absolute path, "
1090					    "'none', or 'legacy'"), propname);
1091					break;
1092				case NAME_ERR_TOOLONG:
1093					zfs_error_aux(hdl,
1094					    dgettext(TEXT_DOMAIN,
1095					    "component of '%s' is too long"),
1096					    propname);
1097					break;
1098				}
1099				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1100				goto error;
1101			}
1102		}
1103
1104			/*FALLTHRU*/
1105
1106		case ZFS_PROP_SHARESMB:
1107		case ZFS_PROP_SHARENFS:
1108			/*
1109			 * For the mountpoint and sharenfs or sharesmb
1110			 * properties, check if it can be set in a
1111			 * global/non-global zone based on
1112			 * the zoned property value:
1113			 *
1114			 *		global zone	    non-global zone
1115			 * --------------------------------------------------
1116			 * zoned=on	mountpoint (no)	    mountpoint (yes)
1117			 *		sharenfs (no)	    sharenfs (no)
1118			 *		sharesmb (no)	    sharesmb (no)
1119			 *
1120			 * zoned=off	mountpoint (yes)	N/A
1121			 *		sharenfs (yes)
1122			 *		sharesmb (yes)
1123			 */
1124			if (zoned) {
1125				if (getzoneid() == GLOBAL_ZONEID) {
1126					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1127					    "'%s' cannot be set on "
1128					    "dataset in a non-global zone"),
1129					    propname);
1130					(void) zfs_error(hdl, EZFS_ZONED,
1131					    errbuf);
1132					goto error;
1133				} else if (prop == ZFS_PROP_SHARENFS ||
1134				    prop == ZFS_PROP_SHARESMB) {
1135					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1136					    "'%s' cannot be set in "
1137					    "a non-global zone"), propname);
1138					(void) zfs_error(hdl, EZFS_ZONED,
1139					    errbuf);
1140					goto error;
1141				}
1142			} else if (getzoneid() != GLOBAL_ZONEID) {
1143				/*
1144				 * If zoned property is 'off', this must be in
1145				 * a global zone. If not, something is wrong.
1146				 */
1147				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1148				    "'%s' cannot be set while dataset "
1149				    "'zoned' property is set"), propname);
1150				(void) zfs_error(hdl, EZFS_ZONED, errbuf);
1151				goto error;
1152			}
1153
1154			/*
1155			 * At this point, it is legitimate to set the
1156			 * property. Now we want to make sure that the
1157			 * property value is valid if it is sharenfs.
1158			 */
1159			if ((prop == ZFS_PROP_SHARENFS ||
1160			    prop == ZFS_PROP_SHARESMB) &&
1161			    strcmp(strval, "on") != 0 &&
1162			    strcmp(strval, "off") != 0) {
1163				zfs_share_proto_t proto;
1164
1165				if (prop == ZFS_PROP_SHARESMB)
1166					proto = PROTO_SMB;
1167				else
1168					proto = PROTO_NFS;
1169
1170				/*
1171				 * Must be an valid sharing protocol
1172				 * option string so init the libshare
1173				 * in order to enable the parser and
1174				 * then parse the options. We use the
1175				 * control API since we don't care about
1176				 * the current configuration and don't
1177				 * want the overhead of loading it
1178				 * until we actually do something.
1179				 */
1180
1181				if (zfs_init_libshare(hdl,
1182				    SA_INIT_CONTROL_API) != SA_OK) {
1183					/*
1184					 * An error occurred so we can't do
1185					 * anything
1186					 */
1187					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1188					    "'%s' cannot be set: problem "
1189					    "in share initialization"),
1190					    propname);
1191					(void) zfs_error(hdl, EZFS_BADPROP,
1192					    errbuf);
1193					goto error;
1194				}
1195
1196				if (zfs_parse_options(strval, proto) != SA_OK) {
1197					/*
1198					 * There was an error in parsing so
1199					 * deal with it by issuing an error
1200					 * message and leaving after
1201					 * uninitializing the the libshare
1202					 * interface.
1203					 */
1204					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1205					    "'%s' cannot be set to invalid "
1206					    "options"), propname);
1207					(void) zfs_error(hdl, EZFS_BADPROP,
1208					    errbuf);
1209					zfs_uninit_libshare(hdl);
1210					goto error;
1211				}
1212				zfs_uninit_libshare(hdl);
1213			}
1214
1215			break;
1216		case ZFS_PROP_UTF8ONLY:
1217			chosen_utf = (int)intval;
1218			break;
1219		case ZFS_PROP_NORMALIZE:
1220			chosen_normal = (int)intval;
1221			break;
1222		}
1223
1224		/*
1225		 * For changes to existing volumes, we have some additional
1226		 * checks to enforce.
1227		 */
1228		if (type == ZFS_TYPE_VOLUME && zhp != NULL) {
1229			uint64_t volsize = zfs_prop_get_int(zhp,
1230			    ZFS_PROP_VOLSIZE);
1231			uint64_t blocksize = zfs_prop_get_int(zhp,
1232			    ZFS_PROP_VOLBLOCKSIZE);
1233			char buf[64];
1234
1235			switch (prop) {
1236			case ZFS_PROP_RESERVATION:
1237			case ZFS_PROP_REFRESERVATION:
1238				if (intval > volsize) {
1239					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1240					    "'%s' is greater than current "
1241					    "volume size"), propname);
1242					(void) zfs_error(hdl, EZFS_BADPROP,
1243					    errbuf);
1244					goto error;
1245				}
1246				break;
1247
1248			case ZFS_PROP_VOLSIZE:
1249				if (intval % blocksize != 0) {
1250					zfs_nicenum(blocksize, buf,
1251					    sizeof (buf));
1252					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1253					    "'%s' must be a multiple of "
1254					    "volume block size (%s)"),
1255					    propname, buf);
1256					(void) zfs_error(hdl, EZFS_BADPROP,
1257					    errbuf);
1258					goto error;
1259				}
1260
1261				if (intval == 0) {
1262					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1263					    "'%s' cannot be zero"),
1264					    propname);
1265					(void) zfs_error(hdl, EZFS_BADPROP,
1266					    errbuf);
1267					goto error;
1268				}
1269				break;
1270			}
1271		}
1272	}
1273
1274	/*
1275	 * If normalization was chosen, but no UTF8 choice was made,
1276	 * enforce rejection of non-UTF8 names.
1277	 *
1278	 * If normalization was chosen, but rejecting non-UTF8 names
1279	 * was explicitly not chosen, it is an error.
1280	 */
1281	if (chosen_normal > 0 && chosen_utf < 0) {
1282		if (nvlist_add_uint64(ret,
1283		    zfs_prop_to_name(ZFS_PROP_UTF8ONLY), 1) != 0) {
1284			(void) no_memory(hdl);
1285			goto error;
1286		}
1287	} else if (chosen_normal > 0 && chosen_utf == 0) {
1288		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1289		    "'%s' must be set 'on' if normalization chosen"),
1290		    zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
1291		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1292		goto error;
1293	}
1294	return (ret);
1295
1296error:
1297	nvlist_free(ret);
1298	return (NULL);
1299}
1300
1301int
1302zfs_add_synthetic_resv(zfs_handle_t *zhp, nvlist_t *nvl)
1303{
1304	uint64_t old_volsize;
1305	uint64_t new_volsize;
1306	uint64_t old_reservation;
1307	uint64_t new_reservation;
1308	zfs_prop_t resv_prop;
1309
1310	/*
1311	 * If this is an existing volume, and someone is setting the volsize,
1312	 * make sure that it matches the reservation, or add it if necessary.
1313	 */
1314	old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
1315	if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
1316		return (-1);
1317	old_reservation = zfs_prop_get_int(zhp, resv_prop);
1318	if ((zvol_volsize_to_reservation(old_volsize, zhp->zfs_props) !=
1319	    old_reservation) || nvlist_lookup_uint64(nvl,
1320	    zfs_prop_to_name(resv_prop), &new_reservation) != ENOENT) {
1321		return (0);
1322	}
1323	if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1324	    &new_volsize) != 0)
1325		return (-1);
1326	new_reservation = zvol_volsize_to_reservation(new_volsize,
1327	    zhp->zfs_props);
1328	if (nvlist_add_uint64(nvl, zfs_prop_to_name(resv_prop),
1329	    new_reservation) != 0) {
1330		(void) no_memory(zhp->zfs_hdl);
1331		return (-1);
1332	}
1333	return (1);
1334}
1335
1336void
1337zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
1338    char *errbuf)
1339{
1340	switch (err) {
1341
1342	case ENOSPC:
1343		/*
1344		 * For quotas and reservations, ENOSPC indicates
1345		 * something different; setting a quota or reservation
1346		 * doesn't use any disk space.
1347		 */
1348		switch (prop) {
1349		case ZFS_PROP_QUOTA:
1350		case ZFS_PROP_REFQUOTA:
1351			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1352			    "size is less than current used or "
1353			    "reserved space"));
1354			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1355			break;
1356
1357		case ZFS_PROP_RESERVATION:
1358		case ZFS_PROP_REFRESERVATION:
1359			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1360			    "size is greater than available space"));
1361			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1362			break;
1363
1364		default:
1365			(void) zfs_standard_error(hdl, err, errbuf);
1366			break;
1367		}
1368		break;
1369
1370	case EBUSY:
1371		(void) zfs_standard_error(hdl, EBUSY, errbuf);
1372		break;
1373
1374	case EROFS:
1375		(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
1376		break;
1377
1378	case ENOTSUP:
1379		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1380		    "pool and or dataset must be upgraded to set this "
1381		    "property or value"));
1382		(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
1383		break;
1384
1385	case ERANGE:
1386		if (prop == ZFS_PROP_COMPRESSION) {
1387			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1388			    "property setting is not allowed on "
1389			    "bootable datasets"));
1390			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
1391		} else {
1392			(void) zfs_standard_error(hdl, err, errbuf);
1393		}
1394		break;
1395
1396	case EINVAL:
1397		if (prop == ZPROP_INVAL) {
1398			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1399		} else {
1400			(void) zfs_standard_error(hdl, err, errbuf);
1401		}
1402		break;
1403
1404	case EOVERFLOW:
1405		/*
1406		 * This platform can't address a volume this big.
1407		 */
1408#ifdef _ILP32
1409		if (prop == ZFS_PROP_VOLSIZE) {
1410			(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
1411			break;
1412		}
1413#endif
1414		/* FALLTHROUGH */
1415	default:
1416		(void) zfs_standard_error(hdl, err, errbuf);
1417	}
1418}
1419
1420/*
1421 * Given a property name and value, set the property for the given dataset.
1422 */
1423int
1424zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
1425{
1426	zfs_cmd_t zc = { 0 };
1427	int ret = -1;
1428	prop_changelist_t *cl = NULL;
1429	char errbuf[1024];
1430	libzfs_handle_t *hdl = zhp->zfs_hdl;
1431	nvlist_t *nvl = NULL, *realprops;
1432	zfs_prop_t prop;
1433	boolean_t do_prefix;
1434	uint64_t idx;
1435	int added_resv;
1436
1437	(void) snprintf(errbuf, sizeof (errbuf),
1438	    dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1439	    zhp->zfs_name);
1440
1441	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
1442	    nvlist_add_string(nvl, propname, propval) != 0) {
1443		(void) no_memory(hdl);
1444		goto error;
1445	}
1446
1447	if ((realprops = zfs_valid_proplist(hdl, zhp->zfs_type, nvl,
1448	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, errbuf)) == NULL)
1449		goto error;
1450
1451	nvlist_free(nvl);
1452	nvl = realprops;
1453
1454	prop = zfs_name_to_prop(propname);
1455
1456	/* We don't support those properties on FreeBSD. */
1457	switch (prop) {
1458	case ZFS_PROP_DEVICES:
1459	case ZFS_PROP_ISCSIOPTIONS:
1460	case ZFS_PROP_XATTR:
1461	case ZFS_PROP_VSCAN:
1462	case ZFS_PROP_NBMAND:
1463	case ZFS_PROP_MLSLABEL:
1464		(void) snprintf(errbuf, sizeof (errbuf),
1465		    "property '%s' not supported on FreeBSD", propname);
1466		ret = zfs_error(hdl, EZFS_PERM, errbuf);
1467		goto error;
1468	}
1469
1470	if (prop == ZFS_PROP_VOLSIZE) {
1471		if ((added_resv = zfs_add_synthetic_resv(zhp, nvl)) == -1)
1472			goto error;
1473	}
1474
1475	if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1476		goto error;
1477
1478	if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1479		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1480		    "child dataset with inherited mountpoint is used "
1481		    "in a non-global zone"));
1482		ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1483		goto error;
1484	}
1485
1486	/*
1487	 * We don't want to unmount & remount the dataset when changing
1488	 * its canmount property to 'on' or 'noauto'.  We only use
1489	 * the changelist logic to unmount when setting canmount=off.
1490	 */
1491	if (prop == ZFS_PROP_CANMOUNT) {
1492		uint64_t idx;
1493		int err = zprop_string_to_index(prop, propval, &idx,
1494		    ZFS_TYPE_DATASET);
1495		if (err == 0 && idx != ZFS_CANMOUNT_OFF)
1496			do_prefix = B_FALSE;
1497	}
1498
1499	if (do_prefix && (ret = changelist_prefix(cl)) != 0)
1500		goto error;
1501
1502	/*
1503	 * Execute the corresponding ioctl() to set this property.
1504	 */
1505	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1506
1507	if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1508		goto error;
1509
1510	ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1511
1512	if (ret != 0) {
1513		zfs_setprop_error(hdl, prop, errno, errbuf);
1514		if (added_resv && errno == ENOSPC) {
1515			/* clean up the volsize property we tried to set */
1516			uint64_t old_volsize = zfs_prop_get_int(zhp,
1517			    ZFS_PROP_VOLSIZE);
1518			nvlist_free(nvl);
1519			zcmd_free_nvlists(&zc);
1520			if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
1521				goto error;
1522			if (nvlist_add_uint64(nvl,
1523			    zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1524			    old_volsize) != 0)
1525				goto error;
1526			if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1527				goto error;
1528			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1529		}
1530	} else {
1531		if (do_prefix)
1532			ret = changelist_postfix(cl);
1533
1534		/*
1535		 * Refresh the statistics so the new property value
1536		 * is reflected.
1537		 */
1538		if (ret == 0)
1539			(void) get_stats(zhp);
1540	}
1541
1542error:
1543	nvlist_free(nvl);
1544	zcmd_free_nvlists(&zc);
1545	if (cl)
1546		changelist_free(cl);
1547	return (ret);
1548}
1549
1550/*
1551 * Given a property, inherit the value from the parent dataset, or if received
1552 * is TRUE, revert to the received value, if any.
1553 */
1554int
1555zfs_prop_inherit(zfs_handle_t *zhp, const char *propname, boolean_t received)
1556{
1557	zfs_cmd_t zc = { 0 };
1558	int ret;
1559	prop_changelist_t *cl;
1560	libzfs_handle_t *hdl = zhp->zfs_hdl;
1561	char errbuf[1024];
1562	zfs_prop_t prop;
1563
1564	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1565	    "cannot inherit %s for '%s'"), propname, zhp->zfs_name);
1566
1567	zc.zc_cookie = received;
1568	if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
1569		/*
1570		 * For user properties, the amount of work we have to do is very
1571		 * small, so just do it here.
1572		 */
1573		if (!zfs_prop_user(propname)) {
1574			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1575			    "invalid property"));
1576			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1577		}
1578
1579		(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1580		(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1581
1582		if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
1583			return (zfs_standard_error(hdl, errno, errbuf));
1584
1585		return (0);
1586	}
1587
1588	/*
1589	 * Verify that this property is inheritable.
1590	 */
1591	if (zfs_prop_readonly(prop))
1592		return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
1593
1594	if (!zfs_prop_inheritable(prop) && !received)
1595		return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
1596
1597	/*
1598	 * Check to see if the value applies to this type
1599	 */
1600	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1601		return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
1602
1603	/*
1604	 * Normalize the name, to get rid of shorthand abbreviations.
1605	 */
1606	propname = zfs_prop_to_name(prop);
1607	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1608	(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1609
1610	if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
1611	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
1612		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1613		    "dataset is used in a non-global zone"));
1614		return (zfs_error(hdl, EZFS_ZONED, errbuf));
1615	}
1616
1617	/*
1618	 * Determine datasets which will be affected by this change, if any.
1619	 */
1620	if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1621		return (-1);
1622
1623	if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1624		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1625		    "child dataset with inherited mountpoint is used "
1626		    "in a non-global zone"));
1627		ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1628		goto error;
1629	}
1630
1631	if ((ret = changelist_prefix(cl)) != 0)
1632		goto error;
1633
1634	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
1635		return (zfs_standard_error(hdl, errno, errbuf));
1636	} else {
1637
1638		if ((ret = changelist_postfix(cl)) != 0)
1639			goto error;
1640
1641		/*
1642		 * Refresh the statistics so the new property is reflected.
1643		 */
1644		(void) get_stats(zhp);
1645	}
1646
1647error:
1648	changelist_free(cl);
1649	return (ret);
1650}
1651
1652/*
1653 * True DSL properties are stored in an nvlist.  The following two functions
1654 * extract them appropriately.
1655 */
1656static uint64_t
1657getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1658{
1659	nvlist_t *nv;
1660	uint64_t value;
1661
1662	*source = NULL;
1663	if (nvlist_lookup_nvlist(zhp->zfs_props,
1664	    zfs_prop_to_name(prop), &nv) == 0) {
1665		verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
1666		(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1667	} else {
1668		verify(!zhp->zfs_props_table ||
1669		    zhp->zfs_props_table[prop] == B_TRUE);
1670		value = zfs_prop_default_numeric(prop);
1671		*source = "";
1672	}
1673
1674	return (value);
1675}
1676
1677static char *
1678getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1679{
1680	nvlist_t *nv;
1681	char *value;
1682
1683	*source = NULL;
1684	if (nvlist_lookup_nvlist(zhp->zfs_props,
1685	    zfs_prop_to_name(prop), &nv) == 0) {
1686		verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
1687		(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1688	} else {
1689		verify(!zhp->zfs_props_table ||
1690		    zhp->zfs_props_table[prop] == B_TRUE);
1691		if ((value = (char *)zfs_prop_default_string(prop)) == NULL)
1692			value = "";
1693		*source = "";
1694	}
1695
1696	return (value);
1697}
1698
1699static boolean_t
1700zfs_is_recvd_props_mode(zfs_handle_t *zhp)
1701{
1702	return (zhp->zfs_props == zhp->zfs_recvd_props);
1703}
1704
1705static void
1706zfs_set_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
1707{
1708	*cookie = (uint64_t)(uintptr_t)zhp->zfs_props;
1709	zhp->zfs_props = zhp->zfs_recvd_props;
1710}
1711
1712static void
1713zfs_unset_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
1714{
1715	zhp->zfs_props = (nvlist_t *)(uintptr_t)*cookie;
1716	*cookie = 0;
1717}
1718
1719/*
1720 * Internal function for getting a numeric property.  Both zfs_prop_get() and
1721 * zfs_prop_get_int() are built using this interface.
1722 *
1723 * Certain properties can be overridden using 'mount -o'.  In this case, scan
1724 * the contents of the /etc/mnttab entry, searching for the appropriate options.
1725 * If they differ from the on-disk values, report the current values and mark
1726 * the source "temporary".
1727 */
1728static int
1729get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
1730    char **source, uint64_t *val)
1731{
1732	zfs_cmd_t zc = { 0 };
1733	nvlist_t *zplprops = NULL;
1734	struct mnttab mnt;
1735	char *mntopt_on = NULL;
1736	char *mntopt_off = NULL;
1737	boolean_t received = zfs_is_recvd_props_mode(zhp);
1738
1739	*source = NULL;
1740
1741	switch (prop) {
1742	case ZFS_PROP_ATIME:
1743		mntopt_on = MNTOPT_ATIME;
1744		mntopt_off = MNTOPT_NOATIME;
1745		break;
1746
1747	case ZFS_PROP_DEVICES:
1748		mntopt_on = MNTOPT_DEVICES;
1749		mntopt_off = MNTOPT_NODEVICES;
1750		break;
1751
1752	case ZFS_PROP_EXEC:
1753		mntopt_on = MNTOPT_EXEC;
1754		mntopt_off = MNTOPT_NOEXEC;
1755		break;
1756
1757	case ZFS_PROP_READONLY:
1758		mntopt_on = MNTOPT_RO;
1759		mntopt_off = MNTOPT_RW;
1760		break;
1761
1762	case ZFS_PROP_SETUID:
1763		mntopt_on = MNTOPT_SETUID;
1764		mntopt_off = MNTOPT_NOSETUID;
1765		break;
1766
1767	case ZFS_PROP_XATTR:
1768		mntopt_on = MNTOPT_XATTR;
1769		mntopt_off = MNTOPT_NOXATTR;
1770		break;
1771
1772	case ZFS_PROP_NBMAND:
1773		mntopt_on = MNTOPT_NBMAND;
1774		mntopt_off = MNTOPT_NONBMAND;
1775		break;
1776	}
1777
1778	/*
1779	 * Because looking up the mount options is potentially expensive
1780	 * (iterating over all of /etc/mnttab), we defer its calculation until
1781	 * we're looking up a property which requires its presence.
1782	 */
1783	if (!zhp->zfs_mntcheck &&
1784	    (mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
1785		libzfs_handle_t *hdl = zhp->zfs_hdl;
1786		struct mnttab entry;
1787
1788		if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
1789			zhp->zfs_mntopts = zfs_strdup(hdl,
1790			    entry.mnt_mntopts);
1791			if (zhp->zfs_mntopts == NULL)
1792				return (-1);
1793		}
1794
1795		zhp->zfs_mntcheck = B_TRUE;
1796	}
1797
1798	if (zhp->zfs_mntopts == NULL)
1799		mnt.mnt_mntopts = "";
1800	else
1801		mnt.mnt_mntopts = zhp->zfs_mntopts;
1802
1803	switch (prop) {
1804	case ZFS_PROP_ATIME:
1805	case ZFS_PROP_DEVICES:
1806	case ZFS_PROP_EXEC:
1807	case ZFS_PROP_READONLY:
1808	case ZFS_PROP_SETUID:
1809	case ZFS_PROP_XATTR:
1810	case ZFS_PROP_NBMAND:
1811		*val = getprop_uint64(zhp, prop, source);
1812
1813		if (received)
1814			break;
1815
1816		if (hasmntopt(&mnt, mntopt_on) && !*val) {
1817			*val = B_TRUE;
1818			if (src)
1819				*src = ZPROP_SRC_TEMPORARY;
1820		} else if (hasmntopt(&mnt, mntopt_off) && *val) {
1821			*val = B_FALSE;
1822			if (src)
1823				*src = ZPROP_SRC_TEMPORARY;
1824		}
1825		break;
1826
1827	case ZFS_PROP_CANMOUNT:
1828	case ZFS_PROP_VOLSIZE:
1829	case ZFS_PROP_QUOTA:
1830	case ZFS_PROP_REFQUOTA:
1831	case ZFS_PROP_RESERVATION:
1832	case ZFS_PROP_REFRESERVATION:
1833		*val = getprop_uint64(zhp, prop, source);
1834
1835		if (*source == NULL) {
1836			/* not default, must be local */
1837			*source = zhp->zfs_name;
1838		}
1839		break;
1840
1841	case ZFS_PROP_MOUNTED:
1842		*val = (zhp->zfs_mntopts != NULL);
1843		break;
1844
1845	case ZFS_PROP_NUMCLONES:
1846		*val = zhp->zfs_dmustats.dds_num_clones;
1847		break;
1848
1849	case ZFS_PROP_VERSION:
1850	case ZFS_PROP_NORMALIZE:
1851	case ZFS_PROP_UTF8ONLY:
1852	case ZFS_PROP_CASE:
1853		if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
1854		    zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
1855			return (-1);
1856		(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1857		if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
1858			zcmd_free_nvlists(&zc);
1859			return (-1);
1860		}
1861		if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
1862		    nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
1863		    val) != 0) {
1864			zcmd_free_nvlists(&zc);
1865			return (-1);
1866		}
1867		if (zplprops)
1868			nvlist_free(zplprops);
1869		zcmd_free_nvlists(&zc);
1870		break;
1871
1872	default:
1873		switch (zfs_prop_get_type(prop)) {
1874		case PROP_TYPE_NUMBER:
1875		case PROP_TYPE_INDEX:
1876			*val = getprop_uint64(zhp, prop, source);
1877			/*
1878			 * If we tried to use a default value for a
1879			 * readonly property, it means that it was not
1880			 * present.
1881			 */
1882			if (zfs_prop_readonly(prop) &&
1883			    *source != NULL && (*source)[0] == '\0') {
1884				*source = NULL;
1885			}
1886			break;
1887
1888		case PROP_TYPE_STRING:
1889		default:
1890			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1891			    "cannot get non-numeric property"));
1892			return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
1893			    dgettext(TEXT_DOMAIN, "internal error")));
1894		}
1895	}
1896
1897	return (0);
1898}
1899
1900/*
1901 * Calculate the source type, given the raw source string.
1902 */
1903static void
1904get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
1905    char *statbuf, size_t statlen)
1906{
1907	if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
1908		return;
1909
1910	if (source == NULL) {
1911		*srctype = ZPROP_SRC_NONE;
1912	} else if (source[0] == '\0') {
1913		*srctype = ZPROP_SRC_DEFAULT;
1914	} else if (strstr(source, ZPROP_SOURCE_VAL_RECVD) != NULL) {
1915		*srctype = ZPROP_SRC_RECEIVED;
1916	} else {
1917		if (strcmp(source, zhp->zfs_name) == 0) {
1918			*srctype = ZPROP_SRC_LOCAL;
1919		} else {
1920			(void) strlcpy(statbuf, source, statlen);
1921			*srctype = ZPROP_SRC_INHERITED;
1922		}
1923	}
1924
1925}
1926
1927int
1928zfs_prop_get_recvd(zfs_handle_t *zhp, const char *propname, char *propbuf,
1929    size_t proplen, boolean_t literal)
1930{
1931	zfs_prop_t prop;
1932	int err = 0;
1933
1934	if (zhp->zfs_recvd_props == NULL)
1935		if (get_recvd_props_ioctl(zhp) != 0)
1936			return (-1);
1937
1938	prop = zfs_name_to_prop(propname);
1939
1940	if (prop != ZPROP_INVAL) {
1941		uint64_t cookie;
1942		if (!nvlist_exists(zhp->zfs_recvd_props, propname))
1943			return (-1);
1944		zfs_set_recvd_props_mode(zhp, &cookie);
1945		err = zfs_prop_get(zhp, prop, propbuf, proplen,
1946		    NULL, NULL, 0, literal);
1947		zfs_unset_recvd_props_mode(zhp, &cookie);
1948	} else {
1949		nvlist_t *propval;
1950		char *recvdval;
1951		if (nvlist_lookup_nvlist(zhp->zfs_recvd_props,
1952		    propname, &propval) != 0)
1953			return (-1);
1954		verify(nvlist_lookup_string(propval, ZPROP_VALUE,
1955		    &recvdval) == 0);
1956		(void) strlcpy(propbuf, recvdval, proplen);
1957	}
1958
1959	return (err == 0 ? 0 : -1);
1960}
1961
1962static int
1963get_clones_string(zfs_handle_t *zhp, char *propbuf, size_t proplen)
1964{
1965	nvlist_t *value;
1966	nvpair_t *pair;
1967
1968	value = zfs_get_clones_nvl(zhp);
1969	if (value == NULL)
1970		return (-1);
1971
1972	propbuf[0] = '\0';
1973	for (pair = nvlist_next_nvpair(value, NULL); pair != NULL;
1974	    pair = nvlist_next_nvpair(value, pair)) {
1975		if (propbuf[0] != '\0')
1976			(void) strlcat(propbuf, ",", proplen);
1977		(void) strlcat(propbuf, nvpair_name(pair), proplen);
1978	}
1979
1980	return (0);
1981}
1982
1983struct get_clones_arg {
1984	uint64_t numclones;
1985	nvlist_t *value;
1986	const char *origin;
1987	char buf[ZFS_MAXNAMELEN];
1988};
1989
1990int
1991get_clones_cb(zfs_handle_t *zhp, void *arg)
1992{
1993	struct get_clones_arg *gca = arg;
1994
1995	if (gca->numclones == 0) {
1996		zfs_close(zhp);
1997		return (0);
1998	}
1999
2000	if (zfs_prop_get(zhp, ZFS_PROP_ORIGIN, gca->buf, sizeof (gca->buf),
2001	    NULL, NULL, 0, B_TRUE) != 0)
2002		goto out;
2003	if (strcmp(gca->buf, gca->origin) == 0) {
2004		if (nvlist_add_boolean(gca->value, zfs_get_name(zhp)) != 0) {
2005			zfs_close(zhp);
2006			return (no_memory(zhp->zfs_hdl));
2007		}
2008		gca->numclones--;
2009	}
2010
2011out:
2012	(void) zfs_iter_children(zhp, get_clones_cb, gca);
2013	zfs_close(zhp);
2014	return (0);
2015}
2016
2017nvlist_t *
2018zfs_get_clones_nvl(zfs_handle_t *zhp)
2019{
2020	nvlist_t *nv, *value;
2021
2022	if (nvlist_lookup_nvlist(zhp->zfs_props,
2023	    zfs_prop_to_name(ZFS_PROP_CLONES), &nv) != 0) {
2024		struct get_clones_arg gca;
2025
2026		/*
2027		 * if this is a snapshot, then the kernel wasn't able
2028		 * to get the clones.  Do it by slowly iterating.
2029		 */
2030		if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT)
2031			return (NULL);
2032		if (nvlist_alloc(&nv, NV_UNIQUE_NAME, 0) != 0)
2033			return (NULL);
2034		if (nvlist_alloc(&value, NV_UNIQUE_NAME, 0) != 0) {
2035			nvlist_free(nv);
2036			return (NULL);
2037		}
2038
2039		gca.numclones = zfs_prop_get_int(zhp, ZFS_PROP_NUMCLONES);
2040		gca.value = value;
2041		gca.origin = zhp->zfs_name;
2042
2043		if (gca.numclones != 0) {
2044			zfs_handle_t *root;
2045			char pool[ZFS_MAXNAMELEN];
2046			char *cp = pool;
2047
2048			/* get the pool name */
2049			(void) strlcpy(pool, zhp->zfs_name, sizeof (pool));
2050			(void) strsep(&cp, "/@");
2051			root = zfs_open(zhp->zfs_hdl, pool,
2052			    ZFS_TYPE_FILESYSTEM);
2053
2054			(void) get_clones_cb(root, &gca);
2055		}
2056
2057		if (gca.numclones != 0 ||
2058		    nvlist_add_nvlist(nv, ZPROP_VALUE, value) != 0 ||
2059		    nvlist_add_nvlist(zhp->zfs_props,
2060		    zfs_prop_to_name(ZFS_PROP_CLONES), nv) != 0) {
2061			nvlist_free(nv);
2062			nvlist_free(value);
2063			return (NULL);
2064		}
2065		nvlist_free(nv);
2066		nvlist_free(value);
2067		verify(0 == nvlist_lookup_nvlist(zhp->zfs_props,
2068		    zfs_prop_to_name(ZFS_PROP_CLONES), &nv));
2069	}
2070
2071	verify(nvlist_lookup_nvlist(nv, ZPROP_VALUE, &value) == 0);
2072
2073	return (value);
2074}
2075
2076/*
2077 * Retrieve a property from the given object.  If 'literal' is specified, then
2078 * numbers are left as exact values.  Otherwise, numbers are converted to a
2079 * human-readable form.
2080 *
2081 * Returns 0 on success, or -1 on error.
2082 */
2083int
2084zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
2085    zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
2086{
2087	char *source = NULL;
2088	uint64_t val;
2089	char *str;
2090	const char *strval;
2091	boolean_t received = zfs_is_recvd_props_mode(zhp);
2092
2093	/*
2094	 * Check to see if this property applies to our object
2095	 */
2096	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
2097		return (-1);
2098
2099	if (received && zfs_prop_readonly(prop))
2100		return (-1);
2101
2102	if (src)
2103		*src = ZPROP_SRC_NONE;
2104
2105	switch (prop) {
2106	case ZFS_PROP_CREATION:
2107		/*
2108		 * 'creation' is a time_t stored in the statistics.  We convert
2109		 * this into a string unless 'literal' is specified.
2110		 */
2111		{
2112			val = getprop_uint64(zhp, prop, &source);
2113			time_t time = (time_t)val;
2114			struct tm t;
2115
2116			if (literal ||
2117			    localtime_r(&time, &t) == NULL ||
2118			    strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
2119			    &t) == 0)
2120				(void) snprintf(propbuf, proplen, "%llu", val);
2121		}
2122		break;
2123
2124	case ZFS_PROP_MOUNTPOINT:
2125		/*
2126		 * Getting the precise mountpoint can be tricky.
2127		 *
2128		 *  - for 'none' or 'legacy', return those values.
2129		 *  - for inherited mountpoints, we want to take everything
2130		 *    after our ancestor and append it to the inherited value.
2131		 *
2132		 * If the pool has an alternate root, we want to prepend that
2133		 * root to any values we return.
2134		 */
2135
2136		str = getprop_string(zhp, prop, &source);
2137
2138		if (str[0] == '/') {
2139			char buf[MAXPATHLEN];
2140			char *root = buf;
2141			const char *relpath;
2142
2143			/*
2144			 * If we inherit the mountpoint, even from a dataset
2145			 * with a received value, the source will be the path of
2146			 * the dataset we inherit from. If source is
2147			 * ZPROP_SOURCE_VAL_RECVD, the received value is not
2148			 * inherited.
2149			 */
2150			if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2151				relpath = "";
2152			} else {
2153				relpath = zhp->zfs_name + strlen(source);
2154				if (relpath[0] == '/')
2155					relpath++;
2156			}
2157
2158			if ((zpool_get_prop(zhp->zpool_hdl,
2159			    ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL)) ||
2160			    (strcmp(root, "-") == 0))
2161				root[0] = '\0';
2162			/*
2163			 * Special case an alternate root of '/'. This will
2164			 * avoid having multiple leading slashes in the
2165			 * mountpoint path.
2166			 */
2167			if (strcmp(root, "/") == 0)
2168				root++;
2169
2170			/*
2171			 * If the mountpoint is '/' then skip over this
2172			 * if we are obtaining either an alternate root or
2173			 * an inherited mountpoint.
2174			 */
2175			if (str[1] == '\0' && (root[0] != '\0' ||
2176			    relpath[0] != '\0'))
2177				str++;
2178
2179			if (relpath[0] == '\0')
2180				(void) snprintf(propbuf, proplen, "%s%s",
2181				    root, str);
2182			else
2183				(void) snprintf(propbuf, proplen, "%s%s%s%s",
2184				    root, str, relpath[0] == '@' ? "" : "/",
2185				    relpath);
2186		} else {
2187			/* 'legacy' or 'none' */
2188			(void) strlcpy(propbuf, str, proplen);
2189		}
2190
2191		break;
2192
2193	case ZFS_PROP_ORIGIN:
2194		(void) strlcpy(propbuf, getprop_string(zhp, prop, &source),
2195		    proplen);
2196		/*
2197		 * If there is no parent at all, return failure to indicate that
2198		 * it doesn't apply to this dataset.
2199		 */
2200		if (propbuf[0] == '\0')
2201			return (-1);
2202		break;
2203
2204	case ZFS_PROP_CLONES:
2205		if (get_clones_string(zhp, propbuf, proplen) != 0)
2206			return (-1);
2207		break;
2208
2209	case ZFS_PROP_QUOTA:
2210	case ZFS_PROP_REFQUOTA:
2211	case ZFS_PROP_RESERVATION:
2212	case ZFS_PROP_REFRESERVATION:
2213
2214		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2215			return (-1);
2216
2217		/*
2218		 * If quota or reservation is 0, we translate this into 'none'
2219		 * (unless literal is set), and indicate that it's the default
2220		 * value.  Otherwise, we print the number nicely and indicate
2221		 * that its set locally.
2222		 */
2223		if (val == 0) {
2224			if (literal)
2225				(void) strlcpy(propbuf, "0", proplen);
2226			else
2227				(void) strlcpy(propbuf, "none", proplen);
2228		} else {
2229			if (literal)
2230				(void) snprintf(propbuf, proplen, "%llu",
2231				    (u_longlong_t)val);
2232			else
2233				zfs_nicenum(val, propbuf, proplen);
2234		}
2235		break;
2236
2237	case ZFS_PROP_REFRATIO:
2238	case ZFS_PROP_COMPRESSRATIO:
2239		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2240			return (-1);
2241		(void) snprintf(propbuf, proplen, "%llu.%02llux",
2242		    (u_longlong_t)(val / 100),
2243		    (u_longlong_t)(val % 100));
2244		break;
2245
2246	case ZFS_PROP_TYPE:
2247		switch (zhp->zfs_type) {
2248		case ZFS_TYPE_FILESYSTEM:
2249			str = "filesystem";
2250			break;
2251		case ZFS_TYPE_VOLUME:
2252			str = "volume";
2253			break;
2254		case ZFS_TYPE_SNAPSHOT:
2255			str = "snapshot";
2256			break;
2257		default:
2258			abort();
2259		}
2260		(void) snprintf(propbuf, proplen, "%s", str);
2261		break;
2262
2263	case ZFS_PROP_MOUNTED:
2264		/*
2265		 * The 'mounted' property is a pseudo-property that described
2266		 * whether the filesystem is currently mounted.  Even though
2267		 * it's a boolean value, the typical values of "on" and "off"
2268		 * don't make sense, so we translate to "yes" and "no".
2269		 */
2270		if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
2271		    src, &source, &val) != 0)
2272			return (-1);
2273		if (val)
2274			(void) strlcpy(propbuf, "yes", proplen);
2275		else
2276			(void) strlcpy(propbuf, "no", proplen);
2277		break;
2278
2279	case ZFS_PROP_NAME:
2280		/*
2281		 * The 'name' property is a pseudo-property derived from the
2282		 * dataset name.  It is presented as a real property to simplify
2283		 * consumers.
2284		 */
2285		(void) strlcpy(propbuf, zhp->zfs_name, proplen);
2286		break;
2287
2288	case ZFS_PROP_MLSLABEL:
2289		{
2290#ifdef sun
2291			m_label_t *new_sl = NULL;
2292			char *ascii = NULL;	/* human readable label */
2293
2294			(void) strlcpy(propbuf,
2295			    getprop_string(zhp, prop, &source), proplen);
2296
2297			if (literal || (strcasecmp(propbuf,
2298			    ZFS_MLSLABEL_DEFAULT) == 0))
2299				break;
2300
2301			/*
2302			 * Try to translate the internal hex string to
2303			 * human-readable output.  If there are any
2304			 * problems just use the hex string.
2305			 */
2306
2307			if (str_to_label(propbuf, &new_sl, MAC_LABEL,
2308			    L_NO_CORRECTION, NULL) == -1) {
2309				m_label_free(new_sl);
2310				break;
2311			}
2312
2313			if (label_to_str(new_sl, &ascii, M_LABEL,
2314			    DEF_NAMES) != 0) {
2315				if (ascii)
2316					free(ascii);
2317				m_label_free(new_sl);
2318				break;
2319			}
2320			m_label_free(new_sl);
2321
2322			(void) strlcpy(propbuf, ascii, proplen);
2323			free(ascii);
2324#else	/* !sun */
2325			propbuf[0] = '\0';
2326#endif	/* !sun */
2327		}
2328		break;
2329
2330	case ZFS_PROP_GUID:
2331		/*
2332		 * GUIDs are stored as numbers, but they are identifiers.
2333		 * We don't want them to be pretty printed, because pretty
2334		 * printing mangles the ID into a truncated and useless value.
2335		 */
2336		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2337			return (-1);
2338		(void) snprintf(propbuf, proplen, "%llu", (u_longlong_t)val);
2339		break;
2340
2341	default:
2342		switch (zfs_prop_get_type(prop)) {
2343		case PROP_TYPE_NUMBER:
2344			if (get_numeric_property(zhp, prop, src,
2345			    &source, &val) != 0)
2346				return (-1);
2347			if (literal)
2348				(void) snprintf(propbuf, proplen, "%llu",
2349				    (u_longlong_t)val);
2350			else
2351				zfs_nicenum(val, propbuf, proplen);
2352			break;
2353
2354		case PROP_TYPE_STRING:
2355			(void) strlcpy(propbuf,
2356			    getprop_string(zhp, prop, &source), proplen);
2357			break;
2358
2359		case PROP_TYPE_INDEX:
2360			if (get_numeric_property(zhp, prop, src,
2361			    &source, &val) != 0)
2362				return (-1);
2363			if (zfs_prop_index_to_string(prop, val, &strval) != 0)
2364				return (-1);
2365			(void) strlcpy(propbuf, strval, proplen);
2366			break;
2367
2368		default:
2369			abort();
2370		}
2371	}
2372
2373	get_source(zhp, src, source, statbuf, statlen);
2374
2375	return (0);
2376}
2377
2378/*
2379 * Utility function to get the given numeric property.  Does no validation that
2380 * the given property is the appropriate type; should only be used with
2381 * hard-coded property types.
2382 */
2383uint64_t
2384zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
2385{
2386	char *source;
2387	uint64_t val;
2388
2389	(void) get_numeric_property(zhp, prop, NULL, &source, &val);
2390
2391	return (val);
2392}
2393
2394int
2395zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
2396{
2397	char buf[64];
2398
2399	(void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
2400	return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
2401}
2402
2403/*
2404 * Similar to zfs_prop_get(), but returns the value as an integer.
2405 */
2406int
2407zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
2408    zprop_source_t *src, char *statbuf, size_t statlen)
2409{
2410	char *source;
2411
2412	/*
2413	 * Check to see if this property applies to our object
2414	 */
2415	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
2416		return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
2417		    dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
2418		    zfs_prop_to_name(prop)));
2419	}
2420
2421	if (src)
2422		*src = ZPROP_SRC_NONE;
2423
2424	if (get_numeric_property(zhp, prop, src, &source, value) != 0)
2425		return (-1);
2426
2427	get_source(zhp, src, source, statbuf, statlen);
2428
2429	return (0);
2430}
2431
2432static int
2433idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
2434    char **domainp, idmap_rid_t *ridp)
2435{
2436#ifdef sun
2437	idmap_get_handle_t *get_hdl = NULL;
2438	idmap_stat status;
2439	int err = EINVAL;
2440
2441	if (idmap_get_create(&get_hdl) != IDMAP_SUCCESS)
2442		goto out;
2443
2444	if (isuser) {
2445		err = idmap_get_sidbyuid(get_hdl, id,
2446		    IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2447	} else {
2448		err = idmap_get_sidbygid(get_hdl, id,
2449		    IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2450	}
2451	if (err == IDMAP_SUCCESS &&
2452	    idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
2453	    status == IDMAP_SUCCESS)
2454		err = 0;
2455	else
2456		err = EINVAL;
2457out:
2458	if (get_hdl)
2459		idmap_get_destroy(get_hdl);
2460	return (err);
2461#else	/* !sun */
2462	assert(!"invalid code path");
2463#endif	/* !sun */
2464}
2465
2466/*
2467 * convert the propname into parameters needed by kernel
2468 * Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
2469 * Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
2470 */
2471static int
2472userquota_propname_decode(const char *propname, boolean_t zoned,
2473    zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
2474{
2475	zfs_userquota_prop_t type;
2476	char *cp, *end;
2477	char *numericsid = NULL;
2478	boolean_t isuser;
2479
2480	domain[0] = '\0';
2481
2482	/* Figure out the property type ({user|group}{quota|space}) */
2483	for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
2484		if (strncmp(propname, zfs_userquota_prop_prefixes[type],
2485		    strlen(zfs_userquota_prop_prefixes[type])) == 0)
2486			break;
2487	}
2488	if (type == ZFS_NUM_USERQUOTA_PROPS)
2489		return (EINVAL);
2490	*typep = type;
2491
2492	isuser = (type == ZFS_PROP_USERQUOTA ||
2493	    type == ZFS_PROP_USERUSED);
2494
2495	cp = strchr(propname, '@') + 1;
2496
2497	if (strchr(cp, '@')) {
2498#ifdef sun
2499		/*
2500		 * It's a SID name (eg "user@domain") that needs to be
2501		 * turned into S-1-domainID-RID.
2502		 */
2503		directory_error_t e;
2504		if (zoned && getzoneid() == GLOBAL_ZONEID)
2505			return (ENOENT);
2506		if (isuser) {
2507			e = directory_sid_from_user_name(NULL,
2508			    cp, &numericsid);
2509		} else {
2510			e = directory_sid_from_group_name(NULL,
2511			    cp, &numericsid);
2512		}
2513		if (e != NULL) {
2514			directory_error_free(e);
2515			return (ENOENT);
2516		}
2517		if (numericsid == NULL)
2518			return (ENOENT);
2519		cp = numericsid;
2520		/* will be further decoded below */
2521#else	/* !sun */
2522		return (ENOENT);
2523#endif	/* !sun */
2524	}
2525
2526	if (strncmp(cp, "S-1-", 4) == 0) {
2527		/* It's a numeric SID (eg "S-1-234-567-89") */
2528		(void) strlcpy(domain, cp, domainlen);
2529		cp = strrchr(domain, '-');
2530		*cp = '\0';
2531		cp++;
2532
2533		errno = 0;
2534		*ridp = strtoull(cp, &end, 10);
2535		if (numericsid) {
2536			free(numericsid);
2537			numericsid = NULL;
2538		}
2539		if (errno != 0 || *end != '\0')
2540			return (EINVAL);
2541	} else if (!isdigit(*cp)) {
2542		/*
2543		 * It's a user/group name (eg "user") that needs to be
2544		 * turned into a uid/gid
2545		 */
2546		if (zoned && getzoneid() == GLOBAL_ZONEID)
2547			return (ENOENT);
2548		if (isuser) {
2549			struct passwd *pw;
2550			pw = getpwnam(cp);
2551			if (pw == NULL)
2552				return (ENOENT);
2553			*ridp = pw->pw_uid;
2554		} else {
2555			struct group *gr;
2556			gr = getgrnam(cp);
2557			if (gr == NULL)
2558				return (ENOENT);
2559			*ridp = gr->gr_gid;
2560		}
2561	} else {
2562		/* It's a user/group ID (eg "12345"). */
2563		uid_t id = strtoul(cp, &end, 10);
2564		idmap_rid_t rid;
2565		char *mapdomain;
2566
2567		if (*end != '\0')
2568			return (EINVAL);
2569		if (id > MAXUID) {
2570			/* It's an ephemeral ID. */
2571			if (idmap_id_to_numeric_domain_rid(id, isuser,
2572			    &mapdomain, &rid) != 0)
2573				return (ENOENT);
2574			(void) strlcpy(domain, mapdomain, domainlen);
2575			*ridp = rid;
2576		} else {
2577			*ridp = id;
2578		}
2579	}
2580
2581	ASSERT3P(numericsid, ==, NULL);
2582	return (0);
2583}
2584
2585static int
2586zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
2587    uint64_t *propvalue, zfs_userquota_prop_t *typep)
2588{
2589	int err;
2590	zfs_cmd_t zc = { 0 };
2591
2592	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2593
2594	err = userquota_propname_decode(propname,
2595	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
2596	    typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
2597	zc.zc_objset_type = *typep;
2598	if (err)
2599		return (err);
2600
2601	err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
2602	if (err)
2603		return (err);
2604
2605	*propvalue = zc.zc_cookie;
2606	return (0);
2607}
2608
2609int
2610zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
2611    uint64_t *propvalue)
2612{
2613	zfs_userquota_prop_t type;
2614
2615	return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
2616	    &type));
2617}
2618
2619int
2620zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
2621    char *propbuf, int proplen, boolean_t literal)
2622{
2623	int err;
2624	uint64_t propvalue;
2625	zfs_userquota_prop_t type;
2626
2627	err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
2628	    &type);
2629
2630	if (err)
2631		return (err);
2632
2633	if (literal) {
2634		(void) snprintf(propbuf, proplen, "%llu", propvalue);
2635	} else if (propvalue == 0 &&
2636	    (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA)) {
2637		(void) strlcpy(propbuf, "none", proplen);
2638	} else {
2639		zfs_nicenum(propvalue, propbuf, proplen);
2640	}
2641	return (0);
2642}
2643
2644int
2645zfs_prop_get_written_int(zfs_handle_t *zhp, const char *propname,
2646    uint64_t *propvalue)
2647{
2648	int err;
2649	zfs_cmd_t zc = { 0 };
2650	const char *snapname;
2651
2652	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2653
2654	snapname = strchr(propname, '@') + 1;
2655	if (strchr(snapname, '@')) {
2656		(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
2657	} else {
2658		/* snapname is the short name, append it to zhp's fsname */
2659		char *cp;
2660
2661		(void) strlcpy(zc.zc_value, zhp->zfs_name,
2662		    sizeof (zc.zc_value));
2663		cp = strchr(zc.zc_value, '@');
2664		if (cp != NULL)
2665			*cp = '\0';
2666		(void) strlcat(zc.zc_value, "@", sizeof (zc.zc_value));
2667		(void) strlcat(zc.zc_value, snapname, sizeof (zc.zc_value));
2668	}
2669
2670	err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_WRITTEN, &zc);
2671	if (err)
2672		return (err);
2673
2674	*propvalue = zc.zc_cookie;
2675	return (0);
2676}
2677
2678int
2679zfs_prop_get_written(zfs_handle_t *zhp, const char *propname,
2680    char *propbuf, int proplen, boolean_t literal)
2681{
2682	int err;
2683	uint64_t propvalue;
2684
2685	err = zfs_prop_get_written_int(zhp, propname, &propvalue);
2686
2687	if (err)
2688		return (err);
2689
2690	if (literal) {
2691		(void) snprintf(propbuf, proplen, "%llu", propvalue);
2692	} else {
2693		zfs_nicenum(propvalue, propbuf, proplen);
2694	}
2695	return (0);
2696}
2697
2698int
2699zfs_get_snapused_int(zfs_handle_t *firstsnap, zfs_handle_t *lastsnap,
2700    uint64_t *usedp)
2701{
2702	int err;
2703	zfs_cmd_t zc = { 0 };
2704
2705	(void) strlcpy(zc.zc_name, lastsnap->zfs_name, sizeof (zc.zc_name));
2706	(void) strlcpy(zc.zc_value, firstsnap->zfs_name, sizeof (zc.zc_value));
2707
2708	err = ioctl(lastsnap->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_SNAPS, &zc);
2709	if (err)
2710		return (err);
2711
2712	*usedp = zc.zc_cookie;
2713
2714	return (0);
2715}
2716
2717/*
2718 * Returns the name of the given zfs handle.
2719 */
2720const char *
2721zfs_get_name(const zfs_handle_t *zhp)
2722{
2723	return (zhp->zfs_name);
2724}
2725
2726/*
2727 * Returns the type of the given zfs handle.
2728 */
2729zfs_type_t
2730zfs_get_type(const zfs_handle_t *zhp)
2731{
2732	return (zhp->zfs_type);
2733}
2734
2735/*
2736 * Is one dataset name a child dataset of another?
2737 *
2738 * Needs to handle these cases:
2739 * Dataset 1	"a/foo"		"a/foo"		"a/foo"		"a/foo"
2740 * Dataset 2	"a/fo"		"a/foobar"	"a/bar/baz"	"a/foo/bar"
2741 * Descendant?	No.		No.		No.		Yes.
2742 */
2743static boolean_t
2744is_descendant(const char *ds1, const char *ds2)
2745{
2746	size_t d1len = strlen(ds1);
2747
2748	/* ds2 can't be a descendant if it's smaller */
2749	if (strlen(ds2) < d1len)
2750		return (B_FALSE);
2751
2752	/* otherwise, compare strings and verify that there's a '/' char */
2753	return (ds2[d1len] == '/' && (strncmp(ds1, ds2, d1len) == 0));
2754}
2755
2756/*
2757 * Given a complete name, return just the portion that refers to the parent.
2758 * Will return -1 if there is no parent (path is just the name of the
2759 * pool).
2760 */
2761static int
2762parent_name(const char *path, char *buf, size_t buflen)
2763{
2764	char *slashp;
2765
2766	(void) strlcpy(buf, path, buflen);
2767
2768	if ((slashp = strrchr(buf, '/')) == NULL)
2769		return (-1);
2770	*slashp = '\0';
2771
2772	return (0);
2773}
2774
2775/*
2776 * If accept_ancestor is false, then check to make sure that the given path has
2777 * a parent, and that it exists.  If accept_ancestor is true, then find the
2778 * closest existing ancestor for the given path.  In prefixlen return the
2779 * length of already existing prefix of the given path.  We also fetch the
2780 * 'zoned' property, which is used to validate property settings when creating
2781 * new datasets.
2782 */
2783static int
2784check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
2785    boolean_t accept_ancestor, int *prefixlen)
2786{
2787	zfs_cmd_t zc = { 0 };
2788	char parent[ZFS_MAXNAMELEN];
2789	char *slash;
2790	zfs_handle_t *zhp;
2791	char errbuf[1024];
2792	uint64_t is_zoned;
2793
2794	(void) snprintf(errbuf, sizeof (errbuf),
2795	    dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
2796
2797	/* get parent, and check to see if this is just a pool */
2798	if (parent_name(path, parent, sizeof (parent)) != 0) {
2799		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2800		    "missing dataset name"));
2801		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2802	}
2803
2804	/* check to see if the pool exists */
2805	if ((slash = strchr(parent, '/')) == NULL)
2806		slash = parent + strlen(parent);
2807	(void) strncpy(zc.zc_name, parent, slash - parent);
2808	zc.zc_name[slash - parent] = '\0';
2809	if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
2810	    errno == ENOENT) {
2811		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2812		    "no such pool '%s'"), zc.zc_name);
2813		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2814	}
2815
2816	/* check to see if the parent dataset exists */
2817	while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
2818		if (errno == ENOENT && accept_ancestor) {
2819			/*
2820			 * Go deeper to find an ancestor, give up on top level.
2821			 */
2822			if (parent_name(parent, parent, sizeof (parent)) != 0) {
2823				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2824				    "no such pool '%s'"), zc.zc_name);
2825				return (zfs_error(hdl, EZFS_NOENT, errbuf));
2826			}
2827		} else if (errno == ENOENT) {
2828			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2829			    "parent does not exist"));
2830			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2831		} else
2832			return (zfs_standard_error(hdl, errno, errbuf));
2833	}
2834
2835	is_zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2836	if (zoned != NULL)
2837		*zoned = is_zoned;
2838
2839	/* we are in a non-global zone, but parent is in the global zone */
2840	if (getzoneid() != GLOBAL_ZONEID && !is_zoned) {
2841		(void) zfs_standard_error(hdl, EPERM, errbuf);
2842		zfs_close(zhp);
2843		return (-1);
2844	}
2845
2846	/* make sure parent is a filesystem */
2847	if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
2848		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2849		    "parent is not a filesystem"));
2850		(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
2851		zfs_close(zhp);
2852		return (-1);
2853	}
2854
2855	zfs_close(zhp);
2856	if (prefixlen != NULL)
2857		*prefixlen = strlen(parent);
2858	return (0);
2859}
2860
2861/*
2862 * Finds whether the dataset of the given type(s) exists.
2863 */
2864boolean_t
2865zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
2866{
2867	zfs_handle_t *zhp;
2868
2869	if (!zfs_validate_name(hdl, path, types, B_FALSE))
2870		return (B_FALSE);
2871
2872	/*
2873	 * Try to get stats for the dataset, which will tell us if it exists.
2874	 */
2875	if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
2876		int ds_type = zhp->zfs_type;
2877
2878		zfs_close(zhp);
2879		if (types & ds_type)
2880			return (B_TRUE);
2881	}
2882	return (B_FALSE);
2883}
2884
2885/*
2886 * Given a path to 'target', create all the ancestors between
2887 * the prefixlen portion of the path, and the target itself.
2888 * Fail if the initial prefixlen-ancestor does not already exist.
2889 */
2890int
2891create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
2892{
2893	zfs_handle_t *h;
2894	char *cp;
2895	const char *opname;
2896
2897	/* make sure prefix exists */
2898	cp = target + prefixlen;
2899	if (*cp != '/') {
2900		assert(strchr(cp, '/') == NULL);
2901		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2902	} else {
2903		*cp = '\0';
2904		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2905		*cp = '/';
2906	}
2907	if (h == NULL)
2908		return (-1);
2909	zfs_close(h);
2910
2911	/*
2912	 * Attempt to create, mount, and share any ancestor filesystems,
2913	 * up to the prefixlen-long one.
2914	 */
2915	for (cp = target + prefixlen + 1;
2916	    cp = strchr(cp, '/'); *cp = '/', cp++) {
2917		char *logstr;
2918
2919		*cp = '\0';
2920
2921		h = make_dataset_handle(hdl, target);
2922		if (h) {
2923			/* it already exists, nothing to do here */
2924			zfs_close(h);
2925			continue;
2926		}
2927
2928		logstr = hdl->libzfs_log_str;
2929		hdl->libzfs_log_str = NULL;
2930		if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
2931		    NULL) != 0) {
2932			hdl->libzfs_log_str = logstr;
2933			opname = dgettext(TEXT_DOMAIN, "create");
2934			goto ancestorerr;
2935		}
2936
2937		hdl->libzfs_log_str = logstr;
2938		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2939		if (h == NULL) {
2940			opname = dgettext(TEXT_DOMAIN, "open");
2941			goto ancestorerr;
2942		}
2943
2944		if (zfs_mount(h, NULL, 0) != 0) {
2945			opname = dgettext(TEXT_DOMAIN, "mount");
2946			goto ancestorerr;
2947		}
2948
2949		if (zfs_share(h) != 0) {
2950			opname = dgettext(TEXT_DOMAIN, "share");
2951			goto ancestorerr;
2952		}
2953
2954		zfs_close(h);
2955	}
2956
2957	return (0);
2958
2959ancestorerr:
2960	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2961	    "failed to %s ancestor '%s'"), opname, target);
2962	return (-1);
2963}
2964
2965/*
2966 * Creates non-existing ancestors of the given path.
2967 */
2968int
2969zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
2970{
2971	int prefix;
2972	char *path_copy;
2973	int rc;
2974
2975	if (check_parents(hdl, path, NULL, B_TRUE, &prefix) != 0)
2976		return (-1);
2977
2978	if ((path_copy = strdup(path)) != NULL) {
2979		rc = create_parents(hdl, path_copy, prefix);
2980		free(path_copy);
2981	}
2982	if (path_copy == NULL || rc != 0)
2983		return (-1);
2984
2985	return (0);
2986}
2987
2988/*
2989 * Create a new filesystem or volume.
2990 */
2991int
2992zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
2993    nvlist_t *props)
2994{
2995	zfs_cmd_t zc = { 0 };
2996	int ret;
2997	uint64_t size = 0;
2998	uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
2999	char errbuf[1024];
3000	uint64_t zoned;
3001
3002	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3003	    "cannot create '%s'"), path);
3004
3005	/* validate the path, taking care to note the extended error message */
3006	if (!zfs_validate_name(hdl, path, type, B_TRUE))
3007		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3008
3009	/* validate parents exist */
3010	if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
3011		return (-1);
3012
3013	/*
3014	 * The failure modes when creating a dataset of a different type over
3015	 * one that already exists is a little strange.  In particular, if you
3016	 * try to create a dataset on top of an existing dataset, the ioctl()
3017	 * will return ENOENT, not EEXIST.  To prevent this from happening, we
3018	 * first try to see if the dataset exists.
3019	 */
3020	(void) strlcpy(zc.zc_name, path, sizeof (zc.zc_name));
3021	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
3022		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3023		    "dataset already exists"));
3024		return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3025	}
3026
3027	if (type == ZFS_TYPE_VOLUME)
3028		zc.zc_objset_type = DMU_OST_ZVOL;
3029	else
3030		zc.zc_objset_type = DMU_OST_ZFS;
3031
3032	if (props && (props = zfs_valid_proplist(hdl, type, props,
3033	    zoned, NULL, errbuf)) == 0)
3034		return (-1);
3035
3036	if (type == ZFS_TYPE_VOLUME) {
3037		/*
3038		 * If we are creating a volume, the size and block size must
3039		 * satisfy a few restraints.  First, the blocksize must be a
3040		 * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
3041		 * volsize must be a multiple of the block size, and cannot be
3042		 * zero.
3043		 */
3044		if (props == NULL || nvlist_lookup_uint64(props,
3045		    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
3046			nvlist_free(props);
3047			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3048			    "missing volume size"));
3049			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3050		}
3051
3052		if ((ret = nvlist_lookup_uint64(props,
3053		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3054		    &blocksize)) != 0) {
3055			if (ret == ENOENT) {
3056				blocksize = zfs_prop_default_numeric(
3057				    ZFS_PROP_VOLBLOCKSIZE);
3058			} else {
3059				nvlist_free(props);
3060				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3061				    "missing volume block size"));
3062				return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3063			}
3064		}
3065
3066		if (size == 0) {
3067			nvlist_free(props);
3068			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3069			    "volume size cannot be zero"));
3070			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3071		}
3072
3073		if (size % blocksize != 0) {
3074			nvlist_free(props);
3075			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3076			    "volume size must be a multiple of volume block "
3077			    "size"));
3078			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3079		}
3080	}
3081
3082	if (props && zcmd_write_src_nvlist(hdl, &zc, props) != 0)
3083		return (-1);
3084	nvlist_free(props);
3085
3086	/* create the dataset */
3087	ret = zfs_ioctl(hdl, ZFS_IOC_CREATE, &zc);
3088
3089	zcmd_free_nvlists(&zc);
3090
3091	/* check for failure */
3092	if (ret != 0) {
3093		char parent[ZFS_MAXNAMELEN];
3094		(void) parent_name(path, parent, sizeof (parent));
3095
3096		switch (errno) {
3097		case ENOENT:
3098			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3099			    "no such parent '%s'"), parent);
3100			return (zfs_error(hdl, EZFS_NOENT, errbuf));
3101
3102		case EINVAL:
3103			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3104			    "parent '%s' is not a filesystem"), parent);
3105			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3106
3107		case EDOM:
3108			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3109			    "volume block size must be power of 2 from "
3110			    "%u to %uk"),
3111			    (uint_t)SPA_MINBLOCKSIZE,
3112			    (uint_t)SPA_MAXBLOCKSIZE >> 10);
3113
3114			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3115
3116		case ENOTSUP:
3117			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3118			    "pool must be upgraded to set this "
3119			    "property or value"));
3120			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3121#ifdef _ILP32
3122		case EOVERFLOW:
3123			/*
3124			 * This platform can't address a volume this big.
3125			 */
3126			if (type == ZFS_TYPE_VOLUME)
3127				return (zfs_error(hdl, EZFS_VOLTOOBIG,
3128				    errbuf));
3129#endif
3130			/* FALLTHROUGH */
3131		default:
3132			return (zfs_standard_error(hdl, errno, errbuf));
3133		}
3134	}
3135
3136	return (0);
3137}
3138
3139/*
3140 * Destroys the given dataset.  The caller must make sure that the filesystem
3141 * isn't mounted, and that there are no active dependents. If the file system
3142 * does not exist this function does nothing.
3143 */
3144int
3145zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
3146{
3147	zfs_cmd_t zc = { 0 };
3148
3149	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3150
3151	if (ZFS_IS_VOLUME(zhp)) {
3152		zc.zc_objset_type = DMU_OST_ZVOL;
3153	} else {
3154		zc.zc_objset_type = DMU_OST_ZFS;
3155	}
3156
3157	zc.zc_defer_destroy = defer;
3158	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY, &zc) != 0 &&
3159	    errno != ENOENT) {
3160		return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3161		    dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3162		    zhp->zfs_name));
3163	}
3164
3165	remove_mountpoint(zhp);
3166
3167	return (0);
3168}
3169
3170struct destroydata {
3171	nvlist_t *nvl;
3172	const char *snapname;
3173};
3174
3175static int
3176zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
3177{
3178	struct destroydata *dd = arg;
3179	zfs_handle_t *szhp;
3180	char name[ZFS_MAXNAMELEN];
3181	int rv = 0;
3182
3183	(void) snprintf(name, sizeof (name),
3184	    "%s@%s", zhp->zfs_name, dd->snapname);
3185
3186	szhp = make_dataset_handle(zhp->zfs_hdl, name);
3187	if (szhp) {
3188		verify(nvlist_add_boolean(dd->nvl, name) == 0);
3189		zfs_close(szhp);
3190	}
3191
3192	rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, dd);
3193	zfs_close(zhp);
3194	return (rv);
3195}
3196
3197/*
3198 * Destroys all snapshots with the given name in zhp & descendants.
3199 */
3200int
3201zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
3202{
3203	int ret;
3204	struct destroydata dd = { 0 };
3205
3206	dd.snapname = snapname;
3207	verify(nvlist_alloc(&dd.nvl, NV_UNIQUE_NAME, 0) == 0);
3208	(void) zfs_check_snap_cb(zfs_handle_dup(zhp), &dd);
3209
3210	if (nvlist_next_nvpair(dd.nvl, NULL) == NULL) {
3211		ret = zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
3212		    dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
3213		    zhp->zfs_name, snapname);
3214	} else {
3215		ret = zfs_destroy_snaps_nvl(zhp, dd.nvl, defer);
3216	}
3217	nvlist_free(dd.nvl);
3218	return (ret);
3219}
3220
3221/*
3222 * Destroys all the snapshots named in the nvlist.  They must be underneath
3223 * the zhp (either snapshots of it, or snapshots of its descendants).
3224 */
3225int
3226zfs_destroy_snaps_nvl(zfs_handle_t *zhp, nvlist_t *snaps, boolean_t defer)
3227{
3228	int ret;
3229	zfs_cmd_t zc = { 0 };
3230
3231	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3232	if (zcmd_write_src_nvlist(zhp->zfs_hdl, &zc, snaps) != 0)
3233		return (-1);
3234	zc.zc_defer_destroy = defer;
3235
3236	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY_SNAPS_NVL, &zc);
3237	if (ret != 0) {
3238		char errbuf[1024];
3239
3240		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3241		    "cannot destroy snapshots in %s"), zc.zc_name);
3242
3243		switch (errno) {
3244		case EEXIST:
3245			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3246			    "snapshot is cloned"));
3247			return (zfs_error(zhp->zfs_hdl, EZFS_EXISTS, errbuf));
3248
3249		default:
3250			return (zfs_standard_error(zhp->zfs_hdl, errno,
3251			    errbuf));
3252		}
3253	}
3254
3255	return (0);
3256}
3257
3258/*
3259 * Clones the given dataset.  The target must be of the same type as the source.
3260 */
3261int
3262zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
3263{
3264	zfs_cmd_t zc = { 0 };
3265	char parent[ZFS_MAXNAMELEN];
3266	int ret;
3267	char errbuf[1024];
3268	libzfs_handle_t *hdl = zhp->zfs_hdl;
3269	zfs_type_t type;
3270	uint64_t zoned;
3271
3272	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
3273
3274	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3275	    "cannot create '%s'"), target);
3276
3277	/* validate the target/clone name */
3278	if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
3279		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3280
3281	/* validate parents exist */
3282	if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
3283		return (-1);
3284
3285	(void) parent_name(target, parent, sizeof (parent));
3286
3287	/* do the clone */
3288	if (ZFS_IS_VOLUME(zhp)) {
3289		zc.zc_objset_type = DMU_OST_ZVOL;
3290		type = ZFS_TYPE_VOLUME;
3291	} else {
3292		zc.zc_objset_type = DMU_OST_ZFS;
3293		type = ZFS_TYPE_FILESYSTEM;
3294	}
3295
3296	if (props) {
3297		if ((props = zfs_valid_proplist(hdl, type, props, zoned,
3298		    zhp, errbuf)) == NULL)
3299			return (-1);
3300
3301		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
3302			nvlist_free(props);
3303			return (-1);
3304		}
3305
3306		nvlist_free(props);
3307	}
3308
3309	(void) strlcpy(zc.zc_name, target, sizeof (zc.zc_name));
3310	(void) strlcpy(zc.zc_value, zhp->zfs_name, sizeof (zc.zc_value));
3311	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_CREATE, &zc);
3312
3313	zcmd_free_nvlists(&zc);
3314
3315	if (ret != 0) {
3316		switch (errno) {
3317
3318		case ENOENT:
3319			/*
3320			 * The parent doesn't exist.  We should have caught this
3321			 * above, but there may a race condition that has since
3322			 * destroyed the parent.
3323			 *
3324			 * At this point, we don't know whether it's the source
3325			 * that doesn't exist anymore, or whether the target
3326			 * dataset doesn't exist.
3327			 */
3328			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3329			    "no such parent '%s'"), parent);
3330			return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
3331
3332		case EXDEV:
3333			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3334			    "source and target pools differ"));
3335			return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
3336			    errbuf));
3337
3338		default:
3339			return (zfs_standard_error(zhp->zfs_hdl, errno,
3340			    errbuf));
3341		}
3342	}
3343
3344	return (ret);
3345}
3346
3347/*
3348 * Promotes the given clone fs to be the clone parent.
3349 */
3350int
3351zfs_promote(zfs_handle_t *zhp)
3352{
3353	libzfs_handle_t *hdl = zhp->zfs_hdl;
3354	zfs_cmd_t zc = { 0 };
3355	char parent[MAXPATHLEN];
3356	int ret;
3357	char errbuf[1024];
3358
3359	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3360	    "cannot promote '%s'"), zhp->zfs_name);
3361
3362	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3363		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3364		    "snapshots can not be promoted"));
3365		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3366	}
3367
3368	(void) strlcpy(parent, zhp->zfs_dmustats.dds_origin, sizeof (parent));
3369	if (parent[0] == '\0') {
3370		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3371		    "not a cloned filesystem"));
3372		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3373	}
3374
3375	(void) strlcpy(zc.zc_value, zhp->zfs_dmustats.dds_origin,
3376	    sizeof (zc.zc_value));
3377	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3378	ret = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
3379
3380	if (ret != 0) {
3381		int save_errno = errno;
3382
3383		switch (save_errno) {
3384		case EEXIST:
3385			/* There is a conflicting snapshot name. */
3386			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3387			    "conflicting snapshot '%s' from parent '%s'"),
3388			    zc.zc_string, parent);
3389			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3390
3391		default:
3392			return (zfs_standard_error(hdl, save_errno, errbuf));
3393		}
3394	}
3395	return (ret);
3396}
3397
3398/*
3399 * Takes a snapshot of the given dataset.
3400 */
3401int
3402zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
3403    nvlist_t *props)
3404{
3405	const char *delim;
3406	char parent[ZFS_MAXNAMELEN];
3407	zfs_handle_t *zhp;
3408	zfs_cmd_t zc = { 0 };
3409	int ret;
3410	char errbuf[1024];
3411
3412	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3413	    "cannot snapshot '%s'"), path);
3414
3415	/* validate the target name */
3416	if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
3417		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3418
3419	if (props) {
3420		if ((props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
3421		    props, B_FALSE, NULL, errbuf)) == NULL)
3422			return (-1);
3423
3424		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
3425			nvlist_free(props);
3426			return (-1);
3427		}
3428
3429		nvlist_free(props);
3430	}
3431
3432	/* make sure the parent exists and is of the appropriate type */
3433	delim = strchr(path, '@');
3434	(void) strncpy(parent, path, delim - path);
3435	parent[delim - path] = '\0';
3436
3437	if ((zhp = zfs_open(hdl, parent, ZFS_TYPE_FILESYSTEM |
3438	    ZFS_TYPE_VOLUME)) == NULL) {
3439		zcmd_free_nvlists(&zc);
3440		return (-1);
3441	}
3442
3443	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3444	(void) strlcpy(zc.zc_value, delim+1, sizeof (zc.zc_value));
3445	if (ZFS_IS_VOLUME(zhp))
3446		zc.zc_objset_type = DMU_OST_ZVOL;
3447	else
3448		zc.zc_objset_type = DMU_OST_ZFS;
3449	zc.zc_cookie = recursive;
3450	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SNAPSHOT, &zc);
3451
3452	zcmd_free_nvlists(&zc);
3453
3454	/*
3455	 * if it was recursive, the one that actually failed will be in
3456	 * zc.zc_name.
3457	 */
3458	if (ret != 0) {
3459		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3460		    "cannot create snapshot '%s@%s'"), zc.zc_name, zc.zc_value);
3461		(void) zfs_standard_error(hdl, errno, errbuf);
3462	}
3463
3464	zfs_close(zhp);
3465
3466	return (ret);
3467}
3468
3469/*
3470 * Destroy any more recent snapshots.  We invoke this callback on any dependents
3471 * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
3472 * is a dependent and we should just destroy it without checking the transaction
3473 * group.
3474 */
3475typedef struct rollback_data {
3476	const char	*cb_target;		/* the snapshot */
3477	uint64_t	cb_create;		/* creation time reference */
3478	boolean_t	cb_error;
3479	boolean_t	cb_dependent;
3480	boolean_t	cb_force;
3481} rollback_data_t;
3482
3483static int
3484rollback_destroy(zfs_handle_t *zhp, void *data)
3485{
3486	rollback_data_t *cbp = data;
3487
3488	if (!cbp->cb_dependent) {
3489		if (strcmp(zhp->zfs_name, cbp->cb_target) != 0 &&
3490		    zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3491		    zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3492		    cbp->cb_create) {
3493			char *logstr;
3494
3495			cbp->cb_dependent = B_TRUE;
3496			cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
3497			    rollback_destroy, cbp);
3498			cbp->cb_dependent = B_FALSE;
3499
3500			logstr = zhp->zfs_hdl->libzfs_log_str;
3501			zhp->zfs_hdl->libzfs_log_str = NULL;
3502			cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
3503			zhp->zfs_hdl->libzfs_log_str = logstr;
3504		}
3505	} else {
3506		/* We must destroy this clone; first unmount it */
3507		prop_changelist_t *clp;
3508
3509		clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
3510		    cbp->cb_force ? MS_FORCE: 0);
3511		if (clp == NULL || changelist_prefix(clp) != 0) {
3512			cbp->cb_error = B_TRUE;
3513			zfs_close(zhp);
3514			return (0);
3515		}
3516		if (zfs_destroy(zhp, B_FALSE) != 0)
3517			cbp->cb_error = B_TRUE;
3518		else
3519			changelist_remove(clp, zhp->zfs_name);
3520		(void) changelist_postfix(clp);
3521		changelist_free(clp);
3522	}
3523
3524	zfs_close(zhp);
3525	return (0);
3526}
3527
3528/*
3529 * Given a dataset, rollback to a specific snapshot, discarding any
3530 * data changes since then and making it the active dataset.
3531 *
3532 * Any snapshots more recent than the target are destroyed, along with
3533 * their dependents.
3534 */
3535int
3536zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
3537{
3538	rollback_data_t cb = { 0 };
3539	int err;
3540	zfs_cmd_t zc = { 0 };
3541	boolean_t restore_resv = 0;
3542	uint64_t old_volsize, new_volsize;
3543	zfs_prop_t resv_prop;
3544
3545	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
3546	    zhp->zfs_type == ZFS_TYPE_VOLUME);
3547
3548	/*
3549	 * Destroy all recent snapshots and their dependents.
3550	 */
3551	cb.cb_force = force;
3552	cb.cb_target = snap->zfs_name;
3553	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3554	(void) zfs_iter_children(zhp, rollback_destroy, &cb);
3555
3556	if (cb.cb_error)
3557		return (-1);
3558
3559	/*
3560	 * Now that we have verified that the snapshot is the latest,
3561	 * rollback to the given snapshot.
3562	 */
3563
3564	if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3565		if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
3566			return (-1);
3567		old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3568		restore_resv =
3569		    (old_volsize == zfs_prop_get_int(zhp, resv_prop));
3570	}
3571
3572	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3573
3574	if (ZFS_IS_VOLUME(zhp))
3575		zc.zc_objset_type = DMU_OST_ZVOL;
3576	else
3577		zc.zc_objset_type = DMU_OST_ZFS;
3578
3579	/*
3580	 * We rely on zfs_iter_children() to verify that there are no
3581	 * newer snapshots for the given dataset.  Therefore, we can
3582	 * simply pass the name on to the ioctl() call.  There is still
3583	 * an unlikely race condition where the user has taken a
3584	 * snapshot since we verified that this was the most recent.
3585	 *
3586	 */
3587	if ((err = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_ROLLBACK, &zc)) != 0) {
3588		(void) zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3589		    dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
3590		    zhp->zfs_name);
3591		return (err);
3592	}
3593
3594	/*
3595	 * For volumes, if the pre-rollback volsize matched the pre-
3596	 * rollback reservation and the volsize has changed then set
3597	 * the reservation property to the post-rollback volsize.
3598	 * Make a new handle since the rollback closed the dataset.
3599	 */
3600	if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
3601	    (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
3602		if (restore_resv) {
3603			new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3604			if (old_volsize != new_volsize)
3605				err = zfs_prop_set_int(zhp, resv_prop,
3606				    new_volsize);
3607		}
3608		zfs_close(zhp);
3609	}
3610	return (err);
3611}
3612
3613/*
3614 * Renames the given dataset.
3615 */
3616int
3617zfs_rename(zfs_handle_t *zhp, const char *target, renameflags_t flags)
3618{
3619	int ret;
3620	zfs_cmd_t zc = { 0 };
3621	char *delim;
3622	prop_changelist_t *cl = NULL;
3623	zfs_handle_t *zhrp = NULL;
3624	char *parentname = NULL;
3625	char parent[ZFS_MAXNAMELEN];
3626	char property[ZFS_MAXPROPLEN];
3627	libzfs_handle_t *hdl = zhp->zfs_hdl;
3628	char errbuf[1024];
3629
3630	/* if we have the same exact name, just return success */
3631	if (strcmp(zhp->zfs_name, target) == 0)
3632		return (0);
3633
3634	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3635	    "cannot rename to '%s'"), target);
3636
3637	/*
3638	 * Make sure the target name is valid
3639	 */
3640	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3641		if ((strchr(target, '@') == NULL) ||
3642		    *target == '@') {
3643			/*
3644			 * Snapshot target name is abbreviated,
3645			 * reconstruct full dataset name
3646			 */
3647			(void) strlcpy(parent, zhp->zfs_name,
3648			    sizeof (parent));
3649			delim = strchr(parent, '@');
3650			if (strchr(target, '@') == NULL)
3651				*(++delim) = '\0';
3652			else
3653				*delim = '\0';
3654			(void) strlcat(parent, target, sizeof (parent));
3655			target = parent;
3656		} else {
3657			/*
3658			 * Make sure we're renaming within the same dataset.
3659			 */
3660			delim = strchr(target, '@');
3661			if (strncmp(zhp->zfs_name, target, delim - target)
3662			    != 0 || zhp->zfs_name[delim - target] != '@') {
3663				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3664				    "snapshots must be part of same "
3665				    "dataset"));
3666				return (zfs_error(hdl, EZFS_CROSSTARGET,
3667				    errbuf));
3668			}
3669		}
3670		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3671			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3672	} else {
3673		if (flags.recurse) {
3674			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3675			    "recursive rename must be a snapshot"));
3676			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3677		}
3678
3679		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3680			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3681
3682		/* validate parents */
3683		if (check_parents(hdl, target, NULL, B_FALSE, NULL) != 0)
3684			return (-1);
3685
3686		/* make sure we're in the same pool */
3687		verify((delim = strchr(target, '/')) != NULL);
3688		if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
3689		    zhp->zfs_name[delim - target] != '/') {
3690			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3691			    "datasets must be within same pool"));
3692			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
3693		}
3694
3695		/* new name cannot be a child of the current dataset name */
3696		if (is_descendant(zhp->zfs_name, target)) {
3697			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3698			    "New dataset name cannot be a descendant of "
3699			    "current dataset name"));
3700			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3701		}
3702	}
3703
3704	(void) snprintf(errbuf, sizeof (errbuf),
3705	    dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
3706
3707	if (getzoneid() == GLOBAL_ZONEID &&
3708	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
3709		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3710		    "dataset is used in a non-global zone"));
3711		return (zfs_error(hdl, EZFS_ZONED, errbuf));
3712	}
3713
3714	/*
3715	 * Avoid unmounting file systems with mountpoint property set to
3716	 * 'legacy' or 'none' even if -u option is not given.
3717	 */
3718	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
3719	    !flags.recurse && !flags.nounmount &&
3720	    zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, property,
3721	    sizeof (property), NULL, NULL, 0, B_FALSE) == 0 &&
3722	    (strcmp(property, "legacy") == 0 ||
3723	     strcmp(property, "none") == 0)) {
3724		flags.nounmount = B_TRUE;
3725	}
3726
3727	if (flags.recurse) {
3728
3729		parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
3730		if (parentname == NULL) {
3731			ret = -1;
3732			goto error;
3733		}
3734		delim = strchr(parentname, '@');
3735		*delim = '\0';
3736		zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
3737		if (zhrp == NULL) {
3738			ret = -1;
3739			goto error;
3740		}
3741
3742	} else {
3743		if ((cl = changelist_gather(zhp, ZFS_PROP_NAME,
3744		    flags.nounmount ? CL_GATHER_DONT_UNMOUNT : 0,
3745		    flags.forceunmount ? MS_FORCE : 0)) == NULL) {
3746			return (-1);
3747		}
3748
3749		if (changelist_haszonedchild(cl)) {
3750			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3751			    "child dataset with inherited mountpoint is used "
3752			    "in a non-global zone"));
3753			(void) zfs_error(hdl, EZFS_ZONED, errbuf);
3754			goto error;
3755		}
3756
3757		if ((ret = changelist_prefix(cl)) != 0)
3758			goto error;
3759	}
3760
3761	if (ZFS_IS_VOLUME(zhp))
3762		zc.zc_objset_type = DMU_OST_ZVOL;
3763	else
3764		zc.zc_objset_type = DMU_OST_ZFS;
3765
3766	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3767	(void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
3768
3769	zc.zc_cookie = flags.recurse ? 1 : 0;
3770	if (flags.nounmount)
3771		zc.zc_cookie |= 2;
3772
3773	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
3774		/*
3775		 * if it was recursive, the one that actually failed will
3776		 * be in zc.zc_name
3777		 */
3778		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3779		    "cannot rename '%s'"), zc.zc_name);
3780
3781		if (flags.recurse && errno == EEXIST) {
3782			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3783			    "a child dataset already has a snapshot "
3784			    "with the new name"));
3785			(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3786		} else {
3787			(void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
3788		}
3789
3790		/*
3791		 * On failure, we still want to remount any filesystems that
3792		 * were previously mounted, so we don't alter the system state.
3793		 */
3794		if (!flags.recurse)
3795			(void) changelist_postfix(cl);
3796	} else {
3797		if (!flags.recurse) {
3798			changelist_rename(cl, zfs_get_name(zhp), target);
3799			ret = changelist_postfix(cl);
3800		}
3801	}
3802
3803error:
3804	if (parentname) {
3805		free(parentname);
3806	}
3807	if (zhrp) {
3808		zfs_close(zhrp);
3809	}
3810	if (cl) {
3811		changelist_free(cl);
3812	}
3813	return (ret);
3814}
3815
3816nvlist_t *
3817zfs_get_user_props(zfs_handle_t *zhp)
3818{
3819	return (zhp->zfs_user_props);
3820}
3821
3822nvlist_t *
3823zfs_get_recvd_props(zfs_handle_t *zhp)
3824{
3825	if (zhp->zfs_recvd_props == NULL)
3826		if (get_recvd_props_ioctl(zhp) != 0)
3827			return (NULL);
3828	return (zhp->zfs_recvd_props);
3829}
3830
3831/*
3832 * This function is used by 'zfs list' to determine the exact set of columns to
3833 * display, and their maximum widths.  This does two main things:
3834 *
3835 *      - If this is a list of all properties, then expand the list to include
3836 *        all native properties, and set a flag so that for each dataset we look
3837 *        for new unique user properties and add them to the list.
3838 *
3839 *      - For non fixed-width properties, keep track of the maximum width seen
3840 *        so that we can size the column appropriately. If the user has
3841 *        requested received property values, we also need to compute the width
3842 *        of the RECEIVED column.
3843 */
3844int
3845zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp, boolean_t received)
3846{
3847	libzfs_handle_t *hdl = zhp->zfs_hdl;
3848	zprop_list_t *entry;
3849	zprop_list_t **last, **start;
3850	nvlist_t *userprops, *propval;
3851	nvpair_t *elem;
3852	char *strval;
3853	char buf[ZFS_MAXPROPLEN];
3854
3855	if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
3856		return (-1);
3857
3858	userprops = zfs_get_user_props(zhp);
3859
3860	entry = *plp;
3861	if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
3862		/*
3863		 * Go through and add any user properties as necessary.  We
3864		 * start by incrementing our list pointer to the first
3865		 * non-native property.
3866		 */
3867		start = plp;
3868		while (*start != NULL) {
3869			if ((*start)->pl_prop == ZPROP_INVAL)
3870				break;
3871			start = &(*start)->pl_next;
3872		}
3873
3874		elem = NULL;
3875		while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
3876			/*
3877			 * See if we've already found this property in our list.
3878			 */
3879			for (last = start; *last != NULL;
3880			    last = &(*last)->pl_next) {
3881				if (strcmp((*last)->pl_user_prop,
3882				    nvpair_name(elem)) == 0)
3883					break;
3884			}
3885
3886			if (*last == NULL) {
3887				if ((entry = zfs_alloc(hdl,
3888				    sizeof (zprop_list_t))) == NULL ||
3889				    ((entry->pl_user_prop = zfs_strdup(hdl,
3890				    nvpair_name(elem)))) == NULL) {
3891					free(entry);
3892					return (-1);
3893				}
3894
3895				entry->pl_prop = ZPROP_INVAL;
3896				entry->pl_width = strlen(nvpair_name(elem));
3897				entry->pl_all = B_TRUE;
3898				*last = entry;
3899			}
3900		}
3901	}
3902
3903	/*
3904	 * Now go through and check the width of any non-fixed columns
3905	 */
3906	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
3907		if (entry->pl_fixed)
3908			continue;
3909
3910		if (entry->pl_prop != ZPROP_INVAL) {
3911			if (zfs_prop_get(zhp, entry->pl_prop,
3912			    buf, sizeof (buf), NULL, NULL, 0, B_FALSE) == 0) {
3913				if (strlen(buf) > entry->pl_width)
3914					entry->pl_width = strlen(buf);
3915			}
3916			if (received && zfs_prop_get_recvd(zhp,
3917			    zfs_prop_to_name(entry->pl_prop),
3918			    buf, sizeof (buf), B_FALSE) == 0)
3919				if (strlen(buf) > entry->pl_recvd_width)
3920					entry->pl_recvd_width = strlen(buf);
3921		} else {
3922			if (nvlist_lookup_nvlist(userprops, entry->pl_user_prop,
3923			    &propval) == 0) {
3924				verify(nvlist_lookup_string(propval,
3925				    ZPROP_VALUE, &strval) == 0);
3926				if (strlen(strval) > entry->pl_width)
3927					entry->pl_width = strlen(strval);
3928			}
3929			if (received && zfs_prop_get_recvd(zhp,
3930			    entry->pl_user_prop,
3931			    buf, sizeof (buf), B_FALSE) == 0)
3932				if (strlen(buf) > entry->pl_recvd_width)
3933					entry->pl_recvd_width = strlen(buf);
3934		}
3935	}
3936
3937	return (0);
3938}
3939
3940int
3941zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
3942    char *resource, void *export, void *sharetab,
3943    int sharemax, zfs_share_op_t operation)
3944{
3945	zfs_cmd_t zc = { 0 };
3946	int error;
3947
3948	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3949	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
3950	if (resource)
3951		(void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
3952	zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
3953	zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
3954	zc.zc_share.z_sharetype = operation;
3955	zc.zc_share.z_sharemax = sharemax;
3956	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
3957	return (error);
3958}
3959
3960void
3961zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
3962{
3963	nvpair_t *curr;
3964
3965	/*
3966	 * Keep a reference to the props-table against which we prune the
3967	 * properties.
3968	 */
3969	zhp->zfs_props_table = props;
3970
3971	curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
3972
3973	while (curr) {
3974		zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
3975		nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
3976
3977		/*
3978		 * User properties will result in ZPROP_INVAL, and since we
3979		 * only know how to prune standard ZFS properties, we always
3980		 * leave these in the list.  This can also happen if we
3981		 * encounter an unknown DSL property (when running older
3982		 * software, for example).
3983		 */
3984		if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
3985			(void) nvlist_remove(zhp->zfs_props,
3986			    nvpair_name(curr), nvpair_type(curr));
3987		curr = next;
3988	}
3989}
3990
3991#ifdef sun
3992static int
3993zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
3994    zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
3995{
3996	zfs_cmd_t zc = { 0 };
3997	nvlist_t *nvlist = NULL;
3998	int error;
3999
4000	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4001	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4002	zc.zc_cookie = (uint64_t)cmd;
4003
4004	if (cmd == ZFS_SMB_ACL_RENAME) {
4005		if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
4006			(void) no_memory(hdl);
4007			return (NULL);
4008		}
4009	}
4010
4011	switch (cmd) {
4012	case ZFS_SMB_ACL_ADD:
4013	case ZFS_SMB_ACL_REMOVE:
4014		(void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
4015		break;
4016	case ZFS_SMB_ACL_RENAME:
4017		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
4018		    resource1) != 0) {
4019				(void) no_memory(hdl);
4020				return (-1);
4021		}
4022		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
4023		    resource2) != 0) {
4024				(void) no_memory(hdl);
4025				return (-1);
4026		}
4027		if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
4028			nvlist_free(nvlist);
4029			return (-1);
4030		}
4031		break;
4032	case ZFS_SMB_ACL_PURGE:
4033		break;
4034	default:
4035		return (-1);
4036	}
4037	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
4038	if (nvlist)
4039		nvlist_free(nvlist);
4040	return (error);
4041}
4042
4043int
4044zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
4045    char *path, char *resource)
4046{
4047	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
4048	    resource, NULL));
4049}
4050
4051int
4052zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
4053    char *path, char *resource)
4054{
4055	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
4056	    resource, NULL));
4057}
4058
4059int
4060zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
4061{
4062	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
4063	    NULL, NULL));
4064}
4065
4066int
4067zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
4068    char *oldname, char *newname)
4069{
4070	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
4071	    oldname, newname));
4072}
4073#endif	/* sun */
4074
4075int
4076zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
4077    zfs_userspace_cb_t func, void *arg)
4078{
4079	zfs_cmd_t zc = { 0 };
4080	int error;
4081	zfs_useracct_t buf[100];
4082
4083	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4084
4085	zc.zc_objset_type = type;
4086	zc.zc_nvlist_dst = (uintptr_t)buf;
4087
4088	/* CONSTCOND */
4089	while (1) {
4090		zfs_useracct_t *zua = buf;
4091
4092		zc.zc_nvlist_dst_size = sizeof (buf);
4093		error = ioctl(zhp->zfs_hdl->libzfs_fd,
4094		    ZFS_IOC_USERSPACE_MANY, &zc);
4095		if (error || zc.zc_nvlist_dst_size == 0)
4096			break;
4097
4098		while (zc.zc_nvlist_dst_size > 0) {
4099			error = func(arg, zua->zu_domain, zua->zu_rid,
4100			    zua->zu_space);
4101			if (error != 0)
4102				return (error);
4103			zua++;
4104			zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
4105		}
4106	}
4107
4108	return (error);
4109}
4110
4111int
4112zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
4113    boolean_t recursive, boolean_t temphold, boolean_t enoent_ok,
4114    int cleanup_fd, uint64_t dsobj, uint64_t createtxg)
4115{
4116	zfs_cmd_t zc = { 0 };
4117	libzfs_handle_t *hdl = zhp->zfs_hdl;
4118
4119	ASSERT(!recursive || dsobj == 0);
4120
4121	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4122	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
4123	if (strlcpy(zc.zc_string, tag, sizeof (zc.zc_string))
4124	    >= sizeof (zc.zc_string))
4125		return (zfs_error(hdl, EZFS_TAGTOOLONG, tag));
4126	zc.zc_cookie = recursive;
4127	zc.zc_temphold = temphold;
4128	zc.zc_cleanup_fd = cleanup_fd;
4129	zc.zc_sendobj = dsobj;
4130	zc.zc_createtxg = createtxg;
4131
4132	if (zfs_ioctl(hdl, ZFS_IOC_HOLD, &zc) != 0) {
4133		char errbuf[ZFS_MAXNAMELEN+32];
4134
4135		/*
4136		 * if it was recursive, the one that actually failed will be in
4137		 * zc.zc_name.
4138		 */
4139		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4140		    "cannot hold '%s@%s'"), zc.zc_name, snapname);
4141		switch (errno) {
4142		case E2BIG:
4143			/*
4144			 * Temporary tags wind up having the ds object id
4145			 * prepended. So even if we passed the length check
4146			 * above, it's still possible for the tag to wind
4147			 * up being slightly too long.
4148			 */
4149			return (zfs_error(hdl, EZFS_TAGTOOLONG, errbuf));
4150		case ENOTSUP:
4151			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4152			    "pool must be upgraded"));
4153			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
4154		case EINVAL:
4155			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4156		case EEXIST:
4157			return (zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf));
4158		case ENOENT:
4159			if (enoent_ok)
4160				return (ENOENT);
4161			/* FALLTHROUGH */
4162		default:
4163			return (zfs_standard_error_fmt(hdl, errno, errbuf));
4164		}
4165	}
4166
4167	return (0);
4168}
4169
4170int
4171zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
4172    boolean_t recursive)
4173{
4174	zfs_cmd_t zc = { 0 };
4175	libzfs_handle_t *hdl = zhp->zfs_hdl;
4176
4177	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4178	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
4179	if (strlcpy(zc.zc_string, tag, sizeof (zc.zc_string))
4180	    >= sizeof (zc.zc_string))
4181		return (zfs_error(hdl, EZFS_TAGTOOLONG, tag));
4182	zc.zc_cookie = recursive;
4183
4184	if (zfs_ioctl(hdl, ZFS_IOC_RELEASE, &zc) != 0) {
4185		char errbuf[ZFS_MAXNAMELEN+32];
4186
4187		/*
4188		 * if it was recursive, the one that actually failed will be in
4189		 * zc.zc_name.
4190		 */
4191		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4192		    "cannot release '%s' from '%s@%s'"), tag, zc.zc_name,
4193		    snapname);
4194		switch (errno) {
4195		case ESRCH:
4196			return (zfs_error(hdl, EZFS_REFTAG_RELE, errbuf));
4197		case ENOTSUP:
4198			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4199			    "pool must be upgraded"));
4200			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
4201		case EINVAL:
4202			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4203		default:
4204			return (zfs_standard_error_fmt(hdl, errno, errbuf));
4205		}
4206	}
4207
4208	return (0);
4209}
4210
4211int
4212zfs_get_fsacl(zfs_handle_t *zhp, nvlist_t **nvl)
4213{
4214	zfs_cmd_t zc = { 0 };
4215	libzfs_handle_t *hdl = zhp->zfs_hdl;
4216	int nvsz = 2048;
4217	void *nvbuf;
4218	int err = 0;
4219	char errbuf[ZFS_MAXNAMELEN+32];
4220
4221	assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
4222	    zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4223
4224tryagain:
4225
4226	nvbuf = malloc(nvsz);
4227	if (nvbuf == NULL) {
4228		err = (zfs_error(hdl, EZFS_NOMEM, strerror(errno)));
4229		goto out;
4230	}
4231
4232	zc.zc_nvlist_dst_size = nvsz;
4233	zc.zc_nvlist_dst = (uintptr_t)nvbuf;
4234
4235	(void) strlcpy(zc.zc_name, zhp->zfs_name, ZFS_MAXNAMELEN);
4236
4237	if (ioctl(hdl->libzfs_fd, ZFS_IOC_GET_FSACL, &zc) != 0) {
4238		(void) snprintf(errbuf, sizeof (errbuf),
4239		    dgettext(TEXT_DOMAIN, "cannot get permissions on '%s'"),
4240		    zc.zc_name);
4241		switch (errno) {
4242		case ENOMEM:
4243			free(nvbuf);
4244			nvsz = zc.zc_nvlist_dst_size;
4245			goto tryagain;
4246
4247		case ENOTSUP:
4248			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4249			    "pool must be upgraded"));
4250			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4251			break;
4252		case EINVAL:
4253			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4254			break;
4255		case ENOENT:
4256			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4257			break;
4258		default:
4259			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4260			break;
4261		}
4262	} else {
4263		/* success */
4264		int rc = nvlist_unpack(nvbuf, zc.zc_nvlist_dst_size, nvl, 0);
4265		if (rc) {
4266			(void) snprintf(errbuf, sizeof (errbuf), dgettext(
4267			    TEXT_DOMAIN, "cannot get permissions on '%s'"),
4268			    zc.zc_name);
4269			err = zfs_standard_error_fmt(hdl, rc, errbuf);
4270		}
4271	}
4272
4273	free(nvbuf);
4274out:
4275	return (err);
4276}
4277
4278int
4279zfs_set_fsacl(zfs_handle_t *zhp, boolean_t un, nvlist_t *nvl)
4280{
4281	zfs_cmd_t zc = { 0 };
4282	libzfs_handle_t *hdl = zhp->zfs_hdl;
4283	char *nvbuf;
4284	char errbuf[ZFS_MAXNAMELEN+32];
4285	size_t nvsz;
4286	int err;
4287
4288	assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
4289	    zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4290
4291	err = nvlist_size(nvl, &nvsz, NV_ENCODE_NATIVE);
4292	assert(err == 0);
4293
4294	nvbuf = malloc(nvsz);
4295
4296	err = nvlist_pack(nvl, &nvbuf, &nvsz, NV_ENCODE_NATIVE, 0);
4297	assert(err == 0);
4298
4299	zc.zc_nvlist_src_size = nvsz;
4300	zc.zc_nvlist_src = (uintptr_t)nvbuf;
4301	zc.zc_perm_action = un;
4302
4303	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4304
4305	if (zfs_ioctl(hdl, ZFS_IOC_SET_FSACL, &zc) != 0) {
4306		(void) snprintf(errbuf, sizeof (errbuf),
4307		    dgettext(TEXT_DOMAIN, "cannot set permissions on '%s'"),
4308		    zc.zc_name);
4309		switch (errno) {
4310		case ENOTSUP:
4311			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4312			    "pool must be upgraded"));
4313			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4314			break;
4315		case EINVAL:
4316			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4317			break;
4318		case ENOENT:
4319			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4320			break;
4321		default:
4322			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4323			break;
4324		}
4325	}
4326
4327	free(nvbuf);
4328
4329	return (err);
4330}
4331
4332int
4333zfs_get_holds(zfs_handle_t *zhp, nvlist_t **nvl)
4334{
4335	zfs_cmd_t zc = { 0 };
4336	libzfs_handle_t *hdl = zhp->zfs_hdl;
4337	int nvsz = 2048;
4338	void *nvbuf;
4339	int err = 0;
4340	char errbuf[ZFS_MAXNAMELEN+32];
4341
4342	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
4343
4344tryagain:
4345
4346	nvbuf = malloc(nvsz);
4347	if (nvbuf == NULL) {
4348		err = (zfs_error(hdl, EZFS_NOMEM, strerror(errno)));
4349		goto out;
4350	}
4351
4352	zc.zc_nvlist_dst_size = nvsz;
4353	zc.zc_nvlist_dst = (uintptr_t)nvbuf;
4354
4355	(void) strlcpy(zc.zc_name, zhp->zfs_name, ZFS_MAXNAMELEN);
4356
4357	if (zfs_ioctl(hdl, ZFS_IOC_GET_HOLDS, &zc) != 0) {
4358		(void) snprintf(errbuf, sizeof (errbuf),
4359		    dgettext(TEXT_DOMAIN, "cannot get holds for '%s'"),
4360		    zc.zc_name);
4361		switch (errno) {
4362		case ENOMEM:
4363			free(nvbuf);
4364			nvsz = zc.zc_nvlist_dst_size;
4365			goto tryagain;
4366
4367		case ENOTSUP:
4368			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4369			    "pool must be upgraded"));
4370			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4371			break;
4372		case EINVAL:
4373			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4374			break;
4375		case ENOENT:
4376			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4377			break;
4378		default:
4379			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4380			break;
4381		}
4382	} else {
4383		/* success */
4384		int rc = nvlist_unpack(nvbuf, zc.zc_nvlist_dst_size, nvl, 0);
4385		if (rc) {
4386			(void) snprintf(errbuf, sizeof (errbuf),
4387			    dgettext(TEXT_DOMAIN, "cannot get holds for '%s'"),
4388			    zc.zc_name);
4389			err = zfs_standard_error_fmt(hdl, rc, errbuf);
4390		}
4391	}
4392
4393	free(nvbuf);
4394out:
4395	return (err);
4396}
4397
4398uint64_t
4399zvol_volsize_to_reservation(uint64_t volsize, nvlist_t *props)
4400{
4401	uint64_t numdb;
4402	uint64_t nblocks, volblocksize;
4403	int ncopies;
4404	char *strval;
4405
4406	if (nvlist_lookup_string(props,
4407	    zfs_prop_to_name(ZFS_PROP_COPIES), &strval) == 0)
4408		ncopies = atoi(strval);
4409	else
4410		ncopies = 1;
4411	if (nvlist_lookup_uint64(props,
4412	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
4413	    &volblocksize) != 0)
4414		volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
4415	nblocks = volsize/volblocksize;
4416	/* start with metadnode L0-L6 */
4417	numdb = 7;
4418	/* calculate number of indirects */
4419	while (nblocks > 1) {
4420		nblocks += DNODES_PER_LEVEL - 1;
4421		nblocks /= DNODES_PER_LEVEL;
4422		numdb += nblocks;
4423	}
4424	numdb *= MIN(SPA_DVAS_PER_BP, ncopies + 1);
4425	volsize *= ncopies;
4426	/*
4427	 * this is exactly DN_MAX_INDBLKSHIFT when metadata isn't
4428	 * compressed, but in practice they compress down to about
4429	 * 1100 bytes
4430	 */
4431	numdb *= 1ULL << DN_MAX_INDBLKSHIFT;
4432	volsize += numdb;
4433	return (volsize);
4434}
4435
4436/*
4437 * Attach/detach the given filesystem to/from the given jail.
4438 */
4439int
4440zfs_jail(zfs_handle_t *zhp, int jailid, int attach)
4441{
4442	libzfs_handle_t *hdl = zhp->zfs_hdl;
4443	zfs_cmd_t zc = { 0 };
4444	char errbuf[1024];
4445	unsigned long cmd;
4446	int ret;
4447
4448	if (attach) {
4449		(void) snprintf(errbuf, sizeof (errbuf),
4450		    dgettext(TEXT_DOMAIN, "cannot jail '%s'"), zhp->zfs_name);
4451	} else {
4452		(void) snprintf(errbuf, sizeof (errbuf),
4453		    dgettext(TEXT_DOMAIN, "cannot jail '%s'"), zhp->zfs_name);
4454	}
4455
4456	switch (zhp->zfs_type) {
4457	case ZFS_TYPE_VOLUME:
4458		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4459		    "volumes can not be jailed"));
4460		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4461	case ZFS_TYPE_SNAPSHOT:
4462		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4463		    "snapshots can not be jailed"));
4464		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4465	}
4466	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4467
4468	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4469	zc.zc_objset_type = DMU_OST_ZFS;
4470	zc.zc_jailid = jailid;
4471
4472	cmd = attach ? ZFS_IOC_JAIL : ZFS_IOC_UNJAIL;
4473	if ((ret = ioctl(hdl->libzfs_fd, cmd, &zc)) != 0)
4474		zfs_standard_error(hdl, errno, errbuf);
4475
4476	return (ret);
4477}
4478