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