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