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