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