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