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