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