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