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