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