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