xref: /titanic_44/usr/src/lib/libzfs/common/libzfs_dataset.c (revision 5bbb4db2c3f208d12bf0fd11769728f9e5ba66a2)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <ctype.h>
28 #include <errno.h>
29 #include <libintl.h>
30 #include <math.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <strings.h>
34 #include <unistd.h>
35 #include <stddef.h>
36 #include <zone.h>
37 #include <fcntl.h>
38 #include <sys/mntent.h>
39 #include <sys/mount.h>
40 #include <priv.h>
41 #include <pwd.h>
42 #include <grp.h>
43 #include <stddef.h>
44 #include <ucred.h>
45 #include <idmap.h>
46 #include <aclutils.h>
47 #include <directory.h>
48 
49 #include <sys/spa.h>
50 #include <sys/zap.h>
51 #include <libzfs.h>
52 
53 #include "zfs_namecheck.h"
54 #include "zfs_prop.h"
55 #include "libzfs_impl.h"
56 #include "zfs_deleg.h"
57 
58 static int userquota_propname_decode(const char *propname, boolean_t zoned,
59     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp);
60 
61 /*
62  * Given a single type (not a mask of types), return the type in a human
63  * readable form.
64  */
65 const char *
66 zfs_type_to_name(zfs_type_t type)
67 {
68 	switch (type) {
69 	case ZFS_TYPE_FILESYSTEM:
70 		return (dgettext(TEXT_DOMAIN, "filesystem"));
71 	case ZFS_TYPE_SNAPSHOT:
72 		return (dgettext(TEXT_DOMAIN, "snapshot"));
73 	case ZFS_TYPE_VOLUME:
74 		return (dgettext(TEXT_DOMAIN, "volume"));
75 	}
76 
77 	return (NULL);
78 }
79 
80 /*
81  * Given a path and mask of ZFS types, return a string describing this dataset.
82  * This is used when we fail to open a dataset and we cannot get an exact type.
83  * We guess what the type would have been based on the path and the mask of
84  * acceptable types.
85  */
86 static const char *
87 path_to_str(const char *path, int types)
88 {
89 	/*
90 	 * When given a single type, always report the exact type.
91 	 */
92 	if (types == ZFS_TYPE_SNAPSHOT)
93 		return (dgettext(TEXT_DOMAIN, "snapshot"));
94 	if (types == ZFS_TYPE_FILESYSTEM)
95 		return (dgettext(TEXT_DOMAIN, "filesystem"));
96 	if (types == ZFS_TYPE_VOLUME)
97 		return (dgettext(TEXT_DOMAIN, "volume"));
98 
99 	/*
100 	 * The user is requesting more than one type of dataset.  If this is the
101 	 * case, consult the path itself.  If we're looking for a snapshot, and
102 	 * a '@' is found, then report it as "snapshot".  Otherwise, remove the
103 	 * snapshot attribute and try again.
104 	 */
105 	if (types & ZFS_TYPE_SNAPSHOT) {
106 		if (strchr(path, '@') != NULL)
107 			return (dgettext(TEXT_DOMAIN, "snapshot"));
108 		return (path_to_str(path, types & ~ZFS_TYPE_SNAPSHOT));
109 	}
110 
111 	/*
112 	 * The user has requested either filesystems or volumes.
113 	 * We have no way of knowing a priori what type this would be, so always
114 	 * report it as "filesystem" or "volume", our two primitive types.
115 	 */
116 	if (types & ZFS_TYPE_FILESYSTEM)
117 		return (dgettext(TEXT_DOMAIN, "filesystem"));
118 
119 	assert(types & ZFS_TYPE_VOLUME);
120 	return (dgettext(TEXT_DOMAIN, "volume"));
121 }
122 
123 /*
124  * Validate a ZFS path.  This is used even before trying to open the dataset, to
125  * provide a more meaningful error message.  We call zfs_error_aux() to
126  * explain exactly why the name was not valid.
127  */
128 static int
129 zfs_validate_name(libzfs_handle_t *hdl, const char *path, int type,
130     boolean_t modifying)
131 {
132 	namecheck_err_t why;
133 	char what;
134 
135 	if (dataset_namecheck(path, &why, &what) != 0) {
136 		if (hdl != NULL) {
137 			switch (why) {
138 			case NAME_ERR_TOOLONG:
139 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
140 				    "name is too long"));
141 				break;
142 
143 			case NAME_ERR_LEADING_SLASH:
144 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
145 				    "leading slash in name"));
146 				break;
147 
148 			case NAME_ERR_EMPTY_COMPONENT:
149 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
150 				    "empty component in name"));
151 				break;
152 
153 			case NAME_ERR_TRAILING_SLASH:
154 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
155 				    "trailing slash in name"));
156 				break;
157 
158 			case NAME_ERR_INVALCHAR:
159 				zfs_error_aux(hdl,
160 				    dgettext(TEXT_DOMAIN, "invalid character "
161 				    "'%c' in name"), what);
162 				break;
163 
164 			case NAME_ERR_MULTIPLE_AT:
165 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
166 				    "multiple '@' delimiters in name"));
167 				break;
168 
169 			case NAME_ERR_NOLETTER:
170 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
171 				    "pool doesn't begin with a letter"));
172 				break;
173 
174 			case NAME_ERR_RESERVED:
175 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
176 				    "name is reserved"));
177 				break;
178 
179 			case NAME_ERR_DISKLIKE:
180 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
181 				    "reserved disk name"));
182 				break;
183 			}
184 		}
185 
186 		return (0);
187 	}
188 
189 	if (!(type & ZFS_TYPE_SNAPSHOT) && strchr(path, '@') != NULL) {
190 		if (hdl != NULL)
191 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
192 			    "snapshot delimiter '@' in filesystem name"));
193 		return (0);
194 	}
195 
196 	if (type == ZFS_TYPE_SNAPSHOT && strchr(path, '@') == NULL) {
197 		if (hdl != NULL)
198 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
199 			    "missing '@' delimiter in snapshot name"));
200 		return (0);
201 	}
202 
203 	if (modifying && strchr(path, '%') != NULL) {
204 		if (hdl != NULL)
205 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
206 			    "invalid character %c in name"), '%');
207 		return (0);
208 	}
209 
210 	return (-1);
211 }
212 
213 int
214 zfs_name_valid(const char *name, zfs_type_t type)
215 {
216 	if (type == ZFS_TYPE_POOL)
217 		return (zpool_name_valid(NULL, B_FALSE, name));
218 	return (zfs_validate_name(NULL, name, type, B_FALSE));
219 }
220 
221 /*
222  * This function takes the raw DSL properties, and filters out the user-defined
223  * properties into a separate nvlist.
224  */
225 static nvlist_t *
226 process_user_props(zfs_handle_t *zhp, nvlist_t *props)
227 {
228 	libzfs_handle_t *hdl = zhp->zfs_hdl;
229 	nvpair_t *elem;
230 	nvlist_t *propval;
231 	nvlist_t *nvl;
232 
233 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
234 		(void) no_memory(hdl);
235 		return (NULL);
236 	}
237 
238 	elem = NULL;
239 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
240 		if (!zfs_prop_user(nvpair_name(elem)))
241 			continue;
242 
243 		verify(nvpair_value_nvlist(elem, &propval) == 0);
244 		if (nvlist_add_nvlist(nvl, nvpair_name(elem), propval) != 0) {
245 			nvlist_free(nvl);
246 			(void) no_memory(hdl);
247 			return (NULL);
248 		}
249 	}
250 
251 	return (nvl);
252 }
253 
254 static zpool_handle_t *
255 zpool_add_handle(zfs_handle_t *zhp, const char *pool_name)
256 {
257 	libzfs_handle_t *hdl = zhp->zfs_hdl;
258 	zpool_handle_t *zph;
259 
260 	if ((zph = zpool_open_canfail(hdl, pool_name)) != NULL) {
261 		if (hdl->libzfs_pool_handles != NULL)
262 			zph->zpool_next = hdl->libzfs_pool_handles;
263 		hdl->libzfs_pool_handles = zph;
264 	}
265 	return (zph);
266 }
267 
268 static zpool_handle_t *
269 zpool_find_handle(zfs_handle_t *zhp, const char *pool_name, int len)
270 {
271 	libzfs_handle_t *hdl = zhp->zfs_hdl;
272 	zpool_handle_t *zph = hdl->libzfs_pool_handles;
273 
274 	while ((zph != NULL) &&
275 	    (strncmp(pool_name, zpool_get_name(zph), len) != 0))
276 		zph = zph->zpool_next;
277 	return (zph);
278 }
279 
280 /*
281  * Returns a handle to the pool that contains the provided dataset.
282  * If a handle to that pool already exists then that handle is returned.
283  * Otherwise, a new handle is created and added to the list of handles.
284  */
285 static zpool_handle_t *
286 zpool_handle(zfs_handle_t *zhp)
287 {
288 	char *pool_name;
289 	int len;
290 	zpool_handle_t *zph;
291 
292 	len = strcspn(zhp->zfs_name, "/@") + 1;
293 	pool_name = zfs_alloc(zhp->zfs_hdl, len);
294 	(void) strlcpy(pool_name, zhp->zfs_name, len);
295 
296 	zph = zpool_find_handle(zhp, pool_name, len);
297 	if (zph == NULL)
298 		zph = zpool_add_handle(zhp, pool_name);
299 
300 	free(pool_name);
301 	return (zph);
302 }
303 
304 void
305 zpool_free_handles(libzfs_handle_t *hdl)
306 {
307 	zpool_handle_t *next, *zph = hdl->libzfs_pool_handles;
308 
309 	while (zph != NULL) {
310 		next = zph->zpool_next;
311 		zpool_close(zph);
312 		zph = next;
313 	}
314 	hdl->libzfs_pool_handles = NULL;
315 }
316 
317 /*
318  * Utility function to gather stats (objset and zpl) for the given object.
319  */
320 static int
321 get_stats_ioctl(zfs_handle_t *zhp, zfs_cmd_t *zc)
322 {
323 	libzfs_handle_t *hdl = zhp->zfs_hdl;
324 
325 	(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
326 
327 	while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, zc) != 0) {
328 		if (errno == ENOMEM) {
329 			if (zcmd_expand_dst_nvlist(hdl, zc) != 0) {
330 				return (-1);
331 			}
332 		} else {
333 			return (-1);
334 		}
335 	}
336 	return (0);
337 }
338 
339 static int
340 put_stats_zhdl(zfs_handle_t *zhp, zfs_cmd_t *zc)
341 {
342 	nvlist_t *allprops, *userprops;
343 
344 	zhp->zfs_dmustats = zc->zc_objset_stats; /* structure assignment */
345 
346 	if (zcmd_read_dst_nvlist(zhp->zfs_hdl, zc, &allprops) != 0) {
347 		return (-1);
348 	}
349 
350 	/*
351 	 * XXX Why do we store the user props separately, in addition to
352 	 * storing them in zfs_props?
353 	 */
354 	if ((userprops = process_user_props(zhp, allprops)) == NULL) {
355 		nvlist_free(allprops);
356 		return (-1);
357 	}
358 
359 	nvlist_free(zhp->zfs_props);
360 	nvlist_free(zhp->zfs_user_props);
361 
362 	zhp->zfs_props = allprops;
363 	zhp->zfs_user_props = userprops;
364 
365 	return (0);
366 }
367 
368 static int
369 get_stats(zfs_handle_t *zhp)
370 {
371 	int rc = 0;
372 	zfs_cmd_t zc = { 0 };
373 
374 	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
375 		return (-1);
376 	if (get_stats_ioctl(zhp, &zc) != 0)
377 		rc = -1;
378 	else if (put_stats_zhdl(zhp, &zc) != 0)
379 		rc = -1;
380 	zcmd_free_nvlists(&zc);
381 	return (rc);
382 }
383 
384 /*
385  * Refresh the properties currently stored in the handle.
386  */
387 void
388 zfs_refresh_properties(zfs_handle_t *zhp)
389 {
390 	(void) get_stats(zhp);
391 }
392 
393 /*
394  * Makes a handle from the given dataset name.  Used by zfs_open() and
395  * zfs_iter_* to create child handles on the fly.
396  */
397 static int
398 make_dataset_handle_common(zfs_handle_t *zhp, zfs_cmd_t *zc)
399 {
400 	if (put_stats_zhdl(zhp, zc) != 0)
401 		return (-1);
402 
403 	/*
404 	 * We've managed to open the dataset and gather statistics.  Determine
405 	 * the high-level type.
406 	 */
407 	if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
408 		zhp->zfs_head_type = ZFS_TYPE_VOLUME;
409 	else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
410 		zhp->zfs_head_type = ZFS_TYPE_FILESYSTEM;
411 	else
412 		abort();
413 
414 	if (zhp->zfs_dmustats.dds_is_snapshot)
415 		zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
416 	else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
417 		zhp->zfs_type = ZFS_TYPE_VOLUME;
418 	else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
419 		zhp->zfs_type = ZFS_TYPE_FILESYSTEM;
420 	else
421 		abort();	/* we should never see any other types */
422 
423 	zhp->zpool_hdl = zpool_handle(zhp);
424 	return (0);
425 }
426 
427 zfs_handle_t *
428 make_dataset_handle(libzfs_handle_t *hdl, const char *path)
429 {
430 	zfs_cmd_t zc = { 0 };
431 
432 	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
433 
434 	if (zhp == NULL)
435 		return (NULL);
436 
437 	zhp->zfs_hdl = hdl;
438 	(void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
439 	if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0) {
440 		free(zhp);
441 		return (NULL);
442 	}
443 	if (get_stats_ioctl(zhp, &zc) == -1) {
444 		zcmd_free_nvlists(&zc);
445 		free(zhp);
446 		return (NULL);
447 	}
448 	if (make_dataset_handle_common(zhp, &zc) == -1) {
449 		free(zhp);
450 		zhp = NULL;
451 	}
452 	zcmd_free_nvlists(&zc);
453 	return (zhp);
454 }
455 
456 static zfs_handle_t *
457 make_dataset_handle_zc(libzfs_handle_t *hdl, zfs_cmd_t *zc)
458 {
459 	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
460 
461 	if (zhp == NULL)
462 		return (NULL);
463 
464 	zhp->zfs_hdl = hdl;
465 	(void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
466 	if (make_dataset_handle_common(zhp, zc) == -1) {
467 		free(zhp);
468 		return (NULL);
469 	}
470 	return (zhp);
471 }
472 
473 /*
474  * Opens the given snapshot, filesystem, or volume.   The 'types'
475  * argument is a mask of acceptable types.  The function will print an
476  * appropriate error message and return NULL if it can't be opened.
477  */
478 zfs_handle_t *
479 zfs_open(libzfs_handle_t *hdl, const char *path, int types)
480 {
481 	zfs_handle_t *zhp;
482 	char errbuf[1024];
483 
484 	(void) snprintf(errbuf, sizeof (errbuf),
485 	    dgettext(TEXT_DOMAIN, "cannot open '%s'"), path);
486 
487 	/*
488 	 * Validate the name before we even try to open it.
489 	 */
490 	if (!zfs_validate_name(hdl, path, ZFS_TYPE_DATASET, B_FALSE)) {
491 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
492 		    "invalid dataset name"));
493 		(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
494 		return (NULL);
495 	}
496 
497 	/*
498 	 * Try to get stats for the dataset, which will tell us if it exists.
499 	 */
500 	errno = 0;
501 	if ((zhp = make_dataset_handle(hdl, path)) == NULL) {
502 		(void) zfs_standard_error(hdl, errno, errbuf);
503 		return (NULL);
504 	}
505 
506 	if (!(types & zhp->zfs_type)) {
507 		(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
508 		zfs_close(zhp);
509 		return (NULL);
510 	}
511 
512 	return (zhp);
513 }
514 
515 /*
516  * Release a ZFS handle.  Nothing to do but free the associated memory.
517  */
518 void
519 zfs_close(zfs_handle_t *zhp)
520 {
521 	if (zhp->zfs_mntopts)
522 		free(zhp->zfs_mntopts);
523 	nvlist_free(zhp->zfs_props);
524 	nvlist_free(zhp->zfs_user_props);
525 	free(zhp);
526 }
527 
528 typedef struct mnttab_node {
529 	struct mnttab mtn_mt;
530 	avl_node_t mtn_node;
531 } mnttab_node_t;
532 
533 static int
534 libzfs_mnttab_cache_compare(const void *arg1, const void *arg2)
535 {
536 	const mnttab_node_t *mtn1 = arg1;
537 	const mnttab_node_t *mtn2 = arg2;
538 	int rv;
539 
540 	rv = strcmp(mtn1->mtn_mt.mnt_special, mtn2->mtn_mt.mnt_special);
541 
542 	if (rv == 0)
543 		return (0);
544 	return (rv > 0 ? 1 : -1);
545 }
546 
547 void
548 libzfs_mnttab_init(libzfs_handle_t *hdl)
549 {
550 	assert(avl_numnodes(&hdl->libzfs_mnttab_cache) == 0);
551 	avl_create(&hdl->libzfs_mnttab_cache, libzfs_mnttab_cache_compare,
552 	    sizeof (mnttab_node_t), offsetof(mnttab_node_t, mtn_node));
553 }
554 
555 void
556 libzfs_mnttab_update(libzfs_handle_t *hdl)
557 {
558 	struct mnttab entry;
559 
560 	rewind(hdl->libzfs_mnttab);
561 	while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
562 		mnttab_node_t *mtn;
563 
564 		if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
565 			continue;
566 		mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
567 		mtn->mtn_mt.mnt_special = zfs_strdup(hdl, entry.mnt_special);
568 		mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, entry.mnt_mountp);
569 		mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, entry.mnt_fstype);
570 		mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, entry.mnt_mntopts);
571 		avl_add(&hdl->libzfs_mnttab_cache, mtn);
572 	}
573 }
574 
575 void
576 libzfs_mnttab_fini(libzfs_handle_t *hdl)
577 {
578 	void *cookie = NULL;
579 	mnttab_node_t *mtn;
580 
581 	while (mtn = avl_destroy_nodes(&hdl->libzfs_mnttab_cache, &cookie)) {
582 		free(mtn->mtn_mt.mnt_special);
583 		free(mtn->mtn_mt.mnt_mountp);
584 		free(mtn->mtn_mt.mnt_fstype);
585 		free(mtn->mtn_mt.mnt_mntopts);
586 		free(mtn);
587 	}
588 	avl_destroy(&hdl->libzfs_mnttab_cache);
589 }
590 
591 void
592 libzfs_mnttab_cache(libzfs_handle_t *hdl, boolean_t enable)
593 {
594 	hdl->libzfs_mnttab_enable = enable;
595 }
596 
597 int
598 libzfs_mnttab_find(libzfs_handle_t *hdl, const char *fsname,
599     struct mnttab *entry)
600 {
601 	mnttab_node_t find;
602 	mnttab_node_t *mtn;
603 
604 	if (!hdl->libzfs_mnttab_enable) {
605 		struct mnttab srch = { 0 };
606 
607 		if (avl_numnodes(&hdl->libzfs_mnttab_cache))
608 			libzfs_mnttab_fini(hdl);
609 		rewind(hdl->libzfs_mnttab);
610 		srch.mnt_special = (char *)fsname;
611 		srch.mnt_fstype = MNTTYPE_ZFS;
612 		if (getmntany(hdl->libzfs_mnttab, entry, &srch) == 0)
613 			return (0);
614 		else
615 			return (ENOENT);
616 	}
617 
618 	if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
619 		libzfs_mnttab_update(hdl);
620 
621 	find.mtn_mt.mnt_special = (char *)fsname;
622 	mtn = avl_find(&hdl->libzfs_mnttab_cache, &find, NULL);
623 	if (mtn) {
624 		*entry = mtn->mtn_mt;
625 		return (0);
626 	}
627 	return (ENOENT);
628 }
629 
630 void
631 libzfs_mnttab_add(libzfs_handle_t *hdl, const char *special,
632     const char *mountp, const char *mntopts)
633 {
634 	mnttab_node_t *mtn;
635 
636 	if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
637 		return;
638 	mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
639 	mtn->mtn_mt.mnt_special = zfs_strdup(hdl, special);
640 	mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, mountp);
641 	mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, MNTTYPE_ZFS);
642 	mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, mntopts);
643 	avl_add(&hdl->libzfs_mnttab_cache, mtn);
644 }
645 
646 void
647 libzfs_mnttab_remove(libzfs_handle_t *hdl, const char *fsname)
648 {
649 	mnttab_node_t find;
650 	mnttab_node_t *ret;
651 
652 	find.mtn_mt.mnt_special = (char *)fsname;
653 	if (ret = avl_find(&hdl->libzfs_mnttab_cache, (void *)&find, NULL)) {
654 		avl_remove(&hdl->libzfs_mnttab_cache, ret);
655 		free(ret->mtn_mt.mnt_special);
656 		free(ret->mtn_mt.mnt_mountp);
657 		free(ret->mtn_mt.mnt_fstype);
658 		free(ret->mtn_mt.mnt_mntopts);
659 		free(ret);
660 	}
661 }
662 
663 int
664 zfs_spa_version(zfs_handle_t *zhp, int *spa_version)
665 {
666 	zpool_handle_t *zpool_handle = zhp->zpool_hdl;
667 
668 	if (zpool_handle == NULL)
669 		return (-1);
670 
671 	*spa_version = zpool_get_prop_int(zpool_handle,
672 	    ZPOOL_PROP_VERSION, NULL);
673 	return (0);
674 }
675 
676 /*
677  * The choice of reservation property depends on the SPA version.
678  */
679 static int
680 zfs_which_resv_prop(zfs_handle_t *zhp, zfs_prop_t *resv_prop)
681 {
682 	int spa_version;
683 
684 	if (zfs_spa_version(zhp, &spa_version) < 0)
685 		return (-1);
686 
687 	if (spa_version >= SPA_VERSION_REFRESERVATION)
688 		*resv_prop = ZFS_PROP_REFRESERVATION;
689 	else
690 		*resv_prop = ZFS_PROP_RESERVATION;
691 
692 	return (0);
693 }
694 
695 /*
696  * Given an nvlist of properties to set, validates that they are correct, and
697  * parses any numeric properties (index, boolean, etc) if they are specified as
698  * strings.
699  */
700 nvlist_t *
701 zfs_valid_proplist(libzfs_handle_t *hdl, zfs_type_t type, nvlist_t *nvl,
702     uint64_t zoned, zfs_handle_t *zhp, const char *errbuf)
703 {
704 	nvpair_t *elem;
705 	uint64_t intval;
706 	char *strval;
707 	zfs_prop_t prop;
708 	nvlist_t *ret;
709 	int chosen_normal = -1;
710 	int chosen_utf = -1;
711 
712 	if (nvlist_alloc(&ret, NV_UNIQUE_NAME, 0) != 0) {
713 		(void) no_memory(hdl);
714 		return (NULL);
715 	}
716 
717 	/*
718 	 * Make sure this property is valid and applies to this type.
719 	 */
720 
721 	elem = NULL;
722 	while ((elem = nvlist_next_nvpair(nvl, elem)) != NULL) {
723 		const char *propname = nvpair_name(elem);
724 
725 		prop = zfs_name_to_prop(propname);
726 		if (prop == ZPROP_INVAL && zfs_prop_user(propname)) {
727 			/*
728 			 * This is a user property: make sure it's a
729 			 * string, and that it's less than ZAP_MAXNAMELEN.
730 			 */
731 			if (nvpair_type(elem) != DATA_TYPE_STRING) {
732 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
733 				    "'%s' must be a string"), propname);
734 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
735 				goto error;
736 			}
737 
738 			if (strlen(nvpair_name(elem)) >= ZAP_MAXNAMELEN) {
739 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
740 				    "property name '%s' is too long"),
741 				    propname);
742 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
743 				goto error;
744 			}
745 
746 			(void) nvpair_value_string(elem, &strval);
747 			if (nvlist_add_string(ret, propname, strval) != 0) {
748 				(void) no_memory(hdl);
749 				goto error;
750 			}
751 			continue;
752 		}
753 
754 		/*
755 		 * Currently, only user properties can be modified on
756 		 * snapshots.
757 		 */
758 		if (type == ZFS_TYPE_SNAPSHOT) {
759 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
760 			    "this property can not be modified for snapshots"));
761 			(void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
762 			goto error;
763 		}
764 
765 		if (prop == ZPROP_INVAL && zfs_prop_userquota(propname)) {
766 			zfs_userquota_prop_t uqtype;
767 			char newpropname[128];
768 			char domain[128];
769 			uint64_t rid;
770 			uint64_t valary[3];
771 
772 			if (userquota_propname_decode(propname, zoned,
773 			    &uqtype, domain, sizeof (domain), &rid) != 0) {
774 				zfs_error_aux(hdl,
775 				    dgettext(TEXT_DOMAIN,
776 				    "'%s' has an invalid user/group name"),
777 				    propname);
778 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
779 				goto error;
780 			}
781 
782 			if (uqtype != ZFS_PROP_USERQUOTA &&
783 			    uqtype != ZFS_PROP_GROUPQUOTA) {
784 				zfs_error_aux(hdl,
785 				    dgettext(TEXT_DOMAIN, "'%s' is readonly"),
786 				    propname);
787 				(void) zfs_error(hdl, EZFS_PROPREADONLY,
788 				    errbuf);
789 				goto error;
790 			}
791 
792 			if (nvpair_type(elem) == DATA_TYPE_STRING) {
793 				(void) nvpair_value_string(elem, &strval);
794 				if (strcmp(strval, "none") == 0) {
795 					intval = 0;
796 				} else if (zfs_nicestrtonum(hdl,
797 				    strval, &intval) != 0) {
798 					(void) zfs_error(hdl,
799 					    EZFS_BADPROP, errbuf);
800 					goto error;
801 				}
802 			} else if (nvpair_type(elem) ==
803 			    DATA_TYPE_UINT64) {
804 				(void) nvpair_value_uint64(elem, &intval);
805 				if (intval == 0) {
806 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
807 					    "use 'none' to disable "
808 					    "userquota/groupquota"));
809 					goto error;
810 				}
811 			} else {
812 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
813 				    "'%s' must be a number"), propname);
814 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
815 				goto error;
816 			}
817 
818 			(void) snprintf(newpropname, sizeof (newpropname),
819 			    "%s%s", zfs_userquota_prop_prefixes[uqtype],
820 			    domain);
821 			valary[0] = uqtype;
822 			valary[1] = rid;
823 			valary[2] = intval;
824 			if (nvlist_add_uint64_array(ret, newpropname,
825 			    valary, 3) != 0) {
826 				(void) no_memory(hdl);
827 				goto error;
828 			}
829 			continue;
830 		}
831 
832 		if (prop == ZPROP_INVAL) {
833 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
834 			    "invalid property '%s'"), propname);
835 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
836 			goto error;
837 		}
838 
839 		if (!zfs_prop_valid_for_type(prop, type)) {
840 			zfs_error_aux(hdl,
841 			    dgettext(TEXT_DOMAIN, "'%s' does not "
842 			    "apply to datasets of this type"), propname);
843 			(void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
844 			goto error;
845 		}
846 
847 		if (zfs_prop_readonly(prop) &&
848 		    (!zfs_prop_setonce(prop) || zhp != NULL)) {
849 			zfs_error_aux(hdl,
850 			    dgettext(TEXT_DOMAIN, "'%s' is readonly"),
851 			    propname);
852 			(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
853 			goto error;
854 		}
855 
856 		if (zprop_parse_value(hdl, elem, prop, type, ret,
857 		    &strval, &intval, errbuf) != 0)
858 			goto error;
859 
860 		/*
861 		 * Perform some additional checks for specific properties.
862 		 */
863 		switch (prop) {
864 		case ZFS_PROP_VERSION:
865 		{
866 			int version;
867 
868 			if (zhp == NULL)
869 				break;
870 			version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
871 			if (intval < version) {
872 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
873 				    "Can not downgrade; already at version %u"),
874 				    version);
875 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
876 				goto error;
877 			}
878 			break;
879 		}
880 
881 		case ZFS_PROP_RECORDSIZE:
882 		case ZFS_PROP_VOLBLOCKSIZE:
883 			/* must be power of two within SPA_{MIN,MAX}BLOCKSIZE */
884 			if (intval < SPA_MINBLOCKSIZE ||
885 			    intval > SPA_MAXBLOCKSIZE || !ISP2(intval)) {
886 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
887 				    "'%s' must be power of 2 from %u "
888 				    "to %uk"), propname,
889 				    (uint_t)SPA_MINBLOCKSIZE,
890 				    (uint_t)SPA_MAXBLOCKSIZE >> 10);
891 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
892 				goto error;
893 			}
894 			break;
895 
896 		case ZFS_PROP_SHAREISCSI:
897 			if (strcmp(strval, "off") != 0 &&
898 			    strcmp(strval, "on") != 0 &&
899 			    strcmp(strval, "type=disk") != 0) {
900 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
901 				    "'%s' must be 'on', 'off', or 'type=disk'"),
902 				    propname);
903 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
904 				goto error;
905 			}
906 
907 			break;
908 
909 		case ZFS_PROP_MOUNTPOINT:
910 		{
911 			namecheck_err_t why;
912 
913 			if (strcmp(strval, ZFS_MOUNTPOINT_NONE) == 0 ||
914 			    strcmp(strval, ZFS_MOUNTPOINT_LEGACY) == 0)
915 				break;
916 
917 			if (mountpoint_namecheck(strval, &why)) {
918 				switch (why) {
919 				case NAME_ERR_LEADING_SLASH:
920 					zfs_error_aux(hdl,
921 					    dgettext(TEXT_DOMAIN,
922 					    "'%s' must be an absolute path, "
923 					    "'none', or 'legacy'"), propname);
924 					break;
925 				case NAME_ERR_TOOLONG:
926 					zfs_error_aux(hdl,
927 					    dgettext(TEXT_DOMAIN,
928 					    "component of '%s' is too long"),
929 					    propname);
930 					break;
931 				}
932 				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
933 				goto error;
934 			}
935 		}
936 
937 			/*FALLTHRU*/
938 
939 		case ZFS_PROP_SHARESMB:
940 		case ZFS_PROP_SHARENFS:
941 			/*
942 			 * For the mountpoint and sharenfs or sharesmb
943 			 * properties, check if it can be set in a
944 			 * global/non-global zone based on
945 			 * the zoned property value:
946 			 *
947 			 *		global zone	    non-global zone
948 			 * --------------------------------------------------
949 			 * zoned=on	mountpoint (no)	    mountpoint (yes)
950 			 *		sharenfs (no)	    sharenfs (no)
951 			 *		sharesmb (no)	    sharesmb (no)
952 			 *
953 			 * zoned=off	mountpoint (yes)	N/A
954 			 *		sharenfs (yes)
955 			 *		sharesmb (yes)
956 			 */
957 			if (zoned) {
958 				if (getzoneid() == GLOBAL_ZONEID) {
959 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
960 					    "'%s' cannot be set on "
961 					    "dataset in a non-global zone"),
962 					    propname);
963 					(void) zfs_error(hdl, EZFS_ZONED,
964 					    errbuf);
965 					goto error;
966 				} else if (prop == ZFS_PROP_SHARENFS ||
967 				    prop == ZFS_PROP_SHARESMB) {
968 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
969 					    "'%s' cannot be set in "
970 					    "a non-global zone"), propname);
971 					(void) zfs_error(hdl, EZFS_ZONED,
972 					    errbuf);
973 					goto error;
974 				}
975 			} else if (getzoneid() != GLOBAL_ZONEID) {
976 				/*
977 				 * If zoned property is 'off', this must be in
978 				 * a global zone. If not, something is wrong.
979 				 */
980 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
981 				    "'%s' cannot be set while dataset "
982 				    "'zoned' property is set"), propname);
983 				(void) zfs_error(hdl, EZFS_ZONED, errbuf);
984 				goto error;
985 			}
986 
987 			/*
988 			 * At this point, it is legitimate to set the
989 			 * property. Now we want to make sure that the
990 			 * property value is valid if it is sharenfs.
991 			 */
992 			if ((prop == ZFS_PROP_SHARENFS ||
993 			    prop == ZFS_PROP_SHARESMB) &&
994 			    strcmp(strval, "on") != 0 &&
995 			    strcmp(strval, "off") != 0) {
996 				zfs_share_proto_t proto;
997 
998 				if (prop == ZFS_PROP_SHARESMB)
999 					proto = PROTO_SMB;
1000 				else
1001 					proto = PROTO_NFS;
1002 
1003 				/*
1004 				 * Must be an valid sharing protocol
1005 				 * option string so init the libshare
1006 				 * in order to enable the parser and
1007 				 * then parse the options. We use the
1008 				 * control API since we don't care about
1009 				 * the current configuration and don't
1010 				 * want the overhead of loading it
1011 				 * until we actually do something.
1012 				 */
1013 
1014 				if (zfs_init_libshare(hdl,
1015 				    SA_INIT_CONTROL_API) != SA_OK) {
1016 					/*
1017 					 * An error occurred so we can't do
1018 					 * anything
1019 					 */
1020 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1021 					    "'%s' cannot be set: problem "
1022 					    "in share initialization"),
1023 					    propname);
1024 					(void) zfs_error(hdl, EZFS_BADPROP,
1025 					    errbuf);
1026 					goto error;
1027 				}
1028 
1029 				if (zfs_parse_options(strval, proto) != SA_OK) {
1030 					/*
1031 					 * There was an error in parsing so
1032 					 * deal with it by issuing an error
1033 					 * message and leaving after
1034 					 * uninitializing the the libshare
1035 					 * interface.
1036 					 */
1037 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1038 					    "'%s' cannot be set to invalid "
1039 					    "options"), propname);
1040 					(void) zfs_error(hdl, EZFS_BADPROP,
1041 					    errbuf);
1042 					zfs_uninit_libshare(hdl);
1043 					goto error;
1044 				}
1045 				zfs_uninit_libshare(hdl);
1046 			}
1047 
1048 			break;
1049 		case ZFS_PROP_UTF8ONLY:
1050 			chosen_utf = (int)intval;
1051 			break;
1052 		case ZFS_PROP_NORMALIZE:
1053 			chosen_normal = (int)intval;
1054 			break;
1055 		}
1056 
1057 		/*
1058 		 * For changes to existing volumes, we have some additional
1059 		 * checks to enforce.
1060 		 */
1061 		if (type == ZFS_TYPE_VOLUME && zhp != NULL) {
1062 			uint64_t volsize = zfs_prop_get_int(zhp,
1063 			    ZFS_PROP_VOLSIZE);
1064 			uint64_t blocksize = zfs_prop_get_int(zhp,
1065 			    ZFS_PROP_VOLBLOCKSIZE);
1066 			char buf[64];
1067 
1068 			switch (prop) {
1069 			case ZFS_PROP_RESERVATION:
1070 			case ZFS_PROP_REFRESERVATION:
1071 				if (intval > volsize) {
1072 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1073 					    "'%s' is greater than current "
1074 					    "volume size"), propname);
1075 					(void) zfs_error(hdl, EZFS_BADPROP,
1076 					    errbuf);
1077 					goto error;
1078 				}
1079 				break;
1080 
1081 			case ZFS_PROP_VOLSIZE:
1082 				if (intval % blocksize != 0) {
1083 					zfs_nicenum(blocksize, buf,
1084 					    sizeof (buf));
1085 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1086 					    "'%s' must be a multiple of "
1087 					    "volume block size (%s)"),
1088 					    propname, buf);
1089 					(void) zfs_error(hdl, EZFS_BADPROP,
1090 					    errbuf);
1091 					goto error;
1092 				}
1093 
1094 				if (intval == 0) {
1095 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1096 					    "'%s' cannot be zero"),
1097 					    propname);
1098 					(void) zfs_error(hdl, EZFS_BADPROP,
1099 					    errbuf);
1100 					goto error;
1101 				}
1102 				break;
1103 			}
1104 		}
1105 	}
1106 
1107 	/*
1108 	 * If normalization was chosen, but no UTF8 choice was made,
1109 	 * enforce rejection of non-UTF8 names.
1110 	 *
1111 	 * If normalization was chosen, but rejecting non-UTF8 names
1112 	 * was explicitly not chosen, it is an error.
1113 	 */
1114 	if (chosen_normal > 0 && chosen_utf < 0) {
1115 		if (nvlist_add_uint64(ret,
1116 		    zfs_prop_to_name(ZFS_PROP_UTF8ONLY), 1) != 0) {
1117 			(void) no_memory(hdl);
1118 			goto error;
1119 		}
1120 	} else if (chosen_normal > 0 && chosen_utf == 0) {
1121 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1122 		    "'%s' must be set 'on' if normalization chosen"),
1123 		    zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
1124 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1125 		goto error;
1126 	}
1127 
1128 	/*
1129 	 * If this is an existing volume, and someone is setting the volsize,
1130 	 * make sure that it matches the reservation, or add it if necessary.
1131 	 */
1132 	if (zhp != NULL && type == ZFS_TYPE_VOLUME &&
1133 	    nvlist_lookup_uint64(ret, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1134 	    &intval) == 0) {
1135 		uint64_t old_volsize = zfs_prop_get_int(zhp,
1136 		    ZFS_PROP_VOLSIZE);
1137 		uint64_t old_reservation;
1138 		uint64_t new_reservation;
1139 		zfs_prop_t resv_prop;
1140 
1141 		if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
1142 			goto error;
1143 		old_reservation = zfs_prop_get_int(zhp, resv_prop);
1144 
1145 		if (old_volsize == old_reservation &&
1146 		    nvlist_lookup_uint64(ret, zfs_prop_to_name(resv_prop),
1147 		    &new_reservation) != 0) {
1148 			if (nvlist_add_uint64(ret,
1149 			    zfs_prop_to_name(resv_prop), intval) != 0) {
1150 				(void) no_memory(hdl);
1151 				goto error;
1152 			}
1153 		}
1154 	}
1155 	return (ret);
1156 
1157 error:
1158 	nvlist_free(ret);
1159 	return (NULL);
1160 }
1161 
1162 /*
1163  * Given a property name and value, set the property for the given dataset.
1164  */
1165 int
1166 zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
1167 {
1168 	zfs_cmd_t zc = { 0 };
1169 	int ret = -1;
1170 	prop_changelist_t *cl = NULL;
1171 	char errbuf[1024];
1172 	libzfs_handle_t *hdl = zhp->zfs_hdl;
1173 	nvlist_t *nvl = NULL, *realprops;
1174 	zfs_prop_t prop;
1175 	boolean_t do_prefix;
1176 	uint64_t idx;
1177 
1178 	(void) snprintf(errbuf, sizeof (errbuf),
1179 	    dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1180 	    zhp->zfs_name);
1181 
1182 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
1183 	    nvlist_add_string(nvl, propname, propval) != 0) {
1184 		(void) no_memory(hdl);
1185 		goto error;
1186 	}
1187 
1188 	if ((realprops = zfs_valid_proplist(hdl, zhp->zfs_type, nvl,
1189 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, errbuf)) == NULL)
1190 		goto error;
1191 
1192 	nvlist_free(nvl);
1193 	nvl = realprops;
1194 
1195 	prop = zfs_name_to_prop(propname);
1196 
1197 	if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1198 		goto error;
1199 
1200 	if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1201 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1202 		    "child dataset with inherited mountpoint is used "
1203 		    "in a non-global zone"));
1204 		ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1205 		goto error;
1206 	}
1207 
1208 	/*
1209 	 * If the dataset's canmount property is being set to noauto,
1210 	 * then we want to prevent unmounting & remounting it.
1211 	 */
1212 	do_prefix = !((prop == ZFS_PROP_CANMOUNT) &&
1213 	    (zprop_string_to_index(prop, propval, &idx,
1214 	    ZFS_TYPE_DATASET) == 0) && (idx == ZFS_CANMOUNT_NOAUTO));
1215 
1216 	if (do_prefix && (ret = changelist_prefix(cl)) != 0)
1217 		goto error;
1218 
1219 	/*
1220 	 * Execute the corresponding ioctl() to set this property.
1221 	 */
1222 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1223 
1224 	if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1225 		goto error;
1226 
1227 	ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1228 
1229 	if (ret != 0) {
1230 		switch (errno) {
1231 
1232 		case ENOSPC:
1233 			/*
1234 			 * For quotas and reservations, ENOSPC indicates
1235 			 * something different; setting a quota or reservation
1236 			 * doesn't use any disk space.
1237 			 */
1238 			switch (prop) {
1239 			case ZFS_PROP_QUOTA:
1240 			case ZFS_PROP_REFQUOTA:
1241 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1242 				    "size is less than current used or "
1243 				    "reserved space"));
1244 				(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1245 				break;
1246 
1247 			case ZFS_PROP_RESERVATION:
1248 			case ZFS_PROP_REFRESERVATION:
1249 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1250 				    "size is greater than available space"));
1251 				(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1252 				break;
1253 
1254 			default:
1255 				(void) zfs_standard_error(hdl, errno, errbuf);
1256 				break;
1257 			}
1258 			break;
1259 
1260 		case EBUSY:
1261 			(void) zfs_standard_error(hdl, EBUSY, errbuf);
1262 			break;
1263 
1264 		case EROFS:
1265 			(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
1266 			break;
1267 
1268 		case ENOTSUP:
1269 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1270 			    "pool and or dataset must be upgraded to set this "
1271 			    "property or value"));
1272 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
1273 			break;
1274 
1275 		case ERANGE:
1276 			if (prop == ZFS_PROP_COMPRESSION) {
1277 				(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1278 				    "property setting is not allowed on "
1279 				    "bootable datasets"));
1280 				(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
1281 			} else {
1282 				(void) zfs_standard_error(hdl, errno, errbuf);
1283 			}
1284 			break;
1285 
1286 		case EOVERFLOW:
1287 			/*
1288 			 * This platform can't address a volume this big.
1289 			 */
1290 #ifdef _ILP32
1291 			if (prop == ZFS_PROP_VOLSIZE) {
1292 				(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
1293 				break;
1294 			}
1295 #endif
1296 			/* FALLTHROUGH */
1297 		default:
1298 			(void) zfs_standard_error(hdl, errno, errbuf);
1299 		}
1300 	} else {
1301 		if (do_prefix)
1302 			ret = changelist_postfix(cl);
1303 
1304 		/*
1305 		 * Refresh the statistics so the new property value
1306 		 * is reflected.
1307 		 */
1308 		if (ret == 0)
1309 			(void) get_stats(zhp);
1310 	}
1311 
1312 error:
1313 	nvlist_free(nvl);
1314 	zcmd_free_nvlists(&zc);
1315 	if (cl)
1316 		changelist_free(cl);
1317 	return (ret);
1318 }
1319 
1320 /*
1321  * Given a property, inherit the value from the parent dataset.
1322  */
1323 int
1324 zfs_prop_inherit(zfs_handle_t *zhp, const char *propname)
1325 {
1326 	zfs_cmd_t zc = { 0 };
1327 	int ret;
1328 	prop_changelist_t *cl;
1329 	libzfs_handle_t *hdl = zhp->zfs_hdl;
1330 	char errbuf[1024];
1331 	zfs_prop_t prop;
1332 
1333 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1334 	    "cannot inherit %s for '%s'"), propname, zhp->zfs_name);
1335 
1336 	if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
1337 		/*
1338 		 * For user properties, the amount of work we have to do is very
1339 		 * small, so just do it here.
1340 		 */
1341 		if (!zfs_prop_user(propname)) {
1342 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1343 			    "invalid property"));
1344 			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1345 		}
1346 
1347 		(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1348 		(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1349 
1350 		if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
1351 			return (zfs_standard_error(hdl, errno, errbuf));
1352 
1353 		return (0);
1354 	}
1355 
1356 	/*
1357 	 * Verify that this property is inheritable.
1358 	 */
1359 	if (zfs_prop_readonly(prop))
1360 		return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
1361 
1362 	if (!zfs_prop_inheritable(prop))
1363 		return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
1364 
1365 	/*
1366 	 * Check to see if the value applies to this type
1367 	 */
1368 	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1369 		return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
1370 
1371 	/*
1372 	 * Normalize the name, to get rid of shorthand abbrevations.
1373 	 */
1374 	propname = zfs_prop_to_name(prop);
1375 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1376 	(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
1377 
1378 	if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
1379 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
1380 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1381 		    "dataset is used in a non-global zone"));
1382 		return (zfs_error(hdl, EZFS_ZONED, errbuf));
1383 	}
1384 
1385 	/*
1386 	 * Determine datasets which will be affected by this change, if any.
1387 	 */
1388 	if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
1389 		return (-1);
1390 
1391 	if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
1392 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1393 		    "child dataset with inherited mountpoint is used "
1394 		    "in a non-global zone"));
1395 		ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1396 		goto error;
1397 	}
1398 
1399 	if ((ret = changelist_prefix(cl)) != 0)
1400 		goto error;
1401 
1402 	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
1403 		return (zfs_standard_error(hdl, errno, errbuf));
1404 	} else {
1405 
1406 		if ((ret = changelist_postfix(cl)) != 0)
1407 			goto error;
1408 
1409 		/*
1410 		 * Refresh the statistics so the new property is reflected.
1411 		 */
1412 		(void) get_stats(zhp);
1413 	}
1414 
1415 error:
1416 	changelist_free(cl);
1417 	return (ret);
1418 }
1419 
1420 /*
1421  * True DSL properties are stored in an nvlist.  The following two functions
1422  * extract them appropriately.
1423  */
1424 static uint64_t
1425 getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1426 {
1427 	nvlist_t *nv;
1428 	uint64_t value;
1429 
1430 	*source = NULL;
1431 	if (nvlist_lookup_nvlist(zhp->zfs_props,
1432 	    zfs_prop_to_name(prop), &nv) == 0) {
1433 		verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
1434 		(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1435 	} else {
1436 		verify(!zhp->zfs_props_table ||
1437 		    zhp->zfs_props_table[prop] == B_TRUE);
1438 		value = zfs_prop_default_numeric(prop);
1439 		*source = "";
1440 	}
1441 
1442 	return (value);
1443 }
1444 
1445 static char *
1446 getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
1447 {
1448 	nvlist_t *nv;
1449 	char *value;
1450 
1451 	*source = NULL;
1452 	if (nvlist_lookup_nvlist(zhp->zfs_props,
1453 	    zfs_prop_to_name(prop), &nv) == 0) {
1454 		verify(nvlist_lookup_string(nv, ZPROP_VALUE, &value) == 0);
1455 		(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
1456 	} else {
1457 		verify(!zhp->zfs_props_table ||
1458 		    zhp->zfs_props_table[prop] == B_TRUE);
1459 		if ((value = (char *)zfs_prop_default_string(prop)) == NULL)
1460 			value = "";
1461 		*source = "";
1462 	}
1463 
1464 	return (value);
1465 }
1466 
1467 /*
1468  * Internal function for getting a numeric property.  Both zfs_prop_get() and
1469  * zfs_prop_get_int() are built using this interface.
1470  *
1471  * Certain properties can be overridden using 'mount -o'.  In this case, scan
1472  * the contents of the /etc/mnttab entry, searching for the appropriate options.
1473  * If they differ from the on-disk values, report the current values and mark
1474  * the source "temporary".
1475  */
1476 static int
1477 get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
1478     char **source, uint64_t *val)
1479 {
1480 	zfs_cmd_t zc = { 0 };
1481 	nvlist_t *zplprops = NULL;
1482 	struct mnttab mnt;
1483 	char *mntopt_on = NULL;
1484 	char *mntopt_off = NULL;
1485 
1486 	*source = NULL;
1487 
1488 	switch (prop) {
1489 	case ZFS_PROP_ATIME:
1490 		mntopt_on = MNTOPT_ATIME;
1491 		mntopt_off = MNTOPT_NOATIME;
1492 		break;
1493 
1494 	case ZFS_PROP_DEVICES:
1495 		mntopt_on = MNTOPT_DEVICES;
1496 		mntopt_off = MNTOPT_NODEVICES;
1497 		break;
1498 
1499 	case ZFS_PROP_EXEC:
1500 		mntopt_on = MNTOPT_EXEC;
1501 		mntopt_off = MNTOPT_NOEXEC;
1502 		break;
1503 
1504 	case ZFS_PROP_READONLY:
1505 		mntopt_on = MNTOPT_RO;
1506 		mntopt_off = MNTOPT_RW;
1507 		break;
1508 
1509 	case ZFS_PROP_SETUID:
1510 		mntopt_on = MNTOPT_SETUID;
1511 		mntopt_off = MNTOPT_NOSETUID;
1512 		break;
1513 
1514 	case ZFS_PROP_XATTR:
1515 		mntopt_on = MNTOPT_XATTR;
1516 		mntopt_off = MNTOPT_NOXATTR;
1517 		break;
1518 
1519 	case ZFS_PROP_NBMAND:
1520 		mntopt_on = MNTOPT_NBMAND;
1521 		mntopt_off = MNTOPT_NONBMAND;
1522 		break;
1523 	}
1524 
1525 	/*
1526 	 * Because looking up the mount options is potentially expensive
1527 	 * (iterating over all of /etc/mnttab), we defer its calculation until
1528 	 * we're looking up a property which requires its presence.
1529 	 */
1530 	if (!zhp->zfs_mntcheck &&
1531 	    (mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
1532 		libzfs_handle_t *hdl = zhp->zfs_hdl;
1533 		struct mnttab entry;
1534 
1535 		if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
1536 			zhp->zfs_mntopts = zfs_strdup(hdl,
1537 			    entry.mnt_mntopts);
1538 			if (zhp->zfs_mntopts == NULL)
1539 				return (-1);
1540 		}
1541 
1542 		zhp->zfs_mntcheck = B_TRUE;
1543 	}
1544 
1545 	if (zhp->zfs_mntopts == NULL)
1546 		mnt.mnt_mntopts = "";
1547 	else
1548 		mnt.mnt_mntopts = zhp->zfs_mntopts;
1549 
1550 	switch (prop) {
1551 	case ZFS_PROP_ATIME:
1552 	case ZFS_PROP_DEVICES:
1553 	case ZFS_PROP_EXEC:
1554 	case ZFS_PROP_READONLY:
1555 	case ZFS_PROP_SETUID:
1556 	case ZFS_PROP_XATTR:
1557 	case ZFS_PROP_NBMAND:
1558 		*val = getprop_uint64(zhp, prop, source);
1559 
1560 		if (hasmntopt(&mnt, mntopt_on) && !*val) {
1561 			*val = B_TRUE;
1562 			if (src)
1563 				*src = ZPROP_SRC_TEMPORARY;
1564 		} else if (hasmntopt(&mnt, mntopt_off) && *val) {
1565 			*val = B_FALSE;
1566 			if (src)
1567 				*src = ZPROP_SRC_TEMPORARY;
1568 		}
1569 		break;
1570 
1571 	case ZFS_PROP_CANMOUNT:
1572 		*val = getprop_uint64(zhp, prop, source);
1573 		if (*val != ZFS_CANMOUNT_ON)
1574 			*source = zhp->zfs_name;
1575 		else
1576 			*source = "";	/* default */
1577 		break;
1578 
1579 	case ZFS_PROP_QUOTA:
1580 	case ZFS_PROP_REFQUOTA:
1581 	case ZFS_PROP_RESERVATION:
1582 	case ZFS_PROP_REFRESERVATION:
1583 		*val = getprop_uint64(zhp, prop, source);
1584 		if (*val == 0)
1585 			*source = "";	/* default */
1586 		else
1587 			*source = zhp->zfs_name;
1588 		break;
1589 
1590 	case ZFS_PROP_MOUNTED:
1591 		*val = (zhp->zfs_mntopts != NULL);
1592 		break;
1593 
1594 	case ZFS_PROP_NUMCLONES:
1595 		*val = zhp->zfs_dmustats.dds_num_clones;
1596 		break;
1597 
1598 	case ZFS_PROP_VERSION:
1599 	case ZFS_PROP_NORMALIZE:
1600 	case ZFS_PROP_UTF8ONLY:
1601 	case ZFS_PROP_CASE:
1602 		if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
1603 		    zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
1604 			return (-1);
1605 		(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1606 		if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
1607 			zcmd_free_nvlists(&zc);
1608 			return (-1);
1609 		}
1610 		if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
1611 		    nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
1612 		    val) != 0) {
1613 			zcmd_free_nvlists(&zc);
1614 			return (-1);
1615 		}
1616 		if (zplprops)
1617 			nvlist_free(zplprops);
1618 		zcmd_free_nvlists(&zc);
1619 		break;
1620 
1621 	default:
1622 		switch (zfs_prop_get_type(prop)) {
1623 		case PROP_TYPE_NUMBER:
1624 		case PROP_TYPE_INDEX:
1625 			*val = getprop_uint64(zhp, prop, source);
1626 			/*
1627 			 * If we tried to use a default value for a
1628 			 * readonly property, it means that it was not
1629 			 * present; return an error.
1630 			 */
1631 			if (zfs_prop_readonly(prop) &&
1632 			    *source && (*source)[0] == '\0') {
1633 				return (-1);
1634 			}
1635 			break;
1636 
1637 		case PROP_TYPE_STRING:
1638 		default:
1639 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
1640 			    "cannot get non-numeric property"));
1641 			return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
1642 			    dgettext(TEXT_DOMAIN, "internal error")));
1643 		}
1644 	}
1645 
1646 	return (0);
1647 }
1648 
1649 /*
1650  * Calculate the source type, given the raw source string.
1651  */
1652 static void
1653 get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
1654     char *statbuf, size_t statlen)
1655 {
1656 	if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
1657 		return;
1658 
1659 	if (source == NULL) {
1660 		*srctype = ZPROP_SRC_NONE;
1661 	} else if (source[0] == '\0') {
1662 		*srctype = ZPROP_SRC_DEFAULT;
1663 	} else {
1664 		if (strcmp(source, zhp->zfs_name) == 0) {
1665 			*srctype = ZPROP_SRC_LOCAL;
1666 		} else {
1667 			(void) strlcpy(statbuf, source, statlen);
1668 			*srctype = ZPROP_SRC_INHERITED;
1669 		}
1670 	}
1671 
1672 }
1673 
1674 /*
1675  * Retrieve a property from the given object.  If 'literal' is specified, then
1676  * numbers are left as exact values.  Otherwise, numbers are converted to a
1677  * human-readable form.
1678  *
1679  * Returns 0 on success, or -1 on error.
1680  */
1681 int
1682 zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
1683     zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
1684 {
1685 	char *source = NULL;
1686 	uint64_t val;
1687 	char *str;
1688 	const char *strval;
1689 
1690 	/*
1691 	 * Check to see if this property applies to our object
1692 	 */
1693 	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
1694 		return (-1);
1695 
1696 	if (src)
1697 		*src = ZPROP_SRC_NONE;
1698 
1699 	switch (prop) {
1700 	case ZFS_PROP_CREATION:
1701 		/*
1702 		 * 'creation' is a time_t stored in the statistics.  We convert
1703 		 * this into a string unless 'literal' is specified.
1704 		 */
1705 		{
1706 			val = getprop_uint64(zhp, prop, &source);
1707 			time_t time = (time_t)val;
1708 			struct tm t;
1709 
1710 			if (literal ||
1711 			    localtime_r(&time, &t) == NULL ||
1712 			    strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
1713 			    &t) == 0)
1714 				(void) snprintf(propbuf, proplen, "%llu", val);
1715 		}
1716 		break;
1717 
1718 	case ZFS_PROP_MOUNTPOINT:
1719 		/*
1720 		 * Getting the precise mountpoint can be tricky.
1721 		 *
1722 		 *  - for 'none' or 'legacy', return those values.
1723 		 *  - for inherited mountpoints, we want to take everything
1724 		 *    after our ancestor and append it to the inherited value.
1725 		 *
1726 		 * If the pool has an alternate root, we want to prepend that
1727 		 * root to any values we return.
1728 		 */
1729 
1730 		str = getprop_string(zhp, prop, &source);
1731 
1732 		if (str[0] == '/') {
1733 			char buf[MAXPATHLEN];
1734 			char *root = buf;
1735 			const char *relpath = zhp->zfs_name + strlen(source);
1736 
1737 			if (relpath[0] == '/')
1738 				relpath++;
1739 
1740 			if ((zpool_get_prop(zhp->zpool_hdl,
1741 			    ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL)) ||
1742 			    (strcmp(root, "-") == 0))
1743 				root[0] = '\0';
1744 			/*
1745 			 * Special case an alternate root of '/'. This will
1746 			 * avoid having multiple leading slashes in the
1747 			 * mountpoint path.
1748 			 */
1749 			if (strcmp(root, "/") == 0)
1750 				root++;
1751 
1752 			/*
1753 			 * If the mountpoint is '/' then skip over this
1754 			 * if we are obtaining either an alternate root or
1755 			 * an inherited mountpoint.
1756 			 */
1757 			if (str[1] == '\0' && (root[0] != '\0' ||
1758 			    relpath[0] != '\0'))
1759 				str++;
1760 
1761 			if (relpath[0] == '\0')
1762 				(void) snprintf(propbuf, proplen, "%s%s",
1763 				    root, str);
1764 			else
1765 				(void) snprintf(propbuf, proplen, "%s%s%s%s",
1766 				    root, str, relpath[0] == '@' ? "" : "/",
1767 				    relpath);
1768 		} else {
1769 			/* 'legacy' or 'none' */
1770 			(void) strlcpy(propbuf, str, proplen);
1771 		}
1772 
1773 		break;
1774 
1775 	case ZFS_PROP_ORIGIN:
1776 		(void) strlcpy(propbuf, getprop_string(zhp, prop, &source),
1777 		    proplen);
1778 		/*
1779 		 * If there is no parent at all, return failure to indicate that
1780 		 * it doesn't apply to this dataset.
1781 		 */
1782 		if (propbuf[0] == '\0')
1783 			return (-1);
1784 		break;
1785 
1786 	case ZFS_PROP_QUOTA:
1787 	case ZFS_PROP_REFQUOTA:
1788 	case ZFS_PROP_RESERVATION:
1789 	case ZFS_PROP_REFRESERVATION:
1790 
1791 		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
1792 			return (-1);
1793 
1794 		/*
1795 		 * If quota or reservation is 0, we translate this into 'none'
1796 		 * (unless literal is set), and indicate that it's the default
1797 		 * value.  Otherwise, we print the number nicely and indicate
1798 		 * that its set locally.
1799 		 */
1800 		if (val == 0) {
1801 			if (literal)
1802 				(void) strlcpy(propbuf, "0", proplen);
1803 			else
1804 				(void) strlcpy(propbuf, "none", proplen);
1805 		} else {
1806 			if (literal)
1807 				(void) snprintf(propbuf, proplen, "%llu",
1808 				    (u_longlong_t)val);
1809 			else
1810 				zfs_nicenum(val, propbuf, proplen);
1811 		}
1812 		break;
1813 
1814 	case ZFS_PROP_COMPRESSRATIO:
1815 		if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
1816 			return (-1);
1817 		(void) snprintf(propbuf, proplen, "%lld.%02lldx", (longlong_t)
1818 		    val / 100, (longlong_t)val % 100);
1819 		break;
1820 
1821 	case ZFS_PROP_TYPE:
1822 		switch (zhp->zfs_type) {
1823 		case ZFS_TYPE_FILESYSTEM:
1824 			str = "filesystem";
1825 			break;
1826 		case ZFS_TYPE_VOLUME:
1827 			str = "volume";
1828 			break;
1829 		case ZFS_TYPE_SNAPSHOT:
1830 			str = "snapshot";
1831 			break;
1832 		default:
1833 			abort();
1834 		}
1835 		(void) snprintf(propbuf, proplen, "%s", str);
1836 		break;
1837 
1838 	case ZFS_PROP_MOUNTED:
1839 		/*
1840 		 * The 'mounted' property is a pseudo-property that described
1841 		 * whether the filesystem is currently mounted.  Even though
1842 		 * it's a boolean value, the typical values of "on" and "off"
1843 		 * don't make sense, so we translate to "yes" and "no".
1844 		 */
1845 		if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
1846 		    src, &source, &val) != 0)
1847 			return (-1);
1848 		if (val)
1849 			(void) strlcpy(propbuf, "yes", proplen);
1850 		else
1851 			(void) strlcpy(propbuf, "no", proplen);
1852 		break;
1853 
1854 	case ZFS_PROP_NAME:
1855 		/*
1856 		 * The 'name' property is a pseudo-property derived from the
1857 		 * dataset name.  It is presented as a real property to simplify
1858 		 * consumers.
1859 		 */
1860 		(void) strlcpy(propbuf, zhp->zfs_name, proplen);
1861 		break;
1862 
1863 	default:
1864 		switch (zfs_prop_get_type(prop)) {
1865 		case PROP_TYPE_NUMBER:
1866 			if (get_numeric_property(zhp, prop, src,
1867 			    &source, &val) != 0)
1868 				return (-1);
1869 			if (literal)
1870 				(void) snprintf(propbuf, proplen, "%llu",
1871 				    (u_longlong_t)val);
1872 			else
1873 				zfs_nicenum(val, propbuf, proplen);
1874 			break;
1875 
1876 		case PROP_TYPE_STRING:
1877 			(void) strlcpy(propbuf,
1878 			    getprop_string(zhp, prop, &source), proplen);
1879 			break;
1880 
1881 		case PROP_TYPE_INDEX:
1882 			if (get_numeric_property(zhp, prop, src,
1883 			    &source, &val) != 0)
1884 				return (-1);
1885 			if (zfs_prop_index_to_string(prop, val, &strval) != 0)
1886 				return (-1);
1887 			(void) strlcpy(propbuf, strval, proplen);
1888 			break;
1889 
1890 		default:
1891 			abort();
1892 		}
1893 	}
1894 
1895 	get_source(zhp, src, source, statbuf, statlen);
1896 
1897 	return (0);
1898 }
1899 
1900 /*
1901  * Utility function to get the given numeric property.  Does no validation that
1902  * the given property is the appropriate type; should only be used with
1903  * hard-coded property types.
1904  */
1905 uint64_t
1906 zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
1907 {
1908 	char *source;
1909 	uint64_t val;
1910 
1911 	(void) get_numeric_property(zhp, prop, NULL, &source, &val);
1912 
1913 	return (val);
1914 }
1915 
1916 int
1917 zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
1918 {
1919 	char buf[64];
1920 
1921 	(void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
1922 	return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
1923 }
1924 
1925 /*
1926  * Similar to zfs_prop_get(), but returns the value as an integer.
1927  */
1928 int
1929 zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
1930     zprop_source_t *src, char *statbuf, size_t statlen)
1931 {
1932 	char *source;
1933 
1934 	/*
1935 	 * Check to see if this property applies to our object
1936 	 */
1937 	if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
1938 		return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
1939 		    dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
1940 		    zfs_prop_to_name(prop)));
1941 	}
1942 
1943 	if (src)
1944 		*src = ZPROP_SRC_NONE;
1945 
1946 	if (get_numeric_property(zhp, prop, src, &source, value) != 0)
1947 		return (-1);
1948 
1949 	get_source(zhp, src, source, statbuf, statlen);
1950 
1951 	return (0);
1952 }
1953 
1954 static int
1955 idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
1956     char **domainp, idmap_rid_t *ridp)
1957 {
1958 	idmap_handle_t *idmap_hdl = NULL;
1959 	idmap_get_handle_t *get_hdl = NULL;
1960 	idmap_stat status;
1961 	int err = EINVAL;
1962 
1963 	if (idmap_init(&idmap_hdl) != IDMAP_SUCCESS)
1964 		goto out;
1965 	if (idmap_get_create(idmap_hdl, &get_hdl) != IDMAP_SUCCESS)
1966 		goto out;
1967 
1968 	if (isuser) {
1969 		err = idmap_get_sidbyuid(get_hdl, id,
1970 		    IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
1971 	} else {
1972 		err = idmap_get_sidbygid(get_hdl, id,
1973 		    IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
1974 	}
1975 	if (err == IDMAP_SUCCESS &&
1976 	    idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
1977 	    status == IDMAP_SUCCESS)
1978 		err = 0;
1979 	else
1980 		err = EINVAL;
1981 out:
1982 	if (get_hdl)
1983 		idmap_get_destroy(get_hdl);
1984 	if (idmap_hdl)
1985 		(void) idmap_fini(idmap_hdl);
1986 	return (err);
1987 }
1988 
1989 /*
1990  * convert the propname into parameters needed by kernel
1991  * Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
1992  * Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
1993  */
1994 static int
1995 userquota_propname_decode(const char *propname, boolean_t zoned,
1996     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
1997 {
1998 	zfs_userquota_prop_t type;
1999 	char *cp, *end;
2000 	char *numericsid = NULL;
2001 	boolean_t isuser;
2002 
2003 	domain[0] = '\0';
2004 
2005 	/* Figure out the property type ({user|group}{quota|space}) */
2006 	for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
2007 		if (strncmp(propname, zfs_userquota_prop_prefixes[type],
2008 		    strlen(zfs_userquota_prop_prefixes[type])) == 0)
2009 			break;
2010 	}
2011 	if (type == ZFS_NUM_USERQUOTA_PROPS)
2012 		return (EINVAL);
2013 	*typep = type;
2014 
2015 	isuser = (type == ZFS_PROP_USERQUOTA ||
2016 	    type == ZFS_PROP_USERUSED);
2017 
2018 	cp = strchr(propname, '@') + 1;
2019 
2020 	if (strchr(cp, '@')) {
2021 		/*
2022 		 * It's a SID name (eg "user@domain") that needs to be
2023 		 * turned into S-1-domainID-RID.
2024 		 */
2025 		directory_error_t e;
2026 		if (zoned && getzoneid() == GLOBAL_ZONEID)
2027 			return (ENOENT);
2028 		if (isuser) {
2029 			e = directory_sid_from_user_name(NULL,
2030 			    cp, &numericsid);
2031 		} else {
2032 			e = directory_sid_from_group_name(NULL,
2033 			    cp, &numericsid);
2034 		}
2035 		if (e != NULL) {
2036 			directory_error_free(e);
2037 			return (ENOENT);
2038 		}
2039 		if (numericsid == NULL)
2040 			return (ENOENT);
2041 		cp = numericsid;
2042 		/* will be further decoded below */
2043 	}
2044 
2045 	if (strncmp(cp, "S-1-", 4) == 0) {
2046 		/* It's a numeric SID (eg "S-1-234-567-89") */
2047 		(void) strlcpy(domain, cp, domainlen);
2048 		cp = strrchr(domain, '-');
2049 		*cp = '\0';
2050 		cp++;
2051 
2052 		errno = 0;
2053 		*ridp = strtoull(cp, &end, 10);
2054 		if (numericsid) {
2055 			free(numericsid);
2056 			numericsid = NULL;
2057 		}
2058 		if (errno != 0 || *end != '\0')
2059 			return (EINVAL);
2060 	} else if (!isdigit(*cp)) {
2061 		/*
2062 		 * It's a user/group name (eg "user") that needs to be
2063 		 * turned into a uid/gid
2064 		 */
2065 		if (zoned && getzoneid() == GLOBAL_ZONEID)
2066 			return (ENOENT);
2067 		if (isuser) {
2068 			struct passwd *pw;
2069 			pw = getpwnam(cp);
2070 			if (pw == NULL)
2071 				return (ENOENT);
2072 			*ridp = pw->pw_uid;
2073 		} else {
2074 			struct group *gr;
2075 			gr = getgrnam(cp);
2076 			if (gr == NULL)
2077 				return (ENOENT);
2078 			*ridp = gr->gr_gid;
2079 		}
2080 	} else {
2081 		/* It's a user/group ID (eg "12345"). */
2082 		uid_t id = strtoul(cp, &end, 10);
2083 		idmap_rid_t rid;
2084 		char *mapdomain;
2085 
2086 		if (*end != '\0')
2087 			return (EINVAL);
2088 		if (id > MAXUID) {
2089 			/* It's an ephemeral ID. */
2090 			if (idmap_id_to_numeric_domain_rid(id, isuser,
2091 			    &mapdomain, &rid) != 0)
2092 				return (ENOENT);
2093 			(void) strlcpy(domain, mapdomain, domainlen);
2094 			*ridp = rid;
2095 		} else {
2096 			*ridp = id;
2097 		}
2098 	}
2099 
2100 	ASSERT3P(numericsid, ==, NULL);
2101 	return (0);
2102 }
2103 
2104 static int
2105 zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
2106     uint64_t *propvalue, zfs_userquota_prop_t *typep)
2107 {
2108 	int err;
2109 	zfs_cmd_t zc = { 0 };
2110 
2111 	(void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2112 
2113 	err = userquota_propname_decode(propname,
2114 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
2115 	    typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
2116 	zc.zc_objset_type = *typep;
2117 	if (err)
2118 		return (err);
2119 
2120 	err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
2121 	if (err)
2122 		return (err);
2123 
2124 	*propvalue = zc.zc_cookie;
2125 	return (0);
2126 }
2127 
2128 int
2129 zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
2130     uint64_t *propvalue)
2131 {
2132 	zfs_userquota_prop_t type;
2133 
2134 	return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
2135 	    &type));
2136 }
2137 
2138 int
2139 zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
2140     char *propbuf, int proplen, boolean_t literal)
2141 {
2142 	int err;
2143 	uint64_t propvalue;
2144 	zfs_userquota_prop_t type;
2145 
2146 	err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
2147 	    &type);
2148 
2149 	if (err)
2150 		return (err);
2151 
2152 	if (literal) {
2153 		(void) snprintf(propbuf, proplen, "%llu", propvalue);
2154 	} else if (propvalue == 0 &&
2155 	    (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA)) {
2156 		(void) strlcpy(propbuf, "none", proplen);
2157 	} else {
2158 		zfs_nicenum(propvalue, propbuf, proplen);
2159 	}
2160 	return (0);
2161 }
2162 
2163 /*
2164  * Returns the name of the given zfs handle.
2165  */
2166 const char *
2167 zfs_get_name(const zfs_handle_t *zhp)
2168 {
2169 	return (zhp->zfs_name);
2170 }
2171 
2172 /*
2173  * Returns the type of the given zfs handle.
2174  */
2175 zfs_type_t
2176 zfs_get_type(const zfs_handle_t *zhp)
2177 {
2178 	return (zhp->zfs_type);
2179 }
2180 
2181 static int
2182 zfs_do_list_ioctl(zfs_handle_t *zhp, int arg, zfs_cmd_t *zc)
2183 {
2184 	int rc;
2185 	uint64_t	orig_cookie;
2186 
2187 	orig_cookie = zc->zc_cookie;
2188 top:
2189 	(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
2190 	rc = ioctl(zhp->zfs_hdl->libzfs_fd, arg, zc);
2191 
2192 	if (rc == -1) {
2193 		switch (errno) {
2194 		case ENOMEM:
2195 			/* expand nvlist memory and try again */
2196 			if (zcmd_expand_dst_nvlist(zhp->zfs_hdl, zc) != 0) {
2197 				zcmd_free_nvlists(zc);
2198 				return (-1);
2199 			}
2200 			zc->zc_cookie = orig_cookie;
2201 			goto top;
2202 		/*
2203 		 * An errno value of ESRCH indicates normal completion.
2204 		 * If ENOENT is returned, then the underlying dataset
2205 		 * has been removed since we obtained the handle.
2206 		 */
2207 		case ESRCH:
2208 		case ENOENT:
2209 			rc = 1;
2210 			break;
2211 		default:
2212 			rc = zfs_standard_error(zhp->zfs_hdl, errno,
2213 			    dgettext(TEXT_DOMAIN,
2214 			    "cannot iterate filesystems"));
2215 			break;
2216 		}
2217 	}
2218 	return (rc);
2219 }
2220 
2221 /*
2222  * Iterate over all child filesystems
2223  */
2224 int
2225 zfs_iter_filesystems(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2226 {
2227 	zfs_cmd_t zc = { 0 };
2228 	zfs_handle_t *nzhp;
2229 	int ret;
2230 
2231 	if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM)
2232 		return (0);
2233 
2234 	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2235 		return (-1);
2236 
2237 	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_DATASET_LIST_NEXT,
2238 	    &zc)) == 0) {
2239 		/*
2240 		 * Silently ignore errors, as the only plausible explanation is
2241 		 * that the pool has since been removed.
2242 		 */
2243 		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
2244 		    &zc)) == NULL) {
2245 			continue;
2246 		}
2247 
2248 		if ((ret = func(nzhp, data)) != 0) {
2249 			zcmd_free_nvlists(&zc);
2250 			return (ret);
2251 		}
2252 	}
2253 	zcmd_free_nvlists(&zc);
2254 	return ((ret < 0) ? ret : 0);
2255 }
2256 
2257 /*
2258  * Iterate over all snapshots
2259  */
2260 int
2261 zfs_iter_snapshots(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2262 {
2263 	zfs_cmd_t zc = { 0 };
2264 	zfs_handle_t *nzhp;
2265 	int ret;
2266 
2267 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
2268 		return (0);
2269 
2270 	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2271 		return (-1);
2272 	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_SNAPSHOT_LIST_NEXT,
2273 	    &zc)) == 0) {
2274 
2275 		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
2276 		    &zc)) == NULL) {
2277 			continue;
2278 		}
2279 
2280 		if ((ret = func(nzhp, data)) != 0) {
2281 			zcmd_free_nvlists(&zc);
2282 			return (ret);
2283 		}
2284 	}
2285 	zcmd_free_nvlists(&zc);
2286 	return ((ret < 0) ? ret : 0);
2287 }
2288 
2289 /*
2290  * Iterate over all children, snapshots and filesystems
2291  */
2292 int
2293 zfs_iter_children(zfs_handle_t *zhp, zfs_iter_f func, void *data)
2294 {
2295 	int ret;
2296 
2297 	if ((ret = zfs_iter_filesystems(zhp, func, data)) != 0)
2298 		return (ret);
2299 
2300 	return (zfs_iter_snapshots(zhp, func, data));
2301 }
2302 
2303 /*
2304  * Given a complete name, return just the portion that refers to the parent.
2305  * Can return NULL if this is a pool.
2306  */
2307 static int
2308 parent_name(const char *path, char *buf, size_t buflen)
2309 {
2310 	char *loc;
2311 
2312 	if ((loc = strrchr(path, '/')) == NULL)
2313 		return (-1);
2314 
2315 	(void) strncpy(buf, path, MIN(buflen, loc - path));
2316 	buf[loc - path] = '\0';
2317 
2318 	return (0);
2319 }
2320 
2321 /*
2322  * If accept_ancestor is false, then check to make sure that the given path has
2323  * a parent, and that it exists.  If accept_ancestor is true, then find the
2324  * closest existing ancestor for the given path.  In prefixlen return the
2325  * length of already existing prefix of the given path.  We also fetch the
2326  * 'zoned' property, which is used to validate property settings when creating
2327  * new datasets.
2328  */
2329 static int
2330 check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
2331     boolean_t accept_ancestor, int *prefixlen)
2332 {
2333 	zfs_cmd_t zc = { 0 };
2334 	char parent[ZFS_MAXNAMELEN];
2335 	char *slash;
2336 	zfs_handle_t *zhp;
2337 	char errbuf[1024];
2338 
2339 	(void) snprintf(errbuf, sizeof (errbuf),
2340 	    dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
2341 
2342 	/* get parent, and check to see if this is just a pool */
2343 	if (parent_name(path, parent, sizeof (parent)) != 0) {
2344 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2345 		    "missing dataset name"));
2346 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2347 	}
2348 
2349 	/* check to see if the pool exists */
2350 	if ((slash = strchr(parent, '/')) == NULL)
2351 		slash = parent + strlen(parent);
2352 	(void) strncpy(zc.zc_name, parent, slash - parent);
2353 	zc.zc_name[slash - parent] = '\0';
2354 	if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
2355 	    errno == ENOENT) {
2356 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2357 		    "no such pool '%s'"), zc.zc_name);
2358 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2359 	}
2360 
2361 	/* check to see if the parent dataset exists */
2362 	while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
2363 		if (errno == ENOENT && accept_ancestor) {
2364 			/*
2365 			 * Go deeper to find an ancestor, give up on top level.
2366 			 */
2367 			if (parent_name(parent, parent, sizeof (parent)) != 0) {
2368 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2369 				    "no such pool '%s'"), zc.zc_name);
2370 				return (zfs_error(hdl, EZFS_NOENT, errbuf));
2371 			}
2372 		} else if (errno == ENOENT) {
2373 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2374 			    "parent does not exist"));
2375 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2376 		} else
2377 			return (zfs_standard_error(hdl, errno, errbuf));
2378 	}
2379 
2380 	*zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
2381 	/* we are in a non-global zone, but parent is in the global zone */
2382 	if (getzoneid() != GLOBAL_ZONEID && !(*zoned)) {
2383 		(void) zfs_standard_error(hdl, EPERM, errbuf);
2384 		zfs_close(zhp);
2385 		return (-1);
2386 	}
2387 
2388 	/* make sure parent is a filesystem */
2389 	if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
2390 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2391 		    "parent is not a filesystem"));
2392 		(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
2393 		zfs_close(zhp);
2394 		return (-1);
2395 	}
2396 
2397 	zfs_close(zhp);
2398 	if (prefixlen != NULL)
2399 		*prefixlen = strlen(parent);
2400 	return (0);
2401 }
2402 
2403 /*
2404  * Finds whether the dataset of the given type(s) exists.
2405  */
2406 boolean_t
2407 zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
2408 {
2409 	zfs_handle_t *zhp;
2410 
2411 	if (!zfs_validate_name(hdl, path, types, B_FALSE))
2412 		return (B_FALSE);
2413 
2414 	/*
2415 	 * Try to get stats for the dataset, which will tell us if it exists.
2416 	 */
2417 	if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
2418 		int ds_type = zhp->zfs_type;
2419 
2420 		zfs_close(zhp);
2421 		if (types & ds_type)
2422 			return (B_TRUE);
2423 	}
2424 	return (B_FALSE);
2425 }
2426 
2427 /*
2428  * Given a path to 'target', create all the ancestors between
2429  * the prefixlen portion of the path, and the target itself.
2430  * Fail if the initial prefixlen-ancestor does not already exist.
2431  */
2432 int
2433 create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
2434 {
2435 	zfs_handle_t *h;
2436 	char *cp;
2437 	const char *opname;
2438 
2439 	/* make sure prefix exists */
2440 	cp = target + prefixlen;
2441 	if (*cp != '/') {
2442 		assert(strchr(cp, '/') == NULL);
2443 		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2444 	} else {
2445 		*cp = '\0';
2446 		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2447 		*cp = '/';
2448 	}
2449 	if (h == NULL)
2450 		return (-1);
2451 	zfs_close(h);
2452 
2453 	/*
2454 	 * Attempt to create, mount, and share any ancestor filesystems,
2455 	 * up to the prefixlen-long one.
2456 	 */
2457 	for (cp = target + prefixlen + 1;
2458 	    cp = strchr(cp, '/'); *cp = '/', cp++) {
2459 		char *logstr;
2460 
2461 		*cp = '\0';
2462 
2463 		h = make_dataset_handle(hdl, target);
2464 		if (h) {
2465 			/* it already exists, nothing to do here */
2466 			zfs_close(h);
2467 			continue;
2468 		}
2469 
2470 		logstr = hdl->libzfs_log_str;
2471 		hdl->libzfs_log_str = NULL;
2472 		if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
2473 		    NULL) != 0) {
2474 			hdl->libzfs_log_str = logstr;
2475 			opname = dgettext(TEXT_DOMAIN, "create");
2476 			goto ancestorerr;
2477 		}
2478 
2479 		hdl->libzfs_log_str = logstr;
2480 		h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
2481 		if (h == NULL) {
2482 			opname = dgettext(TEXT_DOMAIN, "open");
2483 			goto ancestorerr;
2484 		}
2485 
2486 		if (zfs_mount(h, NULL, 0) != 0) {
2487 			opname = dgettext(TEXT_DOMAIN, "mount");
2488 			goto ancestorerr;
2489 		}
2490 
2491 		if (zfs_share(h) != 0) {
2492 			opname = dgettext(TEXT_DOMAIN, "share");
2493 			goto ancestorerr;
2494 		}
2495 
2496 		zfs_close(h);
2497 	}
2498 
2499 	return (0);
2500 
2501 ancestorerr:
2502 	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2503 	    "failed to %s ancestor '%s'"), opname, target);
2504 	return (-1);
2505 }
2506 
2507 /*
2508  * Creates non-existing ancestors of the given path.
2509  */
2510 int
2511 zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
2512 {
2513 	int prefix;
2514 	uint64_t zoned;
2515 	char *path_copy;
2516 	int rc;
2517 
2518 	if (check_parents(hdl, path, &zoned, B_TRUE, &prefix) != 0)
2519 		return (-1);
2520 
2521 	if ((path_copy = strdup(path)) != NULL) {
2522 		rc = create_parents(hdl, path_copy, prefix);
2523 		free(path_copy);
2524 	}
2525 	if (path_copy == NULL || rc != 0)
2526 		return (-1);
2527 
2528 	return (0);
2529 }
2530 
2531 /*
2532  * Create a new filesystem or volume.
2533  */
2534 int
2535 zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
2536     nvlist_t *props)
2537 {
2538 	zfs_cmd_t zc = { 0 };
2539 	int ret;
2540 	uint64_t size = 0;
2541 	uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
2542 	char errbuf[1024];
2543 	uint64_t zoned;
2544 
2545 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2546 	    "cannot create '%s'"), path);
2547 
2548 	/* validate the path, taking care to note the extended error message */
2549 	if (!zfs_validate_name(hdl, path, type, B_TRUE))
2550 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2551 
2552 	/* validate parents exist */
2553 	if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
2554 		return (-1);
2555 
2556 	/*
2557 	 * The failure modes when creating a dataset of a different type over
2558 	 * one that already exists is a little strange.  In particular, if you
2559 	 * try to create a dataset on top of an existing dataset, the ioctl()
2560 	 * will return ENOENT, not EEXIST.  To prevent this from happening, we
2561 	 * first try to see if the dataset exists.
2562 	 */
2563 	(void) strlcpy(zc.zc_name, path, sizeof (zc.zc_name));
2564 	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
2565 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2566 		    "dataset already exists"));
2567 		return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2568 	}
2569 
2570 	if (type == ZFS_TYPE_VOLUME)
2571 		zc.zc_objset_type = DMU_OST_ZVOL;
2572 	else
2573 		zc.zc_objset_type = DMU_OST_ZFS;
2574 
2575 	if (props && (props = zfs_valid_proplist(hdl, type, props,
2576 	    zoned, NULL, errbuf)) == 0)
2577 		return (-1);
2578 
2579 	if (type == ZFS_TYPE_VOLUME) {
2580 		/*
2581 		 * If we are creating a volume, the size and block size must
2582 		 * satisfy a few restraints.  First, the blocksize must be a
2583 		 * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
2584 		 * volsize must be a multiple of the block size, and cannot be
2585 		 * zero.
2586 		 */
2587 		if (props == NULL || nvlist_lookup_uint64(props,
2588 		    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
2589 			nvlist_free(props);
2590 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2591 			    "missing volume size"));
2592 			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2593 		}
2594 
2595 		if ((ret = nvlist_lookup_uint64(props,
2596 		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
2597 		    &blocksize)) != 0) {
2598 			if (ret == ENOENT) {
2599 				blocksize = zfs_prop_default_numeric(
2600 				    ZFS_PROP_VOLBLOCKSIZE);
2601 			} else {
2602 				nvlist_free(props);
2603 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2604 				    "missing volume block size"));
2605 				return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2606 			}
2607 		}
2608 
2609 		if (size == 0) {
2610 			nvlist_free(props);
2611 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2612 			    "volume size cannot be zero"));
2613 			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2614 		}
2615 
2616 		if (size % blocksize != 0) {
2617 			nvlist_free(props);
2618 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2619 			    "volume size must be a multiple of volume block "
2620 			    "size"));
2621 			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2622 		}
2623 	}
2624 
2625 	if (props && zcmd_write_src_nvlist(hdl, &zc, props) != 0)
2626 		return (-1);
2627 	nvlist_free(props);
2628 
2629 	/* create the dataset */
2630 	ret = zfs_ioctl(hdl, ZFS_IOC_CREATE, &zc);
2631 
2632 	zcmd_free_nvlists(&zc);
2633 
2634 	/* check for failure */
2635 	if (ret != 0) {
2636 		char parent[ZFS_MAXNAMELEN];
2637 		(void) parent_name(path, parent, sizeof (parent));
2638 
2639 		switch (errno) {
2640 		case ENOENT:
2641 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2642 			    "no such parent '%s'"), parent);
2643 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2644 
2645 		case EINVAL:
2646 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2647 			    "parent '%s' is not a filesystem"), parent);
2648 			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2649 
2650 		case EDOM:
2651 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2652 			    "volume block size must be power of 2 from "
2653 			    "%u to %uk"),
2654 			    (uint_t)SPA_MINBLOCKSIZE,
2655 			    (uint_t)SPA_MAXBLOCKSIZE >> 10);
2656 
2657 			return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2658 
2659 		case ENOTSUP:
2660 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2661 			    "pool must be upgraded to set this "
2662 			    "property or value"));
2663 			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
2664 #ifdef _ILP32
2665 		case EOVERFLOW:
2666 			/*
2667 			 * This platform can't address a volume this big.
2668 			 */
2669 			if (type == ZFS_TYPE_VOLUME)
2670 				return (zfs_error(hdl, EZFS_VOLTOOBIG,
2671 				    errbuf));
2672 #endif
2673 			/* FALLTHROUGH */
2674 		default:
2675 			return (zfs_standard_error(hdl, errno, errbuf));
2676 		}
2677 	}
2678 
2679 	return (0);
2680 }
2681 
2682 /*
2683  * Destroys the given dataset.  The caller must make sure that the filesystem
2684  * isn't mounted, and that there are no active dependents.
2685  */
2686 int
2687 zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
2688 {
2689 	zfs_cmd_t zc = { 0 };
2690 
2691 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2692 
2693 	if (ZFS_IS_VOLUME(zhp)) {
2694 		/*
2695 		 * If user doesn't have permissions to unshare volume, then
2696 		 * abort the request.  This would only happen for a
2697 		 * non-privileged user.
2698 		 */
2699 		if (zfs_unshare_iscsi(zhp) != 0) {
2700 			return (-1);
2701 		}
2702 
2703 		zc.zc_objset_type = DMU_OST_ZVOL;
2704 	} else {
2705 		zc.zc_objset_type = DMU_OST_ZFS;
2706 	}
2707 
2708 	zc.zc_defer_destroy = defer;
2709 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY, &zc) != 0) {
2710 		return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
2711 		    dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
2712 		    zhp->zfs_name));
2713 	}
2714 
2715 	remove_mountpoint(zhp);
2716 
2717 	return (0);
2718 }
2719 
2720 struct destroydata {
2721 	char *snapname;
2722 	boolean_t gotone;
2723 	boolean_t closezhp;
2724 };
2725 
2726 static int
2727 zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
2728 {
2729 	struct destroydata *dd = arg;
2730 	zfs_handle_t *szhp;
2731 	char name[ZFS_MAXNAMELEN];
2732 	boolean_t closezhp = dd->closezhp;
2733 	int rv = 0;
2734 
2735 	(void) strlcpy(name, zhp->zfs_name, sizeof (name));
2736 	(void) strlcat(name, "@", sizeof (name));
2737 	(void) strlcat(name, dd->snapname, sizeof (name));
2738 
2739 	szhp = make_dataset_handle(zhp->zfs_hdl, name);
2740 	if (szhp) {
2741 		dd->gotone = B_TRUE;
2742 		zfs_close(szhp);
2743 	}
2744 
2745 	dd->closezhp = B_TRUE;
2746 	if (!dd->gotone)
2747 		rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, arg);
2748 	if (closezhp)
2749 		zfs_close(zhp);
2750 	return (rv);
2751 }
2752 
2753 /*
2754  * Destroys all snapshots with the given name in zhp & descendants.
2755  */
2756 int
2757 zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
2758 {
2759 	zfs_cmd_t zc = { 0 };
2760 	int ret;
2761 	struct destroydata dd = { 0 };
2762 
2763 	dd.snapname = snapname;
2764 	(void) zfs_check_snap_cb(zhp, &dd);
2765 
2766 	if (!dd.gotone) {
2767 		return (zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
2768 		    dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
2769 		    zhp->zfs_name, snapname));
2770 	}
2771 
2772 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2773 	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
2774 	zc.zc_defer_destroy = defer;
2775 
2776 	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY_SNAPS, &zc);
2777 	if (ret != 0) {
2778 		char errbuf[1024];
2779 
2780 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2781 		    "cannot destroy '%s@%s'"), zc.zc_name, snapname);
2782 
2783 		switch (errno) {
2784 		case EEXIST:
2785 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2786 			    "snapshot is cloned"));
2787 			return (zfs_error(zhp->zfs_hdl, EZFS_EXISTS, errbuf));
2788 
2789 		default:
2790 			return (zfs_standard_error(zhp->zfs_hdl, errno,
2791 			    errbuf));
2792 		}
2793 	}
2794 
2795 	return (0);
2796 }
2797 
2798 /*
2799  * Clones the given dataset.  The target must be of the same type as the source.
2800  */
2801 int
2802 zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
2803 {
2804 	zfs_cmd_t zc = { 0 };
2805 	char parent[ZFS_MAXNAMELEN];
2806 	int ret;
2807 	char errbuf[1024];
2808 	libzfs_handle_t *hdl = zhp->zfs_hdl;
2809 	zfs_type_t type;
2810 	uint64_t zoned;
2811 
2812 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
2813 
2814 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2815 	    "cannot create '%s'"), target);
2816 
2817 	/* validate the target name */
2818 	if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
2819 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2820 
2821 	/* validate parents exist */
2822 	if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
2823 		return (-1);
2824 
2825 	(void) parent_name(target, parent, sizeof (parent));
2826 
2827 	/* do the clone */
2828 	if (ZFS_IS_VOLUME(zhp)) {
2829 		zc.zc_objset_type = DMU_OST_ZVOL;
2830 		type = ZFS_TYPE_VOLUME;
2831 	} else {
2832 		zc.zc_objset_type = DMU_OST_ZFS;
2833 		type = ZFS_TYPE_FILESYSTEM;
2834 	}
2835 
2836 	if (props) {
2837 		if ((props = zfs_valid_proplist(hdl, type, props, zoned,
2838 		    zhp, errbuf)) == NULL)
2839 			return (-1);
2840 
2841 		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
2842 			nvlist_free(props);
2843 			return (-1);
2844 		}
2845 
2846 		nvlist_free(props);
2847 	}
2848 
2849 	(void) strlcpy(zc.zc_name, target, sizeof (zc.zc_name));
2850 	(void) strlcpy(zc.zc_value, zhp->zfs_name, sizeof (zc.zc_value));
2851 	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_CREATE, &zc);
2852 
2853 	zcmd_free_nvlists(&zc);
2854 
2855 	if (ret != 0) {
2856 		switch (errno) {
2857 
2858 		case ENOENT:
2859 			/*
2860 			 * The parent doesn't exist.  We should have caught this
2861 			 * above, but there may a race condition that has since
2862 			 * destroyed the parent.
2863 			 *
2864 			 * At this point, we don't know whether it's the source
2865 			 * that doesn't exist anymore, or whether the target
2866 			 * dataset doesn't exist.
2867 			 */
2868 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2869 			    "no such parent '%s'"), parent);
2870 			return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
2871 
2872 		case EXDEV:
2873 			zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2874 			    "source and target pools differ"));
2875 			return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
2876 			    errbuf));
2877 
2878 		default:
2879 			return (zfs_standard_error(zhp->zfs_hdl, errno,
2880 			    errbuf));
2881 		}
2882 	}
2883 
2884 	return (ret);
2885 }
2886 
2887 /*
2888  * Promotes the given clone fs to be the clone parent.
2889  */
2890 int
2891 zfs_promote(zfs_handle_t *zhp)
2892 {
2893 	libzfs_handle_t *hdl = zhp->zfs_hdl;
2894 	zfs_cmd_t zc = { 0 };
2895 	char parent[MAXPATHLEN];
2896 	int ret;
2897 	char errbuf[1024];
2898 
2899 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2900 	    "cannot promote '%s'"), zhp->zfs_name);
2901 
2902 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
2903 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2904 		    "snapshots can not be promoted"));
2905 		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2906 	}
2907 
2908 	(void) strlcpy(parent, zhp->zfs_dmustats.dds_origin, sizeof (parent));
2909 	if (parent[0] == '\0') {
2910 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2911 		    "not a cloned filesystem"));
2912 		return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2913 	}
2914 
2915 	(void) strlcpy(zc.zc_value, zhp->zfs_dmustats.dds_origin,
2916 	    sizeof (zc.zc_value));
2917 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2918 	ret = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2919 
2920 	if (ret != 0) {
2921 		int save_errno = errno;
2922 
2923 		switch (save_errno) {
2924 		case EEXIST:
2925 			/* There is a conflicting snapshot name. */
2926 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2927 			    "conflicting snapshot '%s' from parent '%s'"),
2928 			    zc.zc_string, parent);
2929 			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
2930 
2931 		default:
2932 			return (zfs_standard_error(hdl, save_errno, errbuf));
2933 		}
2934 	}
2935 	return (ret);
2936 }
2937 
2938 /*
2939  * Takes a snapshot of the given dataset.
2940  */
2941 int
2942 zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
2943     nvlist_t *props)
2944 {
2945 	const char *delim;
2946 	char parent[ZFS_MAXNAMELEN];
2947 	zfs_handle_t *zhp;
2948 	zfs_cmd_t zc = { 0 };
2949 	int ret;
2950 	char errbuf[1024];
2951 
2952 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2953 	    "cannot snapshot '%s'"), path);
2954 
2955 	/* validate the target name */
2956 	if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
2957 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2958 
2959 	if (props) {
2960 		if ((props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
2961 		    props, B_FALSE, NULL, errbuf)) == NULL)
2962 			return (-1);
2963 
2964 		if (zcmd_write_src_nvlist(hdl, &zc, props) != 0) {
2965 			nvlist_free(props);
2966 			return (-1);
2967 		}
2968 
2969 		nvlist_free(props);
2970 	}
2971 
2972 	/* make sure the parent exists and is of the appropriate type */
2973 	delim = strchr(path, '@');
2974 	(void) strncpy(parent, path, delim - path);
2975 	parent[delim - path] = '\0';
2976 
2977 	if ((zhp = zfs_open(hdl, parent, ZFS_TYPE_FILESYSTEM |
2978 	    ZFS_TYPE_VOLUME)) == NULL) {
2979 		zcmd_free_nvlists(&zc);
2980 		return (-1);
2981 	}
2982 
2983 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2984 	(void) strlcpy(zc.zc_value, delim+1, sizeof (zc.zc_value));
2985 	if (ZFS_IS_VOLUME(zhp))
2986 		zc.zc_objset_type = DMU_OST_ZVOL;
2987 	else
2988 		zc.zc_objset_type = DMU_OST_ZFS;
2989 	zc.zc_cookie = recursive;
2990 	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SNAPSHOT, &zc);
2991 
2992 	zcmd_free_nvlists(&zc);
2993 
2994 	/*
2995 	 * if it was recursive, the one that actually failed will be in
2996 	 * zc.zc_name.
2997 	 */
2998 	if (ret != 0) {
2999 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3000 		    "cannot create snapshot '%s@%s'"), zc.zc_name, zc.zc_value);
3001 		(void) zfs_standard_error(hdl, errno, errbuf);
3002 	}
3003 
3004 	zfs_close(zhp);
3005 
3006 	return (ret);
3007 }
3008 
3009 /*
3010  * Destroy any more recent snapshots.  We invoke this callback on any dependents
3011  * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
3012  * is a dependent and we should just destroy it without checking the transaction
3013  * group.
3014  */
3015 typedef struct rollback_data {
3016 	const char	*cb_target;		/* the snapshot */
3017 	uint64_t	cb_create;		/* creation time reference */
3018 	boolean_t	cb_error;
3019 	boolean_t	cb_dependent;
3020 	boolean_t	cb_force;
3021 } rollback_data_t;
3022 
3023 static int
3024 rollback_destroy(zfs_handle_t *zhp, void *data)
3025 {
3026 	rollback_data_t *cbp = data;
3027 
3028 	if (!cbp->cb_dependent) {
3029 		if (strcmp(zhp->zfs_name, cbp->cb_target) != 0 &&
3030 		    zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3031 		    zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3032 		    cbp->cb_create) {
3033 			char *logstr;
3034 
3035 			cbp->cb_dependent = B_TRUE;
3036 			cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
3037 			    rollback_destroy, cbp);
3038 			cbp->cb_dependent = B_FALSE;
3039 
3040 			logstr = zhp->zfs_hdl->libzfs_log_str;
3041 			zhp->zfs_hdl->libzfs_log_str = NULL;
3042 			cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
3043 			zhp->zfs_hdl->libzfs_log_str = logstr;
3044 		}
3045 	} else {
3046 		/* We must destroy this clone; first unmount it */
3047 		prop_changelist_t *clp;
3048 
3049 		clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
3050 		    cbp->cb_force ? MS_FORCE: 0);
3051 		if (clp == NULL || changelist_prefix(clp) != 0) {
3052 			cbp->cb_error = B_TRUE;
3053 			zfs_close(zhp);
3054 			return (0);
3055 		}
3056 		if (zfs_destroy(zhp, B_FALSE) != 0)
3057 			cbp->cb_error = B_TRUE;
3058 		else
3059 			changelist_remove(clp, zhp->zfs_name);
3060 		(void) changelist_postfix(clp);
3061 		changelist_free(clp);
3062 	}
3063 
3064 	zfs_close(zhp);
3065 	return (0);
3066 }
3067 
3068 /*
3069  * Given a dataset, rollback to a specific snapshot, discarding any
3070  * data changes since then and making it the active dataset.
3071  *
3072  * Any snapshots more recent than the target are destroyed, along with
3073  * their dependents.
3074  */
3075 int
3076 zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
3077 {
3078 	rollback_data_t cb = { 0 };
3079 	int err;
3080 	zfs_cmd_t zc = { 0 };
3081 	boolean_t restore_resv = 0;
3082 	uint64_t old_volsize, new_volsize;
3083 	zfs_prop_t resv_prop;
3084 
3085 	assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
3086 	    zhp->zfs_type == ZFS_TYPE_VOLUME);
3087 
3088 	/*
3089 	 * Destroy all recent snapshots and its dependends.
3090 	 */
3091 	cb.cb_force = force;
3092 	cb.cb_target = snap->zfs_name;
3093 	cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3094 	(void) zfs_iter_children(zhp, rollback_destroy, &cb);
3095 
3096 	if (cb.cb_error)
3097 		return (-1);
3098 
3099 	/*
3100 	 * Now that we have verified that the snapshot is the latest,
3101 	 * rollback to the given snapshot.
3102 	 */
3103 
3104 	if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
3105 		if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
3106 			return (-1);
3107 		old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3108 		restore_resv =
3109 		    (old_volsize == zfs_prop_get_int(zhp, resv_prop));
3110 	}
3111 
3112 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3113 
3114 	if (ZFS_IS_VOLUME(zhp))
3115 		zc.zc_objset_type = DMU_OST_ZVOL;
3116 	else
3117 		zc.zc_objset_type = DMU_OST_ZFS;
3118 
3119 	/*
3120 	 * We rely on zfs_iter_children() to verify that there are no
3121 	 * newer snapshots for the given dataset.  Therefore, we can
3122 	 * simply pass the name on to the ioctl() call.  There is still
3123 	 * an unlikely race condition where the user has taken a
3124 	 * snapshot since we verified that this was the most recent.
3125 	 *
3126 	 */
3127 	if ((err = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_ROLLBACK, &zc)) != 0) {
3128 		(void) zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3129 		    dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
3130 		    zhp->zfs_name);
3131 		return (err);
3132 	}
3133 
3134 	/*
3135 	 * For volumes, if the pre-rollback volsize matched the pre-
3136 	 * rollback reservation and the volsize has changed then set
3137 	 * the reservation property to the post-rollback volsize.
3138 	 * Make a new handle since the rollback closed the dataset.
3139 	 */
3140 	if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
3141 	    (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
3142 		if (restore_resv) {
3143 			new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
3144 			if (old_volsize != new_volsize)
3145 				err = zfs_prop_set_int(zhp, resv_prop,
3146 				    new_volsize);
3147 		}
3148 		zfs_close(zhp);
3149 	}
3150 	return (err);
3151 }
3152 
3153 /*
3154  * Iterate over all dependents for a given dataset.  This includes both
3155  * hierarchical dependents (children) and data dependents (snapshots and
3156  * clones).  The bulk of the processing occurs in get_dependents() in
3157  * libzfs_graph.c.
3158  */
3159 int
3160 zfs_iter_dependents(zfs_handle_t *zhp, boolean_t allowrecursion,
3161     zfs_iter_f func, void *data)
3162 {
3163 	char **dependents;
3164 	size_t count;
3165 	int i;
3166 	zfs_handle_t *child;
3167 	int ret = 0;
3168 
3169 	if (get_dependents(zhp->zfs_hdl, allowrecursion, zhp->zfs_name,
3170 	    &dependents, &count) != 0)
3171 		return (-1);
3172 
3173 	for (i = 0; i < count; i++) {
3174 		if ((child = make_dataset_handle(zhp->zfs_hdl,
3175 		    dependents[i])) == NULL)
3176 			continue;
3177 
3178 		if ((ret = func(child, data)) != 0)
3179 			break;
3180 	}
3181 
3182 	for (i = 0; i < count; i++)
3183 		free(dependents[i]);
3184 	free(dependents);
3185 
3186 	return (ret);
3187 }
3188 
3189 /*
3190  * Renames the given dataset.
3191  */
3192 int
3193 zfs_rename(zfs_handle_t *zhp, const char *target, boolean_t recursive)
3194 {
3195 	int ret;
3196 	zfs_cmd_t zc = { 0 };
3197 	char *delim;
3198 	prop_changelist_t *cl = NULL;
3199 	zfs_handle_t *zhrp = NULL;
3200 	char *parentname = NULL;
3201 	char parent[ZFS_MAXNAMELEN];
3202 	libzfs_handle_t *hdl = zhp->zfs_hdl;
3203 	char errbuf[1024];
3204 
3205 	/* if we have the same exact name, just return success */
3206 	if (strcmp(zhp->zfs_name, target) == 0)
3207 		return (0);
3208 
3209 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3210 	    "cannot rename to '%s'"), target);
3211 
3212 	/*
3213 	 * Make sure the target name is valid
3214 	 */
3215 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3216 		if ((strchr(target, '@') == NULL) ||
3217 		    *target == '@') {
3218 			/*
3219 			 * Snapshot target name is abbreviated,
3220 			 * reconstruct full dataset name
3221 			 */
3222 			(void) strlcpy(parent, zhp->zfs_name,
3223 			    sizeof (parent));
3224 			delim = strchr(parent, '@');
3225 			if (strchr(target, '@') == NULL)
3226 				*(++delim) = '\0';
3227 			else
3228 				*delim = '\0';
3229 			(void) strlcat(parent, target, sizeof (parent));
3230 			target = parent;
3231 		} else {
3232 			/*
3233 			 * Make sure we're renaming within the same dataset.
3234 			 */
3235 			delim = strchr(target, '@');
3236 			if (strncmp(zhp->zfs_name, target, delim - target)
3237 			    != 0 || zhp->zfs_name[delim - target] != '@') {
3238 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3239 				    "snapshots must be part of same "
3240 				    "dataset"));
3241 				return (zfs_error(hdl, EZFS_CROSSTARGET,
3242 				    errbuf));
3243 			}
3244 		}
3245 		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3246 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3247 	} else {
3248 		if (recursive) {
3249 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3250 			    "recursive rename must be a snapshot"));
3251 			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3252 		}
3253 
3254 		if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
3255 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3256 		uint64_t unused;
3257 
3258 		/* validate parents */
3259 		if (check_parents(hdl, target, &unused, B_FALSE, NULL) != 0)
3260 			return (-1);
3261 
3262 		(void) parent_name(target, parent, sizeof (parent));
3263 
3264 		/* make sure we're in the same pool */
3265 		verify((delim = strchr(target, '/')) != NULL);
3266 		if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
3267 		    zhp->zfs_name[delim - target] != '/') {
3268 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3269 			    "datasets must be within same pool"));
3270 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
3271 		}
3272 
3273 		/* new name cannot be a child of the current dataset name */
3274 		if (strncmp(parent, zhp->zfs_name,
3275 		    strlen(zhp->zfs_name)) == 0) {
3276 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3277 			    "New dataset name cannot be a descendent of "
3278 			    "current dataset name"));
3279 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3280 		}
3281 	}
3282 
3283 	(void) snprintf(errbuf, sizeof (errbuf),
3284 	    dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
3285 
3286 	if (getzoneid() == GLOBAL_ZONEID &&
3287 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
3288 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3289 		    "dataset is used in a non-global zone"));
3290 		return (zfs_error(hdl, EZFS_ZONED, errbuf));
3291 	}
3292 
3293 	if (recursive) {
3294 
3295 		parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
3296 		if (parentname == NULL) {
3297 			ret = -1;
3298 			goto error;
3299 		}
3300 		delim = strchr(parentname, '@');
3301 		*delim = '\0';
3302 		zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
3303 		if (zhrp == NULL) {
3304 			ret = -1;
3305 			goto error;
3306 		}
3307 
3308 	} else {
3309 		if ((cl = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0)) == NULL)
3310 			return (-1);
3311 
3312 		if (changelist_haszonedchild(cl)) {
3313 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3314 			    "child dataset with inherited mountpoint is used "
3315 			    "in a non-global zone"));
3316 			(void) zfs_error(hdl, EZFS_ZONED, errbuf);
3317 			goto error;
3318 		}
3319 
3320 		if ((ret = changelist_prefix(cl)) != 0)
3321 			goto error;
3322 	}
3323 
3324 	if (ZFS_IS_VOLUME(zhp))
3325 		zc.zc_objset_type = DMU_OST_ZVOL;
3326 	else
3327 		zc.zc_objset_type = DMU_OST_ZFS;
3328 
3329 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3330 	(void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
3331 
3332 	zc.zc_cookie = recursive;
3333 
3334 	if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
3335 		/*
3336 		 * if it was recursive, the one that actually failed will
3337 		 * be in zc.zc_name
3338 		 */
3339 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3340 		    "cannot rename '%s'"), zc.zc_name);
3341 
3342 		if (recursive && errno == EEXIST) {
3343 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3344 			    "a child dataset already has a snapshot "
3345 			    "with the new name"));
3346 			(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
3347 		} else {
3348 			(void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
3349 		}
3350 
3351 		/*
3352 		 * On failure, we still want to remount any filesystems that
3353 		 * were previously mounted, so we don't alter the system state.
3354 		 */
3355 		if (!recursive)
3356 			(void) changelist_postfix(cl);
3357 	} else {
3358 		if (!recursive) {
3359 			changelist_rename(cl, zfs_get_name(zhp), target);
3360 			ret = changelist_postfix(cl);
3361 		}
3362 	}
3363 
3364 error:
3365 	if (parentname) {
3366 		free(parentname);
3367 	}
3368 	if (zhrp) {
3369 		zfs_close(zhrp);
3370 	}
3371 	if (cl) {
3372 		changelist_free(cl);
3373 	}
3374 	return (ret);
3375 }
3376 
3377 nvlist_t *
3378 zfs_get_user_props(zfs_handle_t *zhp)
3379 {
3380 	return (zhp->zfs_user_props);
3381 }
3382 
3383 /*
3384  * This function is used by 'zfs list' to determine the exact set of columns to
3385  * display, and their maximum widths.  This does two main things:
3386  *
3387  *      - If this is a list of all properties, then expand the list to include
3388  *        all native properties, and set a flag so that for each dataset we look
3389  *        for new unique user properties and add them to the list.
3390  *
3391  *      - For non fixed-width properties, keep track of the maximum width seen
3392  *        so that we can size the column appropriately.
3393  */
3394 int
3395 zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp)
3396 {
3397 	libzfs_handle_t *hdl = zhp->zfs_hdl;
3398 	zprop_list_t *entry;
3399 	zprop_list_t **last, **start;
3400 	nvlist_t *userprops, *propval;
3401 	nvpair_t *elem;
3402 	char *strval;
3403 	char buf[ZFS_MAXPROPLEN];
3404 
3405 	if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
3406 		return (-1);
3407 
3408 	userprops = zfs_get_user_props(zhp);
3409 
3410 	entry = *plp;
3411 	if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
3412 		/*
3413 		 * Go through and add any user properties as necessary.  We
3414 		 * start by incrementing our list pointer to the first
3415 		 * non-native property.
3416 		 */
3417 		start = plp;
3418 		while (*start != NULL) {
3419 			if ((*start)->pl_prop == ZPROP_INVAL)
3420 				break;
3421 			start = &(*start)->pl_next;
3422 		}
3423 
3424 		elem = NULL;
3425 		while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
3426 			/*
3427 			 * See if we've already found this property in our list.
3428 			 */
3429 			for (last = start; *last != NULL;
3430 			    last = &(*last)->pl_next) {
3431 				if (strcmp((*last)->pl_user_prop,
3432 				    nvpair_name(elem)) == 0)
3433 					break;
3434 			}
3435 
3436 			if (*last == NULL) {
3437 				if ((entry = zfs_alloc(hdl,
3438 				    sizeof (zprop_list_t))) == NULL ||
3439 				    ((entry->pl_user_prop = zfs_strdup(hdl,
3440 				    nvpair_name(elem)))) == NULL) {
3441 					free(entry);
3442 					return (-1);
3443 				}
3444 
3445 				entry->pl_prop = ZPROP_INVAL;
3446 				entry->pl_width = strlen(nvpair_name(elem));
3447 				entry->pl_all = B_TRUE;
3448 				*last = entry;
3449 			}
3450 		}
3451 	}
3452 
3453 	/*
3454 	 * Now go through and check the width of any non-fixed columns
3455 	 */
3456 	for (entry = *plp; entry != NULL; entry = entry->pl_next) {
3457 		if (entry->pl_fixed)
3458 			continue;
3459 
3460 		if (entry->pl_prop != ZPROP_INVAL) {
3461 			if (zfs_prop_get(zhp, entry->pl_prop,
3462 			    buf, sizeof (buf), NULL, NULL, 0, B_FALSE) == 0) {
3463 				if (strlen(buf) > entry->pl_width)
3464 					entry->pl_width = strlen(buf);
3465 			}
3466 		} else if (nvlist_lookup_nvlist(userprops,
3467 		    entry->pl_user_prop, &propval)  == 0) {
3468 			verify(nvlist_lookup_string(propval,
3469 			    ZPROP_VALUE, &strval) == 0);
3470 			if (strlen(strval) > entry->pl_width)
3471 				entry->pl_width = strlen(strval);
3472 		}
3473 	}
3474 
3475 	return (0);
3476 }
3477 
3478 int
3479 zfs_iscsi_perm_check(libzfs_handle_t *hdl, char *dataset, ucred_t *cred)
3480 {
3481 	zfs_cmd_t zc = { 0 };
3482 	nvlist_t *nvp;
3483 	gid_t gid;
3484 	uid_t uid;
3485 	const gid_t *groups;
3486 	int group_cnt;
3487 	int error;
3488 
3489 	if (nvlist_alloc(&nvp, NV_UNIQUE_NAME, 0) != 0)
3490 		return (no_memory(hdl));
3491 
3492 	uid = ucred_geteuid(cred);
3493 	gid = ucred_getegid(cred);
3494 	group_cnt = ucred_getgroups(cred, &groups);
3495 
3496 	if (uid == (uid_t)-1 || gid == (uid_t)-1 || group_cnt == (uid_t)-1)
3497 		return (1);
3498 
3499 	if (nvlist_add_uint32(nvp, ZFS_DELEG_PERM_UID, uid) != 0) {
3500 		nvlist_free(nvp);
3501 		return (1);
3502 	}
3503 
3504 	if (nvlist_add_uint32(nvp, ZFS_DELEG_PERM_GID, gid) != 0) {
3505 		nvlist_free(nvp);
3506 		return (1);
3507 	}
3508 
3509 	if (nvlist_add_uint32_array(nvp,
3510 	    ZFS_DELEG_PERM_GROUPS, (uint32_t *)groups, group_cnt) != 0) {
3511 		nvlist_free(nvp);
3512 		return (1);
3513 	}
3514 	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3515 
3516 	if (zcmd_write_src_nvlist(hdl, &zc, nvp))
3517 		return (-1);
3518 
3519 	error = ioctl(hdl->libzfs_fd, ZFS_IOC_ISCSI_PERM_CHECK, &zc);
3520 	nvlist_free(nvp);
3521 	return (error);
3522 }
3523 
3524 int
3525 zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
3526     char *resource, void *export, void *sharetab,
3527     int sharemax, zfs_share_op_t operation)
3528 {
3529 	zfs_cmd_t zc = { 0 };
3530 	int error;
3531 
3532 	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3533 	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
3534 	if (resource)
3535 		(void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
3536 	zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
3537 	zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
3538 	zc.zc_share.z_sharetype = operation;
3539 	zc.zc_share.z_sharemax = sharemax;
3540 	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
3541 	return (error);
3542 }
3543 
3544 void
3545 zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
3546 {
3547 	nvpair_t *curr;
3548 
3549 	/*
3550 	 * Keep a reference to the props-table against which we prune the
3551 	 * properties.
3552 	 */
3553 	zhp->zfs_props_table = props;
3554 
3555 	curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
3556 
3557 	while (curr) {
3558 		zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
3559 		nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
3560 
3561 		/*
3562 		 * We leave user:props in the nvlist, so there will be
3563 		 * some ZPROP_INVAL.  To be extra safe, don't prune
3564 		 * those.
3565 		 */
3566 		if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
3567 			(void) nvlist_remove(zhp->zfs_props,
3568 			    nvpair_name(curr), nvpair_type(curr));
3569 		curr = next;
3570 	}
3571 }
3572 
3573 static int
3574 zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
3575     zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
3576 {
3577 	zfs_cmd_t zc = { 0 };
3578 	nvlist_t *nvlist = NULL;
3579 	int error;
3580 
3581 	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
3582 	(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
3583 	zc.zc_cookie = (uint64_t)cmd;
3584 
3585 	if (cmd == ZFS_SMB_ACL_RENAME) {
3586 		if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
3587 			(void) no_memory(hdl);
3588 			return (NULL);
3589 		}
3590 	}
3591 
3592 	switch (cmd) {
3593 	case ZFS_SMB_ACL_ADD:
3594 	case ZFS_SMB_ACL_REMOVE:
3595 		(void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
3596 		break;
3597 	case ZFS_SMB_ACL_RENAME:
3598 		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
3599 		    resource1) != 0) {
3600 				(void) no_memory(hdl);
3601 				return (-1);
3602 		}
3603 		if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
3604 		    resource2) != 0) {
3605 				(void) no_memory(hdl);
3606 				return (-1);
3607 		}
3608 		if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
3609 			nvlist_free(nvlist);
3610 			return (-1);
3611 		}
3612 		break;
3613 	case ZFS_SMB_ACL_PURGE:
3614 		break;
3615 	default:
3616 		return (-1);
3617 	}
3618 	error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
3619 	if (nvlist)
3620 		nvlist_free(nvlist);
3621 	return (error);
3622 }
3623 
3624 int
3625 zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
3626     char *path, char *resource)
3627 {
3628 	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
3629 	    resource, NULL));
3630 }
3631 
3632 int
3633 zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
3634     char *path, char *resource)
3635 {
3636 	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
3637 	    resource, NULL));
3638 }
3639 
3640 int
3641 zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
3642 {
3643 	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
3644 	    NULL, NULL));
3645 }
3646 
3647 int
3648 zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
3649     char *oldname, char *newname)
3650 {
3651 	return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
3652 	    oldname, newname));
3653 }
3654 
3655 int
3656 zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
3657     zfs_userspace_cb_t func, void *arg)
3658 {
3659 	zfs_cmd_t zc = { 0 };
3660 	int error;
3661 	zfs_useracct_t buf[100];
3662 
3663 	(void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3664 
3665 	zc.zc_objset_type = type;
3666 	zc.zc_nvlist_dst = (uintptr_t)buf;
3667 
3668 	/* CONSTCOND */
3669 	while (1) {
3670 		zfs_useracct_t *zua = buf;
3671 
3672 		zc.zc_nvlist_dst_size = sizeof (buf);
3673 		error = ioctl(zhp->zfs_hdl->libzfs_fd,
3674 		    ZFS_IOC_USERSPACE_MANY, &zc);
3675 		if (error || zc.zc_nvlist_dst_size == 0)
3676 			break;
3677 
3678 		while (zc.zc_nvlist_dst_size > 0) {
3679 			error = func(arg, zua->zu_domain, zua->zu_rid,
3680 			    zua->zu_space);
3681 			if (error != 0)
3682 				return (error);
3683 			zua++;
3684 			zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
3685 		}
3686 	}
3687 
3688 	return (error);
3689 }
3690 
3691 int
3692 zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
3693     boolean_t recursive, boolean_t temphold)
3694 {
3695 	zfs_cmd_t zc = { 0 };
3696 	libzfs_handle_t *hdl = zhp->zfs_hdl;
3697 
3698 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3699 	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
3700 	if (strlcpy(zc.zc_string, tag, sizeof (zc.zc_string))
3701 	    >= sizeof (zc.zc_string))
3702 		return (zfs_error(hdl, EZFS_TAGTOOLONG, tag));
3703 	zc.zc_cookie = recursive;
3704 	zc.zc_temphold = temphold;
3705 
3706 	if (zfs_ioctl(hdl, ZFS_IOC_HOLD, &zc) != 0) {
3707 		char errbuf[ZFS_MAXNAMELEN+32];
3708 
3709 		/*
3710 		 * if it was recursive, the one that actually failed will be in
3711 		 * zc.zc_name.
3712 		 */
3713 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3714 		    "cannot hold '%s@%s'"), zc.zc_name, snapname);
3715 		switch (errno) {
3716 		case ENOTSUP:
3717 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3718 			    "pool must be upgraded"));
3719 			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3720 		case EINVAL:
3721 			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3722 		case EEXIST:
3723 			return (zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf));
3724 		default:
3725 			return (zfs_standard_error_fmt(hdl, errno, errbuf));
3726 		}
3727 	}
3728 
3729 	return (0);
3730 }
3731 
3732 struct hold_range_arg {
3733 	zfs_handle_t	*origin;
3734 	const char	*fromsnap;
3735 	const char	*tosnap;
3736 	char		lastsnapheld[ZFS_MAXNAMELEN];
3737 	const char	*tag;
3738 	boolean_t	temphold;
3739 	boolean_t	seento;
3740 	boolean_t	seenfrom;
3741 	boolean_t	holding;
3742 };
3743 
3744 static int
3745 zfs_hold_range_one(zfs_handle_t *zhp, void *arg)
3746 {
3747 	struct hold_range_arg *hra = arg;
3748 	const char *thissnap;
3749 	int error;
3750 
3751 	thissnap = strchr(zfs_get_name(zhp), '@') + 1;
3752 
3753 	if (hra->fromsnap && !hra->seenfrom &&
3754 	    strcmp(hra->fromsnap, thissnap) == 0)
3755 		hra->seenfrom = B_TRUE;
3756 
3757 	/* snap is older or newer than the desired range, ignore it */
3758 	if (hra->seento || !hra->seenfrom) {
3759 		zfs_close(zhp);
3760 		return (0);
3761 	}
3762 
3763 	if (hra->holding) {
3764 		error = zfs_hold(hra->origin, thissnap, hra->tag, B_FALSE,
3765 		    hra->temphold);
3766 		if (error == 0) {
3767 			(void) strlcpy(hra->lastsnapheld, zfs_get_name(zhp),
3768 			    sizeof (hra->lastsnapheld));
3769 		}
3770 	} else {
3771 		error = zfs_release(hra->origin, thissnap, hra->tag, B_FALSE);
3772 	}
3773 
3774 	if (!hra->seento && strcmp(hra->tosnap, thissnap) == 0)
3775 		hra->seento = B_TRUE;
3776 
3777 	zfs_close(zhp);
3778 	return (error);
3779 }
3780 
3781 /*
3782  * Add a user hold on the set of snapshots starting with fromsnap up to
3783  * and including tosnap. If we're unable to to acquire a particular hold,
3784  * undo any holds up to that point.
3785  */
3786 int
3787 zfs_hold_range(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
3788     const char *tag, boolean_t temphold)
3789 {
3790 	struct hold_range_arg arg = { 0 };
3791 	int error;
3792 
3793 	arg.origin = zhp;
3794 	arg.fromsnap = fromsnap;
3795 	arg.tosnap = tosnap;
3796 	arg.tag = tag;
3797 	arg.temphold = temphold;
3798 	arg.holding = B_TRUE;
3799 
3800 	error = zfs_iter_snapshots_sorted(zhp, zfs_hold_range_one, &arg);
3801 
3802 	/*
3803 	 * Make sure we either hold the entire range or none.
3804 	 */
3805 	if (error && arg.lastsnapheld[0] != '\0') {
3806 		(void) zfs_release_range(zhp, fromsnap,
3807 		    (const char *)arg.lastsnapheld, tag);
3808 	}
3809 	return (error);
3810 }
3811 
3812 int
3813 zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
3814     boolean_t recursive)
3815 {
3816 	zfs_cmd_t zc = { 0 };
3817 	libzfs_handle_t *hdl = zhp->zfs_hdl;
3818 
3819 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3820 	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
3821 	if (strlcpy(zc.zc_string, tag, sizeof (zc.zc_string))
3822 	    >= sizeof (zc.zc_string))
3823 		return (zfs_error(hdl, EZFS_TAGTOOLONG, tag));
3824 	zc.zc_cookie = recursive;
3825 
3826 	if (zfs_ioctl(hdl, ZFS_IOC_RELEASE, &zc) != 0) {
3827 		char errbuf[ZFS_MAXNAMELEN+32];
3828 
3829 		/*
3830 		 * if it was recursive, the one that actually failed will be in
3831 		 * zc.zc_name.
3832 		 */
3833 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3834 		    "cannot release '%s@%s'"), zc.zc_name, snapname);
3835 		switch (errno) {
3836 		case ESRCH:
3837 			return (zfs_error(hdl, EZFS_REFTAG_RELE, errbuf));
3838 		case ENOTSUP:
3839 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3840 			    "pool must be upgraded"));
3841 			return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3842 		case EINVAL:
3843 			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3844 		default:
3845 			return (zfs_standard_error_fmt(hdl, errno, errbuf));
3846 		}
3847 	}
3848 
3849 	return (0);
3850 }
3851 
3852 /*
3853  * Release a user hold from the set of snapshots starting with fromsnap
3854  * up to and including tosnap.
3855  */
3856 int
3857 zfs_release_range(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
3858     const char *tag)
3859 {
3860 	struct hold_range_arg arg = { 0 };
3861 
3862 	arg.origin = zhp;
3863 	arg.fromsnap = fromsnap;
3864 	arg.tosnap = tosnap;
3865 	arg.tag = tag;
3866 
3867 	return (zfs_iter_snapshots_sorted(zhp, zfs_hold_range_one, &arg));
3868 }
3869