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