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