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