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