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