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