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