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