Add linux kernel device support
[zfs.git] / module / 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  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24
25 #include <sys/types.h>
26 #include <sys/param.h>
27 #include <sys/errno.h>
28 #include <sys/uio.h>
29 #include <sys/buf.h>
30 #include <sys/modctl.h>
31 #include <sys/open.h>
32 #include <sys/file.h>
33 #include <sys/kmem.h>
34 #include <sys/conf.h>
35 #include <sys/cmn_err.h>
36 #include <sys/stat.h>
37 #include <sys/zfs_ioctl.h>
38 #include <sys/zfs_vfsops.h>
39 #include <sys/zfs_znode.h>
40 #include <sys/zap.h>
41 #include <sys/spa.h>
42 #include <sys/spa_impl.h>
43 #include <sys/vdev.h>
44 #include <sys/priv_impl.h>
45 #include <sys/dmu.h>
46 #include <sys/dsl_dir.h>
47 #include <sys/dsl_dataset.h>
48 #include <sys/dsl_prop.h>
49 #include <sys/dsl_deleg.h>
50 #include <sys/dmu_objset.h>
51 #include <sys/ddi.h>
52 #include <sys/sunddi.h>
53 #include <sys/sunldi.h>
54 #include <sys/policy.h>
55 #include <sys/zone.h>
56 #include <sys/nvpair.h>
57 #include <sys/pathname.h>
58 #include <sys/mount.h>
59 #include <sys/sdt.h>
60 #include <sys/fs/zfs.h>
61 #include <sys/zfs_ctldir.h>
62 #include <sys/zfs_dir.h>
63 #include <sys/zfs_onexit.h>
64 #include <sys/zvol.h>
65 #include <sys/dsl_scan.h>
66 #include <sharefs/share.h>
67 #include <sys/dmu_objset.h>
68 #include <sys/fm/util.h>
69
70 #include <linux/miscdevice.h>
71
72 #include "zfs_namecheck.h"
73 #include "zfs_prop.h"
74 #include "zfs_deleg.h"
75 #include "zfs_comutil.h"
76
77 kmutex_t zfsdev_state_lock;
78 list_t zfsdev_state_list;
79
80 extern void zfs_init(void);
81 extern void zfs_fini(void);
82
83 typedef int zfs_ioc_func_t(zfs_cmd_t *);
84 typedef int zfs_secpolicy_func_t(zfs_cmd_t *, cred_t *);
85
86 typedef enum {
87         NO_NAME,
88         POOL_NAME,
89         DATASET_NAME
90 } zfs_ioc_namecheck_t;
91
92 typedef enum {
93         POOL_CHECK_NONE         = 1 << 0,
94         POOL_CHECK_SUSPENDED    = 1 << 1,
95         POOL_CHECK_READONLY     = 1 << 2
96 } zfs_ioc_poolcheck_t;
97
98 typedef struct zfs_ioc_vec {
99         zfs_ioc_func_t          *zvec_func;
100         zfs_secpolicy_func_t    *zvec_secpolicy;
101         zfs_ioc_namecheck_t     zvec_namecheck;
102         boolean_t               zvec_his_log;
103         zfs_ioc_poolcheck_t     zvec_pool_check;
104 } zfs_ioc_vec_t;
105
106 /* This array is indexed by zfs_userquota_prop_t */
107 static const char *userquota_perms[] = {
108         ZFS_DELEG_PERM_USERUSED,
109         ZFS_DELEG_PERM_USERQUOTA,
110         ZFS_DELEG_PERM_GROUPUSED,
111         ZFS_DELEG_PERM_GROUPQUOTA,
112 };
113
114 static int zfs_ioc_userspace_upgrade(zfs_cmd_t *zc);
115 static int zfs_check_settable(const char *name, nvpair_t *property,
116     cred_t *cr);
117 static int zfs_check_clearable(char *dataset, nvlist_t *props,
118     nvlist_t **errors);
119 static int zfs_fill_zplprops_root(uint64_t, nvlist_t *, nvlist_t *,
120     boolean_t *);
121 int zfs_set_prop_nvlist(const char *, zprop_source_t, nvlist_t *, nvlist_t **);
122
123 /* _NOTE(PRINTFLIKE(4)) - this is printf-like, but lint is too whiney */
124 void
125 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
126 {
127         const char *newfile;
128         char buf[512];
129         va_list adx;
130
131         /*
132          * Get rid of annoying "../common/" prefix to filename.
133          */
134         newfile = strrchr(file, '/');
135         if (newfile != NULL) {
136                 newfile = newfile + 1; /* Get rid of leading / */
137         } else {
138                 newfile = file;
139         }
140
141         va_start(adx, fmt);
142         (void) vsnprintf(buf, sizeof (buf), fmt, adx);
143         va_end(adx);
144
145         /*
146          * To get this data, use the zfs-dprintf probe as so:
147          * dtrace -q -n 'zfs-dprintf \
148          *      /stringof(arg0) == "dbuf.c"/ \
149          *      {printf("%s: %s", stringof(arg1), stringof(arg3))}'
150          * arg0 = file name
151          * arg1 = function name
152          * arg2 = line number
153          * arg3 = message
154          */
155         DTRACE_PROBE4(zfs__dprintf,
156             char *, newfile, char *, func, int, line, char *, buf);
157 }
158
159 static void
160 history_str_free(char *buf)
161 {
162         kmem_free(buf, HIS_MAX_RECORD_LEN);
163 }
164
165 static char *
166 history_str_get(zfs_cmd_t *zc)
167 {
168         char *buf;
169
170         if (zc->zc_history == 0)
171                 return (NULL);
172
173         buf = kmem_alloc(HIS_MAX_RECORD_LEN, KM_SLEEP);
174         if (copyinstr((void *)(uintptr_t)zc->zc_history,
175             buf, HIS_MAX_RECORD_LEN, NULL) != 0) {
176                 history_str_free(buf);
177                 return (NULL);
178         }
179
180         buf[HIS_MAX_RECORD_LEN -1] = '\0';
181
182         return (buf);
183 }
184
185 /*
186  * Check to see if the named dataset is currently defined as bootable
187  */
188 static boolean_t
189 zfs_is_bootfs(const char *name)
190 {
191         objset_t *os;
192
193         if (dmu_objset_hold(name, FTAG, &os) == 0) {
194                 boolean_t ret;
195                 ret = (dmu_objset_id(os) == spa_bootfs(dmu_objset_spa(os)));
196                 dmu_objset_rele(os, FTAG);
197                 return (ret);
198         }
199         return (B_FALSE);
200 }
201
202 /*
203  * zfs_earlier_version
204  *
205  *      Return non-zero if the spa version is less than requested version.
206  */
207 static int
208 zfs_earlier_version(const char *name, int version)
209 {
210         spa_t *spa;
211
212         if (spa_open(name, &spa, FTAG) == 0) {
213                 if (spa_version(spa) < version) {
214                         spa_close(spa, FTAG);
215                         return (1);
216                 }
217                 spa_close(spa, FTAG);
218         }
219         return (0);
220 }
221
222 /*
223  * zpl_earlier_version
224  *
225  * Return TRUE if the ZPL version is less than requested version.
226  */
227 static boolean_t
228 zpl_earlier_version(const char *name, int version)
229 {
230         objset_t *os;
231         boolean_t rc = B_TRUE;
232
233         if (dmu_objset_hold(name, FTAG, &os) == 0) {
234                 uint64_t zplversion;
235
236                 if (dmu_objset_type(os) != DMU_OST_ZFS) {
237                         dmu_objset_rele(os, FTAG);
238                         return (B_TRUE);
239                 }
240                 /* XXX reading from non-owned objset */
241                 if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &zplversion) == 0)
242                         rc = zplversion < version;
243                 dmu_objset_rele(os, FTAG);
244         }
245         return (rc);
246 }
247
248 static void
249 zfs_log_history(zfs_cmd_t *zc)
250 {
251         spa_t *spa;
252         char *buf;
253
254         if ((buf = history_str_get(zc)) == NULL)
255                 return;
256
257         if (spa_open(zc->zc_name, &spa, FTAG) == 0) {
258                 if (spa_version(spa) >= SPA_VERSION_ZPOOL_HISTORY)
259                         (void) spa_history_log(spa, buf, LOG_CMD_NORMAL);
260                 spa_close(spa, FTAG);
261         }
262         history_str_free(buf);
263 }
264
265 /*
266  * Policy for top-level read operations (list pools).  Requires no privileges,
267  * and can be used in the local zone, as there is no associated dataset.
268  */
269 /* ARGSUSED */
270 static int
271 zfs_secpolicy_none(zfs_cmd_t *zc, cred_t *cr)
272 {
273         return (0);
274 }
275
276 /*
277  * Policy for dataset read operations (list children, get statistics).  Requires
278  * no privileges, but must be visible in the local zone.
279  */
280 /* ARGSUSED */
281 static int
282 zfs_secpolicy_read(zfs_cmd_t *zc, cred_t *cr)
283 {
284         if (INGLOBALZONE(curproc) ||
285             zone_dataset_visible(zc->zc_name, NULL))
286                 return (0);
287
288         return (ENOENT);
289 }
290
291 static int
292 zfs_dozonecheck_impl(const char *dataset, uint64_t zoned, cred_t *cr)
293 {
294         int writable = 1;
295
296         /*
297          * The dataset must be visible by this zone -- check this first
298          * so they don't see EPERM on something they shouldn't know about.
299          */
300         if (!INGLOBALZONE(curproc) &&
301             !zone_dataset_visible(dataset, &writable))
302                 return (ENOENT);
303
304         if (INGLOBALZONE(curproc)) {
305                 /*
306                  * If the fs is zoned, only root can access it from the
307                  * global zone.
308                  */
309                 if (secpolicy_zfs(cr) && zoned)
310                         return (EPERM);
311         } else {
312                 /*
313                  * If we are in a local zone, the 'zoned' property must be set.
314                  */
315                 if (!zoned)
316                         return (EPERM);
317
318                 /* must be writable by this zone */
319                 if (!writable)
320                         return (EPERM);
321         }
322         return (0);
323 }
324
325 static int
326 zfs_dozonecheck(const char *dataset, cred_t *cr)
327 {
328         uint64_t zoned;
329
330         if (dsl_prop_get_integer(dataset, "zoned", &zoned, NULL))
331                 return (ENOENT);
332
333         return (zfs_dozonecheck_impl(dataset, zoned, cr));
334 }
335
336 static int
337 zfs_dozonecheck_ds(const char *dataset, dsl_dataset_t *ds, cred_t *cr)
338 {
339         uint64_t zoned;
340
341         rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
342         if (dsl_prop_get_ds(ds, "zoned", 8, 1, &zoned, NULL)) {
343                 rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
344                 return (ENOENT);
345         }
346         rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
347
348         return (zfs_dozonecheck_impl(dataset, zoned, cr));
349 }
350
351 int
352 zfs_secpolicy_write_perms(const char *name, const char *perm, cred_t *cr)
353 {
354         int error;
355
356         error = zfs_dozonecheck(name, cr);
357         if (error == 0) {
358                 error = secpolicy_zfs(cr);
359                 if (error)
360                         error = dsl_deleg_access(name, perm, cr);
361         }
362         return (error);
363 }
364
365 int
366 zfs_secpolicy_write_perms_ds(const char *name, dsl_dataset_t *ds,
367     const char *perm, cred_t *cr)
368 {
369         int error;
370
371         error = zfs_dozonecheck_ds(name, ds, cr);
372         if (error == 0) {
373                 error = secpolicy_zfs(cr);
374                 if (error)
375                         error = dsl_deleg_access_impl(ds, perm, cr);
376         }
377         return (error);
378 }
379
380 /*
381  * Policy for setting the security label property.
382  *
383  * Returns 0 for success, non-zero for access and other errors.
384  */
385 static int
386 zfs_set_slabel_policy(const char *name, char *strval, cred_t *cr)
387 {
388 #ifdef HAVE_MLSLABEL
389         char            ds_hexsl[MAXNAMELEN];
390         bslabel_t       ds_sl, new_sl;
391         boolean_t       new_default = FALSE;
392         uint64_t        zoned;
393         int             needed_priv = -1;
394         int             error;
395
396         /* First get the existing dataset label. */
397         error = dsl_prop_get(name, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
398             1, sizeof (ds_hexsl), &ds_hexsl, NULL);
399         if (error)
400                 return (EPERM);
401
402         if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
403                 new_default = TRUE;
404
405         /* The label must be translatable */
406         if (!new_default && (hexstr_to_label(strval, &new_sl) != 0))
407                 return (EINVAL);
408
409         /*
410          * In a non-global zone, disallow attempts to set a label that
411          * doesn't match that of the zone; otherwise no other checks
412          * are needed.
413          */
414         if (!INGLOBALZONE(curproc)) {
415                 if (new_default || !blequal(&new_sl, CR_SL(CRED())))
416                         return (EPERM);
417                 return (0);
418         }
419
420         /*
421          * For global-zone datasets (i.e., those whose zoned property is
422          * "off", verify that the specified new label is valid for the
423          * global zone.
424          */
425         if (dsl_prop_get_integer(name,
426             zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
427                 return (EPERM);
428         if (!zoned) {
429                 if (zfs_check_global_label(name, strval) != 0)
430                         return (EPERM);
431         }
432
433         /*
434          * If the existing dataset label is nondefault, check if the
435          * dataset is mounted (label cannot be changed while mounted).
436          * Get the zfsvfs; if there isn't one, then the dataset isn't
437          * mounted (or isn't a dataset, doesn't exist, ...).
438          */
439         if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) != 0) {
440                 objset_t *os;
441                 static char *setsl_tag = "setsl_tag";
442
443                 /*
444                  * Try to own the dataset; abort if there is any error,
445                  * (e.g., already mounted, in use, or other error).
446                  */
447                 error = dmu_objset_own(name, DMU_OST_ZFS, B_TRUE,
448                     setsl_tag, &os);
449                 if (error)
450                         return (EPERM);
451
452                 dmu_objset_disown(os, setsl_tag);
453
454                 if (new_default) {
455                         needed_priv = PRIV_FILE_DOWNGRADE_SL;
456                         goto out_check;
457                 }
458
459                 if (hexstr_to_label(strval, &new_sl) != 0)
460                         return (EPERM);
461
462                 if (blstrictdom(&ds_sl, &new_sl))
463                         needed_priv = PRIV_FILE_DOWNGRADE_SL;
464                 else if (blstrictdom(&new_sl, &ds_sl))
465                         needed_priv = PRIV_FILE_UPGRADE_SL;
466         } else {
467                 /* dataset currently has a default label */
468                 if (!new_default)
469                         needed_priv = PRIV_FILE_UPGRADE_SL;
470         }
471
472 out_check:
473         if (needed_priv != -1)
474                 return (PRIV_POLICY(cr, needed_priv, B_FALSE, EPERM, NULL));
475         return (0);
476 #else
477         return ENOTSUP;
478 #endif /* HAVE_MLSLABEL */
479 }
480
481 static int
482 zfs_secpolicy_setprop(const char *dsname, zfs_prop_t prop, nvpair_t *propval,
483     cred_t *cr)
484 {
485         char *strval;
486
487         /*
488          * Check permissions for special properties.
489          */
490         switch (prop) {
491         default:
492                 break;
493         case ZFS_PROP_ZONED:
494                 /*
495                  * Disallow setting of 'zoned' from within a local zone.
496                  */
497                 if (!INGLOBALZONE(curproc))
498                         return (EPERM);
499                 break;
500
501         case ZFS_PROP_QUOTA:
502                 if (!INGLOBALZONE(curproc)) {
503                         uint64_t zoned;
504                         char setpoint[MAXNAMELEN];
505                         /*
506                          * Unprivileged users are allowed to modify the
507                          * quota on things *under* (ie. contained by)
508                          * the thing they own.
509                          */
510                         if (dsl_prop_get_integer(dsname, "zoned", &zoned,
511                             setpoint))
512                                 return (EPERM);
513                         if (!zoned || strlen(dsname) <= strlen(setpoint))
514                                 return (EPERM);
515                 }
516                 break;
517
518         case ZFS_PROP_MLSLABEL:
519                 if (!is_system_labeled())
520                         return (EPERM);
521
522                 if (nvpair_value_string(propval, &strval) == 0) {
523                         int err;
524
525                         err = zfs_set_slabel_policy(dsname, strval, CRED());
526                         if (err != 0)
527                                 return (err);
528                 }
529                 break;
530         }
531
532         return (zfs_secpolicy_write_perms(dsname, zfs_prop_to_name(prop), cr));
533 }
534
535 int
536 zfs_secpolicy_fsacl(zfs_cmd_t *zc, cred_t *cr)
537 {
538         int error;
539
540         error = zfs_dozonecheck(zc->zc_name, cr);
541         if (error)
542                 return (error);
543
544         /*
545          * permission to set permissions will be evaluated later in
546          * dsl_deleg_can_allow()
547          */
548         return (0);
549 }
550
551 int
552 zfs_secpolicy_rollback(zfs_cmd_t *zc, cred_t *cr)
553 {
554         return (zfs_secpolicy_write_perms(zc->zc_name,
555             ZFS_DELEG_PERM_ROLLBACK, cr));
556 }
557
558 int
559 zfs_secpolicy_send(zfs_cmd_t *zc, cred_t *cr)
560 {
561         spa_t *spa;
562         dsl_pool_t *dp;
563         dsl_dataset_t *ds;
564         char *cp;
565         int error;
566
567         /*
568          * Generate the current snapshot name from the given objsetid, then
569          * use that name for the secpolicy/zone checks.
570          */
571         cp = strchr(zc->zc_name, '@');
572         if (cp == NULL)
573                 return (EINVAL);
574         error = spa_open(zc->zc_name, &spa, FTAG);
575         if (error)
576                 return (error);
577
578         dp = spa_get_dsl(spa);
579         rw_enter(&dp->dp_config_rwlock, RW_READER);
580         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
581         rw_exit(&dp->dp_config_rwlock);
582         spa_close(spa, FTAG);
583         if (error)
584                 return (error);
585
586         dsl_dataset_name(ds, zc->zc_name);
587
588         error = zfs_secpolicy_write_perms_ds(zc->zc_name, ds,
589             ZFS_DELEG_PERM_SEND, cr);
590         dsl_dataset_rele(ds, FTAG);
591
592         return (error);
593 }
594
595 #ifdef HAVE_ZPL
596 static int
597 zfs_secpolicy_deleg_share(zfs_cmd_t *zc, cred_t *cr)
598 {
599         vnode_t *vp;
600         int error;
601
602         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
603             NO_FOLLOW, NULL, &vp)) != 0)
604                 return (error);
605
606         /* Now make sure mntpnt and dataset are ZFS */
607
608         if (vp->v_vfsp->vfs_fstype != zfsfstype ||
609             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
610             zc->zc_name) != 0)) {
611                 VN_RELE(vp);
612                 return (EPERM);
613         }
614
615         VN_RELE(vp);
616         return (dsl_deleg_access(zc->zc_name,
617             ZFS_DELEG_PERM_SHARE, cr));
618 }
619 #endif /* HAVE_ZPL */
620
621 int
622 zfs_secpolicy_share(zfs_cmd_t *zc, cred_t *cr)
623 {
624 #ifdef HAVE_ZPL
625         if (!INGLOBALZONE(curproc))
626                 return (EPERM);
627
628         if (secpolicy_nfs(cr) == 0) {
629                 return (0);
630         } else {
631                 return (zfs_secpolicy_deleg_share(zc, cr));
632         }
633 #else
634         return (ENOTSUP);
635 #endif /* HAVE_ZPL */
636 }
637
638 int
639 zfs_secpolicy_smb_acl(zfs_cmd_t *zc, cred_t *cr)
640 {
641 #ifdef HAVE_ZPL
642         if (!INGLOBALZONE(curproc))
643                 return (EPERM);
644
645         if (secpolicy_smb(cr) == 0) {
646                 return (0);
647         } else {
648                 return (zfs_secpolicy_deleg_share(zc, cr));
649         }
650 #else
651         return (ENOTSUP);
652 #endif /* HAVE_ZPL */
653 }
654
655 static int
656 zfs_get_parent(const char *datasetname, char *parent, int parentsize)
657 {
658         char *cp;
659
660         /*
661          * Remove the @bla or /bla from the end of the name to get the parent.
662          */
663         (void) strncpy(parent, datasetname, parentsize);
664         cp = strrchr(parent, '@');
665         if (cp != NULL) {
666                 cp[0] = '\0';
667         } else {
668                 cp = strrchr(parent, '/');
669                 if (cp == NULL)
670                         return (ENOENT);
671                 cp[0] = '\0';
672         }
673
674         return (0);
675 }
676
677 int
678 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
679 {
680         int error;
681
682         if ((error = zfs_secpolicy_write_perms(name,
683             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
684                 return (error);
685
686         return (zfs_secpolicy_write_perms(name, ZFS_DELEG_PERM_DESTROY, cr));
687 }
688
689 static int
690 zfs_secpolicy_destroy(zfs_cmd_t *zc, cred_t *cr)
691 {
692         return (zfs_secpolicy_destroy_perms(zc->zc_name, cr));
693 }
694
695 /*
696  * Destroying snapshots with delegated permissions requires
697  * descendent mount and destroy permissions.
698  * Reassemble the full filesystem@snap name so dsl_deleg_access()
699  * can do the correct permission check.
700  *
701  * Since this routine is used when doing a recursive destroy of snapshots
702  * and destroying snapshots requires descendent permissions, a successfull
703  * check of the top level snapshot applies to snapshots of all descendent
704  * datasets as well.
705  */
706 static int
707 zfs_secpolicy_destroy_snaps(zfs_cmd_t *zc, cred_t *cr)
708 {
709         int error;
710         char *dsname;
711
712         dsname = kmem_asprintf("%s@%s", zc->zc_name, zc->zc_value);
713
714         error = zfs_secpolicy_destroy_perms(dsname, cr);
715
716         strfree(dsname);
717         return (error);
718 }
719
720 int
721 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
722 {
723         char    parentname[MAXNAMELEN];
724         int     error;
725
726         if ((error = zfs_secpolicy_write_perms(from,
727             ZFS_DELEG_PERM_RENAME, cr)) != 0)
728                 return (error);
729
730         if ((error = zfs_secpolicy_write_perms(from,
731             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
732                 return (error);
733
734         if ((error = zfs_get_parent(to, parentname,
735             sizeof (parentname))) != 0)
736                 return (error);
737
738         if ((error = zfs_secpolicy_write_perms(parentname,
739             ZFS_DELEG_PERM_CREATE, cr)) != 0)
740                 return (error);
741
742         if ((error = zfs_secpolicy_write_perms(parentname,
743             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
744                 return (error);
745
746         return (error);
747 }
748
749 static int
750 zfs_secpolicy_rename(zfs_cmd_t *zc, cred_t *cr)
751 {
752         return (zfs_secpolicy_rename_perms(zc->zc_name, zc->zc_value, cr));
753 }
754
755 static int
756 zfs_secpolicy_promote(zfs_cmd_t *zc, cred_t *cr)
757 {
758         char    parentname[MAXNAMELEN];
759         objset_t *clone;
760         int error;
761
762         error = zfs_secpolicy_write_perms(zc->zc_name,
763             ZFS_DELEG_PERM_PROMOTE, cr);
764         if (error)
765                 return (error);
766
767         error = dmu_objset_hold(zc->zc_name, FTAG, &clone);
768
769         if (error == 0) {
770                 dsl_dataset_t *pclone = NULL;
771                 dsl_dir_t *dd;
772                 dd = clone->os_dsl_dataset->ds_dir;
773
774                 rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
775                 error = dsl_dataset_hold_obj(dd->dd_pool,
776                     dd->dd_phys->dd_origin_obj, FTAG, &pclone);
777                 rw_exit(&dd->dd_pool->dp_config_rwlock);
778                 if (error) {
779                         dmu_objset_rele(clone, FTAG);
780                         return (error);
781                 }
782
783                 error = zfs_secpolicy_write_perms(zc->zc_name,
784                     ZFS_DELEG_PERM_MOUNT, cr);
785
786                 dsl_dataset_name(pclone, parentname);
787                 dmu_objset_rele(clone, FTAG);
788                 dsl_dataset_rele(pclone, FTAG);
789                 if (error == 0)
790                         error = zfs_secpolicy_write_perms(parentname,
791                             ZFS_DELEG_PERM_PROMOTE, cr);
792         }
793         return (error);
794 }
795
796 static int
797 zfs_secpolicy_receive(zfs_cmd_t *zc, cred_t *cr)
798 {
799         int error;
800
801         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
802             ZFS_DELEG_PERM_RECEIVE, cr)) != 0)
803                 return (error);
804
805         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
806             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
807                 return (error);
808
809         return (zfs_secpolicy_write_perms(zc->zc_name,
810             ZFS_DELEG_PERM_CREATE, cr));
811 }
812
813 int
814 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
815 {
816         return (zfs_secpolicy_write_perms(name,
817             ZFS_DELEG_PERM_SNAPSHOT, cr));
818 }
819
820 static int
821 zfs_secpolicy_snapshot(zfs_cmd_t *zc, cred_t *cr)
822 {
823
824         return (zfs_secpolicy_snapshot_perms(zc->zc_name, cr));
825 }
826
827 static int
828 zfs_secpolicy_create(zfs_cmd_t *zc, cred_t *cr)
829 {
830         char    parentname[MAXNAMELEN];
831         int     error;
832
833         if ((error = zfs_get_parent(zc->zc_name, parentname,
834             sizeof (parentname))) != 0)
835                 return (error);
836
837         if (zc->zc_value[0] != '\0') {
838                 if ((error = zfs_secpolicy_write_perms(zc->zc_value,
839                     ZFS_DELEG_PERM_CLONE, cr)) != 0)
840                         return (error);
841         }
842
843         if ((error = zfs_secpolicy_write_perms(parentname,
844             ZFS_DELEG_PERM_CREATE, cr)) != 0)
845                 return (error);
846
847         error = zfs_secpolicy_write_perms(parentname,
848             ZFS_DELEG_PERM_MOUNT, cr);
849
850         return (error);
851 }
852
853 #ifdef HAVE_ZPL
854 static int
855 zfs_secpolicy_umount(zfs_cmd_t *zc, cred_t *cr)
856 {
857         int error;
858
859         error = secpolicy_fs_unmount(cr, NULL);
860         if (error) {
861                 error = dsl_deleg_access(zc->zc_name, ZFS_DELEG_PERM_MOUNT, cr);
862         }
863         return (error);
864 }
865 #endif /* HAVE_ZPL */
866
867 /*
868  * Policy for pool operations - create/destroy pools, add vdevs, etc.  Requires
869  * SYS_CONFIG privilege, which is not available in a local zone.
870  */
871 /* ARGSUSED */
872 static int
873 zfs_secpolicy_config(zfs_cmd_t *zc, cred_t *cr)
874 {
875         if (secpolicy_sys_config(cr, B_FALSE) != 0)
876                 return (EPERM);
877
878         return (0);
879 }
880
881 /*
882  * Policy for object to name lookups.
883  */
884 /* ARGSUSED */
885 static int
886 zfs_secpolicy_diff(zfs_cmd_t *zc, cred_t *cr)
887 {
888         int error;
889
890         if ((error = secpolicy_sys_config(cr, B_FALSE)) == 0)
891                 return (0);
892
893         error = zfs_secpolicy_write_perms(zc->zc_name, ZFS_DELEG_PERM_DIFF, cr);
894         return (error);
895 }
896
897 /*
898  * Policy for fault injection.  Requires all privileges.
899  */
900 /* ARGSUSED */
901 static int
902 zfs_secpolicy_inject(zfs_cmd_t *zc, cred_t *cr)
903 {
904         return (secpolicy_zinject(cr));
905 }
906
907 static int
908 zfs_secpolicy_inherit(zfs_cmd_t *zc, cred_t *cr)
909 {
910         zfs_prop_t prop = zfs_name_to_prop(zc->zc_value);
911
912         if (prop == ZPROP_INVAL) {
913                 if (!zfs_prop_user(zc->zc_value))
914                         return (EINVAL);
915                 return (zfs_secpolicy_write_perms(zc->zc_name,
916                     ZFS_DELEG_PERM_USERPROP, cr));
917         } else {
918                 return (zfs_secpolicy_setprop(zc->zc_name, prop,
919                     NULL, cr));
920         }
921 }
922
923 static int
924 zfs_secpolicy_userspace_one(zfs_cmd_t *zc, cred_t *cr)
925 {
926         int err = zfs_secpolicy_read(zc, cr);
927         if (err)
928                 return (err);
929
930         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
931                 return (EINVAL);
932
933         if (zc->zc_value[0] == 0) {
934                 /*
935                  * They are asking about a posix uid/gid.  If it's
936                  * themself, allow it.
937                  */
938                 if (zc->zc_objset_type == ZFS_PROP_USERUSED ||
939                     zc->zc_objset_type == ZFS_PROP_USERQUOTA) {
940                         if (zc->zc_guid == crgetuid(cr))
941                                 return (0);
942                 } else {
943                         if (groupmember(zc->zc_guid, cr))
944                                 return (0);
945                 }
946         }
947
948         return (zfs_secpolicy_write_perms(zc->zc_name,
949             userquota_perms[zc->zc_objset_type], cr));
950 }
951
952 static int
953 zfs_secpolicy_userspace_many(zfs_cmd_t *zc, cred_t *cr)
954 {
955         int err = zfs_secpolicy_read(zc, cr);
956         if (err)
957                 return (err);
958
959         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
960                 return (EINVAL);
961
962         return (zfs_secpolicy_write_perms(zc->zc_name,
963             userquota_perms[zc->zc_objset_type], cr));
964 }
965
966 static int
967 zfs_secpolicy_userspace_upgrade(zfs_cmd_t *zc, cred_t *cr)
968 {
969         return (zfs_secpolicy_setprop(zc->zc_name, ZFS_PROP_VERSION,
970             NULL, cr));
971 }
972
973 static int
974 zfs_secpolicy_hold(zfs_cmd_t *zc, cred_t *cr)
975 {
976         return (zfs_secpolicy_write_perms(zc->zc_name,
977             ZFS_DELEG_PERM_HOLD, cr));
978 }
979
980 static int
981 zfs_secpolicy_release(zfs_cmd_t *zc, cred_t *cr)
982 {
983         return (zfs_secpolicy_write_perms(zc->zc_name,
984             ZFS_DELEG_PERM_RELEASE, cr));
985 }
986
987 /*
988  * Policy for allowing temporary snapshots to be taken or released
989  */
990 static int
991 zfs_secpolicy_tmp_snapshot(zfs_cmd_t *zc, cred_t *cr)
992 {
993         /*
994          * A temporary snapshot is the same as a snapshot,
995          * hold, destroy and release all rolled into one.
996          * Delegated diff alone is sufficient that we allow this.
997          */
998         int error;
999
1000         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
1001             ZFS_DELEG_PERM_DIFF, cr)) == 0)
1002                 return (0);
1003
1004         error = zfs_secpolicy_snapshot(zc, cr);
1005         if (!error)
1006                 error = zfs_secpolicy_hold(zc, cr);
1007         if (!error)
1008                 error = zfs_secpolicy_release(zc, cr);
1009         if (!error)
1010                 error = zfs_secpolicy_destroy(zc, cr);
1011         return (error);
1012 }
1013
1014 /*
1015  * Returns the nvlist as specified by the user in the zfs_cmd_t.
1016  */
1017 static int
1018 get_nvlist(uint64_t nvl, uint64_t size, int iflag, nvlist_t **nvp)
1019 {
1020         char *packed;
1021         int error;
1022         nvlist_t *list = NULL;
1023
1024         /*
1025          * Read in and unpack the user-supplied nvlist.
1026          */
1027         if (size == 0)
1028                 return (EINVAL);
1029
1030         packed = kmem_alloc(size, KM_SLEEP);
1031
1032         if ((error = ddi_copyin((void *)(uintptr_t)nvl, packed, size,
1033             iflag)) != 0) {
1034                 kmem_free(packed, size);
1035                 return (error);
1036         }
1037
1038         if ((error = nvlist_unpack(packed, size, &list, 0)) != 0) {
1039                 kmem_free(packed, size);
1040                 return (error);
1041         }
1042
1043         kmem_free(packed, size);
1044
1045         *nvp = list;
1046         return (0);
1047 }
1048
1049 static int
1050 fit_error_list(zfs_cmd_t *zc, nvlist_t **errors)
1051 {
1052         size_t size;
1053
1054         VERIFY(nvlist_size(*errors, &size, NV_ENCODE_NATIVE) == 0);
1055
1056         if (size > zc->zc_nvlist_dst_size) {
1057                 nvpair_t *more_errors;
1058                 int n = 0;
1059
1060                 if (zc->zc_nvlist_dst_size < 1024)
1061                         return (ENOMEM);
1062
1063                 VERIFY(nvlist_add_int32(*errors, ZPROP_N_MORE_ERRORS, 0) == 0);
1064                 more_errors = nvlist_prev_nvpair(*errors, NULL);
1065
1066                 do {
1067                         nvpair_t *pair = nvlist_prev_nvpair(*errors,
1068                             more_errors);
1069                         VERIFY(nvlist_remove_nvpair(*errors, pair) == 0);
1070                         n++;
1071                         VERIFY(nvlist_size(*errors, &size,
1072                             NV_ENCODE_NATIVE) == 0);
1073                 } while (size > zc->zc_nvlist_dst_size);
1074
1075                 VERIFY(nvlist_remove_nvpair(*errors, more_errors) == 0);
1076                 VERIFY(nvlist_add_int32(*errors, ZPROP_N_MORE_ERRORS, n) == 0);
1077                 ASSERT(nvlist_size(*errors, &size, NV_ENCODE_NATIVE) == 0);
1078                 ASSERT(size <= zc->zc_nvlist_dst_size);
1079         }
1080
1081         return (0);
1082 }
1083
1084 static int
1085 put_nvlist(zfs_cmd_t *zc, nvlist_t *nvl)
1086 {
1087         char *packed = NULL;
1088         int error = 0;
1089         size_t size;
1090
1091         VERIFY(nvlist_size(nvl, &size, NV_ENCODE_NATIVE) == 0);
1092
1093         if (size > zc->zc_nvlist_dst_size) {
1094                 error = ENOMEM;
1095         } else {
1096                 packed = kmem_alloc(size, KM_SLEEP);
1097                 VERIFY(nvlist_pack(nvl, &packed, &size, NV_ENCODE_NATIVE,
1098                     KM_SLEEP) == 0);
1099                 if (ddi_copyout(packed, (void *)(uintptr_t)zc->zc_nvlist_dst,
1100                     size, zc->zc_iflags) != 0)
1101                         error = EFAULT;
1102                 kmem_free(packed, size);
1103         }
1104
1105         zc->zc_nvlist_dst_size = size;
1106         return (error);
1107 }
1108
1109 #ifdef HAVE_ZPL
1110 static int
1111 getzfsvfs(const char *dsname, zfsvfs_t **zfvp)
1112 {
1113         objset_t *os;
1114         int error;
1115
1116         error = dmu_objset_hold(dsname, FTAG, &os);
1117         if (error)
1118                 return (error);
1119         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1120                 dmu_objset_rele(os, FTAG);
1121                 return (EINVAL);
1122         }
1123
1124         mutex_enter(&os->os_user_ptr_lock);
1125         *zfvp = dmu_objset_get_user(os);
1126         if (*zfvp) {
1127                 VFS_HOLD((*zfvp)->z_vfs);
1128         } else {
1129                 error = ESRCH;
1130         }
1131         mutex_exit(&os->os_user_ptr_lock);
1132         dmu_objset_rele(os, FTAG);
1133         return (error);
1134 }
1135 #endif
1136
1137 /*
1138  * Find a zfsvfs_t for a mounted filesystem, or create our own, in which
1139  * case its z_vfs will be NULL, and it will be opened as the owner.
1140  */
1141 static int
1142 zfsvfs_hold(const char *name, void *tag, zfsvfs_t **zfvp, boolean_t writer)
1143 {
1144 #ifdef HAVE_ZPL
1145         int error = 0;
1146
1147         if (getzfsvfs(name, zfvp) != 0)
1148                 error = zfsvfs_create(name, zfvp);
1149         if (error == 0) {
1150                 rrw_enter(&(*zfvp)->z_teardown_lock, (writer) ? RW_WRITER :
1151                     RW_READER, tag);
1152                 if ((*zfvp)->z_unmounted) {
1153                         /*
1154                          * XXX we could probably try again, since the unmounting
1155                          * thread should be just about to disassociate the
1156                          * objset from the zfsvfs.
1157                          */
1158                         rrw_exit(&(*zfvp)->z_teardown_lock, tag);
1159                         return (EBUSY);
1160                 }
1161         }
1162         return (error);
1163 #else
1164         return ENOTSUP;
1165 #endif
1166 }
1167
1168 static void
1169 zfsvfs_rele(zfsvfs_t *zfsvfs, void *tag)
1170 {
1171 #ifdef HAVE_ZPL
1172         rrw_exit(&zfsvfs->z_teardown_lock, tag);
1173
1174         if (zfsvfs->z_vfs) {
1175                 VFS_RELE(zfsvfs->z_vfs);
1176         } else {
1177                 dmu_objset_disown(zfsvfs->z_os, zfsvfs);
1178                 zfsvfs_free(zfsvfs);
1179         }
1180 #endif
1181 }
1182
1183 static int
1184 zfs_ioc_pool_create(zfs_cmd_t *zc)
1185 {
1186         int error;
1187         nvlist_t *config, *props = NULL;
1188         nvlist_t *rootprops = NULL;
1189         nvlist_t *zplprops = NULL;
1190         char *buf;
1191
1192         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1193             zc->zc_iflags, &config)))
1194                 return (error);
1195
1196         if (zc->zc_nvlist_src_size != 0 && (error =
1197             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1198             zc->zc_iflags, &props))) {
1199                 nvlist_free(config);
1200                 return (error);
1201         }
1202
1203         if (props) {
1204                 nvlist_t *nvl = NULL;
1205                 uint64_t version = SPA_VERSION;
1206
1207                 (void) nvlist_lookup_uint64(props,
1208                     zpool_prop_to_name(ZPOOL_PROP_VERSION), &version);
1209                 if (version < SPA_VERSION_INITIAL || version > SPA_VERSION) {
1210                         error = EINVAL;
1211                         goto pool_props_bad;
1212                 }
1213                 (void) nvlist_lookup_nvlist(props, ZPOOL_ROOTFS_PROPS, &nvl);
1214                 if (nvl) {
1215                         error = nvlist_dup(nvl, &rootprops, KM_SLEEP);
1216                         if (error != 0) {
1217                                 nvlist_free(config);
1218                                 nvlist_free(props);
1219                                 return (error);
1220                         }
1221                         (void) nvlist_remove_all(props, ZPOOL_ROOTFS_PROPS);
1222                 }
1223                 VERIFY(nvlist_alloc(&zplprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1224                 error = zfs_fill_zplprops_root(version, rootprops,
1225                     zplprops, NULL);
1226                 if (error)
1227                         goto pool_props_bad;
1228         }
1229
1230         buf = history_str_get(zc);
1231
1232         error = spa_create(zc->zc_name, config, props, buf, zplprops);
1233
1234         /*
1235          * Set the remaining root properties
1236          */
1237         if (!error && (error = zfs_set_prop_nvlist(zc->zc_name,
1238             ZPROP_SRC_LOCAL, rootprops, NULL)) != 0)
1239                 (void) spa_destroy(zc->zc_name);
1240
1241         if (buf != NULL)
1242                 history_str_free(buf);
1243
1244 pool_props_bad:
1245         nvlist_free(rootprops);
1246         nvlist_free(zplprops);
1247         nvlist_free(config);
1248         nvlist_free(props);
1249
1250         return (error);
1251 }
1252
1253 static int
1254 zfs_ioc_pool_destroy(zfs_cmd_t *zc)
1255 {
1256         int error;
1257         zfs_log_history(zc);
1258         error = spa_destroy(zc->zc_name);
1259         if (error == 0)
1260                 zvol_remove_minors(zc->zc_name);
1261         return (error);
1262 }
1263
1264 static int
1265 zfs_ioc_pool_import(zfs_cmd_t *zc)
1266 {
1267         nvlist_t *config, *props = NULL;
1268         uint64_t guid;
1269         int error;
1270
1271         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1272             zc->zc_iflags, &config)) != 0)
1273                 return (error);
1274
1275         if (zc->zc_nvlist_src_size != 0 && (error =
1276             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1277             zc->zc_iflags, &props))) {
1278                 nvlist_free(config);
1279                 return (error);
1280         }
1281
1282         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1283             guid != zc->zc_guid)
1284                 error = EINVAL;
1285         else
1286                 error = spa_import(zc->zc_name, config, props, zc->zc_cookie);
1287
1288         if (zc->zc_nvlist_dst != 0) {
1289                 int err;
1290
1291                 if ((err = put_nvlist(zc, config)) != 0)
1292                         error = err;
1293         }
1294
1295         nvlist_free(config);
1296
1297         if (props)
1298                 nvlist_free(props);
1299
1300         return (error);
1301 }
1302
1303 static int
1304 zfs_ioc_pool_export(zfs_cmd_t *zc)
1305 {
1306         int error;
1307         boolean_t force = (boolean_t)zc->zc_cookie;
1308         boolean_t hardforce = (boolean_t)zc->zc_guid;
1309
1310         zfs_log_history(zc);
1311         error = spa_export(zc->zc_name, NULL, force, hardforce);
1312         if (error == 0)
1313                 zvol_remove_minors(zc->zc_name);
1314         return (error);
1315 }
1316
1317 static int
1318 zfs_ioc_pool_configs(zfs_cmd_t *zc)
1319 {
1320         nvlist_t *configs;
1321         int error;
1322
1323         if ((configs = spa_all_configs(&zc->zc_cookie)) == NULL)
1324                 return (EEXIST);
1325
1326         error = put_nvlist(zc, configs);
1327
1328         nvlist_free(configs);
1329
1330         return (error);
1331 }
1332
1333 static int
1334 zfs_ioc_pool_stats(zfs_cmd_t *zc)
1335 {
1336         nvlist_t *config;
1337         int error;
1338         int ret = 0;
1339
1340         error = spa_get_stats(zc->zc_name, &config, zc->zc_value,
1341             sizeof (zc->zc_value));
1342
1343         if (config != NULL) {
1344                 ret = put_nvlist(zc, config);
1345                 nvlist_free(config);
1346
1347                 /*
1348                  * The config may be present even if 'error' is non-zero.
1349                  * In this case we return success, and preserve the real errno
1350                  * in 'zc_cookie'.
1351                  */
1352                 zc->zc_cookie = error;
1353         } else {
1354                 ret = error;
1355         }
1356
1357         return (ret);
1358 }
1359
1360 /*
1361  * Try to import the given pool, returning pool stats as appropriate so that
1362  * user land knows which devices are available and overall pool health.
1363  */
1364 static int
1365 zfs_ioc_pool_tryimport(zfs_cmd_t *zc)
1366 {
1367         nvlist_t *tryconfig, *config;
1368         int error;
1369
1370         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1371             zc->zc_iflags, &tryconfig)) != 0)
1372                 return (error);
1373
1374         config = spa_tryimport(tryconfig);
1375
1376         nvlist_free(tryconfig);
1377
1378         if (config == NULL)
1379                 return (EINVAL);
1380
1381         error = put_nvlist(zc, config);
1382         nvlist_free(config);
1383
1384         return (error);
1385 }
1386
1387 /*
1388  * inputs:
1389  * zc_name              name of the pool
1390  * zc_cookie            scan func (pool_scan_func_t)
1391  */
1392 static int
1393 zfs_ioc_pool_scan(zfs_cmd_t *zc)
1394 {
1395         spa_t *spa;
1396         int error;
1397
1398         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1399                 return (error);
1400
1401         if (zc->zc_cookie == POOL_SCAN_NONE)
1402                 error = spa_scan_stop(spa);
1403         else
1404                 error = spa_scan(spa, zc->zc_cookie);
1405
1406         spa_close(spa, FTAG);
1407
1408         return (error);
1409 }
1410
1411 static int
1412 zfs_ioc_pool_freeze(zfs_cmd_t *zc)
1413 {
1414         spa_t *spa;
1415         int error;
1416
1417         error = spa_open(zc->zc_name, &spa, FTAG);
1418         if (error == 0) {
1419                 spa_freeze(spa);
1420                 spa_close(spa, FTAG);
1421         }
1422         return (error);
1423 }
1424
1425 static int
1426 zfs_ioc_pool_upgrade(zfs_cmd_t *zc)
1427 {
1428         spa_t *spa;
1429         int error;
1430
1431         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1432                 return (error);
1433
1434         if (zc->zc_cookie < spa_version(spa) || zc->zc_cookie > SPA_VERSION) {
1435                 spa_close(spa, FTAG);
1436                 return (EINVAL);
1437         }
1438
1439         spa_upgrade(spa, zc->zc_cookie);
1440         spa_close(spa, FTAG);
1441
1442         return (error);
1443 }
1444
1445 static int
1446 zfs_ioc_pool_get_history(zfs_cmd_t *zc)
1447 {
1448         spa_t *spa;
1449         char *hist_buf;
1450         uint64_t size;
1451         int error;
1452
1453         if ((size = zc->zc_history_len) == 0)
1454                 return (EINVAL);
1455
1456         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1457                 return (error);
1458
1459         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
1460                 spa_close(spa, FTAG);
1461                 return (ENOTSUP);
1462         }
1463
1464         hist_buf = kmem_alloc(size, KM_SLEEP);
1465         if ((error = spa_history_get(spa, &zc->zc_history_offset,
1466             &zc->zc_history_len, hist_buf)) == 0) {
1467                 error = ddi_copyout(hist_buf,
1468                     (void *)(uintptr_t)zc->zc_history,
1469                     zc->zc_history_len, zc->zc_iflags);
1470         }
1471
1472         spa_close(spa, FTAG);
1473         kmem_free(hist_buf, size);
1474         return (error);
1475 }
1476
1477 static int
1478 zfs_ioc_dsobj_to_dsname(zfs_cmd_t *zc)
1479 {
1480         int error;
1481
1482         if ((error = dsl_dsobj_to_dsname(zc->zc_name,zc->zc_obj,zc->zc_value)))
1483                 return (error);
1484
1485         return (0);
1486 }
1487
1488 /*
1489  * inputs:
1490  * zc_name              name of filesystem
1491  * zc_obj               object to find
1492  *
1493  * outputs:
1494  * zc_value             name of object
1495  */
1496 static int
1497 zfs_ioc_obj_to_path(zfs_cmd_t *zc)
1498 {
1499         objset_t *os;
1500         int error;
1501
1502         /* XXX reading from objset not owned */
1503         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)) != 0)
1504                 return (error);
1505         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1506                 dmu_objset_rele(os, FTAG);
1507                 return (EINVAL);
1508         }
1509         error = zfs_obj_to_path(os, zc->zc_obj, zc->zc_value,
1510             sizeof (zc->zc_value));
1511         dmu_objset_rele(os, FTAG);
1512
1513         return (error);
1514 }
1515
1516 /*
1517  * inputs:
1518  * zc_name              name of filesystem
1519  * zc_obj               object to find
1520  *
1521  * outputs:
1522  * zc_stat              stats on object
1523  * zc_value             path to object
1524  */
1525 static int
1526 zfs_ioc_obj_to_stats(zfs_cmd_t *zc)
1527 {
1528         objset_t *os;
1529         int error;
1530
1531         /* XXX reading from objset not owned */
1532         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)) != 0)
1533                 return (error);
1534         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1535                 dmu_objset_rele(os, FTAG);
1536                 return (EINVAL);
1537         }
1538         error = zfs_obj_to_stats(os, zc->zc_obj, &zc->zc_stat, zc->zc_value,
1539             sizeof (zc->zc_value));
1540         dmu_objset_rele(os, FTAG);
1541
1542         return (error);
1543 }
1544
1545 static int
1546 zfs_ioc_vdev_add(zfs_cmd_t *zc)
1547 {
1548         spa_t *spa;
1549         int error;
1550         nvlist_t *config, **l2cache, **spares;
1551         uint_t nl2cache = 0, nspares = 0;
1552
1553         error = spa_open(zc->zc_name, &spa, FTAG);
1554         if (error != 0)
1555                 return (error);
1556
1557         error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1558             zc->zc_iflags, &config);
1559         (void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_L2CACHE,
1560             &l2cache, &nl2cache);
1561
1562         (void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_SPARES,
1563             &spares, &nspares);
1564
1565         /*
1566          * A root pool with concatenated devices is not supported.
1567          * Thus, can not add a device to a root pool.
1568          *
1569          * Intent log device can not be added to a rootpool because
1570          * during mountroot, zil is replayed, a seperated log device
1571          * can not be accessed during the mountroot time.
1572          *
1573          * l2cache and spare devices are ok to be added to a rootpool.
1574          */
1575         if (spa_bootfs(spa) != 0 && nl2cache == 0 && nspares == 0) {
1576                 nvlist_free(config);
1577                 spa_close(spa, FTAG);
1578                 return (EDOM);
1579         }
1580
1581         if (error == 0) {
1582                 error = spa_vdev_add(spa, config);
1583                 nvlist_free(config);
1584         }
1585         spa_close(spa, FTAG);
1586         return (error);
1587 }
1588
1589 /*
1590  * inputs:
1591  * zc_name              name of the pool
1592  * zc_nvlist_conf       nvlist of devices to remove
1593  * zc_cookie            to stop the remove?
1594  */
1595 static int
1596 zfs_ioc_vdev_remove(zfs_cmd_t *zc)
1597 {
1598         spa_t *spa;
1599         int error;
1600
1601         error = spa_open(zc->zc_name, &spa, FTAG);
1602         if (error != 0)
1603                 return (error);
1604         error = spa_vdev_remove(spa, zc->zc_guid, B_FALSE);
1605         spa_close(spa, FTAG);
1606         return (error);
1607 }
1608
1609 static int
1610 zfs_ioc_vdev_set_state(zfs_cmd_t *zc)
1611 {
1612         spa_t *spa;
1613         int error;
1614         vdev_state_t newstate = VDEV_STATE_UNKNOWN;
1615
1616         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1617                 return (error);
1618         switch (zc->zc_cookie) {
1619         case VDEV_STATE_ONLINE:
1620                 error = vdev_online(spa, zc->zc_guid, zc->zc_obj, &newstate);
1621                 break;
1622
1623         case VDEV_STATE_OFFLINE:
1624                 error = vdev_offline(spa, zc->zc_guid, zc->zc_obj);
1625                 break;
1626
1627         case VDEV_STATE_FAULTED:
1628                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1629                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1630                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1631
1632                 error = vdev_fault(spa, zc->zc_guid, zc->zc_obj);
1633                 break;
1634
1635         case VDEV_STATE_DEGRADED:
1636                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1637                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1638                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1639
1640                 error = vdev_degrade(spa, zc->zc_guid, zc->zc_obj);
1641                 break;
1642
1643         default:
1644                 error = EINVAL;
1645         }
1646         zc->zc_cookie = newstate;
1647         spa_close(spa, FTAG);
1648         return (error);
1649 }
1650
1651 static int
1652 zfs_ioc_vdev_attach(zfs_cmd_t *zc)
1653 {
1654         spa_t *spa;
1655         int replacing = zc->zc_cookie;
1656         nvlist_t *config;
1657         int error;
1658
1659         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1660                 return (error);
1661
1662         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1663             zc->zc_iflags, &config)) == 0) {
1664                 error = spa_vdev_attach(spa, zc->zc_guid, config, replacing);
1665                 nvlist_free(config);
1666         }
1667
1668         spa_close(spa, FTAG);
1669         return (error);
1670 }
1671
1672 static int
1673 zfs_ioc_vdev_detach(zfs_cmd_t *zc)
1674 {
1675         spa_t *spa;
1676         int error;
1677
1678         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1679                 return (error);
1680
1681         error = spa_vdev_detach(spa, zc->zc_guid, 0, B_FALSE);
1682
1683         spa_close(spa, FTAG);
1684         return (error);
1685 }
1686
1687 static int
1688 zfs_ioc_vdev_split(zfs_cmd_t *zc)
1689 {
1690         spa_t *spa;
1691         nvlist_t *config, *props = NULL;
1692         int error;
1693         boolean_t exp = !!(zc->zc_cookie & ZPOOL_EXPORT_AFTER_SPLIT);
1694
1695         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1696                 return (error);
1697
1698         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1699             zc->zc_iflags, &config))) {
1700                 spa_close(spa, FTAG);
1701                 return (error);
1702         }
1703
1704         if (zc->zc_nvlist_src_size != 0 && (error =
1705             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1706             zc->zc_iflags, &props))) {
1707                 spa_close(spa, FTAG);
1708                 nvlist_free(config);
1709                 return (error);
1710         }
1711
1712         error = spa_vdev_split_mirror(spa, zc->zc_string, config, props, exp);
1713
1714         spa_close(spa, FTAG);
1715
1716         nvlist_free(config);
1717         nvlist_free(props);
1718
1719         return (error);
1720 }
1721
1722 static int
1723 zfs_ioc_vdev_setpath(zfs_cmd_t *zc)
1724 {
1725         spa_t *spa;
1726         char *path = zc->zc_value;
1727         uint64_t guid = zc->zc_guid;
1728         int error;
1729
1730         error = spa_open(zc->zc_name, &spa, FTAG);
1731         if (error != 0)
1732                 return (error);
1733
1734         error = spa_vdev_setpath(spa, guid, path);
1735         spa_close(spa, FTAG);
1736         return (error);
1737 }
1738
1739 static int
1740 zfs_ioc_vdev_setfru(zfs_cmd_t *zc)
1741 {
1742         spa_t *spa;
1743         char *fru = zc->zc_value;
1744         uint64_t guid = zc->zc_guid;
1745         int error;
1746
1747         error = spa_open(zc->zc_name, &spa, FTAG);
1748         if (error != 0)
1749                 return (error);
1750
1751         error = spa_vdev_setfru(spa, guid, fru);
1752         spa_close(spa, FTAG);
1753         return (error);
1754 }
1755
1756 static int
1757 zfs_ioc_objset_stats_impl(zfs_cmd_t *zc, objset_t *os)
1758 {
1759         int error = 0;
1760         nvlist_t *nv;
1761
1762         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
1763
1764         if (zc->zc_nvlist_dst != 0 &&
1765             (error = dsl_prop_get_all(os, &nv)) == 0) {
1766                 dmu_objset_stats(os, nv);
1767                 /*
1768                  * NB: zvol_get_stats() will read the objset contents,
1769                  * which we aren't supposed to do with a
1770                  * DS_MODE_USER hold, because it could be
1771                  * inconsistent.  So this is a bit of a workaround...
1772                  * XXX reading with out owning
1773                  */
1774                 if (!zc->zc_objset_stats.dds_inconsistent) {
1775                         if (dmu_objset_type(os) == DMU_OST_ZVOL)
1776                                 error = zvol_get_stats(os, nv);
1777                 }
1778                 if (error == 0)
1779                         error = put_nvlist(zc, nv);
1780                 nvlist_free(nv);
1781         }
1782
1783         return (error);
1784 }
1785
1786 /*
1787  * inputs:
1788  * zc_name              name of filesystem
1789  * zc_nvlist_dst_size   size of buffer for property nvlist
1790  *
1791  * outputs:
1792  * zc_objset_stats      stats
1793  * zc_nvlist_dst        property nvlist
1794  * zc_nvlist_dst_size   size of property nvlist
1795  */
1796 static int
1797 zfs_ioc_objset_stats(zfs_cmd_t *zc)
1798 {
1799         objset_t *os = NULL;
1800         int error;
1801
1802         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)))
1803                 return (error);
1804
1805         error = zfs_ioc_objset_stats_impl(zc, os);
1806
1807         dmu_objset_rele(os, FTAG);
1808
1809         return (error);
1810 }
1811
1812 /*
1813  * inputs:
1814  * zc_name              name of filesystem
1815  * zc_nvlist_dst_size   size of buffer for property nvlist
1816  *
1817  * outputs:
1818  * zc_nvlist_dst        received property nvlist
1819  * zc_nvlist_dst_size   size of received property nvlist
1820  *
1821  * Gets received properties (distinct from local properties on or after
1822  * SPA_VERSION_RECVD_PROPS) for callers who want to differentiate received from
1823  * local property values.
1824  */
1825 static int
1826 zfs_ioc_objset_recvd_props(zfs_cmd_t *zc)
1827 {
1828         objset_t *os = NULL;
1829         int error;
1830         nvlist_t *nv;
1831
1832         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)))
1833                 return (error);
1834
1835         /*
1836          * Without this check, we would return local property values if the
1837          * caller has not already received properties on or after
1838          * SPA_VERSION_RECVD_PROPS.
1839          */
1840         if (!dsl_prop_get_hasrecvd(os)) {
1841                 dmu_objset_rele(os, FTAG);
1842                 return (ENOTSUP);
1843         }
1844
1845         if (zc->zc_nvlist_dst != 0 &&
1846             (error = dsl_prop_get_received(os, &nv)) == 0) {
1847                 error = put_nvlist(zc, nv);
1848                 nvlist_free(nv);
1849         }
1850
1851         dmu_objset_rele(os, FTAG);
1852         return (error);
1853 }
1854
1855 static int
1856 nvl_add_zplprop(objset_t *os, nvlist_t *props, zfs_prop_t prop)
1857 {
1858         uint64_t value;
1859         int error;
1860
1861         /*
1862          * zfs_get_zplprop() will either find a value or give us
1863          * the default value (if there is one).
1864          */
1865         if ((error = zfs_get_zplprop(os, prop, &value)) != 0)
1866                 return (error);
1867         VERIFY(nvlist_add_uint64(props, zfs_prop_to_name(prop), value) == 0);
1868         return (0);
1869 }
1870
1871 /*
1872  * inputs:
1873  * zc_name              name of filesystem
1874  * zc_nvlist_dst_size   size of buffer for zpl property nvlist
1875  *
1876  * outputs:
1877  * zc_nvlist_dst        zpl property nvlist
1878  * zc_nvlist_dst_size   size of zpl property nvlist
1879  */
1880 static int
1881 zfs_ioc_objset_zplprops(zfs_cmd_t *zc)
1882 {
1883         objset_t *os;
1884         int err;
1885
1886         /* XXX reading without owning */
1887         if ((err = dmu_objset_hold(zc->zc_name, FTAG, &os)))
1888                 return (err);
1889
1890         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
1891
1892         /*
1893          * NB: nvl_add_zplprop() will read the objset contents,
1894          * which we aren't supposed to do with a DS_MODE_USER
1895          * hold, because it could be inconsistent.
1896          */
1897         if (zc->zc_nvlist_dst != 0 &&
1898             !zc->zc_objset_stats.dds_inconsistent &&
1899             dmu_objset_type(os) == DMU_OST_ZFS) {
1900                 nvlist_t *nv;
1901
1902                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1903                 if ((err = nvl_add_zplprop(os, nv, ZFS_PROP_VERSION)) == 0 &&
1904                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_NORMALIZE)) == 0 &&
1905                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_UTF8ONLY)) == 0 &&
1906                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_CASE)) == 0)
1907                         err = put_nvlist(zc, nv);
1908                 nvlist_free(nv);
1909         } else {
1910                 err = ENOENT;
1911         }
1912         dmu_objset_rele(os, FTAG);
1913         return (err);
1914 }
1915
1916 static boolean_t
1917 dataset_name_hidden(const char *name)
1918 {
1919         /*
1920          * Skip over datasets that are not visible in this zone,
1921          * internal datasets (which have a $ in their name), and
1922          * temporary datasets (which have a % in their name).
1923          */
1924         if (strchr(name, '$') != NULL)
1925                 return (B_TRUE);
1926         if (strchr(name, '%') != NULL)
1927                 return (B_TRUE);
1928         if (!INGLOBALZONE(curproc) && !zone_dataset_visible(name, NULL))
1929                 return (B_TRUE);
1930         return (B_FALSE);
1931 }
1932
1933 /*
1934  * inputs:
1935  * zc_name              name of filesystem
1936  * zc_cookie            zap cursor
1937  * zc_nvlist_dst_size   size of buffer for property nvlist
1938  *
1939  * outputs:
1940  * zc_name              name of next filesystem
1941  * zc_cookie            zap cursor
1942  * zc_objset_stats      stats
1943  * zc_nvlist_dst        property nvlist
1944  * zc_nvlist_dst_size   size of property nvlist
1945  */
1946 static int
1947 zfs_ioc_dataset_list_next(zfs_cmd_t *zc)
1948 {
1949         objset_t *os;
1950         int error;
1951         char *p;
1952         size_t orig_len = strlen(zc->zc_name);
1953
1954 top:
1955         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os))) {
1956                 if (error == ENOENT)
1957                         error = ESRCH;
1958                 return (error);
1959         }
1960
1961         p = strrchr(zc->zc_name, '/');
1962         if (p == NULL || p[1] != '\0')
1963                 (void) strlcat(zc->zc_name, "/", sizeof (zc->zc_name));
1964         p = zc->zc_name + strlen(zc->zc_name);
1965
1966         /*
1967          * Pre-fetch the datasets.  dmu_objset_prefetch() always returns 0
1968          * but is not declared void because its called by dmu_objset_find().
1969          */
1970         if (zc->zc_cookie == 0) {
1971                 uint64_t cookie = 0;
1972                 int len = sizeof (zc->zc_name) - (p - zc->zc_name);
1973
1974                 while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0)
1975                         (void) dmu_objset_prefetch(p, NULL);
1976         }
1977
1978         do {
1979                 error = dmu_dir_list_next(os,
1980                     sizeof (zc->zc_name) - (p - zc->zc_name), p,
1981                     NULL, &zc->zc_cookie);
1982                 if (error == ENOENT)
1983                         error = ESRCH;
1984         } while (error == 0 && dataset_name_hidden(zc->zc_name) &&
1985             !(zc->zc_iflags & FKIOCTL));
1986         dmu_objset_rele(os, FTAG);
1987
1988         /*
1989          * If it's an internal dataset (ie. with a '$' in its name),
1990          * don't try to get stats for it, otherwise we'll return ENOENT.
1991          */
1992         if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
1993                 error = zfs_ioc_objset_stats(zc); /* fill in the stats */
1994                 if (error == ENOENT) {
1995                         /* We lost a race with destroy, get the next one. */
1996                         zc->zc_name[orig_len] = '\0';
1997                         goto top;
1998                 }
1999         }
2000         return (error);
2001 }
2002
2003 /*
2004  * inputs:
2005  * zc_name              name of filesystem
2006  * zc_cookie            zap cursor
2007  * zc_nvlist_dst_size   size of buffer for property nvlist
2008  *
2009  * outputs:
2010  * zc_name              name of next snapshot
2011  * zc_objset_stats      stats
2012  * zc_nvlist_dst        property nvlist
2013  * zc_nvlist_dst_size   size of property nvlist
2014  */
2015 static int
2016 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2017 {
2018         objset_t *os;
2019         int error;
2020
2021 top:
2022         if (zc->zc_cookie == 0)
2023                 (void) dmu_objset_find(zc->zc_name, dmu_objset_prefetch,
2024                     NULL, DS_FIND_SNAPSHOTS);
2025
2026         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2027         if (error)
2028                 return (error == ENOENT ? ESRCH : error);
2029
2030         /*
2031          * A dataset name of maximum length cannot have any snapshots,
2032          * so exit immediately.
2033          */
2034         if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >= MAXNAMELEN) {
2035                 dmu_objset_rele(os, FTAG);
2036                 return (ESRCH);
2037         }
2038
2039         error = dmu_snapshot_list_next(os,
2040             sizeof (zc->zc_name) - strlen(zc->zc_name),
2041             zc->zc_name + strlen(zc->zc_name), &zc->zc_obj, &zc->zc_cookie,
2042             NULL);
2043
2044         if (error == 0) {
2045                 dsl_dataset_t *ds;
2046                 dsl_pool_t *dp = os->os_dsl_dataset->ds_dir->dd_pool;
2047
2048                 /*
2049                  * Since we probably don't have a hold on this snapshot,
2050                  * it's possible that the objsetid could have been destroyed
2051                  * and reused for a new objset. It's OK if this happens during
2052                  * a zfs send operation, since the new createtxg will be
2053                  * beyond the range we're interested in.
2054                  */
2055                 rw_enter(&dp->dp_config_rwlock, RW_READER);
2056                 error = dsl_dataset_hold_obj(dp, zc->zc_obj, FTAG, &ds);
2057                 rw_exit(&dp->dp_config_rwlock);
2058                 if (error) {
2059                         if (error == ENOENT) {
2060                                 /* Racing with destroy, get the next one. */
2061                                 *strchr(zc->zc_name, '@') = '\0';
2062                                 dmu_objset_rele(os, FTAG);
2063                                 goto top;
2064                         }
2065                 } else {
2066                         objset_t *ossnap;
2067
2068                         error = dmu_objset_from_ds(ds, &ossnap);
2069                         if (error == 0)
2070                                 error = zfs_ioc_objset_stats_impl(zc, ossnap);
2071                         dsl_dataset_rele(ds, FTAG);
2072                 }
2073         } else if (error == ENOENT) {
2074                 error = ESRCH;
2075         }
2076
2077         dmu_objset_rele(os, FTAG);
2078         /* if we failed, undo the @ that we tacked on to zc_name */
2079         if (error)
2080                 *strchr(zc->zc_name, '@') = '\0';
2081         return (error);
2082 }
2083
2084 static int
2085 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2086 {
2087 #ifdef HAVE_ZPL
2088         const char *propname = nvpair_name(pair);
2089         uint64_t *valary;
2090         unsigned int vallen;
2091         const char *domain;
2092         char *dash;
2093         zfs_userquota_prop_t type;
2094         uint64_t rid;
2095         uint64_t quota;
2096         zfsvfs_t *zfsvfs;
2097         int err;
2098
2099         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2100                 nvlist_t *attrs;
2101                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2102                 if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2103                     &pair) != 0)
2104                         return (EINVAL);
2105         }
2106
2107         /*
2108          * A correctly constructed propname is encoded as
2109          * userquota@<rid>-<domain>.
2110          */
2111         if ((dash = strchr(propname, '-')) == NULL ||
2112             nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2113             vallen != 3)
2114                 return (EINVAL);
2115
2116         domain = dash + 1;
2117         type = valary[0];
2118         rid = valary[1];
2119         quota = valary[2];
2120
2121         err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2122         if (err == 0) {
2123                 err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2124                 zfsvfs_rele(zfsvfs, FTAG);
2125         }
2126
2127         return (err);
2128 #else
2129         return ENOTSUP;
2130 #endif
2131 }
2132
2133 /*
2134  * If the named property is one that has a special function to set its value,
2135  * return 0 on success and a positive error code on failure; otherwise if it is
2136  * not one of the special properties handled by this function, return -1.
2137  *
2138  * XXX: It would be better for callers of the property interface if we handled
2139  * these special cases in dsl_prop.c (in the dsl layer).
2140  */
2141 static int
2142 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2143     nvpair_t *pair)
2144 {
2145         const char *propname = nvpair_name(pair);
2146         zfs_prop_t prop = zfs_name_to_prop(propname);
2147         uint64_t intval;
2148         int err;
2149
2150         if (prop == ZPROP_INVAL) {
2151                 if (zfs_prop_userquota(propname))
2152                         return (zfs_prop_set_userquota(dsname, pair));
2153                 return (-1);
2154         }
2155
2156         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2157                 nvlist_t *attrs;
2158                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2159                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2160                     &pair) == 0);
2161         }
2162
2163         if (zfs_prop_get_type(prop) == PROP_TYPE_STRING)
2164                 return (-1);
2165
2166         VERIFY(0 == nvpair_value_uint64(pair, &intval));
2167
2168         switch (prop) {
2169         case ZFS_PROP_QUOTA:
2170                 err = dsl_dir_set_quota(dsname, source, intval);
2171                 break;
2172         case ZFS_PROP_REFQUOTA:
2173                 err = dsl_dataset_set_quota(dsname, source, intval);
2174                 break;
2175         case ZFS_PROP_RESERVATION:
2176                 err = dsl_dir_set_reservation(dsname, source, intval);
2177                 break;
2178         case ZFS_PROP_REFRESERVATION:
2179                 err = dsl_dataset_set_reservation(dsname, source, intval);
2180                 break;
2181         case ZFS_PROP_VOLSIZE:
2182                 err = zvol_set_volsize(dsname, ddi_driver_major(zfs_dip),
2183                     intval);
2184                 break;
2185         case ZFS_PROP_VERSION:
2186         {
2187                 zfsvfs_t *zfsvfs;
2188
2189                 if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2190                         break;
2191
2192 #ifdef HAVE_ZPL
2193                 err = zfs_set_version(zfsvfs, intval);
2194 #endif
2195                 zfsvfs_rele(zfsvfs, FTAG);
2196
2197                 if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2198                         zfs_cmd_t *zc;
2199
2200                         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2201                         (void) strcpy(zc->zc_name, dsname);
2202                         (void) zfs_ioc_userspace_upgrade(zc);
2203                         kmem_free(zc, sizeof (zfs_cmd_t));
2204                 }
2205                 break;
2206         }
2207
2208         default:
2209                 err = -1;
2210         }
2211
2212         return (err);
2213 }
2214
2215 /*
2216  * This function is best effort. If it fails to set any of the given properties,
2217  * it continues to set as many as it can and returns the first error
2218  * encountered. If the caller provides a non-NULL errlist, it also gives the
2219  * complete list of names of all the properties it failed to set along with the
2220  * corresponding error numbers. The caller is responsible for freeing the
2221  * returned errlist.
2222  *
2223  * If every property is set successfully, zero is returned and the list pointed
2224  * at by errlist is NULL.
2225  */
2226 int
2227 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
2228     nvlist_t **errlist)
2229 {
2230         nvpair_t *pair;
2231         nvpair_t *propval;
2232         int rv = 0;
2233         uint64_t intval;
2234         char *strval;
2235         nvlist_t *genericnvl;
2236         nvlist_t *errors;
2237         nvlist_t *retrynvl;
2238
2239         VERIFY(nvlist_alloc(&genericnvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2240         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2241         VERIFY(nvlist_alloc(&retrynvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2242
2243 retry:
2244         pair = NULL;
2245         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2246                 const char *propname = nvpair_name(pair);
2247                 zfs_prop_t prop = zfs_name_to_prop(propname);
2248                 int err = 0;
2249
2250                 /* decode the property value */
2251                 propval = pair;
2252                 if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2253                         nvlist_t *attrs;
2254                         VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2255                         if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2256                             &propval) != 0)
2257                                 err = EINVAL;
2258                 }
2259
2260                 /* Validate value type */
2261                 if (err == 0 && prop == ZPROP_INVAL) {
2262                         if (zfs_prop_user(propname)) {
2263                                 if (nvpair_type(propval) != DATA_TYPE_STRING)
2264                                         err = EINVAL;
2265                         } else if (zfs_prop_userquota(propname)) {
2266                                 if (nvpair_type(propval) !=
2267                                     DATA_TYPE_UINT64_ARRAY)
2268                                         err = EINVAL;
2269                         }
2270                 } else if (err == 0) {
2271                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2272                                 if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
2273                                         err = EINVAL;
2274                         } else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
2275                                 const char *unused;
2276
2277                                 VERIFY(nvpair_value_uint64(propval,
2278                                     &intval) == 0);
2279
2280                                 switch (zfs_prop_get_type(prop)) {
2281                                 case PROP_TYPE_NUMBER:
2282                                         break;
2283                                 case PROP_TYPE_STRING:
2284                                         err = EINVAL;
2285                                         break;
2286                                 case PROP_TYPE_INDEX:
2287                                         if (zfs_prop_index_to_string(prop,
2288                                             intval, &unused) != 0)
2289                                                 err = EINVAL;
2290                                         break;
2291                                 default:
2292                                         cmn_err(CE_PANIC,
2293                                             "unknown property type");
2294                                 }
2295                         } else {
2296                                 err = EINVAL;
2297                         }
2298                 }
2299
2300                 /* Validate permissions */
2301                 if (err == 0)
2302                         err = zfs_check_settable(dsname, pair, CRED());
2303
2304                 if (err == 0) {
2305                         err = zfs_prop_set_special(dsname, source, pair);
2306                         if (err == -1) {
2307                                 /*
2308                                  * For better performance we build up a list of
2309                                  * properties to set in a single transaction.
2310                                  */
2311                                 err = nvlist_add_nvpair(genericnvl, pair);
2312                         } else if (err != 0 && nvl != retrynvl) {
2313                                 /*
2314                                  * This may be a spurious error caused by
2315                                  * receiving quota and reservation out of order.
2316                                  * Try again in a second pass.
2317                                  */
2318                                 err = nvlist_add_nvpair(retrynvl, pair);
2319                         }
2320                 }
2321
2322                 if (err != 0)
2323                         VERIFY(nvlist_add_int32(errors, propname, err) == 0);
2324         }
2325
2326         if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
2327                 nvl = retrynvl;
2328                 goto retry;
2329         }
2330
2331         if (!nvlist_empty(genericnvl) &&
2332             dsl_props_set(dsname, source, genericnvl) != 0) {
2333                 /*
2334                  * If this fails, we still want to set as many properties as we
2335                  * can, so try setting them individually.
2336                  */
2337                 pair = NULL;
2338                 while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
2339                         const char *propname = nvpair_name(pair);
2340                         int err = 0;
2341
2342                         propval = pair;
2343                         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2344                                 nvlist_t *attrs;
2345                                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2346                                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2347                                     &propval) == 0);
2348                         }
2349
2350                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2351                                 VERIFY(nvpair_value_string(propval,
2352                                     &strval) == 0);
2353                                 err = dsl_prop_set(dsname, propname, source, 1,
2354                                     strlen(strval) + 1, strval);
2355                         } else {
2356                                 VERIFY(nvpair_value_uint64(propval,
2357                                     &intval) == 0);
2358                                 err = dsl_prop_set(dsname, propname, source, 8,
2359                                     1, &intval);
2360                         }
2361
2362                         if (err != 0) {
2363                                 VERIFY(nvlist_add_int32(errors, propname,
2364                                     err) == 0);
2365                         }
2366                 }
2367         }
2368         nvlist_free(genericnvl);
2369         nvlist_free(retrynvl);
2370
2371         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
2372                 nvlist_free(errors);
2373                 errors = NULL;
2374         } else {
2375                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
2376         }
2377
2378         if (errlist == NULL)
2379                 nvlist_free(errors);
2380         else
2381                 *errlist = errors;
2382
2383         return (rv);
2384 }
2385
2386 /*
2387  * Check that all the properties are valid user properties.
2388  */
2389 static int
2390 zfs_check_userprops(char *fsname, nvlist_t *nvl)
2391 {
2392         nvpair_t *pair = NULL;
2393         int error = 0;
2394
2395         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2396                 const char *propname = nvpair_name(pair);
2397                 char *valstr;
2398
2399                 if (!zfs_prop_user(propname) ||
2400                     nvpair_type(pair) != DATA_TYPE_STRING)
2401                         return (EINVAL);
2402
2403                 if ((error = zfs_secpolicy_write_perms(fsname,
2404                     ZFS_DELEG_PERM_USERPROP, CRED())))
2405                         return (error);
2406
2407                 if (strlen(propname) >= ZAP_MAXNAMELEN)
2408                         return (ENAMETOOLONG);
2409
2410                 VERIFY(nvpair_value_string(pair, &valstr) == 0);
2411                 if (strlen(valstr) >= ZAP_MAXVALUELEN)
2412                         return (E2BIG);
2413         }
2414         return (0);
2415 }
2416
2417 static void
2418 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
2419 {
2420         nvpair_t *pair;
2421
2422         VERIFY(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2423
2424         pair = NULL;
2425         while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
2426                 if (nvlist_exists(skipped, nvpair_name(pair)))
2427                         continue;
2428
2429                 VERIFY(nvlist_add_nvpair(*newprops, pair) == 0);
2430         }
2431 }
2432
2433 static int
2434 clear_received_props(objset_t *os, const char *fs, nvlist_t *props,
2435     nvlist_t *skipped)
2436 {
2437         int err = 0;
2438         nvlist_t *cleared_props = NULL;
2439         props_skip(props, skipped, &cleared_props);
2440         if (!nvlist_empty(cleared_props)) {
2441                 /*
2442                  * Acts on local properties until the dataset has received
2443                  * properties at least once on or after SPA_VERSION_RECVD_PROPS.
2444                  */
2445                 zprop_source_t flags = (ZPROP_SRC_NONE |
2446                     (dsl_prop_get_hasrecvd(os) ? ZPROP_SRC_RECEIVED : 0));
2447                 err = zfs_set_prop_nvlist(fs, flags, cleared_props, NULL);
2448         }
2449         nvlist_free(cleared_props);
2450         return (err);
2451 }
2452
2453 /*
2454  * inputs:
2455  * zc_name              name of filesystem
2456  * zc_value             name of property to set
2457  * zc_nvlist_src{_size} nvlist of properties to apply
2458  * zc_cookie            received properties flag
2459  *
2460  * outputs:
2461  * zc_nvlist_dst{_size} error for each unapplied received property
2462  */
2463 static int
2464 zfs_ioc_set_prop(zfs_cmd_t *zc)
2465 {
2466         nvlist_t *nvl;
2467         boolean_t received = zc->zc_cookie;
2468         zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
2469             ZPROP_SRC_LOCAL);
2470         nvlist_t *errors = NULL;
2471         int error;
2472
2473         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2474             zc->zc_iflags, &nvl)) != 0)
2475                 return (error);
2476
2477         if (received) {
2478                 nvlist_t *origprops;
2479                 objset_t *os;
2480
2481                 if (dmu_objset_hold(zc->zc_name, FTAG, &os) == 0) {
2482                         if (dsl_prop_get_received(os, &origprops) == 0) {
2483                                 (void) clear_received_props(os,
2484                                     zc->zc_name, origprops, nvl);
2485                                 nvlist_free(origprops);
2486                         }
2487
2488                         dsl_prop_set_hasrecvd(os);
2489                         dmu_objset_rele(os, FTAG);
2490                 }
2491         }
2492
2493         error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, &errors);
2494
2495         if (zc->zc_nvlist_dst != 0 && errors != NULL) {
2496                 (void) put_nvlist(zc, errors);
2497         }
2498
2499         nvlist_free(errors);
2500         nvlist_free(nvl);
2501         return (error);
2502 }
2503
2504 /*
2505  * inputs:
2506  * zc_name              name of filesystem
2507  * zc_value             name of property to inherit
2508  * zc_cookie            revert to received value if TRUE
2509  *
2510  * outputs:             none
2511  */
2512 static int
2513 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
2514 {
2515         const char *propname = zc->zc_value;
2516         zfs_prop_t prop = zfs_name_to_prop(propname);
2517         boolean_t received = zc->zc_cookie;
2518         zprop_source_t source = (received
2519             ? ZPROP_SRC_NONE            /* revert to received value, if any */
2520             : ZPROP_SRC_INHERITED);     /* explicitly inherit */
2521
2522         if (received) {
2523                 nvlist_t *dummy;
2524                 nvpair_t *pair;
2525                 zprop_type_t type;
2526                 int err;
2527
2528                 /*
2529                  * zfs_prop_set_special() expects properties in the form of an
2530                  * nvpair with type info.
2531                  */
2532                 if (prop == ZPROP_INVAL) {
2533                         if (!zfs_prop_user(propname))
2534                                 return (EINVAL);
2535
2536                         type = PROP_TYPE_STRING;
2537                 } else if (prop == ZFS_PROP_VOLSIZE ||
2538                     prop == ZFS_PROP_VERSION) {
2539                         return (EINVAL);
2540                 } else {
2541                         type = zfs_prop_get_type(prop);
2542                 }
2543
2544                 VERIFY(nvlist_alloc(&dummy, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2545
2546                 switch (type) {
2547                 case PROP_TYPE_STRING:
2548                         VERIFY(0 == nvlist_add_string(dummy, propname, ""));
2549                         break;
2550                 case PROP_TYPE_NUMBER:
2551                 case PROP_TYPE_INDEX:
2552                         VERIFY(0 == nvlist_add_uint64(dummy, propname, 0));
2553                         break;
2554                 default:
2555                         nvlist_free(dummy);
2556                         return (EINVAL);
2557                 }
2558
2559                 pair = nvlist_next_nvpair(dummy, NULL);
2560                 err = zfs_prop_set_special(zc->zc_name, source, pair);
2561                 nvlist_free(dummy);
2562                 if (err != -1)
2563                         return (err); /* special property already handled */
2564         } else {
2565                 /*
2566                  * Only check this in the non-received case. We want to allow
2567                  * 'inherit -S' to revert non-inheritable properties like quota
2568                  * and reservation to the received or default values even though
2569                  * they are not considered inheritable.
2570                  */
2571                 if (prop != ZPROP_INVAL && !zfs_prop_inheritable(prop))
2572                         return (EINVAL);
2573         }
2574
2575         /* the property name has been validated by zfs_secpolicy_inherit() */
2576         return (dsl_prop_set(zc->zc_name, zc->zc_value, source, 0, 0, NULL));
2577 }
2578
2579 static int
2580 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
2581 {
2582         nvlist_t *props;
2583         spa_t *spa;
2584         int error;
2585         nvpair_t *pair;
2586
2587         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2588             zc->zc_iflags, &props)))
2589                 return (error);
2590
2591         /*
2592          * If the only property is the configfile, then just do a spa_lookup()
2593          * to handle the faulted case.
2594          */
2595         pair = nvlist_next_nvpair(props, NULL);
2596         if (pair != NULL && strcmp(nvpair_name(pair),
2597             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
2598             nvlist_next_nvpair(props, pair) == NULL) {
2599                 mutex_enter(&spa_namespace_lock);
2600                 if ((spa = spa_lookup(zc->zc_name)) != NULL) {
2601                         spa_configfile_set(spa, props, B_FALSE);
2602                         spa_config_sync(spa, B_FALSE, B_TRUE);
2603                 }
2604                 mutex_exit(&spa_namespace_lock);
2605                 if (spa != NULL) {
2606                         nvlist_free(props);
2607                         return (0);
2608                 }
2609         }
2610
2611         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2612                 nvlist_free(props);
2613                 return (error);
2614         }
2615
2616         error = spa_prop_set(spa, props);
2617
2618         nvlist_free(props);
2619         spa_close(spa, FTAG);
2620
2621         return (error);
2622 }
2623
2624 static int
2625 zfs_ioc_pool_get_props(zfs_cmd_t *zc)
2626 {
2627         spa_t *spa;
2628         int error;
2629         nvlist_t *nvp = NULL;
2630
2631         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2632                 /*
2633                  * If the pool is faulted, there may be properties we can still
2634                  * get (such as altroot and cachefile), so attempt to get them
2635                  * anyway.
2636                  */
2637                 mutex_enter(&spa_namespace_lock);
2638                 if ((spa = spa_lookup(zc->zc_name)) != NULL)
2639                         error = spa_prop_get(spa, &nvp);
2640                 mutex_exit(&spa_namespace_lock);
2641         } else {
2642                 error = spa_prop_get(spa, &nvp);
2643                 spa_close(spa, FTAG);
2644         }
2645
2646         if (error == 0 && zc->zc_nvlist_dst != 0)
2647                 error = put_nvlist(zc, nvp);
2648         else
2649                 error = EFAULT;
2650
2651         nvlist_free(nvp);
2652         return (error);
2653 }
2654
2655 /*
2656  * inputs:
2657  * zc_name              name of filesystem
2658  * zc_nvlist_src{_size} nvlist of delegated permissions
2659  * zc_perm_action       allow/unallow flag
2660  *
2661  * outputs:             none
2662  */
2663 static int
2664 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
2665 {
2666         int error;
2667         nvlist_t *fsaclnv = NULL;
2668
2669         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2670             zc->zc_iflags, &fsaclnv)) != 0)
2671                 return (error);
2672
2673         /*
2674          * Verify nvlist is constructed correctly
2675          */
2676         if ((error = zfs_deleg_verify_nvlist(fsaclnv)) != 0) {
2677                 nvlist_free(fsaclnv);
2678                 return (EINVAL);
2679         }
2680
2681         /*
2682          * If we don't have PRIV_SYS_MOUNT, then validate
2683          * that user is allowed to hand out each permission in
2684          * the nvlist(s)
2685          */
2686
2687         error = secpolicy_zfs(CRED());
2688         if (error) {
2689                 if (zc->zc_perm_action == B_FALSE) {
2690                         error = dsl_deleg_can_allow(zc->zc_name,
2691                             fsaclnv, CRED());
2692                 } else {
2693                         error = dsl_deleg_can_unallow(zc->zc_name,
2694                             fsaclnv, CRED());
2695                 }
2696         }
2697
2698         if (error == 0)
2699                 error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
2700
2701         nvlist_free(fsaclnv);
2702         return (error);
2703 }
2704
2705 /*
2706  * inputs:
2707  * zc_name              name of filesystem
2708  *
2709  * outputs:
2710  * zc_nvlist_src{_size} nvlist of delegated permissions
2711  */
2712 static int
2713 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
2714 {
2715         nvlist_t *nvp;
2716         int error;
2717
2718         if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
2719                 error = put_nvlist(zc, nvp);
2720                 nvlist_free(nvp);
2721         }
2722
2723         return (error);
2724 }
2725
2726 #ifdef HAVE_ZPL
2727 /*
2728  * Search the vfs list for a specified resource.  Returns a pointer to it
2729  * or NULL if no suitable entry is found. The caller of this routine
2730  * is responsible for releasing the returned vfs pointer.
2731  */
2732 static vfs_t *
2733 zfs_get_vfs(const char *resource)
2734 {
2735         struct vfs *vfsp;
2736         struct vfs *vfs_found = NULL;
2737
2738         vfs_list_read_lock();
2739         vfsp = rootvfs;
2740         do {
2741                 if (strcmp(refstr_value(vfsp->vfs_resource), resource) == 0) {
2742                         VFS_HOLD(vfsp);
2743                         vfs_found = vfsp;
2744                         break;
2745                 }
2746                 vfsp = vfsp->vfs_next;
2747         } while (vfsp != rootvfs);
2748         vfs_list_unlock();
2749         return (vfs_found);
2750 }
2751 #endif /* HAVE_ZPL */
2752
2753 /* ARGSUSED */
2754 static void
2755 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
2756 {
2757         zfs_creat_t *zct = arg;
2758
2759         zfs_create_fs(os, cr, zct->zct_zplprops, tx);
2760 }
2761
2762 #define ZFS_PROP_UNDEFINED      ((uint64_t)-1)
2763
2764 /*
2765  * inputs:
2766  * createprops          list of properties requested by creator
2767  * default_zplver       zpl version to use if unspecified in createprops
2768  * fuids_ok             fuids allowed in this version of the spa?
2769  * os                   parent objset pointer (NULL if root fs)
2770  *
2771  * outputs:
2772  * zplprops     values for the zplprops we attach to the master node object
2773  * is_ci        true if requested file system will be purely case-insensitive
2774  *
2775  * Determine the settings for utf8only, normalization and
2776  * casesensitivity.  Specific values may have been requested by the
2777  * creator and/or we can inherit values from the parent dataset.  If
2778  * the file system is of too early a vintage, a creator can not
2779  * request settings for these properties, even if the requested
2780  * setting is the default value.  We don't actually want to create dsl
2781  * properties for these, so remove them from the source nvlist after
2782  * processing.
2783  */
2784 static int
2785 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
2786     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
2787     nvlist_t *zplprops, boolean_t *is_ci)
2788 {
2789         uint64_t sense = ZFS_PROP_UNDEFINED;
2790         uint64_t norm = ZFS_PROP_UNDEFINED;
2791         uint64_t u8 = ZFS_PROP_UNDEFINED;
2792
2793         ASSERT(zplprops != NULL);
2794
2795         /*
2796          * Pull out creator prop choices, if any.
2797          */
2798         if (createprops) {
2799                 (void) nvlist_lookup_uint64(createprops,
2800                     zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
2801                 (void) nvlist_lookup_uint64(createprops,
2802                     zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
2803                 (void) nvlist_remove_all(createprops,
2804                     zfs_prop_to_name(ZFS_PROP_NORMALIZE));
2805                 (void) nvlist_lookup_uint64(createprops,
2806                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
2807                 (void) nvlist_remove_all(createprops,
2808                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
2809                 (void) nvlist_lookup_uint64(createprops,
2810                     zfs_prop_to_name(ZFS_PROP_CASE), &sense);
2811                 (void) nvlist_remove_all(createprops,
2812                     zfs_prop_to_name(ZFS_PROP_CASE));
2813         }
2814
2815         /*
2816          * If the zpl version requested is whacky or the file system
2817          * or pool is version is too "young" to support normalization
2818          * and the creator tried to set a value for one of the props,
2819          * error out.
2820          */
2821         if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
2822             (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
2823             (zplver >= ZPL_VERSION_SA && !sa_ok) ||
2824             (zplver < ZPL_VERSION_NORMALIZATION &&
2825             (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
2826             sense != ZFS_PROP_UNDEFINED)))
2827                 return (ENOTSUP);
2828
2829         /*
2830          * Put the version in the zplprops
2831          */
2832         VERIFY(nvlist_add_uint64(zplprops,
2833             zfs_prop_to_name(ZFS_PROP_VERSION), zplver) == 0);
2834
2835         if (norm == ZFS_PROP_UNDEFINED)
2836                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm) == 0);
2837         VERIFY(nvlist_add_uint64(zplprops,
2838             zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm) == 0);
2839
2840         /*
2841          * If we're normalizing, names must always be valid UTF-8 strings.
2842          */
2843         if (norm)
2844                 u8 = 1;
2845         if (u8 == ZFS_PROP_UNDEFINED)
2846                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8) == 0);
2847         VERIFY(nvlist_add_uint64(zplprops,
2848             zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8) == 0);
2849
2850         if (sense == ZFS_PROP_UNDEFINED)
2851                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_CASE, &sense) == 0);
2852         VERIFY(nvlist_add_uint64(zplprops,
2853             zfs_prop_to_name(ZFS_PROP_CASE), sense) == 0);
2854
2855         if (is_ci)
2856                 *is_ci = (sense == ZFS_CASE_INSENSITIVE);
2857
2858         return (0);
2859 }
2860
2861 static int
2862 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
2863     nvlist_t *zplprops, boolean_t *is_ci)
2864 {
2865         boolean_t fuids_ok, sa_ok;
2866         uint64_t zplver = ZPL_VERSION;
2867         objset_t *os = NULL;
2868         char parentname[MAXNAMELEN];
2869         char *cp;
2870         spa_t *spa;
2871         uint64_t spa_vers;
2872         int error;
2873
2874         (void) strlcpy(parentname, dataset, sizeof (parentname));
2875         cp = strrchr(parentname, '/');
2876         ASSERT(cp != NULL);
2877         cp[0] = '\0';
2878
2879         if ((error = spa_open(dataset, &spa, FTAG)) != 0)
2880                 return (error);
2881
2882         spa_vers = spa_version(spa);
2883         spa_close(spa, FTAG);
2884
2885         zplver = zfs_zpl_version_map(spa_vers);
2886         fuids_ok = (zplver >= ZPL_VERSION_FUID);
2887         sa_ok = (zplver >= ZPL_VERSION_SA);
2888
2889         /*
2890          * Open parent object set so we can inherit zplprop values.
2891          */
2892         if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
2893                 return (error);
2894
2895         error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
2896             zplprops, is_ci);
2897         dmu_objset_rele(os, FTAG);
2898         return (error);
2899 }
2900
2901 static int
2902 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
2903     nvlist_t *zplprops, boolean_t *is_ci)
2904 {
2905         boolean_t fuids_ok;
2906         boolean_t sa_ok;
2907         uint64_t zplver = ZPL_VERSION;
2908         int error;
2909
2910         zplver = zfs_zpl_version_map(spa_vers);
2911         fuids_ok = (zplver >= ZPL_VERSION_FUID);
2912         sa_ok = (zplver >= ZPL_VERSION_SA);
2913
2914         error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
2915             createprops, zplprops, is_ci);
2916         return (error);
2917 }
2918
2919 /*
2920  * inputs:
2921  * zc_objset_type       type of objset to create (fs vs zvol)
2922  * zc_name              name of new objset
2923  * zc_value             name of snapshot to clone from (may be empty)
2924  * zc_nvlist_src{_size} nvlist of properties to apply
2925  *
2926  * outputs: none
2927  */
2928 static int
2929 zfs_ioc_create(zfs_cmd_t *zc)
2930 {
2931         objset_t *clone;
2932         int error = 0;
2933         zfs_creat_t zct;
2934         nvlist_t *nvprops = NULL;
2935         void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
2936         dmu_objset_type_t type = zc->zc_objset_type;
2937
2938         switch (type) {
2939
2940         case DMU_OST_ZFS:
2941                 cbfunc = zfs_create_cb;
2942                 break;
2943
2944         case DMU_OST_ZVOL:
2945                 cbfunc = zvol_create_cb;
2946                 break;
2947
2948         default:
2949                 cbfunc = NULL;
2950                 break;
2951         }
2952         if (strchr(zc->zc_name, '@') ||
2953             strchr(zc->zc_name, '%'))
2954                 return (EINVAL);
2955
2956         if (zc->zc_nvlist_src != 0 &&
2957             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2958             zc->zc_iflags, &nvprops)) != 0)
2959                 return (error);
2960
2961         zct.zct_zplprops = NULL;
2962         zct.zct_props = nvprops;
2963
2964         if (zc->zc_value[0] != '\0') {
2965                 /*
2966                  * We're creating a clone of an existing snapshot.
2967                  */
2968                 zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
2969                 if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0) {
2970                         nvlist_free(nvprops);
2971                         return (EINVAL);
2972                 }
2973
2974                 error = dmu_objset_hold(zc->zc_value, FTAG, &clone);
2975                 if (error) {
2976                         nvlist_free(nvprops);
2977                         return (error);
2978                 }
2979
2980                 error = dmu_objset_clone(zc->zc_name, dmu_objset_ds(clone), 0);
2981                 dmu_objset_rele(clone, FTAG);
2982                 if (error) {
2983                         nvlist_free(nvprops);
2984                         return (error);
2985                 }
2986         } else {
2987                 boolean_t is_insensitive = B_FALSE;
2988
2989                 if (cbfunc == NULL) {
2990                         nvlist_free(nvprops);
2991                         return (EINVAL);
2992                 }
2993
2994                 if (type == DMU_OST_ZVOL) {
2995                         uint64_t volsize, volblocksize;
2996
2997                         if (nvprops == NULL ||
2998                             nvlist_lookup_uint64(nvprops,
2999                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
3000                             &volsize) != 0) {
3001                                 nvlist_free(nvprops);
3002                                 return (EINVAL);
3003                         }
3004
3005                         if ((error = nvlist_lookup_uint64(nvprops,
3006                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3007                             &volblocksize)) != 0 && error != ENOENT) {
3008                                 nvlist_free(nvprops);
3009                                 return (EINVAL);
3010                         }
3011
3012                         if (error != 0)
3013                                 volblocksize = zfs_prop_default_numeric(
3014                                     ZFS_PROP_VOLBLOCKSIZE);
3015
3016                         if ((error = zvol_check_volblocksize(
3017                             volblocksize)) != 0 ||
3018                             (error = zvol_check_volsize(volsize,
3019                             volblocksize)) != 0) {
3020                                 nvlist_free(nvprops);
3021                                 return (error);
3022                         }
3023                 } else if (type == DMU_OST_ZFS) {
3024                         int error;
3025
3026                         /*
3027                          * We have to have normalization and
3028                          * case-folding flags correct when we do the
3029                          * file system creation, so go figure them out
3030                          * now.
3031                          */
3032                         VERIFY(nvlist_alloc(&zct.zct_zplprops,
3033                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
3034                         error = zfs_fill_zplprops(zc->zc_name, nvprops,
3035                             zct.zct_zplprops, &is_insensitive);
3036                         if (error != 0) {
3037                                 nvlist_free(nvprops);
3038                                 nvlist_free(zct.zct_zplprops);
3039                                 return (error);
3040                         }
3041                 }
3042                 error = dmu_objset_create(zc->zc_name, type,
3043                     is_insensitive ? DS_FLAG_CI_DATASET : 0, cbfunc, &zct);
3044                 nvlist_free(zct.zct_zplprops);
3045         }
3046
3047         /*
3048          * It would be nice to do this atomically.
3049          */
3050         if (error == 0) {
3051                 error = zfs_set_prop_nvlist(zc->zc_name, ZPROP_SRC_LOCAL,
3052                     nvprops, NULL);
3053                 if (error != 0)
3054                         (void) dmu_objset_destroy(zc->zc_name, B_FALSE);
3055         }
3056         nvlist_free(nvprops);
3057         return (error);
3058 }
3059
3060 /*
3061  * inputs:
3062  * zc_name      name of filesystem
3063  * zc_value     short name of snapshot
3064  * zc_cookie    recursive flag
3065  * zc_nvlist_src[_size] property list
3066  *
3067  * outputs:
3068  * zc_value     short snapname (i.e. part after the '@')
3069  */
3070 static int
3071 zfs_ioc_snapshot(zfs_cmd_t *zc)
3072 {
3073         nvlist_t *nvprops = NULL;
3074         int error;
3075         boolean_t recursive = zc->zc_cookie;
3076
3077         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
3078                 return (EINVAL);
3079
3080         if (zc->zc_nvlist_src != 0 &&
3081             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3082             zc->zc_iflags, &nvprops)) != 0)
3083                 return (error);
3084
3085         error = zfs_check_userprops(zc->zc_name, nvprops);
3086         if (error)
3087                 goto out;
3088
3089         if (!nvlist_empty(nvprops) &&
3090             zfs_earlier_version(zc->zc_name, SPA_VERSION_SNAP_PROPS)) {
3091                 error = ENOTSUP;
3092                 goto out;
3093         }
3094
3095         error = dmu_objset_snapshot(zc->zc_name, zc->zc_value, NULL,
3096             nvprops, recursive, B_FALSE, -1);
3097
3098 out:
3099         nvlist_free(nvprops);
3100         return (error);
3101 }
3102
3103 int
3104 zfs_unmount_snap(const char *name, void *arg)
3105 {
3106 #ifdef HAVE_ZPL
3107         vfs_t *vfsp = NULL;
3108
3109         if (arg) {
3110                 char *snapname = arg;
3111                 char *fullname = kmem_asprintf("%s@%s", name, snapname);
3112                 vfsp = zfs_get_vfs(fullname);
3113                 strfree(fullname);
3114         } else if (strchr(name, '@')) {
3115                 vfsp = zfs_get_vfs(name);
3116         }
3117
3118         if (vfsp) {
3119                 /*
3120                  * Always force the unmount for snapshots.
3121                  */
3122                 int flag = MS_FORCE;
3123                 int err;
3124
3125                 if ((err = vn_vfswlock(vfsp->vfs_vnodecovered)) != 0) {
3126                         VFS_RELE(vfsp);
3127                         return (err);
3128                 }
3129                 VFS_RELE(vfsp);
3130                 if ((err = dounmount(vfsp, flag, kcred)) != 0)
3131                         return (err);
3132         }
3133 #endif /* HAVE_ZPL */
3134         return (0);
3135 }
3136
3137 /*
3138  * inputs:
3139  * zc_name              name of filesystem
3140  * zc_value             short name of snapshot
3141  * zc_defer_destroy     mark for deferred destroy
3142  *
3143  * outputs:     none
3144  */
3145 static int
3146 zfs_ioc_destroy_snaps(zfs_cmd_t *zc)
3147 {
3148         int err;
3149
3150         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
3151                 return (EINVAL);
3152         err = dmu_objset_find(zc->zc_name,
3153             zfs_unmount_snap, zc->zc_value, DS_FIND_CHILDREN);
3154         if (err)
3155                 return (err);
3156         return (dmu_snapshots_destroy(zc->zc_name, zc->zc_value,
3157             zc->zc_defer_destroy));
3158 }
3159
3160 /*
3161  * inputs:
3162  * zc_name              name of dataset to destroy
3163  * zc_objset_type       type of objset
3164  * zc_defer_destroy     mark for deferred destroy
3165  *
3166  * outputs:             none
3167  */
3168 static int
3169 zfs_ioc_destroy(zfs_cmd_t *zc)
3170 {
3171         int err;
3172         if (strchr(zc->zc_name, '@') && zc->zc_objset_type == DMU_OST_ZFS) {
3173                 err = zfs_unmount_snap(zc->zc_name, NULL);
3174                 if (err)
3175                         return (err);
3176         }
3177
3178         err = dmu_objset_destroy(zc->zc_name, zc->zc_defer_destroy);
3179         if (zc->zc_objset_type == DMU_OST_ZVOL && err == 0)
3180                 (void) zvol_remove_minor(zc->zc_name);
3181         return (err);
3182 }
3183
3184 /*
3185  * inputs:
3186  * zc_name      name of dataset to rollback (to most recent snapshot)
3187  *
3188  * outputs:     none
3189  */
3190 static int
3191 zfs_ioc_rollback(zfs_cmd_t *zc)
3192 {
3193 #ifdef HAVE_ZPL
3194         dsl_dataset_t *ds, *clone;
3195         int error;
3196         zfsvfs_t *zfsvfs;
3197         char *clone_name;
3198
3199         error = dsl_dataset_hold(zc->zc_name, FTAG, &ds);
3200         if (error)
3201                 return (error);
3202
3203         /* must not be a snapshot */
3204         if (dsl_dataset_is_snapshot(ds)) {
3205                 dsl_dataset_rele(ds, FTAG);
3206                 return (EINVAL);
3207         }
3208
3209         /* must have a most recent snapshot */
3210         if (ds->ds_phys->ds_prev_snap_txg < TXG_INITIAL) {
3211                 dsl_dataset_rele(ds, FTAG);
3212                 return (EINVAL);
3213         }
3214
3215         /*
3216          * Create clone of most recent snapshot.
3217          */
3218         clone_name = kmem_asprintf("%s/%%rollback", zc->zc_name);
3219         error = dmu_objset_clone(clone_name, ds->ds_prev, DS_FLAG_INCONSISTENT);
3220         if (error)
3221                 goto out;
3222
3223         error = dsl_dataset_own(clone_name, B_TRUE, FTAG, &clone);
3224         if (error)
3225                 goto out;
3226
3227         /*
3228          * Do clone swap.
3229          */
3230         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
3231                 error = zfs_suspend_fs(zfsvfs);
3232                 if (error == 0) {
3233                         int resume_err;
3234
3235                         if (dsl_dataset_tryown(ds, B_FALSE, FTAG)) {
3236                                 error = dsl_dataset_clone_swap(clone, ds,
3237                                     B_TRUE);
3238                                 dsl_dataset_disown(ds, FTAG);
3239                                 ds = NULL;
3240                         } else {
3241                                 error = EBUSY;
3242                         }
3243                         resume_err = zfs_resume_fs(zfsvfs, zc->zc_name);
3244                         error = error ? error : resume_err;
3245                 }
3246                 VFS_RELE(zfsvfs->z_vfs);
3247         } else {
3248                 if (dsl_dataset_tryown(ds, B_FALSE, FTAG)) {
3249                         error = dsl_dataset_clone_swap(clone, ds, B_TRUE);
3250                         dsl_dataset_disown(ds, FTAG);
3251                         ds = NULL;
3252                 } else {
3253                         error = EBUSY;
3254                 }
3255         }
3256
3257         /*
3258          * Destroy clone (which also closes it).
3259          */
3260         (void) dsl_dataset_destroy(clone, FTAG, B_FALSE);
3261
3262 out:
3263         strfree(clone_name);
3264         if (ds)
3265                 dsl_dataset_rele(ds, FTAG);
3266         return (error);
3267 #else
3268         return (ENOTSUP);
3269 #endif /* HAVE_ZPL */
3270 }
3271
3272 /*
3273  * inputs:
3274  * zc_name      old name of dataset
3275  * zc_value     new name of dataset
3276  * zc_cookie    recursive flag (only valid for snapshots)
3277  *
3278  * outputs:     none
3279  */
3280 static int
3281 zfs_ioc_rename(zfs_cmd_t *zc)
3282 {
3283         boolean_t recursive = zc->zc_cookie & 1;
3284
3285         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3286         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3287             strchr(zc->zc_value, '%'))
3288                 return (EINVAL);
3289
3290         /*
3291          * Unmount snapshot unless we're doing a recursive rename,
3292          * in which case the dataset code figures out which snapshots
3293          * to unmount.
3294          */
3295         if (!recursive && strchr(zc->zc_name, '@') != NULL &&
3296             zc->zc_objset_type == DMU_OST_ZFS) {
3297                 int err = zfs_unmount_snap(zc->zc_name, NULL);
3298                 if (err)
3299                         return (err);
3300         }
3301         if (zc->zc_objset_type == DMU_OST_ZVOL)
3302                 (void) zvol_remove_minor(zc->zc_name);
3303         return (dmu_objset_rename(zc->zc_name, zc->zc_value, recursive));
3304 }
3305
3306 static int
3307 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3308 {
3309         const char *propname = nvpair_name(pair);
3310         boolean_t issnap = (strchr(dsname, '@') != NULL);
3311         zfs_prop_t prop = zfs_name_to_prop(propname);
3312         uint64_t intval;
3313         int err;
3314
3315         if (prop == ZPROP_INVAL) {
3316                 if (zfs_prop_user(propname)) {
3317                         if ((err = zfs_secpolicy_write_perms(dsname,
3318                             ZFS_DELEG_PERM_USERPROP, cr)))
3319                                 return (err);
3320                         return (0);
3321                 }
3322
3323                 if (!issnap && zfs_prop_userquota(propname)) {
3324                         const char *perm = NULL;
3325                         const char *uq_prefix =
3326                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3327                         const char *gq_prefix =
3328                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3329
3330                         if (strncmp(propname, uq_prefix,
3331                             strlen(uq_prefix)) == 0) {
3332                                 perm = ZFS_DELEG_PERM_USERQUOTA;
3333                         } else if (strncmp(propname, gq_prefix,
3334                             strlen(gq_prefix)) == 0) {
3335                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
3336                         } else {
3337                                 /* USERUSED and GROUPUSED are read-only */
3338                                 return (EINVAL);
3339                         }
3340
3341                         if ((err = zfs_secpolicy_write_perms(dsname, perm, cr)))
3342                                 return (err);
3343                         return (0);
3344                 }
3345
3346                 return (EINVAL);
3347         }
3348
3349         if (issnap)
3350                 return (EINVAL);
3351
3352         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3353                 /*
3354                  * dsl_prop_get_all_impl() returns properties in this
3355                  * format.
3356                  */
3357                 nvlist_t *attrs;
3358                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3359                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3360                     &pair) == 0);
3361         }
3362
3363         /*
3364          * Check that this value is valid for this pool version
3365          */
3366         switch (prop) {
3367         case ZFS_PROP_COMPRESSION:
3368                 /*
3369                  * If the user specified gzip compression, make sure
3370                  * the SPA supports it. We ignore any errors here since
3371                  * we'll catch them later.
3372                  */
3373                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3374                     nvpair_value_uint64(pair, &intval) == 0) {
3375                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
3376                             intval <= ZIO_COMPRESS_GZIP_9 &&
3377                             zfs_earlier_version(dsname,
3378                             SPA_VERSION_GZIP_COMPRESSION)) {
3379                                 return (ENOTSUP);
3380                         }
3381
3382                         if (intval == ZIO_COMPRESS_ZLE &&
3383                             zfs_earlier_version(dsname,
3384                             SPA_VERSION_ZLE_COMPRESSION))
3385                                 return (ENOTSUP);
3386
3387                         /*
3388                          * If this is a bootable dataset then
3389                          * verify that the compression algorithm
3390                          * is supported for booting. We must return
3391                          * something other than ENOTSUP since it
3392                          * implies a downrev pool version.
3393                          */
3394                         if (zfs_is_bootfs(dsname) &&
3395                             !BOOTFS_COMPRESS_VALID(intval)) {
3396                                 return (ERANGE);
3397                         }
3398                 }
3399                 break;
3400
3401         case ZFS_PROP_COPIES:
3402                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
3403                         return (ENOTSUP);
3404                 break;
3405
3406         case ZFS_PROP_DEDUP:
3407                 if (zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
3408                         return (ENOTSUP);
3409                 break;
3410
3411         case ZFS_PROP_SHARESMB:
3412                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
3413                         return (ENOTSUP);
3414                 break;
3415
3416         case ZFS_PROP_ACLINHERIT:
3417                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3418                     nvpair_value_uint64(pair, &intval) == 0) {
3419                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
3420                             zfs_earlier_version(dsname,
3421                             SPA_VERSION_PASSTHROUGH_X))
3422                                 return (ENOTSUP);
3423                 }
3424                 break;
3425         default:
3426                 break;
3427         }
3428
3429         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
3430 }
3431
3432 /*
3433  * Removes properties from the given props list that fail permission checks
3434  * needed to clear them and to restore them in case of a receive error. For each
3435  * property, make sure we have both set and inherit permissions.
3436  *
3437  * Returns the first error encountered if any permission checks fail. If the
3438  * caller provides a non-NULL errlist, it also gives the complete list of names
3439  * of all the properties that failed a permission check along with the
3440  * corresponding error numbers. The caller is responsible for freeing the
3441  * returned errlist.
3442  *
3443  * If every property checks out successfully, zero is returned and the list
3444  * pointed at by errlist is NULL.
3445  */
3446 static int
3447 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
3448 {
3449         zfs_cmd_t *zc;
3450         nvpair_t *pair, *next_pair;
3451         nvlist_t *errors;
3452         int err, rv = 0;
3453
3454         if (props == NULL)
3455                 return (0);
3456
3457         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3458
3459         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
3460         (void) strcpy(zc->zc_name, dataset);
3461         pair = nvlist_next_nvpair(props, NULL);
3462         while (pair != NULL) {
3463                 next_pair = nvlist_next_nvpair(props, pair);
3464
3465                 (void) strcpy(zc->zc_value, nvpair_name(pair));
3466                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
3467                     (err = zfs_secpolicy_inherit(zc, CRED())) != 0) {
3468                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
3469                         VERIFY(nvlist_add_int32(errors,
3470                             zc->zc_value, err) == 0);
3471                 }
3472                 pair = next_pair;
3473         }
3474         kmem_free(zc, sizeof (zfs_cmd_t));
3475
3476         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
3477                 nvlist_free(errors);
3478                 errors = NULL;
3479         } else {
3480                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
3481         }
3482
3483         if (errlist == NULL)
3484                 nvlist_free(errors);
3485         else
3486                 *errlist = errors;
3487
3488         return (rv);
3489 }
3490
3491 static boolean_t
3492 propval_equals(nvpair_t *p1, nvpair_t *p2)
3493 {
3494         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
3495                 /* dsl_prop_get_all_impl() format */
3496                 nvlist_t *attrs;
3497                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
3498                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3499                     &p1) == 0);
3500         }
3501
3502         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
3503                 nvlist_t *attrs;
3504                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
3505                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3506                     &p2) == 0);
3507         }
3508
3509         if (nvpair_type(p1) != nvpair_type(p2))
3510                 return (B_FALSE);
3511
3512         if (nvpair_type(p1) == DATA_TYPE_STRING) {
3513                 char *valstr1, *valstr2;
3514
3515                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
3516                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
3517                 return (strcmp(valstr1, valstr2) == 0);
3518         } else {
3519                 uint64_t intval1, intval2;
3520
3521                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
3522                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
3523                 return (intval1 == intval2);
3524         }
3525 }
3526
3527 /*
3528  * Remove properties from props if they are not going to change (as determined
3529  * by comparison with origprops). Remove them from origprops as well, since we
3530  * do not need to clear or restore properties that won't change.
3531  */
3532 static void
3533 props_reduce(nvlist_t *props, nvlist_t *origprops)
3534 {
3535         nvpair_t *pair, *next_pair;
3536
3537         if (origprops == NULL)
3538                 return; /* all props need to be received */
3539
3540         pair = nvlist_next_nvpair(props, NULL);
3541         while (pair != NULL) {
3542                 const char *propname = nvpair_name(pair);
3543                 nvpair_t *match;
3544
3545                 next_pair = nvlist_next_nvpair(props, pair);
3546
3547                 if ((nvlist_lookup_nvpair(origprops, propname,
3548                     &match) != 0) || !propval_equals(pair, match))
3549                         goto next; /* need to set received value */
3550
3551                 /* don't clear the existing received value */
3552                 (void) nvlist_remove_nvpair(origprops, match);
3553                 /* don't bother receiving the property */
3554                 (void) nvlist_remove_nvpair(props, pair);
3555 next:
3556                 pair = next_pair;
3557         }
3558 }
3559
3560 #ifdef  DEBUG
3561 static boolean_t zfs_ioc_recv_inject_err;
3562 #endif
3563
3564 /*
3565  * inputs:
3566  * zc_name              name of containing filesystem
3567  * zc_nvlist_src{_size} nvlist of properties to apply
3568  * zc_value             name of snapshot to create
3569  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
3570  * zc_cookie            file descriptor to recv from
3571  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
3572  * zc_guid              force flag
3573  * zc_cleanup_fd        cleanup-on-exit file descriptor
3574  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
3575  *
3576  * outputs:
3577  * zc_cookie            number of bytes read
3578  * zc_nvlist_dst{_size} error for each unapplied received property
3579  * zc_obj               zprop_errflags_t
3580  * zc_action_handle     handle for this guid/ds mapping
3581  */
3582 static int
3583 zfs_ioc_recv(zfs_cmd_t *zc)
3584 {
3585         file_t *fp;
3586         objset_t *os;
3587         dmu_recv_cookie_t drc;
3588         boolean_t force = (boolean_t)zc->zc_guid;
3589         int fd;
3590         int error = 0;
3591         int props_error = 0;
3592         nvlist_t *errors;
3593         offset_t off;
3594         nvlist_t *props = NULL; /* sent properties */
3595         nvlist_t *origprops = NULL; /* existing properties */
3596         objset_t *origin = NULL;
3597         char *tosnap;
3598         char tofs[ZFS_MAXNAMELEN];
3599         boolean_t first_recvd_props = B_FALSE;
3600
3601         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3602             strchr(zc->zc_value, '@') == NULL ||
3603             strchr(zc->zc_value, '%'))
3604                 return (EINVAL);
3605
3606         (void) strcpy(tofs, zc->zc_value);
3607         tosnap = strchr(tofs, '@');
3608         *tosnap++ = '\0';
3609
3610         if (zc->zc_nvlist_src != 0 &&
3611             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3612             zc->zc_iflags, &props)) != 0)
3613                 return (error);
3614
3615         fd = zc->zc_cookie;
3616         fp = getf(fd);
3617         if (fp == NULL) {
3618                 nvlist_free(props);
3619                 return (EBADF);
3620         }
3621
3622         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3623
3624         if (props && dmu_objset_hold(tofs, FTAG, &os) == 0) {
3625                 if ((spa_version(os->os_spa) >= SPA_VERSION_RECVD_PROPS) &&
3626                     !dsl_prop_get_hasrecvd(os)) {
3627                         first_recvd_props = B_TRUE;
3628                 }
3629
3630                 /*
3631                  * If new received properties are supplied, they are to
3632                  * completely replace the existing received properties, so stash
3633                  * away the existing ones.
3634                  */
3635                 if (dsl_prop_get_received(os, &origprops) == 0) {
3636                         nvlist_t *errlist = NULL;
3637                         /*
3638                          * Don't bother writing a property if its value won't
3639                          * change (and avoid the unnecessary security checks).
3640                          *
3641                          * The first receive after SPA_VERSION_RECVD_PROPS is a
3642                          * special case where we blow away all local properties
3643                          * regardless.
3644                          */
3645                         if (!first_recvd_props)
3646                                 props_reduce(props, origprops);
3647                         if (zfs_check_clearable(tofs, origprops,
3648                             &errlist) != 0)
3649                                 (void) nvlist_merge(errors, errlist, 0);
3650                         nvlist_free(errlist);
3651                 }
3652
3653                 dmu_objset_rele(os, FTAG);
3654         }
3655
3656         if (zc->zc_string[0]) {
3657                 error = dmu_objset_hold(zc->zc_string, FTAG, &origin);
3658                 if (error)
3659                         goto out;
3660         }
3661
3662         error = dmu_recv_begin(tofs, tosnap, zc->zc_top_ds,
3663             &zc->zc_begin_record, force, origin, &drc);
3664         if (origin)
3665                 dmu_objset_rele(origin, FTAG);
3666         if (error)
3667                 goto out;
3668
3669         /*
3670          * Set properties before we receive the stream so that they are applied
3671          * to the new data. Note that we must call dmu_recv_stream() if
3672          * dmu_recv_begin() succeeds.
3673          */
3674         if (props) {
3675                 nvlist_t *errlist;
3676
3677                 if (dmu_objset_from_ds(drc.drc_logical_ds, &os) == 0) {
3678                         if (drc.drc_newfs) {
3679                                 if (spa_version(os->os_spa) >=
3680                                     SPA_VERSION_RECVD_PROPS)
3681                                         first_recvd_props = B_TRUE;
3682                         } else if (origprops != NULL) {
3683                                 if (clear_received_props(os, tofs, origprops,
3684                                     first_recvd_props ? NULL : props) != 0)
3685                                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3686                         } else {
3687                                 zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3688                         }
3689                         dsl_prop_set_hasrecvd(os);
3690                 } else if (!drc.drc_newfs) {
3691                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3692                 }
3693
3694                 (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
3695                     props, &errlist);
3696                 (void) nvlist_merge(errors, errlist, 0);
3697                 nvlist_free(errlist);
3698         }
3699
3700         if (fit_error_list(zc, &errors) != 0 || put_nvlist(zc, errors) != 0) {
3701                 /*
3702                  * Caller made zc->zc_nvlist_dst less than the minimum expected
3703                  * size or supplied an invalid address.
3704                  */
3705                 props_error = EINVAL;
3706         }
3707
3708         off = fp->f_offset;
3709         error = dmu_recv_stream(&drc, fp->f_vnode, &off, zc->zc_cleanup_fd,
3710             &zc->zc_action_handle);
3711
3712         if (error == 0) {
3713 #ifdef HAVE_ZPL
3714                 zfsvfs_t *zfsvfs = NULL;
3715
3716                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
3717                         /* online recv */
3718                         int end_err;
3719
3720                         error = zfs_suspend_fs(zfsvfs);
3721                         /*
3722                          * If the suspend fails, then the recv_end will
3723                          * likely also fail, and clean up after itself.
3724                          */
3725                         end_err = dmu_recv_end(&drc);
3726                         if (error == 0)
3727                                 error = zfs_resume_fs(zfsvfs, tofs);
3728                         error = error ? error : end_err;
3729                         VFS_RELE(zfsvfs->z_vfs);
3730                 } else {
3731                         error = dmu_recv_end(&drc);
3732                 }
3733 #else
3734                 error = dmu_recv_end(&drc);
3735 #endif /* HAVE_ZPL */
3736         }
3737
3738         zc->zc_cookie = off - fp->f_offset;
3739         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
3740                 fp->f_offset = off;
3741
3742 #ifdef  DEBUG
3743         if (zfs_ioc_recv_inject_err) {
3744                 zfs_ioc_recv_inject_err = B_FALSE;
3745                 error = 1;
3746         }
3747 #endif
3748         /*
3749          * On error, restore the original props.
3750          */
3751         if (error && props) {
3752                 if (dmu_objset_hold(tofs, FTAG, &os) == 0) {
3753                         if (clear_received_props(os, tofs, props, NULL) != 0) {
3754                                 /*
3755                                  * We failed to clear the received properties.
3756                                  * Since we may have left a $recvd value on the
3757                                  * system, we can't clear the $hasrecvd flag.
3758                                  */
3759                                 zc->zc_obj |= ZPROP_ERR_NORESTORE;
3760                         } else if (first_recvd_props) {
3761                                 dsl_prop_unset_hasrecvd(os);
3762                         }
3763                         dmu_objset_rele(os, FTAG);
3764                 } else if (!drc.drc_newfs) {
3765                         /* We failed to clear the received properties. */
3766                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3767                 }
3768
3769                 if (origprops == NULL && !drc.drc_newfs) {
3770                         /* We failed to stash the original properties. */
3771                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3772                 }
3773
3774                 /*
3775                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
3776                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
3777                  * explictly if we're restoring local properties cleared in the
3778                  * first new-style receive.
3779                  */
3780                 if (origprops != NULL &&
3781                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
3782                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
3783                     origprops, NULL) != 0) {
3784                         /*
3785                          * We stashed the original properties but failed to
3786                          * restore them.
3787                          */
3788                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3789                 }
3790         }
3791 out:
3792         nvlist_free(props);
3793         nvlist_free(origprops);
3794         nvlist_free(errors);
3795         releasef(fd);
3796
3797         if (error == 0)
3798                 error = props_error;
3799
3800         return (error);
3801 }
3802
3803 /*
3804  * inputs:
3805  * zc_name      name of snapshot to send
3806  * zc_cookie    file descriptor to send stream to
3807  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
3808  * zc_sendobj   objsetid of snapshot to send
3809  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
3810  *
3811  * outputs: none
3812  */
3813 static int
3814 zfs_ioc_send(zfs_cmd_t *zc)
3815 {
3816         objset_t *fromsnap = NULL;
3817         objset_t *tosnap;
3818         file_t *fp;
3819         int error;
3820         offset_t off;
3821         dsl_dataset_t *ds;
3822         dsl_dataset_t *dsfrom = NULL;
3823         spa_t *spa;
3824         dsl_pool_t *dp;
3825
3826         error = spa_open(zc->zc_name, &spa, FTAG);
3827         if (error)
3828                 return (error);
3829
3830         dp = spa_get_dsl(spa);
3831         rw_enter(&dp->dp_config_rwlock, RW_READER);
3832         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
3833         rw_exit(&dp->dp_config_rwlock);
3834         if (error) {
3835                 spa_close(spa, FTAG);
3836                 return (error);
3837         }
3838
3839         error = dmu_objset_from_ds(ds, &tosnap);
3840         if (error) {
3841                 dsl_dataset_rele(ds, FTAG);
3842                 spa_close(spa, FTAG);
3843                 return (error);
3844         }
3845
3846         if (zc->zc_fromobj != 0) {
3847                 rw_enter(&dp->dp_config_rwlock, RW_READER);
3848                 error = dsl_dataset_hold_obj(dp, zc->zc_fromobj, FTAG, &dsfrom);
3849                 rw_exit(&dp->dp_config_rwlock);
3850                 spa_close(spa, FTAG);
3851                 if (error) {
3852                         dsl_dataset_rele(ds, FTAG);
3853                         return (error);
3854                 }
3855                 error = dmu_objset_from_ds(dsfrom, &fromsnap);
3856                 if (error) {
3857                         dsl_dataset_rele(dsfrom, FTAG);
3858                         dsl_dataset_rele(ds, FTAG);
3859                         return (error);
3860                 }
3861         } else {
3862                 spa_close(spa, FTAG);
3863         }
3864
3865         fp = getf(zc->zc_cookie);
3866         if (fp == NULL) {
3867                 dsl_dataset_rele(ds, FTAG);
3868                 if (dsfrom)
3869                         dsl_dataset_rele(dsfrom, FTAG);
3870                 return (EBADF);
3871         }
3872
3873         off = fp->f_offset;
3874         error = dmu_sendbackup(tosnap, fromsnap, zc->zc_obj, fp->f_vnode, &off);
3875
3876         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
3877                 fp->f_offset = off;
3878         releasef(zc->zc_cookie);
3879         if (dsfrom)
3880                 dsl_dataset_rele(dsfrom, FTAG);
3881         dsl_dataset_rele(ds, FTAG);
3882         return (error);
3883 }
3884
3885 static int
3886 zfs_ioc_inject_fault(zfs_cmd_t *zc)
3887 {
3888         int id, error;
3889
3890         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
3891             &zc->zc_inject_record);
3892
3893         if (error == 0)
3894                 zc->zc_guid = (uint64_t)id;
3895
3896         return (error);
3897 }
3898
3899 static int
3900 zfs_ioc_clear_fault(zfs_cmd_t *zc)
3901 {
3902         return (zio_clear_fault((int)zc->zc_guid));
3903 }
3904
3905 static int
3906 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
3907 {
3908         int id = (int)zc->zc_guid;
3909         int error;
3910
3911         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
3912             &zc->zc_inject_record);
3913
3914         zc->zc_guid = id;
3915
3916         return (error);
3917 }
3918
3919 static int
3920 zfs_ioc_error_log(zfs_cmd_t *zc)
3921 {
3922         spa_t *spa;
3923         int error;
3924         size_t count = (size_t)zc->zc_nvlist_dst_size;
3925
3926         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
3927                 return (error);
3928
3929         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
3930             &count);
3931         if (error == 0)
3932                 zc->zc_nvlist_dst_size = count;
3933         else
3934                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
3935
3936         spa_close(spa, FTAG);
3937
3938         return (error);
3939 }
3940
3941 static int
3942 zfs_ioc_clear(zfs_cmd_t *zc)
3943 {
3944         spa_t *spa;
3945         vdev_t *vd;
3946         int error;
3947
3948         /*
3949          * On zpool clear we also fix up missing slogs
3950          */
3951         mutex_enter(&spa_namespace_lock);
3952         spa = spa_lookup(zc->zc_name);
3953         if (spa == NULL) {
3954                 mutex_exit(&spa_namespace_lock);
3955                 return (EIO);
3956         }
3957         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
3958                 /* we need to let spa_open/spa_load clear the chains */
3959                 spa_set_log_state(spa, SPA_LOG_CLEAR);
3960         }
3961         spa->spa_last_open_failed = 0;
3962         mutex_exit(&spa_namespace_lock);
3963
3964         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
3965                 error = spa_open(zc->zc_name, &spa, FTAG);
3966         } else {
3967                 nvlist_t *policy;
3968                 nvlist_t *config = NULL;
3969
3970                 if (zc->zc_nvlist_src == 0)
3971                         return (EINVAL);
3972
3973                 if ((error = get_nvlist(zc->zc_nvlist_src,
3974                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
3975                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
3976                             policy, &config);
3977                         if (config != NULL) {
3978                                 int err;
3979
3980                                 if ((err = put_nvlist(zc, config)) != 0)
3981                                         error = err;
3982                                 nvlist_free(config);
3983                         }
3984                         nvlist_free(policy);
3985                 }
3986         }
3987
3988         if (error)
3989                 return (error);
3990
3991         spa_vdev_state_enter(spa, SCL_NONE);
3992
3993         if (zc->zc_guid == 0) {
3994                 vd = NULL;
3995         } else {
3996                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
3997                 if (vd == NULL) {
3998                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
3999                         spa_close(spa, FTAG);
4000                         return (ENODEV);
4001                 }
4002         }
4003
4004         vdev_clear(spa, vd);
4005
4006         (void) spa_vdev_state_exit(spa, NULL, 0);
4007
4008         /*
4009          * Resume any suspended I/Os.
4010          */
4011         if (zio_resume(spa) != 0)
4012                 error = EIO;
4013
4014         spa_close(spa, FTAG);
4015
4016         return (error);
4017 }
4018
4019 /*
4020  * inputs:
4021  * zc_name      name of filesystem
4022  * zc_value     name of origin snapshot
4023  *
4024  * outputs:
4025  * zc_string    name of conflicting snapshot, if there is one
4026  */
4027 static int
4028 zfs_ioc_promote(zfs_cmd_t *zc)
4029 {
4030         char *cp;
4031
4032         /*
4033          * We don't need to unmount *all* the origin fs's snapshots, but
4034          * it's easier.
4035          */
4036         cp = strchr(zc->zc_value, '@');
4037         if (cp)
4038                 *cp = '\0';
4039         (void) dmu_objset_find(zc->zc_value,
4040             zfs_unmount_snap, NULL, DS_FIND_SNAPSHOTS);
4041         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
4042 }
4043
4044 /*
4045  * Retrieve a single {user|group}{used|quota}@... property.
4046  *
4047  * inputs:
4048  * zc_name      name of filesystem
4049  * zc_objset_type zfs_userquota_prop_t
4050  * zc_value     domain name (eg. "S-1-234-567-89")
4051  * zc_guid      RID/UID/GID
4052  *
4053  * outputs:
4054  * zc_cookie    property value
4055  */
4056 static int
4057 zfs_ioc_userspace_one(zfs_cmd_t *zc)
4058 {
4059 #ifdef HAVE_ZPL
4060         zfsvfs_t *zfsvfs;
4061         int error;
4062
4063         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
4064                 return (EINVAL);
4065
4066         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4067         if (error)
4068                 return (error);
4069
4070         error = zfs_userspace_one(zfsvfs,
4071             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
4072         zfsvfs_rele(zfsvfs, FTAG);
4073
4074         return (error);
4075 #else
4076         return (ENOTSUP);
4077 #endif /* HAVE_ZPL */
4078 }
4079
4080 /*
4081  * inputs:
4082  * zc_name              name of filesystem
4083  * zc_cookie            zap cursor
4084  * zc_objset_type       zfs_userquota_prop_t
4085  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
4086  *
4087  * outputs:
4088  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
4089  * zc_cookie    zap cursor
4090  */
4091 static int
4092 zfs_ioc_userspace_many(zfs_cmd_t *zc)
4093 {
4094 #ifdef HAVE_ZPL
4095         zfsvfs_t *zfsvfs;
4096         int bufsize = zc->zc_nvlist_dst_size;
4097
4098         if (bufsize <= 0)
4099                 return (ENOMEM);
4100
4101         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4102         if (error)
4103                 return (error);
4104
4105         void *buf = kmem_alloc(bufsize, KM_SLEEP);
4106
4107         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
4108             buf, &zc->zc_nvlist_dst_size);
4109
4110         if (error == 0) {
4111                 error = xcopyout(buf,
4112                     (void *)(uintptr_t)zc->zc_nvlist_dst,
4113                     zc->zc_nvlist_dst_size);
4114         }
4115         kmem_free(buf, bufsize);
4116         zfsvfs_rele(zfsvfs, FTAG);
4117
4118         return (error);
4119 #else
4120         return (ENOTSUP);
4121 #endif /* HAVE_ZPL */
4122 }
4123
4124 /*
4125  * inputs:
4126  * zc_name              name of filesystem
4127  *
4128  * outputs:
4129  * none
4130  */
4131 static int
4132 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
4133 {
4134 #ifdef HAVE_ZPL
4135         objset_t *os;
4136         int error = 0;
4137         zfsvfs_t *zfsvfs;
4138
4139         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
4140                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
4141                         /*
4142                          * If userused is not enabled, it may be because the
4143                          * objset needs to be closed & reopened (to grow the
4144                          * objset_phys_t).  Suspend/resume the fs will do that.
4145                          */
4146                         error = zfs_suspend_fs(zfsvfs);
4147                         if (error == 0)
4148                                 error = zfs_resume_fs(zfsvfs, zc->zc_name);
4149                 }
4150                 if (error == 0)
4151                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
4152                 VFS_RELE(zfsvfs->z_vfs);
4153         } else {
4154                 /* XXX kind of reading contents without owning */
4155                 error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4156                 if (error)
4157                         return (error);
4158
4159                 error = dmu_objset_userspace_upgrade(os);
4160                 dmu_objset_rele(os, FTAG);
4161         }
4162
4163         return (error);
4164 #else
4165         return (ENOTSUP);
4166 #endif /* HAVE_ZPL */
4167 }
4168
4169 /*
4170  * We don't want to have a hard dependency
4171  * against some special symbols in sharefs
4172  * nfs, and smbsrv.  Determine them if needed when
4173  * the first file system is shared.
4174  * Neither sharefs, nfs or smbsrv are unloadable modules.
4175  */
4176 #ifdef HAVE_ZPL
4177 int (*znfsexport_fs)(void *arg);
4178 int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
4179 int (*zsmbexport_fs)(void *arg, boolean_t add_share);
4180
4181 int zfs_nfsshare_inited;
4182 int zfs_smbshare_inited;
4183
4184 ddi_modhandle_t nfs_mod;
4185 ddi_modhandle_t sharefs_mod;
4186 ddi_modhandle_t smbsrv_mod;
4187 kmutex_t zfs_share_lock;
4188
4189 static int
4190 zfs_init_sharefs()
4191 {
4192         int error;
4193
4194         ASSERT(MUTEX_HELD(&zfs_share_lock));
4195         /* Both NFS and SMB shares also require sharetab support. */
4196         if (sharefs_mod == NULL && ((sharefs_mod =
4197             ddi_modopen("fs/sharefs",
4198             KRTLD_MODE_FIRST, &error)) == NULL)) {
4199                 return (ENOSYS);
4200         }
4201         if (zshare_fs == NULL && ((zshare_fs =
4202             (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
4203             ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
4204                 return (ENOSYS);
4205         }
4206         return (0);
4207 }
4208 #endif /* HAVE_ZPL */
4209
4210 static int
4211 zfs_ioc_share(zfs_cmd_t *zc)
4212 {
4213 #ifdef HAVE_ZPL
4214         int error;
4215         int opcode;
4216
4217         switch (zc->zc_share.z_sharetype) {
4218         case ZFS_SHARE_NFS:
4219         case ZFS_UNSHARE_NFS:
4220                 if (zfs_nfsshare_inited == 0) {
4221                         mutex_enter(&zfs_share_lock);
4222                         if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
4223                             KRTLD_MODE_FIRST, &error)) == NULL)) {
4224                                 mutex_exit(&zfs_share_lock);
4225                                 return (ENOSYS);
4226                         }
4227                         if (znfsexport_fs == NULL &&
4228                             ((znfsexport_fs = (int (*)(void *))
4229                             ddi_modsym(nfs_mod,
4230                             "nfs_export", &error)) == NULL)) {
4231                                 mutex_exit(&zfs_share_lock);
4232                                 return (ENOSYS);
4233                         }
4234                         error = zfs_init_sharefs();
4235                         if (error) {
4236                                 mutex_exit(&zfs_share_lock);
4237                                 return (ENOSYS);
4238                         }
4239                         zfs_nfsshare_inited = 1;
4240                         mutex_exit(&zfs_share_lock);
4241                 }
4242                 break;
4243         case ZFS_SHARE_SMB:
4244         case ZFS_UNSHARE_SMB:
4245                 if (zfs_smbshare_inited == 0) {
4246                         mutex_enter(&zfs_share_lock);
4247                         if (smbsrv_mod == NULL && ((smbsrv_mod =
4248                             ddi_modopen("drv/smbsrv",
4249                             KRTLD_MODE_FIRST, &error)) == NULL)) {
4250                                 mutex_exit(&zfs_share_lock);
4251                                 return (ENOSYS);
4252                         }
4253                         if (zsmbexport_fs == NULL && ((zsmbexport_fs =
4254                             (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
4255                             "smb_server_share", &error)) == NULL)) {
4256                                 mutex_exit(&zfs_share_lock);
4257                                 return (ENOSYS);
4258                         }
4259                         error = zfs_init_sharefs();
4260                         if (error) {
4261                                 mutex_exit(&zfs_share_lock);
4262                                 return (ENOSYS);
4263                         }
4264                         zfs_smbshare_inited = 1;
4265                         mutex_exit(&zfs_share_lock);
4266                 }
4267                 break;
4268         default:
4269                 return (EINVAL);
4270         }
4271
4272         switch (zc->zc_share.z_sharetype) {
4273         case ZFS_SHARE_NFS:
4274         case ZFS_UNSHARE_NFS:
4275                 if (error =
4276                     znfsexport_fs((void *)
4277                     (uintptr_t)zc->zc_share.z_exportdata))
4278                         return (error);
4279                 break;
4280         case ZFS_SHARE_SMB:
4281         case ZFS_UNSHARE_SMB:
4282                 if (error = zsmbexport_fs((void *)
4283                     (uintptr_t)zc->zc_share.z_exportdata,
4284                     zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
4285                     B_TRUE: B_FALSE)) {
4286                         return (error);
4287                 }
4288                 break;
4289         }
4290
4291         opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
4292             zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
4293             SHAREFS_ADD : SHAREFS_REMOVE;
4294
4295         /*
4296          * Add or remove share from sharetab
4297          */
4298         error = zshare_fs(opcode,
4299             (void *)(uintptr_t)zc->zc_share.z_sharedata,
4300             zc->zc_share.z_sharemax);
4301
4302         return (error);
4303 #else
4304         return (ENOTSUP);
4305 #endif /* HAVE_ZPL */
4306 }
4307
4308 ace_t full_access[] = {
4309         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
4310 };
4311
4312 /*
4313  * inputs:
4314  * zc_name              name of containing filesystem
4315  * zc_obj               object # beyond which we want next in-use object #
4316  *
4317  * outputs:
4318  * zc_obj               next in-use object #
4319  */
4320 static int
4321 zfs_ioc_next_obj(zfs_cmd_t *zc)
4322 {
4323         objset_t *os = NULL;
4324         int error;
4325
4326         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4327         if (error)
4328                 return (error);
4329
4330         error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
4331             os->os_dsl_dataset->ds_phys->ds_prev_snap_txg);
4332
4333         dmu_objset_rele(os, FTAG);
4334         return (error);
4335 }
4336
4337 /*
4338  * inputs:
4339  * zc_name              name of filesystem
4340  * zc_value             prefix name for snapshot
4341  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
4342  *
4343  * outputs:
4344  */
4345 static int
4346 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
4347 {
4348         char *snap_name;
4349         int error;
4350
4351         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
4352             (u_longlong_t)ddi_get_lbolt64());
4353
4354         if (strlen(snap_name) >= MAXNAMELEN) {
4355                 strfree(snap_name);
4356                 return (E2BIG);
4357         }
4358
4359         error = dmu_objset_snapshot(zc->zc_name, snap_name, snap_name,
4360             NULL, B_FALSE, B_TRUE, zc->zc_cleanup_fd);
4361         if (error != 0) {
4362                 strfree(snap_name);
4363                 return (error);
4364         }
4365
4366         (void) strcpy(zc->zc_value, snap_name);
4367         strfree(snap_name);
4368         return (0);
4369 }
4370
4371 /*
4372  * inputs:
4373  * zc_name              name of "to" snapshot
4374  * zc_value             name of "from" snapshot
4375  * zc_cookie            file descriptor to write diff data on
4376  *
4377  * outputs:
4378  * dmu_diff_record_t's to the file descriptor
4379  */
4380 static int
4381 zfs_ioc_diff(zfs_cmd_t *zc)
4382 {
4383         objset_t *fromsnap;
4384         objset_t *tosnap;
4385         file_t *fp;
4386         offset_t off;
4387         int error;
4388
4389         error = dmu_objset_hold(zc->zc_name, FTAG, &tosnap);
4390         if (error)
4391                 return (error);
4392
4393         error = dmu_objset_hold(zc->zc_value, FTAG, &fromsnap);
4394         if (error) {
4395                 dmu_objset_rele(tosnap, FTAG);
4396                 return (error);
4397         }
4398
4399         fp = getf(zc->zc_cookie);
4400         if (fp == NULL) {
4401                 dmu_objset_rele(fromsnap, FTAG);
4402                 dmu_objset_rele(tosnap, FTAG);
4403                 return (EBADF);
4404         }
4405
4406         off = fp->f_offset;
4407
4408         error = dmu_diff(tosnap, fromsnap, fp->f_vnode, &off);
4409
4410         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
4411                 fp->f_offset = off;
4412         releasef(zc->zc_cookie);
4413
4414         dmu_objset_rele(fromsnap, FTAG);
4415         dmu_objset_rele(tosnap, FTAG);
4416         return (error);
4417 }
4418
4419 /*
4420  * Remove all ACL files in shares dir
4421  */
4422 #ifdef HAVE_ZPL
4423 static int
4424 zfs_smb_acl_purge(znode_t *dzp)
4425 {
4426         zap_cursor_t    zc;
4427         zap_attribute_t zap;
4428         zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
4429         int error;
4430
4431         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
4432             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
4433             zap_cursor_advance(&zc)) {
4434                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
4435                     NULL, 0)) != 0)
4436                         break;
4437         }
4438         zap_cursor_fini(&zc);
4439         return (error);
4440 }
4441 #endif /* HAVE ZPL */
4442
4443 static int
4444 zfs_ioc_smb_acl(zfs_cmd_t *zc)
4445 {
4446 #ifdef HAVE_ZPL
4447         vnode_t *vp;
4448         znode_t *dzp;
4449         vnode_t *resourcevp = NULL;
4450         znode_t *sharedir;
4451         zfsvfs_t *zfsvfs;
4452         nvlist_t *nvlist;
4453         char *src, *target;
4454         vattr_t vattr;
4455         vsecattr_t vsec;
4456         int error = 0;
4457
4458         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
4459             NO_FOLLOW, NULL, &vp)) != 0)
4460                 return (error);
4461
4462         /* Now make sure mntpnt and dataset are ZFS */
4463
4464         if (vp->v_vfsp->vfs_fstype != zfsfstype ||
4465             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
4466             zc->zc_name) != 0)) {
4467                 VN_RELE(vp);
4468                 return (EINVAL);
4469         }
4470
4471         dzp = VTOZ(vp);
4472         zfsvfs = dzp->z_zfsvfs;
4473         ZFS_ENTER(zfsvfs);
4474
4475         /*
4476          * Create share dir if its missing.
4477          */
4478         mutex_enter(&zfsvfs->z_lock);
4479         if (zfsvfs->z_shares_dir == 0) {
4480                 dmu_tx_t *tx;
4481
4482                 tx = dmu_tx_create(zfsvfs->z_os);
4483                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
4484                     ZFS_SHARES_DIR);
4485                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
4486                 error = dmu_tx_assign(tx, TXG_WAIT);
4487                 if (error) {
4488                         dmu_tx_abort(tx);
4489                 } else {
4490                         error = zfs_create_share_dir(zfsvfs, tx);
4491                         dmu_tx_commit(tx);
4492                 }
4493                 if (error) {
4494                         mutex_exit(&zfsvfs->z_lock);
4495                         VN_RELE(vp);
4496                         ZFS_EXIT(zfsvfs);
4497                         return (error);
4498                 }
4499         }
4500         mutex_exit(&zfsvfs->z_lock);
4501
4502         ASSERT(zfsvfs->z_shares_dir);
4503         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
4504                 VN_RELE(vp);
4505                 ZFS_EXIT(zfsvfs);
4506                 return (error);
4507         }
4508
4509         switch (zc->zc_cookie) {
4510         case ZFS_SMB_ACL_ADD:
4511                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
4512                 vattr.va_type = VREG;
4513                 vattr.va_mode = S_IFREG|0777;
4514                 vattr.va_uid = 0;
4515                 vattr.va_gid = 0;
4516
4517                 vsec.vsa_mask = VSA_ACE;
4518                 vsec.vsa_aclentp = &full_access;
4519                 vsec.vsa_aclentsz = sizeof (full_access);
4520                 vsec.vsa_aclcnt = 1;
4521
4522                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
4523                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
4524                 if (resourcevp)
4525                         VN_RELE(resourcevp);
4526                 break;
4527
4528         case ZFS_SMB_ACL_REMOVE:
4529                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
4530                     NULL, 0);
4531                 break;
4532
4533         case ZFS_SMB_ACL_RENAME:
4534                 if ((error = get_nvlist(zc->zc_nvlist_src,
4535                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
4536                         VN_RELE(vp);
4537                         ZFS_EXIT(zfsvfs);
4538                         return (error);
4539                 }
4540                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
4541                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
4542                     &target)) {
4543                         VN_RELE(vp);
4544                         VN_RELE(ZTOV(sharedir));
4545                         ZFS_EXIT(zfsvfs);
4546                         nvlist_free(nvlist);
4547                         return (error);
4548                 }
4549                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
4550                     kcred, NULL, 0);
4551                 nvlist_free(nvlist);
4552                 break;
4553
4554         case ZFS_SMB_ACL_PURGE:
4555                 error = zfs_smb_acl_purge(sharedir);
4556                 break;
4557
4558         default:
4559                 error = EINVAL;
4560                 break;
4561         }
4562
4563         VN_RELE(vp);
4564         VN_RELE(ZTOV(sharedir));
4565
4566         ZFS_EXIT(zfsvfs);
4567
4568         return (error);
4569 #else
4570         return (ENOTSUP);
4571 #endif /* HAVE_ZPL */
4572 }
4573
4574 /*
4575  * inputs:
4576  * zc_name              name of filesystem
4577  * zc_value             short name of snap
4578  * zc_string            user-supplied tag for this hold
4579  * zc_cookie            recursive flag
4580  * zc_temphold          set if hold is temporary
4581  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
4582  * zc_sendobj           if non-zero, the objid for zc_name@zc_value
4583  * zc_createtxg         if zc_sendobj is non-zero, snap must have zc_createtxg
4584  *
4585  * outputs:             none
4586  */
4587 static int
4588 zfs_ioc_hold(zfs_cmd_t *zc)
4589 {
4590         boolean_t recursive = zc->zc_cookie;
4591         spa_t *spa;
4592         dsl_pool_t *dp;
4593         dsl_dataset_t *ds;
4594         int error;
4595         minor_t minor = 0;
4596
4597         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
4598                 return (EINVAL);
4599
4600         if (zc->zc_sendobj == 0) {
4601                 return (dsl_dataset_user_hold(zc->zc_name, zc->zc_value,
4602                     zc->zc_string, recursive, zc->zc_temphold,
4603                     zc->zc_cleanup_fd));
4604         }
4605
4606         if (recursive)
4607                 return (EINVAL);
4608
4609         error = spa_open(zc->zc_name, &spa, FTAG);
4610         if (error)
4611                 return (error);
4612
4613         dp = spa_get_dsl(spa);
4614         rw_enter(&dp->dp_config_rwlock, RW_READER);
4615         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
4616         rw_exit(&dp->dp_config_rwlock);
4617         spa_close(spa, FTAG);
4618         if (error)
4619                 return (error);
4620
4621         /*
4622          * Until we have a hold on this snapshot, it's possible that
4623          * zc_sendobj could've been destroyed and reused as part
4624          * of a later txg.  Make sure we're looking at the right object.
4625          */
4626         if (zc->zc_createtxg != ds->ds_phys->ds_creation_txg) {
4627                 dsl_dataset_rele(ds, FTAG);
4628                 return (ENOENT);
4629         }
4630
4631         if (zc->zc_cleanup_fd != -1 && zc->zc_temphold) {
4632                 error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
4633                 if (error) {
4634                         dsl_dataset_rele(ds, FTAG);
4635                         return (error);
4636                 }
4637         }
4638
4639         error = dsl_dataset_user_hold_for_send(ds, zc->zc_string,
4640             zc->zc_temphold);
4641         if (minor != 0) {
4642                 if (error == 0) {
4643                         dsl_register_onexit_hold_cleanup(ds, zc->zc_string,
4644                             minor);
4645                 }
4646                 zfs_onexit_fd_rele(zc->zc_cleanup_fd);
4647         }
4648         dsl_dataset_rele(ds, FTAG);
4649
4650         return (error);
4651 }
4652
4653 /*
4654  * inputs:
4655  * zc_name      name of dataset from which we're releasing a user hold
4656  * zc_value     short name of snap
4657  * zc_string    user-supplied tag for this hold
4658  * zc_cookie    recursive flag
4659  *
4660  * outputs:     none
4661  */
4662 static int
4663 zfs_ioc_release(zfs_cmd_t *zc)
4664 {
4665         boolean_t recursive = zc->zc_cookie;
4666
4667         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
4668                 return (EINVAL);
4669
4670         return (dsl_dataset_user_release(zc->zc_name, zc->zc_value,
4671             zc->zc_string, recursive));
4672 }
4673
4674 /*
4675  * inputs:
4676  * zc_name              name of filesystem
4677  *
4678  * outputs:
4679  * zc_nvlist_src{_size} nvlist of snapshot holds
4680  */
4681 static int
4682 zfs_ioc_get_holds(zfs_cmd_t *zc)
4683 {
4684         nvlist_t *nvp;
4685         int error;
4686
4687         if ((error = dsl_dataset_get_holds(zc->zc_name, &nvp)) == 0) {
4688                 error = put_nvlist(zc, nvp);
4689                 nvlist_free(nvp);
4690         }
4691
4692         return (error);
4693 }
4694
4695 /*
4696  * inputs:
4697  * zc_guid              flags (ZEVENT_NONBLOCK)
4698  *
4699  * outputs:
4700  * zc_nvlist_dst        next nvlist event
4701  * zc_cookie            dropped events since last get
4702  * zc_cleanup_fd        cleanup-on-exit file descriptor
4703  */
4704 static int
4705 zfs_ioc_events_next(zfs_cmd_t *zc)
4706 {
4707         zfs_zevent_t *ze;
4708         nvlist_t *event = NULL;
4709         minor_t minor;
4710         uint64_t dropped = 0;
4711         int error;
4712
4713         error = zfs_zevent_fd_hold(zc->zc_cleanup_fd, &minor, &ze);
4714         if (error != 0)
4715                 return (error);
4716
4717         do {
4718                 error = zfs_zevent_next(ze, &event, &dropped);
4719                 if (event != NULL) {
4720                         zc->zc_cookie = dropped;
4721                         error = put_nvlist(zc, event);
4722                         nvlist_free(event);
4723                 }
4724
4725                 if (zc->zc_guid & ZEVENT_NONBLOCK)
4726                         break;
4727
4728                 if ((error == 0) || (error != ENOENT))
4729                         break;
4730
4731                 error = zfs_zevent_wait(ze);
4732                 if (error)
4733                         break;
4734         } while (1);
4735
4736         zfs_zevent_fd_rele(zc->zc_cleanup_fd);
4737
4738         return (error);
4739 }
4740
4741 /*
4742  * outputs:
4743  * zc_cookie            cleared events count
4744  */
4745 static int
4746 zfs_ioc_events_clear(zfs_cmd_t *zc)
4747 {
4748         int count;
4749
4750         zfs_zevent_drain_all(&count);
4751         zc->zc_cookie = count;
4752
4753         return 0;
4754 }
4755
4756 /*
4757  * pool create, destroy, and export don't log the history as part of
4758  * zfsdev_ioctl, but rather zfs_ioc_pool_create, and zfs_ioc_pool_export
4759  * do the logging of those commands.
4760  */
4761 static zfs_ioc_vec_t zfs_ioc_vec[] = {
4762         { zfs_ioc_pool_create, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4763             POOL_CHECK_NONE },
4764         { zfs_ioc_pool_destroy, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4765             POOL_CHECK_NONE },
4766         { zfs_ioc_pool_import, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4767             POOL_CHECK_NONE },
4768         { zfs_ioc_pool_export, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4769             POOL_CHECK_NONE },
4770         { zfs_ioc_pool_configs, zfs_secpolicy_none, NO_NAME, B_FALSE,
4771             POOL_CHECK_NONE },
4772         { zfs_ioc_pool_stats, zfs_secpolicy_read, POOL_NAME, B_FALSE,
4773             POOL_CHECK_NONE },
4774         { zfs_ioc_pool_tryimport, zfs_secpolicy_config, NO_NAME, B_FALSE,
4775             POOL_CHECK_NONE },
4776         { zfs_ioc_pool_scan, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4777             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4778         { zfs_ioc_pool_freeze, zfs_secpolicy_config, NO_NAME, B_FALSE,
4779             POOL_CHECK_READONLY },
4780         { zfs_ioc_pool_upgrade, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4781             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4782         { zfs_ioc_pool_get_history, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4783             POOL_CHECK_NONE },
4784         { zfs_ioc_vdev_add, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4785             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4786         { zfs_ioc_vdev_remove, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4787             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4788         { zfs_ioc_vdev_set_state, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4789             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4790         { zfs_ioc_vdev_attach, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4791             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4792         { zfs_ioc_vdev_detach, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4793             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4794         { zfs_ioc_vdev_setpath, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4795             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4796         { zfs_ioc_vdev_setfru,  zfs_secpolicy_config, POOL_NAME, B_FALSE,
4797             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4798         { zfs_ioc_objset_stats, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4799             POOL_CHECK_SUSPENDED },
4800         { zfs_ioc_objset_zplprops, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4801             POOL_CHECK_NONE },
4802         { zfs_ioc_dataset_list_next, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4803             POOL_CHECK_SUSPENDED },
4804         { zfs_ioc_snapshot_list_next, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4805             POOL_CHECK_SUSPENDED },
4806         { zfs_ioc_set_prop, zfs_secpolicy_none, DATASET_NAME, B_TRUE,
4807             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4808         { zfs_ioc_create, zfs_secpolicy_create, DATASET_NAME, B_TRUE,
4809             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4810         { zfs_ioc_destroy, zfs_secpolicy_destroy, DATASET_NAME, B_TRUE,
4811             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4812         { zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME, B_TRUE,
4813             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4814         { zfs_ioc_rename, zfs_secpolicy_rename, DATASET_NAME, B_TRUE,
4815             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4816         { zfs_ioc_recv, zfs_secpolicy_receive, DATASET_NAME, B_TRUE,
4817             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4818         { zfs_ioc_send, zfs_secpolicy_send, DATASET_NAME, B_TRUE,
4819             POOL_CHECK_NONE },
4820         { zfs_ioc_inject_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4821             POOL_CHECK_NONE },
4822         { zfs_ioc_clear_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4823             POOL_CHECK_NONE },
4824         { zfs_ioc_inject_list_next, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4825             POOL_CHECK_NONE },
4826         { zfs_ioc_error_log, zfs_secpolicy_inject, POOL_NAME, B_FALSE,
4827             POOL_CHECK_NONE },
4828         { zfs_ioc_clear, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4829             POOL_CHECK_NONE },
4830         { zfs_ioc_promote, zfs_secpolicy_promote, DATASET_NAME, B_TRUE,
4831             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4832         { zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, DATASET_NAME,
4833             B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4834         { zfs_ioc_snapshot, zfs_secpolicy_snapshot, DATASET_NAME, B_TRUE,
4835             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4836         { zfs_ioc_dsobj_to_dsname, zfs_secpolicy_diff, POOL_NAME, B_FALSE,
4837             POOL_CHECK_NONE },
4838         { zfs_ioc_obj_to_path, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
4839             POOL_CHECK_SUSPENDED },
4840         { zfs_ioc_pool_set_props, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4841             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4842         { zfs_ioc_pool_get_props, zfs_secpolicy_read, POOL_NAME, B_FALSE,
4843             POOL_CHECK_NONE },
4844         { zfs_ioc_set_fsacl, zfs_secpolicy_fsacl, DATASET_NAME, B_TRUE,
4845             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4846         { zfs_ioc_get_fsacl, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4847             POOL_CHECK_NONE },
4848         { zfs_ioc_share, zfs_secpolicy_share, DATASET_NAME, B_FALSE,
4849             POOL_CHECK_NONE },
4850         { zfs_ioc_inherit_prop, zfs_secpolicy_inherit, DATASET_NAME, B_TRUE,
4851             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4852         { zfs_ioc_smb_acl, zfs_secpolicy_smb_acl, DATASET_NAME, B_FALSE,
4853             POOL_CHECK_NONE },
4854         { zfs_ioc_userspace_one, zfs_secpolicy_userspace_one, DATASET_NAME,
4855             B_FALSE, POOL_CHECK_NONE },
4856         { zfs_ioc_userspace_many, zfs_secpolicy_userspace_many, DATASET_NAME,
4857             B_FALSE, POOL_CHECK_NONE },
4858         { zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
4859             DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4860         { zfs_ioc_hold, zfs_secpolicy_hold, DATASET_NAME, B_TRUE,
4861             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4862         { zfs_ioc_release, zfs_secpolicy_release, DATASET_NAME, B_TRUE,
4863             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4864         { zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4865             POOL_CHECK_SUSPENDED },
4866         { zfs_ioc_objset_recvd_props, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4867             POOL_CHECK_NONE },
4868         { zfs_ioc_vdev_split, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4869             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4870         { zfs_ioc_next_obj, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4871             POOL_CHECK_NONE },
4872         { zfs_ioc_diff, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
4873             POOL_CHECK_NONE },
4874         { zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot, DATASET_NAME,
4875             B_FALSE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY },
4876         { zfs_ioc_obj_to_stats, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
4877             POOL_CHECK_SUSPENDED },
4878         { zfs_ioc_events_next, zfs_secpolicy_config, NO_NAME, B_FALSE,
4879             POOL_CHECK_NONE },
4880         { zfs_ioc_events_clear, zfs_secpolicy_config, NO_NAME, B_FALSE,
4881             POOL_CHECK_NONE },
4882 };
4883
4884 int
4885 pool_status_check(const char *name, zfs_ioc_namecheck_t type,
4886     zfs_ioc_poolcheck_t check)
4887 {
4888         spa_t *spa;
4889         int error;
4890
4891         ASSERT(type == POOL_NAME || type == DATASET_NAME);
4892
4893         if (check & POOL_CHECK_NONE)
4894                 return (0);
4895
4896         error = spa_open(name, &spa, FTAG);
4897         if (error == 0) {
4898                 if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
4899                         error = EAGAIN;
4900                 else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
4901                         error = EROFS;
4902                 spa_close(spa, FTAG);
4903         }
4904         return (error);
4905 }
4906
4907 static void *
4908 zfsdev_get_state_impl(minor_t minor, enum zfsdev_state_type which)
4909 {
4910         zfsdev_state_t *zs;
4911
4912         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
4913
4914         for (zs = list_head(&zfsdev_state_list); zs != NULL;
4915              zs = list_next(&zfsdev_state_list, zs)) {
4916                 if (zs->zs_minor == minor) {
4917                         switch (which) {
4918                                 case ZST_ONEXIT:  return (zs->zs_onexit);
4919                                 case ZST_ZEVENT:  return (zs->zs_zevent);
4920                                 case ZST_ALL:     return (zs);
4921                         }
4922                 }
4923         }
4924
4925         return NULL;
4926 }
4927
4928 void *
4929 zfsdev_get_state(minor_t minor, enum zfsdev_state_type which)
4930 {
4931         void *ptr;
4932
4933         mutex_enter(&zfsdev_state_lock);
4934         ptr = zfsdev_get_state_impl(minor, which);
4935         mutex_exit(&zfsdev_state_lock);
4936
4937         return ptr;
4938 }
4939
4940 minor_t
4941 zfsdev_getminor(struct file *filp)
4942 {
4943         ASSERT(filp != NULL);
4944         ASSERT(filp->private_data != NULL);
4945
4946         return (((zfsdev_state_t *)filp->private_data)->zs_minor);
4947 }
4948
4949 /*
4950  * Find a free minor number.  The zfsdev_state_list is expected to
4951  * be short since it is only a list of currently open file handles.
4952  */
4953 minor_t
4954 zfsdev_minor_alloc(void)
4955 {
4956         static minor_t last_minor = 0;
4957         minor_t m;
4958
4959         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
4960
4961         for (m = last_minor + 1; m != last_minor; m++) {
4962                 if (m > ZFSDEV_MAX_MINOR)
4963                         m = 1;
4964                 if (zfsdev_get_state_impl(m, ZST_ALL) == NULL) {
4965                         last_minor = m;
4966                         return (m);
4967                 }
4968         }
4969
4970         return (0);
4971 }
4972
4973 static int
4974 zfsdev_state_init(struct file *filp)
4975 {
4976         zfsdev_state_t *zs;
4977         minor_t minor;
4978
4979         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
4980
4981         minor = zfsdev_minor_alloc();
4982         if (minor == 0)
4983                 return (ENXIO);
4984
4985         zs = kmem_zalloc( sizeof(zfsdev_state_t), KM_SLEEP);
4986         if (zs == NULL)
4987                 return (ENOMEM);
4988
4989         zs->zs_file = filp;
4990         zs->zs_minor = minor;
4991         filp->private_data = zs;
4992
4993         zfs_onexit_init((zfs_onexit_t **)&zs->zs_onexit);
4994         zfs_zevent_init((zfs_zevent_t **)&zs->zs_zevent);
4995
4996         list_insert_tail(&zfsdev_state_list, zs);
4997
4998         return (0);
4999 }
5000
5001 static int
5002 zfsdev_state_destroy(struct file *filp)
5003 {
5004         zfsdev_state_t *zs;
5005
5006         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
5007         ASSERT(filp->private_data != NULL);
5008
5009         zs = filp->private_data;
5010         zfs_onexit_destroy(zs->zs_onexit);
5011         zfs_zevent_destroy(zs->zs_zevent);
5012
5013         list_remove(&zfsdev_state_list, zs);
5014         kmem_free(zs, sizeof(zfsdev_state_t));
5015
5016         return 0;
5017 }
5018
5019 static int
5020 zfsdev_open(struct inode *ino, struct file *filp)
5021 {
5022         int error;
5023
5024         mutex_enter(&zfsdev_state_lock);
5025         error = zfsdev_state_init(filp);
5026         mutex_exit(&zfsdev_state_lock);
5027
5028         return (-error);
5029 }
5030
5031 static int
5032 zfsdev_release(struct inode *ino, struct file *filp)
5033 {
5034         int error;
5035
5036         mutex_enter(&zfsdev_state_lock);
5037         error = zfsdev_state_destroy(filp);
5038         mutex_exit(&zfsdev_state_lock);
5039
5040         return (-error);
5041 }
5042
5043 static long
5044 zfsdev_ioctl(struct file *filp, unsigned cmd, unsigned long arg)
5045 {
5046         zfs_cmd_t *zc;
5047         uint_t vec;
5048         int error, rc, flag = 0;
5049
5050         vec = cmd - ZFS_IOC;
5051         if (vec >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
5052                 return (-EINVAL);
5053
5054         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
5055
5056         error = ddi_copyin((void *)arg, zc, sizeof (zfs_cmd_t), flag);
5057         if (error != 0)
5058                 error = EFAULT;
5059
5060         if ((error == 0) && !(flag & FKIOCTL))
5061                 error = zfs_ioc_vec[vec].zvec_secpolicy(zc, NULL);
5062
5063         /*
5064          * Ensure that all pool/dataset names are valid before we pass down to
5065          * the lower layers.
5066          */
5067         if (error == 0) {
5068                 zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
5069                 zc->zc_iflags = flag & FKIOCTL;
5070                 switch (zfs_ioc_vec[vec].zvec_namecheck) {
5071                 case POOL_NAME:
5072                         if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
5073                                 error = EINVAL;
5074                         error = pool_status_check(zc->zc_name,
5075                             zfs_ioc_vec[vec].zvec_namecheck,
5076                             zfs_ioc_vec[vec].zvec_pool_check);
5077                         break;
5078
5079                 case DATASET_NAME:
5080                         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
5081                                 error = EINVAL;
5082                         error = pool_status_check(zc->zc_name,
5083                             zfs_ioc_vec[vec].zvec_namecheck,
5084                             zfs_ioc_vec[vec].zvec_pool_check);
5085                         break;
5086
5087                 case NO_NAME:
5088                         break;
5089                 }
5090         }
5091
5092         if (error == 0)
5093                 error = zfs_ioc_vec[vec].zvec_func(zc);
5094
5095         rc = ddi_copyout(zc, (void *)arg, sizeof (zfs_cmd_t), flag);
5096         if (error == 0) {
5097                 if (rc != 0)
5098                         error = EFAULT;
5099                 if (zfs_ioc_vec[vec].zvec_his_log)
5100                         zfs_log_history(zc);
5101         }
5102
5103         kmem_free(zc, sizeof (zfs_cmd_t));
5104         return (-error);
5105 }
5106
5107 #ifdef CONFIG_COMPAT
5108 static long
5109 zfsdev_compat_ioctl(struct file *filp, unsigned cmd, unsigned long arg)
5110 {
5111         return zfsdev_ioctl(filp, cmd, arg);
5112 }
5113 #else
5114 #define zfs_compat_ioctl   NULL
5115 #endif
5116
5117 static const struct file_operations zfsdev_fops = {
5118         .open            = zfsdev_open,
5119         .release         = zfsdev_release,
5120         .unlocked_ioctl  = zfsdev_ioctl,
5121         .compat_ioctl    = zfsdev_compat_ioctl,
5122         .owner           = THIS_MODULE,
5123 };
5124
5125 static struct miscdevice zfs_misc = {
5126         .minor          = MISC_DYNAMIC_MINOR,
5127         .name           = ZFS_DRIVER,
5128         .fops           = &zfsdev_fops,
5129 };
5130
5131 static int
5132 zfs_attach(void)
5133 {
5134         int error;
5135
5136         mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
5137         list_create(&zfsdev_state_list, sizeof (zfsdev_state_t),
5138             offsetof(zfsdev_state_t, zs_next));
5139
5140         error = misc_register(&zfs_misc);
5141         if (error) {
5142                 printk(KERN_INFO "ZFS: misc_register() failed %d\n", error);
5143                 return (error);
5144         }
5145
5146         return (0);
5147 }
5148
5149 static void
5150 zfs_detach(void)
5151 {
5152         int error;
5153
5154         error = misc_deregister(&zfs_misc);
5155         if (error)
5156                 printk(KERN_INFO "ZFS: misc_deregister() failed %d\n", error);
5157
5158         mutex_destroy(&zfsdev_state_lock);
5159         list_destroy(&zfsdev_state_list);
5160 }
5161
5162 #ifdef HAVE_ZPL
5163 uint_t zfs_fsyncer_key;
5164 extern uint_t rrw_tsd_key;
5165 #endif
5166
5167 #ifdef DEBUG
5168 #define ZFS_DEBUG_STR   " (DEBUG mode)"
5169 #else
5170 #define ZFS_DEBUG_STR   ""
5171 #endif
5172
5173 int
5174 _init(void)
5175 {
5176         int error;
5177
5178         spa_init(FREAD | FWRITE);
5179         zfs_init();
5180
5181         if ((error = zvol_init()) != 0)
5182                 goto out1;
5183
5184         if ((error = zfs_attach()) != 0)
5185                 goto out2;
5186
5187 #ifdef HAVE_ZPL
5188         tsd_create(&zfs_fsyncer_key, NULL);
5189         tsd_create(&rrw_tsd_key, NULL);
5190
5191         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
5192 #endif /* HAVE_ZPL */
5193
5194         printk(KERN_NOTICE "ZFS: Loaded ZFS Filesystem v%s%s\n",
5195                ZFS_META_VERSION, ZFS_DEBUG_STR);
5196
5197         return (0);
5198
5199 out2:
5200         (void) zvol_fini();
5201 out1:
5202         zfs_fini();
5203         spa_fini();
5204         printk(KERN_NOTICE "ZFS: Failed to Load ZFS Filesystem v%s%s"
5205                ", rc = %d\n", ZFS_META_VERSION, ZFS_DEBUG_STR, error);
5206
5207         return (error);
5208 }
5209
5210 int
5211 _fini(void)
5212 {
5213         zfs_detach();
5214         zvol_fini();
5215         zfs_fini();
5216         spa_fini();
5217 #ifdef HAVE_ZPL
5218         if (zfs_nfsshare_inited)
5219                 (void) ddi_modclose(nfs_mod);
5220         if (zfs_smbshare_inited)
5221                 (void) ddi_modclose(smbsrv_mod);
5222         if (zfs_nfsshare_inited || zfs_smbshare_inited)
5223                 (void) ddi_modclose(sharefs_mod);
5224
5225         mutex_destroy(&zfs_share_lock);
5226         tsd_destroy(&zfs_fsyncer_key);
5227 #endif /* HAVE_ZPL */
5228
5229         printk(KERN_NOTICE "ZFS: Unloaded ZFS Filesystem v%s%s\n",
5230                ZFS_META_VERSION, ZFS_DEBUG_STR);
5231
5232         return (0);
5233 }
5234
5235 #ifdef HAVE_SPL
5236 spl_module_init(_init);
5237 spl_module_exit(_fini);
5238
5239 MODULE_DESCRIPTION("ZFS");
5240 MODULE_AUTHOR(ZFS_META_AUTHOR);
5241 MODULE_LICENSE(ZFS_META_LICENSE);
5242 #endif /* HAVE_SPL */