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