Loading...
1//#define DEBUG
2#include <linux/spinlock.h>
3#include <linux/slab.h>
4#include <linux/blkdev.h>
5#include <linux/hdreg.h>
6#include <linux/module.h>
7#include <linux/mutex.h>
8#include <linux/virtio.h>
9#include <linux/virtio_blk.h>
10#include <linux/scatterlist.h>
11#include <linux/string_helpers.h>
12#include <scsi/scsi_cmnd.h>
13#include <linux/idr.h>
14#include <linux/blk-mq.h>
15#include <linux/numa.h>
16
17#define PART_BITS 4
18
19static int major;
20static DEFINE_IDA(vd_index_ida);
21
22static struct workqueue_struct *virtblk_wq;
23
24struct virtio_blk
25{
26 struct virtio_device *vdev;
27 struct virtqueue *vq;
28 spinlock_t vq_lock;
29
30 /* The disk structure for the kernel. */
31 struct gendisk *disk;
32
33 /* Process context for config space updates */
34 struct work_struct config_work;
35
36 /* Lock for config space updates */
37 struct mutex config_lock;
38
39 /* enable config space updates */
40 bool config_enable;
41
42 /* What host tells us, plus 2 for header & tailer. */
43 unsigned int sg_elems;
44
45 /* Ida index - used to track minor number allocations. */
46 int index;
47};
48
49struct virtblk_req
50{
51 struct request *req;
52 struct virtio_blk_outhdr out_hdr;
53 struct virtio_scsi_inhdr in_hdr;
54 u8 status;
55 struct scatterlist sg[];
56};
57
58static inline int virtblk_result(struct virtblk_req *vbr)
59{
60 switch (vbr->status) {
61 case VIRTIO_BLK_S_OK:
62 return 0;
63 case VIRTIO_BLK_S_UNSUPP:
64 return -ENOTTY;
65 default:
66 return -EIO;
67 }
68}
69
70static int __virtblk_add_req(struct virtqueue *vq,
71 struct virtblk_req *vbr,
72 struct scatterlist *data_sg,
73 bool have_data)
74{
75 struct scatterlist hdr, status, cmd, sense, inhdr, *sgs[6];
76 unsigned int num_out = 0, num_in = 0;
77 int type = vbr->out_hdr.type & ~VIRTIO_BLK_T_OUT;
78
79 sg_init_one(&hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
80 sgs[num_out++] = &hdr;
81
82 /*
83 * If this is a packet command we need a couple of additional headers.
84 * Behind the normal outhdr we put a segment with the scsi command
85 * block, and before the normal inhdr we put the sense data and the
86 * inhdr with additional status information.
87 */
88 if (type == VIRTIO_BLK_T_SCSI_CMD) {
89 sg_init_one(&cmd, vbr->req->cmd, vbr->req->cmd_len);
90 sgs[num_out++] = &cmd;
91 }
92
93 if (have_data) {
94 if (vbr->out_hdr.type & VIRTIO_BLK_T_OUT)
95 sgs[num_out++] = data_sg;
96 else
97 sgs[num_out + num_in++] = data_sg;
98 }
99
100 if (type == VIRTIO_BLK_T_SCSI_CMD) {
101 sg_init_one(&sense, vbr->req->sense, SCSI_SENSE_BUFFERSIZE);
102 sgs[num_out + num_in++] = &sense;
103 sg_init_one(&inhdr, &vbr->in_hdr, sizeof(vbr->in_hdr));
104 sgs[num_out + num_in++] = &inhdr;
105 }
106
107 sg_init_one(&status, &vbr->status, sizeof(vbr->status));
108 sgs[num_out + num_in++] = &status;
109
110 return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
111}
112
113static inline void virtblk_request_done(struct request *req)
114{
115 struct virtblk_req *vbr = req->special;
116 int error = virtblk_result(vbr);
117
118 if (req->cmd_type == REQ_TYPE_BLOCK_PC) {
119 req->resid_len = vbr->in_hdr.residual;
120 req->sense_len = vbr->in_hdr.sense_len;
121 req->errors = vbr->in_hdr.errors;
122 } else if (req->cmd_type == REQ_TYPE_SPECIAL) {
123 req->errors = (error != 0);
124 }
125
126 blk_mq_end_io(req, error);
127}
128
129static void virtblk_done(struct virtqueue *vq)
130{
131 struct virtio_blk *vblk = vq->vdev->priv;
132 bool req_done = false;
133 struct virtblk_req *vbr;
134 unsigned long flags;
135 unsigned int len;
136
137 spin_lock_irqsave(&vblk->vq_lock, flags);
138 do {
139 virtqueue_disable_cb(vq);
140 while ((vbr = virtqueue_get_buf(vblk->vq, &len)) != NULL) {
141 blk_mq_complete_request(vbr->req);
142 req_done = true;
143 }
144 if (unlikely(virtqueue_is_broken(vq)))
145 break;
146 } while (!virtqueue_enable_cb(vq));
147
148 /* In case queue is stopped waiting for more buffers. */
149 if (req_done)
150 blk_mq_start_stopped_hw_queues(vblk->disk->queue);
151 spin_unlock_irqrestore(&vblk->vq_lock, flags);
152}
153
154static int virtio_queue_rq(struct blk_mq_hw_ctx *hctx, struct request *req)
155{
156 struct virtio_blk *vblk = hctx->queue->queuedata;
157 struct virtblk_req *vbr = req->special;
158 unsigned long flags;
159 unsigned int num;
160 const bool last = (req->cmd_flags & REQ_END) != 0;
161 int err;
162
163 BUG_ON(req->nr_phys_segments + 2 > vblk->sg_elems);
164
165 vbr->req = req;
166 if (req->cmd_flags & REQ_FLUSH) {
167 vbr->out_hdr.type = VIRTIO_BLK_T_FLUSH;
168 vbr->out_hdr.sector = 0;
169 vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
170 } else {
171 switch (req->cmd_type) {
172 case REQ_TYPE_FS:
173 vbr->out_hdr.type = 0;
174 vbr->out_hdr.sector = blk_rq_pos(vbr->req);
175 vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
176 break;
177 case REQ_TYPE_BLOCK_PC:
178 vbr->out_hdr.type = VIRTIO_BLK_T_SCSI_CMD;
179 vbr->out_hdr.sector = 0;
180 vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
181 break;
182 case REQ_TYPE_SPECIAL:
183 vbr->out_hdr.type = VIRTIO_BLK_T_GET_ID;
184 vbr->out_hdr.sector = 0;
185 vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
186 break;
187 default:
188 /* We don't put anything else in the queue. */
189 BUG();
190 }
191 }
192
193 num = blk_rq_map_sg(hctx->queue, vbr->req, vbr->sg);
194 if (num) {
195 if (rq_data_dir(vbr->req) == WRITE)
196 vbr->out_hdr.type |= VIRTIO_BLK_T_OUT;
197 else
198 vbr->out_hdr.type |= VIRTIO_BLK_T_IN;
199 }
200
201 spin_lock_irqsave(&vblk->vq_lock, flags);
202 err = __virtblk_add_req(vblk->vq, vbr, vbr->sg, num);
203 if (err) {
204 virtqueue_kick(vblk->vq);
205 blk_mq_stop_hw_queue(hctx);
206 spin_unlock_irqrestore(&vblk->vq_lock, flags);
207 /* Out of mem doesn't actually happen, since we fall back
208 * to direct descriptors */
209 if (err == -ENOMEM || err == -ENOSPC)
210 return BLK_MQ_RQ_QUEUE_BUSY;
211 return BLK_MQ_RQ_QUEUE_ERROR;
212 }
213
214 if (last)
215 virtqueue_kick(vblk->vq);
216
217 spin_unlock_irqrestore(&vblk->vq_lock, flags);
218 return BLK_MQ_RQ_QUEUE_OK;
219}
220
221/* return id (s/n) string for *disk to *id_str
222 */
223static int virtblk_get_id(struct gendisk *disk, char *id_str)
224{
225 struct virtio_blk *vblk = disk->private_data;
226 struct request *req;
227 struct bio *bio;
228 int err;
229
230 bio = bio_map_kern(vblk->disk->queue, id_str, VIRTIO_BLK_ID_BYTES,
231 GFP_KERNEL);
232 if (IS_ERR(bio))
233 return PTR_ERR(bio);
234
235 req = blk_make_request(vblk->disk->queue, bio, GFP_KERNEL);
236 if (IS_ERR(req)) {
237 bio_put(bio);
238 return PTR_ERR(req);
239 }
240
241 req->cmd_type = REQ_TYPE_SPECIAL;
242 err = blk_execute_rq(vblk->disk->queue, vblk->disk, req, false);
243 blk_put_request(req);
244
245 return err;
246}
247
248static int virtblk_ioctl(struct block_device *bdev, fmode_t mode,
249 unsigned int cmd, unsigned long data)
250{
251 struct gendisk *disk = bdev->bd_disk;
252 struct virtio_blk *vblk = disk->private_data;
253
254 /*
255 * Only allow the generic SCSI ioctls if the host can support it.
256 */
257 if (!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_SCSI))
258 return -ENOTTY;
259
260 return scsi_cmd_blk_ioctl(bdev, mode, cmd,
261 (void __user *)data);
262}
263
264/* We provide getgeo only to please some old bootloader/partitioning tools */
265static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
266{
267 struct virtio_blk *vblk = bd->bd_disk->private_data;
268
269 /* see if the host passed in geometry config */
270 if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
271 virtio_cread(vblk->vdev, struct virtio_blk_config,
272 geometry.cylinders, &geo->cylinders);
273 virtio_cread(vblk->vdev, struct virtio_blk_config,
274 geometry.heads, &geo->heads);
275 virtio_cread(vblk->vdev, struct virtio_blk_config,
276 geometry.sectors, &geo->sectors);
277 } else {
278 /* some standard values, similar to sd */
279 geo->heads = 1 << 6;
280 geo->sectors = 1 << 5;
281 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
282 }
283 return 0;
284}
285
286static const struct block_device_operations virtblk_fops = {
287 .ioctl = virtblk_ioctl,
288 .owner = THIS_MODULE,
289 .getgeo = virtblk_getgeo,
290};
291
292static int index_to_minor(int index)
293{
294 return index << PART_BITS;
295}
296
297static int minor_to_index(int minor)
298{
299 return minor >> PART_BITS;
300}
301
302static ssize_t virtblk_serial_show(struct device *dev,
303 struct device_attribute *attr, char *buf)
304{
305 struct gendisk *disk = dev_to_disk(dev);
306 int err;
307
308 /* sysfs gives us a PAGE_SIZE buffer */
309 BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
310
311 buf[VIRTIO_BLK_ID_BYTES] = '\0';
312 err = virtblk_get_id(disk, buf);
313 if (!err)
314 return strlen(buf);
315
316 if (err == -EIO) /* Unsupported? Make it empty. */
317 return 0;
318
319 return err;
320}
321DEVICE_ATTR(serial, S_IRUGO, virtblk_serial_show, NULL);
322
323static void virtblk_config_changed_work(struct work_struct *work)
324{
325 struct virtio_blk *vblk =
326 container_of(work, struct virtio_blk, config_work);
327 struct virtio_device *vdev = vblk->vdev;
328 struct request_queue *q = vblk->disk->queue;
329 char cap_str_2[10], cap_str_10[10];
330 char *envp[] = { "RESIZE=1", NULL };
331 u64 capacity, size;
332
333 mutex_lock(&vblk->config_lock);
334 if (!vblk->config_enable)
335 goto done;
336
337 /* Host must always specify the capacity. */
338 virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
339
340 /* If capacity is too big, truncate with warning. */
341 if ((sector_t)capacity != capacity) {
342 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
343 (unsigned long long)capacity);
344 capacity = (sector_t)-1;
345 }
346
347 size = capacity * queue_logical_block_size(q);
348 string_get_size(size, STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
349 string_get_size(size, STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
350
351 dev_notice(&vdev->dev,
352 "new size: %llu %d-byte logical blocks (%s/%s)\n",
353 (unsigned long long)capacity,
354 queue_logical_block_size(q),
355 cap_str_10, cap_str_2);
356
357 set_capacity(vblk->disk, capacity);
358 revalidate_disk(vblk->disk);
359 kobject_uevent_env(&disk_to_dev(vblk->disk)->kobj, KOBJ_CHANGE, envp);
360done:
361 mutex_unlock(&vblk->config_lock);
362}
363
364static void virtblk_config_changed(struct virtio_device *vdev)
365{
366 struct virtio_blk *vblk = vdev->priv;
367
368 queue_work(virtblk_wq, &vblk->config_work);
369}
370
371static int init_vq(struct virtio_blk *vblk)
372{
373 int err = 0;
374
375 /* We expect one virtqueue, for output. */
376 vblk->vq = virtio_find_single_vq(vblk->vdev, virtblk_done, "requests");
377 if (IS_ERR(vblk->vq))
378 err = PTR_ERR(vblk->vq);
379
380 return err;
381}
382
383/*
384 * Legacy naming scheme used for virtio devices. We are stuck with it for
385 * virtio blk but don't ever use it for any new driver.
386 */
387static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
388{
389 const int base = 'z' - 'a' + 1;
390 char *begin = buf + strlen(prefix);
391 char *end = buf + buflen;
392 char *p;
393 int unit;
394
395 p = end - 1;
396 *p = '\0';
397 unit = base;
398 do {
399 if (p == begin)
400 return -EINVAL;
401 *--p = 'a' + (index % unit);
402 index = (index / unit) - 1;
403 } while (index >= 0);
404
405 memmove(begin, p, end - p);
406 memcpy(buf, prefix, strlen(prefix));
407
408 return 0;
409}
410
411static int virtblk_get_cache_mode(struct virtio_device *vdev)
412{
413 u8 writeback;
414 int err;
415
416 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
417 struct virtio_blk_config, wce,
418 &writeback);
419 if (err)
420 writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_WCE);
421
422 return writeback;
423}
424
425static void virtblk_update_cache_mode(struct virtio_device *vdev)
426{
427 u8 writeback = virtblk_get_cache_mode(vdev);
428 struct virtio_blk *vblk = vdev->priv;
429
430 if (writeback)
431 blk_queue_flush(vblk->disk->queue, REQ_FLUSH);
432 else
433 blk_queue_flush(vblk->disk->queue, 0);
434
435 revalidate_disk(vblk->disk);
436}
437
438static const char *const virtblk_cache_types[] = {
439 "write through", "write back"
440};
441
442static ssize_t
443virtblk_cache_type_store(struct device *dev, struct device_attribute *attr,
444 const char *buf, size_t count)
445{
446 struct gendisk *disk = dev_to_disk(dev);
447 struct virtio_blk *vblk = disk->private_data;
448 struct virtio_device *vdev = vblk->vdev;
449 int i;
450
451 BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
452 for (i = ARRAY_SIZE(virtblk_cache_types); --i >= 0; )
453 if (sysfs_streq(buf, virtblk_cache_types[i]))
454 break;
455
456 if (i < 0)
457 return -EINVAL;
458
459 virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
460 virtblk_update_cache_mode(vdev);
461 return count;
462}
463
464static ssize_t
465virtblk_cache_type_show(struct device *dev, struct device_attribute *attr,
466 char *buf)
467{
468 struct gendisk *disk = dev_to_disk(dev);
469 struct virtio_blk *vblk = disk->private_data;
470 u8 writeback = virtblk_get_cache_mode(vblk->vdev);
471
472 BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
473 return snprintf(buf, 40, "%s\n", virtblk_cache_types[writeback]);
474}
475
476static const struct device_attribute dev_attr_cache_type_ro =
477 __ATTR(cache_type, S_IRUGO,
478 virtblk_cache_type_show, NULL);
479static const struct device_attribute dev_attr_cache_type_rw =
480 __ATTR(cache_type, S_IRUGO|S_IWUSR,
481 virtblk_cache_type_show, virtblk_cache_type_store);
482
483static struct blk_mq_ops virtio_mq_ops = {
484 .queue_rq = virtio_queue_rq,
485 .map_queue = blk_mq_map_queue,
486 .alloc_hctx = blk_mq_alloc_single_hw_queue,
487 .free_hctx = blk_mq_free_single_hw_queue,
488 .complete = virtblk_request_done,
489};
490
491static struct blk_mq_reg virtio_mq_reg = {
492 .ops = &virtio_mq_ops,
493 .nr_hw_queues = 1,
494 .queue_depth = 0, /* Set in virtblk_probe */
495 .numa_node = NUMA_NO_NODE,
496 .flags = BLK_MQ_F_SHOULD_MERGE,
497};
498module_param_named(queue_depth, virtio_mq_reg.queue_depth, uint, 0444);
499
500static int virtblk_init_vbr(void *data, struct blk_mq_hw_ctx *hctx,
501 struct request *rq, unsigned int nr)
502{
503 struct virtio_blk *vblk = data;
504 struct virtblk_req *vbr = rq->special;
505
506 sg_init_table(vbr->sg, vblk->sg_elems);
507 return 0;
508}
509
510static int virtblk_probe(struct virtio_device *vdev)
511{
512 struct virtio_blk *vblk;
513 struct request_queue *q;
514 int err, index;
515
516 u64 cap;
517 u32 v, blk_size, sg_elems, opt_io_size;
518 u16 min_io_size;
519 u8 physical_block_exp, alignment_offset;
520
521 err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
522 GFP_KERNEL);
523 if (err < 0)
524 goto out;
525 index = err;
526
527 /* We need to know how many segments before we allocate. */
528 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
529 struct virtio_blk_config, seg_max,
530 &sg_elems);
531
532 /* We need at least one SG element, whatever they say. */
533 if (err || !sg_elems)
534 sg_elems = 1;
535
536 /* We need an extra sg elements at head and tail. */
537 sg_elems += 2;
538 vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
539 if (!vblk) {
540 err = -ENOMEM;
541 goto out_free_index;
542 }
543
544 vblk->vdev = vdev;
545 vblk->sg_elems = sg_elems;
546 mutex_init(&vblk->config_lock);
547
548 INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
549 vblk->config_enable = true;
550
551 err = init_vq(vblk);
552 if (err)
553 goto out_free_vblk;
554 spin_lock_init(&vblk->vq_lock);
555
556 /* FIXME: How many partitions? How long is a piece of string? */
557 vblk->disk = alloc_disk(1 << PART_BITS);
558 if (!vblk->disk) {
559 err = -ENOMEM;
560 goto out_free_vq;
561 }
562
563 /* Default queue sizing is to fill the ring. */
564 if (!virtio_mq_reg.queue_depth) {
565 virtio_mq_reg.queue_depth = vblk->vq->num_free;
566 /* ... but without indirect descs, we use 2 descs per req */
567 if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
568 virtio_mq_reg.queue_depth /= 2;
569 }
570 virtio_mq_reg.cmd_size =
571 sizeof(struct virtblk_req) +
572 sizeof(struct scatterlist) * sg_elems;
573
574 q = vblk->disk->queue = blk_mq_init_queue(&virtio_mq_reg, vblk);
575 if (!q) {
576 err = -ENOMEM;
577 goto out_put_disk;
578 }
579
580 blk_mq_init_commands(q, virtblk_init_vbr, vblk);
581
582 q->queuedata = vblk;
583
584 virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
585
586 vblk->disk->major = major;
587 vblk->disk->first_minor = index_to_minor(index);
588 vblk->disk->private_data = vblk;
589 vblk->disk->fops = &virtblk_fops;
590 vblk->disk->driverfs_dev = &vdev->dev;
591 vblk->index = index;
592
593 /* configure queue flush support */
594 virtblk_update_cache_mode(vdev);
595
596 /* If disk is read-only in the host, the guest should obey */
597 if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
598 set_disk_ro(vblk->disk, 1);
599
600 /* Host must always specify the capacity. */
601 virtio_cread(vdev, struct virtio_blk_config, capacity, &cap);
602
603 /* If capacity is too big, truncate with warning. */
604 if ((sector_t)cap != cap) {
605 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
606 (unsigned long long)cap);
607 cap = (sector_t)-1;
608 }
609 set_capacity(vblk->disk, cap);
610
611 /* We can handle whatever the host told us to handle. */
612 blk_queue_max_segments(q, vblk->sg_elems-2);
613
614 /* No need to bounce any requests */
615 blk_queue_bounce_limit(q, BLK_BOUNCE_ANY);
616
617 /* No real sector limit. */
618 blk_queue_max_hw_sectors(q, -1U);
619
620 /* Host can optionally specify maximum segment size and number of
621 * segments. */
622 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
623 struct virtio_blk_config, size_max, &v);
624 if (!err)
625 blk_queue_max_segment_size(q, v);
626 else
627 blk_queue_max_segment_size(q, -1U);
628
629 /* Host can optionally specify the block size of the device */
630 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
631 struct virtio_blk_config, blk_size,
632 &blk_size);
633 if (!err)
634 blk_queue_logical_block_size(q, blk_size);
635 else
636 blk_size = queue_logical_block_size(q);
637
638 /* Use topology information if available */
639 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
640 struct virtio_blk_config, physical_block_exp,
641 &physical_block_exp);
642 if (!err && physical_block_exp)
643 blk_queue_physical_block_size(q,
644 blk_size * (1 << physical_block_exp));
645
646 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
647 struct virtio_blk_config, alignment_offset,
648 &alignment_offset);
649 if (!err && alignment_offset)
650 blk_queue_alignment_offset(q, blk_size * alignment_offset);
651
652 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
653 struct virtio_blk_config, min_io_size,
654 &min_io_size);
655 if (!err && min_io_size)
656 blk_queue_io_min(q, blk_size * min_io_size);
657
658 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
659 struct virtio_blk_config, opt_io_size,
660 &opt_io_size);
661 if (!err && opt_io_size)
662 blk_queue_io_opt(q, blk_size * opt_io_size);
663
664 add_disk(vblk->disk);
665 err = device_create_file(disk_to_dev(vblk->disk), &dev_attr_serial);
666 if (err)
667 goto out_del_disk;
668
669 if (virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
670 err = device_create_file(disk_to_dev(vblk->disk),
671 &dev_attr_cache_type_rw);
672 else
673 err = device_create_file(disk_to_dev(vblk->disk),
674 &dev_attr_cache_type_ro);
675 if (err)
676 goto out_del_disk;
677 return 0;
678
679out_del_disk:
680 del_gendisk(vblk->disk);
681 blk_cleanup_queue(vblk->disk->queue);
682out_put_disk:
683 put_disk(vblk->disk);
684out_free_vq:
685 vdev->config->del_vqs(vdev);
686out_free_vblk:
687 kfree(vblk);
688out_free_index:
689 ida_simple_remove(&vd_index_ida, index);
690out:
691 return err;
692}
693
694static void virtblk_remove(struct virtio_device *vdev)
695{
696 struct virtio_blk *vblk = vdev->priv;
697 int index = vblk->index;
698 int refc;
699
700 /* Prevent config work handler from accessing the device. */
701 mutex_lock(&vblk->config_lock);
702 vblk->config_enable = false;
703 mutex_unlock(&vblk->config_lock);
704
705 del_gendisk(vblk->disk);
706 blk_cleanup_queue(vblk->disk->queue);
707
708 /* Stop all the virtqueues. */
709 vdev->config->reset(vdev);
710
711 flush_work(&vblk->config_work);
712
713 refc = atomic_read(&disk_to_dev(vblk->disk)->kobj.kref.refcount);
714 put_disk(vblk->disk);
715 vdev->config->del_vqs(vdev);
716 kfree(vblk);
717
718 /* Only free device id if we don't have any users */
719 if (refc == 1)
720 ida_simple_remove(&vd_index_ida, index);
721}
722
723#ifdef CONFIG_PM_SLEEP
724static int virtblk_freeze(struct virtio_device *vdev)
725{
726 struct virtio_blk *vblk = vdev->priv;
727
728 /* Ensure we don't receive any more interrupts */
729 vdev->config->reset(vdev);
730
731 /* Prevent config work handler from accessing the device. */
732 mutex_lock(&vblk->config_lock);
733 vblk->config_enable = false;
734 mutex_unlock(&vblk->config_lock);
735
736 flush_work(&vblk->config_work);
737
738 blk_mq_stop_hw_queues(vblk->disk->queue);
739
740 vdev->config->del_vqs(vdev);
741 return 0;
742}
743
744static int virtblk_restore(struct virtio_device *vdev)
745{
746 struct virtio_blk *vblk = vdev->priv;
747 int ret;
748
749 vblk->config_enable = true;
750 ret = init_vq(vdev->priv);
751 if (!ret)
752 blk_mq_start_stopped_hw_queues(vblk->disk->queue);
753
754 return ret;
755}
756#endif
757
758static const struct virtio_device_id id_table[] = {
759 { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
760 { 0 },
761};
762
763static unsigned int features[] = {
764 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
765 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE, VIRTIO_BLK_F_SCSI,
766 VIRTIO_BLK_F_WCE, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE
767};
768
769static struct virtio_driver virtio_blk = {
770 .feature_table = features,
771 .feature_table_size = ARRAY_SIZE(features),
772 .driver.name = KBUILD_MODNAME,
773 .driver.owner = THIS_MODULE,
774 .id_table = id_table,
775 .probe = virtblk_probe,
776 .remove = virtblk_remove,
777 .config_changed = virtblk_config_changed,
778#ifdef CONFIG_PM_SLEEP
779 .freeze = virtblk_freeze,
780 .restore = virtblk_restore,
781#endif
782};
783
784static int __init init(void)
785{
786 int error;
787
788 virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
789 if (!virtblk_wq)
790 return -ENOMEM;
791
792 major = register_blkdev(0, "virtblk");
793 if (major < 0) {
794 error = major;
795 goto out_destroy_workqueue;
796 }
797
798 error = register_virtio_driver(&virtio_blk);
799 if (error)
800 goto out_unregister_blkdev;
801 return 0;
802
803out_unregister_blkdev:
804 unregister_blkdev(major, "virtblk");
805out_destroy_workqueue:
806 destroy_workqueue(virtblk_wq);
807 return error;
808}
809
810static void __exit fini(void)
811{
812 unregister_blkdev(major, "virtblk");
813 unregister_virtio_driver(&virtio_blk);
814 destroy_workqueue(virtblk_wq);
815}
816module_init(init);
817module_exit(fini);
818
819MODULE_DEVICE_TABLE(virtio, id_table);
820MODULE_DESCRIPTION("Virtio block driver");
821MODULE_LICENSE("GPL");
1// SPDX-License-Identifier: GPL-2.0-only
2//#define DEBUG
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 <linux/vmalloc.h>
19#include <uapi/linux/virtio_ring.h>
20
21#define PART_BITS 4
22#define VQ_NAME_LEN 16
23#define MAX_DISCARD_SEGMENTS 256u
24
25/* The maximum number of sg elements that fit into a virtqueue */
26#define VIRTIO_BLK_MAX_SG_ELEMS 32768
27
28#ifdef CONFIG_ARCH_NO_SG_CHAIN
29#define VIRTIO_BLK_INLINE_SG_CNT 0
30#else
31#define VIRTIO_BLK_INLINE_SG_CNT 2
32#endif
33
34static unsigned int num_request_queues;
35module_param(num_request_queues, uint, 0644);
36MODULE_PARM_DESC(num_request_queues,
37 "Limit the number of request queues to use for blk device. "
38 "0 for no limit. "
39 "Values > nr_cpu_ids truncated to nr_cpu_ids.");
40
41static unsigned int poll_queues;
42module_param(poll_queues, uint, 0644);
43MODULE_PARM_DESC(poll_queues, "The number of dedicated virtqueues for polling I/O");
44
45static int major;
46static DEFINE_IDA(vd_index_ida);
47
48static struct workqueue_struct *virtblk_wq;
49
50struct virtio_blk_vq {
51 struct virtqueue *vq;
52 spinlock_t lock;
53 char name[VQ_NAME_LEN];
54} ____cacheline_aligned_in_smp;
55
56struct virtio_blk {
57 /*
58 * This mutex must be held by anything that may run after
59 * virtblk_remove() sets vblk->vdev to NULL.
60 *
61 * blk-mq, virtqueue processing, and sysfs attribute code paths are
62 * shut down before vblk->vdev is set to NULL and therefore do not need
63 * to hold this mutex.
64 */
65 struct mutex vdev_mutex;
66 struct virtio_device *vdev;
67
68 /* The disk structure for the kernel. */
69 struct gendisk *disk;
70
71 /* Block layer tags. */
72 struct blk_mq_tag_set tag_set;
73
74 /* Process context for config space updates */
75 struct work_struct config_work;
76
77 /* Ida index - used to track minor number allocations. */
78 int index;
79
80 /* num of vqs */
81 int num_vqs;
82 int io_queues[HCTX_MAX_TYPES];
83 struct virtio_blk_vq *vqs;
84
85 /* For zoned device */
86 unsigned int zone_sectors;
87};
88
89struct virtblk_req {
90 /* Out header */
91 struct virtio_blk_outhdr out_hdr;
92
93 /* In header */
94 union {
95 u8 status;
96
97 /*
98 * The zone append command has an extended in header.
99 * The status field in zone_append_in_hdr must always
100 * be the last byte.
101 */
102 struct {
103 __virtio64 sector;
104 u8 status;
105 } zone_append;
106 } in_hdr;
107
108 size_t in_hdr_len;
109
110 struct sg_table sg_table;
111 struct scatterlist sg[];
112};
113
114static inline blk_status_t virtblk_result(u8 status)
115{
116 switch (status) {
117 case VIRTIO_BLK_S_OK:
118 return BLK_STS_OK;
119 case VIRTIO_BLK_S_UNSUPP:
120 return BLK_STS_NOTSUPP;
121 case VIRTIO_BLK_S_ZONE_OPEN_RESOURCE:
122 return BLK_STS_ZONE_OPEN_RESOURCE;
123 case VIRTIO_BLK_S_ZONE_ACTIVE_RESOURCE:
124 return BLK_STS_ZONE_ACTIVE_RESOURCE;
125 case VIRTIO_BLK_S_IOERR:
126 case VIRTIO_BLK_S_ZONE_UNALIGNED_WP:
127 default:
128 return BLK_STS_IOERR;
129 }
130}
131
132static inline struct virtio_blk_vq *get_virtio_blk_vq(struct blk_mq_hw_ctx *hctx)
133{
134 struct virtio_blk *vblk = hctx->queue->queuedata;
135 struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
136
137 return vq;
138}
139
140static int virtblk_add_req(struct virtqueue *vq, struct virtblk_req *vbr)
141{
142 struct scatterlist out_hdr, in_hdr, *sgs[3];
143 unsigned int num_out = 0, num_in = 0;
144
145 sg_init_one(&out_hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
146 sgs[num_out++] = &out_hdr;
147
148 if (vbr->sg_table.nents) {
149 if (vbr->out_hdr.type & cpu_to_virtio32(vq->vdev, VIRTIO_BLK_T_OUT))
150 sgs[num_out++] = vbr->sg_table.sgl;
151 else
152 sgs[num_out + num_in++] = vbr->sg_table.sgl;
153 }
154
155 sg_init_one(&in_hdr, &vbr->in_hdr.status, vbr->in_hdr_len);
156 sgs[num_out + num_in++] = &in_hdr;
157
158 return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
159}
160
161static int virtblk_setup_discard_write_zeroes_erase(struct request *req, bool unmap)
162{
163 unsigned short segments = blk_rq_nr_discard_segments(req);
164 unsigned short n = 0;
165 struct virtio_blk_discard_write_zeroes *range;
166 struct bio *bio;
167 u32 flags = 0;
168
169 if (unmap)
170 flags |= VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP;
171
172 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
173 if (!range)
174 return -ENOMEM;
175
176 /*
177 * Single max discard segment means multi-range discard isn't
178 * supported, and block layer only runs contiguity merge like
179 * normal RW request. So we can't reply on bio for retrieving
180 * each range info.
181 */
182 if (queue_max_discard_segments(req->q) == 1) {
183 range[0].flags = cpu_to_le32(flags);
184 range[0].num_sectors = cpu_to_le32(blk_rq_sectors(req));
185 range[0].sector = cpu_to_le64(blk_rq_pos(req));
186 n = 1;
187 } else {
188 __rq_for_each_bio(bio, req) {
189 u64 sector = bio->bi_iter.bi_sector;
190 u32 num_sectors = bio->bi_iter.bi_size >> SECTOR_SHIFT;
191
192 range[n].flags = cpu_to_le32(flags);
193 range[n].num_sectors = cpu_to_le32(num_sectors);
194 range[n].sector = cpu_to_le64(sector);
195 n++;
196 }
197 }
198
199 WARN_ON_ONCE(n != segments);
200
201 bvec_set_virt(&req->special_vec, range, sizeof(*range) * segments);
202 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
203
204 return 0;
205}
206
207static void virtblk_unmap_data(struct request *req, struct virtblk_req *vbr)
208{
209 if (blk_rq_nr_phys_segments(req))
210 sg_free_table_chained(&vbr->sg_table,
211 VIRTIO_BLK_INLINE_SG_CNT);
212}
213
214static int virtblk_map_data(struct blk_mq_hw_ctx *hctx, struct request *req,
215 struct virtblk_req *vbr)
216{
217 int err;
218
219 if (!blk_rq_nr_phys_segments(req))
220 return 0;
221
222 vbr->sg_table.sgl = vbr->sg;
223 err = sg_alloc_table_chained(&vbr->sg_table,
224 blk_rq_nr_phys_segments(req),
225 vbr->sg_table.sgl,
226 VIRTIO_BLK_INLINE_SG_CNT);
227 if (unlikely(err))
228 return -ENOMEM;
229
230 return blk_rq_map_sg(hctx->queue, req, vbr->sg_table.sgl);
231}
232
233static void virtblk_cleanup_cmd(struct request *req)
234{
235 if (req->rq_flags & RQF_SPECIAL_PAYLOAD)
236 kfree(bvec_virt(&req->special_vec));
237}
238
239static blk_status_t virtblk_setup_cmd(struct virtio_device *vdev,
240 struct request *req,
241 struct virtblk_req *vbr)
242{
243 size_t in_hdr_len = sizeof(vbr->in_hdr.status);
244 bool unmap = false;
245 u32 type;
246 u64 sector = 0;
247
248 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) && op_is_zone_mgmt(req_op(req)))
249 return BLK_STS_NOTSUPP;
250
251 /* Set fields for all request types */
252 vbr->out_hdr.ioprio = cpu_to_virtio32(vdev, req_get_ioprio(req));
253
254 switch (req_op(req)) {
255 case REQ_OP_READ:
256 type = VIRTIO_BLK_T_IN;
257 sector = blk_rq_pos(req);
258 break;
259 case REQ_OP_WRITE:
260 type = VIRTIO_BLK_T_OUT;
261 sector = blk_rq_pos(req);
262 break;
263 case REQ_OP_FLUSH:
264 type = VIRTIO_BLK_T_FLUSH;
265 break;
266 case REQ_OP_DISCARD:
267 type = VIRTIO_BLK_T_DISCARD;
268 break;
269 case REQ_OP_WRITE_ZEROES:
270 type = VIRTIO_BLK_T_WRITE_ZEROES;
271 unmap = !(req->cmd_flags & REQ_NOUNMAP);
272 break;
273 case REQ_OP_SECURE_ERASE:
274 type = VIRTIO_BLK_T_SECURE_ERASE;
275 break;
276 case REQ_OP_ZONE_OPEN:
277 type = VIRTIO_BLK_T_ZONE_OPEN;
278 sector = blk_rq_pos(req);
279 break;
280 case REQ_OP_ZONE_CLOSE:
281 type = VIRTIO_BLK_T_ZONE_CLOSE;
282 sector = blk_rq_pos(req);
283 break;
284 case REQ_OP_ZONE_FINISH:
285 type = VIRTIO_BLK_T_ZONE_FINISH;
286 sector = blk_rq_pos(req);
287 break;
288 case REQ_OP_ZONE_APPEND:
289 type = VIRTIO_BLK_T_ZONE_APPEND;
290 sector = blk_rq_pos(req);
291 in_hdr_len = sizeof(vbr->in_hdr.zone_append);
292 break;
293 case REQ_OP_ZONE_RESET:
294 type = VIRTIO_BLK_T_ZONE_RESET;
295 sector = blk_rq_pos(req);
296 break;
297 case REQ_OP_ZONE_RESET_ALL:
298 type = VIRTIO_BLK_T_ZONE_RESET_ALL;
299 break;
300 case REQ_OP_DRV_IN:
301 /*
302 * Out header has already been prepared by the caller (virtblk_get_id()
303 * or virtblk_submit_zone_report()), nothing to do here.
304 */
305 return 0;
306 default:
307 WARN_ON_ONCE(1);
308 return BLK_STS_IOERR;
309 }
310
311 /* Set fields for non-REQ_OP_DRV_IN request types */
312 vbr->in_hdr_len = in_hdr_len;
313 vbr->out_hdr.type = cpu_to_virtio32(vdev, type);
314 vbr->out_hdr.sector = cpu_to_virtio64(vdev, sector);
315
316 if (type == VIRTIO_BLK_T_DISCARD || type == VIRTIO_BLK_T_WRITE_ZEROES ||
317 type == VIRTIO_BLK_T_SECURE_ERASE) {
318 if (virtblk_setup_discard_write_zeroes_erase(req, unmap))
319 return BLK_STS_RESOURCE;
320 }
321
322 return 0;
323}
324
325/*
326 * The status byte is always the last byte of the virtblk request
327 * in-header. This helper fetches its value for all in-header formats
328 * that are currently defined.
329 */
330static inline u8 virtblk_vbr_status(struct virtblk_req *vbr)
331{
332 return *((u8 *)&vbr->in_hdr + vbr->in_hdr_len - 1);
333}
334
335static inline void virtblk_request_done(struct request *req)
336{
337 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
338 blk_status_t status = virtblk_result(virtblk_vbr_status(vbr));
339 struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
340
341 virtblk_unmap_data(req, vbr);
342 virtblk_cleanup_cmd(req);
343
344 if (req_op(req) == REQ_OP_ZONE_APPEND)
345 req->__sector = virtio64_to_cpu(vblk->vdev,
346 vbr->in_hdr.zone_append.sector);
347
348 blk_mq_end_request(req, status);
349}
350
351static void virtblk_done(struct virtqueue *vq)
352{
353 struct virtio_blk *vblk = vq->vdev->priv;
354 bool req_done = false;
355 int qid = vq->index;
356 struct virtblk_req *vbr;
357 unsigned long flags;
358 unsigned int len;
359
360 spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
361 do {
362 virtqueue_disable_cb(vq);
363 while ((vbr = virtqueue_get_buf(vblk->vqs[qid].vq, &len)) != NULL) {
364 struct request *req = blk_mq_rq_from_pdu(vbr);
365
366 if (likely(!blk_should_fake_timeout(req->q)))
367 blk_mq_complete_request(req);
368 req_done = true;
369 }
370 } while (!virtqueue_enable_cb(vq));
371
372 /* In case queue is stopped waiting for more buffers. */
373 if (req_done)
374 blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
375 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
376}
377
378static void virtio_commit_rqs(struct blk_mq_hw_ctx *hctx)
379{
380 struct virtio_blk *vblk = hctx->queue->queuedata;
381 struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
382 bool kick;
383
384 spin_lock_irq(&vq->lock);
385 kick = virtqueue_kick_prepare(vq->vq);
386 spin_unlock_irq(&vq->lock);
387
388 if (kick)
389 virtqueue_notify(vq->vq);
390}
391
392static blk_status_t virtblk_fail_to_queue(struct request *req, int rc)
393{
394 virtblk_cleanup_cmd(req);
395 switch (rc) {
396 case -ENOSPC:
397 return BLK_STS_DEV_RESOURCE;
398 case -ENOMEM:
399 return BLK_STS_RESOURCE;
400 default:
401 return BLK_STS_IOERR;
402 }
403}
404
405static blk_status_t virtblk_prep_rq(struct blk_mq_hw_ctx *hctx,
406 struct virtio_blk *vblk,
407 struct request *req,
408 struct virtblk_req *vbr)
409{
410 blk_status_t status;
411 int num;
412
413 status = virtblk_setup_cmd(vblk->vdev, req, vbr);
414 if (unlikely(status))
415 return status;
416
417 num = virtblk_map_data(hctx, req, vbr);
418 if (unlikely(num < 0))
419 return virtblk_fail_to_queue(req, -ENOMEM);
420 vbr->sg_table.nents = num;
421
422 blk_mq_start_request(req);
423
424 return BLK_STS_OK;
425}
426
427static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
428 const struct blk_mq_queue_data *bd)
429{
430 struct virtio_blk *vblk = hctx->queue->queuedata;
431 struct request *req = bd->rq;
432 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
433 unsigned long flags;
434 int qid = hctx->queue_num;
435 bool notify = false;
436 blk_status_t status;
437 int err;
438
439 status = virtblk_prep_rq(hctx, vblk, req, vbr);
440 if (unlikely(status))
441 return status;
442
443 spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
444 err = virtblk_add_req(vblk->vqs[qid].vq, vbr);
445 if (err) {
446 virtqueue_kick(vblk->vqs[qid].vq);
447 /* Don't stop the queue if -ENOMEM: we may have failed to
448 * bounce the buffer due to global resource outage.
449 */
450 if (err == -ENOSPC)
451 blk_mq_stop_hw_queue(hctx);
452 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
453 virtblk_unmap_data(req, vbr);
454 return virtblk_fail_to_queue(req, err);
455 }
456
457 if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
458 notify = true;
459 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
460
461 if (notify)
462 virtqueue_notify(vblk->vqs[qid].vq);
463 return BLK_STS_OK;
464}
465
466static bool virtblk_prep_rq_batch(struct request *req)
467{
468 struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
469 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
470
471 return virtblk_prep_rq(req->mq_hctx, vblk, req, vbr) == BLK_STS_OK;
472}
473
474static void virtblk_add_req_batch(struct virtio_blk_vq *vq,
475 struct rq_list *rqlist)
476{
477 struct request *req;
478 unsigned long flags;
479 bool kick;
480
481 spin_lock_irqsave(&vq->lock, flags);
482
483 while ((req = rq_list_pop(rqlist))) {
484 struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
485 int err;
486
487 err = virtblk_add_req(vq->vq, vbr);
488 if (err) {
489 virtblk_unmap_data(req, vbr);
490 virtblk_cleanup_cmd(req);
491 blk_mq_requeue_request(req, true);
492 }
493 }
494
495 kick = virtqueue_kick_prepare(vq->vq);
496 spin_unlock_irqrestore(&vq->lock, flags);
497
498 if (kick)
499 virtqueue_notify(vq->vq);
500}
501
502static void virtio_queue_rqs(struct rq_list *rqlist)
503{
504 struct rq_list submit_list = { };
505 struct rq_list requeue_list = { };
506 struct virtio_blk_vq *vq = NULL;
507 struct request *req;
508
509 while ((req = rq_list_pop(rqlist))) {
510 struct virtio_blk_vq *this_vq = get_virtio_blk_vq(req->mq_hctx);
511
512 if (vq && vq != this_vq)
513 virtblk_add_req_batch(vq, &submit_list);
514 vq = this_vq;
515
516 if (virtblk_prep_rq_batch(req))
517 rq_list_add_tail(&submit_list, req);
518 else
519 rq_list_add_tail(&requeue_list, req);
520 }
521
522 if (vq)
523 virtblk_add_req_batch(vq, &submit_list);
524 *rqlist = requeue_list;
525}
526
527#ifdef CONFIG_BLK_DEV_ZONED
528static void *virtblk_alloc_report_buffer(struct virtio_blk *vblk,
529 unsigned int nr_zones,
530 size_t *buflen)
531{
532 struct request_queue *q = vblk->disk->queue;
533 size_t bufsize;
534 void *buf;
535
536 nr_zones = min_t(unsigned int, nr_zones,
537 get_capacity(vblk->disk) >> ilog2(vblk->zone_sectors));
538
539 bufsize = sizeof(struct virtio_blk_zone_report) +
540 nr_zones * sizeof(struct virtio_blk_zone_descriptor);
541 bufsize = min_t(size_t, bufsize,
542 queue_max_hw_sectors(q) << SECTOR_SHIFT);
543 bufsize = min_t(size_t, bufsize, queue_max_segments(q) << PAGE_SHIFT);
544
545 while (bufsize >= sizeof(struct virtio_blk_zone_report)) {
546 buf = __vmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);
547 if (buf) {
548 *buflen = bufsize;
549 return buf;
550 }
551 bufsize >>= 1;
552 }
553
554 return NULL;
555}
556
557static int virtblk_submit_zone_report(struct virtio_blk *vblk,
558 char *report_buf, size_t report_len,
559 sector_t sector)
560{
561 struct request_queue *q = vblk->disk->queue;
562 struct request *req;
563 struct virtblk_req *vbr;
564 int err;
565
566 req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
567 if (IS_ERR(req))
568 return PTR_ERR(req);
569
570 vbr = blk_mq_rq_to_pdu(req);
571 vbr->in_hdr_len = sizeof(vbr->in_hdr.status);
572 vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_ZONE_REPORT);
573 vbr->out_hdr.sector = cpu_to_virtio64(vblk->vdev, sector);
574
575 err = blk_rq_map_kern(q, req, report_buf, report_len, GFP_KERNEL);
576 if (err)
577 goto out;
578
579 blk_execute_rq(req, false);
580 err = blk_status_to_errno(virtblk_result(vbr->in_hdr.status));
581out:
582 blk_mq_free_request(req);
583 return err;
584}
585
586static int virtblk_parse_zone(struct virtio_blk *vblk,
587 struct virtio_blk_zone_descriptor *entry,
588 unsigned int idx, report_zones_cb cb, void *data)
589{
590 struct blk_zone zone = { };
591
592 zone.start = virtio64_to_cpu(vblk->vdev, entry->z_start);
593 if (zone.start + vblk->zone_sectors <= get_capacity(vblk->disk))
594 zone.len = vblk->zone_sectors;
595 else
596 zone.len = get_capacity(vblk->disk) - zone.start;
597 zone.capacity = virtio64_to_cpu(vblk->vdev, entry->z_cap);
598 zone.wp = virtio64_to_cpu(vblk->vdev, entry->z_wp);
599
600 switch (entry->z_type) {
601 case VIRTIO_BLK_ZT_SWR:
602 zone.type = BLK_ZONE_TYPE_SEQWRITE_REQ;
603 break;
604 case VIRTIO_BLK_ZT_SWP:
605 zone.type = BLK_ZONE_TYPE_SEQWRITE_PREF;
606 break;
607 case VIRTIO_BLK_ZT_CONV:
608 zone.type = BLK_ZONE_TYPE_CONVENTIONAL;
609 break;
610 default:
611 dev_err(&vblk->vdev->dev, "zone %llu: invalid type %#x\n",
612 zone.start, entry->z_type);
613 return -EIO;
614 }
615
616 switch (entry->z_state) {
617 case VIRTIO_BLK_ZS_EMPTY:
618 zone.cond = BLK_ZONE_COND_EMPTY;
619 break;
620 case VIRTIO_BLK_ZS_CLOSED:
621 zone.cond = BLK_ZONE_COND_CLOSED;
622 break;
623 case VIRTIO_BLK_ZS_FULL:
624 zone.cond = BLK_ZONE_COND_FULL;
625 zone.wp = zone.start + zone.len;
626 break;
627 case VIRTIO_BLK_ZS_EOPEN:
628 zone.cond = BLK_ZONE_COND_EXP_OPEN;
629 break;
630 case VIRTIO_BLK_ZS_IOPEN:
631 zone.cond = BLK_ZONE_COND_IMP_OPEN;
632 break;
633 case VIRTIO_BLK_ZS_NOT_WP:
634 zone.cond = BLK_ZONE_COND_NOT_WP;
635 break;
636 case VIRTIO_BLK_ZS_RDONLY:
637 zone.cond = BLK_ZONE_COND_READONLY;
638 zone.wp = ULONG_MAX;
639 break;
640 case VIRTIO_BLK_ZS_OFFLINE:
641 zone.cond = BLK_ZONE_COND_OFFLINE;
642 zone.wp = ULONG_MAX;
643 break;
644 default:
645 dev_err(&vblk->vdev->dev, "zone %llu: invalid condition %#x\n",
646 zone.start, entry->z_state);
647 return -EIO;
648 }
649
650 /*
651 * The callback below checks the validity of the reported
652 * entry data, no need to further validate it here.
653 */
654 return cb(&zone, idx, data);
655}
656
657static int virtblk_report_zones(struct gendisk *disk, sector_t sector,
658 unsigned int nr_zones, report_zones_cb cb,
659 void *data)
660{
661 struct virtio_blk *vblk = disk->private_data;
662 struct virtio_blk_zone_report *report;
663 unsigned long long nz, i;
664 size_t buflen;
665 unsigned int zone_idx = 0;
666 int ret;
667
668 if (WARN_ON_ONCE(!vblk->zone_sectors))
669 return -EOPNOTSUPP;
670
671 report = virtblk_alloc_report_buffer(vblk, nr_zones, &buflen);
672 if (!report)
673 return -ENOMEM;
674
675 mutex_lock(&vblk->vdev_mutex);
676
677 if (!vblk->vdev) {
678 ret = -ENXIO;
679 goto fail_report;
680 }
681
682 while (zone_idx < nr_zones && sector < get_capacity(vblk->disk)) {
683 memset(report, 0, buflen);
684
685 ret = virtblk_submit_zone_report(vblk, (char *)report,
686 buflen, sector);
687 if (ret)
688 goto fail_report;
689
690 nz = min_t(u64, virtio64_to_cpu(vblk->vdev, report->nr_zones),
691 nr_zones);
692 if (!nz)
693 break;
694
695 for (i = 0; i < nz && zone_idx < nr_zones; i++) {
696 ret = virtblk_parse_zone(vblk, &report->zones[i],
697 zone_idx, cb, data);
698 if (ret)
699 goto fail_report;
700
701 sector = virtio64_to_cpu(vblk->vdev,
702 report->zones[i].z_start) +
703 vblk->zone_sectors;
704 zone_idx++;
705 }
706 }
707
708 if (zone_idx > 0)
709 ret = zone_idx;
710 else
711 ret = -EINVAL;
712fail_report:
713 mutex_unlock(&vblk->vdev_mutex);
714 kvfree(report);
715 return ret;
716}
717
718static int virtblk_read_zoned_limits(struct virtio_blk *vblk,
719 struct queue_limits *lim)
720{
721 struct virtio_device *vdev = vblk->vdev;
722 u32 v, wg;
723
724 dev_dbg(&vdev->dev, "probing host-managed zoned device\n");
725
726 lim->features |= BLK_FEAT_ZONED;
727
728 virtio_cread(vdev, struct virtio_blk_config,
729 zoned.max_open_zones, &v);
730 lim->max_open_zones = v;
731 dev_dbg(&vdev->dev, "max open zones = %u\n", v);
732
733 virtio_cread(vdev, struct virtio_blk_config,
734 zoned.max_active_zones, &v);
735 lim->max_active_zones = v;
736 dev_dbg(&vdev->dev, "max active zones = %u\n", v);
737
738 virtio_cread(vdev, struct virtio_blk_config,
739 zoned.write_granularity, &wg);
740 if (!wg) {
741 dev_warn(&vdev->dev, "zero write granularity reported\n");
742 return -ENODEV;
743 }
744 lim->physical_block_size = wg;
745 lim->io_min = wg;
746
747 dev_dbg(&vdev->dev, "write granularity = %u\n", wg);
748
749 /*
750 * virtio ZBD specification doesn't require zones to be a power of
751 * two sectors in size, but the code in this driver expects that.
752 */
753 virtio_cread(vdev, struct virtio_blk_config, zoned.zone_sectors,
754 &vblk->zone_sectors);
755 if (vblk->zone_sectors == 0 || !is_power_of_2(vblk->zone_sectors)) {
756 dev_err(&vdev->dev,
757 "zoned device with non power of two zone size %u\n",
758 vblk->zone_sectors);
759 return -ENODEV;
760 }
761 lim->chunk_sectors = vblk->zone_sectors;
762 dev_dbg(&vdev->dev, "zone sectors = %u\n", vblk->zone_sectors);
763
764 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
765 dev_warn(&vblk->vdev->dev,
766 "ignoring negotiated F_DISCARD for zoned device\n");
767 lim->max_hw_discard_sectors = 0;
768 }
769
770 virtio_cread(vdev, struct virtio_blk_config,
771 zoned.max_append_sectors, &v);
772 if (!v) {
773 dev_warn(&vdev->dev, "zero max_append_sectors reported\n");
774 return -ENODEV;
775 }
776 if ((v << SECTOR_SHIFT) < wg) {
777 dev_err(&vdev->dev,
778 "write granularity %u exceeds max_append_sectors %u limit\n",
779 wg, v);
780 return -ENODEV;
781 }
782 lim->max_hw_zone_append_sectors = v;
783 dev_dbg(&vdev->dev, "max append sectors = %u\n", v);
784
785 return 0;
786}
787#else
788/*
789 * Zoned block device support is not configured in this kernel, host-managed
790 * zoned devices can't be supported.
791 */
792#define virtblk_report_zones NULL
793static inline int virtblk_read_zoned_limits(struct virtio_blk *vblk,
794 struct queue_limits *lim)
795{
796 dev_err(&vblk->vdev->dev,
797 "virtio_blk: zoned devices are not supported");
798 return -EOPNOTSUPP;
799}
800#endif /* CONFIG_BLK_DEV_ZONED */
801
802/* return id (s/n) string for *disk to *id_str
803 */
804static int virtblk_get_id(struct gendisk *disk, char *id_str)
805{
806 struct virtio_blk *vblk = disk->private_data;
807 struct request_queue *q = vblk->disk->queue;
808 struct request *req;
809 struct virtblk_req *vbr;
810 int err;
811
812 req = blk_mq_alloc_request(q, REQ_OP_DRV_IN, 0);
813 if (IS_ERR(req))
814 return PTR_ERR(req);
815
816 vbr = blk_mq_rq_to_pdu(req);
817 vbr->in_hdr_len = sizeof(vbr->in_hdr.status);
818 vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_GET_ID);
819 vbr->out_hdr.sector = 0;
820
821 err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
822 if (err)
823 goto out;
824
825 blk_execute_rq(req, false);
826 err = blk_status_to_errno(virtblk_result(vbr->in_hdr.status));
827out:
828 blk_mq_free_request(req);
829 return err;
830}
831
832/* We provide getgeo only to please some old bootloader/partitioning tools */
833static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
834{
835 struct virtio_blk *vblk = bd->bd_disk->private_data;
836 int ret = 0;
837
838 mutex_lock(&vblk->vdev_mutex);
839
840 if (!vblk->vdev) {
841 ret = -ENXIO;
842 goto out;
843 }
844
845 /* see if the host passed in geometry config */
846 if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
847 virtio_cread(vblk->vdev, struct virtio_blk_config,
848 geometry.cylinders, &geo->cylinders);
849 virtio_cread(vblk->vdev, struct virtio_blk_config,
850 geometry.heads, &geo->heads);
851 virtio_cread(vblk->vdev, struct virtio_blk_config,
852 geometry.sectors, &geo->sectors);
853 } else {
854 /* some standard values, similar to sd */
855 geo->heads = 1 << 6;
856 geo->sectors = 1 << 5;
857 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
858 }
859out:
860 mutex_unlock(&vblk->vdev_mutex);
861 return ret;
862}
863
864static void virtblk_free_disk(struct gendisk *disk)
865{
866 struct virtio_blk *vblk = disk->private_data;
867
868 ida_free(&vd_index_ida, vblk->index);
869 mutex_destroy(&vblk->vdev_mutex);
870 kfree(vblk);
871}
872
873static const struct block_device_operations virtblk_fops = {
874 .owner = THIS_MODULE,
875 .getgeo = virtblk_getgeo,
876 .free_disk = virtblk_free_disk,
877 .report_zones = virtblk_report_zones,
878};
879
880static int index_to_minor(int index)
881{
882 return index << PART_BITS;
883}
884
885static int minor_to_index(int minor)
886{
887 return minor >> PART_BITS;
888}
889
890static ssize_t serial_show(struct device *dev,
891 struct device_attribute *attr, char *buf)
892{
893 struct gendisk *disk = dev_to_disk(dev);
894 int err;
895
896 /* sysfs gives us a PAGE_SIZE buffer */
897 BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
898
899 buf[VIRTIO_BLK_ID_BYTES] = '\0';
900 err = virtblk_get_id(disk, buf);
901 if (!err)
902 return strlen(buf);
903
904 if (err == -EIO) /* Unsupported? Make it empty. */
905 return 0;
906
907 return err;
908}
909
910static DEVICE_ATTR_RO(serial);
911
912/* The queue's logical block size must be set before calling this */
913static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
914{
915 struct virtio_device *vdev = vblk->vdev;
916 struct request_queue *q = vblk->disk->queue;
917 char cap_str_2[10], cap_str_10[10];
918 unsigned long long nblocks;
919 u64 capacity;
920
921 /* Host must always specify the capacity. */
922 virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
923
924 nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
925
926 string_get_size(nblocks, queue_logical_block_size(q),
927 STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
928 string_get_size(nblocks, queue_logical_block_size(q),
929 STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
930
931 dev_notice(&vdev->dev,
932 "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
933 vblk->disk->disk_name,
934 resize ? "new size: " : "",
935 nblocks,
936 queue_logical_block_size(q),
937 cap_str_10,
938 cap_str_2);
939
940 set_capacity_and_notify(vblk->disk, capacity);
941}
942
943static void virtblk_config_changed_work(struct work_struct *work)
944{
945 struct virtio_blk *vblk =
946 container_of(work, struct virtio_blk, config_work);
947
948 virtblk_update_capacity(vblk, true);
949}
950
951static void virtblk_config_changed(struct virtio_device *vdev)
952{
953 struct virtio_blk *vblk = vdev->priv;
954
955 queue_work(virtblk_wq, &vblk->config_work);
956}
957
958static int init_vq(struct virtio_blk *vblk)
959{
960 int err;
961 unsigned short i;
962 struct virtqueue_info *vqs_info;
963 struct virtqueue **vqs;
964 unsigned short num_vqs;
965 unsigned short num_poll_vqs;
966 struct virtio_device *vdev = vblk->vdev;
967 struct irq_affinity desc = { 0, };
968
969 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
970 struct virtio_blk_config, num_queues,
971 &num_vqs);
972 if (err)
973 num_vqs = 1;
974
975 if (!err && !num_vqs) {
976 dev_err(&vdev->dev, "MQ advertised but zero queues reported\n");
977 return -EINVAL;
978 }
979
980 num_vqs = min_t(unsigned int,
981 min_not_zero(num_request_queues, nr_cpu_ids),
982 num_vqs);
983
984 num_poll_vqs = min_t(unsigned int, poll_queues, num_vqs - 1);
985
986 vblk->io_queues[HCTX_TYPE_DEFAULT] = num_vqs - num_poll_vqs;
987 vblk->io_queues[HCTX_TYPE_READ] = 0;
988 vblk->io_queues[HCTX_TYPE_POLL] = num_poll_vqs;
989
990 dev_info(&vdev->dev, "%d/%d/%d default/read/poll queues\n",
991 vblk->io_queues[HCTX_TYPE_DEFAULT],
992 vblk->io_queues[HCTX_TYPE_READ],
993 vblk->io_queues[HCTX_TYPE_POLL]);
994
995 vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
996 if (!vblk->vqs)
997 return -ENOMEM;
998
999 vqs_info = kcalloc(num_vqs, sizeof(*vqs_info), GFP_KERNEL);
1000 vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
1001 if (!vqs_info || !vqs) {
1002 err = -ENOMEM;
1003 goto out;
1004 }
1005
1006 for (i = 0; i < num_vqs - num_poll_vqs; i++) {
1007 vqs_info[i].callback = virtblk_done;
1008 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%u", i);
1009 vqs_info[i].name = vblk->vqs[i].name;
1010 }
1011
1012 for (; i < num_vqs; i++) {
1013 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req_poll.%u", i);
1014 vqs_info[i].name = vblk->vqs[i].name;
1015 }
1016
1017 /* Discover virtqueues and write information to configuration. */
1018 err = virtio_find_vqs(vdev, num_vqs, vqs, vqs_info, &desc);
1019 if (err)
1020 goto out;
1021
1022 for (i = 0; i < num_vqs; i++) {
1023 spin_lock_init(&vblk->vqs[i].lock);
1024 vblk->vqs[i].vq = vqs[i];
1025 }
1026 vblk->num_vqs = num_vqs;
1027
1028out:
1029 kfree(vqs);
1030 kfree(vqs_info);
1031 if (err)
1032 kfree(vblk->vqs);
1033 return err;
1034}
1035
1036/*
1037 * Legacy naming scheme used for virtio devices. We are stuck with it for
1038 * virtio blk but don't ever use it for any new driver.
1039 */
1040static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
1041{
1042 const int base = 'z' - 'a' + 1;
1043 char *begin = buf + strlen(prefix);
1044 char *end = buf + buflen;
1045 char *p;
1046 int unit;
1047
1048 p = end - 1;
1049 *p = '\0';
1050 unit = base;
1051 do {
1052 if (p == begin)
1053 return -EINVAL;
1054 *--p = 'a' + (index % unit);
1055 index = (index / unit) - 1;
1056 } while (index >= 0);
1057
1058 memmove(begin, p, end - p);
1059 memcpy(buf, prefix, strlen(prefix));
1060
1061 return 0;
1062}
1063
1064static int virtblk_get_cache_mode(struct virtio_device *vdev)
1065{
1066 u8 writeback;
1067 int err;
1068
1069 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
1070 struct virtio_blk_config, wce,
1071 &writeback);
1072
1073 /*
1074 * If WCE is not configurable and flush is not available,
1075 * assume no writeback cache is in use.
1076 */
1077 if (err)
1078 writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
1079
1080 return writeback;
1081}
1082
1083static const char *const virtblk_cache_types[] = {
1084 "write through", "write back"
1085};
1086
1087static ssize_t
1088cache_type_store(struct device *dev, struct device_attribute *attr,
1089 const char *buf, size_t count)
1090{
1091 struct gendisk *disk = dev_to_disk(dev);
1092 struct virtio_blk *vblk = disk->private_data;
1093 struct virtio_device *vdev = vblk->vdev;
1094 struct queue_limits lim;
1095 int i;
1096
1097 BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
1098 i = sysfs_match_string(virtblk_cache_types, buf);
1099 if (i < 0)
1100 return i;
1101
1102 virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
1103
1104 lim = queue_limits_start_update(disk->queue);
1105 if (virtblk_get_cache_mode(vdev))
1106 lim.features |= BLK_FEAT_WRITE_CACHE;
1107 else
1108 lim.features &= ~BLK_FEAT_WRITE_CACHE;
1109 i = queue_limits_commit_update_frozen(disk->queue, &lim);
1110 if (i)
1111 return i;
1112 return count;
1113}
1114
1115static ssize_t
1116cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
1117{
1118 struct gendisk *disk = dev_to_disk(dev);
1119 struct virtio_blk *vblk = disk->private_data;
1120 u8 writeback = virtblk_get_cache_mode(vblk->vdev);
1121
1122 BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
1123 return sysfs_emit(buf, "%s\n", virtblk_cache_types[writeback]);
1124}
1125
1126static DEVICE_ATTR_RW(cache_type);
1127
1128static struct attribute *virtblk_attrs[] = {
1129 &dev_attr_serial.attr,
1130 &dev_attr_cache_type.attr,
1131 NULL,
1132};
1133
1134static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
1135 struct attribute *a, int n)
1136{
1137 struct device *dev = kobj_to_dev(kobj);
1138 struct gendisk *disk = dev_to_disk(dev);
1139 struct virtio_blk *vblk = disk->private_data;
1140 struct virtio_device *vdev = vblk->vdev;
1141
1142 if (a == &dev_attr_cache_type.attr &&
1143 !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
1144 return S_IRUGO;
1145
1146 return a->mode;
1147}
1148
1149static const struct attribute_group virtblk_attr_group = {
1150 .attrs = virtblk_attrs,
1151 .is_visible = virtblk_attrs_are_visible,
1152};
1153
1154static const struct attribute_group *virtblk_attr_groups[] = {
1155 &virtblk_attr_group,
1156 NULL,
1157};
1158
1159static void virtblk_map_queues(struct blk_mq_tag_set *set)
1160{
1161 struct virtio_blk *vblk = set->driver_data;
1162 int i, qoff;
1163
1164 for (i = 0, qoff = 0; i < set->nr_maps; i++) {
1165 struct blk_mq_queue_map *map = &set->map[i];
1166
1167 map->nr_queues = vblk->io_queues[i];
1168 map->queue_offset = qoff;
1169 qoff += map->nr_queues;
1170
1171 if (map->nr_queues == 0)
1172 continue;
1173
1174 /*
1175 * Regular queues have interrupts and hence CPU affinity is
1176 * defined by the core virtio code, but polling queues have
1177 * no interrupts so we let the block layer assign CPU affinity.
1178 */
1179 if (i == HCTX_TYPE_POLL)
1180 blk_mq_map_queues(&set->map[i]);
1181 else
1182 blk_mq_virtio_map_queues(&set->map[i], vblk->vdev, 0);
1183 }
1184}
1185
1186static void virtblk_complete_batch(struct io_comp_batch *iob)
1187{
1188 struct request *req;
1189
1190 rq_list_for_each(&iob->req_list, req) {
1191 virtblk_unmap_data(req, blk_mq_rq_to_pdu(req));
1192 virtblk_cleanup_cmd(req);
1193 }
1194 blk_mq_end_request_batch(iob);
1195}
1196
1197static int virtblk_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
1198{
1199 struct virtio_blk *vblk = hctx->queue->queuedata;
1200 struct virtio_blk_vq *vq = get_virtio_blk_vq(hctx);
1201 struct virtblk_req *vbr;
1202 unsigned long flags;
1203 unsigned int len;
1204 int found = 0;
1205
1206 spin_lock_irqsave(&vq->lock, flags);
1207
1208 while ((vbr = virtqueue_get_buf(vq->vq, &len)) != NULL) {
1209 struct request *req = blk_mq_rq_from_pdu(vbr);
1210
1211 found++;
1212 if (!blk_mq_complete_request_remote(req) &&
1213 !blk_mq_add_to_batch(req, iob, virtblk_vbr_status(vbr),
1214 virtblk_complete_batch))
1215 virtblk_request_done(req);
1216 }
1217
1218 if (found)
1219 blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
1220
1221 spin_unlock_irqrestore(&vq->lock, flags);
1222
1223 return found;
1224}
1225
1226static const struct blk_mq_ops virtio_mq_ops = {
1227 .queue_rq = virtio_queue_rq,
1228 .queue_rqs = virtio_queue_rqs,
1229 .commit_rqs = virtio_commit_rqs,
1230 .complete = virtblk_request_done,
1231 .map_queues = virtblk_map_queues,
1232 .poll = virtblk_poll,
1233};
1234
1235static unsigned int virtblk_queue_depth;
1236module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
1237
1238static int virtblk_read_limits(struct virtio_blk *vblk,
1239 struct queue_limits *lim)
1240{
1241 struct virtio_device *vdev = vblk->vdev;
1242 u32 v, max_size, sg_elems, opt_io_size;
1243 u32 max_discard_segs = 0;
1244 u32 discard_granularity = 0;
1245 u16 min_io_size;
1246 u8 physical_block_exp, alignment_offset;
1247 size_t max_dma_size;
1248 int err;
1249
1250 /* We need to know how many segments before we allocate. */
1251 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
1252 struct virtio_blk_config, seg_max,
1253 &sg_elems);
1254
1255 /* We need at least one SG element, whatever they say. */
1256 if (err || !sg_elems)
1257 sg_elems = 1;
1258
1259 /* Prevent integer overflows and honor max vq size */
1260 sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2);
1261
1262 /* We can handle whatever the host told us to handle. */
1263 lim->max_segments = sg_elems;
1264
1265 /* No real sector limit. */
1266 lim->max_hw_sectors = UINT_MAX;
1267
1268 max_dma_size = virtio_max_dma_size(vdev);
1269 max_size = max_dma_size > U32_MAX ? U32_MAX : max_dma_size;
1270
1271 /* Host can optionally specify maximum segment size and number of
1272 * segments. */
1273 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
1274 struct virtio_blk_config, size_max, &v);
1275 if (!err)
1276 max_size = min(max_size, v);
1277
1278 lim->max_segment_size = max_size;
1279
1280 /* Host can optionally specify the block size of the device */
1281 virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
1282 struct virtio_blk_config, blk_size,
1283 &lim->logical_block_size);
1284
1285 /* Use topology information if available */
1286 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1287 struct virtio_blk_config, physical_block_exp,
1288 &physical_block_exp);
1289 if (!err && physical_block_exp)
1290 lim->physical_block_size =
1291 lim->logical_block_size * (1 << physical_block_exp);
1292
1293 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1294 struct virtio_blk_config, alignment_offset,
1295 &alignment_offset);
1296 if (!err && alignment_offset)
1297 lim->alignment_offset =
1298 lim->logical_block_size * alignment_offset;
1299
1300 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1301 struct virtio_blk_config, min_io_size,
1302 &min_io_size);
1303 if (!err && min_io_size)
1304 lim->io_min = lim->logical_block_size * min_io_size;
1305
1306 err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
1307 struct virtio_blk_config, opt_io_size,
1308 &opt_io_size);
1309 if (!err && opt_io_size)
1310 lim->io_opt = lim->logical_block_size * opt_io_size;
1311
1312 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
1313 virtio_cread(vdev, struct virtio_blk_config,
1314 discard_sector_alignment, &discard_granularity);
1315
1316 virtio_cread(vdev, struct virtio_blk_config,
1317 max_discard_sectors, &v);
1318 lim->max_hw_discard_sectors = v ? v : UINT_MAX;
1319
1320 virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
1321 &max_discard_segs);
1322 }
1323
1324 if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
1325 virtio_cread(vdev, struct virtio_blk_config,
1326 max_write_zeroes_sectors, &v);
1327 lim->max_write_zeroes_sectors = v ? v : UINT_MAX;
1328 }
1329
1330 /* The discard and secure erase limits are combined since the Linux
1331 * block layer uses the same limit for both commands.
1332 *
1333 * If both VIRTIO_BLK_F_SECURE_ERASE and VIRTIO_BLK_F_DISCARD features
1334 * are negotiated, we will use the minimum between the limits.
1335 *
1336 * discard sector alignment is set to the minimum between discard_sector_alignment
1337 * and secure_erase_sector_alignment.
1338 *
1339 * max discard sectors is set to the minimum between max_discard_seg and
1340 * max_secure_erase_seg.
1341 */
1342 if (virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1343
1344 virtio_cread(vdev, struct virtio_blk_config,
1345 secure_erase_sector_alignment, &v);
1346
1347 /* secure_erase_sector_alignment should not be zero, the device should set a
1348 * valid number of sectors.
1349 */
1350 if (!v) {
1351 dev_err(&vdev->dev,
1352 "virtio_blk: secure_erase_sector_alignment can't be 0\n");
1353 return -EINVAL;
1354 }
1355
1356 discard_granularity = min_not_zero(discard_granularity, v);
1357
1358 virtio_cread(vdev, struct virtio_blk_config,
1359 max_secure_erase_sectors, &v);
1360
1361 /* max_secure_erase_sectors should not be zero, the device should set a
1362 * valid number of sectors.
1363 */
1364 if (!v) {
1365 dev_err(&vdev->dev,
1366 "virtio_blk: max_secure_erase_sectors can't be 0\n");
1367 return -EINVAL;
1368 }
1369
1370 lim->max_secure_erase_sectors = v;
1371
1372 virtio_cread(vdev, struct virtio_blk_config,
1373 max_secure_erase_seg, &v);
1374
1375 /* max_secure_erase_seg should not be zero, the device should set a
1376 * valid number of segments
1377 */
1378 if (!v) {
1379 dev_err(&vdev->dev,
1380 "virtio_blk: max_secure_erase_seg can't be 0\n");
1381 return -EINVAL;
1382 }
1383
1384 max_discard_segs = min_not_zero(max_discard_segs, v);
1385 }
1386
1387 if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD) ||
1388 virtio_has_feature(vdev, VIRTIO_BLK_F_SECURE_ERASE)) {
1389 /* max_discard_seg and discard_granularity will be 0 only
1390 * if max_discard_seg and discard_sector_alignment fields in the virtio
1391 * config are 0 and VIRTIO_BLK_F_SECURE_ERASE feature is not negotiated.
1392 * In this case, we use default values.
1393 */
1394 if (!max_discard_segs)
1395 max_discard_segs = sg_elems;
1396
1397 lim->max_discard_segments =
1398 min(max_discard_segs, MAX_DISCARD_SEGMENTS);
1399
1400 if (discard_granularity)
1401 lim->discard_granularity =
1402 discard_granularity << SECTOR_SHIFT;
1403 else
1404 lim->discard_granularity = lim->logical_block_size;
1405 }
1406
1407 if (virtio_has_feature(vdev, VIRTIO_BLK_F_ZONED)) {
1408 u8 model;
1409
1410 virtio_cread(vdev, struct virtio_blk_config, zoned.model, &model);
1411 switch (model) {
1412 case VIRTIO_BLK_Z_NONE:
1413 case VIRTIO_BLK_Z_HA:
1414 /* treat host-aware devices as non-zoned */
1415 return 0;
1416 case VIRTIO_BLK_Z_HM:
1417 err = virtblk_read_zoned_limits(vblk, lim);
1418 if (err)
1419 return err;
1420 break;
1421 default:
1422 dev_err(&vdev->dev, "unsupported zone model %d\n", model);
1423 return -EINVAL;
1424 }
1425 }
1426
1427 return 0;
1428}
1429
1430static int virtblk_probe(struct virtio_device *vdev)
1431{
1432 struct virtio_blk *vblk;
1433 struct queue_limits lim = {
1434 .features = BLK_FEAT_ROTATIONAL,
1435 .logical_block_size = SECTOR_SIZE,
1436 };
1437 int err, index;
1438 unsigned int queue_depth;
1439
1440 if (!vdev->config->get) {
1441 dev_err(&vdev->dev, "%s failure: config access disabled\n",
1442 __func__);
1443 return -EINVAL;
1444 }
1445
1446 err = ida_alloc_range(&vd_index_ida, 0,
1447 minor_to_index(1 << MINORBITS) - 1, GFP_KERNEL);
1448 if (err < 0)
1449 goto out;
1450 index = err;
1451
1452 vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
1453 if (!vblk) {
1454 err = -ENOMEM;
1455 goto out_free_index;
1456 }
1457
1458 mutex_init(&vblk->vdev_mutex);
1459
1460 vblk->vdev = vdev;
1461
1462 INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
1463
1464 err = init_vq(vblk);
1465 if (err)
1466 goto out_free_vblk;
1467
1468 /* Default queue sizing is to fill the ring. */
1469 if (!virtblk_queue_depth) {
1470 queue_depth = vblk->vqs[0].vq->num_free;
1471 /* ... but without indirect descs, we use 2 descs per req */
1472 if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
1473 queue_depth /= 2;
1474 } else {
1475 queue_depth = virtblk_queue_depth;
1476 }
1477
1478 memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
1479 vblk->tag_set.ops = &virtio_mq_ops;
1480 vblk->tag_set.queue_depth = queue_depth;
1481 vblk->tag_set.numa_node = NUMA_NO_NODE;
1482 vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1483 vblk->tag_set.cmd_size =
1484 sizeof(struct virtblk_req) +
1485 sizeof(struct scatterlist) * VIRTIO_BLK_INLINE_SG_CNT;
1486 vblk->tag_set.driver_data = vblk;
1487 vblk->tag_set.nr_hw_queues = vblk->num_vqs;
1488 vblk->tag_set.nr_maps = 1;
1489 if (vblk->io_queues[HCTX_TYPE_POLL])
1490 vblk->tag_set.nr_maps = 3;
1491
1492 err = blk_mq_alloc_tag_set(&vblk->tag_set);
1493 if (err)
1494 goto out_free_vq;
1495
1496 err = virtblk_read_limits(vblk, &lim);
1497 if (err)
1498 goto out_free_tags;
1499
1500 if (virtblk_get_cache_mode(vdev))
1501 lim.features |= BLK_FEAT_WRITE_CACHE;
1502
1503 vblk->disk = blk_mq_alloc_disk(&vblk->tag_set, &lim, vblk);
1504 if (IS_ERR(vblk->disk)) {
1505 err = PTR_ERR(vblk->disk);
1506 goto out_free_tags;
1507 }
1508
1509 virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
1510
1511 vblk->disk->major = major;
1512 vblk->disk->first_minor = index_to_minor(index);
1513 vblk->disk->minors = 1 << PART_BITS;
1514 vblk->disk->private_data = vblk;
1515 vblk->disk->fops = &virtblk_fops;
1516 vblk->index = index;
1517
1518 /* If disk is read-only in the host, the guest should obey */
1519 if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
1520 set_disk_ro(vblk->disk, 1);
1521
1522 virtblk_update_capacity(vblk, false);
1523 virtio_device_ready(vdev);
1524
1525 /*
1526 * All steps that follow use the VQs therefore they need to be
1527 * placed after the virtio_device_ready() call above.
1528 */
1529 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
1530 (lim.features & BLK_FEAT_ZONED)) {
1531 err = blk_revalidate_disk_zones(vblk->disk);
1532 if (err)
1533 goto out_cleanup_disk;
1534 }
1535
1536 err = device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
1537 if (err)
1538 goto out_cleanup_disk;
1539
1540 return 0;
1541
1542out_cleanup_disk:
1543 put_disk(vblk->disk);
1544out_free_tags:
1545 blk_mq_free_tag_set(&vblk->tag_set);
1546out_free_vq:
1547 vdev->config->del_vqs(vdev);
1548 kfree(vblk->vqs);
1549out_free_vblk:
1550 kfree(vblk);
1551out_free_index:
1552 ida_free(&vd_index_ida, index);
1553out:
1554 return err;
1555}
1556
1557static void virtblk_remove(struct virtio_device *vdev)
1558{
1559 struct virtio_blk *vblk = vdev->priv;
1560
1561 /* Make sure no work handler is accessing the device. */
1562 flush_work(&vblk->config_work);
1563
1564 del_gendisk(vblk->disk);
1565 blk_mq_free_tag_set(&vblk->tag_set);
1566
1567 mutex_lock(&vblk->vdev_mutex);
1568
1569 /* Stop all the virtqueues. */
1570 virtio_reset_device(vdev);
1571
1572 /* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
1573 vblk->vdev = NULL;
1574
1575 vdev->config->del_vqs(vdev);
1576 kfree(vblk->vqs);
1577
1578 mutex_unlock(&vblk->vdev_mutex);
1579
1580 put_disk(vblk->disk);
1581}
1582
1583#ifdef CONFIG_PM_SLEEP
1584static int virtblk_freeze(struct virtio_device *vdev)
1585{
1586 struct virtio_blk *vblk = vdev->priv;
1587 struct request_queue *q = vblk->disk->queue;
1588
1589 /* Ensure no requests in virtqueues before deleting vqs. */
1590 blk_mq_freeze_queue(q);
1591 blk_mq_quiesce_queue_nowait(q);
1592 blk_mq_unfreeze_queue(q);
1593
1594 /* Ensure we don't receive any more interrupts */
1595 virtio_reset_device(vdev);
1596
1597 /* Make sure no work handler is accessing the device. */
1598 flush_work(&vblk->config_work);
1599
1600 vdev->config->del_vqs(vdev);
1601 kfree(vblk->vqs);
1602
1603 return 0;
1604}
1605
1606static int virtblk_restore(struct virtio_device *vdev)
1607{
1608 struct virtio_blk *vblk = vdev->priv;
1609 int ret;
1610
1611 ret = init_vq(vdev->priv);
1612 if (ret)
1613 return ret;
1614
1615 virtio_device_ready(vdev);
1616 blk_mq_unquiesce_queue(vblk->disk->queue);
1617
1618 return 0;
1619}
1620#endif
1621
1622static const struct virtio_device_id id_table[] = {
1623 { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
1624 { 0 },
1625};
1626
1627static unsigned int features_legacy[] = {
1628 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1629 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1630 VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1631 VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1632 VIRTIO_BLK_F_SECURE_ERASE,
1633}
1634;
1635static unsigned int features[] = {
1636 VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1637 VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1638 VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1639 VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1640 VIRTIO_BLK_F_SECURE_ERASE, VIRTIO_BLK_F_ZONED,
1641};
1642
1643static struct virtio_driver virtio_blk = {
1644 .feature_table = features,
1645 .feature_table_size = ARRAY_SIZE(features),
1646 .feature_table_legacy = features_legacy,
1647 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
1648 .driver.name = KBUILD_MODNAME,
1649 .id_table = id_table,
1650 .probe = virtblk_probe,
1651 .remove = virtblk_remove,
1652 .config_changed = virtblk_config_changed,
1653#ifdef CONFIG_PM_SLEEP
1654 .freeze = virtblk_freeze,
1655 .restore = virtblk_restore,
1656#endif
1657};
1658
1659static int __init virtio_blk_init(void)
1660{
1661 int error;
1662
1663 virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1664 if (!virtblk_wq)
1665 return -ENOMEM;
1666
1667 major = register_blkdev(0, "virtblk");
1668 if (major < 0) {
1669 error = major;
1670 goto out_destroy_workqueue;
1671 }
1672
1673 error = register_virtio_driver(&virtio_blk);
1674 if (error)
1675 goto out_unregister_blkdev;
1676 return 0;
1677
1678out_unregister_blkdev:
1679 unregister_blkdev(major, "virtblk");
1680out_destroy_workqueue:
1681 destroy_workqueue(virtblk_wq);
1682 return error;
1683}
1684
1685static void __exit virtio_blk_fini(void)
1686{
1687 unregister_virtio_driver(&virtio_blk);
1688 unregister_blkdev(major, "virtblk");
1689 destroy_workqueue(virtblk_wq);
1690}
1691module_init(virtio_blk_init);
1692module_exit(virtio_blk_fini);
1693
1694MODULE_DEVICE_TABLE(virtio, id_table);
1695MODULE_DESCRIPTION("Virtio block driver");
1696MODULE_LICENSE("GPL");