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