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