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