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