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