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_fail_to_queue(struct request *req, int rc)
320 virtblk_cleanup_cmd(req);
323 return BLK_STS_DEV_RESOURCE;
325 return BLK_STS_RESOURCE;
327 return BLK_STS_IOERR;
331 static blk_status_t virtblk_prep_rq(struct blk_mq_hw_ctx *hctx,
332 struct virtio_blk *vblk,
334 struct virtblk_req *vbr)
339 status = virtblk_setup_cmd(vblk->vdev, req, vbr);
340 if (unlikely(status))
343 num = virtblk_map_data(hctx, req, vbr);
344 if (unlikely(num < 0))
345 return virtblk_fail_to_queue(req, -ENOMEM);
346 vbr->sg_table.nents = num;
348 blk_mq_start_request(req);
353 static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
354 const struct blk_mq_queue_data *bd)
356 struct virtio_blk *vblk = hctx->queue->queuedata;
357 struct request *req = bd->rq;
358 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
360 int qid = hctx->queue_num;
365 status = virtblk_prep_rq(hctx, vblk, req, vbr);
366 if (unlikely(status))
369 spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
370 err = virtblk_add_req(vblk->vqs[qid].vq, vbr);
372 virtqueue_kick(vblk->vqs[qid].vq);
373 /* Don't stop the queue if -ENOMEM: we may have failed to
374 * bounce the buffer due to global resource outage.
377 blk_mq_stop_hw_queue(hctx);
378 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
379 virtblk_unmap_data(req, vbr);
380 return virtblk_fail_to_queue(req, err);
383 if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
385 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
388 virtqueue_notify(vblk->vqs[qid].vq);
392 static bool virtblk_prep_rq_batch(struct request *req)
394 struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
395 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
397 req->mq_hctx->tags->rqs[req->tag] = req;
399 return virtblk_prep_rq(req->mq_hctx, vblk, req, vbr) == BLK_STS_OK;
402 static bool virtblk_add_req_batch(struct virtio_blk_vq *vq,
403 struct request **rqlist)
409 spin_lock_irqsave(&vq->lock, flags);
411 while (!rq_list_empty(*rqlist)) {
412 struct request *req = rq_list_pop(rqlist);
413 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
415 err = virtblk_add_req(vq->vq, vbr);
417 virtblk_unmap_data(req, vbr);
418 virtblk_cleanup_cmd(req);
419 blk_mq_requeue_request(req, true);
423 kick = virtqueue_kick_prepare(vq->vq);
424 spin_unlock_irqrestore(&vq->lock, flags);
429 static void virtio_queue_rqs(struct request **rqlist)
431 struct request *req, *next, *prev = NULL;
432 struct request *requeue_list = NULL;
434 rq_list_for_each_safe(rqlist, req, next) {
435 struct virtio_blk_vq *vq = get_virtio_blk_vq(req->mq_hctx);
438 if (!virtblk_prep_rq_batch(req)) {
439 rq_list_move(rqlist, &requeue_list, req, prev);
445 if (!next || req->mq_hctx != next->mq_hctx) {
447 kick = virtblk_add_req_batch(vq, rqlist);
449 virtqueue_notify(vq->vq);
457 *rqlist = requeue_list;
460 /* return id (s/n) string for *disk to *id_str
462 static int virtblk_get_id(struct gendisk *disk, char *id_str)
464 struct virtio_blk *vblk = disk->private_data;
465 struct request_queue *q = vblk->disk->queue;
469 req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
473 err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
477 blk_execute_rq(req, false);
478 err = blk_status_to_errno(virtblk_result(blk_mq_rq_to_pdu(req)));
480 blk_mq_free_request(req);
484 /* We provide getgeo only to please some old bootloader/partitioning tools */
485 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
487 struct virtio_blk *vblk = bd->bd_disk->private_data;
490 mutex_lock(&vblk->vdev_mutex);
497 /* see if the host passed in geometry config */
498 if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
499 virtio_cread(vblk->vdev, struct virtio_blk_config,
500 geometry.cylinders, &geo->cylinders);
501 virtio_cread(vblk->vdev, struct virtio_blk_config,
502 geometry.heads, &geo->heads);
503 virtio_cread(vblk->vdev, struct virtio_blk_config,
504 geometry.sectors, &geo->sectors);
506 /* some standard values, similar to sd */
508 geo->sectors = 1 << 5;
509 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
512 mutex_unlock(&vblk->vdev_mutex);
516 static void virtblk_free_disk(struct gendisk *disk)
518 struct virtio_blk *vblk = disk->private_data;
520 ida_simple_remove(&vd_index_ida, vblk->index);
521 mutex_destroy(&vblk->vdev_mutex);
525 static const struct block_device_operations virtblk_fops = {
526 .owner = THIS_MODULE,
527 .getgeo = virtblk_getgeo,
528 .free_disk = virtblk_free_disk,
531 static int index_to_minor(int index)
533 return index << PART_BITS;
536 static int minor_to_index(int minor)
538 return minor >> PART_BITS;
541 static ssize_t serial_show(struct device *dev,
542 struct device_attribute *attr, char *buf)
544 struct gendisk *disk = dev_to_disk(dev);
547 /* sysfs gives us a PAGE_SIZE buffer */
548 BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
550 buf[VIRTIO_BLK_ID_BYTES] = '\0';
551 err = virtblk_get_id(disk, buf);
555 if (err == -EIO) /* Unsupported? Make it empty. */
561 static DEVICE_ATTR_RO(serial);
563 /* The queue's logical block size must be set before calling this */
564 static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
566 struct virtio_device *vdev = vblk->vdev;
567 struct request_queue *q = vblk->disk->queue;
568 char cap_str_2[10], cap_str_10[10];
569 unsigned long long nblocks;
572 /* Host must always specify the capacity. */
573 virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
575 nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
577 string_get_size(nblocks, queue_logical_block_size(q),
578 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
579 string_get_size(nblocks, queue_logical_block_size(q),
580 STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
582 dev_notice(&vdev->dev,
583 "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
584 vblk->disk->disk_name,
585 resize ? "new size: " : "",
587 queue_logical_block_size(q),
591 set_capacity_and_notify(vblk->disk, capacity);
594 static void virtblk_config_changed_work(struct work_struct *work)
596 struct virtio_blk *vblk =
597 container_of(work, struct virtio_blk, config_work);
599 virtblk_update_capacity(vblk, true);
602 static void virtblk_config_changed(struct virtio_device *vdev)
604 struct virtio_blk *vblk = vdev->priv;
606 queue_work(virtblk_wq, &vblk->config_work);
609 static int init_vq(struct virtio_blk *vblk)
613 vq_callback_t **callbacks;
615 struct virtqueue **vqs;
616 unsigned short num_vqs;
617 unsigned int num_poll_vqs;
618 struct virtio_device *vdev = vblk->vdev;
619 struct irq_affinity desc = { 0, };
621 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
622 struct virtio_blk_config, num_queues,
627 if (!err && !num_vqs) {
628 dev_err(&vdev->dev, "MQ advertised but zero queues reported\n");
632 num_vqs = min_t(unsigned int,
633 min_not_zero(num_request_queues, nr_cpu_ids),
636 num_poll_vqs = min_t(unsigned int, poll_queues, num_vqs - 1);
638 vblk->io_queues[HCTX_TYPE_DEFAULT] = num_vqs - num_poll_vqs;
639 vblk->io_queues[HCTX_TYPE_READ] = 0;
640 vblk->io_queues[HCTX_TYPE_POLL] = num_poll_vqs;
642 dev_info(&vdev->dev, "%d/%d/%d default/read/poll queues\n",
643 vblk->io_queues[HCTX_TYPE_DEFAULT],
644 vblk->io_queues[HCTX_TYPE_READ],
645 vblk->io_queues[HCTX_TYPE_POLL]);
647 vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
651 names = kmalloc_array(num_vqs, sizeof(*names), GFP_KERNEL);
652 callbacks = kmalloc_array(num_vqs, sizeof(*callbacks), GFP_KERNEL);
653 vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
654 if (!names || !callbacks || !vqs) {
659 for (i = 0; i < num_vqs - num_poll_vqs; i++) {
660 callbacks[i] = virtblk_done;
661 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%d", i);
662 names[i] = vblk->vqs[i].name;
665 for (; i < num_vqs; i++) {
667 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req_poll.%d", i);
668 names[i] = vblk->vqs[i].name;
671 /* Discover virtqueues and write information to configuration. */
672 err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
676 for (i = 0; i < num_vqs; i++) {
677 spin_lock_init(&vblk->vqs[i].lock);
678 vblk->vqs[i].vq = vqs[i];
680 vblk->num_vqs = num_vqs;
692 * Legacy naming scheme used for virtio devices. We are stuck with it for
693 * virtio blk but don't ever use it for any new driver.
695 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
697 const int base = 'z' - 'a' + 1;
698 char *begin = buf + strlen(prefix);
699 char *end = buf + buflen;
709 *--p = 'a' + (index % unit);
710 index = (index / unit) - 1;
711 } while (index >= 0);
713 memmove(begin, p, end - p);
714 memcpy(buf, prefix, strlen(prefix));
719 static int virtblk_get_cache_mode(struct virtio_device *vdev)
724 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
725 struct virtio_blk_config, wce,
729 * If WCE is not configurable and flush is not available,
730 * assume no writeback cache is in use.
733 writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
738 static void virtblk_update_cache_mode(struct virtio_device *vdev)
740 u8 writeback = virtblk_get_cache_mode(vdev);
741 struct virtio_blk *vblk = vdev->priv;
743 blk_queue_write_cache(vblk->disk->queue, writeback, false);
746 static const char *const virtblk_cache_types[] = {
747 "write through", "write back"
751 cache_type_store(struct device *dev, struct device_attribute *attr,
752 const char *buf, size_t count)
754 struct gendisk *disk = dev_to_disk(dev);
755 struct virtio_blk *vblk = disk->private_data;
756 struct virtio_device *vdev = vblk->vdev;
759 BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
760 i = sysfs_match_string(virtblk_cache_types, buf);
764 virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
765 virtblk_update_cache_mode(vdev);
770 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
772 struct gendisk *disk = dev_to_disk(dev);
773 struct virtio_blk *vblk = disk->private_data;
774 u8 writeback = virtblk_get_cache_mode(vblk->vdev);
776 BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
777 return sysfs_emit(buf, "%s\n", virtblk_cache_types[writeback]);
780 static DEVICE_ATTR_RW(cache_type);
782 static struct attribute *virtblk_attrs[] = {
783 &dev_attr_serial.attr,
784 &dev_attr_cache_type.attr,
788 static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
789 struct attribute *a, int n)
791 struct device *dev = kobj_to_dev(kobj);
792 struct gendisk *disk = dev_to_disk(dev);
793 struct virtio_blk *vblk = disk->private_data;
794 struct virtio_device *vdev = vblk->vdev;
796 if (a == &dev_attr_cache_type.attr &&
797 !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
803 static const struct attribute_group virtblk_attr_group = {
804 .attrs = virtblk_attrs,
805 .is_visible = virtblk_attrs_are_visible,
808 static const struct attribute_group *virtblk_attr_groups[] = {
813 static void virtblk_map_queues(struct blk_mq_tag_set *set)
815 struct virtio_blk *vblk = set->driver_data;
818 for (i = 0, qoff = 0; i < set->nr_maps; i++) {
819 struct blk_mq_queue_map *map = &set->map[i];
821 map->nr_queues = vblk->io_queues[i];
822 map->queue_offset = qoff;
823 qoff += map->nr_queues;
825 if (map->nr_queues == 0)
829 * Regular queues have interrupts and hence CPU affinity is
830 * defined by the core virtio code, but polling queues have
831 * no interrupts so we let the block layer assign CPU affinity.
833 if (i == HCTX_TYPE_POLL)
834 blk_mq_map_queues(&set->map[i]);
836 blk_mq_virtio_map_queues(&set->map[i], vblk->vdev, 0);
840 static void virtblk_complete_batch(struct io_comp_batch *iob)
844 rq_list_for_each(&iob->req_list, req) {
845 virtblk_unmap_data(req, blk_mq_rq_to_pdu(req));
846 virtblk_cleanup_cmd(req);
848 blk_mq_end_request_batch(iob);
851 static int virtblk_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
853 struct virtio_blk *vblk = hctx->queue->queuedata;
854 struct virtio_blk_vq *vq = get_virtio_blk_vq(hctx);
855 struct virtblk_req *vbr;
860 spin_lock_irqsave(&vq->lock, flags);
862 while ((vbr = virtqueue_get_buf(vq->vq, &len)) != NULL) {
863 struct request *req = blk_mq_rq_from_pdu(vbr);
866 if (!blk_mq_add_to_batch(req, iob, vbr->status,
867 virtblk_complete_batch))
868 blk_mq_complete_request(req);
872 blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
874 spin_unlock_irqrestore(&vq->lock, flags);
879 static const struct blk_mq_ops virtio_mq_ops = {
880 .queue_rq = virtio_queue_rq,
881 .queue_rqs = virtio_queue_rqs,
882 .commit_rqs = virtio_commit_rqs,
883 .complete = virtblk_request_done,
884 .map_queues = virtblk_map_queues,
885 .poll = virtblk_poll,
888 static unsigned int virtblk_queue_depth;
889 module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
891 static int virtblk_probe(struct virtio_device *vdev)
893 struct virtio_blk *vblk;
894 struct request_queue *q;
897 u32 v, blk_size, max_size, sg_elems, opt_io_size;
898 u32 max_discard_segs = 0;
899 u32 discard_granularity = 0;
901 u8 physical_block_exp, alignment_offset;
902 unsigned int queue_depth;
904 if (!vdev->config->get) {
905 dev_err(&vdev->dev, "%s failure: config access disabled\n",
910 err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
916 /* We need to know how many segments before we allocate. */
917 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
918 struct virtio_blk_config, seg_max,
921 /* We need at least one SG element, whatever they say. */
922 if (err || !sg_elems)
925 /* Prevent integer overflows and honor max vq size */
926 sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2);
928 vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
934 mutex_init(&vblk->vdev_mutex);
938 INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
944 /* Default queue sizing is to fill the ring. */
945 if (!virtblk_queue_depth) {
946 queue_depth = vblk->vqs[0].vq->num_free;
947 /* ... but without indirect descs, we use 2 descs per req */
948 if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
951 queue_depth = virtblk_queue_depth;
954 memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
955 vblk->tag_set.ops = &virtio_mq_ops;
956 vblk->tag_set.queue_depth = queue_depth;
957 vblk->tag_set.numa_node = NUMA_NO_NODE;
958 vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
959 vblk->tag_set.cmd_size =
960 sizeof(struct virtblk_req) +
961 sizeof(struct scatterlist) * VIRTIO_BLK_INLINE_SG_CNT;
962 vblk->tag_set.driver_data = vblk;
963 vblk->tag_set.nr_hw_queues = vblk->num_vqs;
964 vblk->tag_set.nr_maps = 1;
965 if (vblk->io_queues[HCTX_TYPE_POLL])
966 vblk->tag_set.nr_maps = 3;
968 err = blk_mq_alloc_tag_set(&vblk->tag_set);
972 vblk->disk = blk_mq_alloc_disk(&vblk->tag_set, vblk);
973 if (IS_ERR(vblk->disk)) {
974 err = PTR_ERR(vblk->disk);
977 q = vblk->disk->queue;
979 virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
981 vblk->disk->major = major;
982 vblk->disk->first_minor = index_to_minor(index);
983 vblk->disk->minors = 1 << PART_BITS;
984 vblk->disk->private_data = vblk;
985 vblk->disk->fops = &virtblk_fops;
988 /* configure queue flush support */
989 virtblk_update_cache_mode(vdev);
991 /* If disk is read-only in the host, the guest should obey */
992 if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
993 set_disk_ro(vblk->disk, 1);
995 /* We can handle whatever the host told us to handle. */
996 blk_queue_max_segments(q, sg_elems);
998 /* No real sector limit. */
999 blk_queue_max_hw_sectors(q, -1U);
1001 max_size = virtio_max_dma_size(vdev);
1003 /* Host can optionally specify maximum segment size and number of
1005 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
1006 struct virtio_blk_config, size_max, &v);
1008 max_size = min(max_size, v);
1010 blk_queue_max_segment_size(q, max_size);
1012 /* Host can optionally specify the block size of the device */
1013 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
1014 struct virtio_blk_config, blk_size,
1017 err = blk_validate_block_size(blk_size);
1020 "virtio_blk: invalid block size: 0x%x\n",
1022 goto out_cleanup_disk;
1025 blk_queue_logical_block_size(q, blk_size);
1027 blk_size = queue_logical_block_size(q);
1029 /* Use topology information if available */
1030 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1031 struct virtio_blk_config, physical_block_exp,
1032 &physical_block_exp);
1033 if (!err && physical_block_exp)
1034 blk_queue_physical_block_size(q,
1035 blk_size * (1 << physical_block_exp));
1037 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1038 struct virtio_blk_config, alignment_offset,
1040 if (!err && alignment_offset)
1041 blk_queue_alignment_offset(q, blk_size * alignment_offset);
1043 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1044 struct virtio_blk_config, min_io_size,
1046 if (!err && min_io_size)
1047 blk_queue_io_min(q, blk_size * min_io_size);
1049 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1050 struct virtio_blk_config, opt_io_size,
1052 if (!err && opt_io_size)
1053 blk_queue_io_opt(q, blk_size * opt_io_size);
1055 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
1056 virtio_cread(vdev, struct virtio_blk_config,
1057 discard_sector_alignment, &discard_granularity);
1059 virtio_cread(vdev, struct virtio_blk_config,
1060 max_discard_sectors, &v);
1061 blk_queue_max_discard_sectors(q, v ? v : UINT_MAX);
1063 virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
1067 if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
1068 virtio_cread(vdev, struct virtio_blk_config,
1069 max_write_zeroes_sectors, &v);
1070 blk_queue_max_write_zeroes_sectors(q, v ? v : UINT_MAX);
1073 /* The discard and secure erase limits are combined since the Linux
1074 * block layer uses the same limit for both commands.
1076 * If both VIRTIO_BLK_F_SECURE_ERASE and VIRTIO_BLK_F_DISCARD features
1077 * are negotiated, we will use the minimum between the limits.
1079 * discard sector alignment is set to the minimum between discard_sector_alignment
1080 * and secure_erase_sector_alignment.
1082 * max discard sectors is set to the minimum between max_discard_seg and
1083 * max_secure_erase_seg.
1085 if (virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1087 virtio_cread(vdev, struct virtio_blk_config,
1088 secure_erase_sector_alignment, &v);
1090 /* secure_erase_sector_alignment should not be zero, the device should set a
1091 * valid number of sectors.
1095 "virtio_blk: secure_erase_sector_alignment can't be 0\n");
1097 goto out_cleanup_disk;
1100 discard_granularity = min_not_zero(discard_granularity, v);
1102 virtio_cread(vdev, struct virtio_blk_config,
1103 max_secure_erase_sectors, &v);
1105 /* max_secure_erase_sectors should not be zero, the device should set a
1106 * valid number of sectors.
1110 "virtio_blk: max_secure_erase_sectors can't be 0\n");
1112 goto out_cleanup_disk;
1115 blk_queue_max_secure_erase_sectors(q, v);
1117 virtio_cread(vdev, struct virtio_blk_config,
1118 max_secure_erase_seg, &v);
1120 /* max_secure_erase_seg should not be zero, the device should set a
1121 * valid number of segments
1125 "virtio_blk: max_secure_erase_seg can't be 0\n");
1127 goto out_cleanup_disk;
1130 max_discard_segs = min_not_zero(max_discard_segs, v);
1133 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD) ||
1134 virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1135 /* max_discard_seg and discard_granularity will be 0 only
1136 * if max_discard_seg and discard_sector_alignment fields in the virtio
1137 * config are 0 and VIRTIO_BLK_F_SECURE_ERASE feature is not negotiated.
1138 * In this case, we use default values.
1140 if (!max_discard_segs)
1141 max_discard_segs = sg_elems;
1143 blk_queue_max_discard_segments(q,
1144 min(max_discard_segs, MAX_DISCARD_SEGMENTS));
1146 if (discard_granularity)
1147 q->limits.discard_granularity = discard_granularity << SECTOR_SHIFT;
1149 q->limits.discard_granularity = blk_size;
1152 virtblk_update_capacity(vblk, false);
1153 virtio_device_ready(vdev);
1155 err = device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
1157 goto out_cleanup_disk;
1162 put_disk(vblk->disk);
1164 blk_mq_free_tag_set(&vblk->tag_set);
1166 vdev->config->del_vqs(vdev);
1171 ida_simple_remove(&vd_index_ida, index);
1176 static void virtblk_remove(struct virtio_device *vdev)
1178 struct virtio_blk *vblk = vdev->priv;
1180 /* Make sure no work handler is accessing the device. */
1181 flush_work(&vblk->config_work);
1183 del_gendisk(vblk->disk);
1184 blk_mq_free_tag_set(&vblk->tag_set);
1186 mutex_lock(&vblk->vdev_mutex);
1188 /* Stop all the virtqueues. */
1189 virtio_reset_device(vdev);
1191 /* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
1194 vdev->config->del_vqs(vdev);
1197 mutex_unlock(&vblk->vdev_mutex);
1199 put_disk(vblk->disk);
1202 #ifdef CONFIG_PM_SLEEP
1203 static int virtblk_freeze(struct virtio_device *vdev)
1205 struct virtio_blk *vblk = vdev->priv;
1207 /* Ensure we don't receive any more interrupts */
1208 virtio_reset_device(vdev);
1210 /* Make sure no work handler is accessing the device. */
1211 flush_work(&vblk->config_work);
1213 blk_mq_quiesce_queue(vblk->disk->queue);
1215 vdev->config->del_vqs(vdev);
1221 static int virtblk_restore(struct virtio_device *vdev)
1223 struct virtio_blk *vblk = vdev->priv;
1226 ret = init_vq(vdev->priv);
1230 virtio_device_ready(vdev);
1232 blk_mq_unquiesce_queue(vblk->disk->queue);
1237 static const struct virtio_device_id id_table[] = {
1238 { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
1242 static unsigned int features_legacy[] = {
1243 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1244 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1245 VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1246 VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1247 VIRTIO_BLK_F_SECURE_ERASE,
1250 static unsigned int features[] = {
1251 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1252 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1253 VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1254 VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1255 VIRTIO_BLK_F_SECURE_ERASE,
1258 static struct virtio_driver virtio_blk = {
1259 .feature_table = features,
1260 .feature_table_size = ARRAY_SIZE(features),
1261 .feature_table_legacy = features_legacy,
1262 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
1263 .driver.name = KBUILD_MODNAME,
1264 .driver.owner = THIS_MODULE,
1265 .id_table = id_table,
1266 .probe = virtblk_probe,
1267 .remove = virtblk_remove,
1268 .config_changed = virtblk_config_changed,
1269 #ifdef CONFIG_PM_SLEEP
1270 .freeze = virtblk_freeze,
1271 .restore = virtblk_restore,
1275 static int __init virtio_blk_init(void)
1279 virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1283 major = register_blkdev(0, "virtblk");
1286 goto out_destroy_workqueue;
1289 error = register_virtio_driver(&virtio_blk);
1291 goto out_unregister_blkdev;
1294 out_unregister_blkdev:
1295 unregister_blkdev(major, "virtblk");
1296 out_destroy_workqueue:
1297 destroy_workqueue(virtblk_wq);
1301 static void __exit virtio_blk_fini(void)
1303 unregister_virtio_driver(&virtio_blk);
1304 unregister_blkdev(major, "virtblk");
1305 destroy_workqueue(virtblk_wq);
1307 module_init(virtio_blk_init);
1308 module_exit(virtio_blk_fini);
1310 MODULE_DEVICE_TABLE(virtio, id_table);
1311 MODULE_DESCRIPTION("Virtio block driver");
1312 MODULE_LICENSE("GPL");