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