]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.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                         if (!dataset_name_hidden(zc->zc_name))
1968                                 (void) dmu_objset_prefetch(zc->zc_name, NULL);
1969                 }
1970         }
1971
1972         do {
1973                 error = dmu_dir_list_next(os,
1974                     sizeof (zc->zc_name) - (p - zc->zc_name), p,
1975                     NULL, &zc->zc_cookie);
1976                 if (error == ENOENT)
1977                         error = ESRCH;
1978         } while (error == 0 && dataset_name_hidden(zc->zc_name) &&
1979             !(zc->zc_iflags & FKIOCTL));
1980         dmu_objset_rele(os, FTAG);
1981
1982         /*
1983          * If it's an internal dataset (ie. with a '$' in its name),
1984          * don't try to get stats for it, otherwise we'll return ENOENT.
1985          */
1986         if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
1987                 error = zfs_ioc_objset_stats(zc); /* fill in the stats */
1988                 if (error == ENOENT) {
1989                         /* We lost a race with destroy, get the next one. */
1990                         zc->zc_name[orig_len] = '\0';
1991                         goto top;
1992                 }
1993         }
1994         return (error);
1995 }
1996
1997 /*
1998  * inputs:
1999  * zc_name              name of filesystem
2000  * zc_cookie            zap cursor
2001  * zc_nvlist_dst_size   size of buffer for property nvlist
2002  *
2003  * outputs:
2004  * zc_name              name of next snapshot
2005  * zc_objset_stats      stats
2006  * zc_nvlist_dst        property nvlist
2007  * zc_nvlist_dst_size   size of property nvlist
2008  */
2009 static int
2010 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2011 {
2012         objset_t *os;
2013         int error;
2014
2015 top:
2016         if (zc->zc_cookie == 0)
2017                 (void) dmu_objset_find(zc->zc_name, dmu_objset_prefetch,
2018                     NULL, DS_FIND_SNAPSHOTS);
2019
2020         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2021         if (error)
2022                 return (error == ENOENT ? ESRCH : error);
2023
2024         /*
2025          * A dataset name of maximum length cannot have any snapshots,
2026          * so exit immediately.
2027          */
2028         if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >= MAXNAMELEN) {
2029                 dmu_objset_rele(os, FTAG);
2030                 return (ESRCH);
2031         }
2032
2033         error = dmu_snapshot_list_next(os,
2034             sizeof (zc->zc_name) - strlen(zc->zc_name),
2035             zc->zc_name + strlen(zc->zc_name), &zc->zc_obj, &zc->zc_cookie,
2036             NULL);
2037
2038         if (error == 0) {
2039                 dsl_dataset_t *ds;
2040                 dsl_pool_t *dp = os->os_dsl_dataset->ds_dir->dd_pool;
2041
2042                 /*
2043                  * Since we probably don't have a hold on this snapshot,
2044                  * it's possible that the objsetid could have been destroyed
2045                  * and reused for a new objset. It's OK if this happens during
2046                  * a zfs send operation, since the new createtxg will be
2047                  * beyond the range we're interested in.
2048                  */
2049                 rw_enter(&dp->dp_config_rwlock, RW_READER);
2050                 error = dsl_dataset_hold_obj(dp, zc->zc_obj, FTAG, &ds);
2051                 rw_exit(&dp->dp_config_rwlock);
2052                 if (error) {
2053                         if (error == ENOENT) {
2054                                 /* Racing with destroy, get the next one. */
2055                                 *strchr(zc->zc_name, '@') = '\0';
2056                                 dmu_objset_rele(os, FTAG);
2057                                 goto top;
2058                         }
2059                 } else {
2060                         objset_t *ossnap;
2061
2062                         error = dmu_objset_from_ds(ds, &ossnap);
2063                         if (error == 0)
2064                                 error = zfs_ioc_objset_stats_impl(zc, ossnap);
2065                         dsl_dataset_rele(ds, FTAG);
2066                 }
2067         } else if (error == ENOENT) {
2068                 error = ESRCH;
2069         }
2070
2071         dmu_objset_rele(os, FTAG);
2072         /* if we failed, undo the @ that we tacked on to zc_name */
2073         if (error)
2074                 *strchr(zc->zc_name, '@') = '\0';
2075         return (error);
2076 }
2077
2078 static int
2079 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2080 {
2081         const char *propname = nvpair_name(pair);
2082         uint64_t *valary;
2083         unsigned int vallen;
2084         const char *domain;
2085         char *dash;
2086         zfs_userquota_prop_t type;
2087         uint64_t rid;
2088         uint64_t quota;
2089         zfsvfs_t *zfsvfs;
2090         int err;
2091
2092         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2093                 nvlist_t *attrs;
2094                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2095                 if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2096                     &pair) != 0)
2097                         return (EINVAL);
2098         }
2099
2100         /*
2101          * A correctly constructed propname is encoded as
2102          * userquota@<rid>-<domain>.
2103          */
2104         if ((dash = strchr(propname, '-')) == NULL ||
2105             nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2106             vallen != 3)
2107                 return (EINVAL);
2108
2109         domain = dash + 1;
2110         type = valary[0];
2111         rid = valary[1];
2112         quota = valary[2];
2113
2114         err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2115         if (err == 0) {
2116                 err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2117                 zfsvfs_rele(zfsvfs, FTAG);
2118         }
2119
2120         return (err);
2121 }
2122
2123 /*
2124  * If the named property is one that has a special function to set its value,
2125  * return 0 on success and a positive error code on failure; otherwise if it is
2126  * not one of the special properties handled by this function, return -1.
2127  *
2128  * XXX: It would be better for callers of the property interface if we handled
2129  * these special cases in dsl_prop.c (in the dsl layer).
2130  */
2131 static int
2132 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2133     nvpair_t *pair)
2134 {
2135         const char *propname = nvpair_name(pair);
2136         zfs_prop_t prop = zfs_name_to_prop(propname);
2137         uint64_t intval;
2138         int err;
2139
2140         if (prop == ZPROP_INVAL) {
2141                 if (zfs_prop_userquota(propname))
2142                         return (zfs_prop_set_userquota(dsname, pair));
2143                 return (-1);
2144         }
2145
2146         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2147                 nvlist_t *attrs;
2148                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2149                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2150                     &pair) == 0);
2151         }
2152
2153         if (zfs_prop_get_type(prop) == PROP_TYPE_STRING)
2154                 return (-1);
2155
2156         VERIFY(0 == nvpair_value_uint64(pair, &intval));
2157
2158         switch (prop) {
2159         case ZFS_PROP_QUOTA:
2160                 err = dsl_dir_set_quota(dsname, source, intval);
2161                 break;
2162         case ZFS_PROP_REFQUOTA:
2163                 err = dsl_dataset_set_quota(dsname, source, intval);
2164                 break;
2165         case ZFS_PROP_RESERVATION:
2166                 err = dsl_dir_set_reservation(dsname, source, intval);
2167                 break;
2168         case ZFS_PROP_REFRESERVATION:
2169                 err = dsl_dataset_set_reservation(dsname, source, intval);
2170                 break;
2171         case ZFS_PROP_VOLSIZE:
2172                 err = zvol_set_volsize(dsname, ddi_driver_major(zfs_dip),
2173                     intval);
2174                 break;
2175         case ZFS_PROP_VERSION:
2176         {
2177                 zfsvfs_t *zfsvfs;
2178
2179                 if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2180                         break;
2181
2182                 err = zfs_set_version(zfsvfs, intval);
2183                 zfsvfs_rele(zfsvfs, FTAG);
2184
2185                 if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2186                         zfs_cmd_t *zc;
2187
2188                         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2189                         (void) strcpy(zc->zc_name, dsname);
2190                         (void) zfs_ioc_userspace_upgrade(zc);
2191                         kmem_free(zc, sizeof (zfs_cmd_t));
2192                 }
2193                 break;
2194         }
2195
2196         default:
2197                 err = -1;
2198         }
2199
2200         return (err);
2201 }
2202
2203 /*
2204  * This function is best effort. If it fails to set any of the given properties,
2205  * it continues to set as many as it can and returns the first error
2206  * encountered. If the caller provides a non-NULL errlist, it also gives the
2207  * complete list of names of all the properties it failed to set along with the
2208  * corresponding error numbers. The caller is responsible for freeing the
2209  * returned errlist.
2210  *
2211  * If every property is set successfully, zero is returned and the list pointed
2212  * at by errlist is NULL.
2213  */
2214 int
2215 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
2216     nvlist_t **errlist)
2217 {
2218         nvpair_t *pair;
2219         nvpair_t *propval;
2220         int rv = 0;
2221         uint64_t intval;
2222         char *strval;
2223         nvlist_t *genericnvl;
2224         nvlist_t *errors;
2225         nvlist_t *retrynvl;
2226
2227         VERIFY(nvlist_alloc(&genericnvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2228         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2229         VERIFY(nvlist_alloc(&retrynvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2230
2231 retry:
2232         pair = NULL;
2233         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2234                 const char *propname = nvpair_name(pair);
2235                 zfs_prop_t prop = zfs_name_to_prop(propname);
2236                 int err = 0;
2237
2238                 /* decode the property value */
2239                 propval = pair;
2240                 if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2241                         nvlist_t *attrs;
2242                         VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2243                         if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2244                             &propval) != 0)
2245                                 err = EINVAL;
2246                 }
2247
2248                 /* Validate value type */
2249                 if (err == 0 && prop == ZPROP_INVAL) {
2250                         if (zfs_prop_user(propname)) {
2251                                 if (nvpair_type(propval) != DATA_TYPE_STRING)
2252                                         err = EINVAL;
2253                         } else if (zfs_prop_userquota(propname)) {
2254                                 if (nvpair_type(propval) !=
2255                                     DATA_TYPE_UINT64_ARRAY)
2256                                         err = EINVAL;
2257                         }
2258                 } else if (err == 0) {
2259                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2260                                 if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
2261                                         err = EINVAL;
2262                         } else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
2263                                 const char *unused;
2264
2265                                 VERIFY(nvpair_value_uint64(propval,
2266                                     &intval) == 0);
2267
2268                                 switch (zfs_prop_get_type(prop)) {
2269                                 case PROP_TYPE_NUMBER:
2270                                         break;
2271                                 case PROP_TYPE_STRING:
2272                                         err = EINVAL;
2273                                         break;
2274                                 case PROP_TYPE_INDEX:
2275                                         if (zfs_prop_index_to_string(prop,
2276                                             intval, &unused) != 0)
2277                                                 err = EINVAL;
2278                                         break;
2279                                 default:
2280                                         cmn_err(CE_PANIC,
2281                                             "unknown property type");
2282                                 }
2283                         } else {
2284                                 err = EINVAL;
2285                         }
2286                 }
2287
2288                 /* Validate permissions */
2289                 if (err == 0)
2290                         err = zfs_check_settable(dsname, pair, CRED());
2291
2292                 if (err == 0) {
2293                         err = zfs_prop_set_special(dsname, source, pair);
2294                         if (err == -1) {
2295                                 /*
2296                                  * For better performance we build up a list of
2297                                  * properties to set in a single transaction.
2298                                  */
2299                                 err = nvlist_add_nvpair(genericnvl, pair);
2300                         } else if (err != 0 && nvl != retrynvl) {
2301                                 /*
2302                                  * This may be a spurious error caused by
2303                                  * receiving quota and reservation out of order.
2304                                  * Try again in a second pass.
2305                                  */
2306                                 err = nvlist_add_nvpair(retrynvl, pair);
2307                         }
2308                 }
2309
2310                 if (err != 0)
2311                         VERIFY(nvlist_add_int32(errors, propname, err) == 0);
2312         }
2313
2314         if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
2315                 nvl = retrynvl;
2316                 goto retry;
2317         }
2318
2319         if (!nvlist_empty(genericnvl) &&
2320             dsl_props_set(dsname, source, genericnvl) != 0) {
2321                 /*
2322                  * If this fails, we still want to set as many properties as we
2323                  * can, so try setting them individually.
2324                  */
2325                 pair = NULL;
2326                 while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
2327                         const char *propname = nvpair_name(pair);
2328                         int err = 0;
2329
2330                         propval = pair;
2331                         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2332                                 nvlist_t *attrs;
2333                                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2334                                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2335                                     &propval) == 0);
2336                         }
2337
2338                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2339                                 VERIFY(nvpair_value_string(propval,
2340                                     &strval) == 0);
2341                                 err = dsl_prop_set(dsname, propname, source, 1,
2342                                     strlen(strval) + 1, strval);
2343                         } else {
2344                                 VERIFY(nvpair_value_uint64(propval,
2345                                     &intval) == 0);
2346                                 err = dsl_prop_set(dsname, propname, source, 8,
2347                                     1, &intval);
2348                         }
2349
2350                         if (err != 0) {
2351                                 VERIFY(nvlist_add_int32(errors, propname,
2352                                     err) == 0);
2353                         }
2354                 }
2355         }
2356         nvlist_free(genericnvl);
2357         nvlist_free(retrynvl);
2358
2359         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
2360                 nvlist_free(errors);
2361                 errors = NULL;
2362         } else {
2363                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
2364         }
2365
2366         if (errlist == NULL)
2367                 nvlist_free(errors);
2368         else
2369                 *errlist = errors;
2370
2371         return (rv);
2372 }
2373
2374 /*
2375  * Check that all the properties are valid user properties.
2376  */
2377 static int
2378 zfs_check_userprops(char *fsname, nvlist_t *nvl)
2379 {
2380         nvpair_t *pair = NULL;
2381         int error = 0;
2382
2383         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2384                 const char *propname = nvpair_name(pair);
2385                 char *valstr;
2386
2387                 if (!zfs_prop_user(propname) ||
2388                     nvpair_type(pair) != DATA_TYPE_STRING)
2389                         return (EINVAL);
2390
2391                 if (error = zfs_secpolicy_write_perms(fsname,
2392                     ZFS_DELEG_PERM_USERPROP, CRED()))
2393                         return (error);
2394
2395                 if (strlen(propname) >= ZAP_MAXNAMELEN)
2396                         return (ENAMETOOLONG);
2397
2398                 VERIFY(nvpair_value_string(pair, &valstr) == 0);
2399                 if (strlen(valstr) >= ZAP_MAXVALUELEN)
2400                         return (E2BIG);
2401         }
2402         return (0);
2403 }
2404
2405 static void
2406 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
2407 {
2408         nvpair_t *pair;
2409
2410         VERIFY(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2411
2412         pair = NULL;
2413         while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
2414                 if (nvlist_exists(skipped, nvpair_name(pair)))
2415                         continue;
2416
2417                 VERIFY(nvlist_add_nvpair(*newprops, pair) == 0);
2418         }
2419 }
2420
2421 static int
2422 clear_received_props(objset_t *os, const char *fs, nvlist_t *props,
2423     nvlist_t *skipped)
2424 {
2425         int err = 0;
2426         nvlist_t *cleared_props = NULL;
2427         props_skip(props, skipped, &cleared_props);
2428         if (!nvlist_empty(cleared_props)) {
2429                 /*
2430                  * Acts on local properties until the dataset has received
2431                  * properties at least once on or after SPA_VERSION_RECVD_PROPS.
2432                  */
2433                 zprop_source_t flags = (ZPROP_SRC_NONE |
2434                     (dsl_prop_get_hasrecvd(os) ? ZPROP_SRC_RECEIVED : 0));
2435                 err = zfs_set_prop_nvlist(fs, flags, cleared_props, NULL);
2436         }
2437         nvlist_free(cleared_props);
2438         return (err);
2439 }
2440
2441 /*
2442  * inputs:
2443  * zc_name              name of filesystem
2444  * zc_value             name of property to set
2445  * zc_nvlist_src{_size} nvlist of properties to apply
2446  * zc_cookie            received properties flag
2447  *
2448  * outputs:
2449  * zc_nvlist_dst{_size} error for each unapplied received property
2450  */
2451 static int
2452 zfs_ioc_set_prop(zfs_cmd_t *zc)
2453 {
2454         nvlist_t *nvl;
2455         boolean_t received = zc->zc_cookie;
2456         zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
2457             ZPROP_SRC_LOCAL);
2458         nvlist_t *errors = NULL;
2459         int error;
2460
2461         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2462             zc->zc_iflags, &nvl)) != 0)
2463                 return (error);
2464
2465         if (received) {
2466                 nvlist_t *origprops;
2467                 objset_t *os;
2468
2469                 if (dmu_objset_hold(zc->zc_name, FTAG, &os) == 0) {
2470                         if (dsl_prop_get_received(os, &origprops) == 0) {
2471                                 (void) clear_received_props(os,
2472                                     zc->zc_name, origprops, nvl);
2473                                 nvlist_free(origprops);
2474                         }
2475
2476                         dsl_prop_set_hasrecvd(os);
2477                         dmu_objset_rele(os, FTAG);
2478                 }
2479         }
2480
2481         error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, &errors);
2482
2483         if (zc->zc_nvlist_dst != 0 && errors != NULL) {
2484                 (void) put_nvlist(zc, errors);
2485         }
2486
2487         nvlist_free(errors);
2488         nvlist_free(nvl);
2489         return (error);
2490 }
2491
2492 /*
2493  * inputs:
2494  * zc_name              name of filesystem
2495  * zc_value             name of property to inherit
2496  * zc_cookie            revert to received value if TRUE
2497  *
2498  * outputs:             none
2499  */
2500 static int
2501 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
2502 {
2503         const char *propname = zc->zc_value;
2504         zfs_prop_t prop = zfs_name_to_prop(propname);
2505         boolean_t received = zc->zc_cookie;
2506         zprop_source_t source = (received
2507             ? ZPROP_SRC_NONE            /* revert to received value, if any */
2508             : ZPROP_SRC_INHERITED);     /* explicitly inherit */
2509
2510         if (received) {
2511                 nvlist_t *dummy;
2512                 nvpair_t *pair;
2513                 zprop_type_t type;
2514                 int err;
2515
2516                 /*
2517                  * zfs_prop_set_special() expects properties in the form of an
2518                  * nvpair with type info.
2519                  */
2520                 if (prop == ZPROP_INVAL) {
2521                         if (!zfs_prop_user(propname))
2522                                 return (EINVAL);
2523
2524                         type = PROP_TYPE_STRING;
2525                 } else if (prop == ZFS_PROP_VOLSIZE ||
2526                     prop == ZFS_PROP_VERSION) {
2527                         return (EINVAL);
2528                 } else {
2529                         type = zfs_prop_get_type(prop);
2530                 }
2531
2532                 VERIFY(nvlist_alloc(&dummy, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2533
2534                 switch (type) {
2535                 case PROP_TYPE_STRING:
2536                         VERIFY(0 == nvlist_add_string(dummy, propname, ""));
2537                         break;
2538                 case PROP_TYPE_NUMBER:
2539                 case PROP_TYPE_INDEX:
2540                         VERIFY(0 == nvlist_add_uint64(dummy, propname, 0));
2541                         break;
2542                 default:
2543                         nvlist_free(dummy);
2544                         return (EINVAL);
2545                 }
2546
2547                 pair = nvlist_next_nvpair(dummy, NULL);
2548                 err = zfs_prop_set_special(zc->zc_name, source, pair);
2549                 nvlist_free(dummy);
2550                 if (err != -1)
2551                         return (err); /* special property already handled */
2552         } else {
2553                 /*
2554                  * Only check this in the non-received case. We want to allow
2555                  * 'inherit -S' to revert non-inheritable properties like quota
2556                  * and reservation to the received or default values even though
2557                  * they are not considered inheritable.
2558                  */
2559                 if (prop != ZPROP_INVAL && !zfs_prop_inheritable(prop))
2560                         return (EINVAL);
2561         }
2562
2563         /* the property name has been validated by zfs_secpolicy_inherit() */
2564         return (dsl_prop_set(zc->zc_name, zc->zc_value, source, 0, 0, NULL));
2565 }
2566
2567 static int
2568 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
2569 {
2570         nvlist_t *props;
2571         spa_t *spa;
2572         int error;
2573         nvpair_t *pair;
2574
2575         if (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2576             zc->zc_iflags, &props))
2577                 return (error);
2578
2579         /*
2580          * If the only property is the configfile, then just do a spa_lookup()
2581          * to handle the faulted case.
2582          */
2583         pair = nvlist_next_nvpair(props, NULL);
2584         if (pair != NULL && strcmp(nvpair_name(pair),
2585             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
2586             nvlist_next_nvpair(props, pair) == NULL) {
2587                 mutex_enter(&spa_namespace_lock);
2588                 if ((spa = spa_lookup(zc->zc_name)) != NULL) {
2589                         spa_configfile_set(spa, props, B_FALSE);
2590                         spa_config_sync(spa, B_FALSE, B_TRUE);
2591                 }
2592                 mutex_exit(&spa_namespace_lock);
2593                 if (spa != NULL) {
2594                         nvlist_free(props);
2595                         return (0);
2596                 }
2597         }
2598
2599         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2600                 nvlist_free(props);
2601                 return (error);
2602         }
2603
2604         error = spa_prop_set(spa, props);
2605
2606         nvlist_free(props);
2607         spa_close(spa, FTAG);
2608
2609         return (error);
2610 }
2611
2612 static int
2613 zfs_ioc_pool_get_props(zfs_cmd_t *zc)
2614 {
2615         spa_t *spa;
2616         int error;
2617         nvlist_t *nvp = NULL;
2618
2619         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2620                 /*
2621                  * If the pool is faulted, there may be properties we can still
2622                  * get (such as altroot and cachefile), so attempt to get them
2623                  * anyway.
2624                  */
2625                 mutex_enter(&spa_namespace_lock);
2626                 if ((spa = spa_lookup(zc->zc_name)) != NULL)
2627                         error = spa_prop_get(spa, &nvp);
2628                 mutex_exit(&spa_namespace_lock);
2629         } else {
2630                 error = spa_prop_get(spa, &nvp);
2631                 spa_close(spa, FTAG);
2632         }
2633
2634         if (error == 0 && zc->zc_nvlist_dst != 0)
2635                 error = put_nvlist(zc, nvp);
2636         else
2637                 error = EFAULT;
2638
2639         nvlist_free(nvp);
2640         return (error);
2641 }
2642
2643 /*
2644  * inputs:
2645  * zc_name              name of filesystem
2646  * zc_nvlist_src{_size} nvlist of delegated permissions
2647  * zc_perm_action       allow/unallow flag
2648  *
2649  * outputs:             none
2650  */
2651 static int
2652 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
2653 {
2654         int error;
2655         nvlist_t *fsaclnv = NULL;
2656
2657         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2658             zc->zc_iflags, &fsaclnv)) != 0)
2659                 return (error);
2660
2661         /*
2662          * Verify nvlist is constructed correctly
2663          */
2664         if ((error = zfs_deleg_verify_nvlist(fsaclnv)) != 0) {
2665                 nvlist_free(fsaclnv);
2666                 return (EINVAL);
2667         }
2668
2669         /*
2670          * If we don't have PRIV_SYS_MOUNT, then validate
2671          * that user is allowed to hand out each permission in
2672          * the nvlist(s)
2673          */
2674
2675         error = secpolicy_zfs(CRED());
2676         if (error) {
2677                 if (zc->zc_perm_action == B_FALSE) {
2678                         error = dsl_deleg_can_allow(zc->zc_name,
2679                             fsaclnv, CRED());
2680                 } else {
2681                         error = dsl_deleg_can_unallow(zc->zc_name,
2682                             fsaclnv, CRED());
2683                 }
2684         }
2685
2686         if (error == 0)
2687                 error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
2688
2689         nvlist_free(fsaclnv);
2690         return (error);
2691 }
2692
2693 /*
2694  * inputs:
2695  * zc_name              name of filesystem
2696  *
2697  * outputs:
2698  * zc_nvlist_src{_size} nvlist of delegated permissions
2699  */
2700 static int
2701 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
2702 {
2703         nvlist_t *nvp;
2704         int error;
2705
2706         if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
2707                 error = put_nvlist(zc, nvp);
2708                 nvlist_free(nvp);
2709         }
2710
2711         return (error);
2712 }
2713
2714 /*
2715  * Search the vfs list for a specified resource.  Returns a pointer to it
2716  * or NULL if no suitable entry is found. The caller of this routine
2717  * is responsible for releasing the returned vfs pointer.
2718  */
2719 static vfs_t *
2720 zfs_get_vfs(const char *resource)
2721 {
2722         vfs_t *vfsp;
2723
2724         mtx_lock(&mountlist_mtx);
2725         TAILQ_FOREACH(vfsp, &mountlist, mnt_list) {
2726                 if (strcmp(refstr_value(vfsp->vfs_resource), resource) == 0) {
2727                         VFS_HOLD(vfsp);
2728                         break;
2729                 }
2730         }
2731         mtx_unlock(&mountlist_mtx);
2732         return (vfsp);
2733 }
2734
2735 /* ARGSUSED */
2736 static void
2737 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
2738 {
2739         zfs_creat_t *zct = arg;
2740
2741         zfs_create_fs(os, cr, zct->zct_zplprops, tx);
2742 }
2743
2744 #define ZFS_PROP_UNDEFINED      ((uint64_t)-1)
2745
2746 /*
2747  * inputs:
2748  * createprops          list of properties requested by creator
2749  * default_zplver       zpl version to use if unspecified in createprops
2750  * fuids_ok             fuids allowed in this version of the spa?
2751  * os                   parent objset pointer (NULL if root fs)
2752  *
2753  * outputs:
2754  * zplprops     values for the zplprops we attach to the master node object
2755  * is_ci        true if requested file system will be purely case-insensitive
2756  *
2757  * Determine the settings for utf8only, normalization and
2758  * casesensitivity.  Specific values may have been requested by the
2759  * creator and/or we can inherit values from the parent dataset.  If
2760  * the file system is of too early a vintage, a creator can not
2761  * request settings for these properties, even if the requested
2762  * setting is the default value.  We don't actually want to create dsl
2763  * properties for these, so remove them from the source nvlist after
2764  * processing.
2765  */
2766 static int
2767 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
2768     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
2769     nvlist_t *zplprops, boolean_t *is_ci)
2770 {
2771         uint64_t sense = ZFS_PROP_UNDEFINED;
2772         uint64_t norm = ZFS_PROP_UNDEFINED;
2773         uint64_t u8 = ZFS_PROP_UNDEFINED;
2774
2775         ASSERT(zplprops != NULL);
2776
2777         /*
2778          * Pull out creator prop choices, if any.
2779          */
2780         if (createprops) {
2781                 (void) nvlist_lookup_uint64(createprops,
2782                     zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
2783                 (void) nvlist_lookup_uint64(createprops,
2784                     zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
2785                 (void) nvlist_remove_all(createprops,
2786                     zfs_prop_to_name(ZFS_PROP_NORMALIZE));
2787                 (void) nvlist_lookup_uint64(createprops,
2788                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
2789                 (void) nvlist_remove_all(createprops,
2790                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
2791                 (void) nvlist_lookup_uint64(createprops,
2792                     zfs_prop_to_name(ZFS_PROP_CASE), &sense);
2793                 (void) nvlist_remove_all(createprops,
2794                     zfs_prop_to_name(ZFS_PROP_CASE));
2795         }
2796
2797         /*
2798          * If the zpl version requested is whacky or the file system
2799          * or pool is version is too "young" to support normalization
2800          * and the creator tried to set a value for one of the props,
2801          * error out.
2802          */
2803         if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
2804             (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
2805             (zplver >= ZPL_VERSION_SA && !sa_ok) ||
2806             (zplver < ZPL_VERSION_NORMALIZATION &&
2807             (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
2808             sense != ZFS_PROP_UNDEFINED)))
2809                 return (ENOTSUP);
2810
2811         /*
2812          * Put the version in the zplprops
2813          */
2814         VERIFY(nvlist_add_uint64(zplprops,
2815             zfs_prop_to_name(ZFS_PROP_VERSION), zplver) == 0);
2816
2817         if (norm == ZFS_PROP_UNDEFINED)
2818                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm) == 0);
2819         VERIFY(nvlist_add_uint64(zplprops,
2820             zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm) == 0);
2821
2822         /*
2823          * If we're normalizing, names must always be valid UTF-8 strings.
2824          */
2825         if (norm)
2826                 u8 = 1;
2827         if (u8 == ZFS_PROP_UNDEFINED)
2828                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8) == 0);
2829         VERIFY(nvlist_add_uint64(zplprops,
2830             zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8) == 0);
2831
2832         if (sense == ZFS_PROP_UNDEFINED)
2833                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_CASE, &sense) == 0);
2834         VERIFY(nvlist_add_uint64(zplprops,
2835             zfs_prop_to_name(ZFS_PROP_CASE), sense) == 0);
2836
2837         if (is_ci)
2838                 *is_ci = (sense == ZFS_CASE_INSENSITIVE);
2839
2840         return (0);
2841 }
2842
2843 static int
2844 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
2845     nvlist_t *zplprops, boolean_t *is_ci)
2846 {
2847         boolean_t fuids_ok, sa_ok;
2848         uint64_t zplver = ZPL_VERSION;
2849         objset_t *os = NULL;
2850         char parentname[MAXNAMELEN];
2851         char *cp;
2852         spa_t *spa;
2853         uint64_t spa_vers;
2854         int error;
2855
2856         (void) strlcpy(parentname, dataset, sizeof (parentname));
2857         cp = strrchr(parentname, '/');
2858         ASSERT(cp != NULL);
2859         cp[0] = '\0';
2860
2861         if ((error = spa_open(dataset, &spa, FTAG)) != 0)
2862                 return (error);
2863
2864         spa_vers = spa_version(spa);
2865         spa_close(spa, FTAG);
2866
2867         zplver = zfs_zpl_version_map(spa_vers);
2868         fuids_ok = (zplver >= ZPL_VERSION_FUID);
2869         sa_ok = (zplver >= ZPL_VERSION_SA);
2870
2871         /*
2872          * Open parent object set so we can inherit zplprop values.
2873          */
2874         if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
2875                 return (error);
2876
2877         error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
2878             zplprops, is_ci);
2879         dmu_objset_rele(os, FTAG);
2880         return (error);
2881 }
2882
2883 static int
2884 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
2885     nvlist_t *zplprops, boolean_t *is_ci)
2886 {
2887         boolean_t fuids_ok;
2888         boolean_t sa_ok;
2889         uint64_t zplver = ZPL_VERSION;
2890         int error;
2891
2892         zplver = zfs_zpl_version_map(spa_vers);
2893         fuids_ok = (zplver >= ZPL_VERSION_FUID);
2894         sa_ok = (zplver >= ZPL_VERSION_SA);
2895
2896         error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
2897             createprops, zplprops, is_ci);
2898         return (error);
2899 }
2900
2901 /*
2902  * inputs:
2903  * zc_objset_type       type of objset to create (fs vs zvol)
2904  * zc_name              name of new objset
2905  * zc_value             name of snapshot to clone from (may be empty)
2906  * zc_nvlist_src{_size} nvlist of properties to apply
2907  *
2908  * outputs: none
2909  */
2910 static int
2911 zfs_ioc_create(zfs_cmd_t *zc)
2912 {
2913         objset_t *clone;
2914         int error = 0;
2915         zfs_creat_t zct;
2916         nvlist_t *nvprops = NULL;
2917         void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
2918         dmu_objset_type_t type = zc->zc_objset_type;
2919
2920         switch (type) {
2921
2922         case DMU_OST_ZFS:
2923                 cbfunc = zfs_create_cb;
2924                 break;
2925
2926         case DMU_OST_ZVOL:
2927                 cbfunc = zvol_create_cb;
2928                 break;
2929
2930         default:
2931                 cbfunc = NULL;
2932                 break;
2933         }
2934         if (strchr(zc->zc_name, '@') ||
2935             strchr(zc->zc_name, '%'))
2936                 return (EINVAL);
2937
2938         if (zc->zc_nvlist_src != 0 &&
2939             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2940             zc->zc_iflags, &nvprops)) != 0)
2941                 return (error);
2942
2943         zct.zct_zplprops = NULL;
2944         zct.zct_props = nvprops;
2945
2946         if (zc->zc_value[0] != '\0') {
2947                 /*
2948                  * We're creating a clone of an existing snapshot.
2949                  */
2950                 zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
2951                 if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0) {
2952                         nvlist_free(nvprops);
2953                         return (EINVAL);
2954                 }
2955
2956                 error = dmu_objset_hold(zc->zc_value, FTAG, &clone);
2957                 if (error) {
2958                         nvlist_free(nvprops);
2959                         return (error);
2960                 }
2961
2962                 error = dmu_objset_clone(zc->zc_name, dmu_objset_ds(clone), 0);
2963                 dmu_objset_rele(clone, FTAG);
2964                 if (error) {
2965                         nvlist_free(nvprops);
2966                         return (error);
2967                 }
2968         } else {
2969                 boolean_t is_insensitive = B_FALSE;
2970
2971                 if (cbfunc == NULL) {
2972                         nvlist_free(nvprops);
2973                         return (EINVAL);
2974                 }
2975
2976                 if (type == DMU_OST_ZVOL) {
2977                         uint64_t volsize, volblocksize;
2978
2979                         if (nvprops == NULL ||
2980                             nvlist_lookup_uint64(nvprops,
2981                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
2982                             &volsize) != 0) {
2983                                 nvlist_free(nvprops);
2984                                 return (EINVAL);
2985                         }
2986
2987                         if ((error = nvlist_lookup_uint64(nvprops,
2988                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
2989                             &volblocksize)) != 0 && error != ENOENT) {
2990                                 nvlist_free(nvprops);
2991                                 return (EINVAL);
2992                         }
2993
2994                         if (error != 0)
2995                                 volblocksize = zfs_prop_default_numeric(
2996                                     ZFS_PROP_VOLBLOCKSIZE);
2997
2998                         if ((error = zvol_check_volblocksize(
2999                             volblocksize)) != 0 ||
3000                             (error = zvol_check_volsize(volsize,
3001                             volblocksize)) != 0) {
3002                                 nvlist_free(nvprops);
3003                                 return (error);
3004                         }
3005                 } else if (type == DMU_OST_ZFS) {
3006                         int error;
3007
3008                         /*
3009                          * We have to have normalization and
3010                          * case-folding flags correct when we do the
3011                          * file system creation, so go figure them out
3012                          * now.
3013                          */
3014                         VERIFY(nvlist_alloc(&zct.zct_zplprops,
3015                             NV_UNIQUE_NAME, KM_SLEEP) == 0);
3016                         error = zfs_fill_zplprops(zc->zc_name, nvprops,
3017                             zct.zct_zplprops, &is_insensitive);
3018                         if (error != 0) {
3019                                 nvlist_free(nvprops);
3020                                 nvlist_free(zct.zct_zplprops);
3021                                 return (error);
3022                         }
3023                 }
3024                 error = dmu_objset_create(zc->zc_name, type,
3025                     is_insensitive ? DS_FLAG_CI_DATASET : 0, cbfunc, &zct);
3026                 nvlist_free(zct.zct_zplprops);
3027         }
3028
3029         /*
3030          * It would be nice to do this atomically.
3031          */
3032         if (error == 0) {
3033                 error = zfs_set_prop_nvlist(zc->zc_name, ZPROP_SRC_LOCAL,
3034                     nvprops, NULL);
3035                 if (error != 0)
3036                         (void) dmu_objset_destroy(zc->zc_name, B_FALSE);
3037         }
3038         nvlist_free(nvprops);
3039 #ifdef __FreeBSD__
3040         if (error == 0 && type == DMU_OST_ZVOL)
3041                 zvol_create_minors(zc->zc_name);
3042 #endif
3043         return (error);
3044 }
3045
3046 /*
3047  * inputs:
3048  * zc_name      name of filesystem
3049  * zc_value     short name of snapshot
3050  * zc_cookie    recursive flag
3051  * zc_nvlist_src[_size] property list
3052  *
3053  * outputs:
3054  * zc_value     short snapname (i.e. part after the '@')
3055  */
3056 static int
3057 zfs_ioc_snapshot(zfs_cmd_t *zc)
3058 {
3059         nvlist_t *nvprops = NULL;
3060         int error;
3061         boolean_t recursive = zc->zc_cookie;
3062
3063         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
3064                 return (EINVAL);
3065
3066         if (zc->zc_nvlist_src != 0 &&
3067             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3068             zc->zc_iflags, &nvprops)) != 0)
3069                 return (error);
3070
3071         error = zfs_check_userprops(zc->zc_name, nvprops);
3072         if (error)
3073                 goto out;
3074
3075         if (!nvlist_empty(nvprops) &&
3076             zfs_earlier_version(zc->zc_name, SPA_VERSION_SNAP_PROPS)) {
3077                 error = ENOTSUP;
3078                 goto out;
3079         }
3080
3081         error = dmu_objset_snapshot(zc->zc_name, zc->zc_value, NULL,
3082             nvprops, recursive, B_FALSE, -1);
3083
3084 out:
3085         nvlist_free(nvprops);
3086         return (error);
3087 }
3088
3089 int
3090 zfs_unmount_snap(const char *name, void *arg)
3091 {
3092         vfs_t *vfsp = NULL;
3093
3094         if (arg) {
3095                 char *snapname = arg;
3096                 char *fullname = kmem_asprintf("%s@%s", name, snapname);
3097                 vfsp = zfs_get_vfs(fullname);
3098                 strfree(fullname);
3099         } else if (strchr(name, '@')) {
3100                 vfsp = zfs_get_vfs(name);
3101         }
3102
3103         if (vfsp) {
3104                 /*
3105                  * Always force the unmount for snapshots.
3106                  */
3107                 int flag = MS_FORCE;
3108                 int err;
3109
3110                 if ((err = vn_vfswlock(vfsp->vfs_vnodecovered)) != 0) {
3111                         VFS_RELE(vfsp);
3112                         return (err);
3113                 }
3114                 VFS_RELE(vfsp);
3115                 mtx_lock(&Giant);       /* dounmount() */
3116                 dounmount(vfsp, flag, curthread);
3117                 mtx_unlock(&Giant);     /* dounmount() */
3118         }
3119         return (0);
3120 }
3121
3122 /*
3123  * inputs:
3124  * zc_name              name of filesystem
3125  * zc_value             short name of snapshot
3126  * zc_defer_destroy     mark for deferred destroy
3127  *
3128  * outputs:     none
3129  */
3130 static int
3131 zfs_ioc_destroy_snaps(zfs_cmd_t *zc)
3132 {
3133         int err;
3134
3135         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
3136                 return (EINVAL);
3137         err = dmu_objset_find(zc->zc_name,
3138             zfs_unmount_snap, zc->zc_value, DS_FIND_CHILDREN);
3139         if (err)
3140                 return (err);
3141         return (dmu_snapshots_destroy(zc->zc_name, zc->zc_value,
3142             zc->zc_defer_destroy));
3143 }
3144
3145 /*
3146  * inputs:
3147  * zc_name              name of dataset to destroy
3148  * zc_objset_type       type of objset
3149  * zc_defer_destroy     mark for deferred destroy
3150  *
3151  * outputs:             none
3152  */
3153 static int
3154 zfs_ioc_destroy(zfs_cmd_t *zc)
3155 {
3156         int err;
3157         if (strchr(zc->zc_name, '@') && zc->zc_objset_type == DMU_OST_ZFS) {
3158                 err = zfs_unmount_snap(zc->zc_name, NULL);
3159                 if (err)
3160                         return (err);
3161         }
3162
3163         err = dmu_objset_destroy(zc->zc_name, zc->zc_defer_destroy);
3164         if (zc->zc_objset_type == DMU_OST_ZVOL && err == 0)
3165                 (void) zvol_remove_minor(zc->zc_name);
3166         return (err);
3167 }
3168
3169 /*
3170  * inputs:
3171  * zc_name      name of dataset to rollback (to most recent snapshot)
3172  *
3173  * outputs:     none
3174  */
3175 static int
3176 zfs_ioc_rollback(zfs_cmd_t *zc)
3177 {
3178         dsl_dataset_t *ds, *clone;
3179         int error;
3180         zfsvfs_t *zfsvfs;
3181         char *clone_name;
3182
3183         error = dsl_dataset_hold(zc->zc_name, FTAG, &ds);
3184         if (error)
3185                 return (error);
3186
3187         /* must not be a snapshot */
3188         if (dsl_dataset_is_snapshot(ds)) {
3189                 dsl_dataset_rele(ds, FTAG);
3190                 return (EINVAL);
3191         }
3192
3193         /* must have a most recent snapshot */
3194         if (ds->ds_phys->ds_prev_snap_txg < TXG_INITIAL) {
3195                 dsl_dataset_rele(ds, FTAG);
3196                 return (EINVAL);
3197         }
3198
3199         /*
3200          * Create clone of most recent snapshot.
3201          */
3202         clone_name = kmem_asprintf("%s/%%rollback", zc->zc_name);
3203         error = dmu_objset_clone(clone_name, ds->ds_prev, DS_FLAG_INCONSISTENT);
3204         if (error)
3205                 goto out;
3206
3207         error = dsl_dataset_own(clone_name, B_TRUE, FTAG, &clone);
3208         if (error)
3209                 goto out;
3210
3211         /*
3212          * Do clone swap.
3213          */
3214         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
3215                 error = zfs_suspend_fs(zfsvfs);
3216                 if (error == 0) {
3217                         int resume_err;
3218
3219                         if (dsl_dataset_tryown(ds, B_FALSE, FTAG)) {
3220                                 error = dsl_dataset_clone_swap(clone, ds,
3221                                     B_TRUE);
3222                                 dsl_dataset_disown(ds, FTAG);
3223                                 ds = NULL;
3224                         } else {
3225                                 error = EBUSY;
3226                         }
3227                         resume_err = zfs_resume_fs(zfsvfs, zc->zc_name);
3228                         error = error ? error : resume_err;
3229                 }
3230                 VFS_RELE(zfsvfs->z_vfs);
3231         } else {
3232                 if (dsl_dataset_tryown(ds, B_FALSE, FTAG)) {
3233                         error = dsl_dataset_clone_swap(clone, ds, B_TRUE);
3234                         dsl_dataset_disown(ds, FTAG);
3235                         ds = NULL;
3236                 } else {
3237                         error = EBUSY;
3238                 }
3239         }
3240
3241         /*
3242          * Destroy clone (which also closes it).
3243          */
3244         (void) dsl_dataset_destroy(clone, FTAG, B_FALSE);
3245
3246 out:
3247         strfree(clone_name);
3248         if (ds)
3249                 dsl_dataset_rele(ds, FTAG);
3250         return (error);
3251 }
3252
3253 /*
3254  * inputs:
3255  * zc_name      old name of dataset
3256  * zc_value     new name of dataset
3257  * zc_cookie    recursive flag (only valid for snapshots)
3258  *
3259  * outputs:     none
3260  */
3261 static int
3262 zfs_ioc_rename(zfs_cmd_t *zc)
3263 {
3264         boolean_t recursive = zc->zc_cookie & 1;
3265
3266         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3267         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3268             strchr(zc->zc_value, '%'))
3269                 return (EINVAL);
3270
3271         /*
3272          * Unmount snapshot unless we're doing a recursive rename,
3273          * in which case the dataset code figures out which snapshots
3274          * to unmount.
3275          */
3276         if (!recursive && strchr(zc->zc_name, '@') != NULL &&
3277             zc->zc_objset_type == DMU_OST_ZFS) {
3278                 int err = zfs_unmount_snap(zc->zc_name, NULL);
3279                 if (err)
3280                         return (err);
3281         }
3282         return (dmu_objset_rename(zc->zc_name, zc->zc_value, recursive));
3283 }
3284
3285 static int
3286 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3287 {
3288         const char *propname = nvpair_name(pair);
3289         boolean_t issnap = (strchr(dsname, '@') != NULL);
3290         zfs_prop_t prop = zfs_name_to_prop(propname);
3291         uint64_t intval;
3292         int err;
3293
3294         if (prop == ZPROP_INVAL) {
3295                 if (zfs_prop_user(propname)) {
3296                         if (err = zfs_secpolicy_write_perms(dsname,
3297                             ZFS_DELEG_PERM_USERPROP, cr))
3298                                 return (err);
3299                         return (0);
3300                 }
3301
3302                 if (!issnap && zfs_prop_userquota(propname)) {
3303                         const char *perm = NULL;
3304                         const char *uq_prefix =
3305                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3306                         const char *gq_prefix =
3307                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3308
3309                         if (strncmp(propname, uq_prefix,
3310                             strlen(uq_prefix)) == 0) {
3311                                 perm = ZFS_DELEG_PERM_USERQUOTA;
3312                         } else if (strncmp(propname, gq_prefix,
3313                             strlen(gq_prefix)) == 0) {
3314                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
3315                         } else {
3316                                 /* USERUSED and GROUPUSED are read-only */
3317                                 return (EINVAL);
3318                         }
3319
3320                         if (err = zfs_secpolicy_write_perms(dsname, perm, cr))
3321                                 return (err);
3322                         return (0);
3323                 }
3324
3325                 return (EINVAL);
3326         }
3327
3328         if (issnap)
3329                 return (EINVAL);
3330
3331         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3332                 /*
3333                  * dsl_prop_get_all_impl() returns properties in this
3334                  * format.
3335                  */
3336                 nvlist_t *attrs;
3337                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3338                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3339                     &pair) == 0);
3340         }
3341
3342         /*
3343          * Check that this value is valid for this pool version
3344          */
3345         switch (prop) {
3346         case ZFS_PROP_COMPRESSION:
3347                 /*
3348                  * If the user specified gzip compression, make sure
3349                  * the SPA supports it. We ignore any errors here since
3350                  * we'll catch them later.
3351                  */
3352                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3353                     nvpair_value_uint64(pair, &intval) == 0) {
3354                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
3355                             intval <= ZIO_COMPRESS_GZIP_9 &&
3356                             zfs_earlier_version(dsname,
3357                             SPA_VERSION_GZIP_COMPRESSION)) {
3358                                 return (ENOTSUP);
3359                         }
3360
3361                         if (intval == ZIO_COMPRESS_ZLE &&
3362                             zfs_earlier_version(dsname,
3363                             SPA_VERSION_ZLE_COMPRESSION))
3364                                 return (ENOTSUP);
3365
3366                         /*
3367                          * If this is a bootable dataset then
3368                          * verify that the compression algorithm
3369                          * is supported for booting. We must return
3370                          * something other than ENOTSUP since it
3371                          * implies a downrev pool version.
3372                          */
3373                         if (zfs_is_bootfs(dsname) &&
3374                             !BOOTFS_COMPRESS_VALID(intval)) {
3375                                 return (ERANGE);
3376                         }
3377                 }
3378                 break;
3379
3380         case ZFS_PROP_COPIES:
3381                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
3382                         return (ENOTSUP);
3383                 break;
3384
3385         case ZFS_PROP_DEDUP:
3386                 if (zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
3387                         return (ENOTSUP);
3388                 break;
3389
3390         case ZFS_PROP_SHARESMB:
3391                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
3392                         return (ENOTSUP);
3393                 break;
3394
3395         case ZFS_PROP_ACLINHERIT:
3396                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3397                     nvpair_value_uint64(pair, &intval) == 0) {
3398                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
3399                             zfs_earlier_version(dsname,
3400                             SPA_VERSION_PASSTHROUGH_X))
3401                                 return (ENOTSUP);
3402                 }
3403                 break;
3404         }
3405
3406         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
3407 }
3408
3409 /*
3410  * Removes properties from the given props list that fail permission checks
3411  * needed to clear them and to restore them in case of a receive error. For each
3412  * property, make sure we have both set and inherit permissions.
3413  *
3414  * Returns the first error encountered if any permission checks fail. If the
3415  * caller provides a non-NULL errlist, it also gives the complete list of names
3416  * of all the properties that failed a permission check along with the
3417  * corresponding error numbers. The caller is responsible for freeing the
3418  * returned errlist.
3419  *
3420  * If every property checks out successfully, zero is returned and the list
3421  * pointed at by errlist is NULL.
3422  */
3423 static int
3424 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
3425 {
3426         zfs_cmd_t *zc;
3427         nvpair_t *pair, *next_pair;
3428         nvlist_t *errors;
3429         int err, rv = 0;
3430
3431         if (props == NULL)
3432                 return (0);
3433
3434         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3435
3436         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
3437         (void) strcpy(zc->zc_name, dataset);
3438         pair = nvlist_next_nvpair(props, NULL);
3439         while (pair != NULL) {
3440                 next_pair = nvlist_next_nvpair(props, pair);
3441
3442                 (void) strcpy(zc->zc_value, nvpair_name(pair));
3443                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
3444                     (err = zfs_secpolicy_inherit(zc, CRED())) != 0) {
3445                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
3446                         VERIFY(nvlist_add_int32(errors,
3447                             zc->zc_value, err) == 0);
3448                 }
3449                 pair = next_pair;
3450         }
3451         kmem_free(zc, sizeof (zfs_cmd_t));
3452
3453         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
3454                 nvlist_free(errors);
3455                 errors = NULL;
3456         } else {
3457                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
3458         }
3459
3460         if (errlist == NULL)
3461                 nvlist_free(errors);
3462         else
3463                 *errlist = errors;
3464
3465         return (rv);
3466 }
3467
3468 static boolean_t
3469 propval_equals(nvpair_t *p1, nvpair_t *p2)
3470 {
3471         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
3472                 /* dsl_prop_get_all_impl() format */
3473                 nvlist_t *attrs;
3474                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
3475                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3476                     &p1) == 0);
3477         }
3478
3479         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
3480                 nvlist_t *attrs;
3481                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
3482                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3483                     &p2) == 0);
3484         }
3485
3486         if (nvpair_type(p1) != nvpair_type(p2))
3487                 return (B_FALSE);
3488
3489         if (nvpair_type(p1) == DATA_TYPE_STRING) {
3490                 char *valstr1, *valstr2;
3491
3492                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
3493                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
3494                 return (strcmp(valstr1, valstr2) == 0);
3495         } else {
3496                 uint64_t intval1, intval2;
3497
3498                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
3499                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
3500                 return (intval1 == intval2);
3501         }
3502 }
3503
3504 /*
3505  * Remove properties from props if they are not going to change (as determined
3506  * by comparison with origprops). Remove them from origprops as well, since we
3507  * do not need to clear or restore properties that won't change.
3508  */
3509 static void
3510 props_reduce(nvlist_t *props, nvlist_t *origprops)
3511 {
3512         nvpair_t *pair, *next_pair;
3513
3514         if (origprops == NULL)
3515                 return; /* all props need to be received */
3516
3517         pair = nvlist_next_nvpair(props, NULL);
3518         while (pair != NULL) {
3519                 const char *propname = nvpair_name(pair);
3520                 nvpair_t *match;
3521
3522                 next_pair = nvlist_next_nvpair(props, pair);
3523
3524                 if ((nvlist_lookup_nvpair(origprops, propname,
3525                     &match) != 0) || !propval_equals(pair, match))
3526                         goto next; /* need to set received value */
3527
3528                 /* don't clear the existing received value */
3529                 (void) nvlist_remove_nvpair(origprops, match);
3530                 /* don't bother receiving the property */
3531                 (void) nvlist_remove_nvpair(props, pair);
3532 next:
3533                 pair = next_pair;
3534         }
3535 }
3536
3537 #ifdef  DEBUG
3538 static boolean_t zfs_ioc_recv_inject_err;
3539 #endif
3540
3541 /*
3542  * inputs:
3543  * zc_name              name of containing filesystem
3544  * zc_nvlist_src{_size} nvlist of properties to apply
3545  * zc_value             name of snapshot to create
3546  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
3547  * zc_cookie            file descriptor to recv from
3548  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
3549  * zc_guid              force flag
3550  * zc_cleanup_fd        cleanup-on-exit file descriptor
3551  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
3552  *
3553  * outputs:
3554  * zc_cookie            number of bytes read
3555  * zc_nvlist_dst{_size} error for each unapplied received property
3556  * zc_obj               zprop_errflags_t
3557  * zc_action_handle     handle for this guid/ds mapping
3558  */
3559 static int
3560 zfs_ioc_recv(zfs_cmd_t *zc)
3561 {
3562         file_t *fp;
3563         objset_t *os;
3564         dmu_recv_cookie_t drc;
3565         boolean_t force = (boolean_t)zc->zc_guid;
3566         int fd;
3567         int error = 0;
3568         int props_error = 0;
3569         nvlist_t *errors;
3570         offset_t off;
3571         nvlist_t *props = NULL; /* sent properties */
3572         nvlist_t *origprops = NULL; /* existing properties */
3573         objset_t *origin = NULL;
3574         char *tosnap;
3575         char tofs[ZFS_MAXNAMELEN];
3576         boolean_t first_recvd_props = B_FALSE;
3577
3578         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3579             strchr(zc->zc_value, '@') == NULL ||
3580             strchr(zc->zc_value, '%'))
3581                 return (EINVAL);
3582
3583         (void) strcpy(tofs, zc->zc_value);
3584         tosnap = strchr(tofs, '@');
3585         *tosnap++ = '\0';
3586
3587         if (zc->zc_nvlist_src != 0 &&
3588             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
3589             zc->zc_iflags, &props)) != 0)
3590                 return (error);
3591
3592         fd = zc->zc_cookie;
3593         fp = getf(fd);
3594         if (fp == NULL) {
3595                 nvlist_free(props);
3596                 return (EBADF);
3597         }
3598
3599         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3600
3601         if (props && dmu_objset_hold(tofs, FTAG, &os) == 0) {
3602                 if ((spa_version(os->os_spa) >= SPA_VERSION_RECVD_PROPS) &&
3603                     !dsl_prop_get_hasrecvd(os)) {
3604                         first_recvd_props = B_TRUE;
3605                 }
3606
3607                 /*
3608                  * If new received properties are supplied, they are to
3609                  * completely replace the existing received properties, so stash
3610                  * away the existing ones.
3611                  */
3612                 if (dsl_prop_get_received(os, &origprops) == 0) {
3613                         nvlist_t *errlist = NULL;
3614                         /*
3615                          * Don't bother writing a property if its value won't
3616                          * change (and avoid the unnecessary security checks).
3617                          *
3618                          * The first receive after SPA_VERSION_RECVD_PROPS is a
3619                          * special case where we blow away all local properties
3620                          * regardless.
3621                          */
3622                         if (!first_recvd_props)
3623                                 props_reduce(props, origprops);
3624                         if (zfs_check_clearable(tofs, origprops,
3625                             &errlist) != 0)
3626                                 (void) nvlist_merge(errors, errlist, 0);
3627                         nvlist_free(errlist);
3628                 }
3629
3630                 dmu_objset_rele(os, FTAG);
3631         }
3632
3633         if (zc->zc_string[0]) {
3634                 error = dmu_objset_hold(zc->zc_string, FTAG, &origin);
3635                 if (error)
3636                         goto out;
3637         }
3638
3639         error = dmu_recv_begin(tofs, tosnap, zc->zc_top_ds,
3640             &zc->zc_begin_record, force, origin, &drc);
3641         if (origin)
3642                 dmu_objset_rele(origin, FTAG);
3643         if (error)
3644                 goto out;
3645
3646         /*
3647          * Set properties before we receive the stream so that they are applied
3648          * to the new data. Note that we must call dmu_recv_stream() if
3649          * dmu_recv_begin() succeeds.
3650          */
3651         if (props) {
3652                 nvlist_t *errlist;
3653
3654                 if (dmu_objset_from_ds(drc.drc_logical_ds, &os) == 0) {
3655                         if (drc.drc_newfs) {
3656                                 if (spa_version(os->os_spa) >=
3657                                     SPA_VERSION_RECVD_PROPS)
3658                                         first_recvd_props = B_TRUE;
3659                         } else if (origprops != NULL) {
3660                                 if (clear_received_props(os, tofs, origprops,
3661                                     first_recvd_props ? NULL : props) != 0)
3662                                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3663                         } else {
3664                                 zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3665                         }
3666                         dsl_prop_set_hasrecvd(os);
3667                 } else if (!drc.drc_newfs) {
3668                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
3669                 }
3670
3671                 (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
3672                     props, &errlist);
3673                 (void) nvlist_merge(errors, errlist, 0);
3674                 nvlist_free(errlist);
3675         }
3676
3677         if (fit_error_list(zc, &errors) != 0 || put_nvlist(zc, errors) != 0) {
3678                 /*
3679                  * Caller made zc->zc_nvlist_dst less than the minimum expected
3680                  * size or supplied an invalid address.
3681                  */
3682                 props_error = EINVAL;
3683         }
3684
3685         off = fp->f_offset;
3686         error = dmu_recv_stream(&drc, fp, &off, zc->zc_cleanup_fd,
3687             &zc->zc_action_handle);
3688
3689         if (error == 0) {
3690                 zfsvfs_t *zfsvfs = NULL;
3691
3692                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
3693                         /* online recv */
3694                         int end_err;
3695
3696                         error = zfs_suspend_fs(zfsvfs);
3697                         /*
3698                          * If the suspend fails, then the recv_end will
3699                          * likely also fail, and clean up after itself.
3700                          */
3701                         end_err = dmu_recv_end(&drc);
3702                         if (error == 0)
3703                                 error = zfs_resume_fs(zfsvfs, tofs);
3704                         error = error ? error : end_err;
3705                         VFS_RELE(zfsvfs->z_vfs);
3706                 } else {
3707                         error = dmu_recv_end(&drc);
3708                 }
3709         }
3710
3711         zc->zc_cookie = off - fp->f_offset;
3712         if (off >= 0 && off <= MAXOFFSET_T)
3713                 fp->f_offset = off;
3714
3715 #ifdef  DEBUG
3716         if (zfs_ioc_recv_inject_err) {
3717                 zfs_ioc_recv_inject_err = B_FALSE;
3718                 error = 1;
3719         }
3720 #endif
3721         /*
3722          * On error, restore the original props.
3723          */
3724         if (error && props) {
3725                 if (dmu_objset_hold(tofs, FTAG, &os) == 0) {
3726                         if (clear_received_props(os, tofs, props, NULL) != 0) {
3727                                 /*
3728                                  * We failed to clear the received properties.
3729                                  * Since we may have left a $recvd value on the
3730                                  * system, we can't clear the $hasrecvd flag.
3731                                  */
3732                                 zc->zc_obj |= ZPROP_ERR_NORESTORE;
3733                         } else if (first_recvd_props) {
3734                                 dsl_prop_unset_hasrecvd(os);
3735                         }
3736                         dmu_objset_rele(os, FTAG);
3737                 } else if (!drc.drc_newfs) {
3738                         /* We failed to clear the received properties. */
3739                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3740                 }
3741
3742                 if (origprops == NULL && !drc.drc_newfs) {
3743                         /* We failed to stash the original properties. */
3744                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3745                 }
3746
3747                 /*
3748                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
3749                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
3750                  * explictly if we're restoring local properties cleared in the
3751                  * first new-style receive.
3752                  */
3753                 if (origprops != NULL &&
3754                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
3755                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
3756                     origprops, NULL) != 0) {
3757                         /*
3758                          * We stashed the original properties but failed to
3759                          * restore them.
3760                          */
3761                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
3762                 }
3763         }
3764 out:
3765         nvlist_free(props);
3766         nvlist_free(origprops);
3767         nvlist_free(errors);
3768         releasef(fd);
3769
3770         if (error == 0)
3771                 error = props_error;
3772
3773         return (error);
3774 }
3775
3776 /*
3777  * inputs:
3778  * zc_name      name of snapshot to send
3779  * zc_cookie    file descriptor to send stream to
3780  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
3781  * zc_sendobj   objsetid of snapshot to send
3782  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
3783  *
3784  * outputs: none
3785  */
3786 static int
3787 zfs_ioc_send(zfs_cmd_t *zc)
3788 {
3789         objset_t *fromsnap = NULL;
3790         objset_t *tosnap;
3791         file_t *fp;
3792         int error;
3793         offset_t off;
3794         dsl_dataset_t *ds;
3795         dsl_dataset_t *dsfrom = NULL;
3796         spa_t *spa;
3797         dsl_pool_t *dp;
3798
3799         error = spa_open(zc->zc_name, &spa, FTAG);
3800         if (error)
3801                 return (error);
3802
3803         dp = spa_get_dsl(spa);
3804         rw_enter(&dp->dp_config_rwlock, RW_READER);
3805         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
3806         rw_exit(&dp->dp_config_rwlock);
3807         if (error) {
3808                 spa_close(spa, FTAG);
3809                 return (error);
3810         }
3811
3812         error = dmu_objset_from_ds(ds, &tosnap);
3813         if (error) {
3814                 dsl_dataset_rele(ds, FTAG);
3815                 spa_close(spa, FTAG);
3816                 return (error);
3817         }
3818
3819         if (zc->zc_fromobj != 0) {
3820                 rw_enter(&dp->dp_config_rwlock, RW_READER);
3821                 error = dsl_dataset_hold_obj(dp, zc->zc_fromobj, FTAG, &dsfrom);
3822                 rw_exit(&dp->dp_config_rwlock);
3823                 spa_close(spa, FTAG);
3824                 if (error) {
3825                         dsl_dataset_rele(ds, FTAG);
3826                         return (error);
3827                 }
3828                 error = dmu_objset_from_ds(dsfrom, &fromsnap);
3829                 if (error) {
3830                         dsl_dataset_rele(dsfrom, FTAG);
3831                         dsl_dataset_rele(ds, FTAG);
3832                         return (error);
3833                 }
3834         } else {
3835                 spa_close(spa, FTAG);
3836         }
3837
3838         fp = getf(zc->zc_cookie);
3839         if (fp == NULL) {
3840                 dsl_dataset_rele(ds, FTAG);
3841                 if (dsfrom)
3842                         dsl_dataset_rele(dsfrom, FTAG);
3843                 return (EBADF);
3844         }
3845
3846         off = fp->f_offset;
3847         error = dmu_sendbackup(tosnap, fromsnap, zc->zc_obj, fp, &off);
3848
3849         if (off >= 0 && off <= MAXOFFSET_T)
3850                 fp->f_offset = off;
3851         releasef(zc->zc_cookie);
3852         if (dsfrom)
3853                 dsl_dataset_rele(dsfrom, FTAG);
3854         dsl_dataset_rele(ds, FTAG);
3855         return (error);
3856 }
3857
3858 static int
3859 zfs_ioc_inject_fault(zfs_cmd_t *zc)
3860 {
3861         int id, error;
3862
3863         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
3864             &zc->zc_inject_record);
3865
3866         if (error == 0)
3867                 zc->zc_guid = (uint64_t)id;
3868
3869         return (error);
3870 }
3871
3872 static int
3873 zfs_ioc_clear_fault(zfs_cmd_t *zc)
3874 {
3875         return (zio_clear_fault((int)zc->zc_guid));
3876 }
3877
3878 static int
3879 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
3880 {
3881         int id = (int)zc->zc_guid;
3882         int error;
3883
3884         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
3885             &zc->zc_inject_record);
3886
3887         zc->zc_guid = id;
3888
3889         return (error);
3890 }
3891
3892 static int
3893 zfs_ioc_error_log(zfs_cmd_t *zc)
3894 {
3895         spa_t *spa;
3896         int error;
3897         size_t count = (size_t)zc->zc_nvlist_dst_size;
3898
3899         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
3900                 return (error);
3901
3902         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
3903             &count);
3904         if (error == 0)
3905                 zc->zc_nvlist_dst_size = count;
3906         else
3907                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
3908
3909         spa_close(spa, FTAG);
3910
3911         return (error);
3912 }
3913
3914 static int
3915 zfs_ioc_clear(zfs_cmd_t *zc)
3916 {
3917         spa_t *spa;
3918         vdev_t *vd;
3919         int error;
3920
3921         /*
3922          * On zpool clear we also fix up missing slogs
3923          */
3924         mutex_enter(&spa_namespace_lock);
3925         spa = spa_lookup(zc->zc_name);
3926         if (spa == NULL) {
3927                 mutex_exit(&spa_namespace_lock);
3928                 return (EIO);
3929         }
3930         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
3931                 /* we need to let spa_open/spa_load clear the chains */
3932                 spa_set_log_state(spa, SPA_LOG_CLEAR);
3933         }
3934         spa->spa_last_open_failed = 0;
3935         mutex_exit(&spa_namespace_lock);
3936
3937         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
3938                 error = spa_open(zc->zc_name, &spa, FTAG);
3939         } else {
3940                 nvlist_t *policy;
3941                 nvlist_t *config = NULL;
3942
3943                 if (zc->zc_nvlist_src == 0)
3944                         return (EINVAL);
3945
3946                 if ((error = get_nvlist(zc->zc_nvlist_src,
3947                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
3948                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
3949                             policy, &config);
3950                         if (config != NULL) {
3951                                 int err;
3952
3953                                 if ((err = put_nvlist(zc, config)) != 0)
3954                                         error = err;
3955                                 nvlist_free(config);
3956                         }
3957                         nvlist_free(policy);
3958                 }
3959         }
3960
3961         if (error)
3962                 return (error);
3963
3964         spa_vdev_state_enter(spa, SCL_NONE);
3965
3966         if (zc->zc_guid == 0) {
3967                 vd = NULL;
3968         } else {
3969                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
3970                 if (vd == NULL) {
3971                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
3972                         spa_close(spa, FTAG);
3973                         return (ENODEV);
3974                 }
3975         }
3976
3977         vdev_clear(spa, vd);
3978
3979         (void) spa_vdev_state_exit(spa, NULL, 0);
3980
3981         /*
3982          * Resume any suspended I/Os.
3983          */
3984         if (zio_resume(spa) != 0)
3985                 error = EIO;
3986
3987         spa_close(spa, FTAG);
3988
3989         return (error);
3990 }
3991
3992 /*
3993  * inputs:
3994  * zc_name      name of filesystem
3995  * zc_value     name of origin snapshot
3996  *
3997  * outputs:
3998  * zc_string    name of conflicting snapshot, if there is one
3999  */
4000 static int
4001 zfs_ioc_promote(zfs_cmd_t *zc)
4002 {
4003         char *cp;
4004
4005         /*
4006          * We don't need to unmount *all* the origin fs's snapshots, but
4007          * it's easier.
4008          */
4009         cp = strchr(zc->zc_value, '@');
4010         if (cp)
4011                 *cp = '\0';
4012         (void) dmu_objset_find(zc->zc_value,
4013             zfs_unmount_snap, NULL, DS_FIND_SNAPSHOTS);
4014         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
4015 }
4016
4017 /*
4018  * Retrieve a single {user|group}{used|quota}@... property.
4019  *
4020  * inputs:
4021  * zc_name      name of filesystem
4022  * zc_objset_type zfs_userquota_prop_t
4023  * zc_value     domain name (eg. "S-1-234-567-89")
4024  * zc_guid      RID/UID/GID
4025  *
4026  * outputs:
4027  * zc_cookie    property value
4028  */
4029 static int
4030 zfs_ioc_userspace_one(zfs_cmd_t *zc)
4031 {
4032         zfsvfs_t *zfsvfs;
4033         int error;
4034
4035         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
4036                 return (EINVAL);
4037
4038         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4039         if (error)
4040                 return (error);
4041
4042         error = zfs_userspace_one(zfsvfs,
4043             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
4044         zfsvfs_rele(zfsvfs, FTAG);
4045
4046         return (error);
4047 }
4048
4049 /*
4050  * inputs:
4051  * zc_name              name of filesystem
4052  * zc_cookie            zap cursor
4053  * zc_objset_type       zfs_userquota_prop_t
4054  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
4055  *
4056  * outputs:
4057  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
4058  * zc_cookie    zap cursor
4059  */
4060 static int
4061 zfs_ioc_userspace_many(zfs_cmd_t *zc)
4062 {
4063         zfsvfs_t *zfsvfs;
4064         int bufsize = zc->zc_nvlist_dst_size;
4065
4066         if (bufsize <= 0)
4067                 return (ENOMEM);
4068
4069         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4070         if (error)
4071                 return (error);
4072
4073         void *buf = kmem_alloc(bufsize, KM_SLEEP);
4074
4075         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
4076             buf, &zc->zc_nvlist_dst_size);
4077
4078         if (error == 0) {
4079                 error = ddi_copyout(buf,
4080                     (void *)(uintptr_t)zc->zc_nvlist_dst,
4081                     zc->zc_nvlist_dst_size, zc->zc_iflags);
4082         }
4083         kmem_free(buf, bufsize);
4084         zfsvfs_rele(zfsvfs, FTAG);
4085
4086         return (error);
4087 }
4088
4089 /*
4090  * inputs:
4091  * zc_name              name of filesystem
4092  *
4093  * outputs:
4094  * none
4095  */
4096 static int
4097 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
4098 {
4099         objset_t *os;
4100         int error = 0;
4101         zfsvfs_t *zfsvfs;
4102
4103         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
4104                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
4105                         /*
4106                          * If userused is not enabled, it may be because the
4107                          * objset needs to be closed & reopened (to grow the
4108                          * objset_phys_t).  Suspend/resume the fs will do that.
4109                          */
4110                         error = zfs_suspend_fs(zfsvfs);
4111                         if (error == 0)
4112                                 error = zfs_resume_fs(zfsvfs, zc->zc_name);
4113                 }
4114                 if (error == 0)
4115                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
4116                 VFS_RELE(zfsvfs->z_vfs);
4117         } else {
4118                 /* XXX kind of reading contents without owning */
4119                 error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4120                 if (error)
4121                         return (error);
4122
4123                 error = dmu_objset_userspace_upgrade(os);
4124                 dmu_objset_rele(os, FTAG);
4125         }
4126
4127         return (error);
4128 }
4129
4130 #ifdef sun
4131 /*
4132  * We don't want to have a hard dependency
4133  * against some special symbols in sharefs
4134  * nfs, and smbsrv.  Determine them if needed when
4135  * the first file system is shared.
4136  * Neither sharefs, nfs or smbsrv are unloadable modules.
4137  */
4138 int (*znfsexport_fs)(void *arg);
4139 int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
4140 int (*zsmbexport_fs)(void *arg, boolean_t add_share);
4141
4142 int zfs_nfsshare_inited;
4143 int zfs_smbshare_inited;
4144
4145 ddi_modhandle_t nfs_mod;
4146 ddi_modhandle_t sharefs_mod;
4147 ddi_modhandle_t smbsrv_mod;
4148 #endif  /* sun */
4149 kmutex_t zfs_share_lock;
4150
4151 #ifdef sun
4152 static int
4153 zfs_init_sharefs()
4154 {
4155         int error;
4156
4157         ASSERT(MUTEX_HELD(&zfs_share_lock));
4158         /* Both NFS and SMB shares also require sharetab support. */
4159         if (sharefs_mod == NULL && ((sharefs_mod =
4160             ddi_modopen("fs/sharefs",
4161             KRTLD_MODE_FIRST, &error)) == NULL)) {
4162                 return (ENOSYS);
4163         }
4164         if (zshare_fs == NULL && ((zshare_fs =
4165             (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
4166             ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
4167                 return (ENOSYS);
4168         }
4169         return (0);
4170 }
4171 #endif  /* sun */
4172
4173 static int
4174 zfs_ioc_share(zfs_cmd_t *zc)
4175 {
4176 #ifdef sun
4177         int error;
4178         int opcode;
4179
4180         switch (zc->zc_share.z_sharetype) {
4181         case ZFS_SHARE_NFS:
4182         case ZFS_UNSHARE_NFS:
4183                 if (zfs_nfsshare_inited == 0) {
4184                         mutex_enter(&zfs_share_lock);
4185                         if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
4186                             KRTLD_MODE_FIRST, &error)) == NULL)) {
4187                                 mutex_exit(&zfs_share_lock);
4188                                 return (ENOSYS);
4189                         }
4190                         if (znfsexport_fs == NULL &&
4191                             ((znfsexport_fs = (int (*)(void *))
4192                             ddi_modsym(nfs_mod,
4193                             "nfs_export", &error)) == NULL)) {
4194                                 mutex_exit(&zfs_share_lock);
4195                                 return (ENOSYS);
4196                         }
4197                         error = zfs_init_sharefs();
4198                         if (error) {
4199                                 mutex_exit(&zfs_share_lock);
4200                                 return (ENOSYS);
4201                         }
4202                         zfs_nfsshare_inited = 1;
4203                         mutex_exit(&zfs_share_lock);
4204                 }
4205                 break;
4206         case ZFS_SHARE_SMB:
4207         case ZFS_UNSHARE_SMB:
4208                 if (zfs_smbshare_inited == 0) {
4209                         mutex_enter(&zfs_share_lock);
4210                         if (smbsrv_mod == NULL && ((smbsrv_mod =
4211                             ddi_modopen("drv/smbsrv",
4212                             KRTLD_MODE_FIRST, &error)) == NULL)) {
4213                                 mutex_exit(&zfs_share_lock);
4214                                 return (ENOSYS);
4215                         }
4216                         if (zsmbexport_fs == NULL && ((zsmbexport_fs =
4217                             (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
4218                             "smb_server_share", &error)) == NULL)) {
4219                                 mutex_exit(&zfs_share_lock);
4220                                 return (ENOSYS);
4221                         }
4222                         error = zfs_init_sharefs();
4223                         if (error) {
4224                                 mutex_exit(&zfs_share_lock);
4225                                 return (ENOSYS);
4226                         }
4227                         zfs_smbshare_inited = 1;
4228                         mutex_exit(&zfs_share_lock);
4229                 }
4230                 break;
4231         default:
4232                 return (EINVAL);
4233         }
4234
4235         switch (zc->zc_share.z_sharetype) {
4236         case ZFS_SHARE_NFS:
4237         case ZFS_UNSHARE_NFS:
4238                 if (error =
4239                     znfsexport_fs((void *)
4240                     (uintptr_t)zc->zc_share.z_exportdata))
4241                         return (error);
4242                 break;
4243         case ZFS_SHARE_SMB:
4244         case ZFS_UNSHARE_SMB:
4245                 if (error = zsmbexport_fs((void *)
4246                     (uintptr_t)zc->zc_share.z_exportdata,
4247                     zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
4248                     B_TRUE: B_FALSE)) {
4249                         return (error);
4250                 }
4251                 break;
4252         }
4253
4254         opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
4255             zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
4256             SHAREFS_ADD : SHAREFS_REMOVE;
4257
4258         /*
4259          * Add or remove share from sharetab
4260          */
4261         error = zshare_fs(opcode,
4262             (void *)(uintptr_t)zc->zc_share.z_sharedata,
4263             zc->zc_share.z_sharemax);
4264
4265         return (error);
4266
4267 #else   /* !sun */
4268         return (ENOSYS);
4269 #endif  /* !sun */
4270 }
4271
4272 ace_t full_access[] = {
4273         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
4274 };
4275
4276 /*
4277  * inputs:
4278  * zc_name              name of containing filesystem
4279  * zc_obj               object # beyond which we want next in-use object #
4280  *
4281  * outputs:
4282  * zc_obj               next in-use object #
4283  */
4284 static int
4285 zfs_ioc_next_obj(zfs_cmd_t *zc)
4286 {
4287         objset_t *os = NULL;
4288         int error;
4289
4290         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4291         if (error)
4292                 return (error);
4293
4294         error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
4295             os->os_dsl_dataset->ds_phys->ds_prev_snap_txg);
4296
4297         dmu_objset_rele(os, FTAG);
4298         return (error);
4299 }
4300
4301 /*
4302  * inputs:
4303  * zc_name              name of filesystem
4304  * zc_value             prefix name for snapshot
4305  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
4306  *
4307  * outputs:
4308  */
4309 static int
4310 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
4311 {
4312         char *snap_name;
4313         int error;
4314
4315         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
4316             (u_longlong_t)ddi_get_lbolt64());
4317
4318         if (strlen(snap_name) >= MAXNAMELEN) {
4319                 strfree(snap_name);
4320                 return (E2BIG);
4321         }
4322
4323         error = dmu_objset_snapshot(zc->zc_name, snap_name, snap_name,
4324             NULL, B_FALSE, B_TRUE, zc->zc_cleanup_fd);
4325         if (error != 0) {
4326                 strfree(snap_name);
4327                 return (error);
4328         }
4329
4330         (void) strcpy(zc->zc_value, snap_name);
4331         strfree(snap_name);
4332         return (0);
4333 }
4334
4335 /*
4336  * inputs:
4337  * zc_name              name of "to" snapshot
4338  * zc_value             name of "from" snapshot
4339  * zc_cookie            file descriptor to write diff data on
4340  *
4341  * outputs:
4342  * dmu_diff_record_t's to the file descriptor
4343  */
4344 static int
4345 zfs_ioc_diff(zfs_cmd_t *zc)
4346 {
4347         objset_t *fromsnap;
4348         objset_t *tosnap;
4349         file_t *fp;
4350         offset_t off;
4351         int error;
4352
4353         error = dmu_objset_hold(zc->zc_name, FTAG, &tosnap);
4354         if (error)
4355                 return (error);
4356
4357         error = dmu_objset_hold(zc->zc_value, FTAG, &fromsnap);
4358         if (error) {
4359                 dmu_objset_rele(tosnap, FTAG);
4360                 return (error);
4361         }
4362
4363         fp = getf(zc->zc_cookie);
4364         if (fp == NULL) {
4365                 dmu_objset_rele(fromsnap, FTAG);
4366                 dmu_objset_rele(tosnap, FTAG);
4367                 return (EBADF);
4368         }
4369
4370         off = fp->f_offset;
4371
4372         error = dmu_diff(tosnap, fromsnap, fp, &off);
4373
4374         if (off >= 0 && off <= MAXOFFSET_T)
4375                 fp->f_offset = off;
4376         releasef(zc->zc_cookie);
4377
4378         dmu_objset_rele(fromsnap, FTAG);
4379         dmu_objset_rele(tosnap, FTAG);
4380         return (error);
4381 }
4382
4383 #ifdef sun
4384 /*
4385  * Remove all ACL files in shares dir
4386  */
4387 static int
4388 zfs_smb_acl_purge(znode_t *dzp)
4389 {
4390         zap_cursor_t    zc;
4391         zap_attribute_t zap;
4392         zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
4393         int error;
4394
4395         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
4396             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
4397             zap_cursor_advance(&zc)) {
4398                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
4399                     NULL, 0)) != 0)
4400                         break;
4401         }
4402         zap_cursor_fini(&zc);
4403         return (error);
4404 }
4405 #endif  /* sun */
4406
4407 static int
4408 zfs_ioc_smb_acl(zfs_cmd_t *zc)
4409 {
4410 #ifdef sun
4411         vnode_t *vp;
4412         znode_t *dzp;
4413         vnode_t *resourcevp = NULL;
4414         znode_t *sharedir;
4415         zfsvfs_t *zfsvfs;
4416         nvlist_t *nvlist;
4417         char *src, *target;
4418         vattr_t vattr;
4419         vsecattr_t vsec;
4420         int error = 0;
4421
4422         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
4423             NO_FOLLOW, NULL, &vp)) != 0)
4424                 return (error);
4425
4426         /* Now make sure mntpnt and dataset are ZFS */
4427
4428         if (strcmp(vp->v_vfsp->mnt_stat.f_fstypename, "zfs") != 0 ||
4429             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
4430             zc->zc_name) != 0)) {
4431                 VN_RELE(vp);
4432                 return (EINVAL);
4433         }
4434
4435         dzp = VTOZ(vp);
4436         zfsvfs = dzp->z_zfsvfs;
4437         ZFS_ENTER(zfsvfs);
4438
4439         /*
4440          * Create share dir if its missing.
4441          */
4442         mutex_enter(&zfsvfs->z_lock);
4443         if (zfsvfs->z_shares_dir == 0) {
4444                 dmu_tx_t *tx;
4445
4446                 tx = dmu_tx_create(zfsvfs->z_os);
4447                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
4448                     ZFS_SHARES_DIR);
4449                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
4450                 error = dmu_tx_assign(tx, TXG_WAIT);
4451                 if (error) {
4452                         dmu_tx_abort(tx);
4453                 } else {
4454                         error = zfs_create_share_dir(zfsvfs, tx);
4455                         dmu_tx_commit(tx);
4456                 }
4457                 if (error) {
4458                         mutex_exit(&zfsvfs->z_lock);
4459                         VN_RELE(vp);
4460                         ZFS_EXIT(zfsvfs);
4461                         return (error);
4462                 }
4463         }
4464         mutex_exit(&zfsvfs->z_lock);
4465
4466         ASSERT(zfsvfs->z_shares_dir);
4467         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
4468                 VN_RELE(vp);
4469                 ZFS_EXIT(zfsvfs);
4470                 return (error);
4471         }
4472
4473         switch (zc->zc_cookie) {
4474         case ZFS_SMB_ACL_ADD:
4475                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
4476                 vattr.va_type = VREG;
4477                 vattr.va_mode = S_IFREG|0777;
4478                 vattr.va_uid = 0;
4479                 vattr.va_gid = 0;
4480
4481                 vsec.vsa_mask = VSA_ACE;
4482                 vsec.vsa_aclentp = &full_access;
4483                 vsec.vsa_aclentsz = sizeof (full_access);
4484                 vsec.vsa_aclcnt = 1;
4485
4486                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
4487                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
4488                 if (resourcevp)
4489                         VN_RELE(resourcevp);
4490                 break;
4491
4492         case ZFS_SMB_ACL_REMOVE:
4493                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
4494                     NULL, 0);
4495                 break;
4496
4497         case ZFS_SMB_ACL_RENAME:
4498                 if ((error = get_nvlist(zc->zc_nvlist_src,
4499                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
4500                         VN_RELE(vp);
4501                         ZFS_EXIT(zfsvfs);
4502                         return (error);
4503                 }
4504                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
4505                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
4506                     &target)) {
4507                         VN_RELE(vp);
4508                         VN_RELE(ZTOV(sharedir));
4509                         ZFS_EXIT(zfsvfs);
4510                         nvlist_free(nvlist);
4511                         return (error);
4512                 }
4513                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
4514                     kcred, NULL, 0);
4515                 nvlist_free(nvlist);
4516                 break;
4517
4518         case ZFS_SMB_ACL_PURGE:
4519                 error = zfs_smb_acl_purge(sharedir);
4520                 break;
4521
4522         default:
4523                 error = EINVAL;
4524                 break;
4525         }
4526
4527         VN_RELE(vp);
4528         VN_RELE(ZTOV(sharedir));
4529
4530         ZFS_EXIT(zfsvfs);
4531
4532         return (error);
4533 #else   /* !sun */
4534         return (EOPNOTSUPP);
4535 #endif  /* !sun */
4536 }
4537
4538 /*
4539  * inputs:
4540  * zc_name              name of filesystem
4541  * zc_value             short name of snap
4542  * zc_string            user-supplied tag for this hold
4543  * zc_cookie            recursive flag
4544  * zc_temphold          set if hold is temporary
4545  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
4546  * zc_sendobj           if non-zero, the objid for zc_name@zc_value
4547  * zc_createtxg         if zc_sendobj is non-zero, snap must have zc_createtxg
4548  *
4549  * outputs:             none
4550  */
4551 static int
4552 zfs_ioc_hold(zfs_cmd_t *zc)
4553 {
4554         boolean_t recursive = zc->zc_cookie;
4555         spa_t *spa;
4556         dsl_pool_t *dp;
4557         dsl_dataset_t *ds;
4558         int error;
4559         minor_t minor = 0;
4560
4561         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
4562                 return (EINVAL);
4563
4564         if (zc->zc_sendobj == 0) {
4565                 return (dsl_dataset_user_hold(zc->zc_name, zc->zc_value,
4566                     zc->zc_string, recursive, zc->zc_temphold,
4567                     zc->zc_cleanup_fd));
4568         }
4569
4570         if (recursive)
4571                 return (EINVAL);
4572
4573         error = spa_open(zc->zc_name, &spa, FTAG);
4574         if (error)
4575                 return (error);
4576
4577         dp = spa_get_dsl(spa);
4578         rw_enter(&dp->dp_config_rwlock, RW_READER);
4579         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
4580         rw_exit(&dp->dp_config_rwlock);
4581         spa_close(spa, FTAG);
4582         if (error)
4583                 return (error);
4584
4585         /*
4586          * Until we have a hold on this snapshot, it's possible that
4587          * zc_sendobj could've been destroyed and reused as part
4588          * of a later txg.  Make sure we're looking at the right object.
4589          */
4590         if (zc->zc_createtxg != ds->ds_phys->ds_creation_txg) {
4591                 dsl_dataset_rele(ds, FTAG);
4592                 return (ENOENT);
4593         }
4594
4595         if (zc->zc_cleanup_fd != -1 && zc->zc_temphold) {
4596                 error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
4597                 if (error) {
4598                         dsl_dataset_rele(ds, FTAG);
4599                         return (error);
4600                 }
4601         }
4602
4603         error = dsl_dataset_user_hold_for_send(ds, zc->zc_string,
4604             zc->zc_temphold);
4605         if (minor != 0) {
4606                 if (error == 0) {
4607                         dsl_register_onexit_hold_cleanup(ds, zc->zc_string,
4608                             minor);
4609                 }
4610                 zfs_onexit_fd_rele(zc->zc_cleanup_fd);
4611         }
4612         dsl_dataset_rele(ds, FTAG);
4613
4614         return (error);
4615 }
4616
4617 /*
4618  * inputs:
4619  * zc_name      name of dataset from which we're releasing a user hold
4620  * zc_value     short name of snap
4621  * zc_string    user-supplied tag for this hold
4622  * zc_cookie    recursive flag
4623  *
4624  * outputs:     none
4625  */
4626 static int
4627 zfs_ioc_release(zfs_cmd_t *zc)
4628 {
4629         boolean_t recursive = zc->zc_cookie;
4630
4631         if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
4632                 return (EINVAL);
4633
4634         return (dsl_dataset_user_release(zc->zc_name, zc->zc_value,
4635             zc->zc_string, recursive));
4636 }
4637
4638 /*
4639  * inputs:
4640  * zc_name              name of filesystem
4641  *
4642  * outputs:
4643  * zc_nvlist_src{_size} nvlist of snapshot holds
4644  */
4645 static int
4646 zfs_ioc_get_holds(zfs_cmd_t *zc)
4647 {
4648         nvlist_t *nvp;
4649         int error;
4650
4651         if ((error = dsl_dataset_get_holds(zc->zc_name, &nvp)) == 0) {
4652                 error = put_nvlist(zc, nvp);
4653                 nvlist_free(nvp);
4654         }
4655
4656         return (error);
4657 }
4658
4659 /*
4660  * pool create, destroy, and export don't log the history as part of
4661  * zfsdev_ioctl, but rather zfs_ioc_pool_create, and zfs_ioc_pool_export
4662  * do the logging of those commands.
4663  */
4664 static int
4665 zfs_ioc_jail(zfs_cmd_t *zc)
4666 {
4667
4668         return (zone_dataset_attach(curthread->td_ucred, zc->zc_name,
4669             (int)zc->zc_jailid));
4670 }
4671
4672 static int
4673 zfs_ioc_unjail(zfs_cmd_t *zc)
4674 {
4675
4676         return (zone_dataset_detach(curthread->td_ucred, zc->zc_name,
4677             (int)zc->zc_jailid));
4678 }
4679
4680 static zfs_ioc_vec_t zfs_ioc_vec[] = {
4681         { zfs_ioc_pool_create, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4682             B_FALSE },
4683         { zfs_ioc_pool_destroy, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4684             B_FALSE },
4685         { zfs_ioc_pool_import, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4686             B_FALSE },
4687         { zfs_ioc_pool_export, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4688             B_FALSE },
4689         { zfs_ioc_pool_configs, zfs_secpolicy_none, NO_NAME, B_FALSE,
4690             B_FALSE },
4691         { zfs_ioc_pool_stats, zfs_secpolicy_read, POOL_NAME, B_FALSE,
4692             B_FALSE },
4693         { zfs_ioc_pool_tryimport, zfs_secpolicy_config, NO_NAME, B_FALSE,
4694             B_FALSE },
4695         { zfs_ioc_pool_scan, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4696             B_TRUE },
4697         { zfs_ioc_pool_freeze, zfs_secpolicy_config, NO_NAME, B_FALSE,
4698             B_FALSE },
4699         { zfs_ioc_pool_upgrade, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4700             B_TRUE },
4701         { zfs_ioc_pool_get_history, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4702             B_FALSE },
4703         { zfs_ioc_vdev_add, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4704             B_TRUE },
4705         { zfs_ioc_vdev_remove, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4706             B_TRUE },
4707         { zfs_ioc_vdev_set_state, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4708             B_FALSE },
4709         { zfs_ioc_vdev_attach, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4710             B_TRUE },
4711         { zfs_ioc_vdev_detach, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4712             B_TRUE },
4713         { zfs_ioc_vdev_setpath, zfs_secpolicy_config, POOL_NAME, B_FALSE,
4714             B_TRUE },
4715         { zfs_ioc_vdev_setfru,  zfs_secpolicy_config, POOL_NAME, B_FALSE,
4716             B_TRUE },
4717         { zfs_ioc_objset_stats, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4718             B_TRUE },
4719         { zfs_ioc_objset_zplprops, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4720             B_FALSE },
4721         { zfs_ioc_dataset_list_next, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4722             B_TRUE },
4723         { zfs_ioc_snapshot_list_next, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4724             B_TRUE },
4725         { zfs_ioc_set_prop, zfs_secpolicy_none, DATASET_NAME, B_TRUE, B_TRUE },
4726         { zfs_ioc_create, zfs_secpolicy_create, DATASET_NAME, B_TRUE, B_TRUE },
4727         { zfs_ioc_destroy, zfs_secpolicy_destroy, DATASET_NAME, B_TRUE,
4728             B_TRUE},
4729         { zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME, B_TRUE,
4730             B_TRUE },
4731         { zfs_ioc_rename, zfs_secpolicy_rename, DATASET_NAME, B_TRUE, B_TRUE },
4732         { zfs_ioc_recv, zfs_secpolicy_receive, DATASET_NAME, B_TRUE, B_TRUE },
4733         { zfs_ioc_send, zfs_secpolicy_send, DATASET_NAME, B_TRUE, B_FALSE },
4734         { zfs_ioc_inject_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4735             B_FALSE },
4736         { zfs_ioc_clear_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4737             B_FALSE },
4738         { zfs_ioc_inject_list_next, zfs_secpolicy_inject, NO_NAME, B_FALSE,
4739             B_FALSE },
4740         { zfs_ioc_error_log, zfs_secpolicy_inject, POOL_NAME, B_FALSE,
4741             B_FALSE },
4742         { zfs_ioc_clear, zfs_secpolicy_config, POOL_NAME, B_TRUE, B_FALSE },
4743         { zfs_ioc_promote, zfs_secpolicy_promote, DATASET_NAME, B_TRUE,
4744             B_TRUE },
4745         { zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, DATASET_NAME,
4746             B_TRUE, B_TRUE },
4747         { zfs_ioc_snapshot, zfs_secpolicy_snapshot, DATASET_NAME, B_TRUE,
4748             B_TRUE },
4749         { zfs_ioc_dsobj_to_dsname, zfs_secpolicy_diff, POOL_NAME, B_FALSE,
4750             B_FALSE },
4751         { zfs_ioc_obj_to_path, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
4752             B_TRUE },
4753         { zfs_ioc_pool_set_props, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4754             B_TRUE },
4755         { zfs_ioc_pool_get_props, zfs_secpolicy_read, POOL_NAME, B_FALSE,
4756             B_FALSE },
4757         { zfs_ioc_set_fsacl, zfs_secpolicy_fsacl, DATASET_NAME, B_TRUE,
4758             B_TRUE },
4759         { zfs_ioc_get_fsacl, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4760             B_FALSE },
4761         { zfs_ioc_share, zfs_secpolicy_share, DATASET_NAME, B_FALSE, B_FALSE },
4762         { zfs_ioc_inherit_prop, zfs_secpolicy_inherit, DATASET_NAME, B_TRUE,
4763             B_TRUE },
4764         { zfs_ioc_smb_acl, zfs_secpolicy_smb_acl, DATASET_NAME, B_FALSE,
4765             B_FALSE },
4766         { zfs_ioc_userspace_one, zfs_secpolicy_userspace_one,
4767             DATASET_NAME, B_FALSE, B_FALSE },
4768         { zfs_ioc_userspace_many, zfs_secpolicy_userspace_many,
4769             DATASET_NAME, B_FALSE, B_FALSE },
4770         { zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
4771             DATASET_NAME, B_FALSE, B_TRUE },
4772         { zfs_ioc_hold, zfs_secpolicy_hold, DATASET_NAME, B_TRUE, B_TRUE },
4773         { zfs_ioc_release, zfs_secpolicy_release, DATASET_NAME, B_TRUE,
4774             B_TRUE },
4775         { zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4776             B_TRUE },
4777         { zfs_ioc_objset_recvd_props, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4778             B_FALSE },
4779         { zfs_ioc_vdev_split, zfs_secpolicy_config, POOL_NAME, B_TRUE,
4780             B_TRUE },
4781         { zfs_ioc_next_obj, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
4782             B_FALSE },
4783         { zfs_ioc_diff, zfs_secpolicy_diff, DATASET_NAME, B_FALSE, B_FALSE },
4784         { zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot, DATASET_NAME,
4785             B_FALSE, B_FALSE },
4786         { zfs_ioc_obj_to_stats, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
4787             B_TRUE },
4788         { zfs_ioc_jail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE },
4789         { zfs_ioc_unjail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE }
4790 };
4791
4792 int
4793 pool_status_check(const char *name, zfs_ioc_namecheck_t type)
4794 {
4795         spa_t *spa;
4796         int error;
4797
4798         ASSERT(type == POOL_NAME || type == DATASET_NAME);
4799
4800         error = spa_open(name, &spa, FTAG);
4801         if (error == 0) {
4802                 if (spa_suspended(spa))
4803                         error = EAGAIN;
4804                 spa_close(spa, FTAG);
4805         }
4806         return (error);
4807 }
4808
4809 /*
4810  * Find a free minor number.
4811  */
4812 minor_t
4813 zfsdev_minor_alloc(void)
4814 {
4815         static minor_t last_minor;
4816         minor_t m;
4817
4818         ASSERT(MUTEX_HELD(&spa_namespace_lock));
4819
4820         for (m = last_minor + 1; m != last_minor; m++) {
4821                 if (m > ZFSDEV_MAX_MINOR)
4822                         m = 1;
4823                 if (ddi_get_soft_state(zfsdev_state, m) == NULL) {
4824                         last_minor = m;
4825                         return (m);
4826                 }
4827         }
4828
4829         return (0);
4830 }
4831
4832 static int
4833 zfs_ctldev_init(struct cdev *devp)
4834 {
4835         minor_t minor;
4836         zfs_soft_state_t *zs;
4837
4838         ASSERT(MUTEX_HELD(&spa_namespace_lock));
4839
4840         minor = zfsdev_minor_alloc();
4841         if (minor == 0)
4842                 return (ENXIO);
4843
4844         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS)
4845                 return (EAGAIN);
4846
4847         devfs_set_cdevpriv((void *)(uintptr_t)minor, zfsdev_close);
4848
4849         zs = ddi_get_soft_state(zfsdev_state, minor);
4850         zs->zss_type = ZSST_CTLDEV;
4851         zfs_onexit_init((zfs_onexit_t **)&zs->zss_data);
4852
4853         return (0);
4854 }
4855
4856 static void
4857 zfs_ctldev_destroy(zfs_onexit_t *zo, minor_t minor)
4858 {
4859         ASSERT(MUTEX_HELD(&spa_namespace_lock));
4860
4861         zfs_onexit_destroy(zo);
4862         ddi_soft_state_free(zfsdev_state, minor);
4863 }
4864
4865 void *
4866 zfsdev_get_soft_state(minor_t minor, enum zfs_soft_state_type which)
4867 {
4868         zfs_soft_state_t *zp;
4869
4870         zp = ddi_get_soft_state(zfsdev_state, minor);
4871         if (zp == NULL || zp->zss_type != which)
4872                 return (NULL);
4873
4874         return (zp->zss_data);
4875 }
4876
4877 static int
4878 zfsdev_open(struct cdev *devp, int flag, int mode, struct thread *td)
4879 {
4880         int error = 0;
4881
4882 #ifdef sun
4883         if (getminor(*devp) != 0)
4884                 return (zvol_open(devp, flag, otyp, cr));
4885 #endif
4886
4887         /* This is the control device. Allocate a new minor if requested. */
4888         if (flag & FEXCL) {
4889                 mutex_enter(&spa_namespace_lock);
4890                 error = zfs_ctldev_init(devp);
4891                 mutex_exit(&spa_namespace_lock);
4892         }
4893
4894         return (error);
4895 }
4896
4897 static void
4898 zfsdev_close(void *data)
4899 {
4900         zfs_onexit_t *zo;
4901         minor_t minor = (minor_t)(uintptr_t)data;
4902
4903         if (minor == 0)
4904                 return;
4905
4906         mutex_enter(&spa_namespace_lock);
4907         zo = zfsdev_get_soft_state(minor, ZSST_CTLDEV);
4908         if (zo == NULL) {
4909                 mutex_exit(&spa_namespace_lock);
4910                 return;
4911         }
4912         zfs_ctldev_destroy(zo, minor);
4913         mutex_exit(&spa_namespace_lock);
4914 }
4915
4916 static int
4917 zfsdev_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
4918     struct thread *td)
4919 {
4920         zfs_cmd_t *zc;
4921         uint_t vec;
4922         int cflag, error, len;
4923
4924         cflag = ZFS_CMD_COMPAT_NONE;
4925         len = IOCPARM_LEN(cmd);
4926
4927         /*
4928          * Check if we have sufficient kernel memory allocated
4929          * for the zfs_cmd_t request.  Bail out if not so we
4930          * will not access undefined memory region.
4931          */
4932         if (len < sizeof(zfs_cmd_t))
4933                 if (len == sizeof(zfs_cmd_v15_t)) {
4934                         cflag = ZFS_CMD_COMPAT_V15;
4935                         vec = zfs_ioctl_v15_to_v28[ZFS_IOC(cmd)];
4936                 } else
4937                         return (EINVAL);
4938         else
4939                 vec = ZFS_IOC(cmd);
4940
4941         if (cflag != ZFS_CMD_COMPAT_NONE) {
4942                 if (vec == ZFS_IOC_COMPAT_PASS)
4943                         return (0);
4944                 else if (vec == ZFS_IOC_COMPAT_FAIL)
4945                         return (ENOTSUP);
4946         }
4947
4948         if (vec >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
4949                 return (EINVAL);
4950
4951         if (cflag != ZFS_CMD_COMPAT_NONE) {
4952                 zc = kmem_zalloc(sizeof(zfs_cmd_t), KM_SLEEP);
4953                 bzero(zc, sizeof(zfs_cmd_t));
4954                 zfs_cmd_compat_get(zc, addr, cflag);
4955                 zfs_ioctl_compat_pre(zc, &vec, cflag);
4956         } else {
4957                 zc = (void *)addr;
4958         }
4959
4960         error = zfs_ioc_vec[vec].zvec_secpolicy(zc, td->td_ucred);
4961
4962         /*
4963          * Ensure that all pool/dataset names are valid before we pass down to
4964          * the lower layers.
4965          */
4966         if (error == 0) {
4967                 zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
4968                 zc->zc_iflags = flag & FKIOCTL;
4969                 switch (zfs_ioc_vec[vec].zvec_namecheck) {
4970                 case POOL_NAME:
4971                         if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
4972                                 error = EINVAL;
4973                         if (zfs_ioc_vec[vec].zvec_pool_check)
4974                                 error = pool_status_check(zc->zc_name,
4975                                     zfs_ioc_vec[vec].zvec_namecheck);
4976                         break;
4977
4978                 case DATASET_NAME:
4979                         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
4980                                 error = EINVAL;
4981                         if (zfs_ioc_vec[vec].zvec_pool_check)
4982                                 error = pool_status_check(zc->zc_name,
4983                                     zfs_ioc_vec[vec].zvec_namecheck);
4984                         break;
4985
4986                 case NO_NAME:
4987                         break;
4988                 }
4989         }
4990
4991         if (error == 0)
4992                 error = zfs_ioc_vec[vec].zvec_func(zc);
4993
4994         if (error == 0) {
4995                 if (zfs_ioc_vec[vec].zvec_his_log)
4996                         zfs_log_history(zc);
4997         }
4998
4999         if (cflag != ZFS_CMD_COMPAT_NONE) {
5000                 zfs_ioctl_compat_post(zc, ZFS_IOC(cmd), cflag);
5001                 zfs_cmd_compat_put(zc, addr, cflag);
5002                 kmem_free(zc, sizeof(zfs_cmd_t));
5003         }
5004
5005         return (error);
5006 }
5007
5008 #ifdef sun
5009 static int
5010 zfs_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
5011 {
5012         if (cmd != DDI_ATTACH)
5013                 return (DDI_FAILURE);
5014
5015         if (ddi_create_minor_node(dip, "zfs", S_IFCHR, 0,
5016             DDI_PSEUDO, 0) == DDI_FAILURE)
5017                 return (DDI_FAILURE);
5018
5019         zfs_dip = dip;
5020
5021         ddi_report_dev(dip);
5022
5023         return (DDI_SUCCESS);
5024 }
5025
5026 static int
5027 zfs_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
5028 {
5029         if (spa_busy() || zfs_busy() || zvol_busy())
5030                 return (DDI_FAILURE);
5031
5032         if (cmd != DDI_DETACH)
5033                 return (DDI_FAILURE);
5034
5035         zfs_dip = NULL;
5036
5037         ddi_prop_remove_all(dip);
5038         ddi_remove_minor_node(dip, NULL);
5039
5040         return (DDI_SUCCESS);
5041 }
5042
5043 /*ARGSUSED*/
5044 static int
5045 zfs_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
5046 {
5047         switch (infocmd) {
5048         case DDI_INFO_DEVT2DEVINFO:
5049                 *result = zfs_dip;
5050                 return (DDI_SUCCESS);
5051
5052         case DDI_INFO_DEVT2INSTANCE:
5053                 *result = (void *)0;
5054                 return (DDI_SUCCESS);
5055         }
5056
5057         return (DDI_FAILURE);
5058 }
5059 #endif  /* sun */
5060
5061 /*
5062  * OK, so this is a little weird.
5063  *
5064  * /dev/zfs is the control node, i.e. minor 0.
5065  * /dev/zvol/[r]dsk/pool/dataset are the zvols, minor > 0.
5066  *
5067  * /dev/zfs has basically nothing to do except serve up ioctls,
5068  * so most of the standard driver entry points are in zvol.c.
5069  */
5070 #ifdef sun
5071 static struct cb_ops zfs_cb_ops = {
5072         zfsdev_open,    /* open */
5073         zfsdev_close,   /* close */
5074         zvol_strategy,  /* strategy */
5075         nodev,          /* print */
5076         zvol_dump,      /* dump */
5077         zvol_read,      /* read */
5078         zvol_write,     /* write */
5079         zfsdev_ioctl,   /* ioctl */
5080         nodev,          /* devmap */
5081         nodev,          /* mmap */
5082         nodev,          /* segmap */
5083         nochpoll,       /* poll */
5084         ddi_prop_op,    /* prop_op */
5085         NULL,           /* streamtab */
5086         D_NEW | D_MP | D_64BIT,         /* Driver compatibility flag */
5087         CB_REV,         /* version */
5088         nodev,          /* async read */
5089         nodev,          /* async write */
5090 };
5091
5092 static struct dev_ops zfs_dev_ops = {
5093         DEVO_REV,       /* version */
5094         0,              /* refcnt */
5095         zfs_info,       /* info */
5096         nulldev,        /* identify */
5097         nulldev,        /* probe */
5098         zfs_attach,     /* attach */
5099         zfs_detach,     /* detach */
5100         nodev,          /* reset */
5101         &zfs_cb_ops,    /* driver operations */
5102         NULL,           /* no bus operations */
5103         NULL,           /* power */
5104         ddi_quiesce_not_needed, /* quiesce */
5105 };
5106
5107 static struct modldrv zfs_modldrv = {
5108         &mod_driverops,
5109         "ZFS storage pool",
5110         &zfs_dev_ops
5111 };
5112
5113 static struct modlinkage modlinkage = {
5114         MODREV_1,
5115         (void *)&zfs_modlfs,
5116         (void *)&zfs_modldrv,
5117         NULL
5118 };
5119 #endif  /* sun */
5120
5121 static struct cdevsw zfs_cdevsw = {
5122         .d_version =    D_VERSION,
5123         .d_open =       zfsdev_open,
5124         .d_ioctl =      zfsdev_ioctl,
5125         .d_name =       ZFS_DEV_NAME
5126 };
5127
5128 static void
5129 zfsdev_init(void)
5130 {
5131         zfsdev = make_dev(&zfs_cdevsw, 0x0, UID_ROOT, GID_OPERATOR, 0666,
5132             ZFS_DEV_NAME);
5133 }
5134
5135 static void
5136 zfsdev_fini(void)
5137 {
5138         if (zfsdev != NULL)
5139                 destroy_dev(zfsdev);
5140 }
5141
5142 static struct root_hold_token *zfs_root_token;
5143 struct proc *zfsproc;
5144
5145 uint_t zfs_fsyncer_key;
5146 extern uint_t rrw_tsd_key;
5147
5148 #ifdef sun
5149 int
5150 _init(void)
5151 {
5152         int error;
5153
5154         spa_init(FREAD | FWRITE);
5155         zfs_init();
5156         zvol_init();
5157
5158         if ((error = mod_install(&modlinkage)) != 0) {
5159                 zvol_fini();
5160                 zfs_fini();
5161                 spa_fini();
5162                 return (error);
5163         }
5164
5165         tsd_create(&zfs_fsyncer_key, NULL);
5166         tsd_create(&rrw_tsd_key, NULL);
5167
5168         error = ldi_ident_from_mod(&modlinkage, &zfs_li);
5169         ASSERT(error == 0);
5170         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
5171
5172         return (0);
5173 }
5174
5175 int
5176 _fini(void)
5177 {
5178         int error;
5179
5180         if (spa_busy() || zfs_busy() || zvol_busy() || zio_injection_enabled)
5181                 return (EBUSY);
5182
5183         if ((error = mod_remove(&modlinkage)) != 0)
5184                 return (error);
5185
5186         zvol_fini();
5187         zfs_fini();
5188         spa_fini();
5189         if (zfs_nfsshare_inited)
5190                 (void) ddi_modclose(nfs_mod);
5191         if (zfs_smbshare_inited)
5192                 (void) ddi_modclose(smbsrv_mod);
5193         if (zfs_nfsshare_inited || zfs_smbshare_inited)
5194                 (void) ddi_modclose(sharefs_mod);
5195
5196         tsd_destroy(&zfs_fsyncer_key);
5197         ldi_ident_release(zfs_li);
5198         zfs_li = NULL;
5199         mutex_destroy(&zfs_share_lock);
5200
5201         return (error);
5202 }
5203
5204 int
5205 _info(struct modinfo *modinfop)
5206 {
5207         return (mod_info(&modlinkage, modinfop));
5208 }
5209 #endif  /* sun */
5210
5211 static int
5212 zfs_modevent(module_t mod, int type, void *unused __unused)
5213 {
5214         int error = 0;
5215
5216         switch (type) {
5217         case MOD_LOAD:
5218                 zfs_root_token = root_mount_hold("ZFS");
5219
5220                 mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
5221
5222                 spa_init(FREAD | FWRITE);
5223                 zfs_init();
5224                 zvol_init();
5225
5226                 tsd_create(&zfs_fsyncer_key, NULL);
5227                 tsd_create(&rrw_tsd_key, NULL);
5228
5229                 printf("ZFS storage pool version " SPA_VERSION_STRING "\n");
5230                 root_mount_rel(zfs_root_token);
5231
5232                 zfsdev_init();
5233                 break;
5234         case MOD_UNLOAD:
5235                 if (spa_busy() || zfs_busy() || zvol_busy() ||
5236                     zio_injection_enabled) {
5237                         error = EBUSY;
5238                         break;
5239                 }
5240
5241                 zfsdev_fini();
5242                 zvol_fini();
5243                 zfs_fini();
5244                 spa_fini();
5245
5246                 tsd_destroy(&zfs_fsyncer_key);
5247                 tsd_destroy(&rrw_tsd_key);
5248
5249                 mutex_destroy(&zfs_share_lock);
5250                 break;
5251         default:
5252                 error = EOPNOTSUPP;
5253                 break;
5254         }
5255         return (error);
5256 }
5257
5258 static moduledata_t zfs_mod = {
5259         "zfsctrl",
5260         zfs_modevent,
5261         0
5262 };
5263 DECLARE_MODULE(zfsctrl, zfs_mod, SI_SUB_VFS, SI_ORDER_ANY);
5264 MODULE_DEPEND(zfsctrl, opensolaris, 1, 1, 1);
5265 MODULE_DEPEND(zfsctrl, krpc, 1, 1, 1);