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