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