GNU Linux-libre 4.4.297-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         /* Copy the request to the ring page. */
497         *final_ring_req = *ring_req;
498         info->shadow[id].inflight = true;
499
500         return 0;
501 }
502
503 struct setup_rw_req {
504         unsigned int grant_idx;
505         struct blkif_request_segment *segments;
506         struct blkfront_info *info;
507         struct blkif_request *ring_req;
508         grant_ref_t gref_head;
509         unsigned int id;
510         /* Only used when persistent grant is used and it's a read request */
511         bool need_copy;
512         unsigned int bvec_off;
513         char *bvec_data;
514 };
515
516 static void blkif_setup_rw_req_grant(unsigned long gfn, unsigned int offset,
517                                      unsigned int len, void *data)
518 {
519         struct setup_rw_req *setup = data;
520         int n, ref;
521         struct grant *gnt_list_entry;
522         unsigned int fsect, lsect;
523         /* Convenient aliases */
524         unsigned int grant_idx = setup->grant_idx;
525         struct blkif_request *ring_req = setup->ring_req;
526         struct blkfront_info *info = setup->info;
527         struct blk_shadow *shadow = &info->shadow[setup->id];
528
529         if ((ring_req->operation == BLKIF_OP_INDIRECT) &&
530             (grant_idx % GRANTS_PER_INDIRECT_FRAME == 0)) {
531                 if (setup->segments)
532                         kunmap_atomic(setup->segments);
533
534                 n = grant_idx / GRANTS_PER_INDIRECT_FRAME;
535                 gnt_list_entry = get_indirect_grant(&setup->gref_head, info);
536                 shadow->indirect_grants[n] = gnt_list_entry;
537                 setup->segments = kmap_atomic(gnt_list_entry->page);
538                 ring_req->u.indirect.indirect_grefs[n] = gnt_list_entry->gref;
539         }
540
541         gnt_list_entry = get_grant(&setup->gref_head, gfn, info);
542         ref = gnt_list_entry->gref;
543         shadow->grants_used[grant_idx] = gnt_list_entry;
544
545         if (setup->need_copy) {
546                 void *shared_data;
547
548                 shared_data = kmap_atomic(gnt_list_entry->page);
549                 /*
550                  * this does not wipe data stored outside the
551                  * range sg->offset..sg->offset+sg->length.
552                  * Therefore, blkback *could* see data from
553                  * previous requests. This is OK as long as
554                  * persistent grants are shared with just one
555                  * domain. It may need refactoring if this
556                  * changes
557                  */
558                 memcpy(shared_data + offset,
559                        setup->bvec_data + setup->bvec_off,
560                        len);
561
562                 kunmap_atomic(shared_data);
563                 setup->bvec_off += len;
564         }
565
566         fsect = offset >> 9;
567         lsect = fsect + (len >> 9) - 1;
568         if (ring_req->operation != BLKIF_OP_INDIRECT) {
569                 ring_req->u.rw.seg[grant_idx] =
570                         (struct blkif_request_segment) {
571                                 .gref       = ref,
572                                 .first_sect = fsect,
573                                 .last_sect  = lsect };
574         } else {
575                 setup->segments[grant_idx % GRANTS_PER_INDIRECT_FRAME] =
576                         (struct blkif_request_segment) {
577                                 .gref       = ref,
578                                 .first_sect = fsect,
579                                 .last_sect  = lsect };
580         }
581
582         (setup->grant_idx)++;
583 }
584
585 static int blkif_queue_rw_req(struct request *req)
586 {
587         struct blkfront_info *info = req->rq_disk->private_data;
588         struct blkif_request *ring_req, *final_ring_req;
589         unsigned long id;
590         int i;
591         struct setup_rw_req setup = {
592                 .grant_idx = 0,
593                 .segments = NULL,
594                 .info = info,
595                 .need_copy = rq_data_dir(req) && info->feature_persistent,
596         };
597
598         /*
599          * Used to store if we are able to queue the request by just using
600          * existing persistent grants, or if we have to get new grants,
601          * as there are not sufficiently many free.
602          */
603         bool new_persistent_gnts;
604         struct scatterlist *sg;
605         int num_sg, max_grefs, num_grant;
606
607         max_grefs = req->nr_phys_segments * GRANTS_PER_PSEG;
608         if (max_grefs > BLKIF_MAX_SEGMENTS_PER_REQUEST)
609                 /*
610                  * If we are using indirect segments we need to account
611                  * for the indirect grefs used in the request.
612                  */
613                 max_grefs += INDIRECT_GREFS(max_grefs);
614
615         /* Check if we have enough grants to allocate a requests */
616         if (info->persistent_gnts_c < max_grefs) {
617                 new_persistent_gnts = 1;
618                 if (gnttab_alloc_grant_references(
619                     max_grefs - info->persistent_gnts_c,
620                     &setup.gref_head) < 0) {
621                         gnttab_request_free_callback(
622                                 &info->callback,
623                                 blkif_restart_queue_callback,
624                                 info,
625                                 max_grefs);
626                         return 1;
627                 }
628         } else
629                 new_persistent_gnts = 0;
630
631         /* Fill out a communications ring structure. */
632         id = blkif_ring_get_request(info, req, &final_ring_req);
633         ring_req = &info->shadow[id].req;
634
635         BUG_ON(info->max_indirect_segments == 0 &&
636                GREFS(req->nr_phys_segments) > BLKIF_MAX_SEGMENTS_PER_REQUEST);
637         BUG_ON(info->max_indirect_segments &&
638                GREFS(req->nr_phys_segments) > info->max_indirect_segments);
639
640         num_sg = blk_rq_map_sg(req->q, req, info->shadow[id].sg);
641         num_grant = 0;
642         /* Calculate the number of grant used */
643         for_each_sg(info->shadow[id].sg, sg, num_sg, i)
644                num_grant += gnttab_count_grant(sg->offset, sg->length);
645
646         ring_req->u.rw.id = id;
647         info->shadow[id].num_sg = num_sg;
648         if (num_grant > BLKIF_MAX_SEGMENTS_PER_REQUEST) {
649                 /*
650                  * The indirect operation can only be a BLKIF_OP_READ or
651                  * BLKIF_OP_WRITE
652                  */
653                 BUG_ON(req->cmd_flags & (REQ_FLUSH | REQ_FUA));
654                 ring_req->operation = BLKIF_OP_INDIRECT;
655                 ring_req->u.indirect.indirect_op = rq_data_dir(req) ?
656                         BLKIF_OP_WRITE : BLKIF_OP_READ;
657                 ring_req->u.indirect.sector_number = (blkif_sector_t)blk_rq_pos(req);
658                 ring_req->u.indirect.handle = info->handle;
659                 ring_req->u.indirect.nr_segments = num_grant;
660         } else {
661                 ring_req->u.rw.sector_number = (blkif_sector_t)blk_rq_pos(req);
662                 ring_req->u.rw.handle = info->handle;
663                 ring_req->operation = rq_data_dir(req) ?
664                         BLKIF_OP_WRITE : BLKIF_OP_READ;
665                 if (req->cmd_flags & (REQ_FLUSH | REQ_FUA)) {
666                         /*
667                          * Ideally we can do an unordered flush-to-disk.
668                          * In case the backend onlysupports barriers, use that.
669                          * A barrier request a superset of FUA, so we can
670                          * implement it the same way.  (It's also a FLUSH+FUA,
671                          * since it is guaranteed ordered WRT previous writes.)
672                          */
673                         switch (info->feature_flush &
674                                 ((REQ_FLUSH|REQ_FUA))) {
675                         case REQ_FLUSH|REQ_FUA:
676                                 ring_req->operation =
677                                         BLKIF_OP_WRITE_BARRIER;
678                                 break;
679                         case REQ_FLUSH:
680                                 ring_req->operation =
681                                         BLKIF_OP_FLUSH_DISKCACHE;
682                                 break;
683                         default:
684                                 ring_req->operation = 0;
685                         }
686                 }
687                 ring_req->u.rw.nr_segments = num_grant;
688         }
689
690         setup.ring_req = ring_req;
691         setup.id = id;
692         for_each_sg(info->shadow[id].sg, sg, num_sg, i) {
693                 BUG_ON(sg->offset + sg->length > PAGE_SIZE);
694
695                 if (setup.need_copy) {
696                         setup.bvec_off = sg->offset;
697                         setup.bvec_data = kmap_atomic(sg_page(sg));
698                 }
699
700                 gnttab_foreach_grant_in_range(sg_page(sg),
701                                               sg->offset,
702                                               sg->length,
703                                               blkif_setup_rw_req_grant,
704                                               &setup);
705
706                 if (setup.need_copy)
707                         kunmap_atomic(setup.bvec_data);
708         }
709         if (setup.segments)
710                 kunmap_atomic(setup.segments);
711
712         /* Copy request(s) to the ring page. */
713         *final_ring_req = *ring_req;
714         info->shadow[id].inflight = true;
715
716         if (new_persistent_gnts)
717                 gnttab_free_grant_references(setup.gref_head);
718
719         return 0;
720 }
721
722 /*
723  * Generate a Xen blkfront IO request from a blk layer request.  Reads
724  * and writes are handled as expected.
725  *
726  * @req: a request struct
727  */
728 static int blkif_queue_request(struct request *req)
729 {
730         struct blkfront_info *info = req->rq_disk->private_data;
731
732         if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
733                 return 1;
734
735         if (unlikely(req->cmd_flags & (REQ_DISCARD | REQ_SECURE)))
736                 return blkif_queue_discard_req(req);
737         else
738                 return blkif_queue_rw_req(req);
739 }
740
741 static inline void flush_requests(struct blkfront_info *info)
742 {
743         int notify;
744
745         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
746
747         if (notify)
748                 notify_remote_via_irq(info->irq);
749 }
750
751 static inline bool blkif_request_flush_invalid(struct request *req,
752                                                struct blkfront_info *info)
753 {
754         return ((req->cmd_type != REQ_TYPE_FS) ||
755                 ((req->cmd_flags & REQ_FLUSH) &&
756                  !(info->feature_flush & REQ_FLUSH)) ||
757                 ((req->cmd_flags & REQ_FUA) &&
758                  !(info->feature_flush & REQ_FUA)));
759 }
760
761 static int blkif_queue_rq(struct blk_mq_hw_ctx *hctx,
762                            const struct blk_mq_queue_data *qd)
763 {
764         struct blkfront_info *info = qd->rq->rq_disk->private_data;
765
766         blk_mq_start_request(qd->rq);
767         spin_lock_irq(&info->io_lock);
768         if (RING_FULL(&info->ring))
769                 goto out_busy;
770
771         if (blkif_request_flush_invalid(qd->rq, info))
772                 goto out_err;
773
774         if (blkif_queue_request(qd->rq))
775                 goto out_busy;
776
777         flush_requests(info);
778         spin_unlock_irq(&info->io_lock);
779         return BLK_MQ_RQ_QUEUE_OK;
780
781 out_err:
782         spin_unlock_irq(&info->io_lock);
783         return BLK_MQ_RQ_QUEUE_ERROR;
784
785 out_busy:
786         spin_unlock_irq(&info->io_lock);
787         blk_mq_stop_hw_queue(hctx);
788         return BLK_MQ_RQ_QUEUE_BUSY;
789 }
790
791 static struct blk_mq_ops blkfront_mq_ops = {
792         .queue_rq = blkif_queue_rq,
793         .map_queue = blk_mq_map_queue,
794 };
795
796 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size,
797                                 unsigned int physical_sector_size,
798                                 unsigned int segments)
799 {
800         struct request_queue *rq;
801         struct blkfront_info *info = gd->private_data;
802
803         memset(&info->tag_set, 0, sizeof(info->tag_set));
804         info->tag_set.ops = &blkfront_mq_ops;
805         info->tag_set.nr_hw_queues = 1;
806         info->tag_set.queue_depth =  BLK_RING_SIZE(info);
807         info->tag_set.numa_node = NUMA_NO_NODE;
808         info->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
809         info->tag_set.cmd_size = 0;
810         info->tag_set.driver_data = info;
811
812         if (blk_mq_alloc_tag_set(&info->tag_set))
813                 return -1;
814         rq = blk_mq_init_queue(&info->tag_set);
815         if (IS_ERR(rq)) {
816                 blk_mq_free_tag_set(&info->tag_set);
817                 return -1;
818         }
819
820         queue_flag_set_unlocked(QUEUE_FLAG_VIRT, rq);
821
822         if (info->feature_discard) {
823                 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, rq);
824                 blk_queue_max_discard_sectors(rq, get_capacity(gd));
825                 rq->limits.discard_granularity = info->discard_granularity;
826                 rq->limits.discard_alignment = info->discard_alignment;
827                 if (info->feature_secdiscard)
828                         queue_flag_set_unlocked(QUEUE_FLAG_SECDISCARD, rq);
829         }
830
831         /* Hard sector size and max sectors impersonate the equiv. hardware. */
832         blk_queue_logical_block_size(rq, sector_size);
833         blk_queue_physical_block_size(rq, physical_sector_size);
834         blk_queue_max_hw_sectors(rq, (segments * XEN_PAGE_SIZE) / 512);
835
836         /* Each segment in a request is up to an aligned page in size. */
837         blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
838         blk_queue_max_segment_size(rq, PAGE_SIZE);
839
840         /* Ensure a merged request will fit in a single I/O ring slot. */
841         blk_queue_max_segments(rq, segments / GRANTS_PER_PSEG);
842
843         /* Make sure buffer addresses are sector-aligned. */
844         blk_queue_dma_alignment(rq, 511);
845
846         /* Make sure we don't use bounce buffers. */
847         blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
848
849         gd->queue = rq;
850
851         return 0;
852 }
853
854 static const char *flush_info(unsigned int feature_flush)
855 {
856         switch (feature_flush & ((REQ_FLUSH | REQ_FUA))) {
857         case REQ_FLUSH|REQ_FUA:
858                 return "barrier: enabled;";
859         case REQ_FLUSH:
860                 return "flush diskcache: enabled;";
861         default:
862                 return "barrier or flush: disabled;";
863         }
864 }
865
866 static void xlvbd_flush(struct blkfront_info *info)
867 {
868         blk_queue_flush(info->rq, info->feature_flush);
869         pr_info("blkfront: %s: %s %s %s %s %s\n",
870                 info->gd->disk_name, flush_info(info->feature_flush),
871                 "persistent grants:", info->feature_persistent ?
872                 "enabled;" : "disabled;", "indirect descriptors:",
873                 info->max_indirect_segments ? "enabled;" : "disabled;");
874 }
875
876 static int xen_translate_vdev(int vdevice, int *minor, unsigned int *offset)
877 {
878         int major;
879         major = BLKIF_MAJOR(vdevice);
880         *minor = BLKIF_MINOR(vdevice);
881         switch (major) {
882                 case XEN_IDE0_MAJOR:
883                         *offset = (*minor / 64) + EMULATED_HD_DISK_NAME_OFFSET;
884                         *minor = ((*minor / 64) * PARTS_PER_DISK) +
885                                 EMULATED_HD_DISK_MINOR_OFFSET;
886                         break;
887                 case XEN_IDE1_MAJOR:
888                         *offset = (*minor / 64) + 2 + EMULATED_HD_DISK_NAME_OFFSET;
889                         *minor = (((*minor / 64) + 2) * PARTS_PER_DISK) +
890                                 EMULATED_HD_DISK_MINOR_OFFSET;
891                         break;
892                 case XEN_SCSI_DISK0_MAJOR:
893                         *offset = (*minor / PARTS_PER_DISK) + EMULATED_SD_DISK_NAME_OFFSET;
894                         *minor = *minor + EMULATED_SD_DISK_MINOR_OFFSET;
895                         break;
896                 case XEN_SCSI_DISK1_MAJOR:
897                 case XEN_SCSI_DISK2_MAJOR:
898                 case XEN_SCSI_DISK3_MAJOR:
899                 case XEN_SCSI_DISK4_MAJOR:
900                 case XEN_SCSI_DISK5_MAJOR:
901                 case XEN_SCSI_DISK6_MAJOR:
902                 case XEN_SCSI_DISK7_MAJOR:
903                         *offset = (*minor / PARTS_PER_DISK) + 
904                                 ((major - XEN_SCSI_DISK1_MAJOR + 1) * 16) +
905                                 EMULATED_SD_DISK_NAME_OFFSET;
906                         *minor = *minor +
907                                 ((major - XEN_SCSI_DISK1_MAJOR + 1) * 16 * PARTS_PER_DISK) +
908                                 EMULATED_SD_DISK_MINOR_OFFSET;
909                         break;
910                 case XEN_SCSI_DISK8_MAJOR:
911                 case XEN_SCSI_DISK9_MAJOR:
912                 case XEN_SCSI_DISK10_MAJOR:
913                 case XEN_SCSI_DISK11_MAJOR:
914                 case XEN_SCSI_DISK12_MAJOR:
915                 case XEN_SCSI_DISK13_MAJOR:
916                 case XEN_SCSI_DISK14_MAJOR:
917                 case XEN_SCSI_DISK15_MAJOR:
918                         *offset = (*minor / PARTS_PER_DISK) + 
919                                 ((major - XEN_SCSI_DISK8_MAJOR + 8) * 16) +
920                                 EMULATED_SD_DISK_NAME_OFFSET;
921                         *minor = *minor +
922                                 ((major - XEN_SCSI_DISK8_MAJOR + 8) * 16 * PARTS_PER_DISK) +
923                                 EMULATED_SD_DISK_MINOR_OFFSET;
924                         break;
925                 case XENVBD_MAJOR:
926                         *offset = *minor / PARTS_PER_DISK;
927                         break;
928                 default:
929                         printk(KERN_WARNING "blkfront: your disk configuration is "
930                                         "incorrect, please use an xvd device instead\n");
931                         return -ENODEV;
932         }
933         return 0;
934 }
935
936 static char *encode_disk_name(char *ptr, unsigned int n)
937 {
938         if (n >= 26)
939                 ptr = encode_disk_name(ptr, n / 26 - 1);
940         *ptr = 'a' + n % 26;
941         return ptr + 1;
942 }
943
944 static int xlvbd_alloc_gendisk(blkif_sector_t capacity,
945                                struct blkfront_info *info,
946                                u16 vdisk_info, u16 sector_size,
947                                unsigned int physical_sector_size)
948 {
949         struct gendisk *gd;
950         int nr_minors = 1;
951         int err;
952         unsigned int offset;
953         int minor;
954         int nr_parts;
955         char *ptr;
956
957         BUG_ON(info->gd != NULL);
958         BUG_ON(info->rq != NULL);
959
960         if ((info->vdevice>>EXT_SHIFT) > 1) {
961                 /* this is above the extended range; something is wrong */
962                 printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
963                 return -ENODEV;
964         }
965
966         if (!VDEV_IS_EXTENDED(info->vdevice)) {
967                 err = xen_translate_vdev(info->vdevice, &minor, &offset);
968                 if (err)
969                         return err;
970                 nr_parts = PARTS_PER_DISK;
971         } else {
972                 minor = BLKIF_MINOR_EXT(info->vdevice);
973                 nr_parts = PARTS_PER_EXT_DISK;
974                 offset = minor / nr_parts;
975                 if (xen_hvm_domain() && offset < EMULATED_HD_DISK_NAME_OFFSET + 4)
976                         printk(KERN_WARNING "blkfront: vdevice 0x%x might conflict with "
977                                         "emulated IDE disks,\n\t choose an xvd device name"
978                                         "from xvde on\n", info->vdevice);
979         }
980         if (minor >> MINORBITS) {
981                 pr_warn("blkfront: %#x's minor (%#x) out of range; ignoring\n",
982                         info->vdevice, minor);
983                 return -ENODEV;
984         }
985
986         if ((minor % nr_parts) == 0)
987                 nr_minors = nr_parts;
988
989         err = xlbd_reserve_minors(minor, nr_minors);
990         if (err)
991                 goto out;
992         err = -ENODEV;
993
994         gd = alloc_disk(nr_minors);
995         if (gd == NULL)
996                 goto release;
997
998         strcpy(gd->disk_name, DEV_NAME);
999         ptr = encode_disk_name(gd->disk_name + sizeof(DEV_NAME) - 1, offset);
1000         BUG_ON(ptr >= gd->disk_name + DISK_NAME_LEN);
1001         if (nr_minors > 1)
1002                 *ptr = 0;
1003         else
1004                 snprintf(ptr, gd->disk_name + DISK_NAME_LEN - ptr,
1005                          "%d", minor & (nr_parts - 1));
1006
1007         gd->major = XENVBD_MAJOR;
1008         gd->first_minor = minor;
1009         gd->fops = &xlvbd_block_fops;
1010         gd->private_data = info;
1011         gd->driverfs_dev = &(info->xbdev->dev);
1012         set_capacity(gd, capacity);
1013
1014         if (xlvbd_init_blk_queue(gd, sector_size, physical_sector_size,
1015                                  info->max_indirect_segments ? :
1016                                  BLKIF_MAX_SEGMENTS_PER_REQUEST)) {
1017                 del_gendisk(gd);
1018                 goto release;
1019         }
1020
1021         info->rq = gd->queue;
1022         info->gd = gd;
1023
1024         xlvbd_flush(info);
1025
1026         if (vdisk_info & VDISK_READONLY)
1027                 set_disk_ro(gd, 1);
1028
1029         if (vdisk_info & VDISK_REMOVABLE)
1030                 gd->flags |= GENHD_FL_REMOVABLE;
1031
1032         if (vdisk_info & VDISK_CDROM)
1033                 gd->flags |= GENHD_FL_CD;
1034
1035         return 0;
1036
1037  release:
1038         xlbd_release_minors(minor, nr_minors);
1039  out:
1040         return err;
1041 }
1042
1043 static void xlvbd_release_gendisk(struct blkfront_info *info)
1044 {
1045         unsigned int minor, nr_minors;
1046
1047         if (info->rq == NULL)
1048                 return;
1049
1050         /* No more blkif_request(). */
1051         blk_mq_stop_hw_queues(info->rq);
1052
1053         /* No more gnttab callback work. */
1054         gnttab_cancel_free_callback(&info->callback);
1055
1056         /* Flush gnttab callback work. Must be done with no locks held. */
1057         flush_work(&info->work);
1058
1059         del_gendisk(info->gd);
1060
1061         minor = info->gd->first_minor;
1062         nr_minors = info->gd->minors;
1063         xlbd_release_minors(minor, nr_minors);
1064
1065         blk_cleanup_queue(info->rq);
1066         blk_mq_free_tag_set(&info->tag_set);
1067         info->rq = NULL;
1068
1069         put_disk(info->gd);
1070         info->gd = NULL;
1071 }
1072
1073 /* Must be called with io_lock holded */
1074 static void kick_pending_request_queues(struct blkfront_info *info)
1075 {
1076         if (!RING_FULL(&info->ring))
1077                 blk_mq_start_stopped_hw_queues(info->rq, true);
1078 }
1079
1080 static void blkif_restart_queue(struct work_struct *work)
1081 {
1082         struct blkfront_info *info = container_of(work, struct blkfront_info, work);
1083
1084         spin_lock_irq(&info->io_lock);
1085         if (info->connected == BLKIF_STATE_CONNECTED)
1086                 kick_pending_request_queues(info);
1087         spin_unlock_irq(&info->io_lock);
1088 }
1089
1090 static void blkif_free(struct blkfront_info *info, int suspend)
1091 {
1092         struct grant *persistent_gnt;
1093         struct grant *n;
1094         int i, j, segs;
1095
1096         /* Prevent new requests being issued until we fix things up. */
1097         spin_lock_irq(&info->io_lock);
1098         info->connected = suspend ?
1099                 BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
1100         /* No more blkif_request(). */
1101         if (info->rq)
1102                 blk_mq_stop_hw_queues(info->rq);
1103
1104         /* Remove all persistent grants */
1105         if (!list_empty(&info->grants)) {
1106                 list_for_each_entry_safe(persistent_gnt, n,
1107                                          &info->grants, node) {
1108                         list_del(&persistent_gnt->node);
1109                         if (persistent_gnt->gref != GRANT_INVALID_REF) {
1110                                 gnttab_end_foreign_access(persistent_gnt->gref,
1111                                                           0, 0UL);
1112                                 info->persistent_gnts_c--;
1113                         }
1114                         if (info->feature_persistent)
1115                                 __free_page(persistent_gnt->page);
1116                         kfree(persistent_gnt);
1117                 }
1118         }
1119         BUG_ON(info->persistent_gnts_c != 0);
1120
1121         /*
1122          * Remove indirect pages, this only happens when using indirect
1123          * descriptors but not persistent grants
1124          */
1125         if (!list_empty(&info->indirect_pages)) {
1126                 struct page *indirect_page, *n;
1127
1128                 BUG_ON(info->feature_persistent);
1129                 list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
1130                         list_del(&indirect_page->lru);
1131                         __free_page(indirect_page);
1132                 }
1133         }
1134
1135         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1136                 /*
1137                  * Clear persistent grants present in requests already
1138                  * on the shared ring
1139                  */
1140                 if (!info->shadow[i].request)
1141                         goto free_shadow;
1142
1143                 segs = info->shadow[i].req.operation == BLKIF_OP_INDIRECT ?
1144                        info->shadow[i].req.u.indirect.nr_segments :
1145                        info->shadow[i].req.u.rw.nr_segments;
1146                 for (j = 0; j < segs; j++) {
1147                         persistent_gnt = info->shadow[i].grants_used[j];
1148                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1149                         if (info->feature_persistent)
1150                                 __free_page(persistent_gnt->page);
1151                         kfree(persistent_gnt);
1152                 }
1153
1154                 if (info->shadow[i].req.operation != BLKIF_OP_INDIRECT)
1155                         /*
1156                          * If this is not an indirect operation don't try to
1157                          * free indirect segments
1158                          */
1159                         goto free_shadow;
1160
1161                 for (j = 0; j < INDIRECT_GREFS(segs); j++) {
1162                         persistent_gnt = info->shadow[i].indirect_grants[j];
1163                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1164                         __free_page(persistent_gnt->page);
1165                         kfree(persistent_gnt);
1166                 }
1167
1168 free_shadow:
1169                 kfree(info->shadow[i].grants_used);
1170                 info->shadow[i].grants_used = NULL;
1171                 kfree(info->shadow[i].indirect_grants);
1172                 info->shadow[i].indirect_grants = NULL;
1173                 kfree(info->shadow[i].sg);
1174                 info->shadow[i].sg = NULL;
1175         }
1176
1177         /* No more gnttab callback work. */
1178         gnttab_cancel_free_callback(&info->callback);
1179         spin_unlock_irq(&info->io_lock);
1180
1181         /* Flush gnttab callback work. Must be done with no locks held. */
1182         flush_work(&info->work);
1183
1184         /* Free resources associated with old device channel. */
1185         for (i = 0; i < info->nr_ring_pages; i++) {
1186                 if (info->ring_ref[i] != GRANT_INVALID_REF) {
1187                         gnttab_end_foreign_access(info->ring_ref[i], 0, 0);
1188                         info->ring_ref[i] = GRANT_INVALID_REF;
1189                 }
1190         }
1191         free_pages((unsigned long)info->ring.sring, get_order(info->nr_ring_pages * PAGE_SIZE));
1192         info->ring.sring = NULL;
1193
1194         if (info->irq)
1195                 unbind_from_irqhandler(info->irq, info);
1196         info->evtchn = info->irq = 0;
1197
1198 }
1199
1200 struct copy_from_grant {
1201         const struct blk_shadow *s;
1202         unsigned int grant_idx;
1203         unsigned int bvec_offset;
1204         char *bvec_data;
1205 };
1206
1207 static void blkif_copy_from_grant(unsigned long gfn, unsigned int offset,
1208                                   unsigned int len, void *data)
1209 {
1210         struct copy_from_grant *info = data;
1211         char *shared_data;
1212         /* Convenient aliases */
1213         const struct blk_shadow *s = info->s;
1214
1215         shared_data = kmap_atomic(s->grants_used[info->grant_idx]->page);
1216
1217         memcpy(info->bvec_data + info->bvec_offset,
1218                shared_data + offset, len);
1219
1220         info->bvec_offset += len;
1221         info->grant_idx++;
1222
1223         kunmap_atomic(shared_data);
1224 }
1225
1226 static void blkif_completion(struct blk_shadow *s, struct blkfront_info *info,
1227                              struct blkif_response *bret)
1228 {
1229         int i = 0;
1230         struct scatterlist *sg;
1231         int num_sg, num_grant;
1232         struct copy_from_grant data = {
1233                 .s = s,
1234                 .grant_idx = 0,
1235         };
1236
1237         num_grant = s->req.operation == BLKIF_OP_INDIRECT ?
1238                 s->req.u.indirect.nr_segments : s->req.u.rw.nr_segments;
1239         num_sg = s->num_sg;
1240
1241         if (bret->operation == BLKIF_OP_READ && info->feature_persistent) {
1242                 for_each_sg(s->sg, sg, num_sg, i) {
1243                         BUG_ON(sg->offset + sg->length > PAGE_SIZE);
1244
1245                         data.bvec_offset = sg->offset;
1246                         data.bvec_data = kmap_atomic(sg_page(sg));
1247
1248                         gnttab_foreach_grant_in_range(sg_page(sg),
1249                                                       sg->offset,
1250                                                       sg->length,
1251                                                       blkif_copy_from_grant,
1252                                                       &data);
1253
1254                         kunmap_atomic(data.bvec_data);
1255                 }
1256         }
1257         /* Add the persistent grant into the list of free grants */
1258         for (i = 0; i < num_grant; i++) {
1259                 if (gnttab_query_foreign_access(s->grants_used[i]->gref)) {
1260                         /*
1261                          * If the grant is still mapped by the backend (the
1262                          * backend has chosen to make this grant persistent)
1263                          * we add it at the head of the list, so it will be
1264                          * reused first.
1265                          */
1266                         if (!info->feature_persistent)
1267                                 pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1268                                                      s->grants_used[i]->gref);
1269                         list_add(&s->grants_used[i]->node, &info->grants);
1270                         info->persistent_gnts_c++;
1271                 } else {
1272                         /*
1273                          * If the grant is not mapped by the backend we end the
1274                          * foreign access and add it to the tail of the list,
1275                          * so it will not be picked again unless we run out of
1276                          * persistent grants.
1277                          */
1278                         gnttab_end_foreign_access(s->grants_used[i]->gref, 0, 0UL);
1279                         s->grants_used[i]->gref = GRANT_INVALID_REF;
1280                         list_add_tail(&s->grants_used[i]->node, &info->grants);
1281                 }
1282         }
1283         if (s->req.operation == BLKIF_OP_INDIRECT) {
1284                 for (i = 0; i < INDIRECT_GREFS(num_grant); i++) {
1285                         if (gnttab_query_foreign_access(s->indirect_grants[i]->gref)) {
1286                                 if (!info->feature_persistent)
1287                                         pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1288                                                              s->indirect_grants[i]->gref);
1289                                 list_add(&s->indirect_grants[i]->node, &info->grants);
1290                                 info->persistent_gnts_c++;
1291                         } else {
1292                                 struct page *indirect_page;
1293
1294                                 gnttab_end_foreign_access(s->indirect_grants[i]->gref, 0, 0UL);
1295                                 /*
1296                                  * Add the used indirect page back to the list of
1297                                  * available pages for indirect grefs.
1298                                  */
1299                                 if (!info->feature_persistent) {
1300                                         indirect_page = s->indirect_grants[i]->page;
1301                                         list_add(&indirect_page->lru, &info->indirect_pages);
1302                                 }
1303                                 s->indirect_grants[i]->gref = GRANT_INVALID_REF;
1304                                 list_add_tail(&s->indirect_grants[i]->node, &info->grants);
1305                         }
1306                 }
1307         }
1308 }
1309
1310 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
1311 {
1312         struct request *req;
1313         struct blkif_response bret;
1314         RING_IDX i, rp;
1315         unsigned long flags;
1316         struct blkfront_info *info = (struct blkfront_info *)dev_id;
1317         int error;
1318         unsigned int eoiflag = XEN_EOI_FLAG_SPURIOUS;
1319
1320         spin_lock_irqsave(&info->io_lock, flags);
1321
1322         if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
1323                 spin_unlock_irqrestore(&info->io_lock, flags);
1324                 xen_irq_lateeoi(irq, XEN_EOI_FLAG_SPURIOUS);
1325                 return IRQ_HANDLED;
1326         }
1327
1328  again:
1329         rp = READ_ONCE(info->ring.sring->rsp_prod);
1330         rmb(); /* Ensure we see queued responses up to 'rp'. */
1331         if (RING_RESPONSE_PROD_OVERFLOW(&info->ring, rp)) {
1332                 pr_alert("%s: illegal number of responses %u\n",
1333                          info->gd->disk_name, rp - info->ring.rsp_cons);
1334                 goto err;
1335         }
1336
1337         for (i = info->ring.rsp_cons; i != rp; i++) {
1338                 unsigned long id;
1339                 unsigned int op;
1340
1341                 eoiflag = 0;
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         xen_irq_lateeoi(irq, eoiflag);
1448
1449         return IRQ_HANDLED;
1450
1451  err:
1452         info->connected = BLKIF_STATE_ERROR;
1453
1454         spin_unlock_irqrestore(&info->io_lock, flags);
1455
1456         /* No EOI in order to avoid further interrupts. */
1457
1458         pr_alert("%s disabled for further use\n", info->gd->disk_name);
1459         return IRQ_HANDLED;
1460 }
1461
1462
1463 static int setup_blkring(struct xenbus_device *dev,
1464                          struct blkfront_info *info)
1465 {
1466         struct blkif_sring *sring;
1467         int err, i;
1468         unsigned long ring_size = info->nr_ring_pages * XEN_PAGE_SIZE;
1469         grant_ref_t gref[XENBUS_MAX_RING_GRANTS];
1470
1471         for (i = 0; i < info->nr_ring_pages; i++)
1472                 info->ring_ref[i] = GRANT_INVALID_REF;
1473
1474         sring = (struct blkif_sring *)__get_free_pages(GFP_NOIO | __GFP_HIGH,
1475                                                        get_order(ring_size));
1476         if (!sring) {
1477                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
1478                 return -ENOMEM;
1479         }
1480         SHARED_RING_INIT(sring);
1481         FRONT_RING_INIT(&info->ring, sring, ring_size);
1482
1483         err = xenbus_grant_ring(dev, info->ring.sring, info->nr_ring_pages, gref);
1484         if (err < 0) {
1485                 free_pages((unsigned long)sring, get_order(ring_size));
1486                 info->ring.sring = NULL;
1487                 goto fail;
1488         }
1489         for (i = 0; i < info->nr_ring_pages; i++)
1490                 info->ring_ref[i] = gref[i];
1491
1492         err = xenbus_alloc_evtchn(dev, &info->evtchn);
1493         if (err)
1494                 goto fail;
1495
1496         err = bind_evtchn_to_irqhandler_lateeoi(info->evtchn, blkif_interrupt,
1497                                                 0, "blkif", info);
1498         if (err <= 0) {
1499                 xenbus_dev_fatal(dev, err,
1500                                  "bind_evtchn_to_irqhandler failed");
1501                 goto fail;
1502         }
1503         info->irq = err;
1504
1505         return 0;
1506 fail:
1507         blkif_free(info, 0);
1508         return err;
1509 }
1510
1511
1512 /* Common code used when first setting up, and when resuming. */
1513 static int talk_to_blkback(struct xenbus_device *dev,
1514                            struct blkfront_info *info)
1515 {
1516         const char *message = NULL;
1517         struct xenbus_transaction xbt;
1518         int err, i;
1519         unsigned int max_page_order = 0;
1520         unsigned int ring_page_order = 0;
1521
1522         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1523                            "max-ring-page-order", "%u", &max_page_order);
1524         if (err != 1)
1525                 info->nr_ring_pages = 1;
1526         else {
1527                 ring_page_order = min(xen_blkif_max_ring_order, max_page_order);
1528                 info->nr_ring_pages = 1 << ring_page_order;
1529         }
1530
1531         /* Create shared ring, alloc event channel. */
1532         err = setup_blkring(dev, info);
1533         if (err)
1534                 goto out;
1535
1536 again:
1537         err = xenbus_transaction_start(&xbt);
1538         if (err) {
1539                 xenbus_dev_fatal(dev, err, "starting transaction");
1540                 goto destroy_blkring;
1541         }
1542
1543         if (info->nr_ring_pages == 1) {
1544                 err = xenbus_printf(xbt, dev->nodename,
1545                                     "ring-ref", "%u", info->ring_ref[0]);
1546                 if (err) {
1547                         message = "writing ring-ref";
1548                         goto abort_transaction;
1549                 }
1550         } else {
1551                 err = xenbus_printf(xbt, dev->nodename,
1552                                     "ring-page-order", "%u", ring_page_order);
1553                 if (err) {
1554                         message = "writing ring-page-order";
1555                         goto abort_transaction;
1556                 }
1557
1558                 for (i = 0; i < info->nr_ring_pages; i++) {
1559                         char ring_ref_name[RINGREF_NAME_LEN];
1560
1561                         snprintf(ring_ref_name, RINGREF_NAME_LEN, "ring-ref%u", i);
1562                         err = xenbus_printf(xbt, dev->nodename, ring_ref_name,
1563                                             "%u", info->ring_ref[i]);
1564                         if (err) {
1565                                 message = "writing ring-ref";
1566                                 goto abort_transaction;
1567                         }
1568                 }
1569         }
1570         err = xenbus_printf(xbt, dev->nodename,
1571                             "event-channel", "%u", info->evtchn);
1572         if (err) {
1573                 message = "writing event-channel";
1574                 goto abort_transaction;
1575         }
1576         err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
1577                             XEN_IO_PROTO_ABI_NATIVE);
1578         if (err) {
1579                 message = "writing protocol";
1580                 goto abort_transaction;
1581         }
1582         err = xenbus_printf(xbt, dev->nodename,
1583                             "feature-persistent", "%u", 1);
1584         if (err)
1585                 dev_warn(&dev->dev,
1586                          "writing persistent grants feature to xenbus");
1587
1588         err = xenbus_transaction_end(xbt, 0);
1589         if (err) {
1590                 if (err == -EAGAIN)
1591                         goto again;
1592                 xenbus_dev_fatal(dev, err, "completing transaction");
1593                 goto destroy_blkring;
1594         }
1595
1596         for (i = 0; i < BLK_RING_SIZE(info); i++)
1597                 info->shadow[i].req.u.rw.id = i+1;
1598         info->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1599         xenbus_switch_state(dev, XenbusStateInitialised);
1600
1601         return 0;
1602
1603  abort_transaction:
1604         xenbus_transaction_end(xbt, 1);
1605         if (message)
1606                 xenbus_dev_fatal(dev, err, "%s", message);
1607  destroy_blkring:
1608         blkif_free(info, 0);
1609  out:
1610         return err;
1611 }
1612
1613 /**
1614  * Entry point to this code when a new device is created.  Allocate the basic
1615  * structures and the ring buffer for communication with the backend, and
1616  * inform the backend of the appropriate details for those.  Switch to
1617  * Initialised state.
1618  */
1619 static int blkfront_probe(struct xenbus_device *dev,
1620                           const struct xenbus_device_id *id)
1621 {
1622         int err, vdevice;
1623         struct blkfront_info *info;
1624
1625         /* FIXME: Use dynamic device id if this is not set. */
1626         err = xenbus_scanf(XBT_NIL, dev->nodename,
1627                            "virtual-device", "%i", &vdevice);
1628         if (err != 1) {
1629                 /* go looking in the extended area instead */
1630                 err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
1631                                    "%i", &vdevice);
1632                 if (err != 1) {
1633                         xenbus_dev_fatal(dev, err, "reading virtual-device");
1634                         return err;
1635                 }
1636         }
1637
1638         if (xen_hvm_domain()) {
1639                 char *type;
1640                 int len;
1641                 /* no unplug has been done: do not hook devices != xen vbds */
1642                 if (xen_has_pv_and_legacy_disk_devices()) {
1643                         int major;
1644
1645                         if (!VDEV_IS_EXTENDED(vdevice))
1646                                 major = BLKIF_MAJOR(vdevice);
1647                         else
1648                                 major = XENVBD_MAJOR;
1649
1650                         if (major != XENVBD_MAJOR) {
1651                                 printk(KERN_INFO
1652                                                 "%s: HVM does not support vbd %d as xen block device\n",
1653                                                 __func__, vdevice);
1654                                 return -ENODEV;
1655                         }
1656                 }
1657                 /* do not create a PV cdrom device if we are an HVM guest */
1658                 type = xenbus_read(XBT_NIL, dev->nodename, "device-type", &len);
1659                 if (IS_ERR(type))
1660                         return -ENODEV;
1661                 if (strncmp(type, "cdrom", 5) == 0) {
1662                         kfree(type);
1663                         return -ENODEV;
1664                 }
1665                 kfree(type);
1666         }
1667         info = kzalloc(sizeof(*info), GFP_KERNEL);
1668         if (!info) {
1669                 xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
1670                 return -ENOMEM;
1671         }
1672
1673         mutex_init(&info->mutex);
1674         spin_lock_init(&info->io_lock);
1675         info->xbdev = dev;
1676         info->vdevice = vdevice;
1677         INIT_LIST_HEAD(&info->grants);
1678         INIT_LIST_HEAD(&info->indirect_pages);
1679         info->persistent_gnts_c = 0;
1680         info->connected = BLKIF_STATE_DISCONNECTED;
1681         INIT_WORK(&info->work, blkif_restart_queue);
1682
1683         /* Front end dir is a number, which is used as the id. */
1684         info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
1685         dev_set_drvdata(&dev->dev, info);
1686
1687         return 0;
1688 }
1689
1690 static void split_bio_end(struct bio *bio)
1691 {
1692         struct split_bio *split_bio = bio->bi_private;
1693
1694         if (atomic_dec_and_test(&split_bio->pending)) {
1695                 split_bio->bio->bi_phys_segments = 0;
1696                 split_bio->bio->bi_error = bio->bi_error;
1697                 bio_endio(split_bio->bio);
1698                 kfree(split_bio);
1699         }
1700         bio_put(bio);
1701 }
1702
1703 static int blkif_recover(struct blkfront_info *info)
1704 {
1705         int i;
1706         struct request *req, *n;
1707         struct blk_shadow *copy;
1708         int rc;
1709         struct bio *bio, *cloned_bio;
1710         struct bio_list bio_list, merge_bio;
1711         unsigned int segs, offset;
1712         int pending, size;
1713         struct split_bio *split_bio;
1714         struct list_head requests;
1715
1716         /* Stage 1: Make a safe copy of the shadow state. */
1717         copy = kmemdup(info->shadow, sizeof(info->shadow),
1718                        GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
1719         if (!copy)
1720                 return -ENOMEM;
1721
1722         /* Stage 2: Set up free list. */
1723         memset(&info->shadow, 0, sizeof(info->shadow));
1724         for (i = 0; i < BLK_RING_SIZE(info); i++)
1725                 info->shadow[i].req.u.rw.id = i+1;
1726         info->shadow_free = info->ring.req_prod_pvt;
1727         info->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1728
1729         rc = blkfront_gather_backend_features(info);
1730         if (rc) {
1731                 kfree(copy);
1732                 return rc;
1733         }
1734
1735         segs = info->max_indirect_segments ? : BLKIF_MAX_SEGMENTS_PER_REQUEST;
1736         blk_queue_max_segments(info->rq, segs);
1737         bio_list_init(&bio_list);
1738         INIT_LIST_HEAD(&requests);
1739         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1740                 /* Not in use? */
1741                 if (!copy[i].request)
1742                         continue;
1743
1744                 /*
1745                  * Get the bios in the request so we can re-queue them.
1746                  */
1747                 if (copy[i].request->cmd_flags &
1748                     (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1749                         /*
1750                          * Flush operations don't contain bios, so
1751                          * we need to requeue the whole request
1752                          */
1753                         list_add(&copy[i].request->queuelist, &requests);
1754                         continue;
1755                 }
1756                 merge_bio.head = copy[i].request->bio;
1757                 merge_bio.tail = copy[i].request->biotail;
1758                 bio_list_merge(&bio_list, &merge_bio);
1759                 copy[i].request->bio = NULL;
1760                 blk_end_request_all(copy[i].request, 0);
1761         }
1762
1763         kfree(copy);
1764
1765         xenbus_switch_state(info->xbdev, XenbusStateConnected);
1766
1767         spin_lock_irq(&info->io_lock);
1768
1769         /* Now safe for us to use the shared ring */
1770         info->connected = BLKIF_STATE_CONNECTED;
1771
1772         /* Kick any other new requests queued since we resumed */
1773         kick_pending_request_queues(info);
1774
1775         list_for_each_entry_safe(req, n, &requests, queuelist) {
1776                 /* Requeue pending requests (flush or discard) */
1777                 list_del_init(&req->queuelist);
1778                 BUG_ON(req->nr_phys_segments > segs);
1779                 blk_mq_requeue_request(req);
1780         }
1781         spin_unlock_irq(&info->io_lock);
1782         blk_mq_kick_requeue_list(info->rq);
1783
1784         while ((bio = bio_list_pop(&bio_list)) != NULL) {
1785                 /* Traverse the list of pending bios and re-queue them */
1786                 if (bio_segments(bio) > segs) {
1787                         /*
1788                          * This bio has more segments than what we can
1789                          * handle, we have to split it.
1790                          */
1791                         pending = (bio_segments(bio) + segs - 1) / segs;
1792                         split_bio = kzalloc(sizeof(*split_bio), GFP_NOIO);
1793                         BUG_ON(split_bio == NULL);
1794                         atomic_set(&split_bio->pending, pending);
1795                         split_bio->bio = bio;
1796                         for (i = 0; i < pending; i++) {
1797                                 offset = (i * segs * XEN_PAGE_SIZE) >> 9;
1798                                 size = min((unsigned int)(segs * XEN_PAGE_SIZE) >> 9,
1799                                            (unsigned int)bio_sectors(bio) - offset);
1800                                 cloned_bio = bio_clone(bio, GFP_NOIO);
1801                                 BUG_ON(cloned_bio == NULL);
1802                                 bio_trim(cloned_bio, offset, size);
1803                                 cloned_bio->bi_private = split_bio;
1804                                 cloned_bio->bi_end_io = split_bio_end;
1805                                 submit_bio(cloned_bio->bi_rw, cloned_bio);
1806                         }
1807                         /*
1808                          * Now we have to wait for all those smaller bios to
1809                          * end, so we can also end the "parent" bio.
1810                          */
1811                         continue;
1812                 }
1813                 /* We don't need to split this bio */
1814                 submit_bio(bio->bi_rw, bio);
1815         }
1816
1817         return 0;
1818 }
1819
1820 /**
1821  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1822  * driver restart.  We tear down our blkif structure and recreate it, but
1823  * leave the device-layer structures intact so that this is transparent to the
1824  * rest of the kernel.
1825  */
1826 static int blkfront_resume(struct xenbus_device *dev)
1827 {
1828         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1829         int err;
1830
1831         dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
1832
1833         blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
1834
1835         err = talk_to_blkback(dev, info);
1836
1837         /*
1838          * We have to wait for the backend to switch to
1839          * connected state, since we want to read which
1840          * features it supports.
1841          */
1842
1843         return err;
1844 }
1845
1846 static void
1847 blkfront_closing(struct blkfront_info *info)
1848 {
1849         struct xenbus_device *xbdev = info->xbdev;
1850         struct block_device *bdev = NULL;
1851
1852         mutex_lock(&info->mutex);
1853
1854         if (xbdev->state == XenbusStateClosing) {
1855                 mutex_unlock(&info->mutex);
1856                 return;
1857         }
1858
1859         if (info->gd)
1860                 bdev = bdget_disk(info->gd, 0);
1861
1862         mutex_unlock(&info->mutex);
1863
1864         if (!bdev) {
1865                 xenbus_frontend_closed(xbdev);
1866                 return;
1867         }
1868
1869         mutex_lock(&bdev->bd_mutex);
1870
1871         if (bdev->bd_openers) {
1872                 xenbus_dev_error(xbdev, -EBUSY,
1873                                  "Device in use; refusing to close");
1874                 xenbus_switch_state(xbdev, XenbusStateClosing);
1875         } else {
1876                 xlvbd_release_gendisk(info);
1877                 xenbus_frontend_closed(xbdev);
1878         }
1879
1880         mutex_unlock(&bdev->bd_mutex);
1881         bdput(bdev);
1882 }
1883
1884 static void blkfront_setup_discard(struct blkfront_info *info)
1885 {
1886         int err;
1887         unsigned int discard_granularity;
1888         unsigned int discard_alignment;
1889         unsigned int discard_secure;
1890
1891         info->feature_discard = 1;
1892         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1893                 "discard-granularity", "%u", &discard_granularity,
1894                 "discard-alignment", "%u", &discard_alignment,
1895                 NULL);
1896         if (!err) {
1897                 info->discard_granularity = discard_granularity;
1898                 info->discard_alignment = discard_alignment;
1899         }
1900         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1901                     "discard-secure", "%d", &discard_secure,
1902                     NULL);
1903         if (!err)
1904                 info->feature_secdiscard = !!discard_secure;
1905 }
1906
1907 static int blkfront_setup_indirect(struct blkfront_info *info)
1908 {
1909         unsigned int psegs, grants;
1910         int err, i;
1911
1912         if (info->max_indirect_segments == 0)
1913                 grants = BLKIF_MAX_SEGMENTS_PER_REQUEST;
1914         else
1915                 grants = info->max_indirect_segments;
1916         psegs = grants / GRANTS_PER_PSEG;
1917
1918         err = fill_grant_buffer(info,
1919                                 (grants + INDIRECT_GREFS(grants)) * BLK_RING_SIZE(info));
1920         if (err)
1921                 goto out_of_memory;
1922
1923         if (!info->feature_persistent && info->max_indirect_segments) {
1924                 /*
1925                  * We are using indirect descriptors but not persistent
1926                  * grants, we need to allocate a set of pages that can be
1927                  * used for mapping indirect grefs
1928                  */
1929                 int num = INDIRECT_GREFS(grants) * BLK_RING_SIZE(info);
1930
1931                 BUG_ON(!list_empty(&info->indirect_pages));
1932                 for (i = 0; i < num; i++) {
1933                         struct page *indirect_page = alloc_page(GFP_NOIO);
1934                         if (!indirect_page)
1935                                 goto out_of_memory;
1936                         list_add(&indirect_page->lru, &info->indirect_pages);
1937                 }
1938         }
1939
1940         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1941                 info->shadow[i].grants_used = kzalloc(
1942                         sizeof(info->shadow[i].grants_used[0]) * grants,
1943                         GFP_NOIO);
1944                 info->shadow[i].sg = kzalloc(sizeof(info->shadow[i].sg[0]) * psegs, GFP_NOIO);
1945                 if (info->max_indirect_segments)
1946                         info->shadow[i].indirect_grants = kzalloc(
1947                                 sizeof(info->shadow[i].indirect_grants[0]) *
1948                                 INDIRECT_GREFS(grants),
1949                                 GFP_NOIO);
1950                 if ((info->shadow[i].grants_used == NULL) ||
1951                         (info->shadow[i].sg == NULL) ||
1952                      (info->max_indirect_segments &&
1953                      (info->shadow[i].indirect_grants == NULL)))
1954                         goto out_of_memory;
1955                 sg_init_table(info->shadow[i].sg, psegs);
1956         }
1957
1958
1959         return 0;
1960
1961 out_of_memory:
1962         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1963                 kfree(info->shadow[i].grants_used);
1964                 info->shadow[i].grants_used = NULL;
1965                 kfree(info->shadow[i].sg);
1966                 info->shadow[i].sg = NULL;
1967                 kfree(info->shadow[i].indirect_grants);
1968                 info->shadow[i].indirect_grants = NULL;
1969                 info->shadow[i].inflight = false;
1970         }
1971         if (!list_empty(&info->indirect_pages)) {
1972                 struct page *indirect_page, *n;
1973                 list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
1974                         list_del(&indirect_page->lru);
1975                         __free_page(indirect_page);
1976                 }
1977         }
1978         return -ENOMEM;
1979 }
1980
1981 /*
1982  * Gather all backend feature-*
1983  */
1984 static int blkfront_gather_backend_features(struct blkfront_info *info)
1985 {
1986         int err;
1987         int barrier, flush, discard, persistent;
1988         unsigned int indirect_segments;
1989
1990         info->feature_flush = 0;
1991
1992         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1993                         "feature-barrier", "%d", &barrier,
1994                         NULL);
1995
1996         /*
1997          * If there's no "feature-barrier" defined, then it means
1998          * we're dealing with a very old backend which writes
1999          * synchronously; nothing to do.
2000          *
2001          * If there are barriers, then we use flush.
2002          */
2003         if (!err && barrier)
2004                 info->feature_flush = REQ_FLUSH | REQ_FUA;
2005         /*
2006          * And if there is "feature-flush-cache" use that above
2007          * barriers.
2008          */
2009         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
2010                         "feature-flush-cache", "%d", &flush,
2011                         NULL);
2012
2013         if (!err && flush)
2014                 info->feature_flush = REQ_FLUSH;
2015
2016         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
2017                         "feature-discard", "%d", &discard,
2018                         NULL);
2019
2020         if (!err && discard)
2021                 blkfront_setup_discard(info);
2022
2023         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
2024                         "feature-persistent", "%u", &persistent,
2025                         NULL);
2026         if (err)
2027                 info->feature_persistent = 0;
2028         else
2029                 info->feature_persistent = persistent;
2030
2031         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
2032                             "feature-max-indirect-segments", "%u", &indirect_segments,
2033                             NULL);
2034         if (err)
2035                 info->max_indirect_segments = 0;
2036         else
2037                 info->max_indirect_segments = min(indirect_segments,
2038                                                   xen_blkif_max_segments);
2039
2040         return blkfront_setup_indirect(info);
2041 }
2042
2043 /*
2044  * Invoked when the backend is finally 'ready' (and has told produced
2045  * the details about the physical device - #sectors, size, etc).
2046  */
2047 static void blkfront_connect(struct blkfront_info *info)
2048 {
2049         unsigned long long sectors;
2050         unsigned long sector_size;
2051         unsigned int physical_sector_size;
2052         unsigned int binfo;
2053         int err;
2054
2055         switch (info->connected) {
2056         case BLKIF_STATE_CONNECTED:
2057                 /*
2058                  * Potentially, the back-end may be signalling
2059                  * a capacity change; update the capacity.
2060                  */
2061                 err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
2062                                    "sectors", "%Lu", &sectors);
2063                 if (XENBUS_EXIST_ERR(err))
2064                         return;
2065                 printk(KERN_INFO "Setting capacity to %Lu\n",
2066                        sectors);
2067                 set_capacity(info->gd, sectors);
2068                 revalidate_disk(info->gd);
2069
2070                 return;
2071         case BLKIF_STATE_SUSPENDED:
2072                 /*
2073                  * If we are recovering from suspension, we need to wait
2074                  * for the backend to announce it's features before
2075                  * reconnecting, at least we need to know if the backend
2076                  * supports indirect descriptors, and how many.
2077                  */
2078                 blkif_recover(info);
2079                 return;
2080
2081         default:
2082                 break;
2083         }
2084
2085         dev_dbg(&info->xbdev->dev, "%s:%s.\n",
2086                 __func__, info->xbdev->otherend);
2087
2088         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
2089                             "sectors", "%llu", &sectors,
2090                             "info", "%u", &binfo,
2091                             "sector-size", "%lu", &sector_size,
2092                             NULL);
2093         if (err) {
2094                 xenbus_dev_fatal(info->xbdev, err,
2095                                  "reading backend fields at %s",
2096                                  info->xbdev->otherend);
2097                 return;
2098         }
2099
2100         /*
2101          * physcial-sector-size is a newer field, so old backends may not
2102          * provide this. Assume physical sector size to be the same as
2103          * sector_size in that case.
2104          */
2105         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
2106                            "physical-sector-size", "%u", &physical_sector_size);
2107         if (err != 1)
2108                 physical_sector_size = sector_size;
2109
2110         err = blkfront_gather_backend_features(info);
2111         if (err) {
2112                 xenbus_dev_fatal(info->xbdev, err, "setup_indirect at %s",
2113                                  info->xbdev->otherend);
2114                 return;
2115         }
2116
2117         err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size,
2118                                   physical_sector_size);
2119         if (err) {
2120                 xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
2121                                  info->xbdev->otherend);
2122                 return;
2123         }
2124
2125         xenbus_switch_state(info->xbdev, XenbusStateConnected);
2126
2127         /* Kick pending requests. */
2128         spin_lock_irq(&info->io_lock);
2129         info->connected = BLKIF_STATE_CONNECTED;
2130         kick_pending_request_queues(info);
2131         spin_unlock_irq(&info->io_lock);
2132
2133         add_disk(info->gd);
2134
2135         info->is_ready = 1;
2136 }
2137
2138 /**
2139  * Callback received when the backend's state changes.
2140  */
2141 static void blkback_changed(struct xenbus_device *dev,
2142                             enum xenbus_state backend_state)
2143 {
2144         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2145
2146         dev_dbg(&dev->dev, "blkfront:blkback_changed to state %d.\n", backend_state);
2147
2148         switch (backend_state) {
2149         case XenbusStateInitWait:
2150                 if (dev->state != XenbusStateInitialising)
2151                         break;
2152                 if (talk_to_blkback(dev, info)) {
2153                         kfree(info);
2154                         dev_set_drvdata(&dev->dev, NULL);
2155                         break;
2156                 }
2157         case XenbusStateInitialising:
2158         case XenbusStateInitialised:
2159         case XenbusStateReconfiguring:
2160         case XenbusStateReconfigured:
2161         case XenbusStateUnknown:
2162                 break;
2163
2164         case XenbusStateConnected:
2165                 blkfront_connect(info);
2166                 break;
2167
2168         case XenbusStateClosed:
2169                 if (dev->state == XenbusStateClosed)
2170                         break;
2171                 /* Missed the backend's Closing state -- fallthrough */
2172         case XenbusStateClosing:
2173                 if (info)
2174                         blkfront_closing(info);
2175                 break;
2176         }
2177 }
2178
2179 static int blkfront_remove(struct xenbus_device *xbdev)
2180 {
2181         struct blkfront_info *info = dev_get_drvdata(&xbdev->dev);
2182         struct block_device *bdev = NULL;
2183         struct gendisk *disk;
2184
2185         dev_dbg(&xbdev->dev, "%s removed", xbdev->nodename);
2186
2187         blkif_free(info, 0);
2188
2189         mutex_lock(&info->mutex);
2190
2191         disk = info->gd;
2192         if (disk)
2193                 bdev = bdget_disk(disk, 0);
2194
2195         info->xbdev = NULL;
2196         mutex_unlock(&info->mutex);
2197
2198         if (!bdev) {
2199                 kfree(info);
2200                 return 0;
2201         }
2202
2203         /*
2204          * The xbdev was removed before we reached the Closed
2205          * state. See if it's safe to remove the disk. If the bdev
2206          * isn't closed yet, we let release take care of it.
2207          */
2208
2209         mutex_lock(&bdev->bd_mutex);
2210         info = disk->private_data;
2211
2212         dev_warn(disk_to_dev(disk),
2213                  "%s was hot-unplugged, %d stale handles\n",
2214                  xbdev->nodename, bdev->bd_openers);
2215
2216         if (info && !bdev->bd_openers) {
2217                 xlvbd_release_gendisk(info);
2218                 disk->private_data = NULL;
2219                 kfree(info);
2220         }
2221
2222         mutex_unlock(&bdev->bd_mutex);
2223         bdput(bdev);
2224
2225         return 0;
2226 }
2227
2228 static int blkfront_is_ready(struct xenbus_device *dev)
2229 {
2230         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2231
2232         return info->is_ready && info->xbdev;
2233 }
2234
2235 static int blkif_open(struct block_device *bdev, fmode_t mode)
2236 {
2237         struct gendisk *disk = bdev->bd_disk;
2238         struct blkfront_info *info;
2239         int err = 0;
2240
2241         mutex_lock(&blkfront_mutex);
2242
2243         info = disk->private_data;
2244         if (!info) {
2245                 /* xbdev gone */
2246                 err = -ERESTARTSYS;
2247                 goto out;
2248         }
2249
2250         mutex_lock(&info->mutex);
2251
2252         if (!info->gd)
2253                 /* xbdev is closed */
2254                 err = -ERESTARTSYS;
2255
2256         mutex_unlock(&info->mutex);
2257
2258 out:
2259         mutex_unlock(&blkfront_mutex);
2260         return err;
2261 }
2262
2263 static void blkif_release(struct gendisk *disk, fmode_t mode)
2264 {
2265         struct blkfront_info *info = disk->private_data;
2266         struct block_device *bdev;
2267         struct xenbus_device *xbdev;
2268
2269         mutex_lock(&blkfront_mutex);
2270
2271         bdev = bdget_disk(disk, 0);
2272
2273         if (!bdev) {
2274                 WARN(1, "Block device %s yanked out from us!\n", disk->disk_name);
2275                 goto out_mutex;
2276         }
2277         if (bdev->bd_openers)
2278                 goto out;
2279
2280         /*
2281          * Check if we have been instructed to close. We will have
2282          * deferred this request, because the bdev was still open.
2283          */
2284
2285         mutex_lock(&info->mutex);
2286         xbdev = info->xbdev;
2287
2288         if (xbdev && xbdev->state == XenbusStateClosing) {
2289                 /* pending switch to state closed */
2290                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2291                 xlvbd_release_gendisk(info);
2292                 xenbus_frontend_closed(info->xbdev);
2293         }
2294
2295         mutex_unlock(&info->mutex);
2296
2297         if (!xbdev) {
2298                 /* sudden device removal */
2299                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2300                 xlvbd_release_gendisk(info);
2301                 disk->private_data = NULL;
2302                 kfree(info);
2303         }
2304
2305 out:
2306         bdput(bdev);
2307 out_mutex:
2308         mutex_unlock(&blkfront_mutex);
2309 }
2310
2311 static const struct block_device_operations xlvbd_block_fops =
2312 {
2313         .owner = THIS_MODULE,
2314         .open = blkif_open,
2315         .release = blkif_release,
2316         .getgeo = blkif_getgeo,
2317         .ioctl = blkif_ioctl,
2318 };
2319
2320
2321 static const struct xenbus_device_id blkfront_ids[] = {
2322         { "vbd" },
2323         { "" }
2324 };
2325
2326 static struct xenbus_driver blkfront_driver = {
2327         .ids  = blkfront_ids,
2328         .probe = blkfront_probe,
2329         .remove = blkfront_remove,
2330         .resume = blkfront_resume,
2331         .otherend_changed = blkback_changed,
2332         .is_ready = blkfront_is_ready,
2333 };
2334
2335 static int __init xlblk_init(void)
2336 {
2337         int ret;
2338
2339         if (!xen_domain())
2340                 return -ENODEV;
2341
2342         if (xen_blkif_max_ring_order > XENBUS_MAX_RING_GRANT_ORDER) {
2343                 pr_info("Invalid max_ring_order (%d), will use default max: %d.\n",
2344                         xen_blkif_max_ring_order, XENBUS_MAX_RING_GRANT_ORDER);
2345                 xen_blkif_max_ring_order = 0;
2346         }
2347
2348         if (!xen_has_pv_disk_devices())
2349                 return -ENODEV;
2350
2351         if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
2352                 printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
2353                        XENVBD_MAJOR, DEV_NAME);
2354                 return -ENODEV;
2355         }
2356
2357         ret = xenbus_register_frontend(&blkfront_driver);
2358         if (ret) {
2359                 unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2360                 return ret;
2361         }
2362
2363         return 0;
2364 }
2365 module_init(xlblk_init);
2366
2367
2368 static void __exit xlblk_exit(void)
2369 {
2370         xenbus_unregister_driver(&blkfront_driver);
2371         unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2372         kfree(minors);
2373 }
2374 module_exit(xlblk_exit);
2375
2376 MODULE_DESCRIPTION("Xen virtual block device frontend");
2377 MODULE_LICENSE("GPL");
2378 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
2379 MODULE_ALIAS("xen:vbd");
2380 MODULE_ALIAS("xenblk");