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