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