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