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