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