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