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