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