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