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