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