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