]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
Merge ACPICA 20191018.
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zfs_ioctl.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011-2012 Pawel Jakub Dawidek. All rights reserved.
25  * Copyright 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
26  * Copyright 2014 Xin Li <delphij@FreeBSD.org>. All rights reserved.
27  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
28  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
29  * Copyright (c) 2014, 2016 Joyent, Inc. All rights reserved.
30  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
31  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
32  * Copyright (c) 2013 Steven Hartland. All rights reserved.
33  * Copyright (c) 2014 Integros [integros.com]
34  * Copyright 2016 Toomas Soome <tsoome@me.com>
35  * Copyright 2017 RackTop Systems.
36  * Copyright (c) 2017 Datto Inc.
37  */
38
39 /*
40  * ZFS ioctls.
41  *
42  * This file handles the ioctls to /dev/zfs, used for configuring ZFS storage
43  * pools and filesystems, e.g. with /sbin/zfs and /sbin/zpool.
44  *
45  * There are two ways that we handle ioctls: the legacy way where almost
46  * all of the logic is in the ioctl callback, and the new way where most
47  * of the marshalling is handled in the common entry point, zfsdev_ioctl().
48  *
49  * Non-legacy ioctls should be registered by calling
50  * zfs_ioctl_register() from zfs_ioctl_init().  The ioctl is invoked
51  * from userland by lzc_ioctl().
52  *
53  * The registration arguments are as follows:
54  *
55  * const char *name
56  *   The name of the ioctl.  This is used for history logging.  If the
57  *   ioctl returns successfully (the callback returns 0), and allow_log
58  *   is true, then a history log entry will be recorded with the input &
59  *   output nvlists.  The log entry can be printed with "zpool history -i".
60  *
61  * zfs_ioc_t ioc
62  *   The ioctl request number, which userland will pass to ioctl(2).
63  *   The ioctl numbers can change from release to release, because
64  *   the caller (libzfs) must be matched to the kernel.
65  *
66  * zfs_secpolicy_func_t *secpolicy
67  *   This function will be called before the zfs_ioc_func_t, to
68  *   determine if this operation is permitted.  It should return EPERM
69  *   on failure, and 0 on success.  Checks include determining if the
70  *   dataset is visible in this zone, and if the user has either all
71  *   zfs privileges in the zone (SYS_MOUNT), or has been granted permission
72  *   to do this operation on this dataset with "zfs allow".
73  *
74  * zfs_ioc_namecheck_t namecheck
75  *   This specifies what to expect in the zfs_cmd_t:zc_name -- a pool
76  *   name, a dataset name, or nothing.  If the name is not well-formed,
77  *   the ioctl will fail and the callback will not be called.
78  *   Therefore, the callback can assume that the name is well-formed
79  *   (e.g. is null-terminated, doesn't have more than one '@' character,
80  *   doesn't have invalid characters).
81  *
82  * zfs_ioc_poolcheck_t pool_check
83  *   This specifies requirements on the pool state.  If the pool does
84  *   not meet them (is suspended or is readonly), the ioctl will fail
85  *   and the callback will not be called.  If any checks are specified
86  *   (i.e. it is not POOL_CHECK_NONE), namecheck must not be NO_NAME.
87  *   Multiple checks can be or-ed together (e.g. POOL_CHECK_SUSPENDED |
88  *   POOL_CHECK_READONLY).
89  *
90  * boolean_t smush_outnvlist
91  *   If smush_outnvlist is true, then the output is presumed to be a
92  *   list of errors, and it will be "smushed" down to fit into the
93  *   caller's buffer, by removing some entries and replacing them with a
94  *   single "N_MORE_ERRORS" entry indicating how many were removed.  See
95  *   nvlist_smush() for details.  If smush_outnvlist is false, and the
96  *   outnvlist does not fit into the userland-provided buffer, then the
97  *   ioctl will fail with ENOMEM.
98  *
99  * zfs_ioc_func_t *func
100  *   The callback function that will perform the operation.
101  *
102  *   The callback should return 0 on success, or an error number on
103  *   failure.  If the function fails, the userland ioctl will return -1,
104  *   and errno will be set to the callback's return value.  The callback
105  *   will be called with the following arguments:
106  *
107  *   const char *name
108  *     The name of the pool or dataset to operate on, from
109  *     zfs_cmd_t:zc_name.  The 'namecheck' argument specifies the
110  *     expected type (pool, dataset, or none).
111  *
112  *   nvlist_t *innvl
113  *     The input nvlist, deserialized from zfs_cmd_t:zc_nvlist_src.  Or
114  *     NULL if no input nvlist was provided.  Changes to this nvlist are
115  *     ignored.  If the input nvlist could not be deserialized, the
116  *     ioctl will fail and the callback will not be called.
117  *
118  *   nvlist_t *outnvl
119  *     The output nvlist, initially empty.  The callback can fill it in,
120  *     and it will be returned to userland by serializing it into
121  *     zfs_cmd_t:zc_nvlist_dst.  If it is non-empty, and serialization
122  *     fails (e.g. because the caller didn't supply a large enough
123  *     buffer), then the overall ioctl will fail.  See the
124  *     'smush_nvlist' argument above for additional behaviors.
125  *
126  *     There are two typical uses of the output nvlist:
127  *       - To return state, e.g. property values.  In this case,
128  *         smush_outnvlist should be false.  If the buffer was not large
129  *         enough, the caller will reallocate a larger buffer and try
130  *         the ioctl again.
131  *
132  *       - To return multiple errors from an ioctl which makes on-disk
133  *         changes.  In this case, smush_outnvlist should be true.
134  *         Ioctls which make on-disk modifications should generally not
135  *         use the outnvl if they succeed, because the caller can not
136  *         distinguish between the operation failing, and
137  *         deserialization failing.
138  */
139 #ifdef __FreeBSD__
140 #include "opt_kstack_pages.h"
141 #endif
142
143 #include <sys/types.h>
144 #include <sys/param.h>
145 #include <sys/systm.h>
146 #include <sys/conf.h>
147 #include <sys/kernel.h>
148 #include <sys/lock.h>
149 #include <sys/malloc.h>
150 #include <sys/mutex.h>
151 #include <sys/proc.h>
152 #include <sys/errno.h>
153 #include <sys/uio.h>
154 #include <sys/buf.h>
155 #include <sys/file.h>
156 #include <sys/kmem.h>
157 #include <sys/conf.h>
158 #include <sys/cmn_err.h>
159 #include <sys/stat.h>
160 #include <sys/zfs_ioctl.h>
161 #include <sys/zfs_vfsops.h>
162 #include <sys/zfs_znode.h>
163 #include <sys/zap.h>
164 #include <sys/spa.h>
165 #include <sys/spa_impl.h>
166 #include <sys/vdev.h>
167 #include <sys/dmu.h>
168 #include <sys/dsl_dir.h>
169 #include <sys/dsl_dataset.h>
170 #include <sys/dsl_prop.h>
171 #include <sys/dsl_deleg.h>
172 #include <sys/dmu_objset.h>
173 #include <sys/dmu_impl.h>
174 #include <sys/dmu_tx.h>
175 #include <sys/sunddi.h>
176 #include <sys/policy.h>
177 #include <sys/zone.h>
178 #include <sys/nvpair.h>
179 #include <sys/mount.h>
180 #include <sys/taskqueue.h>
181 #include <sys/sdt.h>
182 #include <sys/varargs.h>
183 #include <sys/fs/zfs.h>
184 #include <sys/zfs_ctldir.h>
185 #include <sys/zfs_dir.h>
186 #include <sys/zfs_onexit.h>
187 #include <sys/zvol.h>
188 #include <sys/dsl_scan.h>
189 #include <sys/dmu_objset.h>
190 #include <sys/dmu_send.h>
191 #include <sys/dsl_destroy.h>
192 #include <sys/dsl_bookmark.h>
193 #include <sys/dsl_userhold.h>
194 #include <sys/zfeature.h>
195 #include <sys/zcp.h>
196 #include <sys/zio_checksum.h>
197 #include <sys/vdev_removal.h>
198 #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_dst_size   size of buffer for property nvlist
2349  *
2350  * outputs:
2351  * zc_name              name of next filesystem
2352  * zc_cookie            zap cursor
2353  * zc_objset_stats      stats
2354  * zc_nvlist_dst        property nvlist
2355  * zc_nvlist_dst_size   size of property nvlist
2356  */
2357 static int
2358 zfs_ioc_dataset_list_next(zfs_cmd_t *zc)
2359 {
2360         objset_t *os;
2361         int error;
2362         char *p;
2363         size_t orig_len = strlen(zc->zc_name);
2364
2365 top:
2366         if (error = dmu_objset_hold(zc->zc_name, FTAG, &os)) {
2367                 if (error == ENOENT)
2368                         error = SET_ERROR(ESRCH);
2369                 return (error);
2370         }
2371
2372         p = strrchr(zc->zc_name, '/');
2373         if (p == NULL || p[1] != '\0')
2374                 (void) strlcat(zc->zc_name, "/", sizeof (zc->zc_name));
2375         p = zc->zc_name + strlen(zc->zc_name);
2376
2377         do {
2378                 error = dmu_dir_list_next(os,
2379                     sizeof (zc->zc_name) - (p - zc->zc_name), p,
2380                     NULL, &zc->zc_cookie);
2381                 if (error == ENOENT)
2382                         error = SET_ERROR(ESRCH);
2383         } while (error == 0 && dataset_name_hidden(zc->zc_name));
2384         dmu_objset_rele(os, FTAG);
2385
2386         /*
2387          * If it's an internal dataset (ie. with a '$' in its name),
2388          * don't try to get stats for it, otherwise we'll return ENOENT.
2389          */
2390         if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
2391                 error = zfs_ioc_objset_stats(zc); /* fill in the stats */
2392                 if (error == ENOENT) {
2393                         /* We lost a race with destroy, get the next one. */
2394                         zc->zc_name[orig_len] = '\0';
2395                         goto top;
2396                 }
2397         }
2398         return (error);
2399 }
2400
2401 /*
2402  * inputs:
2403  * zc_name              name of filesystem
2404  * zc_cookie            zap cursor
2405  * zc_nvlist_dst_size   size of buffer for property nvlist
2406  * zc_simple            when set, only name is requested
2407  *
2408  * outputs:
2409  * zc_name              name of next snapshot
2410  * zc_objset_stats      stats
2411  * zc_nvlist_dst        property nvlist
2412  * zc_nvlist_dst_size   size of property nvlist
2413  */
2414 static int
2415 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2416 {
2417         objset_t *os;
2418         int error;
2419
2420         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2421         if (error != 0) {
2422                 return (error == ENOENT ? ESRCH : error);
2423         }
2424
2425         /*
2426          * A dataset name of maximum length cannot have any snapshots,
2427          * so exit immediately.
2428          */
2429         if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >=
2430             ZFS_MAX_DATASET_NAME_LEN) {
2431                 dmu_objset_rele(os, FTAG);
2432                 return (SET_ERROR(ESRCH));
2433         }
2434
2435         error = dmu_snapshot_list_next(os,
2436             sizeof (zc->zc_name) - strlen(zc->zc_name),
2437             zc->zc_name + strlen(zc->zc_name), &zc->zc_obj, &zc->zc_cookie,
2438             NULL);
2439
2440         if (error == 0 && !zc->zc_simple) {
2441                 dsl_dataset_t *ds;
2442                 dsl_pool_t *dp = os->os_dsl_dataset->ds_dir->dd_pool;
2443
2444                 error = dsl_dataset_hold_obj(dp, zc->zc_obj, FTAG, &ds);
2445                 if (error == 0) {
2446                         objset_t *ossnap;
2447
2448                         error = dmu_objset_from_ds(ds, &ossnap);
2449                         if (error == 0)
2450                                 error = zfs_ioc_objset_stats_impl(zc, ossnap);
2451                         dsl_dataset_rele(ds, FTAG);
2452                 }
2453         } else if (error == ENOENT) {
2454                 error = SET_ERROR(ESRCH);
2455         }
2456
2457         dmu_objset_rele(os, FTAG);
2458         /* if we failed, undo the @ that we tacked on to zc_name */
2459         if (error != 0)
2460                 *strchr(zc->zc_name, '@') = '\0';
2461         return (error);
2462 }
2463
2464 static int
2465 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2466 {
2467         const char *propname = nvpair_name(pair);
2468         uint64_t *valary;
2469         unsigned int vallen;
2470         const char *domain;
2471         char *dash;
2472         zfs_userquota_prop_t type;
2473         uint64_t rid;
2474         uint64_t quota;
2475         zfsvfs_t *zfsvfs;
2476         int err;
2477
2478         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2479                 nvlist_t *attrs;
2480                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2481                 if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2482                     &pair) != 0)
2483                         return (SET_ERROR(EINVAL));
2484         }
2485
2486         /*
2487          * A correctly constructed propname is encoded as
2488          * userquota@<rid>-<domain>.
2489          */
2490         if ((dash = strchr(propname, '-')) == NULL ||
2491             nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2492             vallen != 3)
2493                 return (SET_ERROR(EINVAL));
2494
2495         domain = dash + 1;
2496         type = valary[0];
2497         rid = valary[1];
2498         quota = valary[2];
2499
2500         err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2501         if (err == 0) {
2502                 err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2503                 zfsvfs_rele(zfsvfs, FTAG);
2504         }
2505
2506         return (err);
2507 }
2508
2509 /*
2510  * If the named property is one that has a special function to set its value,
2511  * return 0 on success and a positive error code on failure; otherwise if it is
2512  * not one of the special properties handled by this function, return -1.
2513  *
2514  * XXX: It would be better for callers of the property interface if we handled
2515  * these special cases in dsl_prop.c (in the dsl layer).
2516  */
2517 static int
2518 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2519     nvpair_t *pair)
2520 {
2521         const char *propname = nvpair_name(pair);
2522         zfs_prop_t prop = zfs_name_to_prop(propname);
2523         uint64_t intval;
2524         int err = -1;
2525
2526         if (prop == ZPROP_INVAL) {
2527                 if (zfs_prop_userquota(propname))
2528                         return (zfs_prop_set_userquota(dsname, pair));
2529                 return (-1);
2530         }
2531
2532         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2533                 nvlist_t *attrs;
2534                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2535                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2536                     &pair) == 0);
2537         }
2538
2539         if (zfs_prop_get_type(prop) == PROP_TYPE_STRING)
2540                 return (-1);
2541
2542         VERIFY(0 == nvpair_value_uint64(pair, &intval));
2543
2544         switch (prop) {
2545         case ZFS_PROP_QUOTA:
2546                 err = dsl_dir_set_quota(dsname, source, intval);
2547                 break;
2548         case ZFS_PROP_REFQUOTA:
2549                 err = dsl_dataset_set_refquota(dsname, source, intval);
2550                 break;
2551         case ZFS_PROP_FILESYSTEM_LIMIT:
2552         case ZFS_PROP_SNAPSHOT_LIMIT:
2553                 if (intval == UINT64_MAX) {
2554                         /* clearing the limit, just do it */
2555                         err = 0;
2556                 } else {
2557                         err = dsl_dir_activate_fs_ss_limit(dsname);
2558                 }
2559                 /*
2560                  * Set err to -1 to force the zfs_set_prop_nvlist code down the
2561                  * default path to set the value in the nvlist.
2562                  */
2563                 if (err == 0)
2564                         err = -1;
2565                 break;
2566         case ZFS_PROP_RESERVATION:
2567                 err = dsl_dir_set_reservation(dsname, source, intval);
2568                 break;
2569         case ZFS_PROP_REFRESERVATION:
2570                 err = dsl_dataset_set_refreservation(dsname, source, intval);
2571                 break;
2572         case ZFS_PROP_VOLSIZE:
2573                 err = zvol_set_volsize(dsname, intval);
2574                 break;
2575         case ZFS_PROP_VERSION:
2576         {
2577                 zfsvfs_t *zfsvfs;
2578
2579                 if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2580                         break;
2581
2582                 err = zfs_set_version(zfsvfs, intval);
2583                 zfsvfs_rele(zfsvfs, FTAG);
2584
2585                 if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2586                         zfs_cmd_t *zc;
2587
2588                         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2589                         (void) strcpy(zc->zc_name, dsname);
2590                         (void) zfs_ioc_userspace_upgrade(zc);
2591                         kmem_free(zc, sizeof (zfs_cmd_t));
2592                 }
2593                 break;
2594         }
2595         default:
2596                 err = -1;
2597         }
2598
2599         return (err);
2600 }
2601
2602 /*
2603  * This function is best effort. If it fails to set any of the given properties,
2604  * it continues to set as many as it can and returns the last error
2605  * encountered. If the caller provides a non-NULL errlist, it will be filled in
2606  * with the list of names of all the properties that failed along with the
2607  * corresponding error numbers.
2608  *
2609  * If every property is set successfully, zero is returned and errlist is not
2610  * modified.
2611  */
2612 int
2613 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
2614     nvlist_t *errlist)
2615 {
2616         nvpair_t *pair;
2617         nvpair_t *propval;
2618         int rv = 0;
2619         uint64_t intval;
2620         char *strval;
2621         nvlist_t *genericnvl = fnvlist_alloc();
2622         nvlist_t *retrynvl = fnvlist_alloc();
2623
2624 retry:
2625         pair = NULL;
2626         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2627                 const char *propname = nvpair_name(pair);
2628                 zfs_prop_t prop = zfs_name_to_prop(propname);
2629                 int err = 0;
2630
2631                 /* decode the property value */
2632                 propval = pair;
2633                 if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2634                         nvlist_t *attrs;
2635                         attrs = fnvpair_value_nvlist(pair);
2636                         if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2637                             &propval) != 0)
2638                                 err = SET_ERROR(EINVAL);
2639                 }
2640
2641                 /* Validate value type */
2642                 if (err == 0 && prop == ZPROP_INVAL) {
2643                         if (zfs_prop_user(propname)) {
2644                                 if (nvpair_type(propval) != DATA_TYPE_STRING)
2645                                         err = SET_ERROR(EINVAL);
2646                         } else if (zfs_prop_userquota(propname)) {
2647                                 if (nvpair_type(propval) !=
2648                                     DATA_TYPE_UINT64_ARRAY)
2649                                         err = SET_ERROR(EINVAL);
2650                         } else {
2651                                 err = SET_ERROR(EINVAL);
2652                         }
2653                 } else if (err == 0) {
2654                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2655                                 if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
2656                                         err = SET_ERROR(EINVAL);
2657                         } else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
2658                                 const char *unused;
2659
2660                                 intval = fnvpair_value_uint64(propval);
2661
2662                                 switch (zfs_prop_get_type(prop)) {
2663                                 case PROP_TYPE_NUMBER:
2664                                         break;
2665                                 case PROP_TYPE_STRING:
2666                                         err = SET_ERROR(EINVAL);
2667                                         break;
2668                                 case PROP_TYPE_INDEX:
2669                                         if (zfs_prop_index_to_string(prop,
2670                                             intval, &unused) != 0)
2671                                                 err = SET_ERROR(EINVAL);
2672                                         break;
2673                                 default:
2674                                         cmn_err(CE_PANIC,
2675                                             "unknown property type");
2676                                 }
2677                         } else {
2678                                 err = SET_ERROR(EINVAL);
2679                         }
2680                 }
2681
2682                 /* Validate permissions */
2683                 if (err == 0)
2684                         err = zfs_check_settable(dsname, pair, CRED());
2685
2686                 if (err == 0) {
2687                         err = zfs_prop_set_special(dsname, source, pair);
2688                         if (err == -1) {
2689                                 /*
2690                                  * For better performance we build up a list of
2691                                  * properties to set in a single transaction.
2692                                  */
2693                                 err = nvlist_add_nvpair(genericnvl, pair);
2694                         } else if (err != 0 && nvl != retrynvl) {
2695                                 /*
2696                                  * This may be a spurious error caused by
2697                                  * receiving quota and reservation out of order.
2698                                  * Try again in a second pass.
2699                                  */
2700                                 err = nvlist_add_nvpair(retrynvl, pair);
2701                         }
2702                 }
2703
2704                 if (err != 0) {
2705                         if (errlist != NULL)
2706                                 fnvlist_add_int32(errlist, propname, err);
2707                         rv = err;
2708                 }
2709         }
2710
2711         if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
2712                 nvl = retrynvl;
2713                 goto retry;
2714         }
2715
2716         if (!nvlist_empty(genericnvl) &&
2717             dsl_props_set(dsname, source, genericnvl) != 0) {
2718                 /*
2719                  * If this fails, we still want to set as many properties as we
2720                  * can, so try setting them individually.
2721                  */
2722                 pair = NULL;
2723                 while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
2724                         const char *propname = nvpair_name(pair);
2725                         int err = 0;
2726
2727                         propval = pair;
2728                         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2729                                 nvlist_t *attrs;
2730                                 attrs = fnvpair_value_nvlist(pair);
2731                                 propval = fnvlist_lookup_nvpair(attrs,
2732                                     ZPROP_VALUE);
2733                         }
2734
2735                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2736                                 strval = fnvpair_value_string(propval);
2737                                 err = dsl_prop_set_string(dsname, propname,
2738                                     source, strval);
2739                         } else {
2740                                 intval = fnvpair_value_uint64(propval);
2741                                 err = dsl_prop_set_int(dsname, propname, source,
2742                                     intval);
2743                         }
2744
2745                         if (err != 0) {
2746                                 if (errlist != NULL) {
2747                                         fnvlist_add_int32(errlist, propname,
2748                                             err);
2749                                 }
2750                                 rv = err;
2751                         }
2752                 }
2753         }
2754         nvlist_free(genericnvl);
2755         nvlist_free(retrynvl);
2756
2757         return (rv);
2758 }
2759
2760 /*
2761  * Check that all the properties are valid user properties.
2762  */
2763 static int
2764 zfs_check_userprops(nvlist_t *nvl)
2765 {
2766         nvpair_t *pair = NULL;
2767
2768         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2769                 const char *propname = nvpair_name(pair);
2770
2771                 if (!zfs_prop_user(propname) ||
2772                     nvpair_type(pair) != DATA_TYPE_STRING)
2773                         return (SET_ERROR(EINVAL));
2774
2775                 if (strlen(propname) >= ZAP_MAXNAMELEN)
2776                         return (SET_ERROR(ENAMETOOLONG));
2777
2778                 if (strlen(fnvpair_value_string(pair)) >= ZAP_MAXVALUELEN)
2779                         return (E2BIG);
2780         }
2781         return (0);
2782 }
2783
2784 static void
2785 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
2786 {
2787         nvpair_t *pair;
2788
2789         VERIFY(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2790
2791         pair = NULL;
2792         while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
2793                 if (nvlist_exists(skipped, nvpair_name(pair)))
2794                         continue;
2795
2796                 VERIFY(nvlist_add_nvpair(*newprops, pair) == 0);
2797         }
2798 }
2799
2800 static int
2801 clear_received_props(const char *dsname, nvlist_t *props,
2802     nvlist_t *skipped)
2803 {
2804         int err = 0;
2805         nvlist_t *cleared_props = NULL;
2806         props_skip(props, skipped, &cleared_props);
2807         if (!nvlist_empty(cleared_props)) {
2808                 /*
2809                  * Acts on local properties until the dataset has received
2810                  * properties at least once on or after SPA_VERSION_RECVD_PROPS.
2811                  */
2812                 zprop_source_t flags = (ZPROP_SRC_NONE |
2813                     (dsl_prop_get_hasrecvd(dsname) ? ZPROP_SRC_RECEIVED : 0));
2814                 err = zfs_set_prop_nvlist(dsname, flags, cleared_props, NULL);
2815         }
2816         nvlist_free(cleared_props);
2817         return (err);
2818 }
2819
2820 /*
2821  * inputs:
2822  * zc_name              name of filesystem
2823  * zc_value             name of property to set
2824  * zc_nvlist_src{_size} nvlist of properties to apply
2825  * zc_cookie            received properties flag
2826  *
2827  * outputs:
2828  * zc_nvlist_dst{_size} error for each unapplied received property
2829  */
2830 static int
2831 zfs_ioc_set_prop(zfs_cmd_t *zc)
2832 {
2833         nvlist_t *nvl;
2834         boolean_t received = zc->zc_cookie;
2835         zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
2836             ZPROP_SRC_LOCAL);
2837         nvlist_t *errors;
2838         int error;
2839
2840         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2841             zc->zc_iflags, &nvl)) != 0)
2842                 return (error);
2843
2844         if (received) {
2845                 nvlist_t *origprops;
2846
2847                 if (dsl_prop_get_received(zc->zc_name, &origprops) == 0) {
2848                         (void) clear_received_props(zc->zc_name,
2849                             origprops, nvl);
2850                         nvlist_free(origprops);
2851                 }
2852
2853                 error = dsl_prop_set_hasrecvd(zc->zc_name);
2854         }
2855
2856         errors = fnvlist_alloc();
2857         if (error == 0)
2858                 error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, errors);
2859
2860         if (zc->zc_nvlist_dst != 0 && errors != NULL) {
2861                 (void) put_nvlist(zc, errors);
2862         }
2863
2864         nvlist_free(errors);
2865         nvlist_free(nvl);
2866         return (error);
2867 }
2868
2869 /*
2870  * inputs:
2871  * zc_name              name of filesystem
2872  * zc_value             name of property to inherit
2873  * zc_cookie            revert to received value if TRUE
2874  *
2875  * outputs:             none
2876  */
2877 static int
2878 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
2879 {
2880         const char *propname = zc->zc_value;
2881         zfs_prop_t prop = zfs_name_to_prop(propname);
2882         boolean_t received = zc->zc_cookie;
2883         zprop_source_t source = (received
2884             ? ZPROP_SRC_NONE            /* revert to received value, if any */
2885             : ZPROP_SRC_INHERITED);     /* explicitly inherit */
2886
2887         if (received) {
2888                 nvlist_t *dummy;
2889                 nvpair_t *pair;
2890                 zprop_type_t type;
2891                 int err;
2892
2893                 /*
2894                  * zfs_prop_set_special() expects properties in the form of an
2895                  * nvpair with type info.
2896                  */
2897                 if (prop == ZPROP_INVAL) {
2898                         if (!zfs_prop_user(propname))
2899                                 return (SET_ERROR(EINVAL));
2900
2901                         type = PROP_TYPE_STRING;
2902                 } else if (prop == ZFS_PROP_VOLSIZE ||
2903                     prop == ZFS_PROP_VERSION) {
2904                         return (SET_ERROR(EINVAL));
2905                 } else {
2906                         type = zfs_prop_get_type(prop);
2907                 }
2908
2909                 VERIFY(nvlist_alloc(&dummy, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2910
2911                 switch (type) {
2912                 case PROP_TYPE_STRING:
2913                         VERIFY(0 == nvlist_add_string(dummy, propname, ""));
2914                         break;
2915                 case PROP_TYPE_NUMBER:
2916                 case PROP_TYPE_INDEX:
2917                         VERIFY(0 == nvlist_add_uint64(dummy, propname, 0));
2918                         break;
2919                 default:
2920                         nvlist_free(dummy);
2921                         return (SET_ERROR(EINVAL));
2922                 }
2923
2924                 pair = nvlist_next_nvpair(dummy, NULL);
2925                 err = zfs_prop_set_special(zc->zc_name, source, pair);
2926                 nvlist_free(dummy);
2927                 if (err != -1)
2928                         return (err); /* special property already handled */
2929         } else {
2930                 /*
2931                  * Only check this in the non-received case. We want to allow
2932                  * 'inherit -S' to revert non-inheritable properties like quota
2933                  * and reservation to the received or default values even though
2934                  * they are not considered inheritable.
2935                  */
2936                 if (prop != ZPROP_INVAL && !zfs_prop_inheritable(prop))
2937                         return (SET_ERROR(EINVAL));
2938         }
2939
2940         /* property name has been validated by zfs_secpolicy_inherit_prop() */
2941         return (dsl_prop_inherit(zc->zc_name, zc->zc_value, source));
2942 }
2943
2944 static int
2945 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
2946 {
2947         nvlist_t *props;
2948         spa_t *spa;
2949         int error;
2950         nvpair_t *pair;
2951
2952         if (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2953             zc->zc_iflags, &props))
2954                 return (error);
2955
2956         /*
2957          * If the only property is the configfile, then just do a spa_lookup()
2958          * to handle the faulted case.
2959          */
2960         pair = nvlist_next_nvpair(props, NULL);
2961         if (pair != NULL && strcmp(nvpair_name(pair),
2962             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
2963             nvlist_next_nvpair(props, pair) == NULL) {
2964                 mutex_enter(&spa_namespace_lock);
2965                 if ((spa = spa_lookup(zc->zc_name)) != NULL) {
2966                         spa_configfile_set(spa, props, B_FALSE);
2967                         spa_write_cachefile(spa, B_FALSE, B_TRUE);
2968                 }
2969                 mutex_exit(&spa_namespace_lock);
2970                 if (spa != NULL) {
2971                         nvlist_free(props);
2972                         return (0);
2973                 }
2974         }
2975
2976         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2977                 nvlist_free(props);
2978                 return (error);
2979         }
2980
2981         error = spa_prop_set(spa, props);
2982
2983         nvlist_free(props);
2984         spa_close(spa, FTAG);
2985
2986         return (error);
2987 }
2988
2989 static int
2990 zfs_ioc_pool_get_props(zfs_cmd_t *zc)
2991 {
2992         spa_t *spa;
2993         int error;
2994         nvlist_t *nvp = NULL;
2995
2996         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2997                 /*
2998                  * If the pool is faulted, there may be properties we can still
2999                  * get (such as altroot and cachefile), so attempt to get them
3000                  * anyway.
3001                  */
3002                 mutex_enter(&spa_namespace_lock);
3003                 if ((spa = spa_lookup(zc->zc_name)) != NULL)
3004                         error = spa_prop_get(spa, &nvp);
3005                 mutex_exit(&spa_namespace_lock);
3006         } else {
3007                 error = spa_prop_get(spa, &nvp);
3008                 spa_close(spa, FTAG);
3009         }
3010
3011         if (error == 0 && zc->zc_nvlist_dst != 0)
3012                 error = put_nvlist(zc, nvp);
3013         else
3014                 error = SET_ERROR(EFAULT);
3015
3016         nvlist_free(nvp);
3017         return (error);
3018 }
3019
3020 /*
3021  * inputs:
3022  * zc_name              name of filesystem
3023  * zc_nvlist_src{_size} nvlist of delegated permissions
3024  * zc_perm_action       allow/unallow flag
3025  *
3026  * outputs:             none
3027  */
3028 static int
3029 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
3030 {
3031         int error;
3032         nvlist_t *fsaclnv = NULL;
3033
3034         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3035             zc->zc_iflags, &fsaclnv)) != 0)
3036                 return (error);
3037
3038         /*
3039          * Verify nvlist is constructed correctly
3040          */
3041         if ((error = zfs_deleg_verify_nvlist(fsaclnv)) != 0) {
3042                 nvlist_free(fsaclnv);
3043                 return (SET_ERROR(EINVAL));
3044         }
3045
3046         /*
3047          * If we don't have PRIV_SYS_MOUNT, then validate
3048          * that user is allowed to hand out each permission in
3049          * the nvlist(s)
3050          */
3051
3052         error = secpolicy_zfs(CRED());
3053         if (error != 0) {
3054                 if (zc->zc_perm_action == B_FALSE) {
3055                         error = dsl_deleg_can_allow(zc->zc_name,
3056                             fsaclnv, CRED());
3057                 } else {
3058                         error = dsl_deleg_can_unallow(zc->zc_name,
3059                             fsaclnv, CRED());
3060                 }
3061         }
3062
3063         if (error == 0)
3064                 error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
3065
3066         nvlist_free(fsaclnv);
3067         return (error);
3068 }
3069
3070 /*
3071  * inputs:
3072  * zc_name              name of filesystem
3073  *
3074  * outputs:
3075  * zc_nvlist_src{_size} nvlist of delegated permissions
3076  */
3077 static int
3078 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
3079 {
3080         nvlist_t *nvp;
3081         int error;
3082
3083         if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
3084                 error = put_nvlist(zc, nvp);
3085                 nvlist_free(nvp);
3086         }
3087
3088         return (error);
3089 }
3090
3091 /* ARGSUSED */
3092 static void
3093 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3094 {
3095         zfs_creat_t *zct = arg;
3096
3097         zfs_create_fs(os, cr, zct->zct_zplprops, tx);
3098 }
3099
3100 #define ZFS_PROP_UNDEFINED      ((uint64_t)-1)
3101
3102 /*
3103  * inputs:
3104  * os                   parent objset pointer (NULL if root fs)
3105  * fuids_ok             fuids allowed in this version of the spa?
3106  * sa_ok                SAs allowed in this version of the spa?
3107  * createprops          list of properties requested by creator
3108  *
3109  * outputs:
3110  * zplprops     values for the zplprops we attach to the master node object
3111  * is_ci        true if requested file system will be purely case-insensitive
3112  *
3113  * Determine the settings for utf8only, normalization and
3114  * casesensitivity.  Specific values may have been requested by the
3115  * creator and/or we can inherit values from the parent dataset.  If
3116  * the file system is of too early a vintage, a creator can not
3117  * request settings for these properties, even if the requested
3118  * setting is the default value.  We don't actually want to create dsl
3119  * properties for these, so remove them from the source nvlist after
3120  * processing.
3121  */
3122 static int
3123 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
3124     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
3125     nvlist_t *zplprops, boolean_t *is_ci)
3126 {
3127         uint64_t sense = ZFS_PROP_UNDEFINED;
3128         uint64_t norm = ZFS_PROP_UNDEFINED;
3129         uint64_t u8 = ZFS_PROP_UNDEFINED;
3130
3131         ASSERT(zplprops != NULL);
3132
3133         if (os != NULL && os->os_phys->os_type != DMU_OST_ZFS)
3134                 return (SET_ERROR(EINVAL));
3135
3136         /*
3137          * Pull out creator prop choices, if any.
3138          */
3139         if (createprops) {
3140                 (void) nvlist_lookup_uint64(createprops,
3141                     zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
3142                 (void) nvlist_lookup_uint64(createprops,
3143                     zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
3144                 (void) nvlist_remove_all(createprops,
3145                     zfs_prop_to_name(ZFS_PROP_NORMALIZE));
3146                 (void) nvlist_lookup_uint64(createprops,
3147                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
3148                 (void) nvlist_remove_all(createprops,
3149                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
3150                 (void) nvlist_lookup_uint64(createprops,
3151                     zfs_prop_to_name(ZFS_PROP_CASE), &sense);
3152                 (void) nvlist_remove_all(createprops,
3153                     zfs_prop_to_name(ZFS_PROP_CASE));
3154         }
3155
3156         /*
3157          * If the zpl version requested is whacky or the file system
3158          * or pool is version is too "young" to support normalization
3159          * and the creator tried to set a value for one of the props,
3160          * error out.
3161          */
3162         if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
3163             (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
3164             (zplver >= ZPL_VERSION_SA && !sa_ok) ||
3165             (zplver < ZPL_VERSION_NORMALIZATION &&
3166             (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
3167             sense != ZFS_PROP_UNDEFINED)))
3168                 return (SET_ERROR(ENOTSUP));
3169
3170         /*
3171          * Put the version in the zplprops
3172          */
3173         VERIFY(nvlist_add_uint64(zplprops,
3174             zfs_prop_to_name(ZFS_PROP_VERSION), zplver) == 0);
3175
3176         if (norm == ZFS_PROP_UNDEFINED)
3177                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm) == 0);
3178         VERIFY(nvlist_add_uint64(zplprops,
3179             zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm) == 0);
3180
3181         /*
3182          * If we're normalizing, names must always be valid UTF-8 strings.
3183          */
3184         if (norm)
3185                 u8 = 1;
3186         if (u8 == ZFS_PROP_UNDEFINED)
3187                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8) == 0);
3188         VERIFY(nvlist_add_uint64(zplprops,
3189             zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8) == 0);
3190
3191         if (sense == ZFS_PROP_UNDEFINED)
3192                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_CASE, &sense) == 0);
3193         VERIFY(nvlist_add_uint64(zplprops,
3194             zfs_prop_to_name(ZFS_PROP_CASE), sense) == 0);
3195
3196         if (is_ci)
3197                 *is_ci = (sense == ZFS_CASE_INSENSITIVE);
3198
3199         return (0);
3200 }
3201
3202 static int
3203 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
3204     nvlist_t *zplprops, boolean_t *is_ci)
3205 {
3206         boolean_t fuids_ok, sa_ok;
3207         uint64_t zplver = ZPL_VERSION;
3208         objset_t *os = NULL;
3209         char parentname[ZFS_MAX_DATASET_NAME_LEN];
3210         char *cp;
3211         spa_t *spa;
3212         uint64_t spa_vers;
3213         int error;
3214
3215         (void) strlcpy(parentname, dataset, sizeof (parentname));
3216         cp = strrchr(parentname, '/');
3217         ASSERT(cp != NULL);
3218         cp[0] = '\0';
3219
3220         if ((error = spa_open(dataset, &spa, FTAG)) != 0)
3221                 return (error);
3222
3223         spa_vers = spa_version(spa);
3224         spa_close(spa, FTAG);
3225
3226         zplver = zfs_zpl_version_map(spa_vers);
3227         fuids_ok = (zplver >= ZPL_VERSION_FUID);
3228         sa_ok = (zplver >= ZPL_VERSION_SA);
3229
3230         /*
3231          * Open parent object set so we can inherit zplprop values.
3232          */
3233         if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
3234                 return (error);
3235
3236         error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
3237             zplprops, is_ci);
3238         dmu_objset_rele(os, FTAG);
3239         return (error);
3240 }
3241
3242 static int
3243 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
3244     nvlist_t *zplprops, boolean_t *is_ci)
3245 {
3246         boolean_t fuids_ok;
3247         boolean_t sa_ok;
3248         uint64_t zplver = ZPL_VERSION;
3249         int error;
3250
3251         zplver = zfs_zpl_version_map(spa_vers);
3252         fuids_ok = (zplver >= ZPL_VERSION_FUID);
3253         sa_ok = (zplver >= ZPL_VERSION_SA);
3254
3255         error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
3256             createprops, zplprops, is_ci);
3257         return (error);
3258 }
3259
3260 /*
3261  * innvl: {
3262  *     "type" -> dmu_objset_type_t (int32)
3263  *     (optional) "props" -> { prop -> value }
3264  * }
3265  *
3266  * outnvl: propname -> error code (int32)
3267  */
3268 static int
3269 zfs_ioc_create(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3270 {
3271         int error = 0;
3272         zfs_creat_t zct = { 0 };
3273         nvlist_t *nvprops = NULL;
3274         void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
3275         int32_t type32;
3276         dmu_objset_type_t type;
3277         boolean_t is_insensitive = B_FALSE;
3278
3279         if (nvlist_lookup_int32(innvl, "type", &type32) != 0)
3280                 return (SET_ERROR(EINVAL));
3281         type = type32;
3282         (void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3283
3284         switch (type) {
3285         case DMU_OST_ZFS:
3286                 cbfunc = zfs_create_cb;
3287                 break;
3288
3289         case DMU_OST_ZVOL:
3290                 cbfunc = zvol_create_cb;
3291                 break;
3292
3293         default:
3294                 cbfunc = NULL;
3295                 break;
3296         }
3297         if (strchr(fsname, '@') ||
3298             strchr(fsname, '%'))
3299                 return (SET_ERROR(EINVAL));
3300
3301         zct.zct_props = nvprops;
3302
3303         if (cbfunc == NULL)
3304                 return (SET_ERROR(EINVAL));
3305
3306         if (type == DMU_OST_ZVOL) {
3307                 uint64_t volsize, volblocksize;
3308
3309                 if (nvprops == NULL)
3310                         return (SET_ERROR(EINVAL));
3311                 if (nvlist_lookup_uint64(nvprops,
3312                     zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) != 0)
3313                         return (SET_ERROR(EINVAL));
3314
3315                 if ((error = nvlist_lookup_uint64(nvprops,
3316                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3317                     &volblocksize)) != 0 && error != ENOENT)
3318                         return (SET_ERROR(EINVAL));
3319
3320                 if (error != 0)
3321                         volblocksize = zfs_prop_default_numeric(
3322                             ZFS_PROP_VOLBLOCKSIZE);
3323
3324                 if ((error = zvol_check_volblocksize(
3325                     volblocksize)) != 0 ||
3326                     (error = zvol_check_volsize(volsize,
3327                     volblocksize)) != 0)
3328                         return (error);
3329         } else if (type == DMU_OST_ZFS) {
3330                 int error;
3331
3332                 /*
3333                  * We have to have normalization and
3334                  * case-folding flags correct when we do the
3335                  * file system creation, so go figure them out
3336                  * now.
3337                  */
3338                 VERIFY(nvlist_alloc(&zct.zct_zplprops,
3339                     NV_UNIQUE_NAME, KM_SLEEP) == 0);
3340                 error = zfs_fill_zplprops(fsname, nvprops,
3341                     zct.zct_zplprops, &is_insensitive);
3342                 if (error != 0) {
3343                         nvlist_free(zct.zct_zplprops);
3344                         return (error);
3345                 }
3346         }
3347
3348         error = dmu_objset_create(fsname, type,
3349             is_insensitive ? DS_FLAG_CI_DATASET : 0, cbfunc, &zct);
3350         nvlist_free(zct.zct_zplprops);
3351
3352         /*
3353          * It would be nice to do this atomically.
3354          */
3355         if (error == 0) {
3356                 error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
3357                     nvprops, outnvl);
3358                 if (error != 0)
3359                         (void) dsl_destroy_head(fsname);
3360         }
3361 #ifdef __FreeBSD__
3362         if (error == 0 && type == DMU_OST_ZVOL)
3363                 zvol_create_minors(fsname);
3364 #endif
3365         return (error);
3366 }
3367
3368 /*
3369  * innvl: {
3370  *     "origin" -> name of origin snapshot
3371  *     (optional) "props" -> { prop -> value }
3372  * }
3373  *
3374  * outnvl: propname -> error code (int32)
3375  */
3376 static int
3377 zfs_ioc_clone(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3378 {
3379         int error = 0;
3380         nvlist_t *nvprops = NULL;
3381         char *origin_name;
3382
3383         if (nvlist_lookup_string(innvl, "origin", &origin_name) != 0)
3384                 return (SET_ERROR(EINVAL));
3385         (void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3386
3387         if (strchr(fsname, '@') ||
3388             strchr(fsname, '%'))
3389                 return (SET_ERROR(EINVAL));
3390
3391         if (dataset_namecheck(origin_name, NULL, NULL) != 0)
3392                 return (SET_ERROR(EINVAL));
3393         error = dmu_objset_clone(fsname, origin_name);
3394         if (error != 0)
3395                 return (error);
3396
3397         /*
3398          * It would be nice to do this atomically.
3399          */
3400         if (error == 0) {
3401                 error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
3402                     nvprops, outnvl);
3403                 if (error != 0)
3404                         (void) dsl_destroy_head(fsname);
3405         }
3406 #ifdef __FreeBSD__
3407         if (error == 0)
3408                 zvol_create_minors(fsname);
3409 #endif
3410         return (error);
3411 }
3412
3413 /* ARGSUSED */
3414 static int
3415 zfs_ioc_remap(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3416 {
3417         if (strchr(fsname, '@') ||
3418             strchr(fsname, '%'))
3419                 return (SET_ERROR(EINVAL));
3420
3421         return (dmu_objset_remap_indirects(fsname));
3422 }
3423
3424 /*
3425  * innvl: {
3426  *     "snaps" -> { snapshot1, snapshot2 }
3427  *     (optional) "props" -> { prop -> value (string) }
3428  * }
3429  *
3430  * outnvl: snapshot -> error code (int32)
3431  */
3432 static int
3433 zfs_ioc_snapshot(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3434 {
3435         nvlist_t *snaps;
3436         nvlist_t *props = NULL;
3437         int error, poollen;
3438         nvpair_t *pair;
3439
3440         (void) nvlist_lookup_nvlist(innvl, "props", &props);
3441         if (!nvlist_empty(props) &&
3442             zfs_earlier_version(poolname, SPA_VERSION_SNAP_PROPS))
3443                 return (SET_ERROR(ENOTSUP));
3444         if ((error = zfs_check_userprops(props)) != 0)
3445                 return (error);
3446
3447         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3448                 return (SET_ERROR(EINVAL));
3449         poollen = strlen(poolname);
3450         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3451             pair = nvlist_next_nvpair(snaps, pair)) {
3452                 const char *name = nvpair_name(pair);
3453                 char *cp = strchr(name, '@');
3454
3455                 /*
3456                  * The snap name must contain an @, and the part after it must
3457                  * contain only valid characters.
3458                  */
3459                 if (cp == NULL ||
3460                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3461                         return (SET_ERROR(EINVAL));
3462
3463                 /*
3464                  * The snap must be in the specified pool.
3465                  */
3466                 if (strncmp(name, poolname, poollen) != 0 ||
3467                     (name[poollen] != '/' && name[poollen] != '@'))
3468                         return (SET_ERROR(EXDEV));
3469
3470                 /*
3471                  * Check for permission to set the properties on the fs.
3472                  */
3473                 if (!nvlist_empty(props)) {
3474                         *cp = '\0';
3475                         error = zfs_secpolicy_write_perms(name,
3476                             ZFS_DELEG_PERM_USERPROP, CRED());
3477                         *cp = '@';
3478                         if (error != 0)
3479                                 return (error);
3480                 }
3481
3482                 /* This must be the only snap of this fs. */
3483                 for (nvpair_t *pair2 = nvlist_next_nvpair(snaps, pair);
3484                     pair2 != NULL; pair2 = nvlist_next_nvpair(snaps, pair2)) {
3485                         if (strncmp(name, nvpair_name(pair2), cp - name + 1)
3486                             == 0) {
3487                                 return (SET_ERROR(EXDEV));
3488                         }
3489                 }
3490         }
3491
3492         error = dsl_dataset_snapshot(snaps, props, outnvl);
3493         return (error);
3494 }
3495
3496 /*
3497  * innvl: "message" -> string
3498  */
3499 /* ARGSUSED */
3500 static int
3501 zfs_ioc_log_history(const char *unused, nvlist_t *innvl, nvlist_t *outnvl)
3502 {
3503         char *message;
3504         spa_t *spa;
3505         int error;
3506         char *poolname;
3507
3508         /*
3509          * The poolname in the ioctl is not set, we get it from the TSD,
3510          * which was set at the end of the last successful ioctl that allows
3511          * logging.  The secpolicy func already checked that it is set.
3512          * Only one log ioctl is allowed after each successful ioctl, so
3513          * we clear the TSD here.
3514          */
3515         poolname = tsd_get(zfs_allow_log_key);
3516         (void) tsd_set(zfs_allow_log_key, NULL);
3517         error = spa_open(poolname, &spa, FTAG);
3518         strfree(poolname);
3519         if (error != 0)
3520                 return (error);
3521
3522         if (nvlist_lookup_string(innvl, "message", &message) != 0)  {
3523                 spa_close(spa, FTAG);
3524                 return (SET_ERROR(EINVAL));
3525         }
3526
3527         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
3528                 spa_close(spa, FTAG);
3529                 return (SET_ERROR(ENOTSUP));
3530         }
3531
3532         error = spa_history_log(spa, message);
3533         spa_close(spa, FTAG);
3534         return (error);
3535 }
3536
3537 #ifdef __FreeBSD__
3538 static int
3539 zfs_ioc_nextboot(const char *unused, nvlist_t *innvl, nvlist_t *outnvl)
3540 {
3541         char name[MAXNAMELEN];
3542         spa_t *spa;
3543         vdev_t *vd;
3544         char *command;
3545         uint64_t pool_guid;
3546         uint64_t vdev_guid;
3547         int error;
3548
3549         if (nvlist_lookup_uint64(innvl,
3550             ZPOOL_CONFIG_POOL_GUID, &pool_guid) != 0)
3551                 return (EINVAL);
3552         if (nvlist_lookup_uint64(innvl,
3553             ZPOOL_CONFIG_GUID, &vdev_guid) != 0)
3554                 return (EINVAL);
3555         if (nvlist_lookup_string(innvl,
3556             "command", &command) != 0)
3557                 return (EINVAL);
3558
3559         mutex_enter(&spa_namespace_lock);
3560         spa = spa_by_guid(pool_guid, vdev_guid);
3561         if (spa != NULL)
3562                 strcpy(name, spa_name(spa));
3563         mutex_exit(&spa_namespace_lock);
3564         if (spa == NULL)
3565                 return (ENOENT);
3566
3567         if ((error = spa_open(name, &spa, FTAG)) != 0)
3568                 return (error);
3569         spa_vdev_state_enter(spa, SCL_ALL);
3570         vd = spa_lookup_by_guid(spa, vdev_guid, B_TRUE);
3571         if (vd == NULL) {
3572                 (void) spa_vdev_state_exit(spa, NULL, ENXIO);
3573                 spa_close(spa, FTAG);
3574                 return (ENODEV);
3575         }
3576         error = vdev_label_write_pad2(vd, command, strlen(command));
3577         (void) spa_vdev_state_exit(spa, NULL, 0);
3578         txg_wait_synced(spa->spa_dsl_pool, 0);
3579         spa_close(spa, FTAG);
3580         return (error);
3581 }
3582 #endif
3583
3584 /*
3585  * The dp_config_rwlock must not be held when calling this, because the
3586  * unmount may need to write out data.
3587  *
3588  * This function is best-effort.  Callers must deal gracefully if it
3589  * remains mounted (or is remounted after this call).
3590  *
3591  * Returns 0 if the argument is not a snapshot, or it is not currently a
3592  * filesystem, or we were able to unmount it.  Returns error code otherwise.
3593  */
3594 void
3595 zfs_unmount_snap(const char *snapname)
3596 {
3597         vfs_t *vfsp = NULL;
3598         zfsvfs_t *zfsvfs = NULL;
3599
3600         if (strchr(snapname, '@') == NULL)
3601                 return;
3602
3603         int err = getzfsvfs(snapname, &zfsvfs);
3604         if (err != 0) {
3605                 ASSERT3P(zfsvfs, ==, NULL);
3606                 return;
3607         }
3608         vfsp = zfsvfs->z_vfs;
3609
3610         ASSERT(!dsl_pool_config_held(dmu_objset_pool(zfsvfs->z_os)));
3611
3612 #ifdef illumos
3613         err = vn_vfswlock(vfsp->vfs_vnodecovered);
3614         VFS_RELE(vfsp);
3615         if (err != 0)
3616                 return;
3617 #endif
3618
3619         /*
3620          * Always force the unmount for snapshots.
3621          */
3622 #ifdef illumos
3623         (void) dounmount(vfsp, MS_FORCE, kcred);
3624 #else
3625         vfs_ref(vfsp);
3626         vfs_unbusy(vfsp);
3627         (void) dounmount(vfsp, MS_FORCE, curthread);
3628 #endif
3629 }
3630
3631 /* ARGSUSED */
3632 static int
3633 zfs_unmount_snap_cb(const char *snapname, void *arg)
3634 {
3635         zfs_unmount_snap(snapname);
3636         return (0);
3637 }
3638
3639 /*
3640  * When a clone is destroyed, its origin may also need to be destroyed,
3641  * in which case it must be unmounted.  This routine will do that unmount
3642  * if necessary.
3643  */
3644 void
3645 zfs_destroy_unmount_origin(const char *fsname)
3646 {
3647         int error;
3648         objset_t *os;
3649         dsl_dataset_t *ds;
3650
3651         error = dmu_objset_hold(fsname, FTAG, &os);
3652         if (error != 0)
3653                 return;
3654         ds = dmu_objset_ds(os);
3655         if (dsl_dir_is_clone(ds->ds_dir) && DS_IS_DEFER_DESTROY(ds->ds_prev)) {
3656                 char originname[ZFS_MAX_DATASET_NAME_LEN];
3657                 dsl_dataset_name(ds->ds_prev, originname);
3658                 dmu_objset_rele(os, FTAG);
3659                 zfs_unmount_snap(originname);
3660         } else {
3661                 dmu_objset_rele(os, FTAG);
3662         }
3663 }
3664
3665 /*
3666  * innvl: {
3667  *     "snaps" -> { snapshot1, snapshot2 }
3668  *     (optional boolean) "defer"
3669  * }
3670  *
3671  * outnvl: snapshot -> error code (int32)
3672  *
3673  */
3674 /* ARGSUSED */
3675 static int
3676 zfs_ioc_destroy_snaps(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3677 {
3678         int error, poollen;
3679         nvlist_t *snaps;
3680         nvpair_t *pair;
3681         boolean_t defer;
3682
3683         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3684                 return (SET_ERROR(EINVAL));
3685         defer = nvlist_exists(innvl, "defer");
3686
3687         poollen = strlen(poolname);
3688         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3689             pair = nvlist_next_nvpair(snaps, pair)) {
3690                 const char *name = nvpair_name(pair);
3691
3692                 /*
3693                  * The snap must be in the specified pool to prevent the
3694                  * invalid removal of zvol minors below.
3695                  */
3696                 if (strncmp(name, poolname, poollen) != 0 ||
3697                     (name[poollen] != '/' && name[poollen] != '@'))
3698                         return (SET_ERROR(EXDEV));
3699
3700                 zfs_unmount_snap(nvpair_name(pair));
3701 #if defined(__FreeBSD__)
3702                 zvol_remove_minors(name);
3703 #endif
3704         }
3705
3706         return (dsl_destroy_snapshots_nvl(snaps, defer, outnvl));
3707 }
3708
3709 /*
3710  * Create bookmarks.  Bookmark names are of the form <fs>#<bmark>.
3711  * All bookmarks must be in the same pool.
3712  *
3713  * innvl: {
3714  *     bookmark1 -> snapshot1, bookmark2 -> snapshot2
3715  * }
3716  *
3717  * outnvl: bookmark -> error code (int32)
3718  *
3719  */
3720 /* ARGSUSED */
3721 static int
3722 zfs_ioc_bookmark(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3723 {
3724         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3725             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3726                 char *snap_name;
3727
3728                 /*
3729                  * Verify the snapshot argument.
3730                  */
3731                 if (nvpair_value_string(pair, &snap_name) != 0)
3732                         return (SET_ERROR(EINVAL));
3733
3734
3735                 /* Verify that the keys (bookmarks) are unique */
3736                 for (nvpair_t *pair2 = nvlist_next_nvpair(innvl, pair);
3737                     pair2 != NULL; pair2 = nvlist_next_nvpair(innvl, pair2)) {
3738                         if (strcmp(nvpair_name(pair), nvpair_name(pair2)) == 0)
3739                                 return (SET_ERROR(EINVAL));
3740                 }
3741         }
3742
3743         return (dsl_bookmark_create(innvl, outnvl));
3744 }
3745
3746 /*
3747  * innvl: {
3748  *     property 1, property 2, ...
3749  * }
3750  *
3751  * outnvl: {
3752  *     bookmark name 1 -> { property 1, property 2, ... },
3753  *     bookmark name 2 -> { property 1, property 2, ... }
3754  * }
3755  *
3756  */
3757 static int
3758 zfs_ioc_get_bookmarks(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3759 {
3760         return (dsl_get_bookmarks(fsname, innvl, outnvl));
3761 }
3762
3763 /*
3764  * innvl: {
3765  *     bookmark name 1, bookmark name 2
3766  * }
3767  *
3768  * outnvl: bookmark -> error code (int32)
3769  *
3770  */
3771 static int
3772 zfs_ioc_destroy_bookmarks(const char *poolname, nvlist_t *innvl,
3773     nvlist_t *outnvl)
3774 {
3775         int error, poollen;
3776
3777         poollen = strlen(poolname);
3778         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3779             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3780                 const char *name = nvpair_name(pair);
3781                 const char *cp = strchr(name, '#');
3782
3783                 /*
3784                  * The bookmark name must contain an #, and the part after it
3785                  * must contain only valid characters.
3786                  */
3787                 if (cp == NULL ||
3788                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3789                         return (SET_ERROR(EINVAL));
3790
3791                 /*
3792                  * The bookmark must be in the specified pool.
3793                  */
3794                 if (strncmp(name, poolname, poollen) != 0 ||
3795                     (name[poollen] != '/' && name[poollen] != '#'))
3796                         return (SET_ERROR(EXDEV));
3797         }
3798
3799         error = dsl_bookmark_destroy(innvl, outnvl);
3800         return (error);
3801 }
3802
3803 static int
3804 zfs_ioc_channel_program(const char *poolname, nvlist_t *innvl,
3805     nvlist_t *outnvl)
3806 {
3807         char *program;
3808         uint64_t instrlimit, memlimit;
3809         boolean_t sync_flag;
3810         nvpair_t *nvarg = NULL;
3811
3812         if (0 != nvlist_lookup_string(innvl, ZCP_ARG_PROGRAM, &program)) {
3813                 return (EINVAL);
3814         }
3815         if (0 != nvlist_lookup_boolean_value(innvl, ZCP_ARG_SYNC, &sync_flag)) {
3816                 sync_flag = B_TRUE;
3817         }
3818         if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_INSTRLIMIT, &instrlimit)) {
3819                 instrlimit = ZCP_DEFAULT_INSTRLIMIT;
3820         }
3821         if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_MEMLIMIT, &memlimit)) {
3822                 memlimit = ZCP_DEFAULT_MEMLIMIT;
3823         }
3824         if (0 != nvlist_lookup_nvpair(innvl, ZCP_ARG_ARGLIST, &nvarg)) {
3825                 return (EINVAL);
3826         }
3827
3828         if (instrlimit == 0 || instrlimit > zfs_lua_max_instrlimit)
3829                 return (EINVAL);
3830         if (memlimit == 0 || memlimit > zfs_lua_max_memlimit)
3831                 return (EINVAL);
3832
3833         return (zcp_eval(poolname, program, sync_flag, instrlimit, memlimit,
3834             nvarg, outnvl));
3835 }
3836
3837 /*
3838  * innvl: unused
3839  * outnvl: empty
3840  */
3841 /* ARGSUSED */
3842 static int
3843 zfs_ioc_pool_checkpoint(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3844 {
3845         return (spa_checkpoint(poolname));
3846 }
3847
3848 /*
3849  * innvl: unused
3850  * outnvl: empty
3851  */
3852 /* ARGSUSED */
3853 static int
3854 zfs_ioc_pool_discard_checkpoint(const char *poolname, nvlist_t *innvl,
3855     nvlist_t *outnvl)
3856 {
3857         return (spa_checkpoint_discard(poolname));
3858 }
3859
3860 /*
3861  * inputs:
3862  * zc_name              name of dataset to destroy
3863  * zc_defer_destroy     mark for deferred destroy
3864  *
3865  * outputs:             none
3866  */
3867 static int
3868 zfs_ioc_destroy(zfs_cmd_t *zc)
3869 {
3870         objset_t *os;
3871         dmu_objset_type_t ost;
3872         int err;
3873
3874         err = dmu_objset_hold(zc->zc_name, FTAG, &os);
3875         if (err != 0)
3876                 return (err);
3877         ost = dmu_objset_type(os);
3878         dmu_objset_rele(os, FTAG);
3879
3880         if (ost == DMU_OST_ZFS)
3881                 zfs_unmount_snap(zc->zc_name);
3882
3883         if (strchr(zc->zc_name, '@'))
3884                 err = dsl_destroy_snapshot(zc->zc_name, zc->zc_defer_destroy);
3885         else
3886                 err = dsl_destroy_head(zc->zc_name);
3887         if (ost == DMU_OST_ZVOL && err == 0)
3888 #ifdef __FreeBSD__
3889                 zvol_remove_minors(zc->zc_name);
3890 #else
3891                 (void) zvol_remove_minor(zc->zc_name);
3892 #endif
3893         return (err);
3894 }
3895
3896 /*
3897  * innvl: {
3898  *     vdevs: {
3899  *         guid 1, guid 2, ...
3900  *     },
3901  *     func: POOL_INITIALIZE_{CANCEL|DO|SUSPEND}
3902  * }
3903  *
3904  * outnvl: {
3905  *     [func: EINVAL (if provided command type didn't make sense)],
3906  *     [vdevs: {
3907  *         guid1: errno, (see function body for possible errnos)
3908  *         ...
3909  *     }]
3910  * }
3911  *
3912  */
3913 static int
3914 zfs_ioc_pool_initialize(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3915 {
3916         spa_t *spa;
3917         int error;
3918
3919         error = spa_open(poolname, &spa, FTAG);
3920         if (error != 0)
3921                 return (error);
3922
3923         uint64_t cmd_type;
3924         if (nvlist_lookup_uint64(innvl, ZPOOL_INITIALIZE_COMMAND,
3925             &cmd_type) != 0) {
3926                 spa_close(spa, FTAG);
3927                 return (SET_ERROR(EINVAL));
3928         }
3929         if (!(cmd_type == POOL_INITIALIZE_CANCEL ||
3930             cmd_type == POOL_INITIALIZE_DO ||
3931             cmd_type == POOL_INITIALIZE_SUSPEND)) {
3932                 spa_close(spa, FTAG);
3933                 return (SET_ERROR(EINVAL));
3934         }
3935
3936         nvlist_t *vdev_guids;
3937         if (nvlist_lookup_nvlist(innvl, ZPOOL_INITIALIZE_VDEVS,
3938             &vdev_guids) != 0) {
3939                 spa_close(spa, FTAG);
3940                 return (SET_ERROR(EINVAL));
3941         }
3942
3943         nvlist_t *vdev_errlist = fnvlist_alloc();
3944         int total_errors = 0;
3945
3946         for (nvpair_t *pair = nvlist_next_nvpair(vdev_guids, NULL);
3947             pair != NULL; pair = nvlist_next_nvpair(vdev_guids, pair)) {
3948                 uint64_t vdev_guid = fnvpair_value_uint64(pair);
3949
3950                 error = spa_vdev_initialize(spa, vdev_guid, cmd_type);
3951                 if (error != 0) {
3952                         char guid_as_str[MAXNAMELEN];
3953
3954                         (void) snprintf(guid_as_str, sizeof (guid_as_str),
3955                             "%llu", (unsigned long long)vdev_guid);
3956                         fnvlist_add_int64(vdev_errlist, guid_as_str, error);
3957                         total_errors++;
3958                 }
3959         }
3960         if (fnvlist_size(vdev_errlist) > 0) {
3961                 fnvlist_add_nvlist(outnvl, ZPOOL_INITIALIZE_VDEVS,
3962                     vdev_errlist);
3963         }
3964         fnvlist_free(vdev_errlist);
3965
3966         spa_close(spa, FTAG);
3967         return (total_errors > 0 ? EINVAL : 0);
3968 }
3969
3970 /*
3971  * fsname is name of dataset to rollback (to most recent snapshot)
3972  *
3973  * innvl may contain name of expected target snapshot
3974  *
3975  * outnvl: "target" -> name of most recent snapshot
3976  * }
3977  */
3978 /* ARGSUSED */
3979 static int
3980 zfs_ioc_rollback(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3981 {
3982         zfsvfs_t *zfsvfs;
3983         char *target = NULL;
3984         int error;
3985
3986         (void) nvlist_lookup_string(innvl, "target", &target);
3987         if (target != NULL) {
3988                 const char *cp = strchr(target, '@');
3989
3990                 /*
3991                  * The snap name must contain an @, and the part after it must
3992                  * contain only valid characters.
3993                  */
3994                 if (cp == NULL ||
3995                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3996                         return (SET_ERROR(EINVAL));
3997         }
3998
3999         if (getzfsvfs(fsname, &zfsvfs) == 0) {
4000                 dsl_dataset_t *ds;
4001
4002                 ds = dmu_objset_ds(zfsvfs->z_os);
4003                 error = zfs_suspend_fs(zfsvfs);
4004                 if (error == 0) {
4005                         int resume_err;
4006
4007                         error = dsl_dataset_rollback(fsname, target, zfsvfs,
4008                             outnvl);
4009                         resume_err = zfs_resume_fs(zfsvfs, ds);
4010                         error = error ? error : resume_err;
4011                 }
4012 #ifdef illumos
4013                 VFS_RELE(zfsvfs->z_vfs);
4014 #else
4015                 vfs_unbusy(zfsvfs->z_vfs);
4016 #endif
4017         } else {
4018                 error = dsl_dataset_rollback(fsname, target, NULL, outnvl);
4019         }
4020         return (error);
4021 }
4022
4023 static int
4024 recursive_unmount(const char *fsname, void *arg)
4025 {
4026         const char *snapname = arg;
4027         char fullname[ZFS_MAX_DATASET_NAME_LEN];
4028
4029         (void) snprintf(fullname, sizeof (fullname), "%s@%s", fsname, snapname);
4030         zfs_unmount_snap(fullname);
4031
4032         return (0);
4033 }
4034
4035 /*
4036  * inputs:
4037  * zc_name      old name of dataset or bookmark
4038  * zc_value     new name of dataset or bookmark
4039  * zc_cookie    recursive flag (only valid for snapshots)
4040  *
4041  * outputs:     none
4042  */
4043 static int
4044 zfs_ioc_rename(zfs_cmd_t *zc)
4045 {
4046         objset_t *os;
4047         dmu_objset_type_t ost;
4048         boolean_t recursive = zc->zc_cookie & 1;
4049         char *pos, *pos2;
4050         boolean_t allow_mounted = B_TRUE;
4051         int err;
4052
4053 #ifdef __FreeBSD__
4054         allow_mounted = (zc->zc_cookie & 2) != 0;
4055 #endif
4056
4057         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
4058         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
4059
4060         pos = strchr(zc->zc_name, '#');
4061         if (pos != NULL) {
4062                 /* Bookmarks must be in same fs. */
4063                 pos2 = strchr(zc->zc_value, '#');
4064                 if (pos2 == NULL)
4065                         return (SET_ERROR(EINVAL));
4066
4067                 /* Recursive flag is not supported yet. */
4068                 if (recursive)
4069                         return (SET_ERROR(ENOTSUP));
4070
4071                 *pos = '\0';
4072                 *pos2 = '\0';
4073                 if (strcmp(zc->zc_name, zc->zc_value) == 0) {
4074                         err = dsl_bookmark_rename(zc->zc_name,
4075                             pos + 1, pos2 + 1);
4076                 } else {
4077                         err = SET_ERROR(EXDEV);
4078                 }
4079                 *pos = '#';
4080                 *pos2 = '#';
4081                 return (err);
4082         }
4083
4084         /* "zfs rename" from and to ...%recv datasets should both fail */
4085         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
4086             dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
4087             strchr(zc->zc_name, '%') || strchr(zc->zc_value, '%'))
4088                 return (SET_ERROR(EINVAL));
4089
4090         err = dmu_objset_hold(zc->zc_name, FTAG, &os);
4091         if (err != 0)
4092                 return (err);
4093         ost = dmu_objset_type(os);
4094         dmu_objset_rele(os, FTAG);
4095
4096         pos = strchr(zc->zc_name, '@');
4097         if (pos != NULL) {
4098                 /* Snapshots must be in same fs. */
4099                 pos2 = strchr(zc->zc_value, '@');
4100                 if (pos2 == NULL)
4101                         return (SET_ERROR(EINVAL));
4102                 *pos = '\0';
4103                 *pos2 = '\0';
4104                 if (strcmp(zc->zc_name, zc->zc_value) != 0) {
4105                         err = SET_ERROR(EXDEV);
4106                 } else {
4107                         if (ost == DMU_OST_ZFS && !allow_mounted) {
4108                                 err = dmu_objset_find(zc->zc_name,
4109                                     recursive_unmount, pos + 1,
4110                                     recursive ? DS_FIND_CHILDREN : 0);
4111                         }
4112                         if (err == 0) {
4113                                 err = dsl_dataset_rename_snapshot(zc->zc_name,
4114                                     pos + 1, pos2 + 1, recursive);
4115                         }
4116                 }
4117                 *pos = '@';
4118                 *pos2 = '@';
4119                 return (err);
4120         } else {
4121 #ifdef illumos
4122                 if (ost == DMU_OST_ZVOL)
4123                         (void) zvol_remove_minor(zc->zc_name);
4124 #endif
4125                 return (dsl_dir_rename(zc->zc_name, zc->zc_value));
4126         }
4127 }
4128
4129 static int
4130 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
4131 {
4132         const char *propname = nvpair_name(pair);
4133         boolean_t issnap = (strchr(dsname, '@') != NULL);
4134         zfs_prop_t prop = zfs_name_to_prop(propname);
4135         uint64_t intval;
4136         int err;
4137
4138         if (prop == ZPROP_INVAL) {
4139                 if (zfs_prop_user(propname)) {
4140                         if (err = zfs_secpolicy_write_perms(dsname,
4141                             ZFS_DELEG_PERM_USERPROP, cr))
4142                                 return (err);
4143                         return (0);
4144                 }
4145
4146                 if (!issnap && zfs_prop_userquota(propname)) {
4147                         const char *perm = NULL;
4148                         const char *uq_prefix =
4149                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
4150                         const char *gq_prefix =
4151                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
4152
4153                         if (strncmp(propname, uq_prefix,
4154                             strlen(uq_prefix)) == 0) {
4155                                 perm = ZFS_DELEG_PERM_USERQUOTA;
4156                         } else if (strncmp(propname, gq_prefix,
4157                             strlen(gq_prefix)) == 0) {
4158                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
4159                         } else {
4160                                 /* USERUSED and GROUPUSED are read-only */
4161                                 return (SET_ERROR(EINVAL));
4162                         }
4163
4164                         if (err = zfs_secpolicy_write_perms(dsname, perm, cr))
4165                                 return (err);
4166                         return (0);
4167                 }
4168
4169                 return (SET_ERROR(EINVAL));
4170         }
4171
4172         if (issnap)
4173                 return (SET_ERROR(EINVAL));
4174
4175         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
4176                 /*
4177                  * dsl_prop_get_all_impl() returns properties in this
4178                  * format.
4179                  */
4180                 nvlist_t *attrs;
4181                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
4182                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4183                     &pair) == 0);
4184         }
4185
4186         /*
4187          * Check that this value is valid for this pool version
4188          */
4189         switch (prop) {
4190         case ZFS_PROP_COMPRESSION:
4191                 /*
4192                  * If the user specified gzip compression, make sure
4193                  * the SPA supports it. We ignore any errors here since
4194                  * we'll catch them later.
4195                  */
4196                 if (nvpair_value_uint64(pair, &intval) == 0) {
4197                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
4198                             intval <= ZIO_COMPRESS_GZIP_9 &&
4199                             zfs_earlier_version(dsname,
4200                             SPA_VERSION_GZIP_COMPRESSION)) {
4201                                 return (SET_ERROR(ENOTSUP));
4202                         }
4203
4204                         if (intval == ZIO_COMPRESS_ZLE &&
4205                             zfs_earlier_version(dsname,
4206                             SPA_VERSION_ZLE_COMPRESSION))
4207                                 return (SET_ERROR(ENOTSUP));
4208
4209                         if (intval == ZIO_COMPRESS_LZ4) {
4210                                 spa_t *spa;
4211
4212                                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4213                                         return (err);
4214
4215                                 if (!spa_feature_is_enabled(spa,
4216                                     SPA_FEATURE_LZ4_COMPRESS)) {
4217                                         spa_close(spa, FTAG);
4218                                         return (SET_ERROR(ENOTSUP));
4219                                 }
4220                                 spa_close(spa, FTAG);
4221                         }
4222
4223                         /*
4224                          * If this is a bootable dataset then
4225                          * verify that the compression algorithm
4226                          * is supported for booting. We must return
4227                          * something other than ENOTSUP since it
4228                          * implies a downrev pool version.
4229                          */
4230                         if (zfs_is_bootfs(dsname) &&
4231                             !BOOTFS_COMPRESS_VALID(intval)) {
4232                                 return (SET_ERROR(ERANGE));
4233                         }
4234                 }
4235                 break;
4236
4237         case ZFS_PROP_COPIES:
4238                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
4239                         return (SET_ERROR(ENOTSUP));
4240                 break;
4241
4242         case ZFS_PROP_RECORDSIZE:
4243                 /* Record sizes above 128k need the feature to be enabled */
4244                 if (nvpair_value_uint64(pair, &intval) == 0 &&
4245                     intval > SPA_OLD_MAXBLOCKSIZE) {
4246                         spa_t *spa;
4247
4248                         /*
4249                          * We don't allow setting the property above 1MB,
4250                          * unless the tunable has been changed.
4251                          */
4252                         if (intval > zfs_max_recordsize ||
4253                             intval > SPA_MAXBLOCKSIZE)
4254                                 return (SET_ERROR(ERANGE));
4255
4256                         if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4257                                 return (err);
4258
4259                         if (!spa_feature_is_enabled(spa,
4260                             SPA_FEATURE_LARGE_BLOCKS)) {
4261                                 spa_close(spa, FTAG);
4262                                 return (SET_ERROR(ENOTSUP));
4263                         }
4264                         spa_close(spa, FTAG);
4265                 }
4266                 break;
4267
4268         case ZFS_PROP_DNODESIZE:
4269                 /* Dnode sizes above 512 need the feature to be enabled */
4270                 if (nvpair_value_uint64(pair, &intval) == 0 &&
4271                     intval != ZFS_DNSIZE_LEGACY) {
4272                         spa_t *spa;
4273
4274                         if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4275                                 return (err);
4276
4277                         if (!spa_feature_is_enabled(spa,
4278                             SPA_FEATURE_LARGE_DNODE)) {
4279                                 spa_close(spa, FTAG);
4280                                 return (SET_ERROR(ENOTSUP));
4281                         }
4282                         spa_close(spa, FTAG);
4283                 }
4284                 break;
4285
4286         case ZFS_PROP_SHARESMB:
4287                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
4288                         return (SET_ERROR(ENOTSUP));
4289                 break;
4290
4291         case ZFS_PROP_ACLINHERIT:
4292                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
4293                     nvpair_value_uint64(pair, &intval) == 0) {
4294                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
4295                             zfs_earlier_version(dsname,
4296                             SPA_VERSION_PASSTHROUGH_X))
4297                                 return (SET_ERROR(ENOTSUP));
4298                 }
4299                 break;
4300
4301         case ZFS_PROP_CHECKSUM:
4302         case ZFS_PROP_DEDUP:
4303         {
4304                 spa_feature_t feature;
4305                 spa_t *spa;
4306
4307                 /* dedup feature version checks */
4308                 if (prop == ZFS_PROP_DEDUP &&
4309                     zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
4310                         return (SET_ERROR(ENOTSUP));
4311
4312                 if (nvpair_value_uint64(pair, &intval) != 0)
4313                         return (SET_ERROR(EINVAL));
4314
4315                 /* check prop value is enabled in features */
4316                 feature = zio_checksum_to_feature(intval & ZIO_CHECKSUM_MASK);
4317                 if (feature == SPA_FEATURE_NONE)
4318                         break;
4319
4320                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
4321                         return (err);
4322                 /*
4323                  * Salted checksums are not supported on root pools.
4324                  */
4325                 if (spa_bootfs(spa) != 0 &&
4326                     intval < ZIO_CHECKSUM_FUNCTIONS &&
4327                     (zio_checksum_table[intval].ci_flags &
4328                     ZCHECKSUM_FLAG_SALTED)) {
4329                         spa_close(spa, FTAG);
4330                         return (SET_ERROR(ERANGE));
4331                 }
4332                 if (!spa_feature_is_enabled(spa, feature)) {
4333                         spa_close(spa, FTAG);
4334                         return (SET_ERROR(ENOTSUP));
4335                 }
4336                 spa_close(spa, FTAG);
4337                 break;
4338         }
4339         }
4340
4341         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
4342 }
4343
4344 /*
4345  * Checks for a race condition to make sure we don't increment a feature flag
4346  * multiple times.
4347  */
4348 static int
4349 zfs_prop_activate_feature_check(void *arg, dmu_tx_t *tx)
4350 {
4351         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4352         spa_feature_t *featurep = arg;
4353
4354         if (!spa_feature_is_active(spa, *featurep))
4355                 return (0);
4356         else
4357                 return (SET_ERROR(EBUSY));
4358 }
4359
4360 /*
4361  * The callback invoked on feature activation in the sync task caused by
4362  * zfs_prop_activate_feature.
4363  */
4364 static void
4365 zfs_prop_activate_feature_sync(void *arg, dmu_tx_t *tx)
4366 {
4367         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4368         spa_feature_t *featurep = arg;
4369
4370         spa_feature_incr(spa, *featurep, tx);
4371 }
4372
4373 /*
4374  * Activates a feature on a pool in response to a property setting. This
4375  * creates a new sync task which modifies the pool to reflect the feature
4376  * as being active.
4377  */
4378 static int
4379 zfs_prop_activate_feature(spa_t *spa, spa_feature_t feature)
4380 {
4381         int err;
4382
4383         /* EBUSY here indicates that the feature is already active */
4384         err = dsl_sync_task(spa_name(spa),
4385             zfs_prop_activate_feature_check, zfs_prop_activate_feature_sync,
4386             &feature, 2, ZFS_SPACE_CHECK_RESERVED);
4387
4388         if (err != 0 && err != EBUSY)
4389                 return (err);
4390         else
4391                 return (0);
4392 }
4393
4394 /*
4395  * Removes properties from the given props list that fail permission checks
4396  * needed to clear them and to restore them in case of a receive error. For each
4397  * property, make sure we have both set and inherit permissions.
4398  *
4399  * Returns the first error encountered if any permission checks fail. If the
4400  * caller provides a non-NULL errlist, it also gives the complete list of names
4401  * of all the properties that failed a permission check along with the
4402  * corresponding error numbers. The caller is responsible for freeing the
4403  * returned errlist.
4404  *
4405  * If every property checks out successfully, zero is returned and the list
4406  * pointed at by errlist is NULL.
4407  */
4408 static int
4409 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
4410 {
4411         zfs_cmd_t *zc;
4412         nvpair_t *pair, *next_pair;
4413         nvlist_t *errors;
4414         int err, rv = 0;
4415
4416         if (props == NULL)
4417                 return (0);
4418
4419         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4420
4421         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
4422         (void) strcpy(zc->zc_name, dataset);
4423         pair = nvlist_next_nvpair(props, NULL);
4424         while (pair != NULL) {
4425                 next_pair = nvlist_next_nvpair(props, pair);
4426
4427                 (void) strcpy(zc->zc_value, nvpair_name(pair));
4428                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
4429                     (err = zfs_secpolicy_inherit_prop(zc, NULL, CRED())) != 0) {
4430                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
4431                         VERIFY(nvlist_add_int32(errors,
4432                             zc->zc_value, err) == 0);
4433                 }
4434                 pair = next_pair;
4435         }
4436         kmem_free(zc, sizeof (zfs_cmd_t));
4437
4438         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
4439                 nvlist_free(errors);
4440                 errors = NULL;
4441         } else {
4442                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
4443         }
4444
4445         if (errlist == NULL)
4446                 nvlist_free(errors);
4447         else
4448                 *errlist = errors;
4449
4450         return (rv);
4451 }
4452
4453 static boolean_t
4454 propval_equals(nvpair_t *p1, nvpair_t *p2)
4455 {
4456         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
4457                 /* dsl_prop_get_all_impl() format */
4458                 nvlist_t *attrs;
4459                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
4460                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4461                     &p1) == 0);
4462         }
4463
4464         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
4465                 nvlist_t *attrs;
4466                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
4467                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4468                     &p2) == 0);
4469         }
4470
4471         if (nvpair_type(p1) != nvpair_type(p2))
4472                 return (B_FALSE);
4473
4474         if (nvpair_type(p1) == DATA_TYPE_STRING) {
4475                 char *valstr1, *valstr2;
4476
4477                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
4478                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
4479                 return (strcmp(valstr1, valstr2) == 0);
4480         } else {
4481                 uint64_t intval1, intval2;
4482
4483                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
4484                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
4485                 return (intval1 == intval2);
4486         }
4487 }
4488
4489 /*
4490  * Remove properties from props if they are not going to change (as determined
4491  * by comparison with origprops). Remove them from origprops as well, since we
4492  * do not need to clear or restore properties that won't change.
4493  */
4494 static void
4495 props_reduce(nvlist_t *props, nvlist_t *origprops)
4496 {
4497         nvpair_t *pair, *next_pair;
4498
4499         if (origprops == NULL)
4500                 return; /* all props need to be received */
4501
4502         pair = nvlist_next_nvpair(props, NULL);
4503         while (pair != NULL) {
4504                 const char *propname = nvpair_name(pair);
4505                 nvpair_t *match;
4506
4507                 next_pair = nvlist_next_nvpair(props, pair);
4508
4509                 if ((nvlist_lookup_nvpair(origprops, propname,
4510                     &match) != 0) || !propval_equals(pair, match))
4511                         goto next; /* need to set received value */
4512
4513                 /* don't clear the existing received value */
4514                 (void) nvlist_remove_nvpair(origprops, match);
4515                 /* don't bother receiving the property */
4516                 (void) nvlist_remove_nvpair(props, pair);
4517 next:
4518                 pair = next_pair;
4519         }
4520 }
4521
4522 /*
4523  * Extract properties that cannot be set PRIOR to the receipt of a dataset.
4524  * For example, refquota cannot be set until after the receipt of a dataset,
4525  * because in replication streams, an older/earlier snapshot may exceed the
4526  * refquota.  We want to receive the older/earlier snapshot, but setting
4527  * refquota pre-receipt will set the dsl's ACTUAL quota, which will prevent
4528  * the older/earlier snapshot from being received (with EDQUOT).
4529  *
4530  * The ZFS test "zfs_receive_011_pos" demonstrates such a scenario.
4531  *
4532  * libzfs will need to be judicious handling errors encountered by props
4533  * extracted by this function.
4534  */
4535 static nvlist_t *
4536 extract_delay_props(nvlist_t *props)
4537 {
4538         nvlist_t *delayprops;
4539         nvpair_t *nvp, *tmp;
4540         static const zfs_prop_t delayable[] = { ZFS_PROP_REFQUOTA, 0 };
4541         int i;
4542
4543         VERIFY(nvlist_alloc(&delayprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4544
4545         for (nvp = nvlist_next_nvpair(props, NULL); nvp != NULL;
4546             nvp = nvlist_next_nvpair(props, nvp)) {
4547                 /*
4548                  * strcmp() is safe because zfs_prop_to_name() always returns
4549                  * a bounded string.
4550                  */
4551                 for (i = 0; delayable[i] != 0; i++) {
4552                         if (strcmp(zfs_prop_to_name(delayable[i]),
4553                             nvpair_name(nvp)) == 0) {
4554                                 break;
4555                         }
4556                 }
4557                 if (delayable[i] != 0) {
4558                         tmp = nvlist_prev_nvpair(props, nvp);
4559                         VERIFY(nvlist_add_nvpair(delayprops, nvp) == 0);
4560                         VERIFY(nvlist_remove_nvpair(props, nvp) == 0);
4561                         nvp = tmp;
4562                 }
4563         }
4564
4565         if (nvlist_empty(delayprops)) {
4566                 nvlist_free(delayprops);
4567                 delayprops = NULL;
4568         }
4569         return (delayprops);
4570 }
4571
4572 #ifdef  DEBUG
4573 static boolean_t zfs_ioc_recv_inject_err;
4574 #endif
4575
4576 /*
4577  * inputs:
4578  * zc_name              name of containing filesystem
4579  * zc_nvlist_src{_size} nvlist of properties to apply
4580  * zc_value             name of snapshot to create
4581  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
4582  * zc_cookie            file descriptor to recv from
4583  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
4584  * zc_guid              force flag
4585  * zc_cleanup_fd        cleanup-on-exit file descriptor
4586  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
4587  * zc_resumable         if data is incomplete assume sender will resume
4588  *
4589  * outputs:
4590  * zc_cookie            number of bytes read
4591  * zc_nvlist_dst{_size} error for each unapplied received property
4592  * zc_obj               zprop_errflags_t
4593  * zc_action_handle     handle for this guid/ds mapping
4594  */
4595 static int
4596 zfs_ioc_recv(zfs_cmd_t *zc)
4597 {
4598         file_t *fp;
4599         dmu_recv_cookie_t drc;
4600         boolean_t force = (boolean_t)zc->zc_guid;
4601         int fd;
4602         int error = 0;
4603         int props_error = 0;
4604         nvlist_t *errors;
4605         offset_t off;
4606         nvlist_t *props = NULL; /* sent properties */
4607         nvlist_t *origprops = NULL; /* existing properties */
4608         nvlist_t *delayprops = NULL; /* sent properties applied post-receive */
4609         char *origin = NULL;
4610         char *tosnap;
4611         char tofs[ZFS_MAX_DATASET_NAME_LEN];
4612         boolean_t first_recvd_props = B_FALSE;
4613
4614         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
4615             strchr(zc->zc_value, '@') == NULL ||
4616             strchr(zc->zc_value, '%'))
4617                 return (SET_ERROR(EINVAL));
4618
4619         (void) strcpy(tofs, zc->zc_value);
4620         tosnap = strchr(tofs, '@');
4621         *tosnap++ = '\0';
4622
4623         if (zc->zc_nvlist_src != 0 &&
4624             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
4625             zc->zc_iflags, &props)) != 0)
4626                 return (error);
4627
4628         fd = zc->zc_cookie;
4629 #ifdef illumos
4630         fp = getf(fd);
4631 #else
4632         fget_read(curthread, fd, &cap_pread_rights, &fp);
4633 #endif
4634         if (fp == NULL) {
4635                 nvlist_free(props);
4636                 return (SET_ERROR(EBADF));
4637         }
4638
4639         errors = fnvlist_alloc();
4640
4641         if (zc->zc_string[0])
4642                 origin = zc->zc_string;
4643
4644         error = dmu_recv_begin(tofs, tosnap,
4645             &zc->zc_begin_record, force, zc->zc_resumable, origin, &drc);
4646         if (error != 0)
4647                 goto out;
4648
4649         /*
4650          * Set properties before we receive the stream so that they are applied
4651          * to the new data. Note that we must call dmu_recv_stream() if
4652          * dmu_recv_begin() succeeds.
4653          */
4654         if (props != NULL && !drc.drc_newfs) {
4655                 if (spa_version(dsl_dataset_get_spa(drc.drc_ds)) >=
4656                     SPA_VERSION_RECVD_PROPS &&
4657                     !dsl_prop_get_hasrecvd(tofs))
4658                         first_recvd_props = B_TRUE;
4659
4660                 /*
4661                  * If new received properties are supplied, they are to
4662                  * completely replace the existing received properties, so stash
4663                  * away the existing ones.
4664                  */
4665                 if (dsl_prop_get_received(tofs, &origprops) == 0) {
4666                         nvlist_t *errlist = NULL;
4667                         /*
4668                          * Don't bother writing a property if its value won't
4669                          * change (and avoid the unnecessary security checks).
4670                          *
4671                          * The first receive after SPA_VERSION_RECVD_PROPS is a
4672                          * special case where we blow away all local properties
4673                          * regardless.
4674                          */
4675                         if (!first_recvd_props)
4676                                 props_reduce(props, origprops);
4677                         if (zfs_check_clearable(tofs, origprops, &errlist) != 0)
4678                                 (void) nvlist_merge(errors, errlist, 0);
4679                         nvlist_free(errlist);
4680
4681                         if (clear_received_props(tofs, origprops,
4682                             first_recvd_props ? NULL : props) != 0)
4683                                 zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4684                 } else {
4685                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4686                 }
4687         }
4688
4689         if (props != NULL) {
4690                 props_error = dsl_prop_set_hasrecvd(tofs);
4691
4692                 if (props_error == 0) {
4693                         delayprops = extract_delay_props(props);
4694                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4695                             props, errors);
4696                 }
4697         }
4698
4699         off = fp->f_offset;
4700         error = dmu_recv_stream(&drc, fp, &off, zc->zc_cleanup_fd,
4701             &zc->zc_action_handle);
4702
4703         if (error == 0) {
4704                 zfsvfs_t *zfsvfs = NULL;
4705
4706                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
4707                         /* online recv */
4708                         dsl_dataset_t *ds;
4709                         int end_err;
4710
4711                         ds = dmu_objset_ds(zfsvfs->z_os);
4712                         error = zfs_suspend_fs(zfsvfs);
4713                         /*
4714                          * If the suspend fails, then the recv_end will
4715                          * likely also fail, and clean up after itself.
4716                          */
4717                         end_err = dmu_recv_end(&drc, zfsvfs);
4718                         if (error == 0)
4719                                 error = zfs_resume_fs(zfsvfs, ds);
4720                         error = error ? error : end_err;
4721 #ifdef illumos
4722                         VFS_RELE(zfsvfs->z_vfs);
4723 #else
4724                         vfs_unbusy(zfsvfs->z_vfs);
4725 #endif
4726                 } else {
4727                         error = dmu_recv_end(&drc, NULL);
4728                 }
4729
4730                 /* Set delayed properties now, after we're done receiving. */
4731                 if (delayprops != NULL && error == 0) {
4732                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4733                             delayprops, errors);
4734                 }
4735         }
4736
4737         if (delayprops != NULL) {
4738                 /*
4739                  * Merge delayed props back in with initial props, in case
4740                  * we're DEBUG and zfs_ioc_recv_inject_err is set (which means
4741                  * we have to make sure clear_received_props() includes
4742                  * the delayed properties).
4743                  *
4744                  * Since zfs_ioc_recv_inject_err is only in DEBUG kernels,
4745                  * using ASSERT() will be just like a VERIFY.
4746                  */
4747                 ASSERT(nvlist_merge(props, delayprops, 0) == 0);
4748                 nvlist_free(delayprops);
4749         }
4750
4751         /*
4752          * Now that all props, initial and delayed, are set, report the prop
4753          * errors to the caller.
4754          */
4755         if (zc->zc_nvlist_dst_size != 0 &&
4756             (nvlist_smush(errors, zc->zc_nvlist_dst_size) != 0 ||
4757             put_nvlist(zc, errors) != 0)) {
4758                 /*
4759                  * Caller made zc->zc_nvlist_dst less than the minimum expected
4760                  * size or supplied an invalid address.
4761                  */
4762                 props_error = SET_ERROR(EINVAL);
4763         }
4764
4765         zc->zc_cookie = off - fp->f_offset;
4766         if (off >= 0 && off <= MAXOFFSET_T)
4767                 fp->f_offset = off;
4768
4769 #ifdef  DEBUG
4770         if (zfs_ioc_recv_inject_err) {
4771                 zfs_ioc_recv_inject_err = B_FALSE;
4772                 error = 1;
4773         }
4774 #endif
4775
4776 #ifdef __FreeBSD__
4777         if (error == 0)
4778                 zvol_create_minors(tofs);
4779 #endif
4780
4781         /*
4782          * On error, restore the original props.
4783          */
4784         if (error != 0 && props != NULL && !drc.drc_newfs) {
4785                 if (clear_received_props(tofs, props, NULL) != 0) {
4786                         /*
4787                          * We failed to clear the received properties.
4788                          * Since we may have left a $recvd value on the
4789                          * system, we can't clear the $hasrecvd flag.
4790                          */
4791                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4792                 } else if (first_recvd_props) {
4793                         dsl_prop_unset_hasrecvd(tofs);
4794                 }
4795
4796                 if (origprops == NULL && !drc.drc_newfs) {
4797                         /* We failed to stash the original properties. */
4798                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4799                 }
4800
4801                 /*
4802                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
4803                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
4804                  * explictly if we're restoring local properties cleared in the
4805                  * first new-style receive.
4806                  */
4807                 if (origprops != NULL &&
4808                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
4809                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
4810                     origprops, NULL) != 0) {
4811                         /*
4812                          * We stashed the original properties but failed to
4813                          * restore them.
4814                          */
4815                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4816                 }
4817         }
4818 out:
4819         nvlist_free(props);
4820         nvlist_free(origprops);
4821         nvlist_free(errors);
4822         releasef(fd);
4823
4824         if (error == 0)
4825                 error = props_error;
4826
4827         return (error);
4828 }
4829
4830 /*
4831  * inputs:
4832  * zc_name      name of snapshot to send
4833  * zc_cookie    file descriptor to send stream to
4834  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
4835  * zc_sendobj   objsetid of snapshot to send
4836  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
4837  * zc_guid      if set, estimate size of stream only.  zc_cookie is ignored.
4838  *              output size in zc_objset_type.
4839  * zc_flags     lzc_send_flags
4840  *
4841  * outputs:
4842  * zc_objset_type       estimated size, if zc_guid is set
4843  *
4844  * NOTE: This is no longer the preferred interface, any new functionality
4845  *        should be added to zfs_ioc_send_new() instead.
4846  */
4847 static int
4848 zfs_ioc_send(zfs_cmd_t *zc)
4849 {
4850         int error;
4851         offset_t off;
4852         boolean_t estimate = (zc->zc_guid != 0);
4853         boolean_t embedok = (zc->zc_flags & 0x1);
4854         boolean_t large_block_ok = (zc->zc_flags & 0x2);
4855         boolean_t compressok = (zc->zc_flags & 0x4);
4856
4857         if (zc->zc_obj != 0) {
4858                 dsl_pool_t *dp;
4859                 dsl_dataset_t *tosnap;
4860
4861                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4862                 if (error != 0)
4863                         return (error);
4864
4865                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4866                 if (error != 0) {
4867                         dsl_pool_rele(dp, FTAG);
4868                         return (error);
4869                 }
4870
4871                 if (dsl_dir_is_clone(tosnap->ds_dir))
4872                         zc->zc_fromobj =
4873                             dsl_dir_phys(tosnap->ds_dir)->dd_origin_obj;
4874                 dsl_dataset_rele(tosnap, FTAG);
4875                 dsl_pool_rele(dp, FTAG);
4876         }
4877
4878         if (estimate) {
4879                 dsl_pool_t *dp;
4880                 dsl_dataset_t *tosnap;
4881                 dsl_dataset_t *fromsnap = NULL;
4882
4883                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4884                 if (error != 0)
4885                         return (error);
4886
4887                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4888                 if (error != 0) {
4889                         dsl_pool_rele(dp, FTAG);
4890                         return (error);
4891                 }
4892
4893                 if (zc->zc_fromobj != 0) {
4894                         error = dsl_dataset_hold_obj(dp, zc->zc_fromobj,
4895                             FTAG, &fromsnap);
4896                         if (error != 0) {
4897                                 dsl_dataset_rele(tosnap, FTAG);
4898                                 dsl_pool_rele(dp, FTAG);
4899                                 return (error);
4900                         }
4901                 }
4902
4903                 error = dmu_send_estimate(tosnap, fromsnap, compressok,
4904                     &zc->zc_objset_type);
4905
4906                 if (fromsnap != NULL)
4907                         dsl_dataset_rele(fromsnap, FTAG);
4908                 dsl_dataset_rele(tosnap, FTAG);
4909                 dsl_pool_rele(dp, FTAG);
4910         } else {
4911                 file_t *fp;
4912
4913 #ifdef illumos
4914                 fp = getf(zc->zc_cookie);
4915 #else
4916                 fget_write(curthread, zc->zc_cookie, &cap_write_rights, &fp);
4917 #endif
4918                 if (fp == NULL)
4919                         return (SET_ERROR(EBADF));
4920
4921                 off = fp->f_offset;
4922                 error = dmu_send_obj(zc->zc_name, zc->zc_sendobj,
4923                     zc->zc_fromobj, embedok, large_block_ok, compressok,
4924 #ifdef illumos
4925                     zc->zc_cookie, fp->f_vnode, &off);
4926 #else
4927                     zc->zc_cookie, fp, &off);
4928 #endif
4929
4930                 if (off >= 0 && off <= MAXOFFSET_T)
4931                         fp->f_offset = off;
4932                 releasef(zc->zc_cookie);
4933         }
4934         return (error);
4935 }
4936
4937 /*
4938  * inputs:
4939  * zc_name      name of snapshot on which to report progress
4940  * zc_cookie    file descriptor of send stream
4941  *
4942  * outputs:
4943  * zc_cookie    number of bytes written in send stream thus far
4944  */
4945 static int
4946 zfs_ioc_send_progress(zfs_cmd_t *zc)
4947 {
4948         dsl_pool_t *dp;
4949         dsl_dataset_t *ds;
4950         dmu_sendarg_t *dsp = NULL;
4951         int error;
4952
4953         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4954         if (error != 0)
4955                 return (error);
4956
4957         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4958         if (error != 0) {
4959                 dsl_pool_rele(dp, FTAG);
4960                 return (error);
4961         }
4962
4963         mutex_enter(&ds->ds_sendstream_lock);
4964
4965         /*
4966          * Iterate over all the send streams currently active on this dataset.
4967          * If there's one which matches the specified file descriptor _and_ the
4968          * stream was started by the current process, return the progress of
4969          * that stream.
4970          */
4971         for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
4972             dsp = list_next(&ds->ds_sendstreams, dsp)) {
4973                 if (dsp->dsa_outfd == zc->zc_cookie &&
4974                     dsp->dsa_proc == curproc)
4975                         break;
4976         }
4977
4978         if (dsp != NULL)
4979                 zc->zc_cookie = *(dsp->dsa_off);
4980         else
4981                 error = SET_ERROR(ENOENT);
4982
4983         mutex_exit(&ds->ds_sendstream_lock);
4984         dsl_dataset_rele(ds, FTAG);
4985         dsl_pool_rele(dp, FTAG);
4986         return (error);
4987 }
4988
4989 static int
4990 zfs_ioc_inject_fault(zfs_cmd_t *zc)
4991 {
4992         int id, error;
4993
4994         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
4995             &zc->zc_inject_record);
4996
4997         if (error == 0)
4998                 zc->zc_guid = (uint64_t)id;
4999
5000         return (error);
5001 }
5002
5003 static int
5004 zfs_ioc_clear_fault(zfs_cmd_t *zc)
5005 {
5006         return (zio_clear_fault((int)zc->zc_guid));
5007 }
5008
5009 static int
5010 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
5011 {
5012         int id = (int)zc->zc_guid;
5013         int error;
5014
5015         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
5016             &zc->zc_inject_record);
5017
5018         zc->zc_guid = id;
5019
5020         return (error);
5021 }
5022
5023 static int
5024 zfs_ioc_error_log(zfs_cmd_t *zc)
5025 {
5026         spa_t *spa;
5027         int error;
5028         size_t count = (size_t)zc->zc_nvlist_dst_size;
5029
5030         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
5031                 return (error);
5032
5033         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
5034             &count);
5035         if (error == 0)
5036                 zc->zc_nvlist_dst_size = count;
5037         else
5038                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
5039
5040         spa_close(spa, FTAG);
5041
5042         return (error);
5043 }
5044
5045 static int
5046 zfs_ioc_clear(zfs_cmd_t *zc)
5047 {
5048         spa_t *spa;
5049         vdev_t *vd;
5050         int error;
5051
5052         /*
5053          * On zpool clear we also fix up missing slogs
5054          */
5055         mutex_enter(&spa_namespace_lock);
5056         spa = spa_lookup(zc->zc_name);
5057         if (spa == NULL) {
5058                 mutex_exit(&spa_namespace_lock);
5059                 return (SET_ERROR(EIO));
5060         }
5061         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
5062                 /* we need to let spa_open/spa_load clear the chains */
5063                 spa_set_log_state(spa, SPA_LOG_CLEAR);
5064         }
5065         spa->spa_last_open_failed = 0;
5066         mutex_exit(&spa_namespace_lock);
5067
5068         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
5069                 error = spa_open(zc->zc_name, &spa, FTAG);
5070         } else {
5071                 nvlist_t *policy;
5072                 nvlist_t *config = NULL;
5073
5074                 if (zc->zc_nvlist_src == 0)
5075                         return (SET_ERROR(EINVAL));
5076
5077                 if ((error = get_nvlist(zc->zc_nvlist_src,
5078                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
5079                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
5080                             policy, &config);
5081                         if (config != NULL) {
5082                                 int err;
5083
5084                                 if ((err = put_nvlist(zc, config)) != 0)
5085                                         error = err;
5086                                 nvlist_free(config);
5087                         }
5088                         nvlist_free(policy);
5089                 }
5090         }
5091
5092         if (error != 0)
5093                 return (error);
5094
5095         spa_vdev_state_enter(spa, SCL_NONE);
5096
5097         if (zc->zc_guid == 0) {
5098                 vd = NULL;
5099         } else {
5100                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
5101                 if (vd == NULL) {
5102                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
5103                         spa_close(spa, FTAG);
5104                         return (SET_ERROR(ENODEV));
5105                 }
5106         }
5107
5108         vdev_clear(spa, vd);
5109
5110         (void) spa_vdev_state_exit(spa, NULL, 0);
5111
5112         /*
5113          * Resume any suspended I/Os.
5114          */
5115         if (zio_resume(spa) != 0)
5116                 error = SET_ERROR(EIO);
5117
5118         spa_close(spa, FTAG);
5119
5120         return (error);
5121 }
5122
5123 static int
5124 zfs_ioc_pool_reopen(zfs_cmd_t *zc)
5125 {
5126         spa_t *spa;
5127         int error;
5128
5129         error = spa_open(zc->zc_name, &spa, FTAG);
5130         if (error != 0)
5131                 return (error);
5132
5133         spa_vdev_state_enter(spa, SCL_NONE);
5134
5135         /*
5136          * If a resilver is already in progress then set the
5137          * spa_scrub_reopen flag to B_TRUE so that we don't restart
5138          * the scan as a side effect of the reopen. Otherwise, let
5139          * vdev_open() decided if a resilver is required.
5140          */
5141         spa->spa_scrub_reopen = dsl_scan_resilvering(spa->spa_dsl_pool);
5142         vdev_reopen(spa->spa_root_vdev);
5143         spa->spa_scrub_reopen = B_FALSE;
5144
5145         (void) spa_vdev_state_exit(spa, NULL, 0);
5146         spa_close(spa, FTAG);
5147         return (0);
5148 }
5149 /*
5150  * inputs:
5151  * zc_name      name of filesystem
5152  *
5153  * outputs:
5154  * zc_string    name of conflicting snapshot, if there is one
5155  */
5156 static int
5157 zfs_ioc_promote(zfs_cmd_t *zc)
5158 {
5159         dsl_pool_t *dp;
5160         dsl_dataset_t *ds, *ods;
5161         char origin[ZFS_MAX_DATASET_NAME_LEN];
5162         char *cp;
5163         int error;
5164
5165         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
5166         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
5167             strchr(zc->zc_name, '%'))
5168                 return (SET_ERROR(EINVAL));
5169
5170         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5171         if (error != 0)
5172                 return (error);
5173
5174         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
5175         if (error != 0) {
5176                 dsl_pool_rele(dp, FTAG);
5177                 return (error);
5178         }
5179
5180         if (!dsl_dir_is_clone(ds->ds_dir)) {
5181                 dsl_dataset_rele(ds, FTAG);
5182                 dsl_pool_rele(dp, FTAG);
5183                 return (SET_ERROR(EINVAL));
5184         }
5185
5186         error = dsl_dataset_hold_obj(dp,
5187             dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &ods);
5188         if (error != 0) {
5189                 dsl_dataset_rele(ds, FTAG);
5190                 dsl_pool_rele(dp, FTAG);
5191                 return (error);
5192         }
5193
5194         dsl_dataset_name(ods, origin);
5195         dsl_dataset_rele(ods, FTAG);
5196         dsl_dataset_rele(ds, FTAG);
5197         dsl_pool_rele(dp, FTAG);
5198
5199         /*
5200          * We don't need to unmount *all* the origin fs's snapshots, but
5201          * it's easier.
5202          */
5203         cp = strchr(origin, '@');
5204         if (cp)
5205                 *cp = '\0';
5206         (void) dmu_objset_find(origin,
5207             zfs_unmount_snap_cb, NULL, DS_FIND_SNAPSHOTS);
5208         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
5209 }
5210
5211 /*
5212  * Retrieve a single {user|group}{used|quota}@... property.
5213  *
5214  * inputs:
5215  * zc_name      name of filesystem
5216  * zc_objset_type zfs_userquota_prop_t
5217  * zc_value     domain name (eg. "S-1-234-567-89")
5218  * zc_guid      RID/UID/GID
5219  *
5220  * outputs:
5221  * zc_cookie    property value
5222  */
5223 static int
5224 zfs_ioc_userspace_one(zfs_cmd_t *zc)
5225 {
5226         zfsvfs_t *zfsvfs;
5227         int error;
5228
5229         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
5230                 return (SET_ERROR(EINVAL));
5231
5232         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
5233         if (error != 0)
5234                 return (error);
5235
5236         error = zfs_userspace_one(zfsvfs,
5237             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
5238         zfsvfs_rele(zfsvfs, FTAG);
5239
5240         return (error);
5241 }
5242
5243 /*
5244  * inputs:
5245  * zc_name              name of filesystem
5246  * zc_cookie            zap cursor
5247  * zc_objset_type       zfs_userquota_prop_t
5248  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
5249  *
5250  * outputs:
5251  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
5252  * zc_cookie    zap cursor
5253  */
5254 static int
5255 zfs_ioc_userspace_many(zfs_cmd_t *zc)
5256 {
5257         zfsvfs_t *zfsvfs;
5258         int bufsize = zc->zc_nvlist_dst_size;
5259
5260         if (bufsize <= 0)
5261                 return (SET_ERROR(ENOMEM));
5262
5263         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
5264         if (error != 0)
5265                 return (error);
5266
5267         void *buf = kmem_alloc(bufsize, KM_SLEEP);
5268
5269         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
5270             buf, &zc->zc_nvlist_dst_size);
5271
5272         if (error == 0) {
5273                 error = ddi_copyout(buf,
5274                     (void *)(uintptr_t)zc->zc_nvlist_dst,
5275                     zc->zc_nvlist_dst_size, zc->zc_iflags);
5276         }
5277         kmem_free(buf, bufsize);
5278         zfsvfs_rele(zfsvfs, FTAG);
5279
5280         return (error);
5281 }
5282
5283 /*
5284  * inputs:
5285  * zc_name              name of filesystem
5286  *
5287  * outputs:
5288  * none
5289  */
5290 static int
5291 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
5292 {
5293         objset_t *os;
5294         int error = 0;
5295         zfsvfs_t *zfsvfs;
5296
5297         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
5298                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
5299                         /*
5300                          * If userused is not enabled, it may be because the
5301                          * objset needs to be closed & reopened (to grow the
5302                          * objset_phys_t).  Suspend/resume the fs will do that.
5303                          */
5304                         dsl_dataset_t *ds, *newds;
5305
5306                         ds = dmu_objset_ds(zfsvfs->z_os);
5307                         error = zfs_suspend_fs(zfsvfs);
5308                         if (error == 0) {
5309                                 dmu_objset_refresh_ownership(ds, &newds,
5310                                     zfsvfs);
5311                                 error = zfs_resume_fs(zfsvfs, newds);
5312                         }
5313                 }
5314                 if (error == 0)
5315                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
5316 #ifdef illumos
5317                 VFS_RELE(zfsvfs->z_vfs);
5318 #else
5319                 vfs_unbusy(zfsvfs->z_vfs);
5320 #endif
5321         } else {
5322                 /* XXX kind of reading contents without owning */
5323                 error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5324                 if (error != 0)
5325                         return (error);
5326
5327                 error = dmu_objset_userspace_upgrade(os);
5328                 dmu_objset_rele(os, FTAG);
5329         }
5330
5331         return (error);
5332 }
5333
5334 #ifdef illumos
5335 /*
5336  * We don't want to have a hard dependency
5337  * against some special symbols in sharefs
5338  * nfs, and smbsrv.  Determine them if needed when
5339  * the first file system is shared.
5340  * Neither sharefs, nfs or smbsrv are unloadable modules.
5341  */
5342 int (*znfsexport_fs)(void *arg);
5343 int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
5344 int (*zsmbexport_fs)(void *arg, boolean_t add_share);
5345
5346 int zfs_nfsshare_inited;
5347 int zfs_smbshare_inited;
5348
5349 ddi_modhandle_t nfs_mod;
5350 ddi_modhandle_t sharefs_mod;
5351 ddi_modhandle_t smbsrv_mod;
5352 #endif  /* illumos */
5353 kmutex_t zfs_share_lock;
5354
5355 #ifdef illumos
5356 static int
5357 zfs_init_sharefs()
5358 {
5359         int error;
5360
5361         ASSERT(MUTEX_HELD(&zfs_share_lock));
5362         /* Both NFS and SMB shares also require sharetab support. */
5363         if (sharefs_mod == NULL && ((sharefs_mod =
5364             ddi_modopen("fs/sharefs",
5365             KRTLD_MODE_FIRST, &error)) == NULL)) {
5366                 return (SET_ERROR(ENOSYS));
5367         }
5368         if (zshare_fs == NULL && ((zshare_fs =
5369             (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
5370             ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
5371                 return (SET_ERROR(ENOSYS));
5372         }
5373         return (0);
5374 }
5375 #endif  /* illumos */
5376
5377 static int
5378 zfs_ioc_share(zfs_cmd_t *zc)
5379 {
5380 #ifdef illumos
5381         int error;
5382         int opcode;
5383
5384         switch (zc->zc_share.z_sharetype) {
5385         case ZFS_SHARE_NFS:
5386         case ZFS_UNSHARE_NFS:
5387                 if (zfs_nfsshare_inited == 0) {
5388                         mutex_enter(&zfs_share_lock);
5389                         if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
5390                             KRTLD_MODE_FIRST, &error)) == NULL)) {
5391                                 mutex_exit(&zfs_share_lock);
5392                                 return (SET_ERROR(ENOSYS));
5393                         }
5394                         if (znfsexport_fs == NULL &&
5395                             ((znfsexport_fs = (int (*)(void *))
5396                             ddi_modsym(nfs_mod,
5397                             "nfs_export", &error)) == NULL)) {
5398                                 mutex_exit(&zfs_share_lock);
5399                                 return (SET_ERROR(ENOSYS));
5400                         }
5401                         error = zfs_init_sharefs();
5402                         if (error != 0) {
5403                                 mutex_exit(&zfs_share_lock);
5404                                 return (SET_ERROR(ENOSYS));
5405                         }
5406                         zfs_nfsshare_inited = 1;
5407                         mutex_exit(&zfs_share_lock);
5408                 }
5409                 break;
5410         case ZFS_SHARE_SMB:
5411         case ZFS_UNSHARE_SMB:
5412                 if (zfs_smbshare_inited == 0) {
5413                         mutex_enter(&zfs_share_lock);
5414                         if (smbsrv_mod == NULL && ((smbsrv_mod =
5415                             ddi_modopen("drv/smbsrv",
5416                             KRTLD_MODE_FIRST, &error)) == NULL)) {
5417                                 mutex_exit(&zfs_share_lock);
5418                                 return (SET_ERROR(ENOSYS));
5419                         }
5420                         if (zsmbexport_fs == NULL && ((zsmbexport_fs =
5421                             (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
5422                             "smb_server_share", &error)) == NULL)) {
5423                                 mutex_exit(&zfs_share_lock);
5424                                 return (SET_ERROR(ENOSYS));
5425                         }
5426                         error = zfs_init_sharefs();
5427                         if (error != 0) {
5428                                 mutex_exit(&zfs_share_lock);
5429                                 return (SET_ERROR(ENOSYS));
5430                         }
5431                         zfs_smbshare_inited = 1;
5432                         mutex_exit(&zfs_share_lock);
5433                 }
5434                 break;
5435         default:
5436                 return (SET_ERROR(EINVAL));
5437         }
5438
5439         switch (zc->zc_share.z_sharetype) {
5440         case ZFS_SHARE_NFS:
5441         case ZFS_UNSHARE_NFS:
5442                 if (error =
5443                     znfsexport_fs((void *)
5444                     (uintptr_t)zc->zc_share.z_exportdata))
5445                         return (error);
5446                 break;
5447         case ZFS_SHARE_SMB:
5448         case ZFS_UNSHARE_SMB:
5449                 if (error = zsmbexport_fs((void *)
5450                     (uintptr_t)zc->zc_share.z_exportdata,
5451                     zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
5452                     B_TRUE: B_FALSE)) {
5453                         return (error);
5454                 }
5455                 break;
5456         }
5457
5458         opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
5459             zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
5460             SHAREFS_ADD : SHAREFS_REMOVE;
5461
5462         /*
5463          * Add or remove share from sharetab
5464          */
5465         error = zshare_fs(opcode,
5466             (void *)(uintptr_t)zc->zc_share.z_sharedata,
5467             zc->zc_share.z_sharemax);
5468
5469         return (error);
5470
5471 #else   /* !illumos */
5472         return (ENOSYS);
5473 #endif  /* illumos */
5474 }
5475
5476 ace_t full_access[] = {
5477         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
5478 };
5479
5480 /*
5481  * inputs:
5482  * zc_name              name of containing filesystem
5483  * zc_obj               object # beyond which we want next in-use object #
5484  *
5485  * outputs:
5486  * zc_obj               next in-use object #
5487  */
5488 static int
5489 zfs_ioc_next_obj(zfs_cmd_t *zc)
5490 {
5491         objset_t *os = NULL;
5492         int error;
5493
5494         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5495         if (error != 0)
5496                 return (error);
5497
5498         error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
5499             dsl_dataset_phys(os->os_dsl_dataset)->ds_prev_snap_txg);
5500
5501         dmu_objset_rele(os, FTAG);
5502         return (error);
5503 }
5504
5505 /*
5506  * inputs:
5507  * zc_name              name of filesystem
5508  * zc_value             prefix name for snapshot
5509  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
5510  *
5511  * outputs:
5512  * zc_value             short name of new snapshot
5513  */
5514 static int
5515 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
5516 {
5517         char *snap_name;
5518         char *hold_name;
5519         int error;
5520         minor_t minor;
5521
5522         error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
5523         if (error != 0)
5524                 return (error);
5525
5526         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
5527             (u_longlong_t)ddi_get_lbolt64());
5528         hold_name = kmem_asprintf("%%%s", zc->zc_value);
5529
5530         error = dsl_dataset_snapshot_tmp(zc->zc_name, snap_name, minor,
5531             hold_name);
5532         if (error == 0)
5533                 (void) strcpy(zc->zc_value, snap_name);
5534         strfree(snap_name);
5535         strfree(hold_name);
5536         zfs_onexit_fd_rele(zc->zc_cleanup_fd);
5537         return (error);
5538 }
5539
5540 /*
5541  * inputs:
5542  * zc_name              name of "to" snapshot
5543  * zc_value             name of "from" snapshot
5544  * zc_cookie            file descriptor to write diff data on
5545  *
5546  * outputs:
5547  * dmu_diff_record_t's to the file descriptor
5548  */
5549 static int
5550 zfs_ioc_diff(zfs_cmd_t *zc)
5551 {
5552         file_t *fp;
5553         offset_t off;
5554         int error;
5555
5556 #ifdef illumos
5557         fp = getf(zc->zc_cookie);
5558 #else
5559         fget_write(curthread, zc->zc_cookie, &cap_write_rights, &fp);
5560 #endif
5561         if (fp == NULL)
5562                 return (SET_ERROR(EBADF));
5563
5564         off = fp->f_offset;
5565
5566 #ifdef illumos
5567         error = dmu_diff(zc->zc_name, zc->zc_value, fp->f_vnode, &off);
5568 #else
5569         error = dmu_diff(zc->zc_name, zc->zc_value, fp, &off);
5570 #endif
5571
5572         if (off >= 0 && off <= MAXOFFSET_T)
5573                 fp->f_offset = off;
5574         releasef(zc->zc_cookie);
5575
5576         return (error);
5577 }
5578
5579 #ifdef illumos
5580 /*
5581  * Remove all ACL files in shares dir
5582  */
5583 static int
5584 zfs_smb_acl_purge(znode_t *dzp)
5585 {
5586         zap_cursor_t    zc;
5587         zap_attribute_t zap;
5588         zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
5589         int error;
5590
5591         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
5592             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
5593             zap_cursor_advance(&zc)) {
5594                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
5595                     NULL, 0)) != 0)
5596                         break;
5597         }
5598         zap_cursor_fini(&zc);
5599         return (error);
5600 }
5601 #endif  /* illumos */
5602
5603 static int
5604 zfs_ioc_smb_acl(zfs_cmd_t *zc)
5605 {
5606 #ifdef illumos
5607         vnode_t *vp;
5608         znode_t *dzp;
5609         vnode_t *resourcevp = NULL;
5610         znode_t *sharedir;
5611         zfsvfs_t *zfsvfs;
5612         nvlist_t *nvlist;
5613         char *src, *target;
5614         vattr_t vattr;
5615         vsecattr_t vsec;
5616         int error = 0;
5617
5618         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
5619             NO_FOLLOW, NULL, &vp)) != 0)
5620                 return (error);
5621
5622         /* Now make sure mntpnt and dataset are ZFS */
5623
5624         if (strcmp(vp->v_vfsp->mnt_stat.f_fstypename, "zfs") != 0 ||
5625             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
5626             zc->zc_name) != 0)) {
5627                 VN_RELE(vp);
5628                 return (SET_ERROR(EINVAL));
5629         }
5630
5631         dzp = VTOZ(vp);
5632         zfsvfs = dzp->z_zfsvfs;
5633         ZFS_ENTER(zfsvfs);
5634
5635         /*
5636          * Create share dir if its missing.
5637          */
5638         mutex_enter(&zfsvfs->z_lock);
5639         if (zfsvfs->z_shares_dir == 0) {
5640                 dmu_tx_t *tx;
5641
5642                 tx = dmu_tx_create(zfsvfs->z_os);
5643                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
5644                     ZFS_SHARES_DIR);
5645                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
5646                 error = dmu_tx_assign(tx, TXG_WAIT);
5647                 if (error != 0) {
5648                         dmu_tx_abort(tx);
5649                 } else {
5650                         error = zfs_create_share_dir(zfsvfs, tx);
5651                         dmu_tx_commit(tx);
5652                 }
5653                 if (error != 0) {
5654                         mutex_exit(&zfsvfs->z_lock);
5655                         VN_RELE(vp);
5656                         ZFS_EXIT(zfsvfs);
5657                         return (error);
5658                 }
5659         }
5660         mutex_exit(&zfsvfs->z_lock);
5661
5662         ASSERT(zfsvfs->z_shares_dir);
5663         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
5664                 VN_RELE(vp);
5665                 ZFS_EXIT(zfsvfs);
5666                 return (error);
5667         }
5668
5669         switch (zc->zc_cookie) {
5670         case ZFS_SMB_ACL_ADD:
5671                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
5672                 vattr.va_type = VREG;
5673                 vattr.va_mode = S_IFREG|0777;
5674                 vattr.va_uid = 0;
5675                 vattr.va_gid = 0;
5676
5677                 vsec.vsa_mask = VSA_ACE;
5678                 vsec.vsa_aclentp = &full_access;
5679                 vsec.vsa_aclentsz = sizeof (full_access);
5680                 vsec.vsa_aclcnt = 1;
5681
5682                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
5683                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
5684                 if (resourcevp)
5685                         VN_RELE(resourcevp);
5686                 break;
5687
5688         case ZFS_SMB_ACL_REMOVE:
5689                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
5690                     NULL, 0);
5691                 break;
5692
5693         case ZFS_SMB_ACL_RENAME:
5694                 if ((error = get_nvlist(zc->zc_nvlist_src,
5695                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
5696                         VN_RELE(vp);
5697                         VN_RELE(ZTOV(sharedir));
5698                         ZFS_EXIT(zfsvfs);
5699                         return (error);
5700                 }
5701                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
5702                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
5703                     &target)) {
5704                         VN_RELE(vp);
5705                         VN_RELE(ZTOV(sharedir));
5706                         ZFS_EXIT(zfsvfs);
5707                         nvlist_free(nvlist);
5708                         return (error);
5709                 }
5710                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
5711                     kcred, NULL, 0);
5712                 nvlist_free(nvlist);
5713                 break;
5714
5715         case ZFS_SMB_ACL_PURGE:
5716                 error = zfs_smb_acl_purge(sharedir);
5717                 break;
5718
5719         default:
5720                 error = SET_ERROR(EINVAL);
5721                 break;
5722         }
5723
5724         VN_RELE(vp);
5725         VN_RELE(ZTOV(sharedir));
5726
5727         ZFS_EXIT(zfsvfs);
5728
5729         return (error);
5730 #else   /* !illumos */
5731         return (EOPNOTSUPP);
5732 #endif  /* illumos */
5733 }
5734
5735 /*
5736  * innvl: {
5737  *     "holds" -> { snapname -> holdname (string), ... }
5738  *     (optional) "cleanup_fd" -> fd (int32)
5739  * }
5740  *
5741  * outnvl: {
5742  *     snapname -> error value (int32)
5743  *     ...
5744  * }
5745  */
5746 /* ARGSUSED */
5747 static int
5748 zfs_ioc_hold(const char *pool, nvlist_t *args, nvlist_t *errlist)
5749 {
5750         nvpair_t *pair;
5751         nvlist_t *holds;
5752         int cleanup_fd = -1;
5753         int error;
5754         minor_t minor = 0;
5755
5756         error = nvlist_lookup_nvlist(args, "holds", &holds);
5757         if (error != 0)
5758                 return (SET_ERROR(EINVAL));
5759
5760         /* make sure the user didn't pass us any invalid (empty) tags */
5761         for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
5762             pair = nvlist_next_nvpair(holds, pair)) {
5763                 char *htag;
5764
5765                 error = nvpair_value_string(pair, &htag);
5766                 if (error != 0)
5767                         return (SET_ERROR(error));
5768
5769                 if (strlen(htag) == 0)
5770                         return (SET_ERROR(EINVAL));
5771         }
5772
5773         if (nvlist_lookup_int32(args, "cleanup_fd", &cleanup_fd) == 0) {
5774                 error = zfs_onexit_fd_hold(cleanup_fd, &minor);
5775                 if (error != 0)
5776                         return (error);
5777         }
5778
5779         error = dsl_dataset_user_hold(holds, minor, errlist);
5780         if (minor != 0)
5781                 zfs_onexit_fd_rele(cleanup_fd);
5782         return (error);
5783 }
5784
5785 /*
5786  * innvl is not used.
5787  *
5788  * outnvl: {
5789  *    holdname -> time added (uint64 seconds since epoch)
5790  *    ...
5791  * }
5792  */
5793 /* ARGSUSED */
5794 static int
5795 zfs_ioc_get_holds(const char *snapname, nvlist_t *args, nvlist_t *outnvl)
5796 {
5797         return (dsl_dataset_get_holds(snapname, outnvl));
5798 }
5799
5800 /*
5801  * innvl: {
5802  *     snapname -> { holdname, ... }
5803  *     ...
5804  * }
5805  *
5806  * outnvl: {
5807  *     snapname -> error value (int32)
5808  *     ...
5809  * }
5810  */
5811 /* ARGSUSED */
5812 static int
5813 zfs_ioc_release(const char *pool, nvlist_t *holds, nvlist_t *errlist)
5814 {
5815         return (dsl_dataset_user_release(holds, errlist));
5816 }
5817
5818 /*
5819  * inputs:
5820  * zc_name              name of new filesystem or snapshot
5821  * zc_value             full name of old snapshot
5822  *
5823  * outputs:
5824  * zc_cookie            space in bytes
5825  * zc_objset_type       compressed space in bytes
5826  * zc_perm_action       uncompressed space in bytes
5827  */
5828 static int
5829 zfs_ioc_space_written(zfs_cmd_t *zc)
5830 {
5831         int error;
5832         dsl_pool_t *dp;
5833         dsl_dataset_t *new, *old;
5834
5835         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5836         if (error != 0)
5837                 return (error);
5838         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &new);
5839         if (error != 0) {
5840                 dsl_pool_rele(dp, FTAG);
5841                 return (error);
5842         }
5843         error = dsl_dataset_hold(dp, zc->zc_value, FTAG, &old);
5844         if (error != 0) {
5845                 dsl_dataset_rele(new, FTAG);
5846                 dsl_pool_rele(dp, FTAG);
5847                 return (error);
5848         }
5849
5850         error = dsl_dataset_space_written(old, new, &zc->zc_cookie,
5851             &zc->zc_objset_type, &zc->zc_perm_action);
5852         dsl_dataset_rele(old, FTAG);
5853         dsl_dataset_rele(new, FTAG);
5854         dsl_pool_rele(dp, FTAG);
5855         return (error);
5856 }
5857
5858 /*
5859  * innvl: {
5860  *     "firstsnap" -> snapshot name
5861  * }
5862  *
5863  * outnvl: {
5864  *     "used" -> space in bytes
5865  *     "compressed" -> compressed space in bytes
5866  *     "uncompressed" -> uncompressed space in bytes
5867  * }
5868  */
5869 static int
5870 zfs_ioc_space_snaps(const char *lastsnap, nvlist_t *innvl, nvlist_t *outnvl)
5871 {
5872         int error;
5873         dsl_pool_t *dp;
5874         dsl_dataset_t *new, *old;
5875         char *firstsnap;
5876         uint64_t used, comp, uncomp;
5877
5878         if (nvlist_lookup_string(innvl, "firstsnap", &firstsnap) != 0)
5879                 return (SET_ERROR(EINVAL));
5880
5881         error = dsl_pool_hold(lastsnap, FTAG, &dp);
5882         if (error != 0)
5883                 return (error);
5884
5885         error = dsl_dataset_hold(dp, lastsnap, FTAG, &new);
5886         if (error == 0 && !new->ds_is_snapshot) {
5887                 dsl_dataset_rele(new, FTAG);
5888                 error = SET_ERROR(EINVAL);
5889         }
5890         if (error != 0) {
5891                 dsl_pool_rele(dp, FTAG);
5892                 return (error);
5893         }
5894         error = dsl_dataset_hold(dp, firstsnap, FTAG, &old);
5895         if (error == 0 && !old->ds_is_snapshot) {
5896                 dsl_dataset_rele(old, FTAG);
5897                 error = SET_ERROR(EINVAL);
5898         }
5899         if (error != 0) {
5900                 dsl_dataset_rele(new, FTAG);
5901                 dsl_pool_rele(dp, FTAG);
5902                 return (error);
5903         }
5904
5905         error = dsl_dataset_space_wouldfree(old, new, &used, &comp, &uncomp);
5906         dsl_dataset_rele(old, FTAG);
5907         dsl_dataset_rele(new, FTAG);
5908         dsl_pool_rele(dp, FTAG);
5909         fnvlist_add_uint64(outnvl, "used", used);
5910         fnvlist_add_uint64(outnvl, "compressed", comp);
5911         fnvlist_add_uint64(outnvl, "uncompressed", uncomp);
5912         return (error);
5913 }
5914
5915 static int
5916 zfs_ioc_jail(zfs_cmd_t *zc)
5917 {
5918
5919         return (zone_dataset_attach(curthread->td_ucred, zc->zc_name,
5920             (int)zc->zc_jailid));
5921 }
5922
5923 static int
5924 zfs_ioc_unjail(zfs_cmd_t *zc)
5925 {
5926
5927         return (zone_dataset_detach(curthread->td_ucred, zc->zc_name,
5928             (int)zc->zc_jailid));
5929 }
5930
5931 /*
5932  * innvl: {
5933  *     "fd" -> file descriptor to write stream to (int32)
5934  *     (optional) "fromsnap" -> full snap name to send an incremental from
5935  *     (optional) "largeblockok" -> (value ignored)
5936  *         indicates that blocks > 128KB are permitted
5937  *     (optional) "embedok" -> (value ignored)
5938  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5939  *     (optional) "compressok" -> (value ignored)
5940  *         presence indicates compressed DRR_WRITE records are permitted
5941  *     (optional) "resume_object" and "resume_offset" -> (uint64)
5942  *         if present, resume send stream from specified object and offset.
5943  * }
5944  *
5945  * outnvl is unused
5946  */
5947 /* ARGSUSED */
5948 static int
5949 zfs_ioc_send_new(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5950 {
5951         file_t *fp;
5952         int error;
5953         offset_t off;
5954         char *fromname = NULL;
5955         int fd;
5956         boolean_t largeblockok;
5957         boolean_t embedok;
5958         boolean_t compressok;
5959         uint64_t resumeobj = 0;
5960         uint64_t resumeoff = 0;
5961
5962         error = nvlist_lookup_int32(innvl, "fd", &fd);
5963         if (error != 0)
5964                 return (SET_ERROR(EINVAL));
5965
5966         (void) nvlist_lookup_string(innvl, "fromsnap", &fromname);
5967
5968         largeblockok = nvlist_exists(innvl, "largeblockok");
5969         embedok = nvlist_exists(innvl, "embedok");
5970         compressok = nvlist_exists(innvl, "compressok");
5971
5972         (void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
5973         (void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
5974
5975 #ifdef illumos
5976         file_t *fp = getf(fd);
5977 #else
5978         fget_write(curthread, fd, &cap_write_rights, &fp);
5979 #endif
5980         if (fp == NULL)
5981                 return (SET_ERROR(EBADF));
5982
5983         off = fp->f_offset;
5984         error = dmu_send(snapname, fromname, embedok, largeblockok, compressok,
5985 #ifdef illumos
5986             fd, resumeobj, resumeoff, fp->f_vnode, &off);
5987 #else
5988             fd, resumeobj, resumeoff, fp, &off);
5989 #endif
5990
5991 #ifdef illumos
5992         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5993                 fp->f_offset = off;
5994 #else
5995         fp->f_offset = off;
5996 #endif
5997
5998         releasef(fd);
5999         return (error);
6000 }
6001
6002 /*
6003  * Determine approximately how large a zfs send stream will be -- the number
6004  * of bytes that will be written to the fd supplied to zfs_ioc_send_new().
6005  *
6006  * innvl: {
6007  *     (optional) "from" -> full snap or bookmark name to send an incremental
6008  *                          from
6009  *     (optional) "largeblockok" -> (value ignored)
6010  *         indicates that blocks > 128KB are permitted
6011  *     (optional) "embedok" -> (value ignored)
6012  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
6013  *     (optional) "compressok" -> (value ignored)
6014  *         presence indicates compressed DRR_WRITE records are permitted
6015  * }
6016  *
6017  * outnvl: {
6018  *     "space" -> bytes of space (uint64)
6019  * }
6020  */
6021 static int
6022 zfs_ioc_send_space(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
6023 {
6024         dsl_pool_t *dp;
6025         dsl_dataset_t *tosnap;
6026         int error;
6027         char *fromname;
6028         boolean_t compressok;
6029         uint64_t space;
6030
6031         error = dsl_pool_hold(snapname, FTAG, &dp);
6032         if (error != 0)
6033                 return (error);
6034
6035         error = dsl_dataset_hold(dp, snapname, FTAG, &tosnap);
6036         if (error != 0) {
6037                 dsl_pool_rele(dp, FTAG);
6038                 return (error);
6039         }
6040
6041         compressok = nvlist_exists(innvl, "compressok");
6042
6043         error = nvlist_lookup_string(innvl, "from", &fromname);
6044         if (error == 0) {
6045                 if (strchr(fromname, '@') != NULL) {
6046                         /*
6047                          * If from is a snapshot, hold it and use the more
6048                          * efficient dmu_send_estimate to estimate send space
6049                          * size using deadlists.
6050                          */
6051                         dsl_dataset_t *fromsnap;
6052                         error = dsl_dataset_hold(dp, fromname, FTAG, &fromsnap);
6053                         if (error != 0)
6054                                 goto out;
6055                         error = dmu_send_estimate(tosnap, fromsnap, compressok,
6056                             &space);
6057                         dsl_dataset_rele(fromsnap, FTAG);
6058                 } else if (strchr(fromname, '#') != NULL) {
6059                         /*
6060                          * If from is a bookmark, fetch the creation TXG of the
6061                          * snapshot it was created from and use that to find
6062                          * blocks that were born after it.
6063                          */
6064                         zfs_bookmark_phys_t frombm;
6065
6066                         error = dsl_bookmark_lookup(dp, fromname, tosnap,
6067                             &frombm);
6068                         if (error != 0)
6069                                 goto out;
6070                         error = dmu_send_estimate_from_txg(tosnap,
6071                             frombm.zbm_creation_txg, compressok, &space);
6072                 } else {
6073                         /*
6074                          * from is not properly formatted as a snapshot or
6075                          * bookmark
6076                          */
6077                         error = SET_ERROR(EINVAL);
6078                         goto out;
6079                 }
6080         } else {
6081                 /*
6082                  * If estimating the size of a full send, use dmu_send_estimate.
6083                  */
6084                 error = dmu_send_estimate(tosnap, NULL, compressok, &space);
6085         }
6086
6087         fnvlist_add_uint64(outnvl, "space", space);
6088
6089 out:
6090         dsl_dataset_rele(tosnap, FTAG);
6091         dsl_pool_rele(dp, FTAG);
6092         return (error);
6093 }
6094
6095 static zfs_ioc_vec_t zfs_ioc_vec[ZFS_IOC_LAST - ZFS_IOC_FIRST];
6096
6097 static void
6098 zfs_ioctl_register_legacy(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6099     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
6100     boolean_t log_history, zfs_ioc_poolcheck_t pool_check)
6101 {
6102         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
6103
6104         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
6105         ASSERT3U(ioc, <, ZFS_IOC_LAST);
6106         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
6107         ASSERT3P(vec->zvec_func, ==, NULL);
6108
6109         vec->zvec_legacy_func = func;
6110         vec->zvec_secpolicy = secpolicy;
6111         vec->zvec_namecheck = namecheck;
6112         vec->zvec_allow_log = log_history;
6113         vec->zvec_pool_check = pool_check;
6114 }
6115
6116 /*
6117  * See the block comment at the beginning of this file for details on
6118  * each argument to this function.
6119  */
6120 static void
6121 zfs_ioctl_register(const char *name, zfs_ioc_t ioc, zfs_ioc_func_t *func,
6122     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
6123     zfs_ioc_poolcheck_t pool_check, boolean_t smush_outnvlist,
6124     boolean_t allow_log)
6125 {
6126         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
6127
6128         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
6129         ASSERT3U(ioc, <, ZFS_IOC_LAST);
6130         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
6131         ASSERT3P(vec->zvec_func, ==, NULL);
6132
6133         /* if we are logging, the name must be valid */
6134         ASSERT(!allow_log || namecheck != NO_NAME);
6135
6136         vec->zvec_name = name;
6137         vec->zvec_func = func;
6138         vec->zvec_secpolicy = secpolicy;
6139         vec->zvec_namecheck = namecheck;
6140         vec->zvec_pool_check = pool_check;
6141         vec->zvec_smush_outnvlist = smush_outnvlist;
6142         vec->zvec_allow_log = allow_log;
6143 }
6144
6145 static void
6146 zfs_ioctl_register_pool(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6147     zfs_secpolicy_func_t *secpolicy, boolean_t log_history,
6148     zfs_ioc_poolcheck_t pool_check)
6149 {
6150         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6151             POOL_NAME, log_history, pool_check);
6152 }
6153
6154 static void
6155 zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6156     zfs_secpolicy_func_t *secpolicy, zfs_ioc_poolcheck_t pool_check)
6157 {
6158         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6159             DATASET_NAME, B_FALSE, pool_check);
6160 }
6161
6162 static void
6163 zfs_ioctl_register_pool_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
6164 {
6165         zfs_ioctl_register_legacy(ioc, func, zfs_secpolicy_config,
6166             POOL_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6167 }
6168
6169 static void
6170 zfs_ioctl_register_pool_meta(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6171     zfs_secpolicy_func_t *secpolicy)
6172 {
6173         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6174             NO_NAME, B_FALSE, POOL_CHECK_NONE);
6175 }
6176
6177 static void
6178 zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,
6179     zfs_ioc_legacy_func_t *func, zfs_secpolicy_func_t *secpolicy)
6180 {
6181         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6182             DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED);
6183 }
6184
6185 static void
6186 zfs_ioctl_register_dataset_read(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
6187 {
6188         zfs_ioctl_register_dataset_read_secpolicy(ioc, func,
6189             zfs_secpolicy_read);
6190 }
6191
6192 static void
6193 zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
6194     zfs_secpolicy_func_t *secpolicy)
6195 {
6196         zfs_ioctl_register_legacy(ioc, func, secpolicy,
6197             DATASET_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6198 }
6199
6200 static void
6201 zfs_ioctl_init(void)
6202 {
6203         zfs_ioctl_register("snapshot", ZFS_IOC_SNAPSHOT,
6204             zfs_ioc_snapshot, zfs_secpolicy_snapshot, POOL_NAME,
6205             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6206
6207         zfs_ioctl_register("log_history", ZFS_IOC_LOG_HISTORY,
6208             zfs_ioc_log_history, zfs_secpolicy_log_history, NO_NAME,
6209             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE);
6210
6211         zfs_ioctl_register("space_snaps", ZFS_IOC_SPACE_SNAPS,
6212             zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME,
6213             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6214
6215         zfs_ioctl_register("send", ZFS_IOC_SEND_NEW,
6216             zfs_ioc_send_new, zfs_secpolicy_send_new, DATASET_NAME,
6217             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6218
6219         zfs_ioctl_register("send_space", ZFS_IOC_SEND_SPACE,
6220             zfs_ioc_send_space, zfs_secpolicy_read, DATASET_NAME,
6221             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6222
6223         zfs_ioctl_register("create", ZFS_IOC_CREATE,
6224             zfs_ioc_create, zfs_secpolicy_create_clone, DATASET_NAME,
6225             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6226
6227         zfs_ioctl_register("clone", ZFS_IOC_CLONE,
6228             zfs_ioc_clone, zfs_secpolicy_create_clone, DATASET_NAME,
6229             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6230
6231         zfs_ioctl_register("remap", ZFS_IOC_REMAP,
6232             zfs_ioc_remap, zfs_secpolicy_remap, DATASET_NAME,
6233             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
6234
6235         zfs_ioctl_register("destroy_snaps", ZFS_IOC_DESTROY_SNAPS,
6236             zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, POOL_NAME,
6237             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6238
6239         zfs_ioctl_register("hold", ZFS_IOC_HOLD,
6240             zfs_ioc_hold, zfs_secpolicy_hold, POOL_NAME,
6241             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6242         zfs_ioctl_register("release", ZFS_IOC_RELEASE,
6243             zfs_ioc_release, zfs_secpolicy_release, POOL_NAME,
6244             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6245
6246         zfs_ioctl_register("get_holds", ZFS_IOC_GET_HOLDS,
6247             zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME,
6248             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6249
6250         zfs_ioctl_register("rollback", ZFS_IOC_ROLLBACK,
6251             zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME,
6252             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
6253
6254         zfs_ioctl_register("bookmark", ZFS_IOC_BOOKMARK,
6255             zfs_ioc_bookmark, zfs_secpolicy_bookmark, POOL_NAME,
6256             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6257
6258         zfs_ioctl_register("get_bookmarks", ZFS_IOC_GET_BOOKMARKS,
6259             zfs_ioc_get_bookmarks, zfs_secpolicy_read, DATASET_NAME,
6260             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
6261
6262         zfs_ioctl_register("destroy_bookmarks", ZFS_IOC_DESTROY_BOOKMARKS,
6263             zfs_ioc_destroy_bookmarks, zfs_secpolicy_destroy_bookmarks,
6264             POOL_NAME,
6265             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6266
6267         zfs_ioctl_register("channel_program", ZFS_IOC_CHANNEL_PROGRAM,
6268             zfs_ioc_channel_program, zfs_secpolicy_config,
6269             POOL_NAME, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE,
6270             B_TRUE);
6271
6272         zfs_ioctl_register("zpool_checkpoint", ZFS_IOC_POOL_CHECKPOINT,
6273             zfs_ioc_pool_checkpoint, zfs_secpolicy_config, POOL_NAME,
6274             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6275
6276         zfs_ioctl_register("zpool_discard_checkpoint",
6277             ZFS_IOC_POOL_DISCARD_CHECKPOINT, zfs_ioc_pool_discard_checkpoint,
6278             zfs_secpolicy_config, POOL_NAME,
6279             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6280
6281         zfs_ioctl_register("initialize", ZFS_IOC_POOL_INITIALIZE,
6282             zfs_ioc_pool_initialize, zfs_secpolicy_config, POOL_NAME,
6283             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
6284
6285         /* IOCTLS that use the legacy function signature */
6286
6287         zfs_ioctl_register_legacy(ZFS_IOC_POOL_FREEZE, zfs_ioc_pool_freeze,
6288             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_READONLY);
6289
6290         zfs_ioctl_register_pool(ZFS_IOC_POOL_CREATE, zfs_ioc_pool_create,
6291             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6292         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SCAN,
6293             zfs_ioc_pool_scan);
6294         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_UPGRADE,
6295             zfs_ioc_pool_upgrade);
6296         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ADD,
6297             zfs_ioc_vdev_add);
6298         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_REMOVE,
6299             zfs_ioc_vdev_remove);
6300         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SET_STATE,
6301             zfs_ioc_vdev_set_state);
6302         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ATTACH,
6303             zfs_ioc_vdev_attach);
6304         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_DETACH,
6305             zfs_ioc_vdev_detach);
6306         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETPATH,
6307             zfs_ioc_vdev_setpath);
6308         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETFRU,
6309             zfs_ioc_vdev_setfru);
6310         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SET_PROPS,
6311             zfs_ioc_pool_set_props);
6312         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SPLIT,
6313             zfs_ioc_vdev_split);
6314         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_REGUID,
6315             zfs_ioc_pool_reguid);
6316
6317         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_CONFIGS,
6318             zfs_ioc_pool_configs, zfs_secpolicy_none);
6319         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_TRYIMPORT,
6320             zfs_ioc_pool_tryimport, zfs_secpolicy_config);
6321         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_FAULT,
6322             zfs_ioc_inject_fault, zfs_secpolicy_inject);
6323         zfs_ioctl_register_pool_meta(ZFS_IOC_CLEAR_FAULT,
6324             zfs_ioc_clear_fault, zfs_secpolicy_inject);
6325         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_LIST_NEXT,
6326             zfs_ioc_inject_list_next, zfs_secpolicy_inject);
6327
6328         /*
6329          * pool destroy, and export don't log the history as part of
6330          * zfsdev_ioctl, but rather zfs_ioc_pool_export
6331          * does the logging of those commands.
6332          */
6333         zfs_ioctl_register_pool(ZFS_IOC_POOL_DESTROY, zfs_ioc_pool_destroy,
6334             zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
6335         zfs_ioctl_register_pool(ZFS_IOC_POOL_EXPORT, zfs_ioc_pool_export,
6336             zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
6337
6338         zfs_ioctl_register_pool(ZFS_IOC_POOL_STATS, zfs_ioc_pool_stats,
6339             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6340         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_PROPS, zfs_ioc_pool_get_props,
6341             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
6342
6343         zfs_ioctl_register_pool(ZFS_IOC_ERROR_LOG, zfs_ioc_error_log,
6344             zfs_secpolicy_inject, B_FALSE, POOL_CHECK_NONE);
6345         zfs_ioctl_register_pool(ZFS_IOC_DSOBJ_TO_DSNAME,
6346             zfs_ioc_dsobj_to_dsname,
6347             zfs_secpolicy_diff, B_FALSE, POOL_CHECK_NONE);
6348         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_HISTORY,
6349             zfs_ioc_pool_get_history,
6350             zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
6351
6352         zfs_ioctl_register_pool(ZFS_IOC_POOL_IMPORT, zfs_ioc_pool_import,
6353             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
6354
6355         zfs_ioctl_register_pool(ZFS_IOC_CLEAR, zfs_ioc_clear,
6356             zfs_secpolicy_config, B_TRUE, POOL_CHECK_READONLY);
6357         zfs_ioctl_register_pool(ZFS_IOC_POOL_REOPEN, zfs_ioc_pool_reopen,
6358             zfs_secpolicy_config, B_TRUE, POOL_CHECK_SUSPENDED);
6359
6360         zfs_ioctl_register_dataset_read(ZFS_IOC_SPACE_WRITTEN,
6361             zfs_ioc_space_written);
6362         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_RECVD_PROPS,
6363             zfs_ioc_objset_recvd_props);
6364         zfs_ioctl_register_dataset_read(ZFS_IOC_NEXT_OBJ,
6365             zfs_ioc_next_obj);
6366         zfs_ioctl_register_dataset_read(ZFS_IOC_GET_FSACL,
6367             zfs_ioc_get_fsacl);
6368         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_STATS,
6369             zfs_ioc_objset_stats);
6370         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_ZPLPROPS,
6371             zfs_ioc_objset_zplprops);
6372         zfs_ioctl_register_dataset_read(ZFS_IOC_DATASET_LIST_NEXT,
6373             zfs_ioc_dataset_list_next);
6374         zfs_ioctl_register_dataset_read(ZFS_IOC_SNAPSHOT_LIST_NEXT,
6375             zfs_ioc_snapshot_list_next);
6376         zfs_ioctl_register_dataset_read(ZFS_IOC_SEND_PROGRESS,
6377             zfs_ioc_send_progress);
6378
6379         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_DIFF,
6380             zfs_ioc_diff, zfs_secpolicy_diff);
6381         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_STATS,
6382             zfs_ioc_obj_to_stats, zfs_secpolicy_diff);
6383         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_PATH,
6384             zfs_ioc_obj_to_path, zfs_secpolicy_diff);
6385         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_ONE,
6386             zfs_ioc_userspace_one, zfs_secpolicy_userspace_one);
6387         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_MANY,
6388             zfs_ioc_userspace_many, zfs_secpolicy_userspace_many);
6389         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_SEND,
6390             zfs_ioc_send, zfs_secpolicy_send);
6391
6392         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_PROP, zfs_ioc_set_prop,
6393             zfs_secpolicy_none);
6394         zfs_ioctl_register_dataset_modify(ZFS_IOC_DESTROY, zfs_ioc_destroy,
6395             zfs_secpolicy_destroy);
6396         zfs_ioctl_register_dataset_modify(ZFS_IOC_RECV, zfs_ioc_recv,
6397             zfs_secpolicy_recv);
6398         zfs_ioctl_register_dataset_modify(ZFS_IOC_PROMOTE, zfs_ioc_promote,
6399             zfs_secpolicy_promote);
6400         zfs_ioctl_register_dataset_modify(ZFS_IOC_INHERIT_PROP,
6401             zfs_ioc_inherit_prop, zfs_secpolicy_inherit_prop);
6402         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_FSACL, zfs_ioc_set_fsacl,
6403             zfs_secpolicy_set_fsacl);
6404
6405         /*
6406          * Not using zfs_ioctl_register_dataset_modify as DATASET_NAME check
6407          * won't allow a bookmark name.
6408          */
6409         zfs_ioctl_register_legacy(ZFS_IOC_RENAME, zfs_ioc_rename,
6410             zfs_secpolicy_rename, ENTITY_NAME, B_TRUE,
6411             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6412
6413         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SHARE, zfs_ioc_share,
6414             zfs_secpolicy_share, POOL_CHECK_NONE);
6415         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SMB_ACL, zfs_ioc_smb_acl,
6416             zfs_secpolicy_smb_acl, POOL_CHECK_NONE);
6417         zfs_ioctl_register_dataset_nolog(ZFS_IOC_USERSPACE_UPGRADE,
6418             zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
6419             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6420         zfs_ioctl_register_dataset_nolog(ZFS_IOC_TMP_SNAPSHOT,
6421             zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot,
6422             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
6423
6424 #ifdef __FreeBSD__
6425         zfs_ioctl_register_dataset_nolog(ZFS_IOC_JAIL, zfs_ioc_jail,
6426             zfs_secpolicy_config, POOL_CHECK_NONE);
6427         zfs_ioctl_register_dataset_nolog(ZFS_IOC_UNJAIL, zfs_ioc_unjail,
6428             zfs_secpolicy_config, POOL_CHECK_NONE);
6429         zfs_ioctl_register("fbsd_nextboot", ZFS_IOC_NEXTBOOT,
6430             zfs_ioc_nextboot, zfs_secpolicy_config, NO_NAME,
6431             POOL_CHECK_NONE, B_FALSE, B_FALSE);
6432 #endif
6433 }
6434
6435 int
6436 pool_status_check(const char *name, zfs_ioc_namecheck_t type,
6437     zfs_ioc_poolcheck_t check)
6438 {
6439         spa_t *spa;
6440         int error;
6441
6442         ASSERT(type == POOL_NAME || type == DATASET_NAME ||
6443             type == ENTITY_NAME);
6444
6445         if (check & POOL_CHECK_NONE)
6446                 return (0);
6447
6448         error = spa_open(name, &spa, FTAG);
6449         if (error == 0) {
6450                 if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
6451                         error = SET_ERROR(EAGAIN);
6452                 else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
6453                         error = SET_ERROR(EROFS);
6454                 spa_close(spa, FTAG);
6455         }
6456         return (error);
6457 }
6458
6459 /*
6460  * Find a free minor number.
6461  */
6462 minor_t
6463 zfsdev_minor_alloc(void)
6464 {
6465         static minor_t last_minor;
6466         minor_t m;
6467
6468         ASSERT(MUTEX_HELD(&spa_namespace_lock));
6469
6470         for (m = last_minor + 1; m != last_minor; m++) {
6471                 if (m > ZFSDEV_MAX_MINOR)
6472                         m = 1;
6473                 if (ddi_get_soft_state(zfsdev_state, m) == NULL) {
6474                         last_minor = m;
6475                         return (m);
6476                 }
6477         }
6478
6479         return (0);
6480 }
6481
6482 static int
6483 zfs_ctldev_init(struct cdev *devp)
6484 {
6485         minor_t minor;
6486         zfs_soft_state_t *zs;
6487
6488         ASSERT(MUTEX_HELD(&spa_namespace_lock));
6489
6490         minor = zfsdev_minor_alloc();
6491         if (minor == 0)
6492                 return (SET_ERROR(ENXIO));
6493
6494         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS)
6495                 return (SET_ERROR(EAGAIN));
6496
6497         devfs_set_cdevpriv((void *)(uintptr_t)minor, zfsdev_close);
6498
6499         zs = ddi_get_soft_state(zfsdev_state, minor);
6500         zs->zss_type = ZSST_CTLDEV;
6501         zfs_onexit_init((zfs_onexit_t **)&zs->zss_data);
6502
6503         return (0);
6504 }
6505
6506 static void
6507 zfs_ctldev_destroy(zfs_onexit_t *zo, minor_t minor)
6508 {
6509         ASSERT(MUTEX_HELD(&spa_namespace_lock));
6510
6511         zfs_onexit_destroy(zo);
6512         ddi_soft_state_free(zfsdev_state, minor);
6513 }
6514
6515 void *
6516 zfsdev_get_soft_state(minor_t minor, enum zfs_soft_state_type which)
6517 {
6518         zfs_soft_state_t *zp;
6519
6520         zp = ddi_get_soft_state(zfsdev_state, minor);
6521         if (zp == NULL || zp->zss_type != which)
6522                 return (NULL);
6523
6524         return (zp->zss_data);
6525 }
6526
6527 static int
6528 zfsdev_open(struct cdev *devp, int flag, int mode, struct thread *td)
6529 {
6530         int error = 0;
6531
6532 #ifdef illumos
6533         if (getminor(*devp) != 0)
6534                 return (zvol_open(devp, flag, otyp, cr));
6535 #endif
6536
6537         /* This is the control device. Allocate a new minor if requested. */
6538         if (flag & FEXCL) {
6539                 mutex_enter(&spa_namespace_lock);
6540                 error = zfs_ctldev_init(devp);
6541                 mutex_exit(&spa_namespace_lock);
6542         }
6543
6544         return (error);
6545 }
6546
6547 static void
6548 zfsdev_close(void *data)
6549 {
6550         zfs_onexit_t *zo;
6551         minor_t minor = (minor_t)(uintptr_t)data;
6552
6553         if (minor == 0)
6554                 return;
6555
6556         mutex_enter(&spa_namespace_lock);
6557         zo = zfsdev_get_soft_state(minor, ZSST_CTLDEV);
6558         if (zo == NULL) {
6559                 mutex_exit(&spa_namespace_lock);
6560                 return;
6561         }
6562         zfs_ctldev_destroy(zo, minor);
6563         mutex_exit(&spa_namespace_lock);
6564 }
6565
6566 static int
6567 zfsdev_ioctl(struct cdev *dev, u_long zcmd, caddr_t arg, int flag,
6568     struct thread *td)
6569 {
6570         zfs_cmd_t *zc;
6571         uint_t vecnum;
6572         int error, rc, len;
6573 #ifdef illumos
6574         minor_t minor = getminor(dev);
6575 #else
6576         zfs_iocparm_t *zc_iocparm;
6577         int cflag, cmd, oldvecnum;
6578         boolean_t newioc, compat;
6579         void *compat_zc = NULL;
6580         cred_t *cr = td->td_ucred;
6581 #endif
6582         const zfs_ioc_vec_t *vec;
6583         char *saved_poolname = NULL;
6584         nvlist_t *innvl = NULL;
6585
6586         cflag = ZFS_CMD_COMPAT_NONE;
6587         compat = B_FALSE;
6588         newioc = B_TRUE;        /* "new" style (zfs_iocparm_t) ioctl */
6589
6590         len = IOCPARM_LEN(zcmd);
6591         vecnum = cmd = zcmd & 0xff;
6592
6593         /*
6594          * Check if we are talking to supported older binaries
6595          * and translate zfs_cmd if necessary
6596          */
6597         if (len != sizeof(zfs_iocparm_t)) {
6598                 newioc = B_FALSE;
6599                 compat = B_TRUE;
6600
6601                 vecnum = cmd;
6602
6603                 switch (len) {
6604                 case sizeof(zfs_cmd_zcmd_t):
6605                         cflag = ZFS_CMD_COMPAT_LZC;
6606                         break;
6607                 case sizeof(zfs_cmd_deadman_t):
6608                         cflag = ZFS_CMD_COMPAT_DEADMAN;
6609                         break;
6610                 case sizeof(zfs_cmd_v28_t):
6611                         cflag = ZFS_CMD_COMPAT_V28;
6612                         break;
6613                 case sizeof(zfs_cmd_v15_t):
6614                         if (cmd >= sizeof(zfs_ioctl_v15_to_v28) /
6615                             sizeof(zfs_ioctl_v15_to_v28[0]))
6616                                 return (EINVAL);
6617
6618                         cflag = ZFS_CMD_COMPAT_V15;
6619                         vecnum = zfs_ioctl_v15_to_v28[cmd];
6620
6621                         /*
6622                          * Return without further handling
6623                          * if the command is blacklisted.
6624                          */
6625                         if (vecnum == ZFS_IOC_COMPAT_PASS)
6626                                 return (0);
6627                         else if (vecnum == ZFS_IOC_COMPAT_FAIL)
6628                                 return (ENOTSUP);
6629                         break;
6630                 default:
6631                         return (EINVAL);
6632                 }
6633         }
6634
6635 #ifdef illumos
6636         vecnum = cmd - ZFS_IOC_FIRST;
6637         ASSERT3U(getmajor(dev), ==, ddi_driver_major(zfs_dip));
6638 #endif
6639
6640         if (vecnum >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
6641                 return (SET_ERROR(EINVAL));
6642         vec = &zfs_ioc_vec[vecnum];
6643
6644         zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
6645
6646 #ifdef illumos
6647         error = ddi_copyin((void *)arg, zc, sizeof (zfs_cmd_t), flag);
6648         if (error != 0) {
6649                 error = SET_ERROR(EFAULT);
6650                 goto out;
6651         }
6652 #else   /* !illumos */
6653         bzero(zc, sizeof(zfs_cmd_t));
6654
6655         if (newioc) {
6656                 zc_iocparm = (void *)arg;
6657
6658                 switch (zc_iocparm->zfs_ioctl_version) {
6659                 case ZFS_IOCVER_CURRENT:
6660                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_t)) {
6661                                 error = SET_ERROR(EINVAL);
6662                                 goto out;
6663                         }
6664                         break;
6665                 case ZFS_IOCVER_INLANES:
6666                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_inlanes_t)) {
6667                                 error = SET_ERROR(EFAULT);
6668                                 goto out;
6669                         }
6670                         compat = B_TRUE;
6671                         cflag = ZFS_CMD_COMPAT_INLANES;
6672                         break;
6673                 case ZFS_IOCVER_RESUME:
6674                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_resume_t)) {
6675                                 error = SET_ERROR(EFAULT);
6676                                 goto out;
6677                         }
6678                         compat = B_TRUE;
6679                         cflag = ZFS_CMD_COMPAT_RESUME;
6680                         break;
6681                 case ZFS_IOCVER_EDBP:
6682                         if (zc_iocparm->zfs_cmd_size != sizeof(zfs_cmd_edbp_t)) {
6683                                 error = SET_ERROR(EFAULT);
6684                                 goto out;
6685                         }
6686                         compat = B_TRUE;
6687                         cflag = ZFS_CMD_COMPAT_EDBP;
6688                         break;
6689                 case ZFS_IOCVER_ZCMD:
6690                         if (zc_iocparm->zfs_cmd_size > sizeof(zfs_cmd_t) ||
6691                             zc_iocparm->zfs_cmd_size < sizeof(zfs_cmd_zcmd_t)) {
6692                                 error = SET_ERROR(EFAULT);
6693                                 goto out;
6694                         }
6695                         compat = B_TRUE;
6696                         cflag = ZFS_CMD_COMPAT_ZCMD;
6697                         break;
6698                 default:
6699                         error = SET_ERROR(EINVAL);
6700                         goto out;
6701                         /* NOTREACHED */
6702                 }
6703
6704                 if (compat) {
6705                         ASSERT(sizeof(zfs_cmd_t) >= zc_iocparm->zfs_cmd_size);
6706                         compat_zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
6707                         bzero(compat_zc, sizeof(zfs_cmd_t));
6708
6709                         error = ddi_copyin((void *)(uintptr_t)zc_iocparm->zfs_cmd,
6710                             compat_zc, zc_iocparm->zfs_cmd_size, flag);
6711                         if (error != 0) {
6712                                 error = SET_ERROR(EFAULT);
6713                                 goto out;
6714                         }
6715                 } else {
6716                         error = ddi_copyin((void *)(uintptr_t)zc_iocparm->zfs_cmd,
6717                             zc, zc_iocparm->zfs_cmd_size, flag);
6718                         if (error != 0) {
6719                                 error = SET_ERROR(EFAULT);
6720                                 goto out;
6721                         }
6722                 }
6723         }
6724
6725         if (compat) {
6726                 if (newioc) {
6727                         ASSERT(compat_zc != NULL);
6728                         zfs_cmd_compat_get(zc, compat_zc, cflag);
6729                 } else {
6730                         ASSERT(compat_zc == NULL);
6731                         zfs_cmd_compat_get(zc, arg, cflag);
6732                 }
6733                 oldvecnum = vecnum;
6734                 error = zfs_ioctl_compat_pre(zc, &vecnum, cflag);
6735                 if (error != 0)
6736                         goto out;
6737                 if (oldvecnum != vecnum)
6738                         vec = &zfs_ioc_vec[vecnum];
6739         }
6740 #endif  /* !illumos */
6741
6742         zc->zc_iflags = flag & FKIOCTL;
6743         if (zc->zc_nvlist_src_size != 0) {
6744                 error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
6745                     zc->zc_iflags, &innvl);
6746                 if (error != 0)
6747                         goto out;
6748         }
6749
6750         /* rewrite innvl for backwards compatibility */
6751         if (compat)
6752                 innvl = zfs_ioctl_compat_innvl(zc, innvl, vecnum, cflag);
6753
6754         /*
6755          * Ensure that all pool/dataset names are valid before we pass down to
6756          * the lower layers.
6757          */
6758         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
6759         switch (vec->zvec_namecheck) {
6760         case POOL_NAME:
6761                 if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
6762                         error = SET_ERROR(EINVAL);
6763                 else
6764                         error = pool_status_check(zc->zc_name,
6765                             vec->zvec_namecheck, vec->zvec_pool_check);
6766                 break;
6767
6768         case DATASET_NAME:
6769                 if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
6770                         error = SET_ERROR(EINVAL);
6771                 else
6772                         error = pool_status_check(zc->zc_name,
6773                             vec->zvec_namecheck, vec->zvec_pool_check);
6774                 break;
6775
6776         case ENTITY_NAME:
6777                 if (entity_namecheck(zc->zc_name, NULL, NULL) != 0) {
6778                         error = SET_ERROR(EINVAL);
6779                 } else {
6780                         error = pool_status_check(zc->zc_name,
6781                             vec->zvec_namecheck, vec->zvec_pool_check);
6782                 }
6783                 break;
6784
6785         case NO_NAME:
6786                 break;
6787         }
6788
6789         if (error == 0)
6790                 error = vec->zvec_secpolicy(zc, innvl, cr);
6791
6792         if (error != 0)
6793                 goto out;
6794
6795         /* legacy ioctls can modify zc_name */
6796         len = strcspn(zc->zc_name, "/@#") + 1;
6797         saved_poolname = kmem_alloc(len, KM_SLEEP);
6798         (void) strlcpy(saved_poolname, zc->zc_name, len);
6799
6800         if (vec->zvec_func != NULL) {
6801                 nvlist_t *outnvl;
6802                 int puterror = 0;
6803                 spa_t *spa;
6804                 nvlist_t *lognv = NULL;
6805
6806                 ASSERT(vec->zvec_legacy_func == NULL);
6807
6808                 /*
6809                  * Add the innvl to the lognv before calling the func,
6810                  * in case the func changes the innvl.
6811                  */
6812                 if (vec->zvec_allow_log) {
6813                         lognv = fnvlist_alloc();
6814                         fnvlist_add_string(lognv, ZPOOL_HIST_IOCTL,
6815                             vec->zvec_name);
6816                         if (!nvlist_empty(innvl)) {
6817                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_INPUT_NVL,
6818                                     innvl);
6819                         }
6820                 }
6821
6822                 outnvl = fnvlist_alloc();
6823                 error = vec->zvec_func(zc->zc_name, innvl, outnvl);
6824
6825                 /*
6826                  * Some commands can partially execute, modify state, and still
6827                  * return an error.  In these cases, attempt to record what
6828                  * was modified.
6829                  */
6830                 if ((error == 0 ||
6831                     (cmd == ZFS_IOC_CHANNEL_PROGRAM && error != EINVAL)) &&
6832                     vec->zvec_allow_log &&
6833                     spa_open(zc->zc_name, &spa, FTAG) == 0) {
6834                         if (!nvlist_empty(outnvl)) {
6835                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_OUTPUT_NVL,
6836                                     outnvl);
6837                         }
6838                         if (error != 0) {
6839                                 fnvlist_add_int64(lognv, ZPOOL_HIST_ERRNO,
6840                                     error);
6841                         }
6842                         (void) spa_history_log_nvl(spa, lognv);
6843                         spa_close(spa, FTAG);
6844                 }
6845                 fnvlist_free(lognv);
6846
6847                 /* rewrite outnvl for backwards compatibility */
6848                 if (compat)
6849                         outnvl = zfs_ioctl_compat_outnvl(zc, outnvl, vecnum,
6850                             cflag);
6851
6852                 if (!nvlist_empty(outnvl) || zc->zc_nvlist_dst_size != 0) {
6853                         int smusherror = 0;
6854                         if (vec->zvec_smush_outnvlist) {
6855                                 smusherror = nvlist_smush(outnvl,
6856                                     zc->zc_nvlist_dst_size);
6857                         }
6858                         if (smusherror == 0)
6859                                 puterror = put_nvlist(zc, outnvl);
6860                 }
6861
6862                 if (puterror != 0)
6863                         error = puterror;
6864
6865                 nvlist_free(outnvl);
6866         } else {
6867                 error = vec->zvec_legacy_func(zc);
6868         }
6869
6870 out:
6871         nvlist_free(innvl);
6872
6873 #ifdef illumos
6874         rc = ddi_copyout(zc, (void *)arg, sizeof (zfs_cmd_t), flag);
6875         if (error == 0 && rc != 0)
6876                 error = SET_ERROR(EFAULT);
6877 #else
6878         if (compat) {
6879                 zfs_ioctl_compat_post(zc, cmd, cflag);
6880                 if (newioc) {
6881                         ASSERT(compat_zc != NULL);
6882                         ASSERT(sizeof(zfs_cmd_t) >= zc_iocparm->zfs_cmd_size);
6883
6884                         zfs_cmd_compat_put(zc, compat_zc, vecnum, cflag);
6885                         rc = ddi_copyout(compat_zc,
6886                             (void *)(uintptr_t)zc_iocparm->zfs_cmd,
6887                             zc_iocparm->zfs_cmd_size, flag);
6888                         if (error == 0 && rc != 0)
6889                                 error = SET_ERROR(EFAULT);
6890                         kmem_free(compat_zc, sizeof (zfs_cmd_t));
6891                 } else {
6892                         zfs_cmd_compat_put(zc, arg, vecnum, cflag);
6893                 }
6894         } else {
6895                 ASSERT(newioc);
6896
6897                 rc = ddi_copyout(zc, (void *)(uintptr_t)zc_iocparm->zfs_cmd,
6898                     sizeof (zfs_cmd_t), flag);
6899                 if (error == 0 && rc != 0)
6900                         error = SET_ERROR(EFAULT);
6901         }
6902 #endif
6903         if (error == 0 && vec->zvec_allow_log) {
6904                 char *s = tsd_get(zfs_allow_log_key);
6905                 if (s != NULL)
6906                         strfree(s);
6907                 (void) tsd_set(zfs_allow_log_key, saved_poolname);
6908         } else {
6909                 if (saved_poolname != NULL)
6910                         strfree(saved_poolname);
6911         }
6912
6913         kmem_free(zc, sizeof (zfs_cmd_t));
6914         return (error);
6915 }
6916
6917 #ifdef illumos
6918 static int
6919 zfs_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
6920 {
6921         if (cmd != DDI_ATTACH)
6922                 return (DDI_FAILURE);
6923
6924         if (ddi_create_minor_node(dip, "zfs", S_IFCHR, 0,
6925             DDI_PSEUDO, 0) == DDI_FAILURE)
6926                 return (DDI_FAILURE);
6927
6928         zfs_dip = dip;
6929
6930         ddi_report_dev(dip);
6931
6932         return (DDI_SUCCESS);
6933 }
6934
6935 static int
6936 zfs_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
6937 {
6938         if (spa_busy() || zfs_busy() || zvol_busy())
6939                 return (DDI_FAILURE);
6940
6941         if (cmd != DDI_DETACH)
6942                 return (DDI_FAILURE);
6943
6944         zfs_dip = NULL;
6945
6946         ddi_prop_remove_all(dip);
6947         ddi_remove_minor_node(dip, NULL);
6948
6949         return (DDI_SUCCESS);
6950 }
6951
6952 /*ARGSUSED*/
6953 static int
6954 zfs_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
6955 {
6956         switch (infocmd) {
6957         case DDI_INFO_DEVT2DEVINFO:
6958                 *result = zfs_dip;
6959                 return (DDI_SUCCESS);
6960
6961         case DDI_INFO_DEVT2INSTANCE:
6962                 *result = (void *)0;
6963                 return (DDI_SUCCESS);
6964         }
6965
6966         return (DDI_FAILURE);
6967 }
6968 #endif  /* illumos */
6969
6970 /*
6971  * OK, so this is a little weird.
6972  *
6973  * /dev/zfs is the control node, i.e. minor 0.
6974  * /dev/zvol/[r]dsk/pool/dataset are the zvols, minor > 0.
6975  *
6976  * /dev/zfs has basically nothing to do except serve up ioctls,
6977  * so most of the standard driver entry points are in zvol.c.
6978  */
6979 #ifdef illumos
6980 static struct cb_ops zfs_cb_ops = {
6981         zfsdev_open,    /* open */
6982         zfsdev_close,   /* close */
6983         zvol_strategy,  /* strategy */
6984         nodev,          /* print */
6985         zvol_dump,      /* dump */
6986         zvol_read,      /* read */
6987         zvol_write,     /* write */
6988         zfsdev_ioctl,   /* ioctl */
6989         nodev,          /* devmap */
6990         nodev,          /* mmap */
6991         nodev,          /* segmap */
6992         nochpoll,       /* poll */
6993         ddi_prop_op,    /* prop_op */
6994         NULL,           /* streamtab */
6995         D_NEW | D_MP | D_64BIT,         /* Driver compatibility flag */
6996         CB_REV,         /* version */
6997         nodev,          /* async read */
6998         nodev,          /* async write */
6999 };
7000
7001 static struct dev_ops zfs_dev_ops = {
7002         DEVO_REV,       /* version */
7003         0,              /* refcnt */
7004         zfs_info,       /* info */
7005         nulldev,        /* identify */
7006         nulldev,        /* probe */
7007         zfs_attach,     /* attach */
7008         zfs_detach,     /* detach */
7009         nodev,          /* reset */
7010         &zfs_cb_ops,    /* driver operations */
7011         NULL,           /* no bus operations */
7012         NULL,           /* power */
7013         ddi_quiesce_not_needed, /* quiesce */
7014 };
7015
7016 static struct modldrv zfs_modldrv = {
7017         &mod_driverops,
7018         "ZFS storage pool",
7019         &zfs_dev_ops
7020 };
7021
7022 static struct modlinkage modlinkage = {
7023         MODREV_1,
7024         (void *)&zfs_modlfs,
7025         (void *)&zfs_modldrv,
7026         NULL
7027 };
7028 #endif  /* illumos */
7029
7030 static struct cdevsw zfs_cdevsw = {
7031         .d_version =    D_VERSION,
7032         .d_open =       zfsdev_open,
7033         .d_ioctl =      zfsdev_ioctl,
7034         .d_name =       ZFS_DEV_NAME
7035 };
7036
7037 static void
7038 zfs_allow_log_destroy(void *arg)
7039 {
7040         char *poolname = arg;
7041         strfree(poolname);
7042 }
7043
7044 static void
7045 zfsdev_init(void)
7046 {
7047         zfsdev = make_dev(&zfs_cdevsw, 0x0, UID_ROOT, GID_OPERATOR, 0666,
7048             ZFS_DEV_NAME);
7049 }
7050
7051 static void
7052 zfsdev_fini(void)
7053 {
7054         if (zfsdev != NULL)
7055                 destroy_dev(zfsdev);
7056 }
7057
7058 static struct root_hold_token *zfs_root_token;
7059 struct proc *zfsproc;
7060
7061 #ifdef illumos
7062 int
7063 _init(void)
7064 {
7065         int error;
7066
7067         spa_init(FREAD | FWRITE);
7068         zfs_init();
7069         zvol_init();
7070         zfs_ioctl_init();
7071
7072         if ((error = mod_install(&modlinkage)) != 0) {
7073                 zvol_fini();
7074                 zfs_fini();
7075                 spa_fini();
7076                 return (error);
7077         }
7078
7079         tsd_create(&zfs_fsyncer_key, NULL);
7080         tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
7081         tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
7082
7083         error = ldi_ident_from_mod(&modlinkage, &zfs_li);
7084         ASSERT(error == 0);
7085         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
7086
7087         return (0);
7088 }
7089
7090 int
7091 _fini(void)
7092 {
7093         int error;
7094
7095         if (spa_busy() || zfs_busy() || zvol_busy() || zio_injection_enabled)
7096                 return (SET_ERROR(EBUSY));
7097
7098         if ((error = mod_remove(&modlinkage)) != 0)
7099                 return (error);
7100
7101         zvol_fini();
7102         zfs_fini();
7103         spa_fini();
7104         if (zfs_nfsshare_inited)
7105                 (void) ddi_modclose(nfs_mod);
7106         if (zfs_smbshare_inited)
7107                 (void) ddi_modclose(smbsrv_mod);
7108         if (zfs_nfsshare_inited || zfs_smbshare_inited)
7109                 (void) ddi_modclose(sharefs_mod);
7110
7111         tsd_destroy(&zfs_fsyncer_key);
7112         ldi_ident_release(zfs_li);
7113         zfs_li = NULL;
7114         mutex_destroy(&zfs_share_lock);
7115
7116         return (error);
7117 }
7118
7119 int
7120 _info(struct modinfo *modinfop)
7121 {
7122         return (mod_info(&modlinkage, modinfop));
7123 }
7124 #endif  /* illumos */
7125
7126 static int zfs__init(void);
7127 static int zfs__fini(void);
7128 static void zfs_shutdown(void *, int);
7129
7130 static eventhandler_tag zfs_shutdown_event_tag;
7131
7132 #ifdef __FreeBSD__
7133 #define ZFS_MIN_KSTACK_PAGES 4
7134 #endif
7135
7136 int
7137 zfs__init(void)
7138 {
7139
7140 #ifdef __FreeBSD__
7141 #if KSTACK_PAGES < ZFS_MIN_KSTACK_PAGES
7142         printf("ZFS NOTICE: KSTACK_PAGES is %d which could result in stack "
7143             "overflow panic!\nPlease consider adding "
7144             "'options KSTACK_PAGES=%d' to your kernel config\n", KSTACK_PAGES,
7145             ZFS_MIN_KSTACK_PAGES);
7146 #endif
7147 #endif
7148         zfs_root_token = root_mount_hold("ZFS");
7149
7150         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
7151
7152         spa_init(FREAD | FWRITE);
7153         zfs_init();
7154         zvol_init();
7155         zfs_ioctl_init();
7156
7157         tsd_create(&zfs_fsyncer_key, NULL);
7158         tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
7159         tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
7160         tsd_create(&zfs_geom_probe_vdev_key, NULL);
7161
7162         printf("ZFS storage pool version: features support (" SPA_VERSION_STRING ")\n");
7163         root_mount_rel(zfs_root_token);
7164
7165         zfsdev_init();
7166
7167         return (0);
7168 }
7169
7170 int
7171 zfs__fini(void)
7172 {
7173         if (spa_busy() || zfs_busy() || zvol_busy() ||
7174             zio_injection_enabled) {
7175                 return (EBUSY);
7176         }
7177
7178         zfsdev_fini();
7179         zvol_fini();
7180         zfs_fini();
7181         spa_fini();
7182
7183         tsd_destroy(&zfs_fsyncer_key);
7184         tsd_destroy(&rrw_tsd_key);
7185         tsd_destroy(&zfs_allow_log_key);
7186
7187         mutex_destroy(&zfs_share_lock);
7188
7189         return (0);
7190 }
7191
7192 static void
7193 zfs_shutdown(void *arg __unused, int howto __unused)
7194 {
7195
7196         /*
7197          * ZFS fini routines can not properly work in a panic-ed system.
7198          */
7199         if (panicstr == NULL)
7200                 (void)zfs__fini();
7201 }
7202
7203
7204 static int
7205 zfs_modevent(module_t mod, int type, void *unused __unused)
7206 {
7207         int err;
7208
7209         switch (type) {
7210         case MOD_LOAD:
7211                 err = zfs__init();
7212                 if (err == 0)
7213                         zfs_shutdown_event_tag = EVENTHANDLER_REGISTER(
7214                             shutdown_post_sync, zfs_shutdown, NULL,
7215                             SHUTDOWN_PRI_FIRST);
7216                 return (err);
7217         case MOD_UNLOAD:
7218                 err = zfs__fini();
7219                 if (err == 0 && zfs_shutdown_event_tag != NULL)
7220                         EVENTHANDLER_DEREGISTER(shutdown_post_sync,
7221                             zfs_shutdown_event_tag);
7222                 return (err);
7223         case MOD_SHUTDOWN:
7224                 return (0);
7225         default:
7226                 break;
7227         }
7228         return (EOPNOTSUPP);
7229 }
7230
7231 static moduledata_t zfs_mod = {
7232         "zfsctrl",
7233         zfs_modevent,
7234         0
7235 };
7236 DECLARE_MODULE(zfsctrl, zfs_mod, SI_SUB_VFS, SI_ORDER_ANY);
7237 MODULE_VERSION(zfsctrl, 1);
7238 MODULE_DEPEND(zfsctrl, opensolaris, 1, 1, 1);
7239 MODULE_DEPEND(zfsctrl, krpc, 1, 1, 1);
7240 MODULE_DEPEND(zfsctrl, acl_nfs4, 1, 1, 1);
7241 MODULE_DEPEND(zfsctrl, zlib, 1, 1, 1);