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