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