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