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