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