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