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