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