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