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