Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Virtio-based remote processor messaging bus
0004  *
0005  * Copyright (C) 2011 Texas Instruments, Inc.
0006  * Copyright (C) 2011 Google, Inc.
0007  *
0008  * Ohad Ben-Cohen <ohad@wizery.com>
0009  * Brian Swetland <swetland@google.com>
0010  */
0011 
0012 #define pr_fmt(fmt) "%s: " fmt, __func__
0013 
0014 #include <linux/dma-mapping.h>
0015 #include <linux/idr.h>
0016 #include <linux/jiffies.h>
0017 #include <linux/kernel.h>
0018 #include <linux/module.h>
0019 #include <linux/mutex.h>
0020 #include <linux/rpmsg.h>
0021 #include <linux/rpmsg/byteorder.h>
0022 #include <linux/rpmsg/ns.h>
0023 #include <linux/scatterlist.h>
0024 #include <linux/slab.h>
0025 #include <linux/sched.h>
0026 #include <linux/virtio.h>
0027 #include <linux/virtio_ids.h>
0028 #include <linux/virtio_config.h>
0029 #include <linux/wait.h>
0030 
0031 #include "rpmsg_internal.h"
0032 
0033 /**
0034  * struct virtproc_info - virtual remote processor state
0035  * @vdev:   the virtio device
0036  * @rvq:    rx virtqueue
0037  * @svq:    tx virtqueue
0038  * @rbufs:  kernel address of rx buffers
0039  * @sbufs:  kernel address of tx buffers
0040  * @num_bufs:   total number of buffers for rx and tx
0041  * @buf_size:   size of one rx or tx buffer
0042  * @last_sbuf:  index of last tx buffer used
0043  * @bufs_dma:   dma base addr of the buffers
0044  * @tx_lock:    protects svq, sbufs and sleepers, to allow concurrent senders.
0045  *      sending a message might require waking up a dozing remote
0046  *      processor, which involves sleeping, hence the mutex.
0047  * @endpoints:  idr of local endpoints, allows fast retrieval
0048  * @endpoints_lock: lock of the endpoints set
0049  * @sendq:  wait queue of sending contexts waiting for a tx buffers
0050  * @sleepers:   number of senders that are waiting for a tx buffer
0051  *
0052  * This structure stores the rpmsg state of a given virtio remote processor
0053  * device (there might be several virtio proc devices for each physical
0054  * remote processor).
0055  */
0056 struct virtproc_info {
0057     struct virtio_device *vdev;
0058     struct virtqueue *rvq, *svq;
0059     void *rbufs, *sbufs;
0060     unsigned int num_bufs;
0061     unsigned int buf_size;
0062     int last_sbuf;
0063     dma_addr_t bufs_dma;
0064     struct mutex tx_lock;
0065     struct idr endpoints;
0066     struct mutex endpoints_lock;
0067     wait_queue_head_t sendq;
0068     atomic_t sleepers;
0069 };
0070 
0071 /* The feature bitmap for virtio rpmsg */
0072 #define VIRTIO_RPMSG_F_NS   0 /* RP supports name service notifications */
0073 
0074 /**
0075  * struct rpmsg_hdr - common header for all rpmsg messages
0076  * @src: source address
0077  * @dst: destination address
0078  * @reserved: reserved for future use
0079  * @len: length of payload (in bytes)
0080  * @flags: message flags
0081  * @data: @len bytes of message payload data
0082  *
0083  * Every message sent(/received) on the rpmsg bus begins with this header.
0084  */
0085 struct rpmsg_hdr {
0086     __rpmsg32 src;
0087     __rpmsg32 dst;
0088     __rpmsg32 reserved;
0089     __rpmsg16 len;
0090     __rpmsg16 flags;
0091     u8 data[];
0092 } __packed;
0093 
0094 
0095 /**
0096  * struct virtio_rpmsg_channel - rpmsg channel descriptor
0097  * @rpdev: the rpmsg channel device
0098  * @vrp: the virtio remote processor device this channel belongs to
0099  *
0100  * This structure stores the channel that links the rpmsg device to the virtio
0101  * remote processor device.
0102  */
0103 struct virtio_rpmsg_channel {
0104     struct rpmsg_device rpdev;
0105 
0106     struct virtproc_info *vrp;
0107 };
0108 
0109 #define to_virtio_rpmsg_channel(_rpdev) \
0110     container_of(_rpdev, struct virtio_rpmsg_channel, rpdev)
0111 
0112 /*
0113  * We're allocating buffers of 512 bytes each for communications. The
0114  * number of buffers will be computed from the number of buffers supported
0115  * by the vring, upto a maximum of 512 buffers (256 in each direction).
0116  *
0117  * Each buffer will have 16 bytes for the msg header and 496 bytes for
0118  * the payload.
0119  *
0120  * This will utilize a maximum total space of 256KB for the buffers.
0121  *
0122  * We might also want to add support for user-provided buffers in time.
0123  * This will allow bigger buffer size flexibility, and can also be used
0124  * to achieve zero-copy messaging.
0125  *
0126  * Note that these numbers are purely a decision of this driver - we
0127  * can change this without changing anything in the firmware of the remote
0128  * processor.
0129  */
0130 #define MAX_RPMSG_NUM_BUFS  (512)
0131 #define MAX_RPMSG_BUF_SIZE  (512)
0132 
0133 /*
0134  * Local addresses are dynamically allocated on-demand.
0135  * We do not dynamically assign addresses from the low 1024 range,
0136  * in order to reserve that address range for predefined services.
0137  */
0138 #define RPMSG_RESERVED_ADDRESSES    (1024)
0139 
0140 static void virtio_rpmsg_destroy_ept(struct rpmsg_endpoint *ept);
0141 static int virtio_rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len);
0142 static int virtio_rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len,
0143                    u32 dst);
0144 static int virtio_rpmsg_send_offchannel(struct rpmsg_endpoint *ept, u32 src,
0145                     u32 dst, void *data, int len);
0146 static int virtio_rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len);
0147 static int virtio_rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data,
0148                   int len, u32 dst);
0149 static int virtio_rpmsg_trysend_offchannel(struct rpmsg_endpoint *ept, u32 src,
0150                        u32 dst, void *data, int len);
0151 static ssize_t virtio_rpmsg_get_mtu(struct rpmsg_endpoint *ept);
0152 static struct rpmsg_device *__rpmsg_create_channel(struct virtproc_info *vrp,
0153                            struct rpmsg_channel_info *chinfo);
0154 
0155 static const struct rpmsg_endpoint_ops virtio_endpoint_ops = {
0156     .destroy_ept = virtio_rpmsg_destroy_ept,
0157     .send = virtio_rpmsg_send,
0158     .sendto = virtio_rpmsg_sendto,
0159     .send_offchannel = virtio_rpmsg_send_offchannel,
0160     .trysend = virtio_rpmsg_trysend,
0161     .trysendto = virtio_rpmsg_trysendto,
0162     .trysend_offchannel = virtio_rpmsg_trysend_offchannel,
0163     .get_mtu = virtio_rpmsg_get_mtu,
0164 };
0165 
0166 /**
0167  * rpmsg_sg_init - initialize scatterlist according to cpu address location
0168  * @sg: scatterlist to fill
0169  * @cpu_addr: virtual address of the buffer
0170  * @len: buffer length
0171  *
0172  * An internal function filling scatterlist according to virtual address
0173  * location (in vmalloc or in kernel).
0174  */
0175 static void
0176 rpmsg_sg_init(struct scatterlist *sg, void *cpu_addr, unsigned int len)
0177 {
0178     if (is_vmalloc_addr(cpu_addr)) {
0179         sg_init_table(sg, 1);
0180         sg_set_page(sg, vmalloc_to_page(cpu_addr), len,
0181                 offset_in_page(cpu_addr));
0182     } else {
0183         WARN_ON(!virt_addr_valid(cpu_addr));
0184         sg_init_one(sg, cpu_addr, len);
0185     }
0186 }
0187 
0188 /**
0189  * __ept_release() - deallocate an rpmsg endpoint
0190  * @kref: the ept's reference count
0191  *
0192  * This function deallocates an ept, and is invoked when its @kref refcount
0193  * drops to zero.
0194  *
0195  * Never invoke this function directly!
0196  */
0197 static void __ept_release(struct kref *kref)
0198 {
0199     struct rpmsg_endpoint *ept = container_of(kref, struct rpmsg_endpoint,
0200                           refcount);
0201     /*
0202      * At this point no one holds a reference to ept anymore,
0203      * so we can directly free it
0204      */
0205     kfree(ept);
0206 }
0207 
0208 /* for more info, see below documentation of rpmsg_create_ept() */
0209 static struct rpmsg_endpoint *__rpmsg_create_ept(struct virtproc_info *vrp,
0210                          struct rpmsg_device *rpdev,
0211                          rpmsg_rx_cb_t cb,
0212                          void *priv, u32 addr)
0213 {
0214     int id_min, id_max, id;
0215     struct rpmsg_endpoint *ept;
0216     struct device *dev = rpdev ? &rpdev->dev : &vrp->vdev->dev;
0217 
0218     ept = kzalloc(sizeof(*ept), GFP_KERNEL);
0219     if (!ept)
0220         return NULL;
0221 
0222     kref_init(&ept->refcount);
0223     mutex_init(&ept->cb_lock);
0224 
0225     ept->rpdev = rpdev;
0226     ept->cb = cb;
0227     ept->priv = priv;
0228     ept->ops = &virtio_endpoint_ops;
0229 
0230     /* do we need to allocate a local address ? */
0231     if (addr == RPMSG_ADDR_ANY) {
0232         id_min = RPMSG_RESERVED_ADDRESSES;
0233         id_max = 0;
0234     } else {
0235         id_min = addr;
0236         id_max = addr + 1;
0237     }
0238 
0239     mutex_lock(&vrp->endpoints_lock);
0240 
0241     /* bind the endpoint to an rpmsg address (and allocate one if needed) */
0242     id = idr_alloc(&vrp->endpoints, ept, id_min, id_max, GFP_KERNEL);
0243     if (id < 0) {
0244         dev_err(dev, "idr_alloc failed: %d\n", id);
0245         goto free_ept;
0246     }
0247     ept->addr = id;
0248 
0249     mutex_unlock(&vrp->endpoints_lock);
0250 
0251     return ept;
0252 
0253 free_ept:
0254     mutex_unlock(&vrp->endpoints_lock);
0255     kref_put(&ept->refcount, __ept_release);
0256     return NULL;
0257 }
0258 
0259 static struct rpmsg_device *virtio_rpmsg_create_channel(struct rpmsg_device *rpdev,
0260                             struct rpmsg_channel_info *chinfo)
0261 {
0262     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0263     struct virtproc_info *vrp = vch->vrp;
0264 
0265     return __rpmsg_create_channel(vrp, chinfo);
0266 }
0267 
0268 static int virtio_rpmsg_release_channel(struct rpmsg_device *rpdev,
0269                     struct rpmsg_channel_info *chinfo)
0270 {
0271     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0272     struct virtproc_info *vrp = vch->vrp;
0273 
0274     return rpmsg_unregister_device(&vrp->vdev->dev, chinfo);
0275 }
0276 
0277 static struct rpmsg_endpoint *virtio_rpmsg_create_ept(struct rpmsg_device *rpdev,
0278                               rpmsg_rx_cb_t cb,
0279                               void *priv,
0280                               struct rpmsg_channel_info chinfo)
0281 {
0282     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0283 
0284     return __rpmsg_create_ept(vch->vrp, rpdev, cb, priv, chinfo.src);
0285 }
0286 
0287 /**
0288  * __rpmsg_destroy_ept() - destroy an existing rpmsg endpoint
0289  * @vrp: virtproc which owns this ept
0290  * @ept: endpoing to destroy
0291  *
0292  * An internal function which destroy an ept without assuming it is
0293  * bound to an rpmsg channel. This is needed for handling the internal
0294  * name service endpoint, which isn't bound to an rpmsg channel.
0295  * See also __rpmsg_create_ept().
0296  */
0297 static void
0298 __rpmsg_destroy_ept(struct virtproc_info *vrp, struct rpmsg_endpoint *ept)
0299 {
0300     /* make sure new inbound messages can't find this ept anymore */
0301     mutex_lock(&vrp->endpoints_lock);
0302     idr_remove(&vrp->endpoints, ept->addr);
0303     mutex_unlock(&vrp->endpoints_lock);
0304 
0305     /* make sure in-flight inbound messages won't invoke cb anymore */
0306     mutex_lock(&ept->cb_lock);
0307     ept->cb = NULL;
0308     mutex_unlock(&ept->cb_lock);
0309 
0310     kref_put(&ept->refcount, __ept_release);
0311 }
0312 
0313 static void virtio_rpmsg_destroy_ept(struct rpmsg_endpoint *ept)
0314 {
0315     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(ept->rpdev);
0316 
0317     __rpmsg_destroy_ept(vch->vrp, ept);
0318 }
0319 
0320 static int virtio_rpmsg_announce_create(struct rpmsg_device *rpdev)
0321 {
0322     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0323     struct virtproc_info *vrp = vch->vrp;
0324     struct device *dev = &rpdev->dev;
0325     int err = 0;
0326 
0327     /* need to tell remote processor's name service about this channel ? */
0328     if (rpdev->announce && rpdev->ept &&
0329         virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) {
0330         struct rpmsg_ns_msg nsm;
0331 
0332         strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE);
0333         nsm.addr = cpu_to_rpmsg32(rpdev, rpdev->ept->addr);
0334         nsm.flags = cpu_to_rpmsg32(rpdev, RPMSG_NS_CREATE);
0335 
0336         err = rpmsg_sendto(rpdev->ept, &nsm, sizeof(nsm), RPMSG_NS_ADDR);
0337         if (err)
0338             dev_err(dev, "failed to announce service %d\n", err);
0339     }
0340 
0341     return err;
0342 }
0343 
0344 static int virtio_rpmsg_announce_destroy(struct rpmsg_device *rpdev)
0345 {
0346     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0347     struct virtproc_info *vrp = vch->vrp;
0348     struct device *dev = &rpdev->dev;
0349     int err = 0;
0350 
0351     /* tell remote processor's name service we're removing this channel */
0352     if (rpdev->announce && rpdev->ept &&
0353         virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) {
0354         struct rpmsg_ns_msg nsm;
0355 
0356         strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE);
0357         nsm.addr = cpu_to_rpmsg32(rpdev, rpdev->ept->addr);
0358         nsm.flags = cpu_to_rpmsg32(rpdev, RPMSG_NS_DESTROY);
0359 
0360         err = rpmsg_sendto(rpdev->ept, &nsm, sizeof(nsm), RPMSG_NS_ADDR);
0361         if (err)
0362             dev_err(dev, "failed to announce service %d\n", err);
0363     }
0364 
0365     return err;
0366 }
0367 
0368 static const struct rpmsg_device_ops virtio_rpmsg_ops = {
0369     .create_channel = virtio_rpmsg_create_channel,
0370     .release_channel = virtio_rpmsg_release_channel,
0371     .create_ept = virtio_rpmsg_create_ept,
0372     .announce_create = virtio_rpmsg_announce_create,
0373     .announce_destroy = virtio_rpmsg_announce_destroy,
0374 };
0375 
0376 static void virtio_rpmsg_release_device(struct device *dev)
0377 {
0378     struct rpmsg_device *rpdev = to_rpmsg_device(dev);
0379     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0380 
0381     kfree(vch);
0382 }
0383 
0384 /*
0385  * create an rpmsg channel using its name and address info.
0386  * this function will be used to create both static and dynamic
0387  * channels.
0388  */
0389 static struct rpmsg_device *__rpmsg_create_channel(struct virtproc_info *vrp,
0390                            struct rpmsg_channel_info *chinfo)
0391 {
0392     struct virtio_rpmsg_channel *vch;
0393     struct rpmsg_device *rpdev;
0394     struct device *tmp, *dev = &vrp->vdev->dev;
0395     int ret;
0396 
0397     /* make sure a similar channel doesn't already exist */
0398     tmp = rpmsg_find_device(dev, chinfo);
0399     if (tmp) {
0400         /* decrement the matched device's refcount back */
0401         put_device(tmp);
0402         dev_err(dev, "channel %s:%x:%x already exist\n",
0403                 chinfo->name, chinfo->src, chinfo->dst);
0404         return NULL;
0405     }
0406 
0407     vch = kzalloc(sizeof(*vch), GFP_KERNEL);
0408     if (!vch)
0409         return NULL;
0410 
0411     /* Link the channel to our vrp */
0412     vch->vrp = vrp;
0413 
0414     /* Assign public information to the rpmsg_device */
0415     rpdev = &vch->rpdev;
0416     rpdev->src = chinfo->src;
0417     rpdev->dst = chinfo->dst;
0418     rpdev->ops = &virtio_rpmsg_ops;
0419     rpdev->little_endian = virtio_is_little_endian(vrp->vdev);
0420 
0421     /*
0422      * rpmsg server channels has predefined local address (for now),
0423      * and their existence needs to be announced remotely
0424      */
0425     rpdev->announce = rpdev->src != RPMSG_ADDR_ANY;
0426 
0427     strncpy(rpdev->id.name, chinfo->name, RPMSG_NAME_SIZE);
0428 
0429     rpdev->dev.parent = &vrp->vdev->dev;
0430     rpdev->dev.release = virtio_rpmsg_release_device;
0431     ret = rpmsg_register_device(rpdev);
0432     if (ret)
0433         return NULL;
0434 
0435     return rpdev;
0436 }
0437 
0438 /* super simple buffer "allocator" that is just enough for now */
0439 static void *get_a_tx_buf(struct virtproc_info *vrp)
0440 {
0441     unsigned int len;
0442     void *ret;
0443 
0444     /* support multiple concurrent senders */
0445     mutex_lock(&vrp->tx_lock);
0446 
0447     /*
0448      * either pick the next unused tx buffer
0449      * (half of our buffers are used for sending messages)
0450      */
0451     if (vrp->last_sbuf < vrp->num_bufs / 2)
0452         ret = vrp->sbufs + vrp->buf_size * vrp->last_sbuf++;
0453     /* or recycle a used one */
0454     else
0455         ret = virtqueue_get_buf(vrp->svq, &len);
0456 
0457     mutex_unlock(&vrp->tx_lock);
0458 
0459     return ret;
0460 }
0461 
0462 /**
0463  * rpmsg_upref_sleepers() - enable "tx-complete" interrupts, if needed
0464  * @vrp: virtual remote processor state
0465  *
0466  * This function is called before a sender is blocked, waiting for
0467  * a tx buffer to become available.
0468  *
0469  * If we already have blocking senders, this function merely increases
0470  * the "sleepers" reference count, and exits.
0471  *
0472  * Otherwise, if this is the first sender to block, we also enable
0473  * virtio's tx callbacks, so we'd be immediately notified when a tx
0474  * buffer is consumed (we rely on virtio's tx callback in order
0475  * to wake up sleeping senders as soon as a tx buffer is used by the
0476  * remote processor).
0477  */
0478 static void rpmsg_upref_sleepers(struct virtproc_info *vrp)
0479 {
0480     /* support multiple concurrent senders */
0481     mutex_lock(&vrp->tx_lock);
0482 
0483     /* are we the first sleeping context waiting for tx buffers ? */
0484     if (atomic_inc_return(&vrp->sleepers) == 1)
0485         /* enable "tx-complete" interrupts before dozing off */
0486         virtqueue_enable_cb(vrp->svq);
0487 
0488     mutex_unlock(&vrp->tx_lock);
0489 }
0490 
0491 /**
0492  * rpmsg_downref_sleepers() - disable "tx-complete" interrupts, if needed
0493  * @vrp: virtual remote processor state
0494  *
0495  * This function is called after a sender, that waited for a tx buffer
0496  * to become available, is unblocked.
0497  *
0498  * If we still have blocking senders, this function merely decreases
0499  * the "sleepers" reference count, and exits.
0500  *
0501  * Otherwise, if there are no more blocking senders, we also disable
0502  * virtio's tx callbacks, to avoid the overhead incurred with handling
0503  * those (now redundant) interrupts.
0504  */
0505 static void rpmsg_downref_sleepers(struct virtproc_info *vrp)
0506 {
0507     /* support multiple concurrent senders */
0508     mutex_lock(&vrp->tx_lock);
0509 
0510     /* are we the last sleeping context waiting for tx buffers ? */
0511     if (atomic_dec_and_test(&vrp->sleepers))
0512         /* disable "tx-complete" interrupts */
0513         virtqueue_disable_cb(vrp->svq);
0514 
0515     mutex_unlock(&vrp->tx_lock);
0516 }
0517 
0518 /**
0519  * rpmsg_send_offchannel_raw() - send a message across to the remote processor
0520  * @rpdev: the rpmsg channel
0521  * @src: source address
0522  * @dst: destination address
0523  * @data: payload of message
0524  * @len: length of payload
0525  * @wait: indicates whether caller should block in case no TX buffers available
0526  *
0527  * This function is the base implementation for all of the rpmsg sending API.
0528  *
0529  * It will send @data of length @len to @dst, and say it's from @src. The
0530  * message will be sent to the remote processor which the @rpdev channel
0531  * belongs to.
0532  *
0533  * The message is sent using one of the TX buffers that are available for
0534  * communication with this remote processor.
0535  *
0536  * If @wait is true, the caller will be blocked until either a TX buffer is
0537  * available, or 15 seconds elapses (we don't want callers to
0538  * sleep indefinitely due to misbehaving remote processors), and in that
0539  * case -ERESTARTSYS is returned. The number '15' itself was picked
0540  * arbitrarily; there's little point in asking drivers to provide a timeout
0541  * value themselves.
0542  *
0543  * Otherwise, if @wait is false, and there are no TX buffers available,
0544  * the function will immediately fail, and -ENOMEM will be returned.
0545  *
0546  * Normally drivers shouldn't use this function directly; instead, drivers
0547  * should use the appropriate rpmsg_{try}send{to, _offchannel} API
0548  * (see include/linux/rpmsg.h).
0549  *
0550  * Return: 0 on success and an appropriate error value on failure.
0551  */
0552 static int rpmsg_send_offchannel_raw(struct rpmsg_device *rpdev,
0553                      u32 src, u32 dst,
0554                      void *data, int len, bool wait)
0555 {
0556     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0557     struct virtproc_info *vrp = vch->vrp;
0558     struct device *dev = &rpdev->dev;
0559     struct scatterlist sg;
0560     struct rpmsg_hdr *msg;
0561     int err;
0562 
0563     /* bcasting isn't allowed */
0564     if (src == RPMSG_ADDR_ANY || dst == RPMSG_ADDR_ANY) {
0565         dev_err(dev, "invalid addr (src 0x%x, dst 0x%x)\n", src, dst);
0566         return -EINVAL;
0567     }
0568 
0569     /*
0570      * We currently use fixed-sized buffers, and therefore the payload
0571      * length is limited.
0572      *
0573      * One of the possible improvements here is either to support
0574      * user-provided buffers (and then we can also support zero-copy
0575      * messaging), or to improve the buffer allocator, to support
0576      * variable-length buffer sizes.
0577      */
0578     if (len > vrp->buf_size - sizeof(struct rpmsg_hdr)) {
0579         dev_err(dev, "message is too big (%d)\n", len);
0580         return -EMSGSIZE;
0581     }
0582 
0583     /* grab a buffer */
0584     msg = get_a_tx_buf(vrp);
0585     if (!msg && !wait)
0586         return -ENOMEM;
0587 
0588     /* no free buffer ? wait for one (but bail after 15 seconds) */
0589     while (!msg) {
0590         /* enable "tx-complete" interrupts, if not already enabled */
0591         rpmsg_upref_sleepers(vrp);
0592 
0593         /*
0594          * sleep until a free buffer is available or 15 secs elapse.
0595          * the timeout period is not configurable because there's
0596          * little point in asking drivers to specify that.
0597          * if later this happens to be required, it'd be easy to add.
0598          */
0599         err = wait_event_interruptible_timeout(vrp->sendq,
0600                     (msg = get_a_tx_buf(vrp)),
0601                     msecs_to_jiffies(15000));
0602 
0603         /* disable "tx-complete" interrupts if we're the last sleeper */
0604         rpmsg_downref_sleepers(vrp);
0605 
0606         /* timeout ? */
0607         if (!err) {
0608             dev_err(dev, "timeout waiting for a tx buffer\n");
0609             return -ERESTARTSYS;
0610         }
0611     }
0612 
0613     msg->len = cpu_to_rpmsg16(rpdev, len);
0614     msg->flags = 0;
0615     msg->src = cpu_to_rpmsg32(rpdev, src);
0616     msg->dst = cpu_to_rpmsg32(rpdev, dst);
0617     msg->reserved = 0;
0618     memcpy(msg->data, data, len);
0619 
0620     dev_dbg(dev, "TX From 0x%x, To 0x%x, Len %d, Flags %d, Reserved %d\n",
0621         src, dst, len, msg->flags, msg->reserved);
0622 #if defined(CONFIG_DYNAMIC_DEBUG)
0623     dynamic_hex_dump("rpmsg_virtio TX: ", DUMP_PREFIX_NONE, 16, 1,
0624              msg, sizeof(*msg) + len, true);
0625 #endif
0626 
0627     rpmsg_sg_init(&sg, msg, sizeof(*msg) + len);
0628 
0629     mutex_lock(&vrp->tx_lock);
0630 
0631     /* add message to the remote processor's virtqueue */
0632     err = virtqueue_add_outbuf(vrp->svq, &sg, 1, msg, GFP_KERNEL);
0633     if (err) {
0634         /*
0635          * need to reclaim the buffer here, otherwise it's lost
0636          * (memory won't leak, but rpmsg won't use it again for TX).
0637          * this will wait for a buffer management overhaul.
0638          */
0639         dev_err(dev, "virtqueue_add_outbuf failed: %d\n", err);
0640         goto out;
0641     }
0642 
0643     /* tell the remote processor it has a pending message to read */
0644     virtqueue_kick(vrp->svq);
0645 out:
0646     mutex_unlock(&vrp->tx_lock);
0647     return err;
0648 }
0649 
0650 static int virtio_rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len)
0651 {
0652     struct rpmsg_device *rpdev = ept->rpdev;
0653     u32 src = ept->addr, dst = rpdev->dst;
0654 
0655     return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, true);
0656 }
0657 
0658 static int virtio_rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len,
0659                    u32 dst)
0660 {
0661     struct rpmsg_device *rpdev = ept->rpdev;
0662     u32 src = ept->addr;
0663 
0664     return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, true);
0665 }
0666 
0667 static int virtio_rpmsg_send_offchannel(struct rpmsg_endpoint *ept, u32 src,
0668                     u32 dst, void *data, int len)
0669 {
0670     struct rpmsg_device *rpdev = ept->rpdev;
0671 
0672     return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, true);
0673 }
0674 
0675 static int virtio_rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len)
0676 {
0677     struct rpmsg_device *rpdev = ept->rpdev;
0678     u32 src = ept->addr, dst = rpdev->dst;
0679 
0680     return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, false);
0681 }
0682 
0683 static int virtio_rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data,
0684                   int len, u32 dst)
0685 {
0686     struct rpmsg_device *rpdev = ept->rpdev;
0687     u32 src = ept->addr;
0688 
0689     return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, false);
0690 }
0691 
0692 static int virtio_rpmsg_trysend_offchannel(struct rpmsg_endpoint *ept, u32 src,
0693                        u32 dst, void *data, int len)
0694 {
0695     struct rpmsg_device *rpdev = ept->rpdev;
0696 
0697     return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, false);
0698 }
0699 
0700 static ssize_t virtio_rpmsg_get_mtu(struct rpmsg_endpoint *ept)
0701 {
0702     struct rpmsg_device *rpdev = ept->rpdev;
0703     struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev);
0704 
0705     return vch->vrp->buf_size - sizeof(struct rpmsg_hdr);
0706 }
0707 
0708 static int rpmsg_recv_single(struct virtproc_info *vrp, struct device *dev,
0709                  struct rpmsg_hdr *msg, unsigned int len)
0710 {
0711     struct rpmsg_endpoint *ept;
0712     struct scatterlist sg;
0713     bool little_endian = virtio_is_little_endian(vrp->vdev);
0714     unsigned int msg_len = __rpmsg16_to_cpu(little_endian, msg->len);
0715     int err;
0716 
0717     dev_dbg(dev, "From: 0x%x, To: 0x%x, Len: %d, Flags: %d, Reserved: %d\n",
0718         __rpmsg32_to_cpu(little_endian, msg->src),
0719         __rpmsg32_to_cpu(little_endian, msg->dst), msg_len,
0720         __rpmsg16_to_cpu(little_endian, msg->flags),
0721         __rpmsg32_to_cpu(little_endian, msg->reserved));
0722 #if defined(CONFIG_DYNAMIC_DEBUG)
0723     dynamic_hex_dump("rpmsg_virtio RX: ", DUMP_PREFIX_NONE, 16, 1,
0724              msg, sizeof(*msg) + msg_len, true);
0725 #endif
0726 
0727     /*
0728      * We currently use fixed-sized buffers, so trivially sanitize
0729      * the reported payload length.
0730      */
0731     if (len > vrp->buf_size ||
0732         msg_len > (len - sizeof(struct rpmsg_hdr))) {
0733         dev_warn(dev, "inbound msg too big: (%d, %d)\n", len, msg_len);
0734         return -EINVAL;
0735     }
0736 
0737     /* use the dst addr to fetch the callback of the appropriate user */
0738     mutex_lock(&vrp->endpoints_lock);
0739 
0740     ept = idr_find(&vrp->endpoints, __rpmsg32_to_cpu(little_endian, msg->dst));
0741 
0742     /* let's make sure no one deallocates ept while we use it */
0743     if (ept)
0744         kref_get(&ept->refcount);
0745 
0746     mutex_unlock(&vrp->endpoints_lock);
0747 
0748     if (ept) {
0749         /* make sure ept->cb doesn't go away while we use it */
0750         mutex_lock(&ept->cb_lock);
0751 
0752         if (ept->cb)
0753             ept->cb(ept->rpdev, msg->data, msg_len, ept->priv,
0754                 __rpmsg32_to_cpu(little_endian, msg->src));
0755 
0756         mutex_unlock(&ept->cb_lock);
0757 
0758         /* farewell, ept, we don't need you anymore */
0759         kref_put(&ept->refcount, __ept_release);
0760     } else
0761         dev_warn_ratelimited(dev, "msg received with no recipient\n");
0762 
0763     /* publish the real size of the buffer */
0764     rpmsg_sg_init(&sg, msg, vrp->buf_size);
0765 
0766     /* add the buffer back to the remote processor's virtqueue */
0767     err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, msg, GFP_KERNEL);
0768     if (err < 0) {
0769         dev_err(dev, "failed to add a virtqueue buffer: %d\n", err);
0770         return err;
0771     }
0772 
0773     return 0;
0774 }
0775 
0776 /* called when an rx buffer is used, and it's time to digest a message */
0777 static void rpmsg_recv_done(struct virtqueue *rvq)
0778 {
0779     struct virtproc_info *vrp = rvq->vdev->priv;
0780     struct device *dev = &rvq->vdev->dev;
0781     struct rpmsg_hdr *msg;
0782     unsigned int len, msgs_received = 0;
0783     int err;
0784 
0785     msg = virtqueue_get_buf(rvq, &len);
0786     if (!msg) {
0787         dev_err(dev, "uhm, incoming signal, but no used buffer ?\n");
0788         return;
0789     }
0790 
0791     while (msg) {
0792         err = rpmsg_recv_single(vrp, dev, msg, len);
0793         if (err)
0794             break;
0795 
0796         msgs_received++;
0797 
0798         msg = virtqueue_get_buf(rvq, &len);
0799     }
0800 
0801     dev_dbg(dev, "Received %u messages\n", msgs_received);
0802 
0803     /* tell the remote processor we added another available rx buffer */
0804     if (msgs_received)
0805         virtqueue_kick(vrp->rvq);
0806 }
0807 
0808 /*
0809  * This is invoked whenever the remote processor completed processing
0810  * a TX msg we just sent it, and the buffer is put back to the used ring.
0811  *
0812  * Normally, though, we suppress this "tx complete" interrupt in order to
0813  * avoid the incurred overhead.
0814  */
0815 static void rpmsg_xmit_done(struct virtqueue *svq)
0816 {
0817     struct virtproc_info *vrp = svq->vdev->priv;
0818 
0819     dev_dbg(&svq->vdev->dev, "%s\n", __func__);
0820 
0821     /* wake up potential senders that are waiting for a tx buffer */
0822     wake_up_interruptible(&vrp->sendq);
0823 }
0824 
0825 /*
0826  * Called to expose to user a /dev/rpmsg_ctrlX interface allowing to
0827  * create endpoint-to-endpoint communication without associated RPMsg channel.
0828  * The endpoints are rattached to the ctrldev RPMsg device.
0829  */
0830 static struct rpmsg_device *rpmsg_virtio_add_ctrl_dev(struct virtio_device *vdev)
0831 {
0832     struct virtproc_info *vrp = vdev->priv;
0833     struct virtio_rpmsg_channel *vch;
0834     struct rpmsg_device *rpdev_ctrl;
0835     int err = 0;
0836 
0837     vch = kzalloc(sizeof(*vch), GFP_KERNEL);
0838     if (!vch)
0839         return ERR_PTR(-ENOMEM);
0840 
0841     /* Link the channel to the vrp */
0842     vch->vrp = vrp;
0843 
0844     /* Assign public information to the rpmsg_device */
0845     rpdev_ctrl = &vch->rpdev;
0846     rpdev_ctrl->ops = &virtio_rpmsg_ops;
0847 
0848     rpdev_ctrl->dev.parent = &vrp->vdev->dev;
0849     rpdev_ctrl->dev.release = virtio_rpmsg_release_device;
0850     rpdev_ctrl->little_endian = virtio_is_little_endian(vrp->vdev);
0851 
0852     err = rpmsg_ctrldev_register_device(rpdev_ctrl);
0853     if (err) {
0854         /* vch will be free in virtio_rpmsg_release_device() */
0855         return ERR_PTR(err);
0856     }
0857 
0858     return rpdev_ctrl;
0859 }
0860 
0861 static void rpmsg_virtio_del_ctrl_dev(struct rpmsg_device *rpdev_ctrl)
0862 {
0863     if (!rpdev_ctrl)
0864         return;
0865     device_unregister(&rpdev_ctrl->dev);
0866 }
0867 
0868 static int rpmsg_probe(struct virtio_device *vdev)
0869 {
0870     vq_callback_t *vq_cbs[] = { rpmsg_recv_done, rpmsg_xmit_done };
0871     static const char * const names[] = { "input", "output" };
0872     struct virtqueue *vqs[2];
0873     struct virtproc_info *vrp;
0874     struct virtio_rpmsg_channel *vch = NULL;
0875     struct rpmsg_device *rpdev_ns, *rpdev_ctrl;
0876     void *bufs_va;
0877     int err = 0, i;
0878     size_t total_buf_space;
0879     bool notify;
0880 
0881     vrp = kzalloc(sizeof(*vrp), GFP_KERNEL);
0882     if (!vrp)
0883         return -ENOMEM;
0884 
0885     vrp->vdev = vdev;
0886 
0887     idr_init(&vrp->endpoints);
0888     mutex_init(&vrp->endpoints_lock);
0889     mutex_init(&vrp->tx_lock);
0890     init_waitqueue_head(&vrp->sendq);
0891 
0892     /* We expect two virtqueues, rx and tx (and in this order) */
0893     err = virtio_find_vqs(vdev, 2, vqs, vq_cbs, names, NULL);
0894     if (err)
0895         goto free_vrp;
0896 
0897     vrp->rvq = vqs[0];
0898     vrp->svq = vqs[1];
0899 
0900     /* we expect symmetric tx/rx vrings */
0901     WARN_ON(virtqueue_get_vring_size(vrp->rvq) !=
0902         virtqueue_get_vring_size(vrp->svq));
0903 
0904     /* we need less buffers if vrings are small */
0905     if (virtqueue_get_vring_size(vrp->rvq) < MAX_RPMSG_NUM_BUFS / 2)
0906         vrp->num_bufs = virtqueue_get_vring_size(vrp->rvq) * 2;
0907     else
0908         vrp->num_bufs = MAX_RPMSG_NUM_BUFS;
0909 
0910     vrp->buf_size = MAX_RPMSG_BUF_SIZE;
0911 
0912     total_buf_space = vrp->num_bufs * vrp->buf_size;
0913 
0914     /* allocate coherent memory for the buffers */
0915     bufs_va = dma_alloc_coherent(vdev->dev.parent,
0916                      total_buf_space, &vrp->bufs_dma,
0917                      GFP_KERNEL);
0918     if (!bufs_va) {
0919         err = -ENOMEM;
0920         goto vqs_del;
0921     }
0922 
0923     dev_dbg(&vdev->dev, "buffers: va %pK, dma %pad\n",
0924         bufs_va, &vrp->bufs_dma);
0925 
0926     /* half of the buffers is dedicated for RX */
0927     vrp->rbufs = bufs_va;
0928 
0929     /* and half is dedicated for TX */
0930     vrp->sbufs = bufs_va + total_buf_space / 2;
0931 
0932     /* set up the receive buffers */
0933     for (i = 0; i < vrp->num_bufs / 2; i++) {
0934         struct scatterlist sg;
0935         void *cpu_addr = vrp->rbufs + i * vrp->buf_size;
0936 
0937         rpmsg_sg_init(&sg, cpu_addr, vrp->buf_size);
0938 
0939         err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, cpu_addr,
0940                       GFP_KERNEL);
0941         WARN_ON(err); /* sanity check; this can't really happen */
0942     }
0943 
0944     /* suppress "tx-complete" interrupts */
0945     virtqueue_disable_cb(vrp->svq);
0946 
0947     vdev->priv = vrp;
0948 
0949     rpdev_ctrl = rpmsg_virtio_add_ctrl_dev(vdev);
0950     if (IS_ERR(rpdev_ctrl)) {
0951         err = PTR_ERR(rpdev_ctrl);
0952         goto free_coherent;
0953     }
0954 
0955     /* if supported by the remote processor, enable the name service */
0956     if (virtio_has_feature(vdev, VIRTIO_RPMSG_F_NS)) {
0957         vch = kzalloc(sizeof(*vch), GFP_KERNEL);
0958         if (!vch) {
0959             err = -ENOMEM;
0960             goto free_ctrldev;
0961         }
0962 
0963         /* Link the channel to our vrp */
0964         vch->vrp = vrp;
0965 
0966         /* Assign public information to the rpmsg_device */
0967         rpdev_ns = &vch->rpdev;
0968         rpdev_ns->ops = &virtio_rpmsg_ops;
0969         rpdev_ns->little_endian = virtio_is_little_endian(vrp->vdev);
0970 
0971         rpdev_ns->dev.parent = &vrp->vdev->dev;
0972         rpdev_ns->dev.release = virtio_rpmsg_release_device;
0973 
0974         err = rpmsg_ns_register_device(rpdev_ns);
0975         if (err)
0976             /* vch will be free in virtio_rpmsg_release_device() */
0977             goto free_ctrldev;
0978     }
0979 
0980     /*
0981      * Prepare to kick but don't notify yet - we can't do this before
0982      * device is ready.
0983      */
0984     notify = virtqueue_kick_prepare(vrp->rvq);
0985 
0986     /* From this point on, we can notify and get callbacks. */
0987     virtio_device_ready(vdev);
0988 
0989     /* tell the remote processor it can start sending messages */
0990     /*
0991      * this might be concurrent with callbacks, but we are only
0992      * doing notify, not a full kick here, so that's ok.
0993      */
0994     if (notify)
0995         virtqueue_notify(vrp->rvq);
0996 
0997     dev_info(&vdev->dev, "rpmsg host is online\n");
0998 
0999     return 0;
1000 
1001 free_ctrldev:
1002     rpmsg_virtio_del_ctrl_dev(rpdev_ctrl);
1003 free_coherent:
1004     dma_free_coherent(vdev->dev.parent, total_buf_space,
1005               bufs_va, vrp->bufs_dma);
1006 vqs_del:
1007     vdev->config->del_vqs(vrp->vdev);
1008 free_vrp:
1009     kfree(vrp);
1010     return err;
1011 }
1012 
1013 static int rpmsg_remove_device(struct device *dev, void *data)
1014 {
1015     device_unregister(dev);
1016 
1017     return 0;
1018 }
1019 
1020 static void rpmsg_remove(struct virtio_device *vdev)
1021 {
1022     struct virtproc_info *vrp = vdev->priv;
1023     size_t total_buf_space = vrp->num_bufs * vrp->buf_size;
1024     int ret;
1025 
1026     virtio_reset_device(vdev);
1027 
1028     ret = device_for_each_child(&vdev->dev, NULL, rpmsg_remove_device);
1029     if (ret)
1030         dev_warn(&vdev->dev, "can't remove rpmsg device: %d\n", ret);
1031 
1032     idr_destroy(&vrp->endpoints);
1033 
1034     vdev->config->del_vqs(vrp->vdev);
1035 
1036     dma_free_coherent(vdev->dev.parent, total_buf_space,
1037               vrp->rbufs, vrp->bufs_dma);
1038 
1039     kfree(vrp);
1040 }
1041 
1042 static struct virtio_device_id id_table[] = {
1043     { VIRTIO_ID_RPMSG, VIRTIO_DEV_ANY_ID },
1044     { 0 },
1045 };
1046 
1047 static unsigned int features[] = {
1048     VIRTIO_RPMSG_F_NS,
1049 };
1050 
1051 static struct virtio_driver virtio_ipc_driver = {
1052     .feature_table  = features,
1053     .feature_table_size = ARRAY_SIZE(features),
1054     .driver.name    = KBUILD_MODNAME,
1055     .driver.owner   = THIS_MODULE,
1056     .id_table   = id_table,
1057     .probe      = rpmsg_probe,
1058     .remove     = rpmsg_remove,
1059 };
1060 
1061 static int __init rpmsg_init(void)
1062 {
1063     int ret;
1064 
1065     ret = register_virtio_driver(&virtio_ipc_driver);
1066     if (ret)
1067         pr_err("failed to register virtio driver: %d\n", ret);
1068 
1069     return ret;
1070 }
1071 subsys_initcall(rpmsg_init);
1072 
1073 static void __exit rpmsg_fini(void)
1074 {
1075     unregister_virtio_driver(&virtio_ipc_driver);
1076 }
1077 module_exit(rpmsg_fini);
1078 
1079 MODULE_DEVICE_TABLE(virtio, id_table);
1080 MODULE_DESCRIPTION("Virtio-based remote processor messaging bus");
1081 MODULE_LICENSE("GPL v2");