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