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