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