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