]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/zfs_ioctl.c
OpenZFS 7614, 9064 - zfs device evacuation/removal
[FreeBSD/FreeBSD.git] / module / zfs / zfs_ioctl.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Portions Copyright 2011 Martin Matuska
25  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
26  * Portions Copyright 2012 Pawel Jakub Dawidek <pawel@dawidek.net>
27  * Copyright (c) 2014, 2016 Joyent, Inc. All rights reserved.
28  * Copyright 2016 Nexenta Systems, Inc.  All rights reserved.
29  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
30  * Copyright (c) 2011, 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
1523         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1524             zc->zc_iflags, &config)))
1525                 return (error);
1526
1527         if (zc->zc_nvlist_src_size != 0 && (error =
1528             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1529             zc->zc_iflags, &props))) {
1530                 nvlist_free(config);
1531                 return (error);
1532         }
1533
1534         if (props) {
1535                 nvlist_t *nvl = NULL;
1536                 nvlist_t *hidden_args = NULL;
1537                 uint64_t version = SPA_VERSION;
1538
1539                 (void) nvlist_lookup_uint64(props,
1540                     zpool_prop_to_name(ZPOOL_PROP_VERSION), &version);
1541                 if (!SPA_VERSION_IS_SUPPORTED(version)) {
1542                         error = SET_ERROR(EINVAL);
1543                         goto pool_props_bad;
1544                 }
1545                 (void) nvlist_lookup_nvlist(props, ZPOOL_ROOTFS_PROPS, &nvl);
1546                 if (nvl) {
1547                         error = nvlist_dup(nvl, &rootprops, KM_SLEEP);
1548                         if (error != 0) {
1549                                 nvlist_free(config);
1550                                 nvlist_free(props);
1551                                 return (error);
1552                         }
1553                         (void) nvlist_remove_all(props, ZPOOL_ROOTFS_PROPS);
1554                 }
1555
1556                 (void) nvlist_lookup_nvlist(props, ZPOOL_HIDDEN_ARGS,
1557                     &hidden_args);
1558                 error = dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
1559                     rootprops, hidden_args, &dcp);
1560                 if (error != 0) {
1561                         nvlist_free(config);
1562                         nvlist_free(props);
1563                         return (error);
1564                 }
1565                 (void) nvlist_remove_all(props, ZPOOL_HIDDEN_ARGS);
1566
1567                 VERIFY(nvlist_alloc(&zplprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1568                 error = zfs_fill_zplprops_root(version, rootprops,
1569                     zplprops, NULL);
1570                 if (error != 0)
1571                         goto pool_props_bad;
1572         }
1573
1574         error = spa_create(zc->zc_name, config, props, zplprops, dcp);
1575
1576         /*
1577          * Set the remaining root properties
1578          */
1579         if (!error && (error = zfs_set_prop_nvlist(zc->zc_name,
1580             ZPROP_SRC_LOCAL, rootprops, NULL)) != 0)
1581                 (void) spa_destroy(zc->zc_name);
1582
1583 pool_props_bad:
1584         nvlist_free(rootprops);
1585         nvlist_free(zplprops);
1586         nvlist_free(config);
1587         nvlist_free(props);
1588         dsl_crypto_params_free(dcp, !!error);
1589
1590         return (error);
1591 }
1592
1593 static int
1594 zfs_ioc_pool_destroy(zfs_cmd_t *zc)
1595 {
1596         int error;
1597         zfs_log_history(zc);
1598         error = spa_destroy(zc->zc_name);
1599
1600         return (error);
1601 }
1602
1603 static int
1604 zfs_ioc_pool_import(zfs_cmd_t *zc)
1605 {
1606         nvlist_t *config, *props = NULL;
1607         uint64_t guid;
1608         int error;
1609
1610         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1611             zc->zc_iflags, &config)) != 0)
1612                 return (error);
1613
1614         if (zc->zc_nvlist_src_size != 0 && (error =
1615             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1616             zc->zc_iflags, &props))) {
1617                 nvlist_free(config);
1618                 return (error);
1619         }
1620
1621         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1622             guid != zc->zc_guid)
1623                 error = SET_ERROR(EINVAL);
1624         else
1625                 error = spa_import(zc->zc_name, config, props, zc->zc_cookie);
1626
1627         if (zc->zc_nvlist_dst != 0) {
1628                 int err;
1629
1630                 if ((err = put_nvlist(zc, config)) != 0)
1631                         error = err;
1632         }
1633
1634         nvlist_free(config);
1635         nvlist_free(props);
1636
1637         return (error);
1638 }
1639
1640 static int
1641 zfs_ioc_pool_export(zfs_cmd_t *zc)
1642 {
1643         int error;
1644         boolean_t force = (boolean_t)zc->zc_cookie;
1645         boolean_t hardforce = (boolean_t)zc->zc_guid;
1646
1647         zfs_log_history(zc);
1648         error = spa_export(zc->zc_name, NULL, force, hardforce);
1649
1650         return (error);
1651 }
1652
1653 static int
1654 zfs_ioc_pool_configs(zfs_cmd_t *zc)
1655 {
1656         nvlist_t *configs;
1657         int error;
1658
1659         if ((configs = spa_all_configs(&zc->zc_cookie)) == NULL)
1660                 return (SET_ERROR(EEXIST));
1661
1662         error = put_nvlist(zc, configs);
1663
1664         nvlist_free(configs);
1665
1666         return (error);
1667 }
1668
1669 /*
1670  * inputs:
1671  * zc_name              name of the pool
1672  *
1673  * outputs:
1674  * zc_cookie            real errno
1675  * zc_nvlist_dst        config nvlist
1676  * zc_nvlist_dst_size   size of config nvlist
1677  */
1678 static int
1679 zfs_ioc_pool_stats(zfs_cmd_t *zc)
1680 {
1681         nvlist_t *config;
1682         int error;
1683         int ret = 0;
1684
1685         error = spa_get_stats(zc->zc_name, &config, zc->zc_value,
1686             sizeof (zc->zc_value));
1687
1688         if (config != NULL) {
1689                 ret = put_nvlist(zc, config);
1690                 nvlist_free(config);
1691
1692                 /*
1693                  * The config may be present even if 'error' is non-zero.
1694                  * In this case we return success, and preserve the real errno
1695                  * in 'zc_cookie'.
1696                  */
1697                 zc->zc_cookie = error;
1698         } else {
1699                 ret = error;
1700         }
1701
1702         return (ret);
1703 }
1704
1705 /*
1706  * Try to import the given pool, returning pool stats as appropriate so that
1707  * user land knows which devices are available and overall pool health.
1708  */
1709 static int
1710 zfs_ioc_pool_tryimport(zfs_cmd_t *zc)
1711 {
1712         nvlist_t *tryconfig, *config = NULL;
1713         int error;
1714
1715         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1716             zc->zc_iflags, &tryconfig)) != 0)
1717                 return (error);
1718
1719         config = spa_tryimport(tryconfig);
1720
1721         nvlist_free(tryconfig);
1722
1723         if (config == NULL)
1724                 return (SET_ERROR(EINVAL));
1725
1726         error = put_nvlist(zc, config);
1727         nvlist_free(config);
1728
1729         return (error);
1730 }
1731
1732 /*
1733  * inputs:
1734  * zc_name              name of the pool
1735  * zc_cookie            scan func (pool_scan_func_t)
1736  * zc_flags             scrub pause/resume flag (pool_scrub_cmd_t)
1737  */
1738 static int
1739 zfs_ioc_pool_scan(zfs_cmd_t *zc)
1740 {
1741         spa_t *spa;
1742         int error;
1743
1744         if (zc->zc_flags >= POOL_SCRUB_FLAGS_END)
1745                 return (SET_ERROR(EINVAL));
1746
1747         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1748                 return (error);
1749
1750         if (zc->zc_flags == POOL_SCRUB_PAUSE)
1751                 error = spa_scrub_pause_resume(spa, POOL_SCRUB_PAUSE);
1752         else if (zc->zc_cookie == POOL_SCAN_NONE)
1753                 error = spa_scan_stop(spa);
1754         else
1755                 error = spa_scan(spa, zc->zc_cookie);
1756
1757         spa_close(spa, FTAG);
1758
1759         return (error);
1760 }
1761
1762 static int
1763 zfs_ioc_pool_freeze(zfs_cmd_t *zc)
1764 {
1765         spa_t *spa;
1766         int error;
1767
1768         error = spa_open(zc->zc_name, &spa, FTAG);
1769         if (error == 0) {
1770                 spa_freeze(spa);
1771                 spa_close(spa, FTAG);
1772         }
1773         return (error);
1774 }
1775
1776 static int
1777 zfs_ioc_pool_upgrade(zfs_cmd_t *zc)
1778 {
1779         spa_t *spa;
1780         int error;
1781
1782         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1783                 return (error);
1784
1785         if (zc->zc_cookie < spa_version(spa) ||
1786             !SPA_VERSION_IS_SUPPORTED(zc->zc_cookie)) {
1787                 spa_close(spa, FTAG);
1788                 return (SET_ERROR(EINVAL));
1789         }
1790
1791         spa_upgrade(spa, zc->zc_cookie);
1792         spa_close(spa, FTAG);
1793
1794         return (error);
1795 }
1796
1797 static int
1798 zfs_ioc_pool_get_history(zfs_cmd_t *zc)
1799 {
1800         spa_t *spa;
1801         char *hist_buf;
1802         uint64_t size;
1803         int error;
1804
1805         if ((size = zc->zc_history_len) == 0)
1806                 return (SET_ERROR(EINVAL));
1807
1808         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1809                 return (error);
1810
1811         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
1812                 spa_close(spa, FTAG);
1813                 return (SET_ERROR(ENOTSUP));
1814         }
1815
1816         hist_buf = vmem_alloc(size, KM_SLEEP);
1817         if ((error = spa_history_get(spa, &zc->zc_history_offset,
1818             &zc->zc_history_len, hist_buf)) == 0) {
1819                 error = ddi_copyout(hist_buf,
1820                     (void *)(uintptr_t)zc->zc_history,
1821                     zc->zc_history_len, zc->zc_iflags);
1822         }
1823
1824         spa_close(spa, FTAG);
1825         vmem_free(hist_buf, size);
1826         return (error);
1827 }
1828
1829 static int
1830 zfs_ioc_pool_reguid(zfs_cmd_t *zc)
1831 {
1832         spa_t *spa;
1833         int error;
1834
1835         error = spa_open(zc->zc_name, &spa, FTAG);
1836         if (error == 0) {
1837                 error = spa_change_guid(spa);
1838                 spa_close(spa, FTAG);
1839         }
1840         return (error);
1841 }
1842
1843 static int
1844 zfs_ioc_dsobj_to_dsname(zfs_cmd_t *zc)
1845 {
1846         return (dsl_dsobj_to_dsname(zc->zc_name, zc->zc_obj, zc->zc_value));
1847 }
1848
1849 /*
1850  * inputs:
1851  * zc_name              name of filesystem
1852  * zc_obj               object to find
1853  *
1854  * outputs:
1855  * zc_value             name of object
1856  */
1857 static int
1858 zfs_ioc_obj_to_path(zfs_cmd_t *zc)
1859 {
1860         objset_t *os;
1861         int error;
1862
1863         /* XXX reading from objset not owned */
1864         if ((error = dmu_objset_hold_flags(zc->zc_name, B_TRUE,
1865             FTAG, &os)) != 0)
1866                 return (error);
1867         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1868                 dmu_objset_rele_flags(os, B_TRUE, FTAG);
1869                 return (SET_ERROR(EINVAL));
1870         }
1871         error = zfs_obj_to_path(os, zc->zc_obj, zc->zc_value,
1872             sizeof (zc->zc_value));
1873         dmu_objset_rele_flags(os, B_TRUE, FTAG);
1874
1875         return (error);
1876 }
1877
1878 /*
1879  * inputs:
1880  * zc_name              name of filesystem
1881  * zc_obj               object to find
1882  *
1883  * outputs:
1884  * zc_stat              stats on object
1885  * zc_value             path to object
1886  */
1887 static int
1888 zfs_ioc_obj_to_stats(zfs_cmd_t *zc)
1889 {
1890         objset_t *os;
1891         int error;
1892
1893         /* XXX reading from objset not owned */
1894         if ((error = dmu_objset_hold_flags(zc->zc_name, B_TRUE,
1895             FTAG, &os)) != 0)
1896                 return (error);
1897         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1898                 dmu_objset_rele_flags(os, B_TRUE, FTAG);
1899                 return (SET_ERROR(EINVAL));
1900         }
1901         error = zfs_obj_to_stats(os, zc->zc_obj, &zc->zc_stat, zc->zc_value,
1902             sizeof (zc->zc_value));
1903         dmu_objset_rele_flags(os, B_TRUE, FTAG);
1904
1905         return (error);
1906 }
1907
1908 static int
1909 zfs_ioc_vdev_add(zfs_cmd_t *zc)
1910 {
1911         spa_t *spa;
1912         int error;
1913         nvlist_t *config;
1914
1915         error = spa_open(zc->zc_name, &spa, FTAG);
1916         if (error != 0)
1917                 return (error);
1918
1919         error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1920             zc->zc_iflags, &config);
1921         if (error == 0) {
1922                 error = spa_vdev_add(spa, config);
1923                 nvlist_free(config);
1924         }
1925         spa_close(spa, FTAG);
1926         return (error);
1927 }
1928
1929 /*
1930  * inputs:
1931  * zc_name              name of the pool
1932  * zc_guid              guid of vdev to remove
1933  * zc_cookie            cancel removal
1934  */
1935 static int
1936 zfs_ioc_vdev_remove(zfs_cmd_t *zc)
1937 {
1938         spa_t *spa;
1939         int error;
1940
1941         error = spa_open(zc->zc_name, &spa, FTAG);
1942         if (error != 0)
1943                 return (error);
1944         if (zc->zc_cookie != 0) {
1945                 error = spa_vdev_remove_cancel(spa);
1946         } else {
1947                 error = spa_vdev_remove(spa, zc->zc_guid, B_FALSE);
1948         }
1949         spa_close(spa, FTAG);
1950         return (error);
1951 }
1952
1953 static int
1954 zfs_ioc_vdev_set_state(zfs_cmd_t *zc)
1955 {
1956         spa_t *spa;
1957         int error;
1958         vdev_state_t newstate = VDEV_STATE_UNKNOWN;
1959
1960         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1961                 return (error);
1962         switch (zc->zc_cookie) {
1963         case VDEV_STATE_ONLINE:
1964                 error = vdev_online(spa, zc->zc_guid, zc->zc_obj, &newstate);
1965                 break;
1966
1967         case VDEV_STATE_OFFLINE:
1968                 error = vdev_offline(spa, zc->zc_guid, zc->zc_obj);
1969                 break;
1970
1971         case VDEV_STATE_FAULTED:
1972                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1973                     zc->zc_obj != VDEV_AUX_EXTERNAL &&
1974                     zc->zc_obj != VDEV_AUX_EXTERNAL_PERSIST)
1975                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1976
1977                 error = vdev_fault(spa, zc->zc_guid, zc->zc_obj);
1978                 break;
1979
1980         case VDEV_STATE_DEGRADED:
1981                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1982                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1983                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1984
1985                 error = vdev_degrade(spa, zc->zc_guid, zc->zc_obj);
1986                 break;
1987
1988         default:
1989                 error = SET_ERROR(EINVAL);
1990         }
1991         zc->zc_cookie = newstate;
1992         spa_close(spa, FTAG);
1993         return (error);
1994 }
1995
1996 static int
1997 zfs_ioc_vdev_attach(zfs_cmd_t *zc)
1998 {
1999         spa_t *spa;
2000         int replacing = zc->zc_cookie;
2001         nvlist_t *config;
2002         int error;
2003
2004         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2005                 return (error);
2006
2007         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
2008             zc->zc_iflags, &config)) == 0) {
2009                 error = spa_vdev_attach(spa, zc->zc_guid, config, replacing);
2010                 nvlist_free(config);
2011         }
2012
2013         spa_close(spa, FTAG);
2014         return (error);
2015 }
2016
2017 static int
2018 zfs_ioc_vdev_detach(zfs_cmd_t *zc)
2019 {
2020         spa_t *spa;
2021         int error;
2022
2023         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2024                 return (error);
2025
2026         error = spa_vdev_detach(spa, zc->zc_guid, 0, B_FALSE);
2027
2028         spa_close(spa, FTAG);
2029         return (error);
2030 }
2031
2032 static int
2033 zfs_ioc_vdev_split(zfs_cmd_t *zc)
2034 {
2035         spa_t *spa;
2036         nvlist_t *config, *props = NULL;
2037         int error;
2038         boolean_t exp = !!(zc->zc_cookie & ZPOOL_EXPORT_AFTER_SPLIT);
2039
2040         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2041                 return (error);
2042
2043         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
2044             zc->zc_iflags, &config))) {
2045                 spa_close(spa, FTAG);
2046                 return (error);
2047         }
2048
2049         if (zc->zc_nvlist_src_size != 0 && (error =
2050             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2051             zc->zc_iflags, &props))) {
2052                 spa_close(spa, FTAG);
2053                 nvlist_free(config);
2054                 return (error);
2055         }
2056
2057         error = spa_vdev_split_mirror(spa, zc->zc_string, config, props, exp);
2058
2059         spa_close(spa, FTAG);
2060
2061         nvlist_free(config);
2062         nvlist_free(props);
2063
2064         return (error);
2065 }
2066
2067 static int
2068 zfs_ioc_vdev_setpath(zfs_cmd_t *zc)
2069 {
2070         spa_t *spa;
2071         char *path = zc->zc_value;
2072         uint64_t guid = zc->zc_guid;
2073         int error;
2074
2075         error = spa_open(zc->zc_name, &spa, FTAG);
2076         if (error != 0)
2077                 return (error);
2078
2079         error = spa_vdev_setpath(spa, guid, path);
2080         spa_close(spa, FTAG);
2081         return (error);
2082 }
2083
2084 static int
2085 zfs_ioc_vdev_setfru(zfs_cmd_t *zc)
2086 {
2087         spa_t *spa;
2088         char *fru = zc->zc_value;
2089         uint64_t guid = zc->zc_guid;
2090         int error;
2091
2092         error = spa_open(zc->zc_name, &spa, FTAG);
2093         if (error != 0)
2094                 return (error);
2095
2096         error = spa_vdev_setfru(spa, guid, fru);
2097         spa_close(spa, FTAG);
2098         return (error);
2099 }
2100
2101 static int
2102 zfs_ioc_objset_stats_impl(zfs_cmd_t *zc, objset_t *os)
2103 {
2104         int error = 0;
2105         nvlist_t *nv;
2106
2107         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
2108
2109         if (zc->zc_nvlist_dst != 0 &&
2110             (error = dsl_prop_get_all(os, &nv)) == 0) {
2111                 dmu_objset_stats(os, nv);
2112                 /*
2113                  * NB: zvol_get_stats() will read the objset contents,
2114                  * which we aren't supposed to do with a
2115                  * DS_MODE_USER hold, because it could be
2116                  * inconsistent.  So this is a bit of a workaround...
2117                  * XXX reading with out owning
2118                  */
2119                 if (!zc->zc_objset_stats.dds_inconsistent &&
2120                     dmu_objset_type(os) == DMU_OST_ZVOL) {
2121                         error = zvol_get_stats(os, nv);
2122                         if (error == EIO) {
2123                                 nvlist_free(nv);
2124                                 return (error);
2125                         }
2126                         VERIFY0(error);
2127                 }
2128                 if (error == 0)
2129                         error = put_nvlist(zc, nv);
2130                 nvlist_free(nv);
2131         }
2132
2133         return (error);
2134 }
2135
2136 /*
2137  * inputs:
2138  * zc_name              name of filesystem
2139  * zc_nvlist_dst_size   size of buffer for property nvlist
2140  *
2141  * outputs:
2142  * zc_objset_stats      stats
2143  * zc_nvlist_dst        property nvlist
2144  * zc_nvlist_dst_size   size of property nvlist
2145  */
2146 static int
2147 zfs_ioc_objset_stats(zfs_cmd_t *zc)
2148 {
2149         objset_t *os;
2150         int error;
2151
2152         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2153         if (error == 0) {
2154                 error = zfs_ioc_objset_stats_impl(zc, os);
2155                 dmu_objset_rele(os, FTAG);
2156         }
2157
2158         return (error);
2159 }
2160
2161 /*
2162  * inputs:
2163  * zc_name              name of filesystem
2164  * zc_nvlist_dst_size   size of buffer for property nvlist
2165  *
2166  * outputs:
2167  * zc_nvlist_dst        received property nvlist
2168  * zc_nvlist_dst_size   size of received property nvlist
2169  *
2170  * Gets received properties (distinct from local properties on or after
2171  * SPA_VERSION_RECVD_PROPS) for callers who want to differentiate received from
2172  * local property values.
2173  */
2174 static int
2175 zfs_ioc_objset_recvd_props(zfs_cmd_t *zc)
2176 {
2177         int error = 0;
2178         nvlist_t *nv;
2179
2180         /*
2181          * Without this check, we would return local property values if the
2182          * caller has not already received properties on or after
2183          * SPA_VERSION_RECVD_PROPS.
2184          */
2185         if (!dsl_prop_get_hasrecvd(zc->zc_name))
2186                 return (SET_ERROR(ENOTSUP));
2187
2188         if (zc->zc_nvlist_dst != 0 &&
2189             (error = dsl_prop_get_received(zc->zc_name, &nv)) == 0) {
2190                 error = put_nvlist(zc, nv);
2191                 nvlist_free(nv);
2192         }
2193
2194         return (error);
2195 }
2196
2197 static int
2198 nvl_add_zplprop(objset_t *os, nvlist_t *props, zfs_prop_t prop)
2199 {
2200         uint64_t value;
2201         int error;
2202
2203         /*
2204          * zfs_get_zplprop() will either find a value or give us
2205          * the default value (if there is one).
2206          */
2207         if ((error = zfs_get_zplprop(os, prop, &value)) != 0)
2208                 return (error);
2209         VERIFY(nvlist_add_uint64(props, zfs_prop_to_name(prop), value) == 0);
2210         return (0);
2211 }
2212
2213 /*
2214  * inputs:
2215  * zc_name              name of filesystem
2216  * zc_nvlist_dst_size   size of buffer for zpl property nvlist
2217  *
2218  * outputs:
2219  * zc_nvlist_dst        zpl property nvlist
2220  * zc_nvlist_dst_size   size of zpl property nvlist
2221  */
2222 static int
2223 zfs_ioc_objset_zplprops(zfs_cmd_t *zc)
2224 {
2225         objset_t *os;
2226         int err;
2227
2228         /* XXX reading without owning */
2229         if ((err = dmu_objset_hold(zc->zc_name, FTAG, &os)))
2230                 return (err);
2231
2232         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
2233
2234         /*
2235          * NB: nvl_add_zplprop() will read the objset contents,
2236          * which we aren't supposed to do with a DS_MODE_USER
2237          * hold, because it could be inconsistent.
2238          */
2239         if (zc->zc_nvlist_dst != 0 &&
2240             !zc->zc_objset_stats.dds_inconsistent &&
2241             dmu_objset_type(os) == DMU_OST_ZFS) {
2242                 nvlist_t *nv;
2243
2244                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2245                 if ((err = nvl_add_zplprop(os, nv, ZFS_PROP_VERSION)) == 0 &&
2246                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_NORMALIZE)) == 0 &&
2247                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_UTF8ONLY)) == 0 &&
2248                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_CASE)) == 0)
2249                         err = put_nvlist(zc, nv);
2250                 nvlist_free(nv);
2251         } else {
2252                 err = SET_ERROR(ENOENT);
2253         }
2254         dmu_objset_rele(os, FTAG);
2255         return (err);
2256 }
2257
2258 boolean_t
2259 dataset_name_hidden(const char *name)
2260 {
2261         /*
2262          * Skip over datasets that are not visible in this zone,
2263          * internal datasets (which have a $ in their name), and
2264          * temporary datasets (which have a % in their name).
2265          */
2266         if (strchr(name, '$') != NULL)
2267                 return (B_TRUE);
2268         if (strchr(name, '%') != NULL)
2269                 return (B_TRUE);
2270         if (!INGLOBALZONE(curproc) && !zone_dataset_visible(name, NULL))
2271                 return (B_TRUE);
2272         return (B_FALSE);
2273 }
2274
2275 /*
2276  * inputs:
2277  * zc_name              name of filesystem
2278  * zc_cookie            zap cursor
2279  * zc_nvlist_dst_size   size of buffer for property nvlist
2280  *
2281  * outputs:
2282  * zc_name              name of next filesystem
2283  * zc_cookie            zap cursor
2284  * zc_objset_stats      stats
2285  * zc_nvlist_dst        property nvlist
2286  * zc_nvlist_dst_size   size of property nvlist
2287  */
2288 static int
2289 zfs_ioc_dataset_list_next(zfs_cmd_t *zc)
2290 {
2291         objset_t *os;
2292         int error;
2293         char *p;
2294         size_t orig_len = strlen(zc->zc_name);
2295
2296 top:
2297         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os))) {
2298                 if (error == ENOENT)
2299                         error = SET_ERROR(ESRCH);
2300                 return (error);
2301         }
2302
2303         p = strrchr(zc->zc_name, '/');
2304         if (p == NULL || p[1] != '\0')
2305                 (void) strlcat(zc->zc_name, "/", sizeof (zc->zc_name));
2306         p = zc->zc_name + strlen(zc->zc_name);
2307
2308         do {
2309                 error = dmu_dir_list_next(os,
2310                     sizeof (zc->zc_name) - (p - zc->zc_name), p,
2311                     NULL, &zc->zc_cookie);
2312                 if (error == ENOENT)
2313                         error = SET_ERROR(ESRCH);
2314         } while (error == 0 && dataset_name_hidden(zc->zc_name));
2315         dmu_objset_rele(os, FTAG);
2316
2317         /*
2318          * If it's an internal dataset (ie. with a '$' in its name),
2319          * don't try to get stats for it, otherwise we'll return ENOENT.
2320          */
2321         if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
2322                 error = zfs_ioc_objset_stats(zc); /* fill in the stats */
2323                 if (error == ENOENT) {
2324                         /* We lost a race with destroy, get the next one. */
2325                         zc->zc_name[orig_len] = '\0';
2326                         goto top;
2327                 }
2328         }
2329         return (error);
2330 }
2331
2332 /*
2333  * inputs:
2334  * zc_name              name of filesystem
2335  * zc_cookie            zap cursor
2336  * zc_nvlist_dst_size   size of buffer for property nvlist
2337  *
2338  * outputs:
2339  * zc_name              name of next snapshot
2340  * zc_objset_stats      stats
2341  * zc_nvlist_dst        property nvlist
2342  * zc_nvlist_dst_size   size of property nvlist
2343  */
2344 static int
2345 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2346 {
2347         objset_t *os;
2348         int error;
2349
2350         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2351         if (error != 0) {
2352                 return (error == ENOENT ? ESRCH : error);
2353         }
2354
2355         /*
2356          * A dataset name of maximum length cannot have any snapshots,
2357          * so exit immediately.
2358          */
2359         if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >=
2360             ZFS_MAX_DATASET_NAME_LEN) {
2361                 dmu_objset_rele(os, FTAG);
2362                 return (SET_ERROR(ESRCH));
2363         }
2364
2365         error = dmu_snapshot_list_next(os,
2366             sizeof (zc->zc_name) - strlen(zc->zc_name),
2367             zc->zc_name + strlen(zc->zc_name), &zc->zc_obj, &zc->zc_cookie,
2368             NULL);
2369
2370         if (error == 0 && !zc->zc_simple) {
2371                 dsl_dataset_t *ds;
2372                 dsl_pool_t *dp = os->os_dsl_dataset->ds_dir->dd_pool;
2373
2374                 error = dsl_dataset_hold_obj(dp, zc->zc_obj, FTAG, &ds);
2375                 if (error == 0) {
2376                         objset_t *ossnap;
2377
2378                         error = dmu_objset_from_ds(ds, &ossnap);
2379                         if (error == 0)
2380                                 error = zfs_ioc_objset_stats_impl(zc, ossnap);
2381                         dsl_dataset_rele(ds, FTAG);
2382                 }
2383         } else if (error == ENOENT) {
2384                 error = SET_ERROR(ESRCH);
2385         }
2386
2387         dmu_objset_rele(os, FTAG);
2388         /* if we failed, undo the @ that we tacked on to zc_name */
2389         if (error != 0)
2390                 *strchr(zc->zc_name, '@') = '\0';
2391         return (error);
2392 }
2393
2394 static int
2395 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2396 {
2397         const char *propname = nvpair_name(pair);
2398         uint64_t *valary;
2399         unsigned int vallen;
2400         const char *domain;
2401         char *dash;
2402         zfs_userquota_prop_t type;
2403         uint64_t rid;
2404         uint64_t quota;
2405         zfsvfs_t *zfsvfs;
2406         int err;
2407
2408         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2409                 nvlist_t *attrs;
2410                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2411                 if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2412                     &pair) != 0)
2413                         return (SET_ERROR(EINVAL));
2414         }
2415
2416         /*
2417          * A correctly constructed propname is encoded as
2418          * userquota@<rid>-<domain>.
2419          */
2420         if ((dash = strchr(propname, '-')) == NULL ||
2421             nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2422             vallen != 3)
2423                 return (SET_ERROR(EINVAL));
2424
2425         domain = dash + 1;
2426         type = valary[0];
2427         rid = valary[1];
2428         quota = valary[2];
2429
2430         err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2431         if (err == 0) {
2432                 err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2433                 zfsvfs_rele(zfsvfs, FTAG);
2434         }
2435
2436         return (err);
2437 }
2438
2439 /*
2440  * If the named property is one that has a special function to set its value,
2441  * return 0 on success and a positive error code on failure; otherwise if it is
2442  * not one of the special properties handled by this function, return -1.
2443  *
2444  * XXX: It would be better for callers of the property interface if we handled
2445  * these special cases in dsl_prop.c (in the dsl layer).
2446  */
2447 static int
2448 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2449     nvpair_t *pair)
2450 {
2451         const char *propname = nvpair_name(pair);
2452         zfs_prop_t prop = zfs_name_to_prop(propname);
2453         uint64_t intval = 0;
2454         char *strval = NULL;
2455         int err = -1;
2456
2457         if (prop == ZPROP_INVAL) {
2458                 if (zfs_prop_userquota(propname))
2459                         return (zfs_prop_set_userquota(dsname, pair));
2460                 return (-1);
2461         }
2462
2463         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2464                 nvlist_t *attrs;
2465                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2466                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2467                     &pair) == 0);
2468         }
2469
2470         /* all special properties are numeric except for keylocation */
2471         if (zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
2472                 strval = fnvpair_value_string(pair);
2473         } else {
2474                 intval = fnvpair_value_uint64(pair);
2475         }
2476
2477         switch (prop) {
2478         case ZFS_PROP_QUOTA:
2479                 err = dsl_dir_set_quota(dsname, source, intval);
2480                 break;
2481         case ZFS_PROP_REFQUOTA:
2482                 err = dsl_dataset_set_refquota(dsname, source, intval);
2483                 break;
2484         case ZFS_PROP_FILESYSTEM_LIMIT:
2485         case ZFS_PROP_SNAPSHOT_LIMIT:
2486                 if (intval == UINT64_MAX) {
2487                         /* clearing the limit, just do it */
2488                         err = 0;
2489                 } else {
2490                         err = dsl_dir_activate_fs_ss_limit(dsname);
2491                 }
2492                 /*
2493                  * Set err to -1 to force the zfs_set_prop_nvlist code down the
2494                  * default path to set the value in the nvlist.
2495                  */
2496                 if (err == 0)
2497                         err = -1;
2498                 break;
2499         case ZFS_PROP_KEYLOCATION:
2500                 err = dsl_crypto_can_set_keylocation(dsname, strval);
2501
2502                 /*
2503                  * Set err to -1 to force the zfs_set_prop_nvlist code down the
2504                  * default path to set the value in the nvlist.
2505                  */
2506                 if (err == 0)
2507                         err = -1;
2508                 break;
2509         case ZFS_PROP_RESERVATION:
2510                 err = dsl_dir_set_reservation(dsname, source, intval);
2511                 break;
2512         case ZFS_PROP_REFRESERVATION:
2513                 err = dsl_dataset_set_refreservation(dsname, source, intval);
2514                 break;
2515         case ZFS_PROP_VOLSIZE:
2516                 err = zvol_set_volsize(dsname, intval);
2517                 break;
2518         case ZFS_PROP_SNAPDEV:
2519                 err = zvol_set_snapdev(dsname, source, intval);
2520                 break;
2521         case ZFS_PROP_VOLMODE:
2522                 err = zvol_set_volmode(dsname, source, intval);
2523                 break;
2524         case ZFS_PROP_VERSION:
2525         {
2526                 zfsvfs_t *zfsvfs;
2527
2528                 if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2529                         break;
2530
2531                 err = zfs_set_version(zfsvfs, intval);
2532                 zfsvfs_rele(zfsvfs, FTAG);
2533
2534                 if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2535                         zfs_cmd_t *zc;
2536
2537                         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2538                         (void) strcpy(zc->zc_name, dsname);
2539                         (void) zfs_ioc_userspace_upgrade(zc);
2540                         (void) zfs_ioc_id_quota_upgrade(zc);
2541                         kmem_free(zc, sizeof (zfs_cmd_t));
2542                 }
2543                 break;
2544         }
2545         default:
2546                 err = -1;
2547         }
2548
2549         return (err);
2550 }
2551
2552 /*
2553  * This function is best effort. If it fails to set any of the given properties,
2554  * it continues to set as many as it can and returns the last error
2555  * encountered. If the caller provides a non-NULL errlist, it will be filled in
2556  * with the list of names of all the properties that failed along with the
2557  * corresponding error numbers.
2558  *
2559  * If every property is set successfully, zero is returned and errlist is not
2560  * modified.
2561  */
2562 int
2563 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
2564     nvlist_t *errlist)
2565 {
2566         nvpair_t *pair;
2567         nvpair_t *propval;
2568         int rv = 0;
2569         uint64_t intval;
2570         char *strval;
2571
2572         nvlist_t *genericnvl = fnvlist_alloc();
2573         nvlist_t *retrynvl = fnvlist_alloc();
2574 retry:
2575         pair = NULL;
2576         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2577                 const char *propname = nvpair_name(pair);
2578                 zfs_prop_t prop = zfs_name_to_prop(propname);
2579                 int err = 0;
2580
2581                 /* decode the property value */
2582                 propval = pair;
2583                 if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2584                         nvlist_t *attrs;
2585                         attrs = fnvpair_value_nvlist(pair);
2586                         if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2587                             &propval) != 0)
2588                                 err = SET_ERROR(EINVAL);
2589                 }
2590
2591                 /* Validate value type */
2592                 if (err == 0 && source == ZPROP_SRC_INHERITED) {
2593                         /* inherited properties are expected to be booleans */
2594                         if (nvpair_type(propval) != DATA_TYPE_BOOLEAN)
2595                                 err = SET_ERROR(EINVAL);
2596                 } else if (err == 0 && prop == ZPROP_INVAL) {
2597                         if (zfs_prop_user(propname)) {
2598                                 if (nvpair_type(propval) != DATA_TYPE_STRING)
2599                                         err = SET_ERROR(EINVAL);
2600                         } else if (zfs_prop_userquota(propname)) {
2601                                 if (nvpair_type(propval) !=
2602                                     DATA_TYPE_UINT64_ARRAY)
2603                                         err = SET_ERROR(EINVAL);
2604                         } else {
2605                                 err = SET_ERROR(EINVAL);
2606                         }
2607                 } else if (err == 0) {
2608                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2609                                 if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
2610                                         err = SET_ERROR(EINVAL);
2611                         } else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
2612                                 const char *unused;
2613
2614                                 intval = fnvpair_value_uint64(propval);
2615
2616                                 switch (zfs_prop_get_type(prop)) {
2617                                 case PROP_TYPE_NUMBER:
2618                                         break;
2619                                 case PROP_TYPE_STRING:
2620                                         err = SET_ERROR(EINVAL);
2621                                         break;
2622                                 case PROP_TYPE_INDEX:
2623                                         if (zfs_prop_index_to_string(prop,
2624                                             intval, &unused) != 0)
2625                                                 err = SET_ERROR(EINVAL);
2626                                         break;
2627                                 default:
2628                                         cmn_err(CE_PANIC,
2629                                             "unknown property type");
2630                                 }
2631                         } else {
2632                                 err = SET_ERROR(EINVAL);
2633                         }
2634                 }
2635
2636                 /* Validate permissions */
2637                 if (err == 0)
2638                         err = zfs_check_settable(dsname, pair, CRED());
2639
2640                 if (err == 0) {
2641                         if (source == ZPROP_SRC_INHERITED)
2642                                 err = -1; /* does not need special handling */
2643                         else
2644                                 err = zfs_prop_set_special(dsname, source,
2645                                     pair);
2646                         if (err == -1) {
2647                                 /*
2648                                  * For better performance we build up a list of
2649                                  * properties to set in a single transaction.
2650                                  */
2651                                 err = nvlist_add_nvpair(genericnvl, pair);
2652                         } else if (err != 0 && nvl != retrynvl) {
2653                                 /*
2654                                  * This may be a spurious error caused by
2655                                  * receiving quota and reservation out of order.
2656                                  * Try again in a second pass.
2657                                  */
2658                                 err = nvlist_add_nvpair(retrynvl, pair);
2659                         }
2660                 }
2661
2662                 if (err != 0) {
2663                         if (errlist != NULL)
2664                                 fnvlist_add_int32(errlist, propname, err);
2665                         rv = err;
2666                 }
2667         }
2668
2669         if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
2670                 nvl = retrynvl;
2671                 goto retry;
2672         }
2673
2674         if (!nvlist_empty(genericnvl) &&
2675             dsl_props_set(dsname, source, genericnvl) != 0) {
2676                 /*
2677                  * If this fails, we still want to set as many properties as we
2678                  * can, so try setting them individually.
2679                  */
2680                 pair = NULL;
2681                 while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
2682                         const char *propname = nvpair_name(pair);
2683                         int err = 0;
2684
2685                         propval = pair;
2686                         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2687                                 nvlist_t *attrs;
2688                                 attrs = fnvpair_value_nvlist(pair);
2689                                 propval = fnvlist_lookup_nvpair(attrs,
2690                                     ZPROP_VALUE);
2691                         }
2692
2693                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2694                                 strval = fnvpair_value_string(propval);
2695                                 err = dsl_prop_set_string(dsname, propname,
2696                                     source, strval);
2697                         } else if (nvpair_type(propval) == DATA_TYPE_BOOLEAN) {
2698                                 err = dsl_prop_inherit(dsname, propname,
2699                                     source);
2700                         } else {
2701                                 intval = fnvpair_value_uint64(propval);
2702                                 err = dsl_prop_set_int(dsname, propname, source,
2703                                     intval);
2704                         }
2705
2706                         if (err != 0) {
2707                                 if (errlist != NULL) {
2708                                         fnvlist_add_int32(errlist, propname,
2709                                             err);
2710                                 }
2711                                 rv = err;
2712                         }
2713                 }
2714         }
2715         nvlist_free(genericnvl);
2716         nvlist_free(retrynvl);
2717
2718         return (rv);
2719 }
2720
2721 /*
2722  * Check that all the properties are valid user properties.
2723  */
2724 static int
2725 zfs_check_userprops(const char *fsname, nvlist_t *nvl)
2726 {
2727         nvpair_t *pair = NULL;
2728         int error = 0;
2729
2730         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2731                 const char *propname = nvpair_name(pair);
2732
2733                 if (!zfs_prop_user(propname) ||
2734                     nvpair_type(pair) != DATA_TYPE_STRING)
2735                         return (SET_ERROR(EINVAL));
2736
2737                 if ((error = zfs_secpolicy_write_perms(fsname,
2738                     ZFS_DELEG_PERM_USERPROP, CRED())))
2739                         return (error);
2740
2741                 if (strlen(propname) >= ZAP_MAXNAMELEN)
2742                         return (SET_ERROR(ENAMETOOLONG));
2743
2744                 if (strlen(fnvpair_value_string(pair)) >= ZAP_MAXVALUELEN)
2745                         return (SET_ERROR(E2BIG));
2746         }
2747         return (0);
2748 }
2749
2750 static void
2751 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
2752 {
2753         nvpair_t *pair;
2754
2755         VERIFY(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2756
2757         pair = NULL;
2758         while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
2759                 if (nvlist_exists(skipped, nvpair_name(pair)))
2760                         continue;
2761
2762                 VERIFY(nvlist_add_nvpair(*newprops, pair) == 0);
2763         }
2764 }
2765
2766 static int
2767 clear_received_props(const char *dsname, nvlist_t *props,
2768     nvlist_t *skipped)
2769 {
2770         int err = 0;
2771         nvlist_t *cleared_props = NULL;
2772         props_skip(props, skipped, &cleared_props);
2773         if (!nvlist_empty(cleared_props)) {
2774                 /*
2775                  * Acts on local properties until the dataset has received
2776                  * properties at least once on or after SPA_VERSION_RECVD_PROPS.
2777                  */
2778                 zprop_source_t flags = (ZPROP_SRC_NONE |
2779                     (dsl_prop_get_hasrecvd(dsname) ? ZPROP_SRC_RECEIVED : 0));
2780                 err = zfs_set_prop_nvlist(dsname, flags, cleared_props, NULL);
2781         }
2782         nvlist_free(cleared_props);
2783         return (err);
2784 }
2785
2786 /*
2787  * inputs:
2788  * zc_name              name of filesystem
2789  * zc_value             name of property to set
2790  * zc_nvlist_src{_size} nvlist of properties to apply
2791  * zc_cookie            received properties flag
2792  *
2793  * outputs:
2794  * zc_nvlist_dst{_size} error for each unapplied received property
2795  */
2796 static int
2797 zfs_ioc_set_prop(zfs_cmd_t *zc)
2798 {
2799         nvlist_t *nvl;
2800         boolean_t received = zc->zc_cookie;
2801         zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
2802             ZPROP_SRC_LOCAL);
2803         nvlist_t *errors;
2804         int error;
2805
2806         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2807             zc->zc_iflags, &nvl)) != 0)
2808                 return (error);
2809
2810         if (received) {
2811                 nvlist_t *origprops;
2812
2813                 if (dsl_prop_get_received(zc->zc_name, &origprops) == 0) {
2814                         (void) clear_received_props(zc->zc_name,
2815                             origprops, nvl);
2816                         nvlist_free(origprops);
2817                 }
2818
2819                 error = dsl_prop_set_hasrecvd(zc->zc_name);
2820         }
2821
2822         errors = fnvlist_alloc();
2823         if (error == 0)
2824                 error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, errors);
2825
2826         if (zc->zc_nvlist_dst != 0 && errors != NULL) {
2827                 (void) put_nvlist(zc, errors);
2828         }
2829
2830         nvlist_free(errors);
2831         nvlist_free(nvl);
2832         return (error);
2833 }
2834
2835 /*
2836  * inputs:
2837  * zc_name              name of filesystem
2838  * zc_value             name of property to inherit
2839  * zc_cookie            revert to received value if TRUE
2840  *
2841  * outputs:             none
2842  */
2843 static int
2844 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
2845 {
2846         const char *propname = zc->zc_value;
2847         zfs_prop_t prop = zfs_name_to_prop(propname);
2848         boolean_t received = zc->zc_cookie;
2849         zprop_source_t source = (received
2850             ? ZPROP_SRC_NONE            /* revert to received value, if any */
2851             : ZPROP_SRC_INHERITED);     /* explicitly inherit */
2852         nvlist_t *dummy;
2853         nvpair_t *pair;
2854         zprop_type_t type;
2855         int err;
2856
2857         if (!received) {
2858                 /*
2859                  * Only check this in the non-received case. We want to allow
2860                  * 'inherit -S' to revert non-inheritable properties like quota
2861                  * and reservation to the received or default values even though
2862                  * they are not considered inheritable.
2863                  */
2864                 if (prop != ZPROP_INVAL && !zfs_prop_inheritable(prop))
2865                         return (SET_ERROR(EINVAL));
2866         }
2867
2868         if (prop == ZPROP_INVAL) {
2869                 if (!zfs_prop_user(propname))
2870                         return (SET_ERROR(EINVAL));
2871
2872                 type = PROP_TYPE_STRING;
2873         } else if (prop == ZFS_PROP_VOLSIZE || prop == ZFS_PROP_VERSION) {
2874                 return (SET_ERROR(EINVAL));
2875         } else {
2876                 type = zfs_prop_get_type(prop);
2877         }
2878
2879         /*
2880          * zfs_prop_set_special() expects properties in the form of an
2881          * nvpair with type info.
2882          */
2883         dummy = fnvlist_alloc();
2884
2885         switch (type) {
2886         case PROP_TYPE_STRING:
2887                 VERIFY(0 == nvlist_add_string(dummy, propname, ""));
2888                 break;
2889         case PROP_TYPE_NUMBER:
2890         case PROP_TYPE_INDEX:
2891                 VERIFY(0 == nvlist_add_uint64(dummy, propname, 0));
2892                 break;
2893         default:
2894                 err = SET_ERROR(EINVAL);
2895                 goto errout;
2896         }
2897
2898         pair = nvlist_next_nvpair(dummy, NULL);
2899         if (pair == NULL) {
2900                 err = SET_ERROR(EINVAL);
2901         } else {
2902                 err = zfs_prop_set_special(zc->zc_name, source, pair);
2903                 if (err == -1) /* property is not "special", needs handling */
2904                         err = dsl_prop_inherit(zc->zc_name, zc->zc_value,
2905                             source);
2906         }
2907
2908 errout:
2909         nvlist_free(dummy);
2910         return (err);
2911 }
2912
2913 static int
2914 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
2915 {
2916         nvlist_t *props;
2917         spa_t *spa;
2918         int error;
2919         nvpair_t *pair;
2920
2921         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2922             zc->zc_iflags, &props)))
2923                 return (error);
2924
2925         /*
2926          * If the only property is the configfile, then just do a spa_lookup()
2927          * to handle the faulted case.
2928          */
2929         pair = nvlist_next_nvpair(props, NULL);
2930         if (pair != NULL && strcmp(nvpair_name(pair),
2931             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
2932             nvlist_next_nvpair(props, pair) == NULL) {
2933                 mutex_enter(&spa_namespace_lock);
2934                 if ((spa = spa_lookup(zc->zc_name)) != NULL) {
2935                         spa_configfile_set(spa, props, B_FALSE);
2936                         spa_write_cachefile(spa, B_FALSE, B_TRUE);
2937                 }
2938                 mutex_exit(&spa_namespace_lock);
2939                 if (spa != NULL) {
2940                         nvlist_free(props);
2941                         return (0);
2942                 }
2943         }
2944
2945         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2946                 nvlist_free(props);
2947                 return (error);
2948         }
2949
2950         error = spa_prop_set(spa, props);
2951
2952         nvlist_free(props);
2953         spa_close(spa, FTAG);
2954
2955         return (error);
2956 }
2957
2958 static int
2959 zfs_ioc_pool_get_props(zfs_cmd_t *zc)
2960 {
2961         spa_t *spa;
2962         int error;
2963         nvlist_t *nvp = NULL;
2964
2965         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2966                 /*
2967                  * If the pool is faulted, there may be properties we can still
2968                  * get (such as altroot and cachefile), so attempt to get them
2969                  * anyway.
2970                  */
2971                 mutex_enter(&spa_namespace_lock);
2972                 if ((spa = spa_lookup(zc->zc_name)) != NULL)
2973                         error = spa_prop_get(spa, &nvp);
2974                 mutex_exit(&spa_namespace_lock);
2975         } else {
2976                 error = spa_prop_get(spa, &nvp);
2977                 spa_close(spa, FTAG);
2978         }
2979
2980         if (error == 0 && zc->zc_nvlist_dst != 0)
2981                 error = put_nvlist(zc, nvp);
2982         else
2983                 error = SET_ERROR(EFAULT);
2984
2985         nvlist_free(nvp);
2986         return (error);
2987 }
2988
2989 /*
2990  * inputs:
2991  * zc_name              name of filesystem
2992  * zc_nvlist_src{_size} nvlist of delegated permissions
2993  * zc_perm_action       allow/unallow flag
2994  *
2995  * outputs:             none
2996  */
2997 static int
2998 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
2999 {
3000         int error;
3001         nvlist_t *fsaclnv = NULL;
3002
3003         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3004             zc->zc_iflags, &fsaclnv)) != 0)
3005                 return (error);
3006
3007         /*
3008          * Verify nvlist is constructed correctly
3009          */
3010         if ((error = zfs_deleg_verify_nvlist(fsaclnv)) != 0) {
3011                 nvlist_free(fsaclnv);
3012                 return (SET_ERROR(EINVAL));
3013         }
3014
3015         /*
3016          * If we don't have PRIV_SYS_MOUNT, then validate
3017          * that user is allowed to hand out each permission in
3018          * the nvlist(s)
3019          */
3020
3021         error = secpolicy_zfs(CRED());
3022         if (error != 0) {
3023                 if (zc->zc_perm_action == B_FALSE) {
3024                         error = dsl_deleg_can_allow(zc->zc_name,
3025                             fsaclnv, CRED());
3026                 } else {
3027                         error = dsl_deleg_can_unallow(zc->zc_name,
3028                             fsaclnv, CRED());
3029                 }
3030         }
3031
3032         if (error == 0)
3033                 error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
3034
3035         nvlist_free(fsaclnv);
3036         return (error);
3037 }
3038
3039 /*
3040  * inputs:
3041  * zc_name              name of filesystem
3042  *
3043  * outputs:
3044  * zc_nvlist_src{_size} nvlist of delegated permissions
3045  */
3046 static int
3047 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
3048 {
3049         nvlist_t *nvp;
3050         int error;
3051
3052         if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
3053                 error = put_nvlist(zc, nvp);
3054                 nvlist_free(nvp);
3055         }
3056
3057         return (error);
3058 }
3059
3060 /* ARGSUSED */
3061 static void
3062 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3063 {
3064         zfs_creat_t *zct = arg;
3065
3066         zfs_create_fs(os, cr, zct->zct_zplprops, tx);
3067 }
3068
3069 #define ZFS_PROP_UNDEFINED      ((uint64_t)-1)
3070
3071 /*
3072  * inputs:
3073  * os                   parent objset pointer (NULL if root fs)
3074  * fuids_ok             fuids allowed in this version of the spa?
3075  * sa_ok                SAs allowed in this version of the spa?
3076  * createprops          list of properties requested by creator
3077  *
3078  * outputs:
3079  * zplprops     values for the zplprops we attach to the master node object
3080  * is_ci        true if requested file system will be purely case-insensitive
3081  *
3082  * Determine the settings for utf8only, normalization and
3083  * casesensitivity.  Specific values may have been requested by the
3084  * creator and/or we can inherit values from the parent dataset.  If
3085  * the file system is of too early a vintage, a creator can not
3086  * request settings for these properties, even if the requested
3087  * setting is the default value.  We don't actually want to create dsl
3088  * properties for these, so remove them from the source nvlist after
3089  * processing.
3090  */
3091 static int
3092 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
3093     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
3094     nvlist_t *zplprops, boolean_t *is_ci)
3095 {
3096         uint64_t sense = ZFS_PROP_UNDEFINED;
3097         uint64_t norm = ZFS_PROP_UNDEFINED;
3098         uint64_t u8 = ZFS_PROP_UNDEFINED;
3099         int error;
3100
3101         ASSERT(zplprops != NULL);
3102
3103         if (os != NULL && os->os_phys->os_type != DMU_OST_ZFS)
3104                 return (SET_ERROR(EINVAL));
3105
3106         /*
3107          * Pull out creator prop choices, if any.
3108          */
3109         if (createprops) {
3110                 (void) nvlist_lookup_uint64(createprops,
3111                     zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
3112                 (void) nvlist_lookup_uint64(createprops,
3113                     zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
3114                 (void) nvlist_remove_all(createprops,
3115                     zfs_prop_to_name(ZFS_PROP_NORMALIZE));
3116                 (void) nvlist_lookup_uint64(createprops,
3117                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
3118                 (void) nvlist_remove_all(createprops,
3119                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
3120                 (void) nvlist_lookup_uint64(createprops,
3121                     zfs_prop_to_name(ZFS_PROP_CASE), &sense);
3122                 (void) nvlist_remove_all(createprops,
3123                     zfs_prop_to_name(ZFS_PROP_CASE));
3124         }
3125
3126         /*
3127          * If the zpl version requested is whacky or the file system
3128          * or pool is version is too "young" to support normalization
3129          * and the creator tried to set a value for one of the props,
3130          * error out.
3131          */
3132         if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
3133             (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
3134             (zplver >= ZPL_VERSION_SA && !sa_ok) ||
3135             (zplver < ZPL_VERSION_NORMALIZATION &&
3136             (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
3137             sense != ZFS_PROP_UNDEFINED)))
3138                 return (SET_ERROR(ENOTSUP));
3139
3140         /*
3141          * Put the version in the zplprops
3142          */
3143         VERIFY(nvlist_add_uint64(zplprops,
3144             zfs_prop_to_name(ZFS_PROP_VERSION), zplver) == 0);
3145
3146         if (norm == ZFS_PROP_UNDEFINED &&
3147             (error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm)) != 0)
3148                 return (error);
3149         VERIFY(nvlist_add_uint64(zplprops,
3150             zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm) == 0);
3151
3152         /*
3153          * If we're normalizing, names must always be valid UTF-8 strings.
3154          */
3155         if (norm)
3156                 u8 = 1;
3157         if (u8 == ZFS_PROP_UNDEFINED &&
3158             (error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8)) != 0)
3159                 return (error);
3160         VERIFY(nvlist_add_uint64(zplprops,
3161             zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8) == 0);
3162
3163         if (sense == ZFS_PROP_UNDEFINED &&
3164             (error = zfs_get_zplprop(os, ZFS_PROP_CASE, &sense)) != 0)
3165                 return (error);
3166         VERIFY(nvlist_add_uint64(zplprops,
3167             zfs_prop_to_name(ZFS_PROP_CASE), sense) == 0);
3168
3169         if (is_ci)
3170                 *is_ci = (sense == ZFS_CASE_INSENSITIVE);
3171
3172         return (0);
3173 }
3174
3175 static int
3176 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
3177     nvlist_t *zplprops, boolean_t *is_ci)
3178 {
3179         boolean_t fuids_ok, sa_ok;
3180         uint64_t zplver = ZPL_VERSION;
3181         objset_t *os = NULL;
3182         char parentname[ZFS_MAX_DATASET_NAME_LEN];
3183         char *cp;
3184         spa_t *spa;
3185         uint64_t spa_vers;
3186         int error;
3187
3188         (void) strlcpy(parentname, dataset, sizeof (parentname));
3189         cp = strrchr(parentname, '/');
3190         ASSERT(cp != NULL);
3191         cp[0] = '\0';
3192
3193         if ((error = spa_open(dataset, &spa, FTAG)) != 0)
3194                 return (error);
3195
3196         spa_vers = spa_version(spa);
3197         spa_close(spa, FTAG);
3198
3199         zplver = zfs_zpl_version_map(spa_vers);
3200         fuids_ok = (zplver >= ZPL_VERSION_FUID);
3201         sa_ok = (zplver >= ZPL_VERSION_SA);
3202
3203         /*
3204          * Open parent object set so we can inherit zplprop values.
3205          */
3206         if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
3207                 return (error);
3208
3209         error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
3210             zplprops, is_ci);
3211         dmu_objset_rele(os, FTAG);
3212         return (error);
3213 }
3214
3215 static int
3216 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
3217     nvlist_t *zplprops, boolean_t *is_ci)
3218 {
3219         boolean_t fuids_ok;
3220         boolean_t sa_ok;
3221         uint64_t zplver = ZPL_VERSION;
3222         int error;
3223
3224         zplver = zfs_zpl_version_map(spa_vers);
3225         fuids_ok = (zplver >= ZPL_VERSION_FUID);
3226         sa_ok = (zplver >= ZPL_VERSION_SA);
3227
3228         error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
3229             createprops, zplprops, is_ci);
3230         return (error);
3231 }
3232
3233 /*
3234  * innvl: {
3235  *     "type" -> dmu_objset_type_t (int32)
3236  *     (optional) "props" -> { prop -> value }
3237  *     (optional) "hidden_args" -> { "wkeydata" -> value }
3238  *         raw uint8_t array of encryption wrapping key data (32 bytes)
3239  * }
3240  *
3241  * outnvl: propname -> error code (int32)
3242  */
3243 static int
3244 zfs_ioc_create(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3245 {
3246         int error = 0;
3247         zfs_creat_t zct = { 0 };
3248         nvlist_t *nvprops = NULL;
3249         nvlist_t *hidden_args = NULL;
3250         void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
3251         int32_t type32;
3252         dmu_objset_type_t type;
3253         boolean_t is_insensitive = B_FALSE;
3254         dsl_crypto_params_t *dcp = NULL;
3255
3256         if (nvlist_lookup_int32(innvl, "type", &type32) != 0)
3257                 return (SET_ERROR(EINVAL));
3258         type = type32;
3259         (void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3260         (void) nvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS, &hidden_args);
3261
3262         switch (type) {
3263         case DMU_OST_ZFS:
3264                 cbfunc = zfs_create_cb;
3265                 break;
3266
3267         case DMU_OST_ZVOL:
3268                 cbfunc = zvol_create_cb;
3269                 break;
3270
3271         default:
3272                 cbfunc = NULL;
3273                 break;
3274         }
3275         if (strchr(fsname, '@') ||
3276             strchr(fsname, '%'))
3277                 return (SET_ERROR(EINVAL));
3278
3279         zct.zct_props = nvprops;
3280
3281         if (cbfunc == NULL)
3282                 return (SET_ERROR(EINVAL));
3283
3284         if (type == DMU_OST_ZVOL) {
3285                 uint64_t volsize, volblocksize;
3286
3287                 if (nvprops == NULL)
3288                         return (SET_ERROR(EINVAL));
3289                 if (nvlist_lookup_uint64(nvprops,
3290                     zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) != 0)
3291                         return (SET_ERROR(EINVAL));
3292
3293                 if ((error = nvlist_lookup_uint64(nvprops,
3294                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3295                     &volblocksize)) != 0 && error != ENOENT)
3296                         return (SET_ERROR(EINVAL));
3297
3298                 if (error != 0)
3299                         volblocksize = zfs_prop_default_numeric(
3300                             ZFS_PROP_VOLBLOCKSIZE);
3301
3302                 if ((error = zvol_check_volblocksize(fsname,
3303                     volblocksize)) != 0 ||
3304                     (error = zvol_check_volsize(volsize,
3305                     volblocksize)) != 0)
3306                         return (error);
3307         } else if (type == DMU_OST_ZFS) {
3308                 int error;
3309
3310                 /*
3311                  * We have to have normalization and
3312                  * case-folding flags correct when we do the
3313                  * file system creation, so go figure them out
3314                  * now.
3315                  */
3316                 VERIFY(nvlist_alloc(&zct.zct_zplprops,
3317                     NV_UNIQUE_NAME, KM_SLEEP) == 0);
3318                 error = zfs_fill_zplprops(fsname, nvprops,
3319                     zct.zct_zplprops, &is_insensitive);
3320                 if (error != 0) {
3321                         nvlist_free(zct.zct_zplprops);
3322                         return (error);
3323                 }
3324         }
3325
3326         error = dsl_crypto_params_create_nvlist(DCP_CMD_NONE, nvprops,
3327             hidden_args, &dcp);
3328         if (error != 0) {
3329                 nvlist_free(zct.zct_zplprops);
3330                 return (error);
3331         }
3332
3333         error = dmu_objset_create(fsname, type,
3334             is_insensitive ? DS_FLAG_CI_DATASET : 0, dcp, cbfunc, &zct);
3335
3336         nvlist_free(zct.zct_zplprops);
3337         dsl_crypto_params_free(dcp, !!error);
3338
3339         /*
3340          * It would be nice to do this atomically.
3341          */
3342         if (error == 0) {
3343                 error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
3344                     nvprops, outnvl);
3345                 if (error != 0) {
3346                         spa_t *spa;
3347                         int error2;
3348
3349                         /*
3350                          * Volumes will return EBUSY and cannot be destroyed
3351                          * until all asynchronous minor handling has completed.
3352                          * Wait for the spa_zvol_taskq to drain then retry.
3353                          */
3354                         error2 = dsl_destroy_head(fsname);
3355                         while ((error2 == EBUSY) && (type == DMU_OST_ZVOL)) {
3356                                 error2 = spa_open(fsname, &spa, FTAG);
3357                                 if (error2 == 0) {
3358                                         taskq_wait(spa->spa_zvol_taskq);
3359                                         spa_close(spa, FTAG);
3360                                 }
3361                                 error2 = dsl_destroy_head(fsname);
3362                         }
3363                 }
3364         }
3365         return (error);
3366 }
3367
3368 /*
3369  * innvl: {
3370  *     "origin" -> name of origin snapshot
3371  *     (optional) "props" -> { prop -> value }
3372  *     (optional) "hidden_args" -> { "wkeydata" -> value }
3373  *         raw uint8_t array of encryption wrapping key data (32 bytes)
3374  * }
3375  *
3376  * outputs:
3377  * outnvl: propname -> error code (int32)
3378  */
3379 static int
3380 zfs_ioc_clone(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3381 {
3382         int error = 0;
3383         nvlist_t *nvprops = NULL;
3384         char *origin_name;
3385
3386         if (nvlist_lookup_string(innvl, "origin", &origin_name) != 0)
3387                 return (SET_ERROR(EINVAL));
3388         (void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3389
3390         if (strchr(fsname, '@') ||
3391             strchr(fsname, '%'))
3392                 return (SET_ERROR(EINVAL));
3393
3394         if (dataset_namecheck(origin_name, NULL, NULL) != 0)
3395                 return (SET_ERROR(EINVAL));
3396
3397         error = dmu_objset_clone(fsname, origin_name);
3398
3399         /*
3400          * It would be nice to do this atomically.
3401          */
3402         if (error == 0) {
3403                 error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
3404                     nvprops, outnvl);
3405                 if (error != 0)
3406                         (void) dsl_destroy_head(fsname);
3407         }
3408         return (error);
3409 }
3410
3411 /* ARGSUSED */
3412 static int
3413 zfs_ioc_remap(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3414 {
3415         if (strchr(fsname, '@') ||
3416             strchr(fsname, '%'))
3417                 return (SET_ERROR(EINVAL));
3418
3419         return (dmu_objset_remap_indirects(fsname));
3420 }
3421
3422 /*
3423  * innvl: {
3424  *     "snaps" -> { snapshot1, snapshot2 }
3425  *     (optional) "props" -> { prop -> value (string) }
3426  * }
3427  *
3428  * outnvl: snapshot -> error code (int32)
3429  */
3430 static int
3431 zfs_ioc_snapshot(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3432 {
3433         nvlist_t *snaps;
3434         nvlist_t *props = NULL;
3435         int error, poollen;
3436         nvpair_t *pair;
3437
3438         (void) nvlist_lookup_nvlist(innvl, "props", &props);
3439         if ((error = zfs_check_userprops(poolname, props)) != 0)
3440                 return (error);
3441
3442         if (!nvlist_empty(props) &&
3443             zfs_earlier_version(poolname, SPA_VERSION_SNAP_PROPS))
3444                 return (SET_ERROR(ENOTSUP));
3445
3446         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3447                 return (SET_ERROR(EINVAL));
3448         poollen = strlen(poolname);
3449         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3450             pair = nvlist_next_nvpair(snaps, pair)) {
3451                 const char *name = nvpair_name(pair);
3452                 const char *cp = strchr(name, '@');
3453
3454                 /*
3455                  * The snap name must contain an @, and the part after it must
3456                  * contain only valid characters.
3457                  */
3458                 if (cp == NULL ||
3459                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3460                         return (SET_ERROR(EINVAL));
3461
3462                 /*
3463                  * The snap must be in the specified pool.
3464                  */
3465                 if (strncmp(name, poolname, poollen) != 0 ||
3466                     (name[poollen] != '/' && name[poollen] != '@'))
3467                         return (SET_ERROR(EXDEV));
3468
3469                 /* This must be the only snap of this fs. */
3470                 for (nvpair_t *pair2 = nvlist_next_nvpair(snaps, pair);
3471                     pair2 != NULL; pair2 = nvlist_next_nvpair(snaps, pair2)) {
3472                         if (strncmp(name, nvpair_name(pair2), cp - name + 1)
3473                             == 0) {
3474                                 return (SET_ERROR(EXDEV));
3475                         }
3476                 }
3477         }
3478
3479         error = dsl_dataset_snapshot(snaps, props, outnvl);
3480
3481         return (error);
3482 }
3483
3484 /*
3485  * innvl: "message" -> string
3486  */
3487 /* ARGSUSED */
3488 static int
3489 zfs_ioc_log_history(const char *unused, nvlist_t *innvl, nvlist_t *outnvl)
3490 {
3491         char *message;
3492         spa_t *spa;
3493         int error;
3494         char *poolname;
3495
3496         /*
3497          * The poolname in the ioctl is not set, we get it from the TSD,
3498          * which was set at the end of the last successful ioctl that allows
3499          * logging.  The secpolicy func already checked that it is set.
3500          * Only one log ioctl is allowed after each successful ioctl, so
3501          * we clear the TSD here.
3502          */
3503         poolname = tsd_get(zfs_allow_log_key);
3504         if (poolname == NULL)
3505                 return (SET_ERROR(EINVAL));
3506         (void) tsd_set(zfs_allow_log_key, NULL);
3507         error = spa_open(poolname, &spa, FTAG);
3508         strfree(poolname);
3509         if (error != 0)
3510                 return (error);
3511
3512         if (nvlist_lookup_string(innvl, "message", &message) != 0)  {
3513                 spa_close(spa, FTAG);
3514                 return (SET_ERROR(EINVAL));
3515         }
3516
3517         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
3518                 spa_close(spa, FTAG);
3519                 return (SET_ERROR(ENOTSUP));
3520         }
3521
3522         error = spa_history_log(spa, message);
3523         spa_close(spa, FTAG);
3524         return (error);
3525 }
3526
3527 /*
3528  * The dp_config_rwlock must not be held when calling this, because the
3529  * unmount may need to write out data.
3530  *
3531  * This function is best-effort.  Callers must deal gracefully if it
3532  * remains mounted (or is remounted after this call).
3533  *
3534  * Returns 0 if the argument is not a snapshot, or it is not currently a
3535  * filesystem, or we were able to unmount it.  Returns error code otherwise.
3536  */
3537 void
3538 zfs_unmount_snap(const char *snapname)
3539 {
3540         if (strchr(snapname, '@') == NULL)
3541                 return;
3542
3543         (void) zfsctl_snapshot_unmount((char *)snapname, MNT_FORCE);
3544 }
3545
3546 /* ARGSUSED */
3547 static int
3548 zfs_unmount_snap_cb(const char *snapname, void *arg)
3549 {
3550         zfs_unmount_snap(snapname);
3551         return (0);
3552 }
3553
3554 /*
3555  * When a clone is destroyed, its origin may also need to be destroyed,
3556  * in which case it must be unmounted.  This routine will do that unmount
3557  * if necessary.
3558  */
3559 void
3560 zfs_destroy_unmount_origin(const char *fsname)
3561 {
3562         int error;
3563         objset_t *os;
3564         dsl_dataset_t *ds;
3565
3566         error = dmu_objset_hold(fsname, FTAG, &os);
3567         if (error != 0)
3568                 return;
3569         ds = dmu_objset_ds(os);
3570         if (dsl_dir_is_clone(ds->ds_dir) && DS_IS_DEFER_DESTROY(ds->ds_prev)) {
3571                 char originname[ZFS_MAX_DATASET_NAME_LEN];
3572                 dsl_dataset_name(ds->ds_prev, originname);
3573                 dmu_objset_rele(os, FTAG);
3574                 zfs_unmount_snap(originname);
3575         } else {
3576                 dmu_objset_rele(os, FTAG);
3577         }
3578 }
3579
3580 /*
3581  * innvl: {
3582  *     "snaps" -> { snapshot1, snapshot2 }
3583  *     (optional boolean) "defer"
3584  * }
3585  *
3586  * outnvl: snapshot -> error code (int32)
3587  */
3588 /* ARGSUSED */
3589 static int
3590 zfs_ioc_destroy_snaps(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3591 {
3592         nvlist_t *snaps;
3593         nvpair_t *pair;
3594         boolean_t defer;
3595
3596         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3597                 return (SET_ERROR(EINVAL));
3598         defer = nvlist_exists(innvl, "defer");
3599
3600         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3601             pair = nvlist_next_nvpair(snaps, pair)) {
3602                 zfs_unmount_snap(nvpair_name(pair));
3603         }
3604
3605         return (dsl_destroy_snapshots_nvl(snaps, defer, outnvl));
3606 }
3607
3608 /*
3609  * Create bookmarks.  Bookmark names are of the form <fs>#<bmark>.
3610  * All bookmarks must be in the same pool.
3611  *
3612  * innvl: {
3613  *     bookmark1 -> snapshot1, bookmark2 -> snapshot2
3614  * }
3615  *
3616  * outnvl: bookmark -> error code (int32)
3617  *
3618  */
3619 /* ARGSUSED */
3620 static int
3621 zfs_ioc_bookmark(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3622 {
3623         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3624             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3625                 char *snap_name;
3626
3627                 /*
3628                  * Verify the snapshot argument.
3629                  */
3630                 if (nvpair_value_string(pair, &snap_name) != 0)
3631                         return (SET_ERROR(EINVAL));
3632
3633
3634                 /* Verify that the keys (bookmarks) are unique */
3635                 for (nvpair_t *pair2 = nvlist_next_nvpair(innvl, pair);
3636                     pair2 != NULL; pair2 = nvlist_next_nvpair(innvl, pair2)) {
3637                         if (strcmp(nvpair_name(pair), nvpair_name(pair2)) == 0)
3638                                 return (SET_ERROR(EINVAL));
3639                 }
3640         }
3641
3642         return (dsl_bookmark_create(innvl, outnvl));
3643 }
3644
3645 /*
3646  * innvl: {
3647  *     property 1, property 2, ...
3648  * }
3649  *
3650  * outnvl: {
3651  *     bookmark name 1 -> { property 1, property 2, ... },
3652  *     bookmark name 2 -> { property 1, property 2, ... }
3653  * }
3654  *
3655  */
3656 static int
3657 zfs_ioc_get_bookmarks(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3658 {
3659         return (dsl_get_bookmarks(fsname, innvl, outnvl));
3660 }
3661
3662 /*
3663  * innvl: {
3664  *     bookmark name 1, bookmark name 2
3665  * }
3666  *
3667  * outnvl: bookmark -> error code (int32)
3668  *
3669  */
3670 static int
3671 zfs_ioc_destroy_bookmarks(const char *poolname, nvlist_t *innvl,
3672     nvlist_t *outnvl)
3673 {
3674         int error, poollen;
3675
3676         poollen = strlen(poolname);
3677         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3678             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3679                 const char *name = nvpair_name(pair);
3680                 const char *cp = strchr(name, '#');
3681
3682                 /*
3683                  * The bookmark name must contain an #, and the part after it
3684                  * must contain only valid characters.
3685                  */
3686                 if (cp == NULL ||
3687                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3688                         return (SET_ERROR(EINVAL));
3689
3690                 /*
3691                  * The bookmark must be in the specified pool.
3692                  */
3693                 if (strncmp(name, poolname, poollen) != 0 ||
3694                     (name[poollen] != '/' && name[poollen] != '#'))
3695                         return (SET_ERROR(EXDEV));
3696         }
3697
3698         error = dsl_bookmark_destroy(innvl, outnvl);
3699         return (error);
3700 }
3701
3702 static int
3703 zfs_ioc_channel_program(const char *poolname, nvlist_t *innvl,
3704     nvlist_t *outnvl)
3705 {
3706         char *program;
3707         uint64_t instrlimit, memlimit;
3708         boolean_t sync_flag;
3709         nvpair_t *nvarg = NULL;
3710
3711         if (0 != nvlist_lookup_string(innvl, ZCP_ARG_PROGRAM, &program)) {
3712                 return (EINVAL);
3713         }
3714         if (0 != nvlist_lookup_boolean_value(innvl, ZCP_ARG_SYNC, &sync_flag)) {
3715                 sync_flag = B_TRUE;
3716         }
3717         if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_INSTRLIMIT, &instrlimit)) {
3718                 instrlimit = ZCP_DEFAULT_INSTRLIMIT;
3719         }
3720         if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_MEMLIMIT, &memlimit)) {
3721                 memlimit = ZCP_DEFAULT_MEMLIMIT;
3722         }
3723         if (0 != nvlist_lookup_nvpair(innvl, ZCP_ARG_ARGLIST, &nvarg)) {
3724                 return (EINVAL);
3725         }
3726
3727         if (instrlimit == 0 || instrlimit > zfs_lua_max_instrlimit)
3728                 return (EINVAL);
3729         if (memlimit == 0 || memlimit > zfs_lua_max_memlimit)
3730                 return (EINVAL);
3731
3732         return (zcp_eval(poolname, program, sync_flag, instrlimit, memlimit,
3733             nvarg, outnvl));
3734 }
3735
3736 /*
3737  * inputs:
3738  * zc_name              name of dataset to destroy
3739  * zc_objset_type       type of objset
3740  * zc_defer_destroy     mark for deferred destroy
3741  *
3742  * outputs:             none
3743  */
3744 static int
3745 zfs_ioc_destroy(zfs_cmd_t *zc)
3746 {
3747         int err;
3748
3749         if (zc->zc_objset_type == DMU_OST_ZFS)
3750                 zfs_unmount_snap(zc->zc_name);
3751
3752         if (strchr(zc->zc_name, '@')) {
3753                 err = dsl_destroy_snapshot(zc->zc_name, zc->zc_defer_destroy);
3754         } else {
3755                 err = dsl_destroy_head(zc->zc_name);
3756                 if (err == EEXIST) {
3757                         /*
3758                          * It is possible that the given DS may have
3759                          * hidden child (%recv) datasets - "leftovers"
3760                          * resulting from the previously interrupted
3761                          * 'zfs receive'.
3762                          *
3763                          * 6 extra bytes for /%recv
3764                          */
3765                         char namebuf[ZFS_MAX_DATASET_NAME_LEN + 6];
3766
3767                         if (snprintf(namebuf, sizeof (namebuf), "%s/%s",
3768                             zc->zc_name, recv_clone_name) >=
3769                             sizeof (namebuf))
3770                                 return (SET_ERROR(EINVAL));
3771
3772                         /*
3773                          * Try to remove the hidden child (%recv) and after
3774                          * that try to remove the target dataset.
3775                          * If the hidden child (%recv) does not exist
3776                          * the original error (EEXIST) will be returned
3777                          */
3778                         err = dsl_destroy_head(namebuf);
3779                         if (err == 0)
3780                                 err = dsl_destroy_head(zc->zc_name);
3781                         else if (err == ENOENT)
3782                                 err = SET_ERROR(EEXIST);
3783                 }
3784         }
3785
3786         return (err);
3787 }
3788
3789 /*
3790  * fsname is name of dataset to rollback (to most recent snapshot)
3791  *
3792  * innvl may contain name of expected target snapshot
3793  *
3794  * outnvl: "target" -> name of most recent snapshot
3795  * }
3796  */
3797 /* ARGSUSED */
3798 static int
3799 zfs_ioc_rollback(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3800 {
3801         zfsvfs_t *zfsvfs;
3802         zvol_state_t *zv;
3803         char *target = NULL;
3804         int error;
3805
3806         (void) nvlist_lookup_string(innvl, "target", &target);
3807         if (target != NULL) {
3808                 const char *cp = strchr(target, '@');
3809
3810                 /*
3811                  * The snap name must contain an @, and the part after it must
3812                  * contain only valid characters.
3813                  */
3814                 if (cp == NULL ||
3815                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3816                         return (SET_ERROR(EINVAL));
3817         }
3818
3819         if (getzfsvfs(fsname, &zfsvfs) == 0) {
3820                 dsl_dataset_t *ds;
3821
3822                 ds = dmu_objset_ds(zfsvfs->z_os);
3823                 error = zfs_suspend_fs(zfsvfs);
3824                 if (error == 0) {
3825                         int resume_err;
3826
3827                         error = dsl_dataset_rollback(fsname, target, zfsvfs,
3828                             outnvl);
3829                         resume_err = zfs_resume_fs(zfsvfs, ds);
3830                         error = error ? error : resume_err;
3831                 }
3832                 deactivate_super(zfsvfs->z_sb);
3833         } else if ((zv = zvol_suspend(fsname)) != NULL) {
3834                 error = dsl_dataset_rollback(fsname, target, zvol_tag(zv),
3835                     outnvl);
3836                 zvol_resume(zv);
3837         } else {
3838                 error = dsl_dataset_rollback(fsname, target, NULL, outnvl);
3839         }
3840         return (error);
3841 }
3842
3843 static int
3844 recursive_unmount(const char *fsname, void *arg)
3845 {
3846         const char *snapname = arg;
3847         char *fullname;
3848
3849         fullname = kmem_asprintf("%s@%s", fsname, snapname);
3850         zfs_unmount_snap(fullname);
3851         strfree(fullname);
3852
3853         return (0);
3854 }
3855
3856 /*
3857  * inputs:
3858  * zc_name      old name of dataset
3859  * zc_value     new name of dataset
3860  * zc_cookie    recursive flag (only valid for snapshots)
3861  *
3862  * outputs:     none
3863  */
3864 static int
3865 zfs_ioc_rename(zfs_cmd_t *zc)
3866 {
3867         boolean_t recursive = zc->zc_cookie & 1;
3868         char *at;
3869
3870         /* "zfs rename" from and to ...%recv datasets should both fail */
3871         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
3872         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3873         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
3874             dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3875             strchr(zc->zc_name, '%') || strchr(zc->zc_value, '%'))
3876                 return (SET_ERROR(EINVAL));
3877
3878         at = strchr(zc->zc_name, '@');
3879         if (at != NULL) {
3880                 /* snaps must be in same fs */
3881                 int error;
3882
3883                 if (strncmp(zc->zc_name, zc->zc_value, at - zc->zc_name + 1))
3884                         return (SET_ERROR(EXDEV));
3885                 *at = '\0';
3886                 if (zc->zc_objset_type == DMU_OST_ZFS) {
3887                         error = dmu_objset_find(zc->zc_name,
3888                             recursive_unmount, at + 1,
3889                             recursive ? DS_FIND_CHILDREN : 0);
3890                         if (error != 0) {
3891                                 *at = '@';
3892                                 return (error);
3893                         }
3894                 }
3895                 error = dsl_dataset_rename_snapshot(zc->zc_name,
3896                     at + 1, strchr(zc->zc_value, '@') + 1, recursive);
3897                 *at = '@';
3898
3899                 return (error);
3900         } else {
3901                 return (dsl_dir_rename(zc->zc_name, zc->zc_value));
3902         }
3903 }
3904
3905 static int
3906 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3907 {
3908         const char *propname = nvpair_name(pair);
3909         boolean_t issnap = (strchr(dsname, '@') != NULL);
3910         zfs_prop_t prop = zfs_name_to_prop(propname);
3911         uint64_t intval;
3912         int err;
3913
3914         if (prop == ZPROP_INVAL) {
3915                 if (zfs_prop_user(propname)) {
3916                         if ((err = zfs_secpolicy_write_perms(dsname,
3917                             ZFS_DELEG_PERM_USERPROP, cr)))
3918                                 return (err);
3919                         return (0);
3920                 }
3921
3922                 if (!issnap && zfs_prop_userquota(propname)) {
3923                         const char *perm = NULL;
3924                         const char *uq_prefix =
3925                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3926                         const char *gq_prefix =
3927                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3928                         const char *uiq_prefix =
3929                             zfs_userquota_prop_prefixes[ZFS_PROP_USEROBJQUOTA];
3930                         const char *giq_prefix =
3931                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPOBJQUOTA];
3932                         const char *pq_prefix =
3933                             zfs_userquota_prop_prefixes[ZFS_PROP_PROJECTQUOTA];
3934                         const char *piq_prefix = zfs_userquota_prop_prefixes[\
3935                             ZFS_PROP_PROJECTOBJQUOTA];
3936
3937                         if (strncmp(propname, uq_prefix,
3938                             strlen(uq_prefix)) == 0) {
3939                                 perm = ZFS_DELEG_PERM_USERQUOTA;
3940                         } else if (strncmp(propname, uiq_prefix,
3941                             strlen(uiq_prefix)) == 0) {
3942                                 perm = ZFS_DELEG_PERM_USEROBJQUOTA;
3943                         } else if (strncmp(propname, gq_prefix,
3944                             strlen(gq_prefix)) == 0) {
3945                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
3946                         } else if (strncmp(propname, giq_prefix,
3947                             strlen(giq_prefix)) == 0) {
3948                                 perm = ZFS_DELEG_PERM_GROUPOBJQUOTA;
3949                         } else if (strncmp(propname, pq_prefix,
3950                             strlen(pq_prefix)) == 0) {
3951                                 perm = ZFS_DELEG_PERM_PROJECTQUOTA;
3952                         } else if (strncmp(propname, piq_prefix,
3953                             strlen(piq_prefix)) == 0) {
3954                                 perm = ZFS_DELEG_PERM_PROJECTOBJQUOTA;
3955                         } else {
3956                                 /* {USER|GROUP|PROJECT}USED are read-only */
3957                                 return (SET_ERROR(EINVAL));
3958                         }
3959
3960                         if ((err = zfs_secpolicy_write_perms(dsname, perm, cr)))
3961                                 return (err);
3962                         return (0);
3963                 }
3964
3965                 return (SET_ERROR(EINVAL));
3966         }
3967
3968         if (issnap)
3969                 return (SET_ERROR(EINVAL));
3970
3971         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3972                 /*
3973                  * dsl_prop_get_all_impl() returns properties in this
3974                  * format.
3975                  */
3976                 nvlist_t *attrs;
3977                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3978                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3979                     &pair) == 0);
3980         }
3981
3982         /*
3983          * Check that this value is valid for this pool version
3984          */
3985         switch (prop) {
3986         case ZFS_PROP_COMPRESSION:
3987                 /*
3988                  * If the user specified gzip compression, make sure
3989                  * the SPA supports it. We ignore any errors here since
3990                  * we'll catch them later.
3991                  */
3992                 if (nvpair_value_uint64(pair, &intval) == 0) {
3993                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
3994                             intval <= ZIO_COMPRESS_GZIP_9 &&
3995                             zfs_earlier_version(dsname,
3996                             SPA_VERSION_GZIP_COMPRESSION)) {
3997                                 return (SET_ERROR(ENOTSUP));
3998                         }
3999
4000                         if (intval == ZIO_COMPRESS_ZLE &&
4001                             zfs_earlier_version(dsname,
4002                             SPA_VERSION_ZLE_COMPRESSION))
4003                                 return (SET_ERROR(ENOTSUP));
4004
4005                         if (intval == ZIO_COMPRESS_LZ4) {
4006                                 spa_t *spa;
4007
4008                                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4009                                         return (err);
4010
4011                                 if (!spa_feature_is_enabled(spa,
4012                                     SPA_FEATURE_LZ4_COMPRESS)) {
4013                                         spa_close(spa, FTAG);
4014                                         return (SET_ERROR(ENOTSUP));
4015                                 }
4016                                 spa_close(spa, FTAG);
4017                         }
4018
4019                         /*
4020                          * If this is a bootable dataset then
4021                          * verify that the compression algorithm
4022                          * is supported for booting. We must return
4023                          * something other than ENOTSUP since it
4024                          * implies a downrev pool version.
4025                          */
4026                         if (zfs_is_bootfs(dsname) &&
4027                             !BOOTFS_COMPRESS_VALID(intval)) {
4028                                 return (SET_ERROR(ERANGE));
4029                         }
4030                 }
4031                 break;
4032
4033         case ZFS_PROP_COPIES:
4034                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
4035                         return (SET_ERROR(ENOTSUP));
4036                 break;
4037
4038         case ZFS_PROP_VOLBLOCKSIZE:
4039         case ZFS_PROP_RECORDSIZE:
4040                 /* Record sizes above 128k need the feature to be enabled */
4041                 if (nvpair_value_uint64(pair, &intval) == 0 &&
4042                     intval > SPA_OLD_MAXBLOCKSIZE) {
4043                         spa_t *spa;
4044
4045                         /*
4046                          * We don't allow setting the property above 1MB,
4047                          * unless the tunable has been changed.
4048                          */
4049                         if (intval > zfs_max_recordsize ||
4050                             intval > SPA_MAXBLOCKSIZE)
4051                                 return (SET_ERROR(ERANGE));
4052
4053                         if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4054                                 return (err);
4055
4056                         if (!spa_feature_is_enabled(spa,
4057                             SPA_FEATURE_LARGE_BLOCKS)) {
4058                                 spa_close(spa, FTAG);
4059                                 return (SET_ERROR(ENOTSUP));
4060                         }
4061                         spa_close(spa, FTAG);
4062                 }
4063                 break;
4064
4065         case ZFS_PROP_DNODESIZE:
4066                 /* Dnode sizes above 512 need the feature to be enabled */
4067                 if (nvpair_value_uint64(pair, &intval) == 0 &&
4068                     intval != ZFS_DNSIZE_LEGACY) {
4069                         spa_t *spa;
4070
4071                         /*
4072                          * If this is a bootable dataset then
4073                          * we don't allow large (>512B) dnodes,
4074                          * because GRUB doesn't support them.
4075                          */
4076                         if (zfs_is_bootfs(dsname) &&
4077                             intval != ZFS_DNSIZE_LEGACY) {
4078                                 return (SET_ERROR(EDOM));
4079                         }
4080
4081                         if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4082                                 return (err);
4083
4084                         if (!spa_feature_is_enabled(spa,
4085                             SPA_FEATURE_LARGE_DNODE)) {
4086                                 spa_close(spa, FTAG);
4087                                 return (SET_ERROR(ENOTSUP));
4088                         }
4089                         spa_close(spa, FTAG);
4090                 }
4091                 break;
4092
4093         case ZFS_PROP_SHARESMB:
4094                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
4095                         return (SET_ERROR(ENOTSUP));
4096                 break;
4097
4098         case ZFS_PROP_ACLINHERIT:
4099                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
4100                     nvpair_value_uint64(pair, &intval) == 0) {
4101                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
4102                             zfs_earlier_version(dsname,
4103                             SPA_VERSION_PASSTHROUGH_X))
4104                                 return (SET_ERROR(ENOTSUP));
4105                 }
4106                 break;
4107         case ZFS_PROP_CHECKSUM:
4108         case ZFS_PROP_DEDUP:
4109         {
4110                 spa_feature_t feature;
4111                 spa_t *spa;
4112                 uint64_t intval;
4113                 int err;
4114
4115                 /* dedup feature version checks */
4116                 if (prop == ZFS_PROP_DEDUP &&
4117                     zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
4118                         return (SET_ERROR(ENOTSUP));
4119
4120                 if (nvpair_value_uint64(pair, &intval) != 0)
4121                         return (SET_ERROR(EINVAL));
4122
4123                 /* check prop value is enabled in features */
4124                 feature = zio_checksum_to_feature(intval & ZIO_CHECKSUM_MASK);
4125                 if (feature == SPA_FEATURE_NONE)
4126                         break;
4127
4128                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4129                         return (err);
4130                 /*
4131                  * Salted checksums are not supported on root pools.
4132                  */
4133                 if (spa_bootfs(spa) != 0 &&
4134                     intval < ZIO_CHECKSUM_FUNCTIONS &&
4135                     (zio_checksum_table[intval].ci_flags &
4136                     ZCHECKSUM_FLAG_SALTED)) {
4137                         spa_close(spa, FTAG);
4138                         return (SET_ERROR(ERANGE));
4139                 }
4140                 if (!spa_feature_is_enabled(spa, feature)) {
4141                         spa_close(spa, FTAG);
4142                         return (SET_ERROR(ENOTSUP));
4143                 }
4144                 spa_close(spa, FTAG);
4145                 break;
4146         }
4147
4148         default:
4149                 break;
4150         }
4151
4152         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
4153 }
4154
4155 /*
4156  * Removes properties from the given props list that fail permission checks
4157  * needed to clear them and to restore them in case of a receive error. For each
4158  * property, make sure we have both set and inherit permissions.
4159  *
4160  * Returns the first error encountered if any permission checks fail. If the
4161  * caller provides a non-NULL errlist, it also gives the complete list of names
4162  * of all the properties that failed a permission check along with the
4163  * corresponding error numbers. The caller is responsible for freeing the
4164  * returned errlist.
4165  *
4166  * If every property checks out successfully, zero is returned and the list
4167  * pointed at by errlist is NULL.
4168  */
4169 static int
4170 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
4171 {
4172         zfs_cmd_t *zc;
4173         nvpair_t *pair, *next_pair;
4174         nvlist_t *errors;
4175         int err, rv = 0;
4176
4177         if (props == NULL)
4178                 return (0);
4179
4180         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4181
4182         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
4183         (void) strlcpy(zc->zc_name, dataset, sizeof (zc->zc_name));
4184         pair = nvlist_next_nvpair(props, NULL);
4185         while (pair != NULL) {
4186                 next_pair = nvlist_next_nvpair(props, pair);
4187
4188                 (void) strlcpy(zc->zc_value, nvpair_name(pair),
4189                     sizeof (zc->zc_value));
4190                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
4191                     (err = zfs_secpolicy_inherit_prop(zc, NULL, CRED())) != 0) {
4192                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
4193                         VERIFY(nvlist_add_int32(errors,
4194                             zc->zc_value, err) == 0);
4195                 }
4196                 pair = next_pair;
4197         }
4198         kmem_free(zc, sizeof (zfs_cmd_t));
4199
4200         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
4201                 nvlist_free(errors);
4202                 errors = NULL;
4203         } else {
4204                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
4205         }
4206
4207         if (errlist == NULL)
4208                 nvlist_free(errors);
4209         else
4210                 *errlist = errors;
4211
4212         return (rv);
4213 }
4214
4215 static boolean_t
4216 propval_equals(nvpair_t *p1, nvpair_t *p2)
4217 {
4218         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
4219                 /* dsl_prop_get_all_impl() format */
4220                 nvlist_t *attrs;
4221                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
4222                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4223                     &p1) == 0);
4224         }
4225
4226         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
4227                 nvlist_t *attrs;
4228                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
4229                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4230                     &p2) == 0);
4231         }
4232
4233         if (nvpair_type(p1) != nvpair_type(p2))
4234                 return (B_FALSE);
4235
4236         if (nvpair_type(p1) == DATA_TYPE_STRING) {
4237                 char *valstr1, *valstr2;
4238
4239                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
4240                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
4241                 return (strcmp(valstr1, valstr2) == 0);
4242         } else {
4243                 uint64_t intval1, intval2;
4244
4245                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
4246                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
4247                 return (intval1 == intval2);
4248         }
4249 }
4250
4251 /*
4252  * Remove properties from props if they are not going to change (as determined
4253  * by comparison with origprops). Remove them from origprops as well, since we
4254  * do not need to clear or restore properties that won't change.
4255  */
4256 static void
4257 props_reduce(nvlist_t *props, nvlist_t *origprops)
4258 {
4259         nvpair_t *pair, *next_pair;
4260
4261         if (origprops == NULL)
4262                 return; /* all props need to be received */
4263
4264         pair = nvlist_next_nvpair(props, NULL);
4265         while (pair != NULL) {
4266                 const char *propname = nvpair_name(pair);
4267                 nvpair_t *match;
4268
4269                 next_pair = nvlist_next_nvpair(props, pair);
4270
4271                 if ((nvlist_lookup_nvpair(origprops, propname,
4272                     &match) != 0) || !propval_equals(pair, match))
4273                         goto next; /* need to set received value */
4274
4275                 /* don't clear the existing received value */
4276                 (void) nvlist_remove_nvpair(origprops, match);
4277                 /* don't bother receiving the property */
4278                 (void) nvlist_remove_nvpair(props, pair);
4279 next:
4280                 pair = next_pair;
4281         }
4282 }
4283
4284 /*
4285  * Extract properties that cannot be set PRIOR to the receipt of a dataset.
4286  * For example, refquota cannot be set until after the receipt of a dataset,
4287  * because in replication streams, an older/earlier snapshot may exceed the
4288  * refquota.  We want to receive the older/earlier snapshot, but setting
4289  * refquota pre-receipt will set the dsl's ACTUAL quota, which will prevent
4290  * the older/earlier snapshot from being received (with EDQUOT).
4291  *
4292  * The ZFS test "zfs_receive_011_pos" demonstrates such a scenario.
4293  *
4294  * libzfs will need to be judicious handling errors encountered by props
4295  * extracted by this function.
4296  */
4297 static nvlist_t *
4298 extract_delay_props(nvlist_t *props)
4299 {
4300         nvlist_t *delayprops;
4301         nvpair_t *nvp, *tmp;
4302         static const zfs_prop_t delayable[] = {
4303                 ZFS_PROP_REFQUOTA,
4304                 ZFS_PROP_KEYLOCATION,
4305                 0
4306         };
4307         int i;
4308
4309         VERIFY(nvlist_alloc(&delayprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4310
4311         for (nvp = nvlist_next_nvpair(props, NULL); nvp != NULL;
4312             nvp = nvlist_next_nvpair(props, nvp)) {
4313                 /*
4314                  * strcmp() is safe because zfs_prop_to_name() always returns
4315                  * a bounded string.
4316                  */
4317                 for (i = 0; delayable[i] != 0; i++) {
4318                         if (strcmp(zfs_prop_to_name(delayable[i]),
4319                             nvpair_name(nvp)) == 0) {
4320                                 break;
4321                         }
4322                 }
4323                 if (delayable[i] != 0) {
4324                         tmp = nvlist_prev_nvpair(props, nvp);
4325                         VERIFY(nvlist_add_nvpair(delayprops, nvp) == 0);
4326                         VERIFY(nvlist_remove_nvpair(props, nvp) == 0);
4327                         nvp = tmp;
4328                 }
4329         }
4330
4331         if (nvlist_empty(delayprops)) {
4332                 nvlist_free(delayprops);
4333                 delayprops = NULL;
4334         }
4335         return (delayprops);
4336 }
4337
4338 #ifdef  DEBUG
4339 static boolean_t zfs_ioc_recv_inject_err;
4340 #endif
4341
4342 /*
4343  * nvlist 'errors' is always allocated. It will contain descriptions of
4344  * encountered errors, if any. It's the callers responsibility to free.
4345  */
4346 static int
4347 zfs_ioc_recv_impl(char *tofs, char *tosnap, char *origin, nvlist_t *recvprops,
4348     nvlist_t *localprops, boolean_t force, boolean_t resumable, int input_fd,
4349     dmu_replay_record_t *begin_record, int cleanup_fd, uint64_t *read_bytes,
4350     uint64_t *errflags, uint64_t *action_handle, nvlist_t **errors)
4351 {
4352         dmu_recv_cookie_t drc;
4353         int error = 0;
4354         int props_error = 0;
4355         offset_t off;
4356         nvlist_t *delayprops = NULL; /* sent properties applied post-receive */
4357         nvlist_t *origprops = NULL; /* existing properties */
4358         nvlist_t *origrecvd = NULL; /* existing received properties */
4359         boolean_t first_recvd_props = B_FALSE;
4360         file_t *input_fp;
4361
4362         *read_bytes = 0;
4363         *errflags = 0;
4364         *errors = fnvlist_alloc();
4365
4366         input_fp = getf(input_fd);
4367         if (input_fp == NULL)
4368                 return (SET_ERROR(EBADF));
4369
4370         error = dmu_recv_begin(tofs, tosnap,
4371             begin_record, force, resumable, origin, &drc);
4372         if (error != 0)
4373                 goto out;
4374
4375         /*
4376          * Set properties before we receive the stream so that they are applied
4377          * to the new data. Note that we must call dmu_recv_stream() if
4378          * dmu_recv_begin() succeeds.
4379          */
4380         if (recvprops != NULL && !drc.drc_newfs) {
4381                 if (spa_version(dsl_dataset_get_spa(drc.drc_ds)) >=
4382                     SPA_VERSION_RECVD_PROPS &&
4383                     !dsl_prop_get_hasrecvd(tofs))
4384                         first_recvd_props = B_TRUE;
4385
4386                 /*
4387                  * If new received properties are supplied, they are to
4388                  * completely replace the existing received properties, so stash
4389                  * away the existing ones.
4390                  */
4391                 if (dsl_prop_get_received(tofs, &origrecvd) == 0) {
4392                         nvlist_t *errlist = NULL;
4393                         /*
4394                          * Don't bother writing a property if its value won't
4395                          * change (and avoid the unnecessary security checks).
4396                          *
4397                          * The first receive after SPA_VERSION_RECVD_PROPS is a
4398                          * special case where we blow away all local properties
4399                          * regardless.
4400                          */
4401                         if (!first_recvd_props)
4402                                 props_reduce(recvprops, origrecvd);
4403                         if (zfs_check_clearable(tofs, origrecvd, &errlist) != 0)
4404                                 (void) nvlist_merge(*errors, errlist, 0);
4405                         nvlist_free(errlist);
4406
4407                         if (clear_received_props(tofs, origrecvd,
4408                             first_recvd_props ? NULL : recvprops) != 0)
4409                                 *errflags |= ZPROP_ERR_NOCLEAR;
4410                 } else {
4411                         *errflags |= ZPROP_ERR_NOCLEAR;
4412                 }
4413         }
4414
4415         /*
4416          * Stash away existing properties so we can restore them on error unless
4417          * we're doing the first receive after SPA_VERSION_RECVD_PROPS, in which
4418          * case "origrecvd" will take care of that.
4419          */
4420         if (localprops != NULL && !drc.drc_newfs && !first_recvd_props) {
4421                 objset_t *os;
4422                 if (dmu_objset_hold(tofs, FTAG, &os) == 0) {
4423                         if (dsl_prop_get_all(os, &origprops) != 0) {
4424                                 *errflags |= ZPROP_ERR_NOCLEAR;
4425                         }
4426                         dmu_objset_rele(os, FTAG);
4427                 } else {
4428                         *errflags |= ZPROP_ERR_NOCLEAR;
4429                 }
4430         }
4431
4432         if (recvprops != NULL) {
4433                 props_error = dsl_prop_set_hasrecvd(tofs);
4434
4435                 if (props_error == 0) {
4436                         delayprops = extract_delay_props(recvprops);
4437                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4438                             recvprops, *errors);
4439                 }
4440         }
4441
4442         if (localprops != NULL) {
4443                 nvlist_t *oprops = fnvlist_alloc();
4444                 nvlist_t *xprops = fnvlist_alloc();
4445                 nvpair_t *nvp = NULL;
4446
4447                 while ((nvp = nvlist_next_nvpair(localprops, nvp)) != NULL) {
4448                         if (nvpair_type(nvp) == DATA_TYPE_BOOLEAN) {
4449                                 /* -x property */
4450                                 const char *name = nvpair_name(nvp);
4451                                 zfs_prop_t prop = zfs_name_to_prop(name);
4452                                 if (prop != ZPROP_INVAL) {
4453                                         if (!zfs_prop_inheritable(prop))
4454                                                 continue;
4455                                 } else if (!zfs_prop_user(name))
4456                                         continue;
4457                                 fnvlist_add_boolean(xprops, name);
4458                         } else {
4459                                 /* -o property=value */
4460                                 fnvlist_add_nvpair(oprops, nvp);
4461                         }
4462                 }
4463                 (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_LOCAL,
4464                     oprops, *errors);
4465                 (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_INHERITED,
4466                     xprops, *errors);
4467
4468                 nvlist_free(oprops);
4469                 nvlist_free(xprops);
4470         }
4471
4472         off = input_fp->f_offset;
4473         error = dmu_recv_stream(&drc, input_fp->f_vnode, &off, cleanup_fd,
4474             action_handle);
4475
4476         if (error == 0) {
4477                 zfsvfs_t *zfsvfs = NULL;
4478                 zvol_state_t *zv = NULL;
4479
4480                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
4481                         /* online recv */
4482                         dsl_dataset_t *ds;
4483                         int end_err;
4484
4485                         ds = dmu_objset_ds(zfsvfs->z_os);
4486                         error = zfs_suspend_fs(zfsvfs);
4487                         /*
4488                          * If the suspend fails, then the recv_end will
4489                          * likely also fail, and clean up after itself.
4490                          */
4491                         end_err = dmu_recv_end(&drc, zfsvfs);
4492                         if (error == 0)
4493                                 error = zfs_resume_fs(zfsvfs, ds);
4494                         error = error ? error : end_err;
4495                         deactivate_super(zfsvfs->z_sb);
4496                 } else if ((zv = zvol_suspend(tofs)) != NULL) {
4497                         error = dmu_recv_end(&drc, zvol_tag(zv));
4498                         zvol_resume(zv);
4499                 } else {
4500                         error = dmu_recv_end(&drc, NULL);
4501                 }
4502
4503                 /* Set delayed properties now, after we're done receiving. */
4504                 if (delayprops != NULL && error == 0) {
4505                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4506                             delayprops, *errors);
4507                 }
4508         }
4509
4510         if (delayprops != NULL) {
4511                 /*
4512                  * Merge delayed props back in with initial props, in case
4513                  * we're DEBUG and zfs_ioc_recv_inject_err is set (which means
4514                  * we have to make sure clear_received_props() includes
4515                  * the delayed properties).
4516                  *
4517                  * Since zfs_ioc_recv_inject_err is only in DEBUG kernels,
4518                  * using ASSERT() will be just like a VERIFY.
4519                  */
4520                 ASSERT(nvlist_merge(recvprops, delayprops, 0) == 0);
4521                 nvlist_free(delayprops);
4522         }
4523
4524
4525         *read_bytes = off - input_fp->f_offset;
4526         if (VOP_SEEK(input_fp->f_vnode, input_fp->f_offset, &off, NULL) == 0)
4527                 input_fp->f_offset = off;
4528
4529 #ifdef  DEBUG
4530         if (zfs_ioc_recv_inject_err) {
4531                 zfs_ioc_recv_inject_err = B_FALSE;
4532                 error = 1;
4533         }
4534 #endif
4535
4536         /*
4537          * On error, restore the original props.
4538          */
4539         if (error != 0 && recvprops != NULL && !drc.drc_newfs) {
4540                 if (clear_received_props(tofs, recvprops, NULL) != 0) {
4541                         /*
4542                          * We failed to clear the received properties.
4543                          * Since we may have left a $recvd value on the
4544                          * system, we can't clear the $hasrecvd flag.
4545                          */
4546                         *errflags |= ZPROP_ERR_NORESTORE;
4547                 } else if (first_recvd_props) {
4548                         dsl_prop_unset_hasrecvd(tofs);
4549                 }
4550
4551                 if (origrecvd == NULL && !drc.drc_newfs) {
4552                         /* We failed to stash the original properties. */
4553                         *errflags |= ZPROP_ERR_NORESTORE;
4554                 }
4555
4556                 /*
4557                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
4558                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
4559                  * explicitly if we're restoring local properties cleared in the
4560                  * first new-style receive.
4561                  */
4562                 if (origrecvd != NULL &&
4563                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
4564                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
4565                     origrecvd, NULL) != 0) {
4566                         /*
4567                          * We stashed the original properties but failed to
4568                          * restore them.
4569                          */
4570                         *errflags |= ZPROP_ERR_NORESTORE;
4571                 }
4572         }
4573         if (error != 0 && localprops != NULL && !drc.drc_newfs &&
4574             !first_recvd_props) {
4575                 nvlist_t *setprops;
4576                 nvlist_t *inheritprops;
4577                 nvpair_t *nvp;
4578
4579                 if (origprops == NULL) {
4580                         /* We failed to stash the original properties. */
4581                         *errflags |= ZPROP_ERR_NORESTORE;
4582                         goto out;
4583                 }
4584
4585                 /* Restore original props */
4586                 setprops = fnvlist_alloc();
4587                 inheritprops = fnvlist_alloc();
4588                 nvp = NULL;
4589                 while ((nvp = nvlist_next_nvpair(localprops, nvp)) != NULL) {
4590                         const char *name = nvpair_name(nvp);
4591                         const char *source;
4592                         nvlist_t *attrs;
4593
4594                         if (!nvlist_exists(origprops, name)) {
4595                                 /*
4596                                  * Property was not present or was explicitly
4597                                  * inherited before the receive, restore this.
4598                                  */
4599                                 fnvlist_add_boolean(inheritprops, name);
4600                                 continue;
4601                         }
4602                         attrs = fnvlist_lookup_nvlist(origprops, name);
4603                         source = fnvlist_lookup_string(attrs, ZPROP_SOURCE);
4604
4605                         /* Skip received properties */
4606                         if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0)
4607                                 continue;
4608
4609                         if (strcmp(source, tofs) == 0) {
4610                                 /* Property was locally set */
4611                                 fnvlist_add_nvlist(setprops, name, attrs);
4612                         } else {
4613                                 /* Property was implicitly inherited */
4614                                 fnvlist_add_boolean(inheritprops, name);
4615                         }
4616                 }
4617
4618                 if (zfs_set_prop_nvlist(tofs, ZPROP_SRC_LOCAL, setprops,
4619                     NULL) != 0)
4620                         *errflags |= ZPROP_ERR_NORESTORE;
4621                 if (zfs_set_prop_nvlist(tofs, ZPROP_SRC_INHERITED, inheritprops,
4622                     NULL) != 0)
4623                         *errflags |= ZPROP_ERR_NORESTORE;
4624
4625                 nvlist_free(setprops);
4626                 nvlist_free(inheritprops);
4627         }
4628 out:
4629         releasef(input_fd);
4630         nvlist_free(origrecvd);
4631         nvlist_free(origprops);
4632
4633         if (error == 0)
4634                 error = props_error;
4635
4636         return (error);
4637 }
4638
4639 /*
4640  * inputs:
4641  * zc_name              name of containing filesystem (unused)
4642  * zc_nvlist_src{_size} nvlist of properties to apply
4643  * zc_nvlist_conf{_size}        nvlist of properties to exclude
4644  *                      (DATA_TYPE_BOOLEAN) and override (everything else)
4645  * zc_value             name of snapshot to create
4646  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
4647  * zc_cookie            file descriptor to recv from
4648  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
4649  * zc_guid              force flag
4650  * zc_cleanup_fd        cleanup-on-exit file descriptor
4651  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
4652  *
4653  * outputs:
4654  * zc_cookie            number of bytes read
4655  * zc_obj               zprop_errflags_t
4656  * zc_action_handle     handle for this guid/ds mapping
4657  * zc_nvlist_dst{_size} error for each unapplied received property
4658  */
4659 static int
4660 zfs_ioc_recv(zfs_cmd_t *zc)
4661 {
4662         dmu_replay_record_t begin_record;
4663         nvlist_t *errors = NULL;
4664         nvlist_t *recvdprops = NULL;
4665         nvlist_t *localprops = NULL;
4666         char *origin = NULL;
4667         char *tosnap;
4668         char tofs[ZFS_MAX_DATASET_NAME_LEN];
4669         int error = 0;
4670
4671         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
4672             strchr(zc->zc_value, '@') == NULL ||
4673             strchr(zc->zc_value, '%'))
4674                 return (SET_ERROR(EINVAL));
4675
4676         (void) strlcpy(tofs, zc->zc_value, sizeof (tofs));
4677         tosnap = strchr(tofs, '@');
4678         *tosnap++ = '\0';
4679
4680         if (zc->zc_nvlist_src != 0 &&
4681             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
4682             zc->zc_iflags, &recvdprops)) != 0)
4683                 return (error);
4684
4685         if (zc->zc_nvlist_conf != 0 &&
4686             (error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
4687             zc->zc_iflags, &localprops)) != 0)
4688                 return (error);
4689
4690         if (zc->zc_string[0])
4691                 origin = zc->zc_string;
4692
4693         begin_record.drr_type = DRR_BEGIN;
4694         begin_record.drr_payloadlen = 0;
4695         begin_record.drr_u.drr_begin = zc->zc_begin_record;
4696
4697         error = zfs_ioc_recv_impl(tofs, tosnap, origin, recvdprops, localprops,
4698             zc->zc_guid, B_FALSE, zc->zc_cookie, &begin_record,
4699             zc->zc_cleanup_fd, &zc->zc_cookie, &zc->zc_obj,
4700             &zc->zc_action_handle, &errors);
4701         nvlist_free(recvdprops);
4702         nvlist_free(localprops);
4703
4704         /*
4705          * Now that all props, initial and delayed, are set, report the prop
4706          * errors to the caller.
4707          */
4708         if (zc->zc_nvlist_dst_size != 0 && errors != NULL &&
4709             (nvlist_smush(errors, zc->zc_nvlist_dst_size) != 0 ||
4710             put_nvlist(zc, errors) != 0)) {
4711                 /*
4712                  * Caller made zc->zc_nvlist_dst less than the minimum expected
4713                  * size or supplied an invalid address.
4714                  */
4715                 error = SET_ERROR(EINVAL);
4716         }
4717
4718         nvlist_free(errors);
4719
4720         return (error);
4721 }
4722
4723 /*
4724  * innvl: {
4725  *     "snapname" -> full name of the snapshot to create
4726  *     (optional) "props" -> received properties to set (nvlist)
4727  *     (optional) "localprops" -> override and exclude properties (nvlist)
4728  *     (optional) "origin" -> name of clone origin (DRR_FLAG_CLONE)
4729  *     "begin_record" -> non-byteswapped dmu_replay_record_t
4730  *     "input_fd" -> file descriptor to read stream from (int32)
4731  *     (optional) "force" -> force flag (value ignored)
4732  *     (optional) "resumable" -> resumable flag (value ignored)
4733  *     (optional) "cleanup_fd" -> cleanup-on-exit file descriptor
4734  *     (optional) "action_handle" -> handle for this guid/ds mapping
4735  * }
4736  *
4737  * outnvl: {
4738  *     "read_bytes" -> number of bytes read
4739  *     "error_flags" -> zprop_errflags_t
4740  *     "action_handle" -> handle for this guid/ds mapping
4741  *     "errors" -> error for each unapplied received property (nvlist)
4742  * }
4743  */
4744 static int
4745 zfs_ioc_recv_new(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
4746 {
4747         dmu_replay_record_t *begin_record;
4748         uint_t begin_record_size;
4749         nvlist_t *errors = NULL;
4750         nvlist_t *recvprops = NULL;
4751         nvlist_t *localprops = NULL;
4752         char *snapname = NULL;
4753         char *origin = NULL;
4754         char *tosnap;
4755         char tofs[ZFS_MAX_DATASET_NAME_LEN];
4756         boolean_t force;
4757         boolean_t resumable;
4758         uint64_t action_handle = 0;
4759         uint64_t read_bytes = 0;
4760         uint64_t errflags = 0;
4761         int input_fd = -1;
4762         int cleanup_fd = -1;
4763         int error;
4764
4765         error = nvlist_lookup_string(innvl, "snapname", &snapname);
4766         if (error != 0)
4767                 return (SET_ERROR(EINVAL));
4768
4769         if (dataset_namecheck(snapname, NULL, NULL) != 0 ||
4770             strchr(snapname, '@') == NULL ||
4771             strchr(snapname, '%'))
4772                 return (SET_ERROR(EINVAL));
4773
4774         (void) strcpy(tofs, snapname);
4775         tosnap = strchr(tofs, '@');
4776         *tosnap++ = '\0';
4777
4778         error = nvlist_lookup_string(innvl, "origin", &origin);
4779         if (error && error != ENOENT)
4780                 return (error);
4781
4782         error = nvlist_lookup_byte_array(innvl, "begin_record",
4783             (uchar_t **)&begin_record, &begin_record_size);
4784         if (error != 0 || begin_record_size != sizeof (*begin_record))
4785                 return (SET_ERROR(EINVAL));
4786
4787         error = nvlist_lookup_int32(innvl, "input_fd", &input_fd);
4788         if (error != 0)
4789                 return (SET_ERROR(EINVAL));
4790
4791         force = nvlist_exists(innvl, "force");
4792         resumable = nvlist_exists(innvl, "resumable");
4793
4794         error = nvlist_lookup_int32(innvl, "cleanup_fd", &cleanup_fd);
4795         if (error && error != ENOENT)
4796                 return (error);
4797
4798         error = nvlist_lookup_uint64(innvl, "action_handle", &action_handle);
4799         if (error && error != ENOENT)
4800                 return (error);
4801
4802         /* we still use "props" here for backwards compatibility */
4803         error = nvlist_lookup_nvlist(innvl, "props", &recvprops);
4804         if (error && error != ENOENT)
4805                 return (error);
4806
4807         error = nvlist_lookup_nvlist(innvl, "localprops", &localprops);
4808         if (error && error != ENOENT)
4809                 return (error);
4810
4811         error = zfs_ioc_recv_impl(tofs, tosnap, origin, recvprops, localprops,
4812             force, resumable, input_fd, begin_record, cleanup_fd, &read_bytes,
4813             &errflags, &action_handle, &errors);
4814
4815         fnvlist_add_uint64(outnvl, "read_bytes", read_bytes);
4816         fnvlist_add_uint64(outnvl, "error_flags", errflags);
4817         fnvlist_add_uint64(outnvl, "action_handle", action_handle);
4818         fnvlist_add_nvlist(outnvl, "errors", errors);
4819
4820         nvlist_free(errors);
4821         nvlist_free(recvprops);
4822         nvlist_free(localprops);
4823
4824         return (error);
4825 }
4826
4827 /*
4828  * inputs:
4829  * zc_name      name of snapshot to send
4830  * zc_cookie    file descriptor to send stream to
4831  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
4832  * zc_sendobj   objsetid of snapshot to send
4833  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
4834  * zc_guid      if set, estimate size of stream only.  zc_cookie is ignored.
4835  *              output size in zc_objset_type.
4836  * zc_flags     lzc_send_flags
4837  *
4838  * outputs:
4839  * zc_objset_type       estimated size, if zc_guid is set
4840  *
4841  * NOTE: This is no longer the preferred interface, any new functionality
4842  *        should be added to zfs_ioc_send_new() instead.
4843  */
4844 static int
4845 zfs_ioc_send(zfs_cmd_t *zc)
4846 {
4847         int error;
4848         offset_t off;
4849         boolean_t estimate = (zc->zc_guid != 0);
4850         boolean_t embedok = (zc->zc_flags & 0x1);
4851         boolean_t large_block_ok = (zc->zc_flags & 0x2);
4852         boolean_t compressok = (zc->zc_flags & 0x4);
4853         boolean_t rawok = (zc->zc_flags & 0x8);
4854
4855         if (zc->zc_obj != 0) {
4856                 dsl_pool_t *dp;
4857                 dsl_dataset_t *tosnap;
4858
4859                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4860                 if (error != 0)
4861                         return (error);
4862
4863                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4864                 if (error != 0) {
4865                         dsl_pool_rele(dp, FTAG);
4866                         return (error);
4867                 }
4868
4869                 if (dsl_dir_is_clone(tosnap->ds_dir))
4870                         zc->zc_fromobj =
4871                             dsl_dir_phys(tosnap->ds_dir)->dd_origin_obj;
4872                 dsl_dataset_rele(tosnap, FTAG);
4873                 dsl_pool_rele(dp, FTAG);
4874         }
4875
4876         if (estimate) {
4877                 dsl_pool_t *dp;
4878                 dsl_dataset_t *tosnap;
4879                 dsl_dataset_t *fromsnap = NULL;
4880
4881                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4882                 if (error != 0)
4883                         return (error);
4884
4885                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj,
4886                     FTAG, &tosnap);
4887                 if (error != 0) {
4888                         dsl_pool_rele(dp, FTAG);
4889                         return (error);
4890                 }
4891
4892                 if (zc->zc_fromobj != 0) {
4893                         error = dsl_dataset_hold_obj(dp, zc->zc_fromobj,
4894                             FTAG, &fromsnap);
4895                         if (error != 0) {
4896                                 dsl_dataset_rele(tosnap, FTAG);
4897                                 dsl_pool_rele(dp, FTAG);
4898                                 return (error);
4899                         }
4900                 }
4901
4902                 error = dmu_send_estimate(tosnap, fromsnap, compressok || rawok,
4903                     &zc->zc_objset_type);
4904
4905                 if (fromsnap != NULL)
4906                         dsl_dataset_rele(fromsnap, FTAG);
4907                 dsl_dataset_rele(tosnap, FTAG);
4908                 dsl_pool_rele(dp, FTAG);
4909         } else {
4910                 file_t *fp = getf(zc->zc_cookie);
4911                 if (fp == NULL)
4912                         return (SET_ERROR(EBADF));
4913
4914                 off = fp->f_offset;
4915                 error = dmu_send_obj(zc->zc_name, zc->zc_sendobj,
4916                     zc->zc_fromobj, embedok, large_block_ok, compressok, rawok,
4917                     zc->zc_cookie, fp->f_vnode, &off);
4918
4919                 if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
4920                         fp->f_offset = off;
4921                 releasef(zc->zc_cookie);
4922         }
4923         return (error);
4924 }
4925
4926 /*
4927  * inputs:
4928  * zc_name      name of snapshot on which to report progress
4929  * zc_cookie    file descriptor of send stream
4930  *
4931  * outputs:
4932  * zc_cookie    number of bytes written in send stream thus far
4933  */
4934 static int
4935 zfs_ioc_send_progress(zfs_cmd_t *zc)
4936 {
4937         dsl_pool_t *dp;
4938         dsl_dataset_t *ds;
4939         dmu_sendarg_t *dsp = NULL;
4940         int error;
4941
4942         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4943         if (error != 0)
4944                 return (error);
4945
4946         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4947         if (error != 0) {
4948                 dsl_pool_rele(dp, FTAG);
4949                 return (error);
4950         }
4951
4952         mutex_enter(&ds->ds_sendstream_lock);
4953
4954         /*
4955          * Iterate over all the send streams currently active on this dataset.
4956          * If there's one which matches the specified file descriptor _and_ the
4957          * stream was started by the current process, return the progress of
4958          * that stream.
4959          */
4960
4961         for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
4962             dsp = list_next(&ds->ds_sendstreams, dsp)) {
4963                 if (dsp->dsa_outfd == zc->zc_cookie &&
4964                     dsp->dsa_proc->group_leader == curproc->group_leader)
4965                         break;
4966         }
4967
4968         if (dsp != NULL)
4969                 zc->zc_cookie = *(dsp->dsa_off);
4970         else
4971                 error = SET_ERROR(ENOENT);
4972
4973         mutex_exit(&ds->ds_sendstream_lock);
4974         dsl_dataset_rele(ds, FTAG);
4975         dsl_pool_rele(dp, FTAG);
4976         return (error);
4977 }
4978
4979 static int
4980 zfs_ioc_inject_fault(zfs_cmd_t *zc)
4981 {
4982         int id, error;
4983
4984         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
4985             &zc->zc_inject_record);
4986
4987         if (error == 0)
4988                 zc->zc_guid = (uint64_t)id;
4989
4990         return (error);
4991 }
4992
4993 static int
4994 zfs_ioc_clear_fault(zfs_cmd_t *zc)
4995 {
4996         return (zio_clear_fault((int)zc->zc_guid));
4997 }
4998
4999 static int
5000 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
5001 {
5002         int id = (int)zc->zc_guid;
5003         int error;
5004
5005         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
5006             &zc->zc_inject_record);
5007
5008         zc->zc_guid = id;
5009
5010         return (error);
5011 }
5012
5013 static int
5014 zfs_ioc_error_log(zfs_cmd_t *zc)
5015 {
5016         spa_t *spa;
5017         int error;
5018         size_t count = (size_t)zc->zc_nvlist_dst_size;
5019
5020         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
5021                 return (error);
5022
5023         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
5024             &count);
5025         if (error == 0)
5026                 zc->zc_nvlist_dst_size = count;
5027         else
5028                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
5029
5030         spa_close(spa, FTAG);
5031
5032         return (error);
5033 }
5034
5035 static int
5036 zfs_ioc_clear(zfs_cmd_t *zc)
5037 {
5038         spa_t *spa;
5039         vdev_t *vd;
5040         int error;
5041
5042         /*
5043          * On zpool clear we also fix up missing slogs
5044          */
5045         mutex_enter(&spa_namespace_lock);
5046         spa = spa_lookup(zc->zc_name);
5047         if (spa == NULL) {
5048                 mutex_exit(&spa_namespace_lock);
5049                 return (SET_ERROR(EIO));
5050         }
5051         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
5052                 /* we need to let spa_open/spa_load clear the chains */
5053                 spa_set_log_state(spa, SPA_LOG_CLEAR);
5054         }
5055         spa->spa_last_open_failed = 0;
5056         mutex_exit(&spa_namespace_lock);
5057
5058         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
5059                 error = spa_open(zc->zc_name, &spa, FTAG);
5060         } else {
5061                 nvlist_t *policy;
5062                 nvlist_t *config = NULL;
5063
5064                 if (zc->zc_nvlist_src == 0)
5065                         return (SET_ERROR(EINVAL));
5066
5067                 if ((error = get_nvlist(zc->zc_nvlist_src,
5068                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
5069                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
5070                             policy, &config);
5071                         if (config != NULL) {
5072                                 int err;
5073
5074                                 if ((err = put_nvlist(zc, config)) != 0)
5075                                         error = err;
5076                                 nvlist_free(config);
5077                         }
5078                         nvlist_free(policy);
5079                 }
5080         }
5081
5082         if (error != 0)
5083                 return (error);
5084
5085         spa_vdev_state_enter(spa, SCL_NONE);
5086
5087         if (zc->zc_guid == 0) {
5088                 vd = NULL;
5089         } else {
5090                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
5091                 if (vd == NULL) {
5092                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
5093                         spa_close(spa, FTAG);
5094                         return (SET_ERROR(ENODEV));
5095                 }
5096         }
5097
5098         vdev_clear(spa, vd);
5099
5100         (void) spa_vdev_state_exit(spa, spa_suspended(spa) ?
5101             NULL : spa->spa_root_vdev, 0);
5102
5103         /*
5104          * Resume any suspended I/Os.
5105          */
5106         if (zio_resume(spa) != 0)
5107                 error = SET_ERROR(EIO);
5108
5109         spa_close(spa, FTAG);
5110
5111         return (error);
5112 }
5113
5114 /*
5115  * Reopen all the vdevs associated with the pool.
5116  *
5117  * innvl: {
5118  *  "scrub_restart" -> when true and scrub is running, allow to restart
5119  *              scrub as the side effect of the reopen (boolean).
5120  * }
5121  *
5122  * outnvl is unused
5123  */
5124 /* ARGSUSED */
5125 static int
5126 zfs_ioc_pool_reopen(const char *pool, nvlist_t *innvl, nvlist_t *outnvl)
5127 {
5128         spa_t *spa;
5129         int error;
5130         boolean_t scrub_restart = B_TRUE;
5131
5132         if (innvl) {
5133                 if (nvlist_lookup_boolean_value(innvl, "scrub_restart",
5134                     &scrub_restart) != 0) {
5135                         return (SET_ERROR(EINVAL));
5136                 }
5137         }
5138
5139         error = spa_open(pool, &spa, FTAG);
5140         if (error != 0)
5141                 return (error);
5142
5143         spa_vdev_state_enter(spa, SCL_NONE);
5144
5145         /*
5146          * If the scrub_restart flag is B_FALSE and a scrub is already
5147          * in progress then set spa_scrub_reopen flag to B_TRUE so that
5148          * we don't restart the scrub as a side effect of the reopen.
5149          * Otherwise, let vdev_open() decided if a resilver is required.
5150          */
5151
5152         spa->spa_scrub_reopen = (!scrub_restart &&
5153             dsl_scan_scrubbing(spa->spa_dsl_pool));
5154         vdev_reopen(spa->spa_root_vdev);
5155         spa->spa_scrub_reopen = B_FALSE;
5156
5157         (void) spa_vdev_state_exit(spa, NULL, 0);
5158         spa_close(spa, FTAG);
5159         return (0);
5160 }
5161
5162 /*
5163  * inputs:
5164  * zc_name      name of filesystem
5165  *
5166  * outputs:
5167  * zc_string    name of conflicting snapshot, if there is one
5168  */
5169 static int
5170 zfs_ioc_promote(zfs_cmd_t *zc)
5171 {
5172         dsl_pool_t *dp;
5173         dsl_dataset_t *ds, *ods;
5174         char origin[ZFS_MAX_DATASET_NAME_LEN];
5175         char *cp;
5176         int error;
5177
5178         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
5179         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
5180             strchr(zc->zc_name, '%'))
5181                 return (SET_ERROR(EINVAL));
5182
5183         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5184         if (error != 0)
5185                 return (error);
5186
5187         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
5188         if (error != 0) {
5189                 dsl_pool_rele(dp, FTAG);
5190                 return (error);
5191         }
5192
5193         if (!dsl_dir_is_clone(ds->ds_dir)) {
5194                 dsl_dataset_rele(ds, FTAG);
5195                 dsl_pool_rele(dp, FTAG);
5196                 return (SET_ERROR(EINVAL));
5197         }
5198
5199         error = dsl_dataset_hold_obj(dp,
5200             dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &ods);
5201         if (error != 0) {
5202                 dsl_dataset_rele(ds, FTAG);
5203                 dsl_pool_rele(dp, FTAG);
5204                 return (error);
5205         }
5206
5207         dsl_dataset_name(ods, origin);
5208         dsl_dataset_rele(ods, FTAG);
5209         dsl_dataset_rele(ds, FTAG);
5210         dsl_pool_rele(dp, FTAG);
5211
5212         /*
5213          * We don't need to unmount *all* the origin fs's snapshots, but
5214          * it's easier.
5215          */
5216         cp = strchr(origin, '@');
5217         if (cp)
5218                 *cp = '\0';
5219         (void) dmu_objset_find(origin,
5220             zfs_unmount_snap_cb, NULL, DS_FIND_SNAPSHOTS);
5221         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
5222 }
5223
5224 /*
5225  * Retrieve a single {user|group|project}{used|quota}@... property.
5226  *
5227  * inputs:
5228  * zc_name      name of filesystem
5229  * zc_objset_type zfs_userquota_prop_t
5230  * zc_value     domain name (eg. "S-1-234-567-89")
5231  * zc_guid      RID/UID/GID
5232  *
5233  * outputs:
5234  * zc_cookie    property value
5235  */
5236 static int
5237 zfs_ioc_userspace_one(zfs_cmd_t *zc)
5238 {
5239         zfsvfs_t *zfsvfs;
5240         int error;
5241
5242         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
5243                 return (SET_ERROR(EINVAL));
5244
5245         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
5246         if (error != 0)
5247                 return (error);
5248
5249         error = zfs_userspace_one(zfsvfs,
5250             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
5251         zfsvfs_rele(zfsvfs, FTAG);
5252
5253         return (error);
5254 }
5255
5256 /*
5257  * inputs:
5258  * zc_name              name of filesystem
5259  * zc_cookie            zap cursor
5260  * zc_objset_type       zfs_userquota_prop_t
5261  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
5262  *
5263  * outputs:
5264  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
5265  * zc_cookie    zap cursor
5266  */
5267 static int
5268 zfs_ioc_userspace_many(zfs_cmd_t *zc)
5269 {
5270         zfsvfs_t *zfsvfs;
5271         int bufsize = zc->zc_nvlist_dst_size;
5272
5273         if (bufsize <= 0)
5274                 return (SET_ERROR(ENOMEM));
5275
5276         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
5277         if (error != 0)
5278                 return (error);
5279
5280         void *buf = vmem_alloc(bufsize, KM_SLEEP);
5281
5282         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
5283             buf, &zc->zc_nvlist_dst_size);
5284
5285         if (error == 0) {
5286                 error = xcopyout(buf,
5287                     (void *)(uintptr_t)zc->zc_nvlist_dst,
5288                     zc->zc_nvlist_dst_size);
5289         }
5290         vmem_free(buf, bufsize);
5291         zfsvfs_rele(zfsvfs, FTAG);
5292
5293         return (error);
5294 }
5295
5296 /*
5297  * inputs:
5298  * zc_name              name of filesystem
5299  *
5300  * outputs:
5301  * none
5302  */
5303 static int
5304 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
5305 {
5306         objset_t *os;
5307         int error = 0;
5308         zfsvfs_t *zfsvfs;
5309
5310         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
5311                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
5312                         /*
5313                          * If userused is not enabled, it may be because the
5314                          * objset needs to be closed & reopened (to grow the
5315                          * objset_phys_t).  Suspend/resume the fs will do that.
5316                          */
5317                         dsl_dataset_t *ds, *newds;
5318
5319                         ds = dmu_objset_ds(zfsvfs->z_os);
5320                         error = zfs_suspend_fs(zfsvfs);
5321                         if (error == 0) {
5322                                 dmu_objset_refresh_ownership(ds, &newds,
5323                                     B_TRUE, zfsvfs);
5324                                 error = zfs_resume_fs(zfsvfs, newds);
5325                         }
5326                 }
5327                 if (error == 0)
5328                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
5329                 deactivate_super(zfsvfs->z_sb);
5330         } else {
5331                 /* XXX kind of reading contents without owning */
5332                 error = dmu_objset_hold_flags(zc->zc_name, B_TRUE, FTAG, &os);
5333                 if (error != 0)
5334                         return (error);
5335
5336                 error = dmu_objset_userspace_upgrade(os);
5337                 dmu_objset_rele_flags(os, B_TRUE, FTAG);
5338         }
5339
5340         return (error);
5341 }
5342
5343 /*
5344  * inputs:
5345  * zc_name              name of filesystem
5346  *
5347  * outputs:
5348  * none
5349  */
5350 static int
5351 zfs_ioc_id_quota_upgrade(zfs_cmd_t *zc)
5352 {
5353         objset_t *os;
5354         int error;
5355
5356         error = dmu_objset_hold_flags(zc->zc_name, B_TRUE, FTAG, &os);
5357         if (error != 0)
5358                 return (error);
5359
5360         if (dmu_objset_userobjspace_upgradable(os) ||
5361             dmu_objset_projectquota_upgradable(os)) {
5362                 mutex_enter(&os->os_upgrade_lock);
5363                 if (os->os_upgrade_id == 0) {
5364                         /* clear potential error code and retry */
5365                         os->os_upgrade_status = 0;
5366                         mutex_exit(&os->os_upgrade_lock);
5367
5368                         dmu_objset_id_quota_upgrade(os);
5369                 } else {
5370                         mutex_exit(&os->os_upgrade_lock);
5371                 }
5372
5373                 dsl_pool_rele(dmu_objset_pool(os), FTAG);
5374
5375                 taskq_wait_id(os->os_spa->spa_upgrade_taskq, os->os_upgrade_id);
5376                 error = os->os_upgrade_status;
5377         } else {
5378                 dsl_pool_rele(dmu_objset_pool(os), FTAG);
5379         }
5380
5381         dsl_dataset_rele_flags(dmu_objset_ds(os), DS_HOLD_FLAG_DECRYPT, FTAG);
5382
5383         return (error);
5384 }
5385
5386 static int
5387 zfs_ioc_share(zfs_cmd_t *zc)
5388 {
5389         return (SET_ERROR(ENOSYS));
5390 }
5391
5392 ace_t full_access[] = {
5393         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
5394 };
5395
5396 /*
5397  * inputs:
5398  * zc_name              name of containing filesystem
5399  * zc_obj               object # beyond which we want next in-use object #
5400  *
5401  * outputs:
5402  * zc_obj               next in-use object #
5403  */
5404 static int
5405 zfs_ioc_next_obj(zfs_cmd_t *zc)
5406 {
5407         objset_t *os = NULL;
5408         int error;
5409
5410         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5411         if (error != 0)
5412                 return (error);
5413
5414         error = dmu_object_next(os, &zc->zc_obj, B_FALSE, 0);
5415
5416         dmu_objset_rele(os, FTAG);
5417         return (error);
5418 }
5419
5420 /*
5421  * inputs:
5422  * zc_name              name of filesystem
5423  * zc_value             prefix name for snapshot
5424  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
5425  *
5426  * outputs:
5427  * zc_value             short name of new snapshot
5428  */
5429 static int
5430 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
5431 {
5432         char *snap_name;
5433         char *hold_name;
5434         int error;
5435         minor_t minor;
5436
5437         error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
5438         if (error != 0)
5439                 return (error);
5440
5441         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
5442             (u_longlong_t)ddi_get_lbolt64());
5443         hold_name = kmem_asprintf("%%%s", zc->zc_value);
5444
5445         error = dsl_dataset_snapshot_tmp(zc->zc_name, snap_name, minor,
5446             hold_name);
5447         if (error == 0)
5448                 (void) strlcpy(zc->zc_value, snap_name,
5449                     sizeof (zc->zc_value));
5450         strfree(snap_name);
5451         strfree(hold_name);
5452         zfs_onexit_fd_rele(zc->zc_cleanup_fd);
5453         return (error);
5454 }
5455
5456 /*
5457  * inputs:
5458  * zc_name              name of "to" snapshot
5459  * zc_value             name of "from" snapshot
5460  * zc_cookie            file descriptor to write diff data on
5461  *
5462  * outputs:
5463  * dmu_diff_record_t's to the file descriptor
5464  */
5465 static int
5466 zfs_ioc_diff(zfs_cmd_t *zc)
5467 {
5468         file_t *fp;
5469         offset_t off;
5470         int error;
5471
5472         fp = getf(zc->zc_cookie);
5473         if (fp == NULL)
5474                 return (SET_ERROR(EBADF));
5475
5476         off = fp->f_offset;
5477
5478         error = dmu_diff(zc->zc_name, zc->zc_value, fp->f_vnode, &off);
5479
5480         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5481                 fp->f_offset = off;
5482         releasef(zc->zc_cookie);
5483
5484         return (error);
5485 }
5486
5487 /*
5488  * Remove all ACL files in shares dir
5489  */
5490 #ifdef HAVE_SMB_SHARE
5491 static int
5492 zfs_smb_acl_purge(znode_t *dzp)
5493 {
5494         zap_cursor_t    zc;
5495         zap_attribute_t zap;
5496         zfsvfs_t *zfsvfs = ZTOZSB(dzp);
5497         int error;
5498
5499         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
5500             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
5501             zap_cursor_advance(&zc)) {
5502                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
5503                     NULL, 0)) != 0)
5504                         break;
5505         }
5506         zap_cursor_fini(&zc);
5507         return (error);
5508 }
5509 #endif /* HAVE_SMB_SHARE */
5510
5511 static int
5512 zfs_ioc_smb_acl(zfs_cmd_t *zc)
5513 {
5514 #ifdef HAVE_SMB_SHARE
5515         vnode_t *vp;
5516         znode_t *dzp;
5517         vnode_t *resourcevp = NULL;
5518         znode_t *sharedir;
5519         zfsvfs_t *zfsvfs;
5520         nvlist_t *nvlist;
5521         char *src, *target;
5522         vattr_t vattr;
5523         vsecattr_t vsec;
5524         int error = 0;
5525
5526         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
5527             NO_FOLLOW, NULL, &vp)) != 0)
5528                 return (error);
5529
5530         /* Now make sure mntpnt and dataset are ZFS */
5531
5532         if (vp->v_vfsp->vfs_fstype != zfsfstype ||
5533             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
5534             zc->zc_name) != 0)) {
5535                 VN_RELE(vp);
5536                 return (SET_ERROR(EINVAL));
5537         }
5538
5539         dzp = VTOZ(vp);
5540         zfsvfs = ZTOZSB(dzp);
5541         ZFS_ENTER(zfsvfs);
5542
5543         /*
5544          * Create share dir if its missing.
5545          */
5546         mutex_enter(&zfsvfs->z_lock);
5547         if (zfsvfs->z_shares_dir == 0) {
5548                 dmu_tx_t *tx;
5549
5550                 tx = dmu_tx_create(zfsvfs->z_os);
5551                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
5552                     ZFS_SHARES_DIR);
5553                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
5554                 error = dmu_tx_assign(tx, TXG_WAIT);
5555                 if (error != 0) {
5556                         dmu_tx_abort(tx);
5557                 } else {
5558                         error = zfs_create_share_dir(zfsvfs, tx);
5559                         dmu_tx_commit(tx);
5560                 }
5561                 if (error != 0) {
5562                         mutex_exit(&zfsvfs->z_lock);
5563                         VN_RELE(vp);
5564                         ZFS_EXIT(zfsvfs);
5565                         return (error);
5566                 }
5567         }
5568         mutex_exit(&zfsvfs->z_lock);
5569
5570         ASSERT(zfsvfs->z_shares_dir);
5571         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
5572                 VN_RELE(vp);
5573                 ZFS_EXIT(zfsvfs);
5574                 return (error);
5575         }
5576
5577         switch (zc->zc_cookie) {
5578         case ZFS_SMB_ACL_ADD:
5579                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
5580                 vattr.va_mode = S_IFREG|0777;
5581                 vattr.va_uid = 0;
5582                 vattr.va_gid = 0;
5583
5584                 vsec.vsa_mask = VSA_ACE;
5585                 vsec.vsa_aclentp = &full_access;
5586                 vsec.vsa_aclentsz = sizeof (full_access);
5587                 vsec.vsa_aclcnt = 1;
5588
5589                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
5590                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
5591                 if (resourcevp)
5592                         VN_RELE(resourcevp);
5593                 break;
5594
5595         case ZFS_SMB_ACL_REMOVE:
5596                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
5597                     NULL, 0);
5598                 break;
5599
5600         case ZFS_SMB_ACL_RENAME:
5601                 if ((error = get_nvlist(zc->zc_nvlist_src,
5602                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
5603                         VN_RELE(vp);
5604                         VN_RELE(ZTOV(sharedir));
5605                         ZFS_EXIT(zfsvfs);
5606                         return (error);
5607                 }
5608                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
5609                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
5610                     &target)) {
5611                         VN_RELE(vp);
5612                         VN_RELE(ZTOV(sharedir));
5613                         ZFS_EXIT(zfsvfs);
5614                         nvlist_free(nvlist);
5615                         return (error);
5616                 }
5617                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
5618                     kcred, NULL, 0);
5619                 nvlist_free(nvlist);
5620                 break;
5621
5622         case ZFS_SMB_ACL_PURGE:
5623                 error = zfs_smb_acl_purge(sharedir);
5624                 break;
5625
5626         default:
5627                 error = SET_ERROR(EINVAL);
5628                 break;
5629         }
5630
5631         VN_RELE(vp);
5632         VN_RELE(ZTOV(sharedir));
5633
5634         ZFS_EXIT(zfsvfs);
5635
5636         return (error);
5637 #else
5638         return (SET_ERROR(ENOTSUP));
5639 #endif /* HAVE_SMB_SHARE */
5640 }
5641
5642 /*
5643  * innvl: {
5644  *     "holds" -> { snapname -> holdname (string), ... }
5645  *     (optional) "cleanup_fd" -> fd (int32)
5646  * }
5647  *
5648  * outnvl: {
5649  *     snapname -> error value (int32)
5650  *     ...
5651  * }
5652  */
5653 /* ARGSUSED */
5654 static int
5655 zfs_ioc_hold(const char *pool, nvlist_t *args, nvlist_t *errlist)
5656 {
5657         nvpair_t *pair;
5658         nvlist_t *holds;
5659         int cleanup_fd = -1;
5660         int error;
5661         minor_t minor = 0;
5662
5663         error = nvlist_lookup_nvlist(args, "holds", &holds);
5664         if (error != 0)
5665                 return (SET_ERROR(EINVAL));
5666
5667         /* make sure the user didn't pass us any invalid (empty) tags */
5668         for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
5669             pair = nvlist_next_nvpair(holds, pair)) {
5670                 char *htag;
5671
5672                 error = nvpair_value_string(pair, &htag);
5673                 if (error != 0)
5674                         return (SET_ERROR(error));
5675
5676                 if (strlen(htag) == 0)
5677                         return (SET_ERROR(EINVAL));
5678         }
5679
5680         if (nvlist_lookup_int32(args, "cleanup_fd", &cleanup_fd) == 0) {
5681                 error = zfs_onexit_fd_hold(cleanup_fd, &minor);
5682                 if (error != 0)
5683                         return (error);
5684         }
5685
5686         error = dsl_dataset_user_hold(holds, minor, errlist);
5687         if (minor != 0)
5688                 zfs_onexit_fd_rele(cleanup_fd);
5689         return (error);
5690 }
5691
5692 /*
5693  * innvl is not used.
5694  *
5695  * outnvl: {
5696  *    holdname -> time added (uint64 seconds since epoch)
5697  *    ...
5698  * }
5699  */
5700 /* ARGSUSED */
5701 static int
5702 zfs_ioc_get_holds(const char *snapname, nvlist_t *args, nvlist_t *outnvl)
5703 {
5704         ASSERT3P(args, ==, NULL);
5705         return (dsl_dataset_get_holds(snapname, outnvl));
5706 }
5707
5708 /*
5709  * innvl: {
5710  *     snapname -> { holdname, ... }
5711  *     ...
5712  * }
5713  *
5714  * outnvl: {
5715  *     snapname -> error value (int32)
5716  *     ...
5717  * }
5718  */
5719 /* ARGSUSED */
5720 static int
5721 zfs_ioc_release(const char *pool, nvlist_t *holds, nvlist_t *errlist)
5722 {
5723         return (dsl_dataset_user_release(holds, errlist));
5724 }
5725
5726 /*
5727  * inputs:
5728  * zc_guid              flags (ZEVENT_NONBLOCK)
5729  * zc_cleanup_fd        zevent file descriptor
5730  *
5731  * outputs:
5732  * zc_nvlist_dst        next nvlist event
5733  * zc_cookie            dropped events since last get
5734  */
5735 static int
5736 zfs_ioc_events_next(zfs_cmd_t *zc)
5737 {
5738         zfs_zevent_t *ze;
5739         nvlist_t *event = NULL;
5740         minor_t minor;
5741         uint64_t dropped = 0;
5742         int error;
5743
5744         error = zfs_zevent_fd_hold(zc->zc_cleanup_fd, &minor, &ze);
5745         if (error != 0)
5746                 return (error);
5747
5748         do {
5749                 error = zfs_zevent_next(ze, &event,
5750                     &zc->zc_nvlist_dst_size, &dropped);
5751                 if (event != NULL) {
5752                         zc->zc_cookie = dropped;
5753                         error = put_nvlist(zc, event);
5754                         nvlist_free(event);
5755                 }
5756
5757                 if (zc->zc_guid & ZEVENT_NONBLOCK)
5758                         break;
5759
5760                 if ((error == 0) || (error != ENOENT))
5761                         break;
5762
5763                 error = zfs_zevent_wait(ze);
5764                 if (error != 0)
5765                         break;
5766         } while (1);
5767
5768         zfs_zevent_fd_rele(zc->zc_cleanup_fd);
5769
5770         return (error);
5771 }
5772
5773 /*
5774  * outputs:
5775  * zc_cookie            cleared events count
5776  */
5777 static int
5778 zfs_ioc_events_clear(zfs_cmd_t *zc)
5779 {
5780         int count;
5781
5782         zfs_zevent_drain_all(&count);
5783         zc->zc_cookie = count;
5784
5785         return (0);
5786 }
5787
5788 /*
5789  * inputs:
5790  * zc_guid              eid | ZEVENT_SEEK_START | ZEVENT_SEEK_END
5791  * zc_cleanup           zevent file descriptor
5792  */
5793 static int
5794 zfs_ioc_events_seek(zfs_cmd_t *zc)
5795 {
5796         zfs_zevent_t *ze;
5797         minor_t minor;
5798         int error;
5799
5800         error = zfs_zevent_fd_hold(zc->zc_cleanup_fd, &minor, &ze);
5801         if (error != 0)
5802                 return (error);
5803
5804         error = zfs_zevent_seek(ze, zc->zc_guid);
5805         zfs_zevent_fd_rele(zc->zc_cleanup_fd);
5806
5807         return (error);
5808 }
5809
5810 /*
5811  * inputs:
5812  * zc_name              name of new filesystem or snapshot
5813  * zc_value             full name of old snapshot
5814  *
5815  * outputs:
5816  * zc_cookie            space in bytes
5817  * zc_objset_type       compressed space in bytes
5818  * zc_perm_action       uncompressed space in bytes
5819  */
5820 static int
5821 zfs_ioc_space_written(zfs_cmd_t *zc)
5822 {
5823         int error;
5824         dsl_pool_t *dp;
5825         dsl_dataset_t *new, *old;
5826
5827         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5828         if (error != 0)
5829                 return (error);
5830         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &new);
5831         if (error != 0) {
5832                 dsl_pool_rele(dp, FTAG);
5833                 return (error);
5834         }
5835         error = dsl_dataset_hold(dp, zc->zc_value, FTAG, &old);
5836         if (error != 0) {
5837                 dsl_dataset_rele(new, FTAG);
5838                 dsl_pool_rele(dp, FTAG);
5839                 return (error);
5840         }
5841
5842         error = dsl_dataset_space_written(old, new, &zc->zc_cookie,
5843             &zc->zc_objset_type, &zc->zc_perm_action);
5844         dsl_dataset_rele(old, FTAG);
5845         dsl_dataset_rele(new, FTAG);
5846         dsl_pool_rele(dp, FTAG);
5847         return (error);
5848 }
5849
5850 /*
5851  * innvl: {
5852  *     "firstsnap" -> snapshot name
5853  * }
5854  *
5855  * outnvl: {
5856  *     "used" -> space in bytes
5857  *     "compressed" -> compressed space in bytes
5858  *     "uncompressed" -> uncompressed space in bytes
5859  * }
5860  */
5861 static int
5862 zfs_ioc_space_snaps(const char *lastsnap, nvlist_t *innvl, nvlist_t *outnvl)
5863 {
5864         int error;
5865         dsl_pool_t *dp;
5866         dsl_dataset_t *new, *old;
5867         char *firstsnap;
5868         uint64_t used, comp, uncomp;
5869
5870         if (nvlist_lookup_string(innvl, "firstsnap", &firstsnap) != 0)
5871                 return (SET_ERROR(EINVAL));
5872
5873         error = dsl_pool_hold(lastsnap, FTAG, &dp);
5874         if (error != 0)
5875                 return (error);
5876
5877         error = dsl_dataset_hold(dp, lastsnap, FTAG, &new);
5878         if (error == 0 && !new->ds_is_snapshot) {
5879                 dsl_dataset_rele(new, FTAG);
5880                 error = SET_ERROR(EINVAL);
5881         }
5882         if (error != 0) {
5883                 dsl_pool_rele(dp, FTAG);
5884                 return (error);
5885         }
5886         error = dsl_dataset_hold(dp, firstsnap, FTAG, &old);
5887         if (error == 0 && !old->ds_is_snapshot) {
5888                 dsl_dataset_rele(old, FTAG);
5889                 error = SET_ERROR(EINVAL);
5890         }
5891         if (error != 0) {
5892                 dsl_dataset_rele(new, FTAG);
5893                 dsl_pool_rele(dp, FTAG);
5894                 return (error);
5895         }
5896
5897         error = dsl_dataset_space_wouldfree(old, new, &used, &comp, &uncomp);
5898         dsl_dataset_rele(old, FTAG);
5899         dsl_dataset_rele(new, FTAG);
5900         dsl_pool_rele(dp, FTAG);
5901         fnvlist_add_uint64(outnvl, "used", used);
5902         fnvlist_add_uint64(outnvl, "compressed", comp);
5903         fnvlist_add_uint64(outnvl, "uncompressed", uncomp);
5904         return (error);
5905 }
5906
5907 /*
5908  * innvl: {
5909  *     "fd" -> file descriptor to write stream to (int32)
5910  *     (optional) "fromsnap" -> full snap name to send an incremental from
5911  *     (optional) "largeblockok" -> (value ignored)
5912  *         indicates that blocks > 128KB are permitted
5913  *     (optional) "embedok" -> (value ignored)
5914  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5915  *     (optional) "compressok" -> (value ignored)
5916  *         presence indicates compressed DRR_WRITE records are permitted
5917  *     (optional) "rawok" -> (value ignored)
5918  *         presence indicates raw encrypted records should be used.
5919  *     (optional) "resume_object" and "resume_offset" -> (uint64)
5920  *         if present, resume send stream from specified object and offset.
5921  * }
5922  *
5923  * outnvl is unused
5924  */
5925 /* ARGSUSED */
5926 static int
5927 zfs_ioc_send_new(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5928 {
5929         int error;
5930         offset_t off;
5931         char *fromname = NULL;
5932         int fd;
5933         file_t *fp;
5934         boolean_t largeblockok;
5935         boolean_t embedok;
5936         boolean_t compressok;
5937         boolean_t rawok;
5938         uint64_t resumeobj = 0;
5939         uint64_t resumeoff = 0;
5940
5941         error = nvlist_lookup_int32(innvl, "fd", &fd);
5942         if (error != 0)
5943                 return (SET_ERROR(EINVAL));
5944
5945         (void) nvlist_lookup_string(innvl, "fromsnap", &fromname);
5946
5947         largeblockok = nvlist_exists(innvl, "largeblockok");
5948         embedok = nvlist_exists(innvl, "embedok");
5949         compressok = nvlist_exists(innvl, "compressok");
5950         rawok = nvlist_exists(innvl, "rawok");
5951
5952         (void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
5953         (void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
5954
5955         if ((fp = getf(fd)) == NULL)
5956                 return (SET_ERROR(EBADF));
5957
5958         off = fp->f_offset;
5959         error = dmu_send(snapname, fromname, embedok, largeblockok, compressok,
5960             rawok, fd, resumeobj, resumeoff, fp->f_vnode, &off);
5961
5962         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5963                 fp->f_offset = off;
5964
5965         releasef(fd);
5966         return (error);
5967 }
5968
5969 /*
5970  * Determine approximately how large a zfs send stream will be -- the number
5971  * of bytes that will be written to the fd supplied to zfs_ioc_send_new().
5972  *
5973  * innvl: {
5974  *     (optional) "from" -> full snap or bookmark name to send an incremental
5975  *                          from
5976  *     (optional) "largeblockok" -> (value ignored)
5977  *         indicates that blocks > 128KB are permitted
5978  *     (optional) "embedok" -> (value ignored)
5979  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5980  *     (optional) "compressok" -> (value ignored)
5981  *         presence indicates compressed DRR_WRITE records are permitted
5982  *      (optional) "rawok" -> (value ignored)
5983  *         presence indicates raw encrypted records should be used.
5984  * }
5985  *
5986  * outnvl: {
5987  *     "space" -> bytes of space (uint64)
5988  * }
5989  */
5990 static int
5991 zfs_ioc_send_space(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5992 {
5993         dsl_pool_t *dp;
5994         dsl_dataset_t *tosnap;
5995         int error;
5996         char *fromname;
5997         boolean_t compressok;
5998         boolean_t rawok;
5999         uint64_t space;
6000
6001         error = dsl_pool_hold(snapname, FTAG, &dp);
6002         if (error != 0)
6003                 return (error);
6004
6005         error = dsl_dataset_hold(dp, snapname, FTAG, &tosnap);
6006         if (error != 0) {
6007                 dsl_pool_rele(dp, FTAG);
6008                 return (error);
6009         }
6010
6011         compressok = nvlist_exists(innvl, "compressok");
6012         rawok = nvlist_exists(innvl, "rawok");
6013
6014         error = nvlist_lookup_string(innvl, "from", &fromname);
6015         if (error == 0) {
6016                 if (strchr(fromname, '@') != NULL) {
6017                         /*
6018                          * If from is a snapshot, hold it and use the more
6019                          * efficient dmu_send_estimate to estimate send space
6020                          * size using deadlists.
6021                          */
6022                         dsl_dataset_t *fromsnap;
6023                         error = dsl_dataset_hold(dp, fromname, FTAG, &fromsnap);
6024                         if (error != 0)
6025                                 goto out;
6026                         error = dmu_send_estimate(tosnap, fromsnap,
6027                             compressok || rawok, &space);
6028                         dsl_dataset_rele(fromsnap, FTAG);
6029                 } else if (strchr(fromname, '#') != NULL) {
6030                         /*
6031                          * If from is a bookmark, fetch the creation TXG of the
6032                          * snapshot it was created from and use that to find
6033                          * blocks that were born after it.
6034                          */
6035                         zfs_bookmark_phys_t frombm;
6036
6037                         error = dsl_bookmark_lookup(dp, fromname, tosnap,
6038                             &frombm);
6039                         if (error != 0)
6040                                 goto out;
6041                         error = dmu_send_estimate_from_txg(tosnap,
6042                             frombm.zbm_creation_txg, compressok || rawok,
6043                             &space);
6044                 } else {
6045                         /*
6046                          * from is not properly formatted as a snapshot or
6047                          * bookmark
6048                          */
6049                         error = SET_ERROR(EINVAL);
6050                         goto out;
6051                 }
6052         } else {
6053                 /*
6054                  * If estimating the size of a full send, use dmu_send_estimate.
6055                  */
6056                 error = dmu_send_estimate(tosnap, NULL, compressok || rawok,
6057                     &space);
6058         }
6059
6060         fnvlist_add_uint64(outnvl, "space", space);
6061
6062 out:
6063         dsl_dataset_rele(tosnap, FTAG);
6064         dsl_pool_rele(dp, FTAG);
6065         return (error);
6066 }
6067
6068 /*
6069  * Sync the currently open TXG to disk for the specified pool.
6070  * This is somewhat similar to 'zfs_sync()'.
6071  * For cases that do not result in error this ioctl will wait for
6072  * the currently open TXG to commit before returning back to the caller.
6073  *
6074  * innvl: {
6075  *  "force" -> when true, force uberblock update even if there is no dirty data.
6076  *             In addition this will cause the vdev configuration to be written
6077  *             out including updating the zpool cache file. (boolean_t)
6078  * }
6079  *
6080  * onvl is unused
6081  */
6082 /* ARGSUSED */
6083 static int
6084 zfs_ioc_pool_sync(const char *pool, nvlist_t *innvl, nvlist_t *onvl)
6085 {
6086         int err;
6087         boolean_t force = B_FALSE;
6088         spa_t *spa;
6089
6090         if ((err = spa_open(pool, &spa, FTAG)) != 0)
6091                 return (err);
6092
6093         if (innvl) {
6094                 if (nvlist_lookup_boolean_value(innvl, "force", &force) != 0) {
6095                         err = SET_ERROR(EINVAL);
6096                         goto out;
6097                 }
6098         }
6099
6100         if (force) {
6101                 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_WRITER);
6102                 vdev_config_dirty(spa->spa_root_vdev);
6103                 spa_config_exit(spa, SCL_CONFIG, FTAG);
6104         }
6105         txg_wait_synced(spa_get_dsl(spa), 0);
6106 out:
6107         spa_close(spa, FTAG);
6108
6109         return (err);
6110 }
6111
6112 /*
6113  * Load a user's wrapping key into the kernel.
6114  * innvl: {
6115  *     "hidden_args" -> { "wkeydata" -> value }
6116  *         raw uint8_t array of encryption wrapping key data (32 bytes)
6117  *     (optional) "noop" -> (value ignored)
6118  *         presence indicated key should only be verified, not loaded
6119  * }
6120  */
6121 /* ARGSUSED */
6122 static int
6123 zfs_ioc_load_key(const char *dsname, nvlist_t *innvl, nvlist_t *outnvl)
6124 {
6125         int ret;
6126         dsl_crypto_params_t *dcp = NULL;
6127         nvlist_t *hidden_args;
6128         boolean_t noop = nvlist_exists(innvl, "noop");
6129
6130         if (strchr(dsname, '@') != NULL || strchr(dsname, '%') != NULL) {
6131                 ret = SET_ERROR(EINVAL);
6132                 goto error;
6133         }
6134
6135         ret = nvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS, &hidden_args);
6136         if (ret != 0) {
6137                 ret = SET_ERROR(EINVAL);
6138                 goto error;
6139         }
6140
6141         ret = dsl_crypto_params_create_nvlist(DCP_CMD_NONE, NULL,
6142             hidden_args, &dcp);
6143         if (ret != 0)
6144                 goto error;
6145
6146         ret = spa_keystore_load_wkey(dsname, dcp, noop);
6147         if (ret != 0)
6148                 goto error;
6149
6150         dsl_crypto_params_free(dcp, noop);
6151
6152         return (0);
6153
6154 error:
6155         dsl_crypto_params_free(dcp, B_TRUE);
6156         return (ret);
6157 }
6158
6159 /*
6160  * Unload a user's wrapping key from the kernel.
6161  * Both innvl and outnvl are unused.
6162  */
6163 /* ARGSUSED */
6164 static int
6165 zfs_ioc_unload_key(const char *dsname, nvlist_t *innvl, nvlist_t *outnvl)
6166 {
6167         int ret = 0;
6168
6169         if (strchr(dsname, '@') != NULL || strchr(dsname, '%') != NULL) {
6170                 ret = (SET_ERROR(EINVAL));
6171                 goto out;
6172         }
6173
6174         ret = spa_keystore_unload_wkey(dsname);
6175         if (ret != 0)
6176                 goto out;
6177
6178 out:
6179         return (ret);
6180 }
6181
6182 /*
6183  * Changes a user's wrapping key used to decrypt a dataset. The keyformat,
6184  * keylocation, pbkdf2salt, and  pbkdf2iters properties can also be specified
6185  * here to change how the key is derived in userspace.
6186  *
6187  * innvl: {
6188  *    "hidden_args" (optional) -> { "wkeydata" -> value }
6189  *         raw uint8_t array of new encryption wrapping key data (32 bytes)
6190  *    "props" (optional) -> { prop -> value }
6191  * }
6192  *
6193  * outnvl is unused
6194  */
6195 /* ARGSUSED */
6196 static int
6197 zfs_ioc_change_key(const char *dsname, nvlist_t *innvl, nvlist_t *outnvl)
6198 {
6199         int ret;
6200         uint64_t cmd = DCP_CMD_NONE;
6201         dsl_crypto_params_t *dcp = NULL;
6202         nvlist_t *args = NULL, *hidden_args = NULL;
6203
6204         if (strchr(dsname, '@') != NULL || strchr(dsname, '%') != NULL) {
6205                 ret = (SET_ERROR(EINVAL));
6206                 goto error;
6207         }
6208
6209         (void) nvlist_lookup_uint64(innvl, "crypt_cmd", &cmd);
6210         (void) nvlist_lookup_nvlist(innvl, "props", &args);
6211         (void) nvlist_lookup_nvlist(innvl, ZPOOL_HIDDEN_ARGS, &hidden_args);
6212
6213         ret = dsl_crypto_params_create_nvlist(cmd, args, hidden_args, &dcp);
6214         if (ret != 0)
6215                 goto error;
6216
6217         ret = spa_keystore_change_key(dsname, dcp);
6218         if (ret != 0)
6219                 goto error;
6220
6221         dsl_crypto_params_free(dcp, B_FALSE);
6222
6223         return (0);
6224
6225 error:
6226         dsl_crypto_params_free(dcp, B_TRUE);
6227         return (ret);
6228 }
6229
6230 static zfs_ioc_vec_t zfs_ioc_vec[ZFS_IOC_LAST - ZFS_IOC_FIRST];
6231
6232 static void
6233 zfs_ioctl_register_legacy(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6234     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
6235     boolean_t log_history, zfs_ioc_poolcheck_t pool_check)
6236 {
6237         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
6238
6239         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
6240         ASSERT3U(ioc, <, ZFS_IOC_LAST);
6241         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
6242         ASSERT3P(vec->zvec_func, ==, NULL);
6243
6244         vec->zvec_legacy_func = func;
6245         vec->zvec_secpolicy = secpolicy;
6246         vec->zvec_namecheck = namecheck;
6247         vec->zvec_allow_log = log_history;
6248         vec->zvec_pool_check = pool_check;
6249 }
6250
6251 /*
6252  * See the block comment at the beginning of this file for details on
6253  * each argument to this function.
6254  */
6255 static void
6256 zfs_ioctl_register(const char *name, zfs_ioc_t ioc, zfs_ioc_func_t *func,
6257     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
6258     zfs_ioc_poolcheck_t pool_check, boolean_t smush_outnvlist,
6259     boolean_t allow_log)
6260 {
6261         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
6262
6263         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
6264         ASSERT3U(ioc, <, ZFS_IOC_LAST);
6265         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
6266         ASSERT3P(vec->zvec_func, ==, NULL);
6267
6268         /* if we are logging, the name must be valid */
6269         ASSERT(!allow_log || namecheck != NO_NAME);
6270
6271         vec->zvec_name = name;
6272         vec->zvec_func = func;
6273         vec->zvec_secpolicy = secpolicy;
6274         vec->zvec_namecheck = namecheck;
6275         vec->zvec_pool_check = pool_check;
6276         vec->zvec_smush_outnvlist = smush_outnvlist;
6277         vec->zvec_allow_log = allow_log;
6278 }
6279
6280 static void
6281 zfs_ioctl_register_pool(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6282     zfs_secpolicy_func_t *secpolicy, boolean_t log_history,
6283     zfs_ioc_poolcheck_t pool_check)
6284 {
6285         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6286             POOL_NAME, log_history, pool_check);
6287 }
6288
6289 static void
6290 zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6291     zfs_secpolicy_func_t *secpolicy, zfs_ioc_poolcheck_t pool_check)
6292 {
6293         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6294             DATASET_NAME, B_FALSE, pool_check);
6295 }
6296
6297 static void
6298 zfs_ioctl_register_pool_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
6299 {
6300         zfs_ioctl_register_legacy(ioc, func, zfs_secpolicy_config,
6301             POOL_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6302 }
6303
6304 static void
6305 zfs_ioctl_register_pool_meta(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6306     zfs_secpolicy_func_t *secpolicy)
6307 {
6308         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6309             NO_NAME, B_FALSE, POOL_CHECK_NONE);
6310 }
6311
6312 static void
6313 zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,
6314     zfs_ioc_legacy_func_t *func, zfs_secpolicy_func_t *secpolicy)
6315 {
6316         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6317             DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED);
6318 }
6319
6320 static void
6321 zfs_ioctl_register_dataset_read(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
6322 {
6323         zfs_ioctl_register_dataset_read_secpolicy(ioc, func,
6324             zfs_secpolicy_read);
6325 }
6326
6327 static void
6328 zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6329     zfs_secpolicy_func_t *secpolicy)
6330 {
6331         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6332             DATASET_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6333 }
6334
6335 static void
6336 zfs_ioctl_init(void)
6337 {
6338         zfs_ioctl_register("snapshot", ZFS_IOC_SNAPSHOT,
6339             zfs_ioc_snapshot, zfs_secpolicy_snapshot, POOL_NAME,
6340             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6341
6342         zfs_ioctl_register("log_history", ZFS_IOC_LOG_HISTORY,
6343             zfs_ioc_log_history, zfs_secpolicy_log_history, NO_NAME,
6344             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE);
6345
6346         zfs_ioctl_register("space_snaps", ZFS_IOC_SPACE_SNAPS,
6347             zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME,
6348             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6349
6350         zfs_ioctl_register("send", ZFS_IOC_SEND_NEW,
6351             zfs_ioc_send_new, zfs_secpolicy_send_new, DATASET_NAME,
6352             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6353
6354         zfs_ioctl_register("send_space", ZFS_IOC_SEND_SPACE,
6355             zfs_ioc_send_space, zfs_secpolicy_read, DATASET_NAME,
6356             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6357
6358         zfs_ioctl_register("create", ZFS_IOC_CREATE,
6359             zfs_ioc_create, zfs_secpolicy_create_clone, DATASET_NAME,
6360             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6361
6362         zfs_ioctl_register("clone", ZFS_IOC_CLONE,
6363             zfs_ioc_clone, zfs_secpolicy_create_clone, DATASET_NAME,
6364             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6365
6366         zfs_ioctl_register("remap", ZFS_IOC_REMAP,
6367             zfs_ioc_remap, zfs_secpolicy_remap, DATASET_NAME,
6368             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
6369
6370         zfs_ioctl_register("destroy_snaps", ZFS_IOC_DESTROY_SNAPS,
6371             zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, POOL_NAME,
6372             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6373
6374         zfs_ioctl_register("hold", ZFS_IOC_HOLD,
6375             zfs_ioc_hold, zfs_secpolicy_hold, POOL_NAME,
6376             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6377         zfs_ioctl_register("release", ZFS_IOC_RELEASE,
6378             zfs_ioc_release, zfs_secpolicy_release, POOL_NAME,
6379             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6380
6381         zfs_ioctl_register("get_holds", ZFS_IOC_GET_HOLDS,
6382             zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME,
6383             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6384
6385         zfs_ioctl_register("rollback", ZFS_IOC_ROLLBACK,
6386             zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME,
6387             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
6388
6389         zfs_ioctl_register("bookmark", ZFS_IOC_BOOKMARK,
6390             zfs_ioc_bookmark, zfs_secpolicy_bookmark, POOL_NAME,
6391             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6392
6393         zfs_ioctl_register("get_bookmarks", ZFS_IOC_GET_BOOKMARKS,
6394             zfs_ioc_get_bookmarks, zfs_secpolicy_read, DATASET_NAME,
6395             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6396
6397         zfs_ioctl_register("destroy_bookmarks", ZFS_IOC_DESTROY_BOOKMARKS,
6398             zfs_ioc_destroy_bookmarks, zfs_secpolicy_destroy_bookmarks,
6399             POOL_NAME,
6400             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6401
6402         zfs_ioctl_register("receive", ZFS_IOC_RECV_NEW,
6403             zfs_ioc_recv_new, zfs_secpolicy_recv_new, DATASET_NAME,
6404             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6405         zfs_ioctl_register("load-key", ZFS_IOC_LOAD_KEY,
6406             zfs_ioc_load_key, zfs_secpolicy_load_key,
6407             DATASET_NAME, POOL_CHECK_SUSPENDED, B_TRUE, B_TRUE);
6408         zfs_ioctl_register("unload-key", ZFS_IOC_UNLOAD_KEY,
6409             zfs_ioc_unload_key, zfs_secpolicy_load_key,
6410             DATASET_NAME, POOL_CHECK_SUSPENDED, B_TRUE, B_TRUE);
6411         zfs_ioctl_register("change-key", ZFS_IOC_CHANGE_KEY,
6412             zfs_ioc_change_key, zfs_secpolicy_change_key,
6413             DATASET_NAME, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY,
6414             B_TRUE, B_TRUE);
6415
6416         zfs_ioctl_register("sync", ZFS_IOC_POOL_SYNC,
6417             zfs_ioc_pool_sync, zfs_secpolicy_none, POOL_NAME,
6418             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE);
6419         zfs_ioctl_register("reopen", ZFS_IOC_POOL_REOPEN, zfs_ioc_pool_reopen,
6420             zfs_secpolicy_config, POOL_NAME, POOL_CHECK_SUSPENDED, B_TRUE,
6421             B_TRUE);
6422
6423         zfs_ioctl_register("channel_program", ZFS_IOC_CHANNEL_PROGRAM,
6424             zfs_ioc_channel_program, zfs_secpolicy_config,
6425             POOL_NAME, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE,
6426             B_TRUE);
6427
6428         /* IOCTLS that use the legacy function signature */
6429
6430         zfs_ioctl_register_legacy(ZFS_IOC_POOL_FREEZE, zfs_ioc_pool_freeze,
6431             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_READONLY);
6432
6433         zfs_ioctl_register_pool(ZFS_IOC_POOL_CREATE, zfs_ioc_pool_create,
6434             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6435         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SCAN,
6436             zfs_ioc_pool_scan);
6437         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_UPGRADE,
6438             zfs_ioc_pool_upgrade);
6439         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ADD,
6440             zfs_ioc_vdev_add);
6441         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_REMOVE,
6442             zfs_ioc_vdev_remove);
6443         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SET_STATE,
6444             zfs_ioc_vdev_set_state);
6445         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ATTACH,
6446             zfs_ioc_vdev_attach);
6447         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_DETACH,
6448             zfs_ioc_vdev_detach);
6449         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETPATH,
6450             zfs_ioc_vdev_setpath);
6451         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETFRU,
6452             zfs_ioc_vdev_setfru);
6453         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SET_PROPS,
6454             zfs_ioc_pool_set_props);
6455         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SPLIT,
6456             zfs_ioc_vdev_split);
6457         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_REGUID,
6458             zfs_ioc_pool_reguid);
6459
6460         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_CONFIGS,
6461             zfs_ioc_pool_configs, zfs_secpolicy_none);
6462         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_TRYIMPORT,
6463             zfs_ioc_pool_tryimport, zfs_secpolicy_config);
6464         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_FAULT,
6465             zfs_ioc_inject_fault, zfs_secpolicy_inject);
6466         zfs_ioctl_register_pool_meta(ZFS_IOC_CLEAR_FAULT,
6467             zfs_ioc_clear_fault, zfs_secpolicy_inject);
6468         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_LIST_NEXT,
6469             zfs_ioc_inject_list_next, zfs_secpolicy_inject);
6470
6471         /*
6472          * pool destroy, and export don't log the history as part of
6473          * zfsdev_ioctl, but rather zfs_ioc_pool_export
6474          * does the logging of those commands.
6475          */
6476         zfs_ioctl_register_pool(ZFS_IOC_POOL_DESTROY, zfs_ioc_pool_destroy,
6477             zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
6478         zfs_ioctl_register_pool(ZFS_IOC_POOL_EXPORT, zfs_ioc_pool_export,
6479             zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
6480
6481         zfs_ioctl_register_pool(ZFS_IOC_POOL_STATS, zfs_ioc_pool_stats,
6482             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6483         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_PROPS, zfs_ioc_pool_get_props,
6484             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6485
6486         zfs_ioctl_register_pool(ZFS_IOC_ERROR_LOG, zfs_ioc_error_log,
6487             zfs_secpolicy_inject, B_FALSE, POOL_CHECK_SUSPENDED);
6488         zfs_ioctl_register_pool(ZFS_IOC_DSOBJ_TO_DSNAME,
6489             zfs_ioc_dsobj_to_dsname,
6490             zfs_secpolicy_diff, B_FALSE, POOL_CHECK_SUSPENDED);
6491         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_HISTORY,
6492             zfs_ioc_pool_get_history,
6493             zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
6494
6495         zfs_ioctl_register_pool(ZFS_IOC_POOL_IMPORT, zfs_ioc_pool_import,
6496             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6497
6498         zfs_ioctl_register_pool(ZFS_IOC_CLEAR, zfs_ioc_clear,
6499             zfs_secpolicy_config, B_TRUE, POOL_CHECK_READONLY);
6500
6501         zfs_ioctl_register_dataset_read(ZFS_IOC_SPACE_WRITTEN,
6502             zfs_ioc_space_written);
6503         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_RECVD_PROPS,
6504             zfs_ioc_objset_recvd_props);
6505         zfs_ioctl_register_dataset_read(ZFS_IOC_NEXT_OBJ,
6506             zfs_ioc_next_obj);
6507         zfs_ioctl_register_dataset_read(ZFS_IOC_GET_FSACL,
6508             zfs_ioc_get_fsacl);
6509         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_STATS,
6510             zfs_ioc_objset_stats);
6511         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_ZPLPROPS,
6512             zfs_ioc_objset_zplprops);
6513         zfs_ioctl_register_dataset_read(ZFS_IOC_DATASET_LIST_NEXT,
6514             zfs_ioc_dataset_list_next);
6515         zfs_ioctl_register_dataset_read(ZFS_IOC_SNAPSHOT_LIST_NEXT,
6516             zfs_ioc_snapshot_list_next);
6517         zfs_ioctl_register_dataset_read(ZFS_IOC_SEND_PROGRESS,
6518             zfs_ioc_send_progress);
6519
6520         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_DIFF,
6521             zfs_ioc_diff, zfs_secpolicy_diff);
6522         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_STATS,
6523             zfs_ioc_obj_to_stats, zfs_secpolicy_diff);
6524         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_PATH,
6525             zfs_ioc_obj_to_path, zfs_secpolicy_diff);
6526         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_ONE,
6527             zfs_ioc_userspace_one, zfs_secpolicy_userspace_one);
6528         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_MANY,
6529             zfs_ioc_userspace_many, zfs_secpolicy_userspace_many);
6530         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_SEND,
6531             zfs_ioc_send, zfs_secpolicy_send);
6532
6533         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_PROP, zfs_ioc_set_prop,
6534             zfs_secpolicy_none);
6535         zfs_ioctl_register_dataset_modify(ZFS_IOC_DESTROY, zfs_ioc_destroy,
6536             zfs_secpolicy_destroy);
6537         zfs_ioctl_register_dataset_modify(ZFS_IOC_RENAME, zfs_ioc_rename,
6538             zfs_secpolicy_rename);
6539         zfs_ioctl_register_dataset_modify(ZFS_IOC_RECV, zfs_ioc_recv,
6540             zfs_secpolicy_recv);
6541         zfs_ioctl_register_dataset_modify(ZFS_IOC_PROMOTE, zfs_ioc_promote,
6542             zfs_secpolicy_promote);
6543         zfs_ioctl_register_dataset_modify(ZFS_IOC_INHERIT_PROP,
6544             zfs_ioc_inherit_prop, zfs_secpolicy_inherit_prop);
6545         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_FSACL, zfs_ioc_set_fsacl,
6546             zfs_secpolicy_set_fsacl);
6547
6548         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SHARE, zfs_ioc_share,
6549             zfs_secpolicy_share, POOL_CHECK_NONE);
6550         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SMB_ACL, zfs_ioc_smb_acl,
6551             zfs_secpolicy_smb_acl, POOL_CHECK_NONE);
6552         zfs_ioctl_register_dataset_nolog(ZFS_IOC_USERSPACE_UPGRADE,
6553             zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
6554             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6555         zfs_ioctl_register_dataset_nolog(ZFS_IOC_TMP_SNAPSHOT,
6556             zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot,
6557             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6558
6559         /*
6560          * ZoL functions
6561          */
6562         zfs_ioctl_register_legacy(ZFS_IOC_EVENTS_NEXT, zfs_ioc_events_next,
6563             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE);
6564         zfs_ioctl_register_legacy(ZFS_IOC_EVENTS_CLEAR, zfs_ioc_events_clear,
6565             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE);
6566         zfs_ioctl_register_legacy(ZFS_IOC_EVENTS_SEEK, zfs_ioc_events_seek,
6567             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_NONE);
6568 }
6569
6570 int
6571 pool_status_check(const char *name, zfs_ioc_namecheck_t type,
6572     zfs_ioc_poolcheck_t check)
6573 {
6574         spa_t *spa;
6575         int error;
6576
6577         ASSERT(type == POOL_NAME || type == DATASET_NAME);
6578
6579         if (check & POOL_CHECK_NONE)
6580                 return (0);
6581
6582         error = spa_open(name, &spa, FTAG);
6583         if (error == 0) {
6584                 if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
6585                         error = SET_ERROR(EAGAIN);
6586                 else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
6587                         error = SET_ERROR(EROFS);
6588                 spa_close(spa, FTAG);
6589         }
6590         return (error);
6591 }
6592
6593 static void *
6594 zfsdev_get_state_impl(minor_t minor, enum zfsdev_state_type which)
6595 {
6596         zfsdev_state_t *zs;
6597
6598         for (zs = zfsdev_state_list; zs != NULL; zs = zs->zs_next) {
6599                 if (zs->zs_minor == minor) {
6600                         smp_rmb();
6601                         switch (which) {
6602                         case ZST_ONEXIT:
6603                                 return (zs->zs_onexit);
6604                         case ZST_ZEVENT:
6605                                 return (zs->zs_zevent);
6606                         case ZST_ALL:
6607                                 return (zs);
6608                         }
6609                 }
6610         }
6611
6612         return (NULL);
6613 }
6614
6615 void *
6616 zfsdev_get_state(minor_t minor, enum zfsdev_state_type which)
6617 {
6618         void *ptr;
6619
6620         ptr = zfsdev_get_state_impl(minor, which);
6621
6622         return (ptr);
6623 }
6624
6625 int
6626 zfsdev_getminor(struct file *filp, minor_t *minorp)
6627 {
6628         zfsdev_state_t *zs, *fpd;
6629
6630         ASSERT(filp != NULL);
6631         ASSERT(!MUTEX_HELD(&zfsdev_state_lock));
6632
6633         fpd = filp->private_data;
6634         if (fpd == NULL)
6635                 return (SET_ERROR(EBADF));
6636
6637         mutex_enter(&zfsdev_state_lock);
6638
6639         for (zs = zfsdev_state_list; zs != NULL; zs = zs->zs_next) {
6640
6641                 if (zs->zs_minor == -1)
6642                         continue;
6643
6644                 if (fpd == zs) {
6645                         *minorp = fpd->zs_minor;
6646                         mutex_exit(&zfsdev_state_lock);
6647                         return (0);
6648                 }
6649         }
6650
6651         mutex_exit(&zfsdev_state_lock);
6652
6653         return (SET_ERROR(EBADF));
6654 }
6655
6656 /*
6657  * Find a free minor number.  The zfsdev_state_list is expected to
6658  * be short since it is only a list of currently open file handles.
6659  */
6660 minor_t
6661 zfsdev_minor_alloc(void)
6662 {
6663         static minor_t last_minor = 0;
6664         minor_t m;
6665
6666         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
6667
6668         for (m = last_minor + 1; m != last_minor; m++) {
6669                 if (m > ZFSDEV_MAX_MINOR)
6670                         m = 1;
6671                 if (zfsdev_get_state_impl(m, ZST_ALL) == NULL) {
6672                         last_minor = m;
6673                         return (m);
6674                 }
6675         }
6676
6677         return (0);
6678 }
6679
6680 static int
6681 zfsdev_state_init(struct file *filp)
6682 {
6683         zfsdev_state_t *zs, *zsprev = NULL;
6684         minor_t minor;
6685         boolean_t newzs = B_FALSE;
6686
6687         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
6688
6689         minor = zfsdev_minor_alloc();
6690         if (minor == 0)
6691                 return (SET_ERROR(ENXIO));
6692
6693         for (zs = zfsdev_state_list; zs != NULL; zs = zs->zs_next) {
6694                 if (zs->zs_minor == -1)
6695                         break;
6696                 zsprev = zs;
6697         }
6698
6699         if (!zs) {
6700                 zs = kmem_zalloc(sizeof (zfsdev_state_t), KM_SLEEP);
6701                 newzs = B_TRUE;
6702         }
6703
6704         zs->zs_file = filp;
6705         filp->private_data = zs;
6706
6707         zfs_onexit_init((zfs_onexit_t **)&zs->zs_onexit);
6708         zfs_zevent_init((zfs_zevent_t **)&zs->zs_zevent);
6709
6710
6711         /*
6712          * In order to provide for lock-free concurrent read access
6713          * to the minor list in zfsdev_get_state_impl(), new entries
6714          * must be completely written before linking them into the
6715          * list whereas existing entries are already linked; the last
6716          * operation must be updating zs_minor (from -1 to the new
6717          * value).
6718          */
6719         if (newzs) {
6720                 zs->zs_minor = minor;
6721                 smp_wmb();
6722                 zsprev->zs_next = zs;
6723         } else {
6724                 smp_wmb();
6725                 zs->zs_minor = minor;
6726         }
6727
6728         return (0);
6729 }
6730
6731 static int
6732 zfsdev_state_destroy(struct file *filp)
6733 {
6734         zfsdev_state_t *zs;
6735
6736         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
6737         ASSERT(filp->private_data != NULL);
6738
6739         zs = filp->private_data;
6740         zs->zs_minor = -1;
6741         zfs_onexit_destroy(zs->zs_onexit);
6742         zfs_zevent_destroy(zs->zs_zevent);
6743
6744         return (0);
6745 }
6746
6747 static int
6748 zfsdev_open(struct inode *ino, struct file *filp)
6749 {
6750         int error;
6751
6752         mutex_enter(&zfsdev_state_lock);
6753         error = zfsdev_state_init(filp);
6754         mutex_exit(&zfsdev_state_lock);
6755
6756         return (-error);
6757 }
6758
6759 static int
6760 zfsdev_release(struct inode *ino, struct file *filp)
6761 {
6762         int error;
6763
6764         mutex_enter(&zfsdev_state_lock);
6765         error = zfsdev_state_destroy(filp);
6766         mutex_exit(&zfsdev_state_lock);
6767
6768         return (-error);
6769 }
6770
6771 static long
6772 zfsdev_ioctl(struct file *filp, unsigned cmd, unsigned long arg)
6773 {
6774         zfs_cmd_t *zc;
6775         uint_t vecnum;
6776         int error, rc, flag = 0;
6777         const zfs_ioc_vec_t *vec;
6778         char *saved_poolname = NULL;
6779         nvlist_t *innvl = NULL;
6780         fstrans_cookie_t cookie;
6781
6782         vecnum = cmd - ZFS_IOC_FIRST;
6783         if (vecnum >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
6784                 return (-SET_ERROR(EINVAL));
6785         vec = &zfs_ioc_vec[vecnum];
6786
6787         /*
6788          * The registered ioctl list may be sparse, verify that either
6789          * a normal or legacy handler are registered.
6790          */
6791         if (vec->zvec_func == NULL && vec->zvec_legacy_func == NULL)
6792                 return (-SET_ERROR(EINVAL));
6793
6794         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
6795
6796         error = ddi_copyin((void *)arg, zc, sizeof (zfs_cmd_t), flag);
6797         if (error != 0) {
6798                 error = SET_ERROR(EFAULT);
6799                 goto out;
6800         }
6801
6802         zc->zc_iflags = flag & FKIOCTL;
6803         if (zc->zc_nvlist_src_size > MAX_NVLIST_SRC_SIZE) {
6804                 /*
6805                  * Make sure the user doesn't pass in an insane value for
6806                  * zc_nvlist_src_size.  We have to check, since we will end
6807                  * up allocating that much memory inside of get_nvlist().  This
6808                  * prevents a nefarious user from allocating tons of kernel
6809                  * memory.
6810                  *
6811                  * Also, we return EINVAL instead of ENOMEM here.  The reason
6812                  * being that returning ENOMEM from an ioctl() has a special
6813                  * connotation; that the user's size value is too small and
6814                  * needs to be expanded to hold the nvlist.  See
6815                  * zcmd_expand_dst_nvlist() for details.
6816                  */
6817                 error = SET_ERROR(EINVAL);      /* User's size too big */
6818
6819         } else if (zc->zc_nvlist_src_size != 0) {
6820                 error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
6821                     zc->zc_iflags, &innvl);
6822                 if (error != 0)
6823                         goto out;
6824         }
6825
6826         /*
6827          * Ensure that all pool/dataset names are valid before we pass down to
6828          * the lower layers.
6829          */
6830         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
6831         switch (vec->zvec_namecheck) {
6832         case POOL_NAME:
6833                 if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
6834                         error = SET_ERROR(EINVAL);
6835                 else
6836                         error = pool_status_check(zc->zc_name,
6837                             vec->zvec_namecheck, vec->zvec_pool_check);
6838                 break;
6839
6840         case DATASET_NAME:
6841                 if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
6842                         error = SET_ERROR(EINVAL);
6843                 else
6844                         error = pool_status_check(zc->zc_name,
6845                             vec->zvec_namecheck, vec->zvec_pool_check);
6846                 break;
6847
6848         case NO_NAME:
6849                 break;
6850         }
6851
6852
6853         if (error == 0) {
6854                 cookie = spl_fstrans_mark();
6855                 error = vec->zvec_secpolicy(zc, innvl, CRED());
6856                 spl_fstrans_unmark(cookie);
6857         }
6858
6859         if (error != 0)
6860                 goto out;
6861
6862         /* legacy ioctls can modify zc_name */
6863         saved_poolname = strdup(zc->zc_name);
6864         if (saved_poolname == NULL) {
6865                 error = SET_ERROR(ENOMEM);
6866                 goto out;
6867         } else {
6868                 saved_poolname[strcspn(saved_poolname, "/@#")] = '\0';
6869         }
6870
6871         if (vec->zvec_func != NULL) {
6872                 nvlist_t *outnvl;
6873                 int puterror = 0;
6874                 spa_t *spa;
6875                 nvlist_t *lognv = NULL;
6876
6877                 ASSERT(vec->zvec_legacy_func == NULL);
6878
6879                 /*
6880                  * Add the innvl to the lognv before calling the func,
6881                  * in case the func changes the innvl.
6882                  */
6883                 if (vec->zvec_allow_log) {
6884                         lognv = fnvlist_alloc();
6885                         fnvlist_add_string(lognv, ZPOOL_HIST_IOCTL,
6886                             vec->zvec_name);
6887                         if (!nvlist_empty(innvl)) {
6888                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_INPUT_NVL,
6889                                     innvl);
6890                         }
6891                 }
6892
6893                 outnvl = fnvlist_alloc();
6894                 cookie = spl_fstrans_mark();
6895                 error = vec->zvec_func(zc->zc_name, innvl, outnvl);
6896                 spl_fstrans_unmark(cookie);
6897
6898                 /*
6899                  * Some commands can partially execute, modify state, and still
6900                  * return an error.  In these cases, attempt to record what
6901                  * was modified.
6902                  */
6903                 if ((error == 0 ||
6904                     (cmd == ZFS_IOC_CHANNEL_PROGRAM && error != EINVAL)) &&
6905                     vec->zvec_allow_log &&
6906                     spa_open(zc->zc_name, &spa, FTAG) == 0) {
6907                         if (!nvlist_empty(outnvl)) {
6908                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_OUTPUT_NVL,
6909                                     outnvl);
6910                         }
6911                         if (error != 0) {
6912                                 fnvlist_add_int64(lognv, ZPOOL_HIST_ERRNO,
6913                                     error);
6914                         }
6915                         (void) spa_history_log_nvl(spa, lognv);
6916                         spa_close(spa, FTAG);
6917                 }
6918                 fnvlist_free(lognv);
6919
6920                 if (!nvlist_empty(outnvl) || zc->zc_nvlist_dst_size != 0) {
6921                         int smusherror = 0;
6922                         if (vec->zvec_smush_outnvlist) {
6923                                 smusherror = nvlist_smush(outnvl,
6924                                     zc->zc_nvlist_dst_size);
6925                         }
6926                         if (smusherror == 0)
6927                                 puterror = put_nvlist(zc, outnvl);
6928                 }
6929
6930                 if (puterror != 0)
6931                         error = puterror;
6932
6933                 nvlist_free(outnvl);
6934         } else {
6935                 cookie = spl_fstrans_mark();
6936                 error = vec->zvec_legacy_func(zc);
6937                 spl_fstrans_unmark(cookie);
6938         }
6939
6940 out:
6941         nvlist_free(innvl);
6942         rc = ddi_copyout(zc, (void *)arg, sizeof (zfs_cmd_t), flag);
6943         if (error == 0 && rc != 0)
6944                 error = SET_ERROR(EFAULT);
6945         if (error == 0 && vec->zvec_allow_log) {
6946                 char *s = tsd_get(zfs_allow_log_key);
6947                 if (s != NULL)
6948                         strfree(s);
6949                 (void) tsd_set(zfs_allow_log_key, saved_poolname);
6950         } else {
6951                 if (saved_poolname != NULL)
6952                         strfree(saved_poolname);
6953         }
6954
6955         kmem_free(zc, sizeof (zfs_cmd_t));
6956         return (-error);
6957 }
6958
6959 #ifdef CONFIG_COMPAT
6960 static long
6961 zfsdev_compat_ioctl(struct file *filp, unsigned cmd, unsigned long arg)
6962 {
6963         return (zfsdev_ioctl(filp, cmd, arg));
6964 }
6965 #else
6966 #define zfsdev_compat_ioctl     NULL
6967 #endif
6968
6969 static const struct file_operations zfsdev_fops = {
6970         .open           = zfsdev_open,
6971         .release        = zfsdev_release,
6972         .unlocked_ioctl = zfsdev_ioctl,
6973         .compat_ioctl   = zfsdev_compat_ioctl,
6974         .owner          = THIS_MODULE,
6975 };
6976
6977 static struct miscdevice zfs_misc = {
6978         .minor          = ZFS_MINOR,
6979         .name           = ZFS_DRIVER,
6980         .fops           = &zfsdev_fops,
6981 };
6982
6983 MODULE_ALIAS_MISCDEV(ZFS_MINOR);
6984 MODULE_ALIAS("devname:zfs");
6985
6986 static int
6987 zfs_attach(void)
6988 {
6989         int error;
6990
6991         mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
6992         zfsdev_state_list = kmem_zalloc(sizeof (zfsdev_state_t), KM_SLEEP);
6993         zfsdev_state_list->zs_minor = -1;
6994
6995         error = misc_register(&zfs_misc);
6996         if (error == -EBUSY) {
6997                 /*
6998                  * Fallback to dynamic minor allocation in the event of a
6999                  * collision with a reserved minor in linux/miscdevice.h.
7000                  * In this case the kernel modules must be manually loaded.
7001                  */
7002                 printk(KERN_INFO "ZFS: misc_register() with static minor %d "
7003                     "failed %d, retrying with MISC_DYNAMIC_MINOR\n",
7004                     ZFS_MINOR, error);
7005
7006                 zfs_misc.minor = MISC_DYNAMIC_MINOR;
7007                 error = misc_register(&zfs_misc);
7008         }
7009
7010         if (error)
7011                 printk(KERN_INFO "ZFS: misc_register() failed %d\n", error);
7012
7013         return (error);
7014 }
7015
7016 static void
7017 zfs_detach(void)
7018 {
7019         zfsdev_state_t *zs, *zsprev = NULL;
7020
7021         misc_deregister(&zfs_misc);
7022         mutex_destroy(&zfsdev_state_lock);
7023
7024         for (zs = zfsdev_state_list; zs != NULL; zs = zs->zs_next) {
7025                 if (zsprev)
7026                         kmem_free(zsprev, sizeof (zfsdev_state_t));
7027                 zsprev = zs;
7028         }
7029         if (zsprev)
7030                 kmem_free(zsprev, sizeof (zfsdev_state_t));
7031 }
7032
7033 static void
7034 zfs_allow_log_destroy(void *arg)
7035 {
7036         char *poolname = arg;
7037
7038         if (poolname != NULL)
7039                 strfree(poolname);
7040 }
7041
7042 #ifdef DEBUG
7043 #define ZFS_DEBUG_STR   " (DEBUG mode)"
7044 #else
7045 #define ZFS_DEBUG_STR   ""
7046 #endif
7047
7048 static int __init
7049 _init(void)
7050 {
7051         int error;
7052
7053         error = -vn_set_pwd("/");
7054         if (error) {
7055                 printk(KERN_NOTICE
7056                     "ZFS: Warning unable to set pwd to '/': %d\n", error);
7057                 return (error);
7058         }
7059
7060         if ((error = -zvol_init()) != 0)
7061                 return (error);
7062
7063         spa_init(FREAD | FWRITE);
7064         zfs_init();
7065
7066         zfs_ioctl_init();
7067
7068         if ((error = zfs_attach()) != 0)
7069                 goto out;
7070
7071         tsd_create(&zfs_fsyncer_key, NULL);
7072         tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
7073         tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
7074
7075         printk(KERN_NOTICE "ZFS: Loaded module v%s-%s%s, "
7076             "ZFS pool version %s, ZFS filesystem version %s\n",
7077             ZFS_META_VERSION, ZFS_META_RELEASE, ZFS_DEBUG_STR,
7078             SPA_VERSION_STRING, ZPL_VERSION_STRING);
7079 #ifndef CONFIG_FS_POSIX_ACL
7080         printk(KERN_NOTICE "ZFS: Posix ACLs disabled by kernel\n");
7081 #endif /* CONFIG_FS_POSIX_ACL */
7082
7083         return (0);
7084
7085 out:
7086         zfs_fini();
7087         spa_fini();
7088         (void) zvol_fini();
7089         printk(KERN_NOTICE "ZFS: Failed to Load ZFS Filesystem v%s-%s%s"
7090             ", rc = %d\n", ZFS_META_VERSION, ZFS_META_RELEASE,
7091             ZFS_DEBUG_STR, error);
7092
7093         return (error);
7094 }
7095
7096 static void __exit
7097 _fini(void)
7098 {
7099         zfs_detach();
7100         zfs_fini();
7101         spa_fini();
7102         zvol_fini();
7103
7104         tsd_destroy(&zfs_fsyncer_key);
7105         tsd_destroy(&rrw_tsd_key);
7106         tsd_destroy(&zfs_allow_log_key);
7107
7108         printk(KERN_NOTICE "ZFS: Unloaded module v%s-%s%s\n",
7109             ZFS_META_VERSION, ZFS_META_RELEASE, ZFS_DEBUG_STR);
7110 }
7111
7112 #ifdef HAVE_SPL
7113 module_init(_init);
7114 module_exit(_fini);
7115
7116 MODULE_DESCRIPTION("ZFS");
7117 MODULE_AUTHOR(ZFS_META_AUTHOR);
7118 MODULE_LICENSE(ZFS_META_LICENSE);
7119 MODULE_VERSION(ZFS_META_VERSION "-" ZFS_META_RELEASE);
7120 #endif /* HAVE_SPL */