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