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