GNU Linux-libre 5.4.241-gnu1
[releases.git] / drivers / block / virtio_blk.c
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 <scsi/scsi_cmnd.h>
15 #include <linux/idr.h>
16 #include <linux/blk-mq.h>
17 #include <linux/blk-mq-virtio.h>
18 #include <linux/numa.h>
19
20 #define PART_BITS 4
21 #define VQ_NAME_LEN 16
22 #define MAX_DISCARD_SEGMENTS 256u
23
24 static int major;
25 static DEFINE_IDA(vd_index_ida);
26
27 static struct workqueue_struct *virtblk_wq;
28
29 struct virtio_blk_vq {
30         struct virtqueue *vq;
31         spinlock_t lock;
32         char name[VQ_NAME_LEN];
33 } ____cacheline_aligned_in_smp;
34
35 struct virtio_blk {
36         /*
37          * This mutex must be held by anything that may run after
38          * virtblk_remove() sets vblk->vdev to NULL.
39          *
40          * blk-mq, virtqueue processing, and sysfs attribute code paths are
41          * shut down before vblk->vdev is set to NULL and therefore do not need
42          * to hold this mutex.
43          */
44         struct mutex vdev_mutex;
45         struct virtio_device *vdev;
46
47         /* The disk structure for the kernel. */
48         struct gendisk *disk;
49
50         /* Block layer tags. */
51         struct blk_mq_tag_set tag_set;
52
53         /* Process context for config space updates */
54         struct work_struct config_work;
55
56         /*
57          * Tracks references from block_device_operations open/release and
58          * virtio_driver probe/remove so this object can be freed once no
59          * longer in use.
60          */
61         refcount_t refs;
62
63         /* What host tells us, plus 2 for header & tailer. */
64         unsigned int sg_elems;
65
66         /* Ida index - used to track minor number allocations. */
67         int index;
68
69         /* num of vqs */
70         int num_vqs;
71         struct virtio_blk_vq *vqs;
72 };
73
74 struct virtblk_req {
75 #ifdef CONFIG_VIRTIO_BLK_SCSI
76         struct scsi_request sreq;       /* for SCSI passthrough, must be first */
77         u8 sense[SCSI_SENSE_BUFFERSIZE];
78         struct virtio_scsi_inhdr in_hdr;
79 #endif
80         struct virtio_blk_outhdr out_hdr;
81         u8 status;
82         struct scatterlist sg[];
83 };
84
85 static inline blk_status_t virtblk_result(struct virtblk_req *vbr)
86 {
87         switch (vbr->status) {
88         case VIRTIO_BLK_S_OK:
89                 return BLK_STS_OK;
90         case VIRTIO_BLK_S_UNSUPP:
91                 return BLK_STS_NOTSUPP;
92         default:
93                 return BLK_STS_IOERR;
94         }
95 }
96
97 /*
98  * If this is a packet command we need a couple of additional headers.  Behind
99  * the normal outhdr we put a segment with the scsi command block, and before
100  * the normal inhdr we put the sense data and the inhdr with additional status
101  * information.
102  */
103 #ifdef CONFIG_VIRTIO_BLK_SCSI
104 static int virtblk_add_req_scsi(struct virtqueue *vq, struct virtblk_req *vbr,
105                 struct scatterlist *data_sg, bool have_data)
106 {
107         struct scatterlist hdr, status, cmd, sense, inhdr, *sgs[6];
108         unsigned int num_out = 0, num_in = 0;
109
110         sg_init_one(&hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
111         sgs[num_out++] = &hdr;
112         sg_init_one(&cmd, vbr->sreq.cmd, vbr->sreq.cmd_len);
113         sgs[num_out++] = &cmd;
114
115         if (have_data) {
116                 if (vbr->out_hdr.type & cpu_to_virtio32(vq->vdev, VIRTIO_BLK_T_OUT))
117                         sgs[num_out++] = data_sg;
118                 else
119                         sgs[num_out + num_in++] = data_sg;
120         }
121
122         sg_init_one(&sense, vbr->sense, SCSI_SENSE_BUFFERSIZE);
123         sgs[num_out + num_in++] = &sense;
124         sg_init_one(&inhdr, &vbr->in_hdr, sizeof(vbr->in_hdr));
125         sgs[num_out + num_in++] = &inhdr;
126         sg_init_one(&status, &vbr->status, sizeof(vbr->status));
127         sgs[num_out + num_in++] = &status;
128
129         return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
130 }
131
132 static inline void virtblk_scsi_request_done(struct request *req)
133 {
134         struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
135         struct virtio_blk *vblk = req->q->queuedata;
136         struct scsi_request *sreq = &vbr->sreq;
137
138         sreq->resid_len = virtio32_to_cpu(vblk->vdev, vbr->in_hdr.residual);
139         sreq->sense_len = virtio32_to_cpu(vblk->vdev, vbr->in_hdr.sense_len);
140         sreq->result = virtio32_to_cpu(vblk->vdev, vbr->in_hdr.errors);
141 }
142
143 static int virtblk_ioctl(struct block_device *bdev, fmode_t mode,
144                              unsigned int cmd, unsigned long data)
145 {
146         struct gendisk *disk = bdev->bd_disk;
147         struct virtio_blk *vblk = disk->private_data;
148
149         /*
150          * Only allow the generic SCSI ioctls if the host can support it.
151          */
152         if (!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_SCSI))
153                 return -ENOTTY;
154
155         return scsi_cmd_blk_ioctl(bdev, mode, cmd,
156                                   (void __user *)data);
157 }
158 #else
159 static inline int virtblk_add_req_scsi(struct virtqueue *vq,
160                 struct virtblk_req *vbr, struct scatterlist *data_sg,
161                 bool have_data)
162 {
163         return -EIO;
164 }
165 static inline void virtblk_scsi_request_done(struct request *req)
166 {
167 }
168 #define virtblk_ioctl   NULL
169 #endif /* CONFIG_VIRTIO_BLK_SCSI */
170
171 static int virtblk_add_req(struct virtqueue *vq, struct virtblk_req *vbr,
172                 struct scatterlist *data_sg, bool have_data)
173 {
174         struct scatterlist hdr, status, *sgs[3];
175         unsigned int num_out = 0, num_in = 0;
176
177         sg_init_one(&hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
178         sgs[num_out++] = &hdr;
179
180         if (have_data) {
181                 if (vbr->out_hdr.type & cpu_to_virtio32(vq->vdev, VIRTIO_BLK_T_OUT))
182                         sgs[num_out++] = data_sg;
183                 else
184                         sgs[num_out + num_in++] = data_sg;
185         }
186
187         sg_init_one(&status, &vbr->status, sizeof(vbr->status));
188         sgs[num_out + num_in++] = &status;
189
190         return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
191 }
192
193 static int virtblk_setup_discard_write_zeroes(struct request *req, bool unmap)
194 {
195         unsigned short segments = blk_rq_nr_discard_segments(req);
196         unsigned short n = 0;
197         struct virtio_blk_discard_write_zeroes *range;
198         struct bio *bio;
199         u32 flags = 0;
200
201         if (unmap)
202                 flags |= VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP;
203
204         range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
205         if (!range)
206                 return -ENOMEM;
207
208         /*
209          * Single max discard segment means multi-range discard isn't
210          * supported, and block layer only runs contiguity merge like
211          * normal RW request. So we can't reply on bio for retrieving
212          * each range info.
213          */
214         if (queue_max_discard_segments(req->q) == 1) {
215                 range[0].flags = cpu_to_le32(flags);
216                 range[0].num_sectors = cpu_to_le32(blk_rq_sectors(req));
217                 range[0].sector = cpu_to_le64(blk_rq_pos(req));
218                 n = 1;
219         } else {
220                 __rq_for_each_bio(bio, req) {
221                         u64 sector = bio->bi_iter.bi_sector;
222                         u32 num_sectors = bio->bi_iter.bi_size >> SECTOR_SHIFT;
223
224                         range[n].flags = cpu_to_le32(flags);
225                         range[n].num_sectors = cpu_to_le32(num_sectors);
226                         range[n].sector = cpu_to_le64(sector);
227                         n++;
228                 }
229         }
230
231         WARN_ON_ONCE(n != segments);
232
233         req->special_vec.bv_page = virt_to_page(range);
234         req->special_vec.bv_offset = offset_in_page(range);
235         req->special_vec.bv_len = sizeof(*range) * segments;
236         req->rq_flags |= RQF_SPECIAL_PAYLOAD;
237
238         return 0;
239 }
240
241 static inline void virtblk_request_done(struct request *req)
242 {
243         struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
244
245         if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
246                 kfree(page_address(req->special_vec.bv_page) +
247                       req->special_vec.bv_offset);
248         }
249
250         switch (req_op(req)) {
251         case REQ_OP_SCSI_IN:
252         case REQ_OP_SCSI_OUT:
253                 virtblk_scsi_request_done(req);
254                 break;
255         }
256
257         blk_mq_end_request(req, virtblk_result(vbr));
258 }
259
260 static void virtblk_done(struct virtqueue *vq)
261 {
262         struct virtio_blk *vblk = vq->vdev->priv;
263         bool req_done = false;
264         int qid = vq->index;
265         struct virtblk_req *vbr;
266         unsigned long flags;
267         unsigned int len;
268
269         spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
270         do {
271                 virtqueue_disable_cb(vq);
272                 while ((vbr = virtqueue_get_buf(vblk->vqs[qid].vq, &len)) != NULL) {
273                         struct request *req = blk_mq_rq_from_pdu(vbr);
274
275                         blk_mq_complete_request(req);
276                         req_done = true;
277                 }
278                 if (unlikely(virtqueue_is_broken(vq)))
279                         break;
280         } while (!virtqueue_enable_cb(vq));
281
282         /* In case queue is stopped waiting for more buffers. */
283         if (req_done)
284                 blk_mq_start_stopped_hw_queues(vblk->disk->queue, true);
285         spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
286 }
287
288 static void virtio_commit_rqs(struct blk_mq_hw_ctx *hctx)
289 {
290         struct virtio_blk *vblk = hctx->queue->queuedata;
291         struct virtio_blk_vq *vq = &vblk->vqs[hctx->queue_num];
292         bool kick;
293
294         spin_lock_irq(&vq->lock);
295         kick = virtqueue_kick_prepare(vq->vq);
296         spin_unlock_irq(&vq->lock);
297
298         if (kick)
299                 virtqueue_notify(vq->vq);
300 }
301
302 static blk_status_t virtio_queue_rq(struct blk_mq_hw_ctx *hctx,
303                            const struct blk_mq_queue_data *bd)
304 {
305         struct virtio_blk *vblk = hctx->queue->queuedata;
306         struct request *req = bd->rq;
307         struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
308         unsigned long flags;
309         unsigned int num;
310         int qid = hctx->queue_num;
311         int err;
312         bool notify = false;
313         bool unmap = false;
314         u32 type;
315
316         BUG_ON(req->nr_phys_segments + 2 > vblk->sg_elems);
317
318         switch (req_op(req)) {
319         case REQ_OP_READ:
320         case REQ_OP_WRITE:
321                 type = 0;
322                 break;
323         case REQ_OP_FLUSH:
324                 type = VIRTIO_BLK_T_FLUSH;
325                 break;
326         case REQ_OP_DISCARD:
327                 type = VIRTIO_BLK_T_DISCARD;
328                 break;
329         case REQ_OP_WRITE_ZEROES:
330                 type = VIRTIO_BLK_T_WRITE_ZEROES;
331                 unmap = !(req->cmd_flags & REQ_NOUNMAP);
332                 break;
333         case REQ_OP_SCSI_IN:
334         case REQ_OP_SCSI_OUT:
335                 type = VIRTIO_BLK_T_SCSI_CMD;
336                 break;
337         case REQ_OP_DRV_IN:
338                 type = VIRTIO_BLK_T_GET_ID;
339                 break;
340         default:
341                 WARN_ON_ONCE(1);
342                 return BLK_STS_IOERR;
343         }
344
345         vbr->out_hdr.type = cpu_to_virtio32(vblk->vdev, type);
346         vbr->out_hdr.sector = type ?
347                 0 : cpu_to_virtio64(vblk->vdev, blk_rq_pos(req));
348         vbr->out_hdr.ioprio = cpu_to_virtio32(vblk->vdev, req_get_ioprio(req));
349
350         blk_mq_start_request(req);
351
352         if (type == VIRTIO_BLK_T_DISCARD || type == VIRTIO_BLK_T_WRITE_ZEROES) {
353                 err = virtblk_setup_discard_write_zeroes(req, unmap);
354                 if (err)
355                         return BLK_STS_RESOURCE;
356         }
357
358         num = blk_rq_map_sg(hctx->queue, req, vbr->sg);
359         if (num) {
360                 if (rq_data_dir(req) == WRITE)
361                         vbr->out_hdr.type |= cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_OUT);
362                 else
363                         vbr->out_hdr.type |= cpu_to_virtio32(vblk->vdev, VIRTIO_BLK_T_IN);
364         }
365
366         spin_lock_irqsave(&vblk->vqs[qid].lock, flags);
367         if (blk_rq_is_scsi(req))
368                 err = virtblk_add_req_scsi(vblk->vqs[qid].vq, vbr, vbr->sg, num);
369         else
370                 err = virtblk_add_req(vblk->vqs[qid].vq, vbr, vbr->sg, num);
371         if (err) {
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.
375                  */
376                 if (err == -ENOSPC)
377                         blk_mq_stop_hw_queue(hctx);
378                 spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
379                 switch (err) {
380                 case -ENOSPC:
381                         return BLK_STS_DEV_RESOURCE;
382                 case -ENOMEM:
383                         return BLK_STS_RESOURCE;
384                 default:
385                         return BLK_STS_IOERR;
386                 }
387         }
388
389         if (bd->last && virtqueue_kick_prepare(vblk->vqs[qid].vq))
390                 notify = true;
391         spin_unlock_irqrestore(&vblk->vqs[qid].lock, flags);
392
393         if (notify)
394                 virtqueue_notify(vblk->vqs[qid].vq);
395         return BLK_STS_OK;
396 }
397
398 /* return id (s/n) string for *disk to *id_str
399  */
400 static int virtblk_get_id(struct gendisk *disk, char *id_str)
401 {
402         struct virtio_blk *vblk = disk->private_data;
403         struct request_queue *q = vblk->disk->queue;
404         struct request *req;
405         int err;
406
407         req = blk_get_request(q, REQ_OP_DRV_IN, 0);
408         if (IS_ERR(req))
409                 return PTR_ERR(req);
410
411         err = blk_rq_map_kern(q, req, id_str, VIRTIO_BLK_ID_BYTES, GFP_KERNEL);
412         if (err)
413                 goto out;
414
415         blk_execute_rq(vblk->disk->queue, vblk->disk, req, false);
416         err = blk_status_to_errno(virtblk_result(blk_mq_rq_to_pdu(req)));
417 out:
418         blk_put_request(req);
419         return err;
420 }
421
422 static void virtblk_get(struct virtio_blk *vblk)
423 {
424         refcount_inc(&vblk->refs);
425 }
426
427 static void virtblk_put(struct virtio_blk *vblk)
428 {
429         if (refcount_dec_and_test(&vblk->refs)) {
430                 ida_simple_remove(&vd_index_ida, vblk->index);
431                 mutex_destroy(&vblk->vdev_mutex);
432                 kfree(vblk);
433         }
434 }
435
436 static int virtblk_open(struct block_device *bd, fmode_t mode)
437 {
438         struct virtio_blk *vblk = bd->bd_disk->private_data;
439         int ret = 0;
440
441         mutex_lock(&vblk->vdev_mutex);
442
443         if (vblk->vdev)
444                 virtblk_get(vblk);
445         else
446                 ret = -ENXIO;
447
448         mutex_unlock(&vblk->vdev_mutex);
449         return ret;
450 }
451
452 static void virtblk_release(struct gendisk *disk, fmode_t mode)
453 {
454         struct virtio_blk *vblk = disk->private_data;
455
456         virtblk_put(vblk);
457 }
458
459 /* We provide getgeo only to please some old bootloader/partitioning tools */
460 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
461 {
462         struct virtio_blk *vblk = bd->bd_disk->private_data;
463         int ret = 0;
464
465         mutex_lock(&vblk->vdev_mutex);
466
467         if (!vblk->vdev) {
468                 ret = -ENXIO;
469                 goto out;
470         }
471
472         /* see if the host passed in geometry config */
473         if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
474                 virtio_cread(vblk->vdev, struct virtio_blk_config,
475                              geometry.cylinders, &geo->cylinders);
476                 virtio_cread(vblk->vdev, struct virtio_blk_config,
477                              geometry.heads, &geo->heads);
478                 virtio_cread(vblk->vdev, struct virtio_blk_config,
479                              geometry.sectors, &geo->sectors);
480         } else {
481                 /* some standard values, similar to sd */
482                 geo->heads = 1 << 6;
483                 geo->sectors = 1 << 5;
484                 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
485         }
486 out:
487         mutex_unlock(&vblk->vdev_mutex);
488         return ret;
489 }
490
491 static const struct block_device_operations virtblk_fops = {
492         .ioctl  = virtblk_ioctl,
493         .owner  = THIS_MODULE,
494         .open = virtblk_open,
495         .release = virtblk_release,
496         .getgeo = virtblk_getgeo,
497 };
498
499 static int index_to_minor(int index)
500 {
501         return index << PART_BITS;
502 }
503
504 static int minor_to_index(int minor)
505 {
506         return minor >> PART_BITS;
507 }
508
509 static ssize_t serial_show(struct device *dev,
510                            struct device_attribute *attr, char *buf)
511 {
512         struct gendisk *disk = dev_to_disk(dev);
513         int err;
514
515         /* sysfs gives us a PAGE_SIZE buffer */
516         BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
517
518         buf[VIRTIO_BLK_ID_BYTES] = '\0';
519         err = virtblk_get_id(disk, buf);
520         if (!err)
521                 return strlen(buf);
522
523         if (err == -EIO) /* Unsupported? Make it empty. */
524                 return 0;
525
526         return err;
527 }
528
529 static DEVICE_ATTR_RO(serial);
530
531 /* The queue's logical block size must be set before calling this */
532 static void virtblk_update_capacity(struct virtio_blk *vblk, bool resize)
533 {
534         struct virtio_device *vdev = vblk->vdev;
535         struct request_queue *q = vblk->disk->queue;
536         char cap_str_2[10], cap_str_10[10];
537         unsigned long long nblocks;
538         u64 capacity;
539
540         /* Host must always specify the capacity. */
541         virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
542
543         /* If capacity is too big, truncate with warning. */
544         if ((sector_t)capacity != capacity) {
545                 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
546                          (unsigned long long)capacity);
547                 capacity = (sector_t)-1;
548         }
549
550         nblocks = DIV_ROUND_UP_ULL(capacity, queue_logical_block_size(q) >> 9);
551
552         string_get_size(nblocks, queue_logical_block_size(q),
553                         STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
554         string_get_size(nblocks, queue_logical_block_size(q),
555                         STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
556
557         dev_notice(&vdev->dev,
558                    "[%s] %s%llu %d-byte logical blocks (%s/%s)\n",
559                    vblk->disk->disk_name,
560                    resize ? "new size: " : "",
561                    nblocks,
562                    queue_logical_block_size(q),
563                    cap_str_10,
564                    cap_str_2);
565
566         set_capacity(vblk->disk, capacity);
567 }
568
569 static void virtblk_config_changed_work(struct work_struct *work)
570 {
571         struct virtio_blk *vblk =
572                 container_of(work, struct virtio_blk, config_work);
573         char *envp[] = { "RESIZE=1", NULL };
574
575         virtblk_update_capacity(vblk, true);
576         revalidate_disk(vblk->disk);
577         kobject_uevent_env(&disk_to_dev(vblk->disk)->kobj, KOBJ_CHANGE, envp);
578 }
579
580 static void virtblk_config_changed(struct virtio_device *vdev)
581 {
582         struct virtio_blk *vblk = vdev->priv;
583
584         queue_work(virtblk_wq, &vblk->config_work);
585 }
586
587 static int init_vq(struct virtio_blk *vblk)
588 {
589         int err;
590         int i;
591         vq_callback_t **callbacks;
592         const char **names;
593         struct virtqueue **vqs;
594         unsigned short num_vqs;
595         struct virtio_device *vdev = vblk->vdev;
596         struct irq_affinity desc = { 0, };
597
598         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_MQ,
599                                    struct virtio_blk_config, num_queues,
600                                    &num_vqs);
601         if (err)
602                 num_vqs = 1;
603
604         num_vqs = min_t(unsigned int, nr_cpu_ids, num_vqs);
605
606         vblk->vqs = kmalloc_array(num_vqs, sizeof(*vblk->vqs), GFP_KERNEL);
607         if (!vblk->vqs)
608                 return -ENOMEM;
609
610         names = kmalloc_array(num_vqs, sizeof(*names), GFP_KERNEL);
611         callbacks = kmalloc_array(num_vqs, sizeof(*callbacks), GFP_KERNEL);
612         vqs = kmalloc_array(num_vqs, sizeof(*vqs), GFP_KERNEL);
613         if (!names || !callbacks || !vqs) {
614                 err = -ENOMEM;
615                 goto out;
616         }
617
618         for (i = 0; i < num_vqs; i++) {
619                 callbacks[i] = virtblk_done;
620                 snprintf(vblk->vqs[i].name, VQ_NAME_LEN, "req.%d", i);
621                 names[i] = vblk->vqs[i].name;
622         }
623
624         /* Discover virtqueues and write information to configuration.  */
625         err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
626         if (err)
627                 goto out;
628
629         for (i = 0; i < num_vqs; i++) {
630                 spin_lock_init(&vblk->vqs[i].lock);
631                 vblk->vqs[i].vq = vqs[i];
632         }
633         vblk->num_vqs = num_vqs;
634
635 out:
636         kfree(vqs);
637         kfree(callbacks);
638         kfree(names);
639         if (err)
640                 kfree(vblk->vqs);
641         return err;
642 }
643
644 /*
645  * Legacy naming scheme used for virtio devices.  We are stuck with it for
646  * virtio blk but don't ever use it for any new driver.
647  */
648 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
649 {
650         const int base = 'z' - 'a' + 1;
651         char *begin = buf + strlen(prefix);
652         char *end = buf + buflen;
653         char *p;
654         int unit;
655
656         p = end - 1;
657         *p = '\0';
658         unit = base;
659         do {
660                 if (p == begin)
661                         return -EINVAL;
662                 *--p = 'a' + (index % unit);
663                 index = (index / unit) - 1;
664         } while (index >= 0);
665
666         memmove(begin, p, end - p);
667         memcpy(buf, prefix, strlen(prefix));
668
669         return 0;
670 }
671
672 static int virtblk_get_cache_mode(struct virtio_device *vdev)
673 {
674         u8 writeback;
675         int err;
676
677         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
678                                    struct virtio_blk_config, wce,
679                                    &writeback);
680
681         /*
682          * If WCE is not configurable and flush is not available,
683          * assume no writeback cache is in use.
684          */
685         if (err)
686                 writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH);
687
688         return writeback;
689 }
690
691 static void virtblk_update_cache_mode(struct virtio_device *vdev)
692 {
693         u8 writeback = virtblk_get_cache_mode(vdev);
694         struct virtio_blk *vblk = vdev->priv;
695
696         blk_queue_write_cache(vblk->disk->queue, writeback, false);
697         revalidate_disk(vblk->disk);
698 }
699
700 static const char *const virtblk_cache_types[] = {
701         "write through", "write back"
702 };
703
704 static ssize_t
705 cache_type_store(struct device *dev, struct device_attribute *attr,
706                  const char *buf, size_t count)
707 {
708         struct gendisk *disk = dev_to_disk(dev);
709         struct virtio_blk *vblk = disk->private_data;
710         struct virtio_device *vdev = vblk->vdev;
711         int i;
712
713         BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
714         i = sysfs_match_string(virtblk_cache_types, buf);
715         if (i < 0)
716                 return i;
717
718         virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
719         virtblk_update_cache_mode(vdev);
720         return count;
721 }
722
723 static ssize_t
724 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
725 {
726         struct gendisk *disk = dev_to_disk(dev);
727         struct virtio_blk *vblk = disk->private_data;
728         u8 writeback = virtblk_get_cache_mode(vblk->vdev);
729
730         BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
731         return snprintf(buf, 40, "%s\n", virtblk_cache_types[writeback]);
732 }
733
734 static DEVICE_ATTR_RW(cache_type);
735
736 static struct attribute *virtblk_attrs[] = {
737         &dev_attr_serial.attr,
738         &dev_attr_cache_type.attr,
739         NULL,
740 };
741
742 static umode_t virtblk_attrs_are_visible(struct kobject *kobj,
743                 struct attribute *a, int n)
744 {
745         struct device *dev = container_of(kobj, struct device, kobj);
746         struct gendisk *disk = dev_to_disk(dev);
747         struct virtio_blk *vblk = disk->private_data;
748         struct virtio_device *vdev = vblk->vdev;
749
750         if (a == &dev_attr_cache_type.attr &&
751             !virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
752                 return S_IRUGO;
753
754         return a->mode;
755 }
756
757 static const struct attribute_group virtblk_attr_group = {
758         .attrs = virtblk_attrs,
759         .is_visible = virtblk_attrs_are_visible,
760 };
761
762 static const struct attribute_group *virtblk_attr_groups[] = {
763         &virtblk_attr_group,
764         NULL,
765 };
766
767 static int virtblk_init_request(struct blk_mq_tag_set *set, struct request *rq,
768                 unsigned int hctx_idx, unsigned int numa_node)
769 {
770         struct virtio_blk *vblk = set->driver_data;
771         struct virtblk_req *vbr = blk_mq_rq_to_pdu(rq);
772
773 #ifdef CONFIG_VIRTIO_BLK_SCSI
774         vbr->sreq.sense = vbr->sense;
775 #endif
776         sg_init_table(vbr->sg, vblk->sg_elems);
777         return 0;
778 }
779
780 static int virtblk_map_queues(struct blk_mq_tag_set *set)
781 {
782         struct virtio_blk *vblk = set->driver_data;
783
784         return blk_mq_virtio_map_queues(&set->map[HCTX_TYPE_DEFAULT],
785                                         vblk->vdev, 0);
786 }
787
788 #ifdef CONFIG_VIRTIO_BLK_SCSI
789 static void virtblk_initialize_rq(struct request *req)
790 {
791         struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
792
793         scsi_req_init(&vbr->sreq);
794 }
795 #endif
796
797 static const struct blk_mq_ops virtio_mq_ops = {
798         .queue_rq       = virtio_queue_rq,
799         .commit_rqs     = virtio_commit_rqs,
800         .complete       = virtblk_request_done,
801         .init_request   = virtblk_init_request,
802 #ifdef CONFIG_VIRTIO_BLK_SCSI
803         .initialize_rq_fn = virtblk_initialize_rq,
804 #endif
805         .map_queues     = virtblk_map_queues,
806 };
807
808 static unsigned int virtblk_queue_depth;
809 module_param_named(queue_depth, virtblk_queue_depth, uint, 0444);
810
811 static int virtblk_probe(struct virtio_device *vdev)
812 {
813         struct virtio_blk *vblk;
814         struct request_queue *q;
815         int err, index;
816
817         u32 v, blk_size, max_size, sg_elems, opt_io_size;
818         u16 min_io_size;
819         u8 physical_block_exp, alignment_offset;
820
821         if (!vdev->config->get) {
822                 dev_err(&vdev->dev, "%s failure: config access disabled\n",
823                         __func__);
824                 return -EINVAL;
825         }
826
827         err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
828                              GFP_KERNEL);
829         if (err < 0)
830                 goto out;
831         index = err;
832
833         /* We need to know how many segments before we allocate. */
834         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
835                                    struct virtio_blk_config, seg_max,
836                                    &sg_elems);
837
838         /* We need at least one SG element, whatever they say. */
839         if (err || !sg_elems)
840                 sg_elems = 1;
841
842         /* We need an extra sg elements at head and tail. */
843         sg_elems += 2;
844         vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL);
845         if (!vblk) {
846                 err = -ENOMEM;
847                 goto out_free_index;
848         }
849
850         /* This reference is dropped in virtblk_remove(). */
851         refcount_set(&vblk->refs, 1);
852         mutex_init(&vblk->vdev_mutex);
853
854         vblk->vdev = vdev;
855         vblk->sg_elems = sg_elems;
856
857         INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
858
859         err = init_vq(vblk);
860         if (err)
861                 goto out_free_vblk;
862
863         /* FIXME: How many partitions?  How long is a piece of string? */
864         vblk->disk = alloc_disk(1 << PART_BITS);
865         if (!vblk->disk) {
866                 err = -ENOMEM;
867                 goto out_free_vq;
868         }
869
870         /* Default queue sizing is to fill the ring. */
871         if (!virtblk_queue_depth) {
872                 virtblk_queue_depth = vblk->vqs[0].vq->num_free;
873                 /* ... but without indirect descs, we use 2 descs per req */
874                 if (!virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC))
875                         virtblk_queue_depth /= 2;
876         }
877
878         memset(&vblk->tag_set, 0, sizeof(vblk->tag_set));
879         vblk->tag_set.ops = &virtio_mq_ops;
880         vblk->tag_set.queue_depth = virtblk_queue_depth;
881         vblk->tag_set.numa_node = NUMA_NO_NODE;
882         vblk->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
883         vblk->tag_set.cmd_size =
884                 sizeof(struct virtblk_req) +
885                 sizeof(struct scatterlist) * sg_elems;
886         vblk->tag_set.driver_data = vblk;
887         vblk->tag_set.nr_hw_queues = vblk->num_vqs;
888
889         err = blk_mq_alloc_tag_set(&vblk->tag_set);
890         if (err)
891                 goto out_put_disk;
892
893         q = blk_mq_init_queue(&vblk->tag_set);
894         if (IS_ERR(q)) {
895                 err = -ENOMEM;
896                 goto out_free_tags;
897         }
898         vblk->disk->queue = q;
899
900         q->queuedata = vblk;
901
902         virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
903
904         vblk->disk->major = major;
905         vblk->disk->first_minor = index_to_minor(index);
906         vblk->disk->private_data = vblk;
907         vblk->disk->fops = &virtblk_fops;
908         vblk->disk->flags |= GENHD_FL_EXT_DEVT;
909         vblk->index = index;
910
911         /* configure queue flush support */
912         virtblk_update_cache_mode(vdev);
913
914         /* If disk is read-only in the host, the guest should obey */
915         if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
916                 set_disk_ro(vblk->disk, 1);
917
918         /* We can handle whatever the host told us to handle. */
919         blk_queue_max_segments(q, vblk->sg_elems-2);
920
921         /* No real sector limit. */
922         blk_queue_max_hw_sectors(q, -1U);
923
924         max_size = virtio_max_dma_size(vdev);
925
926         /* Host can optionally specify maximum segment size and number of
927          * segments. */
928         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
929                                    struct virtio_blk_config, size_max, &v);
930         if (!err)
931                 max_size = min(max_size, v);
932
933         blk_queue_max_segment_size(q, max_size);
934
935         /* Host can optionally specify the block size of the device */
936         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
937                                    struct virtio_blk_config, blk_size,
938                                    &blk_size);
939         if (!err) {
940                 err = blk_validate_block_size(blk_size);
941                 if (err) {
942                         dev_err(&vdev->dev,
943                                 "virtio_blk: invalid block size: 0x%x\n",
944                                 blk_size);
945                         goto out_free_tags;
946                 }
947
948                 blk_queue_logical_block_size(q, blk_size);
949         } else
950                 blk_size = queue_logical_block_size(q);
951
952         /* Use topology information if available */
953         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
954                                    struct virtio_blk_config, physical_block_exp,
955                                    &physical_block_exp);
956         if (!err && physical_block_exp)
957                 blk_queue_physical_block_size(q,
958                                 blk_size * (1 << physical_block_exp));
959
960         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
961                                    struct virtio_blk_config, alignment_offset,
962                                    &alignment_offset);
963         if (!err && alignment_offset)
964                 blk_queue_alignment_offset(q, blk_size * alignment_offset);
965
966         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
967                                    struct virtio_blk_config, min_io_size,
968                                    &min_io_size);
969         if (!err && min_io_size)
970                 blk_queue_io_min(q, blk_size * min_io_size);
971
972         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
973                                    struct virtio_blk_config, opt_io_size,
974                                    &opt_io_size);
975         if (!err && opt_io_size)
976                 blk_queue_io_opt(q, blk_size * opt_io_size);
977
978         if (virtio_has_feature(vdev, VIRTIO_BLK_F_DISCARD)) {
979                 virtio_cread(vdev, struct virtio_blk_config,
980                              discard_sector_alignment, &v);
981                 if (v)
982                         q->limits.discard_granularity = v << SECTOR_SHIFT;
983                 else
984                         q->limits.discard_granularity = blk_size;
985
986                 virtio_cread(vdev, struct virtio_blk_config,
987                              max_discard_sectors, &v);
988                 blk_queue_max_discard_sectors(q, v ? v : UINT_MAX);
989
990                 virtio_cread(vdev, struct virtio_blk_config, max_discard_seg,
991                              &v);
992
993                 /*
994                  * max_discard_seg == 0 is out of spec but we always
995                  * handled it.
996                  */
997                 if (!v)
998                         v = sg_elems - 2;
999                 blk_queue_max_discard_segments(q,
1000                                                min(v, MAX_DISCARD_SEGMENTS));
1001
1002                 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
1003         }
1004
1005         if (virtio_has_feature(vdev, VIRTIO_BLK_F_WRITE_ZEROES)) {
1006                 virtio_cread(vdev, struct virtio_blk_config,
1007                              max_write_zeroes_sectors, &v);
1008                 blk_queue_max_write_zeroes_sectors(q, v ? v : UINT_MAX);
1009         }
1010
1011         virtblk_update_capacity(vblk, false);
1012         virtio_device_ready(vdev);
1013
1014         device_add_disk(&vdev->dev, vblk->disk, virtblk_attr_groups);
1015         return 0;
1016
1017 out_free_tags:
1018         blk_mq_free_tag_set(&vblk->tag_set);
1019 out_put_disk:
1020         put_disk(vblk->disk);
1021 out_free_vq:
1022         vdev->config->del_vqs(vdev);
1023         kfree(vblk->vqs);
1024 out_free_vblk:
1025         kfree(vblk);
1026 out_free_index:
1027         ida_simple_remove(&vd_index_ida, index);
1028 out:
1029         return err;
1030 }
1031
1032 static void virtblk_remove(struct virtio_device *vdev)
1033 {
1034         struct virtio_blk *vblk = vdev->priv;
1035
1036         /* Make sure no work handler is accessing the device. */
1037         flush_work(&vblk->config_work);
1038
1039         del_gendisk(vblk->disk);
1040         blk_cleanup_queue(vblk->disk->queue);
1041
1042         blk_mq_free_tag_set(&vblk->tag_set);
1043
1044         mutex_lock(&vblk->vdev_mutex);
1045
1046         /* Stop all the virtqueues. */
1047         vdev->config->reset(vdev);
1048
1049         /* Virtqueues are stopped, nothing can use vblk->vdev anymore. */
1050         vblk->vdev = NULL;
1051
1052         put_disk(vblk->disk);
1053         vdev->config->del_vqs(vdev);
1054         kfree(vblk->vqs);
1055
1056         mutex_unlock(&vblk->vdev_mutex);
1057
1058         virtblk_put(vblk);
1059 }
1060
1061 #ifdef CONFIG_PM_SLEEP
1062 static int virtblk_freeze(struct virtio_device *vdev)
1063 {
1064         struct virtio_blk *vblk = vdev->priv;
1065
1066         /* Ensure we don't receive any more interrupts */
1067         vdev->config->reset(vdev);
1068
1069         /* Make sure no work handler is accessing the device. */
1070         flush_work(&vblk->config_work);
1071
1072         blk_mq_quiesce_queue(vblk->disk->queue);
1073
1074         vdev->config->del_vqs(vdev);
1075         kfree(vblk->vqs);
1076
1077         return 0;
1078 }
1079
1080 static int virtblk_restore(struct virtio_device *vdev)
1081 {
1082         struct virtio_blk *vblk = vdev->priv;
1083         int ret;
1084
1085         ret = init_vq(vdev->priv);
1086         if (ret)
1087                 return ret;
1088
1089         virtio_device_ready(vdev);
1090
1091         blk_mq_unquiesce_queue(vblk->disk->queue);
1092         return 0;
1093 }
1094 #endif
1095
1096 static const struct virtio_device_id id_table[] = {
1097         { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
1098         { 0 },
1099 };
1100
1101 static unsigned int features_legacy[] = {
1102         VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1103         VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1104 #ifdef CONFIG_VIRTIO_BLK_SCSI
1105         VIRTIO_BLK_F_SCSI,
1106 #endif
1107         VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1108         VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1109 }
1110 ;
1111 static unsigned int features[] = {
1112         VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
1113         VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE,
1114         VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE,
1115         VIRTIO_BLK_F_MQ, VIRTIO_BLK_F_DISCARD, VIRTIO_BLK_F_WRITE_ZEROES,
1116 };
1117
1118 static struct virtio_driver virtio_blk = {
1119         .feature_table                  = features,
1120         .feature_table_size             = ARRAY_SIZE(features),
1121         .feature_table_legacy           = features_legacy,
1122         .feature_table_size_legacy      = ARRAY_SIZE(features_legacy),
1123         .driver.name                    = KBUILD_MODNAME,
1124         .driver.owner                   = THIS_MODULE,
1125         .id_table                       = id_table,
1126         .probe                          = virtblk_probe,
1127         .remove                         = virtblk_remove,
1128         .config_changed                 = virtblk_config_changed,
1129 #ifdef CONFIG_PM_SLEEP
1130         .freeze                         = virtblk_freeze,
1131         .restore                        = virtblk_restore,
1132 #endif
1133 };
1134
1135 static int __init init(void)
1136 {
1137         int error;
1138
1139         virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
1140         if (!virtblk_wq)
1141                 return -ENOMEM;
1142
1143         major = register_blkdev(0, "virtblk");
1144         if (major < 0) {
1145                 error = major;
1146                 goto out_destroy_workqueue;
1147         }
1148
1149         error = register_virtio_driver(&virtio_blk);
1150         if (error)
1151                 goto out_unregister_blkdev;
1152         return 0;
1153
1154 out_unregister_blkdev:
1155         unregister_blkdev(major, "virtblk");
1156 out_destroy_workqueue:
1157         destroy_workqueue(virtblk_wq);
1158         return error;
1159 }
1160
1161 static void __exit fini(void)
1162 {
1163         unregister_virtio_driver(&virtio_blk);
1164         unregister_blkdev(major, "virtblk");
1165         destroy_workqueue(virtblk_wq);
1166 }
1167 module_init(init);
1168 module_exit(fini);
1169
1170 MODULE_DEVICE_TABLE(virtio, id_table);
1171 MODULE_DESCRIPTION("Virtio block driver");
1172 MODULE_LICENSE("GPL");