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  */
57 struct 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  */
87 struct 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  */
108 struct 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  */
120 enum rpmsg_ns_flags {
121 	RPMSG_NS_CREATE		= 0,
122 	RPMSG_NS_DESTROY	= 1,
123 };
124 
125 /**
126  * @vrp: the remote processor this channel belongs to
127  */
128 struct virtio_rpmsg_channel {
129 	struct rpmsg_device rpdev;
130 
131 	struct virtproc_info *vrp;
132 };
133 
134 #define to_virtio_rpmsg_channel(_rpdev) \
135 	container_of(_rpdev, struct virtio_rpmsg_channel, rpdev)
136 
137 /*
138  * We're allocating buffers of 512 bytes each for communications. The
139  * number of buffers will be computed from the number of buffers supported
140  * by the vring, upto a maximum of 512 buffers (256 in each direction).
141  *
142  * Each buffer will have 16 bytes for the msg header and 496 bytes for
143  * the payload.
144  *
145  * This will utilize a maximum total space of 256KB for the buffers.
146  *
147  * We might also want to add support for user-provided buffers in time.
148  * This will allow bigger buffer size flexibility, and can also be used
149  * to achieve zero-copy messaging.
150  *
151  * Note that these numbers are purely a decision of this driver - we
152  * can change this without changing anything in the firmware of the remote
153  * processor.
154  */
155 #define MAX_RPMSG_NUM_BUFS	(512)
156 #define MAX_RPMSG_BUF_SIZE	(512)
157 
158 /*
159  * Local addresses are dynamically allocated on-demand.
160  * We do not dynamically assign addresses from the low 1024 range,
161  * in order to reserve that address range for predefined services.
162  */
163 #define RPMSG_RESERVED_ADDRESSES	(1024)
164 
165 /* Address 53 is reserved for advertising remote services */
166 #define RPMSG_NS_ADDR			(53)
167 
168 static void virtio_rpmsg_destroy_ept(struct rpmsg_endpoint *ept);
169 static int virtio_rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len);
170 static int virtio_rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len,
171 			       u32 dst);
172 static int virtio_rpmsg_send_offchannel(struct rpmsg_endpoint *ept, u32 src,
173 					u32 dst, void *data, int len);
174 static int virtio_rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len);
175 static int virtio_rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data,
176 				  int len, u32 dst);
177 static int virtio_rpmsg_trysend_offchannel(struct rpmsg_endpoint *ept, u32 src,
178 					   u32 dst, void *data, int len);
179 
180 static const struct rpmsg_endpoint_ops virtio_endpoint_ops = {
181 	.destroy_ept = virtio_rpmsg_destroy_ept,
182 	.send = virtio_rpmsg_send,
183 	.sendto = virtio_rpmsg_sendto,
184 	.send_offchannel = virtio_rpmsg_send_offchannel,
185 	.trysend = virtio_rpmsg_trysend,
186 	.trysendto = virtio_rpmsg_trysendto,
187 	.trysend_offchannel = virtio_rpmsg_trysend_offchannel,
188 };
189 
190 /**
191  * rpmsg_sg_init - initialize scatterlist according to cpu address location
192  * @sg: scatterlist to fill
193  * @cpu_addr: virtual address of the buffer
194  * @len: buffer length
195  *
196  * An internal function filling scatterlist according to virtual address
197  * location (in vmalloc or in kernel).
198  */
199 static void
200 rpmsg_sg_init(struct scatterlist *sg, void *cpu_addr, unsigned int len)
201 {
202 	if (is_vmalloc_addr(cpu_addr)) {
203 		sg_init_table(sg, 1);
204 		sg_set_page(sg, vmalloc_to_page(cpu_addr), len,
205 			    offset_in_page(cpu_addr));
206 	} else {
207 		WARN_ON(!virt_addr_valid(cpu_addr));
208 		sg_init_one(sg, cpu_addr, len);
209 	}
210 }
211 
212 /**
213  * __ept_release() - deallocate an rpmsg endpoint
214  * @kref: the ept's reference count
215  *
216  * This function deallocates an ept, and is invoked when its @kref refcount
217  * drops to zero.
218  *
219  * Never invoke this function directly!
220  */
221 static void __ept_release(struct kref *kref)
222 {
223 	struct rpmsg_endpoint *ept = container_of(kref, struct rpmsg_endpoint,
224 						  refcount);
225 	/*
226 	 * At this point no one holds a reference to ept anymore,
227 	 * so we can directly free it
228 	 */
229 	kfree(ept);
230 }
231 
232 /* for more info, see below documentation of rpmsg_create_ept() */
233 static struct rpmsg_endpoint *__rpmsg_create_ept(struct virtproc_info *vrp,
234 						 struct rpmsg_device *rpdev,
235 						 rpmsg_rx_cb_t cb,
236 						 void *priv, u32 addr)
237 {
238 	int id_min, id_max, id;
239 	struct rpmsg_endpoint *ept;
240 	struct device *dev = rpdev ? &rpdev->dev : &vrp->vdev->dev;
241 
242 	ept = kzalloc(sizeof(*ept), GFP_KERNEL);
243 	if (!ept)
244 		return NULL;
245 
246 	kref_init(&ept->refcount);
247 	mutex_init(&ept->cb_lock);
248 
249 	ept->rpdev = rpdev;
250 	ept->cb = cb;
251 	ept->priv = priv;
252 	ept->ops = &virtio_endpoint_ops;
253 
254 	/* do we need to allocate a local address ? */
255 	if (addr == RPMSG_ADDR_ANY) {
256 		id_min = RPMSG_RESERVED_ADDRESSES;
257 		id_max = 0;
258 	} else {
259 		id_min = addr;
260 		id_max = addr + 1;
261 	}
262 
263 	mutex_lock(&vrp->endpoints_lock);
264 
265 	/* bind the endpoint to an rpmsg address (and allocate one if needed) */
266 	id = idr_alloc(&vrp->endpoints, ept, id_min, id_max, GFP_KERNEL);
267 	if (id < 0) {
268 		dev_err(dev, "idr_alloc failed: %d\n", id);
269 		goto free_ept;
270 	}
271 	ept->addr = id;
272 
273 	mutex_unlock(&vrp->endpoints_lock);
274 
275 	return ept;
276 
277 free_ept:
278 	mutex_unlock(&vrp->endpoints_lock);
279 	kref_put(&ept->refcount, __ept_release);
280 	return NULL;
281 }
282 
283 static struct rpmsg_endpoint *virtio_rpmsg_create_ept(struct rpmsg_device *rpdev,
284 						      rpmsg_rx_cb_t cb,
285 						      void *priv,
286 						      struct rpmsg_channel_info chinfo)
287 {
288 	struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
289 
290 	return __rpmsg_create_ept(vch->vrp, rpdev, cb, priv, chinfo.src);
291 }
292 
293 /**
294  * __rpmsg_destroy_ept() - destroy an existing rpmsg endpoint
295  * @vrp: virtproc which owns this ept
296  * @ept: endpoing to destroy
297  *
298  * An internal function which destroy an ept without assuming it is
299  * bound to an rpmsg channel. This is needed for handling the internal
300  * name service endpoint, which isn't bound to an rpmsg channel.
301  * See also __rpmsg_create_ept().
302  */
303 static void
304 __rpmsg_destroy_ept(struct virtproc_info *vrp, struct rpmsg_endpoint *ept)
305 {
306 	/* make sure new inbound messages can't find this ept anymore */
307 	mutex_lock(&vrp->endpoints_lock);
308 	idr_remove(&vrp->endpoints, ept->addr);
309 	mutex_unlock(&vrp->endpoints_lock);
310 
311 	/* make sure in-flight inbound messages won't invoke cb anymore */
312 	mutex_lock(&ept->cb_lock);
313 	ept->cb = NULL;
314 	mutex_unlock(&ept->cb_lock);
315 
316 	kref_put(&ept->refcount, __ept_release);
317 }
318 
319 static void virtio_rpmsg_destroy_ept(struct rpmsg_endpoint *ept)
320 {
321 	struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(ept->rpdev);
322 
323 	__rpmsg_destroy_ept(vch->vrp, ept);
324 }
325 
326 static int virtio_rpmsg_announce_create(struct rpmsg_device *rpdev)
327 {
328 	struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
329 	struct virtproc_info *vrp = vch->vrp;
330 	struct device *dev = &rpdev->dev;
331 	int err = 0;
332 
333 	/* need to tell remote processor's name service about this channel ? */
334 	if (rpdev->announce && rpdev->ept &&
335 	    virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) {
336 		struct rpmsg_ns_msg nsm;
337 
338 		strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE);
339 		nsm.addr = cpu_to_virtio32(vrp->vdev, rpdev->ept->addr);
340 		nsm.flags = cpu_to_virtio32(vrp->vdev, RPMSG_NS_CREATE);
341 
342 		err = rpmsg_sendto(rpdev->ept, &nsm, sizeof(nsm), RPMSG_NS_ADDR);
343 		if (err)
344 			dev_err(dev, "failed to announce service %d\n", err);
345 	}
346 
347 	return err;
348 }
349 
350 static int virtio_rpmsg_announce_destroy(struct rpmsg_device *rpdev)
351 {
352 	struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
353 	struct virtproc_info *vrp = vch->vrp;
354 	struct device *dev = &rpdev->dev;
355 	int err = 0;
356 
357 	/* tell remote processor's name service we're removing this channel */
358 	if (rpdev->announce && rpdev->ept &&
359 	    virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) {
360 		struct rpmsg_ns_msg nsm;
361 
362 		strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE);
363 		nsm.addr = cpu_to_virtio32(vrp->vdev, rpdev->ept->addr);
364 		nsm.flags = cpu_to_virtio32(vrp->vdev, RPMSG_NS_DESTROY);
365 
366 		err = rpmsg_sendto(rpdev->ept, &nsm, sizeof(nsm), RPMSG_NS_ADDR);
367 		if (err)
368 			dev_err(dev, "failed to announce service %d\n", err);
369 	}
370 
371 	return err;
372 }
373 
374 static const struct rpmsg_device_ops virtio_rpmsg_ops = {
375 	.create_ept = virtio_rpmsg_create_ept,
376 	.announce_create = virtio_rpmsg_announce_create,
377 	.announce_destroy = virtio_rpmsg_announce_destroy,
378 };
379 
380 static void virtio_rpmsg_release_device(struct device *dev)
381 {
382 	struct rpmsg_device *rpdev = to_rpmsg_device(dev);
383 	struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
384 
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  */
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 */
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  */
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  */
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  */
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 = cpu_to_virtio16(vrp->vdev, len);
617 	msg->flags = 0;
618 	msg->src = cpu_to_virtio32(vrp->vdev, src);
619 	msg->dst = cpu_to_virtio32(vrp->vdev, 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 		src, dst, 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) + 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 
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 
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 
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 
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 
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 
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 
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 	unsigned int msg_len = virtio16_to_cpu(vrp->vdev, msg->len);
709 	int err;
710 
711 	dev_dbg(dev, "From: 0x%x, To: 0x%x, Len: %d, Flags: %d, Reserved: %d\n",
712 		virtio32_to_cpu(vrp->vdev, msg->src),
713 		virtio32_to_cpu(vrp->vdev, msg->dst), msg_len,
714 		virtio16_to_cpu(vrp->vdev, msg->flags),
715 		virtio32_to_cpu(vrp->vdev, msg->reserved));
716 #if defined(CONFIG_DYNAMIC_DEBUG)
717 	dynamic_hex_dump("rpmsg_virtio RX: ", DUMP_PREFIX_NONE, 16, 1,
718 			 msg, sizeof(*msg) + msg_len, true);
719 #endif
720 
721 	/*
722 	 * We currently use fixed-sized buffers, so trivially sanitize
723 	 * the reported payload length.
724 	 */
725 	if (len > vrp->buf_size ||
726 	    msg_len > (len - sizeof(struct rpmsg_hdr))) {
727 		dev_warn(dev, "inbound msg too big: (%d, %d)\n", len, msg_len);
728 		return -EINVAL;
729 	}
730 
731 	/* use the dst addr to fetch the callback of the appropriate user */
732 	mutex_lock(&vrp->endpoints_lock);
733 
734 	ept = idr_find(&vrp->endpoints, virtio32_to_cpu(vrp->vdev, msg->dst));
735 
736 	/* let's make sure no one deallocates ept while we use it */
737 	if (ept)
738 		kref_get(&ept->refcount);
739 
740 	mutex_unlock(&vrp->endpoints_lock);
741 
742 	if (ept) {
743 		/* make sure ept->cb doesn't go away while we use it */
744 		mutex_lock(&ept->cb_lock);
745 
746 		if (ept->cb)
747 			ept->cb(ept->rpdev, msg->data, msg_len, ept->priv,
748 				virtio32_to_cpu(vrp->vdev, msg->src));
749 
750 		mutex_unlock(&ept->cb_lock);
751 
752 		/* farewell, ept, we don't need you anymore */
753 		kref_put(&ept->refcount, __ept_release);
754 	} else
755 		dev_warn(dev, "msg received with no recipient\n");
756 
757 	/* publish the real size of the buffer */
758 	rpmsg_sg_init(&sg, msg, vrp->buf_size);
759 
760 	/* add the buffer back to the remote processor's virtqueue */
761 	err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, msg, GFP_KERNEL);
762 	if (err < 0) {
763 		dev_err(dev, "failed to add a virtqueue buffer: %d\n", err);
764 		return err;
765 	}
766 
767 	return 0;
768 }
769 
770 /* called when an rx buffer is used, and it's time to digest a message */
771 static void rpmsg_recv_done(struct virtqueue *rvq)
772 {
773 	struct virtproc_info *vrp = rvq->vdev->priv;
774 	struct device *dev = &rvq->vdev->dev;
775 	struct rpmsg_hdr *msg;
776 	unsigned int len, msgs_received = 0;
777 	int err;
778 
779 	msg = virtqueue_get_buf(rvq, &len);
780 	if (!msg) {
781 		dev_err(dev, "uhm, incoming signal, but no used buffer ?\n");
782 		return;
783 	}
784 
785 	while (msg) {
786 		err = rpmsg_recv_single(vrp, dev, msg, len);
787 		if (err)
788 			break;
789 
790 		msgs_received++;
791 
792 		msg = virtqueue_get_buf(rvq, &len);
793 	}
794 
795 	dev_dbg(dev, "Received %u messages\n", msgs_received);
796 
797 	/* tell the remote processor we added another available rx buffer */
798 	if (msgs_received)
799 		virtqueue_kick(vrp->rvq);
800 }
801 
802 /*
803  * This is invoked whenever the remote processor completed processing
804  * a TX msg we just sent it, and the buffer is put back to the used ring.
805  *
806  * Normally, though, we suppress this "tx complete" interrupt in order to
807  * avoid the incurred overhead.
808  */
809 static void rpmsg_xmit_done(struct virtqueue *svq)
810 {
811 	struct virtproc_info *vrp = svq->vdev->priv;
812 
813 	dev_dbg(&svq->vdev->dev, "%s\n", __func__);
814 
815 	/* wake up potential senders that are waiting for a tx buffer */
816 	wake_up_interruptible(&vrp->sendq);
817 }
818 
819 /* invoked when a name service announcement arrives */
820 static int rpmsg_ns_cb(struct rpmsg_device *rpdev, void *data, int len,
821 		       void *priv, u32 src)
822 {
823 	struct rpmsg_ns_msg *msg = data;
824 	struct rpmsg_device *newch;
825 	struct rpmsg_channel_info chinfo;
826 	struct virtproc_info *vrp = priv;
827 	struct device *dev = &vrp->vdev->dev;
828 	int ret;
829 
830 #if defined(CONFIG_DYNAMIC_DEBUG)
831 	dynamic_hex_dump("NS announcement: ", DUMP_PREFIX_NONE, 16, 1,
832 			 data, len, true);
833 #endif
834 
835 	if (len != sizeof(*msg)) {
836 		dev_err(dev, "malformed ns msg (%d)\n", len);
837 		return -EINVAL;
838 	}
839 
840 	/*
841 	 * the name service ept does _not_ belong to a real rpmsg channel,
842 	 * and is handled by the rpmsg bus itself.
843 	 * for sanity reasons, make sure a valid rpdev has _not_ sneaked
844 	 * in somehow.
845 	 */
846 	if (rpdev) {
847 		dev_err(dev, "anomaly: ns ept has an rpdev handle\n");
848 		return -EINVAL;
849 	}
850 
851 	/* don't trust the remote processor for null terminating the name */
852 	msg->name[RPMSG_NAME_SIZE - 1] = '\0';
853 
854 	strncpy(chinfo.name, msg->name, sizeof(chinfo.name));
855 	chinfo.src = RPMSG_ADDR_ANY;
856 	chinfo.dst = virtio32_to_cpu(vrp->vdev, msg->addr);
857 
858 	dev_info(dev, "%sing channel %s addr 0x%x\n",
859 		 virtio32_to_cpu(vrp->vdev, msg->flags) & RPMSG_NS_DESTROY ?
860 		 "destroy" : "creat", msg->name, chinfo.dst);
861 
862 	if (virtio32_to_cpu(vrp->vdev, msg->flags) & RPMSG_NS_DESTROY) {
863 		ret = rpmsg_unregister_device(&vrp->vdev->dev, &chinfo);
864 		if (ret)
865 			dev_err(dev, "rpmsg_destroy_channel failed: %d\n", ret);
866 	} else {
867 		newch = rpmsg_create_channel(vrp, &chinfo);
868 		if (!newch)
869 			dev_err(dev, "rpmsg_create_channel failed\n");
870 	}
871 
872 	return 0;
873 }
874 
875 static int rpmsg_probe(struct virtio_device *vdev)
876 {
877 	vq_callback_t *vq_cbs[] = { rpmsg_recv_done, rpmsg_xmit_done };
878 	static const char * const names[] = { "input", "output" };
879 	struct virtqueue *vqs[2];
880 	struct virtproc_info *vrp;
881 	void *bufs_va;
882 	int err = 0, i;
883 	size_t total_buf_space;
884 	bool notify;
885 
886 	vrp = kzalloc(sizeof(*vrp), GFP_KERNEL);
887 	if (!vrp)
888 		return -ENOMEM;
889 
890 	vrp->vdev = vdev;
891 
892 	idr_init(&vrp->endpoints);
893 	mutex_init(&vrp->endpoints_lock);
894 	mutex_init(&vrp->tx_lock);
895 	init_waitqueue_head(&vrp->sendq);
896 
897 	/* We expect two virtqueues, rx and tx (and in this order) */
898 	err = virtio_find_vqs(vdev, 2, vqs, vq_cbs, names, NULL);
899 	if (err)
900 		goto free_vrp;
901 
902 	vrp->rvq = vqs[0];
903 	vrp->svq = vqs[1];
904 
905 	/* we expect symmetric tx/rx vrings */
906 	WARN_ON(virtqueue_get_vring_size(vrp->rvq) !=
907 		virtqueue_get_vring_size(vrp->svq));
908 
909 	/* we need less buffers if vrings are small */
910 	if (virtqueue_get_vring_size(vrp->rvq) < MAX_RPMSG_NUM_BUFS / 2)
911 		vrp->num_bufs = virtqueue_get_vring_size(vrp->rvq) * 2;
912 	else
913 		vrp->num_bufs = MAX_RPMSG_NUM_BUFS;
914 
915 	vrp->buf_size = MAX_RPMSG_BUF_SIZE;
916 
917 	total_buf_space = vrp->num_bufs * vrp->buf_size;
918 
919 	/* allocate coherent memory for the buffers */
920 	bufs_va = dma_alloc_coherent(vdev->dev.parent,
921 				     total_buf_space, &vrp->bufs_dma,
922 				     GFP_KERNEL);
923 	if (!bufs_va) {
924 		err = -ENOMEM;
925 		goto vqs_del;
926 	}
927 
928 	dev_dbg(&vdev->dev, "buffers: va %pK, dma %pad\n",
929 		bufs_va, &vrp->bufs_dma);
930 
931 	/* half of the buffers is dedicated for RX */
932 	vrp->rbufs = bufs_va;
933 
934 	/* and half is dedicated for TX */
935 	vrp->sbufs = bufs_va + total_buf_space / 2;
936 
937 	/* set up the receive buffers */
938 	for (i = 0; i < vrp->num_bufs / 2; i++) {
939 		struct scatterlist sg;
940 		void *cpu_addr = vrp->rbufs + i * vrp->buf_size;
941 
942 		rpmsg_sg_init(&sg, cpu_addr, vrp->buf_size);
943 
944 		err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, cpu_addr,
945 					  GFP_KERNEL);
946 		WARN_ON(err); /* sanity check; this can't really happen */
947 	}
948 
949 	/* suppress "tx-complete" interrupts */
950 	virtqueue_disable_cb(vrp->svq);
951 
952 	vdev->priv = vrp;
953 
954 	/* if supported by the remote processor, enable the name service */
955 	if (virtio_has_feature(vdev, VIRTIO_RPMSG_F_NS)) {
956 		/* a dedicated endpoint handles the name service msgs */
957 		vrp->ns_ept = __rpmsg_create_ept(vrp, NULL, rpmsg_ns_cb,
958 						vrp, RPMSG_NS_ADDR);
959 		if (!vrp->ns_ept) {
960 			dev_err(&vdev->dev, "failed to create the ns ept\n");
961 			err = -ENOMEM;
962 			goto free_coherent;
963 		}
964 	}
965 
966 	/*
967 	 * Prepare to kick but don't notify yet - we can't do this before
968 	 * device is ready.
969 	 */
970 	notify = virtqueue_kick_prepare(vrp->rvq);
971 
972 	/* From this point on, we can notify and get callbacks. */
973 	virtio_device_ready(vdev);
974 
975 	/* tell the remote processor it can start sending messages */
976 	/*
977 	 * this might be concurrent with callbacks, but we are only
978 	 * doing notify, not a full kick here, so that's ok.
979 	 */
980 	if (notify)
981 		virtqueue_notify(vrp->rvq);
982 
983 	dev_info(&vdev->dev, "rpmsg host is online\n");
984 
985 	return 0;
986 
987 free_coherent:
988 	dma_free_coherent(vdev->dev.parent, total_buf_space,
989 			  bufs_va, vrp->bufs_dma);
990 vqs_del:
991 	vdev->config->del_vqs(vrp->vdev);
992 free_vrp:
993 	kfree(vrp);
994 	return err;
995 }
996 
997 static int rpmsg_remove_device(struct device *dev, void *data)
998 {
999 	device_unregister(dev);
1000 
1001 	return 0;
1002 }
1003 
1004 static void rpmsg_remove(struct virtio_device *vdev)
1005 {
1006 	struct virtproc_info *vrp = vdev->priv;
1007 	size_t total_buf_space = vrp->num_bufs * vrp->buf_size;
1008 	int ret;
1009 
1010 	vdev->config->reset(vdev);
1011 
1012 	ret = device_for_each_child(&vdev->dev, NULL, rpmsg_remove_device);
1013 	if (ret)
1014 		dev_warn(&vdev->dev, "can't remove rpmsg device: %d\n", ret);
1015 
1016 	if (vrp->ns_ept)
1017 		__rpmsg_destroy_ept(vrp, vrp->ns_ept);
1018 
1019 	idr_destroy(&vrp->endpoints);
1020 
1021 	vdev->config->del_vqs(vrp->vdev);
1022 
1023 	dma_free_coherent(vdev->dev.parent, total_buf_space,
1024 			  vrp->rbufs, vrp->bufs_dma);
1025 
1026 	kfree(vrp);
1027 }
1028 
1029 static struct virtio_device_id id_table[] = {
1030 	{ VIRTIO_ID_RPMSG, VIRTIO_DEV_ANY_ID },
1031 	{ 0 },
1032 };
1033 
1034 static unsigned int features[] = {
1035 	VIRTIO_RPMSG_F_NS,
1036 };
1037 
1038 static struct virtio_driver virtio_ipc_driver = {
1039 	.feature_table	= features,
1040 	.feature_table_size = ARRAY_SIZE(features),
1041 	.driver.name	= KBUILD_MODNAME,
1042 	.driver.owner	= THIS_MODULE,
1043 	.id_table	= id_table,
1044 	.probe		= rpmsg_probe,
1045 	.remove		= rpmsg_remove,
1046 };
1047 
1048 static int __init rpmsg_init(void)
1049 {
1050 	int ret;
1051 
1052 	ret = register_virtio_driver(&virtio_ipc_driver);
1053 	if (ret)
1054 		pr_err("failed to register virtio driver: %d\n", ret);
1055 
1056 	return ret;
1057 }
1058 subsys_initcall(rpmsg_init);
1059 
1060 static void __exit rpmsg_fini(void)
1061 {
1062 	unregister_virtio_driver(&virtio_ipc_driver);
1063 }
1064 module_exit(rpmsg_fini);
1065 
1066 MODULE_DEVICE_TABLE(virtio, id_table);
1067 MODULE_DESCRIPTION("Virtio-based remote processor messaging bus");
1068 MODULE_LICENSE("GPL v2");
1069