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