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