virtio-blk: Use block layer provided spinlock
[pandora-kernel.git] / drivers / block / virtio_blk.c
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/virtio.h>
8 #include <linux/virtio_blk.h>
9 #include <linux/scatterlist.h>
10 #include <linux/string_helpers.h>
11 #include <scsi/scsi_cmnd.h>
12 #include <linux/idr.h>
13
14 #define PART_BITS 4
15
16 static int major;
17 static DEFINE_IDA(vd_index_ida);
18
19 struct workqueue_struct *virtblk_wq;
20
21 struct virtio_blk
22 {
23         struct virtio_device *vdev;
24         struct virtqueue *vq;
25
26         /* The disk structure for the kernel. */
27         struct gendisk *disk;
28
29         /* Request tracking. */
30         struct list_head reqs;
31
32         mempool_t *pool;
33
34         /* Process context for config space updates */
35         struct work_struct config_work;
36
37         /* What host tells us, plus 2 for header & tailer. */
38         unsigned int sg_elems;
39
40         /* Ida index - used to track minor number allocations. */
41         int index;
42
43         /* Scatterlist: can be too big for stack. */
44         struct scatterlist sg[/*sg_elems*/];
45 };
46
47 struct virtblk_req
48 {
49         struct list_head list;
50         struct request *req;
51         struct virtio_blk_outhdr out_hdr;
52         struct virtio_scsi_inhdr in_hdr;
53         u8 status;
54 };
55
56 static void blk_done(struct virtqueue *vq)
57 {
58         struct virtio_blk *vblk = vq->vdev->priv;
59         struct virtblk_req *vbr;
60         unsigned int len;
61         unsigned long flags;
62
63         spin_lock_irqsave(vblk->disk->queue->queue_lock, flags);
64         while ((vbr = virtqueue_get_buf(vblk->vq, &len)) != NULL) {
65                 int error;
66
67                 switch (vbr->status) {
68                 case VIRTIO_BLK_S_OK:
69                         error = 0;
70                         break;
71                 case VIRTIO_BLK_S_UNSUPP:
72                         error = -ENOTTY;
73                         break;
74                 default:
75                         error = -EIO;
76                         break;
77                 }
78
79                 switch (vbr->req->cmd_type) {
80                 case REQ_TYPE_BLOCK_PC:
81                         vbr->req->resid_len = vbr->in_hdr.residual;
82                         vbr->req->sense_len = vbr->in_hdr.sense_len;
83                         vbr->req->errors = vbr->in_hdr.errors;
84                         break;
85                 case REQ_TYPE_SPECIAL:
86                         vbr->req->errors = (error != 0);
87                         break;
88                 default:
89                         break;
90                 }
91
92                 __blk_end_request_all(vbr->req, error);
93                 list_del(&vbr->list);
94                 mempool_free(vbr, vblk->pool);
95         }
96         /* In case queue is stopped waiting for more buffers. */
97         blk_start_queue(vblk->disk->queue);
98         spin_unlock_irqrestore(vblk->disk->queue->queue_lock, flags);
99 }
100
101 static bool do_req(struct request_queue *q, struct virtio_blk *vblk,
102                    struct request *req)
103 {
104         unsigned long num, out = 0, in = 0;
105         struct virtblk_req *vbr;
106
107         vbr = mempool_alloc(vblk->pool, GFP_ATOMIC);
108         if (!vbr)
109                 /* When another request finishes we'll try again. */
110                 return false;
111
112         vbr->req = req;
113
114         if (req->cmd_flags & REQ_FLUSH) {
115                 vbr->out_hdr.type = VIRTIO_BLK_T_FLUSH;
116                 vbr->out_hdr.sector = 0;
117                 vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
118         } else {
119                 switch (req->cmd_type) {
120                 case REQ_TYPE_FS:
121                         vbr->out_hdr.type = 0;
122                         vbr->out_hdr.sector = blk_rq_pos(vbr->req);
123                         vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
124                         break;
125                 case REQ_TYPE_BLOCK_PC:
126                         vbr->out_hdr.type = VIRTIO_BLK_T_SCSI_CMD;
127                         vbr->out_hdr.sector = 0;
128                         vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
129                         break;
130                 case REQ_TYPE_SPECIAL:
131                         vbr->out_hdr.type = VIRTIO_BLK_T_GET_ID;
132                         vbr->out_hdr.sector = 0;
133                         vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
134                         break;
135                 default:
136                         /* We don't put anything else in the queue. */
137                         BUG();
138                 }
139         }
140
141         sg_set_buf(&vblk->sg[out++], &vbr->out_hdr, sizeof(vbr->out_hdr));
142
143         /*
144          * If this is a packet command we need a couple of additional headers.
145          * Behind the normal outhdr we put a segment with the scsi command
146          * block, and before the normal inhdr we put the sense data and the
147          * inhdr with additional status information before the normal inhdr.
148          */
149         if (vbr->req->cmd_type == REQ_TYPE_BLOCK_PC)
150                 sg_set_buf(&vblk->sg[out++], vbr->req->cmd, vbr->req->cmd_len);
151
152         num = blk_rq_map_sg(q, vbr->req, vblk->sg + out);
153
154         if (vbr->req->cmd_type == REQ_TYPE_BLOCK_PC) {
155                 sg_set_buf(&vblk->sg[num + out + in++], vbr->req->sense, SCSI_SENSE_BUFFERSIZE);
156                 sg_set_buf(&vblk->sg[num + out + in++], &vbr->in_hdr,
157                            sizeof(vbr->in_hdr));
158         }
159
160         sg_set_buf(&vblk->sg[num + out + in++], &vbr->status,
161                    sizeof(vbr->status));
162
163         if (num) {
164                 if (rq_data_dir(vbr->req) == WRITE) {
165                         vbr->out_hdr.type |= VIRTIO_BLK_T_OUT;
166                         out += num;
167                 } else {
168                         vbr->out_hdr.type |= VIRTIO_BLK_T_IN;
169                         in += num;
170                 }
171         }
172
173         if (virtqueue_add_buf(vblk->vq, vblk->sg, out, in, vbr) < 0) {
174                 mempool_free(vbr, vblk->pool);
175                 return false;
176         }
177
178         list_add_tail(&vbr->list, &vblk->reqs);
179         return true;
180 }
181
182 static void do_virtblk_request(struct request_queue *q)
183 {
184         struct virtio_blk *vblk = q->queuedata;
185         struct request *req;
186         unsigned int issued = 0;
187
188         while ((req = blk_peek_request(q)) != NULL) {
189                 BUG_ON(req->nr_phys_segments + 2 > vblk->sg_elems);
190
191                 /* If this request fails, stop queue and wait for something to
192                    finish to restart it. */
193                 if (!do_req(q, vblk, req)) {
194                         blk_stop_queue(q);
195                         break;
196                 }
197                 blk_start_request(req);
198                 issued++;
199         }
200
201         if (issued)
202                 virtqueue_kick(vblk->vq);
203 }
204
205 /* return id (s/n) string for *disk to *id_str
206  */
207 static int virtblk_get_id(struct gendisk *disk, char *id_str)
208 {
209         struct virtio_blk *vblk = disk->private_data;
210         struct request *req;
211         struct bio *bio;
212         int err;
213
214         bio = bio_map_kern(vblk->disk->queue, id_str, VIRTIO_BLK_ID_BYTES,
215                            GFP_KERNEL);
216         if (IS_ERR(bio))
217                 return PTR_ERR(bio);
218
219         req = blk_make_request(vblk->disk->queue, bio, GFP_KERNEL);
220         if (IS_ERR(req)) {
221                 bio_put(bio);
222                 return PTR_ERR(req);
223         }
224
225         req->cmd_type = REQ_TYPE_SPECIAL;
226         err = blk_execute_rq(vblk->disk->queue, vblk->disk, req, false);
227         blk_put_request(req);
228
229         return err;
230 }
231
232 static int virtblk_ioctl(struct block_device *bdev, fmode_t mode,
233                              unsigned int cmd, unsigned long data)
234 {
235         struct gendisk *disk = bdev->bd_disk;
236         struct virtio_blk *vblk = disk->private_data;
237
238         /*
239          * Only allow the generic SCSI ioctls if the host can support it.
240          */
241         if (!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_SCSI))
242                 return -ENOTTY;
243
244         return scsi_cmd_blk_ioctl(bdev, mode, cmd,
245                                   (void __user *)data);
246 }
247
248 /* We provide getgeo only to please some old bootloader/partitioning tools */
249 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
250 {
251         struct virtio_blk *vblk = bd->bd_disk->private_data;
252         struct virtio_blk_geometry vgeo;
253         int err;
254
255         /* see if the host passed in geometry config */
256         err = virtio_config_val(vblk->vdev, VIRTIO_BLK_F_GEOMETRY,
257                                 offsetof(struct virtio_blk_config, geometry),
258                                 &vgeo);
259
260         if (!err) {
261                 geo->heads = vgeo.heads;
262                 geo->sectors = vgeo.sectors;
263                 geo->cylinders = vgeo.cylinders;
264         } else {
265                 /* some standard values, similar to sd */
266                 geo->heads = 1 << 6;
267                 geo->sectors = 1 << 5;
268                 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
269         }
270         return 0;
271 }
272
273 static const struct block_device_operations virtblk_fops = {
274         .ioctl  = virtblk_ioctl,
275         .owner  = THIS_MODULE,
276         .getgeo = virtblk_getgeo,
277 };
278
279 static int index_to_minor(int index)
280 {
281         return index << PART_BITS;
282 }
283
284 static int minor_to_index(int minor)
285 {
286         return minor >> PART_BITS;
287 }
288
289 static ssize_t virtblk_serial_show(struct device *dev,
290                                 struct device_attribute *attr, char *buf)
291 {
292         struct gendisk *disk = dev_to_disk(dev);
293         int err;
294
295         /* sysfs gives us a PAGE_SIZE buffer */
296         BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
297
298         buf[VIRTIO_BLK_ID_BYTES] = '\0';
299         err = virtblk_get_id(disk, buf);
300         if (!err)
301                 return strlen(buf);
302
303         if (err == -EIO) /* Unsupported? Make it empty. */
304                 return 0;
305
306         return err;
307 }
308 DEVICE_ATTR(serial, S_IRUGO, virtblk_serial_show, NULL);
309
310 static void virtblk_config_changed_work(struct work_struct *work)
311 {
312         struct virtio_blk *vblk =
313                 container_of(work, struct virtio_blk, config_work);
314         struct virtio_device *vdev = vblk->vdev;
315         struct request_queue *q = vblk->disk->queue;
316         char cap_str_2[10], cap_str_10[10];
317         u64 capacity, size;
318
319         /* Host must always specify the capacity. */
320         vdev->config->get(vdev, offsetof(struct virtio_blk_config, capacity),
321                           &capacity, sizeof(capacity));
322
323         /* If capacity is too big, truncate with warning. */
324         if ((sector_t)capacity != capacity) {
325                 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
326                          (unsigned long long)capacity);
327                 capacity = (sector_t)-1;
328         }
329
330         size = capacity * queue_logical_block_size(q);
331         string_get_size(size, STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
332         string_get_size(size, STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
333
334         dev_notice(&vdev->dev,
335                   "new size: %llu %d-byte logical blocks (%s/%s)\n",
336                   (unsigned long long)capacity,
337                   queue_logical_block_size(q),
338                   cap_str_10, cap_str_2);
339
340         set_capacity(vblk->disk, capacity);
341 }
342
343 static void virtblk_config_changed(struct virtio_device *vdev)
344 {
345         struct virtio_blk *vblk = vdev->priv;
346
347         queue_work(virtblk_wq, &vblk->config_work);
348 }
349
350 static int __devinit virtblk_probe(struct virtio_device *vdev)
351 {
352         struct virtio_blk *vblk;
353         struct request_queue *q;
354         int err, index;
355         u64 cap;
356         u32 v, blk_size, sg_elems, opt_io_size;
357         u16 min_io_size;
358         u8 physical_block_exp, alignment_offset;
359
360         err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
361                              GFP_KERNEL);
362         if (err < 0)
363                 goto out;
364         index = err;
365
366         /* We need to know how many segments before we allocate. */
367         err = virtio_config_val(vdev, VIRTIO_BLK_F_SEG_MAX,
368                                 offsetof(struct virtio_blk_config, seg_max),
369                                 &sg_elems);
370
371         /* We need at least one SG element, whatever they say. */
372         if (err || !sg_elems)
373                 sg_elems = 1;
374
375         /* We need an extra sg elements at head and tail. */
376         sg_elems += 2;
377         vdev->priv = vblk = kmalloc(sizeof(*vblk) +
378                                     sizeof(vblk->sg[0]) * sg_elems, GFP_KERNEL);
379         if (!vblk) {
380                 err = -ENOMEM;
381                 goto out_free_index;
382         }
383
384         INIT_LIST_HEAD(&vblk->reqs);
385         vblk->vdev = vdev;
386         vblk->sg_elems = sg_elems;
387         sg_init_table(vblk->sg, vblk->sg_elems);
388         INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
389
390         /* We expect one virtqueue, for output. */
391         vblk->vq = virtio_find_single_vq(vdev, blk_done, "requests");
392         if (IS_ERR(vblk->vq)) {
393                 err = PTR_ERR(vblk->vq);
394                 goto out_free_vblk;
395         }
396
397         vblk->pool = mempool_create_kmalloc_pool(1,sizeof(struct virtblk_req));
398         if (!vblk->pool) {
399                 err = -ENOMEM;
400                 goto out_free_vq;
401         }
402
403         /* FIXME: How many partitions?  How long is a piece of string? */
404         vblk->disk = alloc_disk(1 << PART_BITS);
405         if (!vblk->disk) {
406                 err = -ENOMEM;
407                 goto out_mempool;
408         }
409
410         q = vblk->disk->queue = blk_init_queue(do_virtblk_request, NULL);
411         if (!q) {
412                 err = -ENOMEM;
413                 goto out_put_disk;
414         }
415
416         q->queuedata = vblk;
417
418         if (index < 26) {
419                 sprintf(vblk->disk->disk_name, "vd%c", 'a' + index % 26);
420         } else if (index < (26 + 1) * 26) {
421                 sprintf(vblk->disk->disk_name, "vd%c%c",
422                         'a' + index / 26 - 1, 'a' + index % 26);
423         } else {
424                 const unsigned int m1 = (index / 26 - 1) / 26 - 1;
425                 const unsigned int m2 = (index / 26 - 1) % 26;
426                 const unsigned int m3 =  index % 26;
427                 sprintf(vblk->disk->disk_name, "vd%c%c%c",
428                         'a' + m1, 'a' + m2, 'a' + m3);
429         }
430
431         vblk->disk->major = major;
432         vblk->disk->first_minor = index_to_minor(index);
433         vblk->disk->private_data = vblk;
434         vblk->disk->fops = &virtblk_fops;
435         vblk->disk->driverfs_dev = &vdev->dev;
436         vblk->index = index;
437
438         /* configure queue flush support */
439         if (virtio_has_feature(vdev, VIRTIO_BLK_F_FLUSH))
440                 blk_queue_flush(q, REQ_FLUSH);
441
442         /* If disk is read-only in the host, the guest should obey */
443         if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
444                 set_disk_ro(vblk->disk, 1);
445
446         /* Host must always specify the capacity. */
447         vdev->config->get(vdev, offsetof(struct virtio_blk_config, capacity),
448                           &cap, sizeof(cap));
449
450         /* If capacity is too big, truncate with warning. */
451         if ((sector_t)cap != cap) {
452                 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
453                          (unsigned long long)cap);
454                 cap = (sector_t)-1;
455         }
456         set_capacity(vblk->disk, cap);
457
458         /* We can handle whatever the host told us to handle. */
459         blk_queue_max_segments(q, vblk->sg_elems-2);
460
461         /* No need to bounce any requests */
462         blk_queue_bounce_limit(q, BLK_BOUNCE_ANY);
463
464         /* No real sector limit. */
465         blk_queue_max_hw_sectors(q, -1U);
466
467         /* Host can optionally specify maximum segment size and number of
468          * segments. */
469         err = virtio_config_val(vdev, VIRTIO_BLK_F_SIZE_MAX,
470                                 offsetof(struct virtio_blk_config, size_max),
471                                 &v);
472         if (!err)
473                 blk_queue_max_segment_size(q, v);
474         else
475                 blk_queue_max_segment_size(q, -1U);
476
477         /* Host can optionally specify the block size of the device */
478         err = virtio_config_val(vdev, VIRTIO_BLK_F_BLK_SIZE,
479                                 offsetof(struct virtio_blk_config, blk_size),
480                                 &blk_size);
481         if (!err)
482                 blk_queue_logical_block_size(q, blk_size);
483         else
484                 blk_size = queue_logical_block_size(q);
485
486         /* Use topology information if available */
487         err = virtio_config_val(vdev, VIRTIO_BLK_F_TOPOLOGY,
488                         offsetof(struct virtio_blk_config, physical_block_exp),
489                         &physical_block_exp);
490         if (!err && physical_block_exp)
491                 blk_queue_physical_block_size(q,
492                                 blk_size * (1 << physical_block_exp));
493
494         err = virtio_config_val(vdev, VIRTIO_BLK_F_TOPOLOGY,
495                         offsetof(struct virtio_blk_config, alignment_offset),
496                         &alignment_offset);
497         if (!err && alignment_offset)
498                 blk_queue_alignment_offset(q, blk_size * alignment_offset);
499
500         err = virtio_config_val(vdev, VIRTIO_BLK_F_TOPOLOGY,
501                         offsetof(struct virtio_blk_config, min_io_size),
502                         &min_io_size);
503         if (!err && min_io_size)
504                 blk_queue_io_min(q, blk_size * min_io_size);
505
506         err = virtio_config_val(vdev, VIRTIO_BLK_F_TOPOLOGY,
507                         offsetof(struct virtio_blk_config, opt_io_size),
508                         &opt_io_size);
509         if (!err && opt_io_size)
510                 blk_queue_io_opt(q, blk_size * opt_io_size);
511
512
513         add_disk(vblk->disk);
514         err = device_create_file(disk_to_dev(vblk->disk), &dev_attr_serial);
515         if (err)
516                 goto out_del_disk;
517
518         return 0;
519
520 out_del_disk:
521         del_gendisk(vblk->disk);
522         blk_cleanup_queue(vblk->disk->queue);
523 out_put_disk:
524         put_disk(vblk->disk);
525 out_mempool:
526         mempool_destroy(vblk->pool);
527 out_free_vq:
528         vdev->config->del_vqs(vdev);
529 out_free_vblk:
530         kfree(vblk);
531 out_free_index:
532         ida_simple_remove(&vd_index_ida, index);
533 out:
534         return err;
535 }
536
537 static void __devexit virtblk_remove(struct virtio_device *vdev)
538 {
539         struct virtio_blk *vblk = vdev->priv;
540         int index = vblk->index;
541
542         flush_work(&vblk->config_work);
543
544         /* Nothing should be pending. */
545         BUG_ON(!list_empty(&vblk->reqs));
546
547         /* Stop all the virtqueues. */
548         vdev->config->reset(vdev);
549
550         del_gendisk(vblk->disk);
551         blk_cleanup_queue(vblk->disk->queue);
552         put_disk(vblk->disk);
553         mempool_destroy(vblk->pool);
554         vdev->config->del_vqs(vdev);
555         kfree(vblk);
556         ida_simple_remove(&vd_index_ida, index);
557 }
558
559 static const struct virtio_device_id id_table[] = {
560         { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
561         { 0 },
562 };
563
564 static unsigned int features[] = {
565         VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
566         VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE, VIRTIO_BLK_F_SCSI,
567         VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_TOPOLOGY
568 };
569
570 /*
571  * virtio_blk causes spurious section mismatch warning by
572  * simultaneously referring to a __devinit and a __devexit function.
573  * Use __refdata to avoid this warning.
574  */
575 static struct virtio_driver __refdata virtio_blk = {
576         .feature_table          = features,
577         .feature_table_size     = ARRAY_SIZE(features),
578         .driver.name            = KBUILD_MODNAME,
579         .driver.owner           = THIS_MODULE,
580         .id_table               = id_table,
581         .probe                  = virtblk_probe,
582         .remove                 = __devexit_p(virtblk_remove),
583         .config_changed         = virtblk_config_changed,
584 };
585
586 static int __init init(void)
587 {
588         int error;
589
590         virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
591         if (!virtblk_wq)
592                 return -ENOMEM;
593
594         major = register_blkdev(0, "virtblk");
595         if (major < 0) {
596                 error = major;
597                 goto out_destroy_workqueue;
598         }
599
600         error = register_virtio_driver(&virtio_blk);
601         if (error)
602                 goto out_unregister_blkdev;
603         return 0;
604
605 out_unregister_blkdev:
606         unregister_blkdev(major, "virtblk");
607 out_destroy_workqueue:
608         destroy_workqueue(virtblk_wq);
609         return error;
610 }
611
612 static void __exit fini(void)
613 {
614         unregister_blkdev(major, "virtblk");
615         unregister_virtio_driver(&virtio_blk);
616         destroy_workqueue(virtblk_wq);
617 }
618 module_init(init);
619 module_exit(fini);
620
621 MODULE_DEVICE_TABLE(virtio, id_table);
622 MODULE_DESCRIPTION("Virtio block driver");
623 MODULE_LICENSE("GPL");