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