]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c
Merge recent vendor changes:
[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
675         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
676         zv->zv_dbuf = NULL;
677
678         /*
679          * Evict cached data
680          */
681         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
682             !(zv->zv_flags & ZVOL_RDONLY))
683                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
684         (void) dmu_objset_evict_dbufs(zv->zv_objset);
685
686         dmu_objset_disown(zv->zv_objset, zvol_tag);
687         zv->zv_objset = NULL;
688 }
689
690 #ifdef sun
691 int
692 zvol_prealloc(zvol_state_t *zv)
693 {
694         objset_t *os = zv->zv_objset;
695         dmu_tx_t *tx;
696         uint64_t refd, avail, usedobjs, availobjs;
697         uint64_t resid = zv->zv_volsize;
698         uint64_t off = 0;
699
700         /* Check the space usage before attempting to allocate the space */
701         dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
702         if (avail < zv->zv_volsize)
703                 return (ENOSPC);
704
705         /* Free old extents if they exist */
706         zvol_free_extents(zv);
707
708         while (resid != 0) {
709                 int error;
710                 uint64_t bytes = MIN(resid, SPA_MAXBLOCKSIZE);
711
712                 tx = dmu_tx_create(os);
713                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
714                 error = dmu_tx_assign(tx, TXG_WAIT);
715                 if (error) {
716                         dmu_tx_abort(tx);
717                         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
718                         return (error);
719                 }
720                 dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
721                 dmu_tx_commit(tx);
722                 off += bytes;
723                 resid -= bytes;
724         }
725         txg_wait_synced(dmu_objset_pool(os), 0);
726
727         return (0);
728 }
729 #endif  /* sun */
730
731 int
732 zvol_update_volsize(objset_t *os, uint64_t volsize)
733 {
734         dmu_tx_t *tx;
735         int error;
736
737         ASSERT(MUTEX_HELD(&spa_namespace_lock));
738
739         tx = dmu_tx_create(os);
740         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
741         error = dmu_tx_assign(tx, TXG_WAIT);
742         if (error) {
743                 dmu_tx_abort(tx);
744                 return (error);
745         }
746
747         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
748             &volsize, tx);
749         dmu_tx_commit(tx);
750
751         if (error == 0)
752                 error = dmu_free_long_range(os,
753                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
754         return (error);
755 }
756
757 void
758 zvol_remove_minors(const char *name)
759 {
760         struct g_geom *gp, *gptmp;
761         struct g_provider *pp;
762         zvol_state_t *zv;
763         size_t namelen;
764
765         namelen = strlen(name);
766
767         DROP_GIANT();
768         mutex_enter(&spa_namespace_lock);
769         g_topology_lock();
770
771         LIST_FOREACH_SAFE(gp, &zfs_zvol_class.geom, geom, gptmp) {
772                 pp = LIST_FIRST(&gp->provider);
773                 if (pp == NULL)
774                         continue;
775                 zv = pp->private;
776                 if (zv == NULL)
777                         continue;
778                 if (strcmp(zv->zv_name, name) == 0 ||
779                     (strncmp(zv->zv_name, name, namelen) == 0 &&
780                      zv->zv_name[namelen] == '/')) {
781                         (void) zvol_remove_zv(zv);
782                 }
783         }
784
785         g_topology_unlock();
786         mutex_exit(&spa_namespace_lock);
787         PICKUP_GIANT();
788 }
789
790 int
791 zvol_set_volsize(const char *name, major_t maj, uint64_t volsize)
792 {
793         zvol_state_t *zv = NULL;
794         objset_t *os;
795         int error;
796         dmu_object_info_t doi;
797         uint64_t old_volsize = 0ULL;
798         uint64_t readonly;
799
800         mutex_enter(&spa_namespace_lock);
801         zv = zvol_minor_lookup(name);
802         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
803                 mutex_exit(&spa_namespace_lock);
804                 return (error);
805         }
806
807         if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
808             (error = zvol_check_volsize(volsize,
809             doi.doi_data_block_size)) != 0)
810                 goto out;
811
812         VERIFY(dsl_prop_get_integer(name, "readonly", &readonly,
813             NULL) == 0);
814         if (readonly) {
815                 error = EROFS;
816                 goto out;
817         }
818
819         error = zvol_update_volsize(os, volsize);
820         /*
821          * Reinitialize the dump area to the new size. If we
822          * failed to resize the dump area then restore it back to
823          * its original size.
824          */
825         if (zv && error == 0) {
826 #ifdef ZVOL_DUMP
827                 if (zv->zv_flags & ZVOL_DUMPIFIED) {
828                         old_volsize = zv->zv_volsize;
829                         zv->zv_volsize = volsize;
830                         if ((error = zvol_dumpify(zv)) != 0 ||
831                             (error = dumpvp_resize()) != 0) {
832                                 (void) zvol_update_volsize(os, old_volsize);
833                                 zv->zv_volsize = old_volsize;
834                                 error = zvol_dumpify(zv);
835                         }
836                 }
837 #endif  /* ZVOL_DUMP */
838                 if (error == 0) {
839                         zv->zv_volsize = volsize;
840                         zvol_size_changed(zv);
841                 }
842         }
843
844 #ifdef sun
845         /*
846          * Generate a LUN expansion event.
847          */
848         if (zv && error == 0) {
849                 sysevent_id_t eid;
850                 nvlist_t *attr;
851                 char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
852
853                 (void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
854                     zv->zv_minor);
855
856                 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
857                 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
858
859                 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
860                     ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
861
862                 nvlist_free(attr);
863                 kmem_free(physpath, MAXPATHLEN);
864         }
865 #endif  /* sun */
866
867 out:
868         dmu_objset_rele(os, FTAG);
869
870         mutex_exit(&spa_namespace_lock);
871
872         return (error);
873 }
874
875 /*ARGSUSED*/
876 static int
877 zvol_open(struct g_provider *pp, int flag, int count)
878 {
879         zvol_state_t *zv;
880         int err = 0;
881
882         if (MUTEX_HELD(&spa_namespace_lock)) {
883                 /*
884                  * If the spa_namespace_lock is being held, it means that ZFS
885                  * is trying to open ZVOL as its VDEV. This is not supported.
886                  */
887                 return (EOPNOTSUPP);
888         }
889
890         mutex_enter(&spa_namespace_lock);
891
892         zv = pp->private;
893         if (zv == NULL) {
894                 mutex_exit(&spa_namespace_lock);
895                 return (ENXIO);
896         }
897
898         if (zv->zv_total_opens == 0)
899                 err = zvol_first_open(zv);
900         if (err) {
901                 mutex_exit(&spa_namespace_lock);
902                 return (err);
903         }
904         if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
905                 err = EROFS;
906                 goto out;
907         }
908         if (zv->zv_flags & ZVOL_EXCL) {
909                 err = EBUSY;
910                 goto out;
911         }
912 #ifdef FEXCL
913         if (flag & FEXCL) {
914                 if (zv->zv_total_opens != 0) {
915                         err = EBUSY;
916                         goto out;
917                 }
918                 zv->zv_flags |= ZVOL_EXCL;
919         }
920 #endif
921
922         zv->zv_total_opens += count;
923         mutex_exit(&spa_namespace_lock);
924
925         return (err);
926 out:
927         if (zv->zv_total_opens == 0)
928                 zvol_last_close(zv);
929         mutex_exit(&spa_namespace_lock);
930         return (err);
931 }
932
933 /*ARGSUSED*/
934 static int
935 zvol_close(struct g_provider *pp, int flag, int count)
936 {
937         zvol_state_t *zv;
938         int error = 0;
939
940         mutex_enter(&spa_namespace_lock);
941
942         zv = pp->private;
943         if (zv == NULL) {
944                 mutex_exit(&spa_namespace_lock);
945                 return (ENXIO);
946         }
947
948         if (zv->zv_flags & ZVOL_EXCL) {
949                 ASSERT(zv->zv_total_opens == 1);
950                 zv->zv_flags &= ~ZVOL_EXCL;
951         }
952
953         /*
954          * If the open count is zero, this is a spurious close.
955          * That indicates a bug in the kernel / DDI framework.
956          */
957         ASSERT(zv->zv_total_opens != 0);
958
959         /*
960          * You may get multiple opens, but only one close.
961          */
962         zv->zv_total_opens -= count;
963
964         if (zv->zv_total_opens == 0)
965                 zvol_last_close(zv);
966
967         mutex_exit(&spa_namespace_lock);
968         return (error);
969 }
970
971 static void
972 zvol_get_done(zgd_t *zgd, int error)
973 {
974         if (zgd->zgd_db)
975                 dmu_buf_rele(zgd->zgd_db, zgd);
976
977         zfs_range_unlock(zgd->zgd_rl);
978
979         if (error == 0 && zgd->zgd_bp)
980                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
981
982         kmem_free(zgd, sizeof (zgd_t));
983 }
984
985 /*
986  * Get data to generate a TX_WRITE intent log record.
987  */
988 static int
989 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
990 {
991         zvol_state_t *zv = arg;
992         objset_t *os = zv->zv_objset;
993         uint64_t object = ZVOL_OBJ;
994         uint64_t offset = lr->lr_offset;
995         uint64_t size = lr->lr_length;  /* length of user data */
996         blkptr_t *bp = &lr->lr_blkptr;
997         dmu_buf_t *db;
998         zgd_t *zgd;
999         int error;
1000
1001         ASSERT(zio != NULL);
1002         ASSERT(size != 0);
1003
1004         zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1005         zgd->zgd_zilog = zv->zv_zilog;
1006         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
1007
1008         /*
1009          * Write records come in two flavors: immediate and indirect.
1010          * For small writes it's cheaper to store the data with the
1011          * log record (immediate); for large writes it's cheaper to
1012          * sync the data and get a pointer to it (indirect) so that
1013          * we don't have to write the data twice.
1014          */
1015         if (buf != NULL) {      /* immediate write */
1016                 error = dmu_read(os, object, offset, size, buf,
1017                     DMU_READ_NO_PREFETCH);
1018         } else {
1019                 size = zv->zv_volblocksize;
1020                 offset = P2ALIGN(offset, size);
1021                 error = dmu_buf_hold(os, object, offset, zgd, &db,
1022                     DMU_READ_NO_PREFETCH);
1023                 if (error == 0) {
1024                         zgd->zgd_db = db;
1025                         zgd->zgd_bp = bp;
1026
1027                         ASSERT(db->db_offset == offset);
1028                         ASSERT(db->db_size == size);
1029
1030                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1031                             zvol_get_done, zgd);
1032
1033                         if (error == 0)
1034                                 return (0);
1035                 }
1036         }
1037
1038         zvol_get_done(zgd, error);
1039
1040         return (error);
1041 }
1042
1043 /*
1044  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1045  *
1046  * We store data in the log buffers if it's small enough.
1047  * Otherwise we will later flush the data out via dmu_sync().
1048  */
1049 ssize_t zvol_immediate_write_sz = 32768;
1050
1051 static void
1052 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1053     boolean_t sync)
1054 {
1055         uint32_t blocksize = zv->zv_volblocksize;
1056         zilog_t *zilog = zv->zv_zilog;
1057         boolean_t slogging;
1058         ssize_t immediate_write_sz;
1059
1060         if (zil_replaying(zilog, tx))
1061                 return;
1062
1063         immediate_write_sz = (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1064             ? 0 : zvol_immediate_write_sz;
1065
1066         slogging = spa_has_slogs(zilog->zl_spa) &&
1067             (zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
1068
1069         while (resid) {
1070                 itx_t *itx;
1071                 lr_write_t *lr;
1072                 ssize_t len;
1073                 itx_wr_state_t write_state;
1074
1075                 /*
1076                  * Unlike zfs_log_write() we can be called with
1077                  * upto DMU_MAX_ACCESS/2 (5MB) writes.
1078                  */
1079                 if (blocksize > immediate_write_sz && !slogging &&
1080                     resid >= blocksize && off % blocksize == 0) {
1081                         write_state = WR_INDIRECT; /* uses dmu_sync */
1082                         len = blocksize;
1083                 } else if (sync) {
1084                         write_state = WR_COPIED;
1085                         len = MIN(ZIL_MAX_LOG_DATA, resid);
1086                 } else {
1087                         write_state = WR_NEED_COPY;
1088                         len = MIN(ZIL_MAX_LOG_DATA, resid);
1089                 }
1090
1091                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1092                     (write_state == WR_COPIED ? len : 0));
1093                 lr = (lr_write_t *)&itx->itx_lr;
1094                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
1095                     ZVOL_OBJ, off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1096                         zil_itx_destroy(itx);
1097                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1098                         lr = (lr_write_t *)&itx->itx_lr;
1099                         write_state = WR_NEED_COPY;
1100                 }
1101
1102                 itx->itx_wr_state = write_state;
1103                 if (write_state == WR_NEED_COPY)
1104                         itx->itx_sod += len;
1105                 lr->lr_foid = ZVOL_OBJ;
1106                 lr->lr_offset = off;
1107                 lr->lr_length = len;
1108                 lr->lr_blkoff = 0;
1109                 BP_ZERO(&lr->lr_blkptr);
1110
1111                 itx->itx_private = zv;
1112                 itx->itx_sync = sync;
1113
1114                 zil_itx_assign(zilog, itx, tx);
1115
1116                 off += len;
1117                 resid -= len;
1118         }
1119 }
1120
1121 #ifdef sun
1122 static int
1123 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t size,
1124     boolean_t doread, boolean_t isdump)
1125 {
1126         vdev_disk_t *dvd;
1127         int c;
1128         int numerrors = 0;
1129
1130         for (c = 0; c < vd->vdev_children; c++) {
1131                 ASSERT(vd->vdev_ops == &vdev_mirror_ops ||
1132                     vd->vdev_ops == &vdev_replacing_ops ||
1133                     vd->vdev_ops == &vdev_spare_ops);
1134                 int err = zvol_dumpio_vdev(vd->vdev_child[c],
1135                     addr, offset, size, doread, isdump);
1136                 if (err != 0) {
1137                         numerrors++;
1138                 } else if (doread) {
1139                         break;
1140                 }
1141         }
1142
1143         if (!vd->vdev_ops->vdev_op_leaf)
1144                 return (numerrors < vd->vdev_children ? 0 : EIO);
1145
1146         if (doread && !vdev_readable(vd))
1147                 return (EIO);
1148         else if (!doread && !vdev_writeable(vd))
1149                 return (EIO);
1150
1151         dvd = vd->vdev_tsd;
1152         ASSERT3P(dvd, !=, NULL);
1153         offset += VDEV_LABEL_START_SIZE;
1154
1155         if (ddi_in_panic() || isdump) {
1156                 ASSERT(!doread);
1157                 if (doread)
1158                         return (EIO);
1159                 return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1160                     lbtodb(size)));
1161         } else {
1162                 return (vdev_disk_physio(dvd->vd_lh, addr, size, offset,
1163                     doread ? B_READ : B_WRITE));
1164         }
1165 }
1166
1167 static int
1168 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1169     boolean_t doread, boolean_t isdump)
1170 {
1171         vdev_t *vd;
1172         int error;
1173         zvol_extent_t *ze;
1174         spa_t *spa = dmu_objset_spa(zv->zv_objset);
1175
1176         /* Must be sector aligned, and not stradle a block boundary. */
1177         if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1178             P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1179                 return (EINVAL);
1180         }
1181         ASSERT(size <= zv->zv_volblocksize);
1182
1183         /* Locate the extent this belongs to */
1184         ze = list_head(&zv->zv_extents);
1185         while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1186                 offset -= ze->ze_nblks * zv->zv_volblocksize;
1187                 ze = list_next(&zv->zv_extents, ze);
1188         }
1189
1190         if (!ddi_in_panic())
1191                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1192
1193         vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1194         offset += DVA_GET_OFFSET(&ze->ze_dva);
1195         error = zvol_dumpio_vdev(vd, addr, offset, size, doread, isdump);
1196
1197         if (!ddi_in_panic())
1198                 spa_config_exit(spa, SCL_STATE, FTAG);
1199
1200         return (error);
1201 }
1202 #endif  /* sun */
1203
1204 int
1205 zvol_strategy(struct bio *bp)
1206 {
1207         zvol_state_t *zv = bp->bio_to->private;
1208         uint64_t off, volsize;
1209         size_t resid;
1210         char *addr;
1211         objset_t *os;
1212         rl_t *rl;
1213         int error = 0;
1214         boolean_t doread = (bp->bio_cmd == BIO_READ);
1215         boolean_t sync;
1216
1217         if (zv == NULL) {
1218                 g_io_deliver(bp, ENXIO);
1219                 return (0);
1220         }
1221
1222         if (bp->bio_cmd != BIO_READ && (zv->zv_flags & ZVOL_RDONLY)) {
1223                 g_io_deliver(bp, EROFS);
1224                 return (0);
1225         }
1226
1227         off = bp->bio_offset;
1228         volsize = zv->zv_volsize;
1229
1230         os = zv->zv_objset;
1231         ASSERT(os != NULL);
1232
1233         addr = bp->bio_data;
1234         resid = bp->bio_length;
1235
1236         if (resid > 0 && (off < 0 || off >= volsize)) {
1237                 g_io_deliver(bp, EIO);
1238                 return (0);
1239         }
1240
1241         sync = !doread && zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
1242
1243         /*
1244          * There must be no buffer changes when doing a dmu_sync() because
1245          * we can't change the data whilst calculating the checksum.
1246          */
1247         rl = zfs_range_lock(&zv->zv_znode, off, resid,
1248             doread ? RL_READER : RL_WRITER);
1249
1250         while (resid != 0 && off < volsize) {
1251                 size_t size = MIN(resid, zvol_maxphys);
1252                 if (doread) {
1253                         error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1254                             DMU_READ_PREFETCH);
1255                 } else {
1256                         dmu_tx_t *tx = dmu_tx_create(os);
1257                         dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1258                         error = dmu_tx_assign(tx, TXG_WAIT);
1259                         if (error) {
1260                                 dmu_tx_abort(tx);
1261                         } else {
1262                                 dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1263                                 zvol_log_write(zv, tx, off, size, sync);
1264                                 dmu_tx_commit(tx);
1265                         }
1266                 }
1267                 if (error) {
1268                         /* convert checksum errors into IO errors */
1269                         if (error == ECKSUM)
1270                                 error = EIO;
1271                         break;
1272                 }
1273                 off += size;
1274                 addr += size;
1275                 resid -= size;
1276         }
1277         zfs_range_unlock(rl);
1278
1279         bp->bio_completed = bp->bio_length - resid;
1280         if (bp->bio_completed < bp->bio_length)
1281                 bp->bio_error = (off > volsize ? EINVAL : error);
1282
1283         if (sync)
1284                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1285         g_io_deliver(bp, 0);
1286
1287         return (0);
1288 }
1289
1290 #ifdef sun
1291 /*
1292  * Set the buffer count to the zvol maximum transfer.
1293  * Using our own routine instead of the default minphys()
1294  * means that for larger writes we write bigger buffers on X86
1295  * (128K instead of 56K) and flush the disk write cache less often
1296  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1297  * 56K on X86 and 128K on sparc).
1298  */
1299 void
1300 zvol_minphys(struct buf *bp)
1301 {
1302         if (bp->b_bcount > zvol_maxphys)
1303                 bp->b_bcount = zvol_maxphys;
1304 }
1305
1306 int
1307 zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1308 {
1309         minor_t minor = getminor(dev);
1310         zvol_state_t *zv;
1311         int error = 0;
1312         uint64_t size;
1313         uint64_t boff;
1314         uint64_t resid;
1315
1316         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1317         if (zv == NULL)
1318                 return (ENXIO);
1319
1320         boff = ldbtob(blkno);
1321         resid = ldbtob(nblocks);
1322
1323         VERIFY3U(boff + resid, <=, zv->zv_volsize);
1324
1325         while (resid) {
1326                 size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1327                 error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1328                 if (error)
1329                         break;
1330                 boff += size;
1331                 addr += size;
1332                 resid -= size;
1333         }
1334
1335         return (error);
1336 }
1337
1338 /*ARGSUSED*/
1339 int
1340 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1341 {
1342         minor_t minor = getminor(dev);
1343         zvol_state_t *zv;
1344         uint64_t volsize;
1345         rl_t *rl;
1346         int error = 0;
1347
1348         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1349         if (zv == NULL)
1350                 return (ENXIO);
1351
1352         volsize = zv->zv_volsize;
1353         if (uio->uio_resid > 0 &&
1354             (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1355                 return (EIO);
1356
1357         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1358                 error = physio(zvol_strategy, NULL, dev, B_READ,
1359                     zvol_minphys, uio);
1360                 return (error);
1361         }
1362
1363         rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1364             RL_READER);
1365         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1366                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1367
1368                 /* don't read past the end */
1369                 if (bytes > volsize - uio->uio_loffset)
1370                         bytes = volsize - uio->uio_loffset;
1371
1372                 error =  dmu_read_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes);
1373                 if (error) {
1374                         /* convert checksum errors into IO errors */
1375                         if (error == ECKSUM)
1376                                 error = EIO;
1377                         break;
1378                 }
1379         }
1380         zfs_range_unlock(rl);
1381         return (error);
1382 }
1383
1384 /*ARGSUSED*/
1385 int
1386 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1387 {
1388         minor_t minor = getminor(dev);
1389         zvol_state_t *zv;
1390         uint64_t volsize;
1391         rl_t *rl;
1392         int error = 0;
1393         boolean_t sync;
1394
1395         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1396         if (zv == NULL)
1397                 return (ENXIO);
1398
1399         volsize = zv->zv_volsize;
1400         if (uio->uio_resid > 0 &&
1401             (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1402                 return (EIO);
1403
1404         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1405                 error = physio(zvol_strategy, NULL, dev, B_WRITE,
1406                     zvol_minphys, uio);
1407                 return (error);
1408         }
1409
1410         sync = !(zv->zv_flags & ZVOL_WCE) ||
1411             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1412
1413         rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1414             RL_WRITER);
1415         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1416                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1417                 uint64_t off = uio->uio_loffset;
1418                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1419
1420                 if (bytes > volsize - off)      /* don't write past the end */
1421                         bytes = volsize - off;
1422
1423                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1424                 error = dmu_tx_assign(tx, TXG_WAIT);
1425                 if (error) {
1426                         dmu_tx_abort(tx);
1427                         break;
1428                 }
1429                 error = dmu_write_uio_dbuf(zv->zv_dbuf, uio, bytes, tx);
1430                 if (error == 0)
1431                         zvol_log_write(zv, tx, off, bytes, sync);
1432                 dmu_tx_commit(tx);
1433
1434                 if (error)
1435                         break;
1436         }
1437         zfs_range_unlock(rl);
1438         if (sync)
1439                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1440         return (error);
1441 }
1442
1443 int
1444 zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1445 {
1446         struct uuid uuid = EFI_RESERVED;
1447         efi_gpe_t gpe = { 0 };
1448         uint32_t crc;
1449         dk_efi_t efi;
1450         int length;
1451         char *ptr;
1452
1453         if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1454                 return (EFAULT);
1455         ptr = (char *)(uintptr_t)efi.dki_data_64;
1456         length = efi.dki_length;
1457         /*
1458          * Some clients may attempt to request a PMBR for the
1459          * zvol.  Currently this interface will return EINVAL to
1460          * such requests.  These requests could be supported by
1461          * adding a check for lba == 0 and consing up an appropriate
1462          * PMBR.
1463          */
1464         if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1465                 return (EINVAL);
1466
1467         gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1468         gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1469         UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1470
1471         if (efi.dki_lba == 1) {
1472                 efi_gpt_t gpt = { 0 };
1473
1474                 gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1475                 gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1476                 gpt.efi_gpt_HeaderSize = LE_32(sizeof (gpt));
1477                 gpt.efi_gpt_MyLBA = LE_64(1ULL);
1478                 gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1479                 gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1480                 gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1481                 gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1482                 gpt.efi_gpt_SizeOfPartitionEntry =
1483                     LE_32(sizeof (efi_gpe_t));
1484                 CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1485                 gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1486                 CRC32(crc, &gpt, sizeof (gpt), -1U, crc32_table);
1487                 gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1488                 if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
1489                     flag))
1490                         return (EFAULT);
1491                 ptr += sizeof (gpt);
1492                 length -= sizeof (gpt);
1493         }
1494         if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
1495             length), flag))
1496                 return (EFAULT);
1497         return (0);
1498 }
1499
1500 /*
1501  * BEGIN entry points to allow external callers access to the volume.
1502  */
1503 /*
1504  * Return the volume parameters needed for access from an external caller.
1505  * These values are invariant as long as the volume is held open.
1506  */
1507 int
1508 zvol_get_volume_params(minor_t minor, uint64_t *blksize,
1509     uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
1510     void **rl_hdl, void **bonus_hdl)
1511 {
1512         zvol_state_t *zv;
1513
1514         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1515         if (zv == NULL)
1516                 return (ENXIO);
1517         if (zv->zv_flags & ZVOL_DUMPIFIED)
1518                 return (ENXIO);
1519
1520         ASSERT(blksize && max_xfer_len && minor_hdl &&
1521             objset_hdl && zil_hdl && rl_hdl && bonus_hdl);
1522
1523         *blksize = zv->zv_volblocksize;
1524         *max_xfer_len = (uint64_t)zvol_maxphys;
1525         *minor_hdl = zv;
1526         *objset_hdl = zv->zv_objset;
1527         *zil_hdl = zv->zv_zilog;
1528         *rl_hdl = &zv->zv_znode;
1529         *bonus_hdl = zv->zv_dbuf;
1530         return (0);
1531 }
1532
1533 /*
1534  * Return the current volume size to an external caller.
1535  * The size can change while the volume is open.
1536  */
1537 uint64_t
1538 zvol_get_volume_size(void *minor_hdl)
1539 {
1540         zvol_state_t *zv = minor_hdl;
1541
1542         return (zv->zv_volsize);
1543 }
1544
1545 /*
1546  * Return the current WCE setting to an external caller.
1547  * The WCE setting can change while the volume is open.
1548  */
1549 int
1550 zvol_get_volume_wce(void *minor_hdl)
1551 {
1552         zvol_state_t *zv = minor_hdl;
1553
1554         return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
1555 }
1556
1557 /*
1558  * Entry point for external callers to zvol_log_write
1559  */
1560 void
1561 zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
1562     boolean_t sync)
1563 {
1564         zvol_state_t *zv = minor_hdl;
1565
1566         zvol_log_write(zv, tx, off, resid, sync);
1567 }
1568 /*
1569  * END entry points to allow external callers access to the volume.
1570  */
1571
1572 /*
1573  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
1574  */
1575 /*ARGSUSED*/
1576 int
1577 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
1578 {
1579         zvol_state_t *zv;
1580         struct dk_cinfo dki;
1581         struct dk_minfo dkm;
1582         struct dk_callback *dkc;
1583         int error = 0;
1584         rl_t *rl;
1585
1586         mutex_enter(&spa_namespace_lock);
1587
1588         zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
1589
1590         if (zv == NULL) {
1591                 mutex_exit(&spa_namespace_lock);
1592                 return (ENXIO);
1593         }
1594         ASSERT(zv->zv_total_opens > 0);
1595
1596         switch (cmd) {
1597
1598         case DKIOCINFO:
1599                 bzero(&dki, sizeof (dki));
1600                 (void) strcpy(dki.dki_cname, "zvol");
1601                 (void) strcpy(dki.dki_dname, "zvol");
1602                 dki.dki_ctype = DKC_UNKNOWN;
1603                 dki.dki_unit = getminor(dev);
1604                 dki.dki_maxtransfer = 1 << (SPA_MAXBLOCKSHIFT - zv->zv_min_bs);
1605                 mutex_exit(&spa_namespace_lock);
1606                 if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
1607                         error = EFAULT;
1608                 return (error);
1609
1610         case DKIOCGMEDIAINFO:
1611                 bzero(&dkm, sizeof (dkm));
1612                 dkm.dki_lbsize = 1U << zv->zv_min_bs;
1613                 dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1614                 dkm.dki_media_type = DK_UNKNOWN;
1615                 mutex_exit(&spa_namespace_lock);
1616                 if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
1617                         error = EFAULT;
1618                 return (error);
1619
1620         case DKIOCGETEFI:
1621                 {
1622                         uint64_t vs = zv->zv_volsize;
1623                         uint8_t bs = zv->zv_min_bs;
1624
1625                         mutex_exit(&spa_namespace_lock);
1626                         error = zvol_getefi((void *)arg, flag, vs, bs);
1627                         return (error);
1628                 }
1629
1630         case DKIOCFLUSHWRITECACHE:
1631                 dkc = (struct dk_callback *)arg;
1632                 mutex_exit(&spa_namespace_lock);
1633                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1634                 if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
1635                         (*dkc->dkc_callback)(dkc->dkc_cookie, error);
1636                         error = 0;
1637                 }
1638                 return (error);
1639
1640         case DKIOCGETWCE:
1641                 {
1642                         int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
1643                         if (ddi_copyout(&wce, (void *)arg, sizeof (int),
1644                             flag))
1645                                 error = EFAULT;
1646                         break;
1647                 }
1648         case DKIOCSETWCE:
1649                 {
1650                         int wce;
1651                         if (ddi_copyin((void *)arg, &wce, sizeof (int),
1652                             flag)) {
1653                                 error = EFAULT;
1654                                 break;
1655                         }
1656                         if (wce) {
1657                                 zv->zv_flags |= ZVOL_WCE;
1658                                 mutex_exit(&spa_namespace_lock);
1659                         } else {
1660                                 zv->zv_flags &= ~ZVOL_WCE;
1661                                 mutex_exit(&spa_namespace_lock);
1662                                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1663                         }
1664                         return (0);
1665                 }
1666
1667         case DKIOCGGEOM:
1668         case DKIOCGVTOC:
1669                 /*
1670                  * commands using these (like prtvtoc) expect ENOTSUP
1671                  * since we're emulating an EFI label
1672                  */
1673                 error = ENOTSUP;
1674                 break;
1675
1676         case DKIOCDUMPINIT:
1677                 rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
1678                     RL_WRITER);
1679                 error = zvol_dumpify(zv);
1680                 zfs_range_unlock(rl);
1681                 break;
1682
1683         case DKIOCDUMPFINI:
1684                 if (!(zv->zv_flags & ZVOL_DUMPIFIED))
1685                         break;
1686                 rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
1687                     RL_WRITER);
1688                 error = zvol_dump_fini(zv);
1689                 zfs_range_unlock(rl);
1690                 break;
1691
1692         default:
1693                 error = ENOTTY;
1694                 break;
1695
1696         }
1697         mutex_exit(&spa_namespace_lock);
1698         return (error);
1699 }
1700 #endif  /* sun */
1701
1702 int
1703 zvol_busy(void)
1704 {
1705         return (zvol_minors != 0);
1706 }
1707
1708 void
1709 zvol_init(void)
1710 {
1711         VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
1712             1) == 0);
1713         ZFS_LOG(1, "ZVOL Initialized.");
1714 }
1715
1716 void
1717 zvol_fini(void)
1718 {
1719         ddi_soft_state_fini(&zfsdev_state);
1720         ZFS_LOG(1, "ZVOL Deinitialized.");
1721 }
1722
1723 #ifdef sun
1724 static int
1725 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
1726 {
1727         dmu_tx_t *tx;
1728         int error = 0;
1729         objset_t *os = zv->zv_objset;
1730         nvlist_t *nv = NULL;
1731         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
1732
1733         ASSERT(MUTEX_HELD(&spa_namespace_lock));
1734         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
1735             DMU_OBJECT_END);
1736         /* wait for dmu_free_long_range to actually free the blocks */
1737         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1738
1739         tx = dmu_tx_create(os);
1740         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1741         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
1742         error = dmu_tx_assign(tx, TXG_WAIT);
1743         if (error) {
1744                 dmu_tx_abort(tx);
1745                 return (error);
1746         }
1747
1748         /*
1749          * If we are resizing the dump device then we only need to
1750          * update the refreservation to match the newly updated
1751          * zvolsize. Otherwise, we save off the original state of the
1752          * zvol so that we can restore them if the zvol is ever undumpified.
1753          */
1754         if (resize) {
1755                 error = zap_update(os, ZVOL_ZAP_OBJ,
1756                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1757                     &zv->zv_volsize, tx);
1758         } else {
1759                 uint64_t checksum, compress, refresrv, vbs, dedup;
1760
1761                 error = dsl_prop_get_integer(zv->zv_name,
1762                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
1763                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1764                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum, NULL);
1765                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1766                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &refresrv, NULL);
1767                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1768                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs, NULL);
1769                 if (version >= SPA_VERSION_DEDUP) {
1770                         error = error ? error :
1771                             dsl_prop_get_integer(zv->zv_name,
1772                             zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
1773                 }
1774
1775                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1776                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
1777                     &compress, tx);
1778                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1779                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum, tx);
1780                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1781                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1782                     &refresrv, tx);
1783                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1784                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
1785                     &vbs, tx);
1786                 error = error ? error : dmu_object_set_blocksize(
1787                     os, ZVOL_OBJ, SPA_MAXBLOCKSIZE, 0, tx);
1788                 if (version >= SPA_VERSION_DEDUP) {
1789                         error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1790                             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
1791                             &dedup, tx);
1792                 }
1793                 if (error == 0)
1794                         zv->zv_volblocksize = SPA_MAXBLOCKSIZE;
1795         }
1796         dmu_tx_commit(tx);
1797
1798         /*
1799          * We only need update the zvol's property if we are initializing
1800          * the dump area for the first time.
1801          */
1802         if (!resize) {
1803                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1804                 VERIFY(nvlist_add_uint64(nv,
1805                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
1806                 VERIFY(nvlist_add_uint64(nv,
1807                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
1808                     ZIO_COMPRESS_OFF) == 0);
1809                 VERIFY(nvlist_add_uint64(nv,
1810                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
1811                     ZIO_CHECKSUM_OFF) == 0);
1812                 if (version >= SPA_VERSION_DEDUP) {
1813                         VERIFY(nvlist_add_uint64(nv,
1814                             zfs_prop_to_name(ZFS_PROP_DEDUP),
1815                             ZIO_CHECKSUM_OFF) == 0);
1816                 }
1817
1818                 error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
1819                     nv, NULL);
1820                 nvlist_free(nv);
1821
1822                 if (error)
1823                         return (error);
1824         }
1825
1826         /* Allocate the space for the dump */
1827         error = zvol_prealloc(zv);
1828         return (error);
1829 }
1830
1831 static int
1832 zvol_dumpify(zvol_state_t *zv)
1833 {
1834         int error = 0;
1835         uint64_t dumpsize = 0;
1836         dmu_tx_t *tx;
1837         objset_t *os = zv->zv_objset;
1838
1839         if (zv->zv_flags & ZVOL_RDONLY)
1840                 return (EROFS);
1841
1842         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
1843             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
1844                 boolean_t resize = (dumpsize > 0) ? B_TRUE : B_FALSE;
1845
1846                 if ((error = zvol_dump_init(zv, resize)) != 0) {
1847                         (void) zvol_dump_fini(zv);
1848                         return (error);
1849                 }
1850         }
1851
1852         /*
1853          * Build up our lba mapping.
1854          */
1855         error = zvol_get_lbas(zv);
1856         if (error) {
1857                 (void) zvol_dump_fini(zv);
1858                 return (error);
1859         }
1860
1861         tx = dmu_tx_create(os);
1862         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1863         error = dmu_tx_assign(tx, TXG_WAIT);
1864         if (error) {
1865                 dmu_tx_abort(tx);
1866                 (void) zvol_dump_fini(zv);
1867                 return (error);
1868         }
1869
1870         zv->zv_flags |= ZVOL_DUMPIFIED;
1871         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
1872             &zv->zv_volsize, tx);
1873         dmu_tx_commit(tx);
1874
1875         if (error) {
1876                 (void) zvol_dump_fini(zv);
1877                 return (error);
1878         }
1879
1880         txg_wait_synced(dmu_objset_pool(os), 0);
1881         return (0);
1882 }
1883
1884 static int
1885 zvol_dump_fini(zvol_state_t *zv)
1886 {
1887         dmu_tx_t *tx;
1888         objset_t *os = zv->zv_objset;
1889         nvlist_t *nv;
1890         int error = 0;
1891         uint64_t checksum, compress, refresrv, vbs, dedup;
1892         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
1893
1894         /*
1895          * Attempt to restore the zvol back to its pre-dumpified state.
1896          * This is a best-effort attempt as it's possible that not all
1897          * of these properties were initialized during the dumpify process
1898          * (i.e. error during zvol_dump_init).
1899          */
1900
1901         tx = dmu_tx_create(os);
1902         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1903         error = dmu_tx_assign(tx, TXG_WAIT);
1904         if (error) {
1905                 dmu_tx_abort(tx);
1906                 return (error);
1907         }
1908         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
1909         dmu_tx_commit(tx);
1910
1911         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1912             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
1913         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1914             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
1915         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1916             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
1917         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1918             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
1919
1920         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1921         (void) nvlist_add_uint64(nv,
1922             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
1923         (void) nvlist_add_uint64(nv,
1924             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
1925         (void) nvlist_add_uint64(nv,
1926             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
1927         if (version >= SPA_VERSION_DEDUP &&
1928             zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1929             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
1930                 (void) nvlist_add_uint64(nv,
1931                     zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
1932         }
1933         (void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
1934             nv, NULL);
1935         nvlist_free(nv);
1936
1937         zvol_free_extents(zv);
1938         zv->zv_flags &= ~ZVOL_DUMPIFIED;
1939         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
1940         /* wait for dmu_free_long_range to actually free the blocks */
1941         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1942         tx = dmu_tx_create(os);
1943         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
1944         error = dmu_tx_assign(tx, TXG_WAIT);
1945         if (error) {
1946                 dmu_tx_abort(tx);
1947                 return (error);
1948         }
1949         if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
1950                 zv->zv_volblocksize = vbs;
1951         dmu_tx_commit(tx);
1952
1953         return (0);
1954 }
1955 #endif  /* sun */
1956
1957 static zvol_state_t *
1958 zvol_geom_create(const char *name)
1959 {
1960         struct g_provider *pp;
1961         struct g_geom *gp;
1962         zvol_state_t *zv;
1963
1964         gp = g_new_geomf(&zfs_zvol_class, "zfs::zvol::%s", name);
1965         gp->start = zvol_geom_start;
1966         gp->access = zvol_geom_access;
1967         pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, name);
1968         pp->sectorsize = DEV_BSIZE;
1969
1970         zv = kmem_zalloc(sizeof(*zv), KM_SLEEP);
1971         zv->zv_provider = pp;
1972         zv->zv_state = 0;
1973         bioq_init(&zv->zv_queue);
1974         mtx_init(&zv->zv_queue_mtx, "zvol", NULL, MTX_DEF);
1975
1976         pp->private = zv;
1977
1978         return (zv);
1979 }
1980
1981 static void
1982 zvol_geom_run(zvol_state_t *zv)
1983 {
1984         struct g_provider *pp;
1985
1986         pp = zv->zv_provider;
1987         g_error_provider(pp, 0);
1988
1989         kproc_kthread_add(zvol_geom_worker, zv, &zfsproc, NULL, 0, 0,
1990             "zfskern", "zvol %s", pp->name + sizeof(ZVOL_DRIVER));
1991 }
1992
1993 static void
1994 zvol_geom_destroy(zvol_state_t *zv)
1995 {
1996         struct g_provider *pp;
1997
1998         g_topology_assert();
1999
2000         mtx_lock(&zv->zv_queue_mtx);
2001         zv->zv_state = 1;
2002         wakeup_one(&zv->zv_queue);
2003         while (zv->zv_state != 2)
2004                 msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
2005         mtx_destroy(&zv->zv_queue_mtx);
2006
2007         pp = zv->zv_provider;
2008         zv->zv_provider = NULL;
2009         pp->private = NULL;
2010         g_wither_geom(pp->geom, ENXIO);
2011
2012         kmem_free(zv, sizeof(*zv));
2013 }
2014
2015 static int
2016 zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace)
2017 {
2018         int count, error, flags;
2019
2020         g_topology_assert();
2021
2022         /*
2023          * To make it easier we expect either open or close, but not both
2024          * at the same time.
2025          */
2026         KASSERT((acr >= 0 && acw >= 0 && ace >= 0) ||
2027             (acr <= 0 && acw <= 0 && ace <= 0),
2028             ("Unsupported access request to %s (acr=%d, acw=%d, ace=%d).",
2029             pp->name, acr, acw, ace));
2030
2031         if (pp->private == NULL) {
2032                 if (acr <= 0 && acw <= 0 && ace <= 0)
2033                         return (0);
2034                 return (pp->error);
2035         }
2036
2037         /*
2038          * We don't pass FEXCL flag to zvol_open()/zvol_close() if ace != 0,
2039          * because GEOM already handles that and handles it a bit differently.
2040          * GEOM allows for multiple read/exclusive consumers and ZFS allows
2041          * only one exclusive consumer, no matter if it is reader or writer.
2042          * I like better the way GEOM works so I'll leave it for GEOM to
2043          * decide what to do.
2044          */
2045
2046         count = acr + acw + ace;
2047         if (count == 0)
2048                 return (0);
2049
2050         flags = 0;
2051         if (acr != 0 || ace != 0)
2052                 flags |= FREAD;
2053         if (acw != 0)
2054                 flags |= FWRITE;
2055
2056         g_topology_unlock();
2057         if (count > 0)
2058                 error = zvol_open(pp, flags, count);
2059         else
2060                 error = zvol_close(pp, flags, -count);
2061         g_topology_lock();
2062         return (error);
2063 }
2064
2065 static void
2066 zvol_geom_start(struct bio *bp)
2067 {
2068         zvol_state_t *zv;
2069         boolean_t first;
2070
2071         switch (bp->bio_cmd) {
2072         case BIO_READ:
2073         case BIO_WRITE:
2074         case BIO_FLUSH:
2075                 zv = bp->bio_to->private;
2076                 ASSERT(zv != NULL);
2077                 mtx_lock(&zv->zv_queue_mtx);
2078                 first = (bioq_first(&zv->zv_queue) == NULL);
2079                 bioq_insert_tail(&zv->zv_queue, bp);
2080                 mtx_unlock(&zv->zv_queue_mtx);
2081                 if (first)
2082                         wakeup_one(&zv->zv_queue);
2083                 break;
2084         case BIO_GETATTR:
2085         case BIO_DELETE:
2086         default:
2087                 g_io_deliver(bp, EOPNOTSUPP);
2088                 break;
2089         }
2090 }
2091
2092 static void
2093 zvol_geom_worker(void *arg)
2094 {
2095         zvol_state_t *zv;
2096         struct bio *bp;
2097
2098         thread_lock(curthread);
2099         sched_prio(curthread, PRIBIO);
2100         thread_unlock(curthread);
2101
2102         zv = arg;
2103         for (;;) {
2104                 mtx_lock(&zv->zv_queue_mtx);
2105                 bp = bioq_takefirst(&zv->zv_queue);
2106                 if (bp == NULL) {
2107                         if (zv->zv_state == 1) {
2108                                 zv->zv_state = 2;
2109                                 wakeup(&zv->zv_state);
2110                                 mtx_unlock(&zv->zv_queue_mtx);
2111                                 kthread_exit();
2112                         }
2113                         msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
2114                             "zvol:io", 0);
2115                         continue;
2116                 }
2117                 mtx_unlock(&zv->zv_queue_mtx);
2118                 switch (bp->bio_cmd) {
2119                 case BIO_FLUSH:
2120                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2121                         g_io_deliver(bp, 0);
2122                         break;
2123                 case BIO_READ:
2124                 case BIO_WRITE:
2125                         zvol_strategy(bp);
2126                         break;
2127                 }
2128         }
2129 }
2130
2131 extern boolean_t dataset_name_hidden(const char *name);
2132
2133 static int
2134 zvol_create_snapshots(objset_t *os, const char *name)
2135 {
2136         uint64_t cookie, obj;
2137         char *sname;
2138         int error, len;
2139
2140         cookie = obj = 0;
2141         sname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2142
2143         (void) dmu_objset_find(name, dmu_objset_prefetch, NULL,
2144             DS_FIND_SNAPSHOTS);
2145
2146         for (;;) {
2147                 len = snprintf(sname, MAXPATHLEN, "%s@", name);
2148                 if (len >= MAXPATHLEN) {
2149                         dmu_objset_rele(os, FTAG);
2150                         error = ENAMETOOLONG;
2151                         break;
2152                 }
2153
2154                 error = dmu_snapshot_list_next(os, MAXPATHLEN - len,
2155                     sname + len, &obj, &cookie, NULL);
2156                 if (error != 0) {
2157                         if (error == ENOENT)
2158                                 error = 0;
2159                         break;
2160                 }
2161
2162                 if ((error = zvol_create_minor(sname)) != 0) {
2163                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2164                             sname, error);
2165                         break;
2166                 }
2167         }
2168
2169         kmem_free(sname, MAXPATHLEN);
2170         return (error);
2171 }
2172
2173 int
2174 zvol_create_minors(const char *name)
2175 {
2176         uint64_t cookie;
2177         objset_t *os;
2178         char *osname, *p;
2179         int error, len;
2180
2181         if (dataset_name_hidden(name))
2182                 return (0);
2183
2184         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2185                 printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2186                     name, error);
2187                 return (error);
2188         }
2189         if (dmu_objset_type(os) == DMU_OST_ZVOL) {
2190                 if ((error = zvol_create_minor(name)) == 0)
2191                         error = zvol_create_snapshots(os, name);
2192                 else {
2193                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2194                             name, error);
2195                 }
2196                 dmu_objset_rele(os, FTAG);
2197                 return (error);
2198         }
2199         if (dmu_objset_type(os) != DMU_OST_ZFS) {
2200                 dmu_objset_rele(os, FTAG);
2201                 return (0);
2202         }
2203
2204         osname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2205         if (snprintf(osname, MAXPATHLEN, "%s/", name) >= MAXPATHLEN) {
2206                 dmu_objset_rele(os, FTAG);
2207                 kmem_free(osname, MAXPATHLEN);
2208                 return (ENOENT);
2209         }
2210         p = osname + strlen(osname);
2211         len = MAXPATHLEN - (p - osname);
2212
2213         /* Prefetch the datasets. */
2214         cookie = 0;
2215         while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2216                 if (!dataset_name_hidden(osname))
2217                         (void) dmu_objset_prefetch(osname, NULL);
2218         }
2219
2220         cookie = 0;
2221         while (dmu_dir_list_next(os, MAXPATHLEN - (p - osname), p, NULL,
2222             &cookie) == 0) {
2223                 dmu_objset_rele(os, FTAG);
2224                 (void)zvol_create_minors(osname);
2225                 if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2226                         printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2227                             name, error);
2228                         return (error);
2229                 }
2230         }
2231
2232         dmu_objset_rele(os, FTAG);
2233         kmem_free(osname, MAXPATHLEN);
2234         return (0);
2235 }
2236
2237 static void
2238 zvol_rename_minor(struct g_geom *gp, const char *newname)
2239 {
2240         struct g_provider *pp;
2241         zvol_state_t *zv;
2242
2243         ASSERT(MUTEX_HELD(&spa_namespace_lock));
2244         g_topology_assert();
2245
2246         pp = LIST_FIRST(&gp->provider);
2247         ASSERT(pp != NULL);
2248         zv = pp->private;
2249         ASSERT(zv != NULL);
2250
2251         zv->zv_provider = NULL;
2252         g_wither_provider(pp, ENXIO);
2253
2254         pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, newname);
2255         pp->sectorsize = DEV_BSIZE;
2256         pp->mediasize = zv->zv_volsize;
2257         pp->private = zv;
2258         zv->zv_provider = pp;
2259         strlcpy(zv->zv_name, newname, sizeof(zv->zv_name));
2260         g_error_provider(pp, 0);
2261 }
2262
2263 void
2264 zvol_rename_minors(const char *oldname, const char *newname)
2265 {
2266         char name[MAXPATHLEN];
2267         struct g_provider *pp;
2268         struct g_geom *gp;
2269         size_t oldnamelen, newnamelen;
2270         zvol_state_t *zv;
2271         char *namebuf;
2272
2273         oldnamelen = strlen(oldname);
2274         newnamelen = strlen(newname);
2275
2276         DROP_GIANT();
2277         mutex_enter(&spa_namespace_lock);
2278         g_topology_lock();
2279
2280         LIST_FOREACH(gp, &zfs_zvol_class.geom, geom) {
2281                 pp = LIST_FIRST(&gp->provider);
2282                 if (pp == NULL)
2283                         continue;
2284                 zv = pp->private;
2285                 if (zv == NULL)
2286                         continue;
2287                 if (strcmp(zv->zv_name, oldname) == 0) {
2288                         zvol_rename_minor(gp, newname);
2289                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
2290                     (zv->zv_name[oldnamelen] == '/' ||
2291                      zv->zv_name[oldnamelen] == '@')) {
2292                         snprintf(name, sizeof(name), "%s%c%s", newname,
2293                             zv->zv_name[oldnamelen],
2294                             zv->zv_name + oldnamelen + 1);
2295                         zvol_rename_minor(gp, name);
2296                 }
2297         }
2298
2299         g_topology_unlock();
2300         mutex_exit(&spa_namespace_lock);
2301         PICKUP_GIANT();
2302 }