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