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