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