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