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