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