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