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