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