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