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