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