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