b220c686089d82b5ffc41eada6efd59c7f7ca7e5
[linux-2.6.git] / 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
44 #include <xen/xenbus.h>
45 #include <xen/grant_table.h>
46 #include <xen/events.h>
47 #include <xen/page.h>
48
49 #include <xen/interface/grant_table.h>
50 #include <xen/interface/io/blkif.h>
51 #include <xen/interface/io/protocols.h>
52
53 #include <asm/xen/hypervisor.h>
54
55 enum blkif_state {
56         BLKIF_STATE_DISCONNECTED,
57         BLKIF_STATE_CONNECTED,
58         BLKIF_STATE_SUSPENDED,
59 };
60
61 struct blk_shadow {
62         struct blkif_request req;
63         unsigned long request;
64         unsigned long frame[BLKIF_MAX_SEGMENTS_PER_REQUEST];
65 };
66
67 static struct block_device_operations xlvbd_block_fops;
68
69 #define BLK_RING_SIZE __RING_SIZE((struct blkif_sring *)0, PAGE_SIZE)
70
71 /*
72  * We have one of these per vbd, whether ide, scsi or 'other'.  They
73  * hang in private_data off the gendisk structure. We may end up
74  * putting all kinds of interesting stuff here :-)
75  */
76 struct blkfront_info
77 {
78         struct xenbus_device *xbdev;
79         struct gendisk *gd;
80         int vdevice;
81         blkif_vdev_t handle;
82         enum blkif_state connected;
83         int ring_ref;
84         struct blkif_front_ring ring;
85         unsigned int evtchn, irq;
86         struct request_queue *rq;
87         struct work_struct work;
88         struct gnttab_free_callback callback;
89         struct blk_shadow shadow[BLK_RING_SIZE];
90         unsigned long shadow_free;
91         int feature_barrier;
92         int is_ready;
93
94         /**
95          * The number of people holding this device open.  We won't allow a
96          * hot-unplug unless this is 0.
97          */
98         int users;
99 };
100
101 static DEFINE_SPINLOCK(blkif_io_lock);
102
103 #define MAXIMUM_OUTSTANDING_BLOCK_REQS \
104         (BLKIF_MAX_SEGMENTS_PER_REQUEST * BLK_RING_SIZE)
105 #define GRANT_INVALID_REF       0
106
107 #define PARTS_PER_DISK          16
108 #define PARTS_PER_EXT_DISK      256
109
110 #define BLKIF_MAJOR(dev) ((dev)>>8)
111 #define BLKIF_MINOR(dev) ((dev) & 0xff)
112
113 #define EXT_SHIFT 28
114 #define EXTENDED (1<<EXT_SHIFT)
115 #define VDEV_IS_EXTENDED(dev) ((dev)&(EXTENDED))
116 #define BLKIF_MINOR_EXT(dev) ((dev)&(~EXTENDED))
117
118 #define DEV_NAME        "xvd"   /* name in /dev */
119
120 static int get_id_from_freelist(struct blkfront_info *info)
121 {
122         unsigned long free = info->shadow_free;
123         BUG_ON(free > BLK_RING_SIZE);
124         info->shadow_free = info->shadow[free].req.id;
125         info->shadow[free].req.id = 0x0fffffee; /* debug */
126         return free;
127 }
128
129 static void add_id_to_freelist(struct blkfront_info *info,
130                                unsigned long id)
131 {
132         info->shadow[id].req.id  = info->shadow_free;
133         info->shadow[id].request = 0;
134         info->shadow_free = id;
135 }
136
137 static void blkif_restart_queue_callback(void *arg)
138 {
139         struct blkfront_info *info = (struct blkfront_info *)arg;
140         schedule_work(&info->work);
141 }
142
143 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
144 {
145         /* We don't have real geometry info, but let's at least return
146            values consistent with the size of the device */
147         sector_t nsect = get_capacity(bd->bd_disk);
148         sector_t cylinders = nsect;
149
150         hg->heads = 0xff;
151         hg->sectors = 0x3f;
152         sector_div(cylinders, hg->heads * hg->sectors);
153         hg->cylinders = cylinders;
154         if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
155                 hg->cylinders = 0xffff;
156         return 0;
157 }
158
159 static int blkif_ioctl(struct block_device *bdev, fmode_t mode,
160                        unsigned command, unsigned long argument)
161 {
162         struct blkfront_info *info = bdev->bd_disk->private_data;
163         int i;
164
165         dev_dbg(&info->xbdev->dev, "command: 0x%x, argument: 0x%lx\n",
166                 command, (long)argument);
167
168         switch (command) {
169         case CDROMMULTISESSION:
170                 dev_dbg(&info->xbdev->dev, "FIXME: support multisession CDs later\n");
171                 for (i = 0; i < sizeof(struct cdrom_multisession); i++)
172                         if (put_user(0, (char __user *)(argument + i)))
173                                 return -EFAULT;
174                 return 0;
175
176         case CDROM_GET_CAPABILITY: {
177                 struct gendisk *gd = info->gd;
178                 if (gd->flags & GENHD_FL_CD)
179                         return 0;
180                 return -EINVAL;
181         }
182
183         default:
184                 /*printk(KERN_ALERT "ioctl %08x not supported by Xen blkdev\n",
185                   command);*/
186                 return -EINVAL; /* same return as native Linux */
187         }
188
189         return 0;
190 }
191
192 /*
193  * blkif_queue_request
194  *
195  * request block io
196  *
197  * id: for guest use only.
198  * operation: BLKIF_OP_{READ,WRITE,PROBE}
199  * buffer: buffer to read/write into. this should be a
200  *   virtual address in the guest os.
201  */
202 static int blkif_queue_request(struct request *req)
203 {
204         struct blkfront_info *info = req->rq_disk->private_data;
205         unsigned long buffer_mfn;
206         struct blkif_request *ring_req;
207         struct req_iterator iter;
208         struct bio_vec *bvec;
209         unsigned long id;
210         unsigned int fsect, lsect;
211         int ref;
212         grant_ref_t gref_head;
213
214         if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
215                 return 1;
216
217         if (gnttab_alloc_grant_references(
218                 BLKIF_MAX_SEGMENTS_PER_REQUEST, &gref_head) < 0) {
219                 gnttab_request_free_callback(
220                         &info->callback,
221                         blkif_restart_queue_callback,
222                         info,
223                         BLKIF_MAX_SEGMENTS_PER_REQUEST);
224                 return 1;
225         }
226
227         /* Fill out a communications ring structure. */
228         ring_req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
229         id = get_id_from_freelist(info);
230         info->shadow[id].request = (unsigned long)req;
231
232         ring_req->id = id;
233         ring_req->sector_number = (blkif_sector_t)req->sector;
234         ring_req->handle = info->handle;
235
236         ring_req->operation = rq_data_dir(req) ?
237                 BLKIF_OP_WRITE : BLKIF_OP_READ;
238         if (blk_barrier_rq(req))
239                 ring_req->operation = BLKIF_OP_WRITE_BARRIER;
240
241         ring_req->nr_segments = 0;
242         rq_for_each_segment(bvec, req, iter) {
243                 BUG_ON(ring_req->nr_segments == BLKIF_MAX_SEGMENTS_PER_REQUEST);
244                 buffer_mfn = pfn_to_mfn(page_to_pfn(bvec->bv_page));
245                 fsect = bvec->bv_offset >> 9;
246                 lsect = fsect + (bvec->bv_len >> 9) - 1;
247                 /* install a grant reference. */
248                 ref = gnttab_claim_grant_reference(&gref_head);
249                 BUG_ON(ref == -ENOSPC);
250
251                 gnttab_grant_foreign_access_ref(
252                                 ref,
253                                 info->xbdev->otherend_id,
254                                 buffer_mfn,
255                                 rq_data_dir(req) );
256
257                 info->shadow[id].frame[ring_req->nr_segments] =
258                                 mfn_to_pfn(buffer_mfn);
259
260                 ring_req->seg[ring_req->nr_segments] =
261                                 (struct blkif_request_segment) {
262                                         .gref       = ref,
263                                         .first_sect = fsect,
264                                         .last_sect  = lsect };
265
266                 ring_req->nr_segments++;
267         }
268
269         info->ring.req_prod_pvt++;
270
271         /* Keep a private copy so we can reissue requests when recovering. */
272         info->shadow[id].req = *ring_req;
273
274         gnttab_free_grant_references(gref_head);
275
276         return 0;
277 }
278
279
280 static inline void flush_requests(struct blkfront_info *info)
281 {
282         int notify;
283
284         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
285
286         if (notify)
287                 notify_remote_via_irq(info->irq);
288 }
289
290 /*
291  * do_blkif_request
292  *  read a block; request is in a request queue
293  */
294 static void do_blkif_request(struct request_queue *rq)
295 {
296         struct blkfront_info *info = NULL;
297         struct request *req;
298         int queued;
299
300         pr_debug("Entered do_blkif_request\n");
301
302         queued = 0;
303
304         while ((req = elv_next_request(rq)) != NULL) {
305                 info = req->rq_disk->private_data;
306                 if (!blk_fs_request(req)) {
307                         end_request(req, 0);
308                         continue;
309                 }
310
311                 if (RING_FULL(&info->ring))
312                         goto wait;
313
314                 pr_debug("do_blk_req %p: cmd %p, sec %lx, "
315                          "(%u/%li) buffer:%p [%s]\n",
316                          req, req->cmd, (unsigned long)req->sector,
317                          req->current_nr_sectors,
318                          req->nr_sectors, req->buffer,
319                          rq_data_dir(req) ? "write" : "read");
320
321
322                 blkdev_dequeue_request(req);
323                 if (blkif_queue_request(req)) {
324                         blk_requeue_request(rq, req);
325 wait:
326                         /* Avoid pointless unplugs. */
327                         blk_stop_queue(rq);
328                         break;
329                 }
330
331                 queued++;
332         }
333
334         if (queued != 0)
335                 flush_requests(info);
336 }
337
338 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size)
339 {
340         struct request_queue *rq;
341
342         rq = blk_init_queue(do_blkif_request, &blkif_io_lock);
343         if (rq == NULL)
344                 return -1;
345
346         elevator_init(rq, "noop");
347
348         /* Hard sector size and max sectors impersonate the equiv. hardware. */
349         blk_queue_hardsect_size(rq, sector_size);
350         blk_queue_max_sectors(rq, 512);
351
352         /* Each segment in a request is up to an aligned page in size. */
353         blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
354         blk_queue_max_segment_size(rq, PAGE_SIZE);
355
356         /* Ensure a merged request will fit in a single I/O ring slot. */
357         blk_queue_max_phys_segments(rq, BLKIF_MAX_SEGMENTS_PER_REQUEST);
358         blk_queue_max_hw_segments(rq, BLKIF_MAX_SEGMENTS_PER_REQUEST);
359
360         /* Make sure buffer addresses are sector-aligned. */
361         blk_queue_dma_alignment(rq, 511);
362
363         /* Make sure we don't use bounce buffers. */
364         blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
365
366         gd->queue = rq;
367
368         return 0;
369 }
370
371
372 static int xlvbd_barrier(struct blkfront_info *info)
373 {
374         int err;
375
376         err = blk_queue_ordered(info->rq,
377                                 info->feature_barrier ? QUEUE_ORDERED_DRAIN : QUEUE_ORDERED_NONE,
378                                 NULL);
379
380         if (err)
381                 return err;
382
383         printk(KERN_INFO "blkfront: %s: barriers %s\n",
384                info->gd->disk_name,
385                info->feature_barrier ? "enabled" : "disabled");
386         return 0;
387 }
388
389
390 static int xlvbd_alloc_gendisk(blkif_sector_t capacity,
391                                struct blkfront_info *info,
392                                u16 vdisk_info, u16 sector_size)
393 {
394         struct gendisk *gd;
395         int nr_minors = 1;
396         int err = -ENODEV;
397         unsigned int offset;
398         int minor;
399         int nr_parts;
400
401         BUG_ON(info->gd != NULL);
402         BUG_ON(info->rq != NULL);
403
404         if ((info->vdevice>>EXT_SHIFT) > 1) {
405                 /* this is above the extended range; something is wrong */
406                 printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
407                 return -ENODEV;
408         }
409
410         if (!VDEV_IS_EXTENDED(info->vdevice)) {
411                 minor = BLKIF_MINOR(info->vdevice);
412                 nr_parts = PARTS_PER_DISK;
413         } else {
414                 minor = BLKIF_MINOR_EXT(info->vdevice);
415                 nr_parts = PARTS_PER_EXT_DISK;
416         }
417
418         if ((minor % nr_parts) == 0)
419                 nr_minors = nr_parts;
420
421         gd = alloc_disk(nr_minors);
422         if (gd == NULL)
423                 goto out;
424
425         offset = minor / nr_parts;
426
427         if (nr_minors > 1) {
428                 if (offset < 26)
429                         sprintf(gd->disk_name, "%s%c", DEV_NAME, 'a' + offset);
430                 else
431                         sprintf(gd->disk_name, "%s%c%c", DEV_NAME,
432                                 'a' + ((offset / 26)-1), 'a' + (offset % 26));
433         } else {
434                 if (offset < 26)
435                         sprintf(gd->disk_name, "%s%c%d", DEV_NAME,
436                                 'a' + offset,
437                                 minor & (nr_parts - 1));
438                 else
439                         sprintf(gd->disk_name, "%s%c%c%d", DEV_NAME,
440                                 'a' + ((offset / 26) - 1),
441                                 'a' + (offset % 26),
442                                 minor & (nr_parts - 1));
443         }
444
445         gd->major = XENVBD_MAJOR;
446         gd->first_minor = minor;
447         gd->fops = &xlvbd_block_fops;
448         gd->private_data = info;
449         gd->driverfs_dev = &(info->xbdev->dev);
450         set_capacity(gd, capacity);
451
452         if (xlvbd_init_blk_queue(gd, sector_size)) {
453                 del_gendisk(gd);
454                 goto out;
455         }
456
457         info->rq = gd->queue;
458         info->gd = gd;
459
460         if (info->feature_barrier)
461                 xlvbd_barrier(info);
462
463         if (vdisk_info & VDISK_READONLY)
464                 set_disk_ro(gd, 1);
465
466         if (vdisk_info & VDISK_REMOVABLE)
467                 gd->flags |= GENHD_FL_REMOVABLE;
468
469         if (vdisk_info & VDISK_CDROM)
470                 gd->flags |= GENHD_FL_CD;
471
472         return 0;
473
474  out:
475         return err;
476 }
477
478 static void kick_pending_request_queues(struct blkfront_info *info)
479 {
480         if (!RING_FULL(&info->ring)) {
481                 /* Re-enable calldowns. */
482                 blk_start_queue(info->rq);
483                 /* Kick things off immediately. */
484                 do_blkif_request(info->rq);
485         }
486 }
487
488 static void blkif_restart_queue(struct work_struct *work)
489 {
490         struct blkfront_info *info = container_of(work, struct blkfront_info, work);
491
492         spin_lock_irq(&blkif_io_lock);
493         if (info->connected == BLKIF_STATE_CONNECTED)
494                 kick_pending_request_queues(info);
495         spin_unlock_irq(&blkif_io_lock);
496 }
497
498 static void blkif_free(struct blkfront_info *info, int suspend)
499 {
500         /* Prevent new requests being issued until we fix things up. */
501         spin_lock_irq(&blkif_io_lock);
502         info->connected = suspend ?
503                 BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
504         /* No more blkif_request(). */
505         if (info->rq)
506                 blk_stop_queue(info->rq);
507         /* No more gnttab callback work. */
508         gnttab_cancel_free_callback(&info->callback);
509         spin_unlock_irq(&blkif_io_lock);
510
511         /* Flush gnttab callback work. Must be done with no locks held. */
512         flush_scheduled_work();
513
514         /* Free resources associated with old device channel. */
515         if (info->ring_ref != GRANT_INVALID_REF) {
516                 gnttab_end_foreign_access(info->ring_ref, 0,
517                                           (unsigned long)info->ring.sring);
518                 info->ring_ref = GRANT_INVALID_REF;
519                 info->ring.sring = NULL;
520         }
521         if (info->irq)
522                 unbind_from_irqhandler(info->irq, info);
523         info->evtchn = info->irq = 0;
524
525 }
526
527 static void blkif_completion(struct blk_shadow *s)
528 {
529         int i;
530         for (i = 0; i < s->req.nr_segments; i++)
531                 gnttab_end_foreign_access(s->req.seg[i].gref, 0, 0UL);
532 }
533
534 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
535 {
536         struct request *req;
537         struct blkif_response *bret;
538         RING_IDX i, rp;
539         unsigned long flags;
540         struct blkfront_info *info = (struct blkfront_info *)dev_id;
541         int error;
542
543         spin_lock_irqsave(&blkif_io_lock, flags);
544
545         if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
546                 spin_unlock_irqrestore(&blkif_io_lock, flags);
547                 return IRQ_HANDLED;
548         }
549
550  again:
551         rp = info->ring.sring->rsp_prod;
552         rmb(); /* Ensure we see queued responses up to 'rp'. */
553
554         for (i = info->ring.rsp_cons; i != rp; i++) {
555                 unsigned long id;
556                 int ret;
557
558                 bret = RING_GET_RESPONSE(&info->ring, i);
559                 id   = bret->id;
560                 req  = (struct request *)info->shadow[id].request;
561
562                 blkif_completion(&info->shadow[id]);
563
564                 add_id_to_freelist(info, id);
565
566                 error = (bret->status == BLKIF_RSP_OKAY) ? 0 : -EIO;
567                 switch (bret->operation) {
568                 case BLKIF_OP_WRITE_BARRIER:
569                         if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
570                                 printk(KERN_WARNING "blkfront: %s: write barrier op failed\n",
571                                        info->gd->disk_name);
572                                 error = -EOPNOTSUPP;
573                                 info->feature_barrier = 0;
574                                 xlvbd_barrier(info);
575                         }
576                         /* fall through */
577                 case BLKIF_OP_READ:
578                 case BLKIF_OP_WRITE:
579                         if (unlikely(bret->status != BLKIF_RSP_OKAY))
580                                 dev_dbg(&info->xbdev->dev, "Bad return from blkdev data "
581                                         "request: %x\n", bret->status);
582
583                         ret = __blk_end_request(req, error, blk_rq_bytes(req));
584                         BUG_ON(ret);
585                         break;
586                 default:
587                         BUG();
588                 }
589         }
590
591         info->ring.rsp_cons = i;
592
593         if (i != info->ring.req_prod_pvt) {
594                 int more_to_do;
595                 RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
596                 if (more_to_do)
597                         goto again;
598         } else
599                 info->ring.sring->rsp_event = i + 1;
600
601         kick_pending_request_queues(info);
602
603         spin_unlock_irqrestore(&blkif_io_lock, flags);
604
605         return IRQ_HANDLED;
606 }
607
608
609 static int setup_blkring(struct xenbus_device *dev,
610                          struct blkfront_info *info)
611 {
612         struct blkif_sring *sring;
613         int err;
614
615         info->ring_ref = GRANT_INVALID_REF;
616
617         sring = (struct blkif_sring *)__get_free_page(GFP_NOIO | __GFP_HIGH);
618         if (!sring) {
619                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
620                 return -ENOMEM;
621         }
622         SHARED_RING_INIT(sring);
623         FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
624
625         err = xenbus_grant_ring(dev, virt_to_mfn(info->ring.sring));
626         if (err < 0) {
627                 free_page((unsigned long)sring);
628                 info->ring.sring = NULL;
629                 goto fail;
630         }
631         info->ring_ref = err;
632
633         err = xenbus_alloc_evtchn(dev, &info->evtchn);
634         if (err)
635                 goto fail;
636
637         err = bind_evtchn_to_irqhandler(info->evtchn,
638                                         blkif_interrupt,
639                                         IRQF_SAMPLE_RANDOM, "blkif", info);
640         if (err <= 0) {
641                 xenbus_dev_fatal(dev, err,
642                                  "bind_evtchn_to_irqhandler failed");
643                 goto fail;
644         }
645         info->irq = err;
646
647         return 0;
648 fail:
649         blkif_free(info, 0);
650         return err;
651 }
652
653
654 /* Common code used when first setting up, and when resuming. */
655 static int talk_to_backend(struct xenbus_device *dev,
656                            struct blkfront_info *info)
657 {
658         const char *message = NULL;
659         struct xenbus_transaction xbt;
660         int err;
661
662         /* Create shared ring, alloc event channel. */
663         err = setup_blkring(dev, info);
664         if (err)
665                 goto out;
666
667 again:
668         err = xenbus_transaction_start(&xbt);
669         if (err) {
670                 xenbus_dev_fatal(dev, err, "starting transaction");
671                 goto destroy_blkring;
672         }
673
674         err = xenbus_printf(xbt, dev->nodename,
675                             "ring-ref", "%u", info->ring_ref);
676         if (err) {
677                 message = "writing ring-ref";
678                 goto abort_transaction;
679         }
680         err = xenbus_printf(xbt, dev->nodename,
681                             "event-channel", "%u", info->evtchn);
682         if (err) {
683                 message = "writing event-channel";
684                 goto abort_transaction;
685         }
686         err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
687                             XEN_IO_PROTO_ABI_NATIVE);
688         if (err) {
689                 message = "writing protocol";
690                 goto abort_transaction;
691         }
692
693         err = xenbus_transaction_end(xbt, 0);
694         if (err) {
695                 if (err == -EAGAIN)
696                         goto again;
697                 xenbus_dev_fatal(dev, err, "completing transaction");
698                 goto destroy_blkring;
699         }
700
701         xenbus_switch_state(dev, XenbusStateInitialised);
702
703         return 0;
704
705  abort_transaction:
706         xenbus_transaction_end(xbt, 1);
707         if (message)
708                 xenbus_dev_fatal(dev, err, "%s", message);
709  destroy_blkring:
710         blkif_free(info, 0);
711  out:
712         return err;
713 }
714
715
716 /**
717  * Entry point to this code when a new device is created.  Allocate the basic
718  * structures and the ring buffer for communication with the backend, and
719  * inform the backend of the appropriate details for those.  Switch to
720  * Initialised state.
721  */
722 static int blkfront_probe(struct xenbus_device *dev,
723                           const struct xenbus_device_id *id)
724 {
725         int err, vdevice, i;
726         struct blkfront_info *info;
727
728         /* FIXME: Use dynamic device id if this is not set. */
729         err = xenbus_scanf(XBT_NIL, dev->nodename,
730                            "virtual-device", "%i", &vdevice);
731         if (err != 1) {
732                 /* go looking in the extended area instead */
733                 err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
734                                    "%i", &vdevice);
735                 if (err != 1) {
736                         xenbus_dev_fatal(dev, err, "reading virtual-device");
737                         return err;
738                 }
739         }
740
741         info = kzalloc(sizeof(*info), GFP_KERNEL);
742         if (!info) {
743                 xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
744                 return -ENOMEM;
745         }
746
747         info->xbdev = dev;
748         info->vdevice = vdevice;
749         info->connected = BLKIF_STATE_DISCONNECTED;
750         INIT_WORK(&info->work, blkif_restart_queue);
751
752         for (i = 0; i < BLK_RING_SIZE; i++)
753                 info->shadow[i].req.id = i+1;
754         info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
755
756         /* Front end dir is a number, which is used as the id. */
757         info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
758         dev->dev.driver_data = info;
759
760         err = talk_to_backend(dev, info);
761         if (err) {
762                 kfree(info);
763                 dev->dev.driver_data = NULL;
764                 return err;
765         }
766
767         return 0;
768 }
769
770
771 static int blkif_recover(struct blkfront_info *info)
772 {
773         int i;
774         struct blkif_request *req;
775         struct blk_shadow *copy;
776         int j;
777
778         /* Stage 1: Make a safe copy of the shadow state. */
779         copy = kmalloc(sizeof(info->shadow),
780                        GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
781         if (!copy)
782                 return -ENOMEM;
783         memcpy(copy, info->shadow, sizeof(info->shadow));
784
785         /* Stage 2: Set up free list. */
786         memset(&info->shadow, 0, sizeof(info->shadow));
787         for (i = 0; i < BLK_RING_SIZE; i++)
788                 info->shadow[i].req.id = i+1;
789         info->shadow_free = info->ring.req_prod_pvt;
790         info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
791
792         /* Stage 3: Find pending requests and requeue them. */
793         for (i = 0; i < BLK_RING_SIZE; i++) {
794                 /* Not in use? */
795                 if (copy[i].request == 0)
796                         continue;
797
798                 /* Grab a request slot and copy shadow state into it. */
799                 req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
800                 *req = copy[i].req;
801
802                 /* We get a new request id, and must reset the shadow state. */
803                 req->id = get_id_from_freelist(info);
804                 memcpy(&info->shadow[req->id], &copy[i], sizeof(copy[i]));
805
806                 /* Rewrite any grant references invalidated by susp/resume. */
807                 for (j = 0; j < req->nr_segments; j++)
808                         gnttab_grant_foreign_access_ref(
809                                 req->seg[j].gref,
810                                 info->xbdev->otherend_id,
811                                 pfn_to_mfn(info->shadow[req->id].frame[j]),
812                                 rq_data_dir(
813                                         (struct request *)
814                                         info->shadow[req->id].request));
815                 info->shadow[req->id].req = *req;
816
817                 info->ring.req_prod_pvt++;
818         }
819
820         kfree(copy);
821
822         xenbus_switch_state(info->xbdev, XenbusStateConnected);
823
824         spin_lock_irq(&blkif_io_lock);
825
826         /* Now safe for us to use the shared ring */
827         info->connected = BLKIF_STATE_CONNECTED;
828
829         /* Send off requeued requests */
830         flush_requests(info);
831
832         /* Kick any other new requests queued since we resumed */
833         kick_pending_request_queues(info);
834
835         spin_unlock_irq(&blkif_io_lock);
836
837         return 0;
838 }
839
840 /**
841  * We are reconnecting to the backend, due to a suspend/resume, or a backend
842  * driver restart.  We tear down our blkif structure and recreate it, but
843  * leave the device-layer structures intact so that this is transparent to the
844  * rest of the kernel.
845  */
846 static int blkfront_resume(struct xenbus_device *dev)
847 {
848         struct blkfront_info *info = dev->dev.driver_data;
849         int err;
850
851         dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
852
853         blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
854
855         err = talk_to_backend(dev, info);
856         if (info->connected == BLKIF_STATE_SUSPENDED && !err)
857                 err = blkif_recover(info);
858
859         return err;
860 }
861
862
863 /*
864  * Invoked when the backend is finally 'ready' (and has told produced
865  * the details about the physical device - #sectors, size, etc).
866  */
867 static void blkfront_connect(struct blkfront_info *info)
868 {
869         unsigned long long sectors;
870         unsigned long sector_size;
871         unsigned int binfo;
872         int err;
873
874         if ((info->connected == BLKIF_STATE_CONNECTED) ||
875             (info->connected == BLKIF_STATE_SUSPENDED) )
876                 return;
877
878         dev_dbg(&info->xbdev->dev, "%s:%s.\n",
879                 __func__, info->xbdev->otherend);
880
881         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
882                             "sectors", "%llu", &sectors,
883                             "info", "%u", &binfo,
884                             "sector-size", "%lu", &sector_size,
885                             NULL);
886         if (err) {
887                 xenbus_dev_fatal(info->xbdev, err,
888                                  "reading backend fields at %s",
889                                  info->xbdev->otherend);
890                 return;
891         }
892
893         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
894                             "feature-barrier", "%lu", &info->feature_barrier,
895                             NULL);
896         if (err)
897                 info->feature_barrier = 0;
898
899         err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size);
900         if (err) {
901                 xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
902                                  info->xbdev->otherend);
903                 return;
904         }
905
906         xenbus_switch_state(info->xbdev, XenbusStateConnected);
907
908         /* Kick pending requests. */
909         spin_lock_irq(&blkif_io_lock);
910         info->connected = BLKIF_STATE_CONNECTED;
911         kick_pending_request_queues(info);
912         spin_unlock_irq(&blkif_io_lock);
913
914         add_disk(info->gd);
915
916         info->is_ready = 1;
917 }
918
919 /**
920  * Handle the change of state of the backend to Closing.  We must delete our
921  * device-layer structures now, to ensure that writes are flushed through to
922  * the backend.  Once is this done, we can switch to Closed in
923  * acknowledgement.
924  */
925 static void blkfront_closing(struct xenbus_device *dev)
926 {
927         struct blkfront_info *info = dev->dev.driver_data;
928         unsigned long flags;
929
930         dev_dbg(&dev->dev, "blkfront_closing: %s removed\n", dev->nodename);
931
932         if (info->rq == NULL)
933                 goto out;
934
935         spin_lock_irqsave(&blkif_io_lock, flags);
936
937         del_gendisk(info->gd);
938
939         /* No more blkif_request(). */
940         blk_stop_queue(info->rq);
941
942         /* No more gnttab callback work. */
943         gnttab_cancel_free_callback(&info->callback);
944         spin_unlock_irqrestore(&blkif_io_lock, flags);
945
946         /* Flush gnttab callback work. Must be done with no locks held. */
947         flush_scheduled_work();
948
949         blk_cleanup_queue(info->rq);
950         info->rq = NULL;
951
952  out:
953         xenbus_frontend_closed(dev);
954 }
955
956 /**
957  * Callback received when the backend's state changes.
958  */
959 static void backend_changed(struct xenbus_device *dev,
960                             enum xenbus_state backend_state)
961 {
962         struct blkfront_info *info = dev->dev.driver_data;
963         struct block_device *bd;
964
965         dev_dbg(&dev->dev, "blkfront:backend_changed.\n");
966
967         switch (backend_state) {
968         case XenbusStateInitialising:
969         case XenbusStateInitWait:
970         case XenbusStateInitialised:
971         case XenbusStateUnknown:
972         case XenbusStateClosed:
973                 break;
974
975         case XenbusStateConnected:
976                 blkfront_connect(info);
977                 break;
978
979         case XenbusStateClosing:
980                 bd = bdget_disk(info->gd, 0);
981                 if (bd == NULL)
982                         xenbus_dev_fatal(dev, -ENODEV, "bdget failed");
983
984                 mutex_lock(&bd->bd_mutex);
985                 if (info->users > 0)
986                         xenbus_dev_error(dev, -EBUSY,
987                                          "Device in use; refusing to close");
988                 else
989                         blkfront_closing(dev);
990                 mutex_unlock(&bd->bd_mutex);
991                 bdput(bd);
992                 break;
993         }
994 }
995
996 static int blkfront_remove(struct xenbus_device *dev)
997 {
998         struct blkfront_info *info = dev->dev.driver_data;
999
1000         dev_dbg(&dev->dev, "blkfront_remove: %s removed\n", dev->nodename);
1001
1002         blkif_free(info, 0);
1003
1004         kfree(info);
1005
1006         return 0;
1007 }
1008
1009 static int blkfront_is_ready(struct xenbus_device *dev)
1010 {
1011         struct blkfront_info *info = dev->dev.driver_data;
1012
1013         return info->is_ready;
1014 }
1015
1016 static int blkif_open(struct block_device *bdev, fmode_t mode)
1017 {
1018         struct blkfront_info *info = bdev->bd_disk->private_data;
1019         info->users++;
1020         return 0;
1021 }
1022
1023 static int blkif_release(struct gendisk *disk, fmode_t mode)
1024 {
1025         struct blkfront_info *info = disk->private_data;
1026         info->users--;
1027         if (info->users == 0) {
1028                 /* Check whether we have been instructed to close.  We will
1029                    have ignored this request initially, as the device was
1030                    still mounted. */
1031                 struct xenbus_device *dev = info->xbdev;
1032                 enum xenbus_state state = xenbus_read_driver_state(dev->otherend);
1033
1034                 if (state == XenbusStateClosing && info->is_ready)
1035                         blkfront_closing(dev);
1036         }
1037         return 0;
1038 }
1039
1040 static struct block_device_operations xlvbd_block_fops =
1041 {
1042         .owner = THIS_MODULE,
1043         .open = blkif_open,
1044         .release = blkif_release,
1045         .getgeo = blkif_getgeo,
1046         .locked_ioctl = blkif_ioctl,
1047 };
1048
1049
1050 static struct xenbus_device_id blkfront_ids[] = {
1051         { "vbd" },
1052         { "" }
1053 };
1054
1055 static struct xenbus_driver blkfront = {
1056         .name = "vbd",
1057         .owner = THIS_MODULE,
1058         .ids = blkfront_ids,
1059         .probe = blkfront_probe,
1060         .remove = blkfront_remove,
1061         .resume = blkfront_resume,
1062         .otherend_changed = backend_changed,
1063         .is_ready = blkfront_is_ready,
1064 };
1065
1066 static int __init xlblk_init(void)
1067 {
1068         if (!xen_domain())
1069                 return -ENODEV;
1070
1071         if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
1072                 printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
1073                        XENVBD_MAJOR, DEV_NAME);
1074                 return -ENODEV;
1075         }
1076
1077         return xenbus_register_frontend(&blkfront);
1078 }
1079 module_init(xlblk_init);
1080
1081
1082 static void __exit xlblk_exit(void)
1083 {
1084         return xenbus_unregister_driver(&blkfront);
1085 }
1086 module_exit(xlblk_exit);
1087
1088 MODULE_DESCRIPTION("Xen virtual block device frontend");
1089 MODULE_LICENSE("GPL");
1090 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
1091 MODULE_ALIAS("xen:vbd");
1092 MODULE_ALIAS("xenblk");