xref: /openbmc/linux/drivers/block/xen-blkfront.c (revision 545e4006)
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 
44 #include <xen/xenbus.h>
45 #include <xen/grant_table.h>
46 #include <xen/events.h>
47 #include <xen/page.h>
48 
49 #include <xen/interface/grant_table.h>
50 #include <xen/interface/io/blkif.h>
51 #include <xen/interface/io/protocols.h>
52 
53 #include <asm/xen/hypervisor.h>
54 
55 enum blkif_state {
56 	BLKIF_STATE_DISCONNECTED,
57 	BLKIF_STATE_CONNECTED,
58 	BLKIF_STATE_SUSPENDED,
59 };
60 
61 struct blk_shadow {
62 	struct blkif_request req;
63 	unsigned long request;
64 	unsigned long frame[BLKIF_MAX_SEGMENTS_PER_REQUEST];
65 };
66 
67 static struct block_device_operations xlvbd_block_fops;
68 
69 #define BLK_RING_SIZE __RING_SIZE((struct blkif_sring *)0, PAGE_SIZE)
70 
71 /*
72  * We have one of these per vbd, whether ide, scsi or 'other'.  They
73  * hang in private_data off the gendisk structure. We may end up
74  * putting all kinds of interesting stuff here :-)
75  */
76 struct blkfront_info
77 {
78 	struct xenbus_device *xbdev;
79 	struct gendisk *gd;
80 	int vdevice;
81 	blkif_vdev_t handle;
82 	enum blkif_state connected;
83 	int ring_ref;
84 	struct blkif_front_ring ring;
85 	unsigned int evtchn, irq;
86 	struct request_queue *rq;
87 	struct work_struct work;
88 	struct gnttab_free_callback callback;
89 	struct blk_shadow shadow[BLK_RING_SIZE];
90 	unsigned long shadow_free;
91 	int feature_barrier;
92 	int is_ready;
93 
94 	/**
95 	 * The number of people holding this device open.  We won't allow a
96 	 * hot-unplug unless this is 0.
97 	 */
98 	int users;
99 };
100 
101 static DEFINE_SPINLOCK(blkif_io_lock);
102 
103 #define MAXIMUM_OUTSTANDING_BLOCK_REQS \
104 	(BLKIF_MAX_SEGMENTS_PER_REQUEST * BLK_RING_SIZE)
105 #define GRANT_INVALID_REF	0
106 
107 #define PARTS_PER_DISK		16
108 
109 #define BLKIF_MAJOR(dev) ((dev)>>8)
110 #define BLKIF_MINOR(dev) ((dev) & 0xff)
111 
112 #define DEV_NAME	"xvd"	/* name in /dev */
113 
114 /* Information about our VBDs. */
115 #define MAX_VBDS 64
116 static LIST_HEAD(vbds_list);
117 
118 static int get_id_from_freelist(struct blkfront_info *info)
119 {
120 	unsigned long free = info->shadow_free;
121 	BUG_ON(free > BLK_RING_SIZE);
122 	info->shadow_free = info->shadow[free].req.id;
123 	info->shadow[free].req.id = 0x0fffffee; /* debug */
124 	return free;
125 }
126 
127 static void add_id_to_freelist(struct blkfront_info *info,
128 			       unsigned long id)
129 {
130 	info->shadow[id].req.id  = info->shadow_free;
131 	info->shadow[id].request = 0;
132 	info->shadow_free = id;
133 }
134 
135 static void blkif_restart_queue_callback(void *arg)
136 {
137 	struct blkfront_info *info = (struct blkfront_info *)arg;
138 	schedule_work(&info->work);
139 }
140 
141 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
142 {
143 	/* We don't have real geometry info, but let's at least return
144 	   values consistent with the size of the device */
145 	sector_t nsect = get_capacity(bd->bd_disk);
146 	sector_t cylinders = nsect;
147 
148 	hg->heads = 0xff;
149 	hg->sectors = 0x3f;
150 	sector_div(cylinders, hg->heads * hg->sectors);
151 	hg->cylinders = cylinders;
152 	if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
153 		hg->cylinders = 0xffff;
154 	return 0;
155 }
156 
157 int blkif_ioctl(struct inode *inode, struct file *filep,
158 		unsigned command, unsigned long argument)
159 {
160 	struct blkfront_info *info =
161 		inode->i_bdev->bd_disk->private_data;
162 	int i;
163 
164 	dev_dbg(&info->xbdev->dev, "command: 0x%x, argument: 0x%lx\n",
165 		command, (long)argument);
166 
167 	switch (command) {
168 	case CDROMMULTISESSION:
169 		dev_dbg(&info->xbdev->dev, "FIXME: support multisession CDs later\n");
170 		for (i = 0; i < sizeof(struct cdrom_multisession); i++)
171 			if (put_user(0, (char __user *)(argument + i)))
172 				return -EFAULT;
173 		return 0;
174 
175 	case CDROM_GET_CAPABILITY: {
176 		struct gendisk *gd = info->gd;
177 		if (gd->flags & GENHD_FL_CD)
178 			return 0;
179 		return -EINVAL;
180 	}
181 
182 	default:
183 		/*printk(KERN_ALERT "ioctl %08x not supported by Xen blkdev\n",
184 		  command);*/
185 		return -EINVAL; /* same return as native Linux */
186 	}
187 
188 	return 0;
189 }
190 
191 /*
192  * blkif_queue_request
193  *
194  * request block io
195  *
196  * id: for guest use only.
197  * operation: BLKIF_OP_{READ,WRITE,PROBE}
198  * buffer: buffer to read/write into. this should be a
199  *   virtual address in the guest os.
200  */
201 static int blkif_queue_request(struct request *req)
202 {
203 	struct blkfront_info *info = req->rq_disk->private_data;
204 	unsigned long buffer_mfn;
205 	struct blkif_request *ring_req;
206 	struct req_iterator iter;
207 	struct bio_vec *bvec;
208 	unsigned long id;
209 	unsigned int fsect, lsect;
210 	int ref;
211 	grant_ref_t gref_head;
212 
213 	if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
214 		return 1;
215 
216 	if (gnttab_alloc_grant_references(
217 		BLKIF_MAX_SEGMENTS_PER_REQUEST, &gref_head) < 0) {
218 		gnttab_request_free_callback(
219 			&info->callback,
220 			blkif_restart_queue_callback,
221 			info,
222 			BLKIF_MAX_SEGMENTS_PER_REQUEST);
223 		return 1;
224 	}
225 
226 	/* Fill out a communications ring structure. */
227 	ring_req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
228 	id = get_id_from_freelist(info);
229 	info->shadow[id].request = (unsigned long)req;
230 
231 	ring_req->id = id;
232 	ring_req->sector_number = (blkif_sector_t)req->sector;
233 	ring_req->handle = info->handle;
234 
235 	ring_req->operation = rq_data_dir(req) ?
236 		BLKIF_OP_WRITE : BLKIF_OP_READ;
237 	if (blk_barrier_rq(req))
238 		ring_req->operation = BLKIF_OP_WRITE_BARRIER;
239 
240 	ring_req->nr_segments = 0;
241 	rq_for_each_segment(bvec, req, iter) {
242 		BUG_ON(ring_req->nr_segments == BLKIF_MAX_SEGMENTS_PER_REQUEST);
243 		buffer_mfn = pfn_to_mfn(page_to_pfn(bvec->bv_page));
244 		fsect = bvec->bv_offset >> 9;
245 		lsect = fsect + (bvec->bv_len >> 9) - 1;
246 		/* install a grant reference. */
247 		ref = gnttab_claim_grant_reference(&gref_head);
248 		BUG_ON(ref == -ENOSPC);
249 
250 		gnttab_grant_foreign_access_ref(
251 				ref,
252 				info->xbdev->otherend_id,
253 				buffer_mfn,
254 				rq_data_dir(req) );
255 
256 		info->shadow[id].frame[ring_req->nr_segments] =
257 				mfn_to_pfn(buffer_mfn);
258 
259 		ring_req->seg[ring_req->nr_segments] =
260 				(struct blkif_request_segment) {
261 					.gref       = ref,
262 					.first_sect = fsect,
263 					.last_sect  = lsect };
264 
265 		ring_req->nr_segments++;
266 	}
267 
268 	info->ring.req_prod_pvt++;
269 
270 	/* Keep a private copy so we can reissue requests when recovering. */
271 	info->shadow[id].req = *ring_req;
272 
273 	gnttab_free_grant_references(gref_head);
274 
275 	return 0;
276 }
277 
278 
279 static inline void flush_requests(struct blkfront_info *info)
280 {
281 	int notify;
282 
283 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
284 
285 	if (notify)
286 		notify_remote_via_irq(info->irq);
287 }
288 
289 /*
290  * do_blkif_request
291  *  read a block; request is in a request queue
292  */
293 static void do_blkif_request(struct request_queue *rq)
294 {
295 	struct blkfront_info *info = NULL;
296 	struct request *req;
297 	int queued;
298 
299 	pr_debug("Entered do_blkif_request\n");
300 
301 	queued = 0;
302 
303 	while ((req = elv_next_request(rq)) != NULL) {
304 		info = req->rq_disk->private_data;
305 		if (!blk_fs_request(req)) {
306 			end_request(req, 0);
307 			continue;
308 		}
309 
310 		if (RING_FULL(&info->ring))
311 			goto wait;
312 
313 		pr_debug("do_blk_req %p: cmd %p, sec %lx, "
314 			 "(%u/%li) buffer:%p [%s]\n",
315 			 req, req->cmd, (unsigned long)req->sector,
316 			 req->current_nr_sectors,
317 			 req->nr_sectors, req->buffer,
318 			 rq_data_dir(req) ? "write" : "read");
319 
320 
321 		blkdev_dequeue_request(req);
322 		if (blkif_queue_request(req)) {
323 			blk_requeue_request(rq, req);
324 wait:
325 			/* Avoid pointless unplugs. */
326 			blk_stop_queue(rq);
327 			break;
328 		}
329 
330 		queued++;
331 	}
332 
333 	if (queued != 0)
334 		flush_requests(info);
335 }
336 
337 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size)
338 {
339 	struct request_queue *rq;
340 
341 	rq = blk_init_queue(do_blkif_request, &blkif_io_lock);
342 	if (rq == NULL)
343 		return -1;
344 
345 	elevator_init(rq, "noop");
346 
347 	/* Hard sector size and max sectors impersonate the equiv. hardware. */
348 	blk_queue_hardsect_size(rq, sector_size);
349 	blk_queue_max_sectors(rq, 512);
350 
351 	/* Each segment in a request is up to an aligned page in size. */
352 	blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
353 	blk_queue_max_segment_size(rq, PAGE_SIZE);
354 
355 	/* Ensure a merged request will fit in a single I/O ring slot. */
356 	blk_queue_max_phys_segments(rq, BLKIF_MAX_SEGMENTS_PER_REQUEST);
357 	blk_queue_max_hw_segments(rq, BLKIF_MAX_SEGMENTS_PER_REQUEST);
358 
359 	/* Make sure buffer addresses are sector-aligned. */
360 	blk_queue_dma_alignment(rq, 511);
361 
362 	/* Make sure we don't use bounce buffers. */
363 	blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
364 
365 	gd->queue = rq;
366 
367 	return 0;
368 }
369 
370 
371 static int xlvbd_barrier(struct blkfront_info *info)
372 {
373 	int err;
374 
375 	err = blk_queue_ordered(info->rq,
376 				info->feature_barrier ? QUEUE_ORDERED_DRAIN : QUEUE_ORDERED_NONE,
377 				NULL);
378 
379 	if (err)
380 		return err;
381 
382 	printk(KERN_INFO "blkfront: %s: barriers %s\n",
383 	       info->gd->disk_name,
384 	       info->feature_barrier ? "enabled" : "disabled");
385 	return 0;
386 }
387 
388 
389 static int xlvbd_alloc_gendisk(int minor, blkif_sector_t capacity,
390 			       int vdevice, u16 vdisk_info, u16 sector_size,
391 			       struct blkfront_info *info)
392 {
393 	struct gendisk *gd;
394 	int nr_minors = 1;
395 	int err = -ENODEV;
396 
397 	BUG_ON(info->gd != NULL);
398 	BUG_ON(info->rq != NULL);
399 
400 	if ((minor % PARTS_PER_DISK) == 0)
401 		nr_minors = PARTS_PER_DISK;
402 
403 	gd = alloc_disk(nr_minors);
404 	if (gd == NULL)
405 		goto out;
406 
407 	if (nr_minors > 1)
408 		sprintf(gd->disk_name, "%s%c", DEV_NAME,
409 			'a' + minor / PARTS_PER_DISK);
410 	else
411 		sprintf(gd->disk_name, "%s%c%d", DEV_NAME,
412 			'a' + minor / PARTS_PER_DISK,
413 			minor % PARTS_PER_DISK);
414 
415 	gd->major = XENVBD_MAJOR;
416 	gd->first_minor = minor;
417 	gd->fops = &xlvbd_block_fops;
418 	gd->private_data = info;
419 	gd->driverfs_dev = &(info->xbdev->dev);
420 	set_capacity(gd, capacity);
421 
422 	if (xlvbd_init_blk_queue(gd, sector_size)) {
423 		del_gendisk(gd);
424 		goto out;
425 	}
426 
427 	info->rq = gd->queue;
428 	info->gd = gd;
429 
430 	if (info->feature_barrier)
431 		xlvbd_barrier(info);
432 
433 	if (vdisk_info & VDISK_READONLY)
434 		set_disk_ro(gd, 1);
435 
436 	if (vdisk_info & VDISK_REMOVABLE)
437 		gd->flags |= GENHD_FL_REMOVABLE;
438 
439 	if (vdisk_info & VDISK_CDROM)
440 		gd->flags |= GENHD_FL_CD;
441 
442 	return 0;
443 
444  out:
445 	return err;
446 }
447 
448 static void kick_pending_request_queues(struct blkfront_info *info)
449 {
450 	if (!RING_FULL(&info->ring)) {
451 		/* Re-enable calldowns. */
452 		blk_start_queue(info->rq);
453 		/* Kick things off immediately. */
454 		do_blkif_request(info->rq);
455 	}
456 }
457 
458 static void blkif_restart_queue(struct work_struct *work)
459 {
460 	struct blkfront_info *info = container_of(work, struct blkfront_info, work);
461 
462 	spin_lock_irq(&blkif_io_lock);
463 	if (info->connected == BLKIF_STATE_CONNECTED)
464 		kick_pending_request_queues(info);
465 	spin_unlock_irq(&blkif_io_lock);
466 }
467 
468 static void blkif_free(struct blkfront_info *info, int suspend)
469 {
470 	/* Prevent new requests being issued until we fix things up. */
471 	spin_lock_irq(&blkif_io_lock);
472 	info->connected = suspend ?
473 		BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
474 	/* No more blkif_request(). */
475 	if (info->rq)
476 		blk_stop_queue(info->rq);
477 	/* No more gnttab callback work. */
478 	gnttab_cancel_free_callback(&info->callback);
479 	spin_unlock_irq(&blkif_io_lock);
480 
481 	/* Flush gnttab callback work. Must be done with no locks held. */
482 	flush_scheduled_work();
483 
484 	/* Free resources associated with old device channel. */
485 	if (info->ring_ref != GRANT_INVALID_REF) {
486 		gnttab_end_foreign_access(info->ring_ref, 0,
487 					  (unsigned long)info->ring.sring);
488 		info->ring_ref = GRANT_INVALID_REF;
489 		info->ring.sring = NULL;
490 	}
491 	if (info->irq)
492 		unbind_from_irqhandler(info->irq, info);
493 	info->evtchn = info->irq = 0;
494 
495 }
496 
497 static void blkif_completion(struct blk_shadow *s)
498 {
499 	int i;
500 	for (i = 0; i < s->req.nr_segments; i++)
501 		gnttab_end_foreign_access(s->req.seg[i].gref, 0, 0UL);
502 }
503 
504 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
505 {
506 	struct request *req;
507 	struct blkif_response *bret;
508 	RING_IDX i, rp;
509 	unsigned long flags;
510 	struct blkfront_info *info = (struct blkfront_info *)dev_id;
511 	int error;
512 
513 	spin_lock_irqsave(&blkif_io_lock, flags);
514 
515 	if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
516 		spin_unlock_irqrestore(&blkif_io_lock, flags);
517 		return IRQ_HANDLED;
518 	}
519 
520  again:
521 	rp = info->ring.sring->rsp_prod;
522 	rmb(); /* Ensure we see queued responses up to 'rp'. */
523 
524 	for (i = info->ring.rsp_cons; i != rp; i++) {
525 		unsigned long id;
526 		int ret;
527 
528 		bret = RING_GET_RESPONSE(&info->ring, i);
529 		id   = bret->id;
530 		req  = (struct request *)info->shadow[id].request;
531 
532 		blkif_completion(&info->shadow[id]);
533 
534 		add_id_to_freelist(info, id);
535 
536 		error = (bret->status == BLKIF_RSP_OKAY) ? 0 : -EIO;
537 		switch (bret->operation) {
538 		case BLKIF_OP_WRITE_BARRIER:
539 			if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
540 				printk(KERN_WARNING "blkfront: %s: write barrier op failed\n",
541 				       info->gd->disk_name);
542 				error = -EOPNOTSUPP;
543 				info->feature_barrier = 0;
544 				xlvbd_barrier(info);
545 			}
546 			/* fall through */
547 		case BLKIF_OP_READ:
548 		case BLKIF_OP_WRITE:
549 			if (unlikely(bret->status != BLKIF_RSP_OKAY))
550 				dev_dbg(&info->xbdev->dev, "Bad return from blkdev data "
551 					"request: %x\n", bret->status);
552 
553 			ret = __blk_end_request(req, error, blk_rq_bytes(req));
554 			BUG_ON(ret);
555 			break;
556 		default:
557 			BUG();
558 		}
559 	}
560 
561 	info->ring.rsp_cons = i;
562 
563 	if (i != info->ring.req_prod_pvt) {
564 		int more_to_do;
565 		RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
566 		if (more_to_do)
567 			goto again;
568 	} else
569 		info->ring.sring->rsp_event = i + 1;
570 
571 	kick_pending_request_queues(info);
572 
573 	spin_unlock_irqrestore(&blkif_io_lock, flags);
574 
575 	return IRQ_HANDLED;
576 }
577 
578 
579 static int setup_blkring(struct xenbus_device *dev,
580 			 struct blkfront_info *info)
581 {
582 	struct blkif_sring *sring;
583 	int err;
584 
585 	info->ring_ref = GRANT_INVALID_REF;
586 
587 	sring = (struct blkif_sring *)__get_free_page(GFP_NOIO | __GFP_HIGH);
588 	if (!sring) {
589 		xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
590 		return -ENOMEM;
591 	}
592 	SHARED_RING_INIT(sring);
593 	FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
594 
595 	err = xenbus_grant_ring(dev, virt_to_mfn(info->ring.sring));
596 	if (err < 0) {
597 		free_page((unsigned long)sring);
598 		info->ring.sring = NULL;
599 		goto fail;
600 	}
601 	info->ring_ref = err;
602 
603 	err = xenbus_alloc_evtchn(dev, &info->evtchn);
604 	if (err)
605 		goto fail;
606 
607 	err = bind_evtchn_to_irqhandler(info->evtchn,
608 					blkif_interrupt,
609 					IRQF_SAMPLE_RANDOM, "blkif", info);
610 	if (err <= 0) {
611 		xenbus_dev_fatal(dev, err,
612 				 "bind_evtchn_to_irqhandler failed");
613 		goto fail;
614 	}
615 	info->irq = err;
616 
617 	return 0;
618 fail:
619 	blkif_free(info, 0);
620 	return err;
621 }
622 
623 
624 /* Common code used when first setting up, and when resuming. */
625 static int talk_to_backend(struct xenbus_device *dev,
626 			   struct blkfront_info *info)
627 {
628 	const char *message = NULL;
629 	struct xenbus_transaction xbt;
630 	int err;
631 
632 	/* Create shared ring, alloc event channel. */
633 	err = setup_blkring(dev, info);
634 	if (err)
635 		goto out;
636 
637 again:
638 	err = xenbus_transaction_start(&xbt);
639 	if (err) {
640 		xenbus_dev_fatal(dev, err, "starting transaction");
641 		goto destroy_blkring;
642 	}
643 
644 	err = xenbus_printf(xbt, dev->nodename,
645 			    "ring-ref", "%u", info->ring_ref);
646 	if (err) {
647 		message = "writing ring-ref";
648 		goto abort_transaction;
649 	}
650 	err = xenbus_printf(xbt, dev->nodename,
651 			    "event-channel", "%u", info->evtchn);
652 	if (err) {
653 		message = "writing event-channel";
654 		goto abort_transaction;
655 	}
656 	err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
657 			    XEN_IO_PROTO_ABI_NATIVE);
658 	if (err) {
659 		message = "writing protocol";
660 		goto abort_transaction;
661 	}
662 
663 	err = xenbus_transaction_end(xbt, 0);
664 	if (err) {
665 		if (err == -EAGAIN)
666 			goto again;
667 		xenbus_dev_fatal(dev, err, "completing transaction");
668 		goto destroy_blkring;
669 	}
670 
671 	xenbus_switch_state(dev, XenbusStateInitialised);
672 
673 	return 0;
674 
675  abort_transaction:
676 	xenbus_transaction_end(xbt, 1);
677 	if (message)
678 		xenbus_dev_fatal(dev, err, "%s", message);
679  destroy_blkring:
680 	blkif_free(info, 0);
681  out:
682 	return err;
683 }
684 
685 
686 /**
687  * Entry point to this code when a new device is created.  Allocate the basic
688  * structures and the ring buffer for communication with the backend, and
689  * inform the backend of the appropriate details for those.  Switch to
690  * Initialised state.
691  */
692 static int blkfront_probe(struct xenbus_device *dev,
693 			  const struct xenbus_device_id *id)
694 {
695 	int err, vdevice, i;
696 	struct blkfront_info *info;
697 
698 	/* FIXME: Use dynamic device id if this is not set. */
699 	err = xenbus_scanf(XBT_NIL, dev->nodename,
700 			   "virtual-device", "%i", &vdevice);
701 	if (err != 1) {
702 		xenbus_dev_fatal(dev, err, "reading virtual-device");
703 		return err;
704 	}
705 
706 	info = kzalloc(sizeof(*info), GFP_KERNEL);
707 	if (!info) {
708 		xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
709 		return -ENOMEM;
710 	}
711 
712 	info->xbdev = dev;
713 	info->vdevice = vdevice;
714 	info->connected = BLKIF_STATE_DISCONNECTED;
715 	INIT_WORK(&info->work, blkif_restart_queue);
716 
717 	for (i = 0; i < BLK_RING_SIZE; i++)
718 		info->shadow[i].req.id = i+1;
719 	info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
720 
721 	/* Front end dir is a number, which is used as the id. */
722 	info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
723 	dev->dev.driver_data = info;
724 
725 	err = talk_to_backend(dev, info);
726 	if (err) {
727 		kfree(info);
728 		dev->dev.driver_data = NULL;
729 		return err;
730 	}
731 
732 	return 0;
733 }
734 
735 
736 static int blkif_recover(struct blkfront_info *info)
737 {
738 	int i;
739 	struct blkif_request *req;
740 	struct blk_shadow *copy;
741 	int j;
742 
743 	/* Stage 1: Make a safe copy of the shadow state. */
744 	copy = kmalloc(sizeof(info->shadow),
745 		       GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
746 	if (!copy)
747 		return -ENOMEM;
748 	memcpy(copy, info->shadow, sizeof(info->shadow));
749 
750 	/* Stage 2: Set up free list. */
751 	memset(&info->shadow, 0, sizeof(info->shadow));
752 	for (i = 0; i < BLK_RING_SIZE; i++)
753 		info->shadow[i].req.id = i+1;
754 	info->shadow_free = info->ring.req_prod_pvt;
755 	info->shadow[BLK_RING_SIZE-1].req.id = 0x0fffffff;
756 
757 	/* Stage 3: Find pending requests and requeue them. */
758 	for (i = 0; i < BLK_RING_SIZE; i++) {
759 		/* Not in use? */
760 		if (copy[i].request == 0)
761 			continue;
762 
763 		/* Grab a request slot and copy shadow state into it. */
764 		req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
765 		*req = copy[i].req;
766 
767 		/* We get a new request id, and must reset the shadow state. */
768 		req->id = get_id_from_freelist(info);
769 		memcpy(&info->shadow[req->id], &copy[i], sizeof(copy[i]));
770 
771 		/* Rewrite any grant references invalidated by susp/resume. */
772 		for (j = 0; j < req->nr_segments; j++)
773 			gnttab_grant_foreign_access_ref(
774 				req->seg[j].gref,
775 				info->xbdev->otherend_id,
776 				pfn_to_mfn(info->shadow[req->id].frame[j]),
777 				rq_data_dir(
778 					(struct request *)
779 					info->shadow[req->id].request));
780 		info->shadow[req->id].req = *req;
781 
782 		info->ring.req_prod_pvt++;
783 	}
784 
785 	kfree(copy);
786 
787 	xenbus_switch_state(info->xbdev, XenbusStateConnected);
788 
789 	spin_lock_irq(&blkif_io_lock);
790 
791 	/* Now safe for us to use the shared ring */
792 	info->connected = BLKIF_STATE_CONNECTED;
793 
794 	/* Send off requeued requests */
795 	flush_requests(info);
796 
797 	/* Kick any other new requests queued since we resumed */
798 	kick_pending_request_queues(info);
799 
800 	spin_unlock_irq(&blkif_io_lock);
801 
802 	return 0;
803 }
804 
805 /**
806  * We are reconnecting to the backend, due to a suspend/resume, or a backend
807  * driver restart.  We tear down our blkif structure and recreate it, but
808  * leave the device-layer structures intact so that this is transparent to the
809  * rest of the kernel.
810  */
811 static int blkfront_resume(struct xenbus_device *dev)
812 {
813 	struct blkfront_info *info = dev->dev.driver_data;
814 	int err;
815 
816 	dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
817 
818 	blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
819 
820 	err = talk_to_backend(dev, info);
821 	if (info->connected == BLKIF_STATE_SUSPENDED && !err)
822 		err = blkif_recover(info);
823 
824 	return err;
825 }
826 
827 
828 /*
829  * Invoked when the backend is finally 'ready' (and has told produced
830  * the details about the physical device - #sectors, size, etc).
831  */
832 static void blkfront_connect(struct blkfront_info *info)
833 {
834 	unsigned long long sectors;
835 	unsigned long sector_size;
836 	unsigned int binfo;
837 	int err;
838 
839 	if ((info->connected == BLKIF_STATE_CONNECTED) ||
840 	    (info->connected == BLKIF_STATE_SUSPENDED) )
841 		return;
842 
843 	dev_dbg(&info->xbdev->dev, "%s:%s.\n",
844 		__func__, info->xbdev->otherend);
845 
846 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
847 			    "sectors", "%llu", &sectors,
848 			    "info", "%u", &binfo,
849 			    "sector-size", "%lu", &sector_size,
850 			    NULL);
851 	if (err) {
852 		xenbus_dev_fatal(info->xbdev, err,
853 				 "reading backend fields at %s",
854 				 info->xbdev->otherend);
855 		return;
856 	}
857 
858 	err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
859 			    "feature-barrier", "%lu", &info->feature_barrier,
860 			    NULL);
861 	if (err)
862 		info->feature_barrier = 0;
863 
864 	err = xlvbd_alloc_gendisk(BLKIF_MINOR(info->vdevice),
865 				  sectors, info->vdevice,
866 				  binfo, sector_size, info);
867 	if (err) {
868 		xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
869 				 info->xbdev->otherend);
870 		return;
871 	}
872 
873 	xenbus_switch_state(info->xbdev, XenbusStateConnected);
874 
875 	/* Kick pending requests. */
876 	spin_lock_irq(&blkif_io_lock);
877 	info->connected = BLKIF_STATE_CONNECTED;
878 	kick_pending_request_queues(info);
879 	spin_unlock_irq(&blkif_io_lock);
880 
881 	add_disk(info->gd);
882 
883 	info->is_ready = 1;
884 }
885 
886 /**
887  * Handle the change of state of the backend to Closing.  We must delete our
888  * device-layer structures now, to ensure that writes are flushed through to
889  * the backend.  Once is this done, we can switch to Closed in
890  * acknowledgement.
891  */
892 static void blkfront_closing(struct xenbus_device *dev)
893 {
894 	struct blkfront_info *info = dev->dev.driver_data;
895 	unsigned long flags;
896 
897 	dev_dbg(&dev->dev, "blkfront_closing: %s removed\n", dev->nodename);
898 
899 	if (info->rq == NULL)
900 		goto out;
901 
902 	spin_lock_irqsave(&blkif_io_lock, flags);
903 
904 	del_gendisk(info->gd);
905 
906 	/* No more blkif_request(). */
907 	blk_stop_queue(info->rq);
908 
909 	/* No more gnttab callback work. */
910 	gnttab_cancel_free_callback(&info->callback);
911 	spin_unlock_irqrestore(&blkif_io_lock, flags);
912 
913 	/* Flush gnttab callback work. Must be done with no locks held. */
914 	flush_scheduled_work();
915 
916 	blk_cleanup_queue(info->rq);
917 	info->rq = NULL;
918 
919  out:
920 	xenbus_frontend_closed(dev);
921 }
922 
923 /**
924  * Callback received when the backend's state changes.
925  */
926 static void backend_changed(struct xenbus_device *dev,
927 			    enum xenbus_state backend_state)
928 {
929 	struct blkfront_info *info = dev->dev.driver_data;
930 	struct block_device *bd;
931 
932 	dev_dbg(&dev->dev, "blkfront:backend_changed.\n");
933 
934 	switch (backend_state) {
935 	case XenbusStateInitialising:
936 	case XenbusStateInitWait:
937 	case XenbusStateInitialised:
938 	case XenbusStateUnknown:
939 	case XenbusStateClosed:
940 		break;
941 
942 	case XenbusStateConnected:
943 		blkfront_connect(info);
944 		break;
945 
946 	case XenbusStateClosing:
947 		bd = bdget_disk(info->gd, 0);
948 		if (bd == NULL)
949 			xenbus_dev_fatal(dev, -ENODEV, "bdget failed");
950 
951 		mutex_lock(&bd->bd_mutex);
952 		if (info->users > 0)
953 			xenbus_dev_error(dev, -EBUSY,
954 					 "Device in use; refusing to close");
955 		else
956 			blkfront_closing(dev);
957 		mutex_unlock(&bd->bd_mutex);
958 		bdput(bd);
959 		break;
960 	}
961 }
962 
963 static int blkfront_remove(struct xenbus_device *dev)
964 {
965 	struct blkfront_info *info = dev->dev.driver_data;
966 
967 	dev_dbg(&dev->dev, "blkfront_remove: %s removed\n", dev->nodename);
968 
969 	blkif_free(info, 0);
970 
971 	kfree(info);
972 
973 	return 0;
974 }
975 
976 static int blkfront_is_ready(struct xenbus_device *dev)
977 {
978 	struct blkfront_info *info = dev->dev.driver_data;
979 
980 	return info->is_ready;
981 }
982 
983 static int blkif_open(struct inode *inode, struct file *filep)
984 {
985 	struct blkfront_info *info = inode->i_bdev->bd_disk->private_data;
986 	info->users++;
987 	return 0;
988 }
989 
990 static int blkif_release(struct inode *inode, struct file *filep)
991 {
992 	struct blkfront_info *info = inode->i_bdev->bd_disk->private_data;
993 	info->users--;
994 	if (info->users == 0) {
995 		/* Check whether we have been instructed to close.  We will
996 		   have ignored this request initially, as the device was
997 		   still mounted. */
998 		struct xenbus_device *dev = info->xbdev;
999 		enum xenbus_state state = xenbus_read_driver_state(dev->otherend);
1000 
1001 		if (state == XenbusStateClosing && info->is_ready)
1002 			blkfront_closing(dev);
1003 	}
1004 	return 0;
1005 }
1006 
1007 static struct block_device_operations xlvbd_block_fops =
1008 {
1009 	.owner = THIS_MODULE,
1010 	.open = blkif_open,
1011 	.release = blkif_release,
1012 	.getgeo = blkif_getgeo,
1013 	.ioctl = blkif_ioctl,
1014 };
1015 
1016 
1017 static struct xenbus_device_id blkfront_ids[] = {
1018 	{ "vbd" },
1019 	{ "" }
1020 };
1021 
1022 static struct xenbus_driver blkfront = {
1023 	.name = "vbd",
1024 	.owner = THIS_MODULE,
1025 	.ids = blkfront_ids,
1026 	.probe = blkfront_probe,
1027 	.remove = blkfront_remove,
1028 	.resume = blkfront_resume,
1029 	.otherend_changed = backend_changed,
1030 	.is_ready = blkfront_is_ready,
1031 };
1032 
1033 static int __init xlblk_init(void)
1034 {
1035 	if (!is_running_on_xen())
1036 		return -ENODEV;
1037 
1038 	if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
1039 		printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
1040 		       XENVBD_MAJOR, DEV_NAME);
1041 		return -ENODEV;
1042 	}
1043 
1044 	return xenbus_register_frontend(&blkfront);
1045 }
1046 module_init(xlblk_init);
1047 
1048 
1049 static void __exit xlblk_exit(void)
1050 {
1051 	return xenbus_unregister_driver(&blkfront);
1052 }
1053 module_exit(xlblk_exit);
1054 
1055 MODULE_DESCRIPTION("Xen virtual block device frontend");
1056 MODULE_LICENSE("GPL");
1057 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
1058 MODULE_ALIAS("xen:vbd");
1059 MODULE_ALIAS("xenblk");
1060