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