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