1 // SPDX-License-Identifier: GPL-2.0-only
3 #include <linux/spinlock.h>
4 #include <linux/slab.h>
5 #include <linux/blkdev.h>
6 #include <linux/hdreg.h>
7 #include <linux/module.h>
8 #include <linux/mutex.h>
9 #include <linux/interrupt.h>
10 #include <linux/virtio.h>
11 #include <linux/virtio_blk.h>
12 #include <linux/scatterlist.h>
13 #include <linux/string_helpers.h>
14 #include <linux/idr.h>
15 #include <linux/blk-mq.h>
16 #include <linux/blk-mq-virtio.h>
17 #include <linux/numa.h>
18 #include <uapi/linux/virtio_ring.h>
21 #define VQ_NAME_LEN 16
22 #define MAX_DISCARD_SEGMENTS 256u
24 /* The maximum number of sg elements that fit into a virtqueue */
25 #define VIRTIO_BLK_MAX_SG_ELEMS 32768
27 #ifdef CONFIG_ARCH_NO_SG_CHAIN
28 #define VIRTIO_BLK_INLINE_SG_CNT 0
30 #define VIRTIO_BLK_INLINE_SG_CNT 2
33 static unsigned int num_request_queues;
34 module_param(num_request_queues, uint, 0644);
35 MODULE_PARM_DESC(num_request_queues,
36 "Limit the number of request queues to use for blk device. "
38 "Values > nr_cpu_ids truncated to nr_cpu_ids.");
40 static unsigned int poll_queues;
41 module_param(poll_queues, uint, 0644);
42 MODULE_PARM_DESC(poll_queues, "The number of dedicated virtqueues for polling I/O");
45 static DEFINE_IDA(vd_index_ida);
47 static struct workqueue_struct *virtblk_wq;
49 struct virtio_blk_vq {
52 char name[VQ_NAME_LEN];
53 } ____cacheline_aligned_in_smp;
57 * This mutex must be held by anything that may run after
58 * virtblk_remove() sets vblk->vdev to NULL.
60 * blk-mq, virtqueue processing, and sysfs attribute code paths are
61 * shut down before vblk->vdev is set to NULL and therefore do not need
64 struct mutex vdev_mutex;
65 struct virtio_device *vdev;
67 /* The disk structure for the kernel. */
70 /* Block layer tags. */
71 struct blk_mq_tag_set tag_set;
73 /* Process context for config space updates */
74 struct work_struct config_work;
76 /* Ida index - used to track minor number allocations. */
81 int io_queues[HCTX_MAX_TYPES];
82 struct virtio_blk_vq *vqs;
86 struct virtio_blk_outhdr out_hdr;
88 struct sg_table sg_table;
89 struct scatterlist sg[];
92 static inline blk_status_t virtblk_result(struct virtblk_req *vbr)
94 switch (vbr->status) {
97 case VIRTIO_BLK_S_UNSUPP:
98 return BLK_STS_NOTSUPP;
100 return BLK_STS_IOERR;
104 static inline struct virtio_blk_vq *get_virtio_blk_vq(struct blk_mq_hw_ctx *hctx)
106 struct virtio_blk *vblk = hctx->queue->queuedata;
107 struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
112 static int virtblk_add_req(struct virtqueue *vq, struct virtblk_req *vbr)
114 struct scatterlist hdr, status, *sgs[3];
115 unsigned int num_out = 0, num_in = 0;
117 sg_init_one(&hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
118 sgs[num_out++] = &hdr;
120 if (vbr->sg_table.nents) {
121 if (vbr->out_hdr.type & cpu_to_virtio32(vq->vdev, VIRTIO_BLK_T_OUT))
122 sgs[num_out++] = vbr->sg_table.sgl;
124 sgs[num_out + num_in++] = vbr->sg_table.sgl;
127 sg_init_one(&status, &vbr->status, sizeof(vbr->status));
128 sgs[num_out + num_in++] = &status;
130 return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
133 static int virtblk_setup_discard_write_zeroes_erase(struct request *req, bool unmap)
135 unsigned short segments = blk_rq_nr_discard_segments(req);
136 unsigned short n = 0;
137 struct virtio_blk_discard_write_zeroes *range;
142 flags |= VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP;
144 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
149 * Single max discard segment means multi-range discard isn't
150 * supported, and block layer only runs contiguity merge like
151 * normal RW request. So we can't reply on bio for retrieving
154 if (queue_max_discard_segments(req->q) == 1) {
155 range[0].flags = cpu_to_le32(flags);
156 range[0].num_sectors = cpu_to_le32(blk_rq_sectors(req));
157 range[0].sector = cpu_to_le64(blk_rq_pos(req));
160 __rq_for_each_bio(bio, req) {
161 u64 sector = bio->bi_iter.bi_sector;
162 u32 num_sectors = bio->bi_iter.bi_size >> SECTOR_SHIFT;
164 range[n].flags = cpu_to_le32(flags);
165 range[n].num_sectors = cpu_to_le32(num_sectors);
166 range[n].sector = cpu_to_le64(sector);
171 WARN_ON_ONCE(n != segments);
173 req->special_vec.bv_page = virt_to_page(range);
174 req->special_vec.bv_offset = offset_in_page(range);
175 req->special_vec.bv_len = sizeof(*range) * segments;
176 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
181 static void virtblk_unmap_data(struct request *req, struct virtblk_req *vbr)
183 if (blk_rq_nr_phys_segments(req))
184 sg_free_table_chained(&vbr->sg_table,
185 VIRTIO_BLK_INLINE_SG_CNT);
188 static int virtblk_map_data(struct blk_mq_hw_ctx *hctx, struct request *req,
189 struct virtblk_req *vbr)
193 if (!blk_rq_nr_phys_segments(req))
196 vbr->sg_table.sgl = vbr->sg;
197 err = sg_alloc_table_chained(&vbr->sg_table,
198 blk_rq_nr_phys_segments(req),
200 VIRTIO_BLK_INLINE_SG_CNT);
204 return blk_rq_map_sg(hctx->queue, req, vbr->sg_table.sgl);
207 static void virtblk_cleanup_cmd(struct request *req)
209 if (req->rq_flags & RQF_SPECIAL_PAYLOAD)
210 kfree(bvec_virt(&req->special_vec));
213 static blk_status_t virtblk_setup_cmd(struct virtio_device *vdev,
215 struct virtblk_req *vbr)
220 vbr->out_hdr.sector = 0;
222 switch (req_op(req)) {
224 type = VIRTIO_BLK_T_IN;
225 vbr->out_hdr.sector = cpu_to_virtio64(vdev,
229 type = VIRTIO_BLK_T_OUT;
230 vbr->out_hdr.sector = cpu_to_virtio64(vdev,
234 type = VIRTIO_BLK_T_FLUSH;
237 type = VIRTIO_BLK_T_DISCARD;
239 case REQ_OP_WRITE_ZEROES:
240 type = VIRTIO_BLK_T_WRITE_ZEROES;
241 unmap = !(req->cmd_flags & REQ_NOUNMAP);
243 case REQ_OP_SECURE_ERASE:
244 type = VIRTIO_BLK_T_SECURE_ERASE;
247 type = VIRTIO_BLK_T_GET_ID;
251 return BLK_STS_IOERR;
254 vbr->out_hdr.type = cpu_to_virtio32(vdev, type);
255 vbr->out_hdr.ioprio = cpu_to_virtio32(vdev, req_get_ioprio(req));
257 if (type == VIRTIO_BLK_T_DISCARD || type == VIRTIO_BLK_T_WRITE_ZEROES ||
258 type == VIRTIO_BLK_T_SECURE_ERASE) {
259 if (virtblk_setup_discard_write_zeroes_erase(req, unmap))
260 return BLK_STS_RESOURCE;
266 static inline void virtblk_request_done(struct request *req)
268 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
270 virtblk_unmap_data(req, vbr);
271 virtblk_cleanup_cmd(req);
272 blk_mq_end_request(req, virtblk_result(vbr));
275 static void virtblk_done(struct virtqueue *vq)
277 struct virtio_blk *vblk = vq->vdev->priv;
278 bool req_done = false;
280 struct virtblk_req *vbr;
284 spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
286 virtqueue_disable_cb(vq);
287 while ((vbr = virtqueue_get_buf(vblk->vqs[qid].vq, &len)) != NULL) {
288 struct request *req = blk_mq_rq_from_pdu(vbr);
290 if (likely(!blk_should_fake_timeout(req->q)))
291 blk_mq_complete_request(req);
294 if (unlikely(virtqueue_is_broken(vq)))
296 } while (!virtqueue_enable_cb(vq));
298 /* In case queue is stopped waiting for more buffers. */
300 blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
301 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
304 static void virtio_commit_rqs(struct blk_mq_hw_ctx *hctx)
306 struct virtio_blk *vblk = hctx->queue->queuedata;
307 struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
310 spin_lock_irq(&vq->lock);
311 kick = virtqueue_kick_prepare(vq->vq);
312 spin_unlock_irq(&vq->lock);
315 virtqueue_notify(vq->vq);
318 static blk_status_t virtblk_prep_rq(struct blk_mq_hw_ctx *hctx,
319 struct virtio_blk *vblk,
321 struct virtblk_req *vbr)
325 status = virtblk_setup_cmd(vblk->vdev, req, vbr);
326 if (unlikely(status))
329 vbr->sg_table.nents = virtblk_map_data(hctx, req, vbr);
330 if (unlikely(vbr->sg_table.nents < 0)) {
331 virtblk_cleanup_cmd(req);
332 return BLK_STS_RESOURCE;
335 blk_mq_start_request(req);
340 static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
341 const struct blk_mq_queue_data *bd)
343 struct virtio_blk *vblk = hctx->queue->queuedata;
344 struct request *req = bd->rq;
345 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
347 int qid = hctx->queue_num;
352 status = virtblk_prep_rq(hctx, vblk, req, vbr);
353 if (unlikely(status))
356 spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
357 err = virtblk_add_req(vblk->vqs[qid].vq, vbr);
359 virtqueue_kick(vblk->vqs[qid].vq);
360 /* Don't stop the queue if -ENOMEM: we may have failed to
361 * bounce the buffer due to global resource outage.
364 blk_mq_stop_hw_queue(hctx);
365 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
366 virtblk_unmap_data(req, vbr);
367 virtblk_cleanup_cmd(req);
370 return BLK_STS_DEV_RESOURCE;
372 return BLK_STS_RESOURCE;
374 return BLK_STS_IOERR;
378 if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
380 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
383 virtqueue_notify(vblk->vqs[qid].vq);
387 static bool virtblk_prep_rq_batch(struct request *req)
389 struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
390 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
392 req->mq_hctx->tags->rqs[req->tag] = req;
394 return virtblk_prep_rq(req->mq_hctx, vblk, req, vbr) == BLK_STS_OK;
397 static bool virtblk_add_req_batch(struct virtio_blk_vq *vq,
398 struct request **rqlist)
404 spin_lock_irqsave(&vq->lock, flags);
406 while (!rq_list_empty(*rqlist)) {
407 struct request *req = rq_list_pop(rqlist);
408 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
410 err = virtblk_add_req(vq->vq, vbr);
412 virtblk_unmap_data(req, vbr);
413 virtblk_cleanup_cmd(req);
414 blk_mq_requeue_request(req, true);
418 kick = virtqueue_kick_prepare(vq->vq);
419 spin_unlock_irqrestore(&vq->lock, flags);
424 static void virtio_queue_rqs(struct request **rqlist)
426 struct request *req, *next, *prev = NULL;
427 struct request *requeue_list = NULL;
429 rq_list_for_each_safe(rqlist, req, next) {
430 struct virtio_blk_vq *vq = get_virtio_blk_vq(req->mq_hctx);
433 if (!virtblk_prep_rq_batch(req)) {
434 rq_list_move(rqlist, &requeue_list, req, prev);
440 if (!next || req->mq_hctx != next->mq_hctx) {
442 kick = virtblk_add_req_batch(vq, rqlist);
444 virtqueue_notify(vq->vq);
452 *rqlist = requeue_list;
455 /* return id (s/n) string for *disk to *id_str
457 static int virtblk_get_id(struct gendisk *disk, char *id_str)
459 struct virtio_blk *vblk = disk->private_data;
460 struct request_queue *q = vblk->disk->queue;
464 req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
468 err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
472 blk_execute_rq(req, false);
473 err = blk_status_to_errno(virtblk_result(blk_mq_rq_to_pdu(req)));
475 blk_mq_free_request(req);
479 /* We provide getgeo only to please some old bootloader/partitioning tools */
480 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
482 struct virtio_blk *vblk = bd->bd_disk->private_data;
485 mutex_lock(&vblk->vdev_mutex);
492 /* see if the host passed in geometry config */
493 if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
494 virtio_cread(vblk->vdev, struct virtio_blk_config,
495 geometry.cylinders, &geo->cylinders);
496 virtio_cread(vblk->vdev, struct virtio_blk_config,
497 geometry.heads, &geo->heads);
498 virtio_cread(vblk->vdev, struct virtio_blk_config,
499 geometry.sectors, &geo->sectors);
501 /* some standard values, similar to sd */
503 geo->sectors = 1 << 5;
504 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
507 mutex_unlock(&vblk->vdev_mutex);
511 static void virtblk_free_disk(struct gendisk *disk)
513 struct virtio_blk *vblk = disk->private_data;
515 ida_simple_remove(&vd_index_ida, vblk->index);
516 mutex_destroy(&vblk->vdev_mutex);
520 static const struct block_device_operations virtblk_fops = {
521 .owner = THIS_MODULE,
522 .getgeo = virtblk_getgeo,
523 .free_disk = virtblk_free_disk,
526 static int index_to_minor(int index)
528 return index << PART_BITS;
531 static int minor_to_index(int minor)
533 return minor >> PART_BITS;
536 static ssize_t serial_show(struct device *dev,
537 struct device_attribute *attr, char *buf)
539 struct gendisk *disk = dev_to_disk(dev);
542 /* sysfs gives us a PAGE_SIZE buffer */
543 BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
545 buf[VIRTIO_BLK_ID_BYTES] = '\0';
546 err = virtblk_get_id(disk, buf);
550 if (err == -EIO) /* Unsupported? Make it empty. */
556 static DEVICE_ATTR_RO(serial);
558 /* The queue's logical block size must be set before calling this */
559 static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
561 struct virtio_device *vdev = vblk->vdev;
562 struct request_queue *q = vblk->disk->queue;
563 char cap_str_2[10], cap_str_10[10];
564 unsigned long long nblocks;
567 /* Host must always specify the capacity. */
568 virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
570 nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
572 string_get_size(nblocks, queue_logical_block_size(q),
573 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
574 string_get_size(nblocks, queue_logical_block_size(q),
575 STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
577 dev_notice(&vdev->dev,
578 "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
579 vblk->disk->disk_name,
580 resize ? "new size: " : "",
582 queue_logical_block_size(q),
586 set_capacity_and_notify(vblk->disk, capacity);
589 static void virtblk_config_changed_work(struct work_struct *work)
591 struct virtio_blk *vblk =
592 container_of(work, struct virtio_blk, config_work);
594 virtblk_update_capacity(vblk, true);
597 static void virtblk_config_changed(struct virtio_device *vdev)
599 struct virtio_blk *vblk = vdev->priv;
601 queue_work(virtblk_wq, &vblk->config_work);
604 static int init_vq(struct virtio_blk *vblk)
608 vq_callback_t **callbacks;
610 struct virtqueue **vqs;
611 unsigned short num_vqs;
612 unsigned int num_poll_vqs;
613 struct virtio_device *vdev = vblk->vdev;
614 struct irq_affinity desc = { 0, };
616 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
617 struct virtio_blk_config, num_queues,
622 if (!err && !num_vqs) {
623 dev_err(&vdev->dev, "MQ advertised but zero queues reported\n");
627 num_vqs = min_t(unsigned int,
628 min_not_zero(num_request_queues, nr_cpu_ids),
631 num_poll_vqs = min_t(unsigned int, poll_queues, num_vqs - 1);
633 vblk->io_queues[HCTX_TYPE_DEFAULT] = num_vqs - num_poll_vqs;
634 vblk->io_queues[HCTX_TYPE_READ] = 0;
635 vblk->io_queues[HCTX_TYPE_POLL] = num_poll_vqs;
637 dev_info(&vdev->dev, "%d/%d/%d default/read/poll queues\n",
638 vblk->io_queues[HCTX_TYPE_DEFAULT],
639 vblk->io_queues[HCTX_TYPE_READ],
640 vblk->io_queues[HCTX_TYPE_POLL]);
642 vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
646 names = kmalloc_array(num_vqs, sizeof(*names), GFP_KERNEL);
647 callbacks = kmalloc_array(num_vqs, sizeof(*callbacks), GFP_KERNEL);
648 vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
649 if (!names || !callbacks || !vqs) {
654 for (i = 0; i < num_vqs - num_poll_vqs; i++) {
655 callbacks[i] = virtblk_done;
656 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%d", i);
657 names[i] = vblk->vqs[i].name;
660 for (; i < num_vqs; i++) {
662 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req_poll.%d", i);
663 names[i] = vblk->vqs[i].name;
666 /* Discover virtqueues and write information to configuration. */
667 err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
671 for (i = 0; i < num_vqs; i++) {
672 spin_lock_init(&vblk->vqs[i].lock);
673 vblk->vqs[i].vq = vqs[i];
675 vblk->num_vqs = num_vqs;
687 * Legacy naming scheme used for virtio devices. We are stuck with it for
688 * virtio blk but don't ever use it for any new driver.
690 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
692 const int base = 'z' - 'a' + 1;
693 char *begin = buf + strlen(prefix);
694 char *end = buf + buflen;
704 *--p = 'a' + (index % unit);
705 index = (index / unit) - 1;
706 } while (index >= 0);
708 memmove(begin, p, end - p);
709 memcpy(buf, prefix, strlen(prefix));
714 static int virtblk_get_cache_mode(struct virtio_device *vdev)
719 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
720 struct virtio_blk_config, wce,
724 * If WCE is not configurable and flush is not available,
725 * assume no writeback cache is in use.
728 writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
733 static void virtblk_update_cache_mode(struct virtio_device *vdev)
735 u8 writeback = virtblk_get_cache_mode(vdev);
736 struct virtio_blk *vblk = vdev->priv;
738 blk_queue_write_cache(vblk->disk->queue, writeback, false);
741 static const char *const virtblk_cache_types[] = {
742 "write through", "write back"
746 cache_type_store(struct device *dev, struct device_attribute *attr,
747 const char *buf, size_t count)
749 struct gendisk *disk = dev_to_disk(dev);
750 struct virtio_blk *vblk = disk->private_data;
751 struct virtio_device *vdev = vblk->vdev;
754 BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
755 i = sysfs_match_string(virtblk_cache_types, buf);
759 virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
760 virtblk_update_cache_mode(vdev);
765 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
767 struct gendisk *disk = dev_to_disk(dev);
768 struct virtio_blk *vblk = disk->private_data;
769 u8 writeback = virtblk_get_cache_mode(vblk->vdev);
771 BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
772 return sysfs_emit(buf, "%s\n", virtblk_cache_types[writeback]);
775 static DEVICE_ATTR_RW(cache_type);
777 static struct attribute *virtblk_attrs[] = {
778 &dev_attr_serial.attr,
779 &dev_attr_cache_type.attr,
783 static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
784 struct attribute *a, int n)
786 struct device *dev = kobj_to_dev(kobj);
787 struct gendisk *disk = dev_to_disk(dev);
788 struct virtio_blk *vblk = disk->private_data;
789 struct virtio_device *vdev = vblk->vdev;
791 if (a == &dev_attr_cache_type.attr &&
792 !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
798 static const struct attribute_group virtblk_attr_group = {
799 .attrs = virtblk_attrs,
800 .is_visible = virtblk_attrs_are_visible,
803 static const struct attribute_group *virtblk_attr_groups[] = {
808 static void virtblk_map_queues(struct blk_mq_tag_set *set)
810 struct virtio_blk *vblk = set->driver_data;
813 for (i = 0, qoff = 0; i < set->nr_maps; i++) {
814 struct blk_mq_queue_map *map = &set->map[i];
816 map->nr_queues = vblk->io_queues[i];
817 map->queue_offset = qoff;
818 qoff += map->nr_queues;
820 if (map->nr_queues == 0)
824 * Regular queues have interrupts and hence CPU affinity is
825 * defined by the core virtio code, but polling queues have
826 * no interrupts so we let the block layer assign CPU affinity.
828 if (i == HCTX_TYPE_POLL)
829 blk_mq_map_queues(&set->map[i]);
831 blk_mq_virtio_map_queues(&set->map[i], vblk->vdev, 0);
835 static void virtblk_complete_batch(struct io_comp_batch *iob)
839 rq_list_for_each(&iob->req_list, req) {
840 virtblk_unmap_data(req, blk_mq_rq_to_pdu(req));
841 virtblk_cleanup_cmd(req);
843 blk_mq_end_request_batch(iob);
846 static int virtblk_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
848 struct virtio_blk *vblk = hctx->queue->queuedata;
849 struct virtio_blk_vq *vq = get_virtio_blk_vq(hctx);
850 struct virtblk_req *vbr;
855 spin_lock_irqsave(&vq->lock, flags);
857 while ((vbr = virtqueue_get_buf(vq->vq, &len)) != NULL) {
858 struct request *req = blk_mq_rq_from_pdu(vbr);
861 if (!blk_mq_add_to_batch(req, iob, vbr->status,
862 virtblk_complete_batch))
863 blk_mq_complete_request(req);
867 blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
869 spin_unlock_irqrestore(&vq->lock, flags);
874 static const struct blk_mq_ops virtio_mq_ops = {
875 .queue_rq = virtio_queue_rq,
876 .queue_rqs = virtio_queue_rqs,
877 .commit_rqs = virtio_commit_rqs,
878 .complete = virtblk_request_done,
879 .map_queues = virtblk_map_queues,
880 .poll = virtblk_poll,
883 static unsigned int virtblk_queue_depth;
884 module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
886 static int virtblk_probe(struct virtio_device *vdev)
888 struct virtio_blk *vblk;
889 struct request_queue *q;
892 u32 v, blk_size, max_size, sg_elems, opt_io_size;
893 u32 max_discard_segs = 0;
894 u32 discard_granularity = 0;
896 u8 physical_block_exp, alignment_offset;
897 unsigned int queue_depth;
899 if (!vdev->config->get) {
900 dev_err(&vdev->dev, "%s failure: config access disabled\n",
905 err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
911 /* We need to know how many segments before we allocate. */
912 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
913 struct virtio_blk_config, seg_max,
916 /* We need at least one SG element, whatever they say. */
917 if (err || !sg_elems)
920 /* Prevent integer overflows and honor max vq size */
921 sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2);
923 vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
929 mutex_init(&vblk->vdev_mutex);
933 INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
939 /* Default queue sizing is to fill the ring. */
940 if (!virtblk_queue_depth) {
941 queue_depth = vblk->vqs[0].vq->num_free;
942 /* ... but without indirect descs, we use 2 descs per req */
943 if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
946 queue_depth = virtblk_queue_depth;
949 memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
950 vblk->tag_set.ops = &virtio_mq_ops;
951 vblk->tag_set.queue_depth = queue_depth;
952 vblk->tag_set.numa_node = NUMA_NO_NODE;
953 vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
954 vblk->tag_set.cmd_size =
955 sizeof(struct virtblk_req) +
956 sizeof(struct scatterlist) * VIRTIO_BLK_INLINE_SG_CNT;
957 vblk->tag_set.driver_data = vblk;
958 vblk->tag_set.nr_hw_queues = vblk->num_vqs;
959 vblk->tag_set.nr_maps = 1;
960 if (vblk->io_queues[HCTX_TYPE_POLL])
961 vblk->tag_set.nr_maps = 3;
963 err = blk_mq_alloc_tag_set(&vblk->tag_set);
967 vblk->disk = blk_mq_alloc_disk(&vblk->tag_set, vblk);
968 if (IS_ERR(vblk->disk)) {
969 err = PTR_ERR(vblk->disk);
972 q = vblk->disk->queue;
974 virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
976 vblk->disk->major = major;
977 vblk->disk->first_minor = index_to_minor(index);
978 vblk->disk->minors = 1 << PART_BITS;
979 vblk->disk->private_data = vblk;
980 vblk->disk->fops = &virtblk_fops;
983 /* configure queue flush support */
984 virtblk_update_cache_mode(vdev);
986 /* If disk is read-only in the host, the guest should obey */
987 if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
988 set_disk_ro(vblk->disk, 1);
990 /* We can handle whatever the host told us to handle. */
991 blk_queue_max_segments(q, sg_elems);
993 /* No real sector limit. */
994 blk_queue_max_hw_sectors(q, -1U);
996 max_size = virtio_max_dma_size(vdev);
998 /* Host can optionally specify maximum segment size and number of
1000 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
1001 struct virtio_blk_config, size_max, &v);
1003 max_size = min(max_size, v);
1005 blk_queue_max_segment_size(q, max_size);
1007 /* Host can optionally specify the block size of the device */
1008 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
1009 struct virtio_blk_config, blk_size,
1012 err = blk_validate_block_size(blk_size);
1015 "virtio_blk: invalid block size: 0x%x\n",
1017 goto out_cleanup_disk;
1020 blk_queue_logical_block_size(q, blk_size);
1022 blk_size = queue_logical_block_size(q);
1024 /* Use topology information if available */
1025 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1026 struct virtio_blk_config, physical_block_exp,
1027 &physical_block_exp);
1028 if (!err && physical_block_exp)
1029 blk_queue_physical_block_size(q,
1030 blk_size * (1 << physical_block_exp));
1032 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1033 struct virtio_blk_config, alignment_offset,
1035 if (!err && alignment_offset)
1036 blk_queue_alignment_offset(q, blk_size * alignment_offset);
1038 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1039 struct virtio_blk_config, min_io_size,
1041 if (!err && min_io_size)
1042 blk_queue_io_min(q, blk_size * min_io_size);
1044 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1045 struct virtio_blk_config, opt_io_size,
1047 if (!err && opt_io_size)
1048 blk_queue_io_opt(q, blk_size * opt_io_size);
1050 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
1051 virtio_cread(vdev, struct virtio_blk_config,
1052 discard_sector_alignment, &discard_granularity);
1054 virtio_cread(vdev, struct virtio_blk_config,
1055 max_discard_sectors, &v);
1056 blk_queue_max_discard_sectors(q, v ? v : UINT_MAX);
1058 virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
1062 if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
1063 virtio_cread(vdev, struct virtio_blk_config,
1064 max_write_zeroes_sectors, &v);
1065 blk_queue_max_write_zeroes_sectors(q, v ? v : UINT_MAX);
1068 /* The discard and secure erase limits are combined since the Linux
1069 * block layer uses the same limit for both commands.
1071 * If both VIRTIO_BLK_F_SECURE_ERASE and VIRTIO_BLK_F_DISCARD features
1072 * are negotiated, we will use the minimum between the limits.
1074 * discard sector alignment is set to the minimum between discard_sector_alignment
1075 * and secure_erase_sector_alignment.
1077 * max discard sectors is set to the minimum between max_discard_seg and
1078 * max_secure_erase_seg.
1080 if (virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1082 virtio_cread(vdev, struct virtio_blk_config,
1083 secure_erase_sector_alignment, &v);
1085 /* secure_erase_sector_alignment should not be zero, the device should set a
1086 * valid number of sectors.
1090 "virtio_blk: secure_erase_sector_alignment can't be 0\n");
1092 goto out_cleanup_disk;
1095 discard_granularity = min_not_zero(discard_granularity, v);
1097 virtio_cread(vdev, struct virtio_blk_config,
1098 max_secure_erase_sectors, &v);
1100 /* max_secure_erase_sectors should not be zero, the device should set a
1101 * valid number of sectors.
1105 "virtio_blk: max_secure_erase_sectors can't be 0\n");
1107 goto out_cleanup_disk;
1110 blk_queue_max_secure_erase_sectors(q, v);
1112 virtio_cread(vdev, struct virtio_blk_config,
1113 max_secure_erase_seg, &v);
1115 /* max_secure_erase_seg should not be zero, the device should set a
1116 * valid number of segments
1120 "virtio_blk: max_secure_erase_seg can't be 0\n");
1122 goto out_cleanup_disk;
1125 max_discard_segs = min_not_zero(max_discard_segs, v);
1128 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD) ||
1129 virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1130 /* max_discard_seg and discard_granularity will be 0 only
1131 * if max_discard_seg and discard_sector_alignment fields in the virtio
1132 * config are 0 and VIRTIO_BLK_F_SECURE_ERASE feature is not negotiated.
1133 * In this case, we use default values.
1135 if (!max_discard_segs)
1136 max_discard_segs = sg_elems;
1138 blk_queue_max_discard_segments(q,
1139 min(max_discard_segs, MAX_DISCARD_SEGMENTS));
1141 if (discard_granularity)
1142 q->limits.discard_granularity = discard_granularity << SECTOR_SHIFT;
1144 q->limits.discard_granularity = blk_size;
1147 virtblk_update_capacity(vblk, false);
1148 virtio_device_ready(vdev);
1150 err = device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
1152 goto out_cleanup_disk;
1157 put_disk(vblk->disk);
1159 blk_mq_free_tag_set(&vblk->tag_set);
1161 vdev->config->del_vqs(vdev);
1166 ida_simple_remove(&vd_index_ida, index);
1171 static void virtblk_remove(struct virtio_device *vdev)
1173 struct virtio_blk *vblk = vdev->priv;
1175 /* Make sure no work handler is accessing the device. */
1176 flush_work(&vblk->config_work);
1178 del_gendisk(vblk->disk);
1179 blk_mq_free_tag_set(&vblk->tag_set);
1181 mutex_lock(&vblk->vdev_mutex);
1183 /* Stop all the virtqueues. */
1184 virtio_reset_device(vdev);
1186 /* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
1189 vdev->config->del_vqs(vdev);
1192 mutex_unlock(&vblk->vdev_mutex);
1194 put_disk(vblk->disk);
1197 #ifdef CONFIG_PM_SLEEP
1198 static int virtblk_freeze(struct virtio_device *vdev)
1200 struct virtio_blk *vblk = vdev->priv;
1202 /* Ensure we don't receive any more interrupts */
1203 virtio_reset_device(vdev);
1205 /* Make sure no work handler is accessing the device. */
1206 flush_work(&vblk->config_work);
1208 blk_mq_quiesce_queue(vblk->disk->queue);
1210 vdev->config->del_vqs(vdev);
1216 static int virtblk_restore(struct virtio_device *vdev)
1218 struct virtio_blk *vblk = vdev->priv;
1221 ret = init_vq(vdev->priv);
1225 virtio_device_ready(vdev);
1227 blk_mq_unquiesce_queue(vblk->disk->queue);
1232 static const struct virtio_device_id id_table[] = {
1233 { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
1237 static unsigned int features_legacy[] = {
1238 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1239 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1240 VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1241 VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1242 VIRTIO_BLK_F_SECURE_ERASE,
1245 static unsigned int features[] = {
1246 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1247 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1248 VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1249 VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1250 VIRTIO_BLK_F_SECURE_ERASE,
1253 static struct virtio_driver virtio_blk = {
1254 .feature_table = features,
1255 .feature_table_size = ARRAY_SIZE(features),
1256 .feature_table_legacy = features_legacy,
1257 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
1258 .driver.name = KBUILD_MODNAME,
1259 .driver.owner = THIS_MODULE,
1260 .id_table = id_table,
1261 .probe = virtblk_probe,
1262 .remove = virtblk_remove,
1263 .config_changed = virtblk_config_changed,
1264 #ifdef CONFIG_PM_SLEEP
1265 .freeze = virtblk_freeze,
1266 .restore = virtblk_restore,
1270 static int __init virtio_blk_init(void)
1274 virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1278 major = register_blkdev(0, "virtblk");
1281 goto out_destroy_workqueue;
1284 error = register_virtio_driver(&virtio_blk);
1286 goto out_unregister_blkdev;
1289 out_unregister_blkdev:
1290 unregister_blkdev(major, "virtblk");
1291 out_destroy_workqueue:
1292 destroy_workqueue(virtblk_wq);
1296 static void __exit virtio_blk_fini(void)
1298 unregister_virtio_driver(&virtio_blk);
1299 unregister_blkdev(major, "virtblk");
1300 destroy_workqueue(virtblk_wq);
1302 module_init(virtio_blk_init);
1303 module_exit(virtio_blk_fini);
1305 MODULE_DEVICE_TABLE(virtio, id_table);
1306 MODULE_DESCRIPTION("Virtio block driver");
1307 MODULE_LICENSE("GPL");