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