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