block: add a bi_error field to struct bio
[linux-2.6-block.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 #include <linux/slab.h>
44 #include <linux/mutex.h>
45 #include <linux/scatterlist.h>
46 #include <linux/bitmap.h>
47 #include <linux/list.h>
48
49 #include <xen/xen.h>
50 #include <xen/xenbus.h>
51 #include <xen/grant_table.h>
52 #include <xen/events.h>
53 #include <xen/page.h>
54 #include <xen/platform_pci.h>
55
56 #include <xen/interface/grant_table.h>
57 #include <xen/interface/io/blkif.h>
58 #include <xen/interface/io/protocols.h>
59
60 #include <asm/xen/hypervisor.h>
61
62 enum blkif_state {
63         BLKIF_STATE_DISCONNECTED,
64         BLKIF_STATE_CONNECTED,
65         BLKIF_STATE_SUSPENDED,
66 };
67
68 struct grant {
69         grant_ref_t gref;
70         unsigned long pfn;
71         struct list_head node;
72 };
73
74 struct blk_shadow {
75         struct blkif_request req;
76         struct request *request;
77         struct grant **grants_used;
78         struct grant **indirect_grants;
79         struct scatterlist *sg;
80 };
81
82 struct split_bio {
83         struct bio *bio;
84         atomic_t pending;
85 };
86
87 static DEFINE_MUTEX(blkfront_mutex);
88 static const struct block_device_operations xlvbd_block_fops;
89
90 /*
91  * Maximum number of segments in indirect requests, the actual value used by
92  * the frontend driver is the minimum of this value and the value provided
93  * by the backend driver.
94  */
95
96 static unsigned int xen_blkif_max_segments = 32;
97 module_param_named(max, xen_blkif_max_segments, int, S_IRUGO);
98 MODULE_PARM_DESC(max, "Maximum amount of segments in indirect requests (default is 32)");
99
100 /*
101  * Maximum order of pages to be used for the shared ring between front and
102  * backend, 4KB page granularity is used.
103  */
104 static unsigned int xen_blkif_max_ring_order;
105 module_param_named(max_ring_page_order, xen_blkif_max_ring_order, int, S_IRUGO);
106 MODULE_PARM_DESC(max_ring_page_order, "Maximum order of pages to be used for the shared ring");
107
108 #define BLK_RING_SIZE(info) __CONST_RING_SIZE(blkif, PAGE_SIZE * (info)->nr_ring_pages)
109 #define BLK_MAX_RING_SIZE __CONST_RING_SIZE(blkif, PAGE_SIZE * XENBUS_MAX_RING_PAGES)
110 /*
111  * ring-ref%i i=(-1UL) would take 11 characters + 'ring-ref' is 8, so 19
112  * characters are enough. Define to 20 to keep consist with backend.
113  */
114 #define RINGREF_NAME_LEN (20)
115
116 /*
117  * We have one of these per vbd, whether ide, scsi or 'other'.  They
118  * hang in private_data off the gendisk structure. We may end up
119  * putting all kinds of interesting stuff here :-)
120  */
121 struct blkfront_info
122 {
123         spinlock_t io_lock;
124         struct mutex mutex;
125         struct xenbus_device *xbdev;
126         struct gendisk *gd;
127         int vdevice;
128         blkif_vdev_t handle;
129         enum blkif_state connected;
130         int ring_ref[XENBUS_MAX_RING_PAGES];
131         unsigned int nr_ring_pages;
132         struct blkif_front_ring ring;
133         unsigned int evtchn, irq;
134         struct request_queue *rq;
135         struct work_struct work;
136         struct gnttab_free_callback callback;
137         struct blk_shadow shadow[BLK_MAX_RING_SIZE];
138         struct list_head grants;
139         struct list_head indirect_pages;
140         unsigned int persistent_gnts_c;
141         unsigned long shadow_free;
142         unsigned int feature_flush;
143         unsigned int feature_discard:1;
144         unsigned int feature_secdiscard:1;
145         unsigned int discard_granularity;
146         unsigned int discard_alignment;
147         unsigned int feature_persistent:1;
148         unsigned int max_indirect_segments;
149         int is_ready;
150 };
151
152 static unsigned int nr_minors;
153 static unsigned long *minors;
154 static DEFINE_SPINLOCK(minor_lock);
155
156 #define GRANT_INVALID_REF       0
157
158 #define PARTS_PER_DISK          16
159 #define PARTS_PER_EXT_DISK      256
160
161 #define BLKIF_MAJOR(dev) ((dev)>>8)
162 #define BLKIF_MINOR(dev) ((dev) & 0xff)
163
164 #define EXT_SHIFT 28
165 #define EXTENDED (1<<EXT_SHIFT)
166 #define VDEV_IS_EXTENDED(dev) ((dev)&(EXTENDED))
167 #define BLKIF_MINOR_EXT(dev) ((dev)&(~EXTENDED))
168 #define EMULATED_HD_DISK_MINOR_OFFSET (0)
169 #define EMULATED_HD_DISK_NAME_OFFSET (EMULATED_HD_DISK_MINOR_OFFSET / 256)
170 #define EMULATED_SD_DISK_MINOR_OFFSET (0)
171 #define EMULATED_SD_DISK_NAME_OFFSET (EMULATED_SD_DISK_MINOR_OFFSET / 256)
172
173 #define DEV_NAME        "xvd"   /* name in /dev */
174
175 #define SEGS_PER_INDIRECT_FRAME \
176         (PAGE_SIZE/sizeof(struct blkif_request_segment))
177 #define INDIRECT_GREFS(_segs) \
178         ((_segs + SEGS_PER_INDIRECT_FRAME - 1)/SEGS_PER_INDIRECT_FRAME)
179
180 static int blkfront_setup_indirect(struct blkfront_info *info);
181
182 static int get_id_from_freelist(struct blkfront_info *info)
183 {
184         unsigned long free = info->shadow_free;
185         BUG_ON(free >= BLK_RING_SIZE(info));
186         info->shadow_free = info->shadow[free].req.u.rw.id;
187         info->shadow[free].req.u.rw.id = 0x0fffffee; /* debug */
188         return free;
189 }
190
191 static int add_id_to_freelist(struct blkfront_info *info,
192                                unsigned long id)
193 {
194         if (info->shadow[id].req.u.rw.id != id)
195                 return -EINVAL;
196         if (info->shadow[id].request == NULL)
197                 return -EINVAL;
198         info->shadow[id].req.u.rw.id  = info->shadow_free;
199         info->shadow[id].request = NULL;
200         info->shadow_free = id;
201         return 0;
202 }
203
204 static int fill_grant_buffer(struct blkfront_info *info, int num)
205 {
206         struct page *granted_page;
207         struct grant *gnt_list_entry, *n;
208         int i = 0;
209
210         while(i < num) {
211                 gnt_list_entry = kzalloc(sizeof(struct grant), GFP_NOIO);
212                 if (!gnt_list_entry)
213                         goto out_of_memory;
214
215                 if (info->feature_persistent) {
216                         granted_page = alloc_page(GFP_NOIO);
217                         if (!granted_page) {
218                                 kfree(gnt_list_entry);
219                                 goto out_of_memory;
220                         }
221                         gnt_list_entry->pfn = page_to_pfn(granted_page);
222                 }
223
224                 gnt_list_entry->gref = GRANT_INVALID_REF;
225                 list_add(&gnt_list_entry->node, &info->grants);
226                 i++;
227         }
228
229         return 0;
230
231 out_of_memory:
232         list_for_each_entry_safe(gnt_list_entry, n,
233                                  &info->grants, node) {
234                 list_del(&gnt_list_entry->node);
235                 if (info->feature_persistent)
236                         __free_page(pfn_to_page(gnt_list_entry->pfn));
237                 kfree(gnt_list_entry);
238                 i--;
239         }
240         BUG_ON(i != 0);
241         return -ENOMEM;
242 }
243
244 static struct grant *get_grant(grant_ref_t *gref_head,
245                                unsigned long pfn,
246                                struct blkfront_info *info)
247 {
248         struct grant *gnt_list_entry;
249         unsigned long buffer_mfn;
250
251         BUG_ON(list_empty(&info->grants));
252         gnt_list_entry = list_first_entry(&info->grants, struct grant,
253                                           node);
254         list_del(&gnt_list_entry->node);
255
256         if (gnt_list_entry->gref != GRANT_INVALID_REF) {
257                 info->persistent_gnts_c--;
258                 return gnt_list_entry;
259         }
260
261         /* Assign a gref to this page */
262         gnt_list_entry->gref = gnttab_claim_grant_reference(gref_head);
263         BUG_ON(gnt_list_entry->gref == -ENOSPC);
264         if (!info->feature_persistent) {
265                 BUG_ON(!pfn);
266                 gnt_list_entry->pfn = pfn;
267         }
268         buffer_mfn = pfn_to_mfn(gnt_list_entry->pfn);
269         gnttab_grant_foreign_access_ref(gnt_list_entry->gref,
270                                         info->xbdev->otherend_id,
271                                         buffer_mfn, 0);
272         return gnt_list_entry;
273 }
274
275 static const char *op_name(int op)
276 {
277         static const char *const names[] = {
278                 [BLKIF_OP_READ] = "read",
279                 [BLKIF_OP_WRITE] = "write",
280                 [BLKIF_OP_WRITE_BARRIER] = "barrier",
281                 [BLKIF_OP_FLUSH_DISKCACHE] = "flush",
282                 [BLKIF_OP_DISCARD] = "discard" };
283
284         if (op < 0 || op >= ARRAY_SIZE(names))
285                 return "unknown";
286
287         if (!names[op])
288                 return "reserved";
289
290         return names[op];
291 }
292 static int xlbd_reserve_minors(unsigned int minor, unsigned int nr)
293 {
294         unsigned int end = minor + nr;
295         int rc;
296
297         if (end > nr_minors) {
298                 unsigned long *bitmap, *old;
299
300                 bitmap = kcalloc(BITS_TO_LONGS(end), sizeof(*bitmap),
301                                  GFP_KERNEL);
302                 if (bitmap == NULL)
303                         return -ENOMEM;
304
305                 spin_lock(&minor_lock);
306                 if (end > nr_minors) {
307                         old = minors;
308                         memcpy(bitmap, minors,
309                                BITS_TO_LONGS(nr_minors) * sizeof(*bitmap));
310                         minors = bitmap;
311                         nr_minors = BITS_TO_LONGS(end) * BITS_PER_LONG;
312                 } else
313                         old = bitmap;
314                 spin_unlock(&minor_lock);
315                 kfree(old);
316         }
317
318         spin_lock(&minor_lock);
319         if (find_next_bit(minors, end, minor) >= end) {
320                 bitmap_set(minors, minor, nr);
321                 rc = 0;
322         } else
323                 rc = -EBUSY;
324         spin_unlock(&minor_lock);
325
326         return rc;
327 }
328
329 static void xlbd_release_minors(unsigned int minor, unsigned int nr)
330 {
331         unsigned int end = minor + nr;
332
333         BUG_ON(end > nr_minors);
334         spin_lock(&minor_lock);
335         bitmap_clear(minors,  minor, nr);
336         spin_unlock(&minor_lock);
337 }
338
339 static void blkif_restart_queue_callback(void *arg)
340 {
341         struct blkfront_info *info = (struct blkfront_info *)arg;
342         schedule_work(&info->work);
343 }
344
345 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
346 {
347         /* We don't have real geometry info, but let's at least return
348            values consistent with the size of the device */
349         sector_t nsect = get_capacity(bd->bd_disk);
350         sector_t cylinders = nsect;
351
352         hg->heads = 0xff;
353         hg->sectors = 0x3f;
354         sector_div(cylinders, hg->heads * hg->sectors);
355         hg->cylinders = cylinders;
356         if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
357                 hg->cylinders = 0xffff;
358         return 0;
359 }
360
361 static int blkif_ioctl(struct block_device *bdev, fmode_t mode,
362                        unsigned command, unsigned long argument)
363 {
364         struct blkfront_info *info = bdev->bd_disk->private_data;
365         int i;
366
367         dev_dbg(&info->xbdev->dev, "command: 0x%x, argument: 0x%lx\n",
368                 command, (long)argument);
369
370         switch (command) {
371         case CDROMMULTISESSION:
372                 dev_dbg(&info->xbdev->dev, "FIXME: support multisession CDs later\n");
373                 for (i = 0; i < sizeof(struct cdrom_multisession); i++)
374                         if (put_user(0, (char __user *)(argument + i)))
375                                 return -EFAULT;
376                 return 0;
377
378         case CDROM_GET_CAPABILITY: {
379                 struct gendisk *gd = info->gd;
380                 if (gd->flags & GENHD_FL_CD)
381                         return 0;
382                 return -EINVAL;
383         }
384
385         default:
386                 /*printk(KERN_ALERT "ioctl %08x not supported by Xen blkdev\n",
387                   command);*/
388                 return -EINVAL; /* same return as native Linux */
389         }
390
391         return 0;
392 }
393
394 /*
395  * Generate a Xen blkfront IO request from a blk layer request.  Reads
396  * and writes are handled as expected.
397  *
398  * @req: a request struct
399  */
400 static int blkif_queue_request(struct request *req)
401 {
402         struct blkfront_info *info = req->rq_disk->private_data;
403         struct blkif_request *ring_req;
404         unsigned long id;
405         unsigned int fsect, lsect;
406         int i, ref, n;
407         struct blkif_request_segment *segments = NULL;
408
409         /*
410          * Used to store if we are able to queue the request by just using
411          * existing persistent grants, or if we have to get new grants,
412          * as there are not sufficiently many free.
413          */
414         bool new_persistent_gnts;
415         grant_ref_t gref_head;
416         struct grant *gnt_list_entry = NULL;
417         struct scatterlist *sg;
418         int nseg, max_grefs;
419
420         if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
421                 return 1;
422
423         max_grefs = req->nr_phys_segments;
424         if (max_grefs > BLKIF_MAX_SEGMENTS_PER_REQUEST)
425                 /*
426                  * If we are using indirect segments we need to account
427                  * for the indirect grefs used in the request.
428                  */
429                 max_grefs += INDIRECT_GREFS(req->nr_phys_segments);
430
431         /* Check if we have enough grants to allocate a requests */
432         if (info->persistent_gnts_c < max_grefs) {
433                 new_persistent_gnts = 1;
434                 if (gnttab_alloc_grant_references(
435                     max_grefs - info->persistent_gnts_c,
436                     &gref_head) < 0) {
437                         gnttab_request_free_callback(
438                                 &info->callback,
439                                 blkif_restart_queue_callback,
440                                 info,
441                                 max_grefs);
442                         return 1;
443                 }
444         } else
445                 new_persistent_gnts = 0;
446
447         /* Fill out a communications ring structure. */
448         ring_req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
449         id = get_id_from_freelist(info);
450         info->shadow[id].request = req;
451
452         if (unlikely(req->cmd_flags & (REQ_DISCARD | REQ_SECURE))) {
453                 ring_req->operation = BLKIF_OP_DISCARD;
454                 ring_req->u.discard.nr_sectors = blk_rq_sectors(req);
455                 ring_req->u.discard.id = id;
456                 ring_req->u.discard.sector_number = (blkif_sector_t)blk_rq_pos(req);
457                 if ((req->cmd_flags & REQ_SECURE) && info->feature_secdiscard)
458                         ring_req->u.discard.flag = BLKIF_DISCARD_SECURE;
459                 else
460                         ring_req->u.discard.flag = 0;
461         } else {
462                 BUG_ON(info->max_indirect_segments == 0 &&
463                        req->nr_phys_segments > BLKIF_MAX_SEGMENTS_PER_REQUEST);
464                 BUG_ON(info->max_indirect_segments &&
465                        req->nr_phys_segments > info->max_indirect_segments);
466                 nseg = blk_rq_map_sg(req->q, req, info->shadow[id].sg);
467                 ring_req->u.rw.id = id;
468                 if (nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST) {
469                         /*
470                          * The indirect operation can only be a BLKIF_OP_READ or
471                          * BLKIF_OP_WRITE
472                          */
473                         BUG_ON(req->cmd_flags & (REQ_FLUSH | REQ_FUA));
474                         ring_req->operation = BLKIF_OP_INDIRECT;
475                         ring_req->u.indirect.indirect_op = rq_data_dir(req) ?
476                                 BLKIF_OP_WRITE : BLKIF_OP_READ;
477                         ring_req->u.indirect.sector_number = (blkif_sector_t)blk_rq_pos(req);
478                         ring_req->u.indirect.handle = info->handle;
479                         ring_req->u.indirect.nr_segments = nseg;
480                 } else {
481                         ring_req->u.rw.sector_number = (blkif_sector_t)blk_rq_pos(req);
482                         ring_req->u.rw.handle = info->handle;
483                         ring_req->operation = rq_data_dir(req) ?
484                                 BLKIF_OP_WRITE : BLKIF_OP_READ;
485                         if (req->cmd_flags & (REQ_FLUSH | REQ_FUA)) {
486                                 /*
487                                  * Ideally we can do an unordered flush-to-disk. In case the
488                                  * backend onlysupports barriers, use that. A barrier request
489                                  * a superset of FUA, so we can implement it the same
490                                  * way.  (It's also a FLUSH+FUA, since it is
491                                  * guaranteed ordered WRT previous writes.)
492                                  */
493                                 switch (info->feature_flush &
494                                         ((REQ_FLUSH|REQ_FUA))) {
495                                 case REQ_FLUSH|REQ_FUA:
496                                         ring_req->operation =
497                                                 BLKIF_OP_WRITE_BARRIER;
498                                         break;
499                                 case REQ_FLUSH:
500                                         ring_req->operation =
501                                                 BLKIF_OP_FLUSH_DISKCACHE;
502                                         break;
503                                 default:
504                                         ring_req->operation = 0;
505                                 }
506                         }
507                         ring_req->u.rw.nr_segments = nseg;
508                 }
509                 for_each_sg(info->shadow[id].sg, sg, nseg, i) {
510                         fsect = sg->offset >> 9;
511                         lsect = fsect + (sg->length >> 9) - 1;
512
513                         if ((ring_req->operation == BLKIF_OP_INDIRECT) &&
514                             (i % SEGS_PER_INDIRECT_FRAME == 0)) {
515                                 unsigned long uninitialized_var(pfn);
516
517                                 if (segments)
518                                         kunmap_atomic(segments);
519
520                                 n = i / SEGS_PER_INDIRECT_FRAME;
521                                 if (!info->feature_persistent) {
522                                         struct page *indirect_page;
523
524                                         /* Fetch a pre-allocated page to use for indirect grefs */
525                                         BUG_ON(list_empty(&info->indirect_pages));
526                                         indirect_page = list_first_entry(&info->indirect_pages,
527                                                                          struct page, lru);
528                                         list_del(&indirect_page->lru);
529                                         pfn = page_to_pfn(indirect_page);
530                                 }
531                                 gnt_list_entry = get_grant(&gref_head, pfn, info);
532                                 info->shadow[id].indirect_grants[n] = gnt_list_entry;
533                                 segments = kmap_atomic(pfn_to_page(gnt_list_entry->pfn));
534                                 ring_req->u.indirect.indirect_grefs[n] = gnt_list_entry->gref;
535                         }
536
537                         gnt_list_entry = get_grant(&gref_head, page_to_pfn(sg_page(sg)), info);
538                         ref = gnt_list_entry->gref;
539
540                         info->shadow[id].grants_used[i] = gnt_list_entry;
541
542                         if (rq_data_dir(req) && info->feature_persistent) {
543                                 char *bvec_data;
544                                 void *shared_data;
545
546                                 BUG_ON(sg->offset + sg->length > PAGE_SIZE);
547
548                                 shared_data = kmap_atomic(pfn_to_page(gnt_list_entry->pfn));
549                                 bvec_data = kmap_atomic(sg_page(sg));
550
551                                 /*
552                                  * this does not wipe data stored outside the
553                                  * range sg->offset..sg->offset+sg->length.
554                                  * Therefore, blkback *could* see data from
555                                  * previous requests. This is OK as long as
556                                  * persistent grants are shared with just one
557                                  * domain. It may need refactoring if this
558                                  * changes
559                                  */
560                                 memcpy(shared_data + sg->offset,
561                                        bvec_data   + sg->offset,
562                                        sg->length);
563
564                                 kunmap_atomic(bvec_data);
565                                 kunmap_atomic(shared_data);
566                         }
567                         if (ring_req->operation != BLKIF_OP_INDIRECT) {
568                                 ring_req->u.rw.seg[i] =
569                                                 (struct blkif_request_segment) {
570                                                         .gref       = ref,
571                                                         .first_sect = fsect,
572                                                         .last_sect  = lsect };
573                         } else {
574                                 n = i % SEGS_PER_INDIRECT_FRAME;
575                                 segments[n] =
576                                         (struct blkif_request_segment) {
577                                                         .gref       = ref,
578                                                         .first_sect = fsect,
579                                                         .last_sect  = lsect };
580                         }
581                 }
582                 if (segments)
583                         kunmap_atomic(segments);
584         }
585
586         info->ring.req_prod_pvt++;
587
588         /* Keep a private copy so we can reissue requests when recovering. */
589         info->shadow[id].req = *ring_req;
590
591         if (new_persistent_gnts)
592                 gnttab_free_grant_references(gref_head);
593
594         return 0;
595 }
596
597
598 static inline void flush_requests(struct blkfront_info *info)
599 {
600         int notify;
601
602         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
603
604         if (notify)
605                 notify_remote_via_irq(info->irq);
606 }
607
608 static inline bool blkif_request_flush_invalid(struct request *req,
609                                                struct blkfront_info *info)
610 {
611         return ((req->cmd_type != REQ_TYPE_FS) ||
612                 ((req->cmd_flags & REQ_FLUSH) &&
613                  !(info->feature_flush & REQ_FLUSH)) ||
614                 ((req->cmd_flags & REQ_FUA) &&
615                  !(info->feature_flush & REQ_FUA)));
616 }
617
618 /*
619  * do_blkif_request
620  *  read a block; request is in a request queue
621  */
622 static void do_blkif_request(struct request_queue *rq)
623 {
624         struct blkfront_info *info = NULL;
625         struct request *req;
626         int queued;
627
628         pr_debug("Entered do_blkif_request\n");
629
630         queued = 0;
631
632         while ((req = blk_peek_request(rq)) != NULL) {
633                 info = req->rq_disk->private_data;
634
635                 if (RING_FULL(&info->ring))
636                         goto wait;
637
638                 blk_start_request(req);
639
640                 if (blkif_request_flush_invalid(req, info)) {
641                         __blk_end_request_all(req, -EOPNOTSUPP);
642                         continue;
643                 }
644
645                 pr_debug("do_blk_req %p: cmd %p, sec %lx, "
646                          "(%u/%u) [%s]\n",
647                          req, req->cmd, (unsigned long)blk_rq_pos(req),
648                          blk_rq_cur_sectors(req), blk_rq_sectors(req),
649                          rq_data_dir(req) ? "write" : "read");
650
651                 if (blkif_queue_request(req)) {
652                         blk_requeue_request(rq, req);
653 wait:
654                         /* Avoid pointless unplugs. */
655                         blk_stop_queue(rq);
656                         break;
657                 }
658
659                 queued++;
660         }
661
662         if (queued != 0)
663                 flush_requests(info);
664 }
665
666 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size,
667                                 unsigned int physical_sector_size,
668                                 unsigned int segments)
669 {
670         struct request_queue *rq;
671         struct blkfront_info *info = gd->private_data;
672
673         rq = blk_init_queue(do_blkif_request, &info->io_lock);
674         if (rq == NULL)
675                 return -1;
676
677         queue_flag_set_unlocked(QUEUE_FLAG_VIRT, rq);
678
679         if (info->feature_discard) {
680                 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, rq);
681                 blk_queue_max_discard_sectors(rq, get_capacity(gd));
682                 rq->limits.discard_granularity = info->discard_granularity;
683                 rq->limits.discard_alignment = info->discard_alignment;
684                 if (info->feature_secdiscard)
685                         queue_flag_set_unlocked(QUEUE_FLAG_SECDISCARD, rq);
686         }
687
688         /* Hard sector size and max sectors impersonate the equiv. hardware. */
689         blk_queue_logical_block_size(rq, sector_size);
690         blk_queue_physical_block_size(rq, physical_sector_size);
691         blk_queue_max_hw_sectors(rq, (segments * PAGE_SIZE) / 512);
692
693         /* Each segment in a request is up to an aligned page in size. */
694         blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
695         blk_queue_max_segment_size(rq, PAGE_SIZE);
696
697         /* Ensure a merged request will fit in a single I/O ring slot. */
698         blk_queue_max_segments(rq, segments);
699
700         /* Make sure buffer addresses are sector-aligned. */
701         blk_queue_dma_alignment(rq, 511);
702
703         /* Make sure we don't use bounce buffers. */
704         blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
705
706         gd->queue = rq;
707
708         return 0;
709 }
710
711 static const char *flush_info(unsigned int feature_flush)
712 {
713         switch (feature_flush & ((REQ_FLUSH | REQ_FUA))) {
714         case REQ_FLUSH|REQ_FUA:
715                 return "barrier: enabled;";
716         case REQ_FLUSH:
717                 return "flush diskcache: enabled;";
718         default:
719                 return "barrier or flush: disabled;";
720         }
721 }
722
723 static void xlvbd_flush(struct blkfront_info *info)
724 {
725         blk_queue_flush(info->rq, info->feature_flush);
726         pr_info("blkfront: %s: %s %s %s %s %s\n",
727                 info->gd->disk_name, flush_info(info->feature_flush),
728                 "persistent grants:", info->feature_persistent ?
729                 "enabled;" : "disabled;", "indirect descriptors:",
730                 info->max_indirect_segments ? "enabled;" : "disabled;");
731 }
732
733 static int xen_translate_vdev(int vdevice, int *minor, unsigned int *offset)
734 {
735         int major;
736         major = BLKIF_MAJOR(vdevice);
737         *minor = BLKIF_MINOR(vdevice);
738         switch (major) {
739                 case XEN_IDE0_MAJOR:
740                         *offset = (*minor / 64) + EMULATED_HD_DISK_NAME_OFFSET;
741                         *minor = ((*minor / 64) * PARTS_PER_DISK) +
742                                 EMULATED_HD_DISK_MINOR_OFFSET;
743                         break;
744                 case XEN_IDE1_MAJOR:
745                         *offset = (*minor / 64) + 2 + EMULATED_HD_DISK_NAME_OFFSET;
746                         *minor = (((*minor / 64) + 2) * PARTS_PER_DISK) +
747                                 EMULATED_HD_DISK_MINOR_OFFSET;
748                         break;
749                 case XEN_SCSI_DISK0_MAJOR:
750                         *offset = (*minor / PARTS_PER_DISK) + EMULATED_SD_DISK_NAME_OFFSET;
751                         *minor = *minor + EMULATED_SD_DISK_MINOR_OFFSET;
752                         break;
753                 case XEN_SCSI_DISK1_MAJOR:
754                 case XEN_SCSI_DISK2_MAJOR:
755                 case XEN_SCSI_DISK3_MAJOR:
756                 case XEN_SCSI_DISK4_MAJOR:
757                 case XEN_SCSI_DISK5_MAJOR:
758                 case XEN_SCSI_DISK6_MAJOR:
759                 case XEN_SCSI_DISK7_MAJOR:
760                         *offset = (*minor / PARTS_PER_DISK) + 
761                                 ((major - XEN_SCSI_DISK1_MAJOR + 1) * 16) +
762                                 EMULATED_SD_DISK_NAME_OFFSET;
763                         *minor = *minor +
764                                 ((major - XEN_SCSI_DISK1_MAJOR + 1) * 16 * PARTS_PER_DISK) +
765                                 EMULATED_SD_DISK_MINOR_OFFSET;
766                         break;
767                 case XEN_SCSI_DISK8_MAJOR:
768                 case XEN_SCSI_DISK9_MAJOR:
769                 case XEN_SCSI_DISK10_MAJOR:
770                 case XEN_SCSI_DISK11_MAJOR:
771                 case XEN_SCSI_DISK12_MAJOR:
772                 case XEN_SCSI_DISK13_MAJOR:
773                 case XEN_SCSI_DISK14_MAJOR:
774                 case XEN_SCSI_DISK15_MAJOR:
775                         *offset = (*minor / PARTS_PER_DISK) + 
776                                 ((major - XEN_SCSI_DISK8_MAJOR + 8) * 16) +
777                                 EMULATED_SD_DISK_NAME_OFFSET;
778                         *minor = *minor +
779                                 ((major - XEN_SCSI_DISK8_MAJOR + 8) * 16 * PARTS_PER_DISK) +
780                                 EMULATED_SD_DISK_MINOR_OFFSET;
781                         break;
782                 case XENVBD_MAJOR:
783                         *offset = *minor / PARTS_PER_DISK;
784                         break;
785                 default:
786                         printk(KERN_WARNING "blkfront: your disk configuration is "
787                                         "incorrect, please use an xvd device instead\n");
788                         return -ENODEV;
789         }
790         return 0;
791 }
792
793 static char *encode_disk_name(char *ptr, unsigned int n)
794 {
795         if (n >= 26)
796                 ptr = encode_disk_name(ptr, n / 26 - 1);
797         *ptr = 'a' + n % 26;
798         return ptr + 1;
799 }
800
801 static int xlvbd_alloc_gendisk(blkif_sector_t capacity,
802                                struct blkfront_info *info,
803                                u16 vdisk_info, u16 sector_size,
804                                unsigned int physical_sector_size)
805 {
806         struct gendisk *gd;
807         int nr_minors = 1;
808         int err;
809         unsigned int offset;
810         int minor;
811         int nr_parts;
812         char *ptr;
813
814         BUG_ON(info->gd != NULL);
815         BUG_ON(info->rq != NULL);
816
817         if ((info->vdevice>>EXT_SHIFT) > 1) {
818                 /* this is above the extended range; something is wrong */
819                 printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
820                 return -ENODEV;
821         }
822
823         if (!VDEV_IS_EXTENDED(info->vdevice)) {
824                 err = xen_translate_vdev(info->vdevice, &minor, &offset);
825                 if (err)
826                         return err;             
827                 nr_parts = PARTS_PER_DISK;
828         } else {
829                 minor = BLKIF_MINOR_EXT(info->vdevice);
830                 nr_parts = PARTS_PER_EXT_DISK;
831                 offset = minor / nr_parts;
832                 if (xen_hvm_domain() && offset < EMULATED_HD_DISK_NAME_OFFSET + 4)
833                         printk(KERN_WARNING "blkfront: vdevice 0x%x might conflict with "
834                                         "emulated IDE disks,\n\t choose an xvd device name"
835                                         "from xvde on\n", info->vdevice);
836         }
837         if (minor >> MINORBITS) {
838                 pr_warn("blkfront: %#x's minor (%#x) out of range; ignoring\n",
839                         info->vdevice, minor);
840                 return -ENODEV;
841         }
842
843         if ((minor % nr_parts) == 0)
844                 nr_minors = nr_parts;
845
846         err = xlbd_reserve_minors(minor, nr_minors);
847         if (err)
848                 goto out;
849         err = -ENODEV;
850
851         gd = alloc_disk(nr_minors);
852         if (gd == NULL)
853                 goto release;
854
855         strcpy(gd->disk_name, DEV_NAME);
856         ptr = encode_disk_name(gd->disk_name + sizeof(DEV_NAME) - 1, offset);
857         BUG_ON(ptr >= gd->disk_name + DISK_NAME_LEN);
858         if (nr_minors > 1)
859                 *ptr = 0;
860         else
861                 snprintf(ptr, gd->disk_name + DISK_NAME_LEN - ptr,
862                          "%d", minor & (nr_parts - 1));
863
864         gd->major = XENVBD_MAJOR;
865         gd->first_minor = minor;
866         gd->fops = &xlvbd_block_fops;
867         gd->private_data = info;
868         gd->driverfs_dev = &(info->xbdev->dev);
869         set_capacity(gd, capacity);
870
871         if (xlvbd_init_blk_queue(gd, sector_size, physical_sector_size,
872                                  info->max_indirect_segments ? :
873                                  BLKIF_MAX_SEGMENTS_PER_REQUEST)) {
874                 del_gendisk(gd);
875                 goto release;
876         }
877
878         info->rq = gd->queue;
879         info->gd = gd;
880
881         xlvbd_flush(info);
882
883         if (vdisk_info & VDISK_READONLY)
884                 set_disk_ro(gd, 1);
885
886         if (vdisk_info & VDISK_REMOVABLE)
887                 gd->flags |= GENHD_FL_REMOVABLE;
888
889         if (vdisk_info & VDISK_CDROM)
890                 gd->flags |= GENHD_FL_CD;
891
892         return 0;
893
894  release:
895         xlbd_release_minors(minor, nr_minors);
896  out:
897         return err;
898 }
899
900 static void xlvbd_release_gendisk(struct blkfront_info *info)
901 {
902         unsigned int minor, nr_minors;
903         unsigned long flags;
904
905         if (info->rq == NULL)
906                 return;
907
908         spin_lock_irqsave(&info->io_lock, flags);
909
910         /* No more blkif_request(). */
911         blk_stop_queue(info->rq);
912
913         /* No more gnttab callback work. */
914         gnttab_cancel_free_callback(&info->callback);
915         spin_unlock_irqrestore(&info->io_lock, flags);
916
917         /* Flush gnttab callback work. Must be done with no locks held. */
918         flush_work(&info->work);
919
920         del_gendisk(info->gd);
921
922         minor = info->gd->first_minor;
923         nr_minors = info->gd->minors;
924         xlbd_release_minors(minor, nr_minors);
925
926         blk_cleanup_queue(info->rq);
927         info->rq = NULL;
928
929         put_disk(info->gd);
930         info->gd = NULL;
931 }
932
933 static void kick_pending_request_queues(struct blkfront_info *info)
934 {
935         if (!RING_FULL(&info->ring)) {
936                 /* Re-enable calldowns. */
937                 blk_start_queue(info->rq);
938                 /* Kick things off immediately. */
939                 do_blkif_request(info->rq);
940         }
941 }
942
943 static void blkif_restart_queue(struct work_struct *work)
944 {
945         struct blkfront_info *info = container_of(work, struct blkfront_info, work);
946
947         spin_lock_irq(&info->io_lock);
948         if (info->connected == BLKIF_STATE_CONNECTED)
949                 kick_pending_request_queues(info);
950         spin_unlock_irq(&info->io_lock);
951 }
952
953 static void blkif_free(struct blkfront_info *info, int suspend)
954 {
955         struct grant *persistent_gnt;
956         struct grant *n;
957         int i, j, segs;
958
959         /* Prevent new requests being issued until we fix things up. */
960         spin_lock_irq(&info->io_lock);
961         info->connected = suspend ?
962                 BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
963         /* No more blkif_request(). */
964         if (info->rq)
965                 blk_stop_queue(info->rq);
966
967         /* Remove all persistent grants */
968         if (!list_empty(&info->grants)) {
969                 list_for_each_entry_safe(persistent_gnt, n,
970                                          &info->grants, node) {
971                         list_del(&persistent_gnt->node);
972                         if (persistent_gnt->gref != GRANT_INVALID_REF) {
973                                 gnttab_end_foreign_access(persistent_gnt->gref,
974                                                           0, 0UL);
975                                 info->persistent_gnts_c--;
976                         }
977                         if (info->feature_persistent)
978                                 __free_page(pfn_to_page(persistent_gnt->pfn));
979                         kfree(persistent_gnt);
980                 }
981         }
982         BUG_ON(info->persistent_gnts_c != 0);
983
984         /*
985          * Remove indirect pages, this only happens when using indirect
986          * descriptors but not persistent grants
987          */
988         if (!list_empty(&info->indirect_pages)) {
989                 struct page *indirect_page, *n;
990
991                 BUG_ON(info->feature_persistent);
992                 list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
993                         list_del(&indirect_page->lru);
994                         __free_page(indirect_page);
995                 }
996         }
997
998         for (i = 0; i < BLK_RING_SIZE(info); i++) {
999                 /*
1000                  * Clear persistent grants present in requests already
1001                  * on the shared ring
1002                  */
1003                 if (!info->shadow[i].request)
1004                         goto free_shadow;
1005
1006                 segs = info->shadow[i].req.operation == BLKIF_OP_INDIRECT ?
1007                        info->shadow[i].req.u.indirect.nr_segments :
1008                        info->shadow[i].req.u.rw.nr_segments;
1009                 for (j = 0; j < segs; j++) {
1010                         persistent_gnt = info->shadow[i].grants_used[j];
1011                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1012                         if (info->feature_persistent)
1013                                 __free_page(pfn_to_page(persistent_gnt->pfn));
1014                         kfree(persistent_gnt);
1015                 }
1016
1017                 if (info->shadow[i].req.operation != BLKIF_OP_INDIRECT)
1018                         /*
1019                          * If this is not an indirect operation don't try to
1020                          * free indirect segments
1021                          */
1022                         goto free_shadow;
1023
1024                 for (j = 0; j < INDIRECT_GREFS(segs); j++) {
1025                         persistent_gnt = info->shadow[i].indirect_grants[j];
1026                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1027                         __free_page(pfn_to_page(persistent_gnt->pfn));
1028                         kfree(persistent_gnt);
1029                 }
1030
1031 free_shadow:
1032                 kfree(info->shadow[i].grants_used);
1033                 info->shadow[i].grants_used = NULL;
1034                 kfree(info->shadow[i].indirect_grants);
1035                 info->shadow[i].indirect_grants = NULL;
1036                 kfree(info->shadow[i].sg);
1037                 info->shadow[i].sg = NULL;
1038         }
1039
1040         /* No more gnttab callback work. */
1041         gnttab_cancel_free_callback(&info->callback);
1042         spin_unlock_irq(&info->io_lock);
1043
1044         /* Flush gnttab callback work. Must be done with no locks held. */
1045         flush_work(&info->work);
1046
1047         /* Free resources associated with old device channel. */
1048         for (i = 0; i < info->nr_ring_pages; i++) {
1049                 if (info->ring_ref[i] != GRANT_INVALID_REF) {
1050                         gnttab_end_foreign_access(info->ring_ref[i], 0, 0);
1051                         info->ring_ref[i] = GRANT_INVALID_REF;
1052                 }
1053         }
1054         free_pages((unsigned long)info->ring.sring, get_order(info->nr_ring_pages * PAGE_SIZE));
1055         info->ring.sring = NULL;
1056
1057         if (info->irq)
1058                 unbind_from_irqhandler(info->irq, info);
1059         info->evtchn = info->irq = 0;
1060
1061 }
1062
1063 static void blkif_completion(struct blk_shadow *s, struct blkfront_info *info,
1064                              struct blkif_response *bret)
1065 {
1066         int i = 0;
1067         struct scatterlist *sg;
1068         char *bvec_data;
1069         void *shared_data;
1070         int nseg;
1071
1072         nseg = s->req.operation == BLKIF_OP_INDIRECT ?
1073                 s->req.u.indirect.nr_segments : s->req.u.rw.nr_segments;
1074
1075         if (bret->operation == BLKIF_OP_READ && info->feature_persistent) {
1076                 for_each_sg(s->sg, sg, nseg, i) {
1077                         BUG_ON(sg->offset + sg->length > PAGE_SIZE);
1078                         shared_data = kmap_atomic(
1079                                 pfn_to_page(s->grants_used[i]->pfn));
1080                         bvec_data = kmap_atomic(sg_page(sg));
1081                         memcpy(bvec_data   + sg->offset,
1082                                shared_data + sg->offset,
1083                                sg->length);
1084                         kunmap_atomic(bvec_data);
1085                         kunmap_atomic(shared_data);
1086                 }
1087         }
1088         /* Add the persistent grant into the list of free grants */
1089         for (i = 0; i < nseg; i++) {
1090                 if (gnttab_query_foreign_access(s->grants_used[i]->gref)) {
1091                         /*
1092                          * If the grant is still mapped by the backend (the
1093                          * backend has chosen to make this grant persistent)
1094                          * we add it at the head of the list, so it will be
1095                          * reused first.
1096                          */
1097                         if (!info->feature_persistent)
1098                                 pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1099                                                      s->grants_used[i]->gref);
1100                         list_add(&s->grants_used[i]->node, &info->grants);
1101                         info->persistent_gnts_c++;
1102                 } else {
1103                         /*
1104                          * If the grant is not mapped by the backend we end the
1105                          * foreign access and add it to the tail of the list,
1106                          * so it will not be picked again unless we run out of
1107                          * persistent grants.
1108                          */
1109                         gnttab_end_foreign_access(s->grants_used[i]->gref, 0, 0UL);
1110                         s->grants_used[i]->gref = GRANT_INVALID_REF;
1111                         list_add_tail(&s->grants_used[i]->node, &info->grants);
1112                 }
1113         }
1114         if (s->req.operation == BLKIF_OP_INDIRECT) {
1115                 for (i = 0; i < INDIRECT_GREFS(nseg); i++) {
1116                         if (gnttab_query_foreign_access(s->indirect_grants[i]->gref)) {
1117                                 if (!info->feature_persistent)
1118                                         pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1119                                                              s->indirect_grants[i]->gref);
1120                                 list_add(&s->indirect_grants[i]->node, &info->grants);
1121                                 info->persistent_gnts_c++;
1122                         } else {
1123                                 struct page *indirect_page;
1124
1125                                 gnttab_end_foreign_access(s->indirect_grants[i]->gref, 0, 0UL);
1126                                 /*
1127                                  * Add the used indirect page back to the list of
1128                                  * available pages for indirect grefs.
1129                                  */
1130                                 indirect_page = pfn_to_page(s->indirect_grants[i]->pfn);
1131                                 list_add(&indirect_page->lru, &info->indirect_pages);
1132                                 s->indirect_grants[i]->gref = GRANT_INVALID_REF;
1133                                 list_add_tail(&s->indirect_grants[i]->node, &info->grants);
1134                         }
1135                 }
1136         }
1137 }
1138
1139 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
1140 {
1141         struct request *req;
1142         struct blkif_response *bret;
1143         RING_IDX i, rp;
1144         unsigned long flags;
1145         struct blkfront_info *info = (struct blkfront_info *)dev_id;
1146         int error;
1147
1148         spin_lock_irqsave(&info->io_lock, flags);
1149
1150         if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
1151                 spin_unlock_irqrestore(&info->io_lock, flags);
1152                 return IRQ_HANDLED;
1153         }
1154
1155  again:
1156         rp = info->ring.sring->rsp_prod;
1157         rmb(); /* Ensure we see queued responses up to 'rp'. */
1158
1159         for (i = info->ring.rsp_cons; i != rp; i++) {
1160                 unsigned long id;
1161
1162                 bret = RING_GET_RESPONSE(&info->ring, i);
1163                 id   = bret->id;
1164                 /*
1165                  * The backend has messed up and given us an id that we would
1166                  * never have given to it (we stamp it up to BLK_RING_SIZE -
1167                  * look in get_id_from_freelist.
1168                  */
1169                 if (id >= BLK_RING_SIZE(info)) {
1170                         WARN(1, "%s: response to %s has incorrect id (%ld)\n",
1171                              info->gd->disk_name, op_name(bret->operation), id);
1172                         /* We can't safely get the 'struct request' as
1173                          * the id is busted. */
1174                         continue;
1175                 }
1176                 req  = info->shadow[id].request;
1177
1178                 if (bret->operation != BLKIF_OP_DISCARD)
1179                         blkif_completion(&info->shadow[id], info, bret);
1180
1181                 if (add_id_to_freelist(info, id)) {
1182                         WARN(1, "%s: response to %s (id %ld) couldn't be recycled!\n",
1183                              info->gd->disk_name, op_name(bret->operation), id);
1184                         continue;
1185                 }
1186
1187                 error = (bret->status == BLKIF_RSP_OKAY) ? 0 : -EIO;
1188                 switch (bret->operation) {
1189                 case BLKIF_OP_DISCARD:
1190                         if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
1191                                 struct request_queue *rq = info->rq;
1192                                 printk(KERN_WARNING "blkfront: %s: %s op failed\n",
1193                                            info->gd->disk_name, op_name(bret->operation));
1194                                 error = -EOPNOTSUPP;
1195                                 info->feature_discard = 0;
1196                                 info->feature_secdiscard = 0;
1197                                 queue_flag_clear(QUEUE_FLAG_DISCARD, rq);
1198                                 queue_flag_clear(QUEUE_FLAG_SECDISCARD, rq);
1199                         }
1200                         __blk_end_request_all(req, error);
1201                         break;
1202                 case BLKIF_OP_FLUSH_DISKCACHE:
1203                 case BLKIF_OP_WRITE_BARRIER:
1204                         if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
1205                                 printk(KERN_WARNING "blkfront: %s: %s op failed\n",
1206                                        info->gd->disk_name, op_name(bret->operation));
1207                                 error = -EOPNOTSUPP;
1208                         }
1209                         if (unlikely(bret->status == BLKIF_RSP_ERROR &&
1210                                      info->shadow[id].req.u.rw.nr_segments == 0)) {
1211                                 printk(KERN_WARNING "blkfront: %s: empty %s op failed\n",
1212                                        info->gd->disk_name, op_name(bret->operation));
1213                                 error = -EOPNOTSUPP;
1214                         }
1215                         if (unlikely(error)) {
1216                                 if (error == -EOPNOTSUPP)
1217                                         error = 0;
1218                                 info->feature_flush = 0;
1219                                 xlvbd_flush(info);
1220                         }
1221                         /* fall through */
1222                 case BLKIF_OP_READ:
1223                 case BLKIF_OP_WRITE:
1224                         if (unlikely(bret->status != BLKIF_RSP_OKAY))
1225                                 dev_dbg(&info->xbdev->dev, "Bad return from blkdev data "
1226                                         "request: %x\n", bret->status);
1227
1228                         __blk_end_request_all(req, error);
1229                         break;
1230                 default:
1231                         BUG();
1232                 }
1233         }
1234
1235         info->ring.rsp_cons = i;
1236
1237         if (i != info->ring.req_prod_pvt) {
1238                 int more_to_do;
1239                 RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
1240                 if (more_to_do)
1241                         goto again;
1242         } else
1243                 info->ring.sring->rsp_event = i + 1;
1244
1245         kick_pending_request_queues(info);
1246
1247         spin_unlock_irqrestore(&info->io_lock, flags);
1248
1249         return IRQ_HANDLED;
1250 }
1251
1252
1253 static int setup_blkring(struct xenbus_device *dev,
1254                          struct blkfront_info *info)
1255 {
1256         struct blkif_sring *sring;
1257         int err, i;
1258         unsigned long ring_size = info->nr_ring_pages * PAGE_SIZE;
1259         grant_ref_t gref[XENBUS_MAX_RING_PAGES];
1260
1261         for (i = 0; i < info->nr_ring_pages; i++)
1262                 info->ring_ref[i] = GRANT_INVALID_REF;
1263
1264         sring = (struct blkif_sring *)__get_free_pages(GFP_NOIO | __GFP_HIGH,
1265                                                        get_order(ring_size));
1266         if (!sring) {
1267                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
1268                 return -ENOMEM;
1269         }
1270         SHARED_RING_INIT(sring);
1271         FRONT_RING_INIT(&info->ring, sring, ring_size);
1272
1273         err = xenbus_grant_ring(dev, info->ring.sring, info->nr_ring_pages, gref);
1274         if (err < 0) {
1275                 free_pages((unsigned long)sring, get_order(ring_size));
1276                 info->ring.sring = NULL;
1277                 goto fail;
1278         }
1279         for (i = 0; i < info->nr_ring_pages; i++)
1280                 info->ring_ref[i] = gref[i];
1281
1282         err = xenbus_alloc_evtchn(dev, &info->evtchn);
1283         if (err)
1284                 goto fail;
1285
1286         err = bind_evtchn_to_irqhandler(info->evtchn, blkif_interrupt, 0,
1287                                         "blkif", info);
1288         if (err <= 0) {
1289                 xenbus_dev_fatal(dev, err,
1290                                  "bind_evtchn_to_irqhandler failed");
1291                 goto fail;
1292         }
1293         info->irq = err;
1294
1295         return 0;
1296 fail:
1297         blkif_free(info, 0);
1298         return err;
1299 }
1300
1301
1302 /* Common code used when first setting up, and when resuming. */
1303 static int talk_to_blkback(struct xenbus_device *dev,
1304                            struct blkfront_info *info)
1305 {
1306         const char *message = NULL;
1307         struct xenbus_transaction xbt;
1308         int err, i;
1309         unsigned int max_page_order = 0;
1310         unsigned int ring_page_order = 0;
1311
1312         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1313                            "max-ring-page-order", "%u", &max_page_order);
1314         if (err != 1)
1315                 info->nr_ring_pages = 1;
1316         else {
1317                 ring_page_order = min(xen_blkif_max_ring_order, max_page_order);
1318                 info->nr_ring_pages = 1 << ring_page_order;
1319         }
1320
1321         /* Create shared ring, alloc event channel. */
1322         err = setup_blkring(dev, info);
1323         if (err)
1324                 goto out;
1325
1326 again:
1327         err = xenbus_transaction_start(&xbt);
1328         if (err) {
1329                 xenbus_dev_fatal(dev, err, "starting transaction");
1330                 goto destroy_blkring;
1331         }
1332
1333         if (info->nr_ring_pages == 1) {
1334                 err = xenbus_printf(xbt, dev->nodename,
1335                                     "ring-ref", "%u", info->ring_ref[0]);
1336                 if (err) {
1337                         message = "writing ring-ref";
1338                         goto abort_transaction;
1339                 }
1340         } else {
1341                 err = xenbus_printf(xbt, dev->nodename,
1342                                     "ring-page-order", "%u", ring_page_order);
1343                 if (err) {
1344                         message = "writing ring-page-order";
1345                         goto abort_transaction;
1346                 }
1347
1348                 for (i = 0; i < info->nr_ring_pages; i++) {
1349                         char ring_ref_name[RINGREF_NAME_LEN];
1350
1351                         snprintf(ring_ref_name, RINGREF_NAME_LEN, "ring-ref%u", i);
1352                         err = xenbus_printf(xbt, dev->nodename, ring_ref_name,
1353                                             "%u", info->ring_ref[i]);
1354                         if (err) {
1355                                 message = "writing ring-ref";
1356                                 goto abort_transaction;
1357                         }
1358                 }
1359         }
1360         err = xenbus_printf(xbt, dev->nodename,
1361                             "event-channel", "%u", info->evtchn);
1362         if (err) {
1363                 message = "writing event-channel";
1364                 goto abort_transaction;
1365         }
1366         err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
1367                             XEN_IO_PROTO_ABI_NATIVE);
1368         if (err) {
1369                 message = "writing protocol";
1370                 goto abort_transaction;
1371         }
1372         err = xenbus_printf(xbt, dev->nodename,
1373                             "feature-persistent", "%u", 1);
1374         if (err)
1375                 dev_warn(&dev->dev,
1376                          "writing persistent grants feature to xenbus");
1377
1378         err = xenbus_transaction_end(xbt, 0);
1379         if (err) {
1380                 if (err == -EAGAIN)
1381                         goto again;
1382                 xenbus_dev_fatal(dev, err, "completing transaction");
1383                 goto destroy_blkring;
1384         }
1385
1386         for (i = 0; i < BLK_RING_SIZE(info); i++)
1387                 info->shadow[i].req.u.rw.id = i+1;
1388         info->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1389         xenbus_switch_state(dev, XenbusStateInitialised);
1390
1391         return 0;
1392
1393  abort_transaction:
1394         xenbus_transaction_end(xbt, 1);
1395         if (message)
1396                 xenbus_dev_fatal(dev, err, "%s", message);
1397  destroy_blkring:
1398         blkif_free(info, 0);
1399  out:
1400         return err;
1401 }
1402
1403 /**
1404  * Entry point to this code when a new device is created.  Allocate the basic
1405  * structures and the ring buffer for communication with the backend, and
1406  * inform the backend of the appropriate details for those.  Switch to
1407  * Initialised state.
1408  */
1409 static int blkfront_probe(struct xenbus_device *dev,
1410                           const struct xenbus_device_id *id)
1411 {
1412         int err, vdevice;
1413         struct blkfront_info *info;
1414
1415         /* FIXME: Use dynamic device id if this is not set. */
1416         err = xenbus_scanf(XBT_NIL, dev->nodename,
1417                            "virtual-device", "%i", &vdevice);
1418         if (err != 1) {
1419                 /* go looking in the extended area instead */
1420                 err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
1421                                    "%i", &vdevice);
1422                 if (err != 1) {
1423                         xenbus_dev_fatal(dev, err, "reading virtual-device");
1424                         return err;
1425                 }
1426         }
1427
1428         if (xen_hvm_domain()) {
1429                 char *type;
1430                 int len;
1431                 /* no unplug has been done: do not hook devices != xen vbds */
1432                 if (xen_has_pv_and_legacy_disk_devices()) {
1433                         int major;
1434
1435                         if (!VDEV_IS_EXTENDED(vdevice))
1436                                 major = BLKIF_MAJOR(vdevice);
1437                         else
1438                                 major = XENVBD_MAJOR;
1439
1440                         if (major != XENVBD_MAJOR) {
1441                                 printk(KERN_INFO
1442                                                 "%s: HVM does not support vbd %d as xen block device\n",
1443                                                 __func__, vdevice);
1444                                 return -ENODEV;
1445                         }
1446                 }
1447                 /* do not create a PV cdrom device if we are an HVM guest */
1448                 type = xenbus_read(XBT_NIL, dev->nodename, "device-type", &len);
1449                 if (IS_ERR(type))
1450                         return -ENODEV;
1451                 if (strncmp(type, "cdrom", 5) == 0) {
1452                         kfree(type);
1453                         return -ENODEV;
1454                 }
1455                 kfree(type);
1456         }
1457         info = kzalloc(sizeof(*info), GFP_KERNEL);
1458         if (!info) {
1459                 xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
1460                 return -ENOMEM;
1461         }
1462
1463         mutex_init(&info->mutex);
1464         spin_lock_init(&info->io_lock);
1465         info->xbdev = dev;
1466         info->vdevice = vdevice;
1467         INIT_LIST_HEAD(&info->grants);
1468         INIT_LIST_HEAD(&info->indirect_pages);
1469         info->persistent_gnts_c = 0;
1470         info->connected = BLKIF_STATE_DISCONNECTED;
1471         INIT_WORK(&info->work, blkif_restart_queue);
1472
1473         /* Front end dir is a number, which is used as the id. */
1474         info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
1475         dev_set_drvdata(&dev->dev, info);
1476
1477         return 0;
1478 }
1479
1480 static void split_bio_end(struct bio *bio)
1481 {
1482         struct split_bio *split_bio = bio->bi_private;
1483
1484         if (atomic_dec_and_test(&split_bio->pending)) {
1485                 split_bio->bio->bi_phys_segments = 0;
1486                 split_bio->bio->bi_error = bio->bi_error;
1487                 bio_endio(split_bio->bio);
1488                 kfree(split_bio);
1489         }
1490         bio_put(bio);
1491 }
1492
1493 static int blkif_recover(struct blkfront_info *info)
1494 {
1495         int i;
1496         struct request *req, *n;
1497         struct blk_shadow *copy;
1498         int rc;
1499         struct bio *bio, *cloned_bio;
1500         struct bio_list bio_list, merge_bio;
1501         unsigned int segs, offset;
1502         int pending, size;
1503         struct split_bio *split_bio;
1504         struct list_head requests;
1505
1506         /* Stage 1: Make a safe copy of the shadow state. */
1507         copy = kmemdup(info->shadow, sizeof(info->shadow),
1508                        GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
1509         if (!copy)
1510                 return -ENOMEM;
1511
1512         /* Stage 2: Set up free list. */
1513         memset(&info->shadow, 0, sizeof(info->shadow));
1514         for (i = 0; i < BLK_RING_SIZE(info); i++)
1515                 info->shadow[i].req.u.rw.id = i+1;
1516         info->shadow_free = info->ring.req_prod_pvt;
1517         info->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1518
1519         rc = blkfront_setup_indirect(info);
1520         if (rc) {
1521                 kfree(copy);
1522                 return rc;
1523         }
1524
1525         segs = info->max_indirect_segments ? : BLKIF_MAX_SEGMENTS_PER_REQUEST;
1526         blk_queue_max_segments(info->rq, segs);
1527         bio_list_init(&bio_list);
1528         INIT_LIST_HEAD(&requests);
1529         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1530                 /* Not in use? */
1531                 if (!copy[i].request)
1532                         continue;
1533
1534                 /*
1535                  * Get the bios in the request so we can re-queue them.
1536                  */
1537                 if (copy[i].request->cmd_flags &
1538                     (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1539                         /*
1540                          * Flush operations don't contain bios, so
1541                          * we need to requeue the whole request
1542                          */
1543                         list_add(&copy[i].request->queuelist, &requests);
1544                         continue;
1545                 }
1546                 merge_bio.head = copy[i].request->bio;
1547                 merge_bio.tail = copy[i].request->biotail;
1548                 bio_list_merge(&bio_list, &merge_bio);
1549                 copy[i].request->bio = NULL;
1550                 blk_end_request_all(copy[i].request, 0);
1551         }
1552
1553         kfree(copy);
1554
1555         /*
1556          * Empty the queue, this is important because we might have
1557          * requests in the queue with more segments than what we
1558          * can handle now.
1559          */
1560         spin_lock_irq(&info->io_lock);
1561         while ((req = blk_fetch_request(info->rq)) != NULL) {
1562                 if (req->cmd_flags &
1563                     (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1564                         list_add(&req->queuelist, &requests);
1565                         continue;
1566                 }
1567                 merge_bio.head = req->bio;
1568                 merge_bio.tail = req->biotail;
1569                 bio_list_merge(&bio_list, &merge_bio);
1570                 req->bio = NULL;
1571                 if (req->cmd_flags & (REQ_FLUSH | REQ_FUA))
1572                         pr_alert("diskcache flush request found!\n");
1573                 __blk_end_request_all(req, 0);
1574         }
1575         spin_unlock_irq(&info->io_lock);
1576
1577         xenbus_switch_state(info->xbdev, XenbusStateConnected);
1578
1579         spin_lock_irq(&info->io_lock);
1580
1581         /* Now safe for us to use the shared ring */
1582         info->connected = BLKIF_STATE_CONNECTED;
1583
1584         /* Kick any other new requests queued since we resumed */
1585         kick_pending_request_queues(info);
1586
1587         list_for_each_entry_safe(req, n, &requests, queuelist) {
1588                 /* Requeue pending requests (flush or discard) */
1589                 list_del_init(&req->queuelist);
1590                 BUG_ON(req->nr_phys_segments > segs);
1591                 blk_requeue_request(info->rq, req);
1592         }
1593         spin_unlock_irq(&info->io_lock);
1594
1595         while ((bio = bio_list_pop(&bio_list)) != NULL) {
1596                 /* Traverse the list of pending bios and re-queue them */
1597                 if (bio_segments(bio) > segs) {
1598                         /*
1599                          * This bio has more segments than what we can
1600                          * handle, we have to split it.
1601                          */
1602                         pending = (bio_segments(bio) + segs - 1) / segs;
1603                         split_bio = kzalloc(sizeof(*split_bio), GFP_NOIO);
1604                         BUG_ON(split_bio == NULL);
1605                         atomic_set(&split_bio->pending, pending);
1606                         split_bio->bio = bio;
1607                         for (i = 0; i < pending; i++) {
1608                                 offset = (i * segs * PAGE_SIZE) >> 9;
1609                                 size = min((unsigned int)(segs * PAGE_SIZE) >> 9,
1610                                            (unsigned int)bio_sectors(bio) - offset);
1611                                 cloned_bio = bio_clone(bio, GFP_NOIO);
1612                                 BUG_ON(cloned_bio == NULL);
1613                                 bio_trim(cloned_bio, offset, size);
1614                                 cloned_bio->bi_private = split_bio;
1615                                 cloned_bio->bi_end_io = split_bio_end;
1616                                 submit_bio(cloned_bio->bi_rw, cloned_bio);
1617                         }
1618                         /*
1619                          * Now we have to wait for all those smaller bios to
1620                          * end, so we can also end the "parent" bio.
1621                          */
1622                         continue;
1623                 }
1624                 /* We don't need to split this bio */
1625                 submit_bio(bio->bi_rw, bio);
1626         }
1627
1628         return 0;
1629 }
1630
1631 /**
1632  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1633  * driver restart.  We tear down our blkif structure and recreate it, but
1634  * leave the device-layer structures intact so that this is transparent to the
1635  * rest of the kernel.
1636  */
1637 static int blkfront_resume(struct xenbus_device *dev)
1638 {
1639         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1640         int err;
1641
1642         dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
1643
1644         blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
1645
1646         err = talk_to_blkback(dev, info);
1647
1648         /*
1649          * We have to wait for the backend to switch to
1650          * connected state, since we want to read which
1651          * features it supports.
1652          */
1653
1654         return err;
1655 }
1656
1657 static void
1658 blkfront_closing(struct blkfront_info *info)
1659 {
1660         struct xenbus_device *xbdev = info->xbdev;
1661         struct block_device *bdev = NULL;
1662
1663         mutex_lock(&info->mutex);
1664
1665         if (xbdev->state == XenbusStateClosing) {
1666                 mutex_unlock(&info->mutex);
1667                 return;
1668         }
1669
1670         if (info->gd)
1671                 bdev = bdget_disk(info->gd, 0);
1672
1673         mutex_unlock(&info->mutex);
1674
1675         if (!bdev) {
1676                 xenbus_frontend_closed(xbdev);
1677                 return;
1678         }
1679
1680         mutex_lock(&bdev->bd_mutex);
1681
1682         if (bdev->bd_openers) {
1683                 xenbus_dev_error(xbdev, -EBUSY,
1684                                  "Device in use; refusing to close");
1685                 xenbus_switch_state(xbdev, XenbusStateClosing);
1686         } else {
1687                 xlvbd_release_gendisk(info);
1688                 xenbus_frontend_closed(xbdev);
1689         }
1690
1691         mutex_unlock(&bdev->bd_mutex);
1692         bdput(bdev);
1693 }
1694
1695 static void blkfront_setup_discard(struct blkfront_info *info)
1696 {
1697         int err;
1698         unsigned int discard_granularity;
1699         unsigned int discard_alignment;
1700         unsigned int discard_secure;
1701
1702         info->feature_discard = 1;
1703         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1704                 "discard-granularity", "%u", &discard_granularity,
1705                 "discard-alignment", "%u", &discard_alignment,
1706                 NULL);
1707         if (!err) {
1708                 info->discard_granularity = discard_granularity;
1709                 info->discard_alignment = discard_alignment;
1710         }
1711         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1712                     "discard-secure", "%d", &discard_secure,
1713                     NULL);
1714         if (!err)
1715                 info->feature_secdiscard = !!discard_secure;
1716 }
1717
1718 static int blkfront_setup_indirect(struct blkfront_info *info)
1719 {
1720         unsigned int indirect_segments, segs;
1721         int err, i;
1722
1723         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1724                             "feature-max-indirect-segments", "%u", &indirect_segments,
1725                             NULL);
1726         if (err) {
1727                 info->max_indirect_segments = 0;
1728                 segs = BLKIF_MAX_SEGMENTS_PER_REQUEST;
1729         } else {
1730                 info->max_indirect_segments = min(indirect_segments,
1731                                                   xen_blkif_max_segments);
1732                 segs = info->max_indirect_segments;
1733         }
1734
1735         err = fill_grant_buffer(info, (segs + INDIRECT_GREFS(segs)) * BLK_RING_SIZE(info));
1736         if (err)
1737                 goto out_of_memory;
1738
1739         if (!info->feature_persistent && info->max_indirect_segments) {
1740                 /*
1741                  * We are using indirect descriptors but not persistent
1742                  * grants, we need to allocate a set of pages that can be
1743                  * used for mapping indirect grefs
1744                  */
1745                 int num = INDIRECT_GREFS(segs) * BLK_RING_SIZE(info);
1746
1747                 BUG_ON(!list_empty(&info->indirect_pages));
1748                 for (i = 0; i < num; i++) {
1749                         struct page *indirect_page = alloc_page(GFP_NOIO);
1750                         if (!indirect_page)
1751                                 goto out_of_memory;
1752                         list_add(&indirect_page->lru, &info->indirect_pages);
1753                 }
1754         }
1755
1756         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1757                 info->shadow[i].grants_used = kzalloc(
1758                         sizeof(info->shadow[i].grants_used[0]) * segs,
1759                         GFP_NOIO);
1760                 info->shadow[i].sg = kzalloc(sizeof(info->shadow[i].sg[0]) * segs, GFP_NOIO);
1761                 if (info->max_indirect_segments)
1762                         info->shadow[i].indirect_grants = kzalloc(
1763                                 sizeof(info->shadow[i].indirect_grants[0]) *
1764                                 INDIRECT_GREFS(segs),
1765                                 GFP_NOIO);
1766                 if ((info->shadow[i].grants_used == NULL) ||
1767                         (info->shadow[i].sg == NULL) ||
1768                      (info->max_indirect_segments &&
1769                      (info->shadow[i].indirect_grants == NULL)))
1770                         goto out_of_memory;
1771                 sg_init_table(info->shadow[i].sg, segs);
1772         }
1773
1774
1775         return 0;
1776
1777 out_of_memory:
1778         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1779                 kfree(info->shadow[i].grants_used);
1780                 info->shadow[i].grants_used = NULL;
1781                 kfree(info->shadow[i].sg);
1782                 info->shadow[i].sg = NULL;
1783                 kfree(info->shadow[i].indirect_grants);
1784                 info->shadow[i].indirect_grants = NULL;
1785         }
1786         if (!list_empty(&info->indirect_pages)) {
1787                 struct page *indirect_page, *n;
1788                 list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
1789                         list_del(&indirect_page->lru);
1790                         __free_page(indirect_page);
1791                 }
1792         }
1793         return -ENOMEM;
1794 }
1795
1796 /*
1797  * Invoked when the backend is finally 'ready' (and has told produced
1798  * the details about the physical device - #sectors, size, etc).
1799  */
1800 static void blkfront_connect(struct blkfront_info *info)
1801 {
1802         unsigned long long sectors;
1803         unsigned long sector_size;
1804         unsigned int physical_sector_size;
1805         unsigned int binfo;
1806         int err;
1807         int barrier, flush, discard, persistent;
1808
1809         switch (info->connected) {
1810         case BLKIF_STATE_CONNECTED:
1811                 /*
1812                  * Potentially, the back-end may be signalling
1813                  * a capacity change; update the capacity.
1814                  */
1815                 err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1816                                    "sectors", "%Lu", &sectors);
1817                 if (XENBUS_EXIST_ERR(err))
1818                         return;
1819                 printk(KERN_INFO "Setting capacity to %Lu\n",
1820                        sectors);
1821                 set_capacity(info->gd, sectors);
1822                 revalidate_disk(info->gd);
1823
1824                 return;
1825         case BLKIF_STATE_SUSPENDED:
1826                 /*
1827                  * If we are recovering from suspension, we need to wait
1828                  * for the backend to announce it's features before
1829                  * reconnecting, at least we need to know if the backend
1830                  * supports indirect descriptors, and how many.
1831                  */
1832                 blkif_recover(info);
1833                 return;
1834
1835         default:
1836                 break;
1837         }
1838
1839         dev_dbg(&info->xbdev->dev, "%s:%s.\n",
1840                 __func__, info->xbdev->otherend);
1841
1842         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1843                             "sectors", "%llu", &sectors,
1844                             "info", "%u", &binfo,
1845                             "sector-size", "%lu", &sector_size,
1846                             NULL);
1847         if (err) {
1848                 xenbus_dev_fatal(info->xbdev, err,
1849                                  "reading backend fields at %s",
1850                                  info->xbdev->otherend);
1851                 return;
1852         }
1853
1854         /*
1855          * physcial-sector-size is a newer field, so old backends may not
1856          * provide this. Assume physical sector size to be the same as
1857          * sector_size in that case.
1858          */
1859         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1860                            "physical-sector-size", "%u", &physical_sector_size);
1861         if (err != 1)
1862                 physical_sector_size = sector_size;
1863
1864         info->feature_flush = 0;
1865
1866         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1867                             "feature-barrier", "%d", &barrier,
1868                             NULL);
1869
1870         /*
1871          * If there's no "feature-barrier" defined, then it means
1872          * we're dealing with a very old backend which writes
1873          * synchronously; nothing to do.
1874          *
1875          * If there are barriers, then we use flush.
1876          */
1877         if (!err && barrier)
1878                 info->feature_flush = REQ_FLUSH | REQ_FUA;
1879         /*
1880          * And if there is "feature-flush-cache" use that above
1881          * barriers.
1882          */
1883         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1884                             "feature-flush-cache", "%d", &flush,
1885                             NULL);
1886
1887         if (!err && flush)
1888                 info->feature_flush = REQ_FLUSH;
1889
1890         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1891                             "feature-discard", "%d", &discard,
1892                             NULL);
1893
1894         if (!err && discard)
1895                 blkfront_setup_discard(info);
1896
1897         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1898                             "feature-persistent", "%u", &persistent,
1899                             NULL);
1900         if (err)
1901                 info->feature_persistent = 0;
1902         else
1903                 info->feature_persistent = persistent;
1904
1905         err = blkfront_setup_indirect(info);
1906         if (err) {
1907                 xenbus_dev_fatal(info->xbdev, err, "setup_indirect at %s",
1908                                  info->xbdev->otherend);
1909                 return;
1910         }
1911
1912         err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size,
1913                                   physical_sector_size);
1914         if (err) {
1915                 xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
1916                                  info->xbdev->otherend);
1917                 return;
1918         }
1919
1920         xenbus_switch_state(info->xbdev, XenbusStateConnected);
1921
1922         /* Kick pending requests. */
1923         spin_lock_irq(&info->io_lock);
1924         info->connected = BLKIF_STATE_CONNECTED;
1925         kick_pending_request_queues(info);
1926         spin_unlock_irq(&info->io_lock);
1927
1928         add_disk(info->gd);
1929
1930         info->is_ready = 1;
1931 }
1932
1933 /**
1934  * Callback received when the backend's state changes.
1935  */
1936 static void blkback_changed(struct xenbus_device *dev,
1937                             enum xenbus_state backend_state)
1938 {
1939         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1940
1941         dev_dbg(&dev->dev, "blkfront:blkback_changed to state %d.\n", backend_state);
1942
1943         switch (backend_state) {
1944         case XenbusStateInitWait:
1945                 if (dev->state != XenbusStateInitialising)
1946                         break;
1947                 if (talk_to_blkback(dev, info)) {
1948                         kfree(info);
1949                         dev_set_drvdata(&dev->dev, NULL);
1950                         break;
1951                 }
1952         case XenbusStateInitialising:
1953         case XenbusStateInitialised:
1954         case XenbusStateReconfiguring:
1955         case XenbusStateReconfigured:
1956         case XenbusStateUnknown:
1957                 break;
1958
1959         case XenbusStateConnected:
1960                 blkfront_connect(info);
1961                 break;
1962
1963         case XenbusStateClosed:
1964                 if (dev->state == XenbusStateClosed)
1965                         break;
1966                 /* Missed the backend's Closing state -- fallthrough */
1967         case XenbusStateClosing:
1968                 blkfront_closing(info);
1969                 break;
1970         }
1971 }
1972
1973 static int blkfront_remove(struct xenbus_device *xbdev)
1974 {
1975         struct blkfront_info *info = dev_get_drvdata(&xbdev->dev);
1976         struct block_device *bdev = NULL;
1977         struct gendisk *disk;
1978
1979         dev_dbg(&xbdev->dev, "%s removed", xbdev->nodename);
1980
1981         blkif_free(info, 0);
1982
1983         mutex_lock(&info->mutex);
1984
1985         disk = info->gd;
1986         if (disk)
1987                 bdev = bdget_disk(disk, 0);
1988
1989         info->xbdev = NULL;
1990         mutex_unlock(&info->mutex);
1991
1992         if (!bdev) {
1993                 kfree(info);
1994                 return 0;
1995         }
1996
1997         /*
1998          * The xbdev was removed before we reached the Closed
1999          * state. See if it's safe to remove the disk. If the bdev
2000          * isn't closed yet, we let release take care of it.
2001          */
2002
2003         mutex_lock(&bdev->bd_mutex);
2004         info = disk->private_data;
2005
2006         dev_warn(disk_to_dev(disk),
2007                  "%s was hot-unplugged, %d stale handles\n",
2008                  xbdev->nodename, bdev->bd_openers);
2009
2010         if (info && !bdev->bd_openers) {
2011                 xlvbd_release_gendisk(info);
2012                 disk->private_data = NULL;
2013                 kfree(info);
2014         }
2015
2016         mutex_unlock(&bdev->bd_mutex);
2017         bdput(bdev);
2018
2019         return 0;
2020 }
2021
2022 static int blkfront_is_ready(struct xenbus_device *dev)
2023 {
2024         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2025
2026         return info->is_ready && info->xbdev;
2027 }
2028
2029 static int blkif_open(struct block_device *bdev, fmode_t mode)
2030 {
2031         struct gendisk *disk = bdev->bd_disk;
2032         struct blkfront_info *info;
2033         int err = 0;
2034
2035         mutex_lock(&blkfront_mutex);
2036
2037         info = disk->private_data;
2038         if (!info) {
2039                 /* xbdev gone */
2040                 err = -ERESTARTSYS;
2041                 goto out;
2042         }
2043
2044         mutex_lock(&info->mutex);
2045
2046         if (!info->gd)
2047                 /* xbdev is closed */
2048                 err = -ERESTARTSYS;
2049
2050         mutex_unlock(&info->mutex);
2051
2052 out:
2053         mutex_unlock(&blkfront_mutex);
2054         return err;
2055 }
2056
2057 static void blkif_release(struct gendisk *disk, fmode_t mode)
2058 {
2059         struct blkfront_info *info = disk->private_data;
2060         struct block_device *bdev;
2061         struct xenbus_device *xbdev;
2062
2063         mutex_lock(&blkfront_mutex);
2064
2065         bdev = bdget_disk(disk, 0);
2066
2067         if (!bdev) {
2068                 WARN(1, "Block device %s yanked out from us!\n", disk->disk_name);
2069                 goto out_mutex;
2070         }
2071         if (bdev->bd_openers)
2072                 goto out;
2073
2074         /*
2075          * Check if we have been instructed to close. We will have
2076          * deferred this request, because the bdev was still open.
2077          */
2078
2079         mutex_lock(&info->mutex);
2080         xbdev = info->xbdev;
2081
2082         if (xbdev && xbdev->state == XenbusStateClosing) {
2083                 /* pending switch to state closed */
2084                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2085                 xlvbd_release_gendisk(info);
2086                 xenbus_frontend_closed(info->xbdev);
2087         }
2088
2089         mutex_unlock(&info->mutex);
2090
2091         if (!xbdev) {
2092                 /* sudden device removal */
2093                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2094                 xlvbd_release_gendisk(info);
2095                 disk->private_data = NULL;
2096                 kfree(info);
2097         }
2098
2099 out:
2100         bdput(bdev);
2101 out_mutex:
2102         mutex_unlock(&blkfront_mutex);
2103 }
2104
2105 static const struct block_device_operations xlvbd_block_fops =
2106 {
2107         .owner = THIS_MODULE,
2108         .open = blkif_open,
2109         .release = blkif_release,
2110         .getgeo = blkif_getgeo,
2111         .ioctl = blkif_ioctl,
2112 };
2113
2114
2115 static const struct xenbus_device_id blkfront_ids[] = {
2116         { "vbd" },
2117         { "" }
2118 };
2119
2120 static struct xenbus_driver blkfront_driver = {
2121         .ids  = blkfront_ids,
2122         .probe = blkfront_probe,
2123         .remove = blkfront_remove,
2124         .resume = blkfront_resume,
2125         .otherend_changed = blkback_changed,
2126         .is_ready = blkfront_is_ready,
2127 };
2128
2129 static int __init xlblk_init(void)
2130 {
2131         int ret;
2132
2133         if (!xen_domain())
2134                 return -ENODEV;
2135
2136         if (xen_blkif_max_ring_order > XENBUS_MAX_RING_PAGE_ORDER) {
2137                 pr_info("Invalid max_ring_order (%d), will use default max: %d.\n",
2138                         xen_blkif_max_ring_order, XENBUS_MAX_RING_PAGE_ORDER);
2139                 xen_blkif_max_ring_order = 0;
2140         }
2141
2142         if (!xen_has_pv_disk_devices())
2143                 return -ENODEV;
2144
2145         if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
2146                 printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
2147                        XENVBD_MAJOR, DEV_NAME);
2148                 return -ENODEV;
2149         }
2150
2151         ret = xenbus_register_frontend(&blkfront_driver);
2152         if (ret) {
2153                 unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2154                 return ret;
2155         }
2156
2157         return 0;
2158 }
2159 module_init(xlblk_init);
2160
2161
2162 static void __exit xlblk_exit(void)
2163 {
2164         xenbus_unregister_driver(&blkfront_driver);
2165         unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2166         kfree(minors);
2167 }
2168 module_exit(xlblk_exit);
2169
2170 MODULE_DESCRIPTION("Xen virtual block device frontend");
2171 MODULE_LICENSE("GPL");
2172 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
2173 MODULE_ALIAS("xen:vbd");
2174 MODULE_ALIAS("xenblk");