xref: /freebsd/sys/contrib/openzfs/module/zfs/zfs_ioctl.c (revision d0b3ecdc274930e190ea233b6b69ff03782eaf8d)
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  * Portions Copyright 2011 Martin Matuska
26  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
27  * Copyright (c) 2012 Pawel Jakub Dawidek
28  * Copyright (c) 2014, 2016 Joyent, Inc. All rights reserved.
29  * Copyright 2016 Nexenta Systems, Inc.  All rights reserved.
30  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
31  * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
32  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
33  * Copyright (c) 2013 Steven Hartland. All rights reserved.
34  * Copyright (c) 2014 Integros [integros.com]
35  * Copyright 2016 Toomas Soome <tsoome@me.com>
36  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
37  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
38  * Copyright 2017 RackTop Systems.
39  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
40  * Copyright (c) 2019 Datto Inc.
41  * Copyright (c) 2019, 2020 by Christian Schwarz. All rights reserved.
42  * Copyright (c) 2019, 2021, 2023, 2024, Klara Inc.
43  * Copyright (c) 2019, Allan Jude
44  * Copyright 2026 Oxide Computer Company
45  */
46 
47 /*
48  * ZFS ioctls.
49  *
50  * This file handles the ioctls to /dev/zfs, used for configuring ZFS storage
51  * pools and filesystems, e.g. with /sbin/zfs and /sbin/zpool.
52  *
53  * There are two ways that we handle ioctls: the legacy way where almost
54  * all of the logic is in the ioctl callback, and the new way where most
55  * of the marshalling is handled in the common entry point, zfsdev_ioctl().
56  *
57  * Non-legacy ioctls should be registered by calling
58  * zfs_ioctl_register() from zfs_ioctl_init().  The ioctl is invoked
59  * from userland by lzc_ioctl().
60  *
61  * The registration arguments are as follows:
62  *
63  * const char *name
64  *   The name of the ioctl.  This is used for history logging.  If the
65  *   ioctl returns successfully (the callback returns 0), and allow_log
66  *   is true, then a history log entry will be recorded with the input &
67  *   output nvlists.  The log entry can be printed with "zpool history -i".
68  *
69  * zfs_ioc_t ioc
70  *   The ioctl request number, which userland will pass to ioctl(2).
71  *   We want newer versions of libzfs and libzfs_core to run against
72  *   existing zfs kernel modules (i.e. a deferred reboot after an update).
73  *   Therefore the ioctl numbers cannot change from release to release.
74  *
75  * zfs_secpolicy_func_t *secpolicy
76  *   This function will be called before the zfs_ioc_func_t, to
77  *   determine if this operation is permitted.  It should return EPERM
78  *   on failure, and 0 on success.  Checks include determining if the
79  *   dataset is visible in this zone, and if the user has either all
80  *   zfs privileges in the zone (SYS_MOUNT), or has been granted permission
81  *   to do this operation on this dataset with "zfs allow".
82  *
83  * zfs_ioc_namecheck_t namecheck
84  *   This specifies what to expect in the zfs_cmd_t:zc_name -- a pool
85  *   name, a dataset name, or nothing.  If the name is not well-formed,
86  *   the ioctl will fail and the callback will not be called.
87  *   Therefore, the callback can assume that the name is well-formed
88  *   (e.g. is null-terminated, doesn't have more than one '@' character,
89  *   doesn't have invalid characters).
90  *
91  * zfs_ioc_poolcheck_t pool_check
92  *   This specifies requirements on the pool state.  If the pool does
93  *   not meet them (is suspended or is readonly), the ioctl will fail
94  *   and the callback will not be called.  If any checks are specified
95  *   (i.e. it is not POOL_CHECK_NONE), namecheck must not be NO_NAME.
96  *   Multiple checks can be or-ed together (e.g. POOL_CHECK_SUSPENDED |
97  *   POOL_CHECK_READONLY).
98  *
99  * zfs_ioc_key_t *nvl_keys
100  *  The list of expected/allowable innvl input keys. This list is used
101  *  to validate the nvlist input to the ioctl.
102  *
103  * boolean_t smush_outnvlist
104  *   If smush_outnvlist is true, then the output is presumed to be a
105  *   list of errors, and it will be "smushed" down to fit into the
106  *   caller's buffer, by removing some entries and replacing them with a
107  *   single "N_MORE_ERRORS" entry indicating how many were removed.  See
108  *   nvlist_smush() for details.  If smush_outnvlist is false, and the
109  *   outnvlist does not fit into the userland-provided buffer, then the
110  *   ioctl will fail with ENOMEM.
111  *
112  * zfs_ioc_func_t *func
113  *   The callback function that will perform the operation.
114  *
115  *   The callback should return 0 on success, or an error number on
116  *   failure.  If the function fails, the userland ioctl will return -1,
117  *   and errno will be set to the callback's return value.  The callback
118  *   will be called with the following arguments:
119  *
120  *   const char *name
121  *     The name of the pool or dataset to operate on, from
122  *     zfs_cmd_t:zc_name.  The 'namecheck' argument specifies the
123  *     expected type (pool, dataset, or none).
124  *
125  *   nvlist_t *innvl
126  *     The input nvlist, deserialized from zfs_cmd_t:zc_nvlist_src.  Or
127  *     NULL if no input nvlist was provided.  Changes to this nvlist are
128  *     ignored.  If the input nvlist could not be deserialized, the
129  *     ioctl will fail and the callback will not be called.
130  *
131  *   nvlist_t *outnvl
132  *     The output nvlist, initially empty.  The callback can fill it in,
133  *     and it will be returned to userland by serializing it into
134  *     zfs_cmd_t:zc_nvlist_dst.  If it is non-empty, and serialization
135  *     fails (e.g. because the caller didn't supply a large enough
136  *     buffer), then the overall ioctl will fail.  See the
137  *     'smush_nvlist' argument above for additional behaviors.
138  *
139  *     There are two typical uses of the output nvlist:
140  *       - To return state, e.g. property values.  In this case,
141  *         smush_outnvlist should be false.  If the buffer was not large
142  *         enough, the caller will reallocate a larger buffer and try
143  *         the ioctl again.
144  *
145  *       - To return multiple errors from an ioctl which makes on-disk
146  *         changes.  In this case, smush_outnvlist should be true.
147  *         Ioctls which make on-disk modifications should generally not
148  *         use the outnvl if they succeed, because the caller can not
149  *         distinguish between the operation failing, and
150  *         deserialization failing.
151  *
152  * IOCTL Interface Errors
153  *
154  * The following ioctl input errors can be returned:
155  *   ZFS_ERR_IOC_CMD_UNAVAIL	the ioctl number is not supported by kernel
156  *   ZFS_ERR_IOC_ARG_UNAVAIL	an input argument is not supported by kernel
157  *   ZFS_ERR_IOC_ARG_REQUIRED	a required input argument is missing
158  *   ZFS_ERR_IOC_ARG_BADTYPE	an input argument has an invalid type
159  */
160 
161 #include <sys/types.h>
162 #include <sys/param.h>
163 #include <sys/errno.h>
164 #include <sys/file.h>
165 #include <sys/kmem.h>
166 #include <sys/cmn_err.h>
167 #include <sys/stat.h>
168 #include <sys/zfs_ioctl.h>
169 #include <sys/zfs_quota.h>
170 #include <sys/zfs_vfsops.h>
171 #include <sys/zfs_znode.h>
172 #include <sys/zap.h>
173 #include <sys/spa.h>
174 #include <sys/spa_impl.h>
175 #include <sys/vdev.h>
176 #include <sys/vdev_impl.h>
177 #include <sys/dmu.h>
178 #include <sys/dsl_dir.h>
179 #include <sys/dsl_dataset.h>
180 #include <sys/dsl_prop.h>
181 #include <sys/dsl_deleg.h>
182 #include <sys/dmu_objset.h>
183 #include <sys/dmu_impl.h>
184 #include <sys/dmu_redact.h>
185 #include <sys/dmu_tx.h>
186 #include <sys/sunddi.h>
187 #include <sys/policy.h>
188 #include <sys/zone.h>
189 #include <sys/nvpair.h>
190 #include <sys/pathname.h>
191 #include <sys/fs/zfs.h>
192 #include <sys/zfs_ctldir.h>
193 #include <sys/zfs_dir.h>
194 #include <sys/zfs_onexit.h>
195 #include <sys/zvol.h>
196 #include <sys/dsl_scan.h>
197 #include <sys/fm/util.h>
198 #include <sys/dsl_crypt.h>
199 #include <sys/rrwlock.h>
200 #include <sys/zfs_file.h>
201 
202 #include <sys/dmu_recv.h>
203 #include <sys/dmu_send.h>
204 #include <sys/dmu_recv.h>
205 #include <sys/dsl_destroy.h>
206 #include <sys/dsl_bookmark.h>
207 #include <sys/dsl_userhold.h>
208 #include <sys/zfeature.h>
209 #include <sys/zcp.h>
210 #include <sys/zio_checksum.h>
211 #include <sys/vdev_removal.h>
212 #include <sys/vdev_impl.h>
213 #include <sys/vdev_initialize.h>
214 #include <sys/vdev_trim.h>
215 #include <sys/brt.h>
216 #include <sys/ddt.h>
217 
218 #include "zfs_namecheck.h"
219 #include "zfs_prop.h"
220 #include "zfs_deleg.h"
221 #include "zfs_comutil.h"
222 
223 #include <sys/lua/lua.h>
224 #include <sys/lua/lauxlib.h>
225 #include <sys/zfs_ioctl_impl.h>
226 
227 kmutex_t zfsdev_state_lock;
228 static zfsdev_state_t zfsdev_state_listhead;
229 
230 /*
231  * Limit maximum nvlist size.  We don't want users passing in insane values
232  * for zc->zc_nvlist_src_size, since we will need to allocate that much memory.
233  * Defaults to 0=auto which is handled by platform code.
234  */
235 uint64_t zfs_max_nvlist_src_size = 0;
236 
237 /*
238  * When logging the output nvlist of an ioctl in the on-disk history, limit
239  * the logged size to this many bytes.  This must be less than DMU_MAX_ACCESS.
240  * This applies primarily to zfs_ioc_channel_program().
241  */
242 static uint64_t zfs_history_output_max = 1024 * 1024;
243 
244 uint_t zfs_allow_log_key;
245 
246 /* DATA_TYPE_ANY is used when zkey_type can vary. */
247 #define	DATA_TYPE_ANY	DATA_TYPE_UNKNOWN
248 
249 typedef struct zfs_ioc_vec {
250 	zfs_ioc_legacy_func_t	*zvec_legacy_func;
251 	zfs_ioc_func_t		*zvec_func;
252 	zfs_secpolicy_func_t	*zvec_secpolicy;
253 	zfs_ioc_namecheck_t	zvec_namecheck;
254 	boolean_t		zvec_allow_log;
255 	zfs_ioc_poolcheck_t	zvec_pool_check;
256 	boolean_t		zvec_smush_outnvlist;
257 	const char		*zvec_name;
258 	const zfs_ioc_key_t	*zvec_nvl_keys;
259 	size_t			zvec_nvl_key_count;
260 } zfs_ioc_vec_t;
261 
262 /* This array is indexed by zfs_userquota_prop_t */
263 static const char *userquota_perms[] = {
264 	ZFS_DELEG_PERM_USERUSED,
265 	ZFS_DELEG_PERM_USERQUOTA,
266 	ZFS_DELEG_PERM_GROUPUSED,
267 	ZFS_DELEG_PERM_GROUPQUOTA,
268 	ZFS_DELEG_PERM_USEROBJUSED,
269 	ZFS_DELEG_PERM_USEROBJQUOTA,
270 	ZFS_DELEG_PERM_GROUPOBJUSED,
271 	ZFS_DELEG_PERM_GROUPOBJQUOTA,
272 	ZFS_DELEG_PERM_PROJECTUSED,
273 	ZFS_DELEG_PERM_PROJECTQUOTA,
274 	ZFS_DELEG_PERM_PROJECTOBJUSED,
275 	ZFS_DELEG_PERM_PROJECTOBJQUOTA,
276 };
277 
278 static int zfs_ioc_userspace_upgrade(zfs_cmd_t *zc);
279 static int zfs_ioc_id_quota_upgrade(zfs_cmd_t *zc);
280 static int zfs_check_settable(const char *name, nvpair_t *property,
281     cred_t *cr);
282 static int zfs_check_clearable(const char *dataset, nvlist_t *props,
283     nvlist_t **errors);
284 static int zfs_fill_zplprops_root(uint64_t, nvlist_t *, nvlist_t *,
285     boolean_t *);
286 int zfs_set_prop_nvlist(const char *, zprop_source_t, nvlist_t *, nvlist_t *);
287 static int get_nvlist(uint64_t nvl, uint64_t size, int iflag, nvlist_t **nvp);
288 
289 /*
290  * Callback for SPL to look up zoned_uid property.
291  * Walks ancestors to find the delegation root with zoned_uid set.
292  * Returns the zoned_uid value if found, or 0 if not set.
293  */
294 static uid_t
zfs_get_zoned_uid(const char * dataset,char * root_out,size_t root_size)295 zfs_get_zoned_uid(const char *dataset, char *root_out, size_t root_size)
296 {
297 	char path[ZFS_MAX_DATASET_NAME_LEN];
298 	char setpoint[ZFS_MAX_DATASET_NAME_LEN];
299 	char *slash, *at;
300 	uint64_t zoned_uid_val = 0;
301 	int error;
302 
303 	(void) strlcpy(path, dataset, sizeof (path));
304 
305 	/*
306 	 * Strip snapshot suffix if present — snapshots inherit properties
307 	 * from their parent filesystem.
308 	 */
309 	at = strchr(path, '@');
310 	if (at != NULL)
311 		*at = '\0';
312 
313 	/*
314 	 * Walk up the hierarchy until we find a dataset with zoned_uid set.
315 	 * This handles the case where the dataset doesn't exist yet (e.g.,
316 	 * rename destination) — dsl_prop_get fails on non-existent datasets,
317 	 * so we walk up to find an existing ancestor.
318 	 *
319 	 * When the property is found (possibly via inheritance), setpoint
320 	 * tells us the actual delegation root where zoned_uid is locally
321 	 * set, rather than the dataset where we happened to query it.
322 	 */
323 	while (path[0] != '\0') {
324 		error = dsl_prop_get(path, "zoned_uid", 8, 1,
325 		    &zoned_uid_val, setpoint);
326 
327 		if (error == 0 && zoned_uid_val != 0) {
328 			if (root_out != NULL)
329 				(void) strlcpy(root_out, setpoint, root_size);
330 			return ((uid_t)zoned_uid_val);
331 		}
332 
333 		slash = strrchr(path, '/');
334 		if (slash == NULL)
335 			break;
336 		*slash = '\0';
337 	}
338 
339 	return (0);
340 }
341 
342 static void
history_str_free(char * buf)343 history_str_free(char *buf)
344 {
345 	kmem_free(buf, HIS_MAX_RECORD_LEN);
346 }
347 
348 static char *
history_str_get(zfs_cmd_t * zc)349 history_str_get(zfs_cmd_t *zc)
350 {
351 	char *buf;
352 
353 	if (zc->zc_history == 0)
354 		return (NULL);
355 
356 	buf = kmem_alloc(HIS_MAX_RECORD_LEN, KM_SLEEP);
357 	if (copyinstr((void *)(uintptr_t)zc->zc_history,
358 	    buf, HIS_MAX_RECORD_LEN, NULL) != 0) {
359 		history_str_free(buf);
360 		return (NULL);
361 	}
362 
363 	buf[HIS_MAX_RECORD_LEN -1] = '\0';
364 
365 	return (buf);
366 }
367 
368 /*
369  * Return non-zero if the spa version is less than requested version.
370  */
371 static int
zfs_earlier_version(const char * name,int version)372 zfs_earlier_version(const char *name, int version)
373 {
374 	spa_t *spa;
375 
376 	if (spa_open(name, &spa, FTAG) == 0) {
377 		if (spa_version(spa) < version) {
378 			spa_close(spa, FTAG);
379 			return (1);
380 		}
381 		spa_close(spa, FTAG);
382 	}
383 	return (0);
384 }
385 
386 /*
387  * Return TRUE if the ZPL version is less than requested version.
388  */
389 static boolean_t
zpl_earlier_version(const char * name,int version)390 zpl_earlier_version(const char *name, int version)
391 {
392 	objset_t *os;
393 	boolean_t rc = B_TRUE;
394 
395 	if (dmu_objset_hold(name, FTAG, &os) == 0) {
396 		uint64_t zplversion;
397 
398 		if (dmu_objset_type(os) != DMU_OST_ZFS) {
399 			dmu_objset_rele(os, FTAG);
400 			return (B_TRUE);
401 		}
402 		/* XXX reading from non-owned objset */
403 		if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &zplversion) == 0)
404 			rc = zplversion < version;
405 		dmu_objset_rele(os, FTAG);
406 	}
407 	return (rc);
408 }
409 
410 static void
zfs_log_history(zfs_cmd_t * zc)411 zfs_log_history(zfs_cmd_t *zc)
412 {
413 	spa_t *spa;
414 	char *buf;
415 
416 	if ((buf = history_str_get(zc)) == NULL)
417 		return;
418 
419 	if (spa_open(zc->zc_name, &spa, FTAG) == 0) {
420 		if (spa_version(spa) >= SPA_VERSION_ZPOOL_HISTORY)
421 			(void) spa_history_log(spa, buf);
422 		spa_close(spa, FTAG);
423 	}
424 	history_str_free(buf);
425 }
426 
427 /*
428  * Policy for top-level read operations (list pools).  Requires no privileges,
429  * and can be used in the local zone, as there is no associated dataset.
430  */
431 static int
zfs_secpolicy_none(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)432 zfs_secpolicy_none(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
433 {
434 	(void) zc, (void) innvl, (void) cr;
435 	return (0);
436 }
437 
438 /*
439  * Policy for dataset read operations (list children, get statistics).  Requires
440  * no privileges, but must be visible in the local zone.
441  */
442 static int
zfs_secpolicy_read(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)443 zfs_secpolicy_read(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
444 {
445 	(void) innvl, (void) cr;
446 	if (INGLOBALZONE(curproc) ||
447 	    zone_dataset_visible(zc->zc_name, NULL))
448 		return (0);
449 
450 	return (SET_ERROR(ENOENT));
451 }
452 
453 static int
zfs_dozonecheck_impl(const char * dataset,uint64_t zoned,cred_t * cr)454 zfs_dozonecheck_impl(const char *dataset, uint64_t zoned, cred_t *cr)
455 {
456 	int writable = 1;
457 
458 	/*
459 	 * The dataset must be visible by this zone -- check this first
460 	 * so they don't see EPERM on something they shouldn't know about.
461 	 */
462 	if (!INGLOBALZONE(curproc) &&
463 	    !zone_dataset_visible(dataset, &writable))
464 		return (SET_ERROR(ENOENT));
465 
466 	if (INGLOBALZONE(curproc)) {
467 		/*
468 		 * If the fs is zoned, only root can access it from the
469 		 * global zone.
470 		 */
471 		if (secpolicy_zfs(cr) && zoned)
472 			return (SET_ERROR(EPERM));
473 	} else {
474 		/*
475 		 * If we are in a local zone, the 'zoned' property must be set.
476 		 */
477 		if (!zoned)
478 			return (SET_ERROR(EPERM));
479 
480 		/* must be writable by this zone */
481 		if (!writable)
482 			return (SET_ERROR(EPERM));
483 	}
484 	return (0);
485 }
486 
487 static int
zfs_dozonecheck(const char * dataset,cred_t * cr)488 zfs_dozonecheck(const char *dataset, cred_t *cr)
489 {
490 	uint64_t zoned;
491 
492 	if (dsl_prop_get_integer(dataset, zfs_prop_to_name(ZFS_PROP_ZONED),
493 	    &zoned, NULL))
494 		return (SET_ERROR(ENOENT));
495 
496 	return (zfs_dozonecheck_impl(dataset, zoned, cr));
497 }
498 
499 static int
zfs_dozonecheck_ds(const char * dataset,dsl_dataset_t * ds,cred_t * cr)500 zfs_dozonecheck_ds(const char *dataset, dsl_dataset_t *ds, cred_t *cr)
501 {
502 	uint64_t zoned;
503 
504 	if (dsl_prop_get_int_ds(ds, zfs_prop_to_name(ZFS_PROP_ZONED), &zoned))
505 		return (SET_ERROR(ENOENT));
506 
507 	return (zfs_dozonecheck_impl(dataset, zoned, cr));
508 }
509 
510 static int
zfs_secpolicy_write_perms_ds(const char * name,dsl_dataset_t * ds,const char * perm,cred_t * cr)511 zfs_secpolicy_write_perms_ds(const char *name, dsl_dataset_t *ds,
512     const char *perm, cred_t *cr)
513 {
514 	int error;
515 
516 	error = zfs_dozonecheck_ds(name, ds, cr);
517 	if (error == 0) {
518 		error = secpolicy_zfs(cr);
519 		if (error != 0)
520 			error = dsl_deleg_access_impl(ds, perm, cr);
521 	}
522 	return (error);
523 }
524 
525 static int
zfs_secpolicy_write_perms(const char * name,const char * perm,cred_t * cr)526 zfs_secpolicy_write_perms(const char *name, const char *perm, cred_t *cr)
527 {
528 	int error;
529 	dsl_dataset_t *ds;
530 	dsl_pool_t *dp;
531 
532 	/*
533 	 * First do a quick check for root in the global zone, which
534 	 * is allowed to do all write_perms.  This ensures that zfs_ioc_*
535 	 * will get to handle nonexistent datasets.
536 	 */
537 	if (INGLOBALZONE(curproc) && secpolicy_zfs(cr) == 0)
538 		return (0);
539 
540 	error = dsl_pool_hold(name, FTAG, &dp);
541 	if (error != 0)
542 		return (error);
543 
544 	error = dsl_dataset_hold(dp, name, FTAG, &ds);
545 	if (error != 0) {
546 		dsl_pool_rele(dp, FTAG);
547 		return (error);
548 	}
549 
550 	error = zfs_secpolicy_write_perms_ds(name, ds, perm, cr);
551 
552 	dsl_dataset_rele(ds, FTAG);
553 	dsl_pool_rele(dp, FTAG);
554 	return (error);
555 }
556 
557 /*
558  * Check dsl_deleg permission for zoned_uid datasets.
559  *
560  * This bypasses zfs_dozonecheck_ds() (which requires the 'zoned' property)
561  * because zoned_uid datasets use a different authentication model.  The zone
562  * check was already performed by zone_dataset_admin_check().
563  *
564  * Returns 0 if permission is granted, error otherwise.
565  * ECANCELED from dsl_deleg_access_impl() means delegation is disabled on the
566  * pool — in that case we deny access (POLP: no delegation = no access).
567  */
568 static int
zfs_secpolicy_zoned_uid_deleg(const char * name,const char * perm,cred_t * cr)569 zfs_secpolicy_zoned_uid_deleg(const char *name, const char *perm, cred_t *cr)
570 {
571 	dsl_pool_t *dp;
572 	dsl_dataset_t *ds;
573 	int error;
574 
575 	error = dsl_pool_hold(name, FTAG, &dp);
576 	if (error != 0)
577 		return (error);
578 	error = dsl_dataset_hold(dp, name, FTAG, &ds);
579 	if (error != 0) {
580 		dsl_pool_rele(dp, FTAG);
581 		return (error);
582 	}
583 	error = dsl_deleg_access_impl(ds, perm, cr);
584 	dsl_dataset_rele(ds, FTAG);
585 	dsl_pool_rele(dp, FTAG);
586 
587 	/* ECANCELED = delegation disabled on pool; deny access (POLP) */
588 	if (error == ECANCELED)
589 		return (SET_ERROR(EPERM));
590 	return (error);
591 }
592 
593 /*
594  * Policy for setting the security label property.
595  *
596  * Returns 0 for success, non-zero for access and other errors.
597  */
598 static int
zfs_set_slabel_policy(const char * name,const char * strval,cred_t * cr)599 zfs_set_slabel_policy(const char *name, const char *strval, cred_t *cr)
600 {
601 #ifdef HAVE_MLSLABEL
602 	char		ds_hexsl[MAXNAMELEN];
603 	bslabel_t	ds_sl, new_sl;
604 	boolean_t	new_default = FALSE;
605 	uint64_t	zoned;
606 	int		needed_priv = -1;
607 	int		error;
608 
609 	/* First get the existing dataset label. */
610 	error = dsl_prop_get(name, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
611 	    1, sizeof (ds_hexsl), &ds_hexsl, NULL);
612 	if (error != 0)
613 		return (SET_ERROR(EPERM));
614 
615 	if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
616 		new_default = TRUE;
617 
618 	/* The label must be translatable */
619 	if (!new_default && (hexstr_to_label(strval, &new_sl) != 0))
620 		return (SET_ERROR(EINVAL));
621 
622 	/*
623 	 * In a non-global zone, disallow attempts to set a label that
624 	 * doesn't match that of the zone; otherwise no other checks
625 	 * are needed.
626 	 */
627 	if (!INGLOBALZONE(curproc)) {
628 		if (new_default || !blequal(&new_sl, CR_SL(CRED())))
629 			return (SET_ERROR(EPERM));
630 		return (0);
631 	}
632 
633 	/*
634 	 * For global-zone datasets (i.e., those whose zoned property is
635 	 * "off", verify that the specified new label is valid for the
636 	 * global zone.
637 	 */
638 	if (dsl_prop_get_integer(name,
639 	    zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
640 		return (SET_ERROR(EPERM));
641 	if (!zoned) {
642 		if (zfs_check_global_label(name, strval) != 0)
643 			return (SET_ERROR(EPERM));
644 	}
645 
646 	/*
647 	 * If the existing dataset label is nondefault, check if the
648 	 * dataset is mounted (label cannot be changed while mounted).
649 	 * Get the zfsvfs_t; if there isn't one, then the dataset isn't
650 	 * mounted (or isn't a dataset, doesn't exist, ...).
651 	 */
652 	if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) != 0) {
653 		objset_t *os;
654 		static const char *setsl_tag = "setsl_tag";
655 
656 		/*
657 		 * Try to own the dataset; abort if there is any error,
658 		 * (e.g., already mounted, in use, or other error).
659 		 */
660 		error = dmu_objset_own(name, DMU_OST_ZFS, B_TRUE, B_TRUE,
661 		    setsl_tag, &os);
662 		if (error != 0)
663 			return (SET_ERROR(EPERM));
664 
665 		dmu_objset_disown(os, B_TRUE, setsl_tag);
666 
667 		if (new_default) {
668 			needed_priv = PRIV_FILE_DOWNGRADE_SL;
669 			goto out_check;
670 		}
671 
672 		if (hexstr_to_label(strval, &new_sl) != 0)
673 			return (SET_ERROR(EPERM));
674 
675 		if (blstrictdom(&ds_sl, &new_sl))
676 			needed_priv = PRIV_FILE_DOWNGRADE_SL;
677 		else if (blstrictdom(&new_sl, &ds_sl))
678 			needed_priv = PRIV_FILE_UPGRADE_SL;
679 	} else {
680 		/* dataset currently has a default label */
681 		if (!new_default)
682 			needed_priv = PRIV_FILE_UPGRADE_SL;
683 	}
684 
685 out_check:
686 	if (needed_priv != -1)
687 		return (PRIV_POLICY(cr, needed_priv, B_FALSE, EPERM, NULL));
688 	return (0);
689 #else
690 	return (SET_ERROR(ENOTSUP));
691 #endif /* HAVE_MLSLABEL */
692 }
693 
694 static int
zfs_secpolicy_setprop(const char * dsname,zfs_prop_t prop,nvpair_t * propval,cred_t * cr)695 zfs_secpolicy_setprop(const char *dsname, zfs_prop_t prop, nvpair_t *propval,
696     cred_t *cr)
697 {
698 	const char *strval;
699 	zone_admin_result_t zone_result;
700 
701 	/*
702 	 * Check zoned_uid delegation first.  However, even delegated
703 	 * namespace users must not be allowed to modify zoned_uid itself.
704 	 */
705 	zone_result = zone_dataset_admin_check(dsname, ZONE_OP_SETPROP, NULL);
706 	if (zone_result == ZONE_ADMIN_ALLOWED) {
707 		if (prop == ZFS_PROP_ZONED_UID)
708 			return (SET_ERROR(EPERM));
709 		if (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
710 		    prop == ZFS_PROP_SNAPSHOT_LIMIT) {
711 			char setpoint[ZFS_MAX_DATASET_NAME_LEN];
712 			uint64_t zoned_uid_val = 0;
713 			if (dsl_prop_get(dsname, "zoned_uid", 8, 1,
714 			    &zoned_uid_val, setpoint) == 0 &&
715 			    zoned_uid_val != 0 &&
716 			    strcmp(dsname, setpoint) == 0)
717 				return (SET_ERROR(EPERM));
718 		}
719 		return (zfs_secpolicy_zoned_uid_deleg(dsname,
720 		    zfs_prop_to_name(prop), cr));
721 	}
722 	if (zone_result == ZONE_ADMIN_DENIED)
723 		return (SET_ERROR(EPERM));
724 
725 	/*
726 	 * Check permissions for special properties.
727 	 */
728 	switch (prop) {
729 	default:
730 		break;
731 	case ZFS_PROP_ZONED:
732 		/*
733 		 * Disallow setting of 'zoned' from within a local zone.
734 		 */
735 		if (!INGLOBALZONE(curproc))
736 			return (SET_ERROR(EPERM));
737 		break;
738 	case ZFS_PROP_ZONED_UID:
739 		/*
740 		 * Disallow setting of 'zoned_uid' from within a
741 		 * delegated namespace -- only global zone can manage
742 		 * delegation assignments.
743 		 */
744 		if (!INGLOBALZONE(curproc))
745 			return (SET_ERROR(EPERM));
746 		break;
747 
748 	case ZFS_PROP_QUOTA:
749 	case ZFS_PROP_FILESYSTEM_LIMIT:
750 	case ZFS_PROP_SNAPSHOT_LIMIT:
751 		if (!INGLOBALZONE(curproc)) {
752 			uint64_t zoned;
753 			char setpoint[ZFS_MAX_DATASET_NAME_LEN];
754 			/*
755 			 * Unprivileged users are allowed to modify the
756 			 * limit on things *under* (ie. contained by)
757 			 * the thing they own.
758 			 */
759 			if (dsl_prop_get_integer(dsname,
760 			    zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, setpoint))
761 				return (SET_ERROR(EPERM));
762 			if (!zoned || strlen(dsname) <= strlen(setpoint))
763 				return (SET_ERROR(EPERM));
764 		}
765 		break;
766 
767 	case ZFS_PROP_MLSLABEL:
768 		if (!is_system_labeled())
769 			return (SET_ERROR(EPERM));
770 
771 		if (nvpair_value_string(propval, &strval) == 0) {
772 			int err;
773 
774 			err = zfs_set_slabel_policy(dsname, strval, CRED());
775 			if (err != 0)
776 				return (err);
777 		}
778 		break;
779 	}
780 
781 	return (zfs_secpolicy_write_perms(dsname, zfs_prop_to_name(prop), cr));
782 }
783 
784 static int
zfs_secpolicy_set_fsacl(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)785 zfs_secpolicy_set_fsacl(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
786 {
787 	/*
788 	 * permission to set permissions will be evaluated later in
789 	 * dsl_deleg_can_allow()
790 	 */
791 	(void) innvl;
792 	return (zfs_dozonecheck(zc->zc_name, cr));
793 }
794 
795 static int
zfs_secpolicy_rollback(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)796 zfs_secpolicy_rollback(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
797 {
798 	(void) innvl;
799 	return (zfs_secpolicy_write_perms(zc->zc_name,
800 	    ZFS_DELEG_PERM_ROLLBACK, cr));
801 }
802 
803 static int
zfs_secpolicy_send_impl(const char * name,dsl_dataset_t * ds,cred_t * cr,boolean_t rawok)804 zfs_secpolicy_send_impl(const char *name, dsl_dataset_t *ds, cred_t *cr,
805     boolean_t rawok)
806 {
807 	/* Can't send from within a zone that can't see the dataset */
808 	int err = zfs_dozonecheck_ds(name, ds, cr);
809 	if (err != 0)
810 		return (err);
811 
812 	/* ZFS global admin (root) can do anything. */
813 	err = secpolicy_zfs(cr);
814 	if (err == 0)
815 		return (0);
816 
817 	/* 'send' permission on this dataset is allowed to send. */
818 	err = dsl_deleg_access_impl(ds, ZFS_DELEG_PERM_SEND, cr);
819 	if (err == 0)
820 		return (0);
821 
822 	/* Raw sends have extra perms that might work. */
823 	if (rawok) {
824 		/* 'send:raw' permission on this dataset can do raw sends. */
825 		err = dsl_deleg_access_impl(ds, ZFS_DELEG_PERM_SEND_RAW, cr);
826 		if (err == 0)
827 			return (0);
828 
829 		if (ds->ds_dir->dd_crypto_obj != 0) {
830 			/*
831 			 * Dataset is encrypted; 'send:encrypted' permission
832 			 * will allow a raw send.
833 			 */
834 			err = dsl_deleg_access_impl(ds,
835 			    ZFS_DELEG_PERM_SEND_ENCRYPTED, cr);
836 			if (err == 0)
837 				return (0);
838 		}
839 	}
840 
841 	return (err);
842 }
843 
844 static int
zfs_secpolicy_send(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)845 zfs_secpolicy_send(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
846 {
847 	(void) innvl;
848 	dsl_pool_t *dp;
849 	dsl_dataset_t *ds;
850 	const char *cp;
851 	int error;
852 	boolean_t rawok = !!(zc->zc_flags & 0x8);
853 
854 	/*
855 	 * Generate the current snapshot name from the given objsetid, then
856 	 * use that name for the secpolicy/zone checks.
857 	 */
858 	cp = strchr(zc->zc_name, '@');
859 	if (cp == NULL)
860 		return (SET_ERROR(EINVAL));
861 	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
862 	if (error != 0)
863 		return (error);
864 
865 	error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
866 	if (error != 0) {
867 		dsl_pool_rele(dp, FTAG);
868 		return (error);
869 	}
870 
871 	dsl_dataset_name(ds, zc->zc_name);
872 
873 	error = zfs_secpolicy_send_impl(zc->zc_name, ds, cr, rawok);
874 
875 	dsl_dataset_rele(ds, FTAG);
876 	dsl_pool_rele(dp, FTAG);
877 
878 	return (error);
879 }
880 
881 static int
zfs_secpolicy_send_new(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)882 zfs_secpolicy_send_new(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
883 {
884 	dsl_pool_t *dp;
885 	dsl_dataset_t *ds;
886 	int error;
887 	boolean_t rawok = nvlist_exists(innvl, "rawok");
888 
889 	if (INGLOBALZONE(curproc) && secpolicy_zfs(cr) == 0)
890 		return (0);
891 
892 	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
893 	if (error != 0)
894 		return (error);
895 
896 	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
897 	if (error != 0) {
898 		dsl_pool_rele(dp, FTAG);
899 		return (error);
900 	}
901 
902 	error = zfs_secpolicy_send_impl(zc->zc_name, ds, cr, rawok);
903 
904 	dsl_dataset_rele(ds, FTAG);
905 	dsl_pool_rele(dp, FTAG);
906 
907 	return (error);
908 }
909 
910 static int
zfs_secpolicy_share(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)911 zfs_secpolicy_share(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
912 {
913 	(void) zc, (void) innvl, (void) cr;
914 	return (SET_ERROR(ENOTSUP));
915 }
916 
917 static int
zfs_secpolicy_smb_acl(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)918 zfs_secpolicy_smb_acl(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
919 {
920 	(void) zc, (void) innvl, (void) cr;
921 	return (SET_ERROR(ENOTSUP));
922 }
923 
924 static int
zfs_get_parent(const char * datasetname,char * parent,int parentsize)925 zfs_get_parent(const char *datasetname, char *parent, int parentsize)
926 {
927 	char *cp;
928 
929 	/*
930 	 * Remove the @bla or /bla from the end of the name to get the parent.
931 	 */
932 	(void) strlcpy(parent, datasetname, parentsize);
933 	cp = strrchr(parent, '@');
934 	if (cp != NULL) {
935 		cp[0] = '\0';
936 	} else {
937 		cp = strrchr(parent, '/');
938 		if (cp == NULL)
939 			return (SET_ERROR(ENOENT));
940 		cp[0] = '\0';
941 	}
942 
943 	return (0);
944 }
945 
946 int
zfs_secpolicy_destroy_perms(const char * name,cred_t * cr)947 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
948 {
949 	int error;
950 	zone_admin_result_t result;
951 
952 	/* Check zoned_uid delegation first */
953 	result = zone_dataset_admin_check(name, ZONE_OP_DESTROY, NULL);
954 	if (result == ZONE_ADMIN_ALLOWED) {
955 		if ((error = zfs_secpolicy_zoned_uid_deleg(name,
956 		    ZFS_DELEG_PERM_DESTROY, cr)) != 0)
957 			return (error);
958 		return (zfs_secpolicy_zoned_uid_deleg(name,
959 		    ZFS_DELEG_PERM_MOUNT, cr));
960 	}
961 	if (result == ZONE_ADMIN_DENIED)
962 		return (SET_ERROR(EPERM));
963 
964 	/* NOT_APPLICABLE: continue with existing checks */
965 	if ((error = zfs_secpolicy_write_perms(name,
966 	    ZFS_DELEG_PERM_MOUNT, cr)) != 0)
967 		return (error);
968 
969 	return (zfs_secpolicy_write_perms(name, ZFS_DELEG_PERM_DESTROY, cr));
970 }
971 
972 static int
zfs_secpolicy_destroy(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)973 zfs_secpolicy_destroy(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
974 {
975 	(void) innvl;
976 	return (zfs_secpolicy_destroy_perms(zc->zc_name, cr));
977 }
978 
979 /*
980  * Destroying snapshots with delegated permissions requires
981  * descendant mount and destroy permissions.
982  */
983 static int
zfs_secpolicy_destroy_snaps(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)984 zfs_secpolicy_destroy_snaps(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
985 {
986 	(void) zc;
987 	nvlist_t *snaps;
988 	nvpair_t *pair, *nextpair;
989 	int error = 0;
990 
991 	snaps = fnvlist_lookup_nvlist(innvl, "snaps");
992 
993 	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
994 	    pair = nextpair) {
995 		nextpair = nvlist_next_nvpair(snaps, pair);
996 		error = zfs_secpolicy_destroy_perms(nvpair_name(pair), cr);
997 		if (error == ENOENT) {
998 			/*
999 			 * Ignore any snapshots that don't exist (we consider
1000 			 * them "already destroyed").  Remove the name from the
1001 			 * nvl here in case the snapshot is created between
1002 			 * now and when we try to destroy it (in which case
1003 			 * we don't want to destroy it since we haven't
1004 			 * checked for permission).
1005 			 */
1006 			fnvlist_remove_nvpair(snaps, pair);
1007 			error = 0;
1008 		}
1009 		if (error != 0)
1010 			break;
1011 	}
1012 
1013 	return (error);
1014 }
1015 
1016 int
zfs_secpolicy_rename_perms(const char * from,const char * to,cred_t * cr)1017 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
1018 {
1019 	char	parentname[ZFS_MAX_DATASET_NAME_LEN];
1020 	int	error;
1021 	zone_admin_result_t result;
1022 
1023 	/* Check zoned_uid delegation first */
1024 	result = zone_dataset_admin_check(from, ZONE_OP_RENAME, to);
1025 	if (result == ZONE_ADMIN_ALLOWED) {
1026 		if ((error = zfs_secpolicy_zoned_uid_deleg(from,
1027 		    ZFS_DELEG_PERM_RENAME, cr)) != 0)
1028 			return (error);
1029 		return (zfs_secpolicy_zoned_uid_deleg(from,
1030 		    ZFS_DELEG_PERM_MOUNT, cr));
1031 	}
1032 	if (result == ZONE_ADMIN_DENIED)
1033 		return (SET_ERROR(EPERM));
1034 
1035 	/* NOT_APPLICABLE: continue with existing checks */
1036 	if ((error = zfs_secpolicy_write_perms(from,
1037 	    ZFS_DELEG_PERM_RENAME, cr)) != 0)
1038 		return (error);
1039 
1040 	if ((error = zfs_secpolicy_write_perms(from,
1041 	    ZFS_DELEG_PERM_MOUNT, cr)) != 0)
1042 		return (error);
1043 
1044 	if ((error = zfs_get_parent(to, parentname,
1045 	    sizeof (parentname))) != 0)
1046 		return (error);
1047 
1048 	if ((error = zfs_secpolicy_write_perms(parentname,
1049 	    ZFS_DELEG_PERM_CREATE, cr)) != 0)
1050 		return (error);
1051 
1052 	if ((error = zfs_secpolicy_write_perms(parentname,
1053 	    ZFS_DELEG_PERM_MOUNT, cr)) != 0)
1054 		return (error);
1055 
1056 	return (error);
1057 }
1058 
1059 static int
zfs_secpolicy_rename(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1060 zfs_secpolicy_rename(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1061 {
1062 	(void) innvl;
1063 	return (zfs_secpolicy_rename_perms(zc->zc_name, zc->zc_value, cr));
1064 }
1065 
1066 static int
zfs_secpolicy_promote(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1067 zfs_secpolicy_promote(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1068 {
1069 	(void) innvl;
1070 	dsl_pool_t *dp;
1071 	dsl_dataset_t *clone;
1072 	int error;
1073 
1074 	error = zfs_secpolicy_write_perms(zc->zc_name,
1075 	    ZFS_DELEG_PERM_PROMOTE, cr);
1076 	if (error != 0)
1077 		return (error);
1078 
1079 	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
1080 	if (error != 0)
1081 		return (error);
1082 
1083 	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &clone);
1084 
1085 	if (error == 0) {
1086 		char parentname[ZFS_MAX_DATASET_NAME_LEN];
1087 		dsl_dataset_t *origin = NULL;
1088 		dsl_dir_t *dd;
1089 		dd = clone->ds_dir;
1090 
1091 		error = dsl_dataset_hold_obj(dd->dd_pool,
1092 		    dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin);
1093 		if (error != 0) {
1094 			dsl_dataset_rele(clone, FTAG);
1095 			dsl_pool_rele(dp, FTAG);
1096 			return (error);
1097 		}
1098 
1099 		error = zfs_secpolicy_write_perms_ds(zc->zc_name, clone,
1100 		    ZFS_DELEG_PERM_MOUNT, cr);
1101 
1102 		dsl_dataset_name(origin, parentname);
1103 		if (error == 0) {
1104 			error = zfs_secpolicy_write_perms_ds(parentname, origin,
1105 			    ZFS_DELEG_PERM_PROMOTE, cr);
1106 		}
1107 		dsl_dataset_rele(clone, FTAG);
1108 		dsl_dataset_rele(origin, FTAG);
1109 	}
1110 	dsl_pool_rele(dp, FTAG);
1111 	return (error);
1112 }
1113 
1114 static int
zfs_secpolicy_recv(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1115 zfs_secpolicy_recv(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1116 {
1117 	(void) innvl;
1118 	int error;
1119 
1120 	/*
1121 	 * zfs receive -F requires full receive permission,
1122 	 * otherwise receive:append permission is enough
1123 	 */
1124 	if ((error = zfs_secpolicy_write_perms(zc->zc_name,
1125 	    ZFS_DELEG_PERM_RECEIVE, cr)) != 0) {
1126 		if (zc->zc_guid || nvlist_exists(innvl, "force"))
1127 			return (error);
1128 		if ((error = zfs_secpolicy_write_perms(zc->zc_name,
1129 		    ZFS_DELEG_PERM_RECEIVE_APPEND, cr)) != 0)
1130 			return (error);
1131 	}
1132 
1133 	if ((error = zfs_secpolicy_write_perms(zc->zc_name,
1134 	    ZFS_DELEG_PERM_MOUNT, cr)) != 0)
1135 		return (error);
1136 
1137 	return (zfs_secpolicy_write_perms(zc->zc_name,
1138 	    ZFS_DELEG_PERM_CREATE, cr));
1139 }
1140 
1141 /*
1142  * Policy for dataset set property operations.  Individual properties checked by
1143  * zfs_check_settable(), additionally require zfs_secpolicy_recv() when setting
1144  * properties as part of a receive.
1145  */
1146 static int
zfs_secpolicy_setprops(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1147 zfs_secpolicy_setprops(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1148 {
1149 	boolean_t received = zc->zc_cookie;
1150 	int error;
1151 
1152 	if (received && (error = zfs_secpolicy_recv(zc, innvl, cr)))
1153 		return (error);
1154 
1155 	return (zfs_secpolicy_read(zc, innvl, cr));
1156 }
1157 
1158 int
zfs_secpolicy_snapshot_perms(const char * name,cred_t * cr)1159 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
1160 {
1161 	zone_admin_result_t result;
1162 
1163 	/* Check zoned_uid delegation first */
1164 	result = zone_dataset_admin_check(name, ZONE_OP_SNAPSHOT, NULL);
1165 	if (result == ZONE_ADMIN_ALLOWED)
1166 		return (zfs_secpolicy_zoned_uid_deleg(name,
1167 		    ZFS_DELEG_PERM_SNAPSHOT, cr));
1168 	if (result == ZONE_ADMIN_DENIED)
1169 		return (SET_ERROR(EPERM));
1170 
1171 	/* NOT_APPLICABLE: continue with existing checks */
1172 	return (zfs_secpolicy_write_perms(name,
1173 	    ZFS_DELEG_PERM_SNAPSHOT, cr));
1174 }
1175 
1176 /*
1177  * Check for permission to create each snapshot in the nvlist.
1178  */
1179 static int
zfs_secpolicy_snapshot(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1180 zfs_secpolicy_snapshot(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1181 {
1182 	(void) zc;
1183 	nvlist_t *snaps;
1184 	int error = 0;
1185 	nvpair_t *pair;
1186 
1187 	snaps = fnvlist_lookup_nvlist(innvl, "snaps");
1188 
1189 	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
1190 	    pair = nvlist_next_nvpair(snaps, pair)) {
1191 		char *name = (char *)nvpair_name(pair);
1192 		char *atp = strchr(name, '@');
1193 
1194 		if (atp == NULL) {
1195 			error = SET_ERROR(EINVAL);
1196 			break;
1197 		}
1198 		*atp = '\0';
1199 		error = zfs_secpolicy_snapshot_perms(name, cr);
1200 		*atp = '@';
1201 		if (error != 0)
1202 			break;
1203 	}
1204 	return (error);
1205 }
1206 
1207 /*
1208  * Check for permission to create each bookmark in the nvlist.
1209  */
1210 static int
zfs_secpolicy_bookmark(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1211 zfs_secpolicy_bookmark(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1212 {
1213 	(void) zc;
1214 	int error = 0;
1215 
1216 	for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
1217 	    pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
1218 		char *name = (char *)nvpair_name(pair);
1219 		char *hashp = strchr(name, '#');
1220 
1221 		if (hashp == NULL) {
1222 			error = SET_ERROR(EINVAL);
1223 			break;
1224 		}
1225 		*hashp = '\0';
1226 		error = zfs_secpolicy_write_perms(name,
1227 		    ZFS_DELEG_PERM_BOOKMARK, cr);
1228 		*hashp = '#';
1229 		if (error != 0)
1230 			break;
1231 	}
1232 	return (error);
1233 }
1234 
1235 static int
zfs_secpolicy_destroy_bookmarks(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1236 zfs_secpolicy_destroy_bookmarks(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1237 {
1238 	(void) zc;
1239 	nvpair_t *pair, *nextpair;
1240 	int error = 0;
1241 
1242 	for (pair = nvlist_next_nvpair(innvl, NULL); pair != NULL;
1243 	    pair = nextpair) {
1244 		char *name = (char *)nvpair_name(pair);
1245 		char *hashp = strchr(name, '#');
1246 		nextpair = nvlist_next_nvpair(innvl, pair);
1247 
1248 		if (hashp == NULL) {
1249 			error = SET_ERROR(EINVAL);
1250 			break;
1251 		}
1252 
1253 		*hashp = '\0';
1254 		error = zfs_secpolicy_write_perms(name,
1255 		    ZFS_DELEG_PERM_DESTROY, cr);
1256 		*hashp = '#';
1257 		if (error == ENOENT) {
1258 			/*
1259 			 * Ignore any filesystems that don't exist (we consider
1260 			 * their bookmarks "already destroyed").  Remove
1261 			 * the name from the nvl here in case the filesystem
1262 			 * is created between now and when we try to destroy
1263 			 * the bookmark (in which case we don't want to
1264 			 * destroy it since we haven't checked for permission).
1265 			 */
1266 			fnvlist_remove_nvpair(innvl, pair);
1267 			error = 0;
1268 		}
1269 		if (error != 0)
1270 			break;
1271 	}
1272 
1273 	return (error);
1274 }
1275 
1276 static int
zfs_secpolicy_log_history(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1277 zfs_secpolicy_log_history(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1278 {
1279 	(void) zc, (void) innvl, (void) cr;
1280 	/*
1281 	 * Even root must have a proper TSD so that we know what pool
1282 	 * to log to.
1283 	 */
1284 	if (tsd_get(zfs_allow_log_key) == NULL)
1285 		return (SET_ERROR(EPERM));
1286 	return (0);
1287 }
1288 
1289 static int
zfs_secpolicy_create_clone(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1290 zfs_secpolicy_create_clone(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1291 {
1292 	char		parentname[ZFS_MAX_DATASET_NAME_LEN];
1293 	int		error;
1294 	const char	*origin = NULL;
1295 	zone_admin_result_t result;
1296 
1297 	if ((error = zfs_get_parent(zc->zc_name, parentname,
1298 	    sizeof (parentname))) != 0)
1299 		return (error);
1300 
1301 	(void) nvlist_lookup_string(innvl, "origin", &origin);
1302 
1303 	/* Check zoned_uid delegation first */
1304 	result = zone_dataset_admin_check(parentname,
1305 	    origin != NULL ? ZONE_OP_CLONE : ZONE_OP_CREATE, origin);
1306 	if (result == ZONE_ADMIN_ALLOWED) {
1307 		if (origin != NULL) {
1308 			if ((error = zfs_secpolicy_zoned_uid_deleg(origin,
1309 			    ZFS_DELEG_PERM_CLONE, cr)) != 0)
1310 				return (error);
1311 		}
1312 		if ((error = zfs_secpolicy_zoned_uid_deleg(parentname,
1313 		    ZFS_DELEG_PERM_CREATE, cr)) != 0)
1314 			return (error);
1315 		return (zfs_secpolicy_zoned_uid_deleg(parentname,
1316 		    ZFS_DELEG_PERM_MOUNT, cr));
1317 	}
1318 	if (result == ZONE_ADMIN_DENIED)
1319 		return (SET_ERROR(EPERM));
1320 
1321 	/* NOT_APPLICABLE: continue with existing checks */
1322 	if (origin != NULL &&
1323 	    (error = zfs_secpolicy_write_perms(origin,
1324 	    ZFS_DELEG_PERM_CLONE, cr)) != 0)
1325 		return (error);
1326 
1327 	if ((error = zfs_secpolicy_write_perms(parentname,
1328 	    ZFS_DELEG_PERM_CREATE, cr)) != 0)
1329 		return (error);
1330 
1331 	return (zfs_secpolicy_write_perms(parentname,
1332 	    ZFS_DELEG_PERM_MOUNT, cr));
1333 }
1334 
1335 /*
1336  * Policy for pool operations - create/destroy pools, add vdevs, etc.  Requires
1337  * SYS_CONFIG privilege, which is not available in a local zone.
1338  */
1339 int
zfs_secpolicy_config(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1340 zfs_secpolicy_config(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1341 {
1342 	(void) zc, (void) innvl;
1343 
1344 	if (secpolicy_sys_config(cr, B_FALSE) != 0)
1345 		return (SET_ERROR(EPERM));
1346 
1347 	return (0);
1348 }
1349 
1350 /*
1351  * Policy for object to name lookups.
1352  */
1353 static int
zfs_secpolicy_diff(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1354 zfs_secpolicy_diff(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1355 {
1356 	(void) innvl;
1357 	int error;
1358 
1359 	if (secpolicy_sys_config(cr, B_FALSE) == 0)
1360 		return (0);
1361 
1362 	error = zfs_secpolicy_write_perms(zc->zc_name, ZFS_DELEG_PERM_DIFF, cr);
1363 	return (error);
1364 }
1365 
1366 /*
1367  * Policy for fault injection.  Requires all privileges.
1368  */
1369 static int
zfs_secpolicy_inject(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1370 zfs_secpolicy_inject(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1371 {
1372 	(void) zc, (void) innvl;
1373 	return (secpolicy_zinject(cr));
1374 }
1375 
1376 static int
zfs_secpolicy_inherit_prop(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1377 zfs_secpolicy_inherit_prop(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1378 {
1379 	(void) innvl;
1380 	zfs_prop_t prop = zfs_name_to_prop(zc->zc_value);
1381 
1382 	if (prop == ZPROP_USERPROP) {
1383 		if (!zfs_prop_user(zc->zc_value))
1384 			return (SET_ERROR(EINVAL));
1385 		zone_admin_result_t zone_result;
1386 		zone_result = zone_dataset_admin_check(zc->zc_name,
1387 		    ZONE_OP_SETPROP, NULL);
1388 		if (zone_result == ZONE_ADMIN_ALLOWED)
1389 			return (zfs_secpolicy_zoned_uid_deleg(zc->zc_name,
1390 			    ZFS_DELEG_PERM_USERPROP, cr));
1391 		if (zone_result == ZONE_ADMIN_DENIED)
1392 			return (SET_ERROR(EPERM));
1393 		return (zfs_secpolicy_write_perms(zc->zc_name,
1394 		    ZFS_DELEG_PERM_USERPROP, cr));
1395 	} else {
1396 		return (zfs_secpolicy_setprop(zc->zc_name, prop,
1397 		    NULL, cr));
1398 	}
1399 }
1400 
1401 static int
zfs_secpolicy_userspace_one(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1402 zfs_secpolicy_userspace_one(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1403 {
1404 	int err = zfs_secpolicy_read(zc, innvl, cr);
1405 	if (err)
1406 		return (err);
1407 
1408 	if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
1409 		return (SET_ERROR(EINVAL));
1410 
1411 	if (zc->zc_value[0] == 0) {
1412 		/*
1413 		 * They are asking about a posix uid/gid.  If it's
1414 		 * themself, allow it.
1415 		 */
1416 		if (zc->zc_objset_type == ZFS_PROP_USERUSED ||
1417 		    zc->zc_objset_type == ZFS_PROP_USERQUOTA ||
1418 		    zc->zc_objset_type == ZFS_PROP_USEROBJUSED ||
1419 		    zc->zc_objset_type == ZFS_PROP_USEROBJQUOTA) {
1420 			if (zc->zc_guid == crgetuid(cr))
1421 				return (0);
1422 		} else if (zc->zc_objset_type == ZFS_PROP_GROUPUSED ||
1423 		    zc->zc_objset_type == ZFS_PROP_GROUPQUOTA ||
1424 		    zc->zc_objset_type == ZFS_PROP_GROUPOBJUSED ||
1425 		    zc->zc_objset_type == ZFS_PROP_GROUPOBJQUOTA) {
1426 			if (groupmember(zc->zc_guid, cr))
1427 				return (0);
1428 		}
1429 		/* else is for project quota/used */
1430 	}
1431 
1432 	return (zfs_secpolicy_write_perms(zc->zc_name,
1433 	    userquota_perms[zc->zc_objset_type], cr));
1434 }
1435 
1436 static int
zfs_secpolicy_userspace_many(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1437 zfs_secpolicy_userspace_many(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1438 {
1439 	int err = zfs_secpolicy_read(zc, innvl, cr);
1440 	if (err)
1441 		return (err);
1442 
1443 	if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
1444 		return (SET_ERROR(EINVAL));
1445 
1446 	return (zfs_secpolicy_write_perms(zc->zc_name,
1447 	    userquota_perms[zc->zc_objset_type], cr));
1448 }
1449 
1450 static int
zfs_secpolicy_userspace_upgrade(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1451 zfs_secpolicy_userspace_upgrade(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1452 {
1453 	(void) innvl;
1454 	return (zfs_secpolicy_setprop(zc->zc_name, ZFS_PROP_VERSION,
1455 	    NULL, cr));
1456 }
1457 
1458 static int
zfs_secpolicy_hold(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1459 zfs_secpolicy_hold(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1460 {
1461 	(void) zc;
1462 	nvpair_t *pair;
1463 	nvlist_t *holds;
1464 	int error;
1465 
1466 	holds = fnvlist_lookup_nvlist(innvl, "holds");
1467 
1468 	for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
1469 	    pair = nvlist_next_nvpair(holds, pair)) {
1470 		char fsname[ZFS_MAX_DATASET_NAME_LEN];
1471 		error = dmu_fsname(nvpair_name(pair), fsname);
1472 		if (error != 0)
1473 			return (error);
1474 		error = zfs_secpolicy_write_perms(fsname,
1475 		    ZFS_DELEG_PERM_HOLD, cr);
1476 		if (error != 0)
1477 			return (error);
1478 	}
1479 	return (0);
1480 }
1481 
1482 static int
zfs_secpolicy_release(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1483 zfs_secpolicy_release(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1484 {
1485 	(void) zc;
1486 	nvpair_t *pair;
1487 	int error;
1488 
1489 	for (pair = nvlist_next_nvpair(innvl, NULL); pair != NULL;
1490 	    pair = nvlist_next_nvpair(innvl, pair)) {
1491 		char fsname[ZFS_MAX_DATASET_NAME_LEN];
1492 		error = dmu_fsname(nvpair_name(pair), fsname);
1493 		if (error != 0)
1494 			return (error);
1495 		error = zfs_secpolicy_write_perms(fsname,
1496 		    ZFS_DELEG_PERM_RELEASE, cr);
1497 		if (error != 0)
1498 			return (error);
1499 	}
1500 	return (0);
1501 }
1502 
1503 /*
1504  * Policy for allowing temporary snapshots to be taken or released
1505  */
1506 static int
zfs_secpolicy_tmp_snapshot(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1507 zfs_secpolicy_tmp_snapshot(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1508 {
1509 	/*
1510 	 * A temporary snapshot is the same as a snapshot,
1511 	 * hold, destroy and release all rolled into one.
1512 	 * Delegated diff alone is sufficient that we allow this.
1513 	 */
1514 	int error;
1515 
1516 	if (zfs_secpolicy_write_perms(zc->zc_name,
1517 	    ZFS_DELEG_PERM_DIFF, cr) == 0)
1518 		return (0);
1519 
1520 	error = zfs_secpolicy_snapshot_perms(zc->zc_name, cr);
1521 
1522 	if (innvl != NULL) {
1523 		if (error == 0)
1524 			error = zfs_secpolicy_hold(zc, innvl, cr);
1525 		if (error == 0)
1526 			error = zfs_secpolicy_release(zc, innvl, cr);
1527 		if (error == 0)
1528 			error = zfs_secpolicy_destroy(zc, innvl, cr);
1529 	}
1530 	return (error);
1531 }
1532 
1533 static int
zfs_secpolicy_load_key(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1534 zfs_secpolicy_load_key(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1535 {
1536 	return (zfs_secpolicy_write_perms(zc->zc_name,
1537 	    ZFS_DELEG_PERM_LOAD_KEY, cr));
1538 }
1539 
1540 static int
zfs_secpolicy_change_key(zfs_cmd_t * zc,nvlist_t * innvl,cred_t * cr)1541 zfs_secpolicy_change_key(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1542 {
1543 	return (zfs_secpolicy_write_perms(zc->zc_name,
1544 	    ZFS_DELEG_PERM_CHANGE_KEY, cr));
1545 }
1546 
1547 /*
1548  * Returns the nvlist as specified by the user in the zfs_cmd_t.
1549  */
1550 static int
get_nvlist(uint64_t nvl,uint64_t size,int iflag,nvlist_t ** nvp)1551 get_nvlist(uint64_t nvl, uint64_t size, int iflag, nvlist_t **nvp)
1552 {
1553 	char *packed;
1554 	int error;
1555 	nvlist_t *list = NULL;
1556 
1557 	/*
1558 	 * Read in and unpack the user-supplied nvlist.
1559 	 */
1560 	if (size == 0)
1561 		return (SET_ERROR(EINVAL));
1562 
1563 	packed = vmem_alloc(size, KM_SLEEP);
1564 
1565 	if (ddi_copyin((void *)(uintptr_t)nvl, packed, size, iflag) != 0) {
1566 		vmem_free(packed, size);
1567 		return (SET_ERROR(EFAULT));
1568 	}
1569 
1570 	if ((error = nvlist_unpack(packed, size, &list, 0)) != 0) {
1571 		vmem_free(packed, size);
1572 		return (error);
1573 	}
1574 
1575 	vmem_free(packed, size);
1576 
1577 	*nvp = list;
1578 	return (0);
1579 }
1580 
1581 /*
1582  * Reduce the size of this nvlist until it can be serialized in 'max' bytes.
1583  * Entries will be removed from the end of the nvlist, and one int32 entry
1584  * named "N_MORE_ERRORS" will be added indicating how many entries were
1585  * removed.
1586  */
1587 static int
nvlist_smush(nvlist_t * errors,size_t max)1588 nvlist_smush(nvlist_t *errors, size_t max)
1589 {
1590 	size_t size;
1591 
1592 	size = fnvlist_size(errors);
1593 
1594 	if (size > max) {
1595 		nvpair_t *more_errors;
1596 		int n = 0;
1597 
1598 		if (max < 1024)
1599 			return (SET_ERROR(ENOMEM));
1600 
1601 		fnvlist_add_int32(errors, ZPROP_N_MORE_ERRORS, 0);
1602 		more_errors = nvlist_prev_nvpair(errors, NULL);
1603 
1604 		do {
1605 			nvpair_t *pair = nvlist_prev_nvpair(errors,
1606 			    more_errors);
1607 			fnvlist_remove_nvpair(errors, pair);
1608 			n++;
1609 			size = fnvlist_size(errors);
1610 		} while (size > max);
1611 
1612 		fnvlist_remove_nvpair(errors, more_errors);
1613 		fnvlist_add_int32(errors, ZPROP_N_MORE_ERRORS, n);
1614 		ASSERT3U(fnvlist_size(errors), <=, max);
1615 	}
1616 
1617 	return (0);
1618 }
1619 
1620 static int
put_nvlist(zfs_cmd_t * zc,nvlist_t * nvl)1621 put_nvlist(zfs_cmd_t *zc, nvlist_t *nvl)
1622 {
1623 	char *packed = NULL;
1624 	int error = 0;
1625 	size_t size;
1626 
1627 	size = fnvlist_size(nvl);
1628 
1629 	if (size > zc->zc_nvlist_dst_size) {
1630 		error = SET_ERROR(ENOMEM);
1631 	} else {
1632 		packed = fnvlist_pack(nvl, &size);
1633 		if (ddi_copyout(packed, (void *)(uintptr_t)zc->zc_nvlist_dst,
1634 		    size, zc->zc_iflags) != 0)
1635 			error = SET_ERROR(EFAULT);
1636 		fnvlist_pack_free(packed, size);
1637 	}
1638 
1639 	zc->zc_nvlist_dst_size = size;
1640 	zc->zc_nvlist_dst_filled = B_TRUE;
1641 	return (error);
1642 }
1643 
1644 int
getzfsvfs_impl(objset_t * os,zfsvfs_t ** zfvp)1645 getzfsvfs_impl(objset_t *os, zfsvfs_t **zfvp)
1646 {
1647 	int error = 0;
1648 	if (dmu_objset_type(os) != DMU_OST_ZFS) {
1649 		return (SET_ERROR(EINVAL));
1650 	}
1651 
1652 	mutex_enter(&os->os_user_ptr_lock);
1653 	*zfvp = dmu_objset_get_user(os);
1654 	/* bump s_active only when non-zero to prevent umount race */
1655 	error = zfs_vfs_ref(zfvp);
1656 	mutex_exit(&os->os_user_ptr_lock);
1657 	return (error);
1658 }
1659 
1660 int
getzfsvfs(const char * dsname,zfsvfs_t ** zfvp)1661 getzfsvfs(const char *dsname, zfsvfs_t **zfvp)
1662 {
1663 	objset_t *os;
1664 	int error;
1665 
1666 	error = dmu_objset_hold(dsname, FTAG, &os);
1667 	if (error != 0)
1668 		return (error);
1669 
1670 	error = getzfsvfs_impl(os, zfvp);
1671 	dmu_objset_rele(os, FTAG);
1672 	return (error);
1673 }
1674 
1675 /*
1676  * Find a zfsvfs_t for a mounted filesystem, or create our own, in which
1677  * case its z_sb will be NULL, and it will be opened as the owner.
1678  * If 'writer' is set, the z_teardown_lock will be held for RW_WRITER,
1679  * which prevents all inode ops from running.
1680  */
1681 static int
zfsvfs_hold(const char * name,const void * tag,zfsvfs_t ** zfvp,boolean_t writer)1682 zfsvfs_hold(const char *name, const void *tag, zfsvfs_t **zfvp,
1683     boolean_t writer)
1684 {
1685 	int error = 0;
1686 
1687 	if (getzfsvfs(name, zfvp) != 0)
1688 		error = zfsvfs_create_hold(name, zfvp);
1689 	if (error == 0) {
1690 		/*
1691 		 * dmu_objset_hold() keeps the pool config read lock held.
1692 		 * Drop it before acquiring the teardown lock to avoid ABBA
1693 		 * deadlock with zfs_resume_fs(), which holds teardown write
1694 		 * then acquires the config lock.
1695 		 */
1696 		if ((*zfvp)->z_use_hold)
1697 			dsl_pool_config_exit(
1698 			    dmu_objset_pool((*zfvp)->z_os), *zfvp);
1699 		if (writer)
1700 			ZFS_TEARDOWN_ENTER_WRITE(*zfvp, tag);
1701 		else
1702 			ZFS_TEARDOWN_ENTER_READ(*zfvp, tag);
1703 		if ((*zfvp)->z_unmounted) {
1704 			/*
1705 			 * XXX we could probably try again, since the unmounting
1706 			 * thread should be just about to disassociate the
1707 			 * objset from the zfsvfs.
1708 			 */
1709 			ZFS_TEARDOWN_EXIT(*zfvp, tag);
1710 			zfs_vfs_rele(*zfvp);
1711 			return (SET_ERROR(EBUSY));
1712 		}
1713 	}
1714 	return (error);
1715 }
1716 
1717 static void
zfsvfs_rele(zfsvfs_t * zfsvfs,const void * tag)1718 zfsvfs_rele(zfsvfs_t *zfsvfs, const void *tag)
1719 {
1720 	ZFS_TEARDOWN_EXIT(zfsvfs, tag);
1721 
1722 	if (zfs_vfs_held(zfsvfs)) {
1723 		zfs_vfs_rele(zfsvfs);
1724 	} else {
1725 		objset_t *os = zfsvfs->z_os;
1726 		if (zfsvfs->z_use_hold) {
1727 			/*
1728 			 * Opened via dmu_objset_hold(): re-acquire the pool
1729 			 * config lock (released in zfsvfs_hold() before the
1730 			 * teardown lock) so that dmu_objset_rele() can exit it.
1731 			 */
1732 			dsl_pool_config_enter(dmu_objset_pool(os), zfsvfs);
1733 			dmu_objset_rele(os, zfsvfs);
1734 		} else {
1735 			dmu_objset_disown(os, B_TRUE, zfsvfs);
1736 		}
1737 		zfsvfs_free(zfsvfs);
1738 	}
1739 }
1740 
1741 static int
zfs_ioc_pool_create(zfs_cmd_t * zc)1742 zfs_ioc_pool_create(zfs_cmd_t *zc)
1743 {
1744 	int error;
1745 	nvlist_t *config, *props = NULL;
1746 	nvlist_t *rootprops = NULL;
1747 	nvlist_t *zplprops = NULL;
1748 	dsl_crypto_params_t *dcp = NULL;
1749 	const char *spa_name = zc->zc_name;
1750 	boolean_t unload_wkey = B_TRUE;
1751 	nvlist_t *errinfo = NULL;
1752 
1753 	if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1754 	    zc->zc_iflags, &config)))
1755 		return (error);
1756 
1757 	if (zc->zc_nvlist_src_size != 0 && (error =
1758 	    get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1759 	    zc->zc_iflags, &props))) {
1760 		nvlist_free(config);
1761 		return (error);
1762 	}
1763 
1764 	if (props) {
1765 		nvlist_t *nvl = NULL;
1766 		nvlist_t *hidden_args = NULL;
1767 		uint64_t version = SPA_VERSION;
1768 		const char *tname;
1769 
1770 		(void) nvlist_lookup_uint64(props,
1771 		    zpool_prop_to_name(ZPOOL_PROP_VERSION), &version);
1772 		if (!SPA_VERSION_IS_SUPPORTED(version)) {
1773 			error = SET_ERROR(EINVAL);
1774 			goto pool_props_bad;
1775 		}
1776 		(void) nvlist_lookup_nvlist(props, ZPOOL_ROOTFS_PROPS, &nvl);
1777 		if (nvl) {
1778 			error = nvlist_dup(nvl, &rootprops, KM_SLEEP);
1779 			if (error != 0)
1780 				goto pool_props_bad;
1781 			(void) nvlist_remove_all(props, ZPOOL_ROOTFS_PROPS);
1782 		}
1783 
1784 		(void) nvlist_lookup_nvlist(props, ZPOOL_HIDDEN_ARGS,
1785 		    &hidden_args);
1786 		error = dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
1787 		    rootprops, hidden_args, &dcp);
1788 		if (error != 0)
1789 			goto pool_props_bad;
1790 		(void) nvlist_remove_all(props, ZPOOL_HIDDEN_ARGS);
1791 
1792 		VERIFY0(nvlist_alloc(&zplprops, NV_UNIQUE_NAME, KM_SLEEP));
1793 		error = zfs_fill_zplprops_root(version, rootprops,
1794 		    zplprops, NULL);
1795 		if (error != 0)
1796 			goto pool_props_bad;
1797 
1798 		if (nvlist_lookup_string(props,
1799 		    zpool_prop_to_name(ZPOOL_PROP_TNAME), &tname) == 0)
1800 			spa_name = tname;
1801 	}
1802 
1803 	error = spa_create(zc->zc_name, config, props, zplprops, dcp,
1804 	    &errinfo);
1805 	if (errinfo != NULL) {
1806 		nvlist_t *outnv = fnvlist_alloc();
1807 		fnvlist_add_nvlist(outnv,
1808 		    ZPOOL_CONFIG_CREATE_INFO, errinfo);
1809 		(void) put_nvlist(zc, outnv);
1810 		nvlist_free(outnv);
1811 		nvlist_free(errinfo);
1812 	}
1813 
1814 	/*
1815 	 * Set the remaining root properties
1816 	 */
1817 	if (!error && (error = zfs_set_prop_nvlist(spa_name,
1818 	    ZPROP_SRC_LOCAL, rootprops, NULL)) != 0) {
1819 		(void) spa_destroy(spa_name);
1820 		unload_wkey = B_FALSE; /* spa_destroy() unloads wrapping keys */
1821 	}
1822 
1823 pool_props_bad:
1824 	nvlist_free(rootprops);
1825 	nvlist_free(zplprops);
1826 	nvlist_free(config);
1827 	nvlist_free(props);
1828 	dsl_crypto_params_free(dcp, unload_wkey && !!error);
1829 
1830 	return (error);
1831 }
1832 
1833 static int
zfs_ioc_pool_destroy(zfs_cmd_t * zc)1834 zfs_ioc_pool_destroy(zfs_cmd_t *zc)
1835 {
1836 	int error;
1837 	zfs_log_history(zc);
1838 	error = spa_destroy(zc->zc_name);
1839 
1840 	return (error);
1841 }
1842 
1843 static int
zfs_ioc_pool_import(zfs_cmd_t * zc)1844 zfs_ioc_pool_import(zfs_cmd_t *zc)
1845 {
1846 	nvlist_t *config, *props = NULL;
1847 	uint64_t guid;
1848 	int error;
1849 
1850 	if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1851 	    zc->zc_iflags, &config)) != 0)
1852 		return (error);
1853 
1854 	if (zc->zc_nvlist_src_size != 0 && (error =
1855 	    get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1856 	    zc->zc_iflags, &props))) {
1857 		nvlist_free(config);
1858 		return (error);
1859 	}
1860 
1861 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1862 	    guid != zc->zc_guid)
1863 		error = SET_ERROR(EINVAL);
1864 	else
1865 		error = spa_import(zc->zc_name, config, props, zc->zc_cookie);
1866 
1867 	if (zc->zc_nvlist_dst != 0) {
1868 		int err;
1869 
1870 		if ((err = put_nvlist(zc, config)) != 0)
1871 			error = err;
1872 	}
1873 
1874 	nvlist_free(config);
1875 	nvlist_free(props);
1876 
1877 	return (error);
1878 }
1879 
1880 static int
zfs_ioc_pool_export(zfs_cmd_t * zc)1881 zfs_ioc_pool_export(zfs_cmd_t *zc)
1882 {
1883 	int error;
1884 	boolean_t force = (boolean_t)zc->zc_cookie;
1885 	boolean_t hardforce = (boolean_t)zc->zc_guid;
1886 
1887 	zfs_log_history(zc);
1888 	error = spa_export(zc->zc_name, NULL, force, hardforce);
1889 
1890 	return (error);
1891 }
1892 
1893 static int
zfs_ioc_pool_configs(zfs_cmd_t * zc)1894 zfs_ioc_pool_configs(zfs_cmd_t *zc)
1895 {
1896 	nvlist_t *configs;
1897 	int error;
1898 
1899 	error = spa_all_configs(&zc->zc_cookie, &configs);
1900 	if (error)
1901 		return (error);
1902 
1903 	error = put_nvlist(zc, configs);
1904 
1905 	nvlist_free(configs);
1906 
1907 	return (error);
1908 }
1909 
1910 /*
1911  * inputs:
1912  * zc_name		name of the pool
1913  *
1914  * outputs:
1915  * zc_cookie		real errno
1916  * zc_nvlist_dst	config nvlist
1917  * zc_nvlist_dst_size	size of config nvlist
1918  */
1919 static int
zfs_ioc_pool_stats(zfs_cmd_t * zc)1920 zfs_ioc_pool_stats(zfs_cmd_t *zc)
1921 {
1922 	nvlist_t *config;
1923 	int error;
1924 	int ret = 0;
1925 
1926 	error = spa_get_stats(zc->zc_name, &config, zc->zc_value,
1927 	    sizeof (zc->zc_value));
1928 
1929 	if (config != NULL) {
1930 		ret = put_nvlist(zc, config);
1931 		nvlist_free(config);
1932 
1933 		/*
1934 		 * The config may be present even if 'error' is non-zero.
1935 		 * In this case we return success, and preserve the real errno
1936 		 * in 'zc_cookie'.
1937 		 */
1938 		zc->zc_cookie = error;
1939 	} else {
1940 		ret = error;
1941 	}
1942 
1943 	return (ret);
1944 }
1945 
1946 /*
1947  * Try to import the given pool, returning pool stats as appropriate so that
1948  * user land knows which devices are available and overall pool health.
1949  */
1950 static int
zfs_ioc_pool_tryimport(zfs_cmd_t * zc)1951 zfs_ioc_pool_tryimport(zfs_cmd_t *zc)
1952 {
1953 	nvlist_t *tryconfig, *config = NULL;
1954 	int error;
1955 
1956 	if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1957 	    zc->zc_iflags, &tryconfig)) != 0)
1958 		return (error);
1959 
1960 	config = spa_tryimport(tryconfig);
1961 
1962 	nvlist_free(tryconfig);
1963 
1964 	if (config == NULL)
1965 		return (SET_ERROR(EINVAL));
1966 
1967 	error = put_nvlist(zc, config);
1968 	nvlist_free(config);
1969 
1970 	return (error);
1971 }
1972 
1973 /*
1974  * inputs:
1975  * zc_name              name of the pool
1976  * zc_cookie            scan func (pool_scan_func_t)
1977  * zc_flags             scrub pause/resume flag (pool_scrub_cmd_t)
1978  */
1979 static int
zfs_ioc_pool_scan(zfs_cmd_t * zc)1980 zfs_ioc_pool_scan(zfs_cmd_t *zc)
1981 {
1982 	spa_t *spa;
1983 	int error;
1984 
1985 	if (zc->zc_flags >= POOL_SCRUB_FLAGS_END)
1986 		return (SET_ERROR(EINVAL));
1987 
1988 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1989 		return (error);
1990 
1991 	if (zc->zc_flags == POOL_SCRUB_PAUSE)
1992 		error = spa_scrub_pause_resume(spa, POOL_SCRUB_PAUSE);
1993 	else if (zc->zc_cookie == POOL_SCAN_NONE)
1994 		error = spa_scan_stop(spa);
1995 	else
1996 		error = spa_scan(spa, zc->zc_cookie);
1997 
1998 	spa_close(spa, FTAG);
1999 
2000 	return (error);
2001 }
2002 
2003 /*
2004  * inputs:
2005  * poolname             name of the pool
2006  * scan_type            scan func (pool_scan_func_t)
2007  * scan_command         scrub pause/resume flag (pool_scrub_cmd_t)
2008  */
2009 static const zfs_ioc_key_t zfs_keys_pool_scrub[] = {
2010 	{"scan_type",		DATA_TYPE_UINT64,	0},
2011 	{"scan_command",	DATA_TYPE_UINT64,	0},
2012 	{"scan_date_start",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
2013 	{"scan_date_end",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
2014 };
2015 
2016 static int
zfs_ioc_pool_scrub(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)2017 zfs_ioc_pool_scrub(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
2018 {
2019 	spa_t *spa;
2020 	int error;
2021 	uint64_t scan_type, scan_cmd;
2022 	uint64_t date_start, date_end;
2023 
2024 	if (nvlist_lookup_uint64(innvl, "scan_type", &scan_type) != 0)
2025 		return (SET_ERROR(EINVAL));
2026 	if (nvlist_lookup_uint64(innvl, "scan_command", &scan_cmd) != 0)
2027 		return (SET_ERROR(EINVAL));
2028 
2029 	if (scan_cmd >= POOL_SCRUB_FLAGS_END)
2030 		return (SET_ERROR(EINVAL));
2031 
2032 	if (nvlist_lookup_uint64(innvl, "scan_date_start", &date_start) != 0)
2033 		date_start = 0;
2034 	if (nvlist_lookup_uint64(innvl, "scan_date_end", &date_end) != 0)
2035 		date_end = 0;
2036 
2037 	if ((error = spa_open(poolname, &spa, FTAG)) != 0)
2038 		return (error);
2039 
2040 	if (scan_cmd == POOL_SCRUB_PAUSE) {
2041 		error = spa_scrub_pause_resume(spa, POOL_SCRUB_PAUSE);
2042 	} else if (scan_type == POOL_SCAN_NONE) {
2043 		error = spa_scan_stop(spa);
2044 	} else if (scan_cmd == POOL_SCRUB_FROM_LAST_TXG) {
2045 		error = spa_scan_range(spa, scan_type,
2046 		    spa_get_last_scrubbed_txg(spa), 0);
2047 	} else {
2048 		uint64_t txg_start, txg_end;
2049 
2050 		txg_start = txg_end = 0;
2051 		if (date_start != 0 || date_end != 0) {
2052 			mutex_enter(&spa->spa_txg_log_time_lock);
2053 			if (date_start != 0) {
2054 				txg_start = dbrrd_query(&spa->spa_txg_log_time,
2055 				    date_start, DBRRD_FLOOR);
2056 			}
2057 
2058 			if (date_end != 0) {
2059 				txg_end = dbrrd_query(&spa->spa_txg_log_time,
2060 				    date_end, DBRRD_CEILING);
2061 			}
2062 			mutex_exit(&spa->spa_txg_log_time_lock);
2063 		}
2064 
2065 		error = spa_scan_range(spa, scan_type, txg_start, txg_end);
2066 	}
2067 
2068 	spa_close(spa, FTAG);
2069 	return (error);
2070 }
2071 
2072 static int
zfs_ioc_pool_freeze(zfs_cmd_t * zc)2073 zfs_ioc_pool_freeze(zfs_cmd_t *zc)
2074 {
2075 	spa_t *spa;
2076 	int error;
2077 
2078 	error = spa_open(zc->zc_name, &spa, FTAG);
2079 	if (error == 0) {
2080 		spa_freeze(spa);
2081 		spa_close(spa, FTAG);
2082 	}
2083 	return (error);
2084 }
2085 
2086 static int
zfs_ioc_pool_upgrade(zfs_cmd_t * zc)2087 zfs_ioc_pool_upgrade(zfs_cmd_t *zc)
2088 {
2089 	spa_t *spa;
2090 	int error;
2091 
2092 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2093 		return (error);
2094 
2095 	if (zc->zc_cookie < spa_version(spa) ||
2096 	    !SPA_VERSION_IS_SUPPORTED(zc->zc_cookie)) {
2097 		spa_close(spa, FTAG);
2098 		return (SET_ERROR(EINVAL));
2099 	}
2100 
2101 	spa_upgrade(spa, zc->zc_cookie);
2102 	spa_close(spa, FTAG);
2103 
2104 	return (error);
2105 }
2106 
2107 static int
zfs_ioc_pool_get_history(zfs_cmd_t * zc)2108 zfs_ioc_pool_get_history(zfs_cmd_t *zc)
2109 {
2110 	spa_t *spa;
2111 	char *hist_buf;
2112 	uint64_t size;
2113 	int error;
2114 
2115 	if ((size = zc->zc_history_len) == 0)
2116 		return (SET_ERROR(EINVAL));
2117 
2118 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2119 		return (error);
2120 
2121 	if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
2122 		spa_close(spa, FTAG);
2123 		return (SET_ERROR(ENOTSUP));
2124 	}
2125 
2126 	hist_buf = vmem_alloc(size, KM_SLEEP);
2127 	if ((error = spa_history_get(spa, &zc->zc_history_offset,
2128 	    &zc->zc_history_len, hist_buf)) == 0) {
2129 		error = ddi_copyout(hist_buf,
2130 		    (void *)(uintptr_t)zc->zc_history,
2131 		    zc->zc_history_len, zc->zc_iflags);
2132 	}
2133 
2134 	spa_close(spa, FTAG);
2135 	vmem_free(hist_buf, size);
2136 	return (error);
2137 }
2138 
2139 /*
2140  * inputs:
2141  * zc_nvlist_src	nvlist optionally containing ZPOOL_REGUID_GUID
2142  * zc_nvlist_src_size	size of the nvlist
2143  */
2144 static int
zfs_ioc_pool_reguid(zfs_cmd_t * zc)2145 zfs_ioc_pool_reguid(zfs_cmd_t *zc)
2146 {
2147 	uint64_t *guidp = NULL;
2148 	nvlist_t *props = NULL;
2149 	spa_t *spa;
2150 	uint64_t guid;
2151 	int error;
2152 
2153 	if (zc->zc_nvlist_src_size != 0) {
2154 		error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2155 		    zc->zc_iflags, &props);
2156 		if (error != 0)
2157 			return (error);
2158 
2159 		error = nvlist_lookup_uint64(props, ZPOOL_REGUID_GUID, &guid);
2160 		if (error == 0)
2161 			guidp = &guid;
2162 		else if (error == ENOENT)
2163 			guidp = NULL;
2164 		else
2165 			goto out;
2166 	}
2167 
2168 	error = spa_open(zc->zc_name, &spa, FTAG);
2169 	if (error == 0) {
2170 		error = spa_change_guid(spa, guidp);
2171 		spa_close(spa, FTAG);
2172 	}
2173 
2174 out:
2175 	if (props != NULL)
2176 		nvlist_free(props);
2177 
2178 	return (error);
2179 }
2180 
2181 static int
zfs_ioc_dsobj_to_dsname(zfs_cmd_t * zc)2182 zfs_ioc_dsobj_to_dsname(zfs_cmd_t *zc)
2183 {
2184 	return (dsl_dsobj_to_dsname(zc->zc_name, zc->zc_obj, zc->zc_value));
2185 }
2186 
2187 /*
2188  * inputs:
2189  * zc_name		name of filesystem
2190  * zc_obj		object to find
2191  *
2192  * outputs:
2193  * zc_value		name of object
2194  */
2195 static int
zfs_ioc_obj_to_path(zfs_cmd_t * zc)2196 zfs_ioc_obj_to_path(zfs_cmd_t *zc)
2197 {
2198 	objset_t *os;
2199 	int error;
2200 
2201 	/* XXX reading from objset not owned */
2202 	if ((error = dmu_objset_hold_flags(zc->zc_name, B_TRUE,
2203 	    FTAG, &os)) != 0)
2204 		return (error);
2205 	if (dmu_objset_type(os) != DMU_OST_ZFS) {
2206 		dmu_objset_rele_flags(os, B_TRUE, FTAG);
2207 		return (SET_ERROR(EINVAL));
2208 	}
2209 	error = zfs_obj_to_path(os, zc->zc_obj, zc->zc_value,
2210 	    sizeof (zc->zc_value));
2211 	dmu_objset_rele_flags(os, B_TRUE, FTAG);
2212 
2213 	return (error);
2214 }
2215 
2216 /*
2217  * inputs:
2218  * zc_name		name of filesystem
2219  * zc_obj		object to find
2220  *
2221  * outputs:
2222  * zc_stat		stats on object
2223  * zc_value		path to object
2224  */
2225 static int
zfs_ioc_obj_to_stats(zfs_cmd_t * zc)2226 zfs_ioc_obj_to_stats(zfs_cmd_t *zc)
2227 {
2228 	objset_t *os;
2229 	int error;
2230 
2231 	/* XXX reading from objset not owned */
2232 	if ((error = dmu_objset_hold_flags(zc->zc_name, B_TRUE,
2233 	    FTAG, &os)) != 0)
2234 		return (error);
2235 	if (dmu_objset_type(os) != DMU_OST_ZFS) {
2236 		dmu_objset_rele_flags(os, B_TRUE, FTAG);
2237 		return (SET_ERROR(EINVAL));
2238 	}
2239 	error = zfs_obj_to_stats(os, zc->zc_obj, &zc->zc_stat, zc->zc_value,
2240 	    sizeof (zc->zc_value));
2241 	dmu_objset_rele_flags(os, B_TRUE, FTAG);
2242 
2243 	return (error);
2244 }
2245 
2246 static int
zfs_ioc_vdev_add(zfs_cmd_t * zc)2247 zfs_ioc_vdev_add(zfs_cmd_t *zc)
2248 {
2249 	spa_t *spa;
2250 	int error;
2251 	nvlist_t *config;
2252 
2253 	error = spa_open(zc->zc_name, &spa, FTAG);
2254 	if (error != 0)
2255 		return (error);
2256 
2257 	error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
2258 	    zc->zc_iflags, &config);
2259 	if (error == 0) {
2260 		error = spa_vdev_add(spa, config, zc->zc_flags);
2261 		nvlist_free(config);
2262 	}
2263 	spa_close(spa, FTAG);
2264 	return (error);
2265 }
2266 
2267 /*
2268  * inputs:
2269  * zc_name		name of the pool
2270  * zc_guid		guid of vdev to remove
2271  * zc_cookie		cancel removal
2272  */
2273 static int
zfs_ioc_vdev_remove(zfs_cmd_t * zc)2274 zfs_ioc_vdev_remove(zfs_cmd_t *zc)
2275 {
2276 	spa_t *spa;
2277 	int error;
2278 
2279 	error = spa_open(zc->zc_name, &spa, FTAG);
2280 	if (error != 0)
2281 		return (error);
2282 	if (zc->zc_cookie != 0) {
2283 		error = spa_vdev_remove_cancel(spa);
2284 	} else {
2285 		error = spa_vdev_remove(spa, zc->zc_guid, B_FALSE);
2286 	}
2287 	spa_close(spa, FTAG);
2288 	return (error);
2289 }
2290 
2291 static int
zfs_ioc_vdev_set_state(zfs_cmd_t * zc)2292 zfs_ioc_vdev_set_state(zfs_cmd_t *zc)
2293 {
2294 	spa_t *spa;
2295 	int error;
2296 	vdev_state_t newstate = VDEV_STATE_UNKNOWN;
2297 
2298 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2299 		return (error);
2300 	switch (zc->zc_cookie) {
2301 	case VDEV_STATE_ONLINE:
2302 		error = vdev_online(spa, zc->zc_guid, zc->zc_obj, &newstate);
2303 		break;
2304 
2305 	case VDEV_STATE_OFFLINE:
2306 		error = vdev_offline(spa, zc->zc_guid, zc->zc_obj);
2307 		break;
2308 
2309 	case VDEV_STATE_FAULTED:
2310 		if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
2311 		    zc->zc_obj != VDEV_AUX_EXTERNAL &&
2312 		    zc->zc_obj != VDEV_AUX_EXTERNAL_PERSIST)
2313 			zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
2314 
2315 		error = vdev_fault(spa, zc->zc_guid, zc->zc_obj);
2316 		break;
2317 
2318 	case VDEV_STATE_DEGRADED:
2319 		if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
2320 		    zc->zc_obj != VDEV_AUX_EXTERNAL)
2321 			zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
2322 
2323 		error = vdev_degrade(spa, zc->zc_guid, zc->zc_obj);
2324 		break;
2325 
2326 	case VDEV_STATE_REMOVED:
2327 		error = vdev_remove_wanted(spa, zc->zc_guid);
2328 		break;
2329 
2330 	default:
2331 		error = SET_ERROR(EINVAL);
2332 	}
2333 	zc->zc_cookie = newstate;
2334 	spa_close(spa, FTAG);
2335 	return (error);
2336 }
2337 
2338 static int
zfs_ioc_vdev_attach(zfs_cmd_t * zc)2339 zfs_ioc_vdev_attach(zfs_cmd_t *zc)
2340 {
2341 	spa_t *spa;
2342 	nvlist_t *config;
2343 	int replacing = zc->zc_cookie;
2344 	int rebuild = zc->zc_simple;
2345 	int error;
2346 
2347 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2348 		return (error);
2349 
2350 	if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
2351 	    zc->zc_iflags, &config)) == 0) {
2352 		error = spa_vdev_attach(spa, zc->zc_guid, config, replacing,
2353 		    rebuild);
2354 		nvlist_free(config);
2355 	}
2356 
2357 	spa_close(spa, FTAG);
2358 	return (error);
2359 }
2360 
2361 static int
zfs_ioc_vdev_detach(zfs_cmd_t * zc)2362 zfs_ioc_vdev_detach(zfs_cmd_t *zc)
2363 {
2364 	spa_t *spa;
2365 	int error;
2366 
2367 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2368 		return (error);
2369 
2370 	error = spa_vdev_detach(spa, zc->zc_guid, 0, B_FALSE);
2371 
2372 	spa_close(spa, FTAG);
2373 	return (error);
2374 }
2375 
2376 static int
zfs_ioc_vdev_split(zfs_cmd_t * zc)2377 zfs_ioc_vdev_split(zfs_cmd_t *zc)
2378 {
2379 	spa_t *spa;
2380 	nvlist_t *config, *props = NULL;
2381 	int error;
2382 	boolean_t exp = !!(zc->zc_cookie & ZPOOL_EXPORT_AFTER_SPLIT);
2383 
2384 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2385 		return (error);
2386 
2387 	if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
2388 	    zc->zc_iflags, &config))) {
2389 		spa_close(spa, FTAG);
2390 		return (error);
2391 	}
2392 
2393 	if (zc->zc_nvlist_src_size != 0 && (error =
2394 	    get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2395 	    zc->zc_iflags, &props))) {
2396 		spa_close(spa, FTAG);
2397 		nvlist_free(config);
2398 		return (error);
2399 	}
2400 
2401 	error = spa_vdev_split_mirror(spa, zc->zc_string, config, props, exp);
2402 
2403 	spa_close(spa, FTAG);
2404 
2405 	nvlist_free(config);
2406 	nvlist_free(props);
2407 
2408 	return (error);
2409 }
2410 
2411 static int
zfs_ioc_vdev_setpath(zfs_cmd_t * zc)2412 zfs_ioc_vdev_setpath(zfs_cmd_t *zc)
2413 {
2414 	spa_t *spa;
2415 	const char *path = zc->zc_value;
2416 	uint64_t guid = zc->zc_guid;
2417 	int error;
2418 
2419 	error = spa_open(zc->zc_name, &spa, FTAG);
2420 	if (error != 0)
2421 		return (error);
2422 
2423 	error = spa_vdev_setpath(spa, guid, path);
2424 	spa_close(spa, FTAG);
2425 	return (error);
2426 }
2427 
2428 static int
zfs_ioc_vdev_setfru(zfs_cmd_t * zc)2429 zfs_ioc_vdev_setfru(zfs_cmd_t *zc)
2430 {
2431 	spa_t *spa;
2432 	const char *fru = zc->zc_value;
2433 	uint64_t guid = zc->zc_guid;
2434 	int error;
2435 
2436 	error = spa_open(zc->zc_name, &spa, FTAG);
2437 	if (error != 0)
2438 		return (error);
2439 
2440 	error = spa_vdev_setfru(spa, guid, fru);
2441 	spa_close(spa, FTAG);
2442 	return (error);
2443 }
2444 
2445 static int
zfs_ioc_objset_stats_impl(zfs_cmd_t * zc,objset_t * os)2446 zfs_ioc_objset_stats_impl(zfs_cmd_t *zc, objset_t *os)
2447 {
2448 	int error = 0;
2449 	nvlist_t *nv;
2450 
2451 	dmu_objset_fast_stat(os, &zc->zc_objset_stats);
2452 
2453 	if (!zc->zc_simple && zc->zc_nvlist_dst != 0 &&
2454 	    (error = dsl_prop_get_all(os, &nv)) == 0) {
2455 		dmu_objset_stats(os, nv);
2456 		/*
2457 		 * NB: zvol_get_stats() will read the objset contents,
2458 		 * which we aren't supposed to do with a
2459 		 * DS_MODE_USER hold, because it could be
2460 		 * inconsistent.  So this is a bit of a workaround...
2461 		 * XXX reading without owning
2462 		 */
2463 		if (!zc->zc_objset_stats.dds_inconsistent &&
2464 		    dmu_objset_type(os) == DMU_OST_ZVOL) {
2465 			error = zvol_get_stats(os, nv);
2466 			if (error == EIO) {
2467 				nvlist_free(nv);
2468 				return (error);
2469 			}
2470 			VERIFY0(error);
2471 		}
2472 		if (error == 0)
2473 			error = put_nvlist(zc, nv);
2474 		nvlist_free(nv);
2475 	}
2476 
2477 	return (error);
2478 }
2479 
2480 /*
2481  * inputs:
2482  * zc_name		name of filesystem
2483  * zc_nvlist_dst_size	size of buffer for property nvlist
2484  *
2485  * outputs:
2486  * zc_objset_stats	stats
2487  * zc_nvlist_dst	property nvlist
2488  * zc_nvlist_dst_size	size of property nvlist
2489  */
2490 static int
zfs_ioc_objset_stats(zfs_cmd_t * zc)2491 zfs_ioc_objset_stats(zfs_cmd_t *zc)
2492 {
2493 	objset_t *os;
2494 	int error;
2495 
2496 	error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2497 	if (error == 0) {
2498 		error = zfs_ioc_objset_stats_impl(zc, os);
2499 		dmu_objset_rele(os, FTAG);
2500 	}
2501 
2502 	return (error);
2503 }
2504 
2505 /*
2506  * inputs:
2507  * zc_name		name of filesystem
2508  * zc_nvlist_dst_size	size of buffer for property nvlist
2509  *
2510  * outputs:
2511  * zc_nvlist_dst	received property nvlist
2512  * zc_nvlist_dst_size	size of received property nvlist
2513  *
2514  * Gets received properties (distinct from local properties on or after
2515  * SPA_VERSION_RECVD_PROPS) for callers who want to differentiate received from
2516  * local property values.
2517  */
2518 static int
zfs_ioc_objset_recvd_props(zfs_cmd_t * zc)2519 zfs_ioc_objset_recvd_props(zfs_cmd_t *zc)
2520 {
2521 	int error = 0;
2522 	nvlist_t *nv;
2523 
2524 	/*
2525 	 * Without this check, we would return local property values if the
2526 	 * caller has not already received properties on or after
2527 	 * SPA_VERSION_RECVD_PROPS.
2528 	 */
2529 	if (!dsl_prop_get_hasrecvd(zc->zc_name))
2530 		return (SET_ERROR(ENOTSUP));
2531 
2532 	if (zc->zc_nvlist_dst != 0 &&
2533 	    (error = dsl_prop_get_received(zc->zc_name, &nv)) == 0) {
2534 		error = put_nvlist(zc, nv);
2535 		nvlist_free(nv);
2536 	}
2537 
2538 	return (error);
2539 }
2540 
2541 static int
nvl_add_zplprop(objset_t * os,nvlist_t * props,zfs_prop_t prop)2542 nvl_add_zplprop(objset_t *os, nvlist_t *props, zfs_prop_t prop)
2543 {
2544 	uint64_t value;
2545 	int error;
2546 
2547 	/*
2548 	 * zfs_get_zplprop() will either find a value or give us
2549 	 * the default value (if there is one).
2550 	 */
2551 	if ((error = zfs_get_zplprop(os, prop, &value)) != 0)
2552 		return (error);
2553 	VERIFY0(nvlist_add_uint64(props, zfs_prop_to_name(prop), value));
2554 	return (0);
2555 }
2556 
2557 /*
2558  * inputs:
2559  * zc_name		name of filesystem
2560  * zc_nvlist_dst_size	size of buffer for zpl property nvlist
2561  *
2562  * outputs:
2563  * zc_nvlist_dst	zpl property nvlist
2564  * zc_nvlist_dst_size	size of zpl property nvlist
2565  */
2566 static int
zfs_ioc_objset_zplprops(zfs_cmd_t * zc)2567 zfs_ioc_objset_zplprops(zfs_cmd_t *zc)
2568 {
2569 	objset_t *os;
2570 	int err;
2571 
2572 	/* XXX reading without owning */
2573 	if ((err = dmu_objset_hold(zc->zc_name, FTAG, &os)))
2574 		return (err);
2575 
2576 	dmu_objset_fast_stat(os, &zc->zc_objset_stats);
2577 
2578 	/*
2579 	 * NB: nvl_add_zplprop() will read the objset contents,
2580 	 * which we aren't supposed to do with a DS_MODE_USER
2581 	 * hold, because it could be inconsistent.
2582 	 */
2583 	if (zc->zc_nvlist_dst != 0 &&
2584 	    !zc->zc_objset_stats.dds_inconsistent &&
2585 	    dmu_objset_type(os) == DMU_OST_ZFS) {
2586 		nvlist_t *nv;
2587 
2588 		VERIFY0(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP));
2589 		if ((err = nvl_add_zplprop(os, nv, ZFS_PROP_VERSION)) == 0 &&
2590 		    (err = nvl_add_zplprop(os, nv, ZFS_PROP_NORMALIZE)) == 0 &&
2591 		    (err = nvl_add_zplprop(os, nv, ZFS_PROP_UTF8ONLY)) == 0 &&
2592 		    (err = nvl_add_zplprop(os, nv, ZFS_PROP_CASE)) == 0 &&
2593 		    (err = nvl_add_zplprop(os, nv,
2594 		    ZFS_PROP_DEFAULTUSERQUOTA)) == 0 &&
2595 		    (err = nvl_add_zplprop(os, nv,
2596 		    ZFS_PROP_DEFAULTGROUPQUOTA)) == 0 &&
2597 		    (err = nvl_add_zplprop(os, nv,
2598 		    ZFS_PROP_DEFAULTPROJECTQUOTA)) == 0 &&
2599 		    (err = nvl_add_zplprop(os, nv,
2600 		    ZFS_PROP_DEFAULTUSEROBJQUOTA)) == 0 &&
2601 		    (err = nvl_add_zplprop(os, nv,
2602 		    ZFS_PROP_DEFAULTGROUPOBJQUOTA)) == 0 &&
2603 		    (err = nvl_add_zplprop(os, nv,
2604 		    ZFS_PROP_DEFAULTPROJECTOBJQUOTA)) == 0)
2605 			err = put_nvlist(zc, nv);
2606 		nvlist_free(nv);
2607 	} else {
2608 		err = SET_ERROR(ENOENT);
2609 	}
2610 	dmu_objset_rele(os, FTAG);
2611 	return (err);
2612 }
2613 
2614 /*
2615  * inputs:
2616  * zc_name		name of filesystem
2617  * zc_cookie		zap cursor
2618  * zc_nvlist_dst_size	size of buffer for property nvlist
2619  *
2620  * outputs:
2621  * zc_name		name of next filesystem
2622  * zc_cookie		zap cursor
2623  * zc_objset_stats	stats
2624  * zc_nvlist_dst	property nvlist
2625  * zc_nvlist_dst_size	size of property nvlist
2626  */
2627 static int
zfs_ioc_dataset_list_next(zfs_cmd_t * zc)2628 zfs_ioc_dataset_list_next(zfs_cmd_t *zc)
2629 {
2630 	objset_t *os;
2631 	int error;
2632 	char *p;
2633 	size_t orig_len = strlen(zc->zc_name);
2634 
2635 top:
2636 	if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os))) {
2637 		if (error == ENOENT)
2638 			error = SET_ERROR(ESRCH);
2639 		return (error);
2640 	}
2641 
2642 	p = strrchr(zc->zc_name, '/');
2643 	if (p == NULL || p[1] != '\0')
2644 		(void) strlcat(zc->zc_name, "/", sizeof (zc->zc_name));
2645 	p = zc->zc_name + strlen(zc->zc_name);
2646 
2647 	do {
2648 		error = dmu_dir_list_next(os,
2649 		    sizeof (zc->zc_name) - (p - zc->zc_name), p,
2650 		    NULL, &zc->zc_cookie);
2651 		if (error == ENOENT)
2652 			error = SET_ERROR(ESRCH);
2653 	} while (error == 0 && zfs_dataset_name_hidden(zc->zc_name));
2654 	dmu_objset_rele(os, FTAG);
2655 
2656 	/*
2657 	 * If it's an internal dataset (ie. with a '$' in its name),
2658 	 * don't try to get stats for it, otherwise we'll return ENOENT.
2659 	 */
2660 	if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
2661 		error = zfs_ioc_objset_stats(zc); /* fill in the stats */
2662 		if (error == ENOENT) {
2663 			/* We lost a race with destroy, get the next one. */
2664 			zc->zc_name[orig_len] = '\0';
2665 			goto top;
2666 		}
2667 	}
2668 	return (error);
2669 }
2670 
2671 /*
2672  * inputs:
2673  * zc_name		name of filesystem
2674  * zc_cookie		zap cursor
2675  * zc_nvlist_src	iteration range nvlist
2676  * zc_nvlist_src_size	size of iteration range nvlist
2677  *
2678  * outputs:
2679  * zc_name		name of next snapshot
2680  * zc_objset_stats	stats
2681  * zc_nvlist_dst	property nvlist
2682  * zc_nvlist_dst_size	size of property nvlist
2683  */
2684 static int
zfs_ioc_snapshot_list_next(zfs_cmd_t * zc)2685 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2686 {
2687 	int error;
2688 	objset_t *os, *ossnap;
2689 	dsl_dataset_t *ds;
2690 	uint64_t min_txg = 0, max_txg = 0;
2691 
2692 	if (zc->zc_nvlist_src_size != 0) {
2693 		nvlist_t *props = NULL;
2694 		error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2695 		    zc->zc_iflags, &props);
2696 		if (error != 0)
2697 			return (error);
2698 		(void) nvlist_lookup_uint64(props, SNAP_ITER_MIN_TXG,
2699 		    &min_txg);
2700 		(void) nvlist_lookup_uint64(props, SNAP_ITER_MAX_TXG,
2701 		    &max_txg);
2702 		nvlist_free(props);
2703 	}
2704 
2705 	error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2706 	if (error != 0) {
2707 		return (error == ENOENT ? SET_ERROR(ESRCH) : error);
2708 	}
2709 
2710 	/*
2711 	 * A dataset name of maximum length cannot have any snapshots,
2712 	 * so exit immediately.
2713 	 */
2714 	if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >=
2715 	    ZFS_MAX_DATASET_NAME_LEN) {
2716 		dmu_objset_rele(os, FTAG);
2717 		return (SET_ERROR(ESRCH));
2718 	}
2719 
2720 	while (error == 0) {
2721 		if (issig()) {
2722 			error = SET_ERROR(EINTR);
2723 			break;
2724 		}
2725 
2726 		error = dmu_snapshot_list_next(os,
2727 		    sizeof (zc->zc_name) - strlen(zc->zc_name),
2728 		    zc->zc_name + strlen(zc->zc_name), &zc->zc_obj,
2729 		    &zc->zc_cookie, NULL);
2730 		if (error == ENOENT) {
2731 			error = SET_ERROR(ESRCH);
2732 			break;
2733 		} else if (error != 0) {
2734 			break;
2735 		}
2736 
2737 		error = dsl_dataset_hold_obj(dmu_objset_pool(os), zc->zc_obj,
2738 		    FTAG, &ds);
2739 		if (error != 0)
2740 			break;
2741 
2742 		if ((min_txg != 0 && dsl_get_creationtxg(ds) < min_txg) ||
2743 		    (max_txg != 0 && dsl_get_creationtxg(ds) > max_txg)) {
2744 			dsl_dataset_rele(ds, FTAG);
2745 			/* undo snapshot name append */
2746 			*(strchr(zc->zc_name, '@') + 1) = '\0';
2747 			/* skip snapshot */
2748 			continue;
2749 		}
2750 
2751 		if (zc->zc_simple) {
2752 			dsl_dataset_fast_stat(ds, &zc->zc_objset_stats);
2753 			dsl_dataset_rele(ds, FTAG);
2754 			break;
2755 		}
2756 
2757 		if ((error = dmu_objset_from_ds(ds, &ossnap)) != 0) {
2758 			dsl_dataset_rele(ds, FTAG);
2759 			break;
2760 		}
2761 		if ((error = zfs_ioc_objset_stats_impl(zc, ossnap)) != 0) {
2762 			dsl_dataset_rele(ds, FTAG);
2763 			break;
2764 		}
2765 		dsl_dataset_rele(ds, FTAG);
2766 		break;
2767 	}
2768 
2769 	dmu_objset_rele(os, FTAG);
2770 	/* if we failed, undo the @ that we tacked on to zc_name */
2771 	if (error != 0)
2772 		*strchr(zc->zc_name, '@') = '\0';
2773 	return (error);
2774 }
2775 
2776 static int
zfs_prop_set_userquota(const char * dsname,nvpair_t * pair)2777 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2778 {
2779 	const char *propname = nvpair_name(pair);
2780 	uint64_t *valary;
2781 	unsigned int vallen;
2782 	const char *dash, *domain;
2783 	zfs_userquota_prop_t type;
2784 	uint64_t rid;
2785 	uint64_t quota;
2786 	zfsvfs_t *zfsvfs;
2787 	int err;
2788 
2789 	if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2790 		nvlist_t *attrs;
2791 		VERIFY0(nvpair_value_nvlist(pair, &attrs));
2792 		if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2793 		    &pair) != 0)
2794 			return (SET_ERROR(EINVAL));
2795 	}
2796 
2797 	/*
2798 	 * A correctly constructed propname is encoded as
2799 	 * userquota@<rid>-<domain>.
2800 	 */
2801 	if ((dash = strchr(propname, '-')) == NULL ||
2802 	    nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2803 	    vallen != 3)
2804 		return (SET_ERROR(EINVAL));
2805 
2806 	domain = dash + 1;
2807 	type = valary[0];
2808 	rid = valary[1];
2809 	quota = valary[2];
2810 
2811 	err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2812 	if (err == 0) {
2813 		err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2814 		zfsvfs_rele(zfsvfs, FTAG);
2815 	}
2816 
2817 	return (err);
2818 }
2819 
2820 /*
2821  * If the named property is one that has a special function to set its value,
2822  * return 0 on success and a positive error code on failure; otherwise if it is
2823  * not one of the special properties handled by this function, return -1.
2824  *
2825  * XXX: It would be better for callers of the property interface if we handled
2826  * these special cases in dsl_prop.c (in the dsl layer).
2827  */
2828 static int
zfs_prop_set_special(const char * dsname,zprop_source_t source,nvpair_t * pair)2829 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2830     nvpair_t *pair)
2831 {
2832 	const char *propname = nvpair_name(pair);
2833 	zfs_prop_t prop = zfs_name_to_prop(propname);
2834 	uint64_t intval = 0;
2835 	const char *strval = NULL;
2836 	int err = -1;
2837 
2838 	if (prop == ZPROP_USERPROP) {
2839 		if (zfs_prop_userquota(propname))
2840 			return (zfs_prop_set_userquota(dsname, pair));
2841 		return (-1);
2842 	}
2843 
2844 	if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2845 		nvlist_t *attrs;
2846 		VERIFY0(nvpair_value_nvlist(pair, &attrs));
2847 		VERIFY0(nvlist_lookup_nvpair(attrs, ZPROP_VALUE, &pair));
2848 	}
2849 
2850 	/* all special properties are numeric except for keylocation */
2851 	if (zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
2852 		strval = fnvpair_value_string(pair);
2853 	} else {
2854 		intval = fnvpair_value_uint64(pair);
2855 	}
2856 
2857 	switch (prop) {
2858 	case ZFS_PROP_QUOTA:
2859 		err = dsl_dir_set_quota(dsname, source, intval);
2860 		break;
2861 	case ZFS_PROP_REFQUOTA:
2862 		err = dsl_dataset_set_refquota(dsname, source, intval);
2863 		break;
2864 	case ZFS_PROP_FILESYSTEM_LIMIT:
2865 	case ZFS_PROP_SNAPSHOT_LIMIT:
2866 		if (intval == UINT64_MAX) {
2867 			/* clearing the limit, just do it */
2868 			err = 0;
2869 		} else {
2870 			err = dsl_dir_activate_fs_ss_limit(dsname);
2871 		}
2872 		/*
2873 		 * Set err to -1 to force the zfs_set_prop_nvlist code down the
2874 		 * default path to set the value in the nvlist.
2875 		 */
2876 		if (err == 0)
2877 			err = -1;
2878 		break;
2879 	case ZFS_PROP_KEYLOCATION:
2880 		err = dsl_crypto_can_set_keylocation(dsname, strval);
2881 
2882 		/*
2883 		 * Set err to -1 to force the zfs_set_prop_nvlist code down the
2884 		 * default path to set the value in the nvlist.
2885 		 */
2886 		if (err == 0)
2887 			err = -1;
2888 		break;
2889 	case ZFS_PROP_RESERVATION:
2890 		err = dsl_dir_set_reservation(dsname, source, intval);
2891 		break;
2892 	case ZFS_PROP_REFRESERVATION:
2893 		err = dsl_dataset_set_refreservation(dsname, source, intval);
2894 		break;
2895 	case ZFS_PROP_COMPRESSION:
2896 		err = dsl_dataset_set_compression(dsname, source, intval);
2897 		/*
2898 		 * Set err to -1 to force the zfs_set_prop_nvlist code down the
2899 		 * default path to set the value in the nvlist.
2900 		 */
2901 		if (err == 0)
2902 			err = -1;
2903 		break;
2904 	case ZFS_PROP_VOLSIZE:
2905 		err = zvol_set_volsize(dsname, intval);
2906 		break;
2907 	case ZFS_PROP_VOLTHREADING:
2908 		err = zvol_set_volthreading(dsname, intval);
2909 		/*
2910 		 * Set err to -1 to force the zfs_set_prop_nvlist code down the
2911 		 * default path to set the value in the nvlist.
2912 		 */
2913 		if (err == 0)
2914 			err = -1;
2915 		break;
2916 	case ZFS_PROP_SNAPDEV:
2917 	case ZFS_PROP_VOLMODE:
2918 		err = zvol_set_common(dsname, prop, source, intval);
2919 		break;
2920 	case ZFS_PROP_READONLY:
2921 		err = zvol_set_ro(dsname, intval);
2922 		/*
2923 		 * Set err to -1 to force the zfs_set_prop_nvlist code down the
2924 		 * default path to set the value in the nvlist.
2925 		 */
2926 		if (err == 0)
2927 			err = -1;
2928 		break;
2929 	case ZFS_PROP_VERSION:
2930 	{
2931 		zfsvfs_t *zfsvfs;
2932 
2933 		if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2934 			break;
2935 
2936 		err = zfs_set_version(zfsvfs, intval);
2937 		zfsvfs_rele(zfsvfs, FTAG);
2938 
2939 		if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2940 			zfs_cmd_t *zc;
2941 
2942 			zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2943 			(void) strlcpy(zc->zc_name, dsname,
2944 			    sizeof (zc->zc_name));
2945 			(void) zfs_ioc_userspace_upgrade(zc);
2946 			(void) zfs_ioc_id_quota_upgrade(zc);
2947 			kmem_free(zc, sizeof (zfs_cmd_t));
2948 		}
2949 		break;
2950 	}
2951 	case ZFS_PROP_LONGNAME:
2952 	{
2953 		zfsvfs_t *zfsvfs;
2954 
2955 		/*
2956 		 * Ignore the checks if the property is being applied as part of
2957 		 * 'zfs receive'. Because, we already check if the local pool
2958 		 * has SPA_FEATURE_LONGNAME enabled in dmu_recv_begin_check().
2959 		 */
2960 		if (source == ZPROP_SRC_RECEIVED) {
2961 			cmn_err(CE_NOTE, "Skipping ZFS_PROP_LONGNAME checks "
2962 			    "for dsname=%s\n", dsname);
2963 			err = -1;
2964 			break;
2965 		}
2966 
2967 		if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE)) != 0) {
2968 			cmn_err(CE_WARN, "%s:%d Failed to hold for dsname=%s "
2969 			    "err=%d\n", __FILE__, __LINE__, dsname, err);
2970 			break;
2971 		}
2972 
2973 		if (!spa_feature_is_enabled(zfsvfs->z_os->os_spa,
2974 		    SPA_FEATURE_LONGNAME)) {
2975 			err = ENOTSUP;
2976 		} else {
2977 			/*
2978 			 * Set err to -1 to force the zfs_set_prop_nvlist code
2979 			 * down the default path to set the value in the nvlist.
2980 			 */
2981 			err = -1;
2982 		}
2983 		zfsvfs_rele(zfsvfs, FTAG);
2984 		break;
2985 	}
2986 	case ZFS_PROP_DEFAULTUSERQUOTA:
2987 	case ZFS_PROP_DEFAULTGROUPQUOTA:
2988 	case ZFS_PROP_DEFAULTPROJECTQUOTA:
2989 	case ZFS_PROP_DEFAULTUSEROBJQUOTA:
2990 	case ZFS_PROP_DEFAULTGROUPOBJQUOTA:
2991 	case ZFS_PROP_DEFAULTPROJECTOBJQUOTA:
2992 	{
2993 		zfsvfs_t *zfsvfs;
2994 		if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2995 			break;
2996 		err = zfs_set_default_quota(zfsvfs, prop, intval);
2997 		zfsvfs_rele(zfsvfs, FTAG);
2998 		break;
2999 	}
3000 	case ZFS_PROP_ZONED_UID:
3001 	{
3002 		uint64_t old_uid = 0;
3003 		(void) dsl_prop_get(dsname, "zoned_uid", 8, 1, &old_uid, NULL);
3004 		if (old_uid != 0)
3005 			(void) zone_dataset_detach_uid(CRED(), dsname,
3006 			    (uid_t)old_uid);
3007 		if (intval != 0) {
3008 			err = zone_dataset_attach_uid(CRED(), dsname,
3009 			    (uid_t)intval);
3010 			if (err == ENXIO)
3011 				err = ZFS_ERR_NO_USER_NS_SUPPORT;
3012 			if (err != 0)
3013 				break;
3014 		}
3015 		/*
3016 		 * Set err to -1 to force the zfs_set_prop_nvlist code down the
3017 		 * default path to set the value in the nvlist.
3018 		 */
3019 		err = -1;
3020 		break;
3021 	}
3022 	default:
3023 		err = -1;
3024 	}
3025 
3026 	return (err);
3027 }
3028 
3029 static boolean_t
zfs_is_namespace_prop(zfs_prop_t prop)3030 zfs_is_namespace_prop(zfs_prop_t prop)
3031 {
3032 	switch (prop) {
3033 
3034 	case ZFS_PROP_ATIME:
3035 	case ZFS_PROP_RELATIME:
3036 	case ZFS_PROP_DEVICES:
3037 	case ZFS_PROP_EXEC:
3038 	case ZFS_PROP_SETUID:
3039 	case ZFS_PROP_READONLY:
3040 	case ZFS_PROP_XATTR:
3041 	case ZFS_PROP_NBMAND:
3042 		return (B_TRUE);
3043 
3044 	default:
3045 		return (B_FALSE);
3046 	}
3047 }
3048 
3049 /*
3050  * This function is best effort. If it fails to set any of the given properties,
3051  * it continues to set as many as it can and returns the last error
3052  * encountered. If the caller provides a non-NULL errlist, it will be filled in
3053  * with the list of names of all the properties that failed along with the
3054  * corresponding error numbers.
3055  *
3056  * If every property is set successfully, zero is returned and errlist is not
3057  * modified.
3058  */
3059 int
zfs_set_prop_nvlist(const char * dsname,zprop_source_t source,nvlist_t * nvl,nvlist_t * errlist)3060 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
3061     nvlist_t *errlist)
3062 {
3063 	nvpair_t *pair;
3064 	nvpair_t *propval;
3065 	int rv = 0;
3066 	int err;
3067 	uint64_t intval;
3068 	const char *strval;
3069 	boolean_t should_update_mount_cache = B_FALSE;
3070 
3071 	nvlist_t *genericnvl = fnvlist_alloc();
3072 	nvlist_t *retrynvl = fnvlist_alloc();
3073 retry:
3074 	pair = NULL;
3075 	while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
3076 		const char *propname = nvpair_name(pair);
3077 		zfs_prop_t prop = zfs_name_to_prop(propname);
3078 		err = 0;
3079 
3080 		/* decode the property value */
3081 		propval = pair;
3082 		if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3083 			nvlist_t *attrs;
3084 			attrs = fnvpair_value_nvlist(pair);
3085 			if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3086 			    &propval) != 0)
3087 				err = SET_ERROR(EINVAL);
3088 		}
3089 
3090 		/* Validate value type */
3091 		if (err == 0 && source == ZPROP_SRC_INHERITED) {
3092 			/* inherited properties are expected to be booleans */
3093 			if (nvpair_type(propval) != DATA_TYPE_BOOLEAN)
3094 				err = SET_ERROR(EINVAL);
3095 		} else if (err == 0 && prop == ZPROP_USERPROP) {
3096 			if (zfs_prop_user(propname)) {
3097 				if (nvpair_type(propval) != DATA_TYPE_STRING)
3098 					err = SET_ERROR(EINVAL);
3099 			} else if (zfs_prop_userquota(propname)) {
3100 				if (nvpair_type(propval) !=
3101 				    DATA_TYPE_UINT64_ARRAY)
3102 					err = SET_ERROR(EINVAL);
3103 			} else {
3104 				err = SET_ERROR(EINVAL);
3105 			}
3106 		} else if (err == 0) {
3107 			if (nvpair_type(propval) == DATA_TYPE_STRING) {
3108 				if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
3109 					err = SET_ERROR(EINVAL);
3110 			} else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
3111 				const char *unused;
3112 
3113 				intval = fnvpair_value_uint64(propval);
3114 
3115 				switch (zfs_prop_get_type(prop)) {
3116 				case PROP_TYPE_NUMBER:
3117 					break;
3118 				case PROP_TYPE_STRING:
3119 					err = SET_ERROR(EINVAL);
3120 					break;
3121 				case PROP_TYPE_INDEX:
3122 					if (zfs_prop_index_to_string(prop,
3123 					    intval, &unused) != 0)
3124 						err =
3125 						    SET_ERROR(ZFS_ERR_BADPROP);
3126 					break;
3127 				default:
3128 					cmn_err(CE_PANIC,
3129 					    "unknown property type");
3130 				}
3131 			} else {
3132 				err = SET_ERROR(EINVAL);
3133 			}
3134 		}
3135 
3136 		/* Validate permissions */
3137 		if (err == 0)
3138 			err = zfs_check_settable(dsname, pair, CRED());
3139 
3140 		if (err == 0) {
3141 			if (source == ZPROP_SRC_INHERITED)
3142 				err = -1; /* does not need special handling */
3143 			else
3144 				err = zfs_prop_set_special(dsname, source,
3145 				    pair);
3146 			if (err == -1) {
3147 				/*
3148 				 * For better performance we build up a list of
3149 				 * properties to set in a single transaction.
3150 				 */
3151 				err = nvlist_add_nvpair(genericnvl, pair);
3152 			} else if (err != 0 && nvl != retrynvl) {
3153 				/*
3154 				 * This may be a spurious error caused by
3155 				 * receiving quota and reservation out of order.
3156 				 * Try again in a second pass.
3157 				 */
3158 				err = nvlist_add_nvpair(retrynvl, pair);
3159 			}
3160 		}
3161 
3162 		if (err != 0) {
3163 			if (errlist != NULL)
3164 				fnvlist_add_int32(errlist, propname, err);
3165 			rv = err;
3166 		}
3167 
3168 		if (zfs_is_namespace_prop(prop))
3169 			should_update_mount_cache = B_TRUE;
3170 	}
3171 
3172 	if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
3173 		nvl = retrynvl;
3174 		goto retry;
3175 	}
3176 
3177 	if (nvlist_empty(genericnvl))
3178 		goto out;
3179 
3180 	/*
3181 	 * Try to set them all in one batch.
3182 	 */
3183 	err = dsl_props_set(dsname, source, genericnvl);
3184 	if (err == 0)
3185 		goto out;
3186 
3187 	/*
3188 	 * If batching fails, we still want to set as many properties as we
3189 	 * can, so try setting them individually.
3190 	 */
3191 	pair = NULL;
3192 	while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
3193 		const char *propname = nvpair_name(pair);
3194 
3195 		propval = pair;
3196 		if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3197 			nvlist_t *attrs;
3198 			attrs = fnvpair_value_nvlist(pair);
3199 			propval = fnvlist_lookup_nvpair(attrs, ZPROP_VALUE);
3200 		}
3201 
3202 		if (nvpair_type(propval) == DATA_TYPE_STRING) {
3203 			strval = fnvpair_value_string(propval);
3204 			err = dsl_prop_set_string(dsname, propname,
3205 			    source, strval);
3206 		} else if (nvpair_type(propval) == DATA_TYPE_BOOLEAN) {
3207 			err = dsl_prop_inherit(dsname, propname, source);
3208 		} else {
3209 			intval = fnvpair_value_uint64(propval);
3210 			err = dsl_prop_set_int(dsname, propname, source,
3211 			    intval);
3212 		}
3213 
3214 		if (err != 0) {
3215 			if (errlist != NULL) {
3216 				fnvlist_add_int32(errlist, propname, err);
3217 			}
3218 			rv = err;
3219 		}
3220 	}
3221 
3222 out:
3223 	if (should_update_mount_cache)
3224 		zfs_ioctl_update_mount_cache(dsname);
3225 
3226 	nvlist_free(genericnvl);
3227 	nvlist_free(retrynvl);
3228 
3229 	return (rv);
3230 }
3231 
3232 /*
3233  * Check that all the properties are valid user properties.
3234  */
3235 static int
zfs_check_userprops(nvlist_t * nvl)3236 zfs_check_userprops(nvlist_t *nvl)
3237 {
3238 	nvpair_t *pair = NULL;
3239 
3240 	while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
3241 		const char *propname = nvpair_name(pair);
3242 
3243 		if (!zfs_prop_user(propname) ||
3244 		    nvpair_type(pair) != DATA_TYPE_STRING)
3245 			return (SET_ERROR(EINVAL));
3246 
3247 		if (strlen(propname) >= ZAP_MAXNAMELEN)
3248 			return (SET_ERROR(ENAMETOOLONG));
3249 
3250 		if (strlen(fnvpair_value_string(pair)) >= ZAP_MAXVALUELEN)
3251 			return (SET_ERROR(E2BIG));
3252 	}
3253 	return (0);
3254 }
3255 
3256 static void
props_skip(nvlist_t * props,nvlist_t * skipped,nvlist_t ** newprops)3257 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
3258 {
3259 	nvpair_t *pair;
3260 
3261 	VERIFY0(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP));
3262 
3263 	pair = NULL;
3264 	while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
3265 		if (nvlist_exists(skipped, nvpair_name(pair)))
3266 			continue;
3267 
3268 		VERIFY0(nvlist_add_nvpair(*newprops, pair));
3269 	}
3270 }
3271 
3272 static int
clear_received_props(const char * dsname,nvlist_t * props,nvlist_t * skipped)3273 clear_received_props(const char *dsname, nvlist_t *props,
3274     nvlist_t *skipped)
3275 {
3276 	int err = 0;
3277 	nvlist_t *cleared_props = NULL;
3278 	props_skip(props, skipped, &cleared_props);
3279 	if (!nvlist_empty(cleared_props)) {
3280 		/*
3281 		 * Acts on local properties until the dataset has received
3282 		 * properties at least once on or after SPA_VERSION_RECVD_PROPS.
3283 		 */
3284 		zprop_source_t flags = (ZPROP_SRC_NONE |
3285 		    (dsl_prop_get_hasrecvd(dsname) ? ZPROP_SRC_RECEIVED : 0));
3286 		err = zfs_set_prop_nvlist(dsname, flags, cleared_props, NULL);
3287 	}
3288 	nvlist_free(cleared_props);
3289 	return (err);
3290 }
3291 
3292 /*
3293  * inputs:
3294  * zc_name		name of filesystem
3295  * zc_value		name of property to set
3296  * zc_nvlist_src{_size}	nvlist of properties to apply
3297  * zc_cookie		received properties flag
3298  *
3299  * outputs:
3300  * zc_nvlist_dst{_size} error for each unapplied received property
3301  */
3302 static int
zfs_ioc_set_prop(zfs_cmd_t * zc)3303 zfs_ioc_set_prop(zfs_cmd_t *zc)
3304 {
3305 	nvlist_t *nvl;
3306 	boolean_t received = zc->zc_cookie;
3307 	zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
3308 	    ZPROP_SRC_LOCAL);
3309 	nvlist_t *errors;
3310 	int error;
3311 
3312 	if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3313 	    zc->zc_iflags, &nvl)) != 0)
3314 		return (error);
3315 
3316 	if (received) {
3317 		nvlist_t *origprops;
3318 
3319 		if (dsl_prop_get_received(zc->zc_name, &origprops) == 0) {
3320 			(void) clear_received_props(zc->zc_name,
3321 			    origprops, nvl);
3322 			nvlist_free(origprops);
3323 		}
3324 
3325 		error = dsl_prop_set_hasrecvd(zc->zc_name);
3326 	}
3327 
3328 	errors = fnvlist_alloc();
3329 	if (error == 0)
3330 		error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, errors);
3331 
3332 	if (zc->zc_nvlist_dst != 0 && errors != NULL) {
3333 		(void) put_nvlist(zc, errors);
3334 	}
3335 
3336 	nvlist_free(errors);
3337 	nvlist_free(nvl);
3338 	return (error);
3339 }
3340 
3341 /*
3342  * inputs:
3343  * zc_name		name of filesystem
3344  * zc_value		name of property to inherit
3345  * zc_cookie		revert to received value if TRUE
3346  *
3347  * outputs:		none
3348  */
3349 static int
zfs_ioc_inherit_prop(zfs_cmd_t * zc)3350 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
3351 {
3352 	const char *propname = zc->zc_value;
3353 	zfs_prop_t prop = zfs_name_to_prop(propname);
3354 	boolean_t received = zc->zc_cookie;
3355 	zprop_source_t source = (received
3356 	    ? ZPROP_SRC_NONE		/* revert to received value, if any */
3357 	    : ZPROP_SRC_INHERITED);	/* explicitly inherit */
3358 	nvlist_t *dummy;
3359 	nvpair_t *pair;
3360 	zprop_type_t type;
3361 	int err;
3362 
3363 	if (!received) {
3364 		/*
3365 		 * Only check this in the non-received case. We want to allow
3366 		 * 'inherit -S' to revert non-inheritable properties like quota
3367 		 * and reservation to the received or default values even though
3368 		 * they are not considered inheritable.
3369 		 */
3370 		if (prop != ZPROP_USERPROP && !zfs_prop_inheritable(prop))
3371 			return (SET_ERROR(EINVAL));
3372 	}
3373 
3374 	if (prop == ZPROP_USERPROP) {
3375 		if (!zfs_prop_user(propname))
3376 			return (SET_ERROR(EINVAL));
3377 
3378 		type = PROP_TYPE_STRING;
3379 	} else if (prop == ZFS_PROP_VOLSIZE || prop == ZFS_PROP_VERSION) {
3380 		return (SET_ERROR(EINVAL));
3381 	} else {
3382 		type = zfs_prop_get_type(prop);
3383 	}
3384 
3385 	/*
3386 	 * zfs_prop_set_special() expects properties in the form of an
3387 	 * nvpair with type info.
3388 	 */
3389 	dummy = fnvlist_alloc();
3390 
3391 	switch (type) {
3392 	case PROP_TYPE_STRING:
3393 		VERIFY0(nvlist_add_string(dummy, propname, ""));
3394 		break;
3395 	case PROP_TYPE_NUMBER:
3396 	case PROP_TYPE_INDEX:
3397 		VERIFY0(nvlist_add_uint64(dummy, propname, 0));
3398 		break;
3399 	default:
3400 		err = SET_ERROR(EINVAL);
3401 		goto errout;
3402 	}
3403 
3404 	pair = nvlist_next_nvpair(dummy, NULL);
3405 	if (pair == NULL) {
3406 		err = SET_ERROR(EINVAL);
3407 	} else {
3408 		err = zfs_prop_set_special(zc->zc_name, source, pair);
3409 		if (err == -1) /* property is not "special", needs handling */
3410 			err = dsl_prop_inherit(zc->zc_name, zc->zc_value,
3411 			    source);
3412 	}
3413 
3414 errout:
3415 	nvlist_free(dummy);
3416 	return (err);
3417 }
3418 
3419 static int
zfs_ioc_pool_set_props(zfs_cmd_t * zc)3420 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
3421 {
3422 	nvlist_t *props;
3423 	spa_t *spa;
3424 	int error;
3425 	nvpair_t *pair;
3426 
3427 	if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3428 	    zc->zc_iflags, &props)))
3429 		return (error);
3430 
3431 	/*
3432 	 * If the only property is the configfile, then just do a spa_lookup()
3433 	 * to handle the faulted case.
3434 	 */
3435 	pair = nvlist_next_nvpair(props, NULL);
3436 	if (pair != NULL && strcmp(nvpair_name(pair),
3437 	    zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
3438 	    nvlist_next_nvpair(props, pair) == NULL) {
3439 		spa_namespace_enter(FTAG);
3440 		if ((spa = spa_lookup(zc->zc_name)) != NULL) {
3441 			spa_configfile_set(spa, props, B_FALSE);
3442 			spa_write_cachefile(spa, B_FALSE, B_TRUE, B_FALSE);
3443 		}
3444 		spa_namespace_exit(FTAG);
3445 		if (spa != NULL) {
3446 			nvlist_free(props);
3447 			return (0);
3448 		}
3449 	}
3450 
3451 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
3452 		nvlist_free(props);
3453 		return (error);
3454 	}
3455 
3456 	error = spa_prop_set(spa, props);
3457 
3458 	nvlist_free(props);
3459 	spa_close(spa, FTAG);
3460 
3461 	return (error);
3462 }
3463 
3464 /*
3465  * innvl: {
3466  *	"get_props_names": [ "prop1", "prop2", ..., "propN" ]
3467  * }
3468  */
3469 
3470 static const zfs_ioc_key_t zfs_keys_get_props[] = {
3471 	{ ZPOOL_GET_PROPS_NAMES,	DATA_TYPE_STRING_ARRAY,	ZK_OPTIONAL },
3472 };
3473 
3474 static int
zfs_ioc_pool_get_props(const char * pool,nvlist_t * innvl,nvlist_t * outnvl)3475 zfs_ioc_pool_get_props(const char *pool, nvlist_t *innvl, nvlist_t *outnvl)
3476 {
3477 	spa_t *spa;
3478 	char **props = NULL;
3479 	unsigned int n_props = 0;
3480 	int error;
3481 
3482 	if (nvlist_lookup_string_array(innvl, ZPOOL_GET_PROPS_NAMES,
3483 	    &props, &n_props) != 0) {
3484 		props = NULL;
3485 	}
3486 
3487 	if ((error = spa_open(pool, &spa, FTAG)) != 0) {
3488 		/*
3489 		 * If the pool is faulted, there may be properties we can still
3490 		 * get (such as altroot and cachefile), so attempt to get them
3491 		 * anyway.
3492 		 */
3493 		spa_namespace_enter(FTAG);
3494 		if ((spa = spa_lookup(pool)) != NULL) {
3495 			error = spa_prop_get(spa, outnvl);
3496 			if (error == 0 && props != NULL)
3497 				error = spa_prop_get_nvlist(spa, props, n_props,
3498 				    outnvl);
3499 		}
3500 		spa_namespace_exit(FTAG);
3501 	} else {
3502 		error = spa_prop_get(spa, outnvl);
3503 		if (error == 0 && props != NULL)
3504 			error = spa_prop_get_nvlist(spa, props, n_props,
3505 			    outnvl);
3506 		spa_close(spa, FTAG);
3507 	}
3508 
3509 	return (error);
3510 }
3511 
3512 /*
3513  * innvl: {
3514  *     "vdevprops_set_vdev" -> guid
3515  *     "vdevprops_set_props" -> { prop -> value }
3516  * }
3517  *
3518  * outnvl: propname -> error code (int32)
3519  */
3520 static const zfs_ioc_key_t zfs_keys_vdev_set_props[] = {
3521 	{ZPOOL_VDEV_PROPS_SET_VDEV,	DATA_TYPE_UINT64,	0},
3522 	{ZPOOL_VDEV_PROPS_SET_PROPS,	DATA_TYPE_NVLIST,	0}
3523 };
3524 
3525 static int
zfs_ioc_vdev_set_props(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)3526 zfs_ioc_vdev_set_props(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3527 {
3528 	spa_t *spa;
3529 	int error;
3530 
3531 	if (outnvl == NULL)
3532 		return (SET_ERROR(EINVAL));
3533 
3534 	if ((error = spa_open(poolname, &spa, FTAG)) != 0)
3535 		return (error);
3536 
3537 	ASSERT(spa_writeable(spa));
3538 
3539 	error = vdev_prop_set(spa, innvl, outnvl);
3540 
3541 	spa_close(spa, FTAG);
3542 
3543 	return (error);
3544 }
3545 
3546 /*
3547  * innvl: {
3548  *     "vdevprops_get_vdev" -> guid
3549  *     (optional) "vdevprops_get_props" -> { propname -> propid }
3550  * }
3551  *
3552  * outnvl: propname -> value
3553  */
3554 static const zfs_ioc_key_t zfs_keys_vdev_get_props[] = {
3555 	{ZPOOL_VDEV_PROPS_GET_VDEV,	DATA_TYPE_UINT64,	0},
3556 	{ZPOOL_VDEV_PROPS_GET_PROPS,	DATA_TYPE_NVLIST,	ZK_OPTIONAL}
3557 };
3558 
3559 static int
zfs_ioc_vdev_get_props(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)3560 zfs_ioc_vdev_get_props(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3561 {
3562 	spa_t *spa;
3563 	int error;
3564 
3565 	if (outnvl == NULL)
3566 		return (SET_ERROR(EINVAL));
3567 
3568 	if ((error = spa_open(poolname, &spa, FTAG)) != 0)
3569 		return (error);
3570 
3571 	error = vdev_prop_get(spa, innvl, outnvl);
3572 
3573 	spa_close(spa, FTAG);
3574 
3575 	return (error);
3576 }
3577 
3578 /*
3579  * inputs:
3580  * zc_name		name of filesystem
3581  * zc_nvlist_src{_size}	nvlist of delegated permissions
3582  * zc_perm_action	allow/unallow flag
3583  *
3584  * outputs:		none
3585  */
3586 static int
zfs_ioc_set_fsacl(zfs_cmd_t * zc)3587 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
3588 {
3589 	int error;
3590 	nvlist_t *fsaclnv = NULL;
3591 
3592 	if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3593 	    zc->zc_iflags, &fsaclnv)) != 0)
3594 		return (error);
3595 
3596 	/*
3597 	 * Verify nvlist is constructed correctly
3598 	 */
3599 	if (zfs_deleg_verify_nvlist(fsaclnv) != 0) {
3600 		nvlist_free(fsaclnv);
3601 		return (SET_ERROR(EINVAL));
3602 	}
3603 
3604 	/*
3605 	 * If we don't have PRIV_SYS_MOUNT, then validate
3606 	 * that user is allowed to hand out each permission in
3607 	 * the nvlist(s)
3608 	 */
3609 
3610 	error = secpolicy_zfs(CRED());
3611 	if (error != 0) {
3612 		if (zc->zc_perm_action == B_FALSE) {
3613 			error = dsl_deleg_can_allow(zc->zc_name,
3614 			    fsaclnv, CRED());
3615 		} else {
3616 			error = dsl_deleg_can_unallow(zc->zc_name,
3617 			    fsaclnv, CRED());
3618 		}
3619 	}
3620 
3621 	if (error == 0)
3622 		error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
3623 
3624 	nvlist_free(fsaclnv);
3625 	return (error);
3626 }
3627 
3628 /*
3629  * inputs:
3630  * zc_name		name of filesystem
3631  *
3632  * outputs:
3633  * zc_nvlist_src{_size}	nvlist of delegated permissions
3634  */
3635 static int
zfs_ioc_get_fsacl(zfs_cmd_t * zc)3636 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
3637 {
3638 	nvlist_t *nvp;
3639 	int error;
3640 
3641 	if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
3642 		error = put_nvlist(zc, nvp);
3643 		nvlist_free(nvp);
3644 	}
3645 
3646 	return (error);
3647 }
3648 
3649 static void
zfs_create_cb(objset_t * os,void * arg,cred_t * cr,dmu_tx_t * tx)3650 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3651 {
3652 	zfs_creat_t *zct = arg;
3653 
3654 	zfs_create_fs(os, cr, zct->zct_zplprops, tx);
3655 }
3656 
3657 #define	ZFS_PROP_UNDEFINED	((uint64_t)-1)
3658 
3659 /*
3660  * inputs:
3661  * os			parent objset pointer (NULL if root fs)
3662  * fuids_ok		fuids allowed in this version of the spa?
3663  * sa_ok		SAs allowed in this version of the spa?
3664  * createprops		list of properties requested by creator
3665  *
3666  * outputs:
3667  * zplprops	values for the zplprops we attach to the master node object
3668  * is_ci	true if requested file system will be purely case-insensitive
3669  *
3670  * Determine the settings for utf8only, normalization and
3671  * casesensitivity.  Specific values may have been requested by the
3672  * creator and/or we can inherit values from the parent dataset.  If
3673  * the file system is of too early a vintage, a creator can not
3674  * request settings for these properties, even if the requested
3675  * setting is the default value.  We don't actually want to create dsl
3676  * properties for these, so remove them from the source nvlist after
3677  * processing.
3678  */
3679 static int
zfs_fill_zplprops_impl(objset_t * os,uint64_t zplver,boolean_t fuids_ok,boolean_t sa_ok,nvlist_t * createprops,nvlist_t * zplprops,boolean_t * is_ci)3680 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
3681     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
3682     nvlist_t *zplprops, boolean_t *is_ci)
3683 {
3684 	uint64_t sense = ZFS_PROP_UNDEFINED;
3685 	uint64_t norm = ZFS_PROP_UNDEFINED;
3686 	uint64_t u8 = ZFS_PROP_UNDEFINED;
3687 	uint64_t duq = ZFS_PROP_UNDEFINED, duoq = ZFS_PROP_UNDEFINED;
3688 	uint64_t dgq = ZFS_PROP_UNDEFINED, dgoq = ZFS_PROP_UNDEFINED;
3689 	uint64_t dpq = ZFS_PROP_UNDEFINED, dpoq = ZFS_PROP_UNDEFINED;
3690 	int error;
3691 
3692 	ASSERT(zplprops != NULL);
3693 
3694 	/* parent dataset must be a filesystem */
3695 	if (os != NULL && os->os_phys->os_type != DMU_OST_ZFS)
3696 		return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
3697 
3698 	/*
3699 	 * Pull out creator prop choices, if any.
3700 	 */
3701 	if (createprops) {
3702 		(void) nvlist_lookup_uint64(createprops,
3703 		    zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
3704 		(void) nvlist_lookup_uint64(createprops,
3705 		    zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
3706 		(void) nvlist_remove_all(createprops,
3707 		    zfs_prop_to_name(ZFS_PROP_NORMALIZE));
3708 		(void) nvlist_lookup_uint64(createprops,
3709 		    zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
3710 		(void) nvlist_remove_all(createprops,
3711 		    zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
3712 		(void) nvlist_lookup_uint64(createprops,
3713 		    zfs_prop_to_name(ZFS_PROP_CASE), &sense);
3714 		(void) nvlist_remove_all(createprops,
3715 		    zfs_prop_to_name(ZFS_PROP_CASE));
3716 		(void) nvlist_lookup_uint64(createprops,
3717 		    zfs_prop_to_name(ZFS_PROP_DEFAULTUSERQUOTA), &duq);
3718 		(void) nvlist_remove_all(createprops,
3719 		    zfs_prop_to_name(ZFS_PROP_DEFAULTUSERQUOTA));
3720 		(void) nvlist_lookup_uint64(createprops,
3721 		    zfs_prop_to_name(ZFS_PROP_DEFAULTGROUPQUOTA), &dgq);
3722 		(void) nvlist_remove_all(createprops,
3723 		    zfs_prop_to_name(ZFS_PROP_DEFAULTGROUPQUOTA));
3724 		(void) nvlist_lookup_uint64(createprops,
3725 		    zfs_prop_to_name(ZFS_PROP_DEFAULTPROJECTQUOTA), &dpq);
3726 		(void) nvlist_remove_all(createprops,
3727 		    zfs_prop_to_name(ZFS_PROP_DEFAULTPROJECTQUOTA));
3728 		(void) nvlist_lookup_uint64(createprops,
3729 		    zfs_prop_to_name(ZFS_PROP_DEFAULTUSEROBJQUOTA), &duoq);
3730 		(void) nvlist_remove_all(createprops,
3731 		    zfs_prop_to_name(ZFS_PROP_DEFAULTUSEROBJQUOTA));
3732 		(void) nvlist_lookup_uint64(createprops,
3733 		    zfs_prop_to_name(ZFS_PROP_DEFAULTGROUPOBJQUOTA), &dgoq);
3734 		(void) nvlist_remove_all(createprops,
3735 		    zfs_prop_to_name(ZFS_PROP_DEFAULTGROUPOBJQUOTA));
3736 		(void) nvlist_lookup_uint64(createprops,
3737 		    zfs_prop_to_name(ZFS_PROP_DEFAULTPROJECTOBJQUOTA), &dpoq);
3738 		(void) nvlist_remove_all(createprops,
3739 		    zfs_prop_to_name(ZFS_PROP_DEFAULTPROJECTOBJQUOTA));
3740 	}
3741 
3742 	/*
3743 	 * If the zpl version requested is whacky or the file system
3744 	 * or pool is version is too "young" to support normalization
3745 	 * and the creator tried to set a value for one of the props,
3746 	 * error out.
3747 	 */
3748 	if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
3749 	    (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
3750 	    (zplver >= ZPL_VERSION_SA && !sa_ok) ||
3751 	    (zplver < ZPL_VERSION_NORMALIZATION &&
3752 	    (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
3753 	    sense != ZFS_PROP_UNDEFINED)))
3754 		return (SET_ERROR(ENOTSUP));
3755 
3756 	/*
3757 	 * Put the version in the zplprops
3758 	 */
3759 	VERIFY0(nvlist_add_uint64(zplprops,
3760 	    zfs_prop_to_name(ZFS_PROP_VERSION), zplver));
3761 
3762 	if (norm == ZFS_PROP_UNDEFINED &&
3763 	    (error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm)) != 0)
3764 		return (error);
3765 	VERIFY0(nvlist_add_uint64(zplprops,
3766 	    zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm));
3767 
3768 	/*
3769 	 * If we're normalizing, names must always be valid UTF-8 strings.
3770 	 */
3771 	if (norm)
3772 		u8 = 1;
3773 	if (u8 == ZFS_PROP_UNDEFINED &&
3774 	    (error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8)) != 0)
3775 		return (error);
3776 	VERIFY0(nvlist_add_uint64(zplprops,
3777 	    zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8));
3778 
3779 	if (sense == ZFS_PROP_UNDEFINED &&
3780 	    (error = zfs_get_zplprop(os, ZFS_PROP_CASE, &sense)) != 0)
3781 		return (error);
3782 	VERIFY0(nvlist_add_uint64(zplprops,
3783 	    zfs_prop_to_name(ZFS_PROP_CASE), sense));
3784 
3785 	if (duq == ZFS_PROP_UNDEFINED &&
3786 	    (error = zfs_get_zplprop(os, ZFS_PROP_DEFAULTUSERQUOTA, &duq)) != 0)
3787 		return (error);
3788 	VERIFY0(nvlist_add_uint64(zplprops,
3789 	    zfs_prop_to_name(ZFS_PROP_DEFAULTUSERQUOTA), duq));
3790 
3791 	if (dgq == ZFS_PROP_UNDEFINED &&
3792 	    (error = zfs_get_zplprop(os, ZFS_PROP_DEFAULTGROUPQUOTA,
3793 	    &dgq)) != 0)
3794 		return (error);
3795 	VERIFY0(nvlist_add_uint64(zplprops,
3796 	    zfs_prop_to_name(ZFS_PROP_DEFAULTGROUPQUOTA), dgq));
3797 
3798 	if (dpq == ZFS_PROP_UNDEFINED &&
3799 	    (error = zfs_get_zplprop(os, ZFS_PROP_DEFAULTPROJECTQUOTA,
3800 	    &dpq)) != 0)
3801 		return (error);
3802 	VERIFY0(nvlist_add_uint64(zplprops,
3803 	    zfs_prop_to_name(ZFS_PROP_DEFAULTPROJECTQUOTA), dpq));
3804 
3805 	if (duoq == ZFS_PROP_UNDEFINED &&
3806 	    (error = zfs_get_zplprop(os, ZFS_PROP_DEFAULTUSEROBJQUOTA,
3807 	    &duoq)) != 0)
3808 		return (error);
3809 	VERIFY0(nvlist_add_uint64(zplprops,
3810 	    zfs_prop_to_name(ZFS_PROP_DEFAULTUSEROBJQUOTA), duoq));
3811 
3812 	if (dgoq == ZFS_PROP_UNDEFINED &&
3813 	    (error = zfs_get_zplprop(os, ZFS_PROP_DEFAULTGROUPOBJQUOTA,
3814 	    &dgoq)) != 0)
3815 		return (error);
3816 	VERIFY0(nvlist_add_uint64(zplprops,
3817 	    zfs_prop_to_name(ZFS_PROP_DEFAULTGROUPOBJQUOTA), dgoq));
3818 
3819 	if (dpoq == ZFS_PROP_UNDEFINED &&
3820 	    (error = zfs_get_zplprop(os, ZFS_PROP_DEFAULTPROJECTOBJQUOTA,
3821 	    &dpoq)) != 0)
3822 		return (error);
3823 	VERIFY0(nvlist_add_uint64(zplprops,
3824 	    zfs_prop_to_name(ZFS_PROP_DEFAULTPROJECTOBJQUOTA), dpoq));
3825 
3826 	if (is_ci)
3827 		*is_ci = (sense == ZFS_CASE_INSENSITIVE);
3828 
3829 	return (0);
3830 }
3831 
3832 static int
zfs_fill_zplprops(const char * dataset,nvlist_t * createprops,nvlist_t * zplprops,boolean_t * is_ci)3833 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
3834     nvlist_t *zplprops, boolean_t *is_ci)
3835 {
3836 	boolean_t fuids_ok, sa_ok;
3837 	uint64_t zplver = ZPL_VERSION;
3838 	objset_t *os = NULL;
3839 	char parentname[ZFS_MAX_DATASET_NAME_LEN];
3840 	spa_t *spa;
3841 	uint64_t spa_vers;
3842 	int error;
3843 
3844 	zfs_get_parent(dataset, parentname, sizeof (parentname));
3845 
3846 	if ((error = spa_open(dataset, &spa, FTAG)) != 0)
3847 		return (error);
3848 
3849 	spa_vers = spa_version(spa);
3850 	spa_close(spa, FTAG);
3851 
3852 	zplver = zfs_zpl_version_map(spa_vers);
3853 	fuids_ok = (zplver >= ZPL_VERSION_FUID);
3854 	sa_ok = (zplver >= ZPL_VERSION_SA);
3855 
3856 	/*
3857 	 * Open parent object set so we can inherit zplprop values.
3858 	 */
3859 	if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
3860 		return (error);
3861 
3862 	error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
3863 	    zplprops, is_ci);
3864 	dmu_objset_rele(os, FTAG);
3865 	return (error);
3866 }
3867 
3868 static int
zfs_fill_zplprops_root(uint64_t spa_vers,nvlist_t * createprops,nvlist_t * zplprops,boolean_t * is_ci)3869 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
3870     nvlist_t *zplprops, boolean_t *is_ci)
3871 {
3872 	boolean_t fuids_ok;
3873 	boolean_t sa_ok;
3874 	uint64_t zplver = ZPL_VERSION;
3875 	int error;
3876 
3877 	zplver = zfs_zpl_version_map(spa_vers);
3878 	fuids_ok = (zplver >= ZPL_VERSION_FUID);
3879 	sa_ok = (zplver >= ZPL_VERSION_SA);
3880 
3881 	error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
3882 	    createprops, zplprops, is_ci);
3883 	return (error);
3884 }
3885 
3886 /*
3887  * innvl: {
3888  *     "type" -> dmu_objset_type_t (int32)
3889  *     (optional) "props" -> { prop -> value }
3890  *     (optional) "hidden_args" -> { "wkeydata" -> value }
3891  *         raw uint8_t array of encryption wrapping key data (32 bytes)
3892  * }
3893  *
3894  * outnvl: propname -> error code (int32)
3895  */
3896 
3897 static const zfs_ioc_key_t zfs_keys_create[] = {
3898 	{"type",	DATA_TYPE_INT32,	0},
3899 	{"props",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
3900 	{"hidden_args",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
3901 };
3902 
3903 static int
zfs_ioc_create(const char * fsname,nvlist_t * innvl,nvlist_t * outnvl)3904 zfs_ioc_create(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3905 {
3906 	int error = 0;
3907 	zfs_creat_t zct = { 0 };
3908 	nvlist_t *nvprops = NULL;
3909 	nvlist_t *hidden_args = NULL;
3910 	void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
3911 	dmu_objset_type_t type;
3912 	boolean_t is_insensitive = B_FALSE;
3913 	dsl_crypto_params_t *dcp = NULL;
3914 
3915 	type = (dmu_objset_type_t)fnvlist_lookup_int32(innvl, "type");
3916 	(void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3917 	(void) nvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS, &hidden_args);
3918 
3919 	switch (type) {
3920 	case DMU_OST_ZFS:
3921 		cbfunc = zfs_create_cb;
3922 		break;
3923 
3924 	case DMU_OST_ZVOL:
3925 		cbfunc = zvol_create_cb;
3926 		break;
3927 
3928 	default:
3929 		cbfunc = NULL;
3930 		break;
3931 	}
3932 	if (strchr(fsname, '@') ||
3933 	    strchr(fsname, '%'))
3934 		return (SET_ERROR(EINVAL));
3935 
3936 	zct.zct_props = nvprops;
3937 
3938 	if (cbfunc == NULL)
3939 		return (SET_ERROR(EINVAL));
3940 
3941 	if (type == DMU_OST_ZVOL) {
3942 		uint64_t volsize, volblocksize;
3943 
3944 		if (nvprops == NULL)
3945 			return (SET_ERROR(EINVAL));
3946 		if (nvlist_lookup_uint64(nvprops,
3947 		    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) != 0)
3948 			return (SET_ERROR(EINVAL));
3949 
3950 		if ((error = nvlist_lookup_uint64(nvprops,
3951 		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3952 		    &volblocksize)) != 0 && error != ENOENT)
3953 			return (SET_ERROR(EINVAL));
3954 
3955 		if (error != 0)
3956 			volblocksize = zfs_prop_default_numeric(
3957 			    ZFS_PROP_VOLBLOCKSIZE);
3958 
3959 		if ((error = zvol_check_volblocksize(fsname,
3960 		    volblocksize)) != 0 ||
3961 		    (error = zvol_check_volsize(volsize,
3962 		    volblocksize)) != 0)
3963 			return (error);
3964 	} else if (type == DMU_OST_ZFS) {
3965 		int error;
3966 
3967 		/*
3968 		 * We have to have normalization and
3969 		 * case-folding flags correct when we do the
3970 		 * file system creation, so go figure them out
3971 		 * now.
3972 		 */
3973 		VERIFY0(nvlist_alloc(&zct.zct_zplprops,
3974 		    NV_UNIQUE_NAME, KM_SLEEP));
3975 		error = zfs_fill_zplprops(fsname, nvprops,
3976 		    zct.zct_zplprops, &is_insensitive);
3977 		if (error != 0) {
3978 			nvlist_free(zct.zct_zplprops);
3979 			return (error);
3980 		}
3981 	}
3982 
3983 	error = dsl_crypto_params_create_nvlist(DCP_CMD_NONE, nvprops,
3984 	    hidden_args, &dcp);
3985 	if (error != 0) {
3986 		nvlist_free(zct.zct_zplprops);
3987 		return (error);
3988 	}
3989 
3990 	error = dmu_objset_create(fsname, type,
3991 	    is_insensitive ? DS_FLAG_CI_DATASET : 0, dcp, cbfunc, &zct);
3992 
3993 	nvlist_free(zct.zct_zplprops);
3994 	dsl_crypto_params_free(dcp, !!error);
3995 
3996 	/*
3997 	 * It would be nice to do this atomically.
3998 	 */
3999 	if (error == 0) {
4000 		error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
4001 		    nvprops, outnvl);
4002 		if (error != 0) {
4003 			spa_t *spa;
4004 			int error2;
4005 
4006 			/*
4007 			 * Volumes will return EBUSY and cannot be destroyed
4008 			 * until all asynchronous minor handling (e.g. from
4009 			 * setting the volmode property) has completed. Wait for
4010 			 * the spa_zvol_taskq to drain then retry.
4011 			 */
4012 			error2 = dsl_destroy_head(fsname);
4013 			while ((error2 == EBUSY) && (type == DMU_OST_ZVOL)) {
4014 				error2 = spa_open(fsname, &spa, FTAG);
4015 				if (error2 == 0) {
4016 					taskq_wait(spa->spa_zvol_taskq);
4017 					spa_close(spa, FTAG);
4018 				}
4019 				error2 = dsl_destroy_head(fsname);
4020 			}
4021 		}
4022 	}
4023 	return (error);
4024 }
4025 
4026 /*
4027  * innvl: {
4028  *     "origin" -> name of origin snapshot
4029  *     (optional) "props" -> { prop -> value }
4030  *     (optional) "hidden_args" -> { "wkeydata" -> value }
4031  *         raw uint8_t array of encryption wrapping key data (32 bytes)
4032  * }
4033  *
4034  * outputs:
4035  * outnvl: propname -> error code (int32)
4036  */
4037 static const zfs_ioc_key_t zfs_keys_clone[] = {
4038 	{"origin",	DATA_TYPE_STRING,	0},
4039 	{"props",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
4040 	{"hidden_args",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
4041 };
4042 
4043 static int
zfs_ioc_clone(const char * fsname,nvlist_t * innvl,nvlist_t * outnvl)4044 zfs_ioc_clone(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
4045 {
4046 	int error = 0;
4047 	nvlist_t *nvprops = NULL;
4048 	const char *origin_name;
4049 
4050 	origin_name = fnvlist_lookup_string(innvl, "origin");
4051 	(void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
4052 
4053 	if (strchr(fsname, '@') ||
4054 	    strchr(fsname, '%'))
4055 		return (SET_ERROR(EINVAL));
4056 
4057 	if (dataset_namecheck(origin_name, NULL, NULL) != 0)
4058 		return (SET_ERROR(EINVAL));
4059 
4060 	error = dsl_dataset_clone(fsname, origin_name);
4061 
4062 	/*
4063 	 * It would be nice to do this atomically.
4064 	 */
4065 	if (error == 0) {
4066 		error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
4067 		    nvprops, outnvl);
4068 		if (error != 0)
4069 			(void) dsl_destroy_head(fsname);
4070 	}
4071 	return (error);
4072 }
4073 
4074 static const zfs_ioc_key_t zfs_keys_remap[] = {
4075 	/* no nvl keys */
4076 };
4077 
4078 static int
zfs_ioc_remap(const char * fsname,nvlist_t * innvl,nvlist_t * outnvl)4079 zfs_ioc_remap(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
4080 {
4081 	/* This IOCTL is no longer supported. */
4082 	(void) fsname, (void) innvl, (void) outnvl;
4083 	return (0);
4084 }
4085 
4086 /*
4087  * innvl: {
4088  *     "snaps" -> { snapshot1, snapshot2 }
4089  *     (optional) "props" -> { prop -> value (string) }
4090  * }
4091  *
4092  * outnvl: snapshot -> error code (int32)
4093  */
4094 static const zfs_ioc_key_t zfs_keys_snapshot[] = {
4095 	{"snaps",	DATA_TYPE_NVLIST,	0},
4096 	{"props",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
4097 };
4098 
4099 static int
zfs_ioc_snapshot(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4100 zfs_ioc_snapshot(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4101 {
4102 	nvlist_t *snaps;
4103 	nvlist_t *props = NULL;
4104 	int error, poollen;
4105 	nvpair_t *pair;
4106 
4107 	(void) nvlist_lookup_nvlist(innvl, "props", &props);
4108 	if (!nvlist_empty(props) &&
4109 	    zfs_earlier_version(poolname, SPA_VERSION_SNAP_PROPS))
4110 		return (SET_ERROR(ENOTSUP));
4111 	if ((error = zfs_check_userprops(props)) != 0)
4112 		return (error);
4113 
4114 	snaps = fnvlist_lookup_nvlist(innvl, "snaps");
4115 	poollen = strlen(poolname);
4116 	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
4117 	    pair = nvlist_next_nvpair(snaps, pair)) {
4118 		const char *name = nvpair_name(pair);
4119 		char *cp = strchr(name, '@');
4120 
4121 		/*
4122 		 * The snap name must contain an @, and the part after it must
4123 		 * contain only valid characters.
4124 		 */
4125 		if (cp == NULL ||
4126 		    zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
4127 			return (SET_ERROR(EINVAL));
4128 
4129 		/*
4130 		 * The snap must be in the specified pool.
4131 		 */
4132 		if (strncmp(name, poolname, poollen) != 0 ||
4133 		    (name[poollen] != '/' && name[poollen] != '@'))
4134 			return (SET_ERROR(EXDEV));
4135 
4136 		/*
4137 		 * Check for permission to set the properties on the fs.
4138 		 */
4139 		if (!nvlist_empty(props)) {
4140 			*cp = '\0';
4141 			zone_admin_result_t zone_result;
4142 			zone_result = zone_dataset_admin_check(name,
4143 			    ZONE_OP_SETPROP, NULL);
4144 			if (zone_result == ZONE_ADMIN_DENIED) {
4145 				*cp = '@';
4146 				return (SET_ERROR(EPERM));
4147 			}
4148 			if (zone_result == ZONE_ADMIN_ALLOWED) {
4149 				error = zfs_secpolicy_zoned_uid_deleg(name,
4150 				    ZFS_DELEG_PERM_USERPROP, CRED());
4151 			} else {
4152 				error = zfs_secpolicy_write_perms(name,
4153 				    ZFS_DELEG_PERM_USERPROP, CRED());
4154 			}
4155 			*cp = '@';
4156 			if (error != 0)
4157 				return (error);
4158 		}
4159 
4160 		/* This must be the only snap of this fs. */
4161 		for (nvpair_t *pair2 = nvlist_next_nvpair(snaps, pair);
4162 		    pair2 != NULL; pair2 = nvlist_next_nvpair(snaps, pair2)) {
4163 			if (strncmp(name, nvpair_name(pair2), cp - name + 1)
4164 			    == 0) {
4165 				return (SET_ERROR(EXDEV));
4166 			}
4167 		}
4168 	}
4169 
4170 	error = dsl_dataset_snapshot(snaps, props, outnvl);
4171 
4172 	return (error);
4173 }
4174 
4175 /*
4176  * innvl: "message" -> string
4177  */
4178 static const zfs_ioc_key_t zfs_keys_log_history[] = {
4179 	{"message",	DATA_TYPE_STRING,	0},
4180 };
4181 
4182 static int
zfs_ioc_log_history(const char * unused,nvlist_t * innvl,nvlist_t * outnvl)4183 zfs_ioc_log_history(const char *unused, nvlist_t *innvl, nvlist_t *outnvl)
4184 {
4185 	(void) unused, (void) outnvl;
4186 	char *poolname;
4187 	spa_t *spa;
4188 	int error;
4189 
4190 	/*
4191 	 * The poolname in the ioctl is not set, we get it from the TSD,
4192 	 * which was set at the end of the last successful ioctl that allows
4193 	 * logging.  The secpolicy func already checked that it is set.
4194 	 * Only one log ioctl is allowed after each successful ioctl, so
4195 	 * we clear the TSD here.
4196 	 */
4197 	poolname = tsd_get(zfs_allow_log_key);
4198 	if (poolname == NULL)
4199 		return (SET_ERROR(EINVAL));
4200 	(void) tsd_set(zfs_allow_log_key, NULL);
4201 	error = spa_open(poolname, &spa, FTAG);
4202 	kmem_strfree(poolname);
4203 	if (error != 0)
4204 		return (error);
4205 
4206 	const char *message = fnvlist_lookup_string(innvl, "message");
4207 
4208 	if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
4209 		spa_close(spa, FTAG);
4210 		return (SET_ERROR(ENOTSUP));
4211 	}
4212 
4213 	error = spa_history_log(spa, message);
4214 	spa_close(spa, FTAG);
4215 	return (error);
4216 }
4217 
4218 /*
4219  * This ioctl is used to set the bootenv configuration on the current
4220  * pool. This configuration is stored in the second padding area of the label,
4221  * and it is used by the bootloader(s) to store the bootloader and/or system
4222  * specific data.
4223  * The data is stored as nvlist data stream, and is protected by
4224  * an embedded checksum.
4225  * The version can have two possible values:
4226  * VB_RAW: nvlist should have key GRUB_ENVMAP, value DATA_TYPE_STRING.
4227  * VB_NVLIST: nvlist with arbitrary <key, value> pairs.
4228  */
4229 static const zfs_ioc_key_t zfs_keys_set_bootenv[] = {
4230 	{"version",	DATA_TYPE_UINT64,	0},
4231 	{"<keys>",	DATA_TYPE_ANY, ZK_OPTIONAL | ZK_WILDCARDLIST},
4232 };
4233 
4234 static int
zfs_ioc_set_bootenv(const char * name,nvlist_t * innvl,nvlist_t * outnvl)4235 zfs_ioc_set_bootenv(const char *name, nvlist_t *innvl, nvlist_t *outnvl)
4236 {
4237 	int error;
4238 	spa_t *spa;
4239 
4240 	if ((error = spa_open(name, &spa, FTAG)) != 0)
4241 		return (error);
4242 	spa_vdev_state_enter(spa, SCL_ALL);
4243 	error = vdev_label_write_bootenv(spa->spa_root_vdev, innvl);
4244 	(void) spa_vdev_state_exit(spa, NULL, 0);
4245 	spa_close(spa, FTAG);
4246 	return (error);
4247 }
4248 
4249 static const zfs_ioc_key_t zfs_keys_get_bootenv[] = {
4250 	/* no nvl keys */
4251 };
4252 
4253 static int
zfs_ioc_get_bootenv(const char * name,nvlist_t * innvl,nvlist_t * outnvl)4254 zfs_ioc_get_bootenv(const char *name, nvlist_t *innvl, nvlist_t *outnvl)
4255 {
4256 	spa_t *spa;
4257 	int error;
4258 
4259 	if ((error = spa_open(name, &spa, FTAG)) != 0)
4260 		return (error);
4261 	spa_vdev_state_enter(spa, SCL_ALL);
4262 	error = vdev_label_read_bootenv(spa->spa_root_vdev, outnvl);
4263 	(void) spa_vdev_state_exit(spa, NULL, 0);
4264 	spa_close(spa, FTAG);
4265 	return (error);
4266 }
4267 
4268 /*
4269  * The dp_config_rwlock must not be held when calling this, because the
4270  * unmount may need to write out data.
4271  *
4272  * This function is best-effort.  Callers must deal gracefully if it
4273  * remains mounted (or is remounted after this call).
4274  *
4275  * Returns 0 if the argument is not a snapshot, or it is not currently a
4276  * filesystem, or we were able to unmount it.  Returns error code otherwise.
4277  */
4278 void
zfs_unmount_snap(const char * snapname)4279 zfs_unmount_snap(const char *snapname)
4280 {
4281 	if (strchr(snapname, '@') == NULL)
4282 		return;
4283 
4284 	(void) zfsctl_snapshot_unmount(snapname, MNT_FORCE);
4285 }
4286 
4287 static int
zfs_unmount_snap_cb(const char * snapname,void * arg)4288 zfs_unmount_snap_cb(const char *snapname, void *arg)
4289 {
4290 	(void) arg;
4291 	zfs_unmount_snap(snapname);
4292 	return (0);
4293 }
4294 
4295 /*
4296  * When a clone is destroyed, its origin may also need to be destroyed,
4297  * in which case it must be unmounted.  This routine will do that unmount
4298  * if necessary.
4299  */
4300 void
zfs_destroy_unmount_origin(const char * fsname)4301 zfs_destroy_unmount_origin(const char *fsname)
4302 {
4303 	int error;
4304 	objset_t *os;
4305 	dsl_dataset_t *ds;
4306 
4307 	error = dmu_objset_hold(fsname, FTAG, &os);
4308 	if (error != 0)
4309 		return;
4310 	ds = dmu_objset_ds(os);
4311 	if (dsl_dir_is_clone(ds->ds_dir) && DS_IS_DEFER_DESTROY(ds->ds_prev)) {
4312 		char originname[ZFS_MAX_DATASET_NAME_LEN];
4313 		dsl_dataset_name(ds->ds_prev, originname);
4314 		dmu_objset_rele(os, FTAG);
4315 		zfs_unmount_snap(originname);
4316 	} else {
4317 		dmu_objset_rele(os, FTAG);
4318 	}
4319 }
4320 
4321 /*
4322  * innvl: {
4323  *     "snaps" -> { snapshot1, snapshot2 }
4324  *     (optional boolean) "defer"
4325  * }
4326  *
4327  * outnvl: snapshot -> error code (int32)
4328  */
4329 static const zfs_ioc_key_t zfs_keys_destroy_snaps[] = {
4330 	{"snaps",	DATA_TYPE_NVLIST,	0},
4331 	{"defer",	DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
4332 };
4333 
4334 static int
zfs_ioc_destroy_snaps(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4335 zfs_ioc_destroy_snaps(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4336 {
4337 	int poollen;
4338 	nvlist_t *snaps;
4339 	nvpair_t *pair;
4340 	boolean_t defer;
4341 	spa_t *spa;
4342 
4343 	snaps = fnvlist_lookup_nvlist(innvl, "snaps");
4344 	defer = nvlist_exists(innvl, "defer");
4345 
4346 	poollen = strlen(poolname);
4347 	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
4348 	    pair = nvlist_next_nvpair(snaps, pair)) {
4349 		const char *name = nvpair_name(pair);
4350 
4351 		/*
4352 		 * The snap must be in the specified pool to prevent the
4353 		 * invalid removal of zvol minors below.
4354 		 */
4355 		if (strncmp(name, poolname, poollen) != 0 ||
4356 		    (name[poollen] != '/' && name[poollen] != '@'))
4357 			return (SET_ERROR(EXDEV));
4358 
4359 		zfs_unmount_snap(nvpair_name(pair));
4360 		if (spa_open(name, &spa, FTAG) == 0) {
4361 			zvol_remove_minors(spa, name, B_TRUE);
4362 			spa_close(spa, FTAG);
4363 		}
4364 	}
4365 
4366 	return (dsl_destroy_snapshots_nvl(snaps, defer, outnvl));
4367 }
4368 
4369 /*
4370  * Create bookmarks. The bookmark names are of the form <fs>#<bmark>.
4371  * All bookmarks and snapshots must be in the same pool.
4372  * dsl_bookmark_create_nvl_validate describes the nvlist schema in more detail.
4373  *
4374  * innvl: {
4375  *     new_bookmark1 -> existing_snapshot,
4376  *     new_bookmark2 -> existing_bookmark,
4377  * }
4378  *
4379  * outnvl: bookmark -> error code (int32)
4380  *
4381  */
4382 static const zfs_ioc_key_t zfs_keys_bookmark[] = {
4383 	{"<bookmark>...",	DATA_TYPE_STRING,	ZK_WILDCARDLIST},
4384 };
4385 
4386 static int
zfs_ioc_bookmark(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4387 zfs_ioc_bookmark(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4388 {
4389 	(void) poolname;
4390 	return (dsl_bookmark_create(innvl, outnvl));
4391 }
4392 
4393 /*
4394  * innvl: {
4395  *     property 1, property 2, ...
4396  * }
4397  *
4398  * outnvl: {
4399  *     bookmark name 1 -> { property 1, property 2, ... },
4400  *     bookmark name 2 -> { property 1, property 2, ... }
4401  * }
4402  *
4403  */
4404 static const zfs_ioc_key_t zfs_keys_get_bookmarks[] = {
4405 	{"<property>...", DATA_TYPE_BOOLEAN, ZK_WILDCARDLIST | ZK_OPTIONAL},
4406 };
4407 
4408 static int
zfs_ioc_get_bookmarks(const char * fsname,nvlist_t * innvl,nvlist_t * outnvl)4409 zfs_ioc_get_bookmarks(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
4410 {
4411 	return (dsl_get_bookmarks(fsname, innvl, outnvl));
4412 }
4413 
4414 /*
4415  * innvl is not used.
4416  *
4417  * outnvl: {
4418  *     property 1, property 2, ...
4419  * }
4420  *
4421  */
4422 static const zfs_ioc_key_t zfs_keys_get_bookmark_props[] = {
4423 	/* no nvl keys */
4424 };
4425 
4426 static int
zfs_ioc_get_bookmark_props(const char * bookmark,nvlist_t * innvl,nvlist_t * outnvl)4427 zfs_ioc_get_bookmark_props(const char *bookmark, nvlist_t *innvl,
4428     nvlist_t *outnvl)
4429 {
4430 	(void) innvl;
4431 	char fsname[ZFS_MAX_DATASET_NAME_LEN];
4432 	char *bmname;
4433 
4434 	bmname = strchr(bookmark, '#');
4435 	if (bmname == NULL)
4436 		return (SET_ERROR(EINVAL));
4437 	bmname++;
4438 
4439 	(void) strlcpy(fsname, bookmark, sizeof (fsname));
4440 	*(strchr(fsname, '#')) = '\0';
4441 
4442 	return (dsl_get_bookmark_props(fsname, bmname, outnvl));
4443 }
4444 
4445 /*
4446  * innvl: {
4447  *     bookmark name 1, bookmark name 2
4448  * }
4449  *
4450  * outnvl: bookmark -> error code (int32)
4451  *
4452  */
4453 static const zfs_ioc_key_t zfs_keys_destroy_bookmarks[] = {
4454 	{"<bookmark>...",	DATA_TYPE_BOOLEAN,	ZK_WILDCARDLIST},
4455 };
4456 
4457 static int
zfs_ioc_destroy_bookmarks(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4458 zfs_ioc_destroy_bookmarks(const char *poolname, nvlist_t *innvl,
4459     nvlist_t *outnvl)
4460 {
4461 	int error, poollen;
4462 
4463 	poollen = strlen(poolname);
4464 	for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
4465 	    pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
4466 		const char *name = nvpair_name(pair);
4467 		const char *cp = strchr(name, '#');
4468 
4469 		/*
4470 		 * The bookmark name must contain an #, and the part after it
4471 		 * must contain only valid characters.
4472 		 */
4473 		if (cp == NULL ||
4474 		    zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
4475 			return (SET_ERROR(EINVAL));
4476 
4477 		/*
4478 		 * The bookmark must be in the specified pool.
4479 		 */
4480 		if (strncmp(name, poolname, poollen) != 0 ||
4481 		    (name[poollen] != '/' && name[poollen] != '#'))
4482 			return (SET_ERROR(EXDEV));
4483 	}
4484 
4485 	error = dsl_bookmark_destroy(innvl, outnvl);
4486 	return (error);
4487 }
4488 
4489 static const zfs_ioc_key_t zfs_keys_channel_program[] = {
4490 	{"program",	DATA_TYPE_STRING,		0},
4491 	{"arg",		DATA_TYPE_ANY,			0},
4492 	{"sync",	DATA_TYPE_BOOLEAN_VALUE,	ZK_OPTIONAL},
4493 	{"instrlimit",	DATA_TYPE_UINT64,		ZK_OPTIONAL},
4494 	{"memlimit",	DATA_TYPE_UINT64,		ZK_OPTIONAL},
4495 };
4496 
4497 static int
zfs_ioc_channel_program(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4498 zfs_ioc_channel_program(const char *poolname, nvlist_t *innvl,
4499     nvlist_t *outnvl)
4500 {
4501 	const char *program;
4502 	uint64_t instrlimit, memlimit;
4503 	boolean_t sync_flag;
4504 	nvpair_t *nvarg = NULL;
4505 
4506 	program = fnvlist_lookup_string(innvl, ZCP_ARG_PROGRAM);
4507 	if (0 != nvlist_lookup_boolean_value(innvl, ZCP_ARG_SYNC, &sync_flag)) {
4508 		sync_flag = B_TRUE;
4509 	}
4510 	if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_INSTRLIMIT, &instrlimit)) {
4511 		instrlimit = ZCP_DEFAULT_INSTRLIMIT;
4512 	}
4513 	if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_MEMLIMIT, &memlimit)) {
4514 		memlimit = ZCP_DEFAULT_MEMLIMIT;
4515 	}
4516 	nvarg = fnvlist_lookup_nvpair(innvl, ZCP_ARG_ARGLIST);
4517 
4518 	if (instrlimit == 0 || instrlimit > zfs_lua_max_instrlimit)
4519 		return (SET_ERROR(EINVAL));
4520 	if (memlimit == 0 || memlimit > zfs_lua_max_memlimit)
4521 		return (SET_ERROR(EINVAL));
4522 
4523 	return (zcp_eval(poolname, program, sync_flag, instrlimit, memlimit,
4524 	    nvarg, outnvl));
4525 }
4526 
4527 /*
4528  * innvl: unused
4529  * outnvl: empty
4530  */
4531 static const zfs_ioc_key_t zfs_keys_pool_checkpoint[] = {
4532 	/* no nvl keys */
4533 };
4534 
4535 static int
zfs_ioc_pool_checkpoint(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4536 zfs_ioc_pool_checkpoint(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4537 {
4538 	(void) innvl, (void) outnvl;
4539 	return (spa_checkpoint(poolname));
4540 }
4541 
4542 /*
4543  * innvl: unused
4544  * outnvl: empty
4545  */
4546 static const zfs_ioc_key_t zfs_keys_pool_discard_checkpoint[] = {
4547 	/* no nvl keys */
4548 };
4549 
4550 static int
zfs_ioc_pool_discard_checkpoint(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4551 zfs_ioc_pool_discard_checkpoint(const char *poolname, nvlist_t *innvl,
4552     nvlist_t *outnvl)
4553 {
4554 	(void) innvl, (void) outnvl;
4555 	return (spa_checkpoint_discard(poolname));
4556 }
4557 
4558 /*
4559  * Loads specific types of data for the given pool
4560  *
4561  * innvl: {
4562  *     "prefetch_type" -> int32_t
4563  * }
4564  *
4565  * outnvl: empty
4566  */
4567 static const zfs_ioc_key_t zfs_keys_pool_prefetch[] = {
4568 	{ZPOOL_PREFETCH_TYPE,	DATA_TYPE_INT32,	0},
4569 };
4570 
4571 static int
zfs_ioc_pool_prefetch(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4572 zfs_ioc_pool_prefetch(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4573 {
4574 	(void) outnvl;
4575 
4576 	int error;
4577 	spa_t *spa;
4578 	int32_t type;
4579 
4580 	if (nvlist_lookup_int32(innvl, ZPOOL_PREFETCH_TYPE, &type) != 0)
4581 		return (EINVAL);
4582 
4583 	if (type != ZPOOL_PREFETCH_DDT && type != ZPOOL_PREFETCH_BRT)
4584 		return (EINVAL);
4585 
4586 	error = spa_open(poolname, &spa, FTAG);
4587 	if (error != 0)
4588 		return (error);
4589 
4590 	hrtime_t start_time = gethrtime();
4591 
4592 	if (type == ZPOOL_PREFETCH_DDT) {
4593 		ddt_prefetch_all(spa);
4594 		zfs_dbgmsg("pool '%s': loaded ddt into ARC in %llu ms",
4595 		    spa->spa_name,
4596 		    (u_longlong_t)NSEC2MSEC(gethrtime() - start_time));
4597 	} else {
4598 		brt_prefetch_all(spa);
4599 		zfs_dbgmsg("pool '%s': loaded brt into ARC in %llu ms",
4600 		    spa->spa_name,
4601 		    (u_longlong_t)NSEC2MSEC(gethrtime() - start_time));
4602 	}
4603 
4604 	spa_close(spa, FTAG);
4605 
4606 	return (error);
4607 }
4608 
4609 /*
4610  * inputs:
4611  * zc_name		name of dataset to destroy
4612  * zc_defer_destroy	mark for deferred destroy
4613  *
4614  * outputs:		none
4615  */
4616 static int
zfs_ioc_destroy(zfs_cmd_t * zc)4617 zfs_ioc_destroy(zfs_cmd_t *zc)
4618 {
4619 	objset_t *os;
4620 	dmu_objset_type_t ost;
4621 	int err;
4622 
4623 	err = dmu_objset_hold(zc->zc_name, FTAG, &os);
4624 	if (err != 0)
4625 		return (err);
4626 	ost = dmu_objset_type(os);
4627 	dmu_objset_rele(os, FTAG);
4628 
4629 	if (ost == DMU_OST_ZFS)
4630 		zfs_unmount_snap(zc->zc_name);
4631 
4632 	if (strchr(zc->zc_name, '@')) {
4633 		err = dsl_destroy_snapshot(zc->zc_name, zc->zc_defer_destroy);
4634 	} else {
4635 		/*
4636 		 * Save zoned_uid before destroying so we can clean up
4637 		 * kernel-side zone tracking after a successful destroy.
4638 		 */
4639 		uint64_t zoned_uid = 0;
4640 		(void) dsl_prop_get(zc->zc_name, "zoned_uid",
4641 		    8, 1, &zoned_uid, NULL);
4642 
4643 		err = dsl_destroy_head(zc->zc_name);
4644 		if (err == EEXIST) {
4645 			/*
4646 			 * It is possible that the given DS may have
4647 			 * hidden child (%recv) datasets - "leftovers"
4648 			 * resulting from the previously interrupted
4649 			 * 'zfs receive'.
4650 			 *
4651 			 * 6 extra bytes for /%recv
4652 			 */
4653 			char namebuf[ZFS_MAX_DATASET_NAME_LEN + 6];
4654 
4655 			if (snprintf(namebuf, sizeof (namebuf), "%s/%s",
4656 			    zc->zc_name, recv_clone_name) >=
4657 			    sizeof (namebuf))
4658 				return (SET_ERROR(EINVAL));
4659 
4660 			/*
4661 			 * Try to remove the hidden child (%recv) and after
4662 			 * that try to remove the target dataset.
4663 			 * If the hidden child (%recv) does not exist
4664 			 * the original error (EEXIST) will be returned
4665 			 */
4666 			err = dsl_destroy_head(namebuf);
4667 			if (err == 0)
4668 				err = dsl_destroy_head(zc->zc_name);
4669 			else if (err == ENOENT)
4670 				err = SET_ERROR(EEXIST);
4671 		}
4672 
4673 		if (err == 0 && zoned_uid != 0) {
4674 			(void) zone_dataset_detach_uid(kcred,
4675 			    zc->zc_name, (uid_t)zoned_uid);
4676 		}
4677 	}
4678 
4679 	return (err);
4680 }
4681 
4682 /*
4683  * innvl: {
4684  *     "initialize_command" -> POOL_INITIALIZE_{CANCEL|START|SUSPEND} (uint64)
4685  *     "initialize_vdevs": { -> guids to initialize (nvlist)
4686  *         "vdev_path_1": vdev_guid_1, (uint64),
4687  *         "vdev_path_2": vdev_guid_2, (uint64),
4688  *         ...
4689  *     },
4690  * }
4691  *
4692  * outnvl: {
4693  *     "initialize_vdevs": { -> initialization errors (nvlist)
4694  *         "vdev_path_1": errno, see function body for possible errnos (uint64)
4695  *         "vdev_path_2": errno, ... (uint64)
4696  *         ...
4697  *     }
4698  * }
4699  *
4700  * EINVAL is returned for an unknown commands or if any of the provided vdev
4701  * guids have be specified with a type other than uint64.
4702  */
4703 static const zfs_ioc_key_t zfs_keys_pool_initialize[] = {
4704 	{ZPOOL_INITIALIZE_COMMAND,	DATA_TYPE_UINT64,	0},
4705 	{ZPOOL_INITIALIZE_VDEVS,	DATA_TYPE_NVLIST,	0}
4706 };
4707 
4708 static int
zfs_ioc_pool_initialize(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4709 zfs_ioc_pool_initialize(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4710 {
4711 	uint64_t cmd_type;
4712 	if (nvlist_lookup_uint64(innvl, ZPOOL_INITIALIZE_COMMAND,
4713 	    &cmd_type) != 0) {
4714 		return (SET_ERROR(EINVAL));
4715 	}
4716 
4717 	if (!(cmd_type == POOL_INITIALIZE_CANCEL ||
4718 	    cmd_type == POOL_INITIALIZE_START ||
4719 	    cmd_type == POOL_INITIALIZE_SUSPEND ||
4720 	    cmd_type == POOL_INITIALIZE_UNINIT)) {
4721 		return (SET_ERROR(EINVAL));
4722 	}
4723 
4724 	nvlist_t *vdev_guids;
4725 	if (nvlist_lookup_nvlist(innvl, ZPOOL_INITIALIZE_VDEVS,
4726 	    &vdev_guids) != 0) {
4727 		return (SET_ERROR(EINVAL));
4728 	}
4729 
4730 	for (nvpair_t *pair = nvlist_next_nvpair(vdev_guids, NULL);
4731 	    pair != NULL; pair = nvlist_next_nvpair(vdev_guids, pair)) {
4732 		uint64_t vdev_guid;
4733 		if (nvpair_value_uint64(pair, &vdev_guid) != 0) {
4734 			return (SET_ERROR(EINVAL));
4735 		}
4736 	}
4737 
4738 	spa_t *spa;
4739 	int error = spa_open(poolname, &spa, FTAG);
4740 	if (error != 0)
4741 		return (error);
4742 
4743 	nvlist_t *vdev_errlist = fnvlist_alloc();
4744 	int total_errors = spa_vdev_initialize(spa, vdev_guids, cmd_type,
4745 	    vdev_errlist);
4746 
4747 	if (fnvlist_size(vdev_errlist) > 0) {
4748 		fnvlist_add_nvlist(outnvl, ZPOOL_INITIALIZE_VDEVS,
4749 		    vdev_errlist);
4750 	}
4751 	fnvlist_free(vdev_errlist);
4752 
4753 	spa_close(spa, FTAG);
4754 	return (total_errors > 0 ? SET_ERROR(EINVAL) : 0);
4755 }
4756 
4757 /*
4758  * innvl: {
4759  *     "trim_command" -> POOL_TRIM_{CANCEL|START|SUSPEND} (uint64)
4760  *     "trim_vdevs": { -> guids to TRIM (nvlist)
4761  *         "vdev_path_1": vdev_guid_1, (uint64),
4762  *         "vdev_path_2": vdev_guid_2, (uint64),
4763  *         ...
4764  *     },
4765  *     "trim_rate" -> Target TRIM rate in bytes/sec.
4766  *     "trim_secure" -> Set to request a secure TRIM.
4767  * }
4768  *
4769  * outnvl: {
4770  *     "trim_vdevs": { -> TRIM errors (nvlist)
4771  *         "vdev_path_1": errno, see function body for possible errnos (uint64)
4772  *         "vdev_path_2": errno, ... (uint64)
4773  *         ...
4774  *     }
4775  * }
4776  *
4777  * EINVAL is returned for an unknown commands or if any of the provided vdev
4778  * guids have be specified with a type other than uint64.
4779  */
4780 static const zfs_ioc_key_t zfs_keys_pool_trim[] = {
4781 	{ZPOOL_TRIM_COMMAND,	DATA_TYPE_UINT64,		0},
4782 	{ZPOOL_TRIM_VDEVS,	DATA_TYPE_NVLIST,		0},
4783 	{ZPOOL_TRIM_RATE,	DATA_TYPE_UINT64,		ZK_OPTIONAL},
4784 	{ZPOOL_TRIM_SECURE,	DATA_TYPE_BOOLEAN_VALUE,	ZK_OPTIONAL},
4785 };
4786 
4787 static int
zfs_ioc_pool_trim(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4788 zfs_ioc_pool_trim(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4789 {
4790 	uint64_t cmd_type;
4791 	if (nvlist_lookup_uint64(innvl, ZPOOL_TRIM_COMMAND, &cmd_type) != 0)
4792 		return (SET_ERROR(EINVAL));
4793 
4794 	if (!(cmd_type == POOL_TRIM_CANCEL ||
4795 	    cmd_type == POOL_TRIM_START ||
4796 	    cmd_type == POOL_TRIM_SUSPEND)) {
4797 		return (SET_ERROR(EINVAL));
4798 	}
4799 
4800 	nvlist_t *vdev_guids;
4801 	if (nvlist_lookup_nvlist(innvl, ZPOOL_TRIM_VDEVS, &vdev_guids) != 0)
4802 		return (SET_ERROR(EINVAL));
4803 
4804 	for (nvpair_t *pair = nvlist_next_nvpair(vdev_guids, NULL);
4805 	    pair != NULL; pair = nvlist_next_nvpair(vdev_guids, pair)) {
4806 		uint64_t vdev_guid;
4807 		if (nvpair_value_uint64(pair, &vdev_guid) != 0) {
4808 			return (SET_ERROR(EINVAL));
4809 		}
4810 	}
4811 
4812 	/* Optional, defaults to maximum rate when not provided */
4813 	uint64_t rate;
4814 	if (nvlist_lookup_uint64(innvl, ZPOOL_TRIM_RATE, &rate) != 0)
4815 		rate = 0;
4816 
4817 	/* Optional, defaults to standard TRIM when not provided */
4818 	boolean_t secure;
4819 	if (nvlist_lookup_boolean_value(innvl, ZPOOL_TRIM_SECURE,
4820 	    &secure) != 0) {
4821 		secure = B_FALSE;
4822 	}
4823 
4824 	spa_t *spa;
4825 	int error = spa_open(poolname, &spa, FTAG);
4826 	if (error != 0)
4827 		return (error);
4828 
4829 	nvlist_t *vdev_errlist = fnvlist_alloc();
4830 	int total_errors = spa_vdev_trim(spa, vdev_guids, cmd_type,
4831 	    rate, !!zfs_trim_metaslab_skip, secure, vdev_errlist);
4832 
4833 	if (fnvlist_size(vdev_errlist) > 0)
4834 		fnvlist_add_nvlist(outnvl, ZPOOL_TRIM_VDEVS, vdev_errlist);
4835 
4836 	fnvlist_free(vdev_errlist);
4837 
4838 	spa_close(spa, FTAG);
4839 	return (total_errors > 0 ? SET_ERROR(EINVAL) : 0);
4840 }
4841 
4842 #define	DDT_PRUNE_UNIT		"ddt_prune_unit"
4843 #define	DDT_PRUNE_AMOUNT	"ddt_prune_amount"
4844 
4845 /*
4846  * innvl: {
4847  *     "ddt_prune_unit" -> uint32_t
4848  *     "ddt_prune_amount" -> uint64_t
4849  * }
4850  *
4851  * outnvl: "waited" -> boolean_t
4852  */
4853 static const zfs_ioc_key_t zfs_keys_ddt_prune[] = {
4854 	{DDT_PRUNE_UNIT,	DATA_TYPE_INT32,	0},
4855 	{DDT_PRUNE_AMOUNT,	DATA_TYPE_UINT64,	0},
4856 };
4857 
4858 static int
zfs_ioc_ddt_prune(const char * poolname,nvlist_t * innvl,nvlist_t * outnvl)4859 zfs_ioc_ddt_prune(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
4860 {
4861 	int32_t unit;
4862 	uint64_t amount;
4863 
4864 	if (nvlist_lookup_int32(innvl, DDT_PRUNE_UNIT, &unit) != 0 ||
4865 	    nvlist_lookup_uint64(innvl, DDT_PRUNE_AMOUNT, &amount) != 0) {
4866 		return (EINVAL);
4867 	}
4868 
4869 	spa_t *spa;
4870 	int error = spa_open(poolname, &spa, FTAG);
4871 	if (error != 0)
4872 		return (error);
4873 
4874 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_FAST_DEDUP)) {
4875 		spa_close(spa, FTAG);
4876 		return (SET_ERROR(ENOTSUP));
4877 	}
4878 
4879 	error = ddt_prune_unique_entries(spa, (zpool_ddt_prune_unit_t)unit,
4880 	    amount);
4881 
4882 	spa_close(spa, FTAG);
4883 
4884 	return (error);
4885 }
4886 
4887 /*
4888  * This ioctl waits for activity of a particular type to complete. If there is
4889  * no activity of that type in progress, it returns immediately, and the
4890  * returned value "waited" is false. If there is activity in progress, and no
4891  * tag is passed in, the ioctl blocks until all activity of that type is
4892  * complete, and then returns with "waited" set to true.
4893  *
4894  * If a tag is provided, it identifies a particular instance of an activity to
4895  * wait for. Currently, this is only valid for use with 'initialize', because
4896  * that is the only activity for which there can be multiple instances running
4897  * concurrently. In the case of 'initialize', the tag corresponds to the guid of
4898  * the vdev on which to wait.
4899  *
4900  * If a thread waiting in the ioctl receives a signal, the call will return
4901  * immediately, and the return value will be EINTR.
4902  *
4903  * innvl: {
4904  *     "wait_activity" -> int32_t
4905  *     (optional) "wait_tag" -> uint64_t
4906  * }
4907  *
4908  * outnvl: "waited" -> boolean_t
4909  */
4910 static const zfs_ioc_key_t zfs_keys_pool_wait[] = {
4911 	{ZPOOL_WAIT_ACTIVITY,	DATA_TYPE_INT32,		0},
4912 	{ZPOOL_WAIT_TAG,	DATA_TYPE_UINT64,		ZK_OPTIONAL},
4913 };
4914 
4915 static int
zfs_ioc_wait(const char * name,nvlist_t * innvl,nvlist_t * outnvl)4916 zfs_ioc_wait(const char *name, nvlist_t *innvl, nvlist_t *outnvl)
4917 {
4918 	int32_t activity;
4919 	uint64_t tag;
4920 	boolean_t waited;
4921 	int error;
4922 
4923 	if (nvlist_lookup_int32(innvl, ZPOOL_WAIT_ACTIVITY, &activity) != 0)
4924 		return (EINVAL);
4925 
4926 	if (nvlist_lookup_uint64(innvl, ZPOOL_WAIT_TAG, &tag) == 0)
4927 		error = spa_wait_tag(name, activity, tag, &waited);
4928 	else
4929 		error = spa_wait(name, activity, &waited);
4930 
4931 	if (error == 0)
4932 		fnvlist_add_boolean_value(outnvl, ZPOOL_WAIT_WAITED, waited);
4933 
4934 	return (error);
4935 }
4936 
4937 /*
4938  * This ioctl waits for activity of a particular type to complete. If there is
4939  * no activity of that type in progress, it returns immediately, and the
4940  * returned value "waited" is false. If there is activity in progress, and no
4941  * tag is passed in, the ioctl blocks until all activity of that type is
4942  * complete, and then returns with "waited" set to true.
4943  *
4944  * If a thread waiting in the ioctl receives a signal, the call will return
4945  * immediately, and the return value will be EINTR.
4946  *
4947  * innvl: {
4948  *     "wait_activity" -> int32_t
4949  * }
4950  *
4951  * outnvl: "waited" -> boolean_t
4952  */
4953 static const zfs_ioc_key_t zfs_keys_fs_wait[] = {
4954 	{ZFS_WAIT_ACTIVITY,	DATA_TYPE_INT32,		0},
4955 };
4956 
4957 static int
zfs_ioc_wait_fs(const char * name,nvlist_t * innvl,nvlist_t * outnvl)4958 zfs_ioc_wait_fs(const char *name, nvlist_t *innvl, nvlist_t *outnvl)
4959 {
4960 	int32_t activity;
4961 	boolean_t waited = B_FALSE;
4962 	int error;
4963 	dsl_pool_t *dp;
4964 	dsl_dir_t *dd;
4965 	dsl_dataset_t *ds;
4966 
4967 	if (nvlist_lookup_int32(innvl, ZFS_WAIT_ACTIVITY, &activity) != 0)
4968 		return (SET_ERROR(EINVAL));
4969 
4970 	if (activity >= ZFS_WAIT_NUM_ACTIVITIES || activity < 0)
4971 		return (SET_ERROR(EINVAL));
4972 
4973 	if ((error = dsl_pool_hold(name, FTAG, &dp)) != 0)
4974 		return (error);
4975 
4976 	if ((error = dsl_dataset_hold(dp, name, FTAG, &ds)) != 0) {
4977 		dsl_pool_rele(dp, FTAG);
4978 		return (error);
4979 	}
4980 
4981 	dd = ds->ds_dir;
4982 	mutex_enter(&dd->dd_activity_lock);
4983 	dd->dd_activity_waiters++;
4984 
4985 	/*
4986 	 * We get a long-hold here so that the dsl_dataset_t and dsl_dir_t
4987 	 * aren't evicted while we're waiting. Normally this is prevented by
4988 	 * holding the pool, but we can't do that while we're waiting since
4989 	 * that would prevent TXGs from syncing out. Some of the functionality
4990 	 * of long-holds (e.g. preventing deletion) is unnecessary for this
4991 	 * case, since we would cancel the waiters before proceeding with a
4992 	 * deletion. An alternative mechanism for keeping the dataset around
4993 	 * could be developed but this is simpler.
4994 	 */
4995 	dsl_dataset_long_hold(ds, FTAG);
4996 	dsl_pool_rele(dp, FTAG);
4997 
4998 	error = dsl_dir_wait(dd, ds, activity, &waited);
4999 
5000 	dsl_dataset_long_rele(ds, FTAG);
5001 	dd->dd_activity_waiters--;
5002 	if (dd->dd_activity_waiters == 0)
5003 		cv_signal(&dd->dd_activity_cv);
5004 	mutex_exit(&dd->dd_activity_lock);
5005 
5006 	dsl_dataset_rele(ds, FTAG);
5007 
5008 	if (error == 0)
5009 		fnvlist_add_boolean_value(outnvl, ZFS_WAIT_WAITED, waited);
5010 
5011 	return (error);
5012 }
5013 
5014 /*
5015  * fsname is name of dataset to rollback (to most recent snapshot)
5016  *
5017  * innvl may contain name of expected target snapshot
5018  *
5019  * outnvl: "target" -> name of most recent snapshot
5020  * }
5021  */
5022 static const zfs_ioc_key_t zfs_keys_rollback[] = {
5023 	{"target",	DATA_TYPE_STRING,	ZK_OPTIONAL},
5024 };
5025 
5026 static int
zfs_ioc_rollback(const char * fsname,nvlist_t * innvl,nvlist_t * outnvl)5027 zfs_ioc_rollback(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
5028 {
5029 	zfsvfs_t *zfsvfs;
5030 	zvol_state_handle_t *zv;
5031 	const char *target = NULL;
5032 	int error;
5033 
5034 	(void) nvlist_lookup_string(innvl, "target", &target);
5035 	if (target != NULL) {
5036 		const char *cp = strchr(target, '@');
5037 
5038 		/*
5039 		 * The snap name must contain an @, and the part after it must
5040 		 * contain only valid characters.
5041 		 */
5042 		if (cp == NULL ||
5043 		    zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
5044 			return (SET_ERROR(EINVAL));
5045 	}
5046 
5047 	if (getzfsvfs(fsname, &zfsvfs) == 0) {
5048 		dsl_dataset_t *ds;
5049 
5050 		ds = dmu_objset_ds(zfsvfs->z_os);
5051 		error = zfs_suspend_fs(zfsvfs);
5052 		if (error == 0) {
5053 			int resume_err;
5054 
5055 			error = dsl_dataset_rollback(fsname, target, zfsvfs,
5056 			    outnvl);
5057 			resume_err = zfs_resume_fs(zfsvfs, ds);
5058 			error = error ? error : resume_err;
5059 		}
5060 		zfs_vfs_rele(zfsvfs);
5061 	} else if (zvol_suspend(fsname, &zv) == 0) {
5062 		error = dsl_dataset_rollback(fsname, target, zvol_tag(zv),
5063 		    outnvl);
5064 		zvol_resume(zv);
5065 	} else {
5066 		error = dsl_dataset_rollback(fsname, target, NULL, outnvl);
5067 	}
5068 	return (error);
5069 }
5070 
5071 static int
recursive_unmount(const char * fsname,void * arg)5072 recursive_unmount(const char *fsname, void *arg)
5073 {
5074 	const char *snapname = arg;
5075 	char *fullname;
5076 
5077 	fullname = kmem_asprintf("%s@%s", fsname, snapname);
5078 	zfs_unmount_snap(fullname);
5079 	kmem_strfree(fullname);
5080 
5081 	return (0);
5082 }
5083 
5084 /*
5085  *
5086  * snapname is the snapshot to redact.
5087  * innvl: {
5088  *     "bookname" -> (string)
5089  *         shortname of the redaction bookmark to generate
5090  *     "snapnv" -> (nvlist, values ignored)
5091  *         snapshots to redact snapname with respect to
5092  * }
5093  *
5094  * outnvl is unused
5095  */
5096 
5097 static const zfs_ioc_key_t zfs_keys_redact[] = {
5098 	{"bookname",		DATA_TYPE_STRING,	0},
5099 	{"snapnv",		DATA_TYPE_NVLIST,	0},
5100 };
5101 
5102 static int
zfs_ioc_redact(const char * snapname,nvlist_t * innvl,nvlist_t * outnvl)5103 zfs_ioc_redact(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5104 {
5105 	(void) outnvl;
5106 	nvlist_t *redactnvl = NULL;
5107 	const char *redactbook = NULL;
5108 
5109 	if (nvlist_lookup_nvlist(innvl, "snapnv", &redactnvl) != 0)
5110 		return (SET_ERROR(EINVAL));
5111 	if (fnvlist_num_pairs(redactnvl) == 0)
5112 		return (SET_ERROR(ENXIO));
5113 	if (nvlist_lookup_string(innvl, "bookname", &redactbook) != 0)
5114 		return (SET_ERROR(EINVAL));
5115 
5116 	return (dmu_redact_snap(snapname, redactnvl, redactbook));
5117 }
5118 
5119 /*
5120  * inputs:
5121  * zc_name	old name of dataset
5122  * zc_value	new name of dataset
5123  * zc_cookie	recursive flag (only valid for snapshots)
5124  *
5125  * outputs:	none
5126  */
5127 static int
zfs_ioc_rename(zfs_cmd_t * zc)5128 zfs_ioc_rename(zfs_cmd_t *zc)
5129 {
5130 	objset_t *os;
5131 	dmu_objset_type_t ost;
5132 	boolean_t recursive = zc->zc_cookie & 1;
5133 	boolean_t nounmount = !!(zc->zc_cookie & 2);
5134 	char *at;
5135 	int err;
5136 
5137 	/* "zfs rename" from and to ...%recv datasets should both fail */
5138 	zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
5139 	zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
5140 	if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
5141 	    dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
5142 	    strchr(zc->zc_name, '%') || strchr(zc->zc_value, '%'))
5143 		return (SET_ERROR(EINVAL));
5144 
5145 	err = dmu_objset_hold(zc->zc_name, FTAG, &os);
5146 	if (err != 0)
5147 		return (err);
5148 	ost = dmu_objset_type(os);
5149 	dmu_objset_rele(os, FTAG);
5150 
5151 	at = strchr(zc->zc_name, '@');
5152 	if (at != NULL) {
5153 		/* snaps must be in same fs */
5154 		int error;
5155 
5156 		if (strncmp(zc->zc_name, zc->zc_value, at - zc->zc_name + 1))
5157 			return (SET_ERROR(EXDEV));
5158 		*at = '\0';
5159 		if (ost == DMU_OST_ZFS && !nounmount) {
5160 			error = dmu_objset_find(zc->zc_name,
5161 			    recursive_unmount, at + 1,
5162 			    recursive ? DS_FIND_CHILDREN : 0);
5163 			if (error != 0) {
5164 				*at = '@';
5165 				return (error);
5166 			}
5167 		}
5168 		error = dsl_dataset_rename_snapshot(zc->zc_name,
5169 		    at + 1, strchr(zc->zc_value, '@') + 1, recursive);
5170 		*at = '@';
5171 
5172 		return (error);
5173 	} else {
5174 		/*
5175 		 * For dataset renames, update kernel-side zone tracking
5176 		 * if the dataset has a zoned_uid delegation.  Read the
5177 		 * property before rename, then detach old / attach new.
5178 		 */
5179 		uint64_t zoned_uid = 0;
5180 		(void) dsl_prop_get(zc->zc_name, "zoned_uid",
5181 		    8, 1, &zoned_uid, NULL);
5182 
5183 		err = dsl_dir_rename(zc->zc_name, zc->zc_value);
5184 
5185 		if (err == 0 && zoned_uid != 0) {
5186 			(void) zone_dataset_detach_uid(kcred,
5187 			    zc->zc_name, (uid_t)zoned_uid);
5188 			(void) zone_dataset_attach_uid(kcred,
5189 			    zc->zc_value, (uid_t)zoned_uid);
5190 		}
5191 		return (err);
5192 	}
5193 }
5194 
5195 static int
zfs_check_settable(const char * dsname,nvpair_t * pair,cred_t * cr)5196 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
5197 {
5198 	const char *propname = nvpair_name(pair);
5199 	boolean_t issnap = (strchr(dsname, '@') != NULL);
5200 	zfs_prop_t prop = zfs_name_to_prop(propname);
5201 	uint64_t intval, compval;
5202 	int err;
5203 
5204 	if (prop == ZPROP_USERPROP) {
5205 		if (zfs_prop_user(propname)) {
5206 			zone_admin_result_t zone_result;
5207 			zone_result = zone_dataset_admin_check(dsname,
5208 			    ZONE_OP_SETPROP, NULL);
5209 			if (zone_result == ZONE_ADMIN_ALLOWED)
5210 				return (zfs_secpolicy_zoned_uid_deleg(dsname,
5211 				    ZFS_DELEG_PERM_USERPROP, cr));
5212 			if (zone_result == ZONE_ADMIN_DENIED)
5213 				return (SET_ERROR(EPERM));
5214 			if ((err = zfs_secpolicy_write_perms(dsname,
5215 			    ZFS_DELEG_PERM_USERPROP, cr)))
5216 				return (err);
5217 			return (0);
5218 		}
5219 
5220 		if (!issnap && zfs_prop_userquota(propname)) {
5221 			const char *perm = NULL;
5222 			const char *uq_prefix =
5223 			    zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
5224 			const char *gq_prefix =
5225 			    zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
5226 			const char *uiq_prefix =
5227 			    zfs_userquota_prop_prefixes[ZFS_PROP_USEROBJQUOTA];
5228 			const char *giq_prefix =
5229 			    zfs_userquota_prop_prefixes[ZFS_PROP_GROUPOBJQUOTA];
5230 			const char *pq_prefix =
5231 			    zfs_userquota_prop_prefixes[ZFS_PROP_PROJECTQUOTA];
5232 			const char *piq_prefix = zfs_userquota_prop_prefixes[\
5233 			    ZFS_PROP_PROJECTOBJQUOTA];
5234 
5235 			if (strncmp(propname, uq_prefix,
5236 			    strlen(uq_prefix)) == 0) {
5237 				perm = ZFS_DELEG_PERM_USERQUOTA;
5238 			} else if (strncmp(propname, uiq_prefix,
5239 			    strlen(uiq_prefix)) == 0) {
5240 				perm = ZFS_DELEG_PERM_USEROBJQUOTA;
5241 			} else if (strncmp(propname, gq_prefix,
5242 			    strlen(gq_prefix)) == 0) {
5243 				perm = ZFS_DELEG_PERM_GROUPQUOTA;
5244 			} else if (strncmp(propname, giq_prefix,
5245 			    strlen(giq_prefix)) == 0) {
5246 				perm = ZFS_DELEG_PERM_GROUPOBJQUOTA;
5247 			} else if (strncmp(propname, pq_prefix,
5248 			    strlen(pq_prefix)) == 0) {
5249 				perm = ZFS_DELEG_PERM_PROJECTQUOTA;
5250 			} else if (strncmp(propname, piq_prefix,
5251 			    strlen(piq_prefix)) == 0) {
5252 				perm = ZFS_DELEG_PERM_PROJECTOBJQUOTA;
5253 			} else {
5254 				/* {USER|GROUP|PROJECT}USED are read-only */
5255 				return (SET_ERROR(EINVAL));
5256 			}
5257 
5258 			zone_admin_result_t zone_result;
5259 			zone_result = zone_dataset_admin_check(dsname,
5260 			    ZONE_OP_SETPROP, NULL);
5261 			if (zone_result == ZONE_ADMIN_ALLOWED)
5262 				return (zfs_secpolicy_zoned_uid_deleg(dsname,
5263 				    perm, cr));
5264 			if (zone_result == ZONE_ADMIN_DENIED)
5265 				return (SET_ERROR(EPERM));
5266 			if ((err = zfs_secpolicy_write_perms(dsname, perm, cr)))
5267 				return (err);
5268 			return (0);
5269 		}
5270 
5271 		return (SET_ERROR(EINVAL));
5272 	}
5273 
5274 	if (issnap)
5275 		return (SET_ERROR(EINVAL));
5276 
5277 	if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
5278 		/*
5279 		 * dsl_prop_get_all_impl() returns properties in this
5280 		 * format.
5281 		 */
5282 		nvlist_t *attrs;
5283 		VERIFY0(nvpair_value_nvlist(pair, &attrs));
5284 		VERIFY0(nvlist_lookup_nvpair(attrs, ZPROP_VALUE, &pair));
5285 	}
5286 
5287 	/*
5288 	 * Check that this value is valid for this pool version
5289 	 */
5290 	switch (prop) {
5291 	case ZFS_PROP_COMPRESSION:
5292 		/*
5293 		 * If the user specified gzip compression, make sure
5294 		 * the SPA supports it. We ignore any errors here since
5295 		 * we'll catch them later.
5296 		 */
5297 		if (nvpair_value_uint64(pair, &intval) == 0) {
5298 			compval = ZIO_COMPRESS_ALGO(intval);
5299 			if (compval >= ZIO_COMPRESS_GZIP_1 &&
5300 			    compval <= ZIO_COMPRESS_GZIP_9 &&
5301 			    zfs_earlier_version(dsname,
5302 			    SPA_VERSION_GZIP_COMPRESSION)) {
5303 				return (SET_ERROR(ENOTSUP));
5304 			}
5305 
5306 			if (compval == ZIO_COMPRESS_ZLE &&
5307 			    zfs_earlier_version(dsname,
5308 			    SPA_VERSION_ZLE_COMPRESSION))
5309 				return (SET_ERROR(ENOTSUP));
5310 
5311 			if (compval == ZIO_COMPRESS_LZ4) {
5312 				spa_t *spa;
5313 
5314 				if ((err = spa_open(dsname, &spa, FTAG)) != 0)
5315 					return (err);
5316 
5317 				if (!spa_feature_is_enabled(spa,
5318 				    SPA_FEATURE_LZ4_COMPRESS)) {
5319 					spa_close(spa, FTAG);
5320 					return (SET_ERROR(ENOTSUP));
5321 				}
5322 				spa_close(spa, FTAG);
5323 			}
5324 
5325 			if (compval == ZIO_COMPRESS_ZSTD) {
5326 				spa_t *spa;
5327 
5328 				if ((err = spa_open(dsname, &spa, FTAG)) != 0)
5329 					return (err);
5330 
5331 				if (!spa_feature_is_enabled(spa,
5332 				    SPA_FEATURE_ZSTD_COMPRESS)) {
5333 					spa_close(spa, FTAG);
5334 					return (SET_ERROR(ENOTSUP));
5335 				}
5336 				spa_close(spa, FTAG);
5337 			}
5338 		}
5339 		break;
5340 
5341 	case ZFS_PROP_COPIES:
5342 		if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
5343 			return (SET_ERROR(ENOTSUP));
5344 		break;
5345 
5346 	case ZFS_PROP_VOLBLOCKSIZE:
5347 	case ZFS_PROP_RECORDSIZE:
5348 		/* Record sizes above 128k need the feature to be enabled */
5349 		if (nvpair_value_uint64(pair, &intval) == 0 &&
5350 		    intval > SPA_OLD_MAXBLOCKSIZE) {
5351 			spa_t *spa;
5352 
5353 			/*
5354 			 * We don't allow setting the property above 1MB,
5355 			 * unless the tunable has been changed.
5356 			 */
5357 			if (intval > zfs_max_recordsize ||
5358 			    intval > SPA_MAXBLOCKSIZE)
5359 				return (SET_ERROR(ERANGE));
5360 
5361 			if ((err = spa_open(dsname, &spa, FTAG)) != 0)
5362 				return (err);
5363 
5364 			if (!spa_feature_is_enabled(spa,
5365 			    SPA_FEATURE_LARGE_BLOCKS)) {
5366 				spa_close(spa, FTAG);
5367 				return (SET_ERROR(ENOTSUP));
5368 			}
5369 			spa_close(spa, FTAG);
5370 		}
5371 		break;
5372 
5373 	case ZFS_PROP_DNODESIZE:
5374 		/* Dnode sizes above 512 need the feature to be enabled */
5375 		if (nvpair_value_uint64(pair, &intval) == 0 &&
5376 		    intval != ZFS_DNSIZE_LEGACY) {
5377 			spa_t *spa;
5378 
5379 			if ((err = spa_open(dsname, &spa, FTAG)) != 0)
5380 				return (err);
5381 
5382 			if (!spa_feature_is_enabled(spa,
5383 			    SPA_FEATURE_LARGE_DNODE)) {
5384 				spa_close(spa, FTAG);
5385 				return (SET_ERROR(ENOTSUP));
5386 			}
5387 			spa_close(spa, FTAG);
5388 		}
5389 		break;
5390 
5391 	case ZFS_PROP_SHARESMB:
5392 		if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
5393 			return (SET_ERROR(ENOTSUP));
5394 		break;
5395 
5396 	case ZFS_PROP_ACLINHERIT:
5397 		if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
5398 		    nvpair_value_uint64(pair, &intval) == 0) {
5399 			if (intval == ZFS_ACL_PASSTHROUGH_X &&
5400 			    zfs_earlier_version(dsname,
5401 			    SPA_VERSION_PASSTHROUGH_X))
5402 				return (SET_ERROR(ENOTSUP));
5403 		}
5404 		break;
5405 	case ZFS_PROP_CHECKSUM:
5406 	case ZFS_PROP_DEDUP:
5407 	{
5408 		spa_feature_t feature;
5409 		spa_t *spa;
5410 		int err;
5411 
5412 		/* dedup feature version checks */
5413 		if (prop == ZFS_PROP_DEDUP &&
5414 		    zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
5415 			return (SET_ERROR(ENOTSUP));
5416 
5417 		if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
5418 		    nvpair_value_uint64(pair, &intval) == 0) {
5419 			/* check prop value is enabled in features */
5420 			feature = zio_checksum_to_feature(
5421 			    intval & ZIO_CHECKSUM_MASK);
5422 			if (feature == SPA_FEATURE_NONE)
5423 				break;
5424 
5425 			if ((err = spa_open(dsname, &spa, FTAG)) != 0)
5426 				return (err);
5427 
5428 			if (!spa_feature_is_enabled(spa, feature)) {
5429 				spa_close(spa, FTAG);
5430 				return (SET_ERROR(ENOTSUP));
5431 			}
5432 			spa_close(spa, FTAG);
5433 		}
5434 		break;
5435 	}
5436 
5437 	default:
5438 		break;
5439 	}
5440 
5441 	return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
5442 }
5443 
5444 /*
5445  * Removes properties from the given props list that fail permission checks
5446  * needed to clear them and to restore them in case of a receive error. For each
5447  * property, make sure we have both set and inherit permissions.
5448  *
5449  * Returns the first error encountered if any permission checks fail. If the
5450  * caller provides a non-NULL errlist, it also gives the complete list of names
5451  * of all the properties that failed a permission check along with the
5452  * corresponding error numbers. The caller is responsible for freeing the
5453  * returned errlist.
5454  *
5455  * If every property checks out successfully, zero is returned and the list
5456  * pointed at by errlist is NULL.
5457  */
5458 static int
zfs_check_clearable(const char * dataset,nvlist_t * props,nvlist_t ** errlist)5459 zfs_check_clearable(const char *dataset, nvlist_t *props, nvlist_t **errlist)
5460 {
5461 	zfs_cmd_t *zc;
5462 	nvpair_t *pair, *next_pair;
5463 	nvlist_t *errors;
5464 	int err, rv = 0;
5465 
5466 	if (props == NULL)
5467 		return (0);
5468 
5469 	VERIFY0(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP));
5470 
5471 	zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
5472 	(void) strlcpy(zc->zc_name, dataset, sizeof (zc->zc_name));
5473 	pair = nvlist_next_nvpair(props, NULL);
5474 	while (pair != NULL) {
5475 		next_pair = nvlist_next_nvpair(props, pair);
5476 
5477 		(void) strlcpy(zc->zc_value, nvpair_name(pair),
5478 		    sizeof (zc->zc_value));
5479 		if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
5480 		    (err = zfs_secpolicy_inherit_prop(zc, NULL, CRED())) != 0) {
5481 			VERIFY0(nvlist_remove_nvpair(props, pair));
5482 			VERIFY0(nvlist_add_int32(errors, zc->zc_value, err));
5483 		}
5484 		pair = next_pair;
5485 	}
5486 	kmem_free(zc, sizeof (zfs_cmd_t));
5487 
5488 	if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
5489 		nvlist_free(errors);
5490 		errors = NULL;
5491 	} else {
5492 		VERIFY0(nvpair_value_int32(pair, &rv));
5493 	}
5494 
5495 	if (errlist == NULL)
5496 		nvlist_free(errors);
5497 	else
5498 		*errlist = errors;
5499 
5500 	return (rv);
5501 }
5502 
5503 static boolean_t
propval_equals(nvpair_t * p1,nvpair_t * p2)5504 propval_equals(nvpair_t *p1, nvpair_t *p2)
5505 {
5506 	if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
5507 		/* dsl_prop_get_all_impl() format */
5508 		nvlist_t *attrs;
5509 		VERIFY0(nvpair_value_nvlist(p1, &attrs));
5510 		VERIFY0(nvlist_lookup_nvpair(attrs, ZPROP_VALUE, &p1));
5511 	}
5512 
5513 	if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
5514 		nvlist_t *attrs;
5515 		VERIFY0(nvpair_value_nvlist(p2, &attrs));
5516 		VERIFY0(nvlist_lookup_nvpair(attrs, ZPROP_VALUE, &p2));
5517 	}
5518 
5519 	if (nvpair_type(p1) != nvpair_type(p2))
5520 		return (B_FALSE);
5521 
5522 	if (nvpair_type(p1) == DATA_TYPE_STRING) {
5523 		const char *valstr1, *valstr2;
5524 
5525 		VERIFY0(nvpair_value_string(p1, &valstr1));
5526 		VERIFY0(nvpair_value_string(p2, &valstr2));
5527 		return (strcmp(valstr1, valstr2) == 0);
5528 	} else {
5529 		uint64_t intval1, intval2;
5530 
5531 		VERIFY0(nvpair_value_uint64(p1, &intval1));
5532 		VERIFY0(nvpair_value_uint64(p2, &intval2));
5533 		return (intval1 == intval2);
5534 	}
5535 }
5536 
5537 /*
5538  * Remove properties from props if they are not going to change (as determined
5539  * by comparison with origprops). Remove them from origprops as well, since we
5540  * do not need to clear or restore properties that won't change.
5541  */
5542 static void
props_reduce(nvlist_t * props,nvlist_t * origprops)5543 props_reduce(nvlist_t *props, nvlist_t *origprops)
5544 {
5545 	nvpair_t *pair, *next_pair;
5546 
5547 	if (origprops == NULL)
5548 		return; /* all props need to be received */
5549 
5550 	pair = nvlist_next_nvpair(props, NULL);
5551 	while (pair != NULL) {
5552 		const char *propname = nvpair_name(pair);
5553 		nvpair_t *match;
5554 
5555 		next_pair = nvlist_next_nvpair(props, pair);
5556 
5557 		if ((nvlist_lookup_nvpair(origprops, propname,
5558 		    &match) != 0) || !propval_equals(pair, match))
5559 			goto next; /* need to set received value */
5560 
5561 		/* don't clear the existing received value */
5562 		(void) nvlist_remove_nvpair(origprops, match);
5563 		/* don't bother receiving the property */
5564 		(void) nvlist_remove_nvpair(props, pair);
5565 next:
5566 		pair = next_pair;
5567 	}
5568 }
5569 
5570 /*
5571  * Extract properties that cannot be set PRIOR to the receipt of a dataset.
5572  * For example, refquota cannot be set until after the receipt of a dataset,
5573  * because in replication streams, an older/earlier snapshot may exceed the
5574  * refquota.  We want to receive the older/earlier snapshot, but setting
5575  * refquota pre-receipt will set the dsl's ACTUAL quota, which will prevent
5576  * the older/earlier snapshot from being received (with EDQUOT).
5577  *
5578  * The ZFS test "zfs_receive_011_pos" demonstrates such a scenario.
5579  *
5580  * libzfs will need to be judicious handling errors encountered by props
5581  * extracted by this function.
5582  */
5583 static nvlist_t *
extract_delay_props(nvlist_t * props)5584 extract_delay_props(nvlist_t *props)
5585 {
5586 	nvlist_t *delayprops;
5587 	nvpair_t *nvp, *tmp;
5588 	static const zfs_prop_t delayable[] = {
5589 		ZFS_PROP_REFQUOTA,
5590 		ZFS_PROP_KEYLOCATION,
5591 		/*
5592 		 * Setting ZFS_PROP_SHARESMB requires the objset type to be
5593 		 * known, which is not possible prior to receipt of raw sends.
5594 		 */
5595 		ZFS_PROP_SHARESMB,
5596 		0
5597 	};
5598 	int i;
5599 
5600 	VERIFY0(nvlist_alloc(&delayprops, NV_UNIQUE_NAME, KM_SLEEP));
5601 
5602 	for (nvp = nvlist_next_nvpair(props, NULL); nvp != NULL;
5603 	    nvp = nvlist_next_nvpair(props, nvp)) {
5604 		/*
5605 		 * strcmp() is safe because zfs_prop_to_name() always returns
5606 		 * a bounded string.
5607 		 */
5608 		for (i = 0; delayable[i] != 0; i++) {
5609 			if (strcmp(zfs_prop_to_name(delayable[i]),
5610 			    nvpair_name(nvp)) == 0) {
5611 				break;
5612 			}
5613 		}
5614 		if (delayable[i] != 0) {
5615 			tmp = nvlist_prev_nvpair(props, nvp);
5616 			VERIFY0(nvlist_add_nvpair(delayprops, nvp));
5617 			VERIFY0(nvlist_remove_nvpair(props, nvp));
5618 			nvp = tmp;
5619 		}
5620 	}
5621 
5622 	if (nvlist_empty(delayprops)) {
5623 		nvlist_free(delayprops);
5624 		delayprops = NULL;
5625 	}
5626 	return (delayprops);
5627 }
5628 
5629 static void
zfs_allow_log_destroy(void * arg)5630 zfs_allow_log_destroy(void *arg)
5631 {
5632 	char *poolname = arg;
5633 
5634 	if (poolname != NULL)
5635 		kmem_strfree(poolname);
5636 }
5637 
5638 #ifdef	ZFS_DEBUG
5639 static boolean_t zfs_ioc_recv_inject_err;
5640 #endif
5641 
5642 /*
5643  * nvlist 'errors' is always allocated. It will contain descriptions of
5644  * encountered errors, if any. It's the callers responsibility to free.
5645  */
5646 static int
zfs_ioc_recv_impl(char * tofs,char * tosnap,const char * origin,nvlist_t * recvprops,nvlist_t * localprops,nvlist_t * hidden_args,boolean_t force,boolean_t heal,boolean_t resumable,int input_fd,dmu_replay_record_t * begin_record,uint64_t * read_bytes,uint64_t * errflags,nvlist_t ** errors)5647 zfs_ioc_recv_impl(char *tofs, char *tosnap, const char *origin,
5648     nvlist_t *recvprops, nvlist_t *localprops, nvlist_t *hidden_args,
5649     boolean_t force, boolean_t heal, boolean_t resumable, int input_fd,
5650     dmu_replay_record_t *begin_record, uint64_t *read_bytes,
5651     uint64_t *errflags, nvlist_t **errors)
5652 {
5653 	dmu_recv_cookie_t drc;
5654 	int error = 0;
5655 	int props_error = 0;
5656 	offset_t off, noff;
5657 	nvlist_t *local_delayprops = NULL;
5658 	nvlist_t *recv_delayprops = NULL;
5659 	nvlist_t *inherited_delayprops = NULL;
5660 	nvlist_t *origprops = NULL; /* existing properties */
5661 	nvlist_t *origrecvd = NULL; /* existing received properties */
5662 	boolean_t first_recvd_props = B_FALSE;
5663 	boolean_t tofs_was_redacted;
5664 	zfs_file_t *input_fp;
5665 
5666 	*read_bytes = 0;
5667 	*errflags = 0;
5668 	*errors = fnvlist_alloc();
5669 	off = 0;
5670 
5671 	if ((input_fp = zfs_file_get(input_fd)) == NULL)
5672 		return (SET_ERROR(EBADF));
5673 
5674 	noff = off = zfs_file_off(input_fp);
5675 	error = dmu_recv_begin(tofs, tosnap, begin_record, force, heal,
5676 	    resumable, localprops, hidden_args, origin, &drc, input_fp,
5677 	    &off);
5678 	if (error != 0)
5679 		goto out;
5680 	tofs_was_redacted = dsl_get_redacted(drc.drc_ds);
5681 
5682 	/*
5683 	 * Set properties before we receive the stream so that they are applied
5684 	 * to the new data. Note that we must call dmu_recv_stream() if
5685 	 * dmu_recv_begin() succeeds.
5686 	 */
5687 	if (recvprops != NULL && !drc.drc_newfs) {
5688 		if (spa_version(dsl_dataset_get_spa(drc.drc_ds)) >=
5689 		    SPA_VERSION_RECVD_PROPS &&
5690 		    !dsl_prop_get_hasrecvd(tofs))
5691 			first_recvd_props = B_TRUE;
5692 
5693 		/*
5694 		 * If new received properties are supplied, they are to
5695 		 * completely replace the existing received properties,
5696 		 * so stash away the existing ones.
5697 		 */
5698 		if (dsl_prop_get_received(tofs, &origrecvd) == 0) {
5699 			nvlist_t *errlist = NULL;
5700 			/*
5701 			 * Don't bother writing a property if its value won't
5702 			 * change (and avoid the unnecessary security checks).
5703 			 *
5704 			 * The first receive after SPA_VERSION_RECVD_PROPS is a
5705 			 * special case where we blow away all local properties
5706 			 * regardless.
5707 			 */
5708 			if (!first_recvd_props)
5709 				props_reduce(recvprops, origrecvd);
5710 			if (zfs_check_clearable(tofs, origrecvd, &errlist) != 0)
5711 				(void) nvlist_merge(*errors, errlist, 0);
5712 			nvlist_free(errlist);
5713 
5714 			if (clear_received_props(tofs, origrecvd,
5715 			    first_recvd_props ? NULL : recvprops) != 0)
5716 				*errflags |= ZPROP_ERR_NOCLEAR;
5717 		} else {
5718 			*errflags |= ZPROP_ERR_NOCLEAR;
5719 		}
5720 	}
5721 
5722 	/*
5723 	 * Stash away existing properties so we can restore them on error unless
5724 	 * we're doing the first receive after SPA_VERSION_RECVD_PROPS, in which
5725 	 * case "origrecvd" will take care of that.
5726 	 */
5727 	if (localprops != NULL && !drc.drc_newfs && !first_recvd_props) {
5728 		objset_t *os;
5729 		if (dmu_objset_hold(tofs, FTAG, &os) == 0) {
5730 			if (dsl_prop_get_all(os, &origprops) != 0) {
5731 				*errflags |= ZPROP_ERR_NOCLEAR;
5732 			}
5733 			dmu_objset_rele(os, FTAG);
5734 		} else {
5735 			*errflags |= ZPROP_ERR_NOCLEAR;
5736 		}
5737 	}
5738 
5739 	if (recvprops != NULL) {
5740 		props_error = dsl_prop_set_hasrecvd(tofs);
5741 
5742 		if (props_error == 0) {
5743 			recv_delayprops = extract_delay_props(recvprops);
5744 			(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
5745 			    recvprops, *errors);
5746 		}
5747 	}
5748 
5749 	if (localprops != NULL) {
5750 		nvlist_t *oprops = fnvlist_alloc();
5751 		nvlist_t *xprops = fnvlist_alloc();
5752 		nvpair_t *nvp = NULL;
5753 
5754 		while ((nvp = nvlist_next_nvpair(localprops, nvp)) != NULL) {
5755 			if (nvpair_type(nvp) == DATA_TYPE_BOOLEAN) {
5756 				/* -x property */
5757 				const char *name = nvpair_name(nvp);
5758 				zfs_prop_t prop = zfs_name_to_prop(name);
5759 				if (prop != ZPROP_USERPROP) {
5760 					if (!zfs_prop_inheritable(prop))
5761 						continue;
5762 				} else if (!zfs_prop_user(name))
5763 					continue;
5764 				fnvlist_add_boolean(xprops, name);
5765 			} else {
5766 				/* -o property=value */
5767 				fnvlist_add_nvpair(oprops, nvp);
5768 			}
5769 		}
5770 
5771 		local_delayprops = extract_delay_props(oprops);
5772 		(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_LOCAL,
5773 		    oprops, *errors);
5774 		inherited_delayprops = extract_delay_props(xprops);
5775 		(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_INHERITED,
5776 		    xprops, *errors);
5777 
5778 		nvlist_free(oprops);
5779 		nvlist_free(xprops);
5780 	}
5781 
5782 	error = dmu_recv_stream(&drc, &off);
5783 
5784 	if (error == 0) {
5785 		zfsvfs_t *zfsvfs = NULL;
5786 		zvol_state_handle_t *zv = NULL;
5787 
5788 		if (getzfsvfs(tofs, &zfsvfs) == 0) {
5789 			/* online recv */
5790 			dsl_dataset_t *ds;
5791 			int end_err;
5792 			boolean_t stream_is_redacted = DMU_GET_FEATUREFLAGS(
5793 			    begin_record->drr_u.drr_begin.
5794 			    drr_versioninfo) & DMU_BACKUP_FEATURE_REDACTED;
5795 
5796 			ds = dmu_objset_ds(zfsvfs->z_os);
5797 			error = zfs_suspend_fs(zfsvfs);
5798 			/*
5799 			 * If the suspend fails, then the recv_end will
5800 			 * likely also fail, and clean up after itself.
5801 			 */
5802 			end_err = dmu_recv_end(&drc, zfsvfs);
5803 			/*
5804 			 * If the dataset was not redacted, but we received a
5805 			 * redacted stream onto it, we need to unmount the
5806 			 * dataset.  Otherwise, resume the filesystem.
5807 			 */
5808 			if (error == 0 && !drc.drc_newfs &&
5809 			    stream_is_redacted && !tofs_was_redacted) {
5810 				error = zfs_end_fs(zfsvfs, ds);
5811 			} else if (error == 0) {
5812 				error = zfs_resume_fs(zfsvfs, ds);
5813 			}
5814 			error = error ? error : end_err;
5815 			zfs_vfs_rele(zfsvfs);
5816 		} else if (zvol_suspend(tofs, &zv) == 0) {
5817 			error = dmu_recv_end(&drc, zvol_tag(zv));
5818 			zvol_resume(zv);
5819 		} else {
5820 			error = dmu_recv_end(&drc, NULL);
5821 		}
5822 
5823 		/* Set delayed properties now, after we're done receiving. */
5824 		if (recv_delayprops != NULL && error == 0) {
5825 			(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
5826 			    recv_delayprops, *errors);
5827 		}
5828 		if (local_delayprops != NULL && error == 0) {
5829 			(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_LOCAL,
5830 			    local_delayprops, *errors);
5831 		}
5832 		if (inherited_delayprops != NULL && error == 0) {
5833 			(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_INHERITED,
5834 			    inherited_delayprops, *errors);
5835 		}
5836 	}
5837 
5838 	/*
5839 	 * Merge delayed props back in with initial props, in case
5840 	 * we're DEBUG and zfs_ioc_recv_inject_err is set (which means
5841 	 * we have to make sure clear_received_props() includes
5842 	 * the delayed properties).
5843 	 *
5844 	 * Since zfs_ioc_recv_inject_err is only in DEBUG kernels,
5845 	 * using ASSERT() will be just like a VERIFY.
5846 	 */
5847 	if (recv_delayprops != NULL) {
5848 		ASSERT0(nvlist_merge(recvprops, recv_delayprops, 0));
5849 		nvlist_free(recv_delayprops);
5850 	}
5851 	if (local_delayprops != NULL) {
5852 		ASSERT0(nvlist_merge(localprops, local_delayprops, 0));
5853 		nvlist_free(local_delayprops);
5854 	}
5855 	if (inherited_delayprops != NULL) {
5856 		ASSERT0(nvlist_merge(localprops, inherited_delayprops, 0));
5857 		nvlist_free(inherited_delayprops);
5858 	}
5859 	*read_bytes = off - noff;
5860 
5861 #ifdef	ZFS_DEBUG
5862 	if (zfs_ioc_recv_inject_err) {
5863 		zfs_ioc_recv_inject_err = B_FALSE;
5864 		error = 1;
5865 	}
5866 #endif
5867 
5868 	/*
5869 	 * On error, restore the original props.
5870 	 */
5871 	if (error != 0 && recvprops != NULL && !drc.drc_newfs) {
5872 		if (clear_received_props(tofs, recvprops, NULL) != 0) {
5873 			/*
5874 			 * We failed to clear the received properties.
5875 			 * Since we may have left a $recvd value on the
5876 			 * system, we can't clear the $hasrecvd flag.
5877 			 */
5878 			*errflags |= ZPROP_ERR_NORESTORE;
5879 		} else if (first_recvd_props) {
5880 			dsl_prop_unset_hasrecvd(tofs);
5881 		}
5882 
5883 		if (origrecvd == NULL && !drc.drc_newfs) {
5884 			/* We failed to stash the original properties. */
5885 			*errflags |= ZPROP_ERR_NORESTORE;
5886 		}
5887 
5888 		/*
5889 		 * dsl_props_set() will not convert RECEIVED to LOCAL on or
5890 		 * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
5891 		 * explicitly if we're restoring local properties cleared in the
5892 		 * first new-style receive.
5893 		 */
5894 		if (origrecvd != NULL &&
5895 		    zfs_set_prop_nvlist(tofs, (first_recvd_props ?
5896 		    ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
5897 		    origrecvd, NULL) != 0) {
5898 			/*
5899 			 * We stashed the original properties but failed to
5900 			 * restore them.
5901 			 */
5902 			*errflags |= ZPROP_ERR_NORESTORE;
5903 		}
5904 	}
5905 	if (error != 0 && localprops != NULL && !drc.drc_newfs &&
5906 	    !first_recvd_props) {
5907 		nvlist_t *setprops;
5908 		nvlist_t *inheritprops;
5909 		nvpair_t *nvp;
5910 
5911 		if (origprops == NULL) {
5912 			/* We failed to stash the original properties. */
5913 			*errflags |= ZPROP_ERR_NORESTORE;
5914 			goto out;
5915 		}
5916 
5917 		/* Restore original props */
5918 		setprops = fnvlist_alloc();
5919 		inheritprops = fnvlist_alloc();
5920 		nvp = NULL;
5921 		while ((nvp = nvlist_next_nvpair(localprops, nvp)) != NULL) {
5922 			const char *name = nvpair_name(nvp);
5923 			const char *source;
5924 			nvlist_t *attrs;
5925 
5926 			if (!nvlist_exists(origprops, name)) {
5927 				/*
5928 				 * Property was not present or was explicitly
5929 				 * inherited before the receive, restore this.
5930 				 */
5931 				fnvlist_add_boolean(inheritprops, name);
5932 				continue;
5933 			}
5934 			attrs = fnvlist_lookup_nvlist(origprops, name);
5935 			source = fnvlist_lookup_string(attrs, ZPROP_SOURCE);
5936 
5937 			/* Skip received properties */
5938 			if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0)
5939 				continue;
5940 
5941 			if (strcmp(source, tofs) == 0) {
5942 				/* Property was locally set */
5943 				fnvlist_add_nvlist(setprops, name, attrs);
5944 			} else {
5945 				/* Property was implicitly inherited */
5946 				fnvlist_add_boolean(inheritprops, name);
5947 			}
5948 		}
5949 
5950 		if (zfs_set_prop_nvlist(tofs, ZPROP_SRC_LOCAL, setprops,
5951 		    NULL) != 0)
5952 			*errflags |= ZPROP_ERR_NORESTORE;
5953 		if (zfs_set_prop_nvlist(tofs, ZPROP_SRC_INHERITED, inheritprops,
5954 		    NULL) != 0)
5955 			*errflags |= ZPROP_ERR_NORESTORE;
5956 
5957 		nvlist_free(setprops);
5958 		nvlist_free(inheritprops);
5959 	}
5960 out:
5961 	zfs_file_put(input_fp);
5962 	nvlist_free(origrecvd);
5963 	nvlist_free(origprops);
5964 
5965 	if (error == 0)
5966 		error = props_error;
5967 
5968 	return (error);
5969 }
5970 
5971 /*
5972  * inputs:
5973  * zc_name		name of containing filesystem (unused)
5974  * zc_nvlist_src{_size}	nvlist of properties to apply
5975  * zc_nvlist_conf{_size}	nvlist of properties to exclude
5976  *			(DATA_TYPE_BOOLEAN) and override (everything else)
5977  * zc_value		name of snapshot to create
5978  * zc_string		name of clone origin (if DRR_FLAG_CLONE)
5979  * zc_cookie		file descriptor to recv from
5980  * zc_begin_record	the BEGIN record of the stream (not byteswapped)
5981  * zc_guid		force flag
5982  *
5983  * outputs:
5984  * zc_cookie		number of bytes read
5985  * zc_obj		zprop_errflags_t
5986  * zc_nvlist_dst{_size} error for each unapplied received property
5987  */
5988 static int
zfs_ioc_recv(zfs_cmd_t * zc)5989 zfs_ioc_recv(zfs_cmd_t *zc)
5990 {
5991 	dmu_replay_record_t begin_record;
5992 	nvlist_t *errors = NULL;
5993 	nvlist_t *recvdprops = NULL;
5994 	nvlist_t *localprops = NULL;
5995 	const char *origin = NULL;
5996 	char *tosnap;
5997 	char tofs[ZFS_MAX_DATASET_NAME_LEN];
5998 	int error = 0;
5999 
6000 	if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
6001 	    strchr(zc->zc_value, '@') == NULL ||
6002 	    strchr(zc->zc_value, '%') != NULL) {
6003 		return (SET_ERROR(EINVAL));
6004 	}
6005 
6006 	(void) strlcpy(tofs, zc->zc_value, sizeof (tofs));
6007 	tosnap = strchr(tofs, '@');
6008 	*tosnap++ = '\0';
6009 
6010 	if (zc->zc_nvlist_src != 0 &&
6011 	    (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
6012 	    zc->zc_iflags, &recvdprops)) != 0) {
6013 		goto out;
6014 	}
6015 
6016 	if (zc->zc_nvlist_conf != 0 &&
6017 	    (error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
6018 	    zc->zc_iflags, &localprops)) != 0) {
6019 		goto out;
6020 	}
6021 
6022 	if (zc->zc_string[0])
6023 		origin = zc->zc_string;
6024 
6025 	begin_record.drr_type = DRR_BEGIN;
6026 	begin_record.drr_payloadlen = 0;
6027 	begin_record.drr_u.drr_begin = zc->zc_begin_record;
6028 
6029 	error = zfs_ioc_recv_impl(tofs, tosnap, origin, recvdprops, localprops,
6030 	    NULL, zc->zc_guid, B_FALSE, B_FALSE, zc->zc_cookie, &begin_record,
6031 	    &zc->zc_cookie, &zc->zc_obj, &errors);
6032 
6033 	/*
6034 	 * Now that all props, initial and delayed, are set, report the prop
6035 	 * errors to the caller.
6036 	 */
6037 	if (zc->zc_nvlist_dst_size != 0 && errors != NULL &&
6038 	    (nvlist_smush(errors, zc->zc_nvlist_dst_size) != 0 ||
6039 	    put_nvlist(zc, errors) != 0)) {
6040 		/*
6041 		 * Caller made zc->zc_nvlist_dst less than the minimum expected
6042 		 * size or supplied an invalid address.
6043 		 */
6044 		error = SET_ERROR(EINVAL);
6045 	}
6046 
6047 out:
6048 	nvlist_free(errors);
6049 	nvlist_free(recvdprops);
6050 	nvlist_free(localprops);
6051 
6052 	return (error);
6053 }
6054 
6055 /*
6056  * innvl: {
6057  *     "snapname" -> full name of the snapshot to create
6058  *     (optional) "props" -> received properties to set (nvlist)
6059  *     (optional) "localprops" -> override and exclude properties (nvlist)
6060  *     (optional) "origin" -> name of clone origin (DRR_FLAG_CLONE)
6061  *     "begin_record" -> non-byteswapped dmu_replay_record_t
6062  *     "input_fd" -> file descriptor to read stream from (int32)
6063  *     (optional) "force" -> force flag (value ignored)
6064  *     (optional) "heal" -> use send stream to heal data corruption
6065  *     (optional) "resumable" -> resumable flag (value ignored)
6066  *     (optional) "cleanup_fd" -> unused
6067  *     (optional) "action_handle" -> unused
6068  *     (optional) "hidden_args" -> { "wkeydata" -> value }
6069  * }
6070  *
6071  * outnvl: {
6072  *     "read_bytes" -> number of bytes read
6073  *     "error_flags" -> zprop_errflags_t
6074  *     "errors" -> error for each unapplied received property (nvlist)
6075  * }
6076  */
6077 static const zfs_ioc_key_t zfs_keys_recv_new[] = {
6078 	{"snapname",		DATA_TYPE_STRING,	0},
6079 	{"props",		DATA_TYPE_NVLIST,	ZK_OPTIONAL},
6080 	{"localprops",		DATA_TYPE_NVLIST,	ZK_OPTIONAL},
6081 	{"origin",		DATA_TYPE_STRING,	ZK_OPTIONAL},
6082 	{"begin_record",	DATA_TYPE_BYTE_ARRAY,	0},
6083 	{"input_fd",		DATA_TYPE_INT32,	0},
6084 	{"force",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
6085 	{"heal",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
6086 	{"resumable",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
6087 	{"cleanup_fd",		DATA_TYPE_INT32,	ZK_OPTIONAL},
6088 	{"action_handle",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
6089 	{"hidden_args",		DATA_TYPE_NVLIST,	ZK_OPTIONAL},
6090 };
6091 
6092 static int
zfs_ioc_recv_new(const char * fsname,nvlist_t * innvl,nvlist_t * outnvl)6093 zfs_ioc_recv_new(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
6094 {
6095 	dmu_replay_record_t *begin_record;
6096 	uint_t begin_record_size;
6097 	nvlist_t *errors = NULL;
6098 	nvlist_t *recvprops = NULL;
6099 	nvlist_t *localprops = NULL;
6100 	nvlist_t *hidden_args = NULL;
6101 	const char *snapname;
6102 	const char *origin = NULL;
6103 	char *tosnap;
6104 	char tofs[ZFS_MAX_DATASET_NAME_LEN];
6105 	boolean_t force;
6106 	boolean_t heal;
6107 	boolean_t resumable;
6108 	uint64_t read_bytes = 0;
6109 	uint64_t errflags = 0;
6110 	int input_fd = -1;
6111 	int error;
6112 
6113 	snapname = fnvlist_lookup_string(innvl, "snapname");
6114 
6115 	if (dataset_namecheck(snapname, NULL, NULL) != 0 ||
6116 	    strchr(snapname, '@') == NULL ||
6117 	    strchr(snapname, '%') != NULL) {
6118 		return (SET_ERROR(EINVAL));
6119 	}
6120 
6121 	(void) strlcpy(tofs, snapname, sizeof (tofs));
6122 	tosnap = strchr(tofs, '@');
6123 	*tosnap++ = '\0';
6124 
6125 	error = nvlist_lookup_string(innvl, "origin", &origin);
6126 	if (error && error != ENOENT)
6127 		return (error);
6128 
6129 	error = nvlist_lookup_byte_array(innvl, "begin_record",
6130 	    (uchar_t **)&begin_record, &begin_record_size);
6131 	if (error != 0 || begin_record_size != sizeof (*begin_record))
6132 		return (SET_ERROR(EINVAL));
6133 
6134 	input_fd = fnvlist_lookup_int32(innvl, "input_fd");
6135 
6136 	force = nvlist_exists(innvl, "force");
6137 	heal = nvlist_exists(innvl, "heal");
6138 	resumable = nvlist_exists(innvl, "resumable");
6139 
6140 	/* we still use "props" here for backwards compatibility */
6141 	error = nvlist_lookup_nvlist(innvl, "props", &recvprops);
6142 	if (error && error != ENOENT)
6143 		goto out;
6144 
6145 	error = nvlist_lookup_nvlist(innvl, "localprops", &localprops);
6146 	if (error && error != ENOENT)
6147 		goto out;
6148 
6149 	error = nvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS, &hidden_args);
6150 	if (error && error != ENOENT)
6151 		goto out;
6152 
6153 	error = zfs_ioc_recv_impl(tofs, tosnap, origin, recvprops, localprops,
6154 	    hidden_args, force, heal, resumable, input_fd, begin_record,
6155 	    &read_bytes, &errflags, &errors);
6156 
6157 	fnvlist_add_uint64(outnvl, "read_bytes", read_bytes);
6158 	fnvlist_add_uint64(outnvl, "error_flags", errflags);
6159 	fnvlist_add_nvlist(outnvl, "errors", errors);
6160 
6161 out:
6162 	nvlist_free(errors);
6163 	nvlist_free(recvprops);
6164 	nvlist_free(localprops);
6165 	nvlist_free(hidden_args);
6166 
6167 	return (error);
6168 }
6169 
6170 /*
6171  * When stack space is limited, we write replication stream data to the target
6172  * on a separate taskq thread, to make sure there's enough stack space.
6173  */
6174 #ifndef HAVE_LARGE_STACKS
6175 #define	USE_SEND_TASKQ	1
6176 #endif
6177 
6178 typedef struct dump_bytes_io {
6179 	zfs_file_t	*dbi_fp;
6180 	caddr_t		dbi_buf;
6181 	int		dbi_len;
6182 	int		dbi_err;
6183 } dump_bytes_io_t;
6184 
6185 static void
dump_bytes_cb(void * arg)6186 dump_bytes_cb(void *arg)
6187 {
6188 	dump_bytes_io_t *dbi = (dump_bytes_io_t *)arg;
6189 	zfs_file_t *fp;
6190 	caddr_t buf;
6191 
6192 	fp = dbi->dbi_fp;
6193 	buf = dbi->dbi_buf;
6194 
6195 	dbi->dbi_err = zfs_file_write(fp, buf, dbi->dbi_len, NULL);
6196 }
6197 
6198 typedef struct dump_bytes_arg {
6199 	zfs_file_t	*dba_fp;
6200 #ifdef USE_SEND_TASKQ
6201 	taskq_t		*dba_tq;
6202 	taskq_ent_t	dba_tqent;
6203 #endif
6204 } dump_bytes_arg_t;
6205 
6206 static int
dump_bytes(objset_t * os,void * buf,int len,void * arg)6207 dump_bytes(objset_t *os, void *buf, int len, void *arg)
6208 {
6209 	dump_bytes_arg_t *dba = (dump_bytes_arg_t *)arg;
6210 	dump_bytes_io_t dbi;
6211 
6212 	dbi.dbi_fp = dba->dba_fp;
6213 	dbi.dbi_buf = buf;
6214 	dbi.dbi_len = len;
6215 
6216 #ifdef USE_SEND_TASKQ
6217 	taskq_dispatch_ent(dba->dba_tq, dump_bytes_cb, &dbi, TQ_SLEEP,
6218 	    &dba->dba_tqent);
6219 	taskq_wait(dba->dba_tq);
6220 #else
6221 	dump_bytes_cb(&dbi);
6222 #endif
6223 
6224 	return (dbi.dbi_err);
6225 }
6226 
6227 static int
dump_bytes_init(dump_bytes_arg_t * dba,int fd,dmu_send_outparams_t * out)6228 dump_bytes_init(dump_bytes_arg_t *dba, int fd, dmu_send_outparams_t *out)
6229 {
6230 	zfs_file_t *fp = zfs_file_get(fd);
6231 	if (fp == NULL)
6232 		return (SET_ERROR(EBADF));
6233 
6234 	dba->dba_fp = fp;
6235 #ifdef USE_SEND_TASKQ
6236 	dba->dba_tq = taskq_create("z_send", 1, defclsyspri, 0, 0, 0);
6237 	taskq_init_ent(&dba->dba_tqent);
6238 #endif
6239 
6240 	memset(out, 0, sizeof (dmu_send_outparams_t));
6241 	out->dso_outfunc = dump_bytes;
6242 	out->dso_arg = dba;
6243 	out->dso_dryrun = B_FALSE;
6244 
6245 	return (0);
6246 }
6247 
6248 static void
dump_bytes_fini(dump_bytes_arg_t * dba)6249 dump_bytes_fini(dump_bytes_arg_t *dba)
6250 {
6251 	zfs_file_put(dba->dba_fp);
6252 #ifdef USE_SEND_TASKQ
6253 	taskq_destroy(dba->dba_tq);
6254 #endif
6255 }
6256 
6257 /*
6258  * inputs:
6259  * zc_name	name of snapshot to send
6260  * zc_cookie	file descriptor to send stream to
6261  * zc_obj	fromorigin flag (mutually exclusive with zc_fromobj)
6262  * zc_sendobj	objsetid of snapshot to send
6263  * zc_fromobj	objsetid of incremental fromsnap (may be zero)
6264  * zc_guid	if set, estimate size of stream only.  zc_cookie is ignored.
6265  *		output size in zc_objset_type.
6266  * zc_flags	lzc_send_flags
6267  *
6268  * outputs:
6269  * zc_objset_type	estimated size, if zc_guid is set
6270  *
6271  * NOTE: This is no longer the preferred interface, any new functionality
6272  *	  should be added to zfs_ioc_send_new() instead.
6273  */
6274 static int
zfs_ioc_send(zfs_cmd_t * zc)6275 zfs_ioc_send(zfs_cmd_t *zc)
6276 {
6277 	int error;
6278 	offset_t off;
6279 	boolean_t estimate = (zc->zc_guid != 0);
6280 	boolean_t embedok = (zc->zc_flags & 0x1);
6281 	boolean_t large_block_ok = (zc->zc_flags & 0x2);
6282 	boolean_t compressok = (zc->zc_flags & 0x4);
6283 	boolean_t rawok = (zc->zc_flags & 0x8);
6284 	boolean_t savedok = (zc->zc_flags & 0x10);
6285 
6286 	if (zc->zc_obj != 0) {
6287 		dsl_pool_t *dp;
6288 		dsl_dataset_t *tosnap;
6289 
6290 		error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
6291 		if (error != 0)
6292 			return (error);
6293 
6294 		error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
6295 		if (error != 0) {
6296 			dsl_pool_rele(dp, FTAG);
6297 			return (error);
6298 		}
6299 
6300 		if (dsl_dir_is_clone(tosnap->ds_dir))
6301 			zc->zc_fromobj =
6302 			    dsl_dir_phys(tosnap->ds_dir)->dd_origin_obj;
6303 		dsl_dataset_rele(tosnap, FTAG);
6304 		dsl_pool_rele(dp, FTAG);
6305 	}
6306 
6307 	if (estimate) {
6308 		dsl_pool_t *dp;
6309 		dsl_dataset_t *tosnap;
6310 		dsl_dataset_t *fromsnap = NULL;
6311 
6312 		error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
6313 		if (error != 0)
6314 			return (error);
6315 
6316 		error = dsl_dataset_hold_obj(dp, zc->zc_sendobj,
6317 		    FTAG, &tosnap);
6318 		if (error != 0) {
6319 			dsl_pool_rele(dp, FTAG);
6320 			return (error);
6321 		}
6322 
6323 		if (zc->zc_fromobj != 0) {
6324 			error = dsl_dataset_hold_obj(dp, zc->zc_fromobj,
6325 			    FTAG, &fromsnap);
6326 			if (error != 0) {
6327 				dsl_dataset_rele(tosnap, FTAG);
6328 				dsl_pool_rele(dp, FTAG);
6329 				return (error);
6330 			}
6331 		}
6332 
6333 		error = dmu_send_estimate_fast(tosnap, fromsnap, NULL,
6334 		    compressok || rawok, savedok, &zc->zc_objset_type);
6335 
6336 		if (fromsnap != NULL)
6337 			dsl_dataset_rele(fromsnap, FTAG);
6338 		dsl_dataset_rele(tosnap, FTAG);
6339 		dsl_pool_rele(dp, FTAG);
6340 	} else {
6341 		dump_bytes_arg_t dba;
6342 		dmu_send_outparams_t out;
6343 		error = dump_bytes_init(&dba, zc->zc_cookie, &out);
6344 		if (error)
6345 			return (error);
6346 
6347 		off = zfs_file_off(dba.dba_fp);
6348 		error = dmu_send_obj(zc->zc_name, zc->zc_sendobj,
6349 		    zc->zc_fromobj, embedok, large_block_ok, compressok,
6350 		    rawok, savedok, zc->zc_cookie, &off, &out);
6351 
6352 		dump_bytes_fini(&dba);
6353 	}
6354 	return (error);
6355 }
6356 
6357 /*
6358  * inputs:
6359  * zc_name		name of snapshot on which to report progress
6360  * zc_cookie		file descriptor of send stream
6361  *
6362  * outputs:
6363  * zc_cookie		number of bytes written in send stream thus far
6364  * zc_objset_type	logical size of data traversed by send thus far
6365  */
6366 static int
zfs_ioc_send_progress(zfs_cmd_t * zc)6367 zfs_ioc_send_progress(zfs_cmd_t *zc)
6368 {
6369 	dsl_pool_t *dp;
6370 	dsl_dataset_t *ds;
6371 	dmu_sendstatus_t *dsp = NULL;
6372 	int error;
6373 
6374 	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
6375 	if (error != 0)
6376 		return (error);
6377 
6378 	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
6379 	if (error != 0) {
6380 		dsl_pool_rele(dp, FTAG);
6381 		return (error);
6382 	}
6383 
6384 	mutex_enter(&ds->ds_sendstream_lock);
6385 
6386 	/*
6387 	 * Iterate over all the send streams currently active on this dataset.
6388 	 * If there's one which matches the specified file descriptor _and_ the
6389 	 * stream was started by the current process, return the progress of
6390 	 * that stream.
6391 	 */
6392 
6393 	for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
6394 	    dsp = list_next(&ds->ds_sendstreams, dsp)) {
6395 		if (dsp->dss_outfd == zc->zc_cookie &&
6396 		    zfs_proc_is_caller(dsp->dss_proc))
6397 			break;
6398 	}
6399 
6400 	if (dsp != NULL) {
6401 		zc->zc_cookie = atomic_cas_64((volatile uint64_t *)dsp->dss_off,
6402 		    0, 0);
6403 		/* This is the closest thing we have to atomic_read_64. */
6404 		zc->zc_objset_type = atomic_cas_64(&dsp->dss_blocks, 0, 0);
6405 	} else {
6406 		error = SET_ERROR(ENOENT);
6407 	}
6408 
6409 	mutex_exit(&ds->ds_sendstream_lock);
6410 	dsl_dataset_rele(ds, FTAG);
6411 	dsl_pool_rele(dp, FTAG);
6412 	return (error);
6413 }
6414 
6415 static int
zfs_ioc_inject_fault(zfs_cmd_t * zc)6416 zfs_ioc_inject_fault(zfs_cmd_t *zc)
6417 {
6418 	int id, error;
6419 
6420 	error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
6421 	    &zc->zc_inject_record);
6422 
6423 	if (error == 0)
6424 		zc->zc_guid = (uint64_t)id;
6425 
6426 	return (error);
6427 }
6428 
6429 static int
zfs_ioc_clear_fault(zfs_cmd_t * zc)6430 zfs_ioc_clear_fault(zfs_cmd_t *zc)
6431 {
6432 	return (zio_clear_fault((int)zc->zc_guid));
6433 }
6434 
6435 static int
zfs_ioc_inject_list_next(zfs_cmd_t * zc)6436 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
6437 {
6438 	int id = (int)zc->zc_guid;
6439 	int error;
6440 
6441 	error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
6442 	    &zc->zc_inject_record);
6443 
6444 	zc->zc_guid = id;
6445 
6446 	return (error);
6447 }
6448 
6449 static int
zfs_ioc_error_log(zfs_cmd_t * zc)6450 zfs_ioc_error_log(zfs_cmd_t *zc)
6451 {
6452 	spa_t *spa;
6453 	int error;
6454 
6455 	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
6456 		return (error);
6457 
6458 	error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
6459 	    &zc->zc_nvlist_dst_size);
6460 
6461 	spa_close(spa, FTAG);
6462 
6463 	return (error);
6464 }
6465 
6466 static int
zfs_ioc_clear(zfs_cmd_t * zc)6467 zfs_ioc_clear(zfs_cmd_t *zc)
6468 {
6469 	spa_t *spa;
6470 	vdev_t *vd;
6471 	int error;
6472 
6473 	/*
6474 	 * On zpool clear we also fix up missing slogs
6475 	 */
6476 	spa_namespace_enter(FTAG);
6477 	spa = spa_lookup(zc->zc_name);
6478 	if (spa == NULL) {
6479 		spa_namespace_exit(FTAG);
6480 		return (SET_ERROR(EIO));
6481 	}
6482 	if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
6483 		/* we need to let spa_open/spa_load clear the chains */
6484 		spa_set_log_state(spa, SPA_LOG_CLEAR);
6485 	}
6486 	spa->spa_last_open_failed = 0;
6487 	spa_namespace_exit(FTAG);
6488 
6489 	if (zc->zc_cookie & ZPOOL_NO_REWIND) {
6490 		error = spa_open(zc->zc_name, &spa, FTAG);
6491 	} else {
6492 		nvlist_t *policy;
6493 		nvlist_t *config = NULL;
6494 
6495 		if (zc->zc_nvlist_src == 0)
6496 			return (SET_ERROR(EINVAL));
6497 
6498 		if ((error = get_nvlist(zc->zc_nvlist_src,
6499 		    zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
6500 			error = spa_open_rewind(zc->zc_name, &spa, FTAG,
6501 			    policy, &config);
6502 			if (config != NULL) {
6503 				int err;
6504 
6505 				if ((err = put_nvlist(zc, config)) != 0)
6506 					error = err;
6507 				nvlist_free(config);
6508 			}
6509 			nvlist_free(policy);
6510 		}
6511 	}
6512 
6513 	if (error != 0)
6514 		return (error);
6515 
6516 	/*
6517 	 * If multihost is enabled, resuming I/O is unsafe as another
6518 	 * host may have imported the pool. Check for remote activity.
6519 	 */
6520 	if (spa_multihost(spa) && spa_suspended(spa) &&
6521 	    spa_mmp_remote_host_activity(spa)) {
6522 		spa_close(spa, FTAG);
6523 		return (SET_ERROR(EREMOTEIO));
6524 	}
6525 
6526 	spa_vdev_state_enter(spa, SCL_NONE);
6527 
6528 	if (zc->zc_guid == 0) {
6529 		vd = NULL;
6530 	} else {
6531 		vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
6532 		if (vd == NULL) {
6533 			error = SET_ERROR(ENODEV);
6534 			(void) spa_vdev_state_exit(spa, NULL, error);
6535 			spa_close(spa, FTAG);
6536 			return (error);
6537 		}
6538 	}
6539 
6540 	vdev_clear(spa, vd);
6541 
6542 	(void) spa_vdev_state_exit(spa, spa_suspended(spa) ?
6543 	    NULL : spa->spa_root_vdev, 0);
6544 
6545 	/*
6546 	 * Resume any suspended I/Os.
6547 	 */
6548 	if (zio_resume(spa) != 0)
6549 		error = SET_ERROR(EIO);
6550 
6551 	spa_close(spa, FTAG);
6552 
6553 	return (error);
6554 }
6555 
6556 /*
6557  * Reopen all the vdevs associated with the pool.
6558  *
6559  * innvl: {
6560  *  "scrub_restart" -> when true and scrub is running, allow to restart
6561  *              scrub as the side effect of the reopen (boolean).
6562  * }
6563  *
6564  * outnvl is unused
6565  */
6566 static const zfs_ioc_key_t zfs_keys_pool_reopen[] = {
6567 	{"scrub_restart",	DATA_TYPE_BOOLEAN_VALUE,	ZK_OPTIONAL},
6568 };
6569 
6570 static int
zfs_ioc_pool_reopen(const char * pool,nvlist_t * innvl,nvlist_t * outnvl)6571 zfs_ioc_pool_reopen(const char *pool, nvlist_t *innvl, nvlist_t *outnvl)
6572 {
6573 	(void) outnvl;
6574 	spa_t *spa;
6575 	int error;
6576 	boolean_t rc, scrub_restart = B_TRUE;
6577 
6578 	if (innvl) {
6579 		error = nvlist_lookup_boolean_value(innvl,
6580 		    "scrub_restart", &rc);
6581 		if (error == 0)
6582 			scrub_restart = rc;
6583 	}
6584 
6585 	error = spa_open(pool, &spa, FTAG);
6586 	if (error != 0)
6587 		return (error);
6588 
6589 	spa_vdev_state_enter(spa, SCL_NONE);
6590 
6591 	/*
6592 	 * If the scrub_restart flag is B_FALSE and a scrub is already
6593 	 * in progress then set spa_scrub_reopen flag to B_TRUE so that
6594 	 * we don't restart the scrub as a side effect of the reopen.
6595 	 * Otherwise, let vdev_open() decided if a resilver is required.
6596 	 */
6597 
6598 	spa->spa_scrub_reopen = (!scrub_restart &&
6599 	    dsl_scan_scrubbing(spa->spa_dsl_pool));
6600 	vdev_reopen(spa->spa_root_vdev);
6601 	spa->spa_scrub_reopen = B_FALSE;
6602 
6603 	(void) spa_vdev_state_exit(spa, NULL, 0);
6604 	spa_close(spa, FTAG);
6605 	return (0);
6606 }
6607 
6608 /*
6609  * inputs:
6610  * zc_name	name of filesystem
6611  *
6612  * outputs:
6613  * zc_string	name of conflicting snapshot, if there is one
6614  */
6615 static int
zfs_ioc_promote(zfs_cmd_t * zc)6616 zfs_ioc_promote(zfs_cmd_t *zc)
6617 {
6618 	dsl_pool_t *dp;
6619 	dsl_dataset_t *ds, *ods;
6620 	char origin[ZFS_MAX_DATASET_NAME_LEN];
6621 	char *cp;
6622 	int error;
6623 
6624 	zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
6625 	if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
6626 	    strchr(zc->zc_name, '%'))
6627 		return (SET_ERROR(EINVAL));
6628 
6629 	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
6630 	if (error != 0)
6631 		return (error);
6632 
6633 	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
6634 	if (error != 0) {
6635 		dsl_pool_rele(dp, FTAG);
6636 		return (error);
6637 	}
6638 
6639 	if (!dsl_dir_is_clone(ds->ds_dir)) {
6640 		dsl_dataset_rele(ds, FTAG);
6641 		dsl_pool_rele(dp, FTAG);
6642 		return (SET_ERROR(EINVAL));
6643 	}
6644 
6645 	error = dsl_dataset_hold_obj(dp,
6646 	    dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &ods);
6647 	if (error != 0) {
6648 		dsl_dataset_rele(ds, FTAG);
6649 		dsl_pool_rele(dp, FTAG);
6650 		return (error);
6651 	}
6652 
6653 	dsl_dataset_name(ods, origin);
6654 	dsl_dataset_rele(ods, FTAG);
6655 	dsl_dataset_rele(ds, FTAG);
6656 	dsl_pool_rele(dp, FTAG);
6657 
6658 	/*
6659 	 * We don't need to unmount *all* the origin fs's snapshots, but
6660 	 * it's easier.
6661 	 */
6662 	cp = strchr(origin, '@');
6663 	if (cp)
6664 		*cp = '\0';
6665 	(void) dmu_objset_find(origin,
6666 	    zfs_unmount_snap_cb, NULL, DS_FIND_SNAPSHOTS);
6667 	return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
6668 }
6669 
6670 /*
6671  * Retrieve a single {user|group|project}{used|quota}@... property.
6672  *
6673  * inputs:
6674  * zc_name	name of filesystem
6675  * zc_objset_type zfs_userquota_prop_t
6676  * zc_value	domain name (eg. "S-1-234-567-89")
6677  * zc_guid	RID/UID/GID
6678  *
6679  * outputs:
6680  * zc_cookie	property value
6681  */
6682 static int
zfs_ioc_userspace_one(zfs_cmd_t * zc)6683 zfs_ioc_userspace_one(zfs_cmd_t *zc)
6684 {
6685 	zfsvfs_t *zfsvfs;
6686 	int error;
6687 
6688 	if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
6689 		return (SET_ERROR(EINVAL));
6690 
6691 	error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
6692 	if (error != 0)
6693 		return (error);
6694 
6695 	error = zfs_userspace_one(zfsvfs,
6696 	    zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
6697 	zfsvfs_rele(zfsvfs, FTAG);
6698 
6699 	return (error);
6700 }
6701 
6702 /*
6703  * inputs:
6704  * zc_name		name of filesystem
6705  * zc_cookie		zap cursor
6706  * zc_objset_type	zfs_userquota_prop_t
6707  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
6708  *
6709  * outputs:
6710  * zc_nvlist_dst[_size]	data buffer (array of zfs_useracct_t)
6711  * zc_cookie	zap cursor
6712  *
6713  * The zc_nvlist_dst output array is limited to 1000 entries.
6714  */
6715 static int
zfs_ioc_userspace_many(zfs_cmd_t * zc)6716 zfs_ioc_userspace_many(zfs_cmd_t *zc)
6717 {
6718 	const size_t batch_limit = 1000 * sizeof (zfs_useracct_t);
6719 	uint64_t bufsize = MIN(zc->zc_nvlist_dst_size, batch_limit);
6720 	zfsvfs_t *zfsvfs;
6721 
6722 	if (bufsize < sizeof (zfs_useracct_t)) {
6723 		zc->zc_nvlist_dst_size = sizeof (zfs_useracct_t);
6724 		return (SET_ERROR(ENOMEM));
6725 	}
6726 
6727 	int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
6728 	if (error != 0)
6729 		return (error);
6730 
6731 	void *buf = vmem_alloc(bufsize, KM_SLEEP);
6732 	zc->zc_nvlist_dst_size = bufsize;
6733 
6734 	error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
6735 	    buf, &zc->zc_nvlist_dst_size, &zc->zc_guid);
6736 
6737 	if (error == 0) {
6738 		error = xcopyout(buf,
6739 		    (void *)(uintptr_t)zc->zc_nvlist_dst,
6740 		    zc->zc_nvlist_dst_size);
6741 	}
6742 	vmem_free(buf, bufsize);
6743 	zfsvfs_rele(zfsvfs, FTAG);
6744 
6745 	return (error);
6746 }
6747 
6748 /*
6749  * inputs:
6750  * zc_name		name of filesystem
6751  *
6752  * outputs:
6753  * none
6754  */
6755 static int
zfs_ioc_userspace_upgrade(zfs_cmd_t * zc)6756 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
6757 {
6758 	int error = 0;
6759 	zfsvfs_t *zfsvfs;
6760 
6761 	if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
6762 		if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
6763 			/*
6764 			 * If userused is not enabled, it may be because the
6765 			 * objset needs to be closed & reopened (to grow the
6766 			 * objset_phys_t).  Suspend/resume the fs will do that.
6767 			 */
6768 			dsl_dataset_t *ds, *newds;
6769 
6770 			ds = dmu_objset_ds(zfsvfs->z_os);
6771 			error = zfs_suspend_fs(zfsvfs);
6772 			if (error == 0) {
6773 				dmu_objset_refresh_ownership(ds, &newds,
6774 				    B_TRUE, zfsvfs);
6775 				error = zfs_resume_fs(zfsvfs, newds);
6776 			}
6777 		}
6778 		if (error == 0) {
6779 			mutex_enter(&zfsvfs->z_os->os_upgrade_lock);
6780 			if (zfsvfs->z_os->os_upgrade_id == 0) {
6781 				/* clear potential error code and retry */
6782 				zfsvfs->z_os->os_upgrade_status = 0;
6783 				mutex_exit(&zfsvfs->z_os->os_upgrade_lock);
6784 
6785 				dsl_pool_config_enter(
6786 				    dmu_objset_pool(zfsvfs->z_os), FTAG);
6787 				dmu_objset_userspace_upgrade(zfsvfs->z_os);
6788 				dsl_pool_config_exit(
6789 				    dmu_objset_pool(zfsvfs->z_os), FTAG);
6790 			} else {
6791 				mutex_exit(&zfsvfs->z_os->os_upgrade_lock);
6792 			}
6793 
6794 			taskq_wait_id(zfsvfs->z_os->os_spa->spa_upgrade_taskq,
6795 			    zfsvfs->z_os->os_upgrade_id);
6796 			error = zfsvfs->z_os->os_upgrade_status;
6797 		}
6798 		zfs_vfs_rele(zfsvfs);
6799 	} else {
6800 		objset_t *os;
6801 
6802 		/* XXX kind of reading contents without owning */
6803 		error = dmu_objset_hold_flags(zc->zc_name, B_TRUE, FTAG, &os);
6804 		if (error != 0)
6805 			return (error);
6806 
6807 		mutex_enter(&os->os_upgrade_lock);
6808 		if (os->os_upgrade_id == 0) {
6809 			/* clear potential error code and retry */
6810 			os->os_upgrade_status = 0;
6811 			mutex_exit(&os->os_upgrade_lock);
6812 
6813 			dmu_objset_userspace_upgrade(os);
6814 		} else {
6815 			mutex_exit(&os->os_upgrade_lock);
6816 		}
6817 
6818 		dsl_pool_rele(dmu_objset_pool(os), FTAG);
6819 
6820 		taskq_wait_id(os->os_spa->spa_upgrade_taskq, os->os_upgrade_id);
6821 		error = os->os_upgrade_status;
6822 
6823 		dsl_dataset_rele_flags(dmu_objset_ds(os), DS_HOLD_FLAG_DECRYPT,
6824 		    FTAG);
6825 	}
6826 	return (error);
6827 }
6828 
6829 /*
6830  * inputs:
6831  * zc_name		name of filesystem
6832  *
6833  * outputs:
6834  * none
6835  */
6836 static int
zfs_ioc_id_quota_upgrade(zfs_cmd_t * zc)6837 zfs_ioc_id_quota_upgrade(zfs_cmd_t *zc)
6838 {
6839 	objset_t *os;
6840 	int error;
6841 
6842 	error = dmu_objset_hold_flags(zc->zc_name, B_TRUE, FTAG, &os);
6843 	if (error != 0)
6844 		return (error);
6845 
6846 	if (dmu_objset_userobjspace_upgradable(os) ||
6847 	    dmu_objset_projectquota_upgradable(os)) {
6848 		mutex_enter(&os->os_upgrade_lock);
6849 		if (os->os_upgrade_id == 0) {
6850 			/* clear potential error code and retry */
6851 			os->os_upgrade_status = 0;
6852 			mutex_exit(&os->os_upgrade_lock);
6853 
6854 			dmu_objset_id_quota_upgrade(os);
6855 		} else {
6856 			mutex_exit(&os->os_upgrade_lock);
6857 		}
6858 
6859 		dsl_pool_rele(dmu_objset_pool(os), FTAG);
6860 
6861 		taskq_wait_id(os->os_spa->spa_upgrade_taskq, os->os_upgrade_id);
6862 		error = os->os_upgrade_status;
6863 	} else {
6864 		dsl_pool_rele(dmu_objset_pool(os), FTAG);
6865 	}
6866 
6867 	dsl_dataset_rele_flags(dmu_objset_ds(os), DS_HOLD_FLAG_DECRYPT, FTAG);
6868 
6869 	return (error);
6870 }
6871 
6872 static int
zfs_ioc_share(zfs_cmd_t * zc)6873 zfs_ioc_share(zfs_cmd_t *zc)
6874 {
6875 	return (SET_ERROR(ENOSYS));
6876 }
6877 
6878 /*
6879  * inputs:
6880  * zc_name		name of containing filesystem
6881  * zc_obj		object # beyond which we want next in-use object #
6882  *
6883  * outputs:
6884  * zc_obj		next in-use object #
6885  */
6886 static int
zfs_ioc_next_obj(zfs_cmd_t * zc)6887 zfs_ioc_next_obj(zfs_cmd_t *zc)
6888 {
6889 	objset_t *os = NULL;
6890 	int error;
6891 
6892 	error = dmu_objset_hold(zc->zc_name, FTAG, &os);
6893 	if (error != 0)
6894 		return (error);
6895 
6896 	error = dmu_object_next(os, &zc->zc_obj, B_FALSE, 0);
6897 
6898 	dmu_objset_rele(os, FTAG);
6899 	return (error);
6900 }
6901 
6902 /*
6903  * inputs:
6904  * zc_name		name of filesystem
6905  * zc_value		prefix name for snapshot
6906  * zc_cleanup_fd	cleanup-on-exit file descriptor for calling process
6907  *
6908  * outputs:
6909  * zc_value		short name of new snapshot
6910  */
6911 static int
zfs_ioc_tmp_snapshot(zfs_cmd_t * zc)6912 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
6913 {
6914 	char *snap_name;
6915 	char *hold_name;
6916 	minor_t minor;
6917 
6918 	zfs_file_t *fp = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
6919 	if (fp == NULL)
6920 		return (SET_ERROR(EBADF));
6921 
6922 	snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
6923 	    (u_longlong_t)ddi_get_lbolt64());
6924 	hold_name = kmem_asprintf("%%%s", zc->zc_value);
6925 
6926 	int error = dsl_dataset_snapshot_tmp(zc->zc_name, snap_name, minor,
6927 	    hold_name);
6928 	if (error == 0)
6929 		(void) strlcpy(zc->zc_value, snap_name,
6930 		    sizeof (zc->zc_value));
6931 	kmem_strfree(snap_name);
6932 	kmem_strfree(hold_name);
6933 	zfs_onexit_fd_rele(fp);
6934 	return (error);
6935 }
6936 
6937 /*
6938  * inputs:
6939  * zc_name		name of "to" snapshot
6940  * zc_value		name of "from" snapshot
6941  * zc_cookie		file descriptor to write diff data on
6942  *
6943  * outputs:
6944  * dmu_diff_record_t's to the file descriptor
6945  */
6946 static int
zfs_ioc_diff(zfs_cmd_t * zc)6947 zfs_ioc_diff(zfs_cmd_t *zc)
6948 {
6949 	zfs_file_t *fp;
6950 	offset_t off;
6951 	int error;
6952 
6953 	if ((fp = zfs_file_get(zc->zc_cookie)) == NULL)
6954 		return (SET_ERROR(EBADF));
6955 
6956 	off = zfs_file_off(fp);
6957 	error = dmu_diff(zc->zc_name, zc->zc_value, fp, &off);
6958 
6959 	zfs_file_put(fp);
6960 
6961 	return (error);
6962 }
6963 
6964 static int
zfs_ioc_smb_acl(zfs_cmd_t * zc)6965 zfs_ioc_smb_acl(zfs_cmd_t *zc)
6966 {
6967 	return (SET_ERROR(ENOTSUP));
6968 }
6969 
6970 /*
6971  * innvl: {
6972  *     "holds" -> { snapname -> holdname (string), ... }
6973  *     (optional) "cleanup_fd" -> fd (int32)
6974  * }
6975  *
6976  * outnvl: {
6977  *     snapname -> error value (int32)
6978  *     ...
6979  * }
6980  */
6981 static const zfs_ioc_key_t zfs_keys_hold[] = {
6982 	{"holds",		DATA_TYPE_NVLIST,	0},
6983 	{"cleanup_fd",		DATA_TYPE_INT32,	ZK_OPTIONAL},
6984 };
6985 
6986 static int
zfs_ioc_hold(const char * pool,nvlist_t * args,nvlist_t * errlist)6987 zfs_ioc_hold(const char *pool, nvlist_t *args, nvlist_t *errlist)
6988 {
6989 	(void) pool;
6990 	nvpair_t *pair;
6991 	nvlist_t *holds;
6992 	int cleanup_fd = -1;
6993 	int error;
6994 	minor_t minor = 0;
6995 	zfs_file_t *fp = NULL;
6996 
6997 	holds = fnvlist_lookup_nvlist(args, "holds");
6998 
6999 	/* make sure the user didn't pass us any invalid (empty) tags */
7000 	for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
7001 	    pair = nvlist_next_nvpair(holds, pair)) {
7002 		const char *htag;
7003 
7004 		error = nvpair_value_string(pair, &htag);
7005 		if (error != 0)
7006 			return (SET_ERROR(error));
7007 
7008 		if (strlen(htag) == 0)
7009 			return (SET_ERROR(EINVAL));
7010 	}
7011 
7012 	if (nvlist_lookup_int32(args, "cleanup_fd", &cleanup_fd) == 0) {
7013 		fp = zfs_onexit_fd_hold(cleanup_fd, &minor);
7014 		if (fp == NULL)
7015 			return (SET_ERROR(EBADF));
7016 	}
7017 
7018 	error = dsl_dataset_user_hold(holds, minor, errlist);
7019 	if (fp != NULL) {
7020 		ASSERT3U(minor, !=, 0);
7021 		zfs_onexit_fd_rele(fp);
7022 	}
7023 	return (SET_ERROR(error));
7024 }
7025 
7026 /*
7027  * innvl is not used.
7028  *
7029  * outnvl: {
7030  *    holdname -> time added (uint64 seconds since epoch)
7031  *    ...
7032  * }
7033  */
7034 static const zfs_ioc_key_t zfs_keys_get_holds[] = {
7035 	/* no nvl keys */
7036 };
7037 
7038 static int
zfs_ioc_get_holds(const char * snapname,nvlist_t * args,nvlist_t * outnvl)7039 zfs_ioc_get_holds(const char *snapname, nvlist_t *args, nvlist_t *outnvl)
7040 {
7041 	(void) args;
7042 	return (dsl_dataset_get_holds(snapname, outnvl));
7043 }
7044 
7045 /*
7046  * innvl: {
7047  *     snapname -> { holdname, ... }
7048  *     ...
7049  * }
7050  *
7051  * outnvl: {
7052  *     snapname -> error value (int32)
7053  *     ...
7054  * }
7055  */
7056 static const zfs_ioc_key_t zfs_keys_release[] = {
7057 	{"<snapname>...",	DATA_TYPE_NVLIST,	ZK_WILDCARDLIST},
7058 };
7059 
7060 static int
zfs_ioc_release(const char * pool,nvlist_t * holds,nvlist_t * errlist)7061 zfs_ioc_release(const char *pool, nvlist_t *holds, nvlist_t *errlist)
7062 {
7063 	(void) pool;
7064 	return (dsl_dataset_user_release(holds, errlist));
7065 }
7066 
7067 /*
7068  * inputs:
7069  * zc_guid		flags (ZEVENT_NONBLOCK)
7070  * zc_cleanup_fd	zevent file descriptor
7071  *
7072  * outputs:
7073  * zc_nvlist_dst	next nvlist event
7074  * zc_cookie		dropped events since last get
7075  */
7076 static int
zfs_ioc_events_next(zfs_cmd_t * zc)7077 zfs_ioc_events_next(zfs_cmd_t *zc)
7078 {
7079 	zfs_zevent_t *ze;
7080 	nvlist_t *event = NULL;
7081 	minor_t minor;
7082 	uint64_t dropped = 0;
7083 	int error;
7084 
7085 	zfs_file_t *fp = zfs_zevent_fd_hold(zc->zc_cleanup_fd, &minor, &ze);
7086 	if (fp == NULL)
7087 		return (SET_ERROR(EBADF));
7088 
7089 	do {
7090 		error = zfs_zevent_next(ze, &event,
7091 		    &zc->zc_nvlist_dst_size, &dropped);
7092 		if (event != NULL) {
7093 			zc->zc_cookie = dropped;
7094 			error = put_nvlist(zc, event);
7095 			nvlist_free(event);
7096 		}
7097 
7098 		if (zc->zc_guid & ZEVENT_NONBLOCK)
7099 			break;
7100 
7101 		if ((error == 0) || (error != ENOENT))
7102 			break;
7103 
7104 		error = zfs_zevent_wait(ze);
7105 		if (error != 0)
7106 			break;
7107 	} while (1);
7108 
7109 	zfs_zevent_fd_rele(fp);
7110 
7111 	return (error);
7112 }
7113 
7114 /*
7115  * outputs:
7116  * zc_cookie		cleared events count
7117  */
7118 static int
zfs_ioc_events_clear(zfs_cmd_t * zc)7119 zfs_ioc_events_clear(zfs_cmd_t *zc)
7120 {
7121 	uint_t count;
7122 
7123 	zfs_zevent_drain_all(&count);
7124 	zc->zc_cookie = count;
7125 
7126 	return (0);
7127 }
7128 
7129 /*
7130  * inputs:
7131  * zc_guid		eid | ZEVENT_SEEK_START | ZEVENT_SEEK_END
7132  * zc_cleanup		zevent file descriptor
7133  */
7134 static int
zfs_ioc_events_seek(zfs_cmd_t * zc)7135 zfs_ioc_events_seek(zfs_cmd_t *zc)
7136 {
7137 	zfs_zevent_t *ze;
7138 	minor_t minor;
7139 	int error;
7140 
7141 	zfs_file_t *fp = zfs_zevent_fd_hold(zc->zc_cleanup_fd, &minor, &ze);
7142 	if (fp == NULL)
7143 		return (SET_ERROR(EBADF));
7144 
7145 	error = zfs_zevent_seek(ze, zc->zc_guid);
7146 	zfs_zevent_fd_rele(fp);
7147 
7148 	return (error);
7149 }
7150 
7151 /*
7152  * inputs:
7153  * zc_name		name of later filesystem or snapshot
7154  * zc_value		full name of old snapshot or bookmark
7155  *
7156  * outputs:
7157  * zc_cookie		space in bytes
7158  * zc_objset_type	compressed space in bytes
7159  * zc_perm_action	uncompressed space in bytes
7160  */
7161 static int
zfs_ioc_space_written(zfs_cmd_t * zc)7162 zfs_ioc_space_written(zfs_cmd_t *zc)
7163 {
7164 	int error;
7165 	dsl_pool_t *dp;
7166 	dsl_dataset_t *new;
7167 
7168 	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
7169 	if (error != 0)
7170 		return (error);
7171 	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &new);
7172 	if (error != 0) {
7173 		dsl_pool_rele(dp, FTAG);
7174 		return (error);
7175 	}
7176 	if (strchr(zc->zc_value, '#') != NULL) {
7177 		zfs_bookmark_phys_t bmp;
7178 		error = dsl_bookmark_lookup(dp, zc->zc_value,
7179 		    new, &bmp);
7180 		if (error == 0) {
7181 			error = dsl_dataset_space_written_bookmark(&bmp, new,
7182 			    &zc->zc_cookie,
7183 			    &zc->zc_objset_type, &zc->zc_perm_action);
7184 		}
7185 	} else {
7186 		dsl_dataset_t *old;
7187 		error = dsl_dataset_hold(dp, zc->zc_value, FTAG, &old);
7188 
7189 		if (error == 0) {
7190 			error = dsl_dataset_space_written(old, new,
7191 			    &zc->zc_cookie,
7192 			    &zc->zc_objset_type, &zc->zc_perm_action);
7193 			dsl_dataset_rele(old, FTAG);
7194 		}
7195 	}
7196 	dsl_dataset_rele(new, FTAG);
7197 	dsl_pool_rele(dp, FTAG);
7198 	return (error);
7199 }
7200 
7201 /*
7202  * innvl: {
7203  *     "firstsnap" -> snapshot name
7204  * }
7205  *
7206  * outnvl: {
7207  *     "used" -> space in bytes
7208  *     "compressed" -> compressed space in bytes
7209  *     "uncompressed" -> uncompressed space in bytes
7210  * }
7211  */
7212 static const zfs_ioc_key_t zfs_keys_space_snaps[] = {
7213 	{"firstsnap",	DATA_TYPE_STRING,	0},
7214 };
7215 
7216 static int
zfs_ioc_space_snaps(const char * lastsnap,nvlist_t * innvl,nvlist_t * outnvl)7217 zfs_ioc_space_snaps(const char *lastsnap, nvlist_t *innvl, nvlist_t *outnvl)
7218 {
7219 	int error;
7220 	dsl_pool_t *dp;
7221 	dsl_dataset_t *new, *old;
7222 	const char *firstsnap;
7223 	uint64_t used = 0, comp = 0, uncomp = 0;
7224 
7225 	firstsnap = fnvlist_lookup_string(innvl, "firstsnap");
7226 
7227 	error = dsl_pool_hold(lastsnap, FTAG, &dp);
7228 	if (error != 0)
7229 		return (error);
7230 
7231 	error = dsl_dataset_hold(dp, lastsnap, FTAG, &new);
7232 	if (error == 0 && !new->ds_is_snapshot) {
7233 		dsl_dataset_rele(new, FTAG);
7234 		error = SET_ERROR(EINVAL);
7235 	}
7236 	if (error != 0) {
7237 		dsl_pool_rele(dp, FTAG);
7238 		return (error);
7239 	}
7240 	error = dsl_dataset_hold(dp, firstsnap, FTAG, &old);
7241 	if (error == 0 && !old->ds_is_snapshot) {
7242 		dsl_dataset_rele(old, FTAG);
7243 		error = SET_ERROR(EINVAL);
7244 	}
7245 	if (error != 0) {
7246 		dsl_dataset_rele(new, FTAG);
7247 		dsl_pool_rele(dp, FTAG);
7248 		return (error);
7249 	}
7250 
7251 	error = dsl_dataset_space_wouldfree(old, new, &used, &comp, &uncomp);
7252 	dsl_dataset_rele(old, FTAG);
7253 	dsl_dataset_rele(new, FTAG);
7254 	dsl_pool_rele(dp, FTAG);
7255 	fnvlist_add_uint64(outnvl, "used", used);
7256 	fnvlist_add_uint64(outnvl, "compressed", comp);
7257 	fnvlist_add_uint64(outnvl, "uncompressed", uncomp);
7258 	return (error);
7259 }
7260 
7261 /*
7262  * innvl: {
7263  *     "fd" -> file descriptor to write stream to (int32)
7264  *     (optional) "fromsnap" -> full snap name to send an incremental from
7265  *     (optional) "largeblockok" -> (value ignored)
7266  *         indicates that blocks > 128KB are permitted
7267  *     (optional) "embedok" -> (value ignored)
7268  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
7269  *     (optional) "compressok" -> (value ignored)
7270  *         presence indicates compressed DRR_WRITE records are permitted
7271  *     (optional) "rawok" -> (value ignored)
7272  *         presence indicates raw encrypted records should be used.
7273  *     (optional) "savedok" -> (value ignored)
7274  *         presence indicates we should send a partially received snapshot
7275  *     (optional) "resume_object" and "resume_offset" -> (uint64)
7276  *         if present, resume send stream from specified object and offset.
7277  *     (optional) "redactbook" -> (string)
7278  *         if present, use this bookmark's redaction list to generate a redacted
7279  *         send stream
7280  * }
7281  *
7282  * outnvl is unused
7283  */
7284 static const zfs_ioc_key_t zfs_keys_send_new[] = {
7285 	{"fd",			DATA_TYPE_INT32,	0},
7286 	{"fromsnap",		DATA_TYPE_STRING,	ZK_OPTIONAL},
7287 	{"largeblockok",	DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7288 	{"embedok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7289 	{"compressok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7290 	{"rawok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7291 	{"savedok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7292 	{"resume_object",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
7293 	{"resume_offset",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
7294 	{"redactbook",		DATA_TYPE_STRING,	ZK_OPTIONAL},
7295 };
7296 
7297 static int
zfs_ioc_send_new(const char * snapname,nvlist_t * innvl,nvlist_t * outnvl)7298 zfs_ioc_send_new(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
7299 {
7300 	(void) outnvl;
7301 	int error;
7302 	offset_t off;
7303 	const char *fromname = NULL;
7304 	int fd;
7305 	boolean_t largeblockok;
7306 	boolean_t embedok;
7307 	boolean_t compressok;
7308 	boolean_t rawok;
7309 	boolean_t savedok;
7310 	uint64_t resumeobj = 0;
7311 	uint64_t resumeoff = 0;
7312 	const char *redactbook = NULL;
7313 
7314 	fd = fnvlist_lookup_int32(innvl, "fd");
7315 
7316 	(void) nvlist_lookup_string(innvl, "fromsnap", &fromname);
7317 
7318 	largeblockok = nvlist_exists(innvl, "largeblockok");
7319 	embedok = nvlist_exists(innvl, "embedok");
7320 	compressok = nvlist_exists(innvl, "compressok");
7321 	rawok = nvlist_exists(innvl, "rawok");
7322 	savedok = nvlist_exists(innvl, "savedok");
7323 
7324 	(void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
7325 	(void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
7326 
7327 	(void) nvlist_lookup_string(innvl, "redactbook", &redactbook);
7328 
7329 	dump_bytes_arg_t dba;
7330 	dmu_send_outparams_t out;
7331 	error = dump_bytes_init(&dba, fd, &out);
7332 	if (error)
7333 		return (error);
7334 
7335 	off = zfs_file_off(dba.dba_fp);
7336 	error = dmu_send(snapname, fromname, embedok, largeblockok,
7337 	    compressok, rawok, savedok, resumeobj, resumeoff,
7338 	    redactbook, fd, &off, &out);
7339 
7340 	dump_bytes_fini(&dba);
7341 
7342 	return (error);
7343 }
7344 
7345 static int
send_space_sum(objset_t * os,void * buf,int len,void * arg)7346 send_space_sum(objset_t *os, void *buf, int len, void *arg)
7347 {
7348 	(void) os, (void) buf;
7349 	uint64_t *size = arg;
7350 
7351 	*size += len;
7352 	return (0);
7353 }
7354 
7355 /*
7356  * Determine approximately how large a zfs send stream will be -- the number
7357  * of bytes that will be written to the fd supplied to zfs_ioc_send_new().
7358  *
7359  * innvl: {
7360  *     (optional) "from" -> full snap or bookmark name to send an incremental
7361  *                          from
7362  *     (optional) "largeblockok" -> (value ignored)
7363  *         indicates that blocks > 128KB are permitted
7364  *     (optional) "embedok" -> (value ignored)
7365  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
7366  *     (optional) "compressok" -> (value ignored)
7367  *         presence indicates compressed DRR_WRITE records are permitted
7368  *     (optional) "rawok" -> (value ignored)
7369  *         presence indicates raw encrypted records should be used.
7370  *     (optional) "resume_object" and "resume_offset" -> (uint64)
7371  *         if present, resume send stream from specified object and offset.
7372  *     (optional) "fd" -> file descriptor to use as a cookie for progress
7373  *         tracking (int32)
7374  * }
7375  *
7376  * outnvl: {
7377  *     "space" -> bytes of space (uint64)
7378  * }
7379  */
7380 static const zfs_ioc_key_t zfs_keys_send_space[] = {
7381 	{"from",		DATA_TYPE_STRING,	ZK_OPTIONAL},
7382 	{"fromsnap",		DATA_TYPE_STRING,	ZK_OPTIONAL},
7383 	{"largeblockok",	DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7384 	{"embedok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7385 	{"compressok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7386 	{"rawok",		DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7387 	{"fd",			DATA_TYPE_INT32,	ZK_OPTIONAL},
7388 	{"redactbook",		DATA_TYPE_STRING,	ZK_OPTIONAL},
7389 	{"resume_object",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
7390 	{"resume_offset",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
7391 	{"bytes",		DATA_TYPE_UINT64,	ZK_OPTIONAL},
7392 };
7393 
7394 static int
zfs_ioc_send_space(const char * snapname,nvlist_t * innvl,nvlist_t * outnvl)7395 zfs_ioc_send_space(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
7396 {
7397 	dsl_pool_t *dp;
7398 	dsl_dataset_t *tosnap;
7399 	dsl_dataset_t *fromsnap = NULL;
7400 	int error;
7401 	const char *fromname = NULL;
7402 	const char *redactlist_book = NULL;
7403 	boolean_t largeblockok;
7404 	boolean_t embedok;
7405 	boolean_t compressok;
7406 	boolean_t rawok;
7407 	boolean_t savedok;
7408 	uint64_t space = 0;
7409 	boolean_t full_estimate = B_FALSE;
7410 	uint64_t resumeobj = 0;
7411 	uint64_t resumeoff = 0;
7412 	uint64_t resume_bytes = 0;
7413 	int32_t fd = -1;
7414 	zfs_bookmark_phys_t zbm = {0};
7415 
7416 	error = dsl_pool_hold(snapname, FTAG, &dp);
7417 	if (error != 0)
7418 		return (error);
7419 
7420 	error = dsl_dataset_hold(dp, snapname, FTAG, &tosnap);
7421 	if (error != 0) {
7422 		dsl_pool_rele(dp, FTAG);
7423 		return (error);
7424 	}
7425 	(void) nvlist_lookup_int32(innvl, "fd", &fd);
7426 
7427 	largeblockok = nvlist_exists(innvl, "largeblockok");
7428 	embedok = nvlist_exists(innvl, "embedok");
7429 	compressok = nvlist_exists(innvl, "compressok");
7430 	rawok = nvlist_exists(innvl, "rawok");
7431 	savedok = nvlist_exists(innvl, "savedok");
7432 	boolean_t from = (nvlist_lookup_string(innvl, "from", &fromname) == 0);
7433 	boolean_t altbook = (nvlist_lookup_string(innvl, "redactbook",
7434 	    &redactlist_book) == 0);
7435 
7436 	(void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
7437 	(void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
7438 	(void) nvlist_lookup_uint64(innvl, "bytes", &resume_bytes);
7439 
7440 	if (altbook) {
7441 		full_estimate = B_TRUE;
7442 	} else if (from) {
7443 		if (strchr(fromname, '#')) {
7444 			error = dsl_bookmark_lookup(dp, fromname, tosnap, &zbm);
7445 
7446 			/*
7447 			 * dsl_bookmark_lookup() will fail with EXDEV if
7448 			 * the from-bookmark and tosnap are at the same txg.
7449 			 * However, it's valid to do a send (and therefore,
7450 			 * a send estimate) from and to the same time point,
7451 			 * if the bookmark is redacted (the incremental send
7452 			 * can change what's redacted on the target).  In
7453 			 * this case, dsl_bookmark_lookup() fills in zbm
7454 			 * but returns EXDEV.  Ignore this error.
7455 			 */
7456 			if (error == EXDEV && zbm.zbm_redaction_obj != 0 &&
7457 			    zbm.zbm_guid ==
7458 			    dsl_dataset_phys(tosnap)->ds_guid)
7459 				error = 0;
7460 
7461 			if (error != 0) {
7462 				dsl_dataset_rele(tosnap, FTAG);
7463 				dsl_pool_rele(dp, FTAG);
7464 				return (error);
7465 			}
7466 			if (zbm.zbm_redaction_obj != 0 || !(zbm.zbm_flags &
7467 			    ZBM_FLAG_HAS_FBN)) {
7468 				full_estimate = B_TRUE;
7469 			}
7470 		} else if (strchr(fromname, '@')) {
7471 			error = dsl_dataset_hold(dp, fromname, FTAG, &fromsnap);
7472 			if (error != 0) {
7473 				dsl_dataset_rele(tosnap, FTAG);
7474 				dsl_pool_rele(dp, FTAG);
7475 				return (error);
7476 			}
7477 
7478 			if (!dsl_dataset_is_before(tosnap, fromsnap, 0)) {
7479 				full_estimate = B_TRUE;
7480 				dsl_dataset_rele(fromsnap, FTAG);
7481 			}
7482 		} else {
7483 			/*
7484 			 * from is not properly formatted as a snapshot or
7485 			 * bookmark
7486 			 */
7487 			dsl_dataset_rele(tosnap, FTAG);
7488 			dsl_pool_rele(dp, FTAG);
7489 			return (SET_ERROR(EINVAL));
7490 		}
7491 	}
7492 
7493 	if (full_estimate) {
7494 		dmu_send_outparams_t out = {0};
7495 		offset_t off = 0;
7496 		out.dso_outfunc = send_space_sum;
7497 		out.dso_arg = &space;
7498 		out.dso_dryrun = B_TRUE;
7499 		/*
7500 		 * We have to release these holds so dmu_send can take them.  It
7501 		 * will do all the error checking we need.
7502 		 */
7503 		dsl_dataset_rele(tosnap, FTAG);
7504 		dsl_pool_rele(dp, FTAG);
7505 		error = dmu_send(snapname, fromname, embedok, largeblockok,
7506 		    compressok, rawok, savedok, resumeobj, resumeoff,
7507 		    redactlist_book, fd, &off, &out);
7508 	} else {
7509 		error = dmu_send_estimate_fast(tosnap, fromsnap,
7510 		    (from && strchr(fromname, '#') != NULL ? &zbm : NULL),
7511 		    compressok || rawok, savedok, &space);
7512 		space -= resume_bytes;
7513 		if (fromsnap != NULL)
7514 			dsl_dataset_rele(fromsnap, FTAG);
7515 		dsl_dataset_rele(tosnap, FTAG);
7516 		dsl_pool_rele(dp, FTAG);
7517 	}
7518 
7519 	fnvlist_add_uint64(outnvl, "space", space);
7520 
7521 	return (error);
7522 }
7523 
7524 /*
7525  * Sync the currently open TXG to disk for the specified pool.
7526  * This is somewhat similar to 'zfs_sync()'.
7527  * For cases that do not result in error this ioctl will wait for
7528  * the currently open TXG to commit before returning back to the caller.
7529  *
7530  * innvl: {
7531  *  "force" -> when true, force uberblock update even if there is no dirty data.
7532  *             In addition this will cause the vdev configuration to be written
7533  *             out including updating the zpool cache file. (boolean_t)
7534  * }
7535  *
7536  * onvl is unused
7537  */
7538 static const zfs_ioc_key_t zfs_keys_pool_sync[] = {
7539 	{"force",	DATA_TYPE_BOOLEAN_VALUE,	0},
7540 };
7541 
7542 static int
zfs_ioc_pool_sync(const char * pool,nvlist_t * innvl,nvlist_t * onvl)7543 zfs_ioc_pool_sync(const char *pool, nvlist_t *innvl, nvlist_t *onvl)
7544 {
7545 	(void) onvl;
7546 	int err;
7547 	boolean_t rc, force = B_FALSE;
7548 	spa_t *spa;
7549 
7550 	if ((err = spa_open(pool, &spa, FTAG)) != 0)
7551 		return (err);
7552 
7553 	if (innvl) {
7554 		err = nvlist_lookup_boolean_value(innvl, "force", &rc);
7555 		if (err == 0)
7556 			force = rc;
7557 	}
7558 
7559 	if (force) {
7560 		spa_config_enter(spa, SCL_CONFIG, FTAG, RW_WRITER);
7561 		vdev_config_dirty(spa->spa_root_vdev);
7562 		spa_config_exit(spa, SCL_CONFIG, FTAG);
7563 	}
7564 	txg_wait_synced(spa_get_dsl(spa), 0);
7565 
7566 	spa_close(spa, FTAG);
7567 
7568 	return (0);
7569 }
7570 
7571 /*
7572  * Load a user's wrapping key into the kernel.
7573  * innvl: {
7574  *     "hidden_args" -> { "wkeydata" -> value }
7575  *         raw uint8_t array of encryption wrapping key data (32 bytes)
7576  *     (optional) "noop" -> (value ignored)
7577  *         presence indicated key should only be verified, not loaded
7578  * }
7579  */
7580 static const zfs_ioc_key_t zfs_keys_load_key[] = {
7581 	{"hidden_args",	DATA_TYPE_NVLIST,	0},
7582 	{"noop",	DATA_TYPE_BOOLEAN,	ZK_OPTIONAL},
7583 };
7584 
7585 static int
zfs_ioc_load_key(const char * dsname,nvlist_t * innvl,nvlist_t * outnvl)7586 zfs_ioc_load_key(const char *dsname, nvlist_t *innvl, nvlist_t *outnvl)
7587 {
7588 	(void) outnvl;
7589 	int ret;
7590 	dsl_crypto_params_t *dcp = NULL;
7591 	nvlist_t *hidden_args;
7592 	boolean_t noop = nvlist_exists(innvl, "noop");
7593 
7594 	if (strchr(dsname, '@') != NULL || strchr(dsname, '%') != NULL) {
7595 		ret = SET_ERROR(EINVAL);
7596 		goto error;
7597 	}
7598 
7599 	hidden_args = fnvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS);
7600 
7601 	ret = dsl_crypto_params_create_nvlist(DCP_CMD_NONE, NULL,
7602 	    hidden_args, &dcp);
7603 	if (ret != 0)
7604 		goto error;
7605 
7606 	ret = spa_keystore_load_wkey(dsname, dcp, noop);
7607 	if (ret != 0)
7608 		goto error;
7609 
7610 	dsl_crypto_params_free(dcp, noop);
7611 
7612 	return (0);
7613 
7614 error:
7615 	dsl_crypto_params_free(dcp, B_TRUE);
7616 	return (ret);
7617 }
7618 
7619 /*
7620  * Unload a user's wrapping key from the kernel.
7621  * Both innvl and outnvl are unused.
7622  */
7623 static const zfs_ioc_key_t zfs_keys_unload_key[] = {
7624 	/* no nvl keys */
7625 };
7626 
7627 static int
zfs_ioc_unload_key(const char * dsname,nvlist_t * innvl,nvlist_t * outnvl)7628 zfs_ioc_unload_key(const char *dsname, nvlist_t *innvl, nvlist_t *outnvl)
7629 {
7630 	(void) innvl, (void) outnvl;
7631 	int ret = 0;
7632 
7633 	if (strchr(dsname, '@') != NULL || strchr(dsname, '%') != NULL) {
7634 		ret = (SET_ERROR(EINVAL));
7635 		goto out;
7636 	}
7637 
7638 	ret = spa_keystore_unload_wkey(dsname);
7639 	if (ret != 0)
7640 		goto out;
7641 
7642 out:
7643 	return (ret);
7644 }
7645 
7646 /*
7647  * Changes a user's wrapping key used to decrypt a dataset. The keyformat,
7648  * keylocation, pbkdf2salt, and pbkdf2iters properties can also be specified
7649  * here to change how the key is derived in userspace.
7650  *
7651  * innvl: {
7652  *    "hidden_args" (optional) -> { "wkeydata" -> value }
7653  *         raw uint8_t array of new encryption wrapping key data (32 bytes)
7654  *    "props" (optional) -> { prop -> value }
7655  * }
7656  *
7657  * outnvl is unused
7658  */
7659 static const zfs_ioc_key_t zfs_keys_change_key[] = {
7660 	{"crypt_cmd",	DATA_TYPE_UINT64,	ZK_OPTIONAL},
7661 	{"hidden_args",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
7662 	{"props",	DATA_TYPE_NVLIST,	ZK_OPTIONAL},
7663 };
7664 
7665 static int
zfs_ioc_change_key(const char * dsname,nvlist_t * innvl,nvlist_t * outnvl)7666 zfs_ioc_change_key(const char *dsname, nvlist_t *innvl, nvlist_t *outnvl)
7667 {
7668 	(void) outnvl;
7669 	int ret;
7670 	uint64_t cmd = DCP_CMD_NONE;
7671 	dsl_crypto_params_t *dcp = NULL;
7672 	nvlist_t *props = NULL, *hidden_args = NULL;
7673 
7674 	if (strchr(dsname, '@') != NULL || strchr(dsname, '%') != NULL) {
7675 		ret = (SET_ERROR(EINVAL));
7676 		goto error;
7677 	}
7678 
7679 	(void) nvlist_lookup_uint64(innvl, "crypt_cmd", &cmd);
7680 	(void) nvlist_lookup_nvlist(innvl, "props", &props);
7681 	(void) nvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS, &hidden_args);
7682 
7683 	ret = dsl_crypto_params_create_nvlist(cmd, props, hidden_args, &dcp);
7684 	if (ret != 0)
7685 		goto error;
7686 
7687 	/* The keylocation property is set from dcp->cp_keylocation. */
7688 	(void) nvlist_remove_all(props, zfs_prop_to_name(ZFS_PROP_KEYLOCATION));
7689 
7690 	if ((ret = zfs_check_userprops(props)) != 0)
7691 		goto error;
7692 
7693 	ret = spa_keystore_change_key(dsname, dcp, props);
7694 	if (ret != 0)
7695 		goto error;
7696 
7697 	dsl_crypto_params_free(dcp, B_FALSE);
7698 
7699 	return (0);
7700 
7701 error:
7702 	dsl_crypto_params_free(dcp, B_TRUE);
7703 	return (ret);
7704 }
7705 
7706 static zfs_ioc_vec_t zfs_ioc_vec[ZFS_IOC_LAST - ZFS_IOC_FIRST];
7707 
7708 static void
zfs_ioctl_register_legacy(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func,zfs_secpolicy_func_t * secpolicy,zfs_ioc_namecheck_t namecheck,boolean_t log_history,zfs_ioc_poolcheck_t pool_check)7709 zfs_ioctl_register_legacy(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
7710     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
7711     boolean_t log_history, zfs_ioc_poolcheck_t pool_check)
7712 {
7713 	zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
7714 
7715 	ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
7716 	ASSERT3U(ioc, <, ZFS_IOC_LAST);
7717 	ASSERT0P(vec->zvec_legacy_func);
7718 	ASSERT0P(vec->zvec_func);
7719 
7720 	vec->zvec_legacy_func = func;
7721 	vec->zvec_secpolicy = secpolicy;
7722 	vec->zvec_namecheck = namecheck;
7723 	vec->zvec_allow_log = log_history;
7724 	vec->zvec_pool_check = pool_check;
7725 }
7726 
7727 /*
7728  * See the block comment at the beginning of this file for details on
7729  * each argument to this function.
7730  */
7731 void
zfs_ioctl_register(const char * name,zfs_ioc_t ioc,zfs_ioc_func_t * func,zfs_secpolicy_func_t * secpolicy,zfs_ioc_namecheck_t namecheck,zfs_ioc_poolcheck_t pool_check,boolean_t smush_outnvlist,boolean_t allow_log,const zfs_ioc_key_t * nvl_keys,size_t num_keys)7732 zfs_ioctl_register(const char *name, zfs_ioc_t ioc, zfs_ioc_func_t *func,
7733     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
7734     zfs_ioc_poolcheck_t pool_check, boolean_t smush_outnvlist,
7735     boolean_t allow_log, const zfs_ioc_key_t *nvl_keys, size_t num_keys)
7736 {
7737 	zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
7738 
7739 	ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
7740 	ASSERT3U(ioc, <, ZFS_IOC_LAST);
7741 	ASSERT0P(vec->zvec_legacy_func);
7742 	ASSERT0P(vec->zvec_func);
7743 
7744 	/* if we are logging, the name must be valid */
7745 	ASSERT(!allow_log || namecheck != NO_NAME);
7746 
7747 	vec->zvec_name = name;
7748 	vec->zvec_func = func;
7749 	vec->zvec_secpolicy = secpolicy;
7750 	vec->zvec_namecheck = namecheck;
7751 	vec->zvec_pool_check = pool_check;
7752 	vec->zvec_smush_outnvlist = smush_outnvlist;
7753 	vec->zvec_allow_log = allow_log;
7754 	vec->zvec_nvl_keys = nvl_keys;
7755 	vec->zvec_nvl_key_count = num_keys;
7756 }
7757 
7758 static void
zfs_ioctl_register_pool(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func,zfs_secpolicy_func_t * secpolicy,boolean_t log_history,zfs_ioc_poolcheck_t pool_check)7759 zfs_ioctl_register_pool(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
7760     zfs_secpolicy_func_t *secpolicy, boolean_t log_history,
7761     zfs_ioc_poolcheck_t pool_check)
7762 {
7763 	zfs_ioctl_register_legacy(ioc, func, secpolicy,
7764 	    POOL_NAME, log_history, pool_check);
7765 }
7766 
7767 void
zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func,zfs_secpolicy_func_t * secpolicy,zfs_ioc_poolcheck_t pool_check)7768 zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
7769     zfs_secpolicy_func_t *secpolicy, zfs_ioc_poolcheck_t pool_check)
7770 {
7771 	zfs_ioctl_register_legacy(ioc, func, secpolicy,
7772 	    DATASET_NAME, B_FALSE, pool_check);
7773 }
7774 
7775 static void
zfs_ioctl_register_pool_modify(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func)7776 zfs_ioctl_register_pool_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
7777 {
7778 	zfs_ioctl_register_legacy(ioc, func, zfs_secpolicy_config,
7779 	    POOL_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
7780 }
7781 
7782 static void
zfs_ioctl_register_pool_meta(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func,zfs_secpolicy_func_t * secpolicy)7783 zfs_ioctl_register_pool_meta(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
7784     zfs_secpolicy_func_t *secpolicy)
7785 {
7786 	zfs_ioctl_register_legacy(ioc, func, secpolicy,
7787 	    NO_NAME, B_FALSE, POOL_CHECK_NONE);
7788 }
7789 
7790 static void
zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func,zfs_secpolicy_func_t * secpolicy)7791 zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,
7792     zfs_ioc_legacy_func_t *func, zfs_secpolicy_func_t *secpolicy)
7793 {
7794 	zfs_ioctl_register_legacy(ioc, func, secpolicy,
7795 	    DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED);
7796 }
7797 
7798 static void
zfs_ioctl_register_dataset_read(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func)7799 zfs_ioctl_register_dataset_read(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
7800 {
7801 	zfs_ioctl_register_dataset_read_secpolicy(ioc, func,
7802 	    zfs_secpolicy_read);
7803 }
7804 
7805 static void
zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc,zfs_ioc_legacy_func_t * func,zfs_secpolicy_func_t * secpolicy)7806 zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
7807     zfs_secpolicy_func_t *secpolicy)
7808 {
7809 	zfs_ioctl_register_legacy(ioc, func, secpolicy,
7810 	    DATASET_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
7811 }
7812 
7813 static void
zfs_ioctl_init(void)7814 zfs_ioctl_init(void)
7815 {
7816 	zfs_ioctl_register("snapshot", ZFS_IOC_SNAPSHOT,
7817 	    zfs_ioc_snapshot, zfs_secpolicy_snapshot, POOL_NAME,
7818 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7819 	    zfs_keys_snapshot, ARRAY_SIZE(zfs_keys_snapshot));
7820 
7821 	zfs_ioctl_register("log_history", ZFS_IOC_LOG_HISTORY,
7822 	    zfs_ioc_log_history, zfs_secpolicy_log_history, NO_NAME,
7823 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE,
7824 	    zfs_keys_log_history, ARRAY_SIZE(zfs_keys_log_history));
7825 
7826 	zfs_ioctl_register("space_snaps", ZFS_IOC_SPACE_SNAPS,
7827 	    zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME,
7828 	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE,
7829 	    zfs_keys_space_snaps, ARRAY_SIZE(zfs_keys_space_snaps));
7830 
7831 	zfs_ioctl_register("send", ZFS_IOC_SEND_NEW,
7832 	    zfs_ioc_send_new, zfs_secpolicy_send_new, DATASET_NAME,
7833 	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE,
7834 	    zfs_keys_send_new, ARRAY_SIZE(zfs_keys_send_new));
7835 
7836 	zfs_ioctl_register("send_space", ZFS_IOC_SEND_SPACE,
7837 	    zfs_ioc_send_space, zfs_secpolicy_read, DATASET_NAME,
7838 	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE,
7839 	    zfs_keys_send_space, ARRAY_SIZE(zfs_keys_send_space));
7840 
7841 	zfs_ioctl_register("create", ZFS_IOC_CREATE,
7842 	    zfs_ioc_create, zfs_secpolicy_create_clone, DATASET_NAME,
7843 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7844 	    zfs_keys_create, ARRAY_SIZE(zfs_keys_create));
7845 
7846 	zfs_ioctl_register("clone", ZFS_IOC_CLONE,
7847 	    zfs_ioc_clone, zfs_secpolicy_create_clone, DATASET_NAME,
7848 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7849 	    zfs_keys_clone, ARRAY_SIZE(zfs_keys_clone));
7850 
7851 	zfs_ioctl_register("remap", ZFS_IOC_REMAP,
7852 	    zfs_ioc_remap, zfs_secpolicy_none, DATASET_NAME,
7853 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE,
7854 	    zfs_keys_remap, ARRAY_SIZE(zfs_keys_remap));
7855 
7856 	zfs_ioctl_register("destroy_snaps", ZFS_IOC_DESTROY_SNAPS,
7857 	    zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, POOL_NAME,
7858 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7859 	    zfs_keys_destroy_snaps, ARRAY_SIZE(zfs_keys_destroy_snaps));
7860 
7861 	zfs_ioctl_register("hold", ZFS_IOC_HOLD,
7862 	    zfs_ioc_hold, zfs_secpolicy_hold, POOL_NAME,
7863 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7864 	    zfs_keys_hold, ARRAY_SIZE(zfs_keys_hold));
7865 	zfs_ioctl_register("release", ZFS_IOC_RELEASE,
7866 	    zfs_ioc_release, zfs_secpolicy_release, POOL_NAME,
7867 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7868 	    zfs_keys_release, ARRAY_SIZE(zfs_keys_release));
7869 
7870 	zfs_ioctl_register("get_holds", ZFS_IOC_GET_HOLDS,
7871 	    zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME,
7872 	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE,
7873 	    zfs_keys_get_holds, ARRAY_SIZE(zfs_keys_get_holds));
7874 
7875 	zfs_ioctl_register("rollback", ZFS_IOC_ROLLBACK,
7876 	    zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME,
7877 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE,
7878 	    zfs_keys_rollback, ARRAY_SIZE(zfs_keys_rollback));
7879 
7880 	zfs_ioctl_register("bookmark", ZFS_IOC_BOOKMARK,
7881 	    zfs_ioc_bookmark, zfs_secpolicy_bookmark, POOL_NAME,
7882 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7883 	    zfs_keys_bookmark, ARRAY_SIZE(zfs_keys_bookmark));
7884 
7885 	zfs_ioctl_register("get_bookmarks", ZFS_IOC_GET_BOOKMARKS,
7886 	    zfs_ioc_get_bookmarks, zfs_secpolicy_read, DATASET_NAME,
7887 	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE,
7888 	    zfs_keys_get_bookmarks, ARRAY_SIZE(zfs_keys_get_bookmarks));
7889 
7890 	zfs_ioctl_register("get_bookmark_props", ZFS_IOC_GET_BOOKMARK_PROPS,
7891 	    zfs_ioc_get_bookmark_props, zfs_secpolicy_read, ENTITY_NAME,
7892 	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE, zfs_keys_get_bookmark_props,
7893 	    ARRAY_SIZE(zfs_keys_get_bookmark_props));
7894 
7895 	zfs_ioctl_register("destroy_bookmarks", ZFS_IOC_DESTROY_BOOKMARKS,
7896 	    zfs_ioc_destroy_bookmarks, zfs_secpolicy_destroy_bookmarks,
7897 	    POOL_NAME,
7898 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7899 	    zfs_keys_destroy_bookmarks,
7900 	    ARRAY_SIZE(zfs_keys_destroy_bookmarks));
7901 
7902 	zfs_ioctl_register("receive", ZFS_IOC_RECV_NEW,
7903 	    zfs_ioc_recv_new, zfs_secpolicy_recv, DATASET_NAME,
7904 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7905 	    zfs_keys_recv_new, ARRAY_SIZE(zfs_keys_recv_new));
7906 	zfs_ioctl_register("load-key", ZFS_IOC_LOAD_KEY,
7907 	    zfs_ioc_load_key, zfs_secpolicy_load_key,
7908 	    DATASET_NAME, POOL_CHECK_SUSPENDED, B_TRUE, B_TRUE,
7909 	    zfs_keys_load_key, ARRAY_SIZE(zfs_keys_load_key));
7910 	zfs_ioctl_register("unload-key", ZFS_IOC_UNLOAD_KEY,
7911 	    zfs_ioc_unload_key, zfs_secpolicy_load_key,
7912 	    DATASET_NAME, POOL_CHECK_SUSPENDED, B_TRUE, B_TRUE,
7913 	    zfs_keys_unload_key, ARRAY_SIZE(zfs_keys_unload_key));
7914 	zfs_ioctl_register("change-key", ZFS_IOC_CHANGE_KEY,
7915 	    zfs_ioc_change_key, zfs_secpolicy_change_key,
7916 	    DATASET_NAME, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY,
7917 	    B_TRUE, B_TRUE, zfs_keys_change_key,
7918 	    ARRAY_SIZE(zfs_keys_change_key));
7919 
7920 	zfs_ioctl_register("sync", ZFS_IOC_POOL_SYNC,
7921 	    zfs_ioc_pool_sync, zfs_secpolicy_none, POOL_NAME,
7922 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE,
7923 	    zfs_keys_pool_sync, ARRAY_SIZE(zfs_keys_pool_sync));
7924 	zfs_ioctl_register("reopen", ZFS_IOC_POOL_REOPEN, zfs_ioc_pool_reopen,
7925 	    zfs_secpolicy_config, POOL_NAME, POOL_CHECK_SUSPENDED, B_TRUE,
7926 	    B_TRUE, zfs_keys_pool_reopen, ARRAY_SIZE(zfs_keys_pool_reopen));
7927 
7928 	zfs_ioctl_register("channel_program", ZFS_IOC_CHANNEL_PROGRAM,
7929 	    zfs_ioc_channel_program, zfs_secpolicy_config,
7930 	    POOL_NAME, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE,
7931 	    B_TRUE, zfs_keys_channel_program,
7932 	    ARRAY_SIZE(zfs_keys_channel_program));
7933 
7934 	zfs_ioctl_register("redact", ZFS_IOC_REDACT,
7935 	    zfs_ioc_redact, zfs_secpolicy_config, DATASET_NAME,
7936 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7937 	    zfs_keys_redact, ARRAY_SIZE(zfs_keys_redact));
7938 
7939 	zfs_ioctl_register("zpool_checkpoint", ZFS_IOC_POOL_CHECKPOINT,
7940 	    zfs_ioc_pool_checkpoint, zfs_secpolicy_config, POOL_NAME,
7941 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7942 	    zfs_keys_pool_checkpoint, ARRAY_SIZE(zfs_keys_pool_checkpoint));
7943 
7944 	zfs_ioctl_register("zpool_discard_checkpoint",
7945 	    ZFS_IOC_POOL_DISCARD_CHECKPOINT, zfs_ioc_pool_discard_checkpoint,
7946 	    zfs_secpolicy_config, POOL_NAME,
7947 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7948 	    zfs_keys_pool_discard_checkpoint,
7949 	    ARRAY_SIZE(zfs_keys_pool_discard_checkpoint));
7950 
7951 	zfs_ioctl_register("zpool_prefetch",
7952 	    ZFS_IOC_POOL_PREFETCH, zfs_ioc_pool_prefetch,
7953 	    zfs_secpolicy_config, POOL_NAME,
7954 	    POOL_CHECK_SUSPENDED, B_TRUE, B_TRUE,
7955 	    zfs_keys_pool_prefetch, ARRAY_SIZE(zfs_keys_pool_prefetch));
7956 
7957 	zfs_ioctl_register("initialize", ZFS_IOC_POOL_INITIALIZE,
7958 	    zfs_ioc_pool_initialize, zfs_secpolicy_config, POOL_NAME,
7959 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7960 	    zfs_keys_pool_initialize, ARRAY_SIZE(zfs_keys_pool_initialize));
7961 
7962 	zfs_ioctl_register("trim", ZFS_IOC_POOL_TRIM,
7963 	    zfs_ioc_pool_trim, zfs_secpolicy_config, POOL_NAME,
7964 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
7965 	    zfs_keys_pool_trim, ARRAY_SIZE(zfs_keys_pool_trim));
7966 
7967 	zfs_ioctl_register("wait", ZFS_IOC_WAIT,
7968 	    zfs_ioc_wait, zfs_secpolicy_none, POOL_NAME,
7969 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE,
7970 	    zfs_keys_pool_wait, ARRAY_SIZE(zfs_keys_pool_wait));
7971 
7972 	zfs_ioctl_register("wait_fs", ZFS_IOC_WAIT_FS,
7973 	    zfs_ioc_wait_fs, zfs_secpolicy_none, DATASET_NAME,
7974 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE,
7975 	    zfs_keys_fs_wait, ARRAY_SIZE(zfs_keys_fs_wait));
7976 
7977 	zfs_ioctl_register("set_bootenv", ZFS_IOC_SET_BOOTENV,
7978 	    zfs_ioc_set_bootenv, zfs_secpolicy_config, POOL_NAME,
7979 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE,
7980 	    zfs_keys_set_bootenv, ARRAY_SIZE(zfs_keys_set_bootenv));
7981 
7982 	zfs_ioctl_register("get_bootenv", ZFS_IOC_GET_BOOTENV,
7983 	    zfs_ioc_get_bootenv, zfs_secpolicy_none, POOL_NAME,
7984 	    POOL_CHECK_SUSPENDED, B_FALSE, B_TRUE,
7985 	    zfs_keys_get_bootenv, ARRAY_SIZE(zfs_keys_get_bootenv));
7986 
7987 	zfs_ioctl_register("zpool_vdev_get_props", ZFS_IOC_VDEV_GET_PROPS,
7988 	    zfs_ioc_vdev_get_props, zfs_secpolicy_read, POOL_NAME,
7989 	    POOL_CHECK_NONE, B_FALSE, B_FALSE, zfs_keys_vdev_get_props,
7990 	    ARRAY_SIZE(zfs_keys_vdev_get_props));
7991 
7992 	zfs_ioctl_register("zpool_vdev_set_props", ZFS_IOC_VDEV_SET_PROPS,
7993 	    zfs_ioc_vdev_set_props, zfs_secpolicy_config, POOL_NAME,
7994 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE,
7995 	    zfs_keys_vdev_set_props, ARRAY_SIZE(zfs_keys_vdev_set_props));
7996 
7997 	zfs_ioctl_register("scrub", ZFS_IOC_POOL_SCRUB,
7998 	    zfs_ioc_pool_scrub, zfs_secpolicy_config, POOL_NAME,
7999 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
8000 	    zfs_keys_pool_scrub, ARRAY_SIZE(zfs_keys_pool_scrub));
8001 
8002 	zfs_ioctl_register("get_props", ZFS_IOC_POOL_GET_PROPS,
8003 	    zfs_ioc_pool_get_props, zfs_secpolicy_read, POOL_NAME,
8004 	    POOL_CHECK_NONE, B_FALSE, B_FALSE,
8005 	    zfs_keys_get_props, ARRAY_SIZE(zfs_keys_get_props));
8006 
8007 	zfs_ioctl_register("zpool_ddt_prune", ZFS_IOC_DDT_PRUNE,
8008 	    zfs_ioc_ddt_prune, zfs_secpolicy_config, POOL_NAME,
8009 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE,
8010 	    zfs_keys_ddt_prune, ARRAY_SIZE(zfs_keys_ddt_prune));
8011 
8012 	/* IOCTLS that use the legacy function signature */
8013 
8014 	zfs_ioctl_register_legacy(ZFS_IOC_POOL_FREEZE, zfs_ioc_pool_freeze,
8015 	    zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_READONLY);
8016 
8017 	zfs_ioctl_register_pool(ZFS_IOC_POOL_CREATE, zfs_ioc_pool_create,
8018 	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
8019 	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SCAN,
8020 	    zfs_ioc_pool_scan);
8021 	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_UPGRADE,
8022 	    zfs_ioc_pool_upgrade);
8023 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ADD,
8024 	    zfs_ioc_vdev_add);
8025 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_REMOVE,
8026 	    zfs_ioc_vdev_remove);
8027 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SET_STATE,
8028 	    zfs_ioc_vdev_set_state);
8029 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ATTACH,
8030 	    zfs_ioc_vdev_attach);
8031 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_DETACH,
8032 	    zfs_ioc_vdev_detach);
8033 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETPATH,
8034 	    zfs_ioc_vdev_setpath);
8035 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETFRU,
8036 	    zfs_ioc_vdev_setfru);
8037 	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SET_PROPS,
8038 	    zfs_ioc_pool_set_props);
8039 	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SPLIT,
8040 	    zfs_ioc_vdev_split);
8041 	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_REGUID,
8042 	    zfs_ioc_pool_reguid);
8043 
8044 	zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_CONFIGS,
8045 	    zfs_ioc_pool_configs, zfs_secpolicy_none);
8046 	zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_TRYIMPORT,
8047 	    zfs_ioc_pool_tryimport, zfs_secpolicy_config);
8048 	zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_FAULT,
8049 	    zfs_ioc_inject_fault, zfs_secpolicy_inject);
8050 	zfs_ioctl_register_pool_meta(ZFS_IOC_CLEAR_FAULT,
8051 	    zfs_ioc_clear_fault, zfs_secpolicy_inject);
8052 	zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_LIST_NEXT,
8053 	    zfs_ioc_inject_list_next, zfs_secpolicy_inject);
8054 
8055 	/*
8056 	 * pool destroy, and export don't log the history as part of
8057 	 * zfsdev_ioctl, but rather zfs_ioc_pool_export
8058 	 * does the logging of those commands.
8059 	 */
8060 	zfs_ioctl_register_pool(ZFS_IOC_POOL_DESTROY, zfs_ioc_pool_destroy,
8061 	    zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
8062 	zfs_ioctl_register_pool(ZFS_IOC_POOL_EXPORT, zfs_ioc_pool_export,
8063 	    zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
8064 
8065 	zfs_ioctl_register_pool(ZFS_IOC_POOL_STATS, zfs_ioc_pool_stats,
8066 	    zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
8067 
8068 	zfs_ioctl_register_pool(ZFS_IOC_ERROR_LOG, zfs_ioc_error_log,
8069 	    zfs_secpolicy_inject, B_FALSE, POOL_CHECK_SUSPENDED);
8070 	zfs_ioctl_register_pool(ZFS_IOC_DSOBJ_TO_DSNAME,
8071 	    zfs_ioc_dsobj_to_dsname,
8072 	    zfs_secpolicy_diff, B_FALSE, POOL_CHECK_SUSPENDED);
8073 	zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_HISTORY,
8074 	    zfs_ioc_pool_get_history,
8075 	    zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
8076 
8077 	zfs_ioctl_register_pool(ZFS_IOC_POOL_IMPORT, zfs_ioc_pool_import,
8078 	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
8079 
8080 	zfs_ioctl_register_pool(ZFS_IOC_CLEAR, zfs_ioc_clear,
8081 	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_READONLY);
8082 
8083 	zfs_ioctl_register_dataset_read(ZFS_IOC_SPACE_WRITTEN,
8084 	    zfs_ioc_space_written);
8085 	zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_RECVD_PROPS,
8086 	    zfs_ioc_objset_recvd_props);
8087 	zfs_ioctl_register_dataset_read(ZFS_IOC_NEXT_OBJ,
8088 	    zfs_ioc_next_obj);
8089 	zfs_ioctl_register_dataset_read(ZFS_IOC_GET_FSACL,
8090 	    zfs_ioc_get_fsacl);
8091 	zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_STATS,
8092 	    zfs_ioc_objset_stats);
8093 	zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_ZPLPROPS,
8094 	    zfs_ioc_objset_zplprops);
8095 	zfs_ioctl_register_dataset_read(ZFS_IOC_DATASET_LIST_NEXT,
8096 	    zfs_ioc_dataset_list_next);
8097 	zfs_ioctl_register_dataset_read(ZFS_IOC_SNAPSHOT_LIST_NEXT,
8098 	    zfs_ioc_snapshot_list_next);
8099 	zfs_ioctl_register_dataset_read(ZFS_IOC_SEND_PROGRESS,
8100 	    zfs_ioc_send_progress);
8101 
8102 	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_DIFF,
8103 	    zfs_ioc_diff, zfs_secpolicy_diff);
8104 	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_STATS,
8105 	    zfs_ioc_obj_to_stats, zfs_secpolicy_diff);
8106 	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_PATH,
8107 	    zfs_ioc_obj_to_path, zfs_secpolicy_diff);
8108 	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_ONE,
8109 	    zfs_ioc_userspace_one, zfs_secpolicy_userspace_one);
8110 	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_MANY,
8111 	    zfs_ioc_userspace_many, zfs_secpolicy_userspace_many);
8112 	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_SEND,
8113 	    zfs_ioc_send, zfs_secpolicy_send);
8114 
8115 	zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_PROP, zfs_ioc_set_prop,
8116 	    zfs_secpolicy_setprops);
8117 	zfs_ioctl_register_dataset_modify(ZFS_IOC_DESTROY, zfs_ioc_destroy,
8118 	    zfs_secpolicy_destroy);
8119 	zfs_ioctl_register_dataset_modify(ZFS_IOC_RENAME, zfs_ioc_rename,
8120 	    zfs_secpolicy_rename);
8121 	zfs_ioctl_register_dataset_modify(ZFS_IOC_RECV, zfs_ioc_recv,
8122 	    zfs_secpolicy_recv);
8123 	zfs_ioctl_register_dataset_modify(ZFS_IOC_PROMOTE, zfs_ioc_promote,
8124 	    zfs_secpolicy_promote);
8125 	zfs_ioctl_register_dataset_modify(ZFS_IOC_INHERIT_PROP,
8126 	    zfs_ioc_inherit_prop, zfs_secpolicy_inherit_prop);
8127 	zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_FSACL, zfs_ioc_set_fsacl,
8128 	    zfs_secpolicy_set_fsacl);
8129 
8130 	zfs_ioctl_register_dataset_nolog(ZFS_IOC_SHARE, zfs_ioc_share,
8131 	    zfs_secpolicy_share, POOL_CHECK_NONE);
8132 	zfs_ioctl_register_dataset_nolog(ZFS_IOC_SMB_ACL, zfs_ioc_smb_acl,
8133 	    zfs_secpolicy_smb_acl, POOL_CHECK_NONE);
8134 	zfs_ioctl_register_dataset_nolog(ZFS_IOC_USERSPACE_UPGRADE,
8135 	    zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
8136 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
8137 	zfs_ioctl_register_dataset_nolog(ZFS_IOC_TMP_SNAPSHOT,
8138 	    zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot,
8139 	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
8140 
8141 	zfs_ioctl_register_legacy(ZFS_IOC_EVENTS_NEXT, zfs_ioc_events_next,
8142 	    zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE);
8143 	zfs_ioctl_register_legacy(ZFS_IOC_EVENTS_CLEAR, zfs_ioc_events_clear,
8144 	    zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE);
8145 	zfs_ioctl_register_legacy(ZFS_IOC_EVENTS_SEEK, zfs_ioc_events_seek,
8146 	    zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE);
8147 
8148 	zfs_ioctl_init_os();
8149 }
8150 
8151 /*
8152  * Verify that for non-legacy ioctls the input nvlist
8153  * pairs match against the expected input.
8154  *
8155  * Possible errors are:
8156  * ZFS_ERR_IOC_ARG_UNAVAIL	An unrecognized nvpair was encountered
8157  * ZFS_ERR_IOC_ARG_REQUIRED	A required nvpair is missing
8158  * ZFS_ERR_IOC_ARG_BADTYPE	Invalid type for nvpair
8159  */
8160 static int
zfs_check_input_nvpairs(nvlist_t * innvl,const zfs_ioc_vec_t * vec)8161 zfs_check_input_nvpairs(nvlist_t *innvl, const zfs_ioc_vec_t *vec)
8162 {
8163 	const zfs_ioc_key_t *nvl_keys = vec->zvec_nvl_keys;
8164 	boolean_t required_keys_found = B_FALSE;
8165 
8166 	/*
8167 	 * examine each input pair
8168 	 */
8169 	for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
8170 	    pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
8171 		const char *name = nvpair_name(pair);
8172 		data_type_t type = nvpair_type(pair);
8173 		boolean_t identified = B_FALSE;
8174 
8175 		/*
8176 		 * check pair against the documented names and type
8177 		 */
8178 		for (int k = 0; k < vec->zvec_nvl_key_count; k++) {
8179 			/* if not a wild card name, check for an exact match */
8180 			if ((nvl_keys[k].zkey_flags & ZK_WILDCARDLIST) == 0 &&
8181 			    strcmp(nvl_keys[k].zkey_name, name) != 0)
8182 				continue;
8183 
8184 			identified = B_TRUE;
8185 
8186 			if (nvl_keys[k].zkey_type != DATA_TYPE_ANY &&
8187 			    nvl_keys[k].zkey_type != type) {
8188 				return (SET_ERROR(ZFS_ERR_IOC_ARG_BADTYPE));
8189 			}
8190 
8191 			if (nvl_keys[k].zkey_flags & ZK_OPTIONAL)
8192 				continue;
8193 
8194 			required_keys_found = B_TRUE;
8195 			break;
8196 		}
8197 
8198 		/* allow an 'optional' key, everything else is invalid */
8199 		if (!identified &&
8200 		    (strcmp(name, "optional") != 0 ||
8201 		    type != DATA_TYPE_NVLIST)) {
8202 			return (SET_ERROR(ZFS_ERR_IOC_ARG_UNAVAIL));
8203 		}
8204 	}
8205 
8206 	/* verify that all required keys were found */
8207 	for (int k = 0; k < vec->zvec_nvl_key_count; k++) {
8208 		if (nvl_keys[k].zkey_flags & ZK_OPTIONAL)
8209 			continue;
8210 
8211 		if (nvl_keys[k].zkey_flags & ZK_WILDCARDLIST) {
8212 			/* at least one non-optional key is expected here */
8213 			if (!required_keys_found)
8214 				return (SET_ERROR(ZFS_ERR_IOC_ARG_REQUIRED));
8215 			continue;
8216 		}
8217 
8218 		if (!nvlist_exists(innvl, nvl_keys[k].zkey_name))
8219 			return (SET_ERROR(ZFS_ERR_IOC_ARG_REQUIRED));
8220 	}
8221 
8222 	return (0);
8223 }
8224 
8225 static int
pool_status_check(const char * name,zfs_ioc_namecheck_t type,zfs_ioc_poolcheck_t check)8226 pool_status_check(const char *name, zfs_ioc_namecheck_t type,
8227     zfs_ioc_poolcheck_t check)
8228 {
8229 	spa_t *spa;
8230 	int error;
8231 
8232 	ASSERT(type == POOL_NAME || type == DATASET_NAME ||
8233 	    type == ENTITY_NAME);
8234 
8235 	if (check & POOL_CHECK_NONE)
8236 		return (0);
8237 
8238 	error = spa_open(name, &spa, FTAG);
8239 	if (error == 0) {
8240 		if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
8241 			error = SET_ERROR(EAGAIN);
8242 		else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
8243 			error = SET_ERROR(EROFS);
8244 		spa_close(spa, FTAG);
8245 	}
8246 	return (error);
8247 }
8248 
8249 int
zfsdev_getminor(zfs_file_t * fp,minor_t * minorp)8250 zfsdev_getminor(zfs_file_t *fp, minor_t *minorp)
8251 {
8252 	zfsdev_state_t *zs, *fpd;
8253 
8254 	ASSERT(!MUTEX_HELD(&zfsdev_state_lock));
8255 
8256 	fpd = zfs_file_private(fp);
8257 	if (fpd == NULL)
8258 		return (SET_ERROR(EBADF));
8259 
8260 	mutex_enter(&zfsdev_state_lock);
8261 
8262 	for (zs = &zfsdev_state_listhead; zs != NULL; zs = zs->zs_next) {
8263 
8264 		if (zs->zs_minor == -1)
8265 			continue;
8266 
8267 		if (fpd == zs) {
8268 			*minorp = fpd->zs_minor;
8269 			mutex_exit(&zfsdev_state_lock);
8270 			return (0);
8271 		}
8272 	}
8273 
8274 	mutex_exit(&zfsdev_state_lock);
8275 
8276 	return (SET_ERROR(EBADF));
8277 }
8278 
8279 void *
zfsdev_get_state(minor_t minor,enum zfsdev_state_type which)8280 zfsdev_get_state(minor_t minor, enum zfsdev_state_type which)
8281 {
8282 	zfsdev_state_t *zs;
8283 
8284 	for (zs = &zfsdev_state_listhead; zs != NULL; zs = zs->zs_next) {
8285 		if (zs->zs_minor == minor) {
8286 			membar_consumer();
8287 			switch (which) {
8288 			case ZST_ONEXIT:
8289 				return (zs->zs_onexit);
8290 			case ZST_ZEVENT:
8291 				return (zs->zs_zevent);
8292 			case ZST_ALL:
8293 				return (zs);
8294 			}
8295 		}
8296 	}
8297 
8298 	return (NULL);
8299 }
8300 
8301 /*
8302  * Find a free minor number.  The zfsdev_state_list is expected to
8303  * be short since it is only a list of currently open file handles.
8304  */
8305 static minor_t
zfsdev_minor_alloc(void)8306 zfsdev_minor_alloc(void)
8307 {
8308 	static minor_t last_minor = 0;
8309 	minor_t m;
8310 
8311 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
8312 
8313 	for (m = last_minor + 1; m != last_minor; m++) {
8314 		if (m > ZFSDEV_MAX_MINOR)
8315 			m = 1;
8316 		if (zfsdev_get_state(m, ZST_ALL) == NULL) {
8317 			last_minor = m;
8318 			return (m);
8319 		}
8320 	}
8321 
8322 	return (0);
8323 }
8324 
8325 int
zfsdev_state_init(void * priv)8326 zfsdev_state_init(void *priv)
8327 {
8328 	zfsdev_state_t *zs, *zsprev = NULL;
8329 	minor_t minor;
8330 	boolean_t newzs = B_FALSE;
8331 
8332 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
8333 
8334 	minor = zfsdev_minor_alloc();
8335 	if (minor == 0)
8336 		return (SET_ERROR(ENXIO));
8337 
8338 	for (zs = &zfsdev_state_listhead; zs != NULL; zs = zs->zs_next) {
8339 		if (zs->zs_minor == -1)
8340 			break;
8341 		zsprev = zs;
8342 	}
8343 
8344 	if (!zs) {
8345 		zs = kmem_zalloc(sizeof (zfsdev_state_t), KM_SLEEP);
8346 		newzs = B_TRUE;
8347 	}
8348 
8349 	zfsdev_private_set_state(priv, zs);
8350 
8351 	zfs_onexit_init((zfs_onexit_t **)&zs->zs_onexit);
8352 	zfs_zevent_init((zfs_zevent_t **)&zs->zs_zevent);
8353 
8354 	/*
8355 	 * In order to provide for lock-free concurrent read access
8356 	 * to the minor list in zfsdev_get_state(), new entries
8357 	 * must be completely written before linking them into the
8358 	 * list whereas existing entries are already linked; the last
8359 	 * operation must be updating zs_minor (from -1 to the new
8360 	 * value).
8361 	 */
8362 	if (newzs) {
8363 		zs->zs_minor = minor;
8364 		membar_producer();
8365 		zsprev->zs_next = zs;
8366 	} else {
8367 		membar_producer();
8368 		zs->zs_minor = minor;
8369 	}
8370 
8371 	return (0);
8372 }
8373 
8374 void
zfsdev_state_destroy(void * priv)8375 zfsdev_state_destroy(void *priv)
8376 {
8377 	zfsdev_state_t *zs = zfsdev_private_get_state(priv);
8378 
8379 	ASSERT(zs != NULL);
8380 	ASSERT3S(zs->zs_minor, >, 0);
8381 
8382 	/*
8383 	 * The last reference to this zfsdev file descriptor is being dropped.
8384 	 * We don't have to worry about lookup grabbing this state object, and
8385 	 * zfsdev_state_init() will not try to reuse this object until it is
8386 	 * invalidated by setting zs_minor to -1.  Invalidation must be done
8387 	 * last, with a memory barrier to ensure ordering.  This lets us avoid
8388 	 * taking the global zfsdev state lock around destruction.
8389 	 */
8390 	zfs_onexit_destroy(zs->zs_onexit);
8391 	zfs_zevent_destroy(zs->zs_zevent);
8392 	zs->zs_onexit = NULL;
8393 	zs->zs_zevent = NULL;
8394 	membar_producer();
8395 	zs->zs_minor = -1;
8396 }
8397 
8398 long
zfsdev_ioctl_common(uint_t vecnum,zfs_cmd_t * zc,int flag)8399 zfsdev_ioctl_common(uint_t vecnum, zfs_cmd_t *zc, int flag)
8400 {
8401 	int error, cmd;
8402 	const zfs_ioc_vec_t *vec;
8403 	char *saved_poolname = NULL;
8404 	uint64_t max_nvlist_src_size;
8405 	size_t saved_poolname_len = 0;
8406 	nvlist_t *innvl = NULL;
8407 	fstrans_cookie_t cookie;
8408 	hrtime_t start_time = gethrtime();
8409 
8410 	cmd = vecnum;
8411 	error = 0;
8412 	if (vecnum >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
8413 		return (SET_ERROR(ZFS_ERR_IOC_CMD_UNAVAIL));
8414 
8415 	vec = &zfs_ioc_vec[vecnum];
8416 
8417 	/*
8418 	 * The registered ioctl list may be sparse, verify that either
8419 	 * a normal or legacy handler are registered.
8420 	 */
8421 	if (vec->zvec_func == NULL && vec->zvec_legacy_func == NULL)
8422 		return (SET_ERROR(ZFS_ERR_IOC_CMD_UNAVAIL));
8423 
8424 	zc->zc_iflags = flag & FKIOCTL;
8425 	max_nvlist_src_size = zfs_max_nvlist_src_size_os();
8426 	if (zc->zc_nvlist_src_size > max_nvlist_src_size) {
8427 		/*
8428 		 * Make sure the user doesn't pass in an insane value for
8429 		 * zc_nvlist_src_size.  We have to check, since we will end
8430 		 * up allocating that much memory inside of get_nvlist().  This
8431 		 * prevents a nefarious user from allocating tons of kernel
8432 		 * memory.
8433 		 *
8434 		 * Also, we return EINVAL instead of ENOMEM here.  The reason
8435 		 * being that returning ENOMEM from an ioctl() has a special
8436 		 * connotation; that the user's size value is too small and
8437 		 * needs to be expanded to hold the nvlist.  See
8438 		 * zcmd_expand_dst_nvlist() for details.
8439 		 */
8440 		error = SET_ERROR(EINVAL);	/* User's size too big */
8441 
8442 	} else if (zc->zc_nvlist_src_size != 0) {
8443 		error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
8444 		    zc->zc_iflags, &innvl);
8445 		if (error != 0)
8446 			goto out;
8447 	}
8448 
8449 	/*
8450 	 * Ensure that all pool/dataset names are valid before we pass down to
8451 	 * the lower layers.
8452 	 */
8453 	zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
8454 	switch (vec->zvec_namecheck) {
8455 	case POOL_NAME:
8456 		if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
8457 			error = SET_ERROR(EINVAL);
8458 		else
8459 			error = pool_status_check(zc->zc_name,
8460 			    vec->zvec_namecheck, vec->zvec_pool_check);
8461 		break;
8462 
8463 	case DATASET_NAME:
8464 		if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
8465 			error = SET_ERROR(EINVAL);
8466 		else
8467 			error = pool_status_check(zc->zc_name,
8468 			    vec->zvec_namecheck, vec->zvec_pool_check);
8469 		break;
8470 
8471 	case ENTITY_NAME:
8472 		if (entity_namecheck(zc->zc_name, NULL, NULL) != 0) {
8473 			error = SET_ERROR(EINVAL);
8474 		} else {
8475 			error = pool_status_check(zc->zc_name,
8476 			    vec->zvec_namecheck, vec->zvec_pool_check);
8477 		}
8478 		break;
8479 
8480 	case NO_NAME:
8481 		break;
8482 	}
8483 	/*
8484 	 * Ensure that all input pairs are valid before we pass them down
8485 	 * to the lower layers.
8486 	 *
8487 	 * The vectored functions can use fnvlist_lookup_{type} for any
8488 	 * required pairs since zfs_check_input_nvpairs() confirmed that
8489 	 * they exist and are of the correct type.
8490 	 */
8491 	if (error == 0 && vec->zvec_func != NULL) {
8492 		error = zfs_check_input_nvpairs(innvl, vec);
8493 		if (error != 0)
8494 			goto out;
8495 	}
8496 
8497 	if (error == 0) {
8498 		cookie = spl_fstrans_mark();
8499 		error = vec->zvec_secpolicy(zc, innvl, CRED());
8500 		spl_fstrans_unmark(cookie);
8501 	}
8502 
8503 	if (error != 0)
8504 		goto out;
8505 
8506 	/* legacy ioctls can modify zc_name */
8507 	/*
8508 	 * Can't use kmem_strdup() as we might truncate the string and
8509 	 * kmem_strfree() would then free with incorrect size.
8510 	 */
8511 	const char *spa_name = zc->zc_name;
8512 	const char *tname;
8513 	if (nvlist_lookup_string(innvl,
8514 	    zpool_prop_to_name(ZPOOL_PROP_TNAME), &tname) == 0) {
8515 		spa_name = tname;
8516 	}
8517 	saved_poolname_len = strlen(spa_name) + 1;
8518 	saved_poolname = kmem_alloc(saved_poolname_len, KM_SLEEP);
8519 
8520 	strlcpy(saved_poolname, spa_name, saved_poolname_len);
8521 	saved_poolname[strcspn(saved_poolname, "/@#")] = '\0';
8522 
8523 	if (vec->zvec_func != NULL) {
8524 		nvlist_t *outnvl;
8525 		int puterror = 0;
8526 		spa_t *spa;
8527 		nvlist_t *lognv = NULL;
8528 
8529 		ASSERT0P(vec->zvec_legacy_func);
8530 
8531 		/*
8532 		 * Add the innvl to the lognv before calling the func,
8533 		 * in case the func changes the innvl.
8534 		 */
8535 		if (vec->zvec_allow_log) {
8536 			lognv = fnvlist_alloc();
8537 			fnvlist_add_string(lognv, ZPOOL_HIST_IOCTL,
8538 			    vec->zvec_name);
8539 			if (!nvlist_empty(innvl)) {
8540 				fnvlist_add_nvlist(lognv, ZPOOL_HIST_INPUT_NVL,
8541 				    innvl);
8542 			}
8543 		}
8544 
8545 		outnvl = fnvlist_alloc();
8546 		cookie = spl_fstrans_mark();
8547 		error = vec->zvec_func(zc->zc_name, innvl, outnvl);
8548 		spl_fstrans_unmark(cookie);
8549 
8550 		/*
8551 		 * Some commands can partially execute, modify state, and still
8552 		 * return an error.  In these cases, attempt to record what
8553 		 * was modified.
8554 		 */
8555 		if ((error == 0 ||
8556 		    (cmd == ZFS_IOC_CHANNEL_PROGRAM && error != EINVAL)) &&
8557 		    vec->zvec_allow_log &&
8558 		    spa_open(zc->zc_name, &spa, FTAG) == 0) {
8559 			if (!nvlist_empty(outnvl)) {
8560 				size_t out_size = fnvlist_size(outnvl);
8561 				if (out_size > zfs_history_output_max) {
8562 					fnvlist_add_int64(lognv,
8563 					    ZPOOL_HIST_OUTPUT_SIZE, out_size);
8564 				} else {
8565 					fnvlist_add_nvlist(lognv,
8566 					    ZPOOL_HIST_OUTPUT_NVL, outnvl);
8567 				}
8568 			}
8569 			if (error != 0) {
8570 				fnvlist_add_int64(lognv, ZPOOL_HIST_ERRNO,
8571 				    error);
8572 			}
8573 			fnvlist_add_int64(lognv, ZPOOL_HIST_ELAPSED_NS,
8574 			    gethrtime() - start_time);
8575 			(void) spa_history_log_nvl(spa, lognv);
8576 			spa_close(spa, FTAG);
8577 		}
8578 		fnvlist_free(lognv);
8579 
8580 		if (!nvlist_empty(outnvl) || zc->zc_nvlist_dst_size != 0) {
8581 			int smusherror = 0;
8582 			if (vec->zvec_smush_outnvlist) {
8583 				smusherror = nvlist_smush(outnvl,
8584 				    zc->zc_nvlist_dst_size);
8585 			}
8586 			if (smusherror == 0)
8587 				puterror = put_nvlist(zc, outnvl);
8588 		}
8589 
8590 		if (puterror != 0)
8591 			error = puterror;
8592 
8593 		nvlist_free(outnvl);
8594 	} else {
8595 		cookie = spl_fstrans_mark();
8596 		error = vec->zvec_legacy_func(zc);
8597 		spl_fstrans_unmark(cookie);
8598 	}
8599 
8600 out:
8601 	nvlist_free(innvl);
8602 	if (error == 0 && vec->zvec_allow_log) {
8603 		char *s = tsd_get(zfs_allow_log_key);
8604 		if (s != NULL)
8605 			kmem_strfree(s);
8606 		(void) tsd_set(zfs_allow_log_key, kmem_strdup(saved_poolname));
8607 	}
8608 	if (saved_poolname != NULL)
8609 		kmem_free(saved_poolname, saved_poolname_len);
8610 
8611 	return (error);
8612 }
8613 
8614 int
zfs_kmod_init(void)8615 zfs_kmod_init(void)
8616 {
8617 	int error;
8618 
8619 	if ((error = zvol_init()) != 0)
8620 		return (error);
8621 
8622 	spa_init(SPA_MODE_READ | SPA_MODE_WRITE);
8623 	zfs_init();
8624 
8625 	zfs_ioctl_init();
8626 
8627 	/* Register zoned_uid property lookup callback with SPL */
8628 	zone_register_zoned_uid_callback(zfs_get_zoned_uid);
8629 
8630 	mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
8631 	zfsdev_state_listhead.zs_minor = -1;
8632 
8633 	if ((error = zfsdev_attach()) != 0)
8634 		goto out;
8635 
8636 	tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
8637 	tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
8638 
8639 	return (0);
8640 out:
8641 	zfs_fini();
8642 	spa_fini();
8643 	zvol_fini();
8644 
8645 	return (error);
8646 }
8647 
8648 void
zfs_kmod_fini(void)8649 zfs_kmod_fini(void)
8650 {
8651 	zfsdev_state_t *zs, *zsnext = NULL;
8652 
8653 	zfsdev_detach();
8654 
8655 	mutex_destroy(&zfsdev_state_lock);
8656 
8657 	for (zs = &zfsdev_state_listhead; zs != NULL; zs = zsnext) {
8658 		zsnext = zs->zs_next;
8659 		if (zs->zs_onexit)
8660 			zfs_onexit_destroy(zs->zs_onexit);
8661 		if (zs->zs_zevent)
8662 			zfs_zevent_destroy(zs->zs_zevent);
8663 		if (zs != &zfsdev_state_listhead)
8664 			kmem_free(zs, sizeof (zfsdev_state_t));
8665 	}
8666 
8667 	zfs_ereport_taskq_fini();	/* run before zfs_fini() on Linux */
8668 
8669 	/* Unregister zoned_uid callback before ZFS layer is torn down */
8670 	zone_unregister_zoned_uid_callback();
8671 
8672 	zfs_fini();
8673 	spa_fini();
8674 	zvol_fini();
8675 
8676 	tsd_destroy(&rrw_tsd_key);
8677 	tsd_destroy(&zfs_allow_log_key);
8678 }
8679 
8680 ZFS_MODULE_PARAM(zfs, zfs_, max_nvlist_src_size, U64, ZMOD_RW,
8681 	"Maximum size in bytes allowed for src nvlist passed with ZFS ioctls");
8682 
8683 ZFS_MODULE_PARAM(zfs, zfs_, history_output_max, U64, ZMOD_RW,
8684 	"Maximum size in bytes of ZFS ioctl output that will be logged");
8685