1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018, Linaro Ltd */
4 #include <linux/miscdevice.h>
5 #include <linux/module.h>
6 #include <linux/poll.h>
7 #include <linux/skbuff.h>
8 #include <linux/uaccess.h>
13 struct qrtr_endpoint ep;
15 struct sk_buff_head queue;
16 wait_queue_head_t readq;
19 static int qrtr_tun_send(struct qrtr_endpoint *ep, struct sk_buff *skb)
21 struct qrtr_tun *tun = container_of(ep, struct qrtr_tun, ep);
23 skb_queue_tail(&tun->queue, skb);
25 /* wake up any blocking processes, waiting for new data */
26 wake_up_interruptible(&tun->readq);
31 static int qrtr_tun_open(struct inode *inode, struct file *filp)
36 tun = kzalloc(sizeof(*tun), GFP_KERNEL);
40 skb_queue_head_init(&tun->queue);
41 init_waitqueue_head(&tun->readq);
43 tun->ep.xmit = qrtr_tun_send;
45 filp->private_data = tun;
47 ret = qrtr_endpoint_register(&tun->ep, QRTR_EP_NID_AUTO);
54 filp->private_data = NULL;
59 static ssize_t qrtr_tun_read_iter(struct kiocb *iocb, struct iov_iter *to)
61 struct file *filp = iocb->ki_filp;
62 struct qrtr_tun *tun = filp->private_data;
66 while (!(skb = skb_dequeue(&tun->queue))) {
67 if (filp->f_flags & O_NONBLOCK)
70 /* Wait until we get data or the endpoint goes away */
71 if (wait_event_interruptible(tun->readq,
72 !skb_queue_empty(&tun->queue)))
76 count = min_t(size_t, iov_iter_count(to), skb->len);
77 if (copy_to_iter(skb->data, count, to) != count)
85 static ssize_t qrtr_tun_write_iter(struct kiocb *iocb, struct iov_iter *from)
87 struct file *filp = iocb->ki_filp;
88 struct qrtr_tun *tun = filp->private_data;
89 size_t len = iov_iter_count(from);
96 if (len > KMALLOC_MAX_SIZE)
99 kbuf = kzalloc(len, GFP_KERNEL);
103 if (!copy_from_iter_full(kbuf, len, from)) {
108 ret = qrtr_endpoint_post(&tun->ep, kbuf, len);
111 return ret < 0 ? ret : len;
114 static __poll_t qrtr_tun_poll(struct file *filp, poll_table *wait)
116 struct qrtr_tun *tun = filp->private_data;
119 poll_wait(filp, &tun->readq, wait);
121 if (!skb_queue_empty(&tun->queue))
122 mask |= EPOLLIN | EPOLLRDNORM;
127 static int qrtr_tun_release(struct inode *inode, struct file *filp)
129 struct qrtr_tun *tun = filp->private_data;
131 qrtr_endpoint_unregister(&tun->ep);
133 /* Discard all SKBs */
134 skb_queue_purge(&tun->queue);
141 static const struct file_operations qrtr_tun_ops = {
142 .owner = THIS_MODULE,
143 .open = qrtr_tun_open,
144 .poll = qrtr_tun_poll,
145 .read_iter = qrtr_tun_read_iter,
146 .write_iter = qrtr_tun_write_iter,
147 .release = qrtr_tun_release,
150 static struct miscdevice qrtr_tun_miscdev = {
156 static int __init qrtr_tun_init(void)
160 ret = misc_register(&qrtr_tun_miscdev);
162 pr_err("failed to register Qualcomm IPC Router tun device\n");
167 static void __exit qrtr_tun_exit(void)
169 misc_deregister(&qrtr_tun_miscdev);
172 module_init(qrtr_tun_init);
173 module_exit(qrtr_tun_exit);
175 MODULE_DESCRIPTION("Qualcomm IPC Router TUN device");
176 MODULE_LICENSE("GPL v2");