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