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