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