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