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