]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
Merge ACPICA 20170728.
[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 is not used.
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 *args, nvlist_t *outnvl)
3791 {
3792         zfsvfs_t *zfsvfs;
3793         int error;
3794
3795         if (getzfsvfs(fsname, &zfsvfs) == 0) {
3796                 dsl_dataset_t *ds;
3797
3798                 ds = dmu_objset_ds(zfsvfs->z_os);
3799                 error = zfs_suspend_fs(zfsvfs);
3800                 if (error == 0) {
3801                         int resume_err;
3802
3803                         error = dsl_dataset_rollback(fsname, zfsvfs, outnvl);
3804                         resume_err = zfs_resume_fs(zfsvfs, ds);
3805                         error = error ? error : resume_err;
3806                 }
3807 #ifdef illumos
3808                 VFS_RELE(zfsvfs->z_vfs);
3809 #else
3810                 vfs_unbusy(zfsvfs->z_vfs);
3811 #endif
3812         } else {
3813                 error = dsl_dataset_rollback(fsname, NULL, outnvl);
3814         }
3815         return (error);
3816 }
3817
3818 static int
3819 recursive_unmount(const char *fsname, void *arg)
3820 {
3821         const char *snapname = arg;
3822         char fullname[ZFS_MAX_DATASET_NAME_LEN];
3823
3824         (void) snprintf(fullname, sizeof (fullname), "%s@%s", fsname, snapname);
3825         return (zfs_unmount_snap(fullname));
3826 }
3827
3828 /*
3829  * inputs:
3830  * zc_name      old name of dataset
3831  * zc_value     new name of dataset
3832  * zc_cookie    recursive flag (only valid for snapshots)
3833  *
3834  * outputs:     none
3835  */
3836 static int
3837 zfs_ioc_rename(zfs_cmd_t *zc)
3838 {
3839         boolean_t recursive = zc->zc_cookie & 1;
3840         char *at;
3841         boolean_t allow_mounted = B_TRUE;
3842
3843 #ifdef __FreeBSD__
3844         allow_mounted = (zc->zc_cookie & 2) != 0;
3845 #endif
3846
3847         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3848         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3849             strchr(zc->zc_value, '%'))
3850                 return (SET_ERROR(EINVAL));
3851
3852         at = strchr(zc->zc_name, '@');
3853         if (at != NULL) {
3854                 /* snaps must be in same fs */
3855                 int error;
3856
3857                 if (strncmp(zc->zc_name, zc->zc_value, at - zc->zc_name + 1))
3858                         return (SET_ERROR(EXDEV));
3859                 *at = '\0';
3860                 if (zc->zc_objset_type == DMU_OST_ZFS && !allow_mounted) {
3861                         error = dmu_objset_find(zc->zc_name,
3862                             recursive_unmount, at + 1,
3863                             recursive ? DS_FIND_CHILDREN : 0);
3864                         if (error != 0) {
3865                                 *at = '@';
3866                                 return (error);
3867                         }
3868                 }
3869                 error = dsl_dataset_rename_snapshot(zc->zc_name,
3870                     at + 1, strchr(zc->zc_value, '@') + 1, recursive);
3871                 *at = '@';
3872
3873                 return (error);
3874         } else {
3875 #ifdef illumos
3876                 if (zc->zc_objset_type == DMU_OST_ZVOL)
3877                         (void) zvol_remove_minor(zc->zc_name);
3878 #endif
3879                 return (dsl_dir_rename(zc->zc_name, zc->zc_value));
3880         }
3881 }
3882
3883 static int
3884 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3885 {
3886         const char *propname = nvpair_name(pair);
3887         boolean_t issnap = (strchr(dsname, '@') != NULL);
3888         zfs_prop_t prop = zfs_name_to_prop(propname);
3889         uint64_t intval;
3890         int err;
3891
3892         if (prop == ZPROP_INVAL) {
3893                 if (zfs_prop_user(propname)) {
3894                         if (err = zfs_secpolicy_write_perms(dsname,
3895                             ZFS_DELEG_PERM_USERPROP, cr))
3896                                 return (err);
3897                         return (0);
3898                 }
3899
3900                 if (!issnap && zfs_prop_userquota(propname)) {
3901                         const char *perm = NULL;
3902                         const char *uq_prefix =
3903                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3904                         const char *gq_prefix =
3905                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3906
3907                         if (strncmp(propname, uq_prefix,
3908                             strlen(uq_prefix)) == 0) {
3909                                 perm = ZFS_DELEG_PERM_USERQUOTA;
3910                         } else if (strncmp(propname, gq_prefix,
3911                             strlen(gq_prefix)) == 0) {
3912                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
3913                         } else {
3914                                 /* USERUSED and GROUPUSED are read-only */
3915                                 return (SET_ERROR(EINVAL));
3916                         }
3917
3918                         if (err = zfs_secpolicy_write_perms(dsname, perm, cr))
3919                                 return (err);
3920                         return (0);
3921                 }
3922
3923                 return (SET_ERROR(EINVAL));
3924         }
3925
3926         if (issnap)
3927                 return (SET_ERROR(EINVAL));
3928
3929         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3930                 /*
3931                  * dsl_prop_get_all_impl() returns properties in this
3932                  * format.
3933                  */
3934                 nvlist_t *attrs;
3935                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3936                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3937                     &pair) == 0);
3938         }
3939
3940         /*
3941          * Check that this value is valid for this pool version
3942          */
3943         switch (prop) {
3944         case ZFS_PROP_COMPRESSION:
3945                 /*
3946                  * If the user specified gzip compression, make sure
3947                  * the SPA supports it. We ignore any errors here since
3948                  * we'll catch them later.
3949                  */
3950                 if (nvpair_value_uint64(pair, &intval) == 0) {
3951                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
3952                             intval <= ZIO_COMPRESS_GZIP_9 &&
3953                             zfs_earlier_version(dsname,
3954                             SPA_VERSION_GZIP_COMPRESSION)) {
3955                                 return (SET_ERROR(ENOTSUP));
3956                         }
3957
3958                         if (intval == ZIO_COMPRESS_ZLE &&
3959                             zfs_earlier_version(dsname,
3960                             SPA_VERSION_ZLE_COMPRESSION))
3961                                 return (SET_ERROR(ENOTSUP));
3962
3963                         if (intval == ZIO_COMPRESS_LZ4) {
3964                                 spa_t *spa;
3965
3966                                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
3967                                         return (err);
3968
3969                                 if (!spa_feature_is_enabled(spa,
3970                                     SPA_FEATURE_LZ4_COMPRESS)) {
3971                                         spa_close(spa, FTAG);
3972                                         return (SET_ERROR(ENOTSUP));
3973                                 }
3974                                 spa_close(spa, FTAG);
3975                         }
3976
3977                         /*
3978                          * If this is a bootable dataset then
3979                          * verify that the compression algorithm
3980                          * is supported for booting. We must return
3981                          * something other than ENOTSUP since it
3982                          * implies a downrev pool version.
3983                          */
3984                         if (zfs_is_bootfs(dsname) &&
3985                             !BOOTFS_COMPRESS_VALID(intval)) {
3986                                 return (SET_ERROR(ERANGE));
3987                         }
3988                 }
3989                 break;
3990
3991         case ZFS_PROP_COPIES:
3992                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
3993                         return (SET_ERROR(ENOTSUP));
3994                 break;
3995
3996         case ZFS_PROP_RECORDSIZE:
3997                 /* Record sizes above 128k need the feature to be enabled */
3998                 if (nvpair_value_uint64(pair, &intval) == 0 &&
3999                     intval > SPA_OLD_MAXBLOCKSIZE) {
4000                         spa_t *spa;
4001
4002                         /*
4003                          * We don't allow setting the property above 1MB,
4004                          * unless the tunable has been changed.
4005                          */
4006                         if (intval > zfs_max_recordsize ||
4007                             intval > SPA_MAXBLOCKSIZE)
4008                                 return (SET_ERROR(ERANGE));
4009
4010                         if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4011                                 return (err);
4012
4013                         if (!spa_feature_is_enabled(spa,
4014                             SPA_FEATURE_LARGE_BLOCKS)) {
4015                                 spa_close(spa, FTAG);
4016                                 return (SET_ERROR(ENOTSUP));
4017                         }
4018                         spa_close(spa, FTAG);
4019                 }
4020                 break;
4021
4022         case ZFS_PROP_SHARESMB:
4023                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
4024                         return (SET_ERROR(ENOTSUP));
4025                 break;
4026
4027         case ZFS_PROP_ACLINHERIT:
4028                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
4029                     nvpair_value_uint64(pair, &intval) == 0) {
4030                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
4031                             zfs_earlier_version(dsname,
4032                             SPA_VERSION_PASSTHROUGH_X))
4033                                 return (SET_ERROR(ENOTSUP));
4034                 }
4035                 break;
4036
4037         case ZFS_PROP_CHECKSUM:
4038         case ZFS_PROP_DEDUP:
4039         {
4040                 spa_feature_t feature;
4041                 spa_t *spa;
4042
4043                 /* dedup feature version checks */
4044                 if (prop == ZFS_PROP_DEDUP &&
4045                     zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
4046                         return (SET_ERROR(ENOTSUP));
4047
4048                 if (nvpair_value_uint64(pair, &intval) != 0)
4049                         return (SET_ERROR(EINVAL));
4050
4051                 /* check prop value is enabled in features */
4052                 feature = zio_checksum_to_feature(intval & ZIO_CHECKSUM_MASK);
4053                 if (feature == SPA_FEATURE_NONE)
4054                         break;
4055
4056                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4057                         return (err);
4058                 /*
4059                  * Salted checksums are not supported on root pools.
4060                  */
4061                 if (spa_bootfs(spa) != 0 &&
4062                     intval < ZIO_CHECKSUM_FUNCTIONS &&
4063                     (zio_checksum_table[intval].ci_flags &
4064                     ZCHECKSUM_FLAG_SALTED)) {
4065                         spa_close(spa, FTAG);
4066                         return (SET_ERROR(ERANGE));
4067                 }
4068                 if (!spa_feature_is_enabled(spa, feature)) {
4069                         spa_close(spa, FTAG);
4070                         return (SET_ERROR(ENOTSUP));
4071                 }
4072                 spa_close(spa, FTAG);
4073                 break;
4074         }
4075         }
4076
4077         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
4078 }
4079
4080 /*
4081  * Checks for a race condition to make sure we don't increment a feature flag
4082  * multiple times.
4083  */
4084 static int
4085 zfs_prop_activate_feature_check(void *arg, dmu_tx_t *tx)
4086 {
4087         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4088         spa_feature_t *featurep = arg;
4089
4090         if (!spa_feature_is_active(spa, *featurep))
4091                 return (0);
4092         else
4093                 return (SET_ERROR(EBUSY));
4094 }
4095
4096 /*
4097  * The callback invoked on feature activation in the sync task caused by
4098  * zfs_prop_activate_feature.
4099  */
4100 static void
4101 zfs_prop_activate_feature_sync(void *arg, dmu_tx_t *tx)
4102 {
4103         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4104         spa_feature_t *featurep = arg;
4105
4106         spa_feature_incr(spa, *featurep, tx);
4107 }
4108
4109 /*
4110  * Activates a feature on a pool in response to a property setting. This
4111  * creates a new sync task which modifies the pool to reflect the feature
4112  * as being active.
4113  */
4114 static int
4115 zfs_prop_activate_feature(spa_t *spa, spa_feature_t feature)
4116 {
4117         int err;
4118
4119         /* EBUSY here indicates that the feature is already active */
4120         err = dsl_sync_task(spa_name(spa),
4121             zfs_prop_activate_feature_check, zfs_prop_activate_feature_sync,
4122             &feature, 2, ZFS_SPACE_CHECK_RESERVED);
4123
4124         if (err != 0 && err != EBUSY)
4125                 return (err);
4126         else
4127                 return (0);
4128 }
4129
4130 /*
4131  * Removes properties from the given props list that fail permission checks
4132  * needed to clear them and to restore them in case of a receive error. For each
4133  * property, make sure we have both set and inherit permissions.
4134  *
4135  * Returns the first error encountered if any permission checks fail. If the
4136  * caller provides a non-NULL errlist, it also gives the complete list of names
4137  * of all the properties that failed a permission check along with the
4138  * corresponding error numbers. The caller is responsible for freeing the
4139  * returned errlist.
4140  *
4141  * If every property checks out successfully, zero is returned and the list
4142  * pointed at by errlist is NULL.
4143  */
4144 static int
4145 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
4146 {
4147         zfs_cmd_t *zc;
4148         nvpair_t *pair, *next_pair;
4149         nvlist_t *errors;
4150         int err, rv = 0;
4151
4152         if (props == NULL)
4153                 return (0);
4154
4155         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4156
4157         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
4158         (void) strcpy(zc->zc_name, dataset);
4159         pair = nvlist_next_nvpair(props, NULL);
4160         while (pair != NULL) {
4161                 next_pair = nvlist_next_nvpair(props, pair);
4162
4163                 (void) strcpy(zc->zc_value, nvpair_name(pair));
4164                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
4165                     (err = zfs_secpolicy_inherit_prop(zc, NULL, CRED())) != 0) {
4166                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
4167                         VERIFY(nvlist_add_int32(errors,
4168                             zc->zc_value, err) == 0);
4169                 }
4170                 pair = next_pair;
4171         }
4172         kmem_free(zc, sizeof (zfs_cmd_t));
4173
4174         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
4175                 nvlist_free(errors);
4176                 errors = NULL;
4177         } else {
4178                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
4179         }
4180
4181         if (errlist == NULL)
4182                 nvlist_free(errors);
4183         else
4184                 *errlist = errors;
4185
4186         return (rv);
4187 }
4188
4189 static boolean_t
4190 propval_equals(nvpair_t *p1, nvpair_t *p2)
4191 {
4192         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
4193                 /* dsl_prop_get_all_impl() format */
4194                 nvlist_t *attrs;
4195                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
4196                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4197                     &p1) == 0);
4198         }
4199
4200         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
4201                 nvlist_t *attrs;
4202                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
4203                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4204                     &p2) == 0);
4205         }
4206
4207         if (nvpair_type(p1) != nvpair_type(p2))
4208                 return (B_FALSE);
4209
4210         if (nvpair_type(p1) == DATA_TYPE_STRING) {
4211                 char *valstr1, *valstr2;
4212
4213                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
4214                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
4215                 return (strcmp(valstr1, valstr2) == 0);
4216         } else {
4217                 uint64_t intval1, intval2;
4218
4219                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
4220                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
4221                 return (intval1 == intval2);
4222         }
4223 }
4224
4225 /*
4226  * Remove properties from props if they are not going to change (as determined
4227  * by comparison with origprops). Remove them from origprops as well, since we
4228  * do not need to clear or restore properties that won't change.
4229  */
4230 static void
4231 props_reduce(nvlist_t *props, nvlist_t *origprops)
4232 {
4233         nvpair_t *pair, *next_pair;
4234
4235         if (origprops == NULL)
4236                 return; /* all props need to be received */
4237
4238         pair = nvlist_next_nvpair(props, NULL);
4239         while (pair != NULL) {
4240                 const char *propname = nvpair_name(pair);
4241                 nvpair_t *match;
4242
4243                 next_pair = nvlist_next_nvpair(props, pair);
4244
4245                 if ((nvlist_lookup_nvpair(origprops, propname,
4246                     &match) != 0) || !propval_equals(pair, match))
4247                         goto next; /* need to set received value */
4248
4249                 /* don't clear the existing received value */
4250                 (void) nvlist_remove_nvpair(origprops, match);
4251                 /* don't bother receiving the property */
4252                 (void) nvlist_remove_nvpair(props, pair);
4253 next:
4254                 pair = next_pair;
4255         }
4256 }
4257
4258 /*
4259  * Extract properties that cannot be set PRIOR to the receipt of a dataset.
4260  * For example, refquota cannot be set until after the receipt of a dataset,
4261  * because in replication streams, an older/earlier snapshot may exceed the
4262  * refquota.  We want to receive the older/earlier snapshot, but setting
4263  * refquota pre-receipt will set the dsl's ACTUAL quota, which will prevent
4264  * the older/earlier snapshot from being received (with EDQUOT).
4265  *
4266  * The ZFS test "zfs_receive_011_pos" demonstrates such a scenario.
4267  *
4268  * libzfs will need to be judicious handling errors encountered by props
4269  * extracted by this function.
4270  */
4271 static nvlist_t *
4272 extract_delay_props(nvlist_t *props)
4273 {
4274         nvlist_t *delayprops;
4275         nvpair_t *nvp, *tmp;
4276         static const zfs_prop_t delayable[] = { ZFS_PROP_REFQUOTA, 0 };
4277         int i;
4278
4279         VERIFY(nvlist_alloc(&delayprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4280
4281         for (nvp = nvlist_next_nvpair(props, NULL); nvp != NULL;
4282             nvp = nvlist_next_nvpair(props, nvp)) {
4283                 /*
4284                  * strcmp() is safe because zfs_prop_to_name() always returns
4285                  * a bounded string.
4286                  */
4287                 for (i = 0; delayable[i] != 0; i++) {
4288                         if (strcmp(zfs_prop_to_name(delayable[i]),
4289                             nvpair_name(nvp)) == 0) {
4290                                 break;
4291                         }
4292                 }
4293                 if (delayable[i] != 0) {
4294                         tmp = nvlist_prev_nvpair(props, nvp);
4295                         VERIFY(nvlist_add_nvpair(delayprops, nvp) == 0);
4296                         VERIFY(nvlist_remove_nvpair(props, nvp) == 0);
4297                         nvp = tmp;
4298                 }
4299         }
4300
4301         if (nvlist_empty(delayprops)) {
4302                 nvlist_free(delayprops);
4303                 delayprops = NULL;
4304         }
4305         return (delayprops);
4306 }
4307
4308 #ifdef  DEBUG
4309 static boolean_t zfs_ioc_recv_inject_err;
4310 #endif
4311
4312 /*
4313  * inputs:
4314  * zc_name              name of containing filesystem
4315  * zc_nvlist_src{_size} nvlist of properties to apply
4316  * zc_value             name of snapshot to create
4317  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
4318  * zc_cookie            file descriptor to recv from
4319  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
4320  * zc_guid              force flag
4321  * zc_cleanup_fd        cleanup-on-exit file descriptor
4322  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
4323  * zc_resumable         if data is incomplete assume sender will resume
4324  *
4325  * outputs:
4326  * zc_cookie            number of bytes read
4327  * zc_nvlist_dst{_size} error for each unapplied received property
4328  * zc_obj               zprop_errflags_t
4329  * zc_action_handle     handle for this guid/ds mapping
4330  */
4331 static int
4332 zfs_ioc_recv(zfs_cmd_t *zc)
4333 {
4334         file_t *fp;
4335         dmu_recv_cookie_t drc;
4336         boolean_t force = (boolean_t)zc->zc_guid;
4337         int fd;
4338         int error = 0;
4339         int props_error = 0;
4340         nvlist_t *errors;
4341         offset_t off;
4342         nvlist_t *props = NULL; /* sent properties */
4343         nvlist_t *origprops = NULL; /* existing properties */
4344         nvlist_t *delayprops = NULL; /* sent properties applied post-receive */
4345         char *origin = NULL;
4346         char *tosnap;
4347         char tofs[ZFS_MAX_DATASET_NAME_LEN];
4348         cap_rights_t rights;
4349         boolean_t first_recvd_props = B_FALSE;
4350
4351         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
4352             strchr(zc->zc_value, '@') == NULL ||
4353             strchr(zc->zc_value, '%'))
4354                 return (SET_ERROR(EINVAL));
4355
4356         (void) strcpy(tofs, zc->zc_value);
4357         tosnap = strchr(tofs, '@');
4358         *tosnap++ = '\0';
4359
4360         if (zc->zc_nvlist_src != 0 &&
4361             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
4362             zc->zc_iflags, &props)) != 0)
4363                 return (error);
4364
4365         fd = zc->zc_cookie;
4366 #ifdef illumos
4367         fp = getf(fd);
4368 #else
4369         fget_read(curthread, fd, cap_rights_init(&rights, CAP_PREAD), &fp);
4370 #endif
4371         if (fp == NULL) {
4372                 nvlist_free(props);
4373                 return (SET_ERROR(EBADF));
4374         }
4375
4376         errors = fnvlist_alloc();
4377
4378         if (zc->zc_string[0])
4379                 origin = zc->zc_string;
4380
4381         error = dmu_recv_begin(tofs, tosnap,
4382             &zc->zc_begin_record, force, zc->zc_resumable, origin, &drc);
4383         if (error != 0)
4384                 goto out;
4385
4386         /*
4387          * Set properties before we receive the stream so that they are applied
4388          * to the new data. Note that we must call dmu_recv_stream() if
4389          * dmu_recv_begin() succeeds.
4390          */
4391         if (props != NULL && !drc.drc_newfs) {
4392                 if (spa_version(dsl_dataset_get_spa(drc.drc_ds)) >=
4393                     SPA_VERSION_RECVD_PROPS &&
4394                     !dsl_prop_get_hasrecvd(tofs))
4395                         first_recvd_props = B_TRUE;
4396
4397                 /*
4398                  * If new received properties are supplied, they are to
4399                  * completely replace the existing received properties, so stash
4400                  * away the existing ones.
4401                  */
4402                 if (dsl_prop_get_received(tofs, &origprops) == 0) {
4403                         nvlist_t *errlist = NULL;
4404                         /*
4405                          * Don't bother writing a property if its value won't
4406                          * change (and avoid the unnecessary security checks).
4407                          *
4408                          * The first receive after SPA_VERSION_RECVD_PROPS is a
4409                          * special case where we blow away all local properties
4410                          * regardless.
4411                          */
4412                         if (!first_recvd_props)
4413                                 props_reduce(props, origprops);
4414                         if (zfs_check_clearable(tofs, origprops, &errlist) != 0)
4415                                 (void) nvlist_merge(errors, errlist, 0);
4416                         nvlist_free(errlist);
4417
4418                         if (clear_received_props(tofs, origprops,
4419                             first_recvd_props ? NULL : props) != 0)
4420                                 zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4421                 } else {
4422                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4423                 }
4424         }
4425
4426         if (props != NULL) {
4427                 props_error = dsl_prop_set_hasrecvd(tofs);
4428
4429                 if (props_error == 0) {
4430                         delayprops = extract_delay_props(props);
4431                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4432                             props, errors);
4433                 }
4434         }
4435
4436         off = fp->f_offset;
4437         error = dmu_recv_stream(&drc, fp, &off, zc->zc_cleanup_fd,
4438             &zc->zc_action_handle);
4439
4440         if (error == 0) {
4441                 zfsvfs_t *zfsvfs = NULL;
4442
4443                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
4444                         /* online recv */
4445                         dsl_dataset_t *ds;
4446                         int end_err;
4447
4448                         ds = dmu_objset_ds(zfsvfs->z_os);
4449                         error = zfs_suspend_fs(zfsvfs);
4450                         /*
4451                          * If the suspend fails, then the recv_end will
4452                          * likely also fail, and clean up after itself.
4453                          */
4454                         end_err = dmu_recv_end(&drc, zfsvfs);
4455                         if (error == 0)
4456                                 error = zfs_resume_fs(zfsvfs, ds);
4457                         error = error ? error : end_err;
4458 #ifdef illumos
4459                         VFS_RELE(zfsvfs->z_vfs);
4460 #else
4461                         vfs_unbusy(zfsvfs->z_vfs);
4462 #endif
4463                 } else {
4464                         error = dmu_recv_end(&drc, NULL);
4465                 }
4466
4467                 /* Set delayed properties now, after we're done receiving. */
4468                 if (delayprops != NULL && error == 0) {
4469                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4470                             delayprops, errors);
4471                 }
4472         }
4473
4474         if (delayprops != NULL) {
4475                 /*
4476                  * Merge delayed props back in with initial props, in case
4477                  * we're DEBUG and zfs_ioc_recv_inject_err is set (which means
4478                  * we have to make sure clear_received_props() includes
4479                  * the delayed properties).
4480                  *
4481                  * Since zfs_ioc_recv_inject_err is only in DEBUG kernels,
4482                  * using ASSERT() will be just like a VERIFY.
4483                  */
4484                 ASSERT(nvlist_merge(props, delayprops, 0) == 0);
4485                 nvlist_free(delayprops);
4486         }
4487
4488         /*
4489          * Now that all props, initial and delayed, are set, report the prop
4490          * errors to the caller.
4491          */
4492         if (zc->zc_nvlist_dst_size != 0 &&
4493             (nvlist_smush(errors, zc->zc_nvlist_dst_size) != 0 ||
4494             put_nvlist(zc, errors) != 0)) {
4495                 /*
4496                  * Caller made zc->zc_nvlist_dst less than the minimum expected
4497                  * size or supplied an invalid address.
4498                  */
4499                 props_error = SET_ERROR(EINVAL);
4500         }
4501
4502         zc->zc_cookie = off - fp->f_offset;
4503         if (off >= 0 && off <= MAXOFFSET_T)
4504                 fp->f_offset = off;
4505
4506 #ifdef  DEBUG
4507         if (zfs_ioc_recv_inject_err) {
4508                 zfs_ioc_recv_inject_err = B_FALSE;
4509                 error = 1;
4510         }
4511 #endif
4512
4513 #ifdef __FreeBSD__
4514         if (error == 0)
4515                 zvol_create_minors(tofs);
4516 #endif
4517
4518         /*
4519          * On error, restore the original props.
4520          */
4521         if (error != 0 && props != NULL && !drc.drc_newfs) {
4522                 if (clear_received_props(tofs, props, NULL) != 0) {
4523                         /*
4524                          * We failed to clear the received properties.
4525                          * Since we may have left a $recvd value on the
4526                          * system, we can't clear the $hasrecvd flag.
4527                          */
4528                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4529                 } else if (first_recvd_props) {
4530                         dsl_prop_unset_hasrecvd(tofs);
4531                 }
4532
4533                 if (origprops == NULL && !drc.drc_newfs) {
4534                         /* We failed to stash the original properties. */
4535                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4536                 }
4537
4538                 /*
4539                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
4540                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
4541                  * explictly if we're restoring local properties cleared in the
4542                  * first new-style receive.
4543                  */
4544                 if (origprops != NULL &&
4545                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
4546                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
4547                     origprops, NULL) != 0) {
4548                         /*
4549                          * We stashed the original properties but failed to
4550                          * restore them.
4551                          */
4552                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4553                 }
4554         }
4555 out:
4556         nvlist_free(props);
4557         nvlist_free(origprops);
4558         nvlist_free(errors);
4559         releasef(fd);
4560
4561         if (error == 0)
4562                 error = props_error;
4563
4564         return (error);
4565 }
4566
4567 /*
4568  * inputs:
4569  * zc_name      name of snapshot to send
4570  * zc_cookie    file descriptor to send stream to
4571  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
4572  * zc_sendobj   objsetid of snapshot to send
4573  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
4574  * zc_guid      if set, estimate size of stream only.  zc_cookie is ignored.
4575  *              output size in zc_objset_type.
4576  * zc_flags     lzc_send_flags
4577  *
4578  * outputs:
4579  * zc_objset_type       estimated size, if zc_guid is set
4580  */
4581 static int
4582 zfs_ioc_send(zfs_cmd_t *zc)
4583 {
4584         int error;
4585         offset_t off;
4586         boolean_t estimate = (zc->zc_guid != 0);
4587         boolean_t embedok = (zc->zc_flags & 0x1);
4588         boolean_t large_block_ok = (zc->zc_flags & 0x2);
4589         boolean_t compressok = (zc->zc_flags & 0x4);
4590
4591         if (zc->zc_obj != 0) {
4592                 dsl_pool_t *dp;
4593                 dsl_dataset_t *tosnap;
4594
4595                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4596                 if (error != 0)
4597                         return (error);
4598
4599                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4600                 if (error != 0) {
4601                         dsl_pool_rele(dp, FTAG);
4602                         return (error);
4603                 }
4604
4605                 if (dsl_dir_is_clone(tosnap->ds_dir))
4606                         zc->zc_fromobj =
4607                             dsl_dir_phys(tosnap->ds_dir)->dd_origin_obj;
4608                 dsl_dataset_rele(tosnap, FTAG);
4609                 dsl_pool_rele(dp, FTAG);
4610         }
4611
4612         if (estimate) {
4613                 dsl_pool_t *dp;
4614                 dsl_dataset_t *tosnap;
4615                 dsl_dataset_t *fromsnap = NULL;
4616
4617                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4618                 if (error != 0)
4619                         return (error);
4620
4621                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4622                 if (error != 0) {
4623                         dsl_pool_rele(dp, FTAG);
4624                         return (error);
4625                 }
4626
4627                 if (zc->zc_fromobj != 0) {
4628                         error = dsl_dataset_hold_obj(dp, zc->zc_fromobj,
4629                             FTAG, &fromsnap);
4630                         if (error != 0) {
4631                                 dsl_dataset_rele(tosnap, FTAG);
4632                                 dsl_pool_rele(dp, FTAG);
4633                                 return (error);
4634                         }
4635                 }
4636
4637                 error = dmu_send_estimate(tosnap, fromsnap, compressok,
4638                     &zc->zc_objset_type);
4639
4640                 if (fromsnap != NULL)
4641                         dsl_dataset_rele(fromsnap, FTAG);
4642                 dsl_dataset_rele(tosnap, FTAG);
4643                 dsl_pool_rele(dp, FTAG);
4644         } else {
4645                 file_t *fp;
4646                 cap_rights_t rights;
4647
4648 #ifdef illumos
4649                 fp = getf(zc->zc_cookie);
4650 #else
4651                 fget_write(curthread, zc->zc_cookie,
4652                     cap_rights_init(&rights, CAP_WRITE), &fp);
4653 #endif
4654                 if (fp == NULL)
4655                         return (SET_ERROR(EBADF));
4656
4657                 off = fp->f_offset;
4658                 error = dmu_send_obj(zc->zc_name, zc->zc_sendobj,
4659                     zc->zc_fromobj, embedok, large_block_ok, compressok,
4660 #ifdef illumos
4661                     zc->zc_cookie, fp->f_vnode, &off);
4662 #else
4663                     zc->zc_cookie, fp, &off);
4664 #endif
4665
4666                 if (off >= 0 && off <= MAXOFFSET_T)
4667                         fp->f_offset = off;
4668                 releasef(zc->zc_cookie);
4669         }
4670         return (error);
4671 }
4672
4673 /*
4674  * inputs:
4675  * zc_name      name of snapshot on which to report progress
4676  * zc_cookie    file descriptor of send stream
4677  *
4678  * outputs:
4679  * zc_cookie    number of bytes written in send stream thus far
4680  */
4681 static int
4682 zfs_ioc_send_progress(zfs_cmd_t *zc)
4683 {
4684         dsl_pool_t *dp;
4685         dsl_dataset_t *ds;
4686         dmu_sendarg_t *dsp = NULL;
4687         int error;
4688
4689         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4690         if (error != 0)
4691                 return (error);
4692
4693         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4694         if (error != 0) {
4695                 dsl_pool_rele(dp, FTAG);
4696                 return (error);
4697         }
4698
4699         mutex_enter(&ds->ds_sendstream_lock);
4700
4701         /*
4702          * Iterate over all the send streams currently active on this dataset.
4703          * If there's one which matches the specified file descriptor _and_ the
4704          * stream was started by the current process, return the progress of
4705          * that stream.
4706          */
4707         for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
4708             dsp = list_next(&ds->ds_sendstreams, dsp)) {
4709                 if (dsp->dsa_outfd == zc->zc_cookie &&
4710                     dsp->dsa_proc == curproc)
4711                         break;
4712         }
4713
4714         if (dsp != NULL)
4715                 zc->zc_cookie = *(dsp->dsa_off);
4716         else
4717                 error = SET_ERROR(ENOENT);
4718
4719         mutex_exit(&ds->ds_sendstream_lock);
4720         dsl_dataset_rele(ds, FTAG);
4721         dsl_pool_rele(dp, FTAG);
4722         return (error);
4723 }
4724
4725 static int
4726 zfs_ioc_inject_fault(zfs_cmd_t *zc)
4727 {
4728         int id, error;
4729
4730         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
4731             &zc->zc_inject_record);
4732
4733         if (error == 0)
4734                 zc->zc_guid = (uint64_t)id;
4735
4736         return (error);
4737 }
4738
4739 static int
4740 zfs_ioc_clear_fault(zfs_cmd_t *zc)
4741 {
4742         return (zio_clear_fault((int)zc->zc_guid));
4743 }
4744
4745 static int
4746 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
4747 {
4748         int id = (int)zc->zc_guid;
4749         int error;
4750
4751         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
4752             &zc->zc_inject_record);
4753
4754         zc->zc_guid = id;
4755
4756         return (error);
4757 }
4758
4759 static int
4760 zfs_ioc_error_log(zfs_cmd_t *zc)
4761 {
4762         spa_t *spa;
4763         int error;
4764         size_t count = (size_t)zc->zc_nvlist_dst_size;
4765
4766         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
4767                 return (error);
4768
4769         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
4770             &count);
4771         if (error == 0)
4772                 zc->zc_nvlist_dst_size = count;
4773         else
4774                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
4775
4776         spa_close(spa, FTAG);
4777
4778         return (error);
4779 }
4780
4781 static int
4782 zfs_ioc_clear(zfs_cmd_t *zc)
4783 {
4784         spa_t *spa;
4785         vdev_t *vd;
4786         int error;
4787
4788         /*
4789          * On zpool clear we also fix up missing slogs
4790          */
4791         mutex_enter(&spa_namespace_lock);
4792         spa = spa_lookup(zc->zc_name);
4793         if (spa == NULL) {
4794                 mutex_exit(&spa_namespace_lock);
4795                 return (SET_ERROR(EIO));
4796         }
4797         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
4798                 /* we need to let spa_open/spa_load clear the chains */
4799                 spa_set_log_state(spa, SPA_LOG_CLEAR);
4800         }
4801         spa->spa_last_open_failed = 0;
4802         mutex_exit(&spa_namespace_lock);
4803
4804         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
4805                 error = spa_open(zc->zc_name, &spa, FTAG);
4806         } else {
4807                 nvlist_t *policy;
4808                 nvlist_t *config = NULL;
4809
4810                 if (zc->zc_nvlist_src == 0)
4811                         return (SET_ERROR(EINVAL));
4812
4813                 if ((error = get_nvlist(zc->zc_nvlist_src,
4814                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
4815                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
4816                             policy, &config);
4817                         if (config != NULL) {
4818                                 int err;
4819
4820                                 if ((err = put_nvlist(zc, config)) != 0)
4821                                         error = err;
4822                                 nvlist_free(config);
4823                         }
4824                         nvlist_free(policy);
4825                 }
4826         }
4827
4828         if (error != 0)
4829                 return (error);
4830
4831         spa_vdev_state_enter(spa, SCL_NONE);
4832
4833         if (zc->zc_guid == 0) {
4834                 vd = NULL;
4835         } else {
4836                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
4837                 if (vd == NULL) {
4838                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
4839                         spa_close(spa, FTAG);
4840                         return (SET_ERROR(ENODEV));
4841                 }
4842         }
4843
4844         vdev_clear(spa, vd);
4845
4846         (void) spa_vdev_state_exit(spa, NULL, 0);
4847
4848         /*
4849          * Resume any suspended I/Os.
4850          */
4851         if (zio_resume(spa) != 0)
4852                 error = SET_ERROR(EIO);
4853
4854         spa_close(spa, FTAG);
4855
4856         return (error);
4857 }
4858
4859 static int
4860 zfs_ioc_pool_reopen(zfs_cmd_t *zc)
4861 {
4862         spa_t *spa;
4863         int error;
4864
4865         error = spa_open(zc->zc_name, &spa, FTAG);
4866         if (error != 0)
4867                 return (error);
4868
4869         spa_vdev_state_enter(spa, SCL_NONE);
4870
4871         /*
4872          * If a resilver is already in progress then set the
4873          * spa_scrub_reopen flag to B_TRUE so that we don't restart
4874          * the scan as a side effect of the reopen. Otherwise, let
4875          * vdev_open() decided if a resilver is required.
4876          */
4877         spa->spa_scrub_reopen = dsl_scan_resilvering(spa->spa_dsl_pool);
4878         vdev_reopen(spa->spa_root_vdev);
4879         spa->spa_scrub_reopen = B_FALSE;
4880
4881         (void) spa_vdev_state_exit(spa, NULL, 0);
4882         spa_close(spa, FTAG);
4883         return (0);
4884 }
4885 /*
4886  * inputs:
4887  * zc_name      name of filesystem
4888  *
4889  * outputs:
4890  * zc_string    name of conflicting snapshot, if there is one
4891  */
4892 static int
4893 zfs_ioc_promote(zfs_cmd_t *zc)
4894 {
4895         dsl_pool_t *dp;
4896         dsl_dataset_t *ds, *ods;
4897         char origin[ZFS_MAX_DATASET_NAME_LEN];
4898         char *cp;
4899         int error;
4900
4901         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4902         if (error != 0)
4903                 return (error);
4904
4905         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4906         if (error != 0) {
4907                 dsl_pool_rele(dp, FTAG);
4908                 return (error);
4909         }
4910
4911         if (!dsl_dir_is_clone(ds->ds_dir)) {
4912                 dsl_dataset_rele(ds, FTAG);
4913                 dsl_pool_rele(dp, FTAG);
4914                 return (SET_ERROR(EINVAL));
4915         }
4916
4917         error = dsl_dataset_hold_obj(dp,
4918             dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &ods);
4919         if (error != 0) {
4920                 dsl_dataset_rele(ds, FTAG);
4921                 dsl_pool_rele(dp, FTAG);
4922                 return (error);
4923         }
4924
4925         dsl_dataset_name(ods, origin);
4926         dsl_dataset_rele(ods, FTAG);
4927         dsl_dataset_rele(ds, FTAG);
4928         dsl_pool_rele(dp, FTAG);
4929
4930         /*
4931          * We don't need to unmount *all* the origin fs's snapshots, but
4932          * it's easier.
4933          */
4934         cp = strchr(origin, '@');
4935         if (cp)
4936                 *cp = '\0';
4937         (void) dmu_objset_find(origin,
4938             zfs_unmount_snap_cb, NULL, DS_FIND_SNAPSHOTS);
4939         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
4940 }
4941
4942 /*
4943  * Retrieve a single {user|group}{used|quota}@... property.
4944  *
4945  * inputs:
4946  * zc_name      name of filesystem
4947  * zc_objset_type zfs_userquota_prop_t
4948  * zc_value     domain name (eg. "S-1-234-567-89")
4949  * zc_guid      RID/UID/GID
4950  *
4951  * outputs:
4952  * zc_cookie    property value
4953  */
4954 static int
4955 zfs_ioc_userspace_one(zfs_cmd_t *zc)
4956 {
4957         zfsvfs_t *zfsvfs;
4958         int error;
4959
4960         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
4961                 return (SET_ERROR(EINVAL));
4962
4963         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4964         if (error != 0)
4965                 return (error);
4966
4967         error = zfs_userspace_one(zfsvfs,
4968             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
4969         zfsvfs_rele(zfsvfs, FTAG);
4970
4971         return (error);
4972 }
4973
4974 /*
4975  * inputs:
4976  * zc_name              name of filesystem
4977  * zc_cookie            zap cursor
4978  * zc_objset_type       zfs_userquota_prop_t
4979  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
4980  *
4981  * outputs:
4982  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
4983  * zc_cookie    zap cursor
4984  */
4985 static int
4986 zfs_ioc_userspace_many(zfs_cmd_t *zc)
4987 {
4988         zfsvfs_t *zfsvfs;
4989         int bufsize = zc->zc_nvlist_dst_size;
4990
4991         if (bufsize <= 0)
4992                 return (SET_ERROR(ENOMEM));
4993
4994         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4995         if (error != 0)
4996                 return (error);
4997
4998         void *buf = kmem_alloc(bufsize, KM_SLEEP);
4999
5000         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
5001             buf, &zc->zc_nvlist_dst_size);
5002
5003         if (error == 0) {
5004                 error = ddi_copyout(buf,
5005                     (void *)(uintptr_t)zc->zc_nvlist_dst,
5006                     zc->zc_nvlist_dst_size, zc->zc_iflags);
5007         }
5008         kmem_free(buf, bufsize);
5009         zfsvfs_rele(zfsvfs, FTAG);
5010
5011         return (error);
5012 }
5013
5014 /*
5015  * inputs:
5016  * zc_name              name of filesystem
5017  *
5018  * outputs:
5019  * none
5020  */
5021 static int
5022 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
5023 {
5024         objset_t *os;
5025         int error = 0;
5026         zfsvfs_t *zfsvfs;
5027
5028         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
5029                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
5030                         /*
5031                          * If userused is not enabled, it may be because the
5032                          * objset needs to be closed & reopened (to grow the
5033                          * objset_phys_t).  Suspend/resume the fs will do that.
5034                          */
5035                         dsl_dataset_t *ds;
5036
5037                         ds = dmu_objset_ds(zfsvfs->z_os);
5038                         error = zfs_suspend_fs(zfsvfs);
5039                         if (error == 0) {
5040                                 dmu_objset_refresh_ownership(zfsvfs->z_os,
5041                                     zfsvfs);
5042                                 error = zfs_resume_fs(zfsvfs, ds);
5043                         }
5044                 }
5045                 if (error == 0)
5046                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
5047 #ifdef illumos
5048                 VFS_RELE(zfsvfs->z_vfs);
5049 #else
5050                 vfs_unbusy(zfsvfs->z_vfs);
5051 #endif
5052         } else {
5053                 /* XXX kind of reading contents without owning */
5054                 error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5055                 if (error != 0)
5056                         return (error);
5057
5058                 error = dmu_objset_userspace_upgrade(os);
5059                 dmu_objset_rele(os, FTAG);
5060         }
5061
5062         return (error);
5063 }
5064
5065 #ifdef illumos
5066 /*
5067  * We don't want to have a hard dependency
5068  * against some special symbols in sharefs
5069  * nfs, and smbsrv.  Determine them if needed when
5070  * the first file system is shared.
5071  * Neither sharefs, nfs or smbsrv are unloadable modules.
5072  */
5073 int (*znfsexport_fs)(void *arg);
5074 int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
5075 int (*zsmbexport_fs)(void *arg, boolean_t add_share);
5076
5077 int zfs_nfsshare_inited;
5078 int zfs_smbshare_inited;
5079
5080 ddi_modhandle_t nfs_mod;
5081 ddi_modhandle_t sharefs_mod;
5082 ddi_modhandle_t smbsrv_mod;
5083 #endif  /* illumos */
5084 kmutex_t zfs_share_lock;
5085
5086 #ifdef illumos
5087 static int
5088 zfs_init_sharefs()
5089 {
5090         int error;
5091
5092         ASSERT(MUTEX_HELD(&zfs_share_lock));
5093         /* Both NFS and SMB shares also require sharetab support. */
5094         if (sharefs_mod == NULL && ((sharefs_mod =
5095             ddi_modopen("fs/sharefs",
5096             KRTLD_MODE_FIRST, &error)) == NULL)) {
5097                 return (SET_ERROR(ENOSYS));
5098         }
5099         if (zshare_fs == NULL && ((zshare_fs =
5100             (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
5101             ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
5102                 return (SET_ERROR(ENOSYS));
5103         }
5104         return (0);
5105 }
5106 #endif  /* illumos */
5107
5108 static int
5109 zfs_ioc_share(zfs_cmd_t *zc)
5110 {
5111 #ifdef illumos
5112         int error;
5113         int opcode;
5114
5115         switch (zc->zc_share.z_sharetype) {
5116         case ZFS_SHARE_NFS:
5117         case ZFS_UNSHARE_NFS:
5118                 if (zfs_nfsshare_inited == 0) {
5119                         mutex_enter(&zfs_share_lock);
5120                         if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
5121                             KRTLD_MODE_FIRST, &error)) == NULL)) {
5122                                 mutex_exit(&zfs_share_lock);
5123                                 return (SET_ERROR(ENOSYS));
5124                         }
5125                         if (znfsexport_fs == NULL &&
5126                             ((znfsexport_fs = (int (*)(void *))
5127                             ddi_modsym(nfs_mod,
5128                             "nfs_export", &error)) == NULL)) {
5129                                 mutex_exit(&zfs_share_lock);
5130                                 return (SET_ERROR(ENOSYS));
5131                         }
5132                         error = zfs_init_sharefs();
5133                         if (error != 0) {
5134                                 mutex_exit(&zfs_share_lock);
5135                                 return (SET_ERROR(ENOSYS));
5136                         }
5137                         zfs_nfsshare_inited = 1;
5138                         mutex_exit(&zfs_share_lock);
5139                 }
5140                 break;
5141         case ZFS_SHARE_SMB:
5142         case ZFS_UNSHARE_SMB:
5143                 if (zfs_smbshare_inited == 0) {
5144                         mutex_enter(&zfs_share_lock);
5145                         if (smbsrv_mod == NULL && ((smbsrv_mod =
5146                             ddi_modopen("drv/smbsrv",
5147                             KRTLD_MODE_FIRST, &error)) == NULL)) {
5148                                 mutex_exit(&zfs_share_lock);
5149                                 return (SET_ERROR(ENOSYS));
5150                         }
5151                         if (zsmbexport_fs == NULL && ((zsmbexport_fs =
5152                             (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
5153                             "smb_server_share", &error)) == NULL)) {
5154                                 mutex_exit(&zfs_share_lock);
5155                                 return (SET_ERROR(ENOSYS));
5156                         }
5157                         error = zfs_init_sharefs();
5158                         if (error != 0) {
5159                                 mutex_exit(&zfs_share_lock);
5160                                 return (SET_ERROR(ENOSYS));
5161                         }
5162                         zfs_smbshare_inited = 1;
5163                         mutex_exit(&zfs_share_lock);
5164                 }
5165                 break;
5166         default:
5167                 return (SET_ERROR(EINVAL));
5168         }
5169
5170         switch (zc->zc_share.z_sharetype) {
5171         case ZFS_SHARE_NFS:
5172         case ZFS_UNSHARE_NFS:
5173                 if (error =
5174                     znfsexport_fs((void *)
5175                     (uintptr_t)zc->zc_share.z_exportdata))
5176                         return (error);
5177                 break;
5178         case ZFS_SHARE_SMB:
5179         case ZFS_UNSHARE_SMB:
5180                 if (error = zsmbexport_fs((void *)
5181                     (uintptr_t)zc->zc_share.z_exportdata,
5182                     zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
5183                     B_TRUE: B_FALSE)) {
5184                         return (error);
5185                 }
5186                 break;
5187         }
5188
5189         opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
5190             zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
5191             SHAREFS_ADD : SHAREFS_REMOVE;
5192
5193         /*
5194          * Add or remove share from sharetab
5195          */
5196         error = zshare_fs(opcode,
5197             (void *)(uintptr_t)zc->zc_share.z_sharedata,
5198             zc->zc_share.z_sharemax);
5199
5200         return (error);
5201
5202 #else   /* !illumos */
5203         return (ENOSYS);
5204 #endif  /* illumos */
5205 }
5206
5207 ace_t full_access[] = {
5208         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
5209 };
5210
5211 /*
5212  * inputs:
5213  * zc_name              name of containing filesystem
5214  * zc_obj               object # beyond which we want next in-use object #
5215  *
5216  * outputs:
5217  * zc_obj               next in-use object #
5218  */
5219 static int
5220 zfs_ioc_next_obj(zfs_cmd_t *zc)
5221 {
5222         objset_t *os = NULL;
5223         int error;
5224
5225         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5226         if (error != 0)
5227                 return (error);
5228
5229         error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
5230             dsl_dataset_phys(os->os_dsl_dataset)->ds_prev_snap_txg);
5231
5232         dmu_objset_rele(os, FTAG);
5233         return (error);
5234 }
5235
5236 /*
5237  * inputs:
5238  * zc_name              name of filesystem
5239  * zc_value             prefix name for snapshot
5240  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
5241  *
5242  * outputs:
5243  * zc_value             short name of new snapshot
5244  */
5245 static int
5246 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
5247 {
5248         char *snap_name;
5249         char *hold_name;
5250         int error;
5251         minor_t minor;
5252
5253         error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
5254         if (error != 0)
5255                 return (error);
5256
5257         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
5258             (u_longlong_t)ddi_get_lbolt64());
5259         hold_name = kmem_asprintf("%%%s", zc->zc_value);
5260
5261         error = dsl_dataset_snapshot_tmp(zc->zc_name, snap_name, minor,
5262             hold_name);
5263         if (error == 0)
5264                 (void) strcpy(zc->zc_value, snap_name);
5265         strfree(snap_name);
5266         strfree(hold_name);
5267         zfs_onexit_fd_rele(zc->zc_cleanup_fd);
5268         return (error);
5269 }
5270
5271 /*
5272  * inputs:
5273  * zc_name              name of "to" snapshot
5274  * zc_value             name of "from" snapshot
5275  * zc_cookie            file descriptor to write diff data on
5276  *
5277  * outputs:
5278  * dmu_diff_record_t's to the file descriptor
5279  */
5280 static int
5281 zfs_ioc_diff(zfs_cmd_t *zc)
5282 {
5283         file_t *fp;
5284         cap_rights_t rights;
5285         offset_t off;
5286         int error;
5287
5288 #ifdef illumos
5289         fp = getf(zc->zc_cookie);
5290 #else
5291         fget_write(curthread, zc->zc_cookie,
5292                     cap_rights_init(&rights, CAP_WRITE), &fp);
5293 #endif
5294         if (fp == NULL)
5295                 return (SET_ERROR(EBADF));
5296
5297         off = fp->f_offset;
5298
5299 #ifdef illumos
5300         error = dmu_diff(zc->zc_name, zc->zc_value, fp->f_vnode, &off);
5301 #else
5302         error = dmu_diff(zc->zc_name, zc->zc_value, fp, &off);
5303 #endif
5304
5305         if (off >= 0 && off <= MAXOFFSET_T)
5306                 fp->f_offset = off;
5307         releasef(zc->zc_cookie);
5308
5309         return (error);
5310 }
5311
5312 #ifdef illumos
5313 /*
5314  * Remove all ACL files in shares dir
5315  */
5316 static int
5317 zfs_smb_acl_purge(znode_t *dzp)
5318 {
5319         zap_cursor_t    zc;
5320         zap_attribute_t zap;
5321         zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
5322         int error;
5323
5324         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
5325             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
5326             zap_cursor_advance(&zc)) {
5327                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
5328                     NULL, 0)) != 0)
5329                         break;
5330         }
5331         zap_cursor_fini(&zc);
5332         return (error);
5333 }
5334 #endif  /* illumos */
5335
5336 static int
5337 zfs_ioc_smb_acl(zfs_cmd_t *zc)
5338 {
5339 #ifdef illumos
5340         vnode_t *vp;
5341         znode_t *dzp;
5342         vnode_t *resourcevp = NULL;
5343         znode_t *sharedir;
5344         zfsvfs_t *zfsvfs;
5345         nvlist_t *nvlist;
5346         char *src, *target;
5347         vattr_t vattr;
5348         vsecattr_t vsec;
5349         int error = 0;
5350
5351         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
5352             NO_FOLLOW, NULL, &vp)) != 0)
5353                 return (error);
5354
5355         /* Now make sure mntpnt and dataset are ZFS */
5356
5357         if (strcmp(vp->v_vfsp->mnt_stat.f_fstypename, "zfs") != 0 ||
5358             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
5359             zc->zc_name) != 0)) {
5360                 VN_RELE(vp);
5361                 return (SET_ERROR(EINVAL));
5362         }
5363
5364         dzp = VTOZ(vp);
5365         zfsvfs = dzp->z_zfsvfs;
5366         ZFS_ENTER(zfsvfs);
5367
5368         /*
5369          * Create share dir if its missing.
5370          */
5371         mutex_enter(&zfsvfs->z_lock);
5372         if (zfsvfs->z_shares_dir == 0) {
5373                 dmu_tx_t *tx;
5374
5375                 tx = dmu_tx_create(zfsvfs->z_os);
5376                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
5377                     ZFS_SHARES_DIR);
5378                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
5379                 error = dmu_tx_assign(tx, TXG_WAIT);
5380                 if (error != 0) {
5381                         dmu_tx_abort(tx);
5382                 } else {
5383                         error = zfs_create_share_dir(zfsvfs, tx);
5384                         dmu_tx_commit(tx);
5385                 }
5386                 if (error != 0) {
5387                         mutex_exit(&zfsvfs->z_lock);
5388                         VN_RELE(vp);
5389                         ZFS_EXIT(zfsvfs);
5390                         return (error);
5391                 }
5392         }
5393         mutex_exit(&zfsvfs->z_lock);
5394
5395         ASSERT(zfsvfs->z_shares_dir);
5396         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
5397                 VN_RELE(vp);
5398                 ZFS_EXIT(zfsvfs);
5399                 return (error);
5400         }
5401
5402         switch (zc->zc_cookie) {
5403         case ZFS_SMB_ACL_ADD:
5404                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
5405                 vattr.va_type = VREG;
5406                 vattr.va_mode = S_IFREG|0777;
5407                 vattr.va_uid = 0;
5408                 vattr.va_gid = 0;
5409
5410                 vsec.vsa_mask = VSA_ACE;
5411                 vsec.vsa_aclentp = &full_access;
5412                 vsec.vsa_aclentsz = sizeof (full_access);
5413                 vsec.vsa_aclcnt = 1;
5414
5415                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
5416                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
5417                 if (resourcevp)
5418                         VN_RELE(resourcevp);
5419                 break;
5420
5421         case ZFS_SMB_ACL_REMOVE:
5422                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
5423                     NULL, 0);
5424                 break;
5425
5426         case ZFS_SMB_ACL_RENAME:
5427                 if ((error = get_nvlist(zc->zc_nvlist_src,
5428                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
5429                         VN_RELE(vp);
5430                         VN_RELE(ZTOV(sharedir));
5431                         ZFS_EXIT(zfsvfs);
5432                         return (error);
5433                 }
5434                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
5435                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
5436                     &target)) {
5437                         VN_RELE(vp);
5438                         VN_RELE(ZTOV(sharedir));
5439                         ZFS_EXIT(zfsvfs);
5440                         nvlist_free(nvlist);
5441                         return (error);
5442                 }
5443                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
5444                     kcred, NULL, 0);
5445                 nvlist_free(nvlist);
5446                 break;
5447
5448         case ZFS_SMB_ACL_PURGE:
5449                 error = zfs_smb_acl_purge(sharedir);
5450                 break;
5451
5452         default:
5453                 error = SET_ERROR(EINVAL);
5454                 break;
5455         }
5456
5457         VN_RELE(vp);
5458         VN_RELE(ZTOV(sharedir));
5459
5460         ZFS_EXIT(zfsvfs);
5461
5462         return (error);
5463 #else   /* !illumos */
5464         return (EOPNOTSUPP);
5465 #endif  /* illumos */
5466 }
5467
5468 /*
5469  * innvl: {
5470  *     "holds" -> { snapname -> holdname (string), ... }
5471  *     (optional) "cleanup_fd" -> fd (int32)
5472  * }
5473  *
5474  * outnvl: {
5475  *     snapname -> error value (int32)
5476  *     ...
5477  * }
5478  */
5479 /* ARGSUSED */
5480 static int
5481 zfs_ioc_hold(const char *pool, nvlist_t *args, nvlist_t *errlist)
5482 {
5483         nvpair_t *pair;
5484         nvlist_t *holds;
5485         int cleanup_fd = -1;
5486         int error;
5487         minor_t minor = 0;
5488
5489         error = nvlist_lookup_nvlist(args, "holds", &holds);
5490         if (error != 0)
5491                 return (SET_ERROR(EINVAL));
5492
5493         /* make sure the user didn't pass us any invalid (empty) tags */
5494         for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
5495             pair = nvlist_next_nvpair(holds, pair)) {
5496                 char *htag;
5497
5498                 error = nvpair_value_string(pair, &htag);
5499                 if (error != 0)
5500                         return (SET_ERROR(error));
5501
5502                 if (strlen(htag) == 0)
5503                         return (SET_ERROR(EINVAL));
5504         }
5505
5506         if (nvlist_lookup_int32(args, "cleanup_fd", &cleanup_fd) == 0) {
5507                 error = zfs_onexit_fd_hold(cleanup_fd, &minor);
5508                 if (error != 0)
5509                         return (error);
5510         }
5511
5512         error = dsl_dataset_user_hold(holds, minor, errlist);
5513         if (minor != 0)
5514                 zfs_onexit_fd_rele(cleanup_fd);
5515         return (error);
5516 }
5517
5518 /*
5519  * innvl is not used.
5520  *
5521  * outnvl: {
5522  *    holdname -> time added (uint64 seconds since epoch)
5523  *    ...
5524  * }
5525  */
5526 /* ARGSUSED */
5527 static int
5528 zfs_ioc_get_holds(const char *snapname, nvlist_t *args, nvlist_t *outnvl)
5529 {
5530         return (dsl_dataset_get_holds(snapname, outnvl));
5531 }
5532
5533 /*
5534  * innvl: {
5535  *     snapname -> { holdname, ... }
5536  *     ...
5537  * }
5538  *
5539  * outnvl: {
5540  *     snapname -> error value (int32)
5541  *     ...
5542  * }
5543  */
5544 /* ARGSUSED */
5545 static int
5546 zfs_ioc_release(const char *pool, nvlist_t *holds, nvlist_t *errlist)
5547 {
5548         return (dsl_dataset_user_release(holds, errlist));
5549 }
5550
5551 /*
5552  * inputs:
5553  * zc_name              name of new filesystem or snapshot
5554  * zc_value             full name of old snapshot
5555  *
5556  * outputs:
5557  * zc_cookie            space in bytes
5558  * zc_objset_type       compressed space in bytes
5559  * zc_perm_action       uncompressed space in bytes
5560  */
5561 static int
5562 zfs_ioc_space_written(zfs_cmd_t *zc)
5563 {
5564         int error;
5565         dsl_pool_t *dp;
5566         dsl_dataset_t *new, *old;
5567
5568         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5569         if (error != 0)
5570                 return (error);
5571         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &new);
5572         if (error != 0) {
5573                 dsl_pool_rele(dp, FTAG);
5574                 return (error);
5575         }
5576         error = dsl_dataset_hold(dp, zc->zc_value, FTAG, &old);
5577         if (error != 0) {
5578                 dsl_dataset_rele(new, FTAG);
5579                 dsl_pool_rele(dp, FTAG);
5580                 return (error);
5581         }
5582
5583         error = dsl_dataset_space_written(old, new, &zc->zc_cookie,
5584             &zc->zc_objset_type, &zc->zc_perm_action);
5585         dsl_dataset_rele(old, FTAG);
5586         dsl_dataset_rele(new, FTAG);
5587         dsl_pool_rele(dp, FTAG);
5588         return (error);
5589 }
5590
5591 /*
5592  * innvl: {
5593  *     "firstsnap" -> snapshot name
5594  * }
5595  *
5596  * outnvl: {
5597  *     "used" -> space in bytes
5598  *     "compressed" -> compressed space in bytes
5599  *     "uncompressed" -> uncompressed space in bytes
5600  * }
5601  */
5602 static int
5603 zfs_ioc_space_snaps(const char *lastsnap, nvlist_t *innvl, nvlist_t *outnvl)
5604 {
5605         int error;
5606         dsl_pool_t *dp;
5607         dsl_dataset_t *new, *old;
5608         char *firstsnap;
5609         uint64_t used, comp, uncomp;
5610
5611         if (nvlist_lookup_string(innvl, "firstsnap", &firstsnap) != 0)
5612                 return (SET_ERROR(EINVAL));
5613
5614         error = dsl_pool_hold(lastsnap, FTAG, &dp);
5615         if (error != 0)
5616                 return (error);
5617
5618         error = dsl_dataset_hold(dp, lastsnap, FTAG, &new);
5619         if (error == 0 && !new->ds_is_snapshot) {
5620                 dsl_dataset_rele(new, FTAG);
5621                 error = SET_ERROR(EINVAL);
5622         }
5623         if (error != 0) {
5624                 dsl_pool_rele(dp, FTAG);
5625                 return (error);
5626         }
5627         error = dsl_dataset_hold(dp, firstsnap, FTAG, &old);
5628         if (error == 0 && !old->ds_is_snapshot) {
5629                 dsl_dataset_rele(old, FTAG);
5630                 error = SET_ERROR(EINVAL);
5631         }
5632         if (error != 0) {
5633                 dsl_dataset_rele(new, FTAG);
5634                 dsl_pool_rele(dp, FTAG);
5635                 return (error);
5636         }
5637
5638         error = dsl_dataset_space_wouldfree(old, new, &used, &comp, &uncomp);
5639         dsl_dataset_rele(old, FTAG);
5640         dsl_dataset_rele(new, FTAG);
5641         dsl_pool_rele(dp, FTAG);
5642         fnvlist_add_uint64(outnvl, "used", used);
5643         fnvlist_add_uint64(outnvl, "compressed", comp);
5644         fnvlist_add_uint64(outnvl, "uncompressed", uncomp);
5645         return (error);
5646 }
5647
5648 static int
5649 zfs_ioc_jail(zfs_cmd_t *zc)
5650 {
5651
5652         return (zone_dataset_attach(curthread->td_ucred, zc->zc_name,
5653             (int)zc->zc_jailid));
5654 }
5655
5656 static int
5657 zfs_ioc_unjail(zfs_cmd_t *zc)
5658 {
5659
5660         return (zone_dataset_detach(curthread->td_ucred, zc->zc_name,
5661             (int)zc->zc_jailid));
5662 }
5663
5664 /*
5665  * innvl: {
5666  *     "fd" -> file descriptor to write stream to (int32)
5667  *     (optional) "fromsnap" -> full snap name to send an incremental from
5668  *     (optional) "largeblockok" -> (value ignored)
5669  *         indicates that blocks > 128KB are permitted
5670  *     (optional) "embedok" -> (value ignored)
5671  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5672  *     (optional) "compressok" -> (value ignored)
5673  *         presence indicates compressed DRR_WRITE records are permitted
5674  *     (optional) "resume_object" and "resume_offset" -> (uint64)
5675  *         if present, resume send stream from specified object and offset.
5676  * }
5677  *
5678  * outnvl is unused
5679  */
5680 /* ARGSUSED */
5681 static int
5682 zfs_ioc_send_new(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5683 {
5684         cap_rights_t rights;
5685         file_t *fp;
5686         int error;
5687         offset_t off;
5688         char *fromname = NULL;
5689         int fd;
5690         boolean_t largeblockok;
5691         boolean_t embedok;
5692         boolean_t compressok;
5693         uint64_t resumeobj = 0;
5694         uint64_t resumeoff = 0;
5695
5696         error = nvlist_lookup_int32(innvl, "fd", &fd);
5697         if (error != 0)
5698                 return (SET_ERROR(EINVAL));
5699
5700         (void) nvlist_lookup_string(innvl, "fromsnap", &fromname);
5701
5702         largeblockok = nvlist_exists(innvl, "largeblockok");
5703         embedok = nvlist_exists(innvl, "embedok");
5704         compressok = nvlist_exists(innvl, "compressok");
5705
5706         (void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
5707         (void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
5708
5709 #ifdef illumos
5710         file_t *fp = getf(fd);
5711 #else
5712         fget_write(curthread, fd, cap_rights_init(&rights, CAP_WRITE), &fp);
5713 #endif
5714         if (fp == NULL)
5715                 return (SET_ERROR(EBADF));
5716
5717         off = fp->f_offset;
5718         error = dmu_send(snapname, fromname, embedok, largeblockok, compressok,
5719 #ifdef illumos
5720             fd, resumeobj, resumeoff, fp->f_vnode, &off);
5721 #else
5722             fd, resumeobj, resumeoff, fp, &off);
5723 #endif
5724
5725 #ifdef illumos
5726         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5727                 fp->f_offset = off;
5728 #else
5729         fp->f_offset = off;
5730 #endif
5731
5732         releasef(fd);
5733         return (error);
5734 }
5735
5736 /*
5737  * Determine approximately how large a zfs send stream will be -- the number
5738  * of bytes that will be written to the fd supplied to zfs_ioc_send_new().
5739  *
5740  * innvl: {
5741  *     (optional) "from" -> full snap or bookmark name to send an incremental
5742  *                          from
5743  *     (optional) "largeblockok" -> (value ignored)
5744  *         indicates that blocks > 128KB are permitted
5745  *     (optional) "embedok" -> (value ignored)
5746  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5747  *     (optional) "compressok" -> (value ignored)
5748  *         presence indicates compressed DRR_WRITE records are permitted
5749  * }
5750  *
5751  * outnvl: {
5752  *     "space" -> bytes of space (uint64)
5753  * }
5754  */
5755 static int
5756 zfs_ioc_send_space(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5757 {
5758         dsl_pool_t *dp;
5759         dsl_dataset_t *tosnap;
5760         int error;
5761         char *fromname;
5762         /* LINTED E_FUNC_SET_NOT_USED */
5763         boolean_t largeblockok;
5764         /* LINTED E_FUNC_SET_NOT_USED */
5765         boolean_t embedok;
5766         boolean_t compressok;
5767         uint64_t space;
5768
5769         error = dsl_pool_hold(snapname, FTAG, &dp);
5770         if (error != 0)
5771                 return (error);
5772
5773         error = dsl_dataset_hold(dp, snapname, FTAG, &tosnap);
5774         if (error != 0) {
5775                 dsl_pool_rele(dp, FTAG);
5776                 return (error);
5777         }
5778
5779         largeblockok = nvlist_exists(innvl, "largeblockok");
5780         embedok = nvlist_exists(innvl, "embedok");
5781         compressok = nvlist_exists(innvl, "compressok");
5782
5783         error = nvlist_lookup_string(innvl, "from", &fromname);
5784         if (error == 0) {
5785                 if (strchr(fromname, '@') != NULL) {
5786                         /*
5787                          * If from is a snapshot, hold it and use the more
5788                          * efficient dmu_send_estimate to estimate send space
5789                          * size using deadlists.
5790                          */
5791                         dsl_dataset_t *fromsnap;
5792                         error = dsl_dataset_hold(dp, fromname, FTAG, &fromsnap);
5793                         if (error != 0)
5794                                 goto out;
5795                         error = dmu_send_estimate(tosnap, fromsnap, compressok,
5796                             &space);
5797                         dsl_dataset_rele(fromsnap, FTAG);
5798                 } else if (strchr(fromname, '#') != NULL) {
5799                         /*
5800                          * If from is a bookmark, fetch the creation TXG of the
5801                          * snapshot it was created from and use that to find
5802                          * blocks that were born after it.
5803                          */
5804                         zfs_bookmark_phys_t frombm;
5805
5806                         error = dsl_bookmark_lookup(dp, fromname, tosnap,
5807                             &frombm);
5808                         if (error != 0)
5809                                 goto out;
5810                         error = dmu_send_estimate_from_txg(tosnap,
5811                             frombm.zbm_creation_txg, compressok, &space);
5812                 } else {
5813                         /*
5814                          * from is not properly formatted as a snapshot or
5815                          * bookmark
5816                          */
5817                         error = SET_ERROR(EINVAL);
5818                         goto out;
5819                 }
5820         } else {
5821                 // If estimating the size of a full send, use dmu_send_estimate
5822                 error = dmu_send_estimate(tosnap, NULL, compressok, &space);
5823         }
5824
5825         fnvlist_add_uint64(outnvl, "space", space);
5826
5827 out:
5828         dsl_dataset_rele(tosnap, FTAG);
5829         dsl_pool_rele(dp, FTAG);
5830         return (error);
5831 }
5832
5833 static zfs_ioc_vec_t zfs_ioc_vec[ZFS_IOC_LAST - ZFS_IOC_FIRST];
5834
5835 static void
5836 zfs_ioctl_register_legacy(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5837     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
5838     boolean_t log_history, zfs_ioc_poolcheck_t pool_check)
5839 {
5840         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
5841
5842         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
5843         ASSERT3U(ioc, <, ZFS_IOC_LAST);
5844         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
5845         ASSERT3P(vec->zvec_func, ==, NULL);
5846
5847         vec->zvec_legacy_func = func;
5848         vec->zvec_secpolicy = secpolicy;
5849         vec->zvec_namecheck = namecheck;
5850         vec->zvec_allow_log = log_history;
5851         vec->zvec_pool_check = pool_check;
5852 }
5853
5854 /*
5855  * See the block comment at the beginning of this file for details on
5856  * each argument to this function.
5857  */
5858 static void
5859 zfs_ioctl_register(const char *name, zfs_ioc_t ioc, zfs_ioc_func_t *func,
5860     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
5861     zfs_ioc_poolcheck_t pool_check, boolean_t smush_outnvlist,
5862     boolean_t allow_log)
5863 {
5864         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
5865
5866         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
5867         ASSERT3U(ioc, <, ZFS_IOC_LAST);
5868         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
5869         ASSERT3P(vec->zvec_func, ==, NULL);
5870
5871         /* if we are logging, the name must be valid */
5872         ASSERT(!allow_log || namecheck != NO_NAME);
5873
5874         vec->zvec_name = name;
5875         vec->zvec_func = func;
5876         vec->zvec_secpolicy = secpolicy;
5877         vec->zvec_namecheck = namecheck;
5878         vec->zvec_pool_check = pool_check;
5879         vec->zvec_smush_outnvlist = smush_outnvlist;
5880         vec->zvec_allow_log = allow_log;
5881 }
5882
5883 static void
5884 zfs_ioctl_register_pool(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5885     zfs_secpolicy_func_t *secpolicy, boolean_t log_history,
5886     zfs_ioc_poolcheck_t pool_check)
5887 {
5888         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5889             POOL_NAME, log_history, pool_check);
5890 }
5891
5892 static void
5893 zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5894     zfs_secpolicy_func_t *secpolicy, zfs_ioc_poolcheck_t pool_check)
5895 {
5896         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5897             DATASET_NAME, B_FALSE, pool_check);
5898 }
5899
5900 static void
5901 zfs_ioctl_register_pool_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
5902 {
5903         zfs_ioctl_register_legacy(ioc, func, zfs_secpolicy_config,
5904             POOL_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5905 }
5906
5907 static void
5908 zfs_ioctl_register_pool_meta(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5909     zfs_secpolicy_func_t *secpolicy)
5910 {
5911         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5912             NO_NAME, B_FALSE, POOL_CHECK_NONE);
5913 }
5914
5915 static void
5916 zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,
5917     zfs_ioc_legacy_func_t *func, zfs_secpolicy_func_t *secpolicy)
5918 {
5919         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5920             DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED);
5921 }
5922
5923 static void
5924 zfs_ioctl_register_dataset_read(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
5925 {
5926         zfs_ioctl_register_dataset_read_secpolicy(ioc, func,
5927             zfs_secpolicy_read);
5928 }
5929
5930 static void
5931 zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5932     zfs_secpolicy_func_t *secpolicy)
5933 {
5934         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5935             DATASET_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5936 }
5937
5938 static void
5939 zfs_ioctl_init(void)
5940 {
5941         zfs_ioctl_register("snapshot", ZFS_IOC_SNAPSHOT,
5942             zfs_ioc_snapshot, zfs_secpolicy_snapshot, POOL_NAME,
5943             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5944
5945         zfs_ioctl_register("log_history", ZFS_IOC_LOG_HISTORY,
5946             zfs_ioc_log_history, zfs_secpolicy_log_history, NO_NAME,
5947             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE);
5948
5949         zfs_ioctl_register("space_snaps", ZFS_IOC_SPACE_SNAPS,
5950             zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME,
5951             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5952
5953         zfs_ioctl_register("send", ZFS_IOC_SEND_NEW,
5954             zfs_ioc_send_new, zfs_secpolicy_send_new, DATASET_NAME,
5955             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5956
5957         zfs_ioctl_register("send_space", ZFS_IOC_SEND_SPACE,
5958             zfs_ioc_send_space, zfs_secpolicy_read, DATASET_NAME,
5959             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5960
5961         zfs_ioctl_register("create", ZFS_IOC_CREATE,
5962             zfs_ioc_create, zfs_secpolicy_create_clone, DATASET_NAME,
5963             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5964
5965         zfs_ioctl_register("clone", ZFS_IOC_CLONE,
5966             zfs_ioc_clone, zfs_secpolicy_create_clone, DATASET_NAME,
5967             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5968
5969         zfs_ioctl_register("destroy_snaps", ZFS_IOC_DESTROY_SNAPS,
5970             zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, POOL_NAME,
5971             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5972
5973         zfs_ioctl_register("hold", ZFS_IOC_HOLD,
5974             zfs_ioc_hold, zfs_secpolicy_hold, POOL_NAME,
5975             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5976         zfs_ioctl_register("release", ZFS_IOC_RELEASE,
5977             zfs_ioc_release, zfs_secpolicy_release, POOL_NAME,
5978             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5979
5980         zfs_ioctl_register("get_holds", ZFS_IOC_GET_HOLDS,
5981             zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME,
5982             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5983
5984         zfs_ioctl_register("rollback", ZFS_IOC_ROLLBACK,
5985             zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME,
5986             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
5987
5988         zfs_ioctl_register("bookmark", ZFS_IOC_BOOKMARK,
5989             zfs_ioc_bookmark, zfs_secpolicy_bookmark, POOL_NAME,
5990             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5991
5992         zfs_ioctl_register("get_bookmarks", ZFS_IOC_GET_BOOKMARKS,
5993             zfs_ioc_get_bookmarks, zfs_secpolicy_read, DATASET_NAME,
5994             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5995
5996         zfs_ioctl_register("destroy_bookmarks", ZFS_IOC_DESTROY_BOOKMARKS,
5997             zfs_ioc_destroy_bookmarks, zfs_secpolicy_destroy_bookmarks,
5998             POOL_NAME,
5999             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6000
6001         /* IOCTLS that use the legacy function signature */
6002
6003         zfs_ioctl_register_legacy(ZFS_IOC_POOL_FREEZE, zfs_ioc_pool_freeze,
6004             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_READONLY);
6005
6006         zfs_ioctl_register_pool(ZFS_IOC_POOL_CREATE, zfs_ioc_pool_create,
6007             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6008         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SCAN,
6009             zfs_ioc_pool_scan);
6010         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_UPGRADE,
6011             zfs_ioc_pool_upgrade);
6012         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ADD,
6013             zfs_ioc_vdev_add);
6014         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_REMOVE,
6015             zfs_ioc_vdev_remove);
6016         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SET_STATE,
6017             zfs_ioc_vdev_set_state);
6018         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ATTACH,
6019             zfs_ioc_vdev_attach);
6020         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_DETACH,
6021             zfs_ioc_vdev_detach);
6022         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETPATH,
6023             zfs_ioc_vdev_setpath);
6024         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETFRU,
6025             zfs_ioc_vdev_setfru);
6026         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SET_PROPS,
6027             zfs_ioc_pool_set_props);
6028         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SPLIT,
6029             zfs_ioc_vdev_split);
6030         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_REGUID,
6031             zfs_ioc_pool_reguid);
6032
6033         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_CONFIGS,
6034             zfs_ioc_pool_configs, zfs_secpolicy_none);
6035         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_TRYIMPORT,
6036             zfs_ioc_pool_tryimport, zfs_secpolicy_config);
6037         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_FAULT,
6038             zfs_ioc_inject_fault, zfs_secpolicy_inject);
6039         zfs_ioctl_register_pool_meta(ZFS_IOC_CLEAR_FAULT,
6040             zfs_ioc_clear_fault, zfs_secpolicy_inject);
6041         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_LIST_NEXT,
6042             zfs_ioc_inject_list_next, zfs_secpolicy_inject);
6043
6044         /*
6045          * pool destroy, and export don't log the history as part of
6046          * zfsdev_ioctl, but rather zfs_ioc_pool_export
6047          * does the logging of those commands.
6048          */
6049         zfs_ioctl_register_pool(ZFS_IOC_POOL_DESTROY, zfs_ioc_pool_destroy,
6050             zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
6051         zfs_ioctl_register_pool(ZFS_IOC_POOL_EXPORT, zfs_ioc_pool_export,
6052             zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
6053
6054         zfs_ioctl_register_pool(ZFS_IOC_POOL_STATS, zfs_ioc_pool_stats,
6055             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6056         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_PROPS, zfs_ioc_pool_get_props,
6057             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6058
6059         zfs_ioctl_register_pool(ZFS_IOC_ERROR_LOG, zfs_ioc_error_log,
6060             zfs_secpolicy_inject, B_FALSE, POOL_CHECK_NONE);
6061         zfs_ioctl_register_pool(ZFS_IOC_DSOBJ_TO_DSNAME,
6062             zfs_ioc_dsobj_to_dsname,
6063             zfs_secpolicy_diff, B_FALSE, POOL_CHECK_NONE);
6064         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_HISTORY,
6065             zfs_ioc_pool_get_history,
6066             zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
6067
6068         zfs_ioctl_register_pool(ZFS_IOC_POOL_IMPORT, zfs_ioc_pool_import,
6069             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6070
6071         zfs_ioctl_register_pool(ZFS_IOC_CLEAR, zfs_ioc_clear,
6072             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6073         zfs_ioctl_register_pool(ZFS_IOC_POOL_REOPEN, zfs_ioc_pool_reopen,
6074             zfs_secpolicy_config, B_TRUE, POOL_CHECK_SUSPENDED);
6075
6076         zfs_ioctl_register_dataset_read(ZFS_IOC_SPACE_WRITTEN,
6077             zfs_ioc_space_written);
6078         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_RECVD_PROPS,
6079             zfs_ioc_objset_recvd_props);
6080         zfs_ioctl_register_dataset_read(ZFS_IOC_NEXT_OBJ,
6081             zfs_ioc_next_obj);
6082         zfs_ioctl_register_dataset_read(ZFS_IOC_GET_FSACL,
6083             zfs_ioc_get_fsacl);
6084         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_STATS,
6085             zfs_ioc_objset_stats);
6086         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_ZPLPROPS,
6087             zfs_ioc_objset_zplprops);
6088         zfs_ioctl_register_dataset_read(ZFS_IOC_DATASET_LIST_NEXT,
6089             zfs_ioc_dataset_list_next);
6090         zfs_ioctl_register_dataset_read(ZFS_IOC_SNAPSHOT_LIST_NEXT,
6091             zfs_ioc_snapshot_list_next);
6092         zfs_ioctl_register_dataset_read(ZFS_IOC_SEND_PROGRESS,
6093             zfs_ioc_send_progress);
6094
6095         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_DIFF,
6096             zfs_ioc_diff, zfs_secpolicy_diff);
6097         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_STATS,
6098             zfs_ioc_obj_to_stats, zfs_secpolicy_diff);
6099         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_PATH,
6100             zfs_ioc_obj_to_path, zfs_secpolicy_diff);
6101         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_ONE,
6102             zfs_ioc_userspace_one, zfs_secpolicy_userspace_one);
6103         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_MANY,
6104             zfs_ioc_userspace_many, zfs_secpolicy_userspace_many);
6105         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_SEND,
6106             zfs_ioc_send, zfs_secpolicy_send);
6107
6108         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_PROP, zfs_ioc_set_prop,
6109             zfs_secpolicy_none);
6110         zfs_ioctl_register_dataset_modify(ZFS_IOC_DESTROY, zfs_ioc_destroy,
6111             zfs_secpolicy_destroy);
6112         zfs_ioctl_register_dataset_modify(ZFS_IOC_RENAME, zfs_ioc_rename,
6113             zfs_secpolicy_rename);
6114         zfs_ioctl_register_dataset_modify(ZFS_IOC_RECV, zfs_ioc_recv,
6115             zfs_secpolicy_recv);
6116         zfs_ioctl_register_dataset_modify(ZFS_IOC_PROMOTE, zfs_ioc_promote,
6117             zfs_secpolicy_promote);
6118         zfs_ioctl_register_dataset_modify(ZFS_IOC_INHERIT_PROP,
6119             zfs_ioc_inherit_prop, zfs_secpolicy_inherit_prop);
6120         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_FSACL, zfs_ioc_set_fsacl,
6121             zfs_secpolicy_set_fsacl);
6122
6123         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SHARE, zfs_ioc_share,
6124             zfs_secpolicy_share, POOL_CHECK_NONE);
6125         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SMB_ACL, zfs_ioc_smb_acl,
6126             zfs_secpolicy_smb_acl, POOL_CHECK_NONE);
6127         zfs_ioctl_register_dataset_nolog(ZFS_IOC_USERSPACE_UPGRADE,
6128             zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
6129             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6130         zfs_ioctl_register_dataset_nolog(ZFS_IOC_TMP_SNAPSHOT,
6131             zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot,
6132             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6133
6134 #ifdef __FreeBSD__
6135         zfs_ioctl_register_dataset_nolog(ZFS_IOC_JAIL, zfs_ioc_jail,
6136             zfs_secpolicy_config, POOL_CHECK_NONE);
6137         zfs_ioctl_register_dataset_nolog(ZFS_IOC_UNJAIL, zfs_ioc_unjail,
6138             zfs_secpolicy_config, POOL_CHECK_NONE);
6139         zfs_ioctl_register("fbsd_nextboot", ZFS_IOC_NEXTBOOT,
6140             zfs_ioc_nextboot, zfs_secpolicy_config, NO_NAME,
6141             POOL_CHECK_NONE, B_FALSE, B_FALSE);
6142 #endif
6143 }
6144
6145 int
6146 pool_status_check(const char *name, zfs_ioc_namecheck_t type,
6147     zfs_ioc_poolcheck_t check)
6148 {
6149         spa_t *spa;
6150         int error;
6151
6152         ASSERT(type == POOL_NAME || type == DATASET_NAME);
6153
6154         if (check & POOL_CHECK_NONE)
6155                 return (0);
6156
6157         error = spa_open(name, &spa, FTAG);
6158         if (error == 0) {
6159                 if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
6160                         error = SET_ERROR(EAGAIN);
6161                 else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
6162                         error = SET_ERROR(EROFS);
6163                 spa_close(spa, FTAG);
6164         }
6165         return (error);
6166 }
6167
6168 /*
6169  * Find a free minor number.
6170  */
6171 minor_t
6172 zfsdev_minor_alloc(void)
6173 {
6174         static minor_t last_minor;
6175         minor_t m;
6176
6177         ASSERT(MUTEX_HELD(&spa_namespace_lock));
6178
6179         for (m = last_minor + 1; m != last_minor; m++) {
6180                 if (m > ZFSDEV_MAX_MINOR)
6181                         m = 1;
6182                 if (ddi_get_soft_state(zfsdev_state, m) == NULL) {
6183                         last_minor = m;
6184                         return (m);
6185                 }
6186         }
6187
6188         return (0);
6189 }
6190
6191 static int
6192 zfs_ctldev_init(struct cdev *devp)
6193 {
6194         minor_t minor;
6195         zfs_soft_state_t *zs;
6196
6197         ASSERT(MUTEX_HELD(&spa_namespace_lock));
6198
6199         minor = zfsdev_minor_alloc();
6200         if (minor == 0)
6201                 return (SET_ERROR(ENXIO));
6202
6203         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS)
6204                 return (SET_ERROR(EAGAIN));
6205
6206         devfs_set_cdevpriv((void *)(uintptr_t)minor, zfsdev_close);
6207
6208         zs = ddi_get_soft_state(zfsdev_state, minor);
6209         zs->zss_type = ZSST_CTLDEV;
6210         zfs_onexit_init((zfs_onexit_t **)&zs->zss_data);
6211
6212         return (0);
6213 }
6214
6215 static void
6216 zfs_ctldev_destroy(zfs_onexit_t *zo, minor_t minor)
6217 {
6218         ASSERT(MUTEX_HELD(&spa_namespace_lock));
6219
6220         zfs_onexit_destroy(zo);
6221         ddi_soft_state_free(zfsdev_state, minor);
6222 }
6223
6224 void *
6225 zfsdev_get_soft_state(minor_t minor, enum zfs_soft_state_type which)
6226 {
6227         zfs_soft_state_t *zp;
6228
6229         zp = ddi_get_soft_state(zfsdev_state, minor);
6230         if (zp == NULL || zp->zss_type != which)
6231                 return (NULL);
6232
6233         return (zp->zss_data);
6234 }
6235
6236 static int
6237 zfsdev_open(struct cdev *devp, int flag, int mode, struct thread *td)
6238 {
6239         int error = 0;
6240
6241 #ifdef illumos
6242         if (getminor(*devp) != 0)
6243                 return (zvol_open(devp, flag, otyp, cr));
6244 #endif
6245
6246         /* This is the control device. Allocate a new minor if requested. */
6247         if (flag & FEXCL) {
6248                 mutex_enter(&spa_namespace_lock);
6249                 error = zfs_ctldev_init(devp);
6250                 mutex_exit(&spa_namespace_lock);
6251         }
6252
6253         return (error);
6254 }
6255
6256 static void
6257 zfsdev_close(void *data)
6258 {
6259         zfs_onexit_t *zo;
6260         minor_t minor = (minor_t)(uintptr_t)data;
6261
6262         if (minor == 0)
6263                 return;
6264
6265         mutex_enter(&spa_namespace_lock);
6266         zo = zfsdev_get_soft_state(minor, ZSST_CTLDEV);
6267         if (zo == NULL) {
6268                 mutex_exit(&spa_namespace_lock);
6269                 return;
6270         }
6271         zfs_ctldev_destroy(zo, minor);
6272         mutex_exit(&spa_namespace_lock);
6273 }
6274
6275 static int
6276 zfsdev_ioctl(struct cdev *dev, u_long zcmd, caddr_t arg, int flag,
6277     struct thread *td)
6278 {
6279         zfs_cmd_t *zc;
6280         uint_t vecnum;
6281         int error, rc, len;
6282 #ifdef illumos
6283         minor_t minor = getminor(dev);
6284 #else
6285         zfs_iocparm_t *zc_iocparm;
6286         int cflag, cmd, oldvecnum;
6287         boolean_t newioc, compat;
6288         void *compat_zc = NULL;
6289         cred_t *cr = td->td_ucred;
6290 #endif
6291         const zfs_ioc_vec_t *vec;
6292         char *saved_poolname = NULL;
6293         nvlist_t *innvl = NULL;
6294
6295         cflag = ZFS_CMD_COMPAT_NONE;
6296         compat = B_FALSE;
6297         newioc = B_TRUE;        /* "new" style (zfs_iocparm_t) ioctl */
6298
6299         len = IOCPARM_LEN(zcmd);
6300         vecnum = cmd = zcmd & 0xff;
6301
6302         /*
6303          * Check if we are talking to supported older binaries
6304          * and translate zfs_cmd if necessary
6305          */
6306         if (len != sizeof(zfs_iocparm_t)) {
6307                 newioc = B_FALSE;
6308                 compat = B_TRUE;
6309
6310                 vecnum = cmd;
6311
6312                 switch (len) {
6313                 case sizeof(zfs_cmd_zcmd_t):
6314                         cflag = ZFS_CMD_COMPAT_LZC;
6315                         break;
6316                 case sizeof(zfs_cmd_deadman_t):
6317                         cflag = ZFS_CMD_COMPAT_DEADMAN;
6318                         break;
6319                 case sizeof(zfs_cmd_v28_t):
6320                         cflag = ZFS_CMD_COMPAT_V28;
6321                         break;
6322                 case sizeof(zfs_cmd_v15_t):
6323                         cflag = ZFS_CMD_COMPAT_V15;
6324                         vecnum = zfs_ioctl_v15_to_v28[cmd];
6325
6326                         /*
6327                          * Return without further handling
6328                          * if the command is blacklisted.
6329                          */
6330                         if (vecnum == ZFS_IOC_COMPAT_PASS)
6331                                 return (0);
6332                         else if (vecnum == ZFS_IOC_COMPAT_FAIL)
6333                                 return (ENOTSUP);
6334                         break;
6335                 default:
6336                         return (EINVAL);
6337                 }
6338         }
6339
6340 #ifdef illumos
6341         vecnum = cmd - ZFS_IOC_FIRST;
6342         ASSERT3U(getmajor(dev), ==, ddi_driver_major(zfs_dip));
6343 #endif
6344
6345         if (vecnum >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
6346                 return (SET_ERROR(EINVAL));
6347         vec = &zfs_ioc_vec[vecnum];
6348
6349         zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
6350
6351 #ifdef illumos
6352         error = ddi_copyin((void *)arg, zc, sizeof (zfs_cmd_t), flag);
6353         if (error != 0) {
6354                 error = SET_ERROR(EFAULT);
6355                 goto out;
6356         }
6357 #else   /* !illumos */
6358         bzero(zc, sizeof(zfs_cmd_t));
6359
6360         if (newioc) {
6361                 zc_iocparm = (void *)arg;
6362
6363                 switch (zc_iocparm->zfs_ioctl_version) {
6364                 case ZFS_IOCVER_CURRENT:
6365                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_t)) {
6366                                 error = SET_ERROR(EINVAL);
6367                                 goto out;
6368                         }
6369                         break;
6370                 case ZFS_IOCVER_INLANES:
6371                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_inlanes_t)) {
6372                                 error = SET_ERROR(EFAULT);
6373                                 goto out;
6374                         }
6375                         compat = B_TRUE;
6376                         cflag = ZFS_CMD_COMPAT_INLANES;
6377                         break;
6378                 case ZFS_IOCVER_RESUME:
6379                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_resume_t)) {
6380                                 error = SET_ERROR(EFAULT);
6381                                 goto out;
6382                         }
6383                         compat = B_TRUE;
6384                         cflag = ZFS_CMD_COMPAT_RESUME;
6385                         break;
6386                 case ZFS_IOCVER_EDBP:
6387                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_edbp_t)) {
6388                                 error = SET_ERROR(EFAULT);
6389                                 goto out;
6390                         }
6391                         compat = B_TRUE;
6392                         cflag = ZFS_CMD_COMPAT_EDBP;
6393                         break;
6394                 case ZFS_IOCVER_ZCMD:
6395                         if (zc_iocparm->zfs_cmd_size > sizeof(zfs_cmd_t) ||
6396                             zc_iocparm->zfs_cmd_size < sizeof(zfs_cmd_zcmd_t)) {
6397                                 error = SET_ERROR(EFAULT);
6398                                 goto out;
6399                         }
6400                         compat = B_TRUE;
6401                         cflag = ZFS_CMD_COMPAT_ZCMD;
6402                         break;
6403                 default:
6404                         error = SET_ERROR(EINVAL);
6405                         goto out;
6406                         /* NOTREACHED */
6407                 }
6408
6409                 if (compat) {
6410                         ASSERT(sizeof(zfs_cmd_t) >= zc_iocparm->zfs_cmd_size);
6411                         compat_zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
6412                         bzero(compat_zc, sizeof(zfs_cmd_t));
6413
6414                         error = ddi_copyin((void *)(uintptr_t)zc_iocparm->zfs_cmd,
6415                             compat_zc, zc_iocparm->zfs_cmd_size, flag);
6416                         if (error != 0) {
6417                                 error = SET_ERROR(EFAULT);
6418                                 goto out;
6419                         }
6420                 } else {
6421                         error = ddi_copyin((void *)(uintptr_t)zc_iocparm->zfs_cmd,
6422                             zc, zc_iocparm->zfs_cmd_size, flag);
6423                         if (error != 0) {
6424                                 error = SET_ERROR(EFAULT);
6425                                 goto out;
6426                         }
6427                 }
6428         }
6429
6430         if (compat) {
6431                 if (newioc) {
6432                         ASSERT(compat_zc != NULL);
6433                         zfs_cmd_compat_get(zc, compat_zc, cflag);
6434                 } else {
6435                         ASSERT(compat_zc == NULL);
6436                         zfs_cmd_compat_get(zc, arg, cflag);
6437                 }
6438                 oldvecnum = vecnum;
6439                 error = zfs_ioctl_compat_pre(zc, &vecnum, cflag);
6440                 if (error != 0)
6441                         goto out;
6442                 if (oldvecnum != vecnum)
6443                         vec = &zfs_ioc_vec[vecnum];
6444         }
6445 #endif  /* !illumos */
6446
6447         zc->zc_iflags = flag & FKIOCTL;
6448         if (zc->zc_nvlist_src_size != 0) {
6449                 error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
6450                     zc->zc_iflags, &innvl);
6451                 if (error != 0)
6452                         goto out;
6453         }
6454
6455         /* rewrite innvl for backwards compatibility */
6456         if (compat)
6457                 innvl = zfs_ioctl_compat_innvl(zc, innvl, vecnum, cflag);
6458
6459         /*
6460          * Ensure that all pool/dataset names are valid before we pass down to
6461          * the lower layers.
6462          */
6463         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
6464         switch (vec->zvec_namecheck) {
6465         case POOL_NAME:
6466                 if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
6467                         error = SET_ERROR(EINVAL);
6468                 else
6469                         error = pool_status_check(zc->zc_name,
6470                             vec->zvec_namecheck, vec->zvec_pool_check);
6471                 break;
6472
6473         case DATASET_NAME:
6474                 if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
6475                         error = SET_ERROR(EINVAL);
6476                 else
6477                         error = pool_status_check(zc->zc_name,
6478                             vec->zvec_namecheck, vec->zvec_pool_check);
6479                 break;
6480
6481         case NO_NAME:
6482                 break;
6483         }
6484
6485         if (error == 0)
6486                 error = vec->zvec_secpolicy(zc, innvl, cr);
6487
6488         if (error != 0)
6489                 goto out;
6490
6491         /* legacy ioctls can modify zc_name */
6492         len = strcspn(zc->zc_name, "/@#") + 1;
6493         saved_poolname = kmem_alloc(len, KM_SLEEP);
6494         (void) strlcpy(saved_poolname, zc->zc_name, len);
6495
6496         if (vec->zvec_func != NULL) {
6497                 nvlist_t *outnvl;
6498                 int puterror = 0;
6499                 spa_t *spa;
6500                 nvlist_t *lognv = NULL;
6501
6502                 ASSERT(vec->zvec_legacy_func == NULL);
6503
6504                 /*
6505                  * Add the innvl to the lognv before calling the func,
6506                  * in case the func changes the innvl.
6507                  */
6508                 if (vec->zvec_allow_log) {
6509                         lognv = fnvlist_alloc();
6510                         fnvlist_add_string(lognv, ZPOOL_HIST_IOCTL,
6511                             vec->zvec_name);
6512                         if (!nvlist_empty(innvl)) {
6513                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_INPUT_NVL,
6514                                     innvl);
6515                         }
6516                 }
6517
6518                 outnvl = fnvlist_alloc();
6519                 error = vec->zvec_func(zc->zc_name, innvl, outnvl);
6520
6521                 if (error == 0 && vec->zvec_allow_log &&
6522                     spa_open(zc->zc_name, &spa, FTAG) == 0) {
6523                         if (!nvlist_empty(outnvl)) {
6524                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_OUTPUT_NVL,
6525                                     outnvl);
6526                         }
6527                         (void) spa_history_log_nvl(spa, lognv);
6528                         spa_close(spa, FTAG);
6529                 }
6530                 fnvlist_free(lognv);
6531
6532                 /* rewrite outnvl for backwards compatibility */
6533                 if (compat)
6534                         outnvl = zfs_ioctl_compat_outnvl(zc, outnvl, vecnum,
6535                             cflag);
6536
6537                 if (!nvlist_empty(outnvl) || zc->zc_nvlist_dst_size != 0) {
6538                         int smusherror = 0;
6539                         if (vec->zvec_smush_outnvlist) {
6540                                 smusherror = nvlist_smush(outnvl,
6541                                     zc->zc_nvlist_dst_size);
6542                         }
6543                         if (smusherror == 0)
6544                                 puterror = put_nvlist(zc, outnvl);
6545                 }
6546
6547                 if (puterror != 0)
6548                         error = puterror;
6549
6550                 nvlist_free(outnvl);
6551         } else {
6552                 error = vec->zvec_legacy_func(zc);
6553         }
6554
6555 out:
6556         nvlist_free(innvl);
6557
6558 #ifdef illumos
6559         rc = ddi_copyout(zc, (void *)arg, sizeof (zfs_cmd_t), flag);
6560         if (error == 0 && rc != 0)
6561                 error = SET_ERROR(EFAULT);
6562 #else
6563         if (compat) {
6564                 zfs_ioctl_compat_post(zc, cmd, cflag);
6565                 if (newioc) {
6566                         ASSERT(compat_zc != NULL);
6567                         ASSERT(sizeof(zfs_cmd_t) >= zc_iocparm->zfs_cmd_size);
6568
6569                         zfs_cmd_compat_put(zc, compat_zc, vecnum, cflag);
6570                         rc = ddi_copyout(compat_zc,
6571                             (void *)(uintptr_t)zc_iocparm->zfs_cmd,
6572                             zc_iocparm->zfs_cmd_size, flag);
6573                         if (error == 0 && rc != 0)
6574                                 error = SET_ERROR(EFAULT);
6575                         kmem_free(compat_zc, sizeof (zfs_cmd_t));
6576                 } else {
6577                         zfs_cmd_compat_put(zc, arg, vecnum, cflag);
6578                 }
6579         } else {
6580                 ASSERT(newioc);
6581
6582                 rc = ddi_copyout(zc, (void *)(uintptr_t)zc_iocparm->zfs_cmd,
6583                     sizeof (zfs_cmd_t), flag);
6584                 if (error == 0 && rc != 0)
6585                         error = SET_ERROR(EFAULT);
6586         }
6587 #endif
6588         if (error == 0 && vec->zvec_allow_log) {
6589                 char *s = tsd_get(zfs_allow_log_key);
6590                 if (s != NULL)
6591                         strfree(s);
6592                 (void) tsd_set(zfs_allow_log_key, saved_poolname);
6593         } else {
6594                 if (saved_poolname != NULL)
6595                         strfree(saved_poolname);
6596         }
6597
6598         kmem_free(zc, sizeof (zfs_cmd_t));
6599         return (error);
6600 }
6601
6602 #ifdef illumos
6603 static int
6604 zfs_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
6605 {
6606         if (cmd != DDI_ATTACH)
6607                 return (DDI_FAILURE);
6608
6609         if (ddi_create_minor_node(dip, "zfs", S_IFCHR, 0,
6610             DDI_PSEUDO, 0) == DDI_FAILURE)
6611                 return (DDI_FAILURE);
6612
6613         zfs_dip = dip;
6614
6615         ddi_report_dev(dip);
6616
6617         return (DDI_SUCCESS);
6618 }
6619
6620 static int
6621 zfs_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
6622 {
6623         if (spa_busy() || zfs_busy() || zvol_busy())
6624                 return (DDI_FAILURE);
6625
6626         if (cmd != DDI_DETACH)
6627                 return (DDI_FAILURE);
6628
6629         zfs_dip = NULL;
6630
6631         ddi_prop_remove_all(dip);
6632         ddi_remove_minor_node(dip, NULL);
6633
6634         return (DDI_SUCCESS);
6635 }
6636
6637 /*ARGSUSED*/
6638 static int
6639 zfs_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
6640 {
6641         switch (infocmd) {
6642         case DDI_INFO_DEVT2DEVINFO:
6643                 *result = zfs_dip;
6644                 return (DDI_SUCCESS);
6645
6646         case DDI_INFO_DEVT2INSTANCE:
6647                 *result = (void *)0;
6648                 return (DDI_SUCCESS);
6649         }
6650
6651         return (DDI_FAILURE);
6652 }
6653 #endif  /* illumos */
6654
6655 /*
6656  * OK, so this is a little weird.
6657  *
6658  * /dev/zfs is the control node, i.e. minor 0.
6659  * /dev/zvol/[r]dsk/pool/dataset are the zvols, minor > 0.
6660  *
6661  * /dev/zfs has basically nothing to do except serve up ioctls,
6662  * so most of the standard driver entry points are in zvol.c.
6663  */
6664 #ifdef illumos
6665 static struct cb_ops zfs_cb_ops = {
6666         zfsdev_open,    /* open */
6667         zfsdev_close,   /* close */
6668         zvol_strategy,  /* strategy */
6669         nodev,          /* print */
6670         zvol_dump,      /* dump */
6671         zvol_read,      /* read */
6672         zvol_write,     /* write */
6673         zfsdev_ioctl,   /* ioctl */
6674         nodev,          /* devmap */
6675         nodev,          /* mmap */
6676         nodev,          /* segmap */
6677         nochpoll,       /* poll */
6678         ddi_prop_op,    /* prop_op */
6679         NULL,           /* streamtab */
6680         D_NEW | D_MP | D_64BIT,         /* Driver compatibility flag */
6681         CB_REV,         /* version */
6682         nodev,          /* async read */
6683         nodev,          /* async write */
6684 };
6685
6686 static struct dev_ops zfs_dev_ops = {
6687         DEVO_REV,       /* version */
6688         0,              /* refcnt */
6689         zfs_info,       /* info */
6690         nulldev,        /* identify */
6691         nulldev,        /* probe */
6692         zfs_attach,     /* attach */
6693         zfs_detach,     /* detach */
6694         nodev,          /* reset */
6695         &zfs_cb_ops,    /* driver operations */
6696         NULL,           /* no bus operations */
6697         NULL,           /* power */
6698         ddi_quiesce_not_needed, /* quiesce */
6699 };
6700
6701 static struct modldrv zfs_modldrv = {
6702         &mod_driverops,
6703         "ZFS storage pool",
6704         &zfs_dev_ops
6705 };
6706
6707 static struct modlinkage modlinkage = {
6708         MODREV_1,
6709         (void *)&zfs_modlfs,
6710         (void *)&zfs_modldrv,
6711         NULL
6712 };
6713 #endif  /* illumos */
6714
6715 static struct cdevsw zfs_cdevsw = {
6716         .d_version =    D_VERSION,
6717         .d_open =       zfsdev_open,
6718         .d_ioctl =      zfsdev_ioctl,
6719         .d_name =       ZFS_DEV_NAME
6720 };
6721
6722 static void
6723 zfs_allow_log_destroy(void *arg)
6724 {
6725         char *poolname = arg;
6726         strfree(poolname);
6727 }
6728
6729 static void
6730 zfsdev_init(void)
6731 {
6732         zfsdev = make_dev(&zfs_cdevsw, 0x0, UID_ROOT, GID_OPERATOR, 0666,
6733             ZFS_DEV_NAME);
6734 }
6735
6736 static void
6737 zfsdev_fini(void)
6738 {
6739         if (zfsdev != NULL)
6740                 destroy_dev(zfsdev);
6741 }
6742
6743 static struct root_hold_token *zfs_root_token;
6744 struct proc *zfsproc;
6745
6746 #ifdef illumos
6747 int
6748 _init(void)
6749 {
6750         int error;
6751
6752         spa_init(FREAD | FWRITE);
6753         zfs_init();
6754         zvol_init();
6755         zfs_ioctl_init();
6756
6757         if ((error = mod_install(&modlinkage)) != 0) {
6758                 zvol_fini();
6759                 zfs_fini();
6760                 spa_fini();
6761                 return (error);
6762         }
6763
6764         tsd_create(&zfs_fsyncer_key, NULL);
6765         tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
6766         tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
6767
6768         error = ldi_ident_from_mod(&modlinkage, &zfs_li);
6769         ASSERT(error == 0);
6770         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
6771
6772         return (0);
6773 }
6774
6775 int
6776 _fini(void)
6777 {
6778         int error;
6779
6780         if (spa_busy() || zfs_busy() || zvol_busy() || zio_injection_enabled)
6781                 return (SET_ERROR(EBUSY));
6782
6783         if ((error = mod_remove(&modlinkage)) != 0)
6784                 return (error);
6785
6786         zvol_fini();
6787         zfs_fini();
6788         spa_fini();
6789         if (zfs_nfsshare_inited)
6790                 (void) ddi_modclose(nfs_mod);
6791         if (zfs_smbshare_inited)
6792                 (void) ddi_modclose(smbsrv_mod);
6793         if (zfs_nfsshare_inited || zfs_smbshare_inited)
6794                 (void) ddi_modclose(sharefs_mod);
6795
6796         tsd_destroy(&zfs_fsyncer_key);
6797         ldi_ident_release(zfs_li);
6798         zfs_li = NULL;
6799         mutex_destroy(&zfs_share_lock);
6800
6801         return (error);
6802 }
6803
6804 int
6805 _info(struct modinfo *modinfop)
6806 {
6807         return (mod_info(&modlinkage, modinfop));
6808 }
6809 #endif  /* illumos */
6810
6811 static int zfs__init(void);
6812 static int zfs__fini(void);
6813 static void zfs_shutdown(void *, int);
6814
6815 static eventhandler_tag zfs_shutdown_event_tag;
6816
6817 #ifdef __FreeBSD__
6818 #define ZFS_MIN_KSTACK_PAGES 4
6819 #endif
6820
6821 int
6822 zfs__init(void)
6823 {
6824
6825 #ifdef __FreeBSD__
6826 #if KSTACK_PAGES < ZFS_MIN_KSTACK_PAGES
6827         printf("ZFS NOTICE: KSTACK_PAGES is %d which could result in stack "
6828             "overflow panic!\nPlease consider adding "
6829             "'options KSTACK_PAGES=%d' to your kernel config\n", KSTACK_PAGES,
6830             ZFS_MIN_KSTACK_PAGES);
6831 #endif
6832 #endif
6833         zfs_root_token = root_mount_hold("ZFS");
6834
6835         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
6836
6837         spa_init(FREAD | FWRITE);
6838         zfs_init();
6839         zvol_init();
6840         zfs_ioctl_init();
6841
6842         tsd_create(&zfs_fsyncer_key, NULL);
6843         tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
6844         tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
6845         tsd_create(&zfs_geom_probe_vdev_key, NULL);
6846
6847         printf("ZFS storage pool version: features support (" SPA_VERSION_STRING ")\n");
6848         root_mount_rel(zfs_root_token);
6849
6850         zfsdev_init();
6851
6852         return (0);
6853 }
6854
6855 int
6856 zfs__fini(void)
6857 {
6858         if (spa_busy() || zfs_busy() || zvol_busy() ||
6859             zio_injection_enabled) {
6860                 return (EBUSY);
6861         }
6862
6863         zfsdev_fini();
6864         zvol_fini();
6865         zfs_fini();
6866         spa_fini();
6867
6868         tsd_destroy(&zfs_fsyncer_key);
6869         tsd_destroy(&rrw_tsd_key);
6870         tsd_destroy(&zfs_allow_log_key);
6871
6872         mutex_destroy(&zfs_share_lock);
6873
6874         return (0);
6875 }
6876
6877 static void
6878 zfs_shutdown(void *arg __unused, int howto __unused)
6879 {
6880
6881         /*
6882          * ZFS fini routines can not properly work in a panic-ed system.
6883          */
6884         if (panicstr == NULL)
6885                 (void)zfs__fini();
6886 }
6887
6888
6889 static int
6890 zfs_modevent(module_t mod, int type, void *unused __unused)
6891 {
6892         int err;
6893
6894         switch (type) {
6895         case MOD_LOAD:
6896                 err = zfs__init();
6897                 if (err == 0)
6898                         zfs_shutdown_event_tag = EVENTHANDLER_REGISTER(
6899                             shutdown_post_sync, zfs_shutdown, NULL,
6900                             SHUTDOWN_PRI_FIRST);
6901                 return (err);
6902         case MOD_UNLOAD:
6903                 err = zfs__fini();
6904                 if (err == 0 && zfs_shutdown_event_tag != NULL)
6905                         EVENTHANDLER_DEREGISTER(shutdown_post_sync,
6906                             zfs_shutdown_event_tag);
6907                 return (err);
6908         case MOD_SHUTDOWN:
6909                 return (0);
6910         default:
6911                 break;
6912         }
6913         return (EOPNOTSUPP);
6914 }
6915
6916 static moduledata_t zfs_mod = {
6917         "zfsctrl",
6918         zfs_modevent,
6919         0
6920 };
6921 DECLARE_MODULE(zfsctrl, zfs_mod, SI_SUB_VFS, SI_ORDER_ANY);
6922 MODULE_VERSION(zfsctrl, 1);
6923 MODULE_DEPEND(zfsctrl, opensolaris, 1, 1, 1);
6924 MODULE_DEPEND(zfsctrl, krpc, 1, 1, 1);
6925 MODULE_DEPEND(zfsctrl, acl_nfs4, 1, 1, 1);