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