zfs_ioctl.c revision 310510
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#ifdef __FreeBSD__
3475static int
3476zfs_ioc_nextboot(const char *unused, nvlist_t *innvl, nvlist_t *outnvl)
3477{
3478	char name[MAXNAMELEN];
3479	spa_t *spa;
3480	vdev_t *vd;
3481	char *command;
3482	uint64_t pool_guid;
3483	uint64_t vdev_guid;
3484	int error;
3485
3486	if (nvlist_lookup_uint64(innvl,
3487	    ZPOOL_CONFIG_POOL_GUID, &pool_guid) != 0)
3488		return (EINVAL);
3489	if (nvlist_lookup_uint64(innvl,
3490	    ZPOOL_CONFIG_GUID, &vdev_guid) != 0)
3491		return (EINVAL);
3492	if (nvlist_lookup_string(innvl,
3493	    "command", &command) != 0)
3494		return (EINVAL);
3495
3496	mutex_enter(&spa_namespace_lock);
3497	spa = spa_by_guid(pool_guid, vdev_guid);
3498	if (spa != NULL)
3499		strcpy(name, spa_name(spa));
3500	mutex_exit(&spa_namespace_lock);
3501	if (spa == NULL)
3502		return (ENOENT);
3503
3504	if ((error = spa_open(name, &spa, FTAG)) != 0)
3505		return (error);
3506	spa_vdev_state_enter(spa, SCL_ALL);
3507	vd = spa_lookup_by_guid(spa, vdev_guid, B_TRUE);
3508	if (vd == NULL) {
3509		(void) spa_vdev_state_exit(spa, NULL, ENXIO);
3510		spa_close(spa, FTAG);
3511		return (ENODEV);
3512	}
3513	error = vdev_label_write_pad2(vd, command, strlen(command));
3514	(void) spa_vdev_state_exit(spa, NULL, 0);
3515	txg_wait_synced(spa->spa_dsl_pool, 0);
3516	spa_close(spa, FTAG);
3517	return (error);
3518}
3519#endif
3520
3521/*
3522 * The dp_config_rwlock must not be held when calling this, because the
3523 * unmount may need to write out data.
3524 *
3525 * This function is best-effort.  Callers must deal gracefully if it
3526 * remains mounted (or is remounted after this call).
3527 *
3528 * Returns 0 if the argument is not a snapshot, or it is not currently a
3529 * filesystem, or we were able to unmount it.  Returns error code otherwise.
3530 */
3531int
3532zfs_unmount_snap(const char *snapname)
3533{
3534	vfs_t *vfsp;
3535	zfsvfs_t *zfsvfs;
3536	int err;
3537
3538	if (strchr(snapname, '@') == NULL)
3539		return (0);
3540
3541	vfsp = zfs_get_vfs(snapname);
3542	if (vfsp == NULL)
3543		return (0);
3544
3545	zfsvfs = vfsp->vfs_data;
3546	ASSERT(!dsl_pool_config_held(dmu_objset_pool(zfsvfs->z_os)));
3547
3548	err = vn_vfswlock(vfsp->vfs_vnodecovered);
3549#ifdef illumos
3550	VFS_RELE(vfsp);
3551#else
3552	vfs_unbusy(vfsp);
3553#endif
3554	if (err != 0)
3555		return (SET_ERROR(err));
3556
3557	/*
3558	 * Always force the unmount for snapshots.
3559	 */
3560
3561#ifdef illumos
3562	(void) dounmount(vfsp, MS_FORCE, kcred);
3563#else
3564	vfs_ref(vfsp);
3565	(void) dounmount(vfsp, MS_FORCE, curthread);
3566#endif
3567	return (0);
3568}
3569
3570/* ARGSUSED */
3571static int
3572zfs_unmount_snap_cb(const char *snapname, void *arg)
3573{
3574	return (zfs_unmount_snap(snapname));
3575}
3576
3577/*
3578 * When a clone is destroyed, its origin may also need to be destroyed,
3579 * in which case it must be unmounted.  This routine will do that unmount
3580 * if necessary.
3581 */
3582void
3583zfs_destroy_unmount_origin(const char *fsname)
3584{
3585	int error;
3586	objset_t *os;
3587	dsl_dataset_t *ds;
3588
3589	error = dmu_objset_hold(fsname, FTAG, &os);
3590	if (error != 0)
3591		return;
3592	ds = dmu_objset_ds(os);
3593	if (dsl_dir_is_clone(ds->ds_dir) && DS_IS_DEFER_DESTROY(ds->ds_prev)) {
3594		char originname[ZFS_MAX_DATASET_NAME_LEN];
3595		dsl_dataset_name(ds->ds_prev, originname);
3596		dmu_objset_rele(os, FTAG);
3597		(void) zfs_unmount_snap(originname);
3598	} else {
3599		dmu_objset_rele(os, FTAG);
3600	}
3601}
3602
3603/*
3604 * innvl: {
3605 *     "snaps" -> { snapshot1, snapshot2 }
3606 *     (optional boolean) "defer"
3607 * }
3608 *
3609 * outnvl: snapshot -> error code (int32)
3610 *
3611 */
3612/* ARGSUSED */
3613static int
3614zfs_ioc_destroy_snaps(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3615{
3616	int error, poollen;
3617	nvlist_t *snaps;
3618	nvpair_t *pair;
3619	boolean_t defer;
3620
3621	if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3622		return (SET_ERROR(EINVAL));
3623	defer = nvlist_exists(innvl, "defer");
3624
3625	poollen = strlen(poolname);
3626	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3627	    pair = nvlist_next_nvpair(snaps, pair)) {
3628		const char *name = nvpair_name(pair);
3629
3630		/*
3631		 * The snap must be in the specified pool to prevent the
3632		 * invalid removal of zvol minors below.
3633		 */
3634		if (strncmp(name, poolname, poollen) != 0 ||
3635		    (name[poollen] != '/' && name[poollen] != '@'))
3636			return (SET_ERROR(EXDEV));
3637
3638		error = zfs_unmount_snap(name);
3639		if (error != 0)
3640			return (error);
3641#if defined(__FreeBSD__)
3642		zvol_remove_minors(name);
3643#endif
3644	}
3645
3646	return (dsl_destroy_snapshots_nvl(snaps, defer, outnvl));
3647}
3648
3649/*
3650 * Create bookmarks.  Bookmark names are of the form <fs>#<bmark>.
3651 * All bookmarks must be in the same pool.
3652 *
3653 * innvl: {
3654 *     bookmark1 -> snapshot1, bookmark2 -> snapshot2
3655 * }
3656 *
3657 * outnvl: bookmark -> error code (int32)
3658 *
3659 */
3660/* ARGSUSED */
3661static int
3662zfs_ioc_bookmark(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3663{
3664	for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3665	    pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3666		char *snap_name;
3667
3668		/*
3669		 * Verify the snapshot argument.
3670		 */
3671		if (nvpair_value_string(pair, &snap_name) != 0)
3672			return (SET_ERROR(EINVAL));
3673
3674
3675		/* Verify that the keys (bookmarks) are unique */
3676		for (nvpair_t *pair2 = nvlist_next_nvpair(innvl, pair);
3677		    pair2 != NULL; pair2 = nvlist_next_nvpair(innvl, pair2)) {
3678			if (strcmp(nvpair_name(pair), nvpair_name(pair2)) == 0)
3679				return (SET_ERROR(EINVAL));
3680		}
3681	}
3682
3683	return (dsl_bookmark_create(innvl, outnvl));
3684}
3685
3686/*
3687 * innvl: {
3688 *     property 1, property 2, ...
3689 * }
3690 *
3691 * outnvl: {
3692 *     bookmark name 1 -> { property 1, property 2, ... },
3693 *     bookmark name 2 -> { property 1, property 2, ... }
3694 * }
3695 *
3696 */
3697static int
3698zfs_ioc_get_bookmarks(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3699{
3700	return (dsl_get_bookmarks(fsname, innvl, outnvl));
3701}
3702
3703/*
3704 * innvl: {
3705 *     bookmark name 1, bookmark name 2
3706 * }
3707 *
3708 * outnvl: bookmark -> error code (int32)
3709 *
3710 */
3711static int
3712zfs_ioc_destroy_bookmarks(const char *poolname, nvlist_t *innvl,
3713    nvlist_t *outnvl)
3714{
3715	int error, poollen;
3716
3717	poollen = strlen(poolname);
3718	for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3719	    pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3720		const char *name = nvpair_name(pair);
3721		const char *cp = strchr(name, '#');
3722
3723		/*
3724		 * The bookmark name must contain an #, and the part after it
3725		 * must contain only valid characters.
3726		 */
3727		if (cp == NULL ||
3728		    zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3729			return (SET_ERROR(EINVAL));
3730
3731		/*
3732		 * The bookmark must be in the specified pool.
3733		 */
3734		if (strncmp(name, poolname, poollen) != 0 ||
3735		    (name[poollen] != '/' && name[poollen] != '#'))
3736			return (SET_ERROR(EXDEV));
3737	}
3738
3739	error = dsl_bookmark_destroy(innvl, outnvl);
3740	return (error);
3741}
3742
3743/*
3744 * inputs:
3745 * zc_name		name of dataset to destroy
3746 * zc_objset_type	type of objset
3747 * zc_defer_destroy	mark for deferred destroy
3748 *
3749 * outputs:		none
3750 */
3751static int
3752zfs_ioc_destroy(zfs_cmd_t *zc)
3753{
3754	int err;
3755
3756	if (zc->zc_objset_type == DMU_OST_ZFS) {
3757		err = zfs_unmount_snap(zc->zc_name);
3758		if (err != 0)
3759			return (err);
3760	}
3761
3762	if (strchr(zc->zc_name, '@'))
3763		err = dsl_destroy_snapshot(zc->zc_name, zc->zc_defer_destroy);
3764	else
3765		err = dsl_destroy_head(zc->zc_name);
3766	if (zc->zc_objset_type == DMU_OST_ZVOL && err == 0)
3767#ifdef __FreeBSD__
3768		zvol_remove_minors(zc->zc_name);
3769#else
3770		(void) zvol_remove_minor(zc->zc_name);
3771#endif
3772	return (err);
3773}
3774
3775/*
3776 * fsname is name of dataset to rollback (to most recent snapshot)
3777 *
3778 * innvl is not used.
3779 *
3780 * outnvl: "target" -> name of most recent snapshot
3781 * }
3782 */
3783/* ARGSUSED */
3784static int
3785zfs_ioc_rollback(const char *fsname, nvlist_t *args, nvlist_t *outnvl)
3786{
3787	zfsvfs_t *zfsvfs;
3788	int error;
3789
3790	if (getzfsvfs(fsname, &zfsvfs) == 0) {
3791		dsl_dataset_t *ds;
3792
3793		ds = dmu_objset_ds(zfsvfs->z_os);
3794		error = zfs_suspend_fs(zfsvfs);
3795		if (error == 0) {
3796			int resume_err;
3797
3798			error = dsl_dataset_rollback(fsname, zfsvfs, outnvl);
3799			resume_err = zfs_resume_fs(zfsvfs, ds);
3800			error = error ? error : resume_err;
3801		}
3802#ifdef illumos
3803		VFS_RELE(zfsvfs->z_vfs);
3804#else
3805		vfs_unbusy(zfsvfs->z_vfs);
3806#endif
3807	} else {
3808		error = dsl_dataset_rollback(fsname, NULL, outnvl);
3809	}
3810	return (error);
3811}
3812
3813static int
3814recursive_unmount(const char *fsname, void *arg)
3815{
3816	const char *snapname = arg;
3817	char fullname[ZFS_MAX_DATASET_NAME_LEN];
3818
3819	(void) snprintf(fullname, sizeof (fullname), "%s@%s", fsname, snapname);
3820	return (zfs_unmount_snap(fullname));
3821}
3822
3823/*
3824 * inputs:
3825 * zc_name	old name of dataset
3826 * zc_value	new name of dataset
3827 * zc_cookie	recursive flag (only valid for snapshots)
3828 *
3829 * outputs:	none
3830 */
3831static int
3832zfs_ioc_rename(zfs_cmd_t *zc)
3833{
3834	boolean_t recursive = zc->zc_cookie & 1;
3835	char *at;
3836	boolean_t allow_mounted = B_TRUE;
3837
3838#ifdef __FreeBSD__
3839	allow_mounted = (zc->zc_cookie & 2) != 0;
3840#endif
3841
3842	zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3843	if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3844	    strchr(zc->zc_value, '%'))
3845		return (SET_ERROR(EINVAL));
3846
3847	at = strchr(zc->zc_name, '@');
3848	if (at != NULL) {
3849		/* snaps must be in same fs */
3850		int error;
3851
3852		if (strncmp(zc->zc_name, zc->zc_value, at - zc->zc_name + 1))
3853			return (SET_ERROR(EXDEV));
3854		*at = '\0';
3855		if (zc->zc_objset_type == DMU_OST_ZFS && !allow_mounted) {
3856			error = dmu_objset_find(zc->zc_name,
3857			    recursive_unmount, at + 1,
3858			    recursive ? DS_FIND_CHILDREN : 0);
3859			if (error != 0) {
3860				*at = '@';
3861				return (error);
3862			}
3863		}
3864		error = dsl_dataset_rename_snapshot(zc->zc_name,
3865		    at + 1, strchr(zc->zc_value, '@') + 1, recursive);
3866		*at = '@';
3867
3868		return (error);
3869	} else {
3870#ifdef illumos
3871		if (zc->zc_objset_type == DMU_OST_ZVOL)
3872			(void) zvol_remove_minor(zc->zc_name);
3873#endif
3874		return (dsl_dir_rename(zc->zc_name, zc->zc_value));
3875	}
3876}
3877
3878static int
3879zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3880{
3881	const char *propname = nvpair_name(pair);
3882	boolean_t issnap = (strchr(dsname, '@') != NULL);
3883	zfs_prop_t prop = zfs_name_to_prop(propname);
3884	uint64_t intval;
3885	int err;
3886
3887	if (prop == ZPROP_INVAL) {
3888		if (zfs_prop_user(propname)) {
3889			if (err = zfs_secpolicy_write_perms(dsname,
3890			    ZFS_DELEG_PERM_USERPROP, cr))
3891				return (err);
3892			return (0);
3893		}
3894
3895		if (!issnap && zfs_prop_userquota(propname)) {
3896			const char *perm = NULL;
3897			const char *uq_prefix =
3898			    zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3899			const char *gq_prefix =
3900			    zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3901
3902			if (strncmp(propname, uq_prefix,
3903			    strlen(uq_prefix)) == 0) {
3904				perm = ZFS_DELEG_PERM_USERQUOTA;
3905			} else if (strncmp(propname, gq_prefix,
3906			    strlen(gq_prefix)) == 0) {
3907				perm = ZFS_DELEG_PERM_GROUPQUOTA;
3908			} else {
3909				/* USERUSED and GROUPUSED are read-only */
3910				return (SET_ERROR(EINVAL));
3911			}
3912
3913			if (err = zfs_secpolicy_write_perms(dsname, perm, cr))
3914				return (err);
3915			return (0);
3916		}
3917
3918		return (SET_ERROR(EINVAL));
3919	}
3920
3921	if (issnap)
3922		return (SET_ERROR(EINVAL));
3923
3924	if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3925		/*
3926		 * dsl_prop_get_all_impl() returns properties in this
3927		 * format.
3928		 */
3929		nvlist_t *attrs;
3930		VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3931		VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3932		    &pair) == 0);
3933	}
3934
3935	/*
3936	 * Check that this value is valid for this pool version
3937	 */
3938	switch (prop) {
3939	case ZFS_PROP_COMPRESSION:
3940		/*
3941		 * If the user specified gzip compression, make sure
3942		 * the SPA supports it. We ignore any errors here since
3943		 * we'll catch them later.
3944		 */
3945		if (nvpair_value_uint64(pair, &intval) == 0) {
3946			if (intval >= ZIO_COMPRESS_GZIP_1 &&
3947			    intval <= ZIO_COMPRESS_GZIP_9 &&
3948			    zfs_earlier_version(dsname,
3949			    SPA_VERSION_GZIP_COMPRESSION)) {
3950				return (SET_ERROR(ENOTSUP));
3951			}
3952
3953			if (intval == ZIO_COMPRESS_ZLE &&
3954			    zfs_earlier_version(dsname,
3955			    SPA_VERSION_ZLE_COMPRESSION))
3956				return (SET_ERROR(ENOTSUP));
3957
3958			if (intval == ZIO_COMPRESS_LZ4) {
3959				spa_t *spa;
3960
3961				if ((err = spa_open(dsname, &spa, FTAG)) != 0)
3962					return (err);
3963
3964				if (!spa_feature_is_enabled(spa,
3965				    SPA_FEATURE_LZ4_COMPRESS)) {
3966					spa_close(spa, FTAG);
3967					return (SET_ERROR(ENOTSUP));
3968				}
3969				spa_close(spa, FTAG);
3970			}
3971
3972			/*
3973			 * If this is a bootable dataset then
3974			 * verify that the compression algorithm
3975			 * is supported for booting. We must return
3976			 * something other than ENOTSUP since it
3977			 * implies a downrev pool version.
3978			 */
3979			if (zfs_is_bootfs(dsname) &&
3980			    !BOOTFS_COMPRESS_VALID(intval)) {
3981				return (SET_ERROR(ERANGE));
3982			}
3983		}
3984		break;
3985
3986	case ZFS_PROP_COPIES:
3987		if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
3988			return (SET_ERROR(ENOTSUP));
3989		break;
3990
3991	case ZFS_PROP_RECORDSIZE:
3992		/* Record sizes above 128k need the feature to be enabled */
3993		if (nvpair_value_uint64(pair, &intval) == 0 &&
3994		    intval > SPA_OLD_MAXBLOCKSIZE) {
3995			spa_t *spa;
3996
3997			/*
3998			 * If this is a bootable dataset then
3999			 * the we don't allow large (>128K) blocks,
4000			 * because GRUB doesn't support them.
4001			 */
4002			if (zfs_is_bootfs(dsname) &&
4003			    intval > SPA_OLD_MAXBLOCKSIZE) {
4004				return (SET_ERROR(ERANGE));
4005			}
4006
4007			/*
4008			 * We don't allow setting the property above 1MB,
4009			 * unless the tunable has been changed.
4010			 */
4011			if (intval > zfs_max_recordsize ||
4012			    intval > SPA_MAXBLOCKSIZE)
4013				return (SET_ERROR(ERANGE));
4014
4015			if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4016				return (err);
4017
4018			if (!spa_feature_is_enabled(spa,
4019			    SPA_FEATURE_LARGE_BLOCKS)) {
4020				spa_close(spa, FTAG);
4021				return (SET_ERROR(ENOTSUP));
4022			}
4023			spa_close(spa, FTAG);
4024		}
4025		break;
4026
4027	case ZFS_PROP_SHARESMB:
4028		if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
4029			return (SET_ERROR(ENOTSUP));
4030		break;
4031
4032	case ZFS_PROP_ACLINHERIT:
4033		if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
4034		    nvpair_value_uint64(pair, &intval) == 0) {
4035			if (intval == ZFS_ACL_PASSTHROUGH_X &&
4036			    zfs_earlier_version(dsname,
4037			    SPA_VERSION_PASSTHROUGH_X))
4038				return (SET_ERROR(ENOTSUP));
4039		}
4040		break;
4041
4042	case ZFS_PROP_CHECKSUM:
4043	case ZFS_PROP_DEDUP:
4044	{
4045		spa_feature_t feature;
4046		spa_t *spa;
4047
4048		/* dedup feature version checks */
4049		if (prop == ZFS_PROP_DEDUP &&
4050		    zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
4051			return (SET_ERROR(ENOTSUP));
4052
4053		if (nvpair_value_uint64(pair, &intval) != 0)
4054			return (SET_ERROR(EINVAL));
4055
4056		/* check prop value is enabled in features */
4057		feature = zio_checksum_to_feature(intval & ZIO_CHECKSUM_MASK);
4058		if (feature == SPA_FEATURE_NONE)
4059			break;
4060
4061		if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4062			return (err);
4063		/*
4064		 * Salted checksums are not supported on root pools.
4065		 */
4066		if (spa_bootfs(spa) != 0 &&
4067		    intval < ZIO_CHECKSUM_FUNCTIONS &&
4068		    (zio_checksum_table[intval].ci_flags &
4069		    ZCHECKSUM_FLAG_SALTED)) {
4070			spa_close(spa, FTAG);
4071			return (SET_ERROR(ERANGE));
4072		}
4073		if (!spa_feature_is_enabled(spa, feature)) {
4074			spa_close(spa, FTAG);
4075			return (SET_ERROR(ENOTSUP));
4076		}
4077		spa_close(spa, FTAG);
4078		break;
4079	}
4080	}
4081
4082	return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
4083}
4084
4085/*
4086 * Checks for a race condition to make sure we don't increment a feature flag
4087 * multiple times.
4088 */
4089static int
4090zfs_prop_activate_feature_check(void *arg, dmu_tx_t *tx)
4091{
4092	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4093	spa_feature_t *featurep = arg;
4094
4095	if (!spa_feature_is_active(spa, *featurep))
4096		return (0);
4097	else
4098		return (SET_ERROR(EBUSY));
4099}
4100
4101/*
4102 * The callback invoked on feature activation in the sync task caused by
4103 * zfs_prop_activate_feature.
4104 */
4105static void
4106zfs_prop_activate_feature_sync(void *arg, dmu_tx_t *tx)
4107{
4108	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4109	spa_feature_t *featurep = arg;
4110
4111	spa_feature_incr(spa, *featurep, tx);
4112}
4113
4114/*
4115 * Activates a feature on a pool in response to a property setting. This
4116 * creates a new sync task which modifies the pool to reflect the feature
4117 * as being active.
4118 */
4119static int
4120zfs_prop_activate_feature(spa_t *spa, spa_feature_t feature)
4121{
4122	int err;
4123
4124	/* EBUSY here indicates that the feature is already active */
4125	err = dsl_sync_task(spa_name(spa),
4126	    zfs_prop_activate_feature_check, zfs_prop_activate_feature_sync,
4127	    &feature, 2, ZFS_SPACE_CHECK_RESERVED);
4128
4129	if (err != 0 && err != EBUSY)
4130		return (err);
4131	else
4132		return (0);
4133}
4134
4135/*
4136 * Removes properties from the given props list that fail permission checks
4137 * needed to clear them and to restore them in case of a receive error. For each
4138 * property, make sure we have both set and inherit permissions.
4139 *
4140 * Returns the first error encountered if any permission checks fail. If the
4141 * caller provides a non-NULL errlist, it also gives the complete list of names
4142 * of all the properties that failed a permission check along with the
4143 * corresponding error numbers. The caller is responsible for freeing the
4144 * returned errlist.
4145 *
4146 * If every property checks out successfully, zero is returned and the list
4147 * pointed at by errlist is NULL.
4148 */
4149static int
4150zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
4151{
4152	zfs_cmd_t *zc;
4153	nvpair_t *pair, *next_pair;
4154	nvlist_t *errors;
4155	int err, rv = 0;
4156
4157	if (props == NULL)
4158		return (0);
4159
4160	VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4161
4162	zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
4163	(void) strcpy(zc->zc_name, dataset);
4164	pair = nvlist_next_nvpair(props, NULL);
4165	while (pair != NULL) {
4166		next_pair = nvlist_next_nvpair(props, pair);
4167
4168		(void) strcpy(zc->zc_value, nvpair_name(pair));
4169		if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
4170		    (err = zfs_secpolicy_inherit_prop(zc, NULL, CRED())) != 0) {
4171			VERIFY(nvlist_remove_nvpair(props, pair) == 0);
4172			VERIFY(nvlist_add_int32(errors,
4173			    zc->zc_value, err) == 0);
4174		}
4175		pair = next_pair;
4176	}
4177	kmem_free(zc, sizeof (zfs_cmd_t));
4178
4179	if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
4180		nvlist_free(errors);
4181		errors = NULL;
4182	} else {
4183		VERIFY(nvpair_value_int32(pair, &rv) == 0);
4184	}
4185
4186	if (errlist == NULL)
4187		nvlist_free(errors);
4188	else
4189		*errlist = errors;
4190
4191	return (rv);
4192}
4193
4194static boolean_t
4195propval_equals(nvpair_t *p1, nvpair_t *p2)
4196{
4197	if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
4198		/* dsl_prop_get_all_impl() format */
4199		nvlist_t *attrs;
4200		VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
4201		VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4202		    &p1) == 0);
4203	}
4204
4205	if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
4206		nvlist_t *attrs;
4207		VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
4208		VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4209		    &p2) == 0);
4210	}
4211
4212	if (nvpair_type(p1) != nvpair_type(p2))
4213		return (B_FALSE);
4214
4215	if (nvpair_type(p1) == DATA_TYPE_STRING) {
4216		char *valstr1, *valstr2;
4217
4218		VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
4219		VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
4220		return (strcmp(valstr1, valstr2) == 0);
4221	} else {
4222		uint64_t intval1, intval2;
4223
4224		VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
4225		VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
4226		return (intval1 == intval2);
4227	}
4228}
4229
4230/*
4231 * Remove properties from props if they are not going to change (as determined
4232 * by comparison with origprops). Remove them from origprops as well, since we
4233 * do not need to clear or restore properties that won't change.
4234 */
4235static void
4236props_reduce(nvlist_t *props, nvlist_t *origprops)
4237{
4238	nvpair_t *pair, *next_pair;
4239
4240	if (origprops == NULL)
4241		return; /* all props need to be received */
4242
4243	pair = nvlist_next_nvpair(props, NULL);
4244	while (pair != NULL) {
4245		const char *propname = nvpair_name(pair);
4246		nvpair_t *match;
4247
4248		next_pair = nvlist_next_nvpair(props, pair);
4249
4250		if ((nvlist_lookup_nvpair(origprops, propname,
4251		    &match) != 0) || !propval_equals(pair, match))
4252			goto next; /* need to set received value */
4253
4254		/* don't clear the existing received value */
4255		(void) nvlist_remove_nvpair(origprops, match);
4256		/* don't bother receiving the property */
4257		(void) nvlist_remove_nvpair(props, pair);
4258next:
4259		pair = next_pair;
4260	}
4261}
4262
4263/*
4264 * Extract properties that cannot be set PRIOR to the receipt of a dataset.
4265 * For example, refquota cannot be set until after the receipt of a dataset,
4266 * because in replication streams, an older/earlier snapshot may exceed the
4267 * refquota.  We want to receive the older/earlier snapshot, but setting
4268 * refquota pre-receipt will set the dsl's ACTUAL quota, which will prevent
4269 * the older/earlier snapshot from being received (with EDQUOT).
4270 *
4271 * The ZFS test "zfs_receive_011_pos" demonstrates such a scenario.
4272 *
4273 * libzfs will need to be judicious handling errors encountered by props
4274 * extracted by this function.
4275 */
4276static nvlist_t *
4277extract_delay_props(nvlist_t *props)
4278{
4279	nvlist_t *delayprops;
4280	nvpair_t *nvp, *tmp;
4281	static const zfs_prop_t delayable[] = { ZFS_PROP_REFQUOTA, 0 };
4282	int i;
4283
4284	VERIFY(nvlist_alloc(&delayprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4285
4286	for (nvp = nvlist_next_nvpair(props, NULL); nvp != NULL;
4287	    nvp = nvlist_next_nvpair(props, nvp)) {
4288		/*
4289		 * strcmp() is safe because zfs_prop_to_name() always returns
4290		 * a bounded string.
4291		 */
4292		for (i = 0; delayable[i] != 0; i++) {
4293			if (strcmp(zfs_prop_to_name(delayable[i]),
4294			    nvpair_name(nvp)) == 0) {
4295				break;
4296			}
4297		}
4298		if (delayable[i] != 0) {
4299			tmp = nvlist_prev_nvpair(props, nvp);
4300			VERIFY(nvlist_add_nvpair(delayprops, nvp) == 0);
4301			VERIFY(nvlist_remove_nvpair(props, nvp) == 0);
4302			nvp = tmp;
4303		}
4304	}
4305
4306	if (nvlist_empty(delayprops)) {
4307		nvlist_free(delayprops);
4308		delayprops = NULL;
4309	}
4310	return (delayprops);
4311}
4312
4313#ifdef	DEBUG
4314static boolean_t zfs_ioc_recv_inject_err;
4315#endif
4316
4317/*
4318 * inputs:
4319 * zc_name		name of containing filesystem
4320 * zc_nvlist_src{_size}	nvlist of properties to apply
4321 * zc_value		name of snapshot to create
4322 * zc_string		name of clone origin (if DRR_FLAG_CLONE)
4323 * zc_cookie		file descriptor to recv from
4324 * zc_begin_record	the BEGIN record of the stream (not byteswapped)
4325 * zc_guid		force flag
4326 * zc_cleanup_fd	cleanup-on-exit file descriptor
4327 * zc_action_handle	handle for this guid/ds mapping (or zero on first call)
4328 * zc_resumable		if data is incomplete assume sender will resume
4329 *
4330 * outputs:
4331 * zc_cookie		number of bytes read
4332 * zc_nvlist_dst{_size} error for each unapplied received property
4333 * zc_obj		zprop_errflags_t
4334 * zc_action_handle	handle for this guid/ds mapping
4335 */
4336static int
4337zfs_ioc_recv(zfs_cmd_t *zc)
4338{
4339	file_t *fp;
4340	dmu_recv_cookie_t drc;
4341	boolean_t force = (boolean_t)zc->zc_guid;
4342	int fd;
4343	int error = 0;
4344	int props_error = 0;
4345	nvlist_t *errors;
4346	offset_t off;
4347	nvlist_t *props = NULL; /* sent properties */
4348	nvlist_t *origprops = NULL; /* existing properties */
4349	nvlist_t *delayprops = NULL; /* sent properties applied post-receive */
4350	char *origin = NULL;
4351	char *tosnap;
4352	char tofs[ZFS_MAX_DATASET_NAME_LEN];
4353	cap_rights_t rights;
4354	boolean_t first_recvd_props = B_FALSE;
4355
4356	if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
4357	    strchr(zc->zc_value, '@') == NULL ||
4358	    strchr(zc->zc_value, '%'))
4359		return (SET_ERROR(EINVAL));
4360
4361	(void) strcpy(tofs, zc->zc_value);
4362	tosnap = strchr(tofs, '@');
4363	*tosnap++ = '\0';
4364
4365	if (zc->zc_nvlist_src != 0 &&
4366	    (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
4367	    zc->zc_iflags, &props)) != 0)
4368		return (error);
4369
4370	fd = zc->zc_cookie;
4371#ifdef illumos
4372	fp = getf(fd);
4373#else
4374	fget_read(curthread, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
4375#endif
4376	if (fp == NULL) {
4377		nvlist_free(props);
4378		return (SET_ERROR(EBADF));
4379	}
4380
4381	errors = fnvlist_alloc();
4382
4383	if (zc->zc_string[0])
4384		origin = zc->zc_string;
4385
4386	error = dmu_recv_begin(tofs, tosnap,
4387	    &zc->zc_begin_record, force, zc->zc_resumable, origin, &drc);
4388	if (error != 0)
4389		goto out;
4390
4391	/*
4392	 * Set properties before we receive the stream so that they are applied
4393	 * to the new data. Note that we must call dmu_recv_stream() if
4394	 * dmu_recv_begin() succeeds.
4395	 */
4396	if (props != NULL && !drc.drc_newfs) {
4397		if (spa_version(dsl_dataset_get_spa(drc.drc_ds)) >=
4398		    SPA_VERSION_RECVD_PROPS &&
4399		    !dsl_prop_get_hasrecvd(tofs))
4400			first_recvd_props = B_TRUE;
4401
4402		/*
4403		 * If new received properties are supplied, they are to
4404		 * completely replace the existing received properties, so stash
4405		 * away the existing ones.
4406		 */
4407		if (dsl_prop_get_received(tofs, &origprops) == 0) {
4408			nvlist_t *errlist = NULL;
4409			/*
4410			 * Don't bother writing a property if its value won't
4411			 * change (and avoid the unnecessary security checks).
4412			 *
4413			 * The first receive after SPA_VERSION_RECVD_PROPS is a
4414			 * special case where we blow away all local properties
4415			 * regardless.
4416			 */
4417			if (!first_recvd_props)
4418				props_reduce(props, origprops);
4419			if (zfs_check_clearable(tofs, origprops, &errlist) != 0)
4420				(void) nvlist_merge(errors, errlist, 0);
4421			nvlist_free(errlist);
4422
4423			if (clear_received_props(tofs, origprops,
4424			    first_recvd_props ? NULL : props) != 0)
4425				zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4426		} else {
4427			zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4428		}
4429	}
4430
4431	if (props != NULL) {
4432		props_error = dsl_prop_set_hasrecvd(tofs);
4433
4434		if (props_error == 0) {
4435			delayprops = extract_delay_props(props);
4436			(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4437			    props, errors);
4438		}
4439	}
4440
4441	off = fp->f_offset;
4442	error = dmu_recv_stream(&drc, fp, &off, zc->zc_cleanup_fd,
4443	    &zc->zc_action_handle);
4444
4445	if (error == 0) {
4446		zfsvfs_t *zfsvfs = NULL;
4447
4448		if (getzfsvfs(tofs, &zfsvfs) == 0) {
4449			/* online recv */
4450			dsl_dataset_t *ds;
4451			int end_err;
4452
4453			ds = dmu_objset_ds(zfsvfs->z_os);
4454			error = zfs_suspend_fs(zfsvfs);
4455			/*
4456			 * If the suspend fails, then the recv_end will
4457			 * likely also fail, and clean up after itself.
4458			 */
4459			end_err = dmu_recv_end(&drc, zfsvfs);
4460			if (error == 0)
4461				error = zfs_resume_fs(zfsvfs, ds);
4462			error = error ? error : end_err;
4463#ifdef illumos
4464			VFS_RELE(zfsvfs->z_vfs);
4465#else
4466			vfs_unbusy(zfsvfs->z_vfs);
4467#endif
4468		} else {
4469			error = dmu_recv_end(&drc, NULL);
4470		}
4471
4472		/* Set delayed properties now, after we're done receiving. */
4473		if (delayprops != NULL && error == 0) {
4474			(void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4475			    delayprops, errors);
4476		}
4477	}
4478
4479	if (delayprops != NULL) {
4480		/*
4481		 * Merge delayed props back in with initial props, in case
4482		 * we're DEBUG and zfs_ioc_recv_inject_err is set (which means
4483		 * we have to make sure clear_received_props() includes
4484		 * the delayed properties).
4485		 *
4486		 * Since zfs_ioc_recv_inject_err is only in DEBUG kernels,
4487		 * using ASSERT() will be just like a VERIFY.
4488		 */
4489		ASSERT(nvlist_merge(props, delayprops, 0) == 0);
4490		nvlist_free(delayprops);
4491	}
4492
4493	/*
4494	 * Now that all props, initial and delayed, are set, report the prop
4495	 * errors to the caller.
4496	 */
4497	if (zc->zc_nvlist_dst_size != 0 &&
4498	    (nvlist_smush(errors, zc->zc_nvlist_dst_size) != 0 ||
4499	    put_nvlist(zc, errors) != 0)) {
4500		/*
4501		 * Caller made zc->zc_nvlist_dst less than the minimum expected
4502		 * size or supplied an invalid address.
4503		 */
4504		props_error = SET_ERROR(EINVAL);
4505	}
4506
4507	zc->zc_cookie = off - fp->f_offset;
4508	if (off >= 0 && off <= MAXOFFSET_T)
4509		fp->f_offset = off;
4510
4511#ifdef	DEBUG
4512	if (zfs_ioc_recv_inject_err) {
4513		zfs_ioc_recv_inject_err = B_FALSE;
4514		error = 1;
4515	}
4516#endif
4517
4518#ifdef __FreeBSD__
4519	if (error == 0)
4520		zvol_create_minors(tofs);
4521#endif
4522
4523	/*
4524	 * On error, restore the original props.
4525	 */
4526	if (error != 0 && props != NULL && !drc.drc_newfs) {
4527		if (clear_received_props(tofs, props, NULL) != 0) {
4528			/*
4529			 * We failed to clear the received properties.
4530			 * Since we may have left a $recvd value on the
4531			 * system, we can't clear the $hasrecvd flag.
4532			 */
4533			zc->zc_obj |= ZPROP_ERR_NORESTORE;
4534		} else if (first_recvd_props) {
4535			dsl_prop_unset_hasrecvd(tofs);
4536		}
4537
4538		if (origprops == NULL && !drc.drc_newfs) {
4539			/* We failed to stash the original properties. */
4540			zc->zc_obj |= ZPROP_ERR_NORESTORE;
4541		}
4542
4543		/*
4544		 * dsl_props_set() will not convert RECEIVED to LOCAL on or
4545		 * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
4546		 * explictly if we're restoring local properties cleared in the
4547		 * first new-style receive.
4548		 */
4549		if (origprops != NULL &&
4550		    zfs_set_prop_nvlist(tofs, (first_recvd_props ?
4551		    ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
4552		    origprops, NULL) != 0) {
4553			/*
4554			 * We stashed the original properties but failed to
4555			 * restore them.
4556			 */
4557			zc->zc_obj |= ZPROP_ERR_NORESTORE;
4558		}
4559	}
4560out:
4561	nvlist_free(props);
4562	nvlist_free(origprops);
4563	nvlist_free(errors);
4564	releasef(fd);
4565
4566	if (error == 0)
4567		error = props_error;
4568
4569	return (error);
4570}
4571
4572/*
4573 * inputs:
4574 * zc_name	name of snapshot to send
4575 * zc_cookie	file descriptor to send stream to
4576 * zc_obj	fromorigin flag (mutually exclusive with zc_fromobj)
4577 * zc_sendobj	objsetid of snapshot to send
4578 * zc_fromobj	objsetid of incremental fromsnap (may be zero)
4579 * zc_guid	if set, estimate size of stream only.  zc_cookie is ignored.
4580 *		output size in zc_objset_type.
4581 * zc_flags	lzc_send_flags
4582 *
4583 * outputs:
4584 * zc_objset_type	estimated size, if zc_guid is set
4585 */
4586static int
4587zfs_ioc_send(zfs_cmd_t *zc)
4588{
4589	int error;
4590	offset_t off;
4591	boolean_t estimate = (zc->zc_guid != 0);
4592	boolean_t embedok = (zc->zc_flags & 0x1);
4593	boolean_t large_block_ok = (zc->zc_flags & 0x2);
4594
4595	if (zc->zc_obj != 0) {
4596		dsl_pool_t *dp;
4597		dsl_dataset_t *tosnap;
4598
4599		error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4600		if (error != 0)
4601			return (error);
4602
4603		error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4604		if (error != 0) {
4605			dsl_pool_rele(dp, FTAG);
4606			return (error);
4607		}
4608
4609		if (dsl_dir_is_clone(tosnap->ds_dir))
4610			zc->zc_fromobj =
4611			    dsl_dir_phys(tosnap->ds_dir)->dd_origin_obj;
4612		dsl_dataset_rele(tosnap, FTAG);
4613		dsl_pool_rele(dp, FTAG);
4614	}
4615
4616	if (estimate) {
4617		dsl_pool_t *dp;
4618		dsl_dataset_t *tosnap;
4619		dsl_dataset_t *fromsnap = NULL;
4620
4621		error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4622		if (error != 0)
4623			return (error);
4624
4625		error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4626		if (error != 0) {
4627			dsl_pool_rele(dp, FTAG);
4628			return (error);
4629		}
4630
4631		if (zc->zc_fromobj != 0) {
4632			error = dsl_dataset_hold_obj(dp, zc->zc_fromobj,
4633			    FTAG, &fromsnap);
4634			if (error != 0) {
4635				dsl_dataset_rele(tosnap, FTAG);
4636				dsl_pool_rele(dp, FTAG);
4637				return (error);
4638			}
4639		}
4640
4641		error = dmu_send_estimate(tosnap, fromsnap,
4642		    &zc->zc_objset_type);
4643
4644		if (fromsnap != NULL)
4645			dsl_dataset_rele(fromsnap, FTAG);
4646		dsl_dataset_rele(tosnap, FTAG);
4647		dsl_pool_rele(dp, FTAG);
4648	} else {
4649		file_t *fp;
4650		cap_rights_t rights;
4651
4652#ifdef illumos
4653		fp = getf(zc->zc_cookie);
4654#else
4655		fget_write(curthread, zc->zc_cookie,
4656		    cap_rights_init(&rights, CAP_WRITE), &fp);
4657#endif
4658		if (fp == NULL)
4659			return (SET_ERROR(EBADF));
4660
4661		off = fp->f_offset;
4662		error = dmu_send_obj(zc->zc_name, zc->zc_sendobj,
4663		    zc->zc_fromobj, embedok, large_block_ok,
4664#ifdef illumos
4665		    zc->zc_cookie, fp->f_vnode, &off);
4666#else
4667		    zc->zc_cookie, fp, &off);
4668#endif
4669
4670		if (off >= 0 && off <= MAXOFFSET_T)
4671			fp->f_offset = off;
4672		releasef(zc->zc_cookie);
4673	}
4674	return (error);
4675}
4676
4677/*
4678 * inputs:
4679 * zc_name	name of snapshot on which to report progress
4680 * zc_cookie	file descriptor of send stream
4681 *
4682 * outputs:
4683 * zc_cookie	number of bytes written in send stream thus far
4684 */
4685static int
4686zfs_ioc_send_progress(zfs_cmd_t *zc)
4687{
4688	dsl_pool_t *dp;
4689	dsl_dataset_t *ds;
4690	dmu_sendarg_t *dsp = NULL;
4691	int error;
4692
4693	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4694	if (error != 0)
4695		return (error);
4696
4697	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4698	if (error != 0) {
4699		dsl_pool_rele(dp, FTAG);
4700		return (error);
4701	}
4702
4703	mutex_enter(&ds->ds_sendstream_lock);
4704
4705	/*
4706	 * Iterate over all the send streams currently active on this dataset.
4707	 * If there's one which matches the specified file descriptor _and_ the
4708	 * stream was started by the current process, return the progress of
4709	 * that stream.
4710	 */
4711	for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
4712	    dsp = list_next(&ds->ds_sendstreams, dsp)) {
4713		if (dsp->dsa_outfd == zc->zc_cookie &&
4714		    dsp->dsa_proc == curproc)
4715			break;
4716	}
4717
4718	if (dsp != NULL)
4719		zc->zc_cookie = *(dsp->dsa_off);
4720	else
4721		error = SET_ERROR(ENOENT);
4722
4723	mutex_exit(&ds->ds_sendstream_lock);
4724	dsl_dataset_rele(ds, FTAG);
4725	dsl_pool_rele(dp, FTAG);
4726	return (error);
4727}
4728
4729static int
4730zfs_ioc_inject_fault(zfs_cmd_t *zc)
4731{
4732	int id, error;
4733
4734	error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
4735	    &zc->zc_inject_record);
4736
4737	if (error == 0)
4738		zc->zc_guid = (uint64_t)id;
4739
4740	return (error);
4741}
4742
4743static int
4744zfs_ioc_clear_fault(zfs_cmd_t *zc)
4745{
4746	return (zio_clear_fault((int)zc->zc_guid));
4747}
4748
4749static int
4750zfs_ioc_inject_list_next(zfs_cmd_t *zc)
4751{
4752	int id = (int)zc->zc_guid;
4753	int error;
4754
4755	error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
4756	    &zc->zc_inject_record);
4757
4758	zc->zc_guid = id;
4759
4760	return (error);
4761}
4762
4763static int
4764zfs_ioc_error_log(zfs_cmd_t *zc)
4765{
4766	spa_t *spa;
4767	int error;
4768	size_t count = (size_t)zc->zc_nvlist_dst_size;
4769
4770	if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
4771		return (error);
4772
4773	error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
4774	    &count);
4775	if (error == 0)
4776		zc->zc_nvlist_dst_size = count;
4777	else
4778		zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
4779
4780	spa_close(spa, FTAG);
4781
4782	return (error);
4783}
4784
4785static int
4786zfs_ioc_clear(zfs_cmd_t *zc)
4787{
4788	spa_t *spa;
4789	vdev_t *vd;
4790	int error;
4791
4792	/*
4793	 * On zpool clear we also fix up missing slogs
4794	 */
4795	mutex_enter(&spa_namespace_lock);
4796	spa = spa_lookup(zc->zc_name);
4797	if (spa == NULL) {
4798		mutex_exit(&spa_namespace_lock);
4799		return (SET_ERROR(EIO));
4800	}
4801	if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
4802		/* we need to let spa_open/spa_load clear the chains */
4803		spa_set_log_state(spa, SPA_LOG_CLEAR);
4804	}
4805	spa->spa_last_open_failed = 0;
4806	mutex_exit(&spa_namespace_lock);
4807
4808	if (zc->zc_cookie & ZPOOL_NO_REWIND) {
4809		error = spa_open(zc->zc_name, &spa, FTAG);
4810	} else {
4811		nvlist_t *policy;
4812		nvlist_t *config = NULL;
4813
4814		if (zc->zc_nvlist_src == 0)
4815			return (SET_ERROR(EINVAL));
4816
4817		if ((error = get_nvlist(zc->zc_nvlist_src,
4818		    zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
4819			error = spa_open_rewind(zc->zc_name, &spa, FTAG,
4820			    policy, &config);
4821			if (config != NULL) {
4822				int err;
4823
4824				if ((err = put_nvlist(zc, config)) != 0)
4825					error = err;
4826				nvlist_free(config);
4827			}
4828			nvlist_free(policy);
4829		}
4830	}
4831
4832	if (error != 0)
4833		return (error);
4834
4835	spa_vdev_state_enter(spa, SCL_NONE);
4836
4837	if (zc->zc_guid == 0) {
4838		vd = NULL;
4839	} else {
4840		vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
4841		if (vd == NULL) {
4842			(void) spa_vdev_state_exit(spa, NULL, ENODEV);
4843			spa_close(spa, FTAG);
4844			return (SET_ERROR(ENODEV));
4845		}
4846	}
4847
4848	vdev_clear(spa, vd);
4849
4850	(void) spa_vdev_state_exit(spa, NULL, 0);
4851
4852	/*
4853	 * Resume any suspended I/Os.
4854	 */
4855	if (zio_resume(spa) != 0)
4856		error = SET_ERROR(EIO);
4857
4858	spa_close(spa, FTAG);
4859
4860	return (error);
4861}
4862
4863static int
4864zfs_ioc_pool_reopen(zfs_cmd_t *zc)
4865{
4866	spa_t *spa;
4867	int error;
4868
4869	error = spa_open(zc->zc_name, &spa, FTAG);
4870	if (error != 0)
4871		return (error);
4872
4873	spa_vdev_state_enter(spa, SCL_NONE);
4874
4875	/*
4876	 * If a resilver is already in progress then set the
4877	 * spa_scrub_reopen flag to B_TRUE so that we don't restart
4878	 * the scan as a side effect of the reopen. Otherwise, let
4879	 * vdev_open() decided if a resilver is required.
4880	 */
4881	spa->spa_scrub_reopen = dsl_scan_resilvering(spa->spa_dsl_pool);
4882	vdev_reopen(spa->spa_root_vdev);
4883	spa->spa_scrub_reopen = B_FALSE;
4884
4885	(void) spa_vdev_state_exit(spa, NULL, 0);
4886	spa_close(spa, FTAG);
4887	return (0);
4888}
4889/*
4890 * inputs:
4891 * zc_name	name of filesystem
4892 * zc_value	name of origin snapshot
4893 *
4894 * outputs:
4895 * zc_string	name of conflicting snapshot, if there is one
4896 */
4897static int
4898zfs_ioc_promote(zfs_cmd_t *zc)
4899{
4900	char *cp;
4901
4902	/*
4903	 * We don't need to unmount *all* the origin fs's snapshots, but
4904	 * it's easier.
4905	 */
4906	cp = strchr(zc->zc_value, '@');
4907	if (cp)
4908		*cp = '\0';
4909	(void) dmu_objset_find(zc->zc_value,
4910	    zfs_unmount_snap_cb, NULL, DS_FIND_SNAPSHOTS);
4911	return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
4912}
4913
4914/*
4915 * Retrieve a single {user|group}{used|quota}@... property.
4916 *
4917 * inputs:
4918 * zc_name	name of filesystem
4919 * zc_objset_type zfs_userquota_prop_t
4920 * zc_value	domain name (eg. "S-1-234-567-89")
4921 * zc_guid	RID/UID/GID
4922 *
4923 * outputs:
4924 * zc_cookie	property value
4925 */
4926static int
4927zfs_ioc_userspace_one(zfs_cmd_t *zc)
4928{
4929	zfsvfs_t *zfsvfs;
4930	int error;
4931
4932	if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
4933		return (SET_ERROR(EINVAL));
4934
4935	error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4936	if (error != 0)
4937		return (error);
4938
4939	error = zfs_userspace_one(zfsvfs,
4940	    zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
4941	zfsvfs_rele(zfsvfs, FTAG);
4942
4943	return (error);
4944}
4945
4946/*
4947 * inputs:
4948 * zc_name		name of filesystem
4949 * zc_cookie		zap cursor
4950 * zc_objset_type	zfs_userquota_prop_t
4951 * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
4952 *
4953 * outputs:
4954 * zc_nvlist_dst[_size]	data buffer (array of zfs_useracct_t)
4955 * zc_cookie	zap cursor
4956 */
4957static int
4958zfs_ioc_userspace_many(zfs_cmd_t *zc)
4959{
4960	zfsvfs_t *zfsvfs;
4961	int bufsize = zc->zc_nvlist_dst_size;
4962
4963	if (bufsize <= 0)
4964		return (SET_ERROR(ENOMEM));
4965
4966	int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4967	if (error != 0)
4968		return (error);
4969
4970	void *buf = kmem_alloc(bufsize, KM_SLEEP);
4971
4972	error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
4973	    buf, &zc->zc_nvlist_dst_size);
4974
4975	if (error == 0) {
4976		error = ddi_copyout(buf,
4977		    (void *)(uintptr_t)zc->zc_nvlist_dst,
4978		    zc->zc_nvlist_dst_size, zc->zc_iflags);
4979	}
4980	kmem_free(buf, bufsize);
4981	zfsvfs_rele(zfsvfs, FTAG);
4982
4983	return (error);
4984}
4985
4986/*
4987 * inputs:
4988 * zc_name		name of filesystem
4989 *
4990 * outputs:
4991 * none
4992 */
4993static int
4994zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
4995{
4996	objset_t *os;
4997	int error = 0;
4998	zfsvfs_t *zfsvfs;
4999
5000	if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
5001		if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
5002			/*
5003			 * If userused is not enabled, it may be because the
5004			 * objset needs to be closed & reopened (to grow the
5005			 * objset_phys_t).  Suspend/resume the fs will do that.
5006			 */
5007			dsl_dataset_t *ds;
5008
5009			ds = dmu_objset_ds(zfsvfs->z_os);
5010			error = zfs_suspend_fs(zfsvfs);
5011			if (error == 0) {
5012				dmu_objset_refresh_ownership(zfsvfs->z_os,
5013				    zfsvfs);
5014				error = zfs_resume_fs(zfsvfs, ds);
5015			}
5016		}
5017		if (error == 0)
5018			error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
5019#ifdef illumos
5020		VFS_RELE(zfsvfs->z_vfs);
5021#else
5022		vfs_unbusy(zfsvfs->z_vfs);
5023#endif
5024	} else {
5025		/* XXX kind of reading contents without owning */
5026		error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5027		if (error != 0)
5028			return (error);
5029
5030		error = dmu_objset_userspace_upgrade(os);
5031		dmu_objset_rele(os, FTAG);
5032	}
5033
5034	return (error);
5035}
5036
5037#ifdef illumos
5038/*
5039 * We don't want to have a hard dependency
5040 * against some special symbols in sharefs
5041 * nfs, and smbsrv.  Determine them if needed when
5042 * the first file system is shared.
5043 * Neither sharefs, nfs or smbsrv are unloadable modules.
5044 */
5045int (*znfsexport_fs)(void *arg);
5046int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
5047int (*zsmbexport_fs)(void *arg, boolean_t add_share);
5048
5049int zfs_nfsshare_inited;
5050int zfs_smbshare_inited;
5051
5052ddi_modhandle_t nfs_mod;
5053ddi_modhandle_t sharefs_mod;
5054ddi_modhandle_t smbsrv_mod;
5055#endif	/* illumos */
5056kmutex_t zfs_share_lock;
5057
5058#ifdef illumos
5059static int
5060zfs_init_sharefs()
5061{
5062	int error;
5063
5064	ASSERT(MUTEX_HELD(&zfs_share_lock));
5065	/* Both NFS and SMB shares also require sharetab support. */
5066	if (sharefs_mod == NULL && ((sharefs_mod =
5067	    ddi_modopen("fs/sharefs",
5068	    KRTLD_MODE_FIRST, &error)) == NULL)) {
5069		return (SET_ERROR(ENOSYS));
5070	}
5071	if (zshare_fs == NULL && ((zshare_fs =
5072	    (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
5073	    ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
5074		return (SET_ERROR(ENOSYS));
5075	}
5076	return (0);
5077}
5078#endif	/* illumos */
5079
5080static int
5081zfs_ioc_share(zfs_cmd_t *zc)
5082{
5083#ifdef illumos
5084	int error;
5085	int opcode;
5086
5087	switch (zc->zc_share.z_sharetype) {
5088	case ZFS_SHARE_NFS:
5089	case ZFS_UNSHARE_NFS:
5090		if (zfs_nfsshare_inited == 0) {
5091			mutex_enter(&zfs_share_lock);
5092			if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
5093			    KRTLD_MODE_FIRST, &error)) == NULL)) {
5094				mutex_exit(&zfs_share_lock);
5095				return (SET_ERROR(ENOSYS));
5096			}
5097			if (znfsexport_fs == NULL &&
5098			    ((znfsexport_fs = (int (*)(void *))
5099			    ddi_modsym(nfs_mod,
5100			    "nfs_export", &error)) == NULL)) {
5101				mutex_exit(&zfs_share_lock);
5102				return (SET_ERROR(ENOSYS));
5103			}
5104			error = zfs_init_sharefs();
5105			if (error != 0) {
5106				mutex_exit(&zfs_share_lock);
5107				return (SET_ERROR(ENOSYS));
5108			}
5109			zfs_nfsshare_inited = 1;
5110			mutex_exit(&zfs_share_lock);
5111		}
5112		break;
5113	case ZFS_SHARE_SMB:
5114	case ZFS_UNSHARE_SMB:
5115		if (zfs_smbshare_inited == 0) {
5116			mutex_enter(&zfs_share_lock);
5117			if (smbsrv_mod == NULL && ((smbsrv_mod =
5118			    ddi_modopen("drv/smbsrv",
5119			    KRTLD_MODE_FIRST, &error)) == NULL)) {
5120				mutex_exit(&zfs_share_lock);
5121				return (SET_ERROR(ENOSYS));
5122			}
5123			if (zsmbexport_fs == NULL && ((zsmbexport_fs =
5124			    (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
5125			    "smb_server_share", &error)) == NULL)) {
5126				mutex_exit(&zfs_share_lock);
5127				return (SET_ERROR(ENOSYS));
5128			}
5129			error = zfs_init_sharefs();
5130			if (error != 0) {
5131				mutex_exit(&zfs_share_lock);
5132				return (SET_ERROR(ENOSYS));
5133			}
5134			zfs_smbshare_inited = 1;
5135			mutex_exit(&zfs_share_lock);
5136		}
5137		break;
5138	default:
5139		return (SET_ERROR(EINVAL));
5140	}
5141
5142	switch (zc->zc_share.z_sharetype) {
5143	case ZFS_SHARE_NFS:
5144	case ZFS_UNSHARE_NFS:
5145		if (error =
5146		    znfsexport_fs((void *)
5147		    (uintptr_t)zc->zc_share.z_exportdata))
5148			return (error);
5149		break;
5150	case ZFS_SHARE_SMB:
5151	case ZFS_UNSHARE_SMB:
5152		if (error = zsmbexport_fs((void *)
5153		    (uintptr_t)zc->zc_share.z_exportdata,
5154		    zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
5155		    B_TRUE: B_FALSE)) {
5156			return (error);
5157		}
5158		break;
5159	}
5160
5161	opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
5162	    zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
5163	    SHAREFS_ADD : SHAREFS_REMOVE;
5164
5165	/*
5166	 * Add or remove share from sharetab
5167	 */
5168	error = zshare_fs(opcode,
5169	    (void *)(uintptr_t)zc->zc_share.z_sharedata,
5170	    zc->zc_share.z_sharemax);
5171
5172	return (error);
5173
5174#else	/* !illumos */
5175	return (ENOSYS);
5176#endif	/* illumos */
5177}
5178
5179ace_t full_access[] = {
5180	{(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
5181};
5182
5183/*
5184 * inputs:
5185 * zc_name		name of containing filesystem
5186 * zc_obj		object # beyond which we want next in-use object #
5187 *
5188 * outputs:
5189 * zc_obj		next in-use object #
5190 */
5191static int
5192zfs_ioc_next_obj(zfs_cmd_t *zc)
5193{
5194	objset_t *os = NULL;
5195	int error;
5196
5197	error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5198	if (error != 0)
5199		return (error);
5200
5201	error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
5202	    dsl_dataset_phys(os->os_dsl_dataset)->ds_prev_snap_txg);
5203
5204	dmu_objset_rele(os, FTAG);
5205	return (error);
5206}
5207
5208/*
5209 * inputs:
5210 * zc_name		name of filesystem
5211 * zc_value		prefix name for snapshot
5212 * zc_cleanup_fd	cleanup-on-exit file descriptor for calling process
5213 *
5214 * outputs:
5215 * zc_value		short name of new snapshot
5216 */
5217static int
5218zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
5219{
5220	char *snap_name;
5221	char *hold_name;
5222	int error;
5223	minor_t minor;
5224
5225	error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
5226	if (error != 0)
5227		return (error);
5228
5229	snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
5230	    (u_longlong_t)ddi_get_lbolt64());
5231	hold_name = kmem_asprintf("%%%s", zc->zc_value);
5232
5233	error = dsl_dataset_snapshot_tmp(zc->zc_name, snap_name, minor,
5234	    hold_name);
5235	if (error == 0)
5236		(void) strcpy(zc->zc_value, snap_name);
5237	strfree(snap_name);
5238	strfree(hold_name);
5239	zfs_onexit_fd_rele(zc->zc_cleanup_fd);
5240	return (error);
5241}
5242
5243/*
5244 * inputs:
5245 * zc_name		name of "to" snapshot
5246 * zc_value		name of "from" snapshot
5247 * zc_cookie		file descriptor to write diff data on
5248 *
5249 * outputs:
5250 * dmu_diff_record_t's to the file descriptor
5251 */
5252static int
5253zfs_ioc_diff(zfs_cmd_t *zc)
5254{
5255	file_t *fp;
5256	cap_rights_t rights;
5257	offset_t off;
5258	int error;
5259
5260#ifdef illumos
5261	fp = getf(zc->zc_cookie);
5262#else
5263	fget_write(curthread, zc->zc_cookie,
5264		    cap_rights_init(&rights, CAP_WRITE), &fp);
5265#endif
5266	if (fp == NULL)
5267		return (SET_ERROR(EBADF));
5268
5269	off = fp->f_offset;
5270
5271#ifdef illumos
5272	error = dmu_diff(zc->zc_name, zc->zc_value, fp->f_vnode, &off);
5273#else
5274	error = dmu_diff(zc->zc_name, zc->zc_value, fp, &off);
5275#endif
5276
5277	if (off >= 0 && off <= MAXOFFSET_T)
5278		fp->f_offset = off;
5279	releasef(zc->zc_cookie);
5280
5281	return (error);
5282}
5283
5284#ifdef illumos
5285/*
5286 * Remove all ACL files in shares dir
5287 */
5288static int
5289zfs_smb_acl_purge(znode_t *dzp)
5290{
5291	zap_cursor_t	zc;
5292	zap_attribute_t	zap;
5293	zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
5294	int error;
5295
5296	for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
5297	    (error = zap_cursor_retrieve(&zc, &zap)) == 0;
5298	    zap_cursor_advance(&zc)) {
5299		if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
5300		    NULL, 0)) != 0)
5301			break;
5302	}
5303	zap_cursor_fini(&zc);
5304	return (error);
5305}
5306#endif	/* illumos */
5307
5308static int
5309zfs_ioc_smb_acl(zfs_cmd_t *zc)
5310{
5311#ifdef illumos
5312	vnode_t *vp;
5313	znode_t *dzp;
5314	vnode_t *resourcevp = NULL;
5315	znode_t *sharedir;
5316	zfsvfs_t *zfsvfs;
5317	nvlist_t *nvlist;
5318	char *src, *target;
5319	vattr_t vattr;
5320	vsecattr_t vsec;
5321	int error = 0;
5322
5323	if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
5324	    NO_FOLLOW, NULL, &vp)) != 0)
5325		return (error);
5326
5327	/* Now make sure mntpnt and dataset are ZFS */
5328
5329	if (strcmp(vp->v_vfsp->mnt_stat.f_fstypename, "zfs") != 0 ||
5330	    (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
5331	    zc->zc_name) != 0)) {
5332		VN_RELE(vp);
5333		return (SET_ERROR(EINVAL));
5334	}
5335
5336	dzp = VTOZ(vp);
5337	zfsvfs = dzp->z_zfsvfs;
5338	ZFS_ENTER(zfsvfs);
5339
5340	/*
5341	 * Create share dir if its missing.
5342	 */
5343	mutex_enter(&zfsvfs->z_lock);
5344	if (zfsvfs->z_shares_dir == 0) {
5345		dmu_tx_t *tx;
5346
5347		tx = dmu_tx_create(zfsvfs->z_os);
5348		dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
5349		    ZFS_SHARES_DIR);
5350		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
5351		error = dmu_tx_assign(tx, TXG_WAIT);
5352		if (error != 0) {
5353			dmu_tx_abort(tx);
5354		} else {
5355			error = zfs_create_share_dir(zfsvfs, tx);
5356			dmu_tx_commit(tx);
5357		}
5358		if (error != 0) {
5359			mutex_exit(&zfsvfs->z_lock);
5360			VN_RELE(vp);
5361			ZFS_EXIT(zfsvfs);
5362			return (error);
5363		}
5364	}
5365	mutex_exit(&zfsvfs->z_lock);
5366
5367	ASSERT(zfsvfs->z_shares_dir);
5368	if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
5369		VN_RELE(vp);
5370		ZFS_EXIT(zfsvfs);
5371		return (error);
5372	}
5373
5374	switch (zc->zc_cookie) {
5375	case ZFS_SMB_ACL_ADD:
5376		vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
5377		vattr.va_type = VREG;
5378		vattr.va_mode = S_IFREG|0777;
5379		vattr.va_uid = 0;
5380		vattr.va_gid = 0;
5381
5382		vsec.vsa_mask = VSA_ACE;
5383		vsec.vsa_aclentp = &full_access;
5384		vsec.vsa_aclentsz = sizeof (full_access);
5385		vsec.vsa_aclcnt = 1;
5386
5387		error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
5388		    &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
5389		if (resourcevp)
5390			VN_RELE(resourcevp);
5391		break;
5392
5393	case ZFS_SMB_ACL_REMOVE:
5394		error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
5395		    NULL, 0);
5396		break;
5397
5398	case ZFS_SMB_ACL_RENAME:
5399		if ((error = get_nvlist(zc->zc_nvlist_src,
5400		    zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
5401			VN_RELE(vp);
5402			VN_RELE(ZTOV(sharedir));
5403			ZFS_EXIT(zfsvfs);
5404			return (error);
5405		}
5406		if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
5407		    nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
5408		    &target)) {
5409			VN_RELE(vp);
5410			VN_RELE(ZTOV(sharedir));
5411			ZFS_EXIT(zfsvfs);
5412			nvlist_free(nvlist);
5413			return (error);
5414		}
5415		error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
5416		    kcred, NULL, 0);
5417		nvlist_free(nvlist);
5418		break;
5419
5420	case ZFS_SMB_ACL_PURGE:
5421		error = zfs_smb_acl_purge(sharedir);
5422		break;
5423
5424	default:
5425		error = SET_ERROR(EINVAL);
5426		break;
5427	}
5428
5429	VN_RELE(vp);
5430	VN_RELE(ZTOV(sharedir));
5431
5432	ZFS_EXIT(zfsvfs);
5433
5434	return (error);
5435#else	/* !illumos */
5436	return (EOPNOTSUPP);
5437#endif	/* illumos */
5438}
5439
5440/*
5441 * innvl: {
5442 *     "holds" -> { snapname -> holdname (string), ... }
5443 *     (optional) "cleanup_fd" -> fd (int32)
5444 * }
5445 *
5446 * outnvl: {
5447 *     snapname -> error value (int32)
5448 *     ...
5449 * }
5450 */
5451/* ARGSUSED */
5452static int
5453zfs_ioc_hold(const char *pool, nvlist_t *args, nvlist_t *errlist)
5454{
5455	nvpair_t *pair;
5456	nvlist_t *holds;
5457	int cleanup_fd = -1;
5458	int error;
5459	minor_t minor = 0;
5460
5461	error = nvlist_lookup_nvlist(args, "holds", &holds);
5462	if (error != 0)
5463		return (SET_ERROR(EINVAL));
5464
5465	/* make sure the user didn't pass us any invalid (empty) tags */
5466	for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
5467	    pair = nvlist_next_nvpair(holds, pair)) {
5468		char *htag;
5469
5470		error = nvpair_value_string(pair, &htag);
5471		if (error != 0)
5472			return (SET_ERROR(error));
5473
5474		if (strlen(htag) == 0)
5475			return (SET_ERROR(EINVAL));
5476	}
5477
5478	if (nvlist_lookup_int32(args, "cleanup_fd", &cleanup_fd) == 0) {
5479		error = zfs_onexit_fd_hold(cleanup_fd, &minor);
5480		if (error != 0)
5481			return (error);
5482	}
5483
5484	error = dsl_dataset_user_hold(holds, minor, errlist);
5485	if (minor != 0)
5486		zfs_onexit_fd_rele(cleanup_fd);
5487	return (error);
5488}
5489
5490/*
5491 * innvl is not used.
5492 *
5493 * outnvl: {
5494 *    holdname -> time added (uint64 seconds since epoch)
5495 *    ...
5496 * }
5497 */
5498/* ARGSUSED */
5499static int
5500zfs_ioc_get_holds(const char *snapname, nvlist_t *args, nvlist_t *outnvl)
5501{
5502	return (dsl_dataset_get_holds(snapname, outnvl));
5503}
5504
5505/*
5506 * innvl: {
5507 *     snapname -> { holdname, ... }
5508 *     ...
5509 * }
5510 *
5511 * outnvl: {
5512 *     snapname -> error value (int32)
5513 *     ...
5514 * }
5515 */
5516/* ARGSUSED */
5517static int
5518zfs_ioc_release(const char *pool, nvlist_t *holds, nvlist_t *errlist)
5519{
5520	return (dsl_dataset_user_release(holds, errlist));
5521}
5522
5523/*
5524 * inputs:
5525 * zc_name		name of new filesystem or snapshot
5526 * zc_value		full name of old snapshot
5527 *
5528 * outputs:
5529 * zc_cookie		space in bytes
5530 * zc_objset_type	compressed space in bytes
5531 * zc_perm_action	uncompressed space in bytes
5532 */
5533static int
5534zfs_ioc_space_written(zfs_cmd_t *zc)
5535{
5536	int error;
5537	dsl_pool_t *dp;
5538	dsl_dataset_t *new, *old;
5539
5540	error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5541	if (error != 0)
5542		return (error);
5543	error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &new);
5544	if (error != 0) {
5545		dsl_pool_rele(dp, FTAG);
5546		return (error);
5547	}
5548	error = dsl_dataset_hold(dp, zc->zc_value, FTAG, &old);
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_written(old, new, &zc->zc_cookie,
5556	    &zc->zc_objset_type, &zc->zc_perm_action);
5557	dsl_dataset_rele(old, FTAG);
5558	dsl_dataset_rele(new, FTAG);
5559	dsl_pool_rele(dp, FTAG);
5560	return (error);
5561}
5562
5563/*
5564 * innvl: {
5565 *     "firstsnap" -> snapshot name
5566 * }
5567 *
5568 * outnvl: {
5569 *     "used" -> space in bytes
5570 *     "compressed" -> compressed space in bytes
5571 *     "uncompressed" -> uncompressed space in bytes
5572 * }
5573 */
5574static int
5575zfs_ioc_space_snaps(const char *lastsnap, nvlist_t *innvl, nvlist_t *outnvl)
5576{
5577	int error;
5578	dsl_pool_t *dp;
5579	dsl_dataset_t *new, *old;
5580	char *firstsnap;
5581	uint64_t used, comp, uncomp;
5582
5583	if (nvlist_lookup_string(innvl, "firstsnap", &firstsnap) != 0)
5584		return (SET_ERROR(EINVAL));
5585
5586	error = dsl_pool_hold(lastsnap, FTAG, &dp);
5587	if (error != 0)
5588		return (error);
5589
5590	error = dsl_dataset_hold(dp, lastsnap, FTAG, &new);
5591	if (error == 0 && !new->ds_is_snapshot) {
5592		dsl_dataset_rele(new, FTAG);
5593		error = SET_ERROR(EINVAL);
5594	}
5595	if (error != 0) {
5596		dsl_pool_rele(dp, FTAG);
5597		return (error);
5598	}
5599	error = dsl_dataset_hold(dp, firstsnap, FTAG, &old);
5600	if (error == 0 && !old->ds_is_snapshot) {
5601		dsl_dataset_rele(old, FTAG);
5602		error = SET_ERROR(EINVAL);
5603	}
5604	if (error != 0) {
5605		dsl_dataset_rele(new, FTAG);
5606		dsl_pool_rele(dp, FTAG);
5607		return (error);
5608	}
5609
5610	error = dsl_dataset_space_wouldfree(old, new, &used, &comp, &uncomp);
5611	dsl_dataset_rele(old, FTAG);
5612	dsl_dataset_rele(new, FTAG);
5613	dsl_pool_rele(dp, FTAG);
5614	fnvlist_add_uint64(outnvl, "used", used);
5615	fnvlist_add_uint64(outnvl, "compressed", comp);
5616	fnvlist_add_uint64(outnvl, "uncompressed", uncomp);
5617	return (error);
5618}
5619
5620static int
5621zfs_ioc_jail(zfs_cmd_t *zc)
5622{
5623
5624	return (zone_dataset_attach(curthread->td_ucred, zc->zc_name,
5625	    (int)zc->zc_jailid));
5626}
5627
5628static int
5629zfs_ioc_unjail(zfs_cmd_t *zc)
5630{
5631
5632	return (zone_dataset_detach(curthread->td_ucred, zc->zc_name,
5633	    (int)zc->zc_jailid));
5634}
5635
5636/*
5637 * innvl: {
5638 *     "fd" -> file descriptor to write stream to (int32)
5639 *     (optional) "fromsnap" -> full snap name to send an incremental from
5640 *     (optional) "largeblockok" -> (value ignored)
5641 *         indicates that blocks > 128KB are permitted
5642 *     (optional) "embedok" -> (value ignored)
5643 *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5644 *     (optional) "resume_object" and "resume_offset" -> (uint64)
5645 *         if present, resume send stream from specified object and offset.
5646 * }
5647 *
5648 * outnvl is unused
5649 */
5650/* ARGSUSED */
5651static int
5652zfs_ioc_send_new(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5653{
5654	cap_rights_t rights;
5655	file_t *fp;
5656	int error;
5657	offset_t off;
5658	char *fromname = NULL;
5659	int fd;
5660	boolean_t largeblockok;
5661	boolean_t embedok;
5662	uint64_t resumeobj = 0;
5663	uint64_t resumeoff = 0;
5664
5665	error = nvlist_lookup_int32(innvl, "fd", &fd);
5666	if (error != 0)
5667		return (SET_ERROR(EINVAL));
5668
5669	(void) nvlist_lookup_string(innvl, "fromsnap", &fromname);
5670
5671	largeblockok = nvlist_exists(innvl, "largeblockok");
5672	embedok = nvlist_exists(innvl, "embedok");
5673
5674	(void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
5675	(void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
5676
5677#ifdef illumos
5678	file_t *fp = getf(fd);
5679#else
5680	fget_write(curthread, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
5681#endif
5682	if (fp == NULL)
5683		return (SET_ERROR(EBADF));
5684
5685	off = fp->f_offset;
5686	error = dmu_send(snapname, fromname, embedok, largeblockok, fd,
5687#ifdef illumos
5688	    resumeobj, resumeoff, fp->f_vnode, &off);
5689#else
5690	    resumeobj, resumeoff, fp, &off);
5691#endif
5692
5693#ifdef illumos
5694	if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5695		fp->f_offset = off;
5696#else
5697	fp->f_offset = off;
5698#endif
5699
5700	releasef(fd);
5701	return (error);
5702}
5703
5704/*
5705 * Determine approximately how large a zfs send stream will be -- the number
5706 * of bytes that will be written to the fd supplied to zfs_ioc_send_new().
5707 *
5708 * innvl: {
5709 *     (optional) "from" -> full snap or bookmark name to send an incremental
5710 *                          from
5711 * }
5712 *
5713 * outnvl: {
5714 *     "space" -> bytes of space (uint64)
5715 * }
5716 */
5717static int
5718zfs_ioc_send_space(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5719{
5720	dsl_pool_t *dp;
5721	dsl_dataset_t *tosnap;
5722	int error;
5723	char *fromname;
5724	uint64_t space;
5725
5726	error = dsl_pool_hold(snapname, FTAG, &dp);
5727	if (error != 0)
5728		return (error);
5729
5730	error = dsl_dataset_hold(dp, snapname, FTAG, &tosnap);
5731	if (error != 0) {
5732		dsl_pool_rele(dp, FTAG);
5733		return (error);
5734	}
5735
5736	error = nvlist_lookup_string(innvl, "from", &fromname);
5737	if (error == 0) {
5738		if (strchr(fromname, '@') != NULL) {
5739			/*
5740			 * If from is a snapshot, hold it and use the more
5741			 * efficient dmu_send_estimate to estimate send space
5742			 * size using deadlists.
5743			 */
5744			dsl_dataset_t *fromsnap;
5745			error = dsl_dataset_hold(dp, fromname, FTAG, &fromsnap);
5746			if (error != 0)
5747				goto out;
5748			error = dmu_send_estimate(tosnap, fromsnap, &space);
5749			dsl_dataset_rele(fromsnap, FTAG);
5750		} else if (strchr(fromname, '#') != NULL) {
5751			/*
5752			 * If from is a bookmark, fetch the creation TXG of the
5753			 * snapshot it was created from and use that to find
5754			 * blocks that were born after it.
5755			 */
5756			zfs_bookmark_phys_t frombm;
5757
5758			error = dsl_bookmark_lookup(dp, fromname, tosnap,
5759			    &frombm);
5760			if (error != 0)
5761				goto out;
5762			error = dmu_send_estimate_from_txg(tosnap,
5763			    frombm.zbm_creation_txg, &space);
5764		} else {
5765			/*
5766			 * from is not properly formatted as a snapshot or
5767			 * bookmark
5768			 */
5769			error = SET_ERROR(EINVAL);
5770			goto out;
5771		}
5772	} else {
5773		// If estimating the size of a full send, use dmu_send_estimate
5774		error = dmu_send_estimate(tosnap, NULL, &space);
5775	}
5776
5777	fnvlist_add_uint64(outnvl, "space", space);
5778
5779out:
5780	dsl_dataset_rele(tosnap, FTAG);
5781	dsl_pool_rele(dp, FTAG);
5782	return (error);
5783}
5784
5785static zfs_ioc_vec_t zfs_ioc_vec[ZFS_IOC_LAST - ZFS_IOC_FIRST];
5786
5787static void
5788zfs_ioctl_register_legacy(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5789    zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
5790    boolean_t log_history, zfs_ioc_poolcheck_t pool_check)
5791{
5792	zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
5793
5794	ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
5795	ASSERT3U(ioc, <, ZFS_IOC_LAST);
5796	ASSERT3P(vec->zvec_legacy_func, ==, NULL);
5797	ASSERT3P(vec->zvec_func, ==, NULL);
5798
5799	vec->zvec_legacy_func = func;
5800	vec->zvec_secpolicy = secpolicy;
5801	vec->zvec_namecheck = namecheck;
5802	vec->zvec_allow_log = log_history;
5803	vec->zvec_pool_check = pool_check;
5804}
5805
5806/*
5807 * See the block comment at the beginning of this file for details on
5808 * each argument to this function.
5809 */
5810static void
5811zfs_ioctl_register(const char *name, zfs_ioc_t ioc, zfs_ioc_func_t *func,
5812    zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
5813    zfs_ioc_poolcheck_t pool_check, boolean_t smush_outnvlist,
5814    boolean_t allow_log)
5815{
5816	zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
5817
5818	ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
5819	ASSERT3U(ioc, <, ZFS_IOC_LAST);
5820	ASSERT3P(vec->zvec_legacy_func, ==, NULL);
5821	ASSERT3P(vec->zvec_func, ==, NULL);
5822
5823	/* if we are logging, the name must be valid */
5824	ASSERT(!allow_log || namecheck != NO_NAME);
5825
5826	vec->zvec_name = name;
5827	vec->zvec_func = func;
5828	vec->zvec_secpolicy = secpolicy;
5829	vec->zvec_namecheck = namecheck;
5830	vec->zvec_pool_check = pool_check;
5831	vec->zvec_smush_outnvlist = smush_outnvlist;
5832	vec->zvec_allow_log = allow_log;
5833}
5834
5835static void
5836zfs_ioctl_register_pool(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5837    zfs_secpolicy_func_t *secpolicy, boolean_t log_history,
5838    zfs_ioc_poolcheck_t pool_check)
5839{
5840	zfs_ioctl_register_legacy(ioc, func, secpolicy,
5841	    POOL_NAME, log_history, pool_check);
5842}
5843
5844static void
5845zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5846    zfs_secpolicy_func_t *secpolicy, zfs_ioc_poolcheck_t pool_check)
5847{
5848	zfs_ioctl_register_legacy(ioc, func, secpolicy,
5849	    DATASET_NAME, B_FALSE, pool_check);
5850}
5851
5852static void
5853zfs_ioctl_register_pool_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
5854{
5855	zfs_ioctl_register_legacy(ioc, func, zfs_secpolicy_config,
5856	    POOL_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5857}
5858
5859static void
5860zfs_ioctl_register_pool_meta(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5861    zfs_secpolicy_func_t *secpolicy)
5862{
5863	zfs_ioctl_register_legacy(ioc, func, secpolicy,
5864	    NO_NAME, B_FALSE, POOL_CHECK_NONE);
5865}
5866
5867static void
5868zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,
5869    zfs_ioc_legacy_func_t *func, zfs_secpolicy_func_t *secpolicy)
5870{
5871	zfs_ioctl_register_legacy(ioc, func, secpolicy,
5872	    DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED);
5873}
5874
5875static void
5876zfs_ioctl_register_dataset_read(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
5877{
5878	zfs_ioctl_register_dataset_read_secpolicy(ioc, func,
5879	    zfs_secpolicy_read);
5880}
5881
5882static void
5883zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5884    zfs_secpolicy_func_t *secpolicy)
5885{
5886	zfs_ioctl_register_legacy(ioc, func, secpolicy,
5887	    DATASET_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5888}
5889
5890static void
5891zfs_ioctl_init(void)
5892{
5893	zfs_ioctl_register("snapshot", ZFS_IOC_SNAPSHOT,
5894	    zfs_ioc_snapshot, zfs_secpolicy_snapshot, POOL_NAME,
5895	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5896
5897	zfs_ioctl_register("log_history", ZFS_IOC_LOG_HISTORY,
5898	    zfs_ioc_log_history, zfs_secpolicy_log_history, NO_NAME,
5899	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE);
5900
5901	zfs_ioctl_register("space_snaps", ZFS_IOC_SPACE_SNAPS,
5902	    zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME,
5903	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5904
5905	zfs_ioctl_register("send", ZFS_IOC_SEND_NEW,
5906	    zfs_ioc_send_new, zfs_secpolicy_send_new, DATASET_NAME,
5907	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5908
5909	zfs_ioctl_register("send_space", ZFS_IOC_SEND_SPACE,
5910	    zfs_ioc_send_space, zfs_secpolicy_read, DATASET_NAME,
5911	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5912
5913	zfs_ioctl_register("create", ZFS_IOC_CREATE,
5914	    zfs_ioc_create, zfs_secpolicy_create_clone, DATASET_NAME,
5915	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5916
5917	zfs_ioctl_register("clone", ZFS_IOC_CLONE,
5918	    zfs_ioc_clone, zfs_secpolicy_create_clone, DATASET_NAME,
5919	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5920
5921	zfs_ioctl_register("destroy_snaps", ZFS_IOC_DESTROY_SNAPS,
5922	    zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, POOL_NAME,
5923	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5924
5925	zfs_ioctl_register("hold", ZFS_IOC_HOLD,
5926	    zfs_ioc_hold, zfs_secpolicy_hold, POOL_NAME,
5927	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5928	zfs_ioctl_register("release", ZFS_IOC_RELEASE,
5929	    zfs_ioc_release, zfs_secpolicy_release, POOL_NAME,
5930	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5931
5932	zfs_ioctl_register("get_holds", ZFS_IOC_GET_HOLDS,
5933	    zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME,
5934	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5935
5936	zfs_ioctl_register("rollback", ZFS_IOC_ROLLBACK,
5937	    zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME,
5938	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
5939
5940	zfs_ioctl_register("bookmark", ZFS_IOC_BOOKMARK,
5941	    zfs_ioc_bookmark, zfs_secpolicy_bookmark, POOL_NAME,
5942	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5943
5944	zfs_ioctl_register("get_bookmarks", ZFS_IOC_GET_BOOKMARKS,
5945	    zfs_ioc_get_bookmarks, zfs_secpolicy_read, DATASET_NAME,
5946	    POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5947
5948	zfs_ioctl_register("destroy_bookmarks", ZFS_IOC_DESTROY_BOOKMARKS,
5949	    zfs_ioc_destroy_bookmarks, zfs_secpolicy_destroy_bookmarks,
5950	    POOL_NAME,
5951	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5952
5953	/* IOCTLS that use the legacy function signature */
5954
5955	zfs_ioctl_register_legacy(ZFS_IOC_POOL_FREEZE, zfs_ioc_pool_freeze,
5956	    zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_READONLY);
5957
5958	zfs_ioctl_register_pool(ZFS_IOC_POOL_CREATE, zfs_ioc_pool_create,
5959	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
5960	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SCAN,
5961	    zfs_ioc_pool_scan);
5962	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_UPGRADE,
5963	    zfs_ioc_pool_upgrade);
5964	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ADD,
5965	    zfs_ioc_vdev_add);
5966	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_REMOVE,
5967	    zfs_ioc_vdev_remove);
5968	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SET_STATE,
5969	    zfs_ioc_vdev_set_state);
5970	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ATTACH,
5971	    zfs_ioc_vdev_attach);
5972	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_DETACH,
5973	    zfs_ioc_vdev_detach);
5974	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETPATH,
5975	    zfs_ioc_vdev_setpath);
5976	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETFRU,
5977	    zfs_ioc_vdev_setfru);
5978	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SET_PROPS,
5979	    zfs_ioc_pool_set_props);
5980	zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SPLIT,
5981	    zfs_ioc_vdev_split);
5982	zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_REGUID,
5983	    zfs_ioc_pool_reguid);
5984
5985	zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_CONFIGS,
5986	    zfs_ioc_pool_configs, zfs_secpolicy_none);
5987	zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_TRYIMPORT,
5988	    zfs_ioc_pool_tryimport, zfs_secpolicy_config);
5989	zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_FAULT,
5990	    zfs_ioc_inject_fault, zfs_secpolicy_inject);
5991	zfs_ioctl_register_pool_meta(ZFS_IOC_CLEAR_FAULT,
5992	    zfs_ioc_clear_fault, zfs_secpolicy_inject);
5993	zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_LIST_NEXT,
5994	    zfs_ioc_inject_list_next, zfs_secpolicy_inject);
5995
5996	/*
5997	 * pool destroy, and export don't log the history as part of
5998	 * zfsdev_ioctl, but rather zfs_ioc_pool_export
5999	 * does the logging of those commands.
6000	 */
6001	zfs_ioctl_register_pool(ZFS_IOC_POOL_DESTROY, zfs_ioc_pool_destroy,
6002	    zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
6003	zfs_ioctl_register_pool(ZFS_IOC_POOL_EXPORT, zfs_ioc_pool_export,
6004	    zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
6005
6006	zfs_ioctl_register_pool(ZFS_IOC_POOL_STATS, zfs_ioc_pool_stats,
6007	    zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6008	zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_PROPS, zfs_ioc_pool_get_props,
6009	    zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6010
6011	zfs_ioctl_register_pool(ZFS_IOC_ERROR_LOG, zfs_ioc_error_log,
6012	    zfs_secpolicy_inject, B_FALSE, POOL_CHECK_NONE);
6013	zfs_ioctl_register_pool(ZFS_IOC_DSOBJ_TO_DSNAME,
6014	    zfs_ioc_dsobj_to_dsname,
6015	    zfs_secpolicy_diff, B_FALSE, POOL_CHECK_NONE);
6016	zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_HISTORY,
6017	    zfs_ioc_pool_get_history,
6018	    zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
6019
6020	zfs_ioctl_register_pool(ZFS_IOC_POOL_IMPORT, zfs_ioc_pool_import,
6021	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6022
6023	zfs_ioctl_register_pool(ZFS_IOC_CLEAR, zfs_ioc_clear,
6024	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6025	zfs_ioctl_register_pool(ZFS_IOC_POOL_REOPEN, zfs_ioc_pool_reopen,
6026	    zfs_secpolicy_config, B_TRUE, POOL_CHECK_SUSPENDED);
6027
6028	zfs_ioctl_register_dataset_read(ZFS_IOC_SPACE_WRITTEN,
6029	    zfs_ioc_space_written);
6030	zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_RECVD_PROPS,
6031	    zfs_ioc_objset_recvd_props);
6032	zfs_ioctl_register_dataset_read(ZFS_IOC_NEXT_OBJ,
6033	    zfs_ioc_next_obj);
6034	zfs_ioctl_register_dataset_read(ZFS_IOC_GET_FSACL,
6035	    zfs_ioc_get_fsacl);
6036	zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_STATS,
6037	    zfs_ioc_objset_stats);
6038	zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_ZPLPROPS,
6039	    zfs_ioc_objset_zplprops);
6040	zfs_ioctl_register_dataset_read(ZFS_IOC_DATASET_LIST_NEXT,
6041	    zfs_ioc_dataset_list_next);
6042	zfs_ioctl_register_dataset_read(ZFS_IOC_SNAPSHOT_LIST_NEXT,
6043	    zfs_ioc_snapshot_list_next);
6044	zfs_ioctl_register_dataset_read(ZFS_IOC_SEND_PROGRESS,
6045	    zfs_ioc_send_progress);
6046
6047	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_DIFF,
6048	    zfs_ioc_diff, zfs_secpolicy_diff);
6049	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_STATS,
6050	    zfs_ioc_obj_to_stats, zfs_secpolicy_diff);
6051	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_PATH,
6052	    zfs_ioc_obj_to_path, zfs_secpolicy_diff);
6053	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_ONE,
6054	    zfs_ioc_userspace_one, zfs_secpolicy_userspace_one);
6055	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_MANY,
6056	    zfs_ioc_userspace_many, zfs_secpolicy_userspace_many);
6057	zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_SEND,
6058	    zfs_ioc_send, zfs_secpolicy_send);
6059
6060	zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_PROP, zfs_ioc_set_prop,
6061	    zfs_secpolicy_none);
6062	zfs_ioctl_register_dataset_modify(ZFS_IOC_DESTROY, zfs_ioc_destroy,
6063	    zfs_secpolicy_destroy);
6064	zfs_ioctl_register_dataset_modify(ZFS_IOC_RENAME, zfs_ioc_rename,
6065	    zfs_secpolicy_rename);
6066	zfs_ioctl_register_dataset_modify(ZFS_IOC_RECV, zfs_ioc_recv,
6067	    zfs_secpolicy_recv);
6068	zfs_ioctl_register_dataset_modify(ZFS_IOC_PROMOTE, zfs_ioc_promote,
6069	    zfs_secpolicy_promote);
6070	zfs_ioctl_register_dataset_modify(ZFS_IOC_INHERIT_PROP,
6071	    zfs_ioc_inherit_prop, zfs_secpolicy_inherit_prop);
6072	zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_FSACL, zfs_ioc_set_fsacl,
6073	    zfs_secpolicy_set_fsacl);
6074
6075	zfs_ioctl_register_dataset_nolog(ZFS_IOC_SHARE, zfs_ioc_share,
6076	    zfs_secpolicy_share, POOL_CHECK_NONE);
6077	zfs_ioctl_register_dataset_nolog(ZFS_IOC_SMB_ACL, zfs_ioc_smb_acl,
6078	    zfs_secpolicy_smb_acl, POOL_CHECK_NONE);
6079	zfs_ioctl_register_dataset_nolog(ZFS_IOC_USERSPACE_UPGRADE,
6080	    zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
6081	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6082	zfs_ioctl_register_dataset_nolog(ZFS_IOC_TMP_SNAPSHOT,
6083	    zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot,
6084	    POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6085
6086#ifdef __FreeBSD__
6087	zfs_ioctl_register_dataset_nolog(ZFS_IOC_JAIL, zfs_ioc_jail,
6088	    zfs_secpolicy_config, POOL_CHECK_NONE);
6089	zfs_ioctl_register_dataset_nolog(ZFS_IOC_UNJAIL, zfs_ioc_unjail,
6090	    zfs_secpolicy_config, POOL_CHECK_NONE);
6091	zfs_ioctl_register("fbsd_nextboot", ZFS_IOC_NEXTBOOT,
6092	    zfs_ioc_nextboot, zfs_secpolicy_config, NO_NAME,
6093	    POOL_CHECK_NONE, B_FALSE, B_FALSE);
6094#endif
6095}
6096
6097int
6098pool_status_check(const char *name, zfs_ioc_namecheck_t type,
6099    zfs_ioc_poolcheck_t check)
6100{
6101	spa_t *spa;
6102	int error;
6103
6104	ASSERT(type == POOL_NAME || type == DATASET_NAME);
6105
6106	if (check & POOL_CHECK_NONE)
6107		return (0);
6108
6109	error = spa_open(name, &spa, FTAG);
6110	if (error == 0) {
6111		if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
6112			error = SET_ERROR(EAGAIN);
6113		else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
6114			error = SET_ERROR(EROFS);
6115		spa_close(spa, FTAG);
6116	}
6117	return (error);
6118}
6119
6120/*
6121 * Find a free minor number.
6122 */
6123minor_t
6124zfsdev_minor_alloc(void)
6125{
6126	static minor_t last_minor;
6127	minor_t m;
6128
6129	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6130
6131	for (m = last_minor + 1; m != last_minor; m++) {
6132		if (m > ZFSDEV_MAX_MINOR)
6133			m = 1;
6134		if (ddi_get_soft_state(zfsdev_state, m) == NULL) {
6135			last_minor = m;
6136			return (m);
6137		}
6138	}
6139
6140	return (0);
6141}
6142
6143static int
6144zfs_ctldev_init(struct cdev *devp)
6145{
6146	minor_t minor;
6147	zfs_soft_state_t *zs;
6148
6149	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6150
6151	minor = zfsdev_minor_alloc();
6152	if (minor == 0)
6153		return (SET_ERROR(ENXIO));
6154
6155	if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS)
6156		return (SET_ERROR(EAGAIN));
6157
6158	devfs_set_cdevpriv((void *)(uintptr_t)minor, zfsdev_close);
6159
6160	zs = ddi_get_soft_state(zfsdev_state, minor);
6161	zs->zss_type = ZSST_CTLDEV;
6162	zfs_onexit_init((zfs_onexit_t **)&zs->zss_data);
6163
6164	return (0);
6165}
6166
6167static void
6168zfs_ctldev_destroy(zfs_onexit_t *zo, minor_t minor)
6169{
6170	ASSERT(MUTEX_HELD(&spa_namespace_lock));
6171
6172	zfs_onexit_destroy(zo);
6173	ddi_soft_state_free(zfsdev_state, minor);
6174}
6175
6176void *
6177zfsdev_get_soft_state(minor_t minor, enum zfs_soft_state_type which)
6178{
6179	zfs_soft_state_t *zp;
6180
6181	zp = ddi_get_soft_state(zfsdev_state, minor);
6182	if (zp == NULL || zp->zss_type != which)
6183		return (NULL);
6184
6185	return (zp->zss_data);
6186}
6187
6188static int
6189zfsdev_open(struct cdev *devp, int flag, int mode, struct thread *td)
6190{
6191	int error = 0;
6192
6193#ifdef illumos
6194	if (getminor(*devp) != 0)
6195		return (zvol_open(devp, flag, otyp, cr));
6196#endif
6197
6198	/* This is the control device. Allocate a new minor if requested. */
6199	if (flag & FEXCL) {
6200		mutex_enter(&spa_namespace_lock);
6201		error = zfs_ctldev_init(devp);
6202		mutex_exit(&spa_namespace_lock);
6203	}
6204
6205	return (error);
6206}
6207
6208static void
6209zfsdev_close(void *data)
6210{
6211	zfs_onexit_t *zo;
6212	minor_t minor = (minor_t)(uintptr_t)data;
6213
6214	if (minor == 0)
6215		return;
6216
6217	mutex_enter(&spa_namespace_lock);
6218	zo = zfsdev_get_soft_state(minor, ZSST_CTLDEV);
6219	if (zo == NULL) {
6220		mutex_exit(&spa_namespace_lock);
6221		return;
6222	}
6223	zfs_ctldev_destroy(zo, minor);
6224	mutex_exit(&spa_namespace_lock);
6225}
6226
6227static int
6228zfsdev_ioctl(struct cdev *dev, u_long zcmd, caddr_t arg, int flag,
6229    struct thread *td)
6230{
6231	zfs_cmd_t *zc;
6232	uint_t vecnum;
6233	int error, rc, len;
6234#ifdef illumos
6235	minor_t minor = getminor(dev);
6236#else
6237	zfs_iocparm_t *zc_iocparm;
6238	int cflag, cmd, oldvecnum;
6239	boolean_t newioc, compat;
6240	void *compat_zc = NULL;
6241	cred_t *cr = td->td_ucred;
6242#endif
6243	const zfs_ioc_vec_t *vec;
6244	char *saved_poolname = NULL;
6245	nvlist_t *innvl = NULL;
6246
6247	cflag = ZFS_CMD_COMPAT_NONE;
6248	compat = B_FALSE;
6249	newioc = B_TRUE;	/* "new" style (zfs_iocparm_t) ioctl */
6250
6251	len = IOCPARM_LEN(zcmd);
6252	vecnum = cmd = zcmd & 0xff;
6253
6254	/*
6255	 * Check if we are talking to supported older binaries
6256	 * and translate zfs_cmd if necessary
6257	 */
6258	if (len != sizeof(zfs_iocparm_t)) {
6259		newioc = B_FALSE;
6260		compat = B_TRUE;
6261
6262		vecnum = cmd;
6263
6264		switch (len) {
6265		case sizeof(zfs_cmd_zcmd_t):
6266			cflag = ZFS_CMD_COMPAT_LZC;
6267			break;
6268		case sizeof(zfs_cmd_deadman_t):
6269			cflag = ZFS_CMD_COMPAT_DEADMAN;
6270			break;
6271		case sizeof(zfs_cmd_v28_t):
6272			cflag = ZFS_CMD_COMPAT_V28;
6273			break;
6274		case sizeof(zfs_cmd_v15_t):
6275			cflag = ZFS_CMD_COMPAT_V15;
6276			vecnum = zfs_ioctl_v15_to_v28[cmd];
6277
6278			/*
6279			 * Return without further handling
6280			 * if the command is blacklisted.
6281			 */
6282			if (vecnum == ZFS_IOC_COMPAT_PASS)
6283				return (0);
6284			else if (vecnum == ZFS_IOC_COMPAT_FAIL)
6285				return (ENOTSUP);
6286			break;
6287		default:
6288			return (EINVAL);
6289		}
6290	}
6291
6292#ifdef illumos
6293	vecnum = cmd - ZFS_IOC_FIRST;
6294	ASSERT3U(getmajor(dev), ==, ddi_driver_major(zfs_dip));
6295#endif
6296
6297	if (vecnum >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
6298		return (SET_ERROR(EINVAL));
6299	vec = &zfs_ioc_vec[vecnum];
6300
6301	zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
6302
6303#ifdef illumos
6304	error = ddi_copyin((void *)arg, zc, sizeof (zfs_cmd_t), flag);
6305	if (error != 0) {
6306		error = SET_ERROR(EFAULT);
6307		goto out;
6308	}
6309#else	/* !illumos */
6310	bzero(zc, sizeof(zfs_cmd_t));
6311
6312	if (newioc) {
6313		zc_iocparm = (void *)arg;
6314
6315		switch (zc_iocparm->zfs_ioctl_version) {
6316		case ZFS_IOCVER_CURRENT:
6317			if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_t)) {
6318				error = SET_ERROR(EINVAL);
6319				goto out;
6320			}
6321			break;
6322		case ZFS_IOCVER_INLANES:
6323			if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_inlanes_t)) {
6324				error = SET_ERROR(EFAULT);
6325				goto out;
6326			}
6327			compat = B_TRUE;
6328			cflag = ZFS_CMD_COMPAT_INLANES;
6329			break;
6330		case ZFS_IOCVER_RESUME:
6331			if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_resume_t)) {
6332				error = SET_ERROR(EFAULT);
6333				goto out;
6334			}
6335			compat = B_TRUE;
6336			cflag = ZFS_CMD_COMPAT_RESUME;
6337			break;
6338		case ZFS_IOCVER_EDBP:
6339			if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_edbp_t)) {
6340				error = SET_ERROR(EFAULT);
6341				goto out;
6342			}
6343			compat = B_TRUE;
6344			cflag = ZFS_CMD_COMPAT_EDBP;
6345			break;
6346		case ZFS_IOCVER_ZCMD:
6347			if (zc_iocparm->zfs_cmd_size > sizeof(zfs_cmd_t) ||
6348			    zc_iocparm->zfs_cmd_size < sizeof(zfs_cmd_zcmd_t)) {
6349				error = SET_ERROR(EFAULT);
6350				goto out;
6351			}
6352			compat = B_TRUE;
6353			cflag = ZFS_CMD_COMPAT_ZCMD;
6354			break;
6355		default:
6356			error = SET_ERROR(EINVAL);
6357			goto out;
6358			/* NOTREACHED */
6359		}
6360
6361		if (compat) {
6362			ASSERT(sizeof(zfs_cmd_t) >= zc_iocparm->zfs_cmd_size);
6363			compat_zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
6364			bzero(compat_zc, sizeof(zfs_cmd_t));
6365
6366			error = ddi_copyin((void *)(uintptr_t)zc_iocparm->zfs_cmd,
6367			    compat_zc, zc_iocparm->zfs_cmd_size, flag);
6368			if (error != 0) {
6369				error = SET_ERROR(EFAULT);
6370				goto out;
6371			}
6372		} else {
6373			error = ddi_copyin((void *)(uintptr_t)zc_iocparm->zfs_cmd,
6374			    zc, zc_iocparm->zfs_cmd_size, flag);
6375			if (error != 0) {
6376				error = SET_ERROR(EFAULT);
6377				goto out;
6378			}
6379		}
6380	}
6381
6382	if (compat) {
6383		if (newioc) {
6384			ASSERT(compat_zc != NULL);
6385			zfs_cmd_compat_get(zc, compat_zc, cflag);
6386		} else {
6387			ASSERT(compat_zc == NULL);
6388			zfs_cmd_compat_get(zc, arg, cflag);
6389		}
6390		oldvecnum = vecnum;
6391		error = zfs_ioctl_compat_pre(zc, &vecnum, cflag);
6392		if (error != 0)
6393			goto out;
6394		if (oldvecnum != vecnum)
6395			vec = &zfs_ioc_vec[vecnum];
6396	}
6397#endif	/* !illumos */
6398
6399	zc->zc_iflags = flag & FKIOCTL;
6400	if (zc->zc_nvlist_src_size != 0) {
6401		error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
6402		    zc->zc_iflags, &innvl);
6403		if (error != 0)
6404			goto out;
6405	}
6406
6407	/* rewrite innvl for backwards compatibility */
6408	if (compat)
6409		innvl = zfs_ioctl_compat_innvl(zc, innvl, vecnum, cflag);
6410
6411	/*
6412	 * Ensure that all pool/dataset names are valid before we pass down to
6413	 * the lower layers.
6414	 */
6415	zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
6416	switch (vec->zvec_namecheck) {
6417	case POOL_NAME:
6418		if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
6419			error = SET_ERROR(EINVAL);
6420		else
6421			error = pool_status_check(zc->zc_name,
6422			    vec->zvec_namecheck, vec->zvec_pool_check);
6423		break;
6424
6425	case DATASET_NAME:
6426		if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
6427			error = SET_ERROR(EINVAL);
6428		else
6429			error = pool_status_check(zc->zc_name,
6430			    vec->zvec_namecheck, vec->zvec_pool_check);
6431		break;
6432
6433	case NO_NAME:
6434		break;
6435	}
6436
6437	if (error == 0)
6438		error = vec->zvec_secpolicy(zc, innvl, cr);
6439
6440	if (error != 0)
6441		goto out;
6442
6443	/* legacy ioctls can modify zc_name */
6444	len = strcspn(zc->zc_name, "/@#") + 1;
6445	saved_poolname = kmem_alloc(len, KM_SLEEP);
6446	(void) strlcpy(saved_poolname, zc->zc_name, len);
6447
6448	if (vec->zvec_func != NULL) {
6449		nvlist_t *outnvl;
6450		int puterror = 0;
6451		spa_t *spa;
6452		nvlist_t *lognv = NULL;
6453
6454		ASSERT(vec->zvec_legacy_func == NULL);
6455
6456		/*
6457		 * Add the innvl to the lognv before calling the func,
6458		 * in case the func changes the innvl.
6459		 */
6460		if (vec->zvec_allow_log) {
6461			lognv = fnvlist_alloc();
6462			fnvlist_add_string(lognv, ZPOOL_HIST_IOCTL,
6463			    vec->zvec_name);
6464			if (!nvlist_empty(innvl)) {
6465				fnvlist_add_nvlist(lognv, ZPOOL_HIST_INPUT_NVL,
6466				    innvl);
6467			}
6468		}
6469
6470		outnvl = fnvlist_alloc();
6471		error = vec->zvec_func(zc->zc_name, innvl, outnvl);
6472
6473		if (error == 0 && vec->zvec_allow_log &&
6474		    spa_open(zc->zc_name, &spa, FTAG) == 0) {
6475			if (!nvlist_empty(outnvl)) {
6476				fnvlist_add_nvlist(lognv, ZPOOL_HIST_OUTPUT_NVL,
6477				    outnvl);
6478			}
6479			(void) spa_history_log_nvl(spa, lognv);
6480			spa_close(spa, FTAG);
6481		}
6482		fnvlist_free(lognv);
6483
6484		/* rewrite outnvl for backwards compatibility */
6485		if (compat)
6486			outnvl = zfs_ioctl_compat_outnvl(zc, outnvl, vecnum,
6487			    cflag);
6488
6489		if (!nvlist_empty(outnvl) || zc->zc_nvlist_dst_size != 0) {
6490			int smusherror = 0;
6491			if (vec->zvec_smush_outnvlist) {
6492				smusherror = nvlist_smush(outnvl,
6493				    zc->zc_nvlist_dst_size);
6494			}
6495			if (smusherror == 0)
6496				puterror = put_nvlist(zc, outnvl);
6497		}
6498
6499		if (puterror != 0)
6500			error = puterror;
6501
6502		nvlist_free(outnvl);
6503	} else {
6504		error = vec->zvec_legacy_func(zc);
6505	}
6506
6507out:
6508	nvlist_free(innvl);
6509
6510#ifdef illumos
6511	rc = ddi_copyout(zc, (void *)arg, sizeof (zfs_cmd_t), flag);
6512	if (error == 0 && rc != 0)
6513		error = SET_ERROR(EFAULT);
6514#else
6515	if (compat) {
6516		zfs_ioctl_compat_post(zc, cmd, cflag);
6517		if (newioc) {
6518			ASSERT(compat_zc != NULL);
6519			ASSERT(sizeof(zfs_cmd_t) >= zc_iocparm->zfs_cmd_size);
6520
6521			zfs_cmd_compat_put(zc, compat_zc, vecnum, cflag);
6522			rc = ddi_copyout(compat_zc,
6523			    (void *)(uintptr_t)zc_iocparm->zfs_cmd,
6524			    zc_iocparm->zfs_cmd_size, flag);
6525			if (error == 0 && rc != 0)
6526				error = SET_ERROR(EFAULT);
6527			kmem_free(compat_zc, sizeof (zfs_cmd_t));
6528		} else {
6529			zfs_cmd_compat_put(zc, arg, vecnum, cflag);
6530		}
6531	} else {
6532		ASSERT(newioc);
6533
6534		rc = ddi_copyout(zc, (void *)(uintptr_t)zc_iocparm->zfs_cmd,
6535		    sizeof (zfs_cmd_t), flag);
6536		if (error == 0 && rc != 0)
6537			error = SET_ERROR(EFAULT);
6538	}
6539#endif
6540	if (error == 0 && vec->zvec_allow_log) {
6541		char *s = tsd_get(zfs_allow_log_key);
6542		if (s != NULL)
6543			strfree(s);
6544		(void) tsd_set(zfs_allow_log_key, saved_poolname);
6545	} else {
6546		if (saved_poolname != NULL)
6547			strfree(saved_poolname);
6548	}
6549
6550	kmem_free(zc, sizeof (zfs_cmd_t));
6551	return (error);
6552}
6553
6554#ifdef illumos
6555static int
6556zfs_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
6557{
6558	if (cmd != DDI_ATTACH)
6559		return (DDI_FAILURE);
6560
6561	if (ddi_create_minor_node(dip, "zfs", S_IFCHR, 0,
6562	    DDI_PSEUDO, 0) == DDI_FAILURE)
6563		return (DDI_FAILURE);
6564
6565	zfs_dip = dip;
6566
6567	ddi_report_dev(dip);
6568
6569	return (DDI_SUCCESS);
6570}
6571
6572static int
6573zfs_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
6574{
6575	if (spa_busy() || zfs_busy() || zvol_busy())
6576		return (DDI_FAILURE);
6577
6578	if (cmd != DDI_DETACH)
6579		return (DDI_FAILURE);
6580
6581	zfs_dip = NULL;
6582
6583	ddi_prop_remove_all(dip);
6584	ddi_remove_minor_node(dip, NULL);
6585
6586	return (DDI_SUCCESS);
6587}
6588
6589/*ARGSUSED*/
6590static int
6591zfs_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
6592{
6593	switch (infocmd) {
6594	case DDI_INFO_DEVT2DEVINFO:
6595		*result = zfs_dip;
6596		return (DDI_SUCCESS);
6597
6598	case DDI_INFO_DEVT2INSTANCE:
6599		*result = (void *)0;
6600		return (DDI_SUCCESS);
6601	}
6602
6603	return (DDI_FAILURE);
6604}
6605#endif	/* illumos */
6606
6607/*
6608 * OK, so this is a little weird.
6609 *
6610 * /dev/zfs is the control node, i.e. minor 0.
6611 * /dev/zvol/[r]dsk/pool/dataset are the zvols, minor > 0.
6612 *
6613 * /dev/zfs has basically nothing to do except serve up ioctls,
6614 * so most of the standard driver entry points are in zvol.c.
6615 */
6616#ifdef illumos
6617static struct cb_ops zfs_cb_ops = {
6618	zfsdev_open,	/* open */
6619	zfsdev_close,	/* close */
6620	zvol_strategy,	/* strategy */
6621	nodev,		/* print */
6622	zvol_dump,	/* dump */
6623	zvol_read,	/* read */
6624	zvol_write,	/* write */
6625	zfsdev_ioctl,	/* ioctl */
6626	nodev,		/* devmap */
6627	nodev,		/* mmap */
6628	nodev,		/* segmap */
6629	nochpoll,	/* poll */
6630	ddi_prop_op,	/* prop_op */
6631	NULL,		/* streamtab */
6632	D_NEW | D_MP | D_64BIT,		/* Driver compatibility flag */
6633	CB_REV,		/* version */
6634	nodev,		/* async read */
6635	nodev,		/* async write */
6636};
6637
6638static struct dev_ops zfs_dev_ops = {
6639	DEVO_REV,	/* version */
6640	0,		/* refcnt */
6641	zfs_info,	/* info */
6642	nulldev,	/* identify */
6643	nulldev,	/* probe */
6644	zfs_attach,	/* attach */
6645	zfs_detach,	/* detach */
6646	nodev,		/* reset */
6647	&zfs_cb_ops,	/* driver operations */
6648	NULL,		/* no bus operations */
6649	NULL,		/* power */
6650	ddi_quiesce_not_needed,	/* quiesce */
6651};
6652
6653static struct modldrv zfs_modldrv = {
6654	&mod_driverops,
6655	"ZFS storage pool",
6656	&zfs_dev_ops
6657};
6658
6659static struct modlinkage modlinkage = {
6660	MODREV_1,
6661	(void *)&zfs_modlfs,
6662	(void *)&zfs_modldrv,
6663	NULL
6664};
6665#endif	/* illumos */
6666
6667static struct cdevsw zfs_cdevsw = {
6668	.d_version =	D_VERSION,
6669	.d_open =	zfsdev_open,
6670	.d_ioctl =	zfsdev_ioctl,
6671	.d_name =	ZFS_DEV_NAME
6672};
6673
6674static void
6675zfs_allow_log_destroy(void *arg)
6676{
6677	char *poolname = arg;
6678	strfree(poolname);
6679}
6680
6681static void
6682zfsdev_init(void)
6683{
6684	zfsdev = make_dev(&zfs_cdevsw, 0x0, UID_ROOT, GID_OPERATOR, 0666,
6685	    ZFS_DEV_NAME);
6686}
6687
6688static void
6689zfsdev_fini(void)
6690{
6691	if (zfsdev != NULL)
6692		destroy_dev(zfsdev);
6693}
6694
6695static struct root_hold_token *zfs_root_token;
6696struct proc *zfsproc;
6697
6698#ifdef illumos
6699int
6700_init(void)
6701{
6702	int error;
6703
6704	spa_init(FREAD | FWRITE);
6705	zfs_init();
6706	zvol_init();
6707	zfs_ioctl_init();
6708
6709	if ((error = mod_install(&modlinkage)) != 0) {
6710		zvol_fini();
6711		zfs_fini();
6712		spa_fini();
6713		return (error);
6714	}
6715
6716	tsd_create(&zfs_fsyncer_key, NULL);
6717	tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
6718	tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
6719
6720	error = ldi_ident_from_mod(&modlinkage, &zfs_li);
6721	ASSERT(error == 0);
6722	mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
6723
6724	return (0);
6725}
6726
6727int
6728_fini(void)
6729{
6730	int error;
6731
6732	if (spa_busy() || zfs_busy() || zvol_busy() || zio_injection_enabled)
6733		return (SET_ERROR(EBUSY));
6734
6735	if ((error = mod_remove(&modlinkage)) != 0)
6736		return (error);
6737
6738	zvol_fini();
6739	zfs_fini();
6740	spa_fini();
6741	if (zfs_nfsshare_inited)
6742		(void) ddi_modclose(nfs_mod);
6743	if (zfs_smbshare_inited)
6744		(void) ddi_modclose(smbsrv_mod);
6745	if (zfs_nfsshare_inited || zfs_smbshare_inited)
6746		(void) ddi_modclose(sharefs_mod);
6747
6748	tsd_destroy(&zfs_fsyncer_key);
6749	ldi_ident_release(zfs_li);
6750	zfs_li = NULL;
6751	mutex_destroy(&zfs_share_lock);
6752
6753	return (error);
6754}
6755
6756int
6757_info(struct modinfo *modinfop)
6758{
6759	return (mod_info(&modlinkage, modinfop));
6760}
6761#endif	/* illumos */
6762
6763static int zfs__init(void);
6764static int zfs__fini(void);
6765static void zfs_shutdown(void *, int);
6766
6767static eventhandler_tag zfs_shutdown_event_tag;
6768
6769#ifdef __FreeBSD__
6770#define ZFS_MIN_KSTACK_PAGES 4
6771#endif
6772
6773int
6774zfs__init(void)
6775{
6776
6777#ifdef __FreeBSD__
6778#if KSTACK_PAGES < ZFS_MIN_KSTACK_PAGES
6779	printf("ZFS NOTICE: KSTACK_PAGES is %d which could result in stack "
6780	    "overflow panic!\nPlease consider adding "
6781	    "'options KSTACK_PAGES=%d' to your kernel config\n", KSTACK_PAGES,
6782	    ZFS_MIN_KSTACK_PAGES);
6783#endif
6784#endif
6785	zfs_root_token = root_mount_hold("ZFS");
6786
6787	mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
6788
6789	spa_init(FREAD | FWRITE);
6790	zfs_init();
6791	zvol_init();
6792	zfs_ioctl_init();
6793
6794	tsd_create(&zfs_fsyncer_key, NULL);
6795	tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
6796	tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
6797	tsd_create(&zfs_geom_probe_vdev_key, NULL);
6798
6799	printf("ZFS storage pool version: features support (" SPA_VERSION_STRING ")\n");
6800	root_mount_rel(zfs_root_token);
6801
6802	zfsdev_init();
6803
6804	return (0);
6805}
6806
6807int
6808zfs__fini(void)
6809{
6810	if (spa_busy() || zfs_busy() || zvol_busy() ||
6811	    zio_injection_enabled) {
6812		return (EBUSY);
6813	}
6814
6815	zfsdev_fini();
6816	zvol_fini();
6817	zfs_fini();
6818	spa_fini();
6819
6820	tsd_destroy(&zfs_fsyncer_key);
6821	tsd_destroy(&rrw_tsd_key);
6822	tsd_destroy(&zfs_allow_log_key);
6823
6824	mutex_destroy(&zfs_share_lock);
6825
6826	return (0);
6827}
6828
6829static void
6830zfs_shutdown(void *arg __unused, int howto __unused)
6831{
6832
6833	/*
6834	 * ZFS fini routines can not properly work in a panic-ed system.
6835	 */
6836	if (panicstr == NULL)
6837		(void)zfs__fini();
6838}
6839
6840
6841static int
6842zfs_modevent(module_t mod, int type, void *unused __unused)
6843{
6844	int err;
6845
6846	switch (type) {
6847	case MOD_LOAD:
6848		err = zfs__init();
6849		if (err == 0)
6850			zfs_shutdown_event_tag = EVENTHANDLER_REGISTER(
6851			    shutdown_post_sync, zfs_shutdown, NULL,
6852			    SHUTDOWN_PRI_FIRST);
6853		return (err);
6854	case MOD_UNLOAD:
6855		err = zfs__fini();
6856		if (err == 0 && zfs_shutdown_event_tag != NULL)
6857			EVENTHANDLER_DEREGISTER(shutdown_post_sync,
6858			    zfs_shutdown_event_tag);
6859		return (err);
6860	case MOD_SHUTDOWN:
6861		return (0);
6862	default:
6863		break;
6864	}
6865	return (EOPNOTSUPP);
6866}
6867
6868static moduledata_t zfs_mod = {
6869	"zfsctrl",
6870	zfs_modevent,
6871	0
6872};
6873DECLARE_MODULE(zfsctrl, zfs_mod, SI_SUB_VFS, SI_ORDER_ANY);
6874MODULE_VERSION(zfsctrl, 1);
6875MODULE_DEPEND(zfsctrl, opensolaris, 1, 1, 1);
6876MODULE_DEPEND(zfsctrl, krpc, 1, 1, 1);
6877MODULE_DEPEND(zfsctrl, acl_nfs4, 1, 1, 1);
6878