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