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