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