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