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