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