xref: /linux/drivers/block/xen-blkfront.c (revision c7e1e3ccfbd153c890240a391f258efaedfa94d0)
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/hdreg.h>
41 #include <linux/cdrom.h>
42 #include <linux/module.h>
43 #include <linux/slab.h>
44 #include <linux/mutex.h>
45 #include <linux/scatterlist.h>
46 #include <linux/bitmap.h>
47 #include <linux/list.h>
48 
49 #include <xen/xen.h>
50 #include <xen/xenbus.h>
51 #include <xen/grant_table.h>
52 #include <xen/events.h>
53 #include <xen/page.h>
54 #include <xen/platform_pci.h>
55 
56 #include <xen/interface/grant_table.h>
57 #include <xen/interface/io/blkif.h>
58 #include <xen/interface/io/protocols.h>
59 
60 #include <asm/xen/hypervisor.h>
61 
62 enum blkif_state {
63 	BLKIF_STATE_DISCONNECTED,
64 	BLKIF_STATE_CONNECTED,
65 	BLKIF_STATE_SUSPENDED,
66 };
67 
68 struct grant {
69 	grant_ref_t gref;
70 	unsigned long pfn;
71 	struct list_head node;
72 };
73 
74 struct blk_shadow {
75 	struct blkif_request req;
76 	struct request *request;
77 	struct grant **grants_used;
78 	struct grant **indirect_grants;
79 	struct scatterlist *sg;
80 };
81 
82 struct split_bio {
83 	struct bio *bio;
84 	atomic_t pending;
85 };
86 
87 static DEFINE_MUTEX(blkfront_mutex);
88 static const struct block_device_operations xlvbd_block_fops;
89 
90 /*
91  * Maximum number of segments in indirect requests, the actual value used by
92  * the frontend driver is the minimum of this value and the value provided
93  * by the backend driver.
94  */
95 
96 static unsigned int xen_blkif_max_segments = 32;
97 module_param_named(max, xen_blkif_max_segments, int, S_IRUGO);
98 MODULE_PARM_DESC(max, "Maximum amount of segments in indirect requests (default is 32)");
99 
100 /*
101  * Maximum order of pages to be used for the shared ring between front and
102  * backend, 4KB page granularity is used.
103  */
104 static unsigned int xen_blkif_max_ring_order;
105 module_param_named(max_ring_page_order, xen_blkif_max_ring_order, int, S_IRUGO);
106 MODULE_PARM_DESC(max_ring_page_order, "Maximum order of pages to be used for the shared ring");
107 
108 #define BLK_RING_SIZE(info) __CONST_RING_SIZE(blkif, PAGE_SIZE * (info)->nr_ring_pages)
109 #define BLK_MAX_RING_SIZE __CONST_RING_SIZE(blkif, PAGE_SIZE * XENBUS_MAX_RING_PAGES)
110 /*
111  * ring-ref%i i=(-1UL) would take 11 characters + 'ring-ref' is 8, so 19
112  * characters are enough. Define to 20 to keep consist with backend.
113  */
114 #define RINGREF_NAME_LEN (20)
115 
116 /*
117  * We have one of these per vbd, whether ide, scsi or 'other'.  They
118  * hang in private_data off the gendisk structure. We may end up
119  * putting all kinds of interesting stuff here :-)
120  */
121 struct blkfront_info
122 {
123 	spinlock_t io_lock;
124 	struct mutex mutex;
125 	struct xenbus_device *xbdev;
126 	struct gendisk *gd;
127 	int vdevice;
128 	blkif_vdev_t handle;
129 	enum blkif_state connected;
130 	int ring_ref[XENBUS_MAX_RING_PAGES];
131 	unsigned int nr_ring_pages;
132 	struct blkif_front_ring ring;
133 	unsigned int evtchn, irq;
134 	struct request_queue *rq;
135 	struct work_struct work;
136 	struct gnttab_free_callback callback;
137 	struct blk_shadow shadow[BLK_MAX_RING_SIZE];
138 	struct list_head grants;
139 	struct list_head indirect_pages;
140 	unsigned int persistent_gnts_c;
141 	unsigned long shadow_free;
142 	unsigned int feature_flush;
143 	unsigned int feature_discard:1;
144 	unsigned int feature_secdiscard:1;
145 	unsigned int discard_granularity;
146 	unsigned int discard_alignment;
147 	unsigned int feature_persistent:1;
148 	unsigned int max_indirect_segments;
149 	int is_ready;
150 };
151 
152 static unsigned int nr_minors;
153 static unsigned long *minors;
154 static DEFINE_SPINLOCK(minor_lock);
155 
156 #define GRANT_INVALID_REF	0
157 
158 #define PARTS_PER_DISK		16
159 #define PARTS_PER_EXT_DISK      256
160 
161 #define BLKIF_MAJOR(dev) ((dev)>>8)
162 #define BLKIF_MINOR(dev) ((dev) & 0xff)
163 
164 #define EXT_SHIFT 28
165 #define EXTENDED (1<<EXT_SHIFT)
166 #define VDEV_IS_EXTENDED(dev) ((dev)&(EXTENDED))
167 #define BLKIF_MINOR_EXT(dev) ((dev)&(~EXTENDED))
168 #define EMULATED_HD_DISK_MINOR_OFFSET (0)
169 #define EMULATED_HD_DISK_NAME_OFFSET (EMULATED_HD_DISK_MINOR_OFFSET / 256)
170 #define EMULATED_SD_DISK_MINOR_OFFSET (0)
171 #define EMULATED_SD_DISK_NAME_OFFSET (EMULATED_SD_DISK_MINOR_OFFSET / 256)
172 
173 #define DEV_NAME	"xvd"	/* name in /dev */
174 
175 #define SEGS_PER_INDIRECT_FRAME \
176 	(PAGE_SIZE/sizeof(struct blkif_request_segment))
177 #define INDIRECT_GREFS(_segs) \
178 	((_segs + SEGS_PER_INDIRECT_FRAME - 1)/SEGS_PER_INDIRECT_FRAME)
179 
180 static int blkfront_setup_indirect(struct blkfront_info *info);
181 static int blkfront_gather_backend_features(struct blkfront_info *info);
182 
183 static int get_id_from_freelist(struct blkfront_info *info)
184 {
185 	unsigned long free = info->shadow_free;
186 	BUG_ON(free >= BLK_RING_SIZE(info));
187 	info->shadow_free = info->shadow[free].req.u.rw.id;
188 	info->shadow[free].req.u.rw.id = 0x0fffffee; /* debug */
189 	return free;
190 }
191 
192 static int add_id_to_freelist(struct blkfront_info *info,
193 			       unsigned long id)
194 {
195 	if (info->shadow[id].req.u.rw.id != id)
196 		return -EINVAL;
197 	if (info->shadow[id].request == NULL)
198 		return -EINVAL;
199 	info->shadow[id].req.u.rw.id  = info->shadow_free;
200 	info->shadow[id].request = NULL;
201 	info->shadow_free = id;
202 	return 0;
203 }
204 
205 static int fill_grant_buffer(struct blkfront_info *info, int num)
206 {
207 	struct page *granted_page;
208 	struct grant *gnt_list_entry, *n;
209 	int i = 0;
210 
211 	while(i < num) {
212 		gnt_list_entry = kzalloc(sizeof(struct grant), GFP_NOIO);
213 		if (!gnt_list_entry)
214 			goto out_of_memory;
215 
216 		if (info->feature_persistent) {
217 			granted_page = alloc_page(GFP_NOIO);
218 			if (!granted_page) {
219 				kfree(gnt_list_entry);
220 				goto out_of_memory;
221 			}
222 			gnt_list_entry->pfn = page_to_pfn(granted_page);
223 		}
224 
225 		gnt_list_entry->gref = GRANT_INVALID_REF;
226 		list_add(&gnt_list_entry->node, &info->grants);
227 		i++;
228 	}
229 
230 	return 0;
231 
232 out_of_memory:
233 	list_for_each_entry_safe(gnt_list_entry, n,
234 	                         &info->grants, node) {
235 		list_del(&gnt_list_entry->node);
236 		if (info->feature_persistent)
237 			__free_page(pfn_to_page(gnt_list_entry->pfn));
238 		kfree(gnt_list_entry);
239 		i--;
240 	}
241 	BUG_ON(i != 0);
242 	return -ENOMEM;
243 }
244 
245 static struct grant *get_grant(grant_ref_t *gref_head,
246                                unsigned long pfn,
247                                struct blkfront_info *info)
248 {
249 	struct grant *gnt_list_entry;
250 	unsigned long buffer_mfn;
251 
252 	BUG_ON(list_empty(&info->grants));
253 	gnt_list_entry = list_first_entry(&info->grants, struct grant,
254 	                                  node);
255 	list_del(&gnt_list_entry->node);
256 
257 	if (gnt_list_entry->gref != GRANT_INVALID_REF) {
258 		info->persistent_gnts_c--;
259 		return gnt_list_entry;
260 	}
261 
262 	/* Assign a gref to this page */
263 	gnt_list_entry->gref = gnttab_claim_grant_reference(gref_head);
264 	BUG_ON(gnt_list_entry->gref == -ENOSPC);
265 	if (!info->feature_persistent) {
266 		BUG_ON(!pfn);
267 		gnt_list_entry->pfn = pfn;
268 	}
269 	buffer_mfn = pfn_to_mfn(gnt_list_entry->pfn);
270 	gnttab_grant_foreign_access_ref(gnt_list_entry->gref,
271 	                                info->xbdev->otherend_id,
272 	                                buffer_mfn, 0);
273 	return gnt_list_entry;
274 }
275 
276 static const char *op_name(int op)
277 {
278 	static const char *const names[] = {
279 		[BLKIF_OP_READ] = "read",
280 		[BLKIF_OP_WRITE] = "write",
281 		[BLKIF_OP_WRITE_BARRIER] = "barrier",
282 		[BLKIF_OP_FLUSH_DISKCACHE] = "flush",
283 		[BLKIF_OP_DISCARD] = "discard" };
284 
285 	if (op < 0 || op >= ARRAY_SIZE(names))
286 		return "unknown";
287 
288 	if (!names[op])
289 		return "reserved";
290 
291 	return names[op];
292 }
293 static int xlbd_reserve_minors(unsigned int minor, unsigned int nr)
294 {
295 	unsigned int end = minor + nr;
296 	int rc;
297 
298 	if (end > nr_minors) {
299 		unsigned long *bitmap, *old;
300 
301 		bitmap = kcalloc(BITS_TO_LONGS(end), sizeof(*bitmap),
302 				 GFP_KERNEL);
303 		if (bitmap == NULL)
304 			return -ENOMEM;
305 
306 		spin_lock(&minor_lock);
307 		if (end > nr_minors) {
308 			old = minors;
309 			memcpy(bitmap, minors,
310 			       BITS_TO_LONGS(nr_minors) * sizeof(*bitmap));
311 			minors = bitmap;
312 			nr_minors = BITS_TO_LONGS(end) * BITS_PER_LONG;
313 		} else
314 			old = bitmap;
315 		spin_unlock(&minor_lock);
316 		kfree(old);
317 	}
318 
319 	spin_lock(&minor_lock);
320 	if (find_next_bit(minors, end, minor) >= end) {
321 		bitmap_set(minors, minor, nr);
322 		rc = 0;
323 	} else
324 		rc = -EBUSY;
325 	spin_unlock(&minor_lock);
326 
327 	return rc;
328 }
329 
330 static void xlbd_release_minors(unsigned int minor, unsigned int nr)
331 {
332 	unsigned int end = minor + nr;
333 
334 	BUG_ON(end > nr_minors);
335 	spin_lock(&minor_lock);
336 	bitmap_clear(minors,  minor, nr);
337 	spin_unlock(&minor_lock);
338 }
339 
340 static void blkif_restart_queue_callback(void *arg)
341 {
342 	struct blkfront_info *info = (struct blkfront_info *)arg;
343 	schedule_work(&info->work);
344 }
345 
346 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
347 {
348 	/* We don't have real geometry info, but let's at least return
349 	   values consistent with the size of the device */
350 	sector_t nsect = get_capacity(bd->bd_disk);
351 	sector_t cylinders = nsect;
352 
353 	hg->heads = 0xff;
354 	hg->sectors = 0x3f;
355 	sector_div(cylinders, hg->heads * hg->sectors);
356 	hg->cylinders = cylinders;
357 	if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
358 		hg->cylinders = 0xffff;
359 	return 0;
360 }
361 
362 static int blkif_ioctl(struct block_device *bdev, fmode_t mode,
363 		       unsigned command, unsigned long argument)
364 {
365 	struct blkfront_info *info = bdev->bd_disk->private_data;
366 	int i;
367 
368 	dev_dbg(&info->xbdev->dev, "command: 0x%x, argument: 0x%lx\n",
369 		command, (long)argument);
370 
371 	switch (command) {
372 	case CDROMMULTISESSION:
373 		dev_dbg(&info->xbdev->dev, "FIXME: support multisession CDs later\n");
374 		for (i = 0; i < sizeof(struct cdrom_multisession); i++)
375 			if (put_user(0, (char __user *)(argument + i)))
376 				return -EFAULT;
377 		return 0;
378 
379 	case CDROM_GET_CAPABILITY: {
380 		struct gendisk *gd = info->gd;
381 		if (gd->flags & GENHD_FL_CD)
382 			return 0;
383 		return -EINVAL;
384 	}
385 
386 	default:
387 		/*printk(KERN_ALERT "ioctl %08x not supported by Xen blkdev\n",
388 		  command);*/
389 		return -EINVAL; /* same return as native Linux */
390 	}
391 
392 	return 0;
393 }
394 
395 /*
396  * Generate a Xen blkfront IO request from a blk layer request.  Reads
397  * and writes are handled as expected.
398  *
399  * @req: a request struct
400  */
401 static int blkif_queue_request(struct request *req)
402 {
403 	struct blkfront_info *info = req->rq_disk->private_data;
404 	struct blkif_request *ring_req;
405 	unsigned long id;
406 	unsigned int fsect, lsect;
407 	int i, ref, n;
408 	struct blkif_request_segment *segments = NULL;
409 
410 	/*
411 	 * Used to store if we are able to queue the request by just using
412 	 * existing persistent grants, or if we have to get new grants,
413 	 * as there are not sufficiently many free.
414 	 */
415 	bool new_persistent_gnts;
416 	grant_ref_t gref_head;
417 	struct grant *gnt_list_entry = NULL;
418 	struct scatterlist *sg;
419 	int nseg, max_grefs;
420 
421 	if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
422 		return 1;
423 
424 	max_grefs = req->nr_phys_segments;
425 	if (max_grefs > BLKIF_MAX_SEGMENTS_PER_REQUEST)
426 		/*
427 		 * If we are using indirect segments we need to account
428 		 * for the indirect grefs used in the request.
429 		 */
430 		max_grefs += INDIRECT_GREFS(req->nr_phys_segments);
431 
432 	/* Check if we have enough grants to allocate a requests */
433 	if (info->persistent_gnts_c < max_grefs) {
434 		new_persistent_gnts = 1;
435 		if (gnttab_alloc_grant_references(
436 		    max_grefs - info->persistent_gnts_c,
437 		    &gref_head) < 0) {
438 			gnttab_request_free_callback(
439 				&info->callback,
440 				blkif_restart_queue_callback,
441 				info,
442 				max_grefs);
443 			return 1;
444 		}
445 	} else
446 		new_persistent_gnts = 0;
447 
448 	/* Fill out a communications ring structure. */
449 	ring_req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
450 	id = get_id_from_freelist(info);
451 	info->shadow[id].request = req;
452 
453 	if (unlikely(req->cmd_flags & (REQ_DISCARD | REQ_SECURE))) {
454 		ring_req->operation = BLKIF_OP_DISCARD;
455 		ring_req->u.discard.nr_sectors = blk_rq_sectors(req);
456 		ring_req->u.discard.id = id;
457 		ring_req->u.discard.sector_number = (blkif_sector_t)blk_rq_pos(req);
458 		if ((req->cmd_flags & REQ_SECURE) && info->feature_secdiscard)
459 			ring_req->u.discard.flag = BLKIF_DISCARD_SECURE;
460 		else
461 			ring_req->u.discard.flag = 0;
462 	} else {
463 		BUG_ON(info->max_indirect_segments == 0 &&
464 		       req->nr_phys_segments > BLKIF_MAX_SEGMENTS_PER_REQUEST);
465 		BUG_ON(info->max_indirect_segments &&
466 		       req->nr_phys_segments > info->max_indirect_segments);
467 		nseg = blk_rq_map_sg(req->q, req, info->shadow[id].sg);
468 		ring_req->u.rw.id = id;
469 		if (nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST) {
470 			/*
471 			 * The indirect operation can only be a BLKIF_OP_READ or
472 			 * BLKIF_OP_WRITE
473 			 */
474 			BUG_ON(req->cmd_flags & (REQ_FLUSH | REQ_FUA));
475 			ring_req->operation = BLKIF_OP_INDIRECT;
476 			ring_req->u.indirect.indirect_op = rq_data_dir(req) ?
477 				BLKIF_OP_WRITE : BLKIF_OP_READ;
478 			ring_req->u.indirect.sector_number = (blkif_sector_t)blk_rq_pos(req);
479 			ring_req->u.indirect.handle = info->handle;
480 			ring_req->u.indirect.nr_segments = nseg;
481 		} else {
482 			ring_req->u.rw.sector_number = (blkif_sector_t)blk_rq_pos(req);
483 			ring_req->u.rw.handle = info->handle;
484 			ring_req->operation = rq_data_dir(req) ?
485 				BLKIF_OP_WRITE : BLKIF_OP_READ;
486 			if (req->cmd_flags & (REQ_FLUSH | REQ_FUA)) {
487 				/*
488 				 * Ideally we can do an unordered flush-to-disk. In case the
489 				 * backend onlysupports barriers, use that. A barrier request
490 				 * a superset of FUA, so we can implement it the same
491 				 * way.  (It's also a FLUSH+FUA, since it is
492 				 * guaranteed ordered WRT previous writes.)
493 				 */
494 				switch (info->feature_flush &
495 					((REQ_FLUSH|REQ_FUA))) {
496 				case REQ_FLUSH|REQ_FUA:
497 					ring_req->operation =
498 						BLKIF_OP_WRITE_BARRIER;
499 					break;
500 				case REQ_FLUSH:
501 					ring_req->operation =
502 						BLKIF_OP_FLUSH_DISKCACHE;
503 					break;
504 				default:
505 					ring_req->operation = 0;
506 				}
507 			}
508 			ring_req->u.rw.nr_segments = nseg;
509 		}
510 		for_each_sg(info->shadow[id].sg, sg, nseg, i) {
511 			fsect = sg->offset >> 9;
512 			lsect = fsect + (sg->length >> 9) - 1;
513 
514 			if ((ring_req->operation == BLKIF_OP_INDIRECT) &&
515 			    (i % SEGS_PER_INDIRECT_FRAME == 0)) {
516 				unsigned long uninitialized_var(pfn);
517 
518 				if (segments)
519 					kunmap_atomic(segments);
520 
521 				n = i / SEGS_PER_INDIRECT_FRAME;
522 				if (!info->feature_persistent) {
523 					struct page *indirect_page;
524 
525 					/* Fetch a pre-allocated page to use for indirect grefs */
526 					BUG_ON(list_empty(&info->indirect_pages));
527 					indirect_page = list_first_entry(&info->indirect_pages,
528 					                                 struct page, lru);
529 					list_del(&indirect_page->lru);
530 					pfn = page_to_pfn(indirect_page);
531 				}
532 				gnt_list_entry = get_grant(&gref_head, pfn, info);
533 				info->shadow[id].indirect_grants[n] = gnt_list_entry;
534 				segments = kmap_atomic(pfn_to_page(gnt_list_entry->pfn));
535 				ring_req->u.indirect.indirect_grefs[n] = gnt_list_entry->gref;
536 			}
537 
538 			gnt_list_entry = get_grant(&gref_head, page_to_pfn(sg_page(sg)), info);
539 			ref = gnt_list_entry->gref;
540 
541 			info->shadow[id].grants_used[i] = gnt_list_entry;
542 
543 			if (rq_data_dir(req) && info->feature_persistent) {
544 				char *bvec_data;
545 				void *shared_data;
546 
547 				BUG_ON(sg->offset + sg->length > PAGE_SIZE);
548 
549 				shared_data = kmap_atomic(pfn_to_page(gnt_list_entry->pfn));
550 				bvec_data = kmap_atomic(sg_page(sg));
551 
552 				/*
553 				 * this does not wipe data stored outside the
554 				 * range sg->offset..sg->offset+sg->length.
555 				 * Therefore, blkback *could* see data from
556 				 * previous requests. This is OK as long as
557 				 * persistent grants are shared with just one
558 				 * domain. It may need refactoring if this
559 				 * changes
560 				 */
561 				memcpy(shared_data + sg->offset,
562 				       bvec_data   + sg->offset,
563 				       sg->length);
564 
565 				kunmap_atomic(bvec_data);
566 				kunmap_atomic(shared_data);
567 			}
568 			if (ring_req->operation != BLKIF_OP_INDIRECT) {
569 				ring_req->u.rw.seg[i] =
570 						(struct blkif_request_segment) {
571 							.gref       = ref,
572 							.first_sect = fsect,
573 							.last_sect  = lsect };
574 			} else {
575 				n = i % SEGS_PER_INDIRECT_FRAME;
576 				segments[n] =
577 					(struct blkif_request_segment) {
578 							.gref       = ref,
579 							.first_sect = fsect,
580 							.last_sect  = lsect };
581 			}
582 		}
583 		if (segments)
584 			kunmap_atomic(segments);
585 	}
586 
587 	info->ring.req_prod_pvt++;
588 
589 	/* Keep a private copy so we can reissue requests when recovering. */
590 	info->shadow[id].req = *ring_req;
591 
592 	if (new_persistent_gnts)
593 		gnttab_free_grant_references(gref_head);
594 
595 	return 0;
596 }
597 
598 
599 static inline void flush_requests(struct blkfront_info *info)
600 {
601 	int notify;
602 
603 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
604 
605 	if (notify)
606 		notify_remote_via_irq(info->irq);
607 }
608 
609 static inline bool blkif_request_flush_invalid(struct request *req,
610 					       struct blkfront_info *info)
611 {
612 	return ((req->cmd_type != REQ_TYPE_FS) ||
613 		((req->cmd_flags & REQ_FLUSH) &&
614 		 !(info->feature_flush & REQ_FLUSH)) ||
615 		((req->cmd_flags & REQ_FUA) &&
616 		 !(info->feature_flush & REQ_FUA)));
617 }
618 
619 /*
620  * do_blkif_request
621  *  read a block; request is in a request queue
622  */
623 static void do_blkif_request(struct request_queue *rq)
624 {
625 	struct blkfront_info *info = NULL;
626 	struct request *req;
627 	int queued;
628 
629 	pr_debug("Entered do_blkif_request\n");
630 
631 	queued = 0;
632 
633 	while ((req = blk_peek_request(rq)) != NULL) {
634 		info = req->rq_disk->private_data;
635 
636 		if (RING_FULL(&info->ring))
637 			goto wait;
638 
639 		blk_start_request(req);
640 
641 		if (blkif_request_flush_invalid(req, info)) {
642 			__blk_end_request_all(req, -EOPNOTSUPP);
643 			continue;
644 		}
645 
646 		pr_debug("do_blk_req %p: cmd %p, sec %lx, "
647 			 "(%u/%u) [%s]\n",
648 			 req, req->cmd, (unsigned long)blk_rq_pos(req),
649 			 blk_rq_cur_sectors(req), blk_rq_sectors(req),
650 			 rq_data_dir(req) ? "write" : "read");
651 
652 		if (blkif_queue_request(req)) {
653 			blk_requeue_request(rq, req);
654 wait:
655 			/* Avoid pointless unplugs. */
656 			blk_stop_queue(rq);
657 			break;
658 		}
659 
660 		queued++;
661 	}
662 
663 	if (queued != 0)
664 		flush_requests(info);
665 }
666 
667 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size,
668 				unsigned int physical_sector_size,
669 				unsigned int segments)
670 {
671 	struct request_queue *rq;
672 	struct blkfront_info *info = gd->private_data;
673 
674 	rq = blk_init_queue(do_blkif_request, &info->io_lock);
675 	if (rq == NULL)
676 		return -1;
677 
678 	queue_flag_set_unlocked(QUEUE_FLAG_VIRT, rq);
679 
680 	if (info->feature_discard) {
681 		queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, rq);
682 		blk_queue_max_discard_sectors(rq, get_capacity(gd));
683 		rq->limits.discard_granularity = info->discard_granularity;
684 		rq->limits.discard_alignment = info->discard_alignment;
685 		if (info->feature_secdiscard)
686 			queue_flag_set_unlocked(QUEUE_FLAG_SECDISCARD, rq);
687 	}
688 
689 	/* Hard sector size and max sectors impersonate the equiv. hardware. */
690 	blk_queue_logical_block_size(rq, sector_size);
691 	blk_queue_physical_block_size(rq, physical_sector_size);
692 	blk_queue_max_hw_sectors(rq, (segments * PAGE_SIZE) / 512);
693 
694 	/* Each segment in a request is up to an aligned page in size. */
695 	blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
696 	blk_queue_max_segment_size(rq, PAGE_SIZE);
697 
698 	/* Ensure a merged request will fit in a single I/O ring slot. */
699 	blk_queue_max_segments(rq, segments);
700 
701 	/* Make sure buffer addresses are sector-aligned. */
702 	blk_queue_dma_alignment(rq, 511);
703 
704 	/* Make sure we don't use bounce buffers. */
705 	blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
706 
707 	gd->queue = rq;
708 
709 	return 0;
710 }
711 
712 static const char *flush_info(unsigned int feature_flush)
713 {
714 	switch (feature_flush & ((REQ_FLUSH | REQ_FUA))) {
715 	case REQ_FLUSH|REQ_FUA:
716 		return "barrier: enabled;";
717 	case REQ_FLUSH:
718 		return "flush diskcache: enabled;";
719 	default:
720 		return "barrier or flush: disabled;";
721 	}
722 }
723 
724 static void xlvbd_flush(struct blkfront_info *info)
725 {
726 	blk_queue_flush(info->rq, info->feature_flush);
727 	pr_info("blkfront: %s: %s %s %s %s %s\n",
728 		info->gd->disk_name, flush_info(info->feature_flush),
729 		"persistent grants:", info->feature_persistent ?
730 		"enabled;" : "disabled;", "indirect descriptors:",
731 		info->max_indirect_segments ? "enabled;" : "disabled;");
732 }
733 
734 static int xen_translate_vdev(int vdevice, int *minor, unsigned int *offset)
735 {
736 	int major;
737 	major = BLKIF_MAJOR(vdevice);
738 	*minor = BLKIF_MINOR(vdevice);
739 	switch (major) {
740 		case XEN_IDE0_MAJOR:
741 			*offset = (*minor / 64) + EMULATED_HD_DISK_NAME_OFFSET;
742 			*minor = ((*minor / 64) * PARTS_PER_DISK) +
743 				EMULATED_HD_DISK_MINOR_OFFSET;
744 			break;
745 		case XEN_IDE1_MAJOR:
746 			*offset = (*minor / 64) + 2 + EMULATED_HD_DISK_NAME_OFFSET;
747 			*minor = (((*minor / 64) + 2) * PARTS_PER_DISK) +
748 				EMULATED_HD_DISK_MINOR_OFFSET;
749 			break;
750 		case XEN_SCSI_DISK0_MAJOR:
751 			*offset = (*minor / PARTS_PER_DISK) + EMULATED_SD_DISK_NAME_OFFSET;
752 			*minor = *minor + EMULATED_SD_DISK_MINOR_OFFSET;
753 			break;
754 		case XEN_SCSI_DISK1_MAJOR:
755 		case XEN_SCSI_DISK2_MAJOR:
756 		case XEN_SCSI_DISK3_MAJOR:
757 		case XEN_SCSI_DISK4_MAJOR:
758 		case XEN_SCSI_DISK5_MAJOR:
759 		case XEN_SCSI_DISK6_MAJOR:
760 		case XEN_SCSI_DISK7_MAJOR:
761 			*offset = (*minor / PARTS_PER_DISK) +
762 				((major - XEN_SCSI_DISK1_MAJOR + 1) * 16) +
763 				EMULATED_SD_DISK_NAME_OFFSET;
764 			*minor = *minor +
765 				((major - XEN_SCSI_DISK1_MAJOR + 1) * 16 * PARTS_PER_DISK) +
766 				EMULATED_SD_DISK_MINOR_OFFSET;
767 			break;
768 		case XEN_SCSI_DISK8_MAJOR:
769 		case XEN_SCSI_DISK9_MAJOR:
770 		case XEN_SCSI_DISK10_MAJOR:
771 		case XEN_SCSI_DISK11_MAJOR:
772 		case XEN_SCSI_DISK12_MAJOR:
773 		case XEN_SCSI_DISK13_MAJOR:
774 		case XEN_SCSI_DISK14_MAJOR:
775 		case XEN_SCSI_DISK15_MAJOR:
776 			*offset = (*minor / PARTS_PER_DISK) +
777 				((major - XEN_SCSI_DISK8_MAJOR + 8) * 16) +
778 				EMULATED_SD_DISK_NAME_OFFSET;
779 			*minor = *minor +
780 				((major - XEN_SCSI_DISK8_MAJOR + 8) * 16 * PARTS_PER_DISK) +
781 				EMULATED_SD_DISK_MINOR_OFFSET;
782 			break;
783 		case XENVBD_MAJOR:
784 			*offset = *minor / PARTS_PER_DISK;
785 			break;
786 		default:
787 			printk(KERN_WARNING "blkfront: your disk configuration is "
788 					"incorrect, please use an xvd device instead\n");
789 			return -ENODEV;
790 	}
791 	return 0;
792 }
793 
794 static char *encode_disk_name(char *ptr, unsigned int n)
795 {
796 	if (n >= 26)
797 		ptr = encode_disk_name(ptr, n / 26 - 1);
798 	*ptr = 'a' + n % 26;
799 	return ptr + 1;
800 }
801 
802 static int xlvbd_alloc_gendisk(blkif_sector_t capacity,
803 			       struct blkfront_info *info,
804 			       u16 vdisk_info, u16 sector_size,
805 			       unsigned int physical_sector_size)
806 {
807 	struct gendisk *gd;
808 	int nr_minors = 1;
809 	int err;
810 	unsigned int offset;
811 	int minor;
812 	int nr_parts;
813 	char *ptr;
814 
815 	BUG_ON(info->gd != NULL);
816 	BUG_ON(info->rq != NULL);
817 
818 	if ((info->vdevice>>EXT_SHIFT) > 1) {
819 		/* this is above the extended range; something is wrong */
820 		printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
821 		return -ENODEV;
822 	}
823 
824 	if (!VDEV_IS_EXTENDED(info->vdevice)) {
825 		err = xen_translate_vdev(info->vdevice, &minor, &offset);
826 		if (err)
827 			return err;
828  		nr_parts = PARTS_PER_DISK;
829 	} else {
830 		minor = BLKIF_MINOR_EXT(info->vdevice);
831 		nr_parts = PARTS_PER_EXT_DISK;
832 		offset = minor / nr_parts;
833 		if (xen_hvm_domain() && offset < EMULATED_HD_DISK_NAME_OFFSET + 4)
834 			printk(KERN_WARNING "blkfront: vdevice 0x%x might conflict with "
835 					"emulated IDE disks,\n\t choose an xvd device name"
836 					"from xvde on\n", info->vdevice);
837 	}
838 	if (minor >> MINORBITS) {
839 		pr_warn("blkfront: %#x's minor (%#x) out of range; ignoring\n",
840 			info->vdevice, minor);
841 		return -ENODEV;
842 	}
843 
844 	if ((minor % nr_parts) == 0)
845 		nr_minors = nr_parts;
846 
847 	err = xlbd_reserve_minors(minor, nr_minors);
848 	if (err)
849 		goto out;
850 	err = -ENODEV;
851 
852 	gd = alloc_disk(nr_minors);
853 	if (gd == NULL)
854 		goto release;
855 
856 	strcpy(gd->disk_name, DEV_NAME);
857 	ptr = encode_disk_name(gd->disk_name + sizeof(DEV_NAME) - 1, offset);
858 	BUG_ON(ptr >= gd->disk_name + DISK_NAME_LEN);
859 	if (nr_minors > 1)
860 		*ptr = 0;
861 	else
862 		snprintf(ptr, gd->disk_name + DISK_NAME_LEN - ptr,
863 			 "%d", minor & (nr_parts - 1));
864 
865 	gd->major = XENVBD_MAJOR;
866 	gd->first_minor = minor;
867 	gd->fops = &xlvbd_block_fops;
868 	gd->private_data = info;
869 	gd->driverfs_dev = &(info->xbdev->dev);
870 	set_capacity(gd, capacity);
871 
872 	if (xlvbd_init_blk_queue(gd, sector_size, physical_sector_size,
873 				 info->max_indirect_segments ? :
874 				 BLKIF_MAX_SEGMENTS_PER_REQUEST)) {
875 		del_gendisk(gd);
876 		goto release;
877 	}
878 
879 	info->rq = gd->queue;
880 	info->gd = gd;
881 
882 	xlvbd_flush(info);
883 
884 	if (vdisk_info & VDISK_READONLY)
885 		set_disk_ro(gd, 1);
886 
887 	if (vdisk_info & VDISK_REMOVABLE)
888 		gd->flags |= GENHD_FL_REMOVABLE;
889 
890 	if (vdisk_info & VDISK_CDROM)
891 		gd->flags |= GENHD_FL_CD;
892 
893 	return 0;
894 
895  release:
896 	xlbd_release_minors(minor, nr_minors);
897  out:
898 	return err;
899 }
900 
901 static void xlvbd_release_gendisk(struct blkfront_info *info)
902 {
903 	unsigned int minor, nr_minors;
904 	unsigned long flags;
905 
906 	if (info->rq == NULL)
907 		return;
908 
909 	spin_lock_irqsave(&info->io_lock, flags);
910 
911 	/* No more blkif_request(). */
912 	blk_stop_queue(info->rq);
913 
914 	/* No more gnttab callback work. */
915 	gnttab_cancel_free_callback(&info->callback);
916 	spin_unlock_irqrestore(&info->io_lock, flags);
917 
918 	/* Flush gnttab callback work. Must be done with no locks held. */
919 	flush_work(&info->work);
920 
921 	del_gendisk(info->gd);
922 
923 	minor = info->gd->first_minor;
924 	nr_minors = info->gd->minors;
925 	xlbd_release_minors(minor, nr_minors);
926 
927 	blk_cleanup_queue(info->rq);
928 	info->rq = NULL;
929 
930 	put_disk(info->gd);
931 	info->gd = NULL;
932 }
933 
934 static void kick_pending_request_queues(struct blkfront_info *info)
935 {
936 	if (!RING_FULL(&info->ring)) {
937 		/* Re-enable calldowns. */
938 		blk_start_queue(info->rq);
939 		/* Kick things off immediately. */
940 		do_blkif_request(info->rq);
941 	}
942 }
943 
944 static void blkif_restart_queue(struct work_struct *work)
945 {
946 	struct blkfront_info *info = container_of(work, struct blkfront_info, work);
947 
948 	spin_lock_irq(&info->io_lock);
949 	if (info->connected == BLKIF_STATE_CONNECTED)
950 		kick_pending_request_queues(info);
951 	spin_unlock_irq(&info->io_lock);
952 }
953 
954 static void blkif_free(struct blkfront_info *info, int suspend)
955 {
956 	struct grant *persistent_gnt;
957 	struct grant *n;
958 	int i, j, segs;
959 
960 	/* Prevent new requests being issued until we fix things up. */
961 	spin_lock_irq(&info->io_lock);
962 	info->connected = suspend ?
963 		BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
964 	/* No more blkif_request(). */
965 	if (info->rq)
966 		blk_stop_queue(info->rq);
967 
968 	/* Remove all persistent grants */
969 	if (!list_empty(&info->grants)) {
970 		list_for_each_entry_safe(persistent_gnt, n,
971 		                         &info->grants, node) {
972 			list_del(&persistent_gnt->node);
973 			if (persistent_gnt->gref != GRANT_INVALID_REF) {
974 				gnttab_end_foreign_access(persistent_gnt->gref,
975 				                          0, 0UL);
976 				info->persistent_gnts_c--;
977 			}
978 			if (info->feature_persistent)
979 				__free_page(pfn_to_page(persistent_gnt->pfn));
980 			kfree(persistent_gnt);
981 		}
982 	}
983 	BUG_ON(info->persistent_gnts_c != 0);
984 
985 	/*
986 	 * Remove indirect pages, this only happens when using indirect
987 	 * descriptors but not persistent grants
988 	 */
989 	if (!list_empty(&info->indirect_pages)) {
990 		struct page *indirect_page, *n;
991 
992 		BUG_ON(info->feature_persistent);
993 		list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
994 			list_del(&indirect_page->lru);
995 			__free_page(indirect_page);
996 		}
997 	}
998 
999 	for (i = 0; i < BLK_RING_SIZE(info); i++) {
1000 		/*
1001 		 * Clear persistent grants present in requests already
1002 		 * on the shared ring
1003 		 */
1004 		if (!info->shadow[i].request)
1005 			goto free_shadow;
1006 
1007 		segs = info->shadow[i].req.operation == BLKIF_OP_INDIRECT ?
1008 		       info->shadow[i].req.u.indirect.nr_segments :
1009 		       info->shadow[i].req.u.rw.nr_segments;
1010 		for (j = 0; j < segs; j++) {
1011 			persistent_gnt = info->shadow[i].grants_used[j];
1012 			gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1013 			if (info->feature_persistent)
1014 				__free_page(pfn_to_page(persistent_gnt->pfn));
1015 			kfree(persistent_gnt);
1016 		}
1017 
1018 		if (info->shadow[i].req.operation != BLKIF_OP_INDIRECT)
1019 			/*
1020 			 * If this is not an indirect operation don't try to
1021 			 * free indirect segments
1022 			 */
1023 			goto free_shadow;
1024 
1025 		for (j = 0; j < INDIRECT_GREFS(segs); j++) {
1026 			persistent_gnt = info->shadow[i].indirect_grants[j];
1027 			gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
1028 			__free_page(pfn_to_page(persistent_gnt->pfn));
1029 			kfree(persistent_gnt);
1030 		}
1031 
1032 free_shadow:
1033 		kfree(info->shadow[i].grants_used);
1034 		info->shadow[i].grants_used = NULL;
1035 		kfree(info->shadow[i].indirect_grants);
1036 		info->shadow[i].indirect_grants = NULL;
1037 		kfree(info->shadow[i].sg);
1038 		info->shadow[i].sg = NULL;
1039 	}
1040 
1041 	/* No more gnttab callback work. */
1042 	gnttab_cancel_free_callback(&info->callback);
1043 	spin_unlock_irq(&info->io_lock);
1044 
1045 	/* Flush gnttab callback work. Must be done with no locks held. */
1046 	flush_work(&info->work);
1047 
1048 	/* Free resources associated with old device channel. */
1049 	for (i = 0; i < info->nr_ring_pages; i++) {
1050 		if (info->ring_ref[i] != GRANT_INVALID_REF) {
1051 			gnttab_end_foreign_access(info->ring_ref[i], 0, 0);
1052 			info->ring_ref[i] = GRANT_INVALID_REF;
1053 		}
1054 	}
1055 	free_pages((unsigned long)info->ring.sring, get_order(info->nr_ring_pages * PAGE_SIZE));
1056 	info->ring.sring = NULL;
1057 
1058 	if (info->irq)
1059 		unbind_from_irqhandler(info->irq, info);
1060 	info->evtchn = info->irq = 0;
1061 
1062 }
1063 
1064 static void blkif_completion(struct blk_shadow *s, struct blkfront_info *info,
1065 			     struct blkif_response *bret)
1066 {
1067 	int i = 0;
1068 	struct scatterlist *sg;
1069 	char *bvec_data;
1070 	void *shared_data;
1071 	int nseg;
1072 
1073 	nseg = s->req.operation == BLKIF_OP_INDIRECT ?
1074 		s->req.u.indirect.nr_segments : s->req.u.rw.nr_segments;
1075 
1076 	if (bret->operation == BLKIF_OP_READ && info->feature_persistent) {
1077 		for_each_sg(s->sg, sg, nseg, i) {
1078 			BUG_ON(sg->offset + sg->length > PAGE_SIZE);
1079 			shared_data = kmap_atomic(
1080 				pfn_to_page(s->grants_used[i]->pfn));
1081 			bvec_data = kmap_atomic(sg_page(sg));
1082 			memcpy(bvec_data   + sg->offset,
1083 			       shared_data + sg->offset,
1084 			       sg->length);
1085 			kunmap_atomic(bvec_data);
1086 			kunmap_atomic(shared_data);
1087 		}
1088 	}
1089 	/* Add the persistent grant into the list of free grants */
1090 	for (i = 0; i < nseg; i++) {
1091 		if (gnttab_query_foreign_access(s->grants_used[i]->gref)) {
1092 			/*
1093 			 * If the grant is still mapped by the backend (the
1094 			 * backend has chosen to make this grant persistent)
1095 			 * we add it at the head of the list, so it will be
1096 			 * reused first.
1097 			 */
1098 			if (!info->feature_persistent)
1099 				pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1100 						     s->grants_used[i]->gref);
1101 			list_add(&s->grants_used[i]->node, &info->grants);
1102 			info->persistent_gnts_c++;
1103 		} else {
1104 			/*
1105 			 * If the grant is not mapped by the backend we end the
1106 			 * foreign access and add it to the tail of the list,
1107 			 * so it will not be picked again unless we run out of
1108 			 * persistent grants.
1109 			 */
1110 			gnttab_end_foreign_access(s->grants_used[i]->gref, 0, 0UL);
1111 			s->grants_used[i]->gref = GRANT_INVALID_REF;
1112 			list_add_tail(&s->grants_used[i]->node, &info->grants);
1113 		}
1114 	}
1115 	if (s->req.operation == BLKIF_OP_INDIRECT) {
1116 		for (i = 0; i < INDIRECT_GREFS(nseg); i++) {
1117 			if (gnttab_query_foreign_access(s->indirect_grants[i]->gref)) {
1118 				if (!info->feature_persistent)
1119 					pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1120 							     s->indirect_grants[i]->gref);
1121 				list_add(&s->indirect_grants[i]->node, &info->grants);
1122 				info->persistent_gnts_c++;
1123 			} else {
1124 				struct page *indirect_page;
1125 
1126 				gnttab_end_foreign_access(s->indirect_grants[i]->gref, 0, 0UL);
1127 				/*
1128 				 * Add the used indirect page back to the list of
1129 				 * available pages for indirect grefs.
1130 				 */
1131 				if (!info->feature_persistent) {
1132 					indirect_page = pfn_to_page(s->indirect_grants[i]->pfn);
1133 					list_add(&indirect_page->lru, &info->indirect_pages);
1134 				}
1135 				s->indirect_grants[i]->gref = GRANT_INVALID_REF;
1136 				list_add_tail(&s->indirect_grants[i]->node, &info->grants);
1137 			}
1138 		}
1139 	}
1140 }
1141 
1142 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
1143 {
1144 	struct request *req;
1145 	struct blkif_response *bret;
1146 	RING_IDX i, rp;
1147 	unsigned long flags;
1148 	struct blkfront_info *info = (struct blkfront_info *)dev_id;
1149 	int error;
1150 
1151 	spin_lock_irqsave(&info->io_lock, flags);
1152 
1153 	if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
1154 		spin_unlock_irqrestore(&info->io_lock, flags);
1155 		return IRQ_HANDLED;
1156 	}
1157 
1158  again:
1159 	rp = info->ring.sring->rsp_prod;
1160 	rmb(); /* Ensure we see queued responses up to 'rp'. */
1161 
1162 	for (i = info->ring.rsp_cons; i != rp; i++) {
1163 		unsigned long id;
1164 
1165 		bret = RING_GET_RESPONSE(&info->ring, i);
1166 		id   = bret->id;
1167 		/*
1168 		 * The backend has messed up and given us an id that we would
1169 		 * never have given to it (we stamp it up to BLK_RING_SIZE -
1170 		 * look in get_id_from_freelist.
1171 		 */
1172 		if (id >= BLK_RING_SIZE(info)) {
1173 			WARN(1, "%s: response to %s has incorrect id (%ld)\n",
1174 			     info->gd->disk_name, op_name(bret->operation), id);
1175 			/* We can't safely get the 'struct request' as
1176 			 * the id is busted. */
1177 			continue;
1178 		}
1179 		req  = info->shadow[id].request;
1180 
1181 		if (bret->operation != BLKIF_OP_DISCARD)
1182 			blkif_completion(&info->shadow[id], info, bret);
1183 
1184 		if (add_id_to_freelist(info, id)) {
1185 			WARN(1, "%s: response to %s (id %ld) couldn't be recycled!\n",
1186 			     info->gd->disk_name, op_name(bret->operation), id);
1187 			continue;
1188 		}
1189 
1190 		error = (bret->status == BLKIF_RSP_OKAY) ? 0 : -EIO;
1191 		switch (bret->operation) {
1192 		case BLKIF_OP_DISCARD:
1193 			if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
1194 				struct request_queue *rq = info->rq;
1195 				printk(KERN_WARNING "blkfront: %s: %s op failed\n",
1196 					   info->gd->disk_name, op_name(bret->operation));
1197 				error = -EOPNOTSUPP;
1198 				info->feature_discard = 0;
1199 				info->feature_secdiscard = 0;
1200 				queue_flag_clear(QUEUE_FLAG_DISCARD, rq);
1201 				queue_flag_clear(QUEUE_FLAG_SECDISCARD, rq);
1202 			}
1203 			__blk_end_request_all(req, error);
1204 			break;
1205 		case BLKIF_OP_FLUSH_DISKCACHE:
1206 		case BLKIF_OP_WRITE_BARRIER:
1207 			if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
1208 				printk(KERN_WARNING "blkfront: %s: %s op failed\n",
1209 				       info->gd->disk_name, op_name(bret->operation));
1210 				error = -EOPNOTSUPP;
1211 			}
1212 			if (unlikely(bret->status == BLKIF_RSP_ERROR &&
1213 				     info->shadow[id].req.u.rw.nr_segments == 0)) {
1214 				printk(KERN_WARNING "blkfront: %s: empty %s op failed\n",
1215 				       info->gd->disk_name, op_name(bret->operation));
1216 				error = -EOPNOTSUPP;
1217 			}
1218 			if (unlikely(error)) {
1219 				if (error == -EOPNOTSUPP)
1220 					error = 0;
1221 				info->feature_flush = 0;
1222 				xlvbd_flush(info);
1223 			}
1224 			/* fall through */
1225 		case BLKIF_OP_READ:
1226 		case BLKIF_OP_WRITE:
1227 			if (unlikely(bret->status != BLKIF_RSP_OKAY))
1228 				dev_dbg(&info->xbdev->dev, "Bad return from blkdev data "
1229 					"request: %x\n", bret->status);
1230 
1231 			__blk_end_request_all(req, error);
1232 			break;
1233 		default:
1234 			BUG();
1235 		}
1236 	}
1237 
1238 	info->ring.rsp_cons = i;
1239 
1240 	if (i != info->ring.req_prod_pvt) {
1241 		int more_to_do;
1242 		RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
1243 		if (more_to_do)
1244 			goto again;
1245 	} else
1246 		info->ring.sring->rsp_event = i + 1;
1247 
1248 	kick_pending_request_queues(info);
1249 
1250 	spin_unlock_irqrestore(&info->io_lock, flags);
1251 
1252 	return IRQ_HANDLED;
1253 }
1254 
1255 
1256 static int setup_blkring(struct xenbus_device *dev,
1257 			 struct blkfront_info *info)
1258 {
1259 	struct blkif_sring *sring;
1260 	int err, i;
1261 	unsigned long ring_size = info->nr_ring_pages * PAGE_SIZE;
1262 	grant_ref_t gref[XENBUS_MAX_RING_PAGES];
1263 
1264 	for (i = 0; i < info->nr_ring_pages; i++)
1265 		info->ring_ref[i] = GRANT_INVALID_REF;
1266 
1267 	sring = (struct blkif_sring *)__get_free_pages(GFP_NOIO | __GFP_HIGH,
1268 						       get_order(ring_size));
1269 	if (!sring) {
1270 		xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
1271 		return -ENOMEM;
1272 	}
1273 	SHARED_RING_INIT(sring);
1274 	FRONT_RING_INIT(&info->ring, sring, ring_size);
1275 
1276 	err = xenbus_grant_ring(dev, info->ring.sring, info->nr_ring_pages, gref);
1277 	if (err < 0) {
1278 		free_pages((unsigned long)sring, get_order(ring_size));
1279 		info->ring.sring = NULL;
1280 		goto fail;
1281 	}
1282 	for (i = 0; i < info->nr_ring_pages; i++)
1283 		info->ring_ref[i] = gref[i];
1284 
1285 	err = xenbus_alloc_evtchn(dev, &info->evtchn);
1286 	if (err)
1287 		goto fail;
1288 
1289 	err = bind_evtchn_to_irqhandler(info->evtchn, blkif_interrupt, 0,
1290 					"blkif", info);
1291 	if (err <= 0) {
1292 		xenbus_dev_fatal(dev, err,
1293 				 "bind_evtchn_to_irqhandler failed");
1294 		goto fail;
1295 	}
1296 	info->irq = err;
1297 
1298 	return 0;
1299 fail:
1300 	blkif_free(info, 0);
1301 	return err;
1302 }
1303 
1304 
1305 /* Common code used when first setting up, and when resuming. */
1306 static int talk_to_blkback(struct xenbus_device *dev,
1307 			   struct blkfront_info *info)
1308 {
1309 	const char *message = NULL;
1310 	struct xenbus_transaction xbt;
1311 	int err, i;
1312 	unsigned int max_page_order = 0;
1313 	unsigned int ring_page_order = 0;
1314 
1315 	err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1316 			   "max-ring-page-order", "%u", &max_page_order);
1317 	if (err != 1)
1318 		info->nr_ring_pages = 1;
1319 	else {
1320 		ring_page_order = min(xen_blkif_max_ring_order, max_page_order);
1321 		info->nr_ring_pages = 1 << ring_page_order;
1322 	}
1323 
1324 	/* Create shared ring, alloc event channel. */
1325 	err = setup_blkring(dev, info);
1326 	if (err)
1327 		goto out;
1328 
1329 again:
1330 	err = xenbus_transaction_start(&xbt);
1331 	if (err) {
1332 		xenbus_dev_fatal(dev, err, "starting transaction");
1333 		goto destroy_blkring;
1334 	}
1335 
1336 	if (info->nr_ring_pages == 1) {
1337 		err = xenbus_printf(xbt, dev->nodename,
1338 				    "ring-ref", "%u", info->ring_ref[0]);
1339 		if (err) {
1340 			message = "writing ring-ref";
1341 			goto abort_transaction;
1342 		}
1343 	} else {
1344 		err = xenbus_printf(xbt, dev->nodename,
1345 				    "ring-page-order", "%u", ring_page_order);
1346 		if (err) {
1347 			message = "writing ring-page-order";
1348 			goto abort_transaction;
1349 		}
1350 
1351 		for (i = 0; i < info->nr_ring_pages; i++) {
1352 			char ring_ref_name[RINGREF_NAME_LEN];
1353 
1354 			snprintf(ring_ref_name, RINGREF_NAME_LEN, "ring-ref%u", i);
1355 			err = xenbus_printf(xbt, dev->nodename, ring_ref_name,
1356 					    "%u", info->ring_ref[i]);
1357 			if (err) {
1358 				message = "writing ring-ref";
1359 				goto abort_transaction;
1360 			}
1361 		}
1362 	}
1363 	err = xenbus_printf(xbt, dev->nodename,
1364 			    "event-channel", "%u", info->evtchn);
1365 	if (err) {
1366 		message = "writing event-channel";
1367 		goto abort_transaction;
1368 	}
1369 	err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
1370 			    XEN_IO_PROTO_ABI_NATIVE);
1371 	if (err) {
1372 		message = "writing protocol";
1373 		goto abort_transaction;
1374 	}
1375 	err = xenbus_printf(xbt, dev->nodename,
1376 			    "feature-persistent", "%u", 1);
1377 	if (err)
1378 		dev_warn(&dev->dev,
1379 			 "writing persistent grants feature to xenbus");
1380 
1381 	err = xenbus_transaction_end(xbt, 0);
1382 	if (err) {
1383 		if (err == -EAGAIN)
1384 			goto again;
1385 		xenbus_dev_fatal(dev, err, "completing transaction");
1386 		goto destroy_blkring;
1387 	}
1388 
1389 	for (i = 0; i < BLK_RING_SIZE(info); i++)
1390 		info->shadow[i].req.u.rw.id = i+1;
1391 	info->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1392 	xenbus_switch_state(dev, XenbusStateInitialised);
1393 
1394 	return 0;
1395 
1396  abort_transaction:
1397 	xenbus_transaction_end(xbt, 1);
1398 	if (message)
1399 		xenbus_dev_fatal(dev, err, "%s", message);
1400  destroy_blkring:
1401 	blkif_free(info, 0);
1402  out:
1403 	return err;
1404 }
1405 
1406 /**
1407  * Entry point to this code when a new device is created.  Allocate the basic
1408  * structures and the ring buffer for communication with the backend, and
1409  * inform the backend of the appropriate details for those.  Switch to
1410  * Initialised state.
1411  */
1412 static int blkfront_probe(struct xenbus_device *dev,
1413 			  const struct xenbus_device_id *id)
1414 {
1415 	int err, vdevice;
1416 	struct blkfront_info *info;
1417 
1418 	/* FIXME: Use dynamic device id if this is not set. */
1419 	err = xenbus_scanf(XBT_NIL, dev->nodename,
1420 			   "virtual-device", "%i", &vdevice);
1421 	if (err != 1) {
1422 		/* go looking in the extended area instead */
1423 		err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
1424 				   "%i", &vdevice);
1425 		if (err != 1) {
1426 			xenbus_dev_fatal(dev, err, "reading virtual-device");
1427 			return err;
1428 		}
1429 	}
1430 
1431 	if (xen_hvm_domain()) {
1432 		char *type;
1433 		int len;
1434 		/* no unplug has been done: do not hook devices != xen vbds */
1435 		if (xen_has_pv_and_legacy_disk_devices()) {
1436 			int major;
1437 
1438 			if (!VDEV_IS_EXTENDED(vdevice))
1439 				major = BLKIF_MAJOR(vdevice);
1440 			else
1441 				major = XENVBD_MAJOR;
1442 
1443 			if (major != XENVBD_MAJOR) {
1444 				printk(KERN_INFO
1445 						"%s: HVM does not support vbd %d as xen block device\n",
1446 						__func__, vdevice);
1447 				return -ENODEV;
1448 			}
1449 		}
1450 		/* do not create a PV cdrom device if we are an HVM guest */
1451 		type = xenbus_read(XBT_NIL, dev->nodename, "device-type", &len);
1452 		if (IS_ERR(type))
1453 			return -ENODEV;
1454 		if (strncmp(type, "cdrom", 5) == 0) {
1455 			kfree(type);
1456 			return -ENODEV;
1457 		}
1458 		kfree(type);
1459 	}
1460 	info = kzalloc(sizeof(*info), GFP_KERNEL);
1461 	if (!info) {
1462 		xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
1463 		return -ENOMEM;
1464 	}
1465 
1466 	mutex_init(&info->mutex);
1467 	spin_lock_init(&info->io_lock);
1468 	info->xbdev = dev;
1469 	info->vdevice = vdevice;
1470 	INIT_LIST_HEAD(&info->grants);
1471 	INIT_LIST_HEAD(&info->indirect_pages);
1472 	info->persistent_gnts_c = 0;
1473 	info->connected = BLKIF_STATE_DISCONNECTED;
1474 	INIT_WORK(&info->work, blkif_restart_queue);
1475 
1476 	/* Front end dir is a number, which is used as the id. */
1477 	info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
1478 	dev_set_drvdata(&dev->dev, info);
1479 
1480 	return 0;
1481 }
1482 
1483 static void split_bio_end(struct bio *bio)
1484 {
1485 	struct split_bio *split_bio = bio->bi_private;
1486 
1487 	if (atomic_dec_and_test(&split_bio->pending)) {
1488 		split_bio->bio->bi_phys_segments = 0;
1489 		split_bio->bio->bi_error = bio->bi_error;
1490 		bio_endio(split_bio->bio);
1491 		kfree(split_bio);
1492 	}
1493 	bio_put(bio);
1494 }
1495 
1496 static int blkif_recover(struct blkfront_info *info)
1497 {
1498 	int i;
1499 	struct request *req, *n;
1500 	struct blk_shadow *copy;
1501 	int rc;
1502 	struct bio *bio, *cloned_bio;
1503 	struct bio_list bio_list, merge_bio;
1504 	unsigned int segs, offset;
1505 	int pending, size;
1506 	struct split_bio *split_bio;
1507 	struct list_head requests;
1508 
1509 	/* Stage 1: Make a safe copy of the shadow state. */
1510 	copy = kmemdup(info->shadow, sizeof(info->shadow),
1511 		       GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
1512 	if (!copy)
1513 		return -ENOMEM;
1514 
1515 	/* Stage 2: Set up free list. */
1516 	memset(&info->shadow, 0, sizeof(info->shadow));
1517 	for (i = 0; i < BLK_RING_SIZE(info); i++)
1518 		info->shadow[i].req.u.rw.id = i+1;
1519 	info->shadow_free = info->ring.req_prod_pvt;
1520 	info->shadow[BLK_RING_SIZE(info)-1].req.u.rw.id = 0x0fffffff;
1521 
1522 	rc = blkfront_gather_backend_features(info);
1523 	if (rc) {
1524 		kfree(copy);
1525 		return rc;
1526 	}
1527 
1528 	segs = info->max_indirect_segments ? : BLKIF_MAX_SEGMENTS_PER_REQUEST;
1529 	blk_queue_max_segments(info->rq, segs);
1530 	bio_list_init(&bio_list);
1531 	INIT_LIST_HEAD(&requests);
1532 	for (i = 0; i < BLK_RING_SIZE(info); i++) {
1533 		/* Not in use? */
1534 		if (!copy[i].request)
1535 			continue;
1536 
1537 		/*
1538 		 * Get the bios in the request so we can re-queue them.
1539 		 */
1540 		if (copy[i].request->cmd_flags &
1541 		    (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1542 			/*
1543 			 * Flush operations don't contain bios, so
1544 			 * we need to requeue the whole request
1545 			 */
1546 			list_add(&copy[i].request->queuelist, &requests);
1547 			continue;
1548 		}
1549 		merge_bio.head = copy[i].request->bio;
1550 		merge_bio.tail = copy[i].request->biotail;
1551 		bio_list_merge(&bio_list, &merge_bio);
1552 		copy[i].request->bio = NULL;
1553 		blk_end_request_all(copy[i].request, 0);
1554 	}
1555 
1556 	kfree(copy);
1557 
1558 	/*
1559 	 * Empty the queue, this is important because we might have
1560 	 * requests in the queue with more segments than what we
1561 	 * can handle now.
1562 	 */
1563 	spin_lock_irq(&info->io_lock);
1564 	while ((req = blk_fetch_request(info->rq)) != NULL) {
1565 		if (req->cmd_flags &
1566 		    (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1567 			list_add(&req->queuelist, &requests);
1568 			continue;
1569 		}
1570 		merge_bio.head = req->bio;
1571 		merge_bio.tail = req->biotail;
1572 		bio_list_merge(&bio_list, &merge_bio);
1573 		req->bio = NULL;
1574 		if (req->cmd_flags & (REQ_FLUSH | REQ_FUA))
1575 			pr_alert("diskcache flush request found!\n");
1576 		__blk_end_request_all(req, 0);
1577 	}
1578 	spin_unlock_irq(&info->io_lock);
1579 
1580 	xenbus_switch_state(info->xbdev, XenbusStateConnected);
1581 
1582 	spin_lock_irq(&info->io_lock);
1583 
1584 	/* Now safe for us to use the shared ring */
1585 	info->connected = BLKIF_STATE_CONNECTED;
1586 
1587 	/* Kick any other new requests queued since we resumed */
1588 	kick_pending_request_queues(info);
1589 
1590 	list_for_each_entry_safe(req, n, &requests, queuelist) {
1591 		/* Requeue pending requests (flush or discard) */
1592 		list_del_init(&req->queuelist);
1593 		BUG_ON(req->nr_phys_segments > segs);
1594 		blk_requeue_request(info->rq, req);
1595 	}
1596 	spin_unlock_irq(&info->io_lock);
1597 
1598 	while ((bio = bio_list_pop(&bio_list)) != NULL) {
1599 		/* Traverse the list of pending bios and re-queue them */
1600 		if (bio_segments(bio) > segs) {
1601 			/*
1602 			 * This bio has more segments than what we can
1603 			 * handle, we have to split it.
1604 			 */
1605 			pending = (bio_segments(bio) + segs - 1) / segs;
1606 			split_bio = kzalloc(sizeof(*split_bio), GFP_NOIO);
1607 			BUG_ON(split_bio == NULL);
1608 			atomic_set(&split_bio->pending, pending);
1609 			split_bio->bio = bio;
1610 			for (i = 0; i < pending; i++) {
1611 				offset = (i * segs * PAGE_SIZE) >> 9;
1612 				size = min((unsigned int)(segs * PAGE_SIZE) >> 9,
1613 					   (unsigned int)bio_sectors(bio) - offset);
1614 				cloned_bio = bio_clone(bio, GFP_NOIO);
1615 				BUG_ON(cloned_bio == NULL);
1616 				bio_trim(cloned_bio, offset, size);
1617 				cloned_bio->bi_private = split_bio;
1618 				cloned_bio->bi_end_io = split_bio_end;
1619 				submit_bio(cloned_bio->bi_rw, cloned_bio);
1620 			}
1621 			/*
1622 			 * Now we have to wait for all those smaller bios to
1623 			 * end, so we can also end the "parent" bio.
1624 			 */
1625 			continue;
1626 		}
1627 		/* We don't need to split this bio */
1628 		submit_bio(bio->bi_rw, bio);
1629 	}
1630 
1631 	return 0;
1632 }
1633 
1634 /**
1635  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1636  * driver restart.  We tear down our blkif structure and recreate it, but
1637  * leave the device-layer structures intact so that this is transparent to the
1638  * rest of the kernel.
1639  */
1640 static int blkfront_resume(struct xenbus_device *dev)
1641 {
1642 	struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1643 	int err;
1644 
1645 	dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
1646 
1647 	blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
1648 
1649 	err = talk_to_blkback(dev, info);
1650 
1651 	/*
1652 	 * We have to wait for the backend to switch to
1653 	 * connected state, since we want to read which
1654 	 * features it supports.
1655 	 */
1656 
1657 	return err;
1658 }
1659 
1660 static void
1661 blkfront_closing(struct blkfront_info *info)
1662 {
1663 	struct xenbus_device *xbdev = info->xbdev;
1664 	struct block_device *bdev = NULL;
1665 
1666 	mutex_lock(&info->mutex);
1667 
1668 	if (xbdev->state == XenbusStateClosing) {
1669 		mutex_unlock(&info->mutex);
1670 		return;
1671 	}
1672 
1673 	if (info->gd)
1674 		bdev = bdget_disk(info->gd, 0);
1675 
1676 	mutex_unlock(&info->mutex);
1677 
1678 	if (!bdev) {
1679 		xenbus_frontend_closed(xbdev);
1680 		return;
1681 	}
1682 
1683 	mutex_lock(&bdev->bd_mutex);
1684 
1685 	if (bdev->bd_openers) {
1686 		xenbus_dev_error(xbdev, -EBUSY,
1687 				 "Device in use; refusing to close");
1688 		xenbus_switch_state(xbdev, XenbusStateClosing);
1689 	} else {
1690 		xlvbd_release_gendisk(info);
1691 		xenbus_frontend_closed(xbdev);
1692 	}
1693 
1694 	mutex_unlock(&bdev->bd_mutex);
1695 	bdput(bdev);
1696 }
1697 
1698 static void blkfront_setup_discard(struct blkfront_info *info)
1699 {
1700 	int err;
1701 	unsigned int discard_granularity;
1702 	unsigned int discard_alignment;
1703 	unsigned int discard_secure;
1704 
1705 	info->feature_discard = 1;
1706 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1707 		"discard-granularity", "%u", &discard_granularity,
1708 		"discard-alignment", "%u", &discard_alignment,
1709 		NULL);
1710 	if (!err) {
1711 		info->discard_granularity = discard_granularity;
1712 		info->discard_alignment = discard_alignment;
1713 	}
1714 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1715 		    "discard-secure", "%d", &discard_secure,
1716 		    NULL);
1717 	if (!err)
1718 		info->feature_secdiscard = !!discard_secure;
1719 }
1720 
1721 static int blkfront_setup_indirect(struct blkfront_info *info)
1722 {
1723 	unsigned int segs;
1724 	int err, i;
1725 
1726 	if (info->max_indirect_segments == 0)
1727 		segs = BLKIF_MAX_SEGMENTS_PER_REQUEST;
1728 	else
1729 		segs = info->max_indirect_segments;
1730 
1731 	err = fill_grant_buffer(info, (segs + INDIRECT_GREFS(segs)) * BLK_RING_SIZE(info));
1732 	if (err)
1733 		goto out_of_memory;
1734 
1735 	if (!info->feature_persistent && info->max_indirect_segments) {
1736 		/*
1737 		 * We are using indirect descriptors but not persistent
1738 		 * grants, we need to allocate a set of pages that can be
1739 		 * used for mapping indirect grefs
1740 		 */
1741 		int num = INDIRECT_GREFS(segs) * BLK_RING_SIZE(info);
1742 
1743 		BUG_ON(!list_empty(&info->indirect_pages));
1744 		for (i = 0; i < num; i++) {
1745 			struct page *indirect_page = alloc_page(GFP_NOIO);
1746 			if (!indirect_page)
1747 				goto out_of_memory;
1748 			list_add(&indirect_page->lru, &info->indirect_pages);
1749 		}
1750 	}
1751 
1752 	for (i = 0; i < BLK_RING_SIZE(info); i++) {
1753 		info->shadow[i].grants_used = kzalloc(
1754 			sizeof(info->shadow[i].grants_used[0]) * segs,
1755 			GFP_NOIO);
1756 		info->shadow[i].sg = kzalloc(sizeof(info->shadow[i].sg[0]) * segs, GFP_NOIO);
1757 		if (info->max_indirect_segments)
1758 			info->shadow[i].indirect_grants = kzalloc(
1759 				sizeof(info->shadow[i].indirect_grants[0]) *
1760 				INDIRECT_GREFS(segs),
1761 				GFP_NOIO);
1762 		if ((info->shadow[i].grants_used == NULL) ||
1763 			(info->shadow[i].sg == NULL) ||
1764 		     (info->max_indirect_segments &&
1765 		     (info->shadow[i].indirect_grants == NULL)))
1766 			goto out_of_memory;
1767 		sg_init_table(info->shadow[i].sg, segs);
1768 	}
1769 
1770 
1771 	return 0;
1772 
1773 out_of_memory:
1774 	for (i = 0; i < BLK_RING_SIZE(info); i++) {
1775 		kfree(info->shadow[i].grants_used);
1776 		info->shadow[i].grants_used = NULL;
1777 		kfree(info->shadow[i].sg);
1778 		info->shadow[i].sg = NULL;
1779 		kfree(info->shadow[i].indirect_grants);
1780 		info->shadow[i].indirect_grants = NULL;
1781 	}
1782 	if (!list_empty(&info->indirect_pages)) {
1783 		struct page *indirect_page, *n;
1784 		list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
1785 			list_del(&indirect_page->lru);
1786 			__free_page(indirect_page);
1787 		}
1788 	}
1789 	return -ENOMEM;
1790 }
1791 
1792 /*
1793  * Gather all backend feature-*
1794  */
1795 static int blkfront_gather_backend_features(struct blkfront_info *info)
1796 {
1797 	int err;
1798 	int barrier, flush, discard, persistent;
1799 	unsigned int indirect_segments;
1800 
1801 	info->feature_flush = 0;
1802 
1803 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1804 			"feature-barrier", "%d", &barrier,
1805 			NULL);
1806 
1807 	/*
1808 	 * If there's no "feature-barrier" defined, then it means
1809 	 * we're dealing with a very old backend which writes
1810 	 * synchronously; nothing to do.
1811 	 *
1812 	 * If there are barriers, then we use flush.
1813 	 */
1814 	if (!err && barrier)
1815 		info->feature_flush = REQ_FLUSH | REQ_FUA;
1816 	/*
1817 	 * And if there is "feature-flush-cache" use that above
1818 	 * barriers.
1819 	 */
1820 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1821 			"feature-flush-cache", "%d", &flush,
1822 			NULL);
1823 
1824 	if (!err && flush)
1825 		info->feature_flush = REQ_FLUSH;
1826 
1827 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1828 			"feature-discard", "%d", &discard,
1829 			NULL);
1830 
1831 	if (!err && discard)
1832 		blkfront_setup_discard(info);
1833 
1834 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1835 			"feature-persistent", "%u", &persistent,
1836 			NULL);
1837 	if (err)
1838 		info->feature_persistent = 0;
1839 	else
1840 		info->feature_persistent = persistent;
1841 
1842 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1843 			    "feature-max-indirect-segments", "%u", &indirect_segments,
1844 			    NULL);
1845 	if (err)
1846 		info->max_indirect_segments = 0;
1847 	else
1848 		info->max_indirect_segments = min(indirect_segments,
1849 						  xen_blkif_max_segments);
1850 
1851 	return blkfront_setup_indirect(info);
1852 }
1853 
1854 /*
1855  * Invoked when the backend is finally 'ready' (and has told produced
1856  * the details about the physical device - #sectors, size, etc).
1857  */
1858 static void blkfront_connect(struct blkfront_info *info)
1859 {
1860 	unsigned long long sectors;
1861 	unsigned long sector_size;
1862 	unsigned int physical_sector_size;
1863 	unsigned int binfo;
1864 	int err;
1865 
1866 	switch (info->connected) {
1867 	case BLKIF_STATE_CONNECTED:
1868 		/*
1869 		 * Potentially, the back-end may be signalling
1870 		 * a capacity change; update the capacity.
1871 		 */
1872 		err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1873 				   "sectors", "%Lu", &sectors);
1874 		if (XENBUS_EXIST_ERR(err))
1875 			return;
1876 		printk(KERN_INFO "Setting capacity to %Lu\n",
1877 		       sectors);
1878 		set_capacity(info->gd, sectors);
1879 		revalidate_disk(info->gd);
1880 
1881 		return;
1882 	case BLKIF_STATE_SUSPENDED:
1883 		/*
1884 		 * If we are recovering from suspension, we need to wait
1885 		 * for the backend to announce it's features before
1886 		 * reconnecting, at least we need to know if the backend
1887 		 * supports indirect descriptors, and how many.
1888 		 */
1889 		blkif_recover(info);
1890 		return;
1891 
1892 	default:
1893 		break;
1894 	}
1895 
1896 	dev_dbg(&info->xbdev->dev, "%s:%s.\n",
1897 		__func__, info->xbdev->otherend);
1898 
1899 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1900 			    "sectors", "%llu", &sectors,
1901 			    "info", "%u", &binfo,
1902 			    "sector-size", "%lu", &sector_size,
1903 			    NULL);
1904 	if (err) {
1905 		xenbus_dev_fatal(info->xbdev, err,
1906 				 "reading backend fields at %s",
1907 				 info->xbdev->otherend);
1908 		return;
1909 	}
1910 
1911 	/*
1912 	 * physcial-sector-size is a newer field, so old backends may not
1913 	 * provide this. Assume physical sector size to be the same as
1914 	 * sector_size in that case.
1915 	 */
1916 	err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1917 			   "physical-sector-size", "%u", &physical_sector_size);
1918 	if (err != 1)
1919 		physical_sector_size = sector_size;
1920 
1921 	err = blkfront_gather_backend_features(info);
1922 	if (err) {
1923 		xenbus_dev_fatal(info->xbdev, err, "setup_indirect at %s",
1924 				 info->xbdev->otherend);
1925 		return;
1926 	}
1927 
1928 	err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size,
1929 				  physical_sector_size);
1930 	if (err) {
1931 		xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
1932 				 info->xbdev->otherend);
1933 		return;
1934 	}
1935 
1936 	xenbus_switch_state(info->xbdev, XenbusStateConnected);
1937 
1938 	/* Kick pending requests. */
1939 	spin_lock_irq(&info->io_lock);
1940 	info->connected = BLKIF_STATE_CONNECTED;
1941 	kick_pending_request_queues(info);
1942 	spin_unlock_irq(&info->io_lock);
1943 
1944 	add_disk(info->gd);
1945 
1946 	info->is_ready = 1;
1947 }
1948 
1949 /**
1950  * Callback received when the backend's state changes.
1951  */
1952 static void blkback_changed(struct xenbus_device *dev,
1953 			    enum xenbus_state backend_state)
1954 {
1955 	struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1956 
1957 	dev_dbg(&dev->dev, "blkfront:blkback_changed to state %d.\n", backend_state);
1958 
1959 	switch (backend_state) {
1960 	case XenbusStateInitWait:
1961 		if (dev->state != XenbusStateInitialising)
1962 			break;
1963 		if (talk_to_blkback(dev, info)) {
1964 			kfree(info);
1965 			dev_set_drvdata(&dev->dev, NULL);
1966 			break;
1967 		}
1968 	case XenbusStateInitialising:
1969 	case XenbusStateInitialised:
1970 	case XenbusStateReconfiguring:
1971 	case XenbusStateReconfigured:
1972 	case XenbusStateUnknown:
1973 		break;
1974 
1975 	case XenbusStateConnected:
1976 		blkfront_connect(info);
1977 		break;
1978 
1979 	case XenbusStateClosed:
1980 		if (dev->state == XenbusStateClosed)
1981 			break;
1982 		/* Missed the backend's Closing state -- fallthrough */
1983 	case XenbusStateClosing:
1984 		blkfront_closing(info);
1985 		break;
1986 	}
1987 }
1988 
1989 static int blkfront_remove(struct xenbus_device *xbdev)
1990 {
1991 	struct blkfront_info *info = dev_get_drvdata(&xbdev->dev);
1992 	struct block_device *bdev = NULL;
1993 	struct gendisk *disk;
1994 
1995 	dev_dbg(&xbdev->dev, "%s removed", xbdev->nodename);
1996 
1997 	blkif_free(info, 0);
1998 
1999 	mutex_lock(&info->mutex);
2000 
2001 	disk = info->gd;
2002 	if (disk)
2003 		bdev = bdget_disk(disk, 0);
2004 
2005 	info->xbdev = NULL;
2006 	mutex_unlock(&info->mutex);
2007 
2008 	if (!bdev) {
2009 		kfree(info);
2010 		return 0;
2011 	}
2012 
2013 	/*
2014 	 * The xbdev was removed before we reached the Closed
2015 	 * state. See if it's safe to remove the disk. If the bdev
2016 	 * isn't closed yet, we let release take care of it.
2017 	 */
2018 
2019 	mutex_lock(&bdev->bd_mutex);
2020 	info = disk->private_data;
2021 
2022 	dev_warn(disk_to_dev(disk),
2023 		 "%s was hot-unplugged, %d stale handles\n",
2024 		 xbdev->nodename, bdev->bd_openers);
2025 
2026 	if (info && !bdev->bd_openers) {
2027 		xlvbd_release_gendisk(info);
2028 		disk->private_data = NULL;
2029 		kfree(info);
2030 	}
2031 
2032 	mutex_unlock(&bdev->bd_mutex);
2033 	bdput(bdev);
2034 
2035 	return 0;
2036 }
2037 
2038 static int blkfront_is_ready(struct xenbus_device *dev)
2039 {
2040 	struct blkfront_info *info = dev_get_drvdata(&dev->dev);
2041 
2042 	return info->is_ready && info->xbdev;
2043 }
2044 
2045 static int blkif_open(struct block_device *bdev, fmode_t mode)
2046 {
2047 	struct gendisk *disk = bdev->bd_disk;
2048 	struct blkfront_info *info;
2049 	int err = 0;
2050 
2051 	mutex_lock(&blkfront_mutex);
2052 
2053 	info = disk->private_data;
2054 	if (!info) {
2055 		/* xbdev gone */
2056 		err = -ERESTARTSYS;
2057 		goto out;
2058 	}
2059 
2060 	mutex_lock(&info->mutex);
2061 
2062 	if (!info->gd)
2063 		/* xbdev is closed */
2064 		err = -ERESTARTSYS;
2065 
2066 	mutex_unlock(&info->mutex);
2067 
2068 out:
2069 	mutex_unlock(&blkfront_mutex);
2070 	return err;
2071 }
2072 
2073 static void blkif_release(struct gendisk *disk, fmode_t mode)
2074 {
2075 	struct blkfront_info *info = disk->private_data;
2076 	struct block_device *bdev;
2077 	struct xenbus_device *xbdev;
2078 
2079 	mutex_lock(&blkfront_mutex);
2080 
2081 	bdev = bdget_disk(disk, 0);
2082 
2083 	if (!bdev) {
2084 		WARN(1, "Block device %s yanked out from us!\n", disk->disk_name);
2085 		goto out_mutex;
2086 	}
2087 	if (bdev->bd_openers)
2088 		goto out;
2089 
2090 	/*
2091 	 * Check if we have been instructed to close. We will have
2092 	 * deferred this request, because the bdev was still open.
2093 	 */
2094 
2095 	mutex_lock(&info->mutex);
2096 	xbdev = info->xbdev;
2097 
2098 	if (xbdev && xbdev->state == XenbusStateClosing) {
2099 		/* pending switch to state closed */
2100 		dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2101 		xlvbd_release_gendisk(info);
2102 		xenbus_frontend_closed(info->xbdev);
2103  	}
2104 
2105 	mutex_unlock(&info->mutex);
2106 
2107 	if (!xbdev) {
2108 		/* sudden device removal */
2109 		dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2110 		xlvbd_release_gendisk(info);
2111 		disk->private_data = NULL;
2112 		kfree(info);
2113 	}
2114 
2115 out:
2116 	bdput(bdev);
2117 out_mutex:
2118 	mutex_unlock(&blkfront_mutex);
2119 }
2120 
2121 static const struct block_device_operations xlvbd_block_fops =
2122 {
2123 	.owner = THIS_MODULE,
2124 	.open = blkif_open,
2125 	.release = blkif_release,
2126 	.getgeo = blkif_getgeo,
2127 	.ioctl = blkif_ioctl,
2128 };
2129 
2130 
2131 static const struct xenbus_device_id blkfront_ids[] = {
2132 	{ "vbd" },
2133 	{ "" }
2134 };
2135 
2136 static struct xenbus_driver blkfront_driver = {
2137 	.ids  = blkfront_ids,
2138 	.probe = blkfront_probe,
2139 	.remove = blkfront_remove,
2140 	.resume = blkfront_resume,
2141 	.otherend_changed = blkback_changed,
2142 	.is_ready = blkfront_is_ready,
2143 };
2144 
2145 static int __init xlblk_init(void)
2146 {
2147 	int ret;
2148 
2149 	if (!xen_domain())
2150 		return -ENODEV;
2151 
2152 	if (xen_blkif_max_ring_order > XENBUS_MAX_RING_PAGE_ORDER) {
2153 		pr_info("Invalid max_ring_order (%d), will use default max: %d.\n",
2154 			xen_blkif_max_ring_order, XENBUS_MAX_RING_PAGE_ORDER);
2155 		xen_blkif_max_ring_order = 0;
2156 	}
2157 
2158 	if (!xen_has_pv_disk_devices())
2159 		return -ENODEV;
2160 
2161 	if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
2162 		printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
2163 		       XENVBD_MAJOR, DEV_NAME);
2164 		return -ENODEV;
2165 	}
2166 
2167 	ret = xenbus_register_frontend(&blkfront_driver);
2168 	if (ret) {
2169 		unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2170 		return ret;
2171 	}
2172 
2173 	return 0;
2174 }
2175 module_init(xlblk_init);
2176 
2177 
2178 static void __exit xlblk_exit(void)
2179 {
2180 	xenbus_unregister_driver(&blkfront_driver);
2181 	unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2182 	kfree(minors);
2183 }
2184 module_exit(xlblk_exit);
2185 
2186 MODULE_DESCRIPTION("Xen virtual block device frontend");
2187 MODULE_LICENSE("GPL");
2188 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
2189 MODULE_ALIAS("xen:vbd");
2190 MODULE_ALIAS("xenblk");
2191