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