1 /*  Xenbus code for blkif backend
2     Copyright (C) 2005 Rusty Russell <rusty@rustcorp.com.au>
3     Copyright (C) 2005 XenSource Ltd
4 
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9 
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14 
15 */
16 
17 #define pr_fmt(fmt) "xen-blkback: " fmt
18 
19 #include <stdarg.h>
20 #include <linux/module.h>
21 #include <linux/kthread.h>
22 #include <xen/events.h>
23 #include <xen/grant_table.h>
24 #include "common.h"
25 
26 /* On the XenBus the max length of 'ring-ref%u'. */
27 #define RINGREF_NAME_LEN (20)
28 
29 struct backend_info {
30 	struct xenbus_device	*dev;
31 	struct xen_blkif	*blkif;
32 	struct xenbus_watch	backend_watch;
33 	unsigned		major;
34 	unsigned		minor;
35 	char			*mode;
36 };
37 
38 static struct kmem_cache *xen_blkif_cachep;
39 static void connect(struct backend_info *);
40 static int connect_ring(struct backend_info *);
41 static void backend_changed(struct xenbus_watch *, const char *,
42 			    const char *);
43 static void xen_blkif_free(struct xen_blkif *blkif);
44 static void xen_vbd_free(struct xen_vbd *vbd);
45 
46 struct xenbus_device *xen_blkbk_xenbus(struct backend_info *be)
47 {
48 	return be->dev;
49 }
50 
51 /*
52  * The last request could free the device from softirq context and
53  * xen_blkif_free() can sleep.
54  */
55 static void xen_blkif_deferred_free(struct work_struct *work)
56 {
57 	struct xen_blkif *blkif;
58 
59 	blkif = container_of(work, struct xen_blkif, free_work);
60 	xen_blkif_free(blkif);
61 }
62 
63 static int blkback_name(struct xen_blkif *blkif, char *buf)
64 {
65 	char *devpath, *devname;
66 	struct xenbus_device *dev = blkif->be->dev;
67 
68 	devpath = xenbus_read(XBT_NIL, dev->nodename, "dev", NULL);
69 	if (IS_ERR(devpath))
70 		return PTR_ERR(devpath);
71 
72 	devname = strstr(devpath, "/dev/");
73 	if (devname != NULL)
74 		devname += strlen("/dev/");
75 	else
76 		devname  = devpath;
77 
78 	snprintf(buf, TASK_COMM_LEN, "%d.%s", blkif->domid, devname);
79 	kfree(devpath);
80 
81 	return 0;
82 }
83 
84 static void xen_update_blkif_status(struct xen_blkif *blkif)
85 {
86 	int err;
87 	char name[TASK_COMM_LEN];
88 	struct xen_blkif_ring *ring;
89 	int i;
90 
91 	/* Not ready to connect? */
92 	if (!blkif->rings || !blkif->rings[0].irq || !blkif->vbd.bdev)
93 		return;
94 
95 	/* Already connected? */
96 	if (blkif->be->dev->state == XenbusStateConnected)
97 		return;
98 
99 	/* Attempt to connect: exit if we fail to. */
100 	connect(blkif->be);
101 	if (blkif->be->dev->state != XenbusStateConnected)
102 		return;
103 
104 	err = blkback_name(blkif, name);
105 	if (err) {
106 		xenbus_dev_error(blkif->be->dev, err, "get blkback dev name");
107 		return;
108 	}
109 
110 	err = filemap_write_and_wait(blkif->vbd.bdev->bd_inode->i_mapping);
111 	if (err) {
112 		xenbus_dev_error(blkif->be->dev, err, "block flush");
113 		return;
114 	}
115 	invalidate_inode_pages2(blkif->vbd.bdev->bd_inode->i_mapping);
116 
117 	for (i = 0; i < blkif->nr_rings; i++) {
118 		ring = &blkif->rings[i];
119 		ring->xenblkd = kthread_run(xen_blkif_schedule, ring, "%s-%d", name, i);
120 		if (IS_ERR(ring->xenblkd)) {
121 			err = PTR_ERR(ring->xenblkd);
122 			ring->xenblkd = NULL;
123 			xenbus_dev_fatal(blkif->be->dev, err,
124 					"start %s-%d xenblkd", name, i);
125 			goto out;
126 		}
127 	}
128 	return;
129 
130 out:
131 	while (--i >= 0) {
132 		ring = &blkif->rings[i];
133 		kthread_stop(ring->xenblkd);
134 	}
135 	return;
136 }
137 
138 static int xen_blkif_alloc_rings(struct xen_blkif *blkif)
139 {
140 	unsigned int r;
141 
142 	blkif->rings = kcalloc(blkif->nr_rings, sizeof(struct xen_blkif_ring),
143 			       GFP_KERNEL);
144 	if (!blkif->rings)
145 		return -ENOMEM;
146 
147 	for (r = 0; r < blkif->nr_rings; r++) {
148 		struct xen_blkif_ring *ring = &blkif->rings[r];
149 
150 		spin_lock_init(&ring->blk_ring_lock);
151 		init_waitqueue_head(&ring->wq);
152 		INIT_LIST_HEAD(&ring->pending_free);
153 		INIT_LIST_HEAD(&ring->persistent_purge_list);
154 		INIT_WORK(&ring->persistent_purge_work, xen_blkbk_unmap_purged_grants);
155 		spin_lock_init(&ring->free_pages_lock);
156 		INIT_LIST_HEAD(&ring->free_pages);
157 
158 		spin_lock_init(&ring->pending_free_lock);
159 		init_waitqueue_head(&ring->pending_free_wq);
160 		init_waitqueue_head(&ring->shutdown_wq);
161 		ring->blkif = blkif;
162 		ring->st_print = jiffies;
163 		ring->active = true;
164 	}
165 
166 	return 0;
167 }
168 
169 static struct xen_blkif *xen_blkif_alloc(domid_t domid)
170 {
171 	struct xen_blkif *blkif;
172 
173 	BUILD_BUG_ON(MAX_INDIRECT_PAGES > BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST);
174 
175 	blkif = kmem_cache_zalloc(xen_blkif_cachep, GFP_KERNEL);
176 	if (!blkif)
177 		return ERR_PTR(-ENOMEM);
178 
179 	blkif->domid = domid;
180 	atomic_set(&blkif->refcnt, 1);
181 	init_completion(&blkif->drain_complete);
182 	INIT_WORK(&blkif->free_work, xen_blkif_deferred_free);
183 
184 	return blkif;
185 }
186 
187 static int xen_blkif_map(struct xen_blkif_ring *ring, grant_ref_t *gref,
188 			 unsigned int nr_grefs, unsigned int evtchn)
189 {
190 	int err;
191 	struct xen_blkif *blkif = ring->blkif;
192 
193 	/* Already connected through? */
194 	if (ring->irq)
195 		return 0;
196 
197 	err = xenbus_map_ring_valloc(blkif->be->dev, gref, nr_grefs,
198 				     &ring->blk_ring);
199 	if (err < 0)
200 		return err;
201 
202 	switch (blkif->blk_protocol) {
203 	case BLKIF_PROTOCOL_NATIVE:
204 	{
205 		struct blkif_sring *sring;
206 		sring = (struct blkif_sring *)ring->blk_ring;
207 		BACK_RING_INIT(&ring->blk_rings.native, sring,
208 			       XEN_PAGE_SIZE * nr_grefs);
209 		break;
210 	}
211 	case BLKIF_PROTOCOL_X86_32:
212 	{
213 		struct blkif_x86_32_sring *sring_x86_32;
214 		sring_x86_32 = (struct blkif_x86_32_sring *)ring->blk_ring;
215 		BACK_RING_INIT(&ring->blk_rings.x86_32, sring_x86_32,
216 			       XEN_PAGE_SIZE * nr_grefs);
217 		break;
218 	}
219 	case BLKIF_PROTOCOL_X86_64:
220 	{
221 		struct blkif_x86_64_sring *sring_x86_64;
222 		sring_x86_64 = (struct blkif_x86_64_sring *)ring->blk_ring;
223 		BACK_RING_INIT(&ring->blk_rings.x86_64, sring_x86_64,
224 			       XEN_PAGE_SIZE * nr_grefs);
225 		break;
226 	}
227 	default:
228 		BUG();
229 	}
230 
231 	err = bind_interdomain_evtchn_to_irqhandler(blkif->domid, evtchn,
232 						    xen_blkif_be_int, 0,
233 						    "blkif-backend", ring);
234 	if (err < 0) {
235 		xenbus_unmap_ring_vfree(blkif->be->dev, ring->blk_ring);
236 		ring->blk_rings.common.sring = NULL;
237 		return err;
238 	}
239 	ring->irq = err;
240 
241 	return 0;
242 }
243 
244 static int xen_blkif_disconnect(struct xen_blkif *blkif)
245 {
246 	struct pending_req *req, *n;
247 	unsigned int j, r;
248 	bool busy = false;
249 
250 	for (r = 0; r < blkif->nr_rings; r++) {
251 		struct xen_blkif_ring *ring = &blkif->rings[r];
252 		unsigned int i = 0;
253 
254 		if (!ring->active)
255 			continue;
256 
257 		if (ring->xenblkd) {
258 			kthread_stop(ring->xenblkd);
259 			wake_up(&ring->shutdown_wq);
260 		}
261 
262 		/* The above kthread_stop() guarantees that at this point we
263 		 * don't have any discard_io or other_io requests. So, checking
264 		 * for inflight IO is enough.
265 		 */
266 		if (atomic_read(&ring->inflight) > 0) {
267 			busy = true;
268 			continue;
269 		}
270 
271 		if (ring->irq) {
272 			unbind_from_irqhandler(ring->irq, ring);
273 			ring->irq = 0;
274 		}
275 
276 		if (ring->blk_rings.common.sring) {
277 			xenbus_unmap_ring_vfree(blkif->be->dev, ring->blk_ring);
278 			ring->blk_rings.common.sring = NULL;
279 		}
280 
281 		/* Remove all persistent grants and the cache of ballooned pages. */
282 		xen_blkbk_free_caches(ring);
283 
284 		/* Check that there is no request in use */
285 		list_for_each_entry_safe(req, n, &ring->pending_free, free_list) {
286 			list_del(&req->free_list);
287 
288 			for (j = 0; j < MAX_INDIRECT_SEGMENTS; j++)
289 				kfree(req->segments[j]);
290 
291 			for (j = 0; j < MAX_INDIRECT_PAGES; j++)
292 				kfree(req->indirect_pages[j]);
293 
294 			kfree(req);
295 			i++;
296 		}
297 
298 		BUG_ON(atomic_read(&ring->persistent_gnt_in_use) != 0);
299 		BUG_ON(!list_empty(&ring->persistent_purge_list));
300 		BUG_ON(!RB_EMPTY_ROOT(&ring->persistent_gnts));
301 		BUG_ON(!list_empty(&ring->free_pages));
302 		BUG_ON(ring->free_pages_num != 0);
303 		BUG_ON(ring->persistent_gnt_c != 0);
304 		WARN_ON(i != (XEN_BLKIF_REQS_PER_PAGE * blkif->nr_ring_pages));
305 		ring->active = false;
306 	}
307 	if (busy)
308 		return -EBUSY;
309 
310 	blkif->nr_ring_pages = 0;
311 	/*
312 	 * blkif->rings was allocated in connect_ring, so we should free it in
313 	 * here.
314 	 */
315 	kfree(blkif->rings);
316 	blkif->rings = NULL;
317 	blkif->nr_rings = 0;
318 
319 	return 0;
320 }
321 
322 static void xen_blkif_free(struct xen_blkif *blkif)
323 {
324 	WARN_ON(xen_blkif_disconnect(blkif));
325 	xen_vbd_free(&blkif->vbd);
326 	kfree(blkif->be->mode);
327 	kfree(blkif->be);
328 
329 	/* Make sure everything is drained before shutting down */
330 	kmem_cache_free(xen_blkif_cachep, blkif);
331 }
332 
333 int __init xen_blkif_interface_init(void)
334 {
335 	xen_blkif_cachep = kmem_cache_create("blkif_cache",
336 					     sizeof(struct xen_blkif),
337 					     0, 0, NULL);
338 	if (!xen_blkif_cachep)
339 		return -ENOMEM;
340 
341 	return 0;
342 }
343 
344 /*
345  *  sysfs interface for VBD I/O requests
346  */
347 
348 #define VBD_SHOW_ALLRING(name, format)					\
349 	static ssize_t show_##name(struct device *_dev,			\
350 				   struct device_attribute *attr,	\
351 				   char *buf)				\
352 	{								\
353 		struct xenbus_device *dev = to_xenbus_device(_dev);	\
354 		struct backend_info *be = dev_get_drvdata(&dev->dev);	\
355 		struct xen_blkif *blkif = be->blkif;			\
356 		unsigned int i;						\
357 		unsigned long long result = 0;				\
358 									\
359 		if (!blkif->rings)				\
360 			goto out;					\
361 									\
362 		for (i = 0; i < blkif->nr_rings; i++) {		\
363 			struct xen_blkif_ring *ring = &blkif->rings[i];	\
364 									\
365 			result += ring->st_##name;			\
366 		}							\
367 									\
368 out:									\
369 		return sprintf(buf, format, result);			\
370 	}								\
371 	static DEVICE_ATTR(name, 0444, show_##name, NULL)
372 
373 VBD_SHOW_ALLRING(oo_req,  "%llu\n");
374 VBD_SHOW_ALLRING(rd_req,  "%llu\n");
375 VBD_SHOW_ALLRING(wr_req,  "%llu\n");
376 VBD_SHOW_ALLRING(f_req,  "%llu\n");
377 VBD_SHOW_ALLRING(ds_req,  "%llu\n");
378 VBD_SHOW_ALLRING(rd_sect, "%llu\n");
379 VBD_SHOW_ALLRING(wr_sect, "%llu\n");
380 
381 static struct attribute *xen_vbdstat_attrs[] = {
382 	&dev_attr_oo_req.attr,
383 	&dev_attr_rd_req.attr,
384 	&dev_attr_wr_req.attr,
385 	&dev_attr_f_req.attr,
386 	&dev_attr_ds_req.attr,
387 	&dev_attr_rd_sect.attr,
388 	&dev_attr_wr_sect.attr,
389 	NULL
390 };
391 
392 static const struct attribute_group xen_vbdstat_group = {
393 	.name = "statistics",
394 	.attrs = xen_vbdstat_attrs,
395 };
396 
397 #define VBD_SHOW(name, format, args...)					\
398 	static ssize_t show_##name(struct device *_dev,			\
399 				   struct device_attribute *attr,	\
400 				   char *buf)				\
401 	{								\
402 		struct xenbus_device *dev = to_xenbus_device(_dev);	\
403 		struct backend_info *be = dev_get_drvdata(&dev->dev);	\
404 									\
405 		return sprintf(buf, format, ##args);			\
406 	}								\
407 	static DEVICE_ATTR(name, 0444, show_##name, NULL)
408 
409 VBD_SHOW(physical_device, "%x:%x\n", be->major, be->minor);
410 VBD_SHOW(mode, "%s\n", be->mode);
411 
412 static int xenvbd_sysfs_addif(struct xenbus_device *dev)
413 {
414 	int error;
415 
416 	error = device_create_file(&dev->dev, &dev_attr_physical_device);
417 	if (error)
418 		goto fail1;
419 
420 	error = device_create_file(&dev->dev, &dev_attr_mode);
421 	if (error)
422 		goto fail2;
423 
424 	error = sysfs_create_group(&dev->dev.kobj, &xen_vbdstat_group);
425 	if (error)
426 		goto fail3;
427 
428 	return 0;
429 
430 fail3:	sysfs_remove_group(&dev->dev.kobj, &xen_vbdstat_group);
431 fail2:	device_remove_file(&dev->dev, &dev_attr_mode);
432 fail1:	device_remove_file(&dev->dev, &dev_attr_physical_device);
433 	return error;
434 }
435 
436 static void xenvbd_sysfs_delif(struct xenbus_device *dev)
437 {
438 	sysfs_remove_group(&dev->dev.kobj, &xen_vbdstat_group);
439 	device_remove_file(&dev->dev, &dev_attr_mode);
440 	device_remove_file(&dev->dev, &dev_attr_physical_device);
441 }
442 
443 
444 static void xen_vbd_free(struct xen_vbd *vbd)
445 {
446 	if (vbd->bdev)
447 		blkdev_put(vbd->bdev, vbd->readonly ? FMODE_READ : FMODE_WRITE);
448 	vbd->bdev = NULL;
449 }
450 
451 static int xen_vbd_create(struct xen_blkif *blkif, blkif_vdev_t handle,
452 			  unsigned major, unsigned minor, int readonly,
453 			  int cdrom)
454 {
455 	struct xen_vbd *vbd;
456 	struct block_device *bdev;
457 	struct request_queue *q;
458 
459 	vbd = &blkif->vbd;
460 	vbd->handle   = handle;
461 	vbd->readonly = readonly;
462 	vbd->type     = 0;
463 
464 	vbd->pdevice  = MKDEV(major, minor);
465 
466 	bdev = blkdev_get_by_dev(vbd->pdevice, vbd->readonly ?
467 				 FMODE_READ : FMODE_WRITE, NULL);
468 
469 	if (IS_ERR(bdev)) {
470 		pr_warn("xen_vbd_create: device %08x could not be opened\n",
471 			vbd->pdevice);
472 		return -ENOENT;
473 	}
474 
475 	vbd->bdev = bdev;
476 	if (vbd->bdev->bd_disk == NULL) {
477 		pr_warn("xen_vbd_create: device %08x doesn't exist\n",
478 			vbd->pdevice);
479 		xen_vbd_free(vbd);
480 		return -ENOENT;
481 	}
482 	vbd->size = vbd_sz(vbd);
483 
484 	if (vbd->bdev->bd_disk->flags & GENHD_FL_CD || cdrom)
485 		vbd->type |= VDISK_CDROM;
486 	if (vbd->bdev->bd_disk->flags & GENHD_FL_REMOVABLE)
487 		vbd->type |= VDISK_REMOVABLE;
488 
489 	q = bdev_get_queue(bdev);
490 	if (q && test_bit(QUEUE_FLAG_WC, &q->queue_flags))
491 		vbd->flush_support = true;
492 
493 	if (q && blk_queue_secure_erase(q))
494 		vbd->discard_secure = true;
495 
496 	pr_debug("Successful creation of handle=%04x (dom=%u)\n",
497 		handle, blkif->domid);
498 	return 0;
499 }
500 static int xen_blkbk_remove(struct xenbus_device *dev)
501 {
502 	struct backend_info *be = dev_get_drvdata(&dev->dev);
503 
504 	pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
505 
506 	if (be->major || be->minor)
507 		xenvbd_sysfs_delif(dev);
508 
509 	if (be->backend_watch.node) {
510 		unregister_xenbus_watch(&be->backend_watch);
511 		kfree(be->backend_watch.node);
512 		be->backend_watch.node = NULL;
513 	}
514 
515 	dev_set_drvdata(&dev->dev, NULL);
516 
517 	if (be->blkif) {
518 		xen_blkif_disconnect(be->blkif);
519 
520 		/* Put the reference we set in xen_blkif_alloc(). */
521 		xen_blkif_put(be->blkif);
522 	}
523 
524 	return 0;
525 }
526 
527 int xen_blkbk_flush_diskcache(struct xenbus_transaction xbt,
528 			      struct backend_info *be, int state)
529 {
530 	struct xenbus_device *dev = be->dev;
531 	int err;
532 
533 	err = xenbus_printf(xbt, dev->nodename, "feature-flush-cache",
534 			    "%d", state);
535 	if (err)
536 		dev_warn(&dev->dev, "writing feature-flush-cache (%d)", err);
537 
538 	return err;
539 }
540 
541 static void xen_blkbk_discard(struct xenbus_transaction xbt, struct backend_info *be)
542 {
543 	struct xenbus_device *dev = be->dev;
544 	struct xen_blkif *blkif = be->blkif;
545 	int err;
546 	int state = 0;
547 	struct block_device *bdev = be->blkif->vbd.bdev;
548 	struct request_queue *q = bdev_get_queue(bdev);
549 
550 	if (!xenbus_read_unsigned(dev->nodename, "discard-enable", 1))
551 		return;
552 
553 	if (blk_queue_discard(q)) {
554 		err = xenbus_printf(xbt, dev->nodename,
555 			"discard-granularity", "%u",
556 			q->limits.discard_granularity);
557 		if (err) {
558 			dev_warn(&dev->dev, "writing discard-granularity (%d)", err);
559 			return;
560 		}
561 		err = xenbus_printf(xbt, dev->nodename,
562 			"discard-alignment", "%u",
563 			q->limits.discard_alignment);
564 		if (err) {
565 			dev_warn(&dev->dev, "writing discard-alignment (%d)", err);
566 			return;
567 		}
568 		state = 1;
569 		/* Optional. */
570 		err = xenbus_printf(xbt, dev->nodename,
571 				    "discard-secure", "%d",
572 				    blkif->vbd.discard_secure);
573 		if (err) {
574 			dev_warn(&dev->dev, "writing discard-secure (%d)", err);
575 			return;
576 		}
577 	}
578 	err = xenbus_printf(xbt, dev->nodename, "feature-discard",
579 			    "%d", state);
580 	if (err)
581 		dev_warn(&dev->dev, "writing feature-discard (%d)", err);
582 }
583 int xen_blkbk_barrier(struct xenbus_transaction xbt,
584 		      struct backend_info *be, int state)
585 {
586 	struct xenbus_device *dev = be->dev;
587 	int err;
588 
589 	err = xenbus_printf(xbt, dev->nodename, "feature-barrier",
590 			    "%d", state);
591 	if (err)
592 		dev_warn(&dev->dev, "writing feature-barrier (%d)", err);
593 
594 	return err;
595 }
596 
597 /*
598  * Entry point to this code when a new device is created.  Allocate the basic
599  * structures, and watch the store waiting for the hotplug scripts to tell us
600  * the device's physical major and minor numbers.  Switch to InitWait.
601  */
602 static int xen_blkbk_probe(struct xenbus_device *dev,
603 			   const struct xenbus_device_id *id)
604 {
605 	int err;
606 	struct backend_info *be = kzalloc(sizeof(struct backend_info),
607 					  GFP_KERNEL);
608 
609 	/* match the pr_debug in xen_blkbk_remove */
610 	pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
611 
612 	if (!be) {
613 		xenbus_dev_fatal(dev, -ENOMEM,
614 				 "allocating backend structure");
615 		return -ENOMEM;
616 	}
617 	be->dev = dev;
618 	dev_set_drvdata(&dev->dev, be);
619 
620 	be->blkif = xen_blkif_alloc(dev->otherend_id);
621 	if (IS_ERR(be->blkif)) {
622 		err = PTR_ERR(be->blkif);
623 		be->blkif = NULL;
624 		xenbus_dev_fatal(dev, err, "creating block interface");
625 		goto fail;
626 	}
627 
628 	err = xenbus_printf(XBT_NIL, dev->nodename,
629 			    "feature-max-indirect-segments", "%u",
630 			    MAX_INDIRECT_SEGMENTS);
631 	if (err)
632 		dev_warn(&dev->dev,
633 			 "writing %s/feature-max-indirect-segments (%d)",
634 			 dev->nodename, err);
635 
636 	/* Multi-queue: advertise how many queues are supported by us.*/
637 	err = xenbus_printf(XBT_NIL, dev->nodename,
638 			    "multi-queue-max-queues", "%u", xenblk_max_queues);
639 	if (err)
640 		pr_warn("Error writing multi-queue-max-queues\n");
641 
642 	/* setup back pointer */
643 	be->blkif->be = be;
644 
645 	err = xenbus_watch_pathfmt(dev, &be->backend_watch, backend_changed,
646 				   "%s/%s", dev->nodename, "physical-device");
647 	if (err)
648 		goto fail;
649 
650 	err = xenbus_printf(XBT_NIL, dev->nodename, "max-ring-page-order", "%u",
651 			    xen_blkif_max_ring_order);
652 	if (err)
653 		pr_warn("%s write out 'max-ring-page-order' failed\n", __func__);
654 
655 	err = xenbus_switch_state(dev, XenbusStateInitWait);
656 	if (err)
657 		goto fail;
658 
659 	return 0;
660 
661 fail:
662 	pr_warn("%s failed\n", __func__);
663 	xen_blkbk_remove(dev);
664 	return err;
665 }
666 
667 
668 /*
669  * Callback received when the hotplug scripts have placed the physical-device
670  * node.  Read it and the mode node, and create a vbd.  If the frontend is
671  * ready, connect.
672  */
673 static void backend_changed(struct xenbus_watch *watch,
674 			    const char *path, const char *token)
675 {
676 	int err;
677 	unsigned major;
678 	unsigned minor;
679 	struct backend_info *be
680 		= container_of(watch, struct backend_info, backend_watch);
681 	struct xenbus_device *dev = be->dev;
682 	int cdrom = 0;
683 	unsigned long handle;
684 	char *device_type;
685 
686 	pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
687 
688 	err = xenbus_scanf(XBT_NIL, dev->nodename, "physical-device", "%x:%x",
689 			   &major, &minor);
690 	if (XENBUS_EXIST_ERR(err)) {
691 		/*
692 		 * Since this watch will fire once immediately after it is
693 		 * registered, we expect this.  Ignore it, and wait for the
694 		 * hotplug scripts.
695 		 */
696 		return;
697 	}
698 	if (err != 2) {
699 		xenbus_dev_fatal(dev, err, "reading physical-device");
700 		return;
701 	}
702 
703 	if (be->major | be->minor) {
704 		if (be->major != major || be->minor != minor)
705 			pr_warn("changing physical device (from %x:%x to %x:%x) not supported.\n",
706 				be->major, be->minor, major, minor);
707 		return;
708 	}
709 
710 	be->mode = xenbus_read(XBT_NIL, dev->nodename, "mode", NULL);
711 	if (IS_ERR(be->mode)) {
712 		err = PTR_ERR(be->mode);
713 		be->mode = NULL;
714 		xenbus_dev_fatal(dev, err, "reading mode");
715 		return;
716 	}
717 
718 	device_type = xenbus_read(XBT_NIL, dev->otherend, "device-type", NULL);
719 	if (!IS_ERR(device_type)) {
720 		cdrom = strcmp(device_type, "cdrom") == 0;
721 		kfree(device_type);
722 	}
723 
724 	/* Front end dir is a number, which is used as the handle. */
725 	err = kstrtoul(strrchr(dev->otherend, '/') + 1, 0, &handle);
726 	if (err) {
727 		kfree(be->mode);
728 		be->mode = NULL;
729 		return;
730 	}
731 
732 	be->major = major;
733 	be->minor = minor;
734 
735 	err = xen_vbd_create(be->blkif, handle, major, minor,
736 			     !strchr(be->mode, 'w'), cdrom);
737 
738 	if (err)
739 		xenbus_dev_fatal(dev, err, "creating vbd structure");
740 	else {
741 		err = xenvbd_sysfs_addif(dev);
742 		if (err) {
743 			xen_vbd_free(&be->blkif->vbd);
744 			xenbus_dev_fatal(dev, err, "creating sysfs entries");
745 		}
746 	}
747 
748 	if (err) {
749 		kfree(be->mode);
750 		be->mode = NULL;
751 		be->major = 0;
752 		be->minor = 0;
753 	} else {
754 		/* We're potentially connected now */
755 		xen_update_blkif_status(be->blkif);
756 	}
757 }
758 
759 
760 /*
761  * Callback received when the frontend's state changes.
762  */
763 static void frontend_changed(struct xenbus_device *dev,
764 			     enum xenbus_state frontend_state)
765 {
766 	struct backend_info *be = dev_get_drvdata(&dev->dev);
767 	int err;
768 
769 	pr_debug("%s %p %s\n", __func__, dev, xenbus_strstate(frontend_state));
770 
771 	switch (frontend_state) {
772 	case XenbusStateInitialising:
773 		if (dev->state == XenbusStateClosed) {
774 			pr_info("%s: prepare for reconnect\n", dev->nodename);
775 			xenbus_switch_state(dev, XenbusStateInitWait);
776 		}
777 		break;
778 
779 	case XenbusStateInitialised:
780 	case XenbusStateConnected:
781 		/*
782 		 * Ensure we connect even when two watches fire in
783 		 * close succession and we miss the intermediate value
784 		 * of frontend_state.
785 		 */
786 		if (dev->state == XenbusStateConnected)
787 			break;
788 
789 		/*
790 		 * Enforce precondition before potential leak point.
791 		 * xen_blkif_disconnect() is idempotent.
792 		 */
793 		err = xen_blkif_disconnect(be->blkif);
794 		if (err) {
795 			xenbus_dev_fatal(dev, err, "pending I/O");
796 			break;
797 		}
798 
799 		err = connect_ring(be);
800 		if (err) {
801 			/*
802 			 * Clean up so that memory resources can be used by
803 			 * other devices. connect_ring reported already error.
804 			 */
805 			xen_blkif_disconnect(be->blkif);
806 			break;
807 		}
808 		xen_update_blkif_status(be->blkif);
809 		break;
810 
811 	case XenbusStateClosing:
812 		xenbus_switch_state(dev, XenbusStateClosing);
813 		break;
814 
815 	case XenbusStateClosed:
816 		xen_blkif_disconnect(be->blkif);
817 		xenbus_switch_state(dev, XenbusStateClosed);
818 		if (xenbus_dev_is_online(dev))
819 			break;
820 		/* fall through */
821 		/* if not online */
822 	case XenbusStateUnknown:
823 		/* implies xen_blkif_disconnect() via xen_blkbk_remove() */
824 		device_unregister(&dev->dev);
825 		break;
826 
827 	default:
828 		xenbus_dev_fatal(dev, -EINVAL, "saw state %d at frontend",
829 				 frontend_state);
830 		break;
831 	}
832 }
833 
834 
835 /* ** Connection ** */
836 
837 
838 /*
839  * Write the physical details regarding the block device to the store, and
840  * switch to Connected state.
841  */
842 static void connect(struct backend_info *be)
843 {
844 	struct xenbus_transaction xbt;
845 	int err;
846 	struct xenbus_device *dev = be->dev;
847 
848 	pr_debug("%s %s\n", __func__, dev->otherend);
849 
850 	/* Supply the information about the device the frontend needs */
851 again:
852 	err = xenbus_transaction_start(&xbt);
853 	if (err) {
854 		xenbus_dev_fatal(dev, err, "starting transaction");
855 		return;
856 	}
857 
858 	/* If we can't advertise it is OK. */
859 	xen_blkbk_flush_diskcache(xbt, be, be->blkif->vbd.flush_support);
860 
861 	xen_blkbk_discard(xbt, be);
862 
863 	xen_blkbk_barrier(xbt, be, be->blkif->vbd.flush_support);
864 
865 	err = xenbus_printf(xbt, dev->nodename, "feature-persistent", "%u", 1);
866 	if (err) {
867 		xenbus_dev_fatal(dev, err, "writing %s/feature-persistent",
868 				 dev->nodename);
869 		goto abort;
870 	}
871 
872 	err = xenbus_printf(xbt, dev->nodename, "sectors", "%llu",
873 			    (unsigned long long)vbd_sz(&be->blkif->vbd));
874 	if (err) {
875 		xenbus_dev_fatal(dev, err, "writing %s/sectors",
876 				 dev->nodename);
877 		goto abort;
878 	}
879 
880 	/* FIXME: use a typename instead */
881 	err = xenbus_printf(xbt, dev->nodename, "info", "%u",
882 			    be->blkif->vbd.type |
883 			    (be->blkif->vbd.readonly ? VDISK_READONLY : 0));
884 	if (err) {
885 		xenbus_dev_fatal(dev, err, "writing %s/info",
886 				 dev->nodename);
887 		goto abort;
888 	}
889 	err = xenbus_printf(xbt, dev->nodename, "sector-size", "%lu",
890 			    (unsigned long)
891 			    bdev_logical_block_size(be->blkif->vbd.bdev));
892 	if (err) {
893 		xenbus_dev_fatal(dev, err, "writing %s/sector-size",
894 				 dev->nodename);
895 		goto abort;
896 	}
897 	err = xenbus_printf(xbt, dev->nodename, "physical-sector-size", "%u",
898 			    bdev_physical_block_size(be->blkif->vbd.bdev));
899 	if (err)
900 		xenbus_dev_error(dev, err, "writing %s/physical-sector-size",
901 				 dev->nodename);
902 
903 	err = xenbus_transaction_end(xbt, 0);
904 	if (err == -EAGAIN)
905 		goto again;
906 	if (err)
907 		xenbus_dev_fatal(dev, err, "ending transaction");
908 
909 	err = xenbus_switch_state(dev, XenbusStateConnected);
910 	if (err)
911 		xenbus_dev_fatal(dev, err, "%s: switching to Connected state",
912 				 dev->nodename);
913 
914 	return;
915  abort:
916 	xenbus_transaction_end(xbt, 1);
917 }
918 
919 /*
920  * Each ring may have multi pages, depends on "ring-page-order".
921  */
922 static int read_per_ring_refs(struct xen_blkif_ring *ring, const char *dir)
923 {
924 	unsigned int ring_ref[XENBUS_MAX_RING_GRANTS];
925 	struct pending_req *req, *n;
926 	int err, i, j;
927 	struct xen_blkif *blkif = ring->blkif;
928 	struct xenbus_device *dev = blkif->be->dev;
929 	unsigned int nr_grefs, evtchn;
930 
931 	err = xenbus_scanf(XBT_NIL, dir, "event-channel", "%u",
932 			  &evtchn);
933 	if (err != 1) {
934 		err = -EINVAL;
935 		xenbus_dev_fatal(dev, err, "reading %s/event-channel", dir);
936 		return err;
937 	}
938 
939 	nr_grefs = blkif->nr_ring_pages;
940 
941 	if (unlikely(!nr_grefs)) {
942 		WARN_ON(true);
943 		return -EINVAL;
944 	}
945 
946 	for (i = 0; i < nr_grefs; i++) {
947 		char ring_ref_name[RINGREF_NAME_LEN];
948 
949 		snprintf(ring_ref_name, RINGREF_NAME_LEN, "ring-ref%u", i);
950 		err = xenbus_scanf(XBT_NIL, dir, ring_ref_name,
951 				   "%u", &ring_ref[i]);
952 
953 		if (err != 1) {
954 			if (nr_grefs == 1)
955 				break;
956 
957 			err = -EINVAL;
958 			xenbus_dev_fatal(dev, err, "reading %s/%s",
959 					 dir, ring_ref_name);
960 			return err;
961 		}
962 	}
963 
964 	if (err != 1) {
965 		WARN_ON(nr_grefs != 1);
966 
967 		err = xenbus_scanf(XBT_NIL, dir, "ring-ref", "%u",
968 				   &ring_ref[0]);
969 		if (err != 1) {
970 			err = -EINVAL;
971 			xenbus_dev_fatal(dev, err, "reading %s/ring-ref", dir);
972 			return err;
973 		}
974 	}
975 
976 	for (i = 0; i < nr_grefs * XEN_BLKIF_REQS_PER_PAGE; i++) {
977 		req = kzalloc(sizeof(*req), GFP_KERNEL);
978 		if (!req)
979 			goto fail;
980 		list_add_tail(&req->free_list, &ring->pending_free);
981 		for (j = 0; j < MAX_INDIRECT_SEGMENTS; j++) {
982 			req->segments[j] = kzalloc(sizeof(*req->segments[0]), GFP_KERNEL);
983 			if (!req->segments[j])
984 				goto fail;
985 		}
986 		for (j = 0; j < MAX_INDIRECT_PAGES; j++) {
987 			req->indirect_pages[j] = kzalloc(sizeof(*req->indirect_pages[0]),
988 							 GFP_KERNEL);
989 			if (!req->indirect_pages[j])
990 				goto fail;
991 		}
992 	}
993 
994 	/* Map the shared frame, irq etc. */
995 	err = xen_blkif_map(ring, ring_ref, nr_grefs, evtchn);
996 	if (err) {
997 		xenbus_dev_fatal(dev, err, "mapping ring-ref port %u", evtchn);
998 		return err;
999 	}
1000 
1001 	return 0;
1002 
1003 fail:
1004 	list_for_each_entry_safe(req, n, &ring->pending_free, free_list) {
1005 		list_del(&req->free_list);
1006 		for (j = 0; j < MAX_INDIRECT_SEGMENTS; j++) {
1007 			if (!req->segments[j])
1008 				break;
1009 			kfree(req->segments[j]);
1010 		}
1011 		for (j = 0; j < MAX_INDIRECT_PAGES; j++) {
1012 			if (!req->indirect_pages[j])
1013 				break;
1014 			kfree(req->indirect_pages[j]);
1015 		}
1016 		kfree(req);
1017 	}
1018 	return -ENOMEM;
1019 
1020 }
1021 
1022 static int connect_ring(struct backend_info *be)
1023 {
1024 	struct xenbus_device *dev = be->dev;
1025 	struct xen_blkif *blkif = be->blkif;
1026 	unsigned int pers_grants;
1027 	char protocol[64] = "";
1028 	int err, i;
1029 	char *xspath;
1030 	size_t xspathsize;
1031 	const size_t xenstore_path_ext_size = 11; /* sufficient for "/queue-NNN" */
1032 	unsigned int requested_num_queues = 0;
1033 	unsigned int ring_page_order;
1034 
1035 	pr_debug("%s %s\n", __func__, dev->otherend);
1036 
1037 	blkif->blk_protocol = BLKIF_PROTOCOL_DEFAULT;
1038 	err = xenbus_scanf(XBT_NIL, dev->otherend, "protocol",
1039 			   "%63s", protocol);
1040 	if (err <= 0)
1041 		strcpy(protocol, "unspecified, assuming default");
1042 	else if (0 == strcmp(protocol, XEN_IO_PROTO_ABI_NATIVE))
1043 		blkif->blk_protocol = BLKIF_PROTOCOL_NATIVE;
1044 	else if (0 == strcmp(protocol, XEN_IO_PROTO_ABI_X86_32))
1045 		blkif->blk_protocol = BLKIF_PROTOCOL_X86_32;
1046 	else if (0 == strcmp(protocol, XEN_IO_PROTO_ABI_X86_64))
1047 		blkif->blk_protocol = BLKIF_PROTOCOL_X86_64;
1048 	else {
1049 		xenbus_dev_fatal(dev, err, "unknown fe protocol %s", protocol);
1050 		return -ENOSYS;
1051 	}
1052 	pers_grants = xenbus_read_unsigned(dev->otherend, "feature-persistent",
1053 					   0);
1054 	blkif->vbd.feature_gnt_persistent = pers_grants;
1055 	blkif->vbd.overflow_max_grants = 0;
1056 
1057 	/*
1058 	 * Read the number of hardware queues from frontend.
1059 	 */
1060 	requested_num_queues = xenbus_read_unsigned(dev->otherend,
1061 						    "multi-queue-num-queues",
1062 						    1);
1063 	if (requested_num_queues > xenblk_max_queues
1064 	    || requested_num_queues == 0) {
1065 		/* Buggy or malicious guest. */
1066 		xenbus_dev_fatal(dev, err,
1067 				"guest requested %u queues, exceeding the maximum of %u.",
1068 				requested_num_queues, xenblk_max_queues);
1069 		return -ENOSYS;
1070 	}
1071 	blkif->nr_rings = requested_num_queues;
1072 	if (xen_blkif_alloc_rings(blkif))
1073 		return -ENOMEM;
1074 
1075 	pr_info("%s: using %d queues, protocol %d (%s) %s\n", dev->nodename,
1076 		 blkif->nr_rings, blkif->blk_protocol, protocol,
1077 		 pers_grants ? "persistent grants" : "");
1078 
1079 	ring_page_order = xenbus_read_unsigned(dev->otherend,
1080 					       "ring-page-order", 0);
1081 
1082 	if (ring_page_order > xen_blkif_max_ring_order) {
1083 		err = -EINVAL;
1084 		xenbus_dev_fatal(dev, err,
1085 				 "requested ring page order %d exceed max:%d",
1086 				 ring_page_order,
1087 				 xen_blkif_max_ring_order);
1088 		return err;
1089 	}
1090 
1091 	blkif->nr_ring_pages = 1 << ring_page_order;
1092 
1093 	if (blkif->nr_rings == 1)
1094 		return read_per_ring_refs(&blkif->rings[0], dev->otherend);
1095 	else {
1096 		xspathsize = strlen(dev->otherend) + xenstore_path_ext_size;
1097 		xspath = kmalloc(xspathsize, GFP_KERNEL);
1098 		if (!xspath) {
1099 			xenbus_dev_fatal(dev, -ENOMEM, "reading ring references");
1100 			return -ENOMEM;
1101 		}
1102 
1103 		for (i = 0; i < blkif->nr_rings; i++) {
1104 			memset(xspath, 0, xspathsize);
1105 			snprintf(xspath, xspathsize, "%s/queue-%u", dev->otherend, i);
1106 			err = read_per_ring_refs(&blkif->rings[i], xspath);
1107 			if (err) {
1108 				kfree(xspath);
1109 				return err;
1110 			}
1111 		}
1112 		kfree(xspath);
1113 	}
1114 	return 0;
1115 }
1116 
1117 static const struct xenbus_device_id xen_blkbk_ids[] = {
1118 	{ "vbd" },
1119 	{ "" }
1120 };
1121 
1122 static struct xenbus_driver xen_blkbk_driver = {
1123 	.ids  = xen_blkbk_ids,
1124 	.probe = xen_blkbk_probe,
1125 	.remove = xen_blkbk_remove,
1126 	.otherend_changed = frontend_changed
1127 };
1128 
1129 int xen_blkif_xenbus_init(void)
1130 {
1131 	return xenbus_register_backend(&xen_blkbk_driver);
1132 }
1133