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