]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zvol.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  *
24  * Copyright (c) 2006-2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
25  * All rights reserved.
26  * Copyright (c) 2013 by Delphix. All rights reserved.
27  */
28
29 /* Portions Copyright 2010 Robert Milkowski */
30 /* Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org> */
31
32 /*
33  * ZFS volume emulation driver.
34  *
35  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
36  * Volumes are accessed through the symbolic links named:
37  *
38  * /dev/zvol/dsk/<pool_name>/<dataset_name>
39  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
40  *
41  * These links are created by the /dev filesystem (sdev_zvolops.c).
42  * Volumes are persistent through reboot.  No user command needs to be
43  * run before opening and using a device.
44  *
45  * FreeBSD notes.
46  * On FreeBSD ZVOLs are simply GEOM providers like any other storage device
47  * in the system.
48  */
49
50 #include <sys/types.h>
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/errno.h>
54 #include <sys/uio.h>
55 #include <sys/bio.h>
56 #include <sys/buf.h>
57 #include <sys/kmem.h>
58 #include <sys/conf.h>
59 #include <sys/cmn_err.h>
60 #include <sys/stat.h>
61 #include <sys/zap.h>
62 #include <sys/spa.h>
63 #include <sys/zio.h>
64 #include <sys/dmu_traverse.h>
65 #include <sys/dnode.h>
66 #include <sys/dsl_dataset.h>
67 #include <sys/dsl_prop.h>
68 #include <sys/dkio.h>
69 #include <sys/byteorder.h>
70 #include <sys/sunddi.h>
71 #include <sys/dirent.h>
72 #include <sys/policy.h>
73 #include <sys/fs/zfs.h>
74 #include <sys/zfs_ioctl.h>
75 #include <sys/zil.h>
76 #include <sys/refcount.h>
77 #include <sys/zfs_znode.h>
78 #include <sys/zfs_rlock.h>
79 #include <sys/vdev_impl.h>
80 #include <sys/zvol.h>
81 #include <sys/zil_impl.h>
82 #include <sys/dbuf.h>
83 #include <geom/geom.h>
84
85 #include "zfs_namecheck.h"
86
87 struct g_class zfs_zvol_class = {
88         .name = "ZFS::ZVOL",
89         .version = G_VERSION,
90 };
91
92 DECLARE_GEOM_CLASS(zfs_zvol_class, zfs_zvol);
93
94 void *zfsdev_state;
95 static char *zvol_tag = "zvol_tag";
96
97 #define ZVOL_DUMPSIZE           "dumpsize"
98
99 /*
100  * The spa_namespace_lock protects the zfsdev_state structure from being
101  * modified while it's being used, e.g. an open that comes in before a
102  * create finishes.  It also protects temporary opens of the dataset so that,
103  * e.g., an open doesn't get a spurious EBUSY.
104  */
105 static uint32_t zvol_minors;
106
107 typedef struct zvol_extent {
108         list_node_t     ze_node;
109         dva_t           ze_dva;         /* dva associated with this extent */
110         uint64_t        ze_nblks;       /* number of blocks in extent */
111 } zvol_extent_t;
112
113 /*
114  * The in-core state of each volume.
115  */
116 typedef struct zvol_state {
117         char            zv_name[MAXPATHLEN]; /* pool/dd name */
118         uint64_t        zv_volsize;     /* amount of space we advertise */
119         uint64_t        zv_volblocksize; /* volume block size */
120         struct g_provider *zv_provider; /* GEOM provider */
121         uint8_t         zv_min_bs;      /* minimum addressable block shift */
122         uint8_t         zv_flags;       /* readonly, dumpified, etc. */
123         objset_t        *zv_objset;     /* objset handle */
124         uint32_t        zv_total_opens; /* total open count */
125         zilog_t         *zv_zilog;      /* ZIL handle */
126         list_t          zv_extents;     /* List of extents for dump */
127         znode_t         zv_znode;       /* for range locking */
128         dmu_buf_t       *zv_dbuf;       /* bonus handle */
129         int             zv_state;
130         struct bio_queue_head zv_queue;
131         struct mtx      zv_queue_mtx;   /* zv_queue mutex */
132 } zvol_state_t;
133
134 /*
135  * zvol specific flags
136  */
137 #define ZVOL_RDONLY     0x1
138 #define ZVOL_DUMPIFIED  0x2
139 #define ZVOL_EXCL       0x4
140 #define ZVOL_WCE        0x8
141
142 /*
143  * zvol maximum transfer in one DMU tx.
144  */
145 int zvol_maxphys = DMU_MAX_ACCESS/2;
146
147 extern int zfs_set_prop_nvlist(const char *, zprop_source_t,
148     nvlist_t *, nvlist_t *);
149 static int zvol_remove_zv(zvol_state_t *);
150 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio);
151 static int zvol_dumpify(zvol_state_t *zv);
152 static int zvol_dump_fini(zvol_state_t *zv);
153 static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
154
155 static zvol_state_t *zvol_geom_create(const char *name);
156 static void zvol_geom_run(zvol_state_t *zv);
157 static void zvol_geom_destroy(zvol_state_t *zv);
158 static int zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace);
159 static void zvol_geom_start(struct bio *bp);
160 static void zvol_geom_worker(void *arg);
161
162 static void
163 zvol_size_changed(zvol_state_t *zv)
164 {
165 #ifdef sun
166         dev_t dev = makedevice(maj, min);
167
168         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
169             "Size", volsize) == DDI_SUCCESS);
170         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
171             "Nblocks", lbtodb(volsize)) == DDI_SUCCESS);
172
173         /* Notify specfs to invalidate the cached size */
174         spec_size_invalidate(dev, VBLK);
175         spec_size_invalidate(dev, VCHR);
176 #else   /* !sun */
177         struct g_provider *pp;
178
179         pp = zv->zv_provider;
180         if (pp == NULL)
181                 return;
182         if (zv->zv_volsize == pp->mediasize)
183                 return;
184         /*
185          * Changing provider size is not really supported by GEOM, but it
186          * should be safe when provider is closed.
187          */
188         if (zv->zv_total_opens > 0)
189                 return;
190         pp->mediasize = zv->zv_volsize;
191 #endif  /* !sun */
192 }
193
194 int
195 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
196 {
197         if (volsize == 0)
198                 return (SET_ERROR(EINVAL));
199
200         if (volsize % blocksize != 0)
201                 return (SET_ERROR(EINVAL));
202
203 #ifdef _ILP32
204         if (volsize - 1 > SPEC_MAXOFFSET_T)
205                 return (SET_ERROR(EOVERFLOW));
206 #endif
207         return (0);
208 }
209
210 int
211 zvol_check_volblocksize(uint64_t volblocksize)
212 {
213         if (volblocksize < SPA_MINBLOCKSIZE ||
214             volblocksize > SPA_MAXBLOCKSIZE ||
215             !ISP2(volblocksize))
216                 return (SET_ERROR(EDOM));
217
218         return (0);
219 }
220
221 int
222 zvol_get_stats(objset_t *os, nvlist_t *nv)
223 {
224         int error;
225         dmu_object_info_t doi;
226         uint64_t val;
227
228         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
229         if (error)
230                 return (error);
231
232         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
233
234         error = dmu_object_info(os, ZVOL_OBJ, &doi);
235
236         if (error == 0) {
237                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
238                     doi.doi_data_block_size);
239         }
240
241         return (error);
242 }
243
244 static zvol_state_t *
245 zvol_minor_lookup(const char *name)
246 {
247         struct g_provider *pp;
248         struct g_geom *gp;
249         zvol_state_t *zv = NULL;
250
251         ASSERT(MUTEX_HELD(&spa_namespace_lock));
252
253         g_topology_lock();
254         LIST_FOREACH(gp, &zfs_zvol_class.geom, geom) {
255                 pp = LIST_FIRST(&gp->provider);
256                 if (pp == NULL)
257                         continue;
258                 zv = pp->private;
259                 if (zv == NULL)
260                         continue;
261                 if (strcmp(zv->zv_name, name) == 0)
262                         break;
263         }
264         g_topology_unlock();
265
266         return (gp != NULL ? zv : NULL);
267 }
268
269 /* extent mapping arg */
270 struct maparg {
271         zvol_state_t    *ma_zv;
272         uint64_t        ma_blks;
273 };
274
275 /*ARGSUSED*/
276 static int
277 zvol_map_block(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
278     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
279 {
280         struct maparg *ma = arg;
281         zvol_extent_t *ze;
282         int bs = ma->ma_zv->zv_volblocksize;
283
284         if (bp == NULL || zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
285                 return (0);
286
287         VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
288         ma->ma_blks++;
289
290         /* Abort immediately if we have encountered gang blocks */
291         if (BP_IS_GANG(bp))
292                 return (SET_ERROR(EFRAGS));
293
294         /*
295          * See if the block is at the end of the previous extent.
296          */
297         ze = list_tail(&ma->ma_zv->zv_extents);
298         if (ze &&
299             DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
300             DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
301             DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
302                 ze->ze_nblks++;
303                 return (0);
304         }
305
306         dprintf_bp(bp, "%s", "next blkptr:");
307
308         /* start a new extent */
309         ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
310         ze->ze_dva = bp->blk_dva[0];    /* structure assignment */
311         ze->ze_nblks = 1;
312         list_insert_tail(&ma->ma_zv->zv_extents, ze);
313         return (0);
314 }
315
316 static void
317 zvol_free_extents(zvol_state_t *zv)
318 {
319         zvol_extent_t *ze;
320
321         while (ze = list_head(&zv->zv_extents)) {
322                 list_remove(&zv->zv_extents, ze);
323                 kmem_free(ze, sizeof (zvol_extent_t));
324         }
325 }
326
327 static int
328 zvol_get_lbas(zvol_state_t *zv)
329 {
330         objset_t *os = zv->zv_objset;
331         struct maparg   ma;
332         int             err;
333
334         ma.ma_zv = zv;
335         ma.ma_blks = 0;
336         zvol_free_extents(zv);
337
338         /* commit any in-flight changes before traversing the dataset */
339         txg_wait_synced(dmu_objset_pool(os), 0);
340         err = traverse_dataset(dmu_objset_ds(os), 0,
341             TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
342         if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
343                 zvol_free_extents(zv);
344                 return (err ? err : EIO);
345         }
346
347         return (0);
348 }
349
350 /* ARGSUSED */
351 void
352 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
353 {
354         zfs_creat_t *zct = arg;
355         nvlist_t *nvprops = zct->zct_props;
356         int error;
357         uint64_t volblocksize, volsize;
358
359         VERIFY(nvlist_lookup_uint64(nvprops,
360             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
361         if (nvlist_lookup_uint64(nvprops,
362             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
363                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
364
365         /*
366          * These properties must be removed from the list so the generic
367          * property setting step won't apply to them.
368          */
369         VERIFY(nvlist_remove_all(nvprops,
370             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
371         (void) nvlist_remove_all(nvprops,
372             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
373
374         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
375             DMU_OT_NONE, 0, tx);
376         ASSERT(error == 0);
377
378         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
379             DMU_OT_NONE, 0, tx);
380         ASSERT(error == 0);
381
382         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
383         ASSERT(error == 0);
384 }
385
386 /*
387  * Replay a TX_WRITE ZIL transaction that didn't get committed
388  * after a system failure
389  */
390 static int
391 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
392 {
393         objset_t *os = zv->zv_objset;
394         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
395         uint64_t offset, length;
396         dmu_tx_t *tx;
397         int error;
398
399         if (byteswap)
400                 byteswap_uint64_array(lr, sizeof (*lr));
401
402         offset = lr->lr_offset;
403         length = lr->lr_length;
404
405         /* If it's a dmu_sync() block, write the whole block */
406         if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
407                 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
408                 if (length < blocksize) {
409                         offset -= offset % blocksize;
410                         length = blocksize;
411                 }
412         }
413
414         tx = dmu_tx_create(os);
415         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
416         error = dmu_tx_assign(tx, TXG_WAIT);
417         if (error) {
418                 dmu_tx_abort(tx);
419         } else {
420                 dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
421                 dmu_tx_commit(tx);
422         }
423
424         return (error);
425 }
426
427 /* ARGSUSED */
428 static int
429 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
430 {
431         return (SET_ERROR(ENOTSUP));
432 }
433
434 /*
435  * Callback vectors for replaying records.
436  * Only TX_WRITE is needed for zvol.
437  */
438 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
439         zvol_replay_err,        /* 0 no such transaction type */
440         zvol_replay_err,        /* TX_CREATE */
441         zvol_replay_err,        /* TX_MKDIR */
442         zvol_replay_err,        /* TX_MKXATTR */
443         zvol_replay_err,        /* TX_SYMLINK */
444         zvol_replay_err,        /* TX_REMOVE */
445         zvol_replay_err,        /* TX_RMDIR */
446         zvol_replay_err,        /* TX_LINK */
447         zvol_replay_err,        /* TX_RENAME */
448         zvol_replay_write,      /* TX_WRITE */
449         zvol_replay_err,        /* TX_TRUNCATE */
450         zvol_replay_err,        /* TX_SETATTR */
451         zvol_replay_err,        /* TX_ACL */
452         zvol_replay_err,        /* TX_CREATE_ACL */
453         zvol_replay_err,        /* TX_CREATE_ATTR */
454         zvol_replay_err,        /* TX_CREATE_ACL_ATTR */
455         zvol_replay_err,        /* TX_MKDIR_ACL */
456         zvol_replay_err,        /* TX_MKDIR_ATTR */
457         zvol_replay_err,        /* TX_MKDIR_ACL_ATTR */
458         zvol_replay_err,        /* TX_WRITE2 */
459 };
460
461 #ifdef sun
462 int
463 zvol_name2minor(const char *name, minor_t *minor)
464 {
465         zvol_state_t *zv;
466
467         mutex_enter(&spa_namespace_lock);
468         zv = zvol_minor_lookup(name);
469         if (minor && zv)
470                 *minor = zv->zv_minor;
471         mutex_exit(&spa_namespace_lock);
472         return (zv ? 0 : -1);
473 }
474 #endif  /* sun */
475
476 /*
477  * Create a minor node (plus a whole lot more) for the specified volume.
478  */
479 int
480 zvol_create_minor(const char *name)
481 {
482         zfs_soft_state_t *zs;
483         zvol_state_t *zv;
484         objset_t *os;
485         dmu_object_info_t doi;
486         uint64_t volsize;
487         int error;
488
489         ZFS_LOG(1, "Creating ZVOL %s...", name);
490
491         mutex_enter(&spa_namespace_lock);
492
493         if (zvol_minor_lookup(name) != NULL) {
494                 mutex_exit(&spa_namespace_lock);
495                 return (SET_ERROR(EEXIST));
496         }
497
498         /* lie and say we're read-only */
499         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, FTAG, &os);
500
501         if (error) {
502                 mutex_exit(&spa_namespace_lock);
503                 return (error);
504         }
505
506 #ifdef sun
507         if ((minor = zfsdev_minor_alloc()) == 0) {
508                 dmu_objset_disown(os, FTAG);
509                 mutex_exit(&spa_namespace_lock);
510                 return (SET_ERROR(ENXIO));
511         }
512
513         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS) {
514                 dmu_objset_disown(os, FTAG);
515                 mutex_exit(&spa_namespace_lock);
516                 return (SET_ERROR(EAGAIN));
517         }
518         (void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
519             (char *)name);
520
521         (void) snprintf(chrbuf, sizeof (chrbuf), "%u,raw", minor);
522
523         if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
524             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
525                 ddi_soft_state_free(zfsdev_state, minor);
526                 dmu_objset_disown(os, FTAG);
527                 mutex_exit(&spa_namespace_lock);
528                 return (SET_ERROR(EAGAIN));
529         }
530
531         (void) snprintf(blkbuf, sizeof (blkbuf), "%u", minor);
532
533         if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
534             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
535                 ddi_remove_minor_node(zfs_dip, chrbuf);
536                 ddi_soft_state_free(zfsdev_state, minor);
537                 dmu_objset_disown(os, FTAG);
538                 mutex_exit(&spa_namespace_lock);
539                 return (SET_ERROR(EAGAIN));
540         }
541
542         zs = ddi_get_soft_state(zfsdev_state, minor);
543         zs->zss_type = ZSST_ZVOL;
544         zv = zs->zss_data = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
545 #else   /* !sun */
546
547         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
548         if (error) {
549                 ASSERT(error == 0);
550                 dmu_objset_disown(os, zvol_tag);
551                 mutex_exit(&spa_namespace_lock);
552                 return (error);
553         }
554
555         DROP_GIANT();
556         g_topology_lock();
557         zv = zvol_geom_create(name);
558         zv->zv_volsize = volsize;
559         zv->zv_provider->mediasize = zv->zv_volsize;
560
561 #endif  /* !sun */
562
563         (void) strlcpy(zv->zv_name, name, MAXPATHLEN);
564         zv->zv_min_bs = DEV_BSHIFT;
565         zv->zv_objset = os;
566         if (dmu_objset_is_snapshot(os) || !spa_writeable(dmu_objset_spa(os)))
567                 zv->zv_flags |= ZVOL_RDONLY;
568         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
569         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
570             sizeof (rl_t), offsetof(rl_t, r_node));
571         list_create(&zv->zv_extents, sizeof (zvol_extent_t),
572             offsetof(zvol_extent_t, ze_node));
573         /* get and cache the blocksize */
574         error = dmu_object_info(os, ZVOL_OBJ, &doi);
575         ASSERT(error == 0);
576         zv->zv_volblocksize = doi.doi_data_block_size;
577
578         if (spa_writeable(dmu_objset_spa(os))) {
579                 if (zil_replay_disable)
580                         zil_destroy(dmu_objset_zil(os), B_FALSE);
581                 else
582                         zil_replay(os, zv, zvol_replay_vector);
583         }
584         dmu_objset_disown(os, FTAG);
585         zv->zv_objset = NULL;
586
587         zvol_minors++;
588
589         mutex_exit(&spa_namespace_lock);
590
591         zvol_geom_run(zv);
592
593         g_topology_unlock();
594         PICKUP_GIANT();
595
596         ZFS_LOG(1, "ZVOL %s created.", name);
597
598         return (0);
599 }
600
601 /*
602  * Remove minor node for the specified volume.
603  */
604 static int
605 zvol_remove_zv(zvol_state_t *zv)
606 {
607 #ifdef sun
608         minor_t minor = zv->zv_minor;
609 #endif
610
611         ASSERT(MUTEX_HELD(&spa_namespace_lock));
612         if (zv->zv_total_opens != 0)
613                 return (SET_ERROR(EBUSY));
614
615         ZFS_LOG(1, "ZVOL %s destroyed.", zv->zv_name);
616
617 #ifdef sun
618         (void) snprintf(nmbuf, sizeof (nmbuf), "%u,raw", minor);
619         ddi_remove_minor_node(zfs_dip, nmbuf);
620 #endif  /* sun */
621
622         avl_destroy(&zv->zv_znode.z_range_avl);
623         mutex_destroy(&zv->zv_znode.z_range_lock);
624
625         zvol_geom_destroy(zv);
626
627         zvol_minors--;
628         return (0);
629 }
630
631 int
632 zvol_remove_minor(const char *name)
633 {
634         zvol_state_t *zv;
635         int rc;
636
637         mutex_enter(&spa_namespace_lock);
638         if ((zv = zvol_minor_lookup(name)) == NULL) {
639                 mutex_exit(&spa_namespace_lock);
640                 return (SET_ERROR(ENXIO));
641         }
642         g_topology_lock();
643         rc = zvol_remove_zv(zv);
644         g_topology_unlock();
645         mutex_exit(&spa_namespace_lock);
646         return (rc);
647 }
648
649 int
650 zvol_first_open(zvol_state_t *zv)
651 {
652         objset_t *os;
653         uint64_t volsize;
654         int error;
655         uint64_t readonly;
656
657         /* lie and say we're read-only */
658         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, B_TRUE,
659             zvol_tag, &os);
660         if (error)
661                 return (error);
662
663         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
664         if (error) {
665                 ASSERT(error == 0);
666                 dmu_objset_disown(os, zvol_tag);
667                 return (error);
668         }
669         zv->zv_objset = os;
670         error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
671         if (error) {
672                 dmu_objset_disown(os, zvol_tag);
673                 return (error);
674         }
675         zv->zv_volsize = volsize;
676         zv->zv_zilog = zil_open(os, zvol_get_data);
677         zvol_size_changed(zv);
678
679         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &readonly,
680             NULL) == 0);
681         if (readonly || dmu_objset_is_snapshot(os) ||
682             !spa_writeable(dmu_objset_spa(os)))
683                 zv->zv_flags |= ZVOL_RDONLY;
684         else
685                 zv->zv_flags &= ~ZVOL_RDONLY;
686         return (error);
687 }
688
689 void
690 zvol_last_close(zvol_state_t *zv)
691 {
692         zil_close(zv->zv_zilog);
693         zv->zv_zilog = NULL;
694
695         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
696         zv->zv_dbuf = NULL;
697
698         /*
699          * Evict cached data
700          */
701         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
702             !(zv->zv_flags & ZVOL_RDONLY))
703                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
704         dmu_objset_evict_dbufs(zv->zv_objset);
705
706         dmu_objset_disown(zv->zv_objset, zvol_tag);
707         zv->zv_objset = NULL;
708 }
709
710 #ifdef sun
711 int
712 zvol_prealloc(zvol_state_t *zv)
713 {
714         objset_t *os = zv->zv_objset;
715         dmu_tx_t *tx;
716         uint64_t refd, avail, usedobjs, availobjs;
717         uint64_t resid = zv->zv_volsize;
718         uint64_t off = 0;
719
720         /* Check the space usage before attempting to allocate the space */
721         dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
722         if (avail < zv->zv_volsize)
723                 return (SET_ERROR(ENOSPC));
724
725         /* Free old extents if they exist */
726         zvol_free_extents(zv);
727
728         while (resid != 0) {
729                 int error;
730                 uint64_t bytes = MIN(resid, SPA_MAXBLOCKSIZE);
731
732                 tx = dmu_tx_create(os);
733                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
734                 error = dmu_tx_assign(tx, TXG_WAIT);
735                 if (error) {
736                         dmu_tx_abort(tx);
737                         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
738                         return (error);
739                 }
740                 dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
741                 dmu_tx_commit(tx);
742                 off += bytes;
743                 resid -= bytes;
744         }
745         txg_wait_synced(dmu_objset_pool(os), 0);
746
747         return (0);
748 }
749 #endif  /* sun */
750
751 static int
752 zvol_update_volsize(objset_t *os, uint64_t volsize)
753 {
754         dmu_tx_t *tx;
755         int error;
756
757         ASSERT(MUTEX_HELD(&spa_namespace_lock));
758
759         tx = dmu_tx_create(os);
760         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
761         error = dmu_tx_assign(tx, TXG_WAIT);
762         if (error) {
763                 dmu_tx_abort(tx);
764                 return (error);
765         }
766
767         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
768             &volsize, tx);
769         dmu_tx_commit(tx);
770
771         if (error == 0)
772                 error = dmu_free_long_range(os,
773                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
774         return (error);
775 }
776
777 void
778 zvol_remove_minors(const char *name)
779 {
780         struct g_geom *gp, *gptmp;
781         struct g_provider *pp;
782         zvol_state_t *zv;
783         size_t namelen;
784
785         namelen = strlen(name);
786
787         DROP_GIANT();
788         mutex_enter(&spa_namespace_lock);
789         g_topology_lock();
790
791         LIST_FOREACH_SAFE(gp, &zfs_zvol_class.geom, geom, gptmp) {
792                 pp = LIST_FIRST(&gp->provider);
793                 if (pp == NULL)
794                         continue;
795                 zv = pp->private;
796                 if (zv == NULL)
797                         continue;
798                 if (strcmp(zv->zv_name, name) == 0 ||
799                     (strncmp(zv->zv_name, name, namelen) == 0 &&
800                      zv->zv_name[namelen] == '/')) {
801                         (void) zvol_remove_zv(zv);
802                 }
803         }
804
805         g_topology_unlock();
806         mutex_exit(&spa_namespace_lock);
807         PICKUP_GIANT();
808 }
809
810 int
811 zvol_set_volsize(const char *name, major_t maj, uint64_t volsize)
812 {
813         zvol_state_t *zv = NULL;
814         objset_t *os;
815         int error;
816         dmu_object_info_t doi;
817         uint64_t old_volsize = 0ULL;
818         uint64_t readonly;
819
820         mutex_enter(&spa_namespace_lock);
821         zv = zvol_minor_lookup(name);
822         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
823                 mutex_exit(&spa_namespace_lock);
824                 return (error);
825         }
826
827         if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
828             (error = zvol_check_volsize(volsize,
829             doi.doi_data_block_size)) != 0)
830                 goto out;
831
832         VERIFY(dsl_prop_get_integer(name, "readonly", &readonly,
833             NULL) == 0);
834         if (readonly) {
835                 error = EROFS;
836                 goto out;
837         }
838
839         error = zvol_update_volsize(os, volsize);
840         /*
841          * Reinitialize the dump area to the new size. If we
842          * failed to resize the dump area then restore it back to
843          * its original size.
844          */
845         if (zv && error == 0) {
846 #ifdef ZVOL_DUMP
847                 if (zv->zv_flags & ZVOL_DUMPIFIED) {
848                         old_volsize = zv->zv_volsize;
849                         zv->zv_volsize = volsize;
850                         if ((error = zvol_dumpify(zv)) != 0 ||
851                             (error = dumpvp_resize()) != 0) {
852                                 (void) zvol_update_volsize(os, old_volsize);
853                                 zv->zv_volsize = old_volsize;
854                                 error = zvol_dumpify(zv);
855                         }
856                 }
857 #endif  /* ZVOL_DUMP */
858                 if (error == 0) {
859                         zv->zv_volsize = volsize;
860                         zvol_size_changed(zv);
861                 }
862         }
863
864 #ifdef sun
865         /*
866          * Generate a LUN expansion event.
867          */
868         if (zv && error == 0) {
869                 sysevent_id_t eid;
870                 nvlist_t *attr;
871                 char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
872
873                 (void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
874                     zv->zv_minor);
875
876                 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
877                 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
878
879                 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
880                     ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
881
882                 nvlist_free(attr);
883                 kmem_free(physpath, MAXPATHLEN);
884         }
885 #endif  /* sun */
886
887 out:
888         dmu_objset_rele(os, FTAG);
889
890         mutex_exit(&spa_namespace_lock);
891
892         return (error);
893 }
894
895 /*ARGSUSED*/
896 static int
897 zvol_open(struct g_provider *pp, int flag, int count)
898 {
899         zvol_state_t *zv;
900         int err = 0;
901         boolean_t locked = B_FALSE;
902
903         /*
904          * Protect against recursively entering spa_namespace_lock
905          * when spa_open() is used for a pool on a (local) ZVOL(s).
906          * This is needed since we replaced upstream zfsdev_state_lock
907          * with spa_namespace_lock in the ZVOL code.
908          * We are using the same trick as spa_open().
909          * Note that calls in zvol_first_open which need to resolve
910          * pool name to a spa object will enter spa_open()
911          * recursively, but that function already has all the
912          * necessary protection.
913          */
914         if (!MUTEX_HELD(&spa_namespace_lock)) {
915                 mutex_enter(&spa_namespace_lock);
916                 locked = B_TRUE;
917         }
918
919         zv = pp->private;
920         if (zv == NULL) {
921                 if (locked)
922                         mutex_exit(&spa_namespace_lock);
923                 return (SET_ERROR(ENXIO));
924         }
925
926         if (zv->zv_total_opens == 0)
927                 err = zvol_first_open(zv);
928         if (err) {
929                 if (locked)
930                         mutex_exit(&spa_namespace_lock);
931                 return (err);
932         }
933         if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
934                 err = SET_ERROR(EROFS);
935                 goto out;
936         }
937         if (zv->zv_flags & ZVOL_EXCL) {
938                 err = SET_ERROR(EBUSY);
939                 goto out;
940         }
941 #ifdef FEXCL
942         if (flag & FEXCL) {
943                 if (zv->zv_total_opens != 0) {
944                         err = SET_ERROR(EBUSY);
945                         goto out;
946                 }
947                 zv->zv_flags |= ZVOL_EXCL;
948         }
949 #endif
950
951         zv->zv_total_opens += count;
952         if (locked)
953                 mutex_exit(&spa_namespace_lock);
954
955         return (err);
956 out:
957         if (zv->zv_total_opens == 0)
958                 zvol_last_close(zv);
959         if (locked)
960                 mutex_exit(&spa_namespace_lock);
961         return (err);
962 }
963
964 /*ARGSUSED*/
965 static int
966 zvol_close(struct g_provider *pp, int flag, int count)
967 {
968         zvol_state_t *zv;
969         int error = 0;
970         boolean_t locked = B_FALSE;
971
972         /* See comment in zvol_open(). */
973         if (!MUTEX_HELD(&spa_namespace_lock)) {
974                 mutex_enter(&spa_namespace_lock);
975                 locked = B_TRUE;
976         }
977
978         zv = pp->private;
979         if (zv == NULL) {
980                 if (locked)
981                         mutex_exit(&spa_namespace_lock);
982                 return (SET_ERROR(ENXIO));
983         }
984
985         if (zv->zv_flags & ZVOL_EXCL) {
986                 ASSERT(zv->zv_total_opens == 1);
987                 zv->zv_flags &= ~ZVOL_EXCL;
988         }
989
990         /*
991          * If the open count is zero, this is a spurious close.
992          * That indicates a bug in the kernel / DDI framework.
993          */
994         ASSERT(zv->zv_total_opens != 0);
995
996         /*
997          * You may get multiple opens, but only one close.
998          */
999         zv->zv_total_opens -= count;
1000
1001         if (zv->zv_total_opens == 0)
1002                 zvol_last_close(zv);
1003
1004         if (locked)
1005                 mutex_exit(&spa_namespace_lock);
1006         return (error);
1007 }
1008
1009 static void
1010 zvol_get_done(zgd_t *zgd, int error)
1011 {
1012         if (zgd->zgd_db)
1013                 dmu_buf_rele(zgd->zgd_db, zgd);
1014
1015         zfs_range_unlock(zgd->zgd_rl);
1016
1017         if (error == 0 && zgd->zgd_bp)
1018                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1019
1020         kmem_free(zgd, sizeof (zgd_t));
1021 }
1022
1023 /*
1024  * Get data to generate a TX_WRITE intent log record.
1025  */
1026 static int
1027 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1028 {
1029         zvol_state_t *zv = arg;
1030         objset_t *os = zv->zv_objset;
1031         uint64_t object = ZVOL_OBJ;
1032         uint64_t offset = lr->lr_offset;
1033         uint64_t size = lr->lr_length;  /* length of user data */
1034         blkptr_t *bp = &lr->lr_blkptr;
1035         dmu_buf_t *db;
1036         zgd_t *zgd;
1037         int error;
1038
1039         ASSERT(zio != NULL);
1040         ASSERT(size != 0);
1041
1042         zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1043         zgd->zgd_zilog = zv->zv_zilog;
1044         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
1045
1046         /*
1047          * Write records come in two flavors: immediate and indirect.
1048          * For small writes it's cheaper to store the data with the
1049          * log record (immediate); for large writes it's cheaper to
1050          * sync the data and get a pointer to it (indirect) so that
1051          * we don't have to write the data twice.
1052          */
1053         if (buf != NULL) {      /* immediate write */
1054                 error = dmu_read(os, object, offset, size, buf,
1055                     DMU_READ_NO_PREFETCH);
1056         } else {
1057                 size = zv->zv_volblocksize;
1058                 offset = P2ALIGN(offset, size);
1059                 error = dmu_buf_hold(os, object, offset, zgd, &db,
1060                     DMU_READ_NO_PREFETCH);
1061                 if (error == 0) {
1062                         blkptr_t *obp = dmu_buf_get_blkptr(db);
1063                         if (obp) {
1064                                 ASSERT(BP_IS_HOLE(bp));
1065                                 *bp = *obp;
1066                         }
1067
1068                         zgd->zgd_db = db;
1069                         zgd->zgd_bp = bp;
1070
1071                         ASSERT(db->db_offset == offset);
1072                         ASSERT(db->db_size == size);
1073
1074                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1075                             zvol_get_done, zgd);
1076
1077                         if (error == 0)
1078                                 return (0);
1079                 }
1080         }
1081
1082         zvol_get_done(zgd, error);
1083
1084         return (error);
1085 }
1086
1087 /*
1088  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1089  *
1090  * We store data in the log buffers if it's small enough.
1091  * Otherwise we will later flush the data out via dmu_sync().
1092  */
1093 ssize_t zvol_immediate_write_sz = 32768;
1094
1095 static void
1096 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1097     boolean_t sync)
1098 {
1099         uint32_t blocksize = zv->zv_volblocksize;
1100         zilog_t *zilog = zv->zv_zilog;
1101         boolean_t slogging;
1102         ssize_t immediate_write_sz;
1103
1104         if (zil_replaying(zilog, tx))
1105                 return;
1106
1107         immediate_write_sz = (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1108             ? 0 : zvol_immediate_write_sz;
1109
1110         slogging = spa_has_slogs(zilog->zl_spa) &&
1111             (zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
1112
1113         while (resid) {
1114                 itx_t *itx;
1115                 lr_write_t *lr;
1116                 ssize_t len;
1117                 itx_wr_state_t write_state;
1118
1119                 /*
1120                  * Unlike zfs_log_write() we can be called with
1121                  * upto DMU_MAX_ACCESS/2 (5MB) writes.
1122                  */
1123                 if (blocksize > immediate_write_sz && !slogging &&
1124                     resid >= blocksize && off % blocksize == 0) {
1125                         write_state = WR_INDIRECT; /* uses dmu_sync */
1126                         len = blocksize;
1127                 } else if (sync) {
1128                         write_state = WR_COPIED;
1129                         len = MIN(ZIL_MAX_LOG_DATA, resid);
1130                 } else {
1131                         write_state = WR_NEED_COPY;
1132                         len = MIN(ZIL_MAX_LOG_DATA, resid);
1133                 }
1134
1135                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1136                     (write_state == WR_COPIED ? len : 0));
1137                 lr = (lr_write_t *)&itx->itx_lr;
1138                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
1139                     ZVOL_OBJ, off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1140                         zil_itx_destroy(itx);
1141                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1142                         lr = (lr_write_t *)&itx->itx_lr;
1143                         write_state = WR_NEED_COPY;
1144                 }
1145
1146                 itx->itx_wr_state = write_state;
1147                 if (write_state == WR_NEED_COPY)
1148                         itx->itx_sod += len;
1149                 lr->lr_foid = ZVOL_OBJ;
1150                 lr->lr_offset = off;
1151                 lr->lr_length = len;
1152                 lr->lr_blkoff = 0;
1153                 BP_ZERO(&lr->lr_blkptr);
1154
1155                 itx->itx_private = zv;
1156                 itx->itx_sync = sync;
1157
1158                 zil_itx_assign(zilog, itx, tx);
1159
1160                 off += len;
1161                 resid -= len;
1162         }
1163 }
1164
1165 #ifdef sun
1166 static int
1167 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t size,
1168     boolean_t doread, boolean_t isdump)
1169 {
1170         vdev_disk_t *dvd;
1171         int c;
1172         int numerrors = 0;
1173
1174         for (c = 0; c < vd->vdev_children; c++) {
1175                 ASSERT(vd->vdev_ops == &vdev_mirror_ops ||
1176                     vd->vdev_ops == &vdev_replacing_ops ||
1177                     vd->vdev_ops == &vdev_spare_ops);
1178                 int err = zvol_dumpio_vdev(vd->vdev_child[c],
1179                     addr, offset, size, doread, isdump);
1180                 if (err != 0) {
1181                         numerrors++;
1182                 } else if (doread) {
1183                         break;
1184                 }
1185         }
1186
1187         if (!vd->vdev_ops->vdev_op_leaf)
1188                 return (numerrors < vd->vdev_children ? 0 : EIO);
1189
1190         if (doread && !vdev_readable(vd))
1191                 return (SET_ERROR(EIO));
1192         else if (!doread && !vdev_writeable(vd))
1193                 return (SET_ERROR(EIO));
1194
1195         dvd = vd->vdev_tsd;
1196         ASSERT3P(dvd, !=, NULL);
1197         offset += VDEV_LABEL_START_SIZE;
1198
1199         if (ddi_in_panic() || isdump) {
1200                 ASSERT(!doread);
1201                 if (doread)
1202                         return (SET_ERROR(EIO));
1203                 return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1204                     lbtodb(size)));
1205         } else {
1206                 return (vdev_disk_physio(dvd->vd_lh, addr, size, offset,
1207                     doread ? B_READ : B_WRITE));
1208         }
1209 }
1210
1211 static int
1212 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1213     boolean_t doread, boolean_t isdump)
1214 {
1215         vdev_t *vd;
1216         int error;
1217         zvol_extent_t *ze;
1218         spa_t *spa = dmu_objset_spa(zv->zv_objset);
1219
1220         /* Must be sector aligned, and not stradle a block boundary. */
1221         if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1222             P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1223                 return (SET_ERROR(EINVAL));
1224         }
1225         ASSERT(size <= zv->zv_volblocksize);
1226
1227         /* Locate the extent this belongs to */
1228         ze = list_head(&zv->zv_extents);
1229         while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1230                 offset -= ze->ze_nblks * zv->zv_volblocksize;
1231                 ze = list_next(&zv->zv_extents, ze);
1232         }
1233
1234         if (ze == NULL)
1235                 return (SET_ERROR(EINVAL));
1236
1237         if (!ddi_in_panic())
1238                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1239
1240         vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1241         offset += DVA_GET_OFFSET(&ze->ze_dva);
1242         error = zvol_dumpio_vdev(vd, addr, offset, size, doread, isdump);
1243
1244         if (!ddi_in_panic())
1245                 spa_config_exit(spa, SCL_STATE, FTAG);
1246
1247         return (error);
1248 }
1249 #endif  /* sun */
1250
1251 int
1252 zvol_strategy(struct bio *bp)
1253 {
1254         zvol_state_t *zv = bp->bio_to->private;
1255         uint64_t off, volsize;
1256         size_t resid;
1257         char *addr;
1258         objset_t *os;
1259         rl_t *rl;
1260         int error = 0;
1261         boolean_t doread = (bp->bio_cmd == BIO_READ);
1262         boolean_t sync;
1263
1264         if (zv == NULL) {
1265                 g_io_deliver(bp, ENXIO);
1266                 return (0);
1267         }
1268
1269         if (bp->bio_cmd != BIO_READ && (zv->zv_flags & ZVOL_RDONLY)) {
1270                 g_io_deliver(bp, EROFS);
1271                 return (0);
1272         }
1273
1274         off = bp->bio_offset;
1275         volsize = zv->zv_volsize;
1276
1277         os = zv->zv_objset;
1278         ASSERT(os != NULL);
1279
1280         addr = bp->bio_data;
1281         resid = bp->bio_length;
1282
1283         if (resid > 0 && (off < 0 || off >= volsize)) {
1284                 g_io_deliver(bp, EIO);
1285                 return (0);
1286         }
1287
1288         sync = !doread && zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
1289
1290         /*
1291          * There must be no buffer changes when doing a dmu_sync() because
1292          * we can't change the data whilst calculating the checksum.
1293          */
1294         rl = zfs_range_lock(&zv->zv_znode, off, resid,
1295             doread ? RL_READER : RL_WRITER);
1296
1297         while (resid != 0 && off < volsize) {
1298                 size_t size = MIN(resid, zvol_maxphys);
1299                 if (doread) {
1300                         error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1301                             DMU_READ_PREFETCH);
1302                 } else {
1303                         dmu_tx_t *tx = dmu_tx_create(os);
1304                         dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1305                         error = dmu_tx_assign(tx, TXG_WAIT);
1306                         if (error) {
1307                                 dmu_tx_abort(tx);
1308                         } else {
1309                                 dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1310                                 zvol_log_write(zv, tx, off, size, sync);
1311                                 dmu_tx_commit(tx);
1312                         }
1313                 }
1314                 if (error) {
1315                         /* convert checksum errors into IO errors */
1316                         if (error == ECKSUM)
1317                                 error = SET_ERROR(EIO);
1318                         break;
1319                 }
1320                 off += size;
1321                 addr += size;
1322                 resid -= size;
1323         }
1324         zfs_range_unlock(rl);
1325
1326         bp->bio_completed = bp->bio_length - resid;
1327         if (bp->bio_completed < bp->bio_length)
1328                 bp->bio_error = (off > volsize ? EINVAL : error);
1329
1330         if (sync)
1331                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1332         g_io_deliver(bp, 0);
1333
1334         return (0);
1335 }
1336
1337 #ifdef sun
1338 /*
1339  * Set the buffer count to the zvol maximum transfer.
1340  * Using our own routine instead of the default minphys()
1341  * means that for larger writes we write bigger buffers on X86
1342  * (128K instead of 56K) and flush the disk write cache less often
1343  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1344  * 56K on X86 and 128K on sparc).
1345  */
1346 void
1347 zvol_minphys(struct buf *bp)
1348 {
1349         if (bp->b_bcount > zvol_maxphys)
1350                 bp->b_bcount = zvol_maxphys;
1351 }
1352
1353 int
1354 zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1355 {
1356         minor_t minor = getminor(dev);
1357         zvol_state_t *zv;
1358         int error = 0;
1359         uint64_t size;
1360         uint64_t boff;
1361         uint64_t resid;
1362
1363         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1364         if (zv == NULL)
1365                 return (SET_ERROR(ENXIO));
1366
1367         if ((zv->zv_flags & ZVOL_DUMPIFIED) == 0)
1368                 return (SET_ERROR(EINVAL));
1369
1370         boff = ldbtob(blkno);
1371         resid = ldbtob(nblocks);
1372
1373         VERIFY3U(boff + resid, <=, zv->zv_volsize);
1374
1375         while (resid) {
1376                 size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1377                 error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1378                 if (error)
1379                         break;
1380                 boff += size;
1381                 addr += size;
1382                 resid -= size;
1383         }
1384
1385         return (error);
1386 }
1387
1388 /*ARGSUSED*/
1389 int
1390 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1391 {
1392         minor_t minor = getminor(dev);
1393         zvol_state_t *zv;
1394         uint64_t volsize;
1395         rl_t *rl;
1396         int error = 0;
1397
1398         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1399         if (zv == NULL)
1400                 return (SET_ERROR(ENXIO));
1401
1402         volsize = zv->zv_volsize;
1403         if (uio->uio_resid > 0 &&
1404             (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1405                 return (SET_ERROR(EIO));
1406
1407         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1408                 error = physio(zvol_strategy, NULL, dev, B_READ,
1409                     zvol_minphys, uio);
1410                 return (error);
1411         }
1412
1413         rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1414             RL_READER);
1415         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1416                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1417
1418                 /* don't read past the end */
1419                 if (bytes > volsize - uio->uio_loffset)
1420                         bytes = volsize - uio->uio_loffset;
1421
1422                 error =  dmu_read_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes);
1423                 if (error) {
1424                         /* convert checksum errors into IO errors */
1425                         if (error == ECKSUM)
1426                                 error = SET_ERROR(EIO);
1427                         break;
1428                 }
1429         }
1430         zfs_range_unlock(rl);
1431         return (error);
1432 }
1433
1434 /*ARGSUSED*/
1435 int
1436 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1437 {
1438         minor_t minor = getminor(dev);
1439         zvol_state_t *zv;
1440         uint64_t volsize;
1441         rl_t *rl;
1442         int error = 0;
1443         boolean_t sync;
1444
1445         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1446         if (zv == NULL)
1447                 return (SET_ERROR(ENXIO));
1448
1449         volsize = zv->zv_volsize;
1450         if (uio->uio_resid > 0 &&
1451             (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1452                 return (SET_ERROR(EIO));
1453
1454         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1455                 error = physio(zvol_strategy, NULL, dev, B_WRITE,
1456                     zvol_minphys, uio);
1457                 return (error);
1458         }
1459
1460         sync = !(zv->zv_flags & ZVOL_WCE) ||
1461             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1462
1463         rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1464             RL_WRITER);
1465         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1466                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1467                 uint64_t off = uio->uio_loffset;
1468                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1469
1470                 if (bytes > volsize - off)      /* don't write past the end */
1471                         bytes = volsize - off;
1472
1473                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1474                 error = dmu_tx_assign(tx, TXG_WAIT);
1475                 if (error) {
1476                         dmu_tx_abort(tx);
1477                         break;
1478                 }
1479                 error = dmu_write_uio_dbuf(zv->zv_dbuf, uio, bytes, tx);
1480                 if (error == 0)
1481                         zvol_log_write(zv, tx, off, bytes, sync);
1482                 dmu_tx_commit(tx);
1483
1484                 if (error)
1485                         break;
1486         }
1487         zfs_range_unlock(rl);
1488         if (sync)
1489                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1490         return (error);
1491 }
1492
1493 int
1494 zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1495 {
1496         struct uuid uuid = EFI_RESERVED;
1497         efi_gpe_t gpe = { 0 };
1498         uint32_t crc;
1499         dk_efi_t efi;
1500         int length;
1501         char *ptr;
1502
1503         if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1504                 return (SET_ERROR(EFAULT));
1505         ptr = (char *)(uintptr_t)efi.dki_data_64;
1506         length = efi.dki_length;
1507         /*
1508          * Some clients may attempt to request a PMBR for the
1509          * zvol.  Currently this interface will return EINVAL to
1510          * such requests.  These requests could be supported by
1511          * adding a check for lba == 0 and consing up an appropriate
1512          * PMBR.
1513          */
1514         if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1515                 return (SET_ERROR(EINVAL));
1516
1517         gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1518         gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1519         UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1520
1521         if (efi.dki_lba == 1) {
1522                 efi_gpt_t gpt = { 0 };
1523
1524                 gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1525                 gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1526                 gpt.efi_gpt_HeaderSize = LE_32(sizeof (gpt));
1527                 gpt.efi_gpt_MyLBA = LE_64(1ULL);
1528                 gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1529                 gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1530                 gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1531                 gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1532                 gpt.efi_gpt_SizeOfPartitionEntry =
1533                     LE_32(sizeof (efi_gpe_t));
1534                 CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1535                 gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1536                 CRC32(crc, &gpt, sizeof (gpt), -1U, crc32_table);
1537                 gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1538                 if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
1539                     flag))
1540                         return (SET_ERROR(EFAULT));
1541                 ptr += sizeof (gpt);
1542                 length -= sizeof (gpt);
1543         }
1544         if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
1545             length), flag))
1546                 return (SET_ERROR(EFAULT));
1547         return (0);
1548 }
1549
1550 /*
1551  * BEGIN entry points to allow external callers access to the volume.
1552  */
1553 /*
1554  * Return the volume parameters needed for access from an external caller.
1555  * These values are invariant as long as the volume is held open.
1556  */
1557 int
1558 zvol_get_volume_params(minor_t minor, uint64_t *blksize,
1559     uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
1560     void **rl_hdl, void **bonus_hdl)
1561 {
1562         zvol_state_t *zv;
1563
1564         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1565         if (zv == NULL)
1566                 return (SET_ERROR(ENXIO));
1567         if (zv->zv_flags & ZVOL_DUMPIFIED)
1568                 return (SET_ERROR(ENXIO));
1569
1570         ASSERT(blksize && max_xfer_len && minor_hdl &&
1571             objset_hdl && zil_hdl && rl_hdl && bonus_hdl);
1572
1573         *blksize = zv->zv_volblocksize;
1574         *max_xfer_len = (uint64_t)zvol_maxphys;
1575         *minor_hdl = zv;
1576         *objset_hdl = zv->zv_objset;
1577         *zil_hdl = zv->zv_zilog;
1578         *rl_hdl = &zv->zv_znode;
1579         *bonus_hdl = zv->zv_dbuf;
1580         return (0);
1581 }
1582
1583 /*
1584  * Return the current volume size to an external caller.
1585  * The size can change while the volume is open.
1586  */
1587 uint64_t
1588 zvol_get_volume_size(void *minor_hdl)
1589 {
1590         zvol_state_t *zv = minor_hdl;
1591
1592         return (zv->zv_volsize);
1593 }
1594
1595 /*
1596  * Return the current WCE setting to an external caller.
1597  * The WCE setting can change while the volume is open.
1598  */
1599 int
1600 zvol_get_volume_wce(void *minor_hdl)
1601 {
1602         zvol_state_t *zv = minor_hdl;
1603
1604         return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
1605 }
1606
1607 /*
1608  * Entry point for external callers to zvol_log_write
1609  */
1610 void
1611 zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
1612     boolean_t sync)
1613 {
1614         zvol_state_t *zv = minor_hdl;
1615
1616         zvol_log_write(zv, tx, off, resid, sync);
1617 }
1618 /*
1619  * END entry points to allow external callers access to the volume.
1620  */
1621
1622 /*
1623  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
1624  */
1625 /*ARGSUSED*/
1626 int
1627 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
1628 {
1629         zvol_state_t *zv;
1630         struct dk_cinfo dki;
1631         struct dk_minfo dkm;
1632         struct dk_callback *dkc;
1633         int error = 0;
1634         rl_t *rl;
1635
1636         mutex_enter(&spa_namespace_lock);
1637
1638         zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
1639
1640         if (zv == NULL) {
1641                 mutex_exit(&spa_namespace_lock);
1642                 return (SET_ERROR(ENXIO));
1643         }
1644         ASSERT(zv->zv_total_opens > 0);
1645
1646         switch (cmd) {
1647
1648         case DKIOCINFO:
1649                 bzero(&dki, sizeof (dki));
1650                 (void) strcpy(dki.dki_cname, "zvol");
1651                 (void) strcpy(dki.dki_dname, "zvol");
1652                 dki.dki_ctype = DKC_UNKNOWN;
1653                 dki.dki_unit = getminor(dev);
1654                 dki.dki_maxtransfer = 1 << (SPA_MAXBLOCKSHIFT - zv->zv_min_bs);
1655                 mutex_exit(&spa_namespace_lock);
1656                 if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
1657                         error = SET_ERROR(EFAULT);
1658                 return (error);
1659
1660         case DKIOCGMEDIAINFO:
1661                 bzero(&dkm, sizeof (dkm));
1662                 dkm.dki_lbsize = 1U << zv->zv_min_bs;
1663                 dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1664                 dkm.dki_media_type = DK_UNKNOWN;
1665                 mutex_exit(&spa_namespace_lock);
1666                 if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
1667                         error = SET_ERROR(EFAULT);
1668                 return (error);
1669
1670         case DKIOCGETEFI:
1671                 {
1672                         uint64_t vs = zv->zv_volsize;
1673                         uint8_t bs = zv->zv_min_bs;
1674
1675                         mutex_exit(&spa_namespace_lock);
1676                         error = zvol_getefi((void *)arg, flag, vs, bs);
1677                         return (error);
1678                 }
1679
1680         case DKIOCFLUSHWRITECACHE:
1681                 dkc = (struct dk_callback *)arg;
1682                 mutex_exit(&spa_namespace_lock);
1683                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1684                 if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
1685                         (*dkc->dkc_callback)(dkc->dkc_cookie, error);
1686                         error = 0;
1687                 }
1688                 return (error);
1689
1690         case DKIOCGETWCE:
1691                 {
1692                         int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
1693                         if (ddi_copyout(&wce, (void *)arg, sizeof (int),
1694                             flag))
1695                                 error = SET_ERROR(EFAULT);
1696                         break;
1697                 }
1698         case DKIOCSETWCE:
1699                 {
1700                         int wce;
1701                         if (ddi_copyin((void *)arg, &wce, sizeof (int),
1702                             flag)) {
1703                                 error = SET_ERROR(EFAULT);
1704                                 break;
1705                         }
1706                         if (wce) {
1707                                 zv->zv_flags |= ZVOL_WCE;
1708                                 mutex_exit(&spa_namespace_lock);
1709                         } else {
1710                                 zv->zv_flags &= ~ZVOL_WCE;
1711                                 mutex_exit(&spa_namespace_lock);
1712                                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1713                         }
1714                         return (0);
1715                 }
1716
1717         case DKIOCGGEOM:
1718         case DKIOCGVTOC:
1719                 /*
1720                  * commands using these (like prtvtoc) expect ENOTSUP
1721                  * since we're emulating an EFI label
1722                  */
1723                 error = SET_ERROR(ENOTSUP);
1724                 break;
1725
1726         case DKIOCDUMPINIT:
1727                 rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
1728                     RL_WRITER);
1729                 error = zvol_dumpify(zv);
1730                 zfs_range_unlock(rl);
1731                 break;
1732
1733         case DKIOCDUMPFINI:
1734                 if (!(zv->zv_flags & ZVOL_DUMPIFIED))
1735                         break;
1736                 rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
1737                     RL_WRITER);
1738                 error = zvol_dump_fini(zv);
1739                 zfs_range_unlock(rl);
1740                 break;
1741
1742         case DKIOCFREE:
1743         {
1744                 dkioc_free_t df;
1745                 dmu_tx_t *tx;
1746
1747                 if (ddi_copyin((void *)arg, &df, sizeof (df), flag)) {
1748                         error = SET_ERROR(EFAULT);
1749                         break;
1750                 }
1751
1752                 /*
1753                  * Apply Postel's Law to length-checking.  If they overshoot,
1754                  * just blank out until the end, if there's a need to blank
1755                  * out anything.
1756                  */
1757                 if (df.df_start >= zv->zv_volsize)
1758                         break;  /* No need to do anything... */
1759                 if (df.df_start + df.df_length > zv->zv_volsize)
1760                         df.df_length = DMU_OBJECT_END;
1761
1762                 rl = zfs_range_lock(&zv->zv_znode, df.df_start, df.df_length,
1763                     RL_WRITER);
1764                 tx = dmu_tx_create(zv->zv_objset);
1765                 error = dmu_tx_assign(tx, TXG_WAIT);
1766                 if (error != 0) {
1767                         dmu_tx_abort(tx);
1768                 } else {
1769                         zvol_log_truncate(zv, tx, df.df_start,
1770                             df.df_length, B_TRUE);
1771                         dmu_tx_commit(tx);
1772                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
1773                             df.df_start, df.df_length);
1774                 }
1775
1776                 zfs_range_unlock(rl);
1777
1778                 if (error == 0) {
1779                         /*
1780                          * If the write-cache is disabled or 'sync' property
1781                          * is set to 'always' then treat this as a synchronous
1782                          * operation (i.e. commit to zil).
1783                          */
1784                         if (!(zv->zv_flags & ZVOL_WCE) ||
1785                             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS))
1786                                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1787
1788                         /*
1789                          * If the caller really wants synchronous writes, and
1790                          * can't wait for them, don't return until the write
1791                          * is done.
1792                          */
1793                         if (df.df_flags & DF_WAIT_SYNC) {
1794                                 txg_wait_synced(
1795                                     dmu_objset_pool(zv->zv_objset), 0);
1796                         }
1797                 }
1798                 break;
1799         }
1800
1801         default:
1802                 error = SET_ERROR(ENOTTY);
1803                 break;
1804
1805         }
1806         mutex_exit(&spa_namespace_lock);
1807         return (error);
1808 }
1809 #endif  /* sun */
1810
1811 int
1812 zvol_busy(void)
1813 {
1814         return (zvol_minors != 0);
1815 }
1816
1817 void
1818 zvol_init(void)
1819 {
1820         VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
1821             1) == 0);
1822         ZFS_LOG(1, "ZVOL Initialized.");
1823 }
1824
1825 void
1826 zvol_fini(void)
1827 {
1828         ddi_soft_state_fini(&zfsdev_state);
1829         ZFS_LOG(1, "ZVOL Deinitialized.");
1830 }
1831
1832 #ifdef sun
1833 static int
1834 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
1835 {
1836         dmu_tx_t *tx;
1837         int error = 0;
1838         objset_t *os = zv->zv_objset;
1839         nvlist_t *nv = NULL;
1840         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
1841
1842         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1843         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
1844             DMU_OBJECT_END);
1845         /* wait for dmu_free_long_range to actually free the blocks */
1846         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1847
1848         tx = dmu_tx_create(os);
1849         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1850         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
1851         error = dmu_tx_assign(tx, TXG_WAIT);
1852         if (error) {
1853                 dmu_tx_abort(tx);
1854                 return (error);
1855         }
1856
1857         /*
1858          * If we are resizing the dump device then we only need to
1859          * update the refreservation to match the newly updated
1860          * zvolsize. Otherwise, we save off the original state of the
1861          * zvol so that we can restore them if the zvol is ever undumpified.
1862          */
1863         if (resize) {
1864                 error = zap_update(os, ZVOL_ZAP_OBJ,
1865                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1866                     &zv->zv_volsize, tx);
1867         } else {
1868                 uint64_t checksum, compress, refresrv, vbs, dedup;
1869
1870                 error = dsl_prop_get_integer(zv->zv_name,
1871                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
1872                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1873                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum, NULL);
1874                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1875                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &refresrv, NULL);
1876                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1877                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs, NULL);
1878                 if (version >= SPA_VERSION_DEDUP) {
1879                         error = error ? error :
1880                             dsl_prop_get_integer(zv->zv_name,
1881                             zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
1882                 }
1883
1884                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1885                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
1886                     &compress, tx);
1887                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1888                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum, tx);
1889                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1890                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1891                     &refresrv, tx);
1892                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1893                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
1894                     &vbs, tx);
1895                 error = error ? error : dmu_object_set_blocksize(
1896                     os, ZVOL_OBJ, SPA_MAXBLOCKSIZE, 0, tx);
1897                 if (version >= SPA_VERSION_DEDUP) {
1898                         error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1899                             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
1900                             &dedup, tx);
1901                 }
1902                 if (error == 0)
1903                         zv->zv_volblocksize = SPA_MAXBLOCKSIZE;
1904         }
1905         dmu_tx_commit(tx);
1906
1907         /*
1908          * We only need update the zvol's property if we are initializing
1909          * the dump area for the first time.
1910          */
1911         if (!resize) {
1912                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1913                 VERIFY(nvlist_add_uint64(nv,
1914                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
1915                 VERIFY(nvlist_add_uint64(nv,
1916                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
1917                     ZIO_COMPRESS_OFF) == 0);
1918                 VERIFY(nvlist_add_uint64(nv,
1919                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
1920                     ZIO_CHECKSUM_OFF) == 0);
1921                 if (version >= SPA_VERSION_DEDUP) {
1922                         VERIFY(nvlist_add_uint64(nv,
1923                             zfs_prop_to_name(ZFS_PROP_DEDUP),
1924                             ZIO_CHECKSUM_OFF) == 0);
1925                 }
1926
1927                 error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
1928                     nv, NULL);
1929                 nvlist_free(nv);
1930
1931                 if (error)
1932                         return (error);
1933         }
1934
1935         /* Allocate the space for the dump */
1936         error = zvol_prealloc(zv);
1937         return (error);
1938 }
1939
1940 static int
1941 zvol_dumpify(zvol_state_t *zv)
1942 {
1943         int error = 0;
1944         uint64_t dumpsize = 0;
1945         dmu_tx_t *tx;
1946         objset_t *os = zv->zv_objset;
1947
1948         if (zv->zv_flags & ZVOL_RDONLY)
1949                 return (SET_ERROR(EROFS));
1950
1951         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
1952             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
1953                 boolean_t resize = (dumpsize > 0);
1954
1955                 if ((error = zvol_dump_init(zv, resize)) != 0) {
1956                         (void) zvol_dump_fini(zv);
1957                         return (error);
1958                 }
1959         }
1960
1961         /*
1962          * Build up our lba mapping.
1963          */
1964         error = zvol_get_lbas(zv);
1965         if (error) {
1966                 (void) zvol_dump_fini(zv);
1967                 return (error);
1968         }
1969
1970         tx = dmu_tx_create(os);
1971         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1972         error = dmu_tx_assign(tx, TXG_WAIT);
1973         if (error) {
1974                 dmu_tx_abort(tx);
1975                 (void) zvol_dump_fini(zv);
1976                 return (error);
1977         }
1978
1979         zv->zv_flags |= ZVOL_DUMPIFIED;
1980         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
1981             &zv->zv_volsize, tx);
1982         dmu_tx_commit(tx);
1983
1984         if (error) {
1985                 (void) zvol_dump_fini(zv);
1986                 return (error);
1987         }
1988
1989         txg_wait_synced(dmu_objset_pool(os), 0);
1990         return (0);
1991 }
1992
1993 static int
1994 zvol_dump_fini(zvol_state_t *zv)
1995 {
1996         dmu_tx_t *tx;
1997         objset_t *os = zv->zv_objset;
1998         nvlist_t *nv;
1999         int error = 0;
2000         uint64_t checksum, compress, refresrv, vbs, dedup;
2001         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2002
2003         /*
2004          * Attempt to restore the zvol back to its pre-dumpified state.
2005          * This is a best-effort attempt as it's possible that not all
2006          * of these properties were initialized during the dumpify process
2007          * (i.e. error during zvol_dump_init).
2008          */
2009
2010         tx = dmu_tx_create(os);
2011         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2012         error = dmu_tx_assign(tx, TXG_WAIT);
2013         if (error) {
2014                 dmu_tx_abort(tx);
2015                 return (error);
2016         }
2017         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2018         dmu_tx_commit(tx);
2019
2020         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2021             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2022         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2023             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2024         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2025             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2026         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2027             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2028
2029         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2030         (void) nvlist_add_uint64(nv,
2031             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2032         (void) nvlist_add_uint64(nv,
2033             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2034         (void) nvlist_add_uint64(nv,
2035             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2036         if (version >= SPA_VERSION_DEDUP &&
2037             zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2038             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2039                 (void) nvlist_add_uint64(nv,
2040                     zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2041         }
2042         (void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2043             nv, NULL);
2044         nvlist_free(nv);
2045
2046         zvol_free_extents(zv);
2047         zv->zv_flags &= ~ZVOL_DUMPIFIED;
2048         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2049         /* wait for dmu_free_long_range to actually free the blocks */
2050         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2051         tx = dmu_tx_create(os);
2052         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2053         error = dmu_tx_assign(tx, TXG_WAIT);
2054         if (error) {
2055                 dmu_tx_abort(tx);
2056                 return (error);
2057         }
2058         if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2059                 zv->zv_volblocksize = vbs;
2060         dmu_tx_commit(tx);
2061
2062         return (0);
2063 }
2064 #endif  /* sun */
2065
2066 static zvol_state_t *
2067 zvol_geom_create(const char *name)
2068 {
2069         struct g_provider *pp;
2070         struct g_geom *gp;
2071         zvol_state_t *zv;
2072
2073         gp = g_new_geomf(&zfs_zvol_class, "zfs::zvol::%s", name);
2074         gp->start = zvol_geom_start;
2075         gp->access = zvol_geom_access;
2076         pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, name);
2077         pp->sectorsize = DEV_BSIZE;
2078
2079         zv = kmem_zalloc(sizeof(*zv), KM_SLEEP);
2080         zv->zv_provider = pp;
2081         zv->zv_state = 0;
2082         bioq_init(&zv->zv_queue);
2083         mtx_init(&zv->zv_queue_mtx, "zvol", NULL, MTX_DEF);
2084
2085         pp->private = zv;
2086
2087         return (zv);
2088 }
2089
2090 static void
2091 zvol_geom_run(zvol_state_t *zv)
2092 {
2093         struct g_provider *pp;
2094
2095         pp = zv->zv_provider;
2096         g_error_provider(pp, 0);
2097
2098         kproc_kthread_add(zvol_geom_worker, zv, &zfsproc, NULL, 0, 0,
2099             "zfskern", "zvol %s", pp->name + sizeof(ZVOL_DRIVER));
2100 }
2101
2102 static void
2103 zvol_geom_destroy(zvol_state_t *zv)
2104 {
2105         struct g_provider *pp;
2106
2107         g_topology_assert();
2108
2109         mtx_lock(&zv->zv_queue_mtx);
2110         zv->zv_state = 1;
2111         wakeup_one(&zv->zv_queue);
2112         while (zv->zv_state != 2)
2113                 msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
2114         mtx_destroy(&zv->zv_queue_mtx);
2115
2116         pp = zv->zv_provider;
2117         zv->zv_provider = NULL;
2118         pp->private = NULL;
2119         g_wither_geom(pp->geom, ENXIO);
2120
2121         kmem_free(zv, sizeof(*zv));
2122 }
2123
2124 static int
2125 zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace)
2126 {
2127         int count, error, flags;
2128
2129         g_topology_assert();
2130
2131         /*
2132          * To make it easier we expect either open or close, but not both
2133          * at the same time.
2134          */
2135         KASSERT((acr >= 0 && acw >= 0 && ace >= 0) ||
2136             (acr <= 0 && acw <= 0 && ace <= 0),
2137             ("Unsupported access request to %s (acr=%d, acw=%d, ace=%d).",
2138             pp->name, acr, acw, ace));
2139
2140         if (pp->private == NULL) {
2141                 if (acr <= 0 && acw <= 0 && ace <= 0)
2142                         return (0);
2143                 return (pp->error);
2144         }
2145
2146         /*
2147          * We don't pass FEXCL flag to zvol_open()/zvol_close() if ace != 0,
2148          * because GEOM already handles that and handles it a bit differently.
2149          * GEOM allows for multiple read/exclusive consumers and ZFS allows
2150          * only one exclusive consumer, no matter if it is reader or writer.
2151          * I like better the way GEOM works so I'll leave it for GEOM to
2152          * decide what to do.
2153          */
2154
2155         count = acr + acw + ace;
2156         if (count == 0)
2157                 return (0);
2158
2159         flags = 0;
2160         if (acr != 0 || ace != 0)
2161                 flags |= FREAD;
2162         if (acw != 0)
2163                 flags |= FWRITE;
2164
2165         g_topology_unlock();
2166         if (count > 0)
2167                 error = zvol_open(pp, flags, count);
2168         else
2169                 error = zvol_close(pp, flags, -count);
2170         g_topology_lock();
2171         return (error);
2172 }
2173
2174 static void
2175 zvol_geom_start(struct bio *bp)
2176 {
2177         zvol_state_t *zv;
2178         boolean_t first;
2179
2180         switch (bp->bio_cmd) {
2181         case BIO_READ:
2182         case BIO_WRITE:
2183         case BIO_FLUSH:
2184                 zv = bp->bio_to->private;
2185                 ASSERT(zv != NULL);
2186                 mtx_lock(&zv->zv_queue_mtx);
2187                 first = (bioq_first(&zv->zv_queue) == NULL);
2188                 bioq_insert_tail(&zv->zv_queue, bp);
2189                 mtx_unlock(&zv->zv_queue_mtx);
2190                 if (first)
2191                         wakeup_one(&zv->zv_queue);
2192                 break;
2193         case BIO_GETATTR:
2194         case BIO_DELETE:
2195         default:
2196                 g_io_deliver(bp, EOPNOTSUPP);
2197                 break;
2198         }
2199 }
2200
2201 static void
2202 zvol_geom_worker(void *arg)
2203 {
2204         zvol_state_t *zv;
2205         struct bio *bp;
2206
2207         thread_lock(curthread);
2208         sched_prio(curthread, PRIBIO);
2209         thread_unlock(curthread);
2210
2211         zv = arg;
2212         for (;;) {
2213                 mtx_lock(&zv->zv_queue_mtx);
2214                 bp = bioq_takefirst(&zv->zv_queue);
2215                 if (bp == NULL) {
2216                         if (zv->zv_state == 1) {
2217                                 zv->zv_state = 2;
2218                                 wakeup(&zv->zv_state);
2219                                 mtx_unlock(&zv->zv_queue_mtx);
2220                                 kthread_exit();
2221                         }
2222                         msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
2223                             "zvol:io", 0);
2224                         continue;
2225                 }
2226                 mtx_unlock(&zv->zv_queue_mtx);
2227                 switch (bp->bio_cmd) {
2228                 case BIO_FLUSH:
2229                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2230                         g_io_deliver(bp, 0);
2231                         break;
2232                 case BIO_READ:
2233                 case BIO_WRITE:
2234                         zvol_strategy(bp);
2235                         break;
2236                 }
2237         }
2238 }
2239
2240 extern boolean_t dataset_name_hidden(const char *name);
2241
2242 static int
2243 zvol_create_snapshots(objset_t *os, const char *name)
2244 {
2245         uint64_t cookie, obj;
2246         char *sname;
2247         int error, len;
2248
2249         cookie = obj = 0;
2250         sname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2251
2252 #if 0
2253         (void) dmu_objset_find(name, dmu_objset_prefetch, NULL,
2254             DS_FIND_SNAPSHOTS);
2255 #endif
2256
2257         for (;;) {
2258                 len = snprintf(sname, MAXPATHLEN, "%s@", name);
2259                 if (len >= MAXPATHLEN) {
2260                         dmu_objset_rele(os, FTAG);
2261                         error = ENAMETOOLONG;
2262                         break;
2263                 }
2264
2265                 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2266                 error = dmu_snapshot_list_next(os, MAXPATHLEN - len,
2267                     sname + len, &obj, &cookie, NULL);
2268                 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2269                 if (error != 0) {
2270                         if (error == ENOENT)
2271                                 error = 0;
2272                         break;
2273                 }
2274
2275                 if ((error = zvol_create_minor(sname)) != 0) {
2276                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2277                             sname, error);
2278                         break;
2279                 }
2280         }
2281
2282         kmem_free(sname, MAXPATHLEN);
2283         return (error);
2284 }
2285
2286 int
2287 zvol_create_minors(const char *name)
2288 {
2289         uint64_t cookie;
2290         objset_t *os;
2291         char *osname, *p;
2292         int error, len;
2293
2294         if (dataset_name_hidden(name))
2295                 return (0);
2296
2297         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2298                 printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2299                     name, error);
2300                 return (error);
2301         }
2302         if (dmu_objset_type(os) == DMU_OST_ZVOL) {
2303                 dsl_dataset_long_hold(os->os_dsl_dataset, FTAG);
2304                 dsl_pool_rele(dmu_objset_pool(os), FTAG);
2305                 if ((error = zvol_create_minor(name)) == 0)
2306                         error = zvol_create_snapshots(os, name);
2307                 else {
2308                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2309                             name, error);
2310                 }
2311                 dsl_dataset_long_rele(os->os_dsl_dataset, FTAG);
2312                 dsl_dataset_rele(os->os_dsl_dataset, FTAG);
2313                 return (error);
2314         }
2315         if (dmu_objset_type(os) != DMU_OST_ZFS) {
2316                 dmu_objset_rele(os, FTAG);
2317                 return (0);
2318         }
2319
2320         osname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2321         if (snprintf(osname, MAXPATHLEN, "%s/", name) >= MAXPATHLEN) {
2322                 dmu_objset_rele(os, FTAG);
2323                 kmem_free(osname, MAXPATHLEN);
2324                 return (ENOENT);
2325         }
2326         p = osname + strlen(osname);
2327         len = MAXPATHLEN - (p - osname);
2328
2329 #if 0
2330         /* Prefetch the datasets. */
2331         cookie = 0;
2332         while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2333                 if (!dataset_name_hidden(osname))
2334                         (void) dmu_objset_prefetch(osname, NULL);
2335         }
2336 #endif
2337
2338         cookie = 0;
2339         while (dmu_dir_list_next(os, MAXPATHLEN - (p - osname), p, NULL,
2340             &cookie) == 0) {
2341                 dmu_objset_rele(os, FTAG);
2342                 (void)zvol_create_minors(osname);
2343                 if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2344                         printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2345                             name, error);
2346                         return (error);
2347                 }
2348         }
2349
2350         dmu_objset_rele(os, FTAG);
2351         kmem_free(osname, MAXPATHLEN);
2352         return (0);
2353 }
2354
2355 static void
2356 zvol_rename_minor(struct g_geom *gp, const char *newname)
2357 {
2358         struct g_provider *pp;
2359         zvol_state_t *zv;
2360
2361         ASSERT(MUTEX_HELD(&spa_namespace_lock));
2362         g_topology_assert();
2363
2364         pp = LIST_FIRST(&gp->provider);
2365         ASSERT(pp != NULL);
2366         zv = pp->private;
2367         ASSERT(zv != NULL);
2368
2369         zv->zv_provider = NULL;
2370         g_wither_provider(pp, ENXIO);
2371
2372         pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, newname);
2373         pp->sectorsize = DEV_BSIZE;
2374         pp->mediasize = zv->zv_volsize;
2375         pp->private = zv;
2376         zv->zv_provider = pp;
2377         strlcpy(zv->zv_name, newname, sizeof(zv->zv_name));
2378         g_error_provider(pp, 0);
2379 }
2380
2381 void
2382 zvol_rename_minors(const char *oldname, const char *newname)
2383 {
2384         char name[MAXPATHLEN];
2385         struct g_provider *pp;
2386         struct g_geom *gp;
2387         size_t oldnamelen, newnamelen;
2388         zvol_state_t *zv;
2389         char *namebuf;
2390
2391         oldnamelen = strlen(oldname);
2392         newnamelen = strlen(newname);
2393
2394         DROP_GIANT();
2395         mutex_enter(&spa_namespace_lock);
2396         g_topology_lock();
2397
2398         LIST_FOREACH(gp, &zfs_zvol_class.geom, geom) {
2399                 pp = LIST_FIRST(&gp->provider);
2400                 if (pp == NULL)
2401                         continue;
2402                 zv = pp->private;
2403                 if (zv == NULL)
2404                         continue;
2405                 if (strcmp(zv->zv_name, oldname) == 0) {
2406                         zvol_rename_minor(gp, newname);
2407                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
2408                     (zv->zv_name[oldnamelen] == '/' ||
2409                      zv->zv_name[oldnamelen] == '@')) {
2410                         snprintf(name, sizeof(name), "%s%c%s", newname,
2411                             zv->zv_name[oldnamelen],
2412                             zv->zv_name + oldnamelen + 1);
2413                         zvol_rename_minor(gp, name);
2414                 }
2415         }
2416
2417         g_topology_unlock();
2418         mutex_exit(&spa_namespace_lock);
2419         PICKUP_GIANT();
2420 }