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