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