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