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