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