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