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