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