]> Pileus Git - ~andy/linux/blob - drivers/block/xen-blkfront.c
67d9bfab59fa53a395f7c2c397827d6322767f17
[~andy/linux] / drivers / block / xen-blkfront.c
1 /*
2  * blkfront.c
3  *
4  * XenLinux virtual block device driver.
5  *
6  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
7  * Modifications by Mark A. Williamson are (c) Intel Research Cambridge
8  * Copyright (c) 2004, Christian Limpach
9  * Copyright (c) 2004, Andrew Warfield
10  * Copyright (c) 2005, Christopher Clark
11  * Copyright (c) 2005, XenSource Ltd
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License version 2
15  * as published by the Free Software Foundation; or, when distributed
16  * separately from the Linux kernel or incorporated into other
17  * software packages, subject to the following license:
18  *
19  * Permission is hereby granted, free of charge, to any person obtaining a copy
20  * of this source file (the "Software"), to deal in the Software without
21  * restriction, including without limitation the rights to use, copy, modify,
22  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
23  * and to permit persons to whom the Software is furnished to do so, subject to
24  * the following conditions:
25  *
26  * The above copyright notice and this permission notice shall be included in
27  * all copies or substantial portions of the Software.
28  *
29  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
34  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
35  * IN THE SOFTWARE.
36  */
37
38 #include <linux/interrupt.h>
39 #include <linux/blkdev.h>
40 #include <linux/hdreg.h>
41 #include <linux/cdrom.h>
42 #include <linux/module.h>
43 #include <linux/slab.h>
44 #include <linux/smp_lock.h>
45 #include <linux/scatterlist.h>
46
47 #include <xen/xen.h>
48 #include <xen/xenbus.h>
49 #include <xen/grant_table.h>
50 #include <xen/events.h>
51 #include <xen/page.h>
52
53 #include <xen/interface/grant_table.h>
54 #include <xen/interface/io/blkif.h>
55 #include <xen/interface/io/protocols.h>
56
57 #include <asm/xen/hypervisor.h>
58
59 enum blkif_state {
60         BLKIF_STATE_DISCONNECTED,
61         BLKIF_STATE_CONNECTED,
62         BLKIF_STATE_SUSPENDED,
63 };
64
65 struct blk_shadow {
66         struct blkif_request req;
67         unsigned long request;
68         unsigned long frame[BLKIF_MAX_SEGMENTS_PER_REQUEST];
69 };
70
71 static const struct block_device_operations xlvbd_block_fops;
72
73 #define BLK_RING_SIZE __RING_SIZE((struct blkif_sring *)0, PAGE_SIZE)
74
75 /*
76  * We have one of these per vbd, whether ide, scsi or 'other'.  They
77  * hang in private_data off the gendisk structure. We may end up
78  * putting all kinds of interesting stuff here :-)
79  */
80 struct blkfront_info
81 {
82         struct mutex mutex;
83         struct xenbus_device *xbdev;
84         struct gendisk *gd;
85         int vdevice;
86         blkif_vdev_t handle;
87         enum blkif_state connected;
88         int ring_ref;
89         struct blkif_front_ring ring;
90         struct scatterlist sg[BLKIF_MAX_SEGMENTS_PER_REQUEST];
91         unsigned int evtchn, irq;
92         struct request_queue *rq;
93         struct work_struct work;
94         struct gnttab_free_callback callback;
95         struct blk_shadow shadow[BLK_RING_SIZE];
96         unsigned long shadow_free;
97         int feature_barrier;
98         int is_ready;
99 };
100
101 static DEFINE_SPINLOCK(blkif_io_lock);
102
103 static unsigned int nr_minors;
104 static unsigned long *minors;
105 static DEFINE_SPINLOCK(minor_lock);
106
107 #define MAXIMUM_OUTSTANDING_BLOCK_REQS \
108         (BLKIF_MAX_SEGMENTS_PER_REQUEST * BLK_RING_SIZE)
109 #define GRANT_INVALID_REF       0
110
111 #define PARTS_PER_DISK          16
112 #define PARTS_PER_EXT_DISK      256
113
114 #define BLKIF_MAJOR(dev) ((dev)>>8)
115 #define BLKIF_MINOR(dev) ((dev) & 0xff)
116
117 #define EXT_SHIFT 28
118 #define EXTENDED (1<<EXT_SHIFT)
119 #define VDEV_IS_EXTENDED(dev) ((dev)&(EXTENDED))
120 #define BLKIF_MINOR_EXT(dev) ((dev)&(~EXTENDED))
121
122 #define DEV_NAME        "xvd"   /* name in /dev */
123
124 static int get_id_from_freelist(struct blkfront_info *info)
125 {
126         unsigned long free = info->shadow_free;
127         BUG_ON(free >= BLK_RING_SIZE);
128         info->shadow_free = info->shadow[free].req.id;
129         info->shadow[free].req.id = 0x0fffffee; /* debug */
130         return free;
131 }
132
133 static void add_id_to_freelist(struct blkfront_info *info,
134                                unsigned long id)
135 {
136         info->shadow[id].req.id  = info->shadow_free;
137         info->shadow[id].request = 0;
138         info->shadow_free = id;
139 }
140
141 static int xlbd_reserve_minors(unsigned int minor, unsigned int nr)
142 {
143         unsigned int end = minor + nr;
144         int rc;
145
146         if (end > nr_minors) {
147                 unsigned long *bitmap, *old;
148
149                 bitmap = kzalloc(BITS_TO_LONGS(end) * sizeof(*bitmap),
150                                  GFP_KERNEL);
151                 if (bitmap == NULL)
152                         return -ENOMEM;
153
154                 spin_lock(&minor_lock);
155                 if (end > nr_minors) {
156                         old = minors;
157                         memcpy(bitmap, minors,
158                                BITS_TO_LONGS(nr_minors) * sizeof(*bitmap));
159                         minors = bitmap;
160                         nr_minors = BITS_TO_LONGS(end) * BITS_PER_LONG;
161                 } else
162                         old = bitmap;
163                 spin_unlock(&minor_lock);
164                 kfree(old);
165         }
166
167         spin_lock(&minor_lock);
168         if (find_next_bit(minors, end, minor) >= end) {
169                 for (; minor < end; ++minor)
170                         __set_bit(minor, minors);
171                 rc = 0;
172         } else
173                 rc = -EBUSY;
174         spin_unlock(&minor_lock);
175
176         return rc;
177 }
178
179 static void xlbd_release_minors(unsigned int minor, unsigned int nr)
180 {
181         unsigned int end = minor + nr;
182
183         BUG_ON(end > nr_minors);
184         spin_lock(&minor_lock);
185         for (; minor < end; ++minor)
186                 __clear_bit(minor, minors);
187         spin_unlock(&minor_lock);
188 }
189
190 static void blkif_restart_queue_callback(void *arg)
191 {
192         struct blkfront_info *info = (struct blkfront_info *)arg;
193         schedule_work(&info->work);
194 }
195
196 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
197 {
198         /* We don't have real geometry info, but let's at least return
199            values consistent with the size of the device */
200         sector_t nsect = get_capacity(bd->bd_disk);
201         sector_t cylinders = nsect;
202
203         hg->heads = 0xff;
204         hg->sectors = 0x3f;
205         sector_div(cylinders, hg->heads * hg->sectors);
206         hg->cylinders = cylinders;
207         if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
208                 hg->cylinders = 0xffff;
209         return 0;
210 }
211
212 static int blkif_ioctl(struct block_device *bdev, fmode_t mode,
213                        unsigned command, unsigned long argument)
214 {
215         struct blkfront_info *info = bdev->bd_disk->private_data;
216         int i;
217
218         dev_dbg(&info->xbdev->dev, "command: 0x%x, argument: 0x%lx\n",
219                 command, (long)argument);
220
221         switch (command) {
222         case CDROMMULTISESSION:
223                 dev_dbg(&info->xbdev->dev, "FIXME: support multisession CDs later\n");
224                 for (i = 0; i < sizeof(struct cdrom_multisession); i++)
225                         if (put_user(0, (char __user *)(argument + i)))
226                                 return -EFAULT;
227                 return 0;
228
229         case CDROM_GET_CAPABILITY: {
230                 struct gendisk *gd = info->gd;
231                 if (gd->flags & GENHD_FL_CD)
232                         return 0;
233                 return -EINVAL;
234         }
235
236         default:
237                 /*printk(KERN_ALERT "ioctl %08x not supported by Xen blkdev\n",
238                   command);*/
239                 return -EINVAL; /* same return as native Linux */
240         }
241
242         return 0;
243 }
244
245 /*
246  * blkif_queue_request
247  *
248  * request block io
249  *
250  * id: for guest use only.
251  * operation: BLKIF_OP_{READ,WRITE,PROBE}
252  * buffer: buffer to read/write into. this should be a
253  *   virtual address in the guest os.
254  */
255 static int blkif_queue_request(struct request *req)
256 {
257         struct blkfront_info *info = req->rq_disk->private_data;
258         unsigned long buffer_mfn;
259         struct blkif_request *ring_req;
260         unsigned long id;
261         unsigned int fsect, lsect;
262         int i, ref;
263         grant_ref_t gref_head;
264         struct scatterlist *sg;
265
266         if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
267                 return 1;
268
269         if (gnttab_alloc_grant_references(
270                 BLKIF_MAX_SEGMENTS_PER_REQUEST, &gref_head) < 0) {
271                 gnttab_request_free_callback(
272                         &info->callback,
273                         blkif_restart_queue_callback,
274                         info,
275                         BLKIF_MAX_SEGMENTS_PER_REQUEST);
276                 return 1;
277         }
278
279         /* Fill out a communications ring structure. */
280         ring_req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
281         id = get_id_from_freelist(info);
282         info->shadow[id].request = (unsigned long)req;
283
284         ring_req->id = id;
285         ring_req->sector_number = (blkif_sector_t)blk_rq_pos(req);
286         ring_req->handle = info->handle;
287
288         ring_req->operation = rq_data_dir(req) ?
289                 BLKIF_OP_WRITE : BLKIF_OP_READ;
290         if (req->cmd_flags & REQ_HARDBARRIER)
291                 ring_req->operation = BLKIF_OP_WRITE_BARRIER;
292
293         ring_req->nr_segments = blk_rq_map_sg(req->q, req, info->sg);
294         BUG_ON(ring_req->nr_segments > BLKIF_MAX_SEGMENTS_PER_REQUEST);
295
296         for_each_sg(info->sg, sg, ring_req->nr_segments, i) {
297                 buffer_mfn = pfn_to_mfn(page_to_pfn(sg_page(sg)));
298                 fsect = sg->offset >> 9;
299                 lsect = fsect + (sg->length >> 9) - 1;
300                 /* install a grant reference. */
301                 ref = gnttab_claim_grant_reference(&gref_head);
302                 BUG_ON(ref == -ENOSPC);
303
304                 gnttab_grant_foreign_access_ref(
305                                 ref,
306                                 info->xbdev->otherend_id,
307                                 buffer_mfn,
308                                 rq_data_dir(req) );
309
310                 info->shadow[id].frame[i] = mfn_to_pfn(buffer_mfn);
311                 ring_req->seg[i] =
312                                 (struct blkif_request_segment) {
313                                         .gref       = ref,
314                                         .first_sect = fsect,
315                                         .last_sect  = lsect };
316         }
317
318         info->ring.req_prod_pvt++;
319
320         /* Keep a private copy so we can reissue requests when recovering. */
321         info->shadow[id].req = *ring_req;
322
323         gnttab_free_grant_references(gref_head);
324
325         return 0;
326 }
327
328
329 static inline void flush_requests(struct blkfront_info *info)
330 {
331         int notify;
332
333         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
334
335         if (notify)
336                 notify_remote_via_irq(info->irq);
337 }
338
339 /*
340  * do_blkif_request
341  *  read a block; request is in a request queue
342  */
343 static void do_blkif_request(struct request_queue *rq)
344 {
345         struct blkfront_info *info = NULL;
346         struct request *req;
347         int queued;
348
349         pr_debug("Entered do_blkif_request\n");
350
351         queued = 0;
352
353         while ((req = blk_peek_request(rq)) != NULL) {
354                 info = req->rq_disk->private_data;
355
356                 if (RING_FULL(&info->ring))
357                         goto wait;
358
359                 blk_start_request(req);
360
361                 if (req->cmd_type != REQ_TYPE_FS) {
362                         __blk_end_request_all(req, -EIO);
363                         continue;
364                 }
365
366                 pr_debug("do_blk_req %p: cmd %p, sec %lx, "
367                          "(%u/%u) buffer:%p [%s]\n",
368                          req, req->cmd, (unsigned long)blk_rq_pos(req),
369                          blk_rq_cur_sectors(req), blk_rq_sectors(req),
370                          req->buffer, rq_data_dir(req) ? "write" : "read");
371
372                 if (blkif_queue_request(req)) {
373                         blk_requeue_request(rq, req);
374 wait:
375                         /* Avoid pointless unplugs. */
376                         blk_stop_queue(rq);
377                         break;
378                 }
379
380                 queued++;
381         }
382
383         if (queued != 0)
384                 flush_requests(info);
385 }
386
387 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size)
388 {
389         struct request_queue *rq;
390
391         rq = blk_init_queue(do_blkif_request, &blkif_io_lock);
392         if (rq == NULL)
393                 return -1;
394
395         queue_flag_set_unlocked(QUEUE_FLAG_VIRT, rq);
396
397         /* Hard sector size and max sectors impersonate the equiv. hardware. */
398         blk_queue_logical_block_size(rq, sector_size);
399         blk_queue_max_hw_sectors(rq, 512);
400
401         /* Each segment in a request is up to an aligned page in size. */
402         blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
403         blk_queue_max_segment_size(rq, PAGE_SIZE);
404
405         /* Ensure a merged request will fit in a single I/O ring slot. */
406         blk_queue_max_segments(rq, BLKIF_MAX_SEGMENTS_PER_REQUEST);
407
408         /* Make sure buffer addresses are sector-aligned. */
409         blk_queue_dma_alignment(rq, 511);
410
411         /* Make sure we don't use bounce buffers. */
412         blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
413
414         gd->queue = rq;
415
416         return 0;
417 }
418
419
420 static int xlvbd_barrier(struct blkfront_info *info)
421 {
422         int err;
423         const char *barrier;
424
425         switch (info->feature_barrier) {
426         case QUEUE_ORDERED_DRAIN:       barrier = "enabled (drain)"; break;
427         case QUEUE_ORDERED_TAG:         barrier = "enabled (tag)"; break;
428         case QUEUE_ORDERED_NONE:        barrier = "disabled"; break;
429         default:                        return -EINVAL;
430         }
431
432         err = blk_queue_ordered(info->rq, info->feature_barrier);
433
434         if (err)
435                 return err;
436
437         printk(KERN_INFO "blkfront: %s: barriers %s\n",
438                info->gd->disk_name, barrier);
439         return 0;
440 }
441
442
443 static int xlvbd_alloc_gendisk(blkif_sector_t capacity,
444                                struct blkfront_info *info,
445                                u16 vdisk_info, u16 sector_size)
446 {
447         struct gendisk *gd;
448         int nr_minors = 1;
449         int err = -ENODEV;
450         unsigned int offset;
451         int minor;
452         int nr_parts;
453
454         BUG_ON(info->gd != NULL);
455         BUG_ON(info->rq != NULL);
456
457         if ((info->vdevice>>EXT_SHIFT) > 1) {
458                 /* this is above the extended range; something is wrong */
459                 printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
460                 return -ENODEV;
461         }
462
463         if (!VDEV_IS_EXTENDED(info->vdevice)) {
464                 minor = BLKIF_MINOR(info->vdevice);
465                 nr_parts = PARTS_PER_DISK;
466         } else {
467                 minor = BLKIF_MINOR_EXT(info->vdevice);
468                 nr_parts = PARTS_PER_EXT_DISK;
469         }
470
471         if ((minor % nr_parts) == 0)
472                 nr_minors = nr_parts;
473
474         err = xlbd_reserve_minors(minor, nr_minors);
475         if (err)
476                 goto out;
477         err = -ENODEV;
478
479         gd = alloc_disk(nr_minors);
480         if (gd == NULL)
481                 goto release;
482
483         offset = minor / nr_parts;
484
485         if (nr_minors > 1) {
486                 if (offset < 26)
487                         sprintf(gd->disk_name, "%s%c", DEV_NAME, 'a' + offset);
488                 else
489                         sprintf(gd->disk_name, "%s%c%c", DEV_NAME,
490                                 'a' + ((offset / 26)-1), 'a' + (offset % 26));
491         } else {
492                 if (offset < 26)
493                         sprintf(gd->disk_name, "%s%c%d", DEV_NAME,
494                                 'a' + offset,
495                                 minor & (nr_parts - 1));
496                 else
497                         sprintf(gd->disk_name, "%s%c%c%d", DEV_NAME,
498                                 'a' + ((offset / 26) - 1),
499                                 'a' + (offset % 26),
500                                 minor & (nr_parts - 1));
501         }
502
503         gd->major = XENVBD_MAJOR;
504         gd->first_minor = minor;
505         gd->fops = &xlvbd_block_fops;
506         gd->private_data = info;
507         gd->driverfs_dev = &(info->xbdev->dev);
508         set_capacity(gd, capacity);
509
510         if (xlvbd_init_blk_queue(gd, sector_size)) {
511                 del_gendisk(gd);
512                 goto release;
513         }
514
515         info->rq = gd->queue;
516         info->gd = gd;
517
518         xlvbd_barrier(info);
519
520         if (vdisk_info & VDISK_READONLY)
521                 set_disk_ro(gd, 1);
522
523         if (vdisk_info & VDISK_REMOVABLE)
524                 gd->flags |= GENHD_FL_REMOVABLE;
525
526         if (vdisk_info & VDISK_CDROM)
527                 gd->flags |= GENHD_FL_CD;
528
529         return 0;
530
531  release:
532         xlbd_release_minors(minor, nr_minors);
533  out:
534         return err;
535 }
536
537 static void xlvbd_release_gendisk(struct blkfront_info *info)
538 {
539         unsigned int minor, nr_minors;
540         unsigned long flags;
541
542         if (info->rq == NULL)
543                 return;
544
545         spin_lock_irqsave(&blkif_io_lock, flags);
546
547         /* No more blkif_request(). */
548         blk_stop_queue(info->rq);
549
550         /* No more gnttab callback work. */
551         gnttab_cancel_free_callback(&info->callback);
552         spin_unlock_irqrestore(&blkif_io_lock, flags);
553
554         /* Flush gnttab callback work. Must be done with no locks held. */
555         flush_scheduled_work();
556
557         del_gendisk(info->gd);
558
559         minor = info->gd->first_minor;
560         nr_minors = info->gd->minors;
561         xlbd_release_minors(minor, nr_minors);
562
563         blk_cleanup_queue(info->rq);
564         info->rq = NULL;
565
566         put_disk(info->gd);
567         info->gd = NULL;
568 }
569
570 static void kick_pending_request_queues(struct blkfront_info *info)
571 {
572         if (!RING_FULL(&info->ring)) {
573                 /* Re-enable calldowns. */
574                 blk_start_queue(info->rq);
575                 /* Kick things off immediately. */
576                 do_blkif_request(info->rq);
577         }
578 }
579
580 static void blkif_restart_queue(struct work_struct *work)
581 {
582         struct blkfront_info *info = container_of(work, struct blkfront_info, work);
583
584         spin_lock_irq(&blkif_io_lock);
585         if (info->connected == BLKIF_STATE_CONNECTED)
586                 kick_pending_request_queues(info);
587         spin_unlock_irq(&blkif_io_lock);
588 }
589
590 static void blkif_free(struct blkfront_info *info, int suspend)
591 {
592         /* Prevent new requests being issued until we fix things up. */
593         spin_lock_irq(&blkif_io_lock);
594         info->connected = suspend ?
595                 BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
596         /* No more blkif_request(). */
597         if (info->rq)
598                 blk_stop_queue(info->rq);
599         /* No more gnttab callback work. */
600         gnttab_cancel_free_callback(&info->callback);
601         spin_unlock_irq(&blkif_io_lock);
602
603         /* Flush gnttab callback work. Must be done with no locks held. */
604         flush_scheduled_work();
605
606         /* Free resources associated with old device channel. */
607         if (info->ring_ref != GRANT_INVALID_REF) {
608                 gnttab_end_foreign_access(info->ring_ref, 0,
609                                           (unsigned long)info->ring.sring);
610                 info->ring_ref = GRANT_INVALID_REF;
611                 info->ring.sring = NULL;
612         }
613         if (info->irq)
614                 unbind_from_irqhandler(info->irq, info);
615         info->evtchn = info->irq = 0;
616
617 }
618
619 static void blkif_completion(struct blk_shadow *s)
620 {
621         int i;
622         for (i = 0; i < s->req.nr_segments; i++)
623                 gnttab_end_foreign_access(s->req.seg[i].gref, 0, 0UL);
624 }
625
626 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
627 {
628         struct request *req;
629         struct blkif_response *bret;
630         RING_IDX i, rp;
631         unsigned long flags;
632         struct blkfront_info *info = (struct blkfront_info *)dev_id;
633         int error;
634
635         spin_lock_irqsave(&blkif_io_lock, flags);
636
637         if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
638                 spin_unlock_irqrestore(&blkif_io_lock, flags);
639                 return IRQ_HANDLED;
640         }
641
642  again:
643         rp = info->ring.sring->rsp_prod;
644         rmb(); /* Ensure we see queued responses up to 'rp'. */
645
646         for (i = info->ring.rsp_cons; i != rp; i++) {
647                 unsigned long id;
648
649                 bret = RING_GET_RESPONSE(&info->ring, i);
650                 id   = bret->id;
651                 req  = (struct request *)info->shadow[id].request;
652
653                 blkif_completion(&info->shadow[id]);
654
655                 add_id_to_freelist(info, id);
656
657                 error = (bret->status == BLKIF_RSP_OKAY) ? 0 : -EIO;
658                 switch (bret->operation) {
659                 case BLKIF_OP_WRITE_BARRIER:
660                         if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
661                                 printk(KERN_WARNING "blkfront: %s: write barrier op failed\n",
662                                        info->gd->disk_name);
663                                 error = -EOPNOTSUPP;
664                                 info->feature_barrier = QUEUE_ORDERED_NONE;
665                                 xlvbd_barrier(info);
666                         }
667                         /* fall through */
668                 case BLKIF_OP_READ:
669                 case BLKIF_OP_WRITE:
670                         if (unlikely(bret->status != BLKIF_RSP_OKAY))
671                                 dev_dbg(&info->xbdev->dev, "Bad return from blkdev data "
672                                         "request: %x\n", bret->status);
673
674                         __blk_end_request_all(req, error);
675                         break;
676                 default:
677                         BUG();
678                 }
679         }
680
681         info->ring.rsp_cons = i;
682
683         if (i != info->ring.req_prod_pvt) {
684                 int more_to_do;
685                 RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
686                 if (more_to_do)
687                         goto again;
688         } else
689                 info->ring.sring->rsp_event = i + 1;
690
691         kick_pending_request_queues(info);
692
693         spin_unlock_irqrestore(&blkif_io_lock, flags);
694
695         return IRQ_HANDLED;
696 }
697
698
699 static int setup_blkring(struct xenbus_device *dev,
700                          struct blkfront_info *info)
701 {
702         struct blkif_sring *sring;
703         int err;
704
705         info->ring_ref = GRANT_INVALID_REF;
706
707         sring = (struct blkif_sring *)__get_free_page(GFP_NOIO | __GFP_HIGH);
708         if (!sring) {
709                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
710                 return -ENOMEM;
711         }
712         SHARED_RING_INIT(sring);
713         FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
714
715         sg_init_table(info->sg, BLKIF_MAX_SEGMENTS_PER_REQUEST);
716
717         err = xenbus_grant_ring(dev, virt_to_mfn(info->ring.sring));
718         if (err < 0) {
719                 free_page((unsigned long)sring);
720                 info->ring.sring = NULL;
721                 goto fail;
722         }
723         info->ring_ref = err;
724
725         err = xenbus_alloc_evtchn(dev, &info->evtchn);
726         if (err)
727                 goto fail;
728
729         err = bind_evtchn_to_irqhandler(info->evtchn,
730                                         blkif_interrupt,
731                                         IRQF_SAMPLE_RANDOM, "blkif", info);
732         if (err <= 0) {
733                 xenbus_dev_fatal(dev, err,
734                                  "bind_evtchn_to_irqhandler failed");
735                 goto fail;
736         }
737         info->irq = err;
738
739         return 0;
740 fail:
741         blkif_free(info, 0);
742         return err;
743 }
744
745
746 /* Common code used when first setting up, and when resuming. */
747 static int talk_to_blkback(struct xenbus_device *dev,
748                            struct blkfront_info *info)
749 {
750         const char *message = NULL;
751         struct xenbus_transaction xbt;
752         int err;
753
754         /* Create shared ring, alloc event channel. */
755         err = setup_blkring(dev, info);
756         if (err)
757                 goto out;
758
759 again:
760         err = xenbus_transaction_start(&xbt);
761         if (err) {
762                 xenbus_dev_fatal(dev, err, "starting transaction");
763                 goto destroy_blkring;
764         }
765
766         err = xenbus_printf(xbt, dev->nodename,
767                             "ring-ref", "%u", info->ring_ref);
768         if (err) {
769                 message = "writing ring-ref";
770                 goto abort_transaction;
771         }
772         err = xenbus_printf(xbt, dev->nodename,
773                             "event-channel", "%u", info->evtchn);
774         if (err) {
775                 message = "writing event-channel";
776                 goto abort_transaction;
777         }
778         err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
779                             XEN_IO_PROTO_ABI_NATIVE);
780         if (err) {
781                 message = "writing protocol";
782                 goto abort_transaction;
783         }
784
785         err = xenbus_transaction_end(xbt, 0);
786         if (err) {
787                 if (err == -EAGAIN)
788                         goto again;
789                 xenbus_dev_fatal(dev, err, "completing transaction");
790                 goto destroy_blkring;
791         }
792
793         xenbus_switch_state(dev, XenbusStateInitialised);
794
795         return 0;
796
797  abort_transaction:
798         xenbus_transaction_end(xbt, 1);
799         if (message)
800                 xenbus_dev_fatal(dev, err, "%s", message);
801  destroy_blkring:
802         blkif_free(info, 0);
803  out:
804         return err;
805 }
806
807 /**
808  * Entry point to this code when a new device is created.  Allocate the basic
809  * structures and the ring buffer for communication with the backend, and
810  * inform the backend of the appropriate details for those.  Switch to
811  * Initialised state.
812  */
813 static int blkfront_probe(struct xenbus_device *dev,
814                           const struct xenbus_device_id *id)
815 {
816         int err, vdevice, i;
817         struct blkfront_info *info;
818
819         /* FIXME: Use dynamic device id if this is not set. */
820         err = xenbus_scanf(XBT_NIL, dev->nodename,
821                            "virtual-device", "%i", &vdevice);
822         if (err != 1) {
823                 /* go looking in the extended area instead */
824                 err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
825                                    "%i", &vdevice);
826                 if (err != 1) {
827                         xenbus_dev_fatal(dev, err, "reading virtual-device");
828                         return err;
829                 }
830         }
831
832         info = kzalloc(sizeof(*info), GFP_KERNEL);
833         if (!info) {
834                 xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
835                 return -ENOMEM;
836         }
837
838         mutex_init(&info->mutex);
839         info->xbdev = dev;
840         info->vdevice = vdevice;
841         info->connected = BLKIF_STATE_DISCONNECTED;
842         INIT_WORK(&info->work, blkif_restart_queue);
843
844         for (i = 0; i < BLK_RING_SIZE; i++)
845                 info->shadow[i].req.id = i+1;
846         info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
847
848         /* Front end dir is a number, which is used as the id. */
849         info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
850         dev_set_drvdata(&dev->dev, info);
851
852         err = talk_to_blkback(dev, info);
853         if (err) {
854                 kfree(info);
855                 dev_set_drvdata(&dev->dev, NULL);
856                 return err;
857         }
858
859         return 0;
860 }
861
862
863 static int blkif_recover(struct blkfront_info *info)
864 {
865         int i;
866         struct blkif_request *req;
867         struct blk_shadow *copy;
868         int j;
869
870         /* Stage 1: Make a safe copy of the shadow state. */
871         copy = kmalloc(sizeof(info->shadow),
872                        GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
873         if (!copy)
874                 return -ENOMEM;
875         memcpy(copy, info->shadow, sizeof(info->shadow));
876
877         /* Stage 2: Set up free list. */
878         memset(&info->shadow, 0, sizeof(info->shadow));
879         for (i = 0; i < BLK_RING_SIZE; i++)
880                 info->shadow[i].req.id = i+1;
881         info->shadow_free = info->ring.req_prod_pvt;
882         info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
883
884         /* Stage 3: Find pending requests and requeue them. */
885         for (i = 0; i < BLK_RING_SIZE; i++) {
886                 /* Not in use? */
887                 if (copy[i].request == 0)
888                         continue;
889
890                 /* Grab a request slot and copy shadow state into it. */
891                 req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
892                 *req = copy[i].req;
893
894                 /* We get a new request id, and must reset the shadow state. */
895                 req->id = get_id_from_freelist(info);
896                 memcpy(&info->shadow[req->id], &copy[i], sizeof(copy[i]));
897
898                 /* Rewrite any grant references invalidated by susp/resume. */
899                 for (j = 0; j < req->nr_segments; j++)
900                         gnttab_grant_foreign_access_ref(
901                                 req->seg[j].gref,
902                                 info->xbdev->otherend_id,
903                                 pfn_to_mfn(info->shadow[req->id].frame[j]),
904                                 rq_data_dir(
905                                         (struct request *)
906                                         info->shadow[req->id].request));
907                 info->shadow[req->id].req = *req;
908
909                 info->ring.req_prod_pvt++;
910         }
911
912         kfree(copy);
913
914         xenbus_switch_state(info->xbdev, XenbusStateConnected);
915
916         spin_lock_irq(&blkif_io_lock);
917
918         /* Now safe for us to use the shared ring */
919         info->connected = BLKIF_STATE_CONNECTED;
920
921         /* Send off requeued requests */
922         flush_requests(info);
923
924         /* Kick any other new requests queued since we resumed */
925         kick_pending_request_queues(info);
926
927         spin_unlock_irq(&blkif_io_lock);
928
929         return 0;
930 }
931
932 /**
933  * We are reconnecting to the backend, due to a suspend/resume, or a backend
934  * driver restart.  We tear down our blkif structure and recreate it, but
935  * leave the device-layer structures intact so that this is transparent to the
936  * rest of the kernel.
937  */
938 static int blkfront_resume(struct xenbus_device *dev)
939 {
940         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
941         int err;
942
943         dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
944
945         blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
946
947         err = talk_to_blkback(dev, info);
948         if (info->connected == BLKIF_STATE_SUSPENDED && !err)
949                 err = blkif_recover(info);
950
951         return err;
952 }
953
954 static void
955 blkfront_closing(struct blkfront_info *info)
956 {
957         struct xenbus_device *xbdev = info->xbdev;
958         struct block_device *bdev = NULL;
959
960         mutex_lock(&info->mutex);
961
962         if (xbdev->state == XenbusStateClosing) {
963                 mutex_unlock(&info->mutex);
964                 return;
965         }
966
967         if (info->gd)
968                 bdev = bdget_disk(info->gd, 0);
969
970         mutex_unlock(&info->mutex);
971
972         if (!bdev) {
973                 xenbus_frontend_closed(xbdev);
974                 return;
975         }
976
977         mutex_lock(&bdev->bd_mutex);
978
979         if (bdev->bd_openers) {
980                 xenbus_dev_error(xbdev, -EBUSY,
981                                  "Device in use; refusing to close");
982                 xenbus_switch_state(xbdev, XenbusStateClosing);
983         } else {
984                 xlvbd_release_gendisk(info);
985                 xenbus_frontend_closed(xbdev);
986         }
987
988         mutex_unlock(&bdev->bd_mutex);
989         bdput(bdev);
990 }
991
992 /*
993  * Invoked when the backend is finally 'ready' (and has told produced
994  * the details about the physical device - #sectors, size, etc).
995  */
996 static void blkfront_connect(struct blkfront_info *info)
997 {
998         unsigned long long sectors;
999         unsigned long sector_size;
1000         unsigned int binfo;
1001         int err;
1002         int barrier;
1003
1004         switch (info->connected) {
1005         case BLKIF_STATE_CONNECTED:
1006                 /*
1007                  * Potentially, the back-end may be signalling
1008                  * a capacity change; update the capacity.
1009                  */
1010                 err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1011                                    "sectors", "%Lu", &sectors);
1012                 if (XENBUS_EXIST_ERR(err))
1013                         return;
1014                 printk(KERN_INFO "Setting capacity to %Lu\n",
1015                        sectors);
1016                 set_capacity(info->gd, sectors);
1017                 revalidate_disk(info->gd);
1018
1019                 /* fall through */
1020         case BLKIF_STATE_SUSPENDED:
1021                 return;
1022
1023         default:
1024                 break;
1025         }
1026
1027         dev_dbg(&info->xbdev->dev, "%s:%s.\n",
1028                 __func__, info->xbdev->otherend);
1029
1030         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1031                             "sectors", "%llu", &sectors,
1032                             "info", "%u", &binfo,
1033                             "sector-size", "%lu", &sector_size,
1034                             NULL);
1035         if (err) {
1036                 xenbus_dev_fatal(info->xbdev, err,
1037                                  "reading backend fields at %s",
1038                                  info->xbdev->otherend);
1039                 return;
1040         }
1041
1042         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1043                             "feature-barrier", "%lu", &barrier,
1044                             NULL);
1045
1046         /*
1047          * If there's no "feature-barrier" defined, then it means
1048          * we're dealing with a very old backend which writes
1049          * synchronously; draining will do what needs to get done.
1050          *
1051          * If there are barriers, then we can do full queued writes
1052          * with tagged barriers.
1053          *
1054          * If barriers are not supported, then there's no much we can
1055          * do, so just set ordering to NONE.
1056          */
1057         if (err)
1058                 info->feature_barrier = QUEUE_ORDERED_DRAIN;
1059         else if (barrier)
1060                 info->feature_barrier = QUEUE_ORDERED_TAG;
1061         else
1062                 info->feature_barrier = QUEUE_ORDERED_NONE;
1063
1064         err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size);
1065         if (err) {
1066                 xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
1067                                  info->xbdev->otherend);
1068                 return;
1069         }
1070
1071         xenbus_switch_state(info->xbdev, XenbusStateConnected);
1072
1073         /* Kick pending requests. */
1074         spin_lock_irq(&blkif_io_lock);
1075         info->connected = BLKIF_STATE_CONNECTED;
1076         kick_pending_request_queues(info);
1077         spin_unlock_irq(&blkif_io_lock);
1078
1079         add_disk(info->gd);
1080
1081         info->is_ready = 1;
1082 }
1083
1084 /**
1085  * Callback received when the backend's state changes.
1086  */
1087 static void blkback_changed(struct xenbus_device *dev,
1088                             enum xenbus_state backend_state)
1089 {
1090         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1091
1092         dev_dbg(&dev->dev, "blkfront:blkback_changed to state %d.\n", backend_state);
1093
1094         switch (backend_state) {
1095         case XenbusStateInitialising:
1096         case XenbusStateInitWait:
1097         case XenbusStateInitialised:
1098         case XenbusStateUnknown:
1099         case XenbusStateClosed:
1100                 break;
1101
1102         case XenbusStateConnected:
1103                 blkfront_connect(info);
1104                 break;
1105
1106         case XenbusStateClosing:
1107                 blkfront_closing(info);
1108                 break;
1109         }
1110 }
1111
1112 static int blkfront_remove(struct xenbus_device *xbdev)
1113 {
1114         struct blkfront_info *info = dev_get_drvdata(&xbdev->dev);
1115         struct block_device *bdev = NULL;
1116         struct gendisk *disk;
1117
1118         dev_dbg(&xbdev->dev, "%s removed", xbdev->nodename);
1119
1120         blkif_free(info, 0);
1121
1122         mutex_lock(&info->mutex);
1123
1124         disk = info->gd;
1125         if (disk)
1126                 bdev = bdget_disk(disk, 0);
1127
1128         info->xbdev = NULL;
1129         mutex_unlock(&info->mutex);
1130
1131         if (!bdev) {
1132                 kfree(info);
1133                 return 0;
1134         }
1135
1136         /*
1137          * The xbdev was removed before we reached the Closed
1138          * state. See if it's safe to remove the disk. If the bdev
1139          * isn't closed yet, we let release take care of it.
1140          */
1141
1142         mutex_lock(&bdev->bd_mutex);
1143         info = disk->private_data;
1144
1145         dev_warn(disk_to_dev(disk),
1146                  "%s was hot-unplugged, %d stale handles\n",
1147                  xbdev->nodename, bdev->bd_openers);
1148
1149         if (info && !bdev->bd_openers) {
1150                 xlvbd_release_gendisk(info);
1151                 disk->private_data = NULL;
1152                 kfree(info);
1153         }
1154
1155         mutex_unlock(&bdev->bd_mutex);
1156         bdput(bdev);
1157
1158         return 0;
1159 }
1160
1161 static int blkfront_is_ready(struct xenbus_device *dev)
1162 {
1163         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1164
1165         return info->is_ready && info->xbdev;
1166 }
1167
1168 static int blkif_open(struct block_device *bdev, fmode_t mode)
1169 {
1170         struct gendisk *disk = bdev->bd_disk;
1171         struct blkfront_info *info;
1172         int err = 0;
1173
1174         lock_kernel();
1175
1176         info = disk->private_data;
1177         if (!info) {
1178                 /* xbdev gone */
1179                 err = -ERESTARTSYS;
1180                 goto out;
1181         }
1182
1183         mutex_lock(&info->mutex);
1184
1185         if (!info->gd)
1186                 /* xbdev is closed */
1187                 err = -ERESTARTSYS;
1188
1189         mutex_unlock(&info->mutex);
1190
1191 out:
1192         unlock_kernel();
1193         return err;
1194 }
1195
1196 static int blkif_release(struct gendisk *disk, fmode_t mode)
1197 {
1198         struct blkfront_info *info = disk->private_data;
1199         struct block_device *bdev;
1200         struct xenbus_device *xbdev;
1201
1202         lock_kernel();
1203
1204         bdev = bdget_disk(disk, 0);
1205         bdput(bdev);
1206
1207         if (bdev->bd_openers)
1208                 goto out;
1209
1210         /*
1211          * Check if we have been instructed to close. We will have
1212          * deferred this request, because the bdev was still open.
1213          */
1214
1215         mutex_lock(&info->mutex);
1216         xbdev = info->xbdev;
1217
1218         if (xbdev && xbdev->state == XenbusStateClosing) {
1219                 /* pending switch to state closed */
1220                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
1221                 xlvbd_release_gendisk(info);
1222                 xenbus_frontend_closed(info->xbdev);
1223         }
1224
1225         mutex_unlock(&info->mutex);
1226
1227         if (!xbdev) {
1228                 /* sudden device removal */
1229                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
1230                 xlvbd_release_gendisk(info);
1231                 disk->private_data = NULL;
1232                 kfree(info);
1233         }
1234
1235 out:
1236         unlock_kernel();
1237         return 0;
1238 }
1239
1240 static const struct block_device_operations xlvbd_block_fops =
1241 {
1242         .owner = THIS_MODULE,
1243         .open = blkif_open,
1244         .release = blkif_release,
1245         .getgeo = blkif_getgeo,
1246         .ioctl = blkif_ioctl,
1247 };
1248
1249
1250 static const struct xenbus_device_id blkfront_ids[] = {
1251         { "vbd" },
1252         { "" }
1253 };
1254
1255 static struct xenbus_driver blkfront = {
1256         .name = "vbd",
1257         .owner = THIS_MODULE,
1258         .ids = blkfront_ids,
1259         .probe = blkfront_probe,
1260         .remove = blkfront_remove,
1261         .resume = blkfront_resume,
1262         .otherend_changed = blkback_changed,
1263         .is_ready = blkfront_is_ready,
1264 };
1265
1266 static int __init xlblk_init(void)
1267 {
1268         if (!xen_domain())
1269                 return -ENODEV;
1270
1271         if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
1272                 printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
1273                        XENVBD_MAJOR, DEV_NAME);
1274                 return -ENODEV;
1275         }
1276
1277         return xenbus_register_frontend(&blkfront);
1278 }
1279 module_init(xlblk_init);
1280
1281
1282 static void __exit xlblk_exit(void)
1283 {
1284         return xenbus_unregister_driver(&blkfront);
1285 }
1286 module_exit(xlblk_exit);
1287
1288 MODULE_DESCRIPTION("Xen virtual block device frontend");
1289 MODULE_LICENSE("GPL");
1290 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
1291 MODULE_ALIAS("xen:vbd");
1292 MODULE_ALIAS("xenblk");