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