1 /*
2  * Virtio-based remote processor messaging bus
3  *
4  * Copyright (C) 2011 Texas Instruments, Inc.
5  * Copyright (C) 2011 Google, Inc.
6  *
7  * Ohad Ben-Cohen <ohad@wizery.com>
8  * Brian Swetland <swetland@google.com>
9  *
10  * This software is licensed under the terms of the GNU General Public
11  * License version 2, as published by the Free Software Foundation, and
12  * may be copied, distributed, and modified under those terms.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  */
19 
20 #define pr_fmt(fmt) "%s: " fmt, __func__
21 
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/virtio.h>
25 #include <linux/virtio_ids.h>
26 #include <linux/virtio_config.h>
27 #include <linux/scatterlist.h>
28 #include <linux/dma-mapping.h>
29 #include <linux/slab.h>
30 #include <linux/idr.h>
31 #include <linux/jiffies.h>
32 #include <linux/sched.h>
33 #include <linux/wait.h>
34 #include <linux/rpmsg.h>
35 #include <linux/mutex.h>
36 
37 /**
38  * struct virtproc_info - virtual remote processor state
39  * @vdev:	the virtio device
40  * @rvq:	rx virtqueue
41  * @svq:	tx virtqueue
42  * @rbufs:	kernel address of rx buffers
43  * @sbufs:	kernel address of tx buffers
44  * @num_bufs:	total number of buffers for rx and tx
45  * @last_sbuf:	index of last tx buffer used
46  * @bufs_dma:	dma base addr of the buffers
47  * @tx_lock:	protects svq, sbufs and sleepers, to allow concurrent senders.
48  *		sending a message might require waking up a dozing remote
49  *		processor, which involves sleeping, hence the mutex.
50  * @endpoints:	idr of local endpoints, allows fast retrieval
51  * @endpoints_lock: lock of the endpoints set
52  * @sendq:	wait queue of sending contexts waiting for a tx buffers
53  * @sleepers:	number of senders that are waiting for a tx buffer
54  * @ns_ept:	the bus's name service endpoint
55  *
56  * This structure stores the rpmsg state of a given virtio remote processor
57  * device (there might be several virtio proc devices for each physical
58  * remote processor).
59  */
60 struct virtproc_info {
61 	struct virtio_device *vdev;
62 	struct virtqueue *rvq, *svq;
63 	void *rbufs, *sbufs;
64 	unsigned int num_bufs;
65 	int last_sbuf;
66 	dma_addr_t bufs_dma;
67 	struct mutex tx_lock;
68 	struct idr endpoints;
69 	struct mutex endpoints_lock;
70 	wait_queue_head_t sendq;
71 	atomic_t sleepers;
72 	struct rpmsg_endpoint *ns_ept;
73 };
74 
75 /**
76  * struct rpmsg_channel_info - internal channel info representation
77  * @name: name of service
78  * @src: local address
79  * @dst: destination address
80  */
81 struct rpmsg_channel_info {
82 	char name[RPMSG_NAME_SIZE];
83 	u32 src;
84 	u32 dst;
85 };
86 
87 #define to_rpmsg_channel(d) container_of(d, struct rpmsg_channel, dev)
88 #define to_rpmsg_driver(d) container_of(d, struct rpmsg_driver, drv)
89 
90 /*
91  * We're allocating buffers of 512 bytes each for communications. The
92  * number of buffers will be computed from the number of buffers supported
93  * by the vring, upto a maximum of 512 buffers (256 in each direction).
94  *
95  * Each buffer will have 16 bytes for the msg header and 496 bytes for
96  * the payload.
97  *
98  * This will utilize a maximum total space of 256KB for the buffers.
99  *
100  * We might also want to add support for user-provided buffers in time.
101  * This will allow bigger buffer size flexibility, and can also be used
102  * to achieve zero-copy messaging.
103  *
104  * Note that these numbers are purely a decision of this driver - we
105  * can change this without changing anything in the firmware of the remote
106  * processor.
107  */
108 #define MAX_RPMSG_NUM_BUFS	(512)
109 #define RPMSG_BUF_SIZE		(512)
110 
111 /*
112  * Local addresses are dynamically allocated on-demand.
113  * We do not dynamically assign addresses from the low 1024 range,
114  * in order to reserve that address range for predefined services.
115  */
116 #define RPMSG_RESERVED_ADDRESSES	(1024)
117 
118 /* Address 53 is reserved for advertising remote services */
119 #define RPMSG_NS_ADDR			(53)
120 
121 /* sysfs show configuration fields */
122 #define rpmsg_show_attr(field, path, format_string)			\
123 static ssize_t								\
124 field##_show(struct device *dev,					\
125 			struct device_attribute *attr, char *buf)	\
126 {									\
127 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);		\
128 									\
129 	return sprintf(buf, format_string, rpdev->path);		\
130 }
131 
132 /* for more info, see Documentation/ABI/testing/sysfs-bus-rpmsg */
133 rpmsg_show_attr(name, id.name, "%s\n");
134 rpmsg_show_attr(src, src, "0x%x\n");
135 rpmsg_show_attr(dst, dst, "0x%x\n");
136 rpmsg_show_attr(announce, announce ? "true" : "false", "%s\n");
137 
138 /*
139  * Unique (and free running) index for rpmsg devices.
140  *
141  * Yeah, we're not recycling those numbers (yet?). will be easy
142  * to change if/when we want to.
143  */
144 static unsigned int rpmsg_dev_index;
145 
146 static ssize_t modalias_show(struct device *dev,
147 			     struct device_attribute *attr, char *buf)
148 {
149 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
150 
151 	return sprintf(buf, RPMSG_DEVICE_MODALIAS_FMT "\n", rpdev->id.name);
152 }
153 
154 static struct device_attribute rpmsg_dev_attrs[] = {
155 	__ATTR_RO(name),
156 	__ATTR_RO(modalias),
157 	__ATTR_RO(dst),
158 	__ATTR_RO(src),
159 	__ATTR_RO(announce),
160 	__ATTR_NULL
161 };
162 
163 /* rpmsg devices and drivers are matched using the service name */
164 static inline int rpmsg_id_match(const struct rpmsg_channel *rpdev,
165 				  const struct rpmsg_device_id *id)
166 {
167 	return strncmp(id->name, rpdev->id.name, RPMSG_NAME_SIZE) == 0;
168 }
169 
170 /* match rpmsg channel and rpmsg driver */
171 static int rpmsg_dev_match(struct device *dev, struct device_driver *drv)
172 {
173 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
174 	struct rpmsg_driver *rpdrv = to_rpmsg_driver(drv);
175 	const struct rpmsg_device_id *ids = rpdrv->id_table;
176 	unsigned int i;
177 
178 	for (i = 0; ids[i].name[0]; i++)
179 		if (rpmsg_id_match(rpdev, &ids[i]))
180 			return 1;
181 
182 	return 0;
183 }
184 
185 static int rpmsg_uevent(struct device *dev, struct kobj_uevent_env *env)
186 {
187 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
188 
189 	return add_uevent_var(env, "MODALIAS=" RPMSG_DEVICE_MODALIAS_FMT,
190 					rpdev->id.name);
191 }
192 
193 /**
194  * __ept_release() - deallocate an rpmsg endpoint
195  * @kref: the ept's reference count
196  *
197  * This function deallocates an ept, and is invoked when its @kref refcount
198  * drops to zero.
199  *
200  * Never invoke this function directly!
201  */
202 static void __ept_release(struct kref *kref)
203 {
204 	struct rpmsg_endpoint *ept = container_of(kref, struct rpmsg_endpoint,
205 						  refcount);
206 	/*
207 	 * At this point no one holds a reference to ept anymore,
208 	 * so we can directly free it
209 	 */
210 	kfree(ept);
211 }
212 
213 /* for more info, see below documentation of rpmsg_create_ept() */
214 static struct rpmsg_endpoint *__rpmsg_create_ept(struct virtproc_info *vrp,
215 		struct rpmsg_channel *rpdev, rpmsg_rx_cb_t cb,
216 		void *priv, u32 addr)
217 {
218 	int id_min, id_max, id;
219 	struct rpmsg_endpoint *ept;
220 	struct device *dev = rpdev ? &rpdev->dev : &vrp->vdev->dev;
221 
222 	ept = kzalloc(sizeof(*ept), GFP_KERNEL);
223 	if (!ept) {
224 		dev_err(dev, "failed to kzalloc a new ept\n");
225 		return NULL;
226 	}
227 
228 	kref_init(&ept->refcount);
229 	mutex_init(&ept->cb_lock);
230 
231 	ept->rpdev = rpdev;
232 	ept->cb = cb;
233 	ept->priv = priv;
234 
235 	/* do we need to allocate a local address ? */
236 	if (addr == RPMSG_ADDR_ANY) {
237 		id_min = RPMSG_RESERVED_ADDRESSES;
238 		id_max = 0;
239 	} else {
240 		id_min = addr;
241 		id_max = addr + 1;
242 	}
243 
244 	mutex_lock(&vrp->endpoints_lock);
245 
246 	/* bind the endpoint to an rpmsg address (and allocate one if needed) */
247 	id = idr_alloc(&vrp->endpoints, ept, id_min, id_max, GFP_KERNEL);
248 	if (id < 0) {
249 		dev_err(dev, "idr_alloc failed: %d\n", id);
250 		goto free_ept;
251 	}
252 	ept->addr = id;
253 
254 	mutex_unlock(&vrp->endpoints_lock);
255 
256 	return ept;
257 
258 free_ept:
259 	mutex_unlock(&vrp->endpoints_lock);
260 	kref_put(&ept->refcount, __ept_release);
261 	return NULL;
262 }
263 
264 /**
265  * rpmsg_create_ept() - create a new rpmsg_endpoint
266  * @rpdev: rpmsg channel device
267  * @cb: rx callback handler
268  * @priv: private data for the driver's use
269  * @addr: local rpmsg address to bind with @cb
270  *
271  * Every rpmsg address in the system is bound to an rx callback (so when
272  * inbound messages arrive, they are dispatched by the rpmsg bus using the
273  * appropriate callback handler) by means of an rpmsg_endpoint struct.
274  *
275  * This function allows drivers to create such an endpoint, and by that,
276  * bind a callback, and possibly some private data too, to an rpmsg address
277  * (either one that is known in advance, or one that will be dynamically
278  * assigned for them).
279  *
280  * Simple rpmsg drivers need not call rpmsg_create_ept, because an endpoint
281  * is already created for them when they are probed by the rpmsg bus
282  * (using the rx callback provided when they registered to the rpmsg bus).
283  *
284  * So things should just work for simple drivers: they already have an
285  * endpoint, their rx callback is bound to their rpmsg address, and when
286  * relevant inbound messages arrive (i.e. messages which their dst address
287  * equals to the src address of their rpmsg channel), the driver's handler
288  * is invoked to process it.
289  *
290  * That said, more complicated drivers might do need to allocate
291  * additional rpmsg addresses, and bind them to different rx callbacks.
292  * To accomplish that, those drivers need to call this function.
293  *
294  * Drivers should provide their @rpdev channel (so the new endpoint would belong
295  * to the same remote processor their channel belongs to), an rx callback
296  * function, an optional private data (which is provided back when the
297  * rx callback is invoked), and an address they want to bind with the
298  * callback. If @addr is RPMSG_ADDR_ANY, then rpmsg_create_ept will
299  * dynamically assign them an available rpmsg address (drivers should have
300  * a very good reason why not to always use RPMSG_ADDR_ANY here).
301  *
302  * Returns a pointer to the endpoint on success, or NULL on error.
303  */
304 struct rpmsg_endpoint *rpmsg_create_ept(struct rpmsg_channel *rpdev,
305 				rpmsg_rx_cb_t cb, void *priv, u32 addr)
306 {
307 	return __rpmsg_create_ept(rpdev->vrp, rpdev, cb, priv, addr);
308 }
309 EXPORT_SYMBOL(rpmsg_create_ept);
310 
311 /**
312  * __rpmsg_destroy_ept() - destroy an existing rpmsg endpoint
313  * @vrp: virtproc which owns this ept
314  * @ept: endpoing to destroy
315  *
316  * An internal function which destroy an ept without assuming it is
317  * bound to an rpmsg channel. This is needed for handling the internal
318  * name service endpoint, which isn't bound to an rpmsg channel.
319  * See also __rpmsg_create_ept().
320  */
321 static void
322 __rpmsg_destroy_ept(struct virtproc_info *vrp, struct rpmsg_endpoint *ept)
323 {
324 	/* make sure new inbound messages can't find this ept anymore */
325 	mutex_lock(&vrp->endpoints_lock);
326 	idr_remove(&vrp->endpoints, ept->addr);
327 	mutex_unlock(&vrp->endpoints_lock);
328 
329 	/* make sure in-flight inbound messages won't invoke cb anymore */
330 	mutex_lock(&ept->cb_lock);
331 	ept->cb = NULL;
332 	mutex_unlock(&ept->cb_lock);
333 
334 	kref_put(&ept->refcount, __ept_release);
335 }
336 
337 /**
338  * rpmsg_destroy_ept() - destroy an existing rpmsg endpoint
339  * @ept: endpoing to destroy
340  *
341  * Should be used by drivers to destroy an rpmsg endpoint previously
342  * created with rpmsg_create_ept().
343  */
344 void rpmsg_destroy_ept(struct rpmsg_endpoint *ept)
345 {
346 	__rpmsg_destroy_ept(ept->rpdev->vrp, ept);
347 }
348 EXPORT_SYMBOL(rpmsg_destroy_ept);
349 
350 /*
351  * when an rpmsg driver is probed with a channel, we seamlessly create
352  * it an endpoint, binding its rx callback to a unique local rpmsg
353  * address.
354  *
355  * if we need to, we also announce about this channel to the remote
356  * processor (needed in case the driver is exposing an rpmsg service).
357  */
358 static int rpmsg_dev_probe(struct device *dev)
359 {
360 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
361 	struct rpmsg_driver *rpdrv = to_rpmsg_driver(rpdev->dev.driver);
362 	struct virtproc_info *vrp = rpdev->vrp;
363 	struct rpmsg_endpoint *ept;
364 	int err;
365 
366 	ept = rpmsg_create_ept(rpdev, rpdrv->callback, NULL, rpdev->src);
367 	if (!ept) {
368 		dev_err(dev, "failed to create endpoint\n");
369 		err = -ENOMEM;
370 		goto out;
371 	}
372 
373 	rpdev->ept = ept;
374 	rpdev->src = ept->addr;
375 
376 	err = rpdrv->probe(rpdev);
377 	if (err) {
378 		dev_err(dev, "%s: failed: %d\n", __func__, err);
379 		rpmsg_destroy_ept(ept);
380 		goto out;
381 	}
382 
383 	/* need to tell remote processor's name service about this channel ? */
384 	if (rpdev->announce &&
385 			virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) {
386 		struct rpmsg_ns_msg nsm;
387 
388 		strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE);
389 		nsm.addr = rpdev->src;
390 		nsm.flags = RPMSG_NS_CREATE;
391 
392 		err = rpmsg_sendto(rpdev, &nsm, sizeof(nsm), RPMSG_NS_ADDR);
393 		if (err)
394 			dev_err(dev, "failed to announce service %d\n", err);
395 	}
396 
397 out:
398 	return err;
399 }
400 
401 static int rpmsg_dev_remove(struct device *dev)
402 {
403 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
404 	struct rpmsg_driver *rpdrv = to_rpmsg_driver(rpdev->dev.driver);
405 	struct virtproc_info *vrp = rpdev->vrp;
406 	int err = 0;
407 
408 	/* tell remote processor's name service we're removing this channel */
409 	if (rpdev->announce &&
410 			virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) {
411 		struct rpmsg_ns_msg nsm;
412 
413 		strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE);
414 		nsm.addr = rpdev->src;
415 		nsm.flags = RPMSG_NS_DESTROY;
416 
417 		err = rpmsg_sendto(rpdev, &nsm, sizeof(nsm), RPMSG_NS_ADDR);
418 		if (err)
419 			dev_err(dev, "failed to announce service %d\n", err);
420 	}
421 
422 	rpdrv->remove(rpdev);
423 
424 	rpmsg_destroy_ept(rpdev->ept);
425 
426 	return err;
427 }
428 
429 static struct bus_type rpmsg_bus = {
430 	.name		= "rpmsg",
431 	.match		= rpmsg_dev_match,
432 	.dev_attrs	= rpmsg_dev_attrs,
433 	.uevent		= rpmsg_uevent,
434 	.probe		= rpmsg_dev_probe,
435 	.remove		= rpmsg_dev_remove,
436 };
437 
438 /**
439  * __register_rpmsg_driver() - register an rpmsg driver with the rpmsg bus
440  * @rpdrv: pointer to a struct rpmsg_driver
441  * @owner: owning module/driver
442  *
443  * Returns 0 on success, and an appropriate error value on failure.
444  */
445 int __register_rpmsg_driver(struct rpmsg_driver *rpdrv, struct module *owner)
446 {
447 	rpdrv->drv.bus = &rpmsg_bus;
448 	rpdrv->drv.owner = owner;
449 	return driver_register(&rpdrv->drv);
450 }
451 EXPORT_SYMBOL(__register_rpmsg_driver);
452 
453 /**
454  * unregister_rpmsg_driver() - unregister an rpmsg driver from the rpmsg bus
455  * @rpdrv: pointer to a struct rpmsg_driver
456  *
457  * Returns 0 on success, and an appropriate error value on failure.
458  */
459 void unregister_rpmsg_driver(struct rpmsg_driver *rpdrv)
460 {
461 	driver_unregister(&rpdrv->drv);
462 }
463 EXPORT_SYMBOL(unregister_rpmsg_driver);
464 
465 static void rpmsg_release_device(struct device *dev)
466 {
467 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
468 
469 	kfree(rpdev);
470 }
471 
472 /*
473  * match an rpmsg channel with a channel info struct.
474  * this is used to make sure we're not creating rpmsg devices for channels
475  * that already exist.
476  */
477 static int rpmsg_channel_match(struct device *dev, void *data)
478 {
479 	struct rpmsg_channel_info *chinfo = data;
480 	struct rpmsg_channel *rpdev = to_rpmsg_channel(dev);
481 
482 	if (chinfo->src != RPMSG_ADDR_ANY && chinfo->src != rpdev->src)
483 		return 0;
484 
485 	if (chinfo->dst != RPMSG_ADDR_ANY && chinfo->dst != rpdev->dst)
486 		return 0;
487 
488 	if (strncmp(chinfo->name, rpdev->id.name, RPMSG_NAME_SIZE))
489 		return 0;
490 
491 	/* found a match ! */
492 	return 1;
493 }
494 
495 /*
496  * create an rpmsg channel using its name and address info.
497  * this function will be used to create both static and dynamic
498  * channels.
499  */
500 static struct rpmsg_channel *rpmsg_create_channel(struct virtproc_info *vrp,
501 				struct rpmsg_channel_info *chinfo)
502 {
503 	struct rpmsg_channel *rpdev;
504 	struct device *tmp, *dev = &vrp->vdev->dev;
505 	int ret;
506 
507 	/* make sure a similar channel doesn't already exist */
508 	tmp = device_find_child(dev, chinfo, rpmsg_channel_match);
509 	if (tmp) {
510 		/* decrement the matched device's refcount back */
511 		put_device(tmp);
512 		dev_err(dev, "channel %s:%x:%x already exist\n",
513 				chinfo->name, chinfo->src, chinfo->dst);
514 		return NULL;
515 	}
516 
517 	rpdev = kzalloc(sizeof(struct rpmsg_channel), GFP_KERNEL);
518 	if (!rpdev) {
519 		pr_err("kzalloc failed\n");
520 		return NULL;
521 	}
522 
523 	rpdev->vrp = vrp;
524 	rpdev->src = chinfo->src;
525 	rpdev->dst = chinfo->dst;
526 
527 	/*
528 	 * rpmsg server channels has predefined local address (for now),
529 	 * and their existence needs to be announced remotely
530 	 */
531 	rpdev->announce = rpdev->src != RPMSG_ADDR_ANY ? true : false;
532 
533 	strncpy(rpdev->id.name, chinfo->name, RPMSG_NAME_SIZE);
534 
535 	/* very simple device indexing plumbing which is enough for now */
536 	dev_set_name(&rpdev->dev, "rpmsg%d", rpmsg_dev_index++);
537 
538 	rpdev->dev.parent = &vrp->vdev->dev;
539 	rpdev->dev.bus = &rpmsg_bus;
540 	rpdev->dev.release = rpmsg_release_device;
541 
542 	ret = device_register(&rpdev->dev);
543 	if (ret) {
544 		dev_err(dev, "device_register failed: %d\n", ret);
545 		put_device(&rpdev->dev);
546 		return NULL;
547 	}
548 
549 	return rpdev;
550 }
551 
552 /*
553  * find an existing channel using its name + address properties,
554  * and destroy it
555  */
556 static int rpmsg_destroy_channel(struct virtproc_info *vrp,
557 					struct rpmsg_channel_info *chinfo)
558 {
559 	struct virtio_device *vdev = vrp->vdev;
560 	struct device *dev;
561 
562 	dev = device_find_child(&vdev->dev, chinfo, rpmsg_channel_match);
563 	if (!dev)
564 		return -EINVAL;
565 
566 	device_unregister(dev);
567 
568 	put_device(dev);
569 
570 	return 0;
571 }
572 
573 /* super simple buffer "allocator" that is just enough for now */
574 static void *get_a_tx_buf(struct virtproc_info *vrp)
575 {
576 	unsigned int len;
577 	void *ret;
578 
579 	/* support multiple concurrent senders */
580 	mutex_lock(&vrp->tx_lock);
581 
582 	/*
583 	 * either pick the next unused tx buffer
584 	 * (half of our buffers are used for sending messages)
585 	 */
586 	if (vrp->last_sbuf < vrp->num_bufs / 2)
587 		ret = vrp->sbufs + RPMSG_BUF_SIZE * vrp->last_sbuf++;
588 	/* or recycle a used one */
589 	else
590 		ret = virtqueue_get_buf(vrp->svq, &len);
591 
592 	mutex_unlock(&vrp->tx_lock);
593 
594 	return ret;
595 }
596 
597 /**
598  * rpmsg_upref_sleepers() - enable "tx-complete" interrupts, if needed
599  * @vrp: virtual remote processor state
600  *
601  * This function is called before a sender is blocked, waiting for
602  * a tx buffer to become available.
603  *
604  * If we already have blocking senders, this function merely increases
605  * the "sleepers" reference count, and exits.
606  *
607  * Otherwise, if this is the first sender to block, we also enable
608  * virtio's tx callbacks, so we'd be immediately notified when a tx
609  * buffer is consumed (we rely on virtio's tx callback in order
610  * to wake up sleeping senders as soon as a tx buffer is used by the
611  * remote processor).
612  */
613 static void rpmsg_upref_sleepers(struct virtproc_info *vrp)
614 {
615 	/* support multiple concurrent senders */
616 	mutex_lock(&vrp->tx_lock);
617 
618 	/* are we the first sleeping context waiting for tx buffers ? */
619 	if (atomic_inc_return(&vrp->sleepers) == 1)
620 		/* enable "tx-complete" interrupts before dozing off */
621 		virtqueue_enable_cb(vrp->svq);
622 
623 	mutex_unlock(&vrp->tx_lock);
624 }
625 
626 /**
627  * rpmsg_downref_sleepers() - disable "tx-complete" interrupts, if needed
628  * @vrp: virtual remote processor state
629  *
630  * This function is called after a sender, that waited for a tx buffer
631  * to become available, is unblocked.
632  *
633  * If we still have blocking senders, this function merely decreases
634  * the "sleepers" reference count, and exits.
635  *
636  * Otherwise, if there are no more blocking senders, we also disable
637  * virtio's tx callbacks, to avoid the overhead incurred with handling
638  * those (now redundant) interrupts.
639  */
640 static void rpmsg_downref_sleepers(struct virtproc_info *vrp)
641 {
642 	/* support multiple concurrent senders */
643 	mutex_lock(&vrp->tx_lock);
644 
645 	/* are we the last sleeping context waiting for tx buffers ? */
646 	if (atomic_dec_and_test(&vrp->sleepers))
647 		/* disable "tx-complete" interrupts */
648 		virtqueue_disable_cb(vrp->svq);
649 
650 	mutex_unlock(&vrp->tx_lock);
651 }
652 
653 /**
654  * rpmsg_send_offchannel_raw() - send a message across to the remote processor
655  * @rpdev: the rpmsg channel
656  * @src: source address
657  * @dst: destination address
658  * @data: payload of message
659  * @len: length of payload
660  * @wait: indicates whether caller should block in case no TX buffers available
661  *
662  * This function is the base implementation for all of the rpmsg sending API.
663  *
664  * It will send @data of length @len to @dst, and say it's from @src. The
665  * message will be sent to the remote processor which the @rpdev channel
666  * belongs to.
667  *
668  * The message is sent using one of the TX buffers that are available for
669  * communication with this remote processor.
670  *
671  * If @wait is true, the caller will be blocked until either a TX buffer is
672  * available, or 15 seconds elapses (we don't want callers to
673  * sleep indefinitely due to misbehaving remote processors), and in that
674  * case -ERESTARTSYS is returned. The number '15' itself was picked
675  * arbitrarily; there's little point in asking drivers to provide a timeout
676  * value themselves.
677  *
678  * Otherwise, if @wait is false, and there are no TX buffers available,
679  * the function will immediately fail, and -ENOMEM will be returned.
680  *
681  * Normally drivers shouldn't use this function directly; instead, drivers
682  * should use the appropriate rpmsg_{try}send{to, _offchannel} API
683  * (see include/linux/rpmsg.h).
684  *
685  * Returns 0 on success and an appropriate error value on failure.
686  */
687 int rpmsg_send_offchannel_raw(struct rpmsg_channel *rpdev, u32 src, u32 dst,
688 					void *data, int len, bool wait)
689 {
690 	struct virtproc_info *vrp = rpdev->vrp;
691 	struct device *dev = &rpdev->dev;
692 	struct scatterlist sg;
693 	struct rpmsg_hdr *msg;
694 	int err;
695 
696 	/* bcasting isn't allowed */
697 	if (src == RPMSG_ADDR_ANY || dst == RPMSG_ADDR_ANY) {
698 		dev_err(dev, "invalid addr (src 0x%x, dst 0x%x)\n", src, dst);
699 		return -EINVAL;
700 	}
701 
702 	/*
703 	 * We currently use fixed-sized buffers, and therefore the payload
704 	 * length is limited.
705 	 *
706 	 * One of the possible improvements here is either to support
707 	 * user-provided buffers (and then we can also support zero-copy
708 	 * messaging), or to improve the buffer allocator, to support
709 	 * variable-length buffer sizes.
710 	 */
711 	if (len > RPMSG_BUF_SIZE - sizeof(struct rpmsg_hdr)) {
712 		dev_err(dev, "message is too big (%d)\n", len);
713 		return -EMSGSIZE;
714 	}
715 
716 	/* grab a buffer */
717 	msg = get_a_tx_buf(vrp);
718 	if (!msg && !wait)
719 		return -ENOMEM;
720 
721 	/* no free buffer ? wait for one (but bail after 15 seconds) */
722 	while (!msg) {
723 		/* enable "tx-complete" interrupts, if not already enabled */
724 		rpmsg_upref_sleepers(vrp);
725 
726 		/*
727 		 * sleep until a free buffer is available or 15 secs elapse.
728 		 * the timeout period is not configurable because there's
729 		 * little point in asking drivers to specify that.
730 		 * if later this happens to be required, it'd be easy to add.
731 		 */
732 		err = wait_event_interruptible_timeout(vrp->sendq,
733 					(msg = get_a_tx_buf(vrp)),
734 					msecs_to_jiffies(15000));
735 
736 		/* disable "tx-complete" interrupts if we're the last sleeper */
737 		rpmsg_downref_sleepers(vrp);
738 
739 		/* timeout ? */
740 		if (!err) {
741 			dev_err(dev, "timeout waiting for a tx buffer\n");
742 			return -ERESTARTSYS;
743 		}
744 	}
745 
746 	msg->len = len;
747 	msg->flags = 0;
748 	msg->src = src;
749 	msg->dst = dst;
750 	msg->reserved = 0;
751 	memcpy(msg->data, data, len);
752 
753 	dev_dbg(dev, "TX From 0x%x, To 0x%x, Len %d, Flags %d, Reserved %d\n",
754 					msg->src, msg->dst, msg->len,
755 					msg->flags, msg->reserved);
756 	print_hex_dump(KERN_DEBUG, "rpmsg_virtio TX: ", DUMP_PREFIX_NONE, 16, 1,
757 					msg, sizeof(*msg) + msg->len, true);
758 
759 	sg_init_one(&sg, msg, sizeof(*msg) + len);
760 
761 	mutex_lock(&vrp->tx_lock);
762 
763 	/* add message to the remote processor's virtqueue */
764 	err = virtqueue_add_outbuf(vrp->svq, &sg, 1, msg, GFP_KERNEL);
765 	if (err) {
766 		/*
767 		 * need to reclaim the buffer here, otherwise it's lost
768 		 * (memory won't leak, but rpmsg won't use it again for TX).
769 		 * this will wait for a buffer management overhaul.
770 		 */
771 		dev_err(dev, "virtqueue_add_outbuf failed: %d\n", err);
772 		goto out;
773 	}
774 
775 	/* tell the remote processor it has a pending message to read */
776 	virtqueue_kick(vrp->svq);
777 out:
778 	mutex_unlock(&vrp->tx_lock);
779 	return err;
780 }
781 EXPORT_SYMBOL(rpmsg_send_offchannel_raw);
782 
783 static int rpmsg_recv_single(struct virtproc_info *vrp, struct device *dev,
784 			     struct rpmsg_hdr *msg, unsigned int len)
785 {
786 	struct rpmsg_endpoint *ept;
787 	struct scatterlist sg;
788 	int err;
789 
790 	dev_dbg(dev, "From: 0x%x, To: 0x%x, Len: %d, Flags: %d, Reserved: %d\n",
791 					msg->src, msg->dst, msg->len,
792 					msg->flags, msg->reserved);
793 	print_hex_dump(KERN_DEBUG, "rpmsg_virtio RX: ", DUMP_PREFIX_NONE, 16, 1,
794 					msg, sizeof(*msg) + msg->len, true);
795 
796 	/*
797 	 * We currently use fixed-sized buffers, so trivially sanitize
798 	 * the reported payload length.
799 	 */
800 	if (len > RPMSG_BUF_SIZE ||
801 		msg->len > (len - sizeof(struct rpmsg_hdr))) {
802 		dev_warn(dev, "inbound msg too big: (%d, %d)\n", len, msg->len);
803 		return -EINVAL;
804 	}
805 
806 	/* use the dst addr to fetch the callback of the appropriate user */
807 	mutex_lock(&vrp->endpoints_lock);
808 
809 	ept = idr_find(&vrp->endpoints, msg->dst);
810 
811 	/* let's make sure no one deallocates ept while we use it */
812 	if (ept)
813 		kref_get(&ept->refcount);
814 
815 	mutex_unlock(&vrp->endpoints_lock);
816 
817 	if (ept) {
818 		/* make sure ept->cb doesn't go away while we use it */
819 		mutex_lock(&ept->cb_lock);
820 
821 		if (ept->cb)
822 			ept->cb(ept->rpdev, msg->data, msg->len, ept->priv,
823 				msg->src);
824 
825 		mutex_unlock(&ept->cb_lock);
826 
827 		/* farewell, ept, we don't need you anymore */
828 		kref_put(&ept->refcount, __ept_release);
829 	} else
830 		dev_warn(dev, "msg received with no recipient\n");
831 
832 	/* publish the real size of the buffer */
833 	sg_init_one(&sg, msg, RPMSG_BUF_SIZE);
834 
835 	/* add the buffer back to the remote processor's virtqueue */
836 	err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, msg, GFP_KERNEL);
837 	if (err < 0) {
838 		dev_err(dev, "failed to add a virtqueue buffer: %d\n", err);
839 		return err;
840 	}
841 
842 	return 0;
843 }
844 
845 /* called when an rx buffer is used, and it's time to digest a message */
846 static void rpmsg_recv_done(struct virtqueue *rvq)
847 {
848 	struct virtproc_info *vrp = rvq->vdev->priv;
849 	struct device *dev = &rvq->vdev->dev;
850 	struct rpmsg_hdr *msg;
851 	unsigned int len, msgs_received = 0;
852 	int err;
853 
854 	msg = virtqueue_get_buf(rvq, &len);
855 	if (!msg) {
856 		dev_err(dev, "uhm, incoming signal, but no used buffer ?\n");
857 		return;
858 	}
859 
860 	while (msg) {
861 		err = rpmsg_recv_single(vrp, dev, msg, len);
862 		if (err)
863 			break;
864 
865 		msgs_received++;
866 
867 		msg = virtqueue_get_buf(rvq, &len);
868 	};
869 
870 	dev_dbg(dev, "Received %u messages\n", msgs_received);
871 
872 	/* tell the remote processor we added another available rx buffer */
873 	if (msgs_received)
874 		virtqueue_kick(vrp->rvq);
875 }
876 
877 /*
878  * This is invoked whenever the remote processor completed processing
879  * a TX msg we just sent it, and the buffer is put back to the used ring.
880  *
881  * Normally, though, we suppress this "tx complete" interrupt in order to
882  * avoid the incurred overhead.
883  */
884 static void rpmsg_xmit_done(struct virtqueue *svq)
885 {
886 	struct virtproc_info *vrp = svq->vdev->priv;
887 
888 	dev_dbg(&svq->vdev->dev, "%s\n", __func__);
889 
890 	/* wake up potential senders that are waiting for a tx buffer */
891 	wake_up_interruptible(&vrp->sendq);
892 }
893 
894 /* invoked when a name service announcement arrives */
895 static void rpmsg_ns_cb(struct rpmsg_channel *rpdev, void *data, int len,
896 							void *priv, u32 src)
897 {
898 	struct rpmsg_ns_msg *msg = data;
899 	struct rpmsg_channel *newch;
900 	struct rpmsg_channel_info chinfo;
901 	struct virtproc_info *vrp = priv;
902 	struct device *dev = &vrp->vdev->dev;
903 	int ret;
904 
905 	print_hex_dump(KERN_DEBUG, "NS announcement: ",
906 			DUMP_PREFIX_NONE, 16, 1,
907 			data, len, true);
908 
909 	if (len != sizeof(*msg)) {
910 		dev_err(dev, "malformed ns msg (%d)\n", len);
911 		return;
912 	}
913 
914 	/*
915 	 * the name service ept does _not_ belong to a real rpmsg channel,
916 	 * and is handled by the rpmsg bus itself.
917 	 * for sanity reasons, make sure a valid rpdev has _not_ sneaked
918 	 * in somehow.
919 	 */
920 	if (rpdev) {
921 		dev_err(dev, "anomaly: ns ept has an rpdev handle\n");
922 		return;
923 	}
924 
925 	/* don't trust the remote processor for null terminating the name */
926 	msg->name[RPMSG_NAME_SIZE - 1] = '\0';
927 
928 	dev_info(dev, "%sing channel %s addr 0x%x\n",
929 			msg->flags & RPMSG_NS_DESTROY ? "destroy" : "creat",
930 			msg->name, msg->addr);
931 
932 	strncpy(chinfo.name, msg->name, sizeof(chinfo.name));
933 	chinfo.src = RPMSG_ADDR_ANY;
934 	chinfo.dst = msg->addr;
935 
936 	if (msg->flags & RPMSG_NS_DESTROY) {
937 		ret = rpmsg_destroy_channel(vrp, &chinfo);
938 		if (ret)
939 			dev_err(dev, "rpmsg_destroy_channel failed: %d\n", ret);
940 	} else {
941 		newch = rpmsg_create_channel(vrp, &chinfo);
942 		if (!newch)
943 			dev_err(dev, "rpmsg_create_channel failed\n");
944 	}
945 }
946 
947 static int rpmsg_probe(struct virtio_device *vdev)
948 {
949 	vq_callback_t *vq_cbs[] = { rpmsg_recv_done, rpmsg_xmit_done };
950 	static const char * const names[] = { "input", "output" };
951 	struct virtqueue *vqs[2];
952 	struct virtproc_info *vrp;
953 	void *bufs_va;
954 	int err = 0, i;
955 	size_t total_buf_space;
956 	bool notify;
957 
958 	vrp = kzalloc(sizeof(*vrp), GFP_KERNEL);
959 	if (!vrp)
960 		return -ENOMEM;
961 
962 	vrp->vdev = vdev;
963 
964 	idr_init(&vrp->endpoints);
965 	mutex_init(&vrp->endpoints_lock);
966 	mutex_init(&vrp->tx_lock);
967 	init_waitqueue_head(&vrp->sendq);
968 
969 	/* We expect two virtqueues, rx and tx (and in this order) */
970 	err = vdev->config->find_vqs(vdev, 2, vqs, vq_cbs, names);
971 	if (err)
972 		goto free_vrp;
973 
974 	vrp->rvq = vqs[0];
975 	vrp->svq = vqs[1];
976 
977 	/* we expect symmetric tx/rx vrings */
978 	WARN_ON(virtqueue_get_vring_size(vrp->rvq) !=
979 		virtqueue_get_vring_size(vrp->svq));
980 
981 	/* we need less buffers if vrings are small */
982 	if (virtqueue_get_vring_size(vrp->rvq) < MAX_RPMSG_NUM_BUFS / 2)
983 		vrp->num_bufs = virtqueue_get_vring_size(vrp->rvq) * 2;
984 	else
985 		vrp->num_bufs = MAX_RPMSG_NUM_BUFS;
986 
987 	total_buf_space = vrp->num_bufs * RPMSG_BUF_SIZE;
988 
989 	/* allocate coherent memory for the buffers */
990 	bufs_va = dma_alloc_coherent(vdev->dev.parent->parent,
991 				     total_buf_space, &vrp->bufs_dma,
992 				     GFP_KERNEL);
993 	if (!bufs_va) {
994 		err = -ENOMEM;
995 		goto vqs_del;
996 	}
997 
998 	dev_dbg(&vdev->dev, "buffers: va %p, dma 0x%llx\n", bufs_va,
999 					(unsigned long long)vrp->bufs_dma);
1000 
1001 	/* half of the buffers is dedicated for RX */
1002 	vrp->rbufs = bufs_va;
1003 
1004 	/* and half is dedicated for TX */
1005 	vrp->sbufs = bufs_va + total_buf_space / 2;
1006 
1007 	/* set up the receive buffers */
1008 	for (i = 0; i < vrp->num_bufs / 2; i++) {
1009 		struct scatterlist sg;
1010 		void *cpu_addr = vrp->rbufs + i * RPMSG_BUF_SIZE;
1011 
1012 		sg_init_one(&sg, cpu_addr, RPMSG_BUF_SIZE);
1013 
1014 		err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, cpu_addr,
1015 								GFP_KERNEL);
1016 		WARN_ON(err); /* sanity check; this can't really happen */
1017 	}
1018 
1019 	/* suppress "tx-complete" interrupts */
1020 	virtqueue_disable_cb(vrp->svq);
1021 
1022 	vdev->priv = vrp;
1023 
1024 	/* if supported by the remote processor, enable the name service */
1025 	if (virtio_has_feature(vdev, VIRTIO_RPMSG_F_NS)) {
1026 		/* a dedicated endpoint handles the name service msgs */
1027 		vrp->ns_ept = __rpmsg_create_ept(vrp, NULL, rpmsg_ns_cb,
1028 						vrp, RPMSG_NS_ADDR);
1029 		if (!vrp->ns_ept) {
1030 			dev_err(&vdev->dev, "failed to create the ns ept\n");
1031 			err = -ENOMEM;
1032 			goto free_coherent;
1033 		}
1034 	}
1035 
1036 	/*
1037 	 * Prepare to kick but don't notify yet - we can't do this before
1038 	 * device is ready.
1039 	 */
1040 	notify = virtqueue_kick_prepare(vrp->rvq);
1041 
1042 	/* From this point on, we can notify and get callbacks. */
1043 	virtio_device_ready(vdev);
1044 
1045 	/* tell the remote processor it can start sending messages */
1046 	/*
1047 	 * this might be concurrent with callbacks, but we are only
1048 	 * doing notify, not a full kick here, so that's ok.
1049 	 */
1050 	if (notify)
1051 		virtqueue_notify(vrp->rvq);
1052 
1053 	dev_info(&vdev->dev, "rpmsg host is online\n");
1054 
1055 	return 0;
1056 
1057 free_coherent:
1058 	dma_free_coherent(vdev->dev.parent->parent, total_buf_space,
1059 			  bufs_va, vrp->bufs_dma);
1060 vqs_del:
1061 	vdev->config->del_vqs(vrp->vdev);
1062 free_vrp:
1063 	kfree(vrp);
1064 	return err;
1065 }
1066 
1067 static int rpmsg_remove_device(struct device *dev, void *data)
1068 {
1069 	device_unregister(dev);
1070 
1071 	return 0;
1072 }
1073 
1074 static void rpmsg_remove(struct virtio_device *vdev)
1075 {
1076 	struct virtproc_info *vrp = vdev->priv;
1077 	size_t total_buf_space = vrp->num_bufs * RPMSG_BUF_SIZE;
1078 	int ret;
1079 
1080 	vdev->config->reset(vdev);
1081 
1082 	ret = device_for_each_child(&vdev->dev, NULL, rpmsg_remove_device);
1083 	if (ret)
1084 		dev_warn(&vdev->dev, "can't remove rpmsg device: %d\n", ret);
1085 
1086 	if (vrp->ns_ept)
1087 		__rpmsg_destroy_ept(vrp, vrp->ns_ept);
1088 
1089 	idr_destroy(&vrp->endpoints);
1090 
1091 	vdev->config->del_vqs(vrp->vdev);
1092 
1093 	dma_free_coherent(vdev->dev.parent->parent, total_buf_space,
1094 			  vrp->rbufs, vrp->bufs_dma);
1095 
1096 	kfree(vrp);
1097 }
1098 
1099 static struct virtio_device_id id_table[] = {
1100 	{ VIRTIO_ID_RPMSG, VIRTIO_DEV_ANY_ID },
1101 	{ 0 },
1102 };
1103 
1104 static unsigned int features[] = {
1105 	VIRTIO_RPMSG_F_NS,
1106 };
1107 
1108 static struct virtio_driver virtio_ipc_driver = {
1109 	.feature_table	= features,
1110 	.feature_table_size = ARRAY_SIZE(features),
1111 	.driver.name	= KBUILD_MODNAME,
1112 	.driver.owner	= THIS_MODULE,
1113 	.id_table	= id_table,
1114 	.probe		= rpmsg_probe,
1115 	.remove		= rpmsg_remove,
1116 };
1117 
1118 static int __init rpmsg_init(void)
1119 {
1120 	int ret;
1121 
1122 	ret = bus_register(&rpmsg_bus);
1123 	if (ret) {
1124 		pr_err("failed to register rpmsg bus: %d\n", ret);
1125 		return ret;
1126 	}
1127 
1128 	ret = register_virtio_driver(&virtio_ipc_driver);
1129 	if (ret) {
1130 		pr_err("failed to register virtio driver: %d\n", ret);
1131 		bus_unregister(&rpmsg_bus);
1132 	}
1133 
1134 	return ret;
1135 }
1136 subsys_initcall(rpmsg_init);
1137 
1138 static void __exit rpmsg_fini(void)
1139 {
1140 	unregister_virtio_driver(&virtio_ipc_driver);
1141 	bus_unregister(&rpmsg_bus);
1142 }
1143 module_exit(rpmsg_fini);
1144 
1145 MODULE_DEVICE_TABLE(virtio, id_table);
1146 MODULE_DESCRIPTION("Virtio-based remote processor messaging bus");
1147 MODULE_LICENSE("GPL v2");
1148