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