libzfs_dataset.c revision 290757
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 if (prop == ZFS_PROP_CHECKSUM ||
1491		    prop == ZFS_PROP_DEDUP) {
1492			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1493			    "property setting is not allowed on "
1494			    "root pools"));
1495			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
1496		} else {
1497			(void) zfs_standard_error(hdl, err, errbuf);
1498		}
1499		break;
1500
1501	case EINVAL:
1502		if (prop == ZPROP_INVAL) {
1503			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1504		} else {
1505			(void) zfs_standard_error(hdl, err, errbuf);
1506		}
1507		break;
1508
1509	case EOVERFLOW:
1510		/*
1511		 * This platform can't address a volume this big.
1512		 */
1513#ifdef _ILP32
1514		if (prop == ZFS_PROP_VOLSIZE) {
1515			(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
1516			break;
1517		}
1518#endif
1519		/* FALLTHROUGH */
1520	default:
1521		(void) zfs_standard_error(hdl, err, errbuf);
1522	}
1523}
1524
1525/*
1526 * Given a property name and value, set the property for the given dataset.
1527 */
1528int
1529zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
1530{
1531	zfs_cmd_t zc = { 0 };
1532	int ret = -1;
1533	prop_changelist_t *cl = NULL;
1534	char errbuf[1024];
1535	libzfs_handle_t *hdl = zhp->zfs_hdl;
1536	nvlist_t *nvl = NULL, *realprops;
1537	zfs_prop_t prop;
1538	boolean_t do_prefix = B_TRUE;
1539	int added_resv;
1540
1541	(void) snprintf(errbuf, sizeof (errbuf),
1542	    dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1543	    zhp->zfs_name);
1544
1545	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
1546	    nvlist_add_string(nvl, propname, propval) != 0) {
1547		(void) no_memory(hdl);
1548		goto error;
1549	}
1550
1551	if ((realprops = zfs_valid_proplist(hdl, zhp->zfs_type, nvl,
1552	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, errbuf)) == NULL)
1553		goto error;
1554
1555	nvlist_free(nvl);
1556	nvl = realprops;
1557
1558	prop = zfs_name_to_prop(propname);
1559
1560	/* We don't support those properties on FreeBSD. */
1561	switch (prop) {
1562	case ZFS_PROP_DEVICES:
1563	case ZFS_PROP_ISCSIOPTIONS:
1564	case ZFS_PROP_XATTR:
1565	case ZFS_PROP_VSCAN:
1566	case ZFS_PROP_NBMAND:
1567	case ZFS_PROP_MLSLABEL:
1568		(void) snprintf(errbuf, sizeof (errbuf),
1569		    "property '%s' not supported on FreeBSD", propname);
1570		ret = zfs_error(hdl, EZFS_PERM, errbuf);
1571		goto error;
1572	}
1573
1574	if (prop == ZFS_PROP_VOLSIZE) {
1575		if ((added_resv = zfs_add_synthetic_resv(zhp, nvl)) == -1)
1576			goto error;
1577	}
1578
1579	if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1580		goto error;
1581
1582	if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1583		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1584		    "child dataset with inherited mountpoint is used "
1585		    "in a non-global zone"));
1586		ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1587		goto error;
1588	}
1589
1590	/*
1591	 * We don't want to unmount & remount the dataset when changing
1592	 * its canmount property to 'on' or 'noauto'.  We only use
1593	 * the changelist logic to unmount when setting canmount=off.
1594	 */
1595	if (prop == ZFS_PROP_CANMOUNT) {
1596		uint64_t idx;
1597		int err = zprop_string_to_index(prop, propval, &idx,
1598		    ZFS_TYPE_DATASET);
1599		if (err == 0 && idx != ZFS_CANMOUNT_OFF)
1600			do_prefix = B_FALSE;
1601	}
1602
1603	if (do_prefix && (ret = changelist_prefix(cl)) != 0)
1604		goto error;
1605
1606	/*
1607	 * Execute the corresponding ioctl() to set this property.
1608	 */
1609	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1610
1611	if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1612		goto error;
1613
1614	ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1615
1616	if (ret != 0) {
1617		zfs_setprop_error(hdl, prop, errno, errbuf);
1618		if (added_resv && errno == ENOSPC) {
1619			/* clean up the volsize property we tried to set */
1620			uint64_t old_volsize = zfs_prop_get_int(zhp,
1621			    ZFS_PROP_VOLSIZE);
1622			nvlist_free(nvl);
1623			zcmd_free_nvlists(&zc);
1624			if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
1625				goto error;
1626			if (nvlist_add_uint64(nvl,
1627			    zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1628			    old_volsize) != 0)
1629				goto error;
1630			if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1631				goto error;
1632			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1633		}
1634	} else {
1635		if (do_prefix)
1636			ret = changelist_postfix(cl);
1637
1638		/*
1639		 * Refresh the statistics so the new property value
1640		 * is reflected.
1641		 */
1642		if (ret == 0)
1643			(void) get_stats(zhp);
1644	}
1645
1646error:
1647	nvlist_free(nvl);
1648	zcmd_free_nvlists(&zc);
1649	if (cl)
1650		changelist_free(cl);
1651	return (ret);
1652}
1653
1654/*
1655 * Given a property, inherit the value from the parent dataset, or if received
1656 * is TRUE, revert to the received value, if any.
1657 */
1658int
1659zfs_prop_inherit(zfs_handle_t *zhp, const char *propname, boolean_t received)
1660{
1661	zfs_cmd_t zc = { 0 };
1662	int ret;
1663	prop_changelist_t *cl;
1664	libzfs_handle_t *hdl = zhp->zfs_hdl;
1665	char errbuf[1024];
1666	zfs_prop_t prop;
1667
1668	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1669	    "cannot inherit %s for '%s'"), propname, zhp->zfs_name);
1670
1671	zc.zc_cookie = received;
1672	if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
1673		/*
1674		 * For user properties, the amount of work we have to do is very
1675		 * small, so just do it here.
1676		 */
1677		if (!zfs_prop_user(propname)) {
1678			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1679			    "invalid property"));
1680			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1681		}
1682
1683		(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1684		(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1685
1686		if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
1687			return (zfs_standard_error(hdl, errno, errbuf));
1688
1689		return (0);
1690	}
1691
1692	/*
1693	 * Verify that this property is inheritable.
1694	 */
1695	if (zfs_prop_readonly(prop))
1696		return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
1697
1698	if (!zfs_prop_inheritable(prop) && !received)
1699		return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
1700
1701	/*
1702	 * Check to see if the value applies to this type
1703	 */
1704	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1705		return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
1706
1707	/*
1708	 * Normalize the name, to get rid of shorthand abbreviations.
1709	 */
1710	propname = zfs_prop_to_name(prop);
1711	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1712	(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1713
1714	if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
1715	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
1716		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1717		    "dataset is used in a non-global zone"));
1718		return (zfs_error(hdl, EZFS_ZONED, errbuf));
1719	}
1720
1721	/*
1722	 * Determine datasets which will be affected by this change, if any.
1723	 */
1724	if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1725		return (-1);
1726
1727	if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1728		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1729		    "child dataset with inherited mountpoint is used "
1730		    "in a non-global zone"));
1731		ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1732		goto error;
1733	}
1734
1735	if ((ret = changelist_prefix(cl)) != 0)
1736		goto error;
1737
1738	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
1739		return (zfs_standard_error(hdl, errno, errbuf));
1740	} else {
1741
1742		if ((ret = changelist_postfix(cl)) != 0)
1743			goto error;
1744
1745		/*
1746		 * Refresh the statistics so the new property is reflected.
1747		 */
1748		(void) get_stats(zhp);
1749	}
1750
1751error:
1752	changelist_free(cl);
1753	return (ret);
1754}
1755
1756/*
1757 * True DSL properties are stored in an nvlist.  The following two functions
1758 * extract them appropriately.
1759 */
1760static uint64_t
1761getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1762{
1763	nvlist_t *nv;
1764	uint64_t value;
1765
1766	*source = NULL;
1767	if (nvlist_lookup_nvlist(zhp->zfs_props,
1768	    zfs_prop_to_name(prop), &nv) == 0) {
1769		verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
1770		(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1771	} else {
1772		verify(!zhp->zfs_props_table ||
1773		    zhp->zfs_props_table[prop] == B_TRUE);
1774		value = zfs_prop_default_numeric(prop);
1775		*source = "";
1776	}
1777
1778	return (value);
1779}
1780
1781static const char *
1782getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1783{
1784	nvlist_t *nv;
1785	const char *value;
1786
1787	*source = NULL;
1788	if (nvlist_lookup_nvlist(zhp->zfs_props,
1789	    zfs_prop_to_name(prop), &nv) == 0) {
1790		value = fnvlist_lookup_string(nv, ZPROP_VALUE);
1791		(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1792	} else {
1793		verify(!zhp->zfs_props_table ||
1794		    zhp->zfs_props_table[prop] == B_TRUE);
1795		value = zfs_prop_default_string(prop);
1796		*source = "";
1797	}
1798
1799	return (value);
1800}
1801
1802static boolean_t
1803zfs_is_recvd_props_mode(zfs_handle_t *zhp)
1804{
1805	return (zhp->zfs_props == zhp->zfs_recvd_props);
1806}
1807
1808static void
1809zfs_set_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
1810{
1811	*cookie = (uint64_t)(uintptr_t)zhp->zfs_props;
1812	zhp->zfs_props = zhp->zfs_recvd_props;
1813}
1814
1815static void
1816zfs_unset_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
1817{
1818	zhp->zfs_props = (nvlist_t *)(uintptr_t)*cookie;
1819	*cookie = 0;
1820}
1821
1822/*
1823 * Internal function for getting a numeric property.  Both zfs_prop_get() and
1824 * zfs_prop_get_int() are built using this interface.
1825 *
1826 * Certain properties can be overridden using 'mount -o'.  In this case, scan
1827 * the contents of the /etc/mnttab entry, searching for the appropriate options.
1828 * If they differ from the on-disk values, report the current values and mark
1829 * the source "temporary".
1830 */
1831static int
1832get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
1833    char **source, uint64_t *val)
1834{
1835	zfs_cmd_t zc = { 0 };
1836	nvlist_t *zplprops = NULL;
1837	struct mnttab mnt;
1838	char *mntopt_on = NULL;
1839	char *mntopt_off = NULL;
1840	boolean_t received = zfs_is_recvd_props_mode(zhp);
1841
1842	*source = NULL;
1843
1844	switch (prop) {
1845	case ZFS_PROP_ATIME:
1846		mntopt_on = MNTOPT_ATIME;
1847		mntopt_off = MNTOPT_NOATIME;
1848		break;
1849
1850	case ZFS_PROP_DEVICES:
1851		mntopt_on = MNTOPT_DEVICES;
1852		mntopt_off = MNTOPT_NODEVICES;
1853		break;
1854
1855	case ZFS_PROP_EXEC:
1856		mntopt_on = MNTOPT_EXEC;
1857		mntopt_off = MNTOPT_NOEXEC;
1858		break;
1859
1860	case ZFS_PROP_READONLY:
1861		mntopt_on = MNTOPT_RO;
1862		mntopt_off = MNTOPT_RW;
1863		break;
1864
1865	case ZFS_PROP_SETUID:
1866		mntopt_on = MNTOPT_SETUID;
1867		mntopt_off = MNTOPT_NOSETUID;
1868		break;
1869
1870	case ZFS_PROP_XATTR:
1871		mntopt_on = MNTOPT_XATTR;
1872		mntopt_off = MNTOPT_NOXATTR;
1873		break;
1874
1875	case ZFS_PROP_NBMAND:
1876		mntopt_on = MNTOPT_NBMAND;
1877		mntopt_off = MNTOPT_NONBMAND;
1878		break;
1879	}
1880
1881	/*
1882	 * Because looking up the mount options is potentially expensive
1883	 * (iterating over all of /etc/mnttab), we defer its calculation until
1884	 * we're looking up a property which requires its presence.
1885	 */
1886	if (!zhp->zfs_mntcheck &&
1887	    (mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
1888		libzfs_handle_t *hdl = zhp->zfs_hdl;
1889		struct mnttab entry;
1890
1891		if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
1892			zhp->zfs_mntopts = zfs_strdup(hdl,
1893			    entry.mnt_mntopts);
1894			if (zhp->zfs_mntopts == NULL)
1895				return (-1);
1896		}
1897
1898		zhp->zfs_mntcheck = B_TRUE;
1899	}
1900
1901	if (zhp->zfs_mntopts == NULL)
1902		mnt.mnt_mntopts = "";
1903	else
1904		mnt.mnt_mntopts = zhp->zfs_mntopts;
1905
1906	switch (prop) {
1907	case ZFS_PROP_ATIME:
1908	case ZFS_PROP_DEVICES:
1909	case ZFS_PROP_EXEC:
1910	case ZFS_PROP_READONLY:
1911	case ZFS_PROP_SETUID:
1912	case ZFS_PROP_XATTR:
1913	case ZFS_PROP_NBMAND:
1914		*val = getprop_uint64(zhp, prop, source);
1915
1916		if (received)
1917			break;
1918
1919		if (hasmntopt(&mnt, mntopt_on) && !*val) {
1920			*val = B_TRUE;
1921			if (src)
1922				*src = ZPROP_SRC_TEMPORARY;
1923		} else if (hasmntopt(&mnt, mntopt_off) && *val) {
1924			*val = B_FALSE;
1925			if (src)
1926				*src = ZPROP_SRC_TEMPORARY;
1927		}
1928		break;
1929
1930	case ZFS_PROP_CANMOUNT:
1931	case ZFS_PROP_VOLSIZE:
1932	case ZFS_PROP_QUOTA:
1933	case ZFS_PROP_REFQUOTA:
1934	case ZFS_PROP_RESERVATION:
1935	case ZFS_PROP_REFRESERVATION:
1936	case ZFS_PROP_FILESYSTEM_LIMIT:
1937	case ZFS_PROP_SNAPSHOT_LIMIT:
1938	case ZFS_PROP_FILESYSTEM_COUNT:
1939	case ZFS_PROP_SNAPSHOT_COUNT:
1940		*val = getprop_uint64(zhp, prop, source);
1941
1942		if (*source == NULL) {
1943			/* not default, must be local */
1944			*source = zhp->zfs_name;
1945		}
1946		break;
1947
1948	case ZFS_PROP_MOUNTED:
1949		*val = (zhp->zfs_mntopts != NULL);
1950		break;
1951
1952	case ZFS_PROP_NUMCLONES:
1953		*val = zhp->zfs_dmustats.dds_num_clones;
1954		break;
1955
1956	case ZFS_PROP_VERSION:
1957	case ZFS_PROP_NORMALIZE:
1958	case ZFS_PROP_UTF8ONLY:
1959	case ZFS_PROP_CASE:
1960		if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
1961		    zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
1962			return (-1);
1963		(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1964		if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
1965			zcmd_free_nvlists(&zc);
1966			return (-1);
1967		}
1968		if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
1969		    nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
1970		    val) != 0) {
1971			zcmd_free_nvlists(&zc);
1972			return (-1);
1973		}
1974		if (zplprops)
1975			nvlist_free(zplprops);
1976		zcmd_free_nvlists(&zc);
1977		break;
1978
1979	case ZFS_PROP_INCONSISTENT:
1980		*val = zhp->zfs_dmustats.dds_inconsistent;
1981		break;
1982
1983	default:
1984		switch (zfs_prop_get_type(prop)) {
1985		case PROP_TYPE_NUMBER:
1986		case PROP_TYPE_INDEX:
1987			*val = getprop_uint64(zhp, prop, source);
1988			/*
1989			 * If we tried to use a default value for a
1990			 * readonly property, it means that it was not
1991			 * present.
1992			 */
1993			if (zfs_prop_readonly(prop) &&
1994			    *source != NULL && (*source)[0] == '\0') {
1995				*source = NULL;
1996			}
1997			break;
1998
1999		case PROP_TYPE_STRING:
2000		default:
2001			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2002			    "cannot get non-numeric property"));
2003			return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
2004			    dgettext(TEXT_DOMAIN, "internal error")));
2005		}
2006	}
2007
2008	return (0);
2009}
2010
2011/*
2012 * Calculate the source type, given the raw source string.
2013 */
2014static void
2015get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
2016    char *statbuf, size_t statlen)
2017{
2018	if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
2019		return;
2020
2021	if (source == NULL) {
2022		*srctype = ZPROP_SRC_NONE;
2023	} else if (source[0] == '\0') {
2024		*srctype = ZPROP_SRC_DEFAULT;
2025	} else if (strstr(source, ZPROP_SOURCE_VAL_RECVD) != NULL) {
2026		*srctype = ZPROP_SRC_RECEIVED;
2027	} else {
2028		if (strcmp(source, zhp->zfs_name) == 0) {
2029			*srctype = ZPROP_SRC_LOCAL;
2030		} else {
2031			(void) strlcpy(statbuf, source, statlen);
2032			*srctype = ZPROP_SRC_INHERITED;
2033		}
2034	}
2035
2036}
2037
2038int
2039zfs_prop_get_recvd(zfs_handle_t *zhp, const char *propname, char *propbuf,
2040    size_t proplen, boolean_t literal)
2041{
2042	zfs_prop_t prop;
2043	int err = 0;
2044
2045	if (zhp->zfs_recvd_props == NULL)
2046		if (get_recvd_props_ioctl(zhp) != 0)
2047			return (-1);
2048
2049	prop = zfs_name_to_prop(propname);
2050
2051	if (prop != ZPROP_INVAL) {
2052		uint64_t cookie;
2053		if (!nvlist_exists(zhp->zfs_recvd_props, propname))
2054			return (-1);
2055		zfs_set_recvd_props_mode(zhp, &cookie);
2056		err = zfs_prop_get(zhp, prop, propbuf, proplen,
2057		    NULL, NULL, 0, literal);
2058		zfs_unset_recvd_props_mode(zhp, &cookie);
2059	} else {
2060		nvlist_t *propval;
2061		char *recvdval;
2062		if (nvlist_lookup_nvlist(zhp->zfs_recvd_props,
2063		    propname, &propval) != 0)
2064			return (-1);
2065		verify(nvlist_lookup_string(propval, ZPROP_VALUE,
2066		    &recvdval) == 0);
2067		(void) strlcpy(propbuf, recvdval, proplen);
2068	}
2069
2070	return (err == 0 ? 0 : -1);
2071}
2072
2073static int
2074get_clones_string(zfs_handle_t *zhp, char *propbuf, size_t proplen)
2075{
2076	nvlist_t *value;
2077	nvpair_t *pair;
2078
2079	value = zfs_get_clones_nvl(zhp);
2080	if (value == NULL)
2081		return (-1);
2082
2083	propbuf[0] = '\0';
2084	for (pair = nvlist_next_nvpair(value, NULL); pair != NULL;
2085	    pair = nvlist_next_nvpair(value, pair)) {
2086		if (propbuf[0] != '\0')
2087			(void) strlcat(propbuf, ",", proplen);
2088		(void) strlcat(propbuf, nvpair_name(pair), proplen);
2089	}
2090
2091	return (0);
2092}
2093
2094struct get_clones_arg {
2095	uint64_t numclones;
2096	nvlist_t *value;
2097	const char *origin;
2098	char buf[ZFS_MAXNAMELEN];
2099};
2100
2101int
2102get_clones_cb(zfs_handle_t *zhp, void *arg)
2103{
2104	struct get_clones_arg *gca = arg;
2105
2106	if (gca->numclones == 0) {
2107		zfs_close(zhp);
2108		return (0);
2109	}
2110
2111	if (zfs_prop_get(zhp, ZFS_PROP_ORIGIN, gca->buf, sizeof (gca->buf),
2112	    NULL, NULL, 0, B_TRUE) != 0)
2113		goto out;
2114	if (strcmp(gca->buf, gca->origin) == 0) {
2115		fnvlist_add_boolean(gca->value, zfs_get_name(zhp));
2116		gca->numclones--;
2117	}
2118
2119out:
2120	(void) zfs_iter_children(zhp, get_clones_cb, gca);
2121	zfs_close(zhp);
2122	return (0);
2123}
2124
2125nvlist_t *
2126zfs_get_clones_nvl(zfs_handle_t *zhp)
2127{
2128	nvlist_t *nv, *value;
2129
2130	if (nvlist_lookup_nvlist(zhp->zfs_props,
2131	    zfs_prop_to_name(ZFS_PROP_CLONES), &nv) != 0) {
2132		struct get_clones_arg gca;
2133
2134		/*
2135		 * if this is a snapshot, then the kernel wasn't able
2136		 * to get the clones.  Do it by slowly iterating.
2137		 */
2138		if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT)
2139			return (NULL);
2140		if (nvlist_alloc(&nv, NV_UNIQUE_NAME, 0) != 0)
2141			return (NULL);
2142		if (nvlist_alloc(&value, NV_UNIQUE_NAME, 0) != 0) {
2143			nvlist_free(nv);
2144			return (NULL);
2145		}
2146
2147		gca.numclones = zfs_prop_get_int(zhp, ZFS_PROP_NUMCLONES);
2148		gca.value = value;
2149		gca.origin = zhp->zfs_name;
2150
2151		if (gca.numclones != 0) {
2152			zfs_handle_t *root;
2153			char pool[ZFS_MAXNAMELEN];
2154			char *cp = pool;
2155
2156			/* get the pool name */
2157			(void) strlcpy(pool, zhp->zfs_name, sizeof (pool));
2158			(void) strsep(&cp, "/@");
2159			root = zfs_open(zhp->zfs_hdl, pool,
2160			    ZFS_TYPE_FILESYSTEM);
2161
2162			(void) get_clones_cb(root, &gca);
2163		}
2164
2165		if (gca.numclones != 0 ||
2166		    nvlist_add_nvlist(nv, ZPROP_VALUE, value) != 0 ||
2167		    nvlist_add_nvlist(zhp->zfs_props,
2168		    zfs_prop_to_name(ZFS_PROP_CLONES), nv) != 0) {
2169			nvlist_free(nv);
2170			nvlist_free(value);
2171			return (NULL);
2172		}
2173		nvlist_free(nv);
2174		nvlist_free(value);
2175		verify(0 == nvlist_lookup_nvlist(zhp->zfs_props,
2176		    zfs_prop_to_name(ZFS_PROP_CLONES), &nv));
2177	}
2178
2179	verify(nvlist_lookup_nvlist(nv, ZPROP_VALUE, &value) == 0);
2180
2181	return (value);
2182}
2183
2184/*
2185 * Retrieve a property from the given object.  If 'literal' is specified, then
2186 * numbers are left as exact values.  Otherwise, numbers are converted to a
2187 * human-readable form.
2188 *
2189 * Returns 0 on success, or -1 on error.
2190 */
2191int
2192zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
2193    zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
2194{
2195	char *source = NULL;
2196	uint64_t val;
2197	const char *str;
2198	const char *strval;
2199	boolean_t received = zfs_is_recvd_props_mode(zhp);
2200
2201	/*
2202	 * Check to see if this property applies to our object
2203	 */
2204	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
2205		return (-1);
2206
2207	if (received && zfs_prop_readonly(prop))
2208		return (-1);
2209
2210	if (src)
2211		*src = ZPROP_SRC_NONE;
2212
2213	switch (prop) {
2214	case ZFS_PROP_CREATION:
2215		/*
2216		 * 'creation' is a time_t stored in the statistics.  We convert
2217		 * this into a string unless 'literal' is specified.
2218		 */
2219		{
2220			val = getprop_uint64(zhp, prop, &source);
2221			time_t time = (time_t)val;
2222			struct tm t;
2223
2224			if (literal ||
2225			    localtime_r(&time, &t) == NULL ||
2226			    strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
2227			    &t) == 0)
2228				(void) snprintf(propbuf, proplen, "%llu", val);
2229		}
2230		break;
2231
2232	case ZFS_PROP_MOUNTPOINT:
2233		/*
2234		 * Getting the precise mountpoint can be tricky.
2235		 *
2236		 *  - for 'none' or 'legacy', return those values.
2237		 *  - for inherited mountpoints, we want to take everything
2238		 *    after our ancestor and append it to the inherited value.
2239		 *
2240		 * If the pool has an alternate root, we want to prepend that
2241		 * root to any values we return.
2242		 */
2243
2244		str = getprop_string(zhp, prop, &source);
2245
2246		if (str[0] == '/') {
2247			char buf[MAXPATHLEN];
2248			char *root = buf;
2249			const char *relpath;
2250
2251			/*
2252			 * If we inherit the mountpoint, even from a dataset
2253			 * with a received value, the source will be the path of
2254			 * the dataset we inherit from. If source is
2255			 * ZPROP_SOURCE_VAL_RECVD, the received value is not
2256			 * inherited.
2257			 */
2258			if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2259				relpath = "";
2260			} else {
2261				relpath = zhp->zfs_name + strlen(source);
2262				if (relpath[0] == '/')
2263					relpath++;
2264			}
2265
2266			if ((zpool_get_prop(zhp->zpool_hdl,
2267			    ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL,
2268			    B_FALSE)) || (strcmp(root, "-") == 0))
2269				root[0] = '\0';
2270			/*
2271			 * Special case an alternate root of '/'. This will
2272			 * avoid having multiple leading slashes in the
2273			 * mountpoint path.
2274			 */
2275			if (strcmp(root, "/") == 0)
2276				root++;
2277
2278			/*
2279			 * If the mountpoint is '/' then skip over this
2280			 * if we are obtaining either an alternate root or
2281			 * an inherited mountpoint.
2282			 */
2283			if (str[1] == '\0' && (root[0] != '\0' ||
2284			    relpath[0] != '\0'))
2285				str++;
2286
2287			if (relpath[0] == '\0')
2288				(void) snprintf(propbuf, proplen, "%s%s",
2289				    root, str);
2290			else
2291				(void) snprintf(propbuf, proplen, "%s%s%s%s",
2292				    root, str, relpath[0] == '@' ? "" : "/",
2293				    relpath);
2294		} else {
2295			/* 'legacy' or 'none' */
2296			(void) strlcpy(propbuf, str, proplen);
2297		}
2298
2299		break;
2300
2301	case ZFS_PROP_ORIGIN:
2302		str = getprop_string(zhp, prop, &source);
2303		if (str == NULL)
2304			return (-1);
2305		(void) strlcpy(propbuf, str, proplen);
2306		break;
2307
2308	case ZFS_PROP_CLONES:
2309		if (get_clones_string(zhp, propbuf, proplen) != 0)
2310			return (-1);
2311		break;
2312
2313	case ZFS_PROP_QUOTA:
2314	case ZFS_PROP_REFQUOTA:
2315	case ZFS_PROP_RESERVATION:
2316	case ZFS_PROP_REFRESERVATION:
2317
2318		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2319			return (-1);
2320
2321		/*
2322		 * If quota or reservation is 0, we translate this into 'none'
2323		 * (unless literal is set), and indicate that it's the default
2324		 * value.  Otherwise, we print the number nicely and indicate
2325		 * that its set locally.
2326		 */
2327		if (val == 0) {
2328			if (literal)
2329				(void) strlcpy(propbuf, "0", proplen);
2330			else
2331				(void) strlcpy(propbuf, "none", proplen);
2332		} else {
2333			if (literal)
2334				(void) snprintf(propbuf, proplen, "%llu",
2335				    (u_longlong_t)val);
2336			else
2337				zfs_nicenum(val, propbuf, proplen);
2338		}
2339		break;
2340
2341	case ZFS_PROP_FILESYSTEM_LIMIT:
2342	case ZFS_PROP_SNAPSHOT_LIMIT:
2343	case ZFS_PROP_FILESYSTEM_COUNT:
2344	case ZFS_PROP_SNAPSHOT_COUNT:
2345
2346		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2347			return (-1);
2348
2349		/*
2350		 * If limit is UINT64_MAX, we translate this into 'none' (unless
2351		 * literal is set), and indicate that it's the default value.
2352		 * Otherwise, we print the number nicely and indicate that it's
2353		 * set locally.
2354		 */
2355		if (literal) {
2356			(void) snprintf(propbuf, proplen, "%llu",
2357			    (u_longlong_t)val);
2358		} else if (val == UINT64_MAX) {
2359			(void) strlcpy(propbuf, "none", proplen);
2360		} else {
2361			zfs_nicenum(val, propbuf, proplen);
2362		}
2363		break;
2364
2365	case ZFS_PROP_REFRATIO:
2366	case ZFS_PROP_COMPRESSRATIO:
2367		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2368			return (-1);
2369		(void) snprintf(propbuf, proplen, "%llu.%02llux",
2370		    (u_longlong_t)(val / 100),
2371		    (u_longlong_t)(val % 100));
2372		break;
2373
2374	case ZFS_PROP_TYPE:
2375		switch (zhp->zfs_type) {
2376		case ZFS_TYPE_FILESYSTEM:
2377			str = "filesystem";
2378			break;
2379		case ZFS_TYPE_VOLUME:
2380			str = "volume";
2381			break;
2382		case ZFS_TYPE_SNAPSHOT:
2383			str = "snapshot";
2384			break;
2385		case ZFS_TYPE_BOOKMARK:
2386			str = "bookmark";
2387			break;
2388		default:
2389			abort();
2390		}
2391		(void) snprintf(propbuf, proplen, "%s", str);
2392		break;
2393
2394	case ZFS_PROP_MOUNTED:
2395		/*
2396		 * The 'mounted' property is a pseudo-property that described
2397		 * whether the filesystem is currently mounted.  Even though
2398		 * it's a boolean value, the typical values of "on" and "off"
2399		 * don't make sense, so we translate to "yes" and "no".
2400		 */
2401		if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
2402		    src, &source, &val) != 0)
2403			return (-1);
2404		if (val)
2405			(void) strlcpy(propbuf, "yes", proplen);
2406		else
2407			(void) strlcpy(propbuf, "no", proplen);
2408		break;
2409
2410	case ZFS_PROP_NAME:
2411		/*
2412		 * The 'name' property is a pseudo-property derived from the
2413		 * dataset name.  It is presented as a real property to simplify
2414		 * consumers.
2415		 */
2416		(void) strlcpy(propbuf, zhp->zfs_name, proplen);
2417		break;
2418
2419	case ZFS_PROP_MLSLABEL:
2420		{
2421#ifdef sun
2422			m_label_t *new_sl = NULL;
2423			char *ascii = NULL;	/* human readable label */
2424
2425			(void) strlcpy(propbuf,
2426			    getprop_string(zhp, prop, &source), proplen);
2427
2428			if (literal || (strcasecmp(propbuf,
2429			    ZFS_MLSLABEL_DEFAULT) == 0))
2430				break;
2431
2432			/*
2433			 * Try to translate the internal hex string to
2434			 * human-readable output.  If there are any
2435			 * problems just use the hex string.
2436			 */
2437
2438			if (str_to_label(propbuf, &new_sl, MAC_LABEL,
2439			    L_NO_CORRECTION, NULL) == -1) {
2440				m_label_free(new_sl);
2441				break;
2442			}
2443
2444			if (label_to_str(new_sl, &ascii, M_LABEL,
2445			    DEF_NAMES) != 0) {
2446				if (ascii)
2447					free(ascii);
2448				m_label_free(new_sl);
2449				break;
2450			}
2451			m_label_free(new_sl);
2452
2453			(void) strlcpy(propbuf, ascii, proplen);
2454			free(ascii);
2455#else	/* !sun */
2456			propbuf[0] = '\0';
2457#endif	/* !sun */
2458		}
2459		break;
2460
2461	case ZFS_PROP_GUID:
2462		/*
2463		 * GUIDs are stored as numbers, but they are identifiers.
2464		 * We don't want them to be pretty printed, because pretty
2465		 * printing mangles the ID into a truncated and useless value.
2466		 */
2467		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2468			return (-1);
2469		(void) snprintf(propbuf, proplen, "%llu", (u_longlong_t)val);
2470		break;
2471
2472	default:
2473		switch (zfs_prop_get_type(prop)) {
2474		case PROP_TYPE_NUMBER:
2475			if (get_numeric_property(zhp, prop, src,
2476			    &source, &val) != 0)
2477				return (-1);
2478			if (literal)
2479				(void) snprintf(propbuf, proplen, "%llu",
2480				    (u_longlong_t)val);
2481			else
2482				zfs_nicenum(val, propbuf, proplen);
2483			break;
2484
2485		case PROP_TYPE_STRING:
2486			str = getprop_string(zhp, prop, &source);
2487			if (str == NULL)
2488				return (-1);
2489			(void) strlcpy(propbuf, str, proplen);
2490			break;
2491
2492		case PROP_TYPE_INDEX:
2493			if (get_numeric_property(zhp, prop, src,
2494			    &source, &val) != 0)
2495				return (-1);
2496			if (zfs_prop_index_to_string(prop, val, &strval) != 0)
2497				return (-1);
2498			(void) strlcpy(propbuf, strval, proplen);
2499			break;
2500
2501		default:
2502			abort();
2503		}
2504	}
2505
2506	get_source(zhp, src, source, statbuf, statlen);
2507
2508	return (0);
2509}
2510
2511/*
2512 * Utility function to get the given numeric property.  Does no validation that
2513 * the given property is the appropriate type; should only be used with
2514 * hard-coded property types.
2515 */
2516uint64_t
2517zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
2518{
2519	char *source;
2520	uint64_t val;
2521
2522	(void) get_numeric_property(zhp, prop, NULL, &source, &val);
2523
2524	return (val);
2525}
2526
2527int
2528zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
2529{
2530	char buf[64];
2531
2532	(void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
2533	return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
2534}
2535
2536/*
2537 * Similar to zfs_prop_get(), but returns the value as an integer.
2538 */
2539int
2540zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
2541    zprop_source_t *src, char *statbuf, size_t statlen)
2542{
2543	char *source;
2544
2545	/*
2546	 * Check to see if this property applies to our object
2547	 */
2548	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
2549		return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
2550		    dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
2551		    zfs_prop_to_name(prop)));
2552	}
2553
2554	if (src)
2555		*src = ZPROP_SRC_NONE;
2556
2557	if (get_numeric_property(zhp, prop, src, &source, value) != 0)
2558		return (-1);
2559
2560	get_source(zhp, src, source, statbuf, statlen);
2561
2562	return (0);
2563}
2564
2565static int
2566idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
2567    char **domainp, idmap_rid_t *ridp)
2568{
2569#ifdef sun
2570	idmap_get_handle_t *get_hdl = NULL;
2571	idmap_stat status;
2572	int err = EINVAL;
2573
2574	if (idmap_get_create(&get_hdl) != IDMAP_SUCCESS)
2575		goto out;
2576
2577	if (isuser) {
2578		err = idmap_get_sidbyuid(get_hdl, id,
2579		    IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2580	} else {
2581		err = idmap_get_sidbygid(get_hdl, id,
2582		    IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
2583	}
2584	if (err == IDMAP_SUCCESS &&
2585	    idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
2586	    status == IDMAP_SUCCESS)
2587		err = 0;
2588	else
2589		err = EINVAL;
2590out:
2591	if (get_hdl)
2592		idmap_get_destroy(get_hdl);
2593	return (err);
2594#else	/* !sun */
2595	assert(!"invalid code path");
2596	return (EINVAL); // silence compiler warning
2597#endif	/* !sun */
2598}
2599
2600/*
2601 * convert the propname into parameters needed by kernel
2602 * Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
2603 * Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
2604 */
2605static int
2606userquota_propname_decode(const char *propname, boolean_t zoned,
2607    zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
2608{
2609	zfs_userquota_prop_t type;
2610	char *cp, *end;
2611	char *numericsid = NULL;
2612	boolean_t isuser;
2613
2614	domain[0] = '\0';
2615	*ridp = 0;
2616	/* Figure out the property type ({user|group}{quota|space}) */
2617	for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
2618		if (strncmp(propname, zfs_userquota_prop_prefixes[type],
2619		    strlen(zfs_userquota_prop_prefixes[type])) == 0)
2620			break;
2621	}
2622	if (type == ZFS_NUM_USERQUOTA_PROPS)
2623		return (EINVAL);
2624	*typep = type;
2625
2626	isuser = (type == ZFS_PROP_USERQUOTA ||
2627	    type == ZFS_PROP_USERUSED);
2628
2629	cp = strchr(propname, '@') + 1;
2630
2631	if (strchr(cp, '@')) {
2632#ifdef sun
2633		/*
2634		 * It's a SID name (eg "user@domain") that needs to be
2635		 * turned into S-1-domainID-RID.
2636		 */
2637		int flag = 0;
2638		idmap_stat stat, map_stat;
2639		uid_t pid;
2640		idmap_rid_t rid;
2641		idmap_get_handle_t *gh = NULL;
2642
2643		stat = idmap_get_create(&gh);
2644		if (stat != IDMAP_SUCCESS) {
2645			idmap_get_destroy(gh);
2646			return (ENOMEM);
2647		}
2648		if (zoned && getzoneid() == GLOBAL_ZONEID)
2649			return (ENOENT);
2650		if (isuser) {
2651			stat = idmap_getuidbywinname(cp, NULL, flag, &pid);
2652			if (stat < 0)
2653				return (ENOENT);
2654			stat = idmap_get_sidbyuid(gh, pid, flag, &numericsid,
2655			    &rid, &map_stat);
2656		} else {
2657			stat = idmap_getgidbywinname(cp, NULL, flag, &pid);
2658			if (stat < 0)
2659				return (ENOENT);
2660			stat = idmap_get_sidbygid(gh, pid, flag, &numericsid,
2661			    &rid, &map_stat);
2662		}
2663		if (stat < 0) {
2664			idmap_get_destroy(gh);
2665			return (ENOENT);
2666		}
2667		stat = idmap_get_mappings(gh);
2668		idmap_get_destroy(gh);
2669
2670		if (stat < 0) {
2671			return (ENOENT);
2672		}
2673		if (numericsid == NULL)
2674			return (ENOENT);
2675		cp = numericsid;
2676		*ridp = rid;
2677		/* will be further decoded below */
2678#else	/* !sun */
2679		return (ENOENT);
2680#endif	/* !sun */
2681	}
2682
2683	if (strncmp(cp, "S-1-", 4) == 0) {
2684		/* It's a numeric SID (eg "S-1-234-567-89") */
2685		(void) strlcpy(domain, cp, domainlen);
2686		errno = 0;
2687		if (*ridp == 0) {
2688			cp = strrchr(domain, '-');
2689			*cp = '\0';
2690			cp++;
2691			*ridp = strtoull(cp, &end, 10);
2692		} else {
2693			end = "";
2694		}
2695		if (numericsid) {
2696			free(numericsid);
2697			numericsid = NULL;
2698		}
2699		if (errno != 0 || *end != '\0')
2700			return (EINVAL);
2701	} else if (!isdigit(*cp)) {
2702		/*
2703		 * It's a user/group name (eg "user") that needs to be
2704		 * turned into a uid/gid
2705		 */
2706		if (zoned && getzoneid() == GLOBAL_ZONEID)
2707			return (ENOENT);
2708		if (isuser) {
2709			struct passwd *pw;
2710			pw = getpwnam(cp);
2711			if (pw == NULL)
2712				return (ENOENT);
2713			*ridp = pw->pw_uid;
2714		} else {
2715			struct group *gr;
2716			gr = getgrnam(cp);
2717			if (gr == NULL)
2718				return (ENOENT);
2719			*ridp = gr->gr_gid;
2720		}
2721	} else {
2722		/* It's a user/group ID (eg "12345"). */
2723		uid_t id = strtoul(cp, &end, 10);
2724		idmap_rid_t rid;
2725		char *mapdomain;
2726
2727		if (*end != '\0')
2728			return (EINVAL);
2729		if (id > MAXUID) {
2730			/* It's an ephemeral ID. */
2731			if (idmap_id_to_numeric_domain_rid(id, isuser,
2732			    &mapdomain, &rid) != 0)
2733				return (ENOENT);
2734			(void) strlcpy(domain, mapdomain, domainlen);
2735			*ridp = rid;
2736		} else {
2737			*ridp = id;
2738		}
2739	}
2740
2741	ASSERT3P(numericsid, ==, NULL);
2742	return (0);
2743}
2744
2745static int
2746zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
2747    uint64_t *propvalue, zfs_userquota_prop_t *typep)
2748{
2749	int err;
2750	zfs_cmd_t zc = { 0 };
2751
2752	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2753
2754	err = userquota_propname_decode(propname,
2755	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
2756	    typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
2757	zc.zc_objset_type = *typep;
2758	if (err)
2759		return (err);
2760
2761	err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
2762	if (err)
2763		return (err);
2764
2765	*propvalue = zc.zc_cookie;
2766	return (0);
2767}
2768
2769int
2770zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
2771    uint64_t *propvalue)
2772{
2773	zfs_userquota_prop_t type;
2774
2775	return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
2776	    &type));
2777}
2778
2779int
2780zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
2781    char *propbuf, int proplen, boolean_t literal)
2782{
2783	int err;
2784	uint64_t propvalue;
2785	zfs_userquota_prop_t type;
2786
2787	err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
2788	    &type);
2789
2790	if (err)
2791		return (err);
2792
2793	if (literal) {
2794		(void) snprintf(propbuf, proplen, "%llu", propvalue);
2795	} else if (propvalue == 0 &&
2796	    (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA)) {
2797		(void) strlcpy(propbuf, "none", proplen);
2798	} else {
2799		zfs_nicenum(propvalue, propbuf, proplen);
2800	}
2801	return (0);
2802}
2803
2804int
2805zfs_prop_get_written_int(zfs_handle_t *zhp, const char *propname,
2806    uint64_t *propvalue)
2807{
2808	int err;
2809	zfs_cmd_t zc = { 0 };
2810	const char *snapname;
2811
2812	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2813
2814	snapname = strchr(propname, '@') + 1;
2815	if (strchr(snapname, '@')) {
2816		(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
2817	} else {
2818		/* snapname is the short name, append it to zhp's fsname */
2819		char *cp;
2820
2821		(void) strlcpy(zc.zc_value, zhp->zfs_name,
2822		    sizeof (zc.zc_value));
2823		cp = strchr(zc.zc_value, '@');
2824		if (cp != NULL)
2825			*cp = '\0';
2826		(void) strlcat(zc.zc_value, "@", sizeof (zc.zc_value));
2827		(void) strlcat(zc.zc_value, snapname, sizeof (zc.zc_value));
2828	}
2829
2830	err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_WRITTEN, &zc);
2831	if (err)
2832		return (err);
2833
2834	*propvalue = zc.zc_cookie;
2835	return (0);
2836}
2837
2838int
2839zfs_prop_get_written(zfs_handle_t *zhp, const char *propname,
2840    char *propbuf, int proplen, boolean_t literal)
2841{
2842	int err;
2843	uint64_t propvalue;
2844
2845	err = zfs_prop_get_written_int(zhp, propname, &propvalue);
2846
2847	if (err)
2848		return (err);
2849
2850	if (literal) {
2851		(void) snprintf(propbuf, proplen, "%llu", propvalue);
2852	} else {
2853		zfs_nicenum(propvalue, propbuf, proplen);
2854	}
2855	return (0);
2856}
2857
2858/*
2859 * Returns the name of the given zfs handle.
2860 */
2861const char *
2862zfs_get_name(const zfs_handle_t *zhp)
2863{
2864	return (zhp->zfs_name);
2865}
2866
2867/*
2868 * Returns the type of the given zfs handle.
2869 */
2870zfs_type_t
2871zfs_get_type(const zfs_handle_t *zhp)
2872{
2873	return (zhp->zfs_type);
2874}
2875
2876/*
2877 * Is one dataset name a child dataset of another?
2878 *
2879 * Needs to handle these cases:
2880 * Dataset 1	"a/foo"		"a/foo"		"a/foo"		"a/foo"
2881 * Dataset 2	"a/fo"		"a/foobar"	"a/bar/baz"	"a/foo/bar"
2882 * Descendant?	No.		No.		No.		Yes.
2883 */
2884static boolean_t
2885is_descendant(const char *ds1, const char *ds2)
2886{
2887	size_t d1len = strlen(ds1);
2888
2889	/* ds2 can't be a descendant if it's smaller */
2890	if (strlen(ds2) < d1len)
2891		return (B_FALSE);
2892
2893	/* otherwise, compare strings and verify that there's a '/' char */
2894	return (ds2[d1len] == '/' && (strncmp(ds1, ds2, d1len) == 0));
2895}
2896
2897/*
2898 * Given a complete name, return just the portion that refers to the parent.
2899 * Will return -1 if there is no parent (path is just the name of the
2900 * pool).
2901 */
2902static int
2903parent_name(const char *path, char *buf, size_t buflen)
2904{
2905	char *slashp;
2906
2907	(void) strlcpy(buf, path, buflen);
2908
2909	if ((slashp = strrchr(buf, '/')) == NULL)
2910		return (-1);
2911	*slashp = '\0';
2912
2913	return (0);
2914}
2915
2916/*
2917 * If accept_ancestor is false, then check to make sure that the given path has
2918 * a parent, and that it exists.  If accept_ancestor is true, then find the
2919 * closest existing ancestor for the given path.  In prefixlen return the
2920 * length of already existing prefix of the given path.  We also fetch the
2921 * 'zoned' property, which is used to validate property settings when creating
2922 * new datasets.
2923 */
2924static int
2925check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
2926    boolean_t accept_ancestor, int *prefixlen)
2927{
2928	zfs_cmd_t zc = { 0 };
2929	char parent[ZFS_MAXNAMELEN];
2930	char *slash;
2931	zfs_handle_t *zhp;
2932	char errbuf[1024];
2933	uint64_t is_zoned;
2934
2935	(void) snprintf(errbuf, sizeof (errbuf),
2936	    dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
2937
2938	/* get parent, and check to see if this is just a pool */
2939	if (parent_name(path, parent, sizeof (parent)) != 0) {
2940		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2941		    "missing dataset name"));
2942		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2943	}
2944
2945	/* check to see if the pool exists */
2946	if ((slash = strchr(parent, '/')) == NULL)
2947		slash = parent + strlen(parent);
2948	(void) strncpy(zc.zc_name, parent, slash - parent);
2949	zc.zc_name[slash - parent] = '\0';
2950	if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
2951	    errno == ENOENT) {
2952		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2953		    "no such pool '%s'"), zc.zc_name);
2954		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2955	}
2956
2957	/* check to see if the parent dataset exists */
2958	while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
2959		if (errno == ENOENT && accept_ancestor) {
2960			/*
2961			 * Go deeper to find an ancestor, give up on top level.
2962			 */
2963			if (parent_name(parent, parent, sizeof (parent)) != 0) {
2964				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2965				    "no such pool '%s'"), zc.zc_name);
2966				return (zfs_error(hdl, EZFS_NOENT, errbuf));
2967			}
2968		} else if (errno == ENOENT) {
2969			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2970			    "parent does not exist"));
2971			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2972		} else
2973			return (zfs_standard_error(hdl, errno, errbuf));
2974	}
2975
2976	is_zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2977	if (zoned != NULL)
2978		*zoned = is_zoned;
2979
2980	/* we are in a non-global zone, but parent is in the global zone */
2981	if (getzoneid() != GLOBAL_ZONEID && !is_zoned) {
2982		(void) zfs_standard_error(hdl, EPERM, errbuf);
2983		zfs_close(zhp);
2984		return (-1);
2985	}
2986
2987	/* make sure parent is a filesystem */
2988	if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
2989		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2990		    "parent is not a filesystem"));
2991		(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
2992		zfs_close(zhp);
2993		return (-1);
2994	}
2995
2996	zfs_close(zhp);
2997	if (prefixlen != NULL)
2998		*prefixlen = strlen(parent);
2999	return (0);
3000}
3001
3002/*
3003 * Finds whether the dataset of the given type(s) exists.
3004 */
3005boolean_t
3006zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
3007{
3008	zfs_handle_t *zhp;
3009
3010	if (!zfs_validate_name(hdl, path, types, B_FALSE))
3011		return (B_FALSE);
3012
3013	/*
3014	 * Try to get stats for the dataset, which will tell us if it exists.
3015	 */
3016	if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
3017		int ds_type = zhp->zfs_type;
3018
3019		zfs_close(zhp);
3020		if (types & ds_type)
3021			return (B_TRUE);
3022	}
3023	return (B_FALSE);
3024}
3025
3026/*
3027 * Given a path to 'target', create all the ancestors between
3028 * the prefixlen portion of the path, and the target itself.
3029 * Fail if the initial prefixlen-ancestor does not already exist.
3030 */
3031int
3032create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
3033{
3034	zfs_handle_t *h;
3035	char *cp;
3036	const char *opname;
3037
3038	/* make sure prefix exists */
3039	cp = target + prefixlen;
3040	if (*cp != '/') {
3041		assert(strchr(cp, '/') == NULL);
3042		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3043	} else {
3044		*cp = '\0';
3045		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3046		*cp = '/';
3047	}
3048	if (h == NULL)
3049		return (-1);
3050	zfs_close(h);
3051
3052	/*
3053	 * Attempt to create, mount, and share any ancestor filesystems,
3054	 * up to the prefixlen-long one.
3055	 */
3056	for (cp = target + prefixlen + 1;
3057	    cp = strchr(cp, '/'); *cp = '/', cp++) {
3058
3059		*cp = '\0';
3060
3061		h = make_dataset_handle(hdl, target);
3062		if (h) {
3063			/* it already exists, nothing to do here */
3064			zfs_close(h);
3065			continue;
3066		}
3067
3068		if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
3069		    NULL) != 0) {
3070			opname = dgettext(TEXT_DOMAIN, "create");
3071			goto ancestorerr;
3072		}
3073
3074		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3075		if (h == NULL) {
3076			opname = dgettext(TEXT_DOMAIN, "open");
3077			goto ancestorerr;
3078		}
3079
3080		if (zfs_mount(h, NULL, 0) != 0) {
3081			opname = dgettext(TEXT_DOMAIN, "mount");
3082			goto ancestorerr;
3083		}
3084
3085		if (zfs_share(h) != 0) {
3086			opname = dgettext(TEXT_DOMAIN, "share");
3087			goto ancestorerr;
3088		}
3089
3090		zfs_close(h);
3091	}
3092
3093	return (0);
3094
3095ancestorerr:
3096	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3097	    "failed to %s ancestor '%s'"), opname, target);
3098	return (-1);
3099}
3100
3101/*
3102 * Creates non-existing ancestors of the given path.
3103 */
3104int
3105zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
3106{
3107	int prefix;
3108	char *path_copy;
3109	int rc;
3110
3111	if (check_parents(hdl, path, NULL, B_TRUE, &prefix) != 0)
3112		return (-1);
3113
3114	if ((path_copy = strdup(path)) != NULL) {
3115		rc = create_parents(hdl, path_copy, prefix);
3116		free(path_copy);
3117	}
3118	if (path_copy == NULL || rc != 0)
3119		return (-1);
3120
3121	return (0);
3122}
3123
3124/*
3125 * Create a new filesystem or volume.
3126 */
3127int
3128zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
3129    nvlist_t *props)
3130{
3131	int ret;
3132	uint64_t size = 0;
3133	uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
3134	char errbuf[1024];
3135	uint64_t zoned;
3136	dmu_objset_type_t ost;
3137
3138	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3139	    "cannot create '%s'"), path);
3140
3141	/* validate the path, taking care to note the extended error message */
3142	if (!zfs_validate_name(hdl, path, type, B_TRUE))
3143		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3144
3145	/* validate parents exist */
3146	if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
3147		return (-1);
3148
3149	/*
3150	 * The failure modes when creating a dataset of a different type over
3151	 * one that already exists is a little strange.  In particular, if you
3152	 * try to create a dataset on top of an existing dataset, the ioctl()
3153	 * will return ENOENT, not EEXIST.  To prevent this from happening, we
3154	 * first try to see if the dataset exists.
3155	 */
3156	if (zfs_dataset_exists(hdl, path, ZFS_TYPE_DATASET)) {
3157		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3158		    "dataset already exists"));
3159		return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3160	}
3161
3162	if (type == ZFS_TYPE_VOLUME)
3163		ost = DMU_OST_ZVOL;
3164	else
3165		ost = DMU_OST_ZFS;
3166
3167	if (props && (props = zfs_valid_proplist(hdl, type, props,
3168	    zoned, NULL, errbuf)) == 0)
3169		return (-1);
3170
3171	if (type == ZFS_TYPE_VOLUME) {
3172		/*
3173		 * If we are creating a volume, the size and block size must
3174		 * satisfy a few restraints.  First, the blocksize must be a
3175		 * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
3176		 * volsize must be a multiple of the block size, and cannot be
3177		 * zero.
3178		 */
3179		if (props == NULL || nvlist_lookup_uint64(props,
3180		    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
3181			nvlist_free(props);
3182			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3183			    "missing volume size"));
3184			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3185		}
3186
3187		if ((ret = nvlist_lookup_uint64(props,
3188		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3189		    &blocksize)) != 0) {
3190			if (ret == ENOENT) {
3191				blocksize = zfs_prop_default_numeric(
3192				    ZFS_PROP_VOLBLOCKSIZE);
3193			} else {
3194				nvlist_free(props);
3195				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3196				    "missing volume block size"));
3197				return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3198			}
3199		}
3200
3201		if (size == 0) {
3202			nvlist_free(props);
3203			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3204			    "volume size cannot be zero"));
3205			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3206		}
3207
3208		if (size % blocksize != 0) {
3209			nvlist_free(props);
3210			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3211			    "volume size must be a multiple of volume block "
3212			    "size"));
3213			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3214		}
3215	}
3216
3217	/* create the dataset */
3218	ret = lzc_create(path, ost, props);
3219	nvlist_free(props);
3220
3221	/* check for failure */
3222	if (ret != 0) {
3223		char parent[ZFS_MAXNAMELEN];
3224		(void) parent_name(path, parent, sizeof (parent));
3225
3226		switch (errno) {
3227		case ENOENT:
3228			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3229			    "no such parent '%s'"), parent);
3230			return (zfs_error(hdl, EZFS_NOENT, errbuf));
3231
3232		case EINVAL:
3233			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3234			    "parent '%s' is not a filesystem"), parent);
3235			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3236
3237		case EDOM:
3238			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3239			    "volume block size must be power of 2 from "
3240			    "512B to 128KB"));
3241
3242			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3243
3244		case ENOTSUP:
3245			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3246			    "pool must be upgraded to set this "
3247			    "property or value"));
3248			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3249#ifdef _ILP32
3250		case EOVERFLOW:
3251			/*
3252			 * This platform can't address a volume this big.
3253			 */
3254			if (type == ZFS_TYPE_VOLUME)
3255				return (zfs_error(hdl, EZFS_VOLTOOBIG,
3256				    errbuf));
3257#endif
3258			/* FALLTHROUGH */
3259		default:
3260			return (zfs_standard_error(hdl, errno, errbuf));
3261		}
3262	}
3263
3264	return (0);
3265}
3266
3267/*
3268 * Destroys the given dataset.  The caller must make sure that the filesystem
3269 * isn't mounted, and that there are no active dependents. If the file system
3270 * does not exist this function does nothing.
3271 */
3272int
3273zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
3274{
3275	zfs_cmd_t zc = { 0 };
3276
3277	if (zhp->zfs_type == ZFS_TYPE_BOOKMARK) {
3278		nvlist_t *nv = fnvlist_alloc();
3279		fnvlist_add_boolean(nv, zhp->zfs_name);
3280		int error = lzc_destroy_bookmarks(nv, NULL);
3281		fnvlist_free(nv);
3282		if (error != 0) {
3283			return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3284			    dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3285			    zhp->zfs_name));
3286		}
3287		return (0);
3288	}
3289
3290	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3291
3292	if (ZFS_IS_VOLUME(zhp)) {
3293		zc.zc_objset_type = DMU_OST_ZVOL;
3294	} else {
3295		zc.zc_objset_type = DMU_OST_ZFS;
3296	}
3297
3298	zc.zc_defer_destroy = defer;
3299	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY, &zc) != 0 &&
3300	    errno != ENOENT) {
3301		return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3302		    dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3303		    zhp->zfs_name));
3304	}
3305
3306	remove_mountpoint(zhp);
3307
3308	return (0);
3309}
3310
3311struct destroydata {
3312	nvlist_t *nvl;
3313	const char *snapname;
3314};
3315
3316static int
3317zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
3318{
3319	struct destroydata *dd = arg;
3320	char name[ZFS_MAXNAMELEN];
3321	int rv = 0;
3322
3323	(void) snprintf(name, sizeof (name),
3324	    "%s@%s", zhp->zfs_name, dd->snapname);
3325
3326	if (lzc_exists(name))
3327		verify(nvlist_add_boolean(dd->nvl, name) == 0);
3328
3329	rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, dd);
3330	zfs_close(zhp);
3331	return (rv);
3332}
3333
3334/*
3335 * Destroys all snapshots with the given name in zhp & descendants.
3336 */
3337int
3338zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
3339{
3340	int ret;
3341	struct destroydata dd = { 0 };
3342
3343	dd.snapname = snapname;
3344	verify(nvlist_alloc(&dd.nvl, NV_UNIQUE_NAME, 0) == 0);
3345	(void) zfs_check_snap_cb(zfs_handle_dup(zhp), &dd);
3346
3347	if (nvlist_empty(dd.nvl)) {
3348		ret = zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
3349		    dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
3350		    zhp->zfs_name, snapname);
3351	} else {
3352		ret = zfs_destroy_snaps_nvl(zhp->zfs_hdl, dd.nvl, defer);
3353	}
3354	nvlist_free(dd.nvl);
3355	return (ret);
3356}
3357
3358/*
3359 * Destroys all the snapshots named in the nvlist.
3360 */
3361int
3362zfs_destroy_snaps_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, boolean_t defer)
3363{
3364	int ret;
3365	nvlist_t *errlist;
3366
3367	ret = lzc_destroy_snaps(snaps, defer, &errlist);
3368
3369	if (ret == 0)
3370		return (0);
3371
3372	if (nvlist_empty(errlist)) {
3373		char errbuf[1024];
3374		(void) snprintf(errbuf, sizeof (errbuf),
3375		    dgettext(TEXT_DOMAIN, "cannot destroy snapshots"));
3376
3377		ret = zfs_standard_error(hdl, ret, errbuf);
3378	}
3379	for (nvpair_t *pair = nvlist_next_nvpair(errlist, NULL);
3380	    pair != NULL; pair = nvlist_next_nvpair(errlist, pair)) {
3381		char errbuf[1024];
3382		(void) snprintf(errbuf, sizeof (errbuf),
3383		    dgettext(TEXT_DOMAIN, "cannot destroy snapshot %s"),
3384		    nvpair_name(pair));
3385
3386		switch (fnvpair_value_int32(pair)) {
3387		case EEXIST:
3388			zfs_error_aux(hdl,
3389			    dgettext(TEXT_DOMAIN, "snapshot is cloned"));
3390			ret = zfs_error(hdl, EZFS_EXISTS, errbuf);
3391			break;
3392		default:
3393			ret = zfs_standard_error(hdl, errno, errbuf);
3394			break;
3395		}
3396	}
3397
3398	return (ret);
3399}
3400
3401/*
3402 * Clones the given dataset.  The target must be of the same type as the source.
3403 */
3404int
3405zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
3406{
3407	char parent[ZFS_MAXNAMELEN];
3408	int ret;
3409	char errbuf[1024];
3410	libzfs_handle_t *hdl = zhp->zfs_hdl;
3411	uint64_t zoned;
3412
3413	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
3414
3415	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3416	    "cannot create '%s'"), target);
3417
3418	/* validate the target/clone name */
3419	if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
3420		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3421
3422	/* validate parents exist */
3423	if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
3424		return (-1);
3425
3426	(void) parent_name(target, parent, sizeof (parent));
3427
3428	/* do the clone */
3429
3430	if (props) {
3431		zfs_type_t type;
3432		if (ZFS_IS_VOLUME(zhp)) {
3433			type = ZFS_TYPE_VOLUME;
3434		} else {
3435			type = ZFS_TYPE_FILESYSTEM;
3436		}
3437		if ((props = zfs_valid_proplist(hdl, type, props, zoned,
3438		    zhp, errbuf)) == NULL)
3439			return (-1);
3440	}
3441
3442	ret = lzc_clone(target, zhp->zfs_name, props);
3443	nvlist_free(props);
3444
3445	if (ret != 0) {
3446		switch (errno) {
3447
3448		case ENOENT:
3449			/*
3450			 * The parent doesn't exist.  We should have caught this
3451			 * above, but there may a race condition that has since
3452			 * destroyed the parent.
3453			 *
3454			 * At this point, we don't know whether it's the source
3455			 * that doesn't exist anymore, or whether the target
3456			 * dataset doesn't exist.
3457			 */
3458			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3459			    "no such parent '%s'"), parent);
3460			return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
3461
3462		case EXDEV:
3463			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3464			    "source and target pools differ"));
3465			return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
3466			    errbuf));
3467
3468		default:
3469			return (zfs_standard_error(zhp->zfs_hdl, errno,
3470			    errbuf));
3471		}
3472	}
3473
3474	return (ret);
3475}
3476
3477/*
3478 * Promotes the given clone fs to be the clone parent.
3479 */
3480int
3481zfs_promote(zfs_handle_t *zhp)
3482{
3483	libzfs_handle_t *hdl = zhp->zfs_hdl;
3484	zfs_cmd_t zc = { 0 };
3485	char parent[MAXPATHLEN];
3486	int ret;
3487	char errbuf[1024];
3488
3489	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3490	    "cannot promote '%s'"), zhp->zfs_name);
3491
3492	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3493		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3494		    "snapshots can not be promoted"));
3495		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3496	}
3497
3498	(void) strlcpy(parent, zhp->zfs_dmustats.dds_origin, sizeof (parent));
3499	if (parent[0] == '\0') {
3500		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3501		    "not a cloned filesystem"));
3502		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3503	}
3504
3505	(void) strlcpy(zc.zc_value, zhp->zfs_dmustats.dds_origin,
3506	    sizeof (zc.zc_value));
3507	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3508	ret = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
3509
3510	if (ret != 0) {
3511		int save_errno = errno;
3512
3513		switch (save_errno) {
3514		case EEXIST:
3515			/* There is a conflicting snapshot name. */
3516			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3517			    "conflicting snapshot '%s' from parent '%s'"),
3518			    zc.zc_string, parent);
3519			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3520
3521		default:
3522			return (zfs_standard_error(hdl, save_errno, errbuf));
3523		}
3524	}
3525	return (ret);
3526}
3527
3528typedef struct snapdata {
3529	nvlist_t *sd_nvl;
3530	const char *sd_snapname;
3531} snapdata_t;
3532
3533static int
3534zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3535{
3536	snapdata_t *sd = arg;
3537	char name[ZFS_MAXNAMELEN];
3538	int rv = 0;
3539
3540	if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) == 0) {
3541		(void) snprintf(name, sizeof (name),
3542		    "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3543
3544		fnvlist_add_boolean(sd->sd_nvl, name);
3545
3546		rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3547	}
3548	zfs_close(zhp);
3549
3550	return (rv);
3551}
3552
3553/*
3554 * Creates snapshots.  The keys in the snaps nvlist are the snapshots to be
3555 * created.
3556 */
3557int
3558zfs_snapshot_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, nvlist_t *props)
3559{
3560	int ret;
3561	char errbuf[1024];
3562	nvpair_t *elem;
3563	nvlist_t *errors;
3564
3565	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3566	    "cannot create snapshots "));
3567
3568	elem = NULL;
3569	while ((elem = nvlist_next_nvpair(snaps, elem)) != NULL) {
3570		const char *snapname = nvpair_name(elem);
3571
3572		/* validate the target name */
3573		if (!zfs_validate_name(hdl, snapname, ZFS_TYPE_SNAPSHOT,
3574		    B_TRUE)) {
3575			(void) snprintf(errbuf, sizeof (errbuf),
3576			    dgettext(TEXT_DOMAIN,
3577			    "cannot create snapshot '%s'"), snapname);
3578			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3579		}
3580	}
3581
3582	if (props != NULL &&
3583	    (props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
3584	    props, B_FALSE, NULL, errbuf)) == NULL) {
3585		return (-1);
3586	}
3587
3588	ret = lzc_snapshot(snaps, props, &errors);
3589
3590	if (ret != 0) {
3591		boolean_t printed = B_FALSE;
3592		for (elem = nvlist_next_nvpair(errors, NULL);
3593		    elem != NULL;
3594		    elem = nvlist_next_nvpair(errors, elem)) {
3595			(void) snprintf(errbuf, sizeof (errbuf),
3596			    dgettext(TEXT_DOMAIN,
3597			    "cannot create snapshot '%s'"), nvpair_name(elem));
3598			(void) zfs_standard_error(hdl,
3599			    fnvpair_value_int32(elem), errbuf);
3600			printed = B_TRUE;
3601		}
3602		if (!printed) {
3603			switch (ret) {
3604			case EXDEV:
3605				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3606				    "multiple snapshots of same "
3607				    "fs not allowed"));
3608				(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3609
3610				break;
3611			default:
3612				(void) zfs_standard_error(hdl, ret, errbuf);
3613			}
3614		}
3615	}
3616
3617	nvlist_free(props);
3618	nvlist_free(errors);
3619	return (ret);
3620}
3621
3622int
3623zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
3624    nvlist_t *props)
3625{
3626	int ret;
3627	snapdata_t sd = { 0 };
3628	char fsname[ZFS_MAXNAMELEN];
3629	char *cp;
3630	zfs_handle_t *zhp;
3631	char errbuf[1024];
3632
3633	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3634	    "cannot snapshot %s"), path);
3635
3636	if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
3637		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3638
3639	(void) strlcpy(fsname, path, sizeof (fsname));
3640	cp = strchr(fsname, '@');
3641	*cp = '\0';
3642	sd.sd_snapname = cp + 1;
3643
3644	if ((zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM |
3645	    ZFS_TYPE_VOLUME)) == NULL) {
3646		return (-1);
3647	}
3648
3649	verify(nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) == 0);
3650	if (recursive) {
3651		(void) zfs_snapshot_cb(zfs_handle_dup(zhp), &sd);
3652	} else {
3653		fnvlist_add_boolean(sd.sd_nvl, path);
3654	}
3655
3656	ret = zfs_snapshot_nvl(hdl, sd.sd_nvl, props);
3657	nvlist_free(sd.sd_nvl);
3658	zfs_close(zhp);
3659	return (ret);
3660}
3661
3662/*
3663 * Destroy any more recent snapshots.  We invoke this callback on any dependents
3664 * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
3665 * is a dependent and we should just destroy it without checking the transaction
3666 * group.
3667 */
3668typedef struct rollback_data {
3669	const char	*cb_target;		/* the snapshot */
3670	uint64_t	cb_create;		/* creation time reference */
3671	boolean_t	cb_error;
3672	boolean_t	cb_force;
3673} rollback_data_t;
3674
3675static int
3676rollback_destroy_dependent(zfs_handle_t *zhp, void *data)
3677{
3678	rollback_data_t *cbp = data;
3679	prop_changelist_t *clp;
3680
3681	/* We must destroy this clone; first unmount it */
3682	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
3683	    cbp->cb_force ? MS_FORCE: 0);
3684	if (clp == NULL || changelist_prefix(clp) != 0) {
3685		cbp->cb_error = B_TRUE;
3686		zfs_close(zhp);
3687		return (0);
3688	}
3689	if (zfs_destroy(zhp, B_FALSE) != 0)
3690		cbp->cb_error = B_TRUE;
3691	else
3692		changelist_remove(clp, zhp->zfs_name);
3693	(void) changelist_postfix(clp);
3694	changelist_free(clp);
3695
3696	zfs_close(zhp);
3697	return (0);
3698}
3699
3700static int
3701rollback_destroy(zfs_handle_t *zhp, void *data)
3702{
3703	rollback_data_t *cbp = data;
3704
3705	if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3706		cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
3707		    rollback_destroy_dependent, cbp);
3708
3709		cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
3710	}
3711
3712	zfs_close(zhp);
3713	return (0);
3714}
3715
3716/*
3717 * Given a dataset, rollback to a specific snapshot, discarding any
3718 * data changes since then and making it the active dataset.
3719 *
3720 * Any snapshots and bookmarks more recent than the target are
3721 * destroyed, along with their dependents (i.e. clones).
3722 */
3723int
3724zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
3725{
3726	rollback_data_t cb = { 0 };
3727	int err;
3728	boolean_t restore_resv = 0;
3729	uint64_t old_volsize, new_volsize;
3730	zfs_prop_t resv_prop;
3731
3732	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
3733	    zhp->zfs_type == ZFS_TYPE_VOLUME);
3734
3735	/*
3736	 * Destroy all recent snapshots and their dependents.
3737	 */
3738	cb.cb_force = force;
3739	cb.cb_target = snap->zfs_name;
3740	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3741	(void) zfs_iter_snapshots(zhp, B_FALSE, rollback_destroy, &cb);
3742	(void) zfs_iter_bookmarks(zhp, rollback_destroy, &cb);
3743
3744	if (cb.cb_error)
3745		return (-1);
3746
3747	/*
3748	 * Now that we have verified that the snapshot is the latest,
3749	 * rollback to the given snapshot.
3750	 */
3751
3752	if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3753		if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
3754			return (-1);
3755		old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3756		restore_resv =
3757		    (old_volsize == zfs_prop_get_int(zhp, resv_prop));
3758	}
3759
3760	/*
3761	 * We rely on zfs_iter_children() to verify that there are no
3762	 * newer snapshots for the given dataset.  Therefore, we can
3763	 * simply pass the name on to the ioctl() call.  There is still
3764	 * an unlikely race condition where the user has taken a
3765	 * snapshot since we verified that this was the most recent.
3766	 */
3767	err = lzc_rollback(zhp->zfs_name, NULL, 0);
3768	if (err != 0) {
3769		(void) zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3770		    dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
3771		    zhp->zfs_name);
3772		return (err);
3773	}
3774
3775	/*
3776	 * For volumes, if the pre-rollback volsize matched the pre-
3777	 * rollback reservation and the volsize has changed then set
3778	 * the reservation property to the post-rollback volsize.
3779	 * Make a new handle since the rollback closed the dataset.
3780	 */
3781	if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
3782	    (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
3783		if (restore_resv) {
3784			new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3785			if (old_volsize != new_volsize)
3786				err = zfs_prop_set_int(zhp, resv_prop,
3787				    new_volsize);
3788		}
3789		zfs_close(zhp);
3790	}
3791	return (err);
3792}
3793
3794/*
3795 * Renames the given dataset.
3796 */
3797int
3798zfs_rename(zfs_handle_t *zhp, const char *source, const char *target,
3799    renameflags_t flags)
3800{
3801	int ret;
3802	zfs_cmd_t zc = { 0 };
3803	char *delim;
3804	prop_changelist_t *cl = NULL;
3805	zfs_handle_t *zhrp = NULL;
3806	char *parentname = NULL;
3807	char parent[ZFS_MAXNAMELEN];
3808	char property[ZFS_MAXPROPLEN];
3809	libzfs_handle_t *hdl = zhp->zfs_hdl;
3810	char errbuf[1024];
3811
3812	/* if we have the same exact name, just return success */
3813	if (strcmp(zhp->zfs_name, target) == 0)
3814		return (0);
3815
3816	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3817	    "cannot rename to '%s'"), target);
3818
3819	if (source != NULL) {
3820		/*
3821		 * This is recursive snapshots rename, put snapshot name
3822		 * (that might not exist) into zfs_name.
3823		 */
3824		assert(flags.recurse);
3825
3826		(void) strlcat(zhp->zfs_name, "@", sizeof(zhp->zfs_name));
3827		(void) strlcat(zhp->zfs_name, source, sizeof(zhp->zfs_name));
3828		zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
3829	}
3830
3831	/*
3832	 * Make sure the target name is valid
3833	 */
3834	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3835		if ((strchr(target, '@') == NULL) ||
3836		    *target == '@') {
3837			/*
3838			 * Snapshot target name is abbreviated,
3839			 * reconstruct full dataset name
3840			 */
3841			(void) strlcpy(parent, zhp->zfs_name,
3842			    sizeof (parent));
3843			delim = strchr(parent, '@');
3844			if (strchr(target, '@') == NULL)
3845				*(++delim) = '\0';
3846			else
3847				*delim = '\0';
3848			(void) strlcat(parent, target, sizeof (parent));
3849			target = parent;
3850		} else {
3851			/*
3852			 * Make sure we're renaming within the same dataset.
3853			 */
3854			delim = strchr(target, '@');
3855			if (strncmp(zhp->zfs_name, target, delim - target)
3856			    != 0 || zhp->zfs_name[delim - target] != '@') {
3857				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3858				    "snapshots must be part of same "
3859				    "dataset"));
3860				return (zfs_error(hdl, EZFS_CROSSTARGET,
3861				    errbuf));
3862			}
3863		}
3864		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3865			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3866	} else {
3867		if (flags.recurse) {
3868			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3869			    "recursive rename must be a snapshot"));
3870			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3871		}
3872
3873		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3874			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3875
3876		/* validate parents */
3877		if (check_parents(hdl, target, NULL, B_FALSE, NULL) != 0)
3878			return (-1);
3879
3880		/* make sure we're in the same pool */
3881		verify((delim = strchr(target, '/')) != NULL);
3882		if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
3883		    zhp->zfs_name[delim - target] != '/') {
3884			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3885			    "datasets must be within same pool"));
3886			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
3887		}
3888
3889		/* new name cannot be a child of the current dataset name */
3890		if (is_descendant(zhp->zfs_name, target)) {
3891			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3892			    "New dataset name cannot be a descendant of "
3893			    "current dataset name"));
3894			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3895		}
3896	}
3897
3898	(void) snprintf(errbuf, sizeof (errbuf),
3899	    dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
3900
3901	if (getzoneid() == GLOBAL_ZONEID &&
3902	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
3903		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3904		    "dataset is used in a non-global zone"));
3905		return (zfs_error(hdl, EZFS_ZONED, errbuf));
3906	}
3907
3908	/*
3909	 * Avoid unmounting file systems with mountpoint property set to
3910	 * 'legacy' or 'none' even if -u option is not given.
3911	 */
3912	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
3913	    !flags.recurse && !flags.nounmount &&
3914	    zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, property,
3915	    sizeof (property), NULL, NULL, 0, B_FALSE) == 0 &&
3916	    (strcmp(property, "legacy") == 0 ||
3917	     strcmp(property, "none") == 0)) {
3918		flags.nounmount = B_TRUE;
3919	}
3920	if (flags.recurse) {
3921
3922		parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
3923		if (parentname == NULL) {
3924			ret = -1;
3925			goto error;
3926		}
3927		delim = strchr(parentname, '@');
3928		*delim = '\0';
3929		zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
3930		if (zhrp == NULL) {
3931			ret = -1;
3932			goto error;
3933		}
3934	} else if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT) {
3935		if ((cl = changelist_gather(zhp, ZFS_PROP_NAME,
3936		    flags.nounmount ? CL_GATHER_DONT_UNMOUNT : 0,
3937		    flags.forceunmount ? MS_FORCE : 0)) == NULL) {
3938			return (-1);
3939		}
3940
3941		if (changelist_haszonedchild(cl)) {
3942			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3943			    "child dataset with inherited mountpoint is used "
3944			    "in a non-global zone"));
3945			(void) zfs_error(hdl, EZFS_ZONED, errbuf);
3946			goto error;
3947		}
3948
3949		if ((ret = changelist_prefix(cl)) != 0)
3950			goto error;
3951	}
3952
3953	if (ZFS_IS_VOLUME(zhp))
3954		zc.zc_objset_type = DMU_OST_ZVOL;
3955	else
3956		zc.zc_objset_type = DMU_OST_ZFS;
3957
3958	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3959	(void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
3960
3961	zc.zc_cookie = flags.recurse ? 1 : 0;
3962	if (flags.nounmount)
3963		zc.zc_cookie |= 2;
3964
3965	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
3966		/*
3967		 * if it was recursive, the one that actually failed will
3968		 * be in zc.zc_name
3969		 */
3970		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3971		    "cannot rename '%s'"), zc.zc_name);
3972
3973		if (flags.recurse && errno == EEXIST) {
3974			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3975			    "a child dataset already has a snapshot "
3976			    "with the new name"));
3977			(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3978		} else {
3979			(void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
3980		}
3981
3982		/*
3983		 * On failure, we still want to remount any filesystems that
3984		 * were previously mounted, so we don't alter the system state.
3985		 */
3986		if (cl != NULL)
3987			(void) changelist_postfix(cl);
3988	} else {
3989		if (cl != NULL) {
3990			changelist_rename(cl, zfs_get_name(zhp), target);
3991			ret = changelist_postfix(cl);
3992		}
3993	}
3994
3995error:
3996	if (parentname != NULL) {
3997		free(parentname);
3998	}
3999	if (zhrp != NULL) {
4000		zfs_close(zhrp);
4001	}
4002	if (cl != NULL) {
4003		changelist_free(cl);
4004	}
4005	return (ret);
4006}
4007
4008nvlist_t *
4009zfs_get_user_props(zfs_handle_t *zhp)
4010{
4011	return (zhp->zfs_user_props);
4012}
4013
4014nvlist_t *
4015zfs_get_recvd_props(zfs_handle_t *zhp)
4016{
4017	if (zhp->zfs_recvd_props == NULL)
4018		if (get_recvd_props_ioctl(zhp) != 0)
4019			return (NULL);
4020	return (zhp->zfs_recvd_props);
4021}
4022
4023/*
4024 * This function is used by 'zfs list' to determine the exact set of columns to
4025 * display, and their maximum widths.  This does two main things:
4026 *
4027 *      - If this is a list of all properties, then expand the list to include
4028 *        all native properties, and set a flag so that for each dataset we look
4029 *        for new unique user properties and add them to the list.
4030 *
4031 *      - For non fixed-width properties, keep track of the maximum width seen
4032 *        so that we can size the column appropriately. If the user has
4033 *        requested received property values, we also need to compute the width
4034 *        of the RECEIVED column.
4035 */
4036int
4037zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp, boolean_t received,
4038    boolean_t literal)
4039{
4040	libzfs_handle_t *hdl = zhp->zfs_hdl;
4041	zprop_list_t *entry;
4042	zprop_list_t **last, **start;
4043	nvlist_t *userprops, *propval;
4044	nvpair_t *elem;
4045	char *strval;
4046	char buf[ZFS_MAXPROPLEN];
4047
4048	if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
4049		return (-1);
4050
4051	userprops = zfs_get_user_props(zhp);
4052
4053	entry = *plp;
4054	if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
4055		/*
4056		 * Go through and add any user properties as necessary.  We
4057		 * start by incrementing our list pointer to the first
4058		 * non-native property.
4059		 */
4060		start = plp;
4061		while (*start != NULL) {
4062			if ((*start)->pl_prop == ZPROP_INVAL)
4063				break;
4064			start = &(*start)->pl_next;
4065		}
4066
4067		elem = NULL;
4068		while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
4069			/*
4070			 * See if we've already found this property in our list.
4071			 */
4072			for (last = start; *last != NULL;
4073			    last = &(*last)->pl_next) {
4074				if (strcmp((*last)->pl_user_prop,
4075				    nvpair_name(elem)) == 0)
4076					break;
4077			}
4078
4079			if (*last == NULL) {
4080				if ((entry = zfs_alloc(hdl,
4081				    sizeof (zprop_list_t))) == NULL ||
4082				    ((entry->pl_user_prop = zfs_strdup(hdl,
4083				    nvpair_name(elem)))) == NULL) {
4084					free(entry);
4085					return (-1);
4086				}
4087
4088				entry->pl_prop = ZPROP_INVAL;
4089				entry->pl_width = strlen(nvpair_name(elem));
4090				entry->pl_all = B_TRUE;
4091				*last = entry;
4092			}
4093		}
4094	}
4095
4096	/*
4097	 * Now go through and check the width of any non-fixed columns
4098	 */
4099	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
4100		if (entry->pl_fixed && !literal)
4101			continue;
4102
4103		if (entry->pl_prop != ZPROP_INVAL) {
4104			if (zfs_prop_get(zhp, entry->pl_prop,
4105			    buf, sizeof (buf), NULL, NULL, 0, literal) == 0) {
4106				if (strlen(buf) > entry->pl_width)
4107					entry->pl_width = strlen(buf);
4108			}
4109			if (received && zfs_prop_get_recvd(zhp,
4110			    zfs_prop_to_name(entry->pl_prop),
4111			    buf, sizeof (buf), literal) == 0)
4112				if (strlen(buf) > entry->pl_recvd_width)
4113					entry->pl_recvd_width = strlen(buf);
4114		} else {
4115			if (nvlist_lookup_nvlist(userprops, entry->pl_user_prop,
4116			    &propval) == 0) {
4117				verify(nvlist_lookup_string(propval,
4118				    ZPROP_VALUE, &strval) == 0);
4119				if (strlen(strval) > entry->pl_width)
4120					entry->pl_width = strlen(strval);
4121			}
4122			if (received && zfs_prop_get_recvd(zhp,
4123			    entry->pl_user_prop,
4124			    buf, sizeof (buf), literal) == 0)
4125				if (strlen(buf) > entry->pl_recvd_width)
4126					entry->pl_recvd_width = strlen(buf);
4127		}
4128	}
4129
4130	return (0);
4131}
4132
4133int
4134zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
4135    char *resource, void *export, void *sharetab,
4136    int sharemax, zfs_share_op_t operation)
4137{
4138	zfs_cmd_t zc = { 0 };
4139	int error;
4140
4141	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4142	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4143	if (resource)
4144		(void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
4145	zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
4146	zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
4147	zc.zc_share.z_sharetype = operation;
4148	zc.zc_share.z_sharemax = sharemax;
4149	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
4150	return (error);
4151}
4152
4153void
4154zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
4155{
4156	nvpair_t *curr;
4157
4158	/*
4159	 * Keep a reference to the props-table against which we prune the
4160	 * properties.
4161	 */
4162	zhp->zfs_props_table = props;
4163
4164	curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
4165
4166	while (curr) {
4167		zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
4168		nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
4169
4170		/*
4171		 * User properties will result in ZPROP_INVAL, and since we
4172		 * only know how to prune standard ZFS properties, we always
4173		 * leave these in the list.  This can also happen if we
4174		 * encounter an unknown DSL property (when running older
4175		 * software, for example).
4176		 */
4177		if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
4178			(void) nvlist_remove(zhp->zfs_props,
4179			    nvpair_name(curr), nvpair_type(curr));
4180		curr = next;
4181	}
4182}
4183
4184#ifdef sun
4185static int
4186zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
4187    zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
4188{
4189	zfs_cmd_t zc = { 0 };
4190	nvlist_t *nvlist = NULL;
4191	int error;
4192
4193	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4194	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4195	zc.zc_cookie = (uint64_t)cmd;
4196
4197	if (cmd == ZFS_SMB_ACL_RENAME) {
4198		if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
4199			(void) no_memory(hdl);
4200			return (NULL);
4201		}
4202	}
4203
4204	switch (cmd) {
4205	case ZFS_SMB_ACL_ADD:
4206	case ZFS_SMB_ACL_REMOVE:
4207		(void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
4208		break;
4209	case ZFS_SMB_ACL_RENAME:
4210		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
4211		    resource1) != 0) {
4212				(void) no_memory(hdl);
4213				return (-1);
4214		}
4215		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
4216		    resource2) != 0) {
4217				(void) no_memory(hdl);
4218				return (-1);
4219		}
4220		if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
4221			nvlist_free(nvlist);
4222			return (-1);
4223		}
4224		break;
4225	case ZFS_SMB_ACL_PURGE:
4226		break;
4227	default:
4228		return (-1);
4229	}
4230	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
4231	if (nvlist)
4232		nvlist_free(nvlist);
4233	return (error);
4234}
4235
4236int
4237zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
4238    char *path, char *resource)
4239{
4240	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
4241	    resource, NULL));
4242}
4243
4244int
4245zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
4246    char *path, char *resource)
4247{
4248	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
4249	    resource, NULL));
4250}
4251
4252int
4253zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
4254{
4255	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
4256	    NULL, NULL));
4257}
4258
4259int
4260zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
4261    char *oldname, char *newname)
4262{
4263	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
4264	    oldname, newname));
4265}
4266#endif	/* sun */
4267
4268int
4269zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
4270    zfs_userspace_cb_t func, void *arg)
4271{
4272	zfs_cmd_t zc = { 0 };
4273	zfs_useracct_t buf[100];
4274	libzfs_handle_t *hdl = zhp->zfs_hdl;
4275	int ret;
4276
4277	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4278
4279	zc.zc_objset_type = type;
4280	zc.zc_nvlist_dst = (uintptr_t)buf;
4281
4282	for (;;) {
4283		zfs_useracct_t *zua = buf;
4284
4285		zc.zc_nvlist_dst_size = sizeof (buf);
4286		if (zfs_ioctl(hdl, ZFS_IOC_USERSPACE_MANY, &zc) != 0) {
4287			char errbuf[1024];
4288
4289			(void) snprintf(errbuf, sizeof (errbuf),
4290			    dgettext(TEXT_DOMAIN,
4291			    "cannot get used/quota for %s"), zc.zc_name);
4292			return (zfs_standard_error_fmt(hdl, errno, errbuf));
4293		}
4294		if (zc.zc_nvlist_dst_size == 0)
4295			break;
4296
4297		while (zc.zc_nvlist_dst_size > 0) {
4298			if ((ret = func(arg, zua->zu_domain, zua->zu_rid,
4299			    zua->zu_space)) != 0)
4300				return (ret);
4301			zua++;
4302			zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
4303		}
4304	}
4305
4306	return (0);
4307}
4308
4309struct holdarg {
4310	nvlist_t *nvl;
4311	const char *snapname;
4312	const char *tag;
4313	boolean_t recursive;
4314	int error;
4315};
4316
4317static int
4318zfs_hold_one(zfs_handle_t *zhp, void *arg)
4319{
4320	struct holdarg *ha = arg;
4321	char name[ZFS_MAXNAMELEN];
4322	int rv = 0;
4323
4324	(void) snprintf(name, sizeof (name),
4325	    "%s@%s", zhp->zfs_name, ha->snapname);
4326
4327	if (lzc_exists(name))
4328		fnvlist_add_string(ha->nvl, name, ha->tag);
4329
4330	if (ha->recursive)
4331		rv = zfs_iter_filesystems(zhp, zfs_hold_one, ha);
4332	zfs_close(zhp);
4333	return (rv);
4334}
4335
4336int
4337zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
4338    boolean_t recursive, int cleanup_fd)
4339{
4340	int ret;
4341	struct holdarg ha;
4342
4343	ha.nvl = fnvlist_alloc();
4344	ha.snapname = snapname;
4345	ha.tag = tag;
4346	ha.recursive = recursive;
4347	(void) zfs_hold_one(zfs_handle_dup(zhp), &ha);
4348
4349	if (nvlist_empty(ha.nvl)) {
4350		char errbuf[1024];
4351
4352		fnvlist_free(ha.nvl);
4353		ret = ENOENT;
4354		(void) snprintf(errbuf, sizeof (errbuf),
4355		    dgettext(TEXT_DOMAIN,
4356		    "cannot hold snapshot '%s@%s'"),
4357		    zhp->zfs_name, snapname);
4358		(void) zfs_standard_error(zhp->zfs_hdl, ret, errbuf);
4359		return (ret);
4360	}
4361
4362	ret = zfs_hold_nvl(zhp, cleanup_fd, ha.nvl);
4363	fnvlist_free(ha.nvl);
4364
4365	return (ret);
4366}
4367
4368int
4369zfs_hold_nvl(zfs_handle_t *zhp, int cleanup_fd, nvlist_t *holds)
4370{
4371	int ret;
4372	nvlist_t *errors;
4373	libzfs_handle_t *hdl = zhp->zfs_hdl;
4374	char errbuf[1024];
4375	nvpair_t *elem;
4376
4377	errors = NULL;
4378	ret = lzc_hold(holds, cleanup_fd, &errors);
4379
4380	if (ret == 0) {
4381		/* There may be errors even in the success case. */
4382		fnvlist_free(errors);
4383		return (0);
4384	}
4385
4386	if (nvlist_empty(errors)) {
4387		/* no hold-specific errors */
4388		(void) snprintf(errbuf, sizeof (errbuf),
4389		    dgettext(TEXT_DOMAIN, "cannot hold"));
4390		switch (ret) {
4391		case ENOTSUP:
4392			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4393			    "pool must be upgraded"));
4394			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4395			break;
4396		case EINVAL:
4397			(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4398			break;
4399		default:
4400			(void) zfs_standard_error(hdl, ret, errbuf);
4401		}
4402	}
4403
4404	for (elem = nvlist_next_nvpair(errors, NULL);
4405	    elem != NULL;
4406	    elem = nvlist_next_nvpair(errors, elem)) {
4407		(void) snprintf(errbuf, sizeof (errbuf),
4408		    dgettext(TEXT_DOMAIN,
4409		    "cannot hold snapshot '%s'"), nvpair_name(elem));
4410		switch (fnvpair_value_int32(elem)) {
4411		case E2BIG:
4412			/*
4413			 * Temporary tags wind up having the ds object id
4414			 * prepended. So even if we passed the length check
4415			 * above, it's still possible for the tag to wind
4416			 * up being slightly too long.
4417			 */
4418			(void) zfs_error(hdl, EZFS_TAGTOOLONG, errbuf);
4419			break;
4420		case EINVAL:
4421			(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4422			break;
4423		case EEXIST:
4424			(void) zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf);
4425			break;
4426		default:
4427			(void) zfs_standard_error(hdl,
4428			    fnvpair_value_int32(elem), errbuf);
4429		}
4430	}
4431
4432	fnvlist_free(errors);
4433	return (ret);
4434}
4435
4436static int
4437zfs_release_one(zfs_handle_t *zhp, void *arg)
4438{
4439	struct holdarg *ha = arg;
4440	char name[ZFS_MAXNAMELEN];
4441	int rv = 0;
4442	nvlist_t *existing_holds;
4443
4444	(void) snprintf(name, sizeof (name),
4445	    "%s@%s", zhp->zfs_name, ha->snapname);
4446
4447	if (lzc_get_holds(name, &existing_holds) != 0) {
4448		ha->error = ENOENT;
4449	} else if (!nvlist_exists(existing_holds, ha->tag)) {
4450		ha->error = ESRCH;
4451	} else {
4452		nvlist_t *torelease = fnvlist_alloc();
4453		fnvlist_add_boolean(torelease, ha->tag);
4454		fnvlist_add_nvlist(ha->nvl, name, torelease);
4455		fnvlist_free(torelease);
4456	}
4457
4458	if (ha->recursive)
4459		rv = zfs_iter_filesystems(zhp, zfs_release_one, ha);
4460	zfs_close(zhp);
4461	return (rv);
4462}
4463
4464int
4465zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
4466    boolean_t recursive)
4467{
4468	int ret;
4469	struct holdarg ha;
4470	nvlist_t *errors = NULL;
4471	nvpair_t *elem;
4472	libzfs_handle_t *hdl = zhp->zfs_hdl;
4473	char errbuf[1024];
4474
4475	ha.nvl = fnvlist_alloc();
4476	ha.snapname = snapname;
4477	ha.tag = tag;
4478	ha.recursive = recursive;
4479	ha.error = 0;
4480	(void) zfs_release_one(zfs_handle_dup(zhp), &ha);
4481
4482	if (nvlist_empty(ha.nvl)) {
4483		fnvlist_free(ha.nvl);
4484		ret = ha.error;
4485		(void) snprintf(errbuf, sizeof (errbuf),
4486		    dgettext(TEXT_DOMAIN,
4487		    "cannot release hold from snapshot '%s@%s'"),
4488		    zhp->zfs_name, snapname);
4489		if (ret == ESRCH) {
4490			(void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
4491		} else {
4492			(void) zfs_standard_error(hdl, ret, errbuf);
4493		}
4494		return (ret);
4495	}
4496
4497	ret = lzc_release(ha.nvl, &errors);
4498	fnvlist_free(ha.nvl);
4499
4500	if (ret == 0) {
4501		/* There may be errors even in the success case. */
4502		fnvlist_free(errors);
4503		return (0);
4504	}
4505
4506	if (nvlist_empty(errors)) {
4507		/* no hold-specific errors */
4508		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4509		    "cannot release"));
4510		switch (errno) {
4511		case ENOTSUP:
4512			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4513			    "pool must be upgraded"));
4514			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4515			break;
4516		default:
4517			(void) zfs_standard_error_fmt(hdl, errno, errbuf);
4518		}
4519	}
4520
4521	for (elem = nvlist_next_nvpair(errors, NULL);
4522	    elem != NULL;
4523	    elem = nvlist_next_nvpair(errors, elem)) {
4524		(void) snprintf(errbuf, sizeof (errbuf),
4525		    dgettext(TEXT_DOMAIN,
4526		    "cannot release hold from snapshot '%s'"),
4527		    nvpair_name(elem));
4528		switch (fnvpair_value_int32(elem)) {
4529		case ESRCH:
4530			(void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
4531			break;
4532		case EINVAL:
4533			(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4534			break;
4535		default:
4536			(void) zfs_standard_error_fmt(hdl,
4537			    fnvpair_value_int32(elem), errbuf);
4538		}
4539	}
4540
4541	fnvlist_free(errors);
4542	return (ret);
4543}
4544
4545int
4546zfs_get_fsacl(zfs_handle_t *zhp, nvlist_t **nvl)
4547{
4548	zfs_cmd_t zc = { 0 };
4549	libzfs_handle_t *hdl = zhp->zfs_hdl;
4550	int nvsz = 2048;
4551	void *nvbuf;
4552	int err = 0;
4553	char errbuf[1024];
4554
4555	assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
4556	    zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4557
4558tryagain:
4559
4560	nvbuf = malloc(nvsz);
4561	if (nvbuf == NULL) {
4562		err = (zfs_error(hdl, EZFS_NOMEM, strerror(errno)));
4563		goto out;
4564	}
4565
4566	zc.zc_nvlist_dst_size = nvsz;
4567	zc.zc_nvlist_dst = (uintptr_t)nvbuf;
4568
4569	(void) strlcpy(zc.zc_name, zhp->zfs_name, ZFS_MAXNAMELEN);
4570
4571	if (ioctl(hdl->libzfs_fd, ZFS_IOC_GET_FSACL, &zc) != 0) {
4572		(void) snprintf(errbuf, sizeof (errbuf),
4573		    dgettext(TEXT_DOMAIN, "cannot get permissions on '%s'"),
4574		    zc.zc_name);
4575		switch (errno) {
4576		case ENOMEM:
4577			free(nvbuf);
4578			nvsz = zc.zc_nvlist_dst_size;
4579			goto tryagain;
4580
4581		case ENOTSUP:
4582			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4583			    "pool must be upgraded"));
4584			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4585			break;
4586		case EINVAL:
4587			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4588			break;
4589		case ENOENT:
4590			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4591			break;
4592		default:
4593			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4594			break;
4595		}
4596	} else {
4597		/* success */
4598		int rc = nvlist_unpack(nvbuf, zc.zc_nvlist_dst_size, nvl, 0);
4599		if (rc) {
4600			(void) snprintf(errbuf, sizeof (errbuf), dgettext(
4601			    TEXT_DOMAIN, "cannot get permissions on '%s'"),
4602			    zc.zc_name);
4603			err = zfs_standard_error_fmt(hdl, rc, errbuf);
4604		}
4605	}
4606
4607	free(nvbuf);
4608out:
4609	return (err);
4610}
4611
4612int
4613zfs_set_fsacl(zfs_handle_t *zhp, boolean_t un, nvlist_t *nvl)
4614{
4615	zfs_cmd_t zc = { 0 };
4616	libzfs_handle_t *hdl = zhp->zfs_hdl;
4617	char *nvbuf;
4618	char errbuf[1024];
4619	size_t nvsz;
4620	int err;
4621
4622	assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
4623	    zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4624
4625	err = nvlist_size(nvl, &nvsz, NV_ENCODE_NATIVE);
4626	assert(err == 0);
4627
4628	nvbuf = malloc(nvsz);
4629
4630	err = nvlist_pack(nvl, &nvbuf, &nvsz, NV_ENCODE_NATIVE, 0);
4631	assert(err == 0);
4632
4633	zc.zc_nvlist_src_size = nvsz;
4634	zc.zc_nvlist_src = (uintptr_t)nvbuf;
4635	zc.zc_perm_action = un;
4636
4637	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4638
4639	if (zfs_ioctl(hdl, ZFS_IOC_SET_FSACL, &zc) != 0) {
4640		(void) snprintf(errbuf, sizeof (errbuf),
4641		    dgettext(TEXT_DOMAIN, "cannot set permissions on '%s'"),
4642		    zc.zc_name);
4643		switch (errno) {
4644		case ENOTSUP:
4645			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4646			    "pool must be upgraded"));
4647			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4648			break;
4649		case EINVAL:
4650			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4651			break;
4652		case ENOENT:
4653			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4654			break;
4655		default:
4656			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4657			break;
4658		}
4659	}
4660
4661	free(nvbuf);
4662
4663	return (err);
4664}
4665
4666int
4667zfs_get_holds(zfs_handle_t *zhp, nvlist_t **nvl)
4668{
4669	int err;
4670	char errbuf[1024];
4671
4672	err = lzc_get_holds(zhp->zfs_name, nvl);
4673
4674	if (err != 0) {
4675		libzfs_handle_t *hdl = zhp->zfs_hdl;
4676
4677		(void) snprintf(errbuf, sizeof (errbuf),
4678		    dgettext(TEXT_DOMAIN, "cannot get holds for '%s'"),
4679		    zhp->zfs_name);
4680		switch (err) {
4681		case ENOTSUP:
4682			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4683			    "pool must be upgraded"));
4684			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4685			break;
4686		case EINVAL:
4687			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4688			break;
4689		case ENOENT:
4690			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4691			break;
4692		default:
4693			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4694			break;
4695		}
4696	}
4697
4698	return (err);
4699}
4700
4701/*
4702 * Convert the zvol's volume size to an appropriate reservation.
4703 * Note: If this routine is updated, it is necessary to update the ZFS test
4704 * suite's shell version in reservation.kshlib.
4705 */
4706uint64_t
4707zvol_volsize_to_reservation(uint64_t volsize, nvlist_t *props)
4708{
4709	uint64_t numdb;
4710	uint64_t nblocks, volblocksize;
4711	int ncopies;
4712	char *strval;
4713
4714	if (nvlist_lookup_string(props,
4715	    zfs_prop_to_name(ZFS_PROP_COPIES), &strval) == 0)
4716		ncopies = atoi(strval);
4717	else
4718		ncopies = 1;
4719	if (nvlist_lookup_uint64(props,
4720	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
4721	    &volblocksize) != 0)
4722		volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
4723	nblocks = volsize/volblocksize;
4724	/* start with metadnode L0-L6 */
4725	numdb = 7;
4726	/* calculate number of indirects */
4727	while (nblocks > 1) {
4728		nblocks += DNODES_PER_LEVEL - 1;
4729		nblocks /= DNODES_PER_LEVEL;
4730		numdb += nblocks;
4731	}
4732	numdb *= MIN(SPA_DVAS_PER_BP, ncopies + 1);
4733	volsize *= ncopies;
4734	/*
4735	 * this is exactly DN_MAX_INDBLKSHIFT when metadata isn't
4736	 * compressed, but in practice they compress down to about
4737	 * 1100 bytes
4738	 */
4739	numdb *= 1ULL << DN_MAX_INDBLKSHIFT;
4740	volsize += numdb;
4741	return (volsize);
4742}
4743
4744/*
4745 * Attach/detach the given filesystem to/from the given jail.
4746 */
4747int
4748zfs_jail(zfs_handle_t *zhp, int jailid, int attach)
4749{
4750	libzfs_handle_t *hdl = zhp->zfs_hdl;
4751	zfs_cmd_t zc = { 0 };
4752	char errbuf[1024];
4753	unsigned long cmd;
4754	int ret;
4755
4756	if (attach) {
4757		(void) snprintf(errbuf, sizeof (errbuf),
4758		    dgettext(TEXT_DOMAIN, "cannot jail '%s'"), zhp->zfs_name);
4759	} else {
4760		(void) snprintf(errbuf, sizeof (errbuf),
4761		    dgettext(TEXT_DOMAIN, "cannot unjail '%s'"), zhp->zfs_name);
4762	}
4763
4764	switch (zhp->zfs_type) {
4765	case ZFS_TYPE_VOLUME:
4766		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4767		    "volumes can not be jailed"));
4768		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4769	case ZFS_TYPE_SNAPSHOT:
4770		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4771		    "snapshots can not be jailed"));
4772		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4773	}
4774	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4775
4776	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4777	zc.zc_objset_type = DMU_OST_ZFS;
4778	zc.zc_jailid = jailid;
4779
4780	cmd = attach ? ZFS_IOC_JAIL : ZFS_IOC_UNJAIL;
4781	if ((ret = ioctl(hdl->libzfs_fd, cmd, &zc)) != 0)
4782		zfs_standard_error(hdl, errno, errbuf);
4783
4784	return (ret);
4785}
4786