Merge branch 'kbuild' of git://git.kernel.org/pub/scm/linux/kernel/git/mmarek/kbuild
[cascardo/linux.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/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
15 #define PART_BITS 4
16
17 static bool use_bio;
18 module_param(use_bio, bool, S_IRUGO);
19
20 static int major;
21 static DEFINE_IDA(vd_index_ida);
22
23 static struct workqueue_struct *virtblk_wq;
24
25 struct virtio_blk
26 {
27         struct virtio_device *vdev;
28         struct virtqueue *vq;
29         wait_queue_head_t queue_wait;
30
31         /* The disk structure for the kernel. */
32         struct gendisk *disk;
33
34         mempool_t *pool;
35
36         /* Process context for config space updates */
37         struct work_struct config_work;
38
39         /* Lock for config space updates */
40         struct mutex config_lock;
41
42         /* enable config space updates */
43         bool config_enable;
44
45         /* What host tells us, plus 2 for header & tailer. */
46         unsigned int sg_elems;
47
48         /* Ida index - used to track minor number allocations. */
49         int index;
50
51         /* Scatterlist: can be too big for stack. */
52         struct scatterlist sg[/*sg_elems*/];
53 };
54
55 struct virtblk_req
56 {
57         struct request *req;
58         struct bio *bio;
59         struct virtio_blk_outhdr out_hdr;
60         struct virtio_scsi_inhdr in_hdr;
61         struct work_struct work;
62         struct virtio_blk *vblk;
63         int flags;
64         u8 status;
65         struct scatterlist sg[];
66 };
67
68 enum {
69         VBLK_IS_FLUSH           = 1,
70         VBLK_REQ_FLUSH          = 2,
71         VBLK_REQ_DATA           = 4,
72         VBLK_REQ_FUA            = 8,
73 };
74
75 static inline int virtblk_result(struct virtblk_req *vbr)
76 {
77         switch (vbr->status) {
78         case VIRTIO_BLK_S_OK:
79                 return 0;
80         case VIRTIO_BLK_S_UNSUPP:
81                 return -ENOTTY;
82         default:
83                 return -EIO;
84         }
85 }
86
87 static inline struct virtblk_req *virtblk_alloc_req(struct virtio_blk *vblk,
88                                                     gfp_t gfp_mask)
89 {
90         struct virtblk_req *vbr;
91
92         vbr = mempool_alloc(vblk->pool, gfp_mask);
93         if (!vbr)
94                 return NULL;
95
96         vbr->vblk = vblk;
97         if (use_bio)
98                 sg_init_table(vbr->sg, vblk->sg_elems);
99
100         return vbr;
101 }
102
103 static int __virtblk_add_req(struct virtqueue *vq,
104                              struct virtblk_req *vbr,
105                              struct scatterlist *data_sg,
106                              bool have_data)
107 {
108         struct scatterlist hdr, status, cmd, sense, inhdr, *sgs[6];
109         unsigned int num_out = 0, num_in = 0;
110         int type = vbr->out_hdr.type & ~VIRTIO_BLK_T_OUT;
111
112         sg_init_one(&hdr, &vbr->out_hdr, sizeof(vbr->out_hdr));
113         sgs[num_out++] = &hdr;
114
115         /*
116          * If this is a packet command we need a couple of additional headers.
117          * Behind the normal outhdr we put a segment with the scsi command
118          * block, and before the normal inhdr we put the sense data and the
119          * inhdr with additional status information.
120          */
121         if (type == VIRTIO_BLK_T_SCSI_CMD) {
122                 sg_init_one(&cmd, vbr->req->cmd, vbr->req->cmd_len);
123                 sgs[num_out++] = &cmd;
124         }
125
126         if (have_data) {
127                 if (vbr->out_hdr.type & VIRTIO_BLK_T_OUT)
128                         sgs[num_out++] = data_sg;
129                 else
130                         sgs[num_out + num_in++] = data_sg;
131         }
132
133         if (type == VIRTIO_BLK_T_SCSI_CMD) {
134                 sg_init_one(&sense, vbr->req->sense, SCSI_SENSE_BUFFERSIZE);
135                 sgs[num_out + num_in++] = &sense;
136                 sg_init_one(&inhdr, &vbr->in_hdr, sizeof(vbr->in_hdr));
137                 sgs[num_out + num_in++] = &inhdr;
138         }
139
140         sg_init_one(&status, &vbr->status, sizeof(vbr->status));
141         sgs[num_out + num_in++] = &status;
142
143         return virtqueue_add_sgs(vq, sgs, num_out, num_in, vbr, GFP_ATOMIC);
144 }
145
146 static void virtblk_add_req(struct virtblk_req *vbr, bool have_data)
147 {
148         struct virtio_blk *vblk = vbr->vblk;
149         DEFINE_WAIT(wait);
150         int ret;
151
152         spin_lock_irq(vblk->disk->queue->queue_lock);
153         while (unlikely((ret = __virtblk_add_req(vblk->vq, vbr, vbr->sg,
154                                                  have_data)) < 0)) {
155                 prepare_to_wait_exclusive(&vblk->queue_wait, &wait,
156                                           TASK_UNINTERRUPTIBLE);
157
158                 spin_unlock_irq(vblk->disk->queue->queue_lock);
159                 io_schedule();
160                 spin_lock_irq(vblk->disk->queue->queue_lock);
161
162                 finish_wait(&vblk->queue_wait, &wait);
163         }
164
165         virtqueue_kick(vblk->vq);
166         spin_unlock_irq(vblk->disk->queue->queue_lock);
167 }
168
169 static void virtblk_bio_send_flush(struct virtblk_req *vbr)
170 {
171         vbr->flags |= VBLK_IS_FLUSH;
172         vbr->out_hdr.type = VIRTIO_BLK_T_FLUSH;
173         vbr->out_hdr.sector = 0;
174         vbr->out_hdr.ioprio = 0;
175
176         virtblk_add_req(vbr, false);
177 }
178
179 static void virtblk_bio_send_data(struct virtblk_req *vbr)
180 {
181         struct virtio_blk *vblk = vbr->vblk;
182         struct bio *bio = vbr->bio;
183         bool have_data;
184
185         vbr->flags &= ~VBLK_IS_FLUSH;
186         vbr->out_hdr.type = 0;
187         vbr->out_hdr.sector = bio->bi_sector;
188         vbr->out_hdr.ioprio = bio_prio(bio);
189
190         if (blk_bio_map_sg(vblk->disk->queue, bio, vbr->sg)) {
191                 have_data = true;
192                 if (bio->bi_rw & REQ_WRITE)
193                         vbr->out_hdr.type |= VIRTIO_BLK_T_OUT;
194                 else
195                         vbr->out_hdr.type |= VIRTIO_BLK_T_IN;
196         } else
197                 have_data = false;
198
199         virtblk_add_req(vbr, have_data);
200 }
201
202 static void virtblk_bio_send_data_work(struct work_struct *work)
203 {
204         struct virtblk_req *vbr;
205
206         vbr = container_of(work, struct virtblk_req, work);
207
208         virtblk_bio_send_data(vbr);
209 }
210
211 static void virtblk_bio_send_flush_work(struct work_struct *work)
212 {
213         struct virtblk_req *vbr;
214
215         vbr = container_of(work, struct virtblk_req, work);
216
217         virtblk_bio_send_flush(vbr);
218 }
219
220 static inline void virtblk_request_done(struct virtblk_req *vbr)
221 {
222         struct virtio_blk *vblk = vbr->vblk;
223         struct request *req = vbr->req;
224         int error = virtblk_result(vbr);
225
226         if (req->cmd_type == REQ_TYPE_BLOCK_PC) {
227                 req->resid_len = vbr->in_hdr.residual;
228                 req->sense_len = vbr->in_hdr.sense_len;
229                 req->errors = vbr->in_hdr.errors;
230         } else if (req->cmd_type == REQ_TYPE_SPECIAL) {
231                 req->errors = (error != 0);
232         }
233
234         __blk_end_request_all(req, error);
235         mempool_free(vbr, vblk->pool);
236 }
237
238 static inline void virtblk_bio_flush_done(struct virtblk_req *vbr)
239 {
240         struct virtio_blk *vblk = vbr->vblk;
241
242         if (vbr->flags & VBLK_REQ_DATA) {
243                 /* Send out the actual write data */
244                 INIT_WORK(&vbr->work, virtblk_bio_send_data_work);
245                 queue_work(virtblk_wq, &vbr->work);
246         } else {
247                 bio_endio(vbr->bio, virtblk_result(vbr));
248                 mempool_free(vbr, vblk->pool);
249         }
250 }
251
252 static inline void virtblk_bio_data_done(struct virtblk_req *vbr)
253 {
254         struct virtio_blk *vblk = vbr->vblk;
255
256         if (unlikely(vbr->flags & VBLK_REQ_FUA)) {
257                 /* Send out a flush before end the bio */
258                 vbr->flags &= ~VBLK_REQ_DATA;
259                 INIT_WORK(&vbr->work, virtblk_bio_send_flush_work);
260                 queue_work(virtblk_wq, &vbr->work);
261         } else {
262                 bio_endio(vbr->bio, virtblk_result(vbr));
263                 mempool_free(vbr, vblk->pool);
264         }
265 }
266
267 static inline void virtblk_bio_done(struct virtblk_req *vbr)
268 {
269         if (unlikely(vbr->flags & VBLK_IS_FLUSH))
270                 virtblk_bio_flush_done(vbr);
271         else
272                 virtblk_bio_data_done(vbr);
273 }
274
275 static void virtblk_done(struct virtqueue *vq)
276 {
277         struct virtio_blk *vblk = vq->vdev->priv;
278         bool bio_done = false, req_done = false;
279         struct virtblk_req *vbr;
280         unsigned long flags;
281         unsigned int len;
282
283         spin_lock_irqsave(vblk->disk->queue->queue_lock, flags);
284         do {
285                 virtqueue_disable_cb(vq);
286                 while ((vbr = virtqueue_get_buf(vblk->vq, &len)) != NULL) {
287                         if (vbr->bio) {
288                                 virtblk_bio_done(vbr);
289                                 bio_done = true;
290                         } else {
291                                 virtblk_request_done(vbr);
292                                 req_done = true;
293                         }
294                 }
295                 if (unlikely(virtqueue_is_broken(vq)))
296                         break;
297         } while (!virtqueue_enable_cb(vq));
298         /* In case queue is stopped waiting for more buffers. */
299         if (req_done)
300                 blk_start_queue(vblk->disk->queue);
301         spin_unlock_irqrestore(vblk->disk->queue->queue_lock, flags);
302
303         if (bio_done)
304                 wake_up(&vblk->queue_wait);
305 }
306
307 static bool do_req(struct request_queue *q, struct virtio_blk *vblk,
308                    struct request *req)
309 {
310         unsigned int num;
311         struct virtblk_req *vbr;
312
313         vbr = virtblk_alloc_req(vblk, GFP_ATOMIC);
314         if (!vbr)
315                 /* When another request finishes we'll try again. */
316                 return false;
317
318         vbr->req = req;
319         vbr->bio = NULL;
320         if (req->cmd_flags & REQ_FLUSH) {
321                 vbr->out_hdr.type = VIRTIO_BLK_T_FLUSH;
322                 vbr->out_hdr.sector = 0;
323                 vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
324         } else {
325                 switch (req->cmd_type) {
326                 case REQ_TYPE_FS:
327                         vbr->out_hdr.type = 0;
328                         vbr->out_hdr.sector = blk_rq_pos(vbr->req);
329                         vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
330                         break;
331                 case REQ_TYPE_BLOCK_PC:
332                         vbr->out_hdr.type = VIRTIO_BLK_T_SCSI_CMD;
333                         vbr->out_hdr.sector = 0;
334                         vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
335                         break;
336                 case REQ_TYPE_SPECIAL:
337                         vbr->out_hdr.type = VIRTIO_BLK_T_GET_ID;
338                         vbr->out_hdr.sector = 0;
339                         vbr->out_hdr.ioprio = req_get_ioprio(vbr->req);
340                         break;
341                 default:
342                         /* We don't put anything else in the queue. */
343                         BUG();
344                 }
345         }
346
347         num = blk_rq_map_sg(q, vbr->req, vblk->sg);
348         if (num) {
349                 if (rq_data_dir(vbr->req) == WRITE)
350                         vbr->out_hdr.type |= VIRTIO_BLK_T_OUT;
351                 else
352                         vbr->out_hdr.type |= VIRTIO_BLK_T_IN;
353         }
354
355         if (__virtblk_add_req(vblk->vq, vbr, vblk->sg, num) < 0) {
356                 mempool_free(vbr, vblk->pool);
357                 return false;
358         }
359
360         return true;
361 }
362
363 static void virtblk_request(struct request_queue *q)
364 {
365         struct virtio_blk *vblk = q->queuedata;
366         struct request *req;
367         unsigned int issued = 0;
368
369         while ((req = blk_peek_request(q)) != NULL) {
370                 BUG_ON(req->nr_phys_segments + 2 > vblk->sg_elems);
371
372                 /* If this request fails, stop queue and wait for something to
373                    finish to restart it. */
374                 if (!do_req(q, vblk, req)) {
375                         blk_stop_queue(q);
376                         break;
377                 }
378                 blk_start_request(req);
379                 issued++;
380         }
381
382         if (issued)
383                 virtqueue_kick(vblk->vq);
384 }
385
386 static void virtblk_make_request(struct request_queue *q, struct bio *bio)
387 {
388         struct virtio_blk *vblk = q->queuedata;
389         struct virtblk_req *vbr;
390
391         BUG_ON(bio->bi_phys_segments + 2 > vblk->sg_elems);
392
393         vbr = virtblk_alloc_req(vblk, GFP_NOIO);
394         if (!vbr) {
395                 bio_endio(bio, -ENOMEM);
396                 return;
397         }
398
399         vbr->bio = bio;
400         vbr->flags = 0;
401         if (bio->bi_rw & REQ_FLUSH)
402                 vbr->flags |= VBLK_REQ_FLUSH;
403         if (bio->bi_rw & REQ_FUA)
404                 vbr->flags |= VBLK_REQ_FUA;
405         if (bio->bi_size)
406                 vbr->flags |= VBLK_REQ_DATA;
407
408         if (unlikely(vbr->flags & VBLK_REQ_FLUSH))
409                 virtblk_bio_send_flush(vbr);
410         else
411                 virtblk_bio_send_data(vbr);
412 }
413
414 /* return id (s/n) string for *disk to *id_str
415  */
416 static int virtblk_get_id(struct gendisk *disk, char *id_str)
417 {
418         struct virtio_blk *vblk = disk->private_data;
419         struct request *req;
420         struct bio *bio;
421         int err;
422
423         bio = bio_map_kern(vblk->disk->queue, id_str, VIRTIO_BLK_ID_BYTES,
424                            GFP_KERNEL);
425         if (IS_ERR(bio))
426                 return PTR_ERR(bio);
427
428         req = blk_make_request(vblk->disk->queue, bio, GFP_KERNEL);
429         if (IS_ERR(req)) {
430                 bio_put(bio);
431                 return PTR_ERR(req);
432         }
433
434         req->cmd_type = REQ_TYPE_SPECIAL;
435         err = blk_execute_rq(vblk->disk->queue, vblk->disk, req, false);
436         blk_put_request(req);
437
438         return err;
439 }
440
441 static int virtblk_ioctl(struct block_device *bdev, fmode_t mode,
442                              unsigned int cmd, unsigned long data)
443 {
444         struct gendisk *disk = bdev->bd_disk;
445         struct virtio_blk *vblk = disk->private_data;
446
447         /*
448          * Only allow the generic SCSI ioctls if the host can support it.
449          */
450         if (!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_SCSI))
451                 return -ENOTTY;
452
453         return scsi_cmd_blk_ioctl(bdev, mode, cmd,
454                                   (void __user *)data);
455 }
456
457 /* We provide getgeo only to please some old bootloader/partitioning tools */
458 static int virtblk_getgeo(struct block_device *bd, struct hd_geometry *geo)
459 {
460         struct virtio_blk *vblk = bd->bd_disk->private_data;
461
462         /* see if the host passed in geometry config */
463         if (virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_GEOMETRY)) {
464                 virtio_cread(vblk->vdev, struct virtio_blk_config,
465                              geometry.cylinders, &geo->cylinders);
466                 virtio_cread(vblk->vdev, struct virtio_blk_config,
467                              geometry.heads, &geo->heads);
468                 virtio_cread(vblk->vdev, struct virtio_blk_config,
469                              geometry.sectors, &geo->sectors);
470         } else {
471                 /* some standard values, similar to sd */
472                 geo->heads = 1 << 6;
473                 geo->sectors = 1 << 5;
474                 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
475         }
476         return 0;
477 }
478
479 static const struct block_device_operations virtblk_fops = {
480         .ioctl  = virtblk_ioctl,
481         .owner  = THIS_MODULE,
482         .getgeo = virtblk_getgeo,
483 };
484
485 static int index_to_minor(int index)
486 {
487         return index << PART_BITS;
488 }
489
490 static int minor_to_index(int minor)
491 {
492         return minor >> PART_BITS;
493 }
494
495 static ssize_t virtblk_serial_show(struct device *dev,
496                                 struct device_attribute *attr, char *buf)
497 {
498         struct gendisk *disk = dev_to_disk(dev);
499         int err;
500
501         /* sysfs gives us a PAGE_SIZE buffer */
502         BUILD_BUG_ON(PAGE_SIZE < VIRTIO_BLK_ID_BYTES);
503
504         buf[VIRTIO_BLK_ID_BYTES] = '\0';
505         err = virtblk_get_id(disk, buf);
506         if (!err)
507                 return strlen(buf);
508
509         if (err == -EIO) /* Unsupported? Make it empty. */
510                 return 0;
511
512         return err;
513 }
514 DEVICE_ATTR(serial, S_IRUGO, virtblk_serial_show, NULL);
515
516 static void virtblk_config_changed_work(struct work_struct *work)
517 {
518         struct virtio_blk *vblk =
519                 container_of(work, struct virtio_blk, config_work);
520         struct virtio_device *vdev = vblk->vdev;
521         struct request_queue *q = vblk->disk->queue;
522         char cap_str_2[10], cap_str_10[10];
523         char *envp[] = { "RESIZE=1", NULL };
524         u64 capacity, size;
525
526         mutex_lock(&vblk->config_lock);
527         if (!vblk->config_enable)
528                 goto done;
529
530         /* Host must always specify the capacity. */
531         virtio_cread(vdev, struct virtio_blk_config, capacity, &capacity);
532
533         /* If capacity is too big, truncate with warning. */
534         if ((sector_t)capacity != capacity) {
535                 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
536                          (unsigned long long)capacity);
537                 capacity = (sector_t)-1;
538         }
539
540         size = capacity * queue_logical_block_size(q);
541         string_get_size(size, STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
542         string_get_size(size, STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
543
544         dev_notice(&vdev->dev,
545                   "new size: %llu %d-byte logical blocks (%s/%s)\n",
546                   (unsigned long long)capacity,
547                   queue_logical_block_size(q),
548                   cap_str_10, cap_str_2);
549
550         set_capacity(vblk->disk, capacity);
551         revalidate_disk(vblk->disk);
552         kobject_uevent_env(&disk_to_dev(vblk->disk)->kobj, KOBJ_CHANGE, envp);
553 done:
554         mutex_unlock(&vblk->config_lock);
555 }
556
557 static void virtblk_config_changed(struct virtio_device *vdev)
558 {
559         struct virtio_blk *vblk = vdev->priv;
560
561         queue_work(virtblk_wq, &vblk->config_work);
562 }
563
564 static int init_vq(struct virtio_blk *vblk)
565 {
566         int err = 0;
567
568         /* We expect one virtqueue, for output. */
569         vblk->vq = virtio_find_single_vq(vblk->vdev, virtblk_done, "requests");
570         if (IS_ERR(vblk->vq))
571                 err = PTR_ERR(vblk->vq);
572
573         return err;
574 }
575
576 /*
577  * Legacy naming scheme used for virtio devices.  We are stuck with it for
578  * virtio blk but don't ever use it for any new driver.
579  */
580 static int virtblk_name_format(char *prefix, int index, char *buf, int buflen)
581 {
582         const int base = 'z' - 'a' + 1;
583         char *begin = buf + strlen(prefix);
584         char *end = buf + buflen;
585         char *p;
586         int unit;
587
588         p = end - 1;
589         *p = '\0';
590         unit = base;
591         do {
592                 if (p == begin)
593                         return -EINVAL;
594                 *--p = 'a' + (index % unit);
595                 index = (index / unit) - 1;
596         } while (index >= 0);
597
598         memmove(begin, p, end - p);
599         memcpy(buf, prefix, strlen(prefix));
600
601         return 0;
602 }
603
604 static int virtblk_get_cache_mode(struct virtio_device *vdev)
605 {
606         u8 writeback;
607         int err;
608
609         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE,
610                                    struct virtio_blk_config, wce,
611                                    &writeback);
612         if (err)
613                 writeback = virtio_has_feature(vdev, VIRTIO_BLK_F_WCE);
614
615         return writeback;
616 }
617
618 static void virtblk_update_cache_mode(struct virtio_device *vdev)
619 {
620         u8 writeback = virtblk_get_cache_mode(vdev);
621         struct virtio_blk *vblk = vdev->priv;
622
623         if (writeback)
624                 blk_queue_flush(vblk->disk->queue, REQ_FLUSH);
625         else
626                 blk_queue_flush(vblk->disk->queue, 0);
627
628         revalidate_disk(vblk->disk);
629 }
630
631 static const char *const virtblk_cache_types[] = {
632         "write through", "write back"
633 };
634
635 static ssize_t
636 virtblk_cache_type_store(struct device *dev, struct device_attribute *attr,
637                          const char *buf, size_t count)
638 {
639         struct gendisk *disk = dev_to_disk(dev);
640         struct virtio_blk *vblk = disk->private_data;
641         struct virtio_device *vdev = vblk->vdev;
642         int i;
643
644         BUG_ON(!virtio_has_feature(vblk->vdev, VIRTIO_BLK_F_CONFIG_WCE));
645         for (i = ARRAY_SIZE(virtblk_cache_types); --i >= 0; )
646                 if (sysfs_streq(buf, virtblk_cache_types[i]))
647                         break;
648
649         if (i < 0)
650                 return -EINVAL;
651
652         virtio_cwrite8(vdev, offsetof(struct virtio_blk_config, wce), i);
653         virtblk_update_cache_mode(vdev);
654         return count;
655 }
656
657 static ssize_t
658 virtblk_cache_type_show(struct device *dev, struct device_attribute *attr,
659                          char *buf)
660 {
661         struct gendisk *disk = dev_to_disk(dev);
662         struct virtio_blk *vblk = disk->private_data;
663         u8 writeback = virtblk_get_cache_mode(vblk->vdev);
664
665         BUG_ON(writeback >= ARRAY_SIZE(virtblk_cache_types));
666         return snprintf(buf, 40, "%s\n", virtblk_cache_types[writeback]);
667 }
668
669 static const struct device_attribute dev_attr_cache_type_ro =
670         __ATTR(cache_type, S_IRUGO,
671                virtblk_cache_type_show, NULL);
672 static const struct device_attribute dev_attr_cache_type_rw =
673         __ATTR(cache_type, S_IRUGO|S_IWUSR,
674                virtblk_cache_type_show, virtblk_cache_type_store);
675
676 static int virtblk_probe(struct virtio_device *vdev)
677 {
678         struct virtio_blk *vblk;
679         struct request_queue *q;
680         int err, index;
681         int pool_size;
682
683         u64 cap;
684         u32 v, blk_size, sg_elems, opt_io_size;
685         u16 min_io_size;
686         u8 physical_block_exp, alignment_offset;
687
688         err = ida_simple_get(&vd_index_ida, 0, minor_to_index(1 << MINORBITS),
689                              GFP_KERNEL);
690         if (err < 0)
691                 goto out;
692         index = err;
693
694         /* We need to know how many segments before we allocate. */
695         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
696                                    struct virtio_blk_config, seg_max,
697                                    &sg_elems);
698
699         /* We need at least one SG element, whatever they say. */
700         if (err || !sg_elems)
701                 sg_elems = 1;
702
703         /* We need an extra sg elements at head and tail. */
704         sg_elems += 2;
705         vdev->priv = vblk = kmalloc(sizeof(*vblk) +
706                                     sizeof(vblk->sg[0]) * sg_elems, GFP_KERNEL);
707         if (!vblk) {
708                 err = -ENOMEM;
709                 goto out_free_index;
710         }
711
712         init_waitqueue_head(&vblk->queue_wait);
713         vblk->vdev = vdev;
714         vblk->sg_elems = sg_elems;
715         sg_init_table(vblk->sg, vblk->sg_elems);
716         mutex_init(&vblk->config_lock);
717
718         INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
719         vblk->config_enable = true;
720
721         err = init_vq(vblk);
722         if (err)
723                 goto out_free_vblk;
724
725         pool_size = sizeof(struct virtblk_req);
726         if (use_bio)
727                 pool_size += sizeof(struct scatterlist) * sg_elems;
728         vblk->pool = mempool_create_kmalloc_pool(1, pool_size);
729         if (!vblk->pool) {
730                 err = -ENOMEM;
731                 goto out_free_vq;
732         }
733
734         /* FIXME: How many partitions?  How long is a piece of string? */
735         vblk->disk = alloc_disk(1 << PART_BITS);
736         if (!vblk->disk) {
737                 err = -ENOMEM;
738                 goto out_mempool;
739         }
740
741         q = vblk->disk->queue = blk_init_queue(virtblk_request, NULL);
742         if (!q) {
743                 err = -ENOMEM;
744                 goto out_put_disk;
745         }
746
747         if (use_bio)
748                 blk_queue_make_request(q, virtblk_make_request);
749         q->queuedata = vblk;
750
751         virtblk_name_format("vd", index, vblk->disk->disk_name, DISK_NAME_LEN);
752
753         vblk->disk->major = major;
754         vblk->disk->first_minor = index_to_minor(index);
755         vblk->disk->private_data = vblk;
756         vblk->disk->fops = &virtblk_fops;
757         vblk->disk->driverfs_dev = &vdev->dev;
758         vblk->index = index;
759
760         /* configure queue flush support */
761         virtblk_update_cache_mode(vdev);
762
763         /* If disk is read-only in the host, the guest should obey */
764         if (virtio_has_feature(vdev, VIRTIO_BLK_F_RO))
765                 set_disk_ro(vblk->disk, 1);
766
767         /* Host must always specify the capacity. */
768         virtio_cread(vdev, struct virtio_blk_config, capacity, &cap);
769
770         /* If capacity is too big, truncate with warning. */
771         if ((sector_t)cap != cap) {
772                 dev_warn(&vdev->dev, "Capacity %llu too large: truncating\n",
773                          (unsigned long long)cap);
774                 cap = (sector_t)-1;
775         }
776         set_capacity(vblk->disk, cap);
777
778         /* We can handle whatever the host told us to handle. */
779         blk_queue_max_segments(q, vblk->sg_elems-2);
780
781         /* No need to bounce any requests */
782         blk_queue_bounce_limit(q, BLK_BOUNCE_ANY);
783
784         /* No real sector limit. */
785         blk_queue_max_hw_sectors(q, -1U);
786
787         /* Host can optionally specify maximum segment size and number of
788          * segments. */
789         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SIZE_MAX,
790                                    struct virtio_blk_config, size_max, &v);
791         if (!err)
792                 blk_queue_max_segment_size(q, v);
793         else
794                 blk_queue_max_segment_size(q, -1U);
795
796         /* Host can optionally specify the block size of the device */
797         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_BLK_SIZE,
798                                    struct virtio_blk_config, blk_size,
799                                    &blk_size);
800         if (!err)
801                 blk_queue_logical_block_size(q, blk_size);
802         else
803                 blk_size = queue_logical_block_size(q);
804
805         /* Use topology information if available */
806         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
807                                    struct virtio_blk_config, physical_block_exp,
808                                    &physical_block_exp);
809         if (!err && physical_block_exp)
810                 blk_queue_physical_block_size(q,
811                                 blk_size * (1 << physical_block_exp));
812
813         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
814                                    struct virtio_blk_config, alignment_offset,
815                                    &alignment_offset);
816         if (!err && alignment_offset)
817                 blk_queue_alignment_offset(q, blk_size * alignment_offset);
818
819         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
820                                    struct virtio_blk_config, min_io_size,
821                                    &min_io_size);
822         if (!err && min_io_size)
823                 blk_queue_io_min(q, blk_size * min_io_size);
824
825         err = virtio_cread_feature(vdev, VIRTIO_BLK_F_TOPOLOGY,
826                                    struct virtio_blk_config, opt_io_size,
827                                    &opt_io_size);
828         if (!err && opt_io_size)
829                 blk_queue_io_opt(q, blk_size * opt_io_size);
830
831         add_disk(vblk->disk);
832         err = device_create_file(disk_to_dev(vblk->disk), &dev_attr_serial);
833         if (err)
834                 goto out_del_disk;
835
836         if (virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE))
837                 err = device_create_file(disk_to_dev(vblk->disk),
838                                          &dev_attr_cache_type_rw);
839         else
840                 err = device_create_file(disk_to_dev(vblk->disk),
841                                          &dev_attr_cache_type_ro);
842         if (err)
843                 goto out_del_disk;
844         return 0;
845
846 out_del_disk:
847         del_gendisk(vblk->disk);
848         blk_cleanup_queue(vblk->disk->queue);
849 out_put_disk:
850         put_disk(vblk->disk);
851 out_mempool:
852         mempool_destroy(vblk->pool);
853 out_free_vq:
854         vdev->config->del_vqs(vdev);
855 out_free_vblk:
856         kfree(vblk);
857 out_free_index:
858         ida_simple_remove(&vd_index_ida, index);
859 out:
860         return err;
861 }
862
863 static void virtblk_remove(struct virtio_device *vdev)
864 {
865         struct virtio_blk *vblk = vdev->priv;
866         int index = vblk->index;
867         int refc;
868
869         /* Prevent config work handler from accessing the device. */
870         mutex_lock(&vblk->config_lock);
871         vblk->config_enable = false;
872         mutex_unlock(&vblk->config_lock);
873
874         del_gendisk(vblk->disk);
875         blk_cleanup_queue(vblk->disk->queue);
876
877         /* Stop all the virtqueues. */
878         vdev->config->reset(vdev);
879
880         flush_work(&vblk->config_work);
881
882         refc = atomic_read(&disk_to_dev(vblk->disk)->kobj.kref.refcount);
883         put_disk(vblk->disk);
884         mempool_destroy(vblk->pool);
885         vdev->config->del_vqs(vdev);
886         kfree(vblk);
887
888         /* Only free device id if we don't have any users */
889         if (refc == 1)
890                 ida_simple_remove(&vd_index_ida, index);
891 }
892
893 #ifdef CONFIG_PM_SLEEP
894 static int virtblk_freeze(struct virtio_device *vdev)
895 {
896         struct virtio_blk *vblk = vdev->priv;
897
898         /* Ensure we don't receive any more interrupts */
899         vdev->config->reset(vdev);
900
901         /* Prevent config work handler from accessing the device. */
902         mutex_lock(&vblk->config_lock);
903         vblk->config_enable = false;
904         mutex_unlock(&vblk->config_lock);
905
906         flush_work(&vblk->config_work);
907
908         spin_lock_irq(vblk->disk->queue->queue_lock);
909         blk_stop_queue(vblk->disk->queue);
910         spin_unlock_irq(vblk->disk->queue->queue_lock);
911         blk_sync_queue(vblk->disk->queue);
912
913         vdev->config->del_vqs(vdev);
914         return 0;
915 }
916
917 static int virtblk_restore(struct virtio_device *vdev)
918 {
919         struct virtio_blk *vblk = vdev->priv;
920         int ret;
921
922         vblk->config_enable = true;
923         ret = init_vq(vdev->priv);
924         if (!ret) {
925                 spin_lock_irq(vblk->disk->queue->queue_lock);
926                 blk_start_queue(vblk->disk->queue);
927                 spin_unlock_irq(vblk->disk->queue->queue_lock);
928         }
929         return ret;
930 }
931 #endif
932
933 static const struct virtio_device_id id_table[] = {
934         { VIRTIO_ID_BLOCK, VIRTIO_DEV_ANY_ID },
935         { 0 },
936 };
937
938 static unsigned int features[] = {
939         VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_SIZE_MAX, VIRTIO_BLK_F_GEOMETRY,
940         VIRTIO_BLK_F_RO, VIRTIO_BLK_F_BLK_SIZE, VIRTIO_BLK_F_SCSI,
941         VIRTIO_BLK_F_WCE, VIRTIO_BLK_F_TOPOLOGY, VIRTIO_BLK_F_CONFIG_WCE
942 };
943
944 static struct virtio_driver virtio_blk = {
945         .feature_table          = features,
946         .feature_table_size     = ARRAY_SIZE(features),
947         .driver.name            = KBUILD_MODNAME,
948         .driver.owner           = THIS_MODULE,
949         .id_table               = id_table,
950         .probe                  = virtblk_probe,
951         .remove                 = virtblk_remove,
952         .config_changed         = virtblk_config_changed,
953 #ifdef CONFIG_PM_SLEEP
954         .freeze                 = virtblk_freeze,
955         .restore                = virtblk_restore,
956 #endif
957 };
958
959 static int __init init(void)
960 {
961         int error;
962
963         virtblk_wq = alloc_workqueue("virtio-blk", 0, 0);
964         if (!virtblk_wq)
965                 return -ENOMEM;
966
967         major = register_blkdev(0, "virtblk");
968         if (major < 0) {
969                 error = major;
970                 goto out_destroy_workqueue;
971         }
972
973         error = register_virtio_driver(&virtio_blk);
974         if (error)
975                 goto out_unregister_blkdev;
976         return 0;
977
978 out_unregister_blkdev:
979         unregister_blkdev(major, "virtblk");
980 out_destroy_workqueue:
981         destroy_workqueue(virtblk_wq);
982         return error;
983 }
984
985 static void __exit fini(void)
986 {
987         unregister_blkdev(major, "virtblk");
988         unregister_virtio_driver(&virtio_blk);
989         destroy_workqueue(virtblk_wq);
990 }
991 module_init(init);
992 module_exit(fini);
993
994 MODULE_DEVICE_TABLE(virtio, id_table);
995 MODULE_DESCRIPTION("Virtio block driver");
996 MODULE_LICENSE("GPL");