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