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