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