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