GNU Linux-libre 5.15.54-gnu
[releases.git] / drivers / block / xen-blkfront.c
1 /*
2  * blkfront.c
3  *
4  * XenLinux virtual block device driver.
5  *
6  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
7  * Modifications by Mark A. Williamson are (c) Intel Research Cambridge
8  * Copyright (c) 2004, Christian Limpach
9  * Copyright (c) 2004, Andrew Warfield
10  * Copyright (c) 2005, Christopher Clark
11  * Copyright (c) 2005, XenSource Ltd
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License version 2
15  * as published by the Free Software Foundation; or, when distributed
16  * separately from the Linux kernel or incorporated into other
17  * software packages, subject to the following license:
18  *
19  * Permission is hereby granted, free of charge, to any person obtaining a copy
20  * of this source file (the "Software"), to deal in the Software without
21  * restriction, including without limitation the rights to use, copy, modify,
22  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
23  * and to permit persons to whom the Software is furnished to do so, subject to
24  * the following conditions:
25  *
26  * The above copyright notice and this permission notice shall be included in
27  * all copies or substantial portions of the Software.
28  *
29  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
34  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
35  * IN THE SOFTWARE.
36  */
37
38 #include <linux/interrupt.h>
39 #include <linux/blkdev.h>
40 #include <linux/blk-mq.h>
41 #include <linux/hdreg.h>
42 #include <linux/cdrom.h>
43 #include <linux/module.h>
44 #include <linux/slab.h>
45 #include <linux/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         int vdevice;
206         blkif_vdev_t handle;
207         enum blkif_state connected;
208         /* Number of pages per ring buffer. */
209         unsigned int nr_ring_pages;
210         struct request_queue *rq;
211         unsigned int feature_flush:1;
212         unsigned int feature_fua:1;
213         unsigned int feature_discard:1;
214         unsigned int feature_secdiscard:1;
215         unsigned int feature_persistent:1;
216         unsigned int bounce:1;
217         unsigned int discard_granularity;
218         unsigned int discard_alignment;
219         /* Number of 4KB segments handled */
220         unsigned int max_indirect_segments;
221         int is_ready;
222         struct blk_mq_tag_set tag_set;
223         struct blkfront_ring_info *rinfo;
224         unsigned int nr_rings;
225         unsigned int rinfo_size;
226         /* Save uncomplete reqs and bios for migration. */
227         struct list_head requests;
228         struct bio_list bio_list;
229         struct list_head info_list;
230 };
231
232 static unsigned int nr_minors;
233 static unsigned long *minors;
234 static DEFINE_SPINLOCK(minor_lock);
235
236 #define GRANT_INVALID_REF       0
237
238 #define PARTS_PER_DISK          16
239 #define PARTS_PER_EXT_DISK      256
240
241 #define BLKIF_MAJOR(dev) ((dev)>>8)
242 #define BLKIF_MINOR(dev) ((dev) & 0xff)
243
244 #define EXT_SHIFT 28
245 #define EXTENDED (1<<EXT_SHIFT)
246 #define VDEV_IS_EXTENDED(dev) ((dev)&(EXTENDED))
247 #define BLKIF_MINOR_EXT(dev) ((dev)&(~EXTENDED))
248 #define EMULATED_HD_DISK_MINOR_OFFSET (0)
249 #define EMULATED_HD_DISK_NAME_OFFSET (EMULATED_HD_DISK_MINOR_OFFSET / 256)
250 #define EMULATED_SD_DISK_MINOR_OFFSET (0)
251 #define EMULATED_SD_DISK_NAME_OFFSET (EMULATED_SD_DISK_MINOR_OFFSET / 256)
252
253 #define DEV_NAME        "xvd"   /* name in /dev */
254
255 /*
256  * Grants are always the same size as a Xen page (i.e 4KB).
257  * A physical segment is always the same size as a Linux page.
258  * Number of grants per physical segment
259  */
260 #define GRANTS_PER_PSEG (PAGE_SIZE / XEN_PAGE_SIZE)
261
262 #define GRANTS_PER_INDIRECT_FRAME \
263         (XEN_PAGE_SIZE / sizeof(struct blkif_request_segment))
264
265 #define INDIRECT_GREFS(_grants)         \
266         DIV_ROUND_UP(_grants, GRANTS_PER_INDIRECT_FRAME)
267
268 static int blkfront_setup_indirect(struct blkfront_ring_info *rinfo);
269 static void blkfront_gather_backend_features(struct blkfront_info *info);
270 static int negotiate_mq(struct blkfront_info *info);
271
272 #define for_each_rinfo(info, ptr, idx)                          \
273         for ((ptr) = (info)->rinfo, (idx) = 0;                  \
274              (idx) < (info)->nr_rings;                          \
275              (idx)++, (ptr) = (void *)(ptr) + (info)->rinfo_size)
276
277 static inline struct blkfront_ring_info *
278 get_rinfo(const struct blkfront_info *info, unsigned int i)
279 {
280         BUG_ON(i >= info->nr_rings);
281         return (void *)info->rinfo + i * info->rinfo_size;
282 }
283
284 static int get_id_from_freelist(struct blkfront_ring_info *rinfo)
285 {
286         unsigned long free = rinfo->shadow_free;
287
288         BUG_ON(free >= BLK_RING_SIZE(rinfo->dev_info));
289         rinfo->shadow_free = rinfo->shadow[free].req.u.rw.id;
290         rinfo->shadow[free].req.u.rw.id = 0x0fffffee; /* debug */
291         return free;
292 }
293
294 static int add_id_to_freelist(struct blkfront_ring_info *rinfo,
295                               unsigned long id)
296 {
297         if (rinfo->shadow[id].req.u.rw.id != id)
298                 return -EINVAL;
299         if (rinfo->shadow[id].request == NULL)
300                 return -EINVAL;
301         rinfo->shadow[id].req.u.rw.id  = rinfo->shadow_free;
302         rinfo->shadow[id].request = NULL;
303         rinfo->shadow_free = id;
304         return 0;
305 }
306
307 static int fill_grant_buffer(struct blkfront_ring_info *rinfo, int num)
308 {
309         struct blkfront_info *info = rinfo->dev_info;
310         struct page *granted_page;
311         struct grant *gnt_list_entry, *n;
312         int i = 0;
313
314         while (i < num) {
315                 gnt_list_entry = kzalloc(sizeof(struct grant), GFP_NOIO);
316                 if (!gnt_list_entry)
317                         goto out_of_memory;
318
319                 if (info->bounce) {
320                         granted_page = alloc_page(GFP_NOIO | __GFP_ZERO);
321                         if (!granted_page) {
322                                 kfree(gnt_list_entry);
323                                 goto out_of_memory;
324                         }
325                         gnt_list_entry->page = granted_page;
326                 }
327
328                 gnt_list_entry->gref = GRANT_INVALID_REF;
329                 list_add(&gnt_list_entry->node, &rinfo->grants);
330                 i++;
331         }
332
333         return 0;
334
335 out_of_memory:
336         list_for_each_entry_safe(gnt_list_entry, n,
337                                  &rinfo->grants, node) {
338                 list_del(&gnt_list_entry->node);
339                 if (info->bounce)
340                         __free_page(gnt_list_entry->page);
341                 kfree(gnt_list_entry);
342                 i--;
343         }
344         BUG_ON(i != 0);
345         return -ENOMEM;
346 }
347
348 static struct grant *get_free_grant(struct blkfront_ring_info *rinfo)
349 {
350         struct grant *gnt_list_entry;
351
352         BUG_ON(list_empty(&rinfo->grants));
353         gnt_list_entry = list_first_entry(&rinfo->grants, struct grant,
354                                           node);
355         list_del(&gnt_list_entry->node);
356
357         if (gnt_list_entry->gref != GRANT_INVALID_REF)
358                 rinfo->persistent_gnts_c--;
359
360         return gnt_list_entry;
361 }
362
363 static inline void grant_foreign_access(const struct grant *gnt_list_entry,
364                                         const struct blkfront_info *info)
365 {
366         gnttab_page_grant_foreign_access_ref_one(gnt_list_entry->gref,
367                                                  info->xbdev->otherend_id,
368                                                  gnt_list_entry->page,
369                                                  0);
370 }
371
372 static struct grant *get_grant(grant_ref_t *gref_head,
373                                unsigned long gfn,
374                                struct blkfront_ring_info *rinfo)
375 {
376         struct grant *gnt_list_entry = get_free_grant(rinfo);
377         struct blkfront_info *info = rinfo->dev_info;
378
379         if (gnt_list_entry->gref != GRANT_INVALID_REF)
380                 return gnt_list_entry;
381
382         /* Assign a gref to this page */
383         gnt_list_entry->gref = gnttab_claim_grant_reference(gref_head);
384         BUG_ON(gnt_list_entry->gref == -ENOSPC);
385         if (info->bounce)
386                 grant_foreign_access(gnt_list_entry, info);
387         else {
388                 /* Grant access to the GFN passed by the caller */
389                 gnttab_grant_foreign_access_ref(gnt_list_entry->gref,
390                                                 info->xbdev->otherend_id,
391                                                 gfn, 0);
392         }
393
394         return gnt_list_entry;
395 }
396
397 static struct grant *get_indirect_grant(grant_ref_t *gref_head,
398                                         struct blkfront_ring_info *rinfo)
399 {
400         struct grant *gnt_list_entry = get_free_grant(rinfo);
401         struct blkfront_info *info = rinfo->dev_info;
402
403         if (gnt_list_entry->gref != GRANT_INVALID_REF)
404                 return gnt_list_entry;
405
406         /* Assign a gref to this page */
407         gnt_list_entry->gref = gnttab_claim_grant_reference(gref_head);
408         BUG_ON(gnt_list_entry->gref == -ENOSPC);
409         if (!info->bounce) {
410                 struct page *indirect_page;
411
412                 /* Fetch a pre-allocated page to use for indirect grefs */
413                 BUG_ON(list_empty(&rinfo->indirect_pages));
414                 indirect_page = list_first_entry(&rinfo->indirect_pages,
415                                                  struct page, lru);
416                 list_del(&indirect_page->lru);
417                 gnt_list_entry->page = indirect_page;
418         }
419         grant_foreign_access(gnt_list_entry, info);
420
421         return gnt_list_entry;
422 }
423
424 static const char *op_name(int op)
425 {
426         static const char *const names[] = {
427                 [BLKIF_OP_READ] = "read",
428                 [BLKIF_OP_WRITE] = "write",
429                 [BLKIF_OP_WRITE_BARRIER] = "barrier",
430                 [BLKIF_OP_FLUSH_DISKCACHE] = "flush",
431                 [BLKIF_OP_DISCARD] = "discard" };
432
433         if (op < 0 || op >= ARRAY_SIZE(names))
434                 return "unknown";
435
436         if (!names[op])
437                 return "reserved";
438
439         return names[op];
440 }
441 static int xlbd_reserve_minors(unsigned int minor, unsigned int nr)
442 {
443         unsigned int end = minor + nr;
444         int rc;
445
446         if (end > nr_minors) {
447                 unsigned long *bitmap, *old;
448
449                 bitmap = kcalloc(BITS_TO_LONGS(end), sizeof(*bitmap),
450                                  GFP_KERNEL);
451                 if (bitmap == NULL)
452                         return -ENOMEM;
453
454                 spin_lock(&minor_lock);
455                 if (end > nr_minors) {
456                         old = minors;
457                         memcpy(bitmap, minors,
458                                BITS_TO_LONGS(nr_minors) * sizeof(*bitmap));
459                         minors = bitmap;
460                         nr_minors = BITS_TO_LONGS(end) * BITS_PER_LONG;
461                 } else
462                         old = bitmap;
463                 spin_unlock(&minor_lock);
464                 kfree(old);
465         }
466
467         spin_lock(&minor_lock);
468         if (find_next_bit(minors, end, minor) >= end) {
469                 bitmap_set(minors, minor, nr);
470                 rc = 0;
471         } else
472                 rc = -EBUSY;
473         spin_unlock(&minor_lock);
474
475         return rc;
476 }
477
478 static void xlbd_release_minors(unsigned int minor, unsigned int nr)
479 {
480         unsigned int end = minor + nr;
481
482         BUG_ON(end > nr_minors);
483         spin_lock(&minor_lock);
484         bitmap_clear(minors,  minor, nr);
485         spin_unlock(&minor_lock);
486 }
487
488 static void blkif_restart_queue_callback(void *arg)
489 {
490         struct blkfront_ring_info *rinfo = (struct blkfront_ring_info *)arg;
491         schedule_work(&rinfo->work);
492 }
493
494 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
495 {
496         /* We don't have real geometry info, but let's at least return
497            values consistent with the size of the device */
498         sector_t nsect = get_capacity(bd->bd_disk);
499         sector_t cylinders = nsect;
500
501         hg->heads = 0xff;
502         hg->sectors = 0x3f;
503         sector_div(cylinders, hg->heads * hg->sectors);
504         hg->cylinders = cylinders;
505         if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
506                 hg->cylinders = 0xffff;
507         return 0;
508 }
509
510 static int blkif_ioctl(struct block_device *bdev, fmode_t mode,
511                        unsigned command, unsigned long argument)
512 {
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 (bdev->bd_disk->flags & GENHD_FL_CD)
523                         return 0;
524                 return -EINVAL;
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 read 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_flag_set(QUEUE_FLAG_DISCARD, rq);
951                 blk_queue_max_discard_sectors(rq, get_capacity(gd));
952                 rq->limits.discard_granularity = info->discard_granularity ?:
953                                                  info->physical_sector_size;
954                 rq->limits.discard_alignment = info->discard_alignment;
955                 if (info->feature_secdiscard)
956                         blk_queue_flag_set(QUEUE_FLAG_SECERASE, rq);
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,
1067                                u16 vdisk_info, u16 sector_size,
1068                                unsigned int physical_sector_size)
1069 {
1070         struct gendisk *gd;
1071         int nr_minors = 1;
1072         int err;
1073         unsigned int offset;
1074         int minor;
1075         int nr_parts;
1076         char *ptr;
1077
1078         BUG_ON(info->gd != NULL);
1079         BUG_ON(info->rq != NULL);
1080
1081         if ((info->vdevice>>EXT_SHIFT) > 1) {
1082                 /* this is above the extended range; something is wrong */
1083                 printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
1084                 return -ENODEV;
1085         }
1086
1087         if (!VDEV_IS_EXTENDED(info->vdevice)) {
1088                 err = xen_translate_vdev(info->vdevice, &minor, &offset);
1089                 if (err)
1090                         return err;
1091                 nr_parts = PARTS_PER_DISK;
1092         } else {
1093                 minor = BLKIF_MINOR_EXT(info->vdevice);
1094                 nr_parts = PARTS_PER_EXT_DISK;
1095                 offset = minor / nr_parts;
1096                 if (xen_hvm_domain() && offset < EMULATED_HD_DISK_NAME_OFFSET + 4)
1097                         printk(KERN_WARNING "blkfront: vdevice 0x%x might conflict with "
1098                                         "emulated IDE disks,\n\t choose an xvd device name"
1099                                         "from xvde on\n", info->vdevice);
1100         }
1101         if (minor >> MINORBITS) {
1102                 pr_warn("blkfront: %#x's minor (%#x) out of range; ignoring\n",
1103                         info->vdevice, minor);
1104                 return -ENODEV;
1105         }
1106
1107         if ((minor % nr_parts) == 0)
1108                 nr_minors = nr_parts;
1109
1110         err = xlbd_reserve_minors(minor, nr_minors);
1111         if (err)
1112                 return err;
1113
1114         memset(&info->tag_set, 0, sizeof(info->tag_set));
1115         info->tag_set.ops = &blkfront_mq_ops;
1116         info->tag_set.nr_hw_queues = info->nr_rings;
1117         if (HAS_EXTRA_REQ && info->max_indirect_segments == 0) {
1118                 /*
1119                  * When indirect descriptior is not supported, the I/O request
1120                  * will be split between multiple request in the ring.
1121                  * To avoid problems when sending the request, divide by
1122                  * 2 the depth of the queue.
1123                  */
1124                 info->tag_set.queue_depth =  BLK_RING_SIZE(info) / 2;
1125         } else
1126                 info->tag_set.queue_depth = BLK_RING_SIZE(info);
1127         info->tag_set.numa_node = NUMA_NO_NODE;
1128         info->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
1129         info->tag_set.cmd_size = sizeof(struct blkif_req);
1130         info->tag_set.driver_data = info;
1131
1132         err = blk_mq_alloc_tag_set(&info->tag_set);
1133         if (err)
1134                 goto out_release_minors;
1135
1136         gd = blk_mq_alloc_disk(&info->tag_set, info);
1137         if (IS_ERR(gd)) {
1138                 err = PTR_ERR(gd);
1139                 goto out_free_tag_set;
1140         }
1141
1142         strcpy(gd->disk_name, DEV_NAME);
1143         ptr = encode_disk_name(gd->disk_name + sizeof(DEV_NAME) - 1, offset);
1144         BUG_ON(ptr >= gd->disk_name + DISK_NAME_LEN);
1145         if (nr_minors > 1)
1146                 *ptr = 0;
1147         else
1148                 snprintf(ptr, gd->disk_name + DISK_NAME_LEN - ptr,
1149                          "%d", minor & (nr_parts - 1));
1150
1151         gd->major = XENVBD_MAJOR;
1152         gd->first_minor = minor;
1153         gd->minors = nr_minors;
1154         gd->fops = &xlvbd_block_fops;
1155         gd->private_data = info;
1156         set_capacity(gd, capacity);
1157
1158         info->rq = gd->queue;
1159         info->gd = gd;
1160         info->sector_size = sector_size;
1161         info->physical_sector_size = physical_sector_size;
1162         blkif_set_queue_limits(info);
1163
1164         xlvbd_flush(info);
1165
1166         if (vdisk_info & VDISK_READONLY)
1167                 set_disk_ro(gd, 1);
1168
1169         if (vdisk_info & VDISK_REMOVABLE)
1170                 gd->flags |= GENHD_FL_REMOVABLE;
1171
1172         if (vdisk_info & VDISK_CDROM)
1173                 gd->flags |= GENHD_FL_CD;
1174
1175         return 0;
1176
1177 out_free_tag_set:
1178         blk_mq_free_tag_set(&info->tag_set);
1179 out_release_minors:
1180         xlbd_release_minors(minor, nr_minors);
1181         return err;
1182 }
1183
1184 /* Already hold rinfo->ring_lock. */
1185 static inline void kick_pending_request_queues_locked(struct blkfront_ring_info *rinfo)
1186 {
1187         if (!RING_FULL(&rinfo->ring))
1188                 blk_mq_start_stopped_hw_queues(rinfo->dev_info->rq, true);
1189 }
1190
1191 static void kick_pending_request_queues(struct blkfront_ring_info *rinfo)
1192 {
1193         unsigned long flags;
1194
1195         spin_lock_irqsave(&rinfo->ring_lock, flags);
1196         kick_pending_request_queues_locked(rinfo);
1197         spin_unlock_irqrestore(&rinfo->ring_lock, flags);
1198 }
1199
1200 static void blkif_restart_queue(struct work_struct *work)
1201 {
1202         struct blkfront_ring_info *rinfo = container_of(work, struct blkfront_ring_info, work);
1203
1204         if (rinfo->dev_info->connected == BLKIF_STATE_CONNECTED)
1205                 kick_pending_request_queues(rinfo);
1206 }
1207
1208 static void blkif_free_ring(struct blkfront_ring_info *rinfo)
1209 {
1210         struct grant *persistent_gnt, *n;
1211         struct blkfront_info *info = rinfo->dev_info;
1212         int i, j, segs;
1213
1214         /*
1215          * Remove indirect pages, this only happens when using indirect
1216          * descriptors but not persistent grants
1217          */
1218         if (!list_empty(&rinfo->indirect_pages)) {
1219                 struct page *indirect_page, *n;
1220
1221                 BUG_ON(info->bounce);
1222                 list_for_each_entry_safe(indirect_page, n, &rinfo->indirect_pages, lru) {
1223                         list_del(&indirect_page->lru);
1224                         __free_page(indirect_page);
1225                 }
1226         }
1227
1228         /* Remove all persistent grants. */
1229         if (!list_empty(&rinfo->grants)) {
1230                 list_for_each_entry_safe(persistent_gnt, n,
1231                                          &rinfo->grants, node) {
1232                         list_del(&persistent_gnt->node);
1233                         if (persistent_gnt->gref != GRANT_INVALID_REF) {
1234                                 gnttab_end_foreign_access(persistent_gnt->gref,
1235                                                           0, 0UL);
1236                                 rinfo->persistent_gnts_c--;
1237                         }
1238                         if (info->bounce)
1239                                 __free_page(persistent_gnt->page);
1240                         kfree(persistent_gnt);
1241                 }
1242         }
1243         BUG_ON(rinfo->persistent_gnts_c != 0);
1244
1245         for (i = 0; i < BLK_RING_SIZE(info); i++) {
1246                 /*
1247                  * Clear persistent grants present in requests already
1248                  * on the shared ring
1249                  */
1250                 if (!rinfo->shadow[i].request)
1251                         goto free_shadow;
1252
1253                 segs = rinfo->shadow[i].req.operation == BLKIF_OP_INDIRECT ?
1254                        rinfo->shadow[i].req.u.indirect.nr_segments :
1255                        rinfo->shadow[i].req.u.rw.nr_segments;
1256                 for (j = 0; j < segs; j++) {
1257                         persistent_gnt = rinfo->shadow[i].grants_used[j];
1258                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1259                         if (info->bounce)
1260                                 __free_page(persistent_gnt->page);
1261                         kfree(persistent_gnt);
1262                 }
1263
1264                 if (rinfo->shadow[i].req.operation != BLKIF_OP_INDIRECT)
1265                         /*
1266                          * If this is not an indirect operation don't try to
1267                          * free indirect segments
1268                          */
1269                         goto free_shadow;
1270
1271                 for (j = 0; j < INDIRECT_GREFS(segs); j++) {
1272                         persistent_gnt = rinfo->shadow[i].indirect_grants[j];
1273                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1274                         __free_page(persistent_gnt->page);
1275                         kfree(persistent_gnt);
1276                 }
1277
1278 free_shadow:
1279                 kvfree(rinfo->shadow[i].grants_used);
1280                 rinfo->shadow[i].grants_used = NULL;
1281                 kvfree(rinfo->shadow[i].indirect_grants);
1282                 rinfo->shadow[i].indirect_grants = NULL;
1283                 kvfree(rinfo->shadow[i].sg);
1284                 rinfo->shadow[i].sg = NULL;
1285         }
1286
1287         /* No more gnttab callback work. */
1288         gnttab_cancel_free_callback(&rinfo->callback);
1289
1290         /* Flush gnttab callback work. Must be done with no locks held. */
1291         flush_work(&rinfo->work);
1292
1293         /* Free resources associated with old device channel. */
1294         for (i = 0; i < info->nr_ring_pages; i++) {
1295                 if (rinfo->ring_ref[i] != GRANT_INVALID_REF) {
1296                         gnttab_end_foreign_access(rinfo->ring_ref[i], 0, 0);
1297                         rinfo->ring_ref[i] = GRANT_INVALID_REF;
1298                 }
1299         }
1300         free_pages_exact(rinfo->ring.sring,
1301                          info->nr_ring_pages * XEN_PAGE_SIZE);
1302         rinfo->ring.sring = NULL;
1303
1304         if (rinfo->irq)
1305                 unbind_from_irqhandler(rinfo->irq, rinfo);
1306         rinfo->evtchn = rinfo->irq = 0;
1307 }
1308
1309 static void blkif_free(struct blkfront_info *info, int suspend)
1310 {
1311         unsigned int i;
1312         struct blkfront_ring_info *rinfo;
1313
1314         /* Prevent new requests being issued until we fix things up. */
1315         info->connected = suspend ?
1316                 BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
1317         /* No more blkif_request(). */
1318         if (info->rq)
1319                 blk_mq_stop_hw_queues(info->rq);
1320
1321         for_each_rinfo(info, rinfo, i)
1322                 blkif_free_ring(rinfo);
1323
1324         kvfree(info->rinfo);
1325         info->rinfo = NULL;
1326         info->nr_rings = 0;
1327 }
1328
1329 struct copy_from_grant {
1330         const struct blk_shadow *s;
1331         unsigned int grant_idx;
1332         unsigned int bvec_offset;
1333         char *bvec_data;
1334 };
1335
1336 static void blkif_copy_from_grant(unsigned long gfn, unsigned int offset,
1337                                   unsigned int len, void *data)
1338 {
1339         struct copy_from_grant *info = data;
1340         char *shared_data;
1341         /* Convenient aliases */
1342         const struct blk_shadow *s = info->s;
1343
1344         shared_data = kmap_atomic(s->grants_used[info->grant_idx]->page);
1345
1346         memcpy(info->bvec_data + info->bvec_offset,
1347                shared_data + offset, len);
1348
1349         info->bvec_offset += len;
1350         info->grant_idx++;
1351
1352         kunmap_atomic(shared_data);
1353 }
1354
1355 static enum blk_req_status blkif_rsp_to_req_status(int rsp)
1356 {
1357         switch (rsp)
1358         {
1359         case BLKIF_RSP_OKAY:
1360                 return REQ_DONE;
1361         case BLKIF_RSP_EOPNOTSUPP:
1362                 return REQ_EOPNOTSUPP;
1363         case BLKIF_RSP_ERROR:
1364         default:
1365                 return REQ_ERROR;
1366         }
1367 }
1368
1369 /*
1370  * Get the final status of the block request based on two ring response
1371  */
1372 static int blkif_get_final_status(enum blk_req_status s1,
1373                                   enum blk_req_status s2)
1374 {
1375         BUG_ON(s1 < REQ_DONE);
1376         BUG_ON(s2 < REQ_DONE);
1377
1378         if (s1 == REQ_ERROR || s2 == REQ_ERROR)
1379                 return BLKIF_RSP_ERROR;
1380         else if (s1 == REQ_EOPNOTSUPP || s2 == REQ_EOPNOTSUPP)
1381                 return BLKIF_RSP_EOPNOTSUPP;
1382         return BLKIF_RSP_OKAY;
1383 }
1384
1385 /*
1386  * Return values:
1387  *  1 response processed.
1388  *  0 missing further responses.
1389  * -1 error while processing.
1390  */
1391 static int blkif_completion(unsigned long *id,
1392                             struct blkfront_ring_info *rinfo,
1393                             struct blkif_response *bret)
1394 {
1395         int i = 0;
1396         struct scatterlist *sg;
1397         int num_sg, num_grant;
1398         struct blkfront_info *info = rinfo->dev_info;
1399         struct blk_shadow *s = &rinfo->shadow[*id];
1400         struct copy_from_grant data = {
1401                 .grant_idx = 0,
1402         };
1403
1404         num_grant = s->req.operation == BLKIF_OP_INDIRECT ?
1405                 s->req.u.indirect.nr_segments : s->req.u.rw.nr_segments;
1406
1407         /* The I/O request may be split in two. */
1408         if (unlikely(s->associated_id != NO_ASSOCIATED_ID)) {
1409                 struct blk_shadow *s2 = &rinfo->shadow[s->associated_id];
1410
1411                 /* Keep the status of the current response in shadow. */
1412                 s->status = blkif_rsp_to_req_status(bret->status);
1413
1414                 /* Wait the second response if not yet here. */
1415                 if (s2->status < REQ_DONE)
1416                         return 0;
1417
1418                 bret->status = blkif_get_final_status(s->status,
1419                                                       s2->status);
1420
1421                 /*
1422                  * All the grants is stored in the first shadow in order
1423                  * to make the completion code simpler.
1424                  */
1425                 num_grant += s2->req.u.rw.nr_segments;
1426
1427                 /*
1428                  * The two responses may not come in order. Only the
1429                  * first request will store the scatter-gather list.
1430                  */
1431                 if (s2->num_sg != 0) {
1432                         /* Update "id" with the ID of the first response. */
1433                         *id = s->associated_id;
1434                         s = s2;
1435                 }
1436
1437                 /*
1438                  * We don't need anymore the second request, so recycling
1439                  * it now.
1440                  */
1441                 if (add_id_to_freelist(rinfo, s->associated_id))
1442                         WARN(1, "%s: can't recycle the second part (id = %ld) of the request\n",
1443                              info->gd->disk_name, s->associated_id);
1444         }
1445
1446         data.s = s;
1447         num_sg = s->num_sg;
1448
1449         if (bret->operation == BLKIF_OP_READ && info->bounce) {
1450                 for_each_sg(s->sg, sg, num_sg, i) {
1451                         BUG_ON(sg->offset + sg->length > PAGE_SIZE);
1452
1453                         data.bvec_offset = sg->offset;
1454                         data.bvec_data = kmap_atomic(sg_page(sg));
1455
1456                         gnttab_foreach_grant_in_range(sg_page(sg),
1457                                                       sg->offset,
1458                                                       sg->length,
1459                                                       blkif_copy_from_grant,
1460                                                       &data);
1461
1462                         kunmap_atomic(data.bvec_data);
1463                 }
1464         }
1465         /* Add the persistent grant into the list of free grants */
1466         for (i = 0; i < num_grant; i++) {
1467                 if (!gnttab_try_end_foreign_access(s->grants_used[i]->gref)) {
1468                         /*
1469                          * If the grant is still mapped by the backend (the
1470                          * backend has chosen to make this grant persistent)
1471                          * we add it at the head of the list, so it will be
1472                          * reused first.
1473                          */
1474                         if (!info->feature_persistent) {
1475                                 pr_alert("backed has not unmapped grant: %u\n",
1476                                          s->grants_used[i]->gref);
1477                                 return -1;
1478                         }
1479                         list_add(&s->grants_used[i]->node, &rinfo->grants);
1480                         rinfo->persistent_gnts_c++;
1481                 } else {
1482                         /*
1483                          * If the grant is not mapped by the backend we add it
1484                          * to the tail of the list, so it will not be picked
1485                          * again unless we run out of persistent grants.
1486                          */
1487                         s->grants_used[i]->gref = GRANT_INVALID_REF;
1488                         list_add_tail(&s->grants_used[i]->node, &rinfo->grants);
1489                 }
1490         }
1491         if (s->req.operation == BLKIF_OP_INDIRECT) {
1492                 for (i = 0; i < INDIRECT_GREFS(num_grant); i++) {
1493                         if (!gnttab_try_end_foreign_access(s->indirect_grants[i]->gref)) {
1494                                 if (!info->feature_persistent) {
1495                                         pr_alert("backed has not unmapped grant: %u\n",
1496                                                  s->indirect_grants[i]->gref);
1497                                         return -1;
1498                                 }
1499                                 list_add(&s->indirect_grants[i]->node, &rinfo->grants);
1500                                 rinfo->persistent_gnts_c++;
1501                         } else {
1502                                 struct page *indirect_page;
1503
1504                                 /*
1505                                  * Add the used indirect page back to the list of
1506                                  * available pages for indirect grefs.
1507                                  */
1508                                 if (!info->bounce) {
1509                                         indirect_page = s->indirect_grants[i]->page;
1510                                         list_add(&indirect_page->lru, &rinfo->indirect_pages);
1511                                 }
1512                                 s->indirect_grants[i]->gref = GRANT_INVALID_REF;
1513                                 list_add_tail(&s->indirect_grants[i]->node, &rinfo->grants);
1514                         }
1515                 }
1516         }
1517
1518         return 1;
1519 }
1520
1521 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
1522 {
1523         struct request *req;
1524         struct blkif_response bret;
1525         RING_IDX i, rp;
1526         unsigned long flags;
1527         struct blkfront_ring_info *rinfo = (struct blkfront_ring_info *)dev_id;
1528         struct blkfront_info *info = rinfo->dev_info;
1529         unsigned int eoiflag = XEN_EOI_FLAG_SPURIOUS;
1530
1531         if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
1532                 xen_irq_lateeoi(irq, XEN_EOI_FLAG_SPURIOUS);
1533                 return IRQ_HANDLED;
1534         }
1535
1536         spin_lock_irqsave(&rinfo->ring_lock, flags);
1537  again:
1538         rp = READ_ONCE(rinfo->ring.sring->rsp_prod);
1539         virt_rmb(); /* Ensure we see queued responses up to 'rp'. */
1540         if (RING_RESPONSE_PROD_OVERFLOW(&rinfo->ring, rp)) {
1541                 pr_alert("%s: illegal number of responses %u\n",
1542                          info->gd->disk_name, rp - rinfo->ring.rsp_cons);
1543                 goto err;
1544         }
1545
1546         for (i = rinfo->ring.rsp_cons; i != rp; i++) {
1547                 unsigned long id;
1548                 unsigned int op;
1549
1550                 eoiflag = 0;
1551
1552                 RING_COPY_RESPONSE(&rinfo->ring, i, &bret);
1553                 id = bret.id;
1554
1555                 /*
1556                  * The backend has messed up and given us an id that we would
1557                  * never have given to it (we stamp it up to BLK_RING_SIZE -
1558                  * look in get_id_from_freelist.
1559                  */
1560                 if (id >= BLK_RING_SIZE(info)) {
1561                         pr_alert("%s: response has incorrect id (%ld)\n",
1562                                  info->gd->disk_name, id);
1563                         goto err;
1564                 }
1565                 if (rinfo->shadow[id].status != REQ_WAITING) {
1566                         pr_alert("%s: response references no pending request\n",
1567                                  info->gd->disk_name);
1568                         goto err;
1569                 }
1570
1571                 rinfo->shadow[id].status = REQ_PROCESSING;
1572                 req  = rinfo->shadow[id].request;
1573
1574                 op = rinfo->shadow[id].req.operation;
1575                 if (op == BLKIF_OP_INDIRECT)
1576                         op = rinfo->shadow[id].req.u.indirect.indirect_op;
1577                 if (bret.operation != op) {
1578                         pr_alert("%s: response has wrong operation (%u instead of %u)\n",
1579                                  info->gd->disk_name, bret.operation, op);
1580                         goto err;
1581                 }
1582
1583                 if (bret.operation != BLKIF_OP_DISCARD) {
1584                         int ret;
1585
1586                         /*
1587                          * We may need to wait for an extra response if the
1588                          * I/O request is split in 2
1589                          */
1590                         ret = blkif_completion(&id, rinfo, &bret);
1591                         if (!ret)
1592                                 continue;
1593                         if (unlikely(ret < 0))
1594                                 goto err;
1595                 }
1596
1597                 if (add_id_to_freelist(rinfo, id)) {
1598                         WARN(1, "%s: response to %s (id %ld) couldn't be recycled!\n",
1599                              info->gd->disk_name, op_name(bret.operation), id);
1600                         continue;
1601                 }
1602
1603                 if (bret.status == BLKIF_RSP_OKAY)
1604                         blkif_req(req)->error = BLK_STS_OK;
1605                 else
1606                         blkif_req(req)->error = BLK_STS_IOERR;
1607
1608                 switch (bret.operation) {
1609                 case BLKIF_OP_DISCARD:
1610                         if (unlikely(bret.status == BLKIF_RSP_EOPNOTSUPP)) {
1611                                 struct request_queue *rq = info->rq;
1612
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                                 info->feature_discard = 0;
1617                                 info->feature_secdiscard = 0;
1618                                 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, rq);
1619                                 blk_queue_flag_clear(QUEUE_FLAG_SECERASE, rq);
1620                         }
1621                         break;
1622                 case BLKIF_OP_FLUSH_DISKCACHE:
1623                 case BLKIF_OP_WRITE_BARRIER:
1624                         if (unlikely(bret.status == BLKIF_RSP_EOPNOTSUPP)) {
1625                                 pr_warn_ratelimited("blkfront: %s: %s op failed\n",
1626                                        info->gd->disk_name, op_name(bret.operation));
1627                                 blkif_req(req)->error = BLK_STS_NOTSUPP;
1628                         }
1629                         if (unlikely(bret.status == BLKIF_RSP_ERROR &&
1630                                      rinfo->shadow[id].req.u.rw.nr_segments == 0)) {
1631                                 pr_warn_ratelimited("blkfront: %s: empty %s op failed\n",
1632                                        info->gd->disk_name, op_name(bret.operation));
1633                                 blkif_req(req)->error = BLK_STS_NOTSUPP;
1634                         }
1635                         if (unlikely(blkif_req(req)->error)) {
1636                                 if (blkif_req(req)->error == BLK_STS_NOTSUPP)
1637                                         blkif_req(req)->error = BLK_STS_OK;
1638                                 info->feature_fua = 0;
1639                                 info->feature_flush = 0;
1640                                 xlvbd_flush(info);
1641                         }
1642                         fallthrough;
1643                 case BLKIF_OP_READ:
1644                 case BLKIF_OP_WRITE:
1645                         if (unlikely(bret.status != BLKIF_RSP_OKAY))
1646                                 dev_dbg_ratelimited(&info->xbdev->dev,
1647                                         "Bad return from blkdev data request: %#x\n",
1648                                         bret.status);
1649
1650                         break;
1651                 default:
1652                         BUG();
1653                 }
1654
1655                 if (likely(!blk_should_fake_timeout(req->q)))
1656                         blk_mq_complete_request(req);
1657         }
1658
1659         rinfo->ring.rsp_cons = i;
1660
1661         if (i != rinfo->ring.req_prod_pvt) {
1662                 int more_to_do;
1663                 RING_FINAL_CHECK_FOR_RESPONSES(&rinfo->ring, more_to_do);
1664                 if (more_to_do)
1665                         goto again;
1666         } else
1667                 rinfo->ring.sring->rsp_event = i + 1;
1668
1669         kick_pending_request_queues_locked(rinfo);
1670
1671         spin_unlock_irqrestore(&rinfo->ring_lock, flags);
1672
1673         xen_irq_lateeoi(irq, eoiflag);
1674
1675         return IRQ_HANDLED;
1676
1677  err:
1678         info->connected = BLKIF_STATE_ERROR;
1679
1680         spin_unlock_irqrestore(&rinfo->ring_lock, flags);
1681
1682         /* No EOI in order to avoid further interrupts. */
1683
1684         pr_alert("%s disabled for further use\n", info->gd->disk_name);
1685         return IRQ_HANDLED;
1686 }
1687
1688
1689 static int setup_blkring(struct xenbus_device *dev,
1690                          struct blkfront_ring_info *rinfo)
1691 {
1692         struct blkif_sring *sring;
1693         int err, i;
1694         struct blkfront_info *info = rinfo->dev_info;
1695         unsigned long ring_size = info->nr_ring_pages * XEN_PAGE_SIZE;
1696         grant_ref_t gref[XENBUS_MAX_RING_GRANTS];
1697
1698         for (i = 0; i < info->nr_ring_pages; i++)
1699                 rinfo->ring_ref[i] = GRANT_INVALID_REF;
1700
1701         sring = alloc_pages_exact(ring_size, GFP_NOIO | __GFP_ZERO);
1702         if (!sring) {
1703                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
1704                 return -ENOMEM;
1705         }
1706         SHARED_RING_INIT(sring);
1707         FRONT_RING_INIT(&rinfo->ring, sring, ring_size);
1708
1709         err = xenbus_grant_ring(dev, rinfo->ring.sring, info->nr_ring_pages, gref);
1710         if (err < 0) {
1711                 free_pages_exact(sring, ring_size);
1712                 rinfo->ring.sring = NULL;
1713                 goto fail;
1714         }
1715         for (i = 0; i < info->nr_ring_pages; i++)
1716                 rinfo->ring_ref[i] = gref[i];
1717
1718         err = xenbus_alloc_evtchn(dev, &rinfo->evtchn);
1719         if (err)
1720                 goto fail;
1721
1722         err = bind_evtchn_to_irqhandler_lateeoi(rinfo->evtchn, blkif_interrupt,
1723                                                 0, "blkif", rinfo);
1724         if (err <= 0) {
1725                 xenbus_dev_fatal(dev, err,
1726                                  "bind_evtchn_to_irqhandler failed");
1727                 goto fail;
1728         }
1729         rinfo->irq = err;
1730
1731         return 0;
1732 fail:
1733         blkif_free(info, 0);
1734         return err;
1735 }
1736
1737 /*
1738  * Write out per-ring/queue nodes including ring-ref and event-channel, and each
1739  * ring buffer may have multi pages depending on ->nr_ring_pages.
1740  */
1741 static int write_per_ring_nodes(struct xenbus_transaction xbt,
1742                                 struct blkfront_ring_info *rinfo, const char *dir)
1743 {
1744         int err;
1745         unsigned int i;
1746         const char *message = NULL;
1747         struct blkfront_info *info = rinfo->dev_info;
1748
1749         if (info->nr_ring_pages == 1) {
1750                 err = xenbus_printf(xbt, dir, "ring-ref", "%u", rinfo->ring_ref[0]);
1751                 if (err) {
1752                         message = "writing ring-ref";
1753                         goto abort_transaction;
1754                 }
1755         } else {
1756                 for (i = 0; i < info->nr_ring_pages; i++) {
1757                         char ring_ref_name[RINGREF_NAME_LEN];
1758
1759                         snprintf(ring_ref_name, RINGREF_NAME_LEN, "ring-ref%u", i);
1760                         err = xenbus_printf(xbt, dir, ring_ref_name,
1761                                             "%u", rinfo->ring_ref[i]);
1762                         if (err) {
1763                                 message = "writing ring-ref";
1764                                 goto abort_transaction;
1765                         }
1766                 }
1767         }
1768
1769         err = xenbus_printf(xbt, dir, "event-channel", "%u", rinfo->evtchn);
1770         if (err) {
1771                 message = "writing event-channel";
1772                 goto abort_transaction;
1773         }
1774
1775         return 0;
1776
1777 abort_transaction:
1778         xenbus_transaction_end(xbt, 1);
1779         if (message)
1780                 xenbus_dev_fatal(info->xbdev, err, "%s", message);
1781
1782         return err;
1783 }
1784
1785 /* Common code used when first setting up, and when resuming. */
1786 static int talk_to_blkback(struct xenbus_device *dev,
1787                            struct blkfront_info *info)
1788 {
1789         const char *message = NULL;
1790         struct xenbus_transaction xbt;
1791         int err;
1792         unsigned int i, max_page_order;
1793         unsigned int ring_page_order;
1794         struct blkfront_ring_info *rinfo;
1795
1796         if (!info)
1797                 return -ENODEV;
1798
1799         /* Check if backend is trusted. */
1800         info->bounce = !xen_blkif_trusted ||
1801                        !xenbus_read_unsigned(dev->nodename, "trusted", 1);
1802
1803         max_page_order = xenbus_read_unsigned(info->xbdev->otherend,
1804                                               "max-ring-page-order", 0);
1805         ring_page_order = min(xen_blkif_max_ring_order, max_page_order);
1806         info->nr_ring_pages = 1 << ring_page_order;
1807
1808         err = negotiate_mq(info);
1809         if (err)
1810                 goto destroy_blkring;
1811
1812         for_each_rinfo(info, rinfo, i) {
1813                 /* Create shared ring, alloc event channel. */
1814                 err = setup_blkring(dev, rinfo);
1815                 if (err)
1816                         goto destroy_blkring;
1817         }
1818
1819 again:
1820         err = xenbus_transaction_start(&xbt);
1821         if (err) {
1822                 xenbus_dev_fatal(dev, err, "starting transaction");
1823                 goto destroy_blkring;
1824         }
1825
1826         if (info->nr_ring_pages > 1) {
1827                 err = xenbus_printf(xbt, dev->nodename, "ring-page-order", "%u",
1828                                     ring_page_order);
1829                 if (err) {
1830                         message = "writing ring-page-order";
1831                         goto abort_transaction;
1832                 }
1833         }
1834
1835         /* We already got the number of queues/rings in _probe */
1836         if (info->nr_rings == 1) {
1837                 err = write_per_ring_nodes(xbt, info->rinfo, dev->nodename);
1838                 if (err)
1839                         goto destroy_blkring;
1840         } else {
1841                 char *path;
1842                 size_t pathsize;
1843
1844                 err = xenbus_printf(xbt, dev->nodename, "multi-queue-num-queues", "%u",
1845                                     info->nr_rings);
1846                 if (err) {
1847                         message = "writing multi-queue-num-queues";
1848                         goto abort_transaction;
1849                 }
1850
1851                 pathsize = strlen(dev->nodename) + QUEUE_NAME_LEN;
1852                 path = kmalloc(pathsize, GFP_KERNEL);
1853                 if (!path) {
1854                         err = -ENOMEM;
1855                         message = "ENOMEM while writing ring references";
1856                         goto abort_transaction;
1857                 }
1858
1859                 for_each_rinfo(info, rinfo, i) {
1860                         memset(path, 0, pathsize);
1861                         snprintf(path, pathsize, "%s/queue-%u", dev->nodename, i);
1862                         err = write_per_ring_nodes(xbt, rinfo, path);
1863                         if (err) {
1864                                 kfree(path);
1865                                 goto destroy_blkring;
1866                         }
1867                 }
1868                 kfree(path);
1869         }
1870         err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
1871                             XEN_IO_PROTO_ABI_NATIVE);
1872         if (err) {
1873                 message = "writing protocol";
1874                 goto abort_transaction;
1875         }
1876         err = xenbus_printf(xbt, dev->nodename, "feature-persistent", "%u",
1877                         info->feature_persistent);
1878         if (err)
1879                 dev_warn(&dev->dev,
1880                          "writing persistent grants feature to xenbus");
1881
1882         err = xenbus_transaction_end(xbt, 0);
1883         if (err) {
1884                 if (err == -EAGAIN)
1885                         goto again;
1886                 xenbus_dev_fatal(dev, err, "completing transaction");
1887                 goto destroy_blkring;
1888         }
1889
1890         for_each_rinfo(info, rinfo, i) {
1891                 unsigned int j;
1892
1893                 for (j = 0; j < BLK_RING_SIZE(info); j++)
1894                         rinfo->shadow[j].req.u.rw.id = j + 1;
1895                 rinfo->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1896         }
1897         xenbus_switch_state(dev, XenbusStateInitialised);
1898
1899         return 0;
1900
1901  abort_transaction:
1902         xenbus_transaction_end(xbt, 1);
1903         if (message)
1904                 xenbus_dev_fatal(dev, err, "%s", message);
1905  destroy_blkring:
1906         blkif_free(info, 0);
1907         return err;
1908 }
1909
1910 static int negotiate_mq(struct blkfront_info *info)
1911 {
1912         unsigned int backend_max_queues;
1913         unsigned int i;
1914         struct blkfront_ring_info *rinfo;
1915
1916         BUG_ON(info->nr_rings);
1917
1918         /* Check if backend supports multiple queues. */
1919         backend_max_queues = xenbus_read_unsigned(info->xbdev->otherend,
1920                                                   "multi-queue-max-queues", 1);
1921         info->nr_rings = min(backend_max_queues, xen_blkif_max_queues);
1922         /* We need at least one ring. */
1923         if (!info->nr_rings)
1924                 info->nr_rings = 1;
1925
1926         info->rinfo_size = struct_size(info->rinfo, shadow,
1927                                        BLK_RING_SIZE(info));
1928         info->rinfo = kvcalloc(info->nr_rings, info->rinfo_size, GFP_KERNEL);
1929         if (!info->rinfo) {
1930                 xenbus_dev_fatal(info->xbdev, -ENOMEM, "allocating ring_info structure");
1931                 info->nr_rings = 0;
1932                 return -ENOMEM;
1933         }
1934
1935         for_each_rinfo(info, rinfo, i) {
1936                 INIT_LIST_HEAD(&rinfo->indirect_pages);
1937                 INIT_LIST_HEAD(&rinfo->grants);
1938                 rinfo->dev_info = info;
1939                 INIT_WORK(&rinfo->work, blkif_restart_queue);
1940                 spin_lock_init(&rinfo->ring_lock);
1941         }
1942         return 0;
1943 }
1944
1945 /* Enable the persistent grants feature. */
1946 static bool feature_persistent = true;
1947 module_param(feature_persistent, bool, 0644);
1948 MODULE_PARM_DESC(feature_persistent,
1949                 "Enables the persistent grants feature");
1950
1951 /*
1952  * Entry point to this code when a new device is created.  Allocate the basic
1953  * structures and the ring buffer for communication with the backend, and
1954  * inform the backend of the appropriate details for those.  Switch to
1955  * Initialised state.
1956  */
1957 static int blkfront_probe(struct xenbus_device *dev,
1958                           const struct xenbus_device_id *id)
1959 {
1960         int err, vdevice;
1961         struct blkfront_info *info;
1962
1963         /* FIXME: Use dynamic device id if this is not set. */
1964         err = xenbus_scanf(XBT_NIL, dev->nodename,
1965                            "virtual-device", "%i", &vdevice);
1966         if (err != 1) {
1967                 /* go looking in the extended area instead */
1968                 err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
1969                                    "%i", &vdevice);
1970                 if (err != 1) {
1971                         xenbus_dev_fatal(dev, err, "reading virtual-device");
1972                         return err;
1973                 }
1974         }
1975
1976         if (xen_hvm_domain()) {
1977                 char *type;
1978                 int len;
1979                 /* no unplug has been done: do not hook devices != xen vbds */
1980                 if (xen_has_pv_and_legacy_disk_devices()) {
1981                         int major;
1982
1983                         if (!VDEV_IS_EXTENDED(vdevice))
1984                                 major = BLKIF_MAJOR(vdevice);
1985                         else
1986                                 major = XENVBD_MAJOR;
1987
1988                         if (major != XENVBD_MAJOR) {
1989                                 printk(KERN_INFO
1990                                                 "%s: HVM does not support vbd %d as xen block device\n",
1991                                                 __func__, vdevice);
1992                                 return -ENODEV;
1993                         }
1994                 }
1995                 /* do not create a PV cdrom device if we are an HVM guest */
1996                 type = xenbus_read(XBT_NIL, dev->nodename, "device-type", &len);
1997                 if (IS_ERR(type))
1998                         return -ENODEV;
1999                 if (strncmp(type, "cdrom", 5) == 0) {
2000                         kfree(type);
2001                         return -ENODEV;
2002                 }
2003                 kfree(type);
2004         }
2005         info = kzalloc(sizeof(*info), GFP_KERNEL);
2006         if (!info) {
2007                 xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
2008                 return -ENOMEM;
2009         }
2010
2011         info->xbdev = dev;
2012
2013         mutex_init(&info->mutex);
2014         info->vdevice = vdevice;
2015         info->connected = BLKIF_STATE_DISCONNECTED;
2016
2017         info->feature_persistent = feature_persistent;
2018
2019         /* Front end dir is a number, which is used as the id. */
2020         info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
2021         dev_set_drvdata(&dev->dev, info);
2022
2023         mutex_lock(&blkfront_mutex);
2024         list_add(&info->info_list, &info_list);
2025         mutex_unlock(&blkfront_mutex);
2026
2027         return 0;
2028 }
2029
2030 static int blkif_recover(struct blkfront_info *info)
2031 {
2032         unsigned int r_index;
2033         struct request *req, *n;
2034         int rc;
2035         struct bio *bio;
2036         unsigned int segs;
2037         struct blkfront_ring_info *rinfo;
2038
2039         blkfront_gather_backend_features(info);
2040         /* Reset limits changed by blk_mq_update_nr_hw_queues(). */
2041         blkif_set_queue_limits(info);
2042         segs = info->max_indirect_segments ? : BLKIF_MAX_SEGMENTS_PER_REQUEST;
2043         blk_queue_max_segments(info->rq, segs / GRANTS_PER_PSEG);
2044
2045         for_each_rinfo(info, rinfo, r_index) {
2046                 rc = blkfront_setup_indirect(rinfo);
2047                 if (rc)
2048                         return rc;
2049         }
2050         xenbus_switch_state(info->xbdev, XenbusStateConnected);
2051
2052         /* Now safe for us to use the shared ring */
2053         info->connected = BLKIF_STATE_CONNECTED;
2054
2055         for_each_rinfo(info, rinfo, r_index) {
2056                 /* Kick any other new requests queued since we resumed */
2057                 kick_pending_request_queues(rinfo);
2058         }
2059
2060         list_for_each_entry_safe(req, n, &info->requests, queuelist) {
2061                 /* Requeue pending requests (flush or discard) */
2062                 list_del_init(&req->queuelist);
2063                 BUG_ON(req->nr_phys_segments > segs);
2064                 blk_mq_requeue_request(req, false);
2065         }
2066         blk_mq_start_stopped_hw_queues(info->rq, true);
2067         blk_mq_kick_requeue_list(info->rq);
2068
2069         while ((bio = bio_list_pop(&info->bio_list)) != NULL) {
2070                 /* Traverse the list of pending bios and re-queue them */
2071                 submit_bio(bio);
2072         }
2073
2074         return 0;
2075 }
2076
2077 /*
2078  * We are reconnecting to the backend, due to a suspend/resume, or a backend
2079  * driver restart.  We tear down our blkif structure and recreate it, but
2080  * leave the device-layer structures intact so that this is transparent to the
2081  * rest of the kernel.
2082  */
2083 static int blkfront_resume(struct xenbus_device *dev)
2084 {
2085         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2086         int err = 0;
2087         unsigned int i, j;
2088         struct blkfront_ring_info *rinfo;
2089
2090         dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
2091
2092         bio_list_init(&info->bio_list);
2093         INIT_LIST_HEAD(&info->requests);
2094         for_each_rinfo(info, rinfo, i) {
2095                 struct bio_list merge_bio;
2096                 struct blk_shadow *shadow = rinfo->shadow;
2097
2098                 for (j = 0; j < BLK_RING_SIZE(info); j++) {
2099                         /* Not in use? */
2100                         if (!shadow[j].request)
2101                                 continue;
2102
2103                         /*
2104                          * Get the bios in the request so we can re-queue them.
2105                          */
2106                         if (req_op(shadow[j].request) == REQ_OP_FLUSH ||
2107                             req_op(shadow[j].request) == REQ_OP_DISCARD ||
2108                             req_op(shadow[j].request) == REQ_OP_SECURE_ERASE ||
2109                             shadow[j].request->cmd_flags & REQ_FUA) {
2110                                 /*
2111                                  * Flush operations don't contain bios, so
2112                                  * we need to requeue the whole request
2113                                  *
2114                                  * XXX: but this doesn't make any sense for a
2115                                  * write with the FUA flag set..
2116                                  */
2117                                 list_add(&shadow[j].request->queuelist, &info->requests);
2118                                 continue;
2119                         }
2120                         merge_bio.head = shadow[j].request->bio;
2121                         merge_bio.tail = shadow[j].request->biotail;
2122                         bio_list_merge(&info->bio_list, &merge_bio);
2123                         shadow[j].request->bio = NULL;
2124                         blk_mq_end_request(shadow[j].request, BLK_STS_OK);
2125                 }
2126         }
2127
2128         blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
2129
2130         err = talk_to_blkback(dev, info);
2131         if (!err)
2132                 blk_mq_update_nr_hw_queues(&info->tag_set, info->nr_rings);
2133
2134         /*
2135          * We have to wait for the backend to switch to
2136          * connected state, since we want to read which
2137          * features it supports.
2138          */
2139
2140         return err;
2141 }
2142
2143 static void blkfront_closing(struct blkfront_info *info)
2144 {
2145         struct xenbus_device *xbdev = info->xbdev;
2146         struct blkfront_ring_info *rinfo;
2147         unsigned int i;
2148
2149         if (xbdev->state == XenbusStateClosing)
2150                 return;
2151
2152         /* No more blkif_request(). */
2153         if (info->rq && info->gd) {
2154                 blk_mq_stop_hw_queues(info->rq);
2155                 blk_mark_disk_dead(info->gd);
2156                 set_capacity(info->gd, 0);
2157         }
2158
2159         for_each_rinfo(info, rinfo, i) {
2160                 /* No more gnttab callback work. */
2161                 gnttab_cancel_free_callback(&rinfo->callback);
2162
2163                 /* Flush gnttab callback work. Must be done with no locks held. */
2164                 flush_work(&rinfo->work);
2165         }
2166
2167         xenbus_frontend_closed(xbdev);
2168 }
2169
2170 static void blkfront_setup_discard(struct blkfront_info *info)
2171 {
2172         info->feature_discard = 1;
2173         info->discard_granularity = xenbus_read_unsigned(info->xbdev->otherend,
2174                                                          "discard-granularity",
2175                                                          0);
2176         info->discard_alignment = xenbus_read_unsigned(info->xbdev->otherend,
2177                                                        "discard-alignment", 0);
2178         info->feature_secdiscard =
2179                 !!xenbus_read_unsigned(info->xbdev->otherend, "discard-secure",
2180                                        0);
2181 }
2182
2183 static int blkfront_setup_indirect(struct blkfront_ring_info *rinfo)
2184 {
2185         unsigned int psegs, grants, memflags;
2186         int err, i;
2187         struct blkfront_info *info = rinfo->dev_info;
2188
2189         memflags = memalloc_noio_save();
2190
2191         if (info->max_indirect_segments == 0) {
2192                 if (!HAS_EXTRA_REQ)
2193                         grants = BLKIF_MAX_SEGMENTS_PER_REQUEST;
2194                 else {
2195                         /*
2196                          * When an extra req is required, the maximum
2197                          * grants supported is related to the size of the
2198                          * Linux block segment.
2199                          */
2200                         grants = GRANTS_PER_PSEG;
2201                 }
2202         }
2203         else
2204                 grants = info->max_indirect_segments;
2205         psegs = DIV_ROUND_UP(grants, GRANTS_PER_PSEG);
2206
2207         err = fill_grant_buffer(rinfo,
2208                                 (grants + INDIRECT_GREFS(grants)) * BLK_RING_SIZE(info));
2209         if (err)
2210                 goto out_of_memory;
2211
2212         if (!info->bounce && info->max_indirect_segments) {
2213                 /*
2214                  * We are using indirect descriptors but don't have a bounce
2215                  * buffer, we need to allocate a set of pages that can be
2216                  * used for mapping indirect grefs
2217                  */
2218                 int num = INDIRECT_GREFS(grants) * BLK_RING_SIZE(info);
2219
2220                 BUG_ON(!list_empty(&rinfo->indirect_pages));
2221                 for (i = 0; i < num; i++) {
2222                         struct page *indirect_page = alloc_page(GFP_KERNEL |
2223                                                                 __GFP_ZERO);
2224                         if (!indirect_page)
2225                                 goto out_of_memory;
2226                         list_add(&indirect_page->lru, &rinfo->indirect_pages);
2227                 }
2228         }
2229
2230         for (i = 0; i < BLK_RING_SIZE(info); i++) {
2231                 rinfo->shadow[i].grants_used =
2232                         kvcalloc(grants,
2233                                  sizeof(rinfo->shadow[i].grants_used[0]),
2234                                  GFP_KERNEL);
2235                 rinfo->shadow[i].sg = kvcalloc(psegs,
2236                                                sizeof(rinfo->shadow[i].sg[0]),
2237                                                GFP_KERNEL);
2238                 if (info->max_indirect_segments)
2239                         rinfo->shadow[i].indirect_grants =
2240                                 kvcalloc(INDIRECT_GREFS(grants),
2241                                          sizeof(rinfo->shadow[i].indirect_grants[0]),
2242                                          GFP_KERNEL);
2243                 if ((rinfo->shadow[i].grants_used == NULL) ||
2244                         (rinfo->shadow[i].sg == NULL) ||
2245                      (info->max_indirect_segments &&
2246                      (rinfo->shadow[i].indirect_grants == NULL)))
2247                         goto out_of_memory;
2248                 sg_init_table(rinfo->shadow[i].sg, psegs);
2249         }
2250
2251         memalloc_noio_restore(memflags);
2252
2253         return 0;
2254
2255 out_of_memory:
2256         for (i = 0; i < BLK_RING_SIZE(info); i++) {
2257                 kvfree(rinfo->shadow[i].grants_used);
2258                 rinfo->shadow[i].grants_used = NULL;
2259                 kvfree(rinfo->shadow[i].sg);
2260                 rinfo->shadow[i].sg = NULL;
2261                 kvfree(rinfo->shadow[i].indirect_grants);
2262                 rinfo->shadow[i].indirect_grants = NULL;
2263         }
2264         if (!list_empty(&rinfo->indirect_pages)) {
2265                 struct page *indirect_page, *n;
2266                 list_for_each_entry_safe(indirect_page, n, &rinfo->indirect_pages, lru) {
2267                         list_del(&indirect_page->lru);
2268                         __free_page(indirect_page);
2269                 }
2270         }
2271
2272         memalloc_noio_restore(memflags);
2273
2274         return -ENOMEM;
2275 }
2276
2277 /*
2278  * Gather all backend feature-*
2279  */
2280 static void blkfront_gather_backend_features(struct blkfront_info *info)
2281 {
2282         unsigned int indirect_segments;
2283
2284         info->feature_flush = 0;
2285         info->feature_fua = 0;
2286
2287         /*
2288          * If there's no "feature-barrier" defined, then it means
2289          * we're dealing with a very old backend which writes
2290          * synchronously; nothing to do.
2291          *
2292          * If there are barriers, then we use flush.
2293          */
2294         if (xenbus_read_unsigned(info->xbdev->otherend, "feature-barrier", 0)) {
2295                 info->feature_flush = 1;
2296                 info->feature_fua = 1;
2297         }
2298
2299         /*
2300          * And if there is "feature-flush-cache" use that above
2301          * barriers.
2302          */
2303         if (xenbus_read_unsigned(info->xbdev->otherend, "feature-flush-cache",
2304                                  0)) {
2305                 info->feature_flush = 1;
2306                 info->feature_fua = 0;
2307         }
2308
2309         if (xenbus_read_unsigned(info->xbdev->otherend, "feature-discard", 0))
2310                 blkfront_setup_discard(info);
2311
2312         if (info->feature_persistent)
2313                 info->feature_persistent =
2314                         !!xenbus_read_unsigned(info->xbdev->otherend,
2315                                                "feature-persistent", 0);
2316         if (info->feature_persistent)
2317                 info->bounce = true;
2318
2319         indirect_segments = xenbus_read_unsigned(info->xbdev->otherend,
2320                                         "feature-max-indirect-segments", 0);
2321         if (indirect_segments > xen_blkif_max_segments)
2322                 indirect_segments = xen_blkif_max_segments;
2323         if (indirect_segments <= BLKIF_MAX_SEGMENTS_PER_REQUEST)
2324                 indirect_segments = 0;
2325         info->max_indirect_segments = indirect_segments;
2326
2327         if (info->feature_persistent) {
2328                 mutex_lock(&blkfront_mutex);
2329                 schedule_delayed_work(&blkfront_work, HZ * 10);
2330                 mutex_unlock(&blkfront_mutex);
2331         }
2332 }
2333
2334 /*
2335  * Invoked when the backend is finally 'ready' (and has told produced
2336  * the details about the physical device - #sectors, size, etc).
2337  */
2338 static void blkfront_connect(struct blkfront_info *info)
2339 {
2340         unsigned long long sectors;
2341         unsigned long sector_size;
2342         unsigned int physical_sector_size;
2343         unsigned int binfo;
2344         int err, i;
2345         struct blkfront_ring_info *rinfo;
2346
2347         switch (info->connected) {
2348         case BLKIF_STATE_CONNECTED:
2349                 /*
2350                  * Potentially, the back-end may be signalling
2351                  * a capacity change; update the capacity.
2352                  */
2353                 err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
2354                                    "sectors", "%Lu", &sectors);
2355                 if (XENBUS_EXIST_ERR(err))
2356                         return;
2357                 printk(KERN_INFO "Setting capacity to %Lu\n",
2358                        sectors);
2359                 set_capacity_and_notify(info->gd, sectors);
2360
2361                 return;
2362         case BLKIF_STATE_SUSPENDED:
2363                 /*
2364                  * If we are recovering from suspension, we need to wait
2365                  * for the backend to announce it's features before
2366                  * reconnecting, at least we need to know if the backend
2367                  * supports indirect descriptors, and how many.
2368                  */
2369                 blkif_recover(info);
2370                 return;
2371
2372         default:
2373                 break;
2374         }
2375
2376         dev_dbg(&info->xbdev->dev, "%s:%s.\n",
2377                 __func__, info->xbdev->otherend);
2378
2379         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
2380                             "sectors", "%llu", &sectors,
2381                             "info", "%u", &binfo,
2382                             "sector-size", "%lu", &sector_size,
2383                             NULL);
2384         if (err) {
2385                 xenbus_dev_fatal(info->xbdev, err,
2386                                  "reading backend fields at %s",
2387                                  info->xbdev->otherend);
2388                 return;
2389         }
2390
2391         /*
2392          * physical-sector-size is a newer field, so old backends may not
2393          * provide this. Assume physical sector size to be the same as
2394          * sector_size in that case.
2395          */
2396         physical_sector_size = xenbus_read_unsigned(info->xbdev->otherend,
2397                                                     "physical-sector-size",
2398                                                     sector_size);
2399         blkfront_gather_backend_features(info);
2400         for_each_rinfo(info, rinfo, i) {
2401                 err = blkfront_setup_indirect(rinfo);
2402                 if (err) {
2403                         xenbus_dev_fatal(info->xbdev, err, "setup_indirect at %s",
2404                                          info->xbdev->otherend);
2405                         blkif_free(info, 0);
2406                         break;
2407                 }
2408         }
2409
2410         err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size,
2411                                   physical_sector_size);
2412         if (err) {
2413                 xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
2414                                  info->xbdev->otherend);
2415                 goto fail;
2416         }
2417
2418         xenbus_switch_state(info->xbdev, XenbusStateConnected);
2419
2420         /* Kick pending requests. */
2421         info->connected = BLKIF_STATE_CONNECTED;
2422         for_each_rinfo(info, rinfo, i)
2423                 kick_pending_request_queues(rinfo);
2424
2425         device_add_disk(&info->xbdev->dev, info->gd, NULL);
2426
2427         info->is_ready = 1;
2428         return;
2429
2430 fail:
2431         blkif_free(info, 0);
2432         return;
2433 }
2434
2435 /*
2436  * Callback received when the backend's state changes.
2437  */
2438 static void blkback_changed(struct xenbus_device *dev,
2439                             enum xenbus_state backend_state)
2440 {
2441         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2442
2443         dev_dbg(&dev->dev, "blkfront:blkback_changed to state %d.\n", backend_state);
2444
2445         switch (backend_state) {
2446         case XenbusStateInitWait:
2447                 if (dev->state != XenbusStateInitialising)
2448                         break;
2449                 if (talk_to_blkback(dev, info))
2450                         break;
2451                 break;
2452         case XenbusStateInitialising:
2453         case XenbusStateInitialised:
2454         case XenbusStateReconfiguring:
2455         case XenbusStateReconfigured:
2456         case XenbusStateUnknown:
2457                 break;
2458
2459         case XenbusStateConnected:
2460                 /*
2461                  * talk_to_blkback sets state to XenbusStateInitialised
2462                  * and blkfront_connect sets it to XenbusStateConnected
2463                  * (if connection went OK).
2464                  *
2465                  * If the backend (or toolstack) decides to poke at backend
2466                  * state (and re-trigger the watch by setting the state repeatedly
2467                  * to XenbusStateConnected (4)) we need to deal with this.
2468                  * This is allowed as this is used to communicate to the guest
2469                  * that the size of disk has changed!
2470                  */
2471                 if ((dev->state != XenbusStateInitialised) &&
2472                     (dev->state != XenbusStateConnected)) {
2473                         if (talk_to_blkback(dev, info))
2474                                 break;
2475                 }
2476
2477                 blkfront_connect(info);
2478                 break;
2479
2480         case XenbusStateClosed:
2481                 if (dev->state == XenbusStateClosed)
2482                         break;
2483                 fallthrough;
2484         case XenbusStateClosing:
2485                 blkfront_closing(info);
2486                 break;
2487         }
2488 }
2489
2490 static int blkfront_remove(struct xenbus_device *xbdev)
2491 {
2492         struct blkfront_info *info = dev_get_drvdata(&xbdev->dev);
2493
2494         dev_dbg(&xbdev->dev, "%s removed", xbdev->nodename);
2495
2496         if (info->gd)
2497                 del_gendisk(info->gd);
2498
2499         mutex_lock(&blkfront_mutex);
2500         list_del(&info->info_list);
2501         mutex_unlock(&blkfront_mutex);
2502
2503         blkif_free(info, 0);
2504         if (info->gd) {
2505                 xlbd_release_minors(info->gd->first_minor, info->gd->minors);
2506                 blk_cleanup_disk(info->gd);
2507                 blk_mq_free_tag_set(&info->tag_set);
2508         }
2509
2510         kfree(info);
2511         return 0;
2512 }
2513
2514 static int blkfront_is_ready(struct xenbus_device *dev)
2515 {
2516         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2517
2518         return info->is_ready && info->xbdev;
2519 }
2520
2521 static const struct block_device_operations xlvbd_block_fops =
2522 {
2523         .owner = THIS_MODULE,
2524         .getgeo = blkif_getgeo,
2525         .ioctl = blkif_ioctl,
2526         .compat_ioctl = blkdev_compat_ptr_ioctl,
2527 };
2528
2529
2530 static const struct xenbus_device_id blkfront_ids[] = {
2531         { "vbd" },
2532         { "" }
2533 };
2534
2535 static struct xenbus_driver blkfront_driver = {
2536         .ids  = blkfront_ids,
2537         .probe = blkfront_probe,
2538         .remove = blkfront_remove,
2539         .resume = blkfront_resume,
2540         .otherend_changed = blkback_changed,
2541         .is_ready = blkfront_is_ready,
2542 };
2543
2544 static void purge_persistent_grants(struct blkfront_info *info)
2545 {
2546         unsigned int i;
2547         unsigned long flags;
2548         struct blkfront_ring_info *rinfo;
2549
2550         for_each_rinfo(info, rinfo, i) {
2551                 struct grant *gnt_list_entry, *tmp;
2552
2553                 spin_lock_irqsave(&rinfo->ring_lock, flags);
2554
2555                 if (rinfo->persistent_gnts_c == 0) {
2556                         spin_unlock_irqrestore(&rinfo->ring_lock, flags);
2557                         continue;
2558                 }
2559
2560                 list_for_each_entry_safe(gnt_list_entry, tmp, &rinfo->grants,
2561                                          node) {
2562                         if (gnt_list_entry->gref == GRANT_INVALID_REF ||
2563                             !gnttab_try_end_foreign_access(gnt_list_entry->gref))
2564                                 continue;
2565
2566                         list_del(&gnt_list_entry->node);
2567                         rinfo->persistent_gnts_c--;
2568                         gnt_list_entry->gref = GRANT_INVALID_REF;
2569                         list_add_tail(&gnt_list_entry->node, &rinfo->grants);
2570                 }
2571
2572                 spin_unlock_irqrestore(&rinfo->ring_lock, flags);
2573         }
2574 }
2575
2576 static void blkfront_delay_work(struct work_struct *work)
2577 {
2578         struct blkfront_info *info;
2579         bool need_schedule_work = false;
2580
2581         /*
2582          * Note that when using bounce buffers but not persistent grants
2583          * there's no need to run blkfront_delay_work because grants are
2584          * revoked in blkif_completion or else an error is reported and the
2585          * connection is closed.
2586          */
2587
2588         mutex_lock(&blkfront_mutex);
2589
2590         list_for_each_entry(info, &info_list, info_list) {
2591                 if (info->feature_persistent) {
2592                         need_schedule_work = true;
2593                         mutex_lock(&info->mutex);
2594                         purge_persistent_grants(info);
2595                         mutex_unlock(&info->mutex);
2596                 }
2597         }
2598
2599         if (need_schedule_work)
2600                 schedule_delayed_work(&blkfront_work, HZ * 10);
2601
2602         mutex_unlock(&blkfront_mutex);
2603 }
2604
2605 static int __init xlblk_init(void)
2606 {
2607         int ret;
2608         int nr_cpus = num_online_cpus();
2609
2610         if (!xen_domain())
2611                 return -ENODEV;
2612
2613         if (!xen_has_pv_disk_devices())
2614                 return -ENODEV;
2615
2616         if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
2617                 pr_warn("xen_blk: can't get major %d with name %s\n",
2618                         XENVBD_MAJOR, DEV_NAME);
2619                 return -ENODEV;
2620         }
2621
2622         if (xen_blkif_max_segments < BLKIF_MAX_SEGMENTS_PER_REQUEST)
2623                 xen_blkif_max_segments = BLKIF_MAX_SEGMENTS_PER_REQUEST;
2624
2625         if (xen_blkif_max_ring_order > XENBUS_MAX_RING_GRANT_ORDER) {
2626                 pr_info("Invalid max_ring_order (%d), will use default max: %d.\n",
2627                         xen_blkif_max_ring_order, XENBUS_MAX_RING_GRANT_ORDER);
2628                 xen_blkif_max_ring_order = XENBUS_MAX_RING_GRANT_ORDER;
2629         }
2630
2631         if (xen_blkif_max_queues > nr_cpus) {
2632                 pr_info("Invalid max_queues (%d), will use default max: %d.\n",
2633                         xen_blkif_max_queues, nr_cpus);
2634                 xen_blkif_max_queues = nr_cpus;
2635         }
2636
2637         INIT_DELAYED_WORK(&blkfront_work, blkfront_delay_work);
2638
2639         ret = xenbus_register_frontend(&blkfront_driver);
2640         if (ret) {
2641                 unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2642                 return ret;
2643         }
2644
2645         return 0;
2646 }
2647 module_init(xlblk_init);
2648
2649
2650 static void __exit xlblk_exit(void)
2651 {
2652         cancel_delayed_work_sync(&blkfront_work);
2653
2654         xenbus_unregister_driver(&blkfront_driver);
2655         unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2656         kfree(minors);
2657 }
2658 module_exit(xlblk_exit);
2659
2660 MODULE_DESCRIPTION("Xen virtual block device frontend");
2661 MODULE_LICENSE("GPL");
2662 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
2663 MODULE_ALIAS("xen:vbd");
2664 MODULE_ALIAS("xenblk");