libzfs_dataset.c revision 307107
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 (c) 2014 Integros [integros.com]
31 * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
32 * Copyright 2016 Nexenta Systems, Inc.
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 = 0;
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 name of the parent pool for the given zfs handle.
2955 */
2956const char *
2957zfs_get_pool_name(const zfs_handle_t *zhp)
2958{
2959	return (zhp->zpool_hdl->zpool_name);
2960}
2961
2962/*
2963 * Returns the type of the given zfs handle.
2964 */
2965zfs_type_t
2966zfs_get_type(const zfs_handle_t *zhp)
2967{
2968	return (zhp->zfs_type);
2969}
2970
2971/*
2972 * Is one dataset name a child dataset of another?
2973 *
2974 * Needs to handle these cases:
2975 * Dataset 1	"a/foo"		"a/foo"		"a/foo"		"a/foo"
2976 * Dataset 2	"a/fo"		"a/foobar"	"a/bar/baz"	"a/foo/bar"
2977 * Descendant?	No.		No.		No.		Yes.
2978 */
2979static boolean_t
2980is_descendant(const char *ds1, const char *ds2)
2981{
2982	size_t d1len = strlen(ds1);
2983
2984	/* ds2 can't be a descendant if it's smaller */
2985	if (strlen(ds2) < d1len)
2986		return (B_FALSE);
2987
2988	/* otherwise, compare strings and verify that there's a '/' char */
2989	return (ds2[d1len] == '/' && (strncmp(ds1, ds2, d1len) == 0));
2990}
2991
2992/*
2993 * Given a complete name, return just the portion that refers to the parent.
2994 * Will return -1 if there is no parent (path is just the name of the
2995 * pool).
2996 */
2997static int
2998parent_name(const char *path, char *buf, size_t buflen)
2999{
3000	char *slashp;
3001
3002	(void) strlcpy(buf, path, buflen);
3003
3004	if ((slashp = strrchr(buf, '/')) == NULL)
3005		return (-1);
3006	*slashp = '\0';
3007
3008	return (0);
3009}
3010
3011/*
3012 * If accept_ancestor is false, then check to make sure that the given path has
3013 * a parent, and that it exists.  If accept_ancestor is true, then find the
3014 * closest existing ancestor for the given path.  In prefixlen return the
3015 * length of already existing prefix of the given path.  We also fetch the
3016 * 'zoned' property, which is used to validate property settings when creating
3017 * new datasets.
3018 */
3019static int
3020check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
3021    boolean_t accept_ancestor, int *prefixlen)
3022{
3023	zfs_cmd_t zc = { 0 };
3024	char parent[ZFS_MAXNAMELEN];
3025	char *slash;
3026	zfs_handle_t *zhp;
3027	char errbuf[1024];
3028	uint64_t is_zoned;
3029
3030	(void) snprintf(errbuf, sizeof (errbuf),
3031	    dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
3032
3033	/* get parent, and check to see if this is just a pool */
3034	if (parent_name(path, parent, sizeof (parent)) != 0) {
3035		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3036		    "missing dataset name"));
3037		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3038	}
3039
3040	/* check to see if the pool exists */
3041	if ((slash = strchr(parent, '/')) == NULL)
3042		slash = parent + strlen(parent);
3043	(void) strncpy(zc.zc_name, parent, slash - parent);
3044	zc.zc_name[slash - parent] = '\0';
3045	if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
3046	    errno == ENOENT) {
3047		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3048		    "no such pool '%s'"), zc.zc_name);
3049		return (zfs_error(hdl, EZFS_NOENT, errbuf));
3050	}
3051
3052	/* check to see if the parent dataset exists */
3053	while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
3054		if (errno == ENOENT && accept_ancestor) {
3055			/*
3056			 * Go deeper to find an ancestor, give up on top level.
3057			 */
3058			if (parent_name(parent, parent, sizeof (parent)) != 0) {
3059				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3060				    "no such pool '%s'"), zc.zc_name);
3061				return (zfs_error(hdl, EZFS_NOENT, errbuf));
3062			}
3063		} else if (errno == ENOENT) {
3064			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3065			    "parent does not exist"));
3066			return (zfs_error(hdl, EZFS_NOENT, errbuf));
3067		} else
3068			return (zfs_standard_error(hdl, errno, errbuf));
3069	}
3070
3071	is_zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3072	if (zoned != NULL)
3073		*zoned = is_zoned;
3074
3075	/* we are in a non-global zone, but parent is in the global zone */
3076	if (getzoneid() != GLOBAL_ZONEID && !is_zoned) {
3077		(void) zfs_standard_error(hdl, EPERM, errbuf);
3078		zfs_close(zhp);
3079		return (-1);
3080	}
3081
3082	/* make sure parent is a filesystem */
3083	if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
3084		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3085		    "parent is not a filesystem"));
3086		(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
3087		zfs_close(zhp);
3088		return (-1);
3089	}
3090
3091	zfs_close(zhp);
3092	if (prefixlen != NULL)
3093		*prefixlen = strlen(parent);
3094	return (0);
3095}
3096
3097/*
3098 * Finds whether the dataset of the given type(s) exists.
3099 */
3100boolean_t
3101zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
3102{
3103	zfs_handle_t *zhp;
3104
3105	if (!zfs_validate_name(hdl, path, types, B_FALSE))
3106		return (B_FALSE);
3107
3108	/*
3109	 * Try to get stats for the dataset, which will tell us if it exists.
3110	 */
3111	if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
3112		int ds_type = zhp->zfs_type;
3113
3114		zfs_close(zhp);
3115		if (types & ds_type)
3116			return (B_TRUE);
3117	}
3118	return (B_FALSE);
3119}
3120
3121/*
3122 * Given a path to 'target', create all the ancestors between
3123 * the prefixlen portion of the path, and the target itself.
3124 * Fail if the initial prefixlen-ancestor does not already exist.
3125 */
3126int
3127create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
3128{
3129	zfs_handle_t *h;
3130	char *cp;
3131	const char *opname;
3132
3133	/* make sure prefix exists */
3134	cp = target + prefixlen;
3135	if (*cp != '/') {
3136		assert(strchr(cp, '/') == NULL);
3137		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3138	} else {
3139		*cp = '\0';
3140		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3141		*cp = '/';
3142	}
3143	if (h == NULL)
3144		return (-1);
3145	zfs_close(h);
3146
3147	/*
3148	 * Attempt to create, mount, and share any ancestor filesystems,
3149	 * up to the prefixlen-long one.
3150	 */
3151	for (cp = target + prefixlen + 1;
3152	    (cp = strchr(cp, '/')) != NULL; *cp = '/', cp++) {
3153
3154		*cp = '\0';
3155
3156		h = make_dataset_handle(hdl, target);
3157		if (h) {
3158			/* it already exists, nothing to do here */
3159			zfs_close(h);
3160			continue;
3161		}
3162
3163		if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
3164		    NULL) != 0) {
3165			opname = dgettext(TEXT_DOMAIN, "create");
3166			goto ancestorerr;
3167		}
3168
3169		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3170		if (h == NULL) {
3171			opname = dgettext(TEXT_DOMAIN, "open");
3172			goto ancestorerr;
3173		}
3174
3175		if (zfs_mount(h, NULL, 0) != 0) {
3176			opname = dgettext(TEXT_DOMAIN, "mount");
3177			goto ancestorerr;
3178		}
3179
3180		if (zfs_share(h) != 0) {
3181			opname = dgettext(TEXT_DOMAIN, "share");
3182			goto ancestorerr;
3183		}
3184
3185		zfs_close(h);
3186	}
3187
3188	return (0);
3189
3190ancestorerr:
3191	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3192	    "failed to %s ancestor '%s'"), opname, target);
3193	return (-1);
3194}
3195
3196/*
3197 * Creates non-existing ancestors of the given path.
3198 */
3199int
3200zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
3201{
3202	int prefix;
3203	char *path_copy;
3204	int rc = 0;
3205
3206	if (check_parents(hdl, path, NULL, B_TRUE, &prefix) != 0)
3207		return (-1);
3208
3209	if ((path_copy = strdup(path)) != NULL) {
3210		rc = create_parents(hdl, path_copy, prefix);
3211		free(path_copy);
3212	}
3213	if (path_copy == NULL || rc != 0)
3214		return (-1);
3215
3216	return (0);
3217}
3218
3219/*
3220 * Create a new filesystem or volume.
3221 */
3222int
3223zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
3224    nvlist_t *props)
3225{
3226	int ret;
3227	uint64_t size = 0;
3228	uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
3229	char errbuf[1024];
3230	uint64_t zoned;
3231	enum lzc_dataset_type ost;
3232
3233	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3234	    "cannot create '%s'"), path);
3235
3236	/* validate the path, taking care to note the extended error message */
3237	if (!zfs_validate_name(hdl, path, type, B_TRUE))
3238		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3239
3240	/* validate parents exist */
3241	if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
3242		return (-1);
3243
3244	/*
3245	 * The failure modes when creating a dataset of a different type over
3246	 * one that already exists is a little strange.  In particular, if you
3247	 * try to create a dataset on top of an existing dataset, the ioctl()
3248	 * will return ENOENT, not EEXIST.  To prevent this from happening, we
3249	 * first try to see if the dataset exists.
3250	 */
3251	if (zfs_dataset_exists(hdl, path, ZFS_TYPE_DATASET)) {
3252		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3253		    "dataset already exists"));
3254		return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3255	}
3256
3257	if (type == ZFS_TYPE_VOLUME)
3258		ost = LZC_DATSET_TYPE_ZVOL;
3259	else
3260		ost = LZC_DATSET_TYPE_ZFS;
3261
3262	/* open zpool handle for prop validation */
3263	char pool_path[MAXNAMELEN];
3264	(void) strlcpy(pool_path, path, sizeof (pool_path));
3265
3266	/* truncate pool_path at first slash */
3267	char *p = strchr(pool_path, '/');
3268	if (p != NULL)
3269		*p = '\0';
3270
3271	zpool_handle_t *zpool_handle = zpool_open(hdl, pool_path);
3272
3273	if (props && (props = zfs_valid_proplist(hdl, type, props,
3274	    zoned, NULL, zpool_handle, errbuf)) == 0) {
3275		zpool_close(zpool_handle);
3276		return (-1);
3277	}
3278	zpool_close(zpool_handle);
3279
3280	if (type == ZFS_TYPE_VOLUME) {
3281		/*
3282		 * If we are creating a volume, the size and block size must
3283		 * satisfy a few restraints.  First, the blocksize must be a
3284		 * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
3285		 * volsize must be a multiple of the block size, and cannot be
3286		 * zero.
3287		 */
3288		if (props == NULL || nvlist_lookup_uint64(props,
3289		    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
3290			nvlist_free(props);
3291			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3292			    "missing volume size"));
3293			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3294		}
3295
3296		if ((ret = nvlist_lookup_uint64(props,
3297		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3298		    &blocksize)) != 0) {
3299			if (ret == ENOENT) {
3300				blocksize = zfs_prop_default_numeric(
3301				    ZFS_PROP_VOLBLOCKSIZE);
3302			} else {
3303				nvlist_free(props);
3304				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3305				    "missing volume block size"));
3306				return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3307			}
3308		}
3309
3310		if (size == 0) {
3311			nvlist_free(props);
3312			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3313			    "volume size cannot be zero"));
3314			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3315		}
3316
3317		if (size % blocksize != 0) {
3318			nvlist_free(props);
3319			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3320			    "volume size must be a multiple of volume block "
3321			    "size"));
3322			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3323		}
3324	}
3325
3326	/* create the dataset */
3327	ret = lzc_create(path, ost, props);
3328	nvlist_free(props);
3329
3330	/* check for failure */
3331	if (ret != 0) {
3332		char parent[ZFS_MAXNAMELEN];
3333		(void) parent_name(path, parent, sizeof (parent));
3334
3335		switch (errno) {
3336		case ENOENT:
3337			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3338			    "no such parent '%s'"), parent);
3339			return (zfs_error(hdl, EZFS_NOENT, errbuf));
3340
3341		case EINVAL:
3342			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3343			    "parent '%s' is not a filesystem"), parent);
3344			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3345
3346		case ENOTSUP:
3347			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3348			    "pool must be upgraded to set this "
3349			    "property or value"));
3350			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3351#ifdef _ILP32
3352		case EOVERFLOW:
3353			/*
3354			 * This platform can't address a volume this big.
3355			 */
3356			if (type == ZFS_TYPE_VOLUME)
3357				return (zfs_error(hdl, EZFS_VOLTOOBIG,
3358				    errbuf));
3359#endif
3360			/* FALLTHROUGH */
3361		default:
3362			return (zfs_standard_error(hdl, errno, errbuf));
3363		}
3364	}
3365
3366	return (0);
3367}
3368
3369/*
3370 * Destroys the given dataset.  The caller must make sure that the filesystem
3371 * isn't mounted, and that there are no active dependents. If the file system
3372 * does not exist this function does nothing.
3373 */
3374int
3375zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
3376{
3377	zfs_cmd_t zc = { 0 };
3378
3379	if (zhp->zfs_type == ZFS_TYPE_BOOKMARK) {
3380		nvlist_t *nv = fnvlist_alloc();
3381		fnvlist_add_boolean(nv, zhp->zfs_name);
3382		int error = lzc_destroy_bookmarks(nv, NULL);
3383		fnvlist_free(nv);
3384		if (error != 0) {
3385			return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3386			    dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3387			    zhp->zfs_name));
3388		}
3389		return (0);
3390	}
3391
3392	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3393
3394	if (ZFS_IS_VOLUME(zhp)) {
3395		zc.zc_objset_type = DMU_OST_ZVOL;
3396	} else {
3397		zc.zc_objset_type = DMU_OST_ZFS;
3398	}
3399
3400	zc.zc_defer_destroy = defer;
3401	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY, &zc) != 0 &&
3402	    errno != ENOENT) {
3403		return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3404		    dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3405		    zhp->zfs_name));
3406	}
3407
3408	remove_mountpoint(zhp);
3409
3410	return (0);
3411}
3412
3413struct destroydata {
3414	nvlist_t *nvl;
3415	const char *snapname;
3416};
3417
3418static int
3419zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
3420{
3421	struct destroydata *dd = arg;
3422	char name[ZFS_MAXNAMELEN];
3423	int rv = 0;
3424
3425	(void) snprintf(name, sizeof (name),
3426	    "%s@%s", zhp->zfs_name, dd->snapname);
3427
3428	if (lzc_exists(name))
3429		verify(nvlist_add_boolean(dd->nvl, name) == 0);
3430
3431	rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, dd);
3432	zfs_close(zhp);
3433	return (rv);
3434}
3435
3436/*
3437 * Destroys all snapshots with the given name in zhp & descendants.
3438 */
3439int
3440zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
3441{
3442	int ret;
3443	struct destroydata dd = { 0 };
3444
3445	dd.snapname = snapname;
3446	verify(nvlist_alloc(&dd.nvl, NV_UNIQUE_NAME, 0) == 0);
3447	(void) zfs_check_snap_cb(zfs_handle_dup(zhp), &dd);
3448
3449	if (nvlist_empty(dd.nvl)) {
3450		ret = zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
3451		    dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
3452		    zhp->zfs_name, snapname);
3453	} else {
3454		ret = zfs_destroy_snaps_nvl(zhp->zfs_hdl, dd.nvl, defer);
3455	}
3456	nvlist_free(dd.nvl);
3457	return (ret);
3458}
3459
3460/*
3461 * Destroys all the snapshots named in the nvlist.
3462 */
3463int
3464zfs_destroy_snaps_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, boolean_t defer)
3465{
3466	int ret;
3467	nvlist_t *errlist = NULL;
3468
3469	ret = lzc_destroy_snaps(snaps, defer, &errlist);
3470
3471	if (ret == 0) {
3472		nvlist_free(errlist);
3473		return (0);
3474	}
3475
3476	if (nvlist_empty(errlist)) {
3477		char errbuf[1024];
3478		(void) snprintf(errbuf, sizeof (errbuf),
3479		    dgettext(TEXT_DOMAIN, "cannot destroy snapshots"));
3480
3481		ret = zfs_standard_error(hdl, ret, errbuf);
3482	}
3483	for (nvpair_t *pair = nvlist_next_nvpair(errlist, NULL);
3484	    pair != NULL; pair = nvlist_next_nvpair(errlist, pair)) {
3485		char errbuf[1024];
3486		(void) snprintf(errbuf, sizeof (errbuf),
3487		    dgettext(TEXT_DOMAIN, "cannot destroy snapshot %s"),
3488		    nvpair_name(pair));
3489
3490		switch (fnvpair_value_int32(pair)) {
3491		case EEXIST:
3492			zfs_error_aux(hdl,
3493			    dgettext(TEXT_DOMAIN, "snapshot is cloned"));
3494			ret = zfs_error(hdl, EZFS_EXISTS, errbuf);
3495			break;
3496		default:
3497			ret = zfs_standard_error(hdl, errno, errbuf);
3498			break;
3499		}
3500	}
3501
3502	nvlist_free(errlist);
3503	return (ret);
3504}
3505
3506/*
3507 * Clones the given dataset.  The target must be of the same type as the source.
3508 */
3509int
3510zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
3511{
3512	char parent[ZFS_MAXNAMELEN];
3513	int ret;
3514	char errbuf[1024];
3515	libzfs_handle_t *hdl = zhp->zfs_hdl;
3516	uint64_t zoned;
3517
3518	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
3519
3520	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3521	    "cannot create '%s'"), target);
3522
3523	/* validate the target/clone name */
3524	if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
3525		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3526
3527	/* validate parents exist */
3528	if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
3529		return (-1);
3530
3531	(void) parent_name(target, parent, sizeof (parent));
3532
3533	/* do the clone */
3534
3535	if (props) {
3536		zfs_type_t type;
3537		if (ZFS_IS_VOLUME(zhp)) {
3538			type = ZFS_TYPE_VOLUME;
3539		} else {
3540			type = ZFS_TYPE_FILESYSTEM;
3541		}
3542		if ((props = zfs_valid_proplist(hdl, type, props, zoned,
3543		    zhp, zhp->zpool_hdl, errbuf)) == NULL)
3544			return (-1);
3545	}
3546
3547	ret = lzc_clone(target, zhp->zfs_name, props);
3548	nvlist_free(props);
3549
3550	if (ret != 0) {
3551		switch (errno) {
3552
3553		case ENOENT:
3554			/*
3555			 * The parent doesn't exist.  We should have caught this
3556			 * above, but there may a race condition that has since
3557			 * destroyed the parent.
3558			 *
3559			 * At this point, we don't know whether it's the source
3560			 * that doesn't exist anymore, or whether the target
3561			 * dataset doesn't exist.
3562			 */
3563			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3564			    "no such parent '%s'"), parent);
3565			return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
3566
3567		case EXDEV:
3568			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3569			    "source and target pools differ"));
3570			return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
3571			    errbuf));
3572
3573		default:
3574			return (zfs_standard_error(zhp->zfs_hdl, errno,
3575			    errbuf));
3576		}
3577	}
3578
3579	return (ret);
3580}
3581
3582/*
3583 * Promotes the given clone fs to be the clone parent.
3584 */
3585int
3586zfs_promote(zfs_handle_t *zhp)
3587{
3588	libzfs_handle_t *hdl = zhp->zfs_hdl;
3589	zfs_cmd_t zc = { 0 };
3590	char parent[MAXPATHLEN];
3591	int ret;
3592	char errbuf[1024];
3593
3594	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3595	    "cannot promote '%s'"), zhp->zfs_name);
3596
3597	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3598		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3599		    "snapshots can not be promoted"));
3600		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3601	}
3602
3603	(void) strlcpy(parent, zhp->zfs_dmustats.dds_origin, sizeof (parent));
3604	if (parent[0] == '\0') {
3605		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3606		    "not a cloned filesystem"));
3607		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3608	}
3609
3610	(void) strlcpy(zc.zc_value, zhp->zfs_dmustats.dds_origin,
3611	    sizeof (zc.zc_value));
3612	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3613	ret = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
3614
3615	if (ret != 0) {
3616		int save_errno = errno;
3617
3618		switch (save_errno) {
3619		case EEXIST:
3620			/* There is a conflicting snapshot name. */
3621			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3622			    "conflicting snapshot '%s' from parent '%s'"),
3623			    zc.zc_string, parent);
3624			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3625
3626		default:
3627			return (zfs_standard_error(hdl, save_errno, errbuf));
3628		}
3629	}
3630	return (ret);
3631}
3632
3633typedef struct snapdata {
3634	nvlist_t *sd_nvl;
3635	const char *sd_snapname;
3636} snapdata_t;
3637
3638static int
3639zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3640{
3641	snapdata_t *sd = arg;
3642	char name[ZFS_MAXNAMELEN];
3643	int rv = 0;
3644
3645	if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) == 0) {
3646		(void) snprintf(name, sizeof (name),
3647		    "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3648
3649		fnvlist_add_boolean(sd->sd_nvl, name);
3650
3651		rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3652	}
3653	zfs_close(zhp);
3654
3655	return (rv);
3656}
3657
3658/*
3659 * Creates snapshots.  The keys in the snaps nvlist are the snapshots to be
3660 * created.
3661 */
3662int
3663zfs_snapshot_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, nvlist_t *props)
3664{
3665	int ret;
3666	char errbuf[1024];
3667	nvpair_t *elem;
3668	nvlist_t *errors;
3669
3670	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3671	    "cannot create snapshots "));
3672
3673	elem = NULL;
3674	while ((elem = nvlist_next_nvpair(snaps, elem)) != NULL) {
3675		const char *snapname = nvpair_name(elem);
3676
3677		/* validate the target name */
3678		if (!zfs_validate_name(hdl, snapname, ZFS_TYPE_SNAPSHOT,
3679		    B_TRUE)) {
3680			(void) snprintf(errbuf, sizeof (errbuf),
3681			    dgettext(TEXT_DOMAIN,
3682			    "cannot create snapshot '%s'"), snapname);
3683			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3684		}
3685	}
3686
3687	/*
3688	 * get pool handle for prop validation. assumes all snaps are in the
3689	 * same pool, as does lzc_snapshot (below).
3690	 */
3691	char pool[MAXNAMELEN];
3692	elem = nvlist_next_nvpair(snaps, NULL);
3693	(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
3694	pool[strcspn(pool, "/@")] = '\0';
3695	zpool_handle_t *zpool_hdl = zpool_open(hdl, pool);
3696
3697	if (props != NULL &&
3698	    (props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
3699	    props, B_FALSE, NULL, zpool_hdl, errbuf)) == NULL) {
3700		zpool_close(zpool_hdl);
3701		return (-1);
3702	}
3703	zpool_close(zpool_hdl);
3704
3705	ret = lzc_snapshot(snaps, props, &errors);
3706
3707	if (ret != 0) {
3708		boolean_t printed = B_FALSE;
3709		for (elem = nvlist_next_nvpair(errors, NULL);
3710		    elem != NULL;
3711		    elem = nvlist_next_nvpair(errors, elem)) {
3712			(void) snprintf(errbuf, sizeof (errbuf),
3713			    dgettext(TEXT_DOMAIN,
3714			    "cannot create snapshot '%s'"), nvpair_name(elem));
3715			(void) zfs_standard_error(hdl,
3716			    fnvpair_value_int32(elem), errbuf);
3717			printed = B_TRUE;
3718		}
3719		if (!printed) {
3720			switch (ret) {
3721			case EXDEV:
3722				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3723				    "multiple snapshots of same "
3724				    "fs not allowed"));
3725				(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3726
3727				break;
3728			default:
3729				(void) zfs_standard_error(hdl, ret, errbuf);
3730			}
3731		}
3732	}
3733
3734	nvlist_free(props);
3735	nvlist_free(errors);
3736	return (ret);
3737}
3738
3739int
3740zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
3741    nvlist_t *props)
3742{
3743	int ret;
3744	snapdata_t sd = { 0 };
3745	char fsname[ZFS_MAXNAMELEN];
3746	char *cp;
3747	zfs_handle_t *zhp;
3748	char errbuf[1024];
3749
3750	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3751	    "cannot snapshot %s"), path);
3752
3753	if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
3754		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3755
3756	(void) strlcpy(fsname, path, sizeof (fsname));
3757	cp = strchr(fsname, '@');
3758	*cp = '\0';
3759	sd.sd_snapname = cp + 1;
3760
3761	if ((zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM |
3762	    ZFS_TYPE_VOLUME)) == NULL) {
3763		return (-1);
3764	}
3765
3766	verify(nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) == 0);
3767	if (recursive) {
3768		(void) zfs_snapshot_cb(zfs_handle_dup(zhp), &sd);
3769	} else {
3770		fnvlist_add_boolean(sd.sd_nvl, path);
3771	}
3772
3773	ret = zfs_snapshot_nvl(hdl, sd.sd_nvl, props);
3774	nvlist_free(sd.sd_nvl);
3775	zfs_close(zhp);
3776	return (ret);
3777}
3778
3779/*
3780 * Destroy any more recent snapshots.  We invoke this callback on any dependents
3781 * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
3782 * is a dependent and we should just destroy it without checking the transaction
3783 * group.
3784 */
3785typedef struct rollback_data {
3786	const char	*cb_target;		/* the snapshot */
3787	uint64_t	cb_create;		/* creation time reference */
3788	boolean_t	cb_error;
3789	boolean_t	cb_force;
3790} rollback_data_t;
3791
3792static int
3793rollback_destroy_dependent(zfs_handle_t *zhp, void *data)
3794{
3795	rollback_data_t *cbp = data;
3796	prop_changelist_t *clp;
3797
3798	/* We must destroy this clone; first unmount it */
3799	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
3800	    cbp->cb_force ? MS_FORCE: 0);
3801	if (clp == NULL || changelist_prefix(clp) != 0) {
3802		cbp->cb_error = B_TRUE;
3803		zfs_close(zhp);
3804		return (0);
3805	}
3806	if (zfs_destroy(zhp, B_FALSE) != 0)
3807		cbp->cb_error = B_TRUE;
3808	else
3809		changelist_remove(clp, zhp->zfs_name);
3810	(void) changelist_postfix(clp);
3811	changelist_free(clp);
3812
3813	zfs_close(zhp);
3814	return (0);
3815}
3816
3817static int
3818rollback_destroy(zfs_handle_t *zhp, void *data)
3819{
3820	rollback_data_t *cbp = data;
3821
3822	if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3823		cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
3824		    rollback_destroy_dependent, cbp);
3825
3826		cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
3827	}
3828
3829	zfs_close(zhp);
3830	return (0);
3831}
3832
3833/*
3834 * Given a dataset, rollback to a specific snapshot, discarding any
3835 * data changes since then and making it the active dataset.
3836 *
3837 * Any snapshots and bookmarks more recent than the target are
3838 * destroyed, along with their dependents (i.e. clones).
3839 */
3840int
3841zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
3842{
3843	rollback_data_t cb = { 0 };
3844	int err;
3845	boolean_t restore_resv = 0;
3846	uint64_t old_volsize = 0, new_volsize;
3847	zfs_prop_t resv_prop;
3848
3849	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
3850	    zhp->zfs_type == ZFS_TYPE_VOLUME);
3851
3852	/*
3853	 * Destroy all recent snapshots and their dependents.
3854	 */
3855	cb.cb_force = force;
3856	cb.cb_target = snap->zfs_name;
3857	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3858	(void) zfs_iter_snapshots(zhp, B_FALSE, rollback_destroy, &cb);
3859	(void) zfs_iter_bookmarks(zhp, rollback_destroy, &cb);
3860
3861	if (cb.cb_error)
3862		return (-1);
3863
3864	/*
3865	 * Now that we have verified that the snapshot is the latest,
3866	 * rollback to the given snapshot.
3867	 */
3868
3869	if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3870		if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
3871			return (-1);
3872		old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3873		restore_resv =
3874		    (old_volsize == zfs_prop_get_int(zhp, resv_prop));
3875	}
3876
3877	/*
3878	 * We rely on zfs_iter_children() to verify that there are no
3879	 * newer snapshots for the given dataset.  Therefore, we can
3880	 * simply pass the name on to the ioctl() call.  There is still
3881	 * an unlikely race condition where the user has taken a
3882	 * snapshot since we verified that this was the most recent.
3883	 */
3884	err = lzc_rollback(zhp->zfs_name, NULL, 0);
3885	if (err != 0) {
3886		(void) zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3887		    dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
3888		    zhp->zfs_name);
3889		return (err);
3890	}
3891
3892	/*
3893	 * For volumes, if the pre-rollback volsize matched the pre-
3894	 * rollback reservation and the volsize has changed then set
3895	 * the reservation property to the post-rollback volsize.
3896	 * Make a new handle since the rollback closed the dataset.
3897	 */
3898	if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
3899	    (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
3900		if (restore_resv) {
3901			new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3902			if (old_volsize != new_volsize)
3903				err = zfs_prop_set_int(zhp, resv_prop,
3904				    new_volsize);
3905		}
3906		zfs_close(zhp);
3907	}
3908	return (err);
3909}
3910
3911/*
3912 * Renames the given dataset.
3913 */
3914int
3915zfs_rename(zfs_handle_t *zhp, const char *source, const char *target,
3916    renameflags_t flags)
3917{
3918	int ret = 0;
3919	zfs_cmd_t zc = { 0 };
3920	char *delim;
3921	prop_changelist_t *cl = NULL;
3922	zfs_handle_t *zhrp = NULL;
3923	char *parentname = NULL;
3924	char parent[ZFS_MAXNAMELEN];
3925	char property[ZFS_MAXPROPLEN];
3926	libzfs_handle_t *hdl = zhp->zfs_hdl;
3927	char errbuf[1024];
3928
3929	/* if we have the same exact name, just return success */
3930	if (strcmp(zhp->zfs_name, target) == 0)
3931		return (0);
3932
3933	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3934	    "cannot rename to '%s'"), target);
3935
3936	if (source != NULL) {
3937		/*
3938		 * This is recursive snapshots rename, put snapshot name
3939		 * (that might not exist) into zfs_name.
3940		 */
3941		assert(flags.recurse);
3942
3943		(void) strlcat(zhp->zfs_name, "@", sizeof(zhp->zfs_name));
3944		(void) strlcat(zhp->zfs_name, source, sizeof(zhp->zfs_name));
3945		zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
3946	}
3947
3948	/*
3949	 * Make sure the target name is valid
3950	 */
3951	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3952		if ((strchr(target, '@') == NULL) ||
3953		    *target == '@') {
3954			/*
3955			 * Snapshot target name is abbreviated,
3956			 * reconstruct full dataset name
3957			 */
3958			(void) strlcpy(parent, zhp->zfs_name,
3959			    sizeof (parent));
3960			delim = strchr(parent, '@');
3961			if (strchr(target, '@') == NULL)
3962				*(++delim) = '\0';
3963			else
3964				*delim = '\0';
3965			(void) strlcat(parent, target, sizeof (parent));
3966			target = parent;
3967		} else {
3968			/*
3969			 * Make sure we're renaming within the same dataset.
3970			 */
3971			delim = strchr(target, '@');
3972			if (strncmp(zhp->zfs_name, target, delim - target)
3973			    != 0 || zhp->zfs_name[delim - target] != '@') {
3974				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3975				    "snapshots must be part of same "
3976				    "dataset"));
3977				return (zfs_error(hdl, EZFS_CROSSTARGET,
3978				    errbuf));
3979			}
3980		}
3981		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3982			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3983	} else {
3984		if (flags.recurse) {
3985			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3986			    "recursive rename must be a snapshot"));
3987			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3988		}
3989
3990		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3991			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3992
3993		/* validate parents */
3994		if (check_parents(hdl, target, NULL, B_FALSE, NULL) != 0)
3995			return (-1);
3996
3997		/* make sure we're in the same pool */
3998		verify((delim = strchr(target, '/')) != NULL);
3999		if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
4000		    zhp->zfs_name[delim - target] != '/') {
4001			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4002			    "datasets must be within same pool"));
4003			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
4004		}
4005
4006		/* new name cannot be a child of the current dataset name */
4007		if (is_descendant(zhp->zfs_name, target)) {
4008			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4009			    "New dataset name cannot be a descendant of "
4010			    "current dataset name"));
4011			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4012		}
4013	}
4014
4015	(void) snprintf(errbuf, sizeof (errbuf),
4016	    dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
4017
4018	if (getzoneid() == GLOBAL_ZONEID &&
4019	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
4020		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4021		    "dataset is used in a non-global zone"));
4022		return (zfs_error(hdl, EZFS_ZONED, errbuf));
4023	}
4024
4025	/*
4026	 * Avoid unmounting file systems with mountpoint property set to
4027	 * 'legacy' or 'none' even if -u option is not given.
4028	 */
4029	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
4030	    !flags.recurse && !flags.nounmount &&
4031	    zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, property,
4032	    sizeof (property), NULL, NULL, 0, B_FALSE) == 0 &&
4033	    (strcmp(property, "legacy") == 0 ||
4034	     strcmp(property, "none") == 0)) {
4035		flags.nounmount = B_TRUE;
4036	}
4037	if (flags.recurse) {
4038
4039		parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
4040		if (parentname == NULL) {
4041			ret = -1;
4042			goto error;
4043		}
4044		delim = strchr(parentname, '@');
4045		*delim = '\0';
4046		zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
4047		if (zhrp == NULL) {
4048			ret = -1;
4049			goto error;
4050		}
4051	} else if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT) {
4052		if ((cl = changelist_gather(zhp, ZFS_PROP_NAME,
4053		    flags.nounmount ? CL_GATHER_DONT_UNMOUNT : 0,
4054		    flags.forceunmount ? MS_FORCE : 0)) == NULL) {
4055			return (-1);
4056		}
4057
4058		if (changelist_haszonedchild(cl)) {
4059			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4060			    "child dataset with inherited mountpoint is used "
4061			    "in a non-global zone"));
4062			(void) zfs_error(hdl, EZFS_ZONED, errbuf);
4063			ret = -1;
4064			goto error;
4065		}
4066
4067		if ((ret = changelist_prefix(cl)) != 0)
4068			goto error;
4069	}
4070
4071	if (ZFS_IS_VOLUME(zhp))
4072		zc.zc_objset_type = DMU_OST_ZVOL;
4073	else
4074		zc.zc_objset_type = DMU_OST_ZFS;
4075
4076	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4077	(void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
4078
4079	zc.zc_cookie = flags.recurse ? 1 : 0;
4080	if (flags.nounmount)
4081		zc.zc_cookie |= 2;
4082
4083	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
4084		/*
4085		 * if it was recursive, the one that actually failed will
4086		 * be in zc.zc_name
4087		 */
4088		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4089		    "cannot rename '%s'"), zc.zc_name);
4090
4091		if (flags.recurse && errno == EEXIST) {
4092			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4093			    "a child dataset already has a snapshot "
4094			    "with the new name"));
4095			(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
4096		} else {
4097			(void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
4098		}
4099
4100		/*
4101		 * On failure, we still want to remount any filesystems that
4102		 * were previously mounted, so we don't alter the system state.
4103		 */
4104		if (cl != NULL)
4105			(void) changelist_postfix(cl);
4106	} else {
4107		if (cl != NULL) {
4108			changelist_rename(cl, zfs_get_name(zhp), target);
4109			ret = changelist_postfix(cl);
4110		}
4111	}
4112
4113error:
4114	if (parentname != NULL) {
4115		free(parentname);
4116	}
4117	if (zhrp != NULL) {
4118		zfs_close(zhrp);
4119	}
4120	if (cl != NULL) {
4121		changelist_free(cl);
4122	}
4123	return (ret);
4124}
4125
4126nvlist_t *
4127zfs_get_user_props(zfs_handle_t *zhp)
4128{
4129	return (zhp->zfs_user_props);
4130}
4131
4132nvlist_t *
4133zfs_get_recvd_props(zfs_handle_t *zhp)
4134{
4135	if (zhp->zfs_recvd_props == NULL)
4136		if (get_recvd_props_ioctl(zhp) != 0)
4137			return (NULL);
4138	return (zhp->zfs_recvd_props);
4139}
4140
4141/*
4142 * This function is used by 'zfs list' to determine the exact set of columns to
4143 * display, and their maximum widths.  This does two main things:
4144 *
4145 *      - If this is a list of all properties, then expand the list to include
4146 *        all native properties, and set a flag so that for each dataset we look
4147 *        for new unique user properties and add them to the list.
4148 *
4149 *      - For non fixed-width properties, keep track of the maximum width seen
4150 *        so that we can size the column appropriately. If the user has
4151 *        requested received property values, we also need to compute the width
4152 *        of the RECEIVED column.
4153 */
4154int
4155zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp, boolean_t received,
4156    boolean_t literal)
4157{
4158	libzfs_handle_t *hdl = zhp->zfs_hdl;
4159	zprop_list_t *entry;
4160	zprop_list_t **last, **start;
4161	nvlist_t *userprops, *propval;
4162	nvpair_t *elem;
4163	char *strval;
4164	char buf[ZFS_MAXPROPLEN];
4165
4166	if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
4167		return (-1);
4168
4169	userprops = zfs_get_user_props(zhp);
4170
4171	entry = *plp;
4172	if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
4173		/*
4174		 * Go through and add any user properties as necessary.  We
4175		 * start by incrementing our list pointer to the first
4176		 * non-native property.
4177		 */
4178		start = plp;
4179		while (*start != NULL) {
4180			if ((*start)->pl_prop == ZPROP_INVAL)
4181				break;
4182			start = &(*start)->pl_next;
4183		}
4184
4185		elem = NULL;
4186		while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
4187			/*
4188			 * See if we've already found this property in our list.
4189			 */
4190			for (last = start; *last != NULL;
4191			    last = &(*last)->pl_next) {
4192				if (strcmp((*last)->pl_user_prop,
4193				    nvpair_name(elem)) == 0)
4194					break;
4195			}
4196
4197			if (*last == NULL) {
4198				if ((entry = zfs_alloc(hdl,
4199				    sizeof (zprop_list_t))) == NULL ||
4200				    ((entry->pl_user_prop = zfs_strdup(hdl,
4201				    nvpair_name(elem)))) == NULL) {
4202					free(entry);
4203					return (-1);
4204				}
4205
4206				entry->pl_prop = ZPROP_INVAL;
4207				entry->pl_width = strlen(nvpair_name(elem));
4208				entry->pl_all = B_TRUE;
4209				*last = entry;
4210			}
4211		}
4212	}
4213
4214	/*
4215	 * Now go through and check the width of any non-fixed columns
4216	 */
4217	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
4218		if (entry->pl_fixed && !literal)
4219			continue;
4220
4221		if (entry->pl_prop != ZPROP_INVAL) {
4222			if (zfs_prop_get(zhp, entry->pl_prop,
4223			    buf, sizeof (buf), NULL, NULL, 0, literal) == 0) {
4224				if (strlen(buf) > entry->pl_width)
4225					entry->pl_width = strlen(buf);
4226			}
4227			if (received && zfs_prop_get_recvd(zhp,
4228			    zfs_prop_to_name(entry->pl_prop),
4229			    buf, sizeof (buf), literal) == 0)
4230				if (strlen(buf) > entry->pl_recvd_width)
4231					entry->pl_recvd_width = strlen(buf);
4232		} else {
4233			if (nvlist_lookup_nvlist(userprops, entry->pl_user_prop,
4234			    &propval) == 0) {
4235				verify(nvlist_lookup_string(propval,
4236				    ZPROP_VALUE, &strval) == 0);
4237				if (strlen(strval) > entry->pl_width)
4238					entry->pl_width = strlen(strval);
4239			}
4240			if (received && zfs_prop_get_recvd(zhp,
4241			    entry->pl_user_prop,
4242			    buf, sizeof (buf), literal) == 0)
4243				if (strlen(buf) > entry->pl_recvd_width)
4244					entry->pl_recvd_width = strlen(buf);
4245		}
4246	}
4247
4248	return (0);
4249}
4250
4251int
4252zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
4253    char *resource, void *export, void *sharetab,
4254    int sharemax, zfs_share_op_t operation)
4255{
4256	zfs_cmd_t zc = { 0 };
4257	int error;
4258
4259	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4260	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4261	if (resource)
4262		(void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
4263	zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
4264	zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
4265	zc.zc_share.z_sharetype = operation;
4266	zc.zc_share.z_sharemax = sharemax;
4267	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
4268	return (error);
4269}
4270
4271void
4272zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
4273{
4274	nvpair_t *curr;
4275
4276	/*
4277	 * Keep a reference to the props-table against which we prune the
4278	 * properties.
4279	 */
4280	zhp->zfs_props_table = props;
4281
4282	curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
4283
4284	while (curr) {
4285		zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
4286		nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
4287
4288		/*
4289		 * User properties will result in ZPROP_INVAL, and since we
4290		 * only know how to prune standard ZFS properties, we always
4291		 * leave these in the list.  This can also happen if we
4292		 * encounter an unknown DSL property (when running older
4293		 * software, for example).
4294		 */
4295		if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
4296			(void) nvlist_remove(zhp->zfs_props,
4297			    nvpair_name(curr), nvpair_type(curr));
4298		curr = next;
4299	}
4300}
4301
4302#ifdef illumos
4303static int
4304zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
4305    zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
4306{
4307	zfs_cmd_t zc = { 0 };
4308	nvlist_t *nvlist = NULL;
4309	int error;
4310
4311	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4312	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4313	zc.zc_cookie = (uint64_t)cmd;
4314
4315	if (cmd == ZFS_SMB_ACL_RENAME) {
4316		if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
4317			(void) no_memory(hdl);
4318			return (0);
4319		}
4320	}
4321
4322	switch (cmd) {
4323	case ZFS_SMB_ACL_ADD:
4324	case ZFS_SMB_ACL_REMOVE:
4325		(void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
4326		break;
4327	case ZFS_SMB_ACL_RENAME:
4328		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
4329		    resource1) != 0) {
4330				(void) no_memory(hdl);
4331				return (-1);
4332		}
4333		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
4334		    resource2) != 0) {
4335				(void) no_memory(hdl);
4336				return (-1);
4337		}
4338		if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
4339			nvlist_free(nvlist);
4340			return (-1);
4341		}
4342		break;
4343	case ZFS_SMB_ACL_PURGE:
4344		break;
4345	default:
4346		return (-1);
4347	}
4348	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
4349	nvlist_free(nvlist);
4350	return (error);
4351}
4352
4353int
4354zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
4355    char *path, char *resource)
4356{
4357	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
4358	    resource, NULL));
4359}
4360
4361int
4362zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
4363    char *path, char *resource)
4364{
4365	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
4366	    resource, NULL));
4367}
4368
4369int
4370zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
4371{
4372	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
4373	    NULL, NULL));
4374}
4375
4376int
4377zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
4378    char *oldname, char *newname)
4379{
4380	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
4381	    oldname, newname));
4382}
4383#endif	/* illumos */
4384
4385int
4386zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
4387    zfs_userspace_cb_t func, void *arg)
4388{
4389	zfs_cmd_t zc = { 0 };
4390	zfs_useracct_t buf[100];
4391	libzfs_handle_t *hdl = zhp->zfs_hdl;
4392	int ret;
4393
4394	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4395
4396	zc.zc_objset_type = type;
4397	zc.zc_nvlist_dst = (uintptr_t)buf;
4398
4399	for (;;) {
4400		zfs_useracct_t *zua = buf;
4401
4402		zc.zc_nvlist_dst_size = sizeof (buf);
4403		if (zfs_ioctl(hdl, ZFS_IOC_USERSPACE_MANY, &zc) != 0) {
4404			char errbuf[1024];
4405
4406			(void) snprintf(errbuf, sizeof (errbuf),
4407			    dgettext(TEXT_DOMAIN,
4408			    "cannot get used/quota for %s"), zc.zc_name);
4409			return (zfs_standard_error_fmt(hdl, errno, errbuf));
4410		}
4411		if (zc.zc_nvlist_dst_size == 0)
4412			break;
4413
4414		while (zc.zc_nvlist_dst_size > 0) {
4415			if ((ret = func(arg, zua->zu_domain, zua->zu_rid,
4416			    zua->zu_space)) != 0)
4417				return (ret);
4418			zua++;
4419			zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
4420		}
4421	}
4422
4423	return (0);
4424}
4425
4426struct holdarg {
4427	nvlist_t *nvl;
4428	const char *snapname;
4429	const char *tag;
4430	boolean_t recursive;
4431	int error;
4432};
4433
4434static int
4435zfs_hold_one(zfs_handle_t *zhp, void *arg)
4436{
4437	struct holdarg *ha = arg;
4438	char name[ZFS_MAXNAMELEN];
4439	int rv = 0;
4440
4441	(void) snprintf(name, sizeof (name),
4442	    "%s@%s", zhp->zfs_name, ha->snapname);
4443
4444	if (lzc_exists(name))
4445		fnvlist_add_string(ha->nvl, name, ha->tag);
4446
4447	if (ha->recursive)
4448		rv = zfs_iter_filesystems(zhp, zfs_hold_one, ha);
4449	zfs_close(zhp);
4450	return (rv);
4451}
4452
4453int
4454zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
4455    boolean_t recursive, int cleanup_fd)
4456{
4457	int ret;
4458	struct holdarg ha;
4459
4460	ha.nvl = fnvlist_alloc();
4461	ha.snapname = snapname;
4462	ha.tag = tag;
4463	ha.recursive = recursive;
4464	(void) zfs_hold_one(zfs_handle_dup(zhp), &ha);
4465
4466	if (nvlist_empty(ha.nvl)) {
4467		char errbuf[1024];
4468
4469		fnvlist_free(ha.nvl);
4470		ret = ENOENT;
4471		(void) snprintf(errbuf, sizeof (errbuf),
4472		    dgettext(TEXT_DOMAIN,
4473		    "cannot hold snapshot '%s@%s'"),
4474		    zhp->zfs_name, snapname);
4475		(void) zfs_standard_error(zhp->zfs_hdl, ret, errbuf);
4476		return (ret);
4477	}
4478
4479	ret = zfs_hold_nvl(zhp, cleanup_fd, ha.nvl);
4480	fnvlist_free(ha.nvl);
4481
4482	return (ret);
4483}
4484
4485int
4486zfs_hold_nvl(zfs_handle_t *zhp, int cleanup_fd, nvlist_t *holds)
4487{
4488	int ret;
4489	nvlist_t *errors;
4490	libzfs_handle_t *hdl = zhp->zfs_hdl;
4491	char errbuf[1024];
4492	nvpair_t *elem;
4493
4494	errors = NULL;
4495	ret = lzc_hold(holds, cleanup_fd, &errors);
4496
4497	if (ret == 0) {
4498		/* There may be errors even in the success case. */
4499		fnvlist_free(errors);
4500		return (0);
4501	}
4502
4503	if (nvlist_empty(errors)) {
4504		/* no hold-specific errors */
4505		(void) snprintf(errbuf, sizeof (errbuf),
4506		    dgettext(TEXT_DOMAIN, "cannot hold"));
4507		switch (ret) {
4508		case ENOTSUP:
4509			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4510			    "pool must be upgraded"));
4511			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4512			break;
4513		case EINVAL:
4514			(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4515			break;
4516		default:
4517			(void) zfs_standard_error(hdl, ret, errbuf);
4518		}
4519	}
4520
4521	for (elem = nvlist_next_nvpair(errors, NULL);
4522	    elem != NULL;
4523	    elem = nvlist_next_nvpair(errors, elem)) {
4524		(void) snprintf(errbuf, sizeof (errbuf),
4525		    dgettext(TEXT_DOMAIN,
4526		    "cannot hold snapshot '%s'"), nvpair_name(elem));
4527		switch (fnvpair_value_int32(elem)) {
4528		case E2BIG:
4529			/*
4530			 * Temporary tags wind up having the ds object id
4531			 * prepended. So even if we passed the length check
4532			 * above, it's still possible for the tag to wind
4533			 * up being slightly too long.
4534			 */
4535			(void) zfs_error(hdl, EZFS_TAGTOOLONG, errbuf);
4536			break;
4537		case EINVAL:
4538			(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4539			break;
4540		case EEXIST:
4541			(void) zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf);
4542			break;
4543		default:
4544			(void) zfs_standard_error(hdl,
4545			    fnvpair_value_int32(elem), errbuf);
4546		}
4547	}
4548
4549	fnvlist_free(errors);
4550	return (ret);
4551}
4552
4553static int
4554zfs_release_one(zfs_handle_t *zhp, void *arg)
4555{
4556	struct holdarg *ha = arg;
4557	char name[ZFS_MAXNAMELEN];
4558	int rv = 0;
4559	nvlist_t *existing_holds;
4560
4561	(void) snprintf(name, sizeof (name),
4562	    "%s@%s", zhp->zfs_name, ha->snapname);
4563
4564	if (lzc_get_holds(name, &existing_holds) != 0) {
4565		ha->error = ENOENT;
4566	} else if (!nvlist_exists(existing_holds, ha->tag)) {
4567		ha->error = ESRCH;
4568	} else {
4569		nvlist_t *torelease = fnvlist_alloc();
4570		fnvlist_add_boolean(torelease, ha->tag);
4571		fnvlist_add_nvlist(ha->nvl, name, torelease);
4572		fnvlist_free(torelease);
4573	}
4574
4575	if (ha->recursive)
4576		rv = zfs_iter_filesystems(zhp, zfs_release_one, ha);
4577	zfs_close(zhp);
4578	return (rv);
4579}
4580
4581int
4582zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
4583    boolean_t recursive)
4584{
4585	int ret;
4586	struct holdarg ha;
4587	nvlist_t *errors = NULL;
4588	nvpair_t *elem;
4589	libzfs_handle_t *hdl = zhp->zfs_hdl;
4590	char errbuf[1024];
4591
4592	ha.nvl = fnvlist_alloc();
4593	ha.snapname = snapname;
4594	ha.tag = tag;
4595	ha.recursive = recursive;
4596	ha.error = 0;
4597	(void) zfs_release_one(zfs_handle_dup(zhp), &ha);
4598
4599	if (nvlist_empty(ha.nvl)) {
4600		fnvlist_free(ha.nvl);
4601		ret = ha.error;
4602		(void) snprintf(errbuf, sizeof (errbuf),
4603		    dgettext(TEXT_DOMAIN,
4604		    "cannot release hold from snapshot '%s@%s'"),
4605		    zhp->zfs_name, snapname);
4606		if (ret == ESRCH) {
4607			(void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
4608		} else {
4609			(void) zfs_standard_error(hdl, ret, errbuf);
4610		}
4611		return (ret);
4612	}
4613
4614	ret = lzc_release(ha.nvl, &errors);
4615	fnvlist_free(ha.nvl);
4616
4617	if (ret == 0) {
4618		/* There may be errors even in the success case. */
4619		fnvlist_free(errors);
4620		return (0);
4621	}
4622
4623	if (nvlist_empty(errors)) {
4624		/* no hold-specific errors */
4625		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4626		    "cannot release"));
4627		switch (errno) {
4628		case ENOTSUP:
4629			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4630			    "pool must be upgraded"));
4631			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4632			break;
4633		default:
4634			(void) zfs_standard_error_fmt(hdl, errno, errbuf);
4635		}
4636	}
4637
4638	for (elem = nvlist_next_nvpair(errors, NULL);
4639	    elem != NULL;
4640	    elem = nvlist_next_nvpair(errors, elem)) {
4641		(void) snprintf(errbuf, sizeof (errbuf),
4642		    dgettext(TEXT_DOMAIN,
4643		    "cannot release hold from snapshot '%s'"),
4644		    nvpair_name(elem));
4645		switch (fnvpair_value_int32(elem)) {
4646		case ESRCH:
4647			(void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
4648			break;
4649		case EINVAL:
4650			(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4651			break;
4652		default:
4653			(void) zfs_standard_error_fmt(hdl,
4654			    fnvpair_value_int32(elem), errbuf);
4655		}
4656	}
4657
4658	fnvlist_free(errors);
4659	return (ret);
4660}
4661
4662int
4663zfs_get_fsacl(zfs_handle_t *zhp, nvlist_t **nvl)
4664{
4665	zfs_cmd_t zc = { 0 };
4666	libzfs_handle_t *hdl = zhp->zfs_hdl;
4667	int nvsz = 2048;
4668	void *nvbuf;
4669	int err = 0;
4670	char errbuf[1024];
4671
4672	assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
4673	    zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4674
4675tryagain:
4676
4677	nvbuf = malloc(nvsz);
4678	if (nvbuf == NULL) {
4679		err = (zfs_error(hdl, EZFS_NOMEM, strerror(errno)));
4680		goto out;
4681	}
4682
4683	zc.zc_nvlist_dst_size = nvsz;
4684	zc.zc_nvlist_dst = (uintptr_t)nvbuf;
4685
4686	(void) strlcpy(zc.zc_name, zhp->zfs_name, ZFS_MAXNAMELEN);
4687
4688	if (ioctl(hdl->libzfs_fd, ZFS_IOC_GET_FSACL, &zc) != 0) {
4689		(void) snprintf(errbuf, sizeof (errbuf),
4690		    dgettext(TEXT_DOMAIN, "cannot get permissions on '%s'"),
4691		    zc.zc_name);
4692		switch (errno) {
4693		case ENOMEM:
4694			free(nvbuf);
4695			nvsz = zc.zc_nvlist_dst_size;
4696			goto tryagain;
4697
4698		case ENOTSUP:
4699			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4700			    "pool must be upgraded"));
4701			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4702			break;
4703		case EINVAL:
4704			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4705			break;
4706		case ENOENT:
4707			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4708			break;
4709		default:
4710			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4711			break;
4712		}
4713	} else {
4714		/* success */
4715		int rc = nvlist_unpack(nvbuf, zc.zc_nvlist_dst_size, nvl, 0);
4716		if (rc) {
4717			(void) snprintf(errbuf, sizeof (errbuf), dgettext(
4718			    TEXT_DOMAIN, "cannot get permissions on '%s'"),
4719			    zc.zc_name);
4720			err = zfs_standard_error_fmt(hdl, rc, errbuf);
4721		}
4722	}
4723
4724	free(nvbuf);
4725out:
4726	return (err);
4727}
4728
4729int
4730zfs_set_fsacl(zfs_handle_t *zhp, boolean_t un, nvlist_t *nvl)
4731{
4732	zfs_cmd_t zc = { 0 };
4733	libzfs_handle_t *hdl = zhp->zfs_hdl;
4734	char *nvbuf;
4735	char errbuf[1024];
4736	size_t nvsz;
4737	int err;
4738
4739	assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
4740	    zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4741
4742	err = nvlist_size(nvl, &nvsz, NV_ENCODE_NATIVE);
4743	assert(err == 0);
4744
4745	nvbuf = malloc(nvsz);
4746
4747	err = nvlist_pack(nvl, &nvbuf, &nvsz, NV_ENCODE_NATIVE, 0);
4748	assert(err == 0);
4749
4750	zc.zc_nvlist_src_size = nvsz;
4751	zc.zc_nvlist_src = (uintptr_t)nvbuf;
4752	zc.zc_perm_action = un;
4753
4754	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4755
4756	if (zfs_ioctl(hdl, ZFS_IOC_SET_FSACL, &zc) != 0) {
4757		(void) snprintf(errbuf, sizeof (errbuf),
4758		    dgettext(TEXT_DOMAIN, "cannot set permissions on '%s'"),
4759		    zc.zc_name);
4760		switch (errno) {
4761		case ENOTSUP:
4762			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4763			    "pool must be upgraded"));
4764			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4765			break;
4766		case EINVAL:
4767			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4768			break;
4769		case ENOENT:
4770			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4771			break;
4772		default:
4773			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4774			break;
4775		}
4776	}
4777
4778	free(nvbuf);
4779
4780	return (err);
4781}
4782
4783int
4784zfs_get_holds(zfs_handle_t *zhp, nvlist_t **nvl)
4785{
4786	int err;
4787	char errbuf[1024];
4788
4789	err = lzc_get_holds(zhp->zfs_name, nvl);
4790
4791	if (err != 0) {
4792		libzfs_handle_t *hdl = zhp->zfs_hdl;
4793
4794		(void) snprintf(errbuf, sizeof (errbuf),
4795		    dgettext(TEXT_DOMAIN, "cannot get holds for '%s'"),
4796		    zhp->zfs_name);
4797		switch (err) {
4798		case ENOTSUP:
4799			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4800			    "pool must be upgraded"));
4801			err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
4802			break;
4803		case EINVAL:
4804			err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
4805			break;
4806		case ENOENT:
4807			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4808			break;
4809		default:
4810			err = zfs_standard_error_fmt(hdl, errno, errbuf);
4811			break;
4812		}
4813	}
4814
4815	return (err);
4816}
4817
4818/*
4819 * Convert the zvol's volume size to an appropriate reservation.
4820 * Note: If this routine is updated, it is necessary to update the ZFS test
4821 * suite's shell version in reservation.kshlib.
4822 */
4823uint64_t
4824zvol_volsize_to_reservation(uint64_t volsize, nvlist_t *props)
4825{
4826	uint64_t numdb;
4827	uint64_t nblocks, volblocksize;
4828	int ncopies;
4829	char *strval;
4830
4831	if (nvlist_lookup_string(props,
4832	    zfs_prop_to_name(ZFS_PROP_COPIES), &strval) == 0)
4833		ncopies = atoi(strval);
4834	else
4835		ncopies = 1;
4836	if (nvlist_lookup_uint64(props,
4837	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
4838	    &volblocksize) != 0)
4839		volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
4840	nblocks = volsize/volblocksize;
4841	/* start with metadnode L0-L6 */
4842	numdb = 7;
4843	/* calculate number of indirects */
4844	while (nblocks > 1) {
4845		nblocks += DNODES_PER_LEVEL - 1;
4846		nblocks /= DNODES_PER_LEVEL;
4847		numdb += nblocks;
4848	}
4849	numdb *= MIN(SPA_DVAS_PER_BP, ncopies + 1);
4850	volsize *= ncopies;
4851	/*
4852	 * this is exactly DN_MAX_INDBLKSHIFT when metadata isn't
4853	 * compressed, but in practice they compress down to about
4854	 * 1100 bytes
4855	 */
4856	numdb *= 1ULL << DN_MAX_INDBLKSHIFT;
4857	volsize += numdb;
4858	return (volsize);
4859}
4860
4861/*
4862 * Attach/detach the given filesystem to/from the given jail.
4863 */
4864int
4865zfs_jail(zfs_handle_t *zhp, int jailid, int attach)
4866{
4867	libzfs_handle_t *hdl = zhp->zfs_hdl;
4868	zfs_cmd_t zc = { 0 };
4869	char errbuf[1024];
4870	unsigned long cmd;
4871	int ret;
4872
4873	if (attach) {
4874		(void) snprintf(errbuf, sizeof (errbuf),
4875		    dgettext(TEXT_DOMAIN, "cannot jail '%s'"), zhp->zfs_name);
4876	} else {
4877		(void) snprintf(errbuf, sizeof (errbuf),
4878		    dgettext(TEXT_DOMAIN, "cannot unjail '%s'"), zhp->zfs_name);
4879	}
4880
4881	switch (zhp->zfs_type) {
4882	case ZFS_TYPE_VOLUME:
4883		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4884		    "volumes can not be jailed"));
4885		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4886	case ZFS_TYPE_SNAPSHOT:
4887		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4888		    "snapshots can not be jailed"));
4889		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4890	}
4891	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
4892
4893	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4894	zc.zc_objset_type = DMU_OST_ZFS;
4895	zc.zc_jailid = jailid;
4896
4897	cmd = attach ? ZFS_IOC_JAIL : ZFS_IOC_UNJAIL;
4898	if ((ret = ioctl(hdl->libzfs_fd, cmd, &zc)) != 0)
4899		zfs_standard_error(hdl, errno, errbuf);
4900
4901	return (ret);
4902}
4903