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