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