]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/vhost/net.c
2fe35354f20e5ea82509fc9859435029a5a2dfcc
[karo-tx-linux.git] / drivers / vhost / net.c
1 /* Copyright (C) 2009 Red Hat, Inc.
2  * Author: Michael S. Tsirkin <mst@redhat.com>
3  *
4  * This work is licensed under the terms of the GNU GPL, version 2.
5  *
6  * virtio-net server in host kernel.
7  */
8
9 #include <linux/compat.h>
10 #include <linux/eventfd.h>
11 #include <linux/vhost.h>
12 #include <linux/virtio_net.h>
13 #include <linux/miscdevice.h>
14 #include <linux/module.h>
15 #include <linux/moduleparam.h>
16 #include <linux/mutex.h>
17 #include <linux/workqueue.h>
18 #include <linux/file.h>
19 #include <linux/slab.h>
20 #include <linux/vmalloc.h>
21
22 #include <linux/net.h>
23 #include <linux/if_packet.h>
24 #include <linux/if_arp.h>
25 #include <linux/if_tun.h>
26 #include <linux/if_macvlan.h>
27 #include <linux/if_tap.h>
28 #include <linux/if_vlan.h>
29
30 #include <net/sock.h>
31
32 #include "vhost.h"
33
34 static int experimental_zcopytx = 1;
35 module_param(experimental_zcopytx, int, 0444);
36 MODULE_PARM_DESC(experimental_zcopytx, "Enable Zero Copy TX;"
37                                        " 1 -Enable; 0 - Disable");
38
39 /* Max number of bytes transferred before requeueing the job.
40  * Using this limit prevents one virtqueue from starving others. */
41 #define VHOST_NET_WEIGHT 0x80000
42
43 /* MAX number of TX used buffers for outstanding zerocopy */
44 #define VHOST_MAX_PEND 128
45 #define VHOST_GOODCOPY_LEN 256
46
47 /*
48  * For transmit, used buffer len is unused; we override it to track buffer
49  * status internally; used for zerocopy tx only.
50  */
51 /* Lower device DMA failed */
52 #define VHOST_DMA_FAILED_LEN    ((__force __virtio32)3)
53 /* Lower device DMA done */
54 #define VHOST_DMA_DONE_LEN      ((__force __virtio32)2)
55 /* Lower device DMA in progress */
56 #define VHOST_DMA_IN_PROGRESS   ((__force __virtio32)1)
57 /* Buffer unused */
58 #define VHOST_DMA_CLEAR_LEN     ((__force __virtio32)0)
59
60 #define VHOST_DMA_IS_DONE(len) ((__force u32)(len) >= (__force u32)VHOST_DMA_DONE_LEN)
61
62 enum {
63         VHOST_NET_FEATURES = VHOST_FEATURES |
64                          (1ULL << VHOST_NET_F_VIRTIO_NET_HDR) |
65                          (1ULL << VIRTIO_NET_F_MRG_RXBUF) |
66                          (1ULL << VIRTIO_F_IOMMU_PLATFORM)
67 };
68
69 enum {
70         VHOST_NET_VQ_RX = 0,
71         VHOST_NET_VQ_TX = 1,
72         VHOST_NET_VQ_MAX = 2,
73 };
74
75 struct vhost_net_ubuf_ref {
76         /* refcount follows semantics similar to kref:
77          *  0: object is released
78          *  1: no outstanding ubufs
79          * >1: outstanding ubufs
80          */
81         atomic_t refcount;
82         wait_queue_head_t wait;
83         struct vhost_virtqueue *vq;
84 };
85
86 struct vhost_net_virtqueue {
87         struct vhost_virtqueue vq;
88         size_t vhost_hlen;
89         size_t sock_hlen;
90         /* vhost zerocopy support fields below: */
91         /* last used idx for outstanding DMA zerocopy buffers */
92         int upend_idx;
93         /* first used idx for DMA done zerocopy buffers */
94         int done_idx;
95         /* an array of userspace buffers info */
96         struct ubuf_info *ubuf_info;
97         /* Reference counting for outstanding ubufs.
98          * Protected by vq mutex. Writers must also take device mutex. */
99         struct vhost_net_ubuf_ref *ubufs;
100 };
101
102 struct vhost_net {
103         struct vhost_dev dev;
104         struct vhost_net_virtqueue vqs[VHOST_NET_VQ_MAX];
105         struct vhost_poll poll[VHOST_NET_VQ_MAX];
106         /* Number of TX recently submitted.
107          * Protected by tx vq lock. */
108         unsigned tx_packets;
109         /* Number of times zerocopy TX recently failed.
110          * Protected by tx vq lock. */
111         unsigned tx_zcopy_err;
112         /* Flush in progress. Protected by tx vq lock. */
113         bool tx_flush;
114 };
115
116 static unsigned vhost_net_zcopy_mask __read_mostly;
117
118 static void vhost_net_enable_zcopy(int vq)
119 {
120         vhost_net_zcopy_mask |= 0x1 << vq;
121 }
122
123 static struct vhost_net_ubuf_ref *
124 vhost_net_ubuf_alloc(struct vhost_virtqueue *vq, bool zcopy)
125 {
126         struct vhost_net_ubuf_ref *ubufs;
127         /* No zero copy backend? Nothing to count. */
128         if (!zcopy)
129                 return NULL;
130         ubufs = kmalloc(sizeof(*ubufs), GFP_KERNEL);
131         if (!ubufs)
132                 return ERR_PTR(-ENOMEM);
133         atomic_set(&ubufs->refcount, 1);
134         init_waitqueue_head(&ubufs->wait);
135         ubufs->vq = vq;
136         return ubufs;
137 }
138
139 static int vhost_net_ubuf_put(struct vhost_net_ubuf_ref *ubufs)
140 {
141         int r = atomic_sub_return(1, &ubufs->refcount);
142         if (unlikely(!r))
143                 wake_up(&ubufs->wait);
144         return r;
145 }
146
147 static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
148 {
149         vhost_net_ubuf_put(ubufs);
150         wait_event(ubufs->wait, !atomic_read(&ubufs->refcount));
151 }
152
153 static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs)
154 {
155         vhost_net_ubuf_put_and_wait(ubufs);
156         kfree(ubufs);
157 }
158
159 static void vhost_net_clear_ubuf_info(struct vhost_net *n)
160 {
161         int i;
162
163         for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
164                 kfree(n->vqs[i].ubuf_info);
165                 n->vqs[i].ubuf_info = NULL;
166         }
167 }
168
169 static int vhost_net_set_ubuf_info(struct vhost_net *n)
170 {
171         bool zcopy;
172         int i;
173
174         for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
175                 zcopy = vhost_net_zcopy_mask & (0x1 << i);
176                 if (!zcopy)
177                         continue;
178                 n->vqs[i].ubuf_info = kmalloc(sizeof(*n->vqs[i].ubuf_info) *
179                                               UIO_MAXIOV, GFP_KERNEL);
180                 if  (!n->vqs[i].ubuf_info)
181                         goto err;
182         }
183         return 0;
184
185 err:
186         vhost_net_clear_ubuf_info(n);
187         return -ENOMEM;
188 }
189
190 static void vhost_net_vq_reset(struct vhost_net *n)
191 {
192         int i;
193
194         vhost_net_clear_ubuf_info(n);
195
196         for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
197                 n->vqs[i].done_idx = 0;
198                 n->vqs[i].upend_idx = 0;
199                 n->vqs[i].ubufs = NULL;
200                 n->vqs[i].vhost_hlen = 0;
201                 n->vqs[i].sock_hlen = 0;
202         }
203
204 }
205
206 static void vhost_net_tx_packet(struct vhost_net *net)
207 {
208         ++net->tx_packets;
209         if (net->tx_packets < 1024)
210                 return;
211         net->tx_packets = 0;
212         net->tx_zcopy_err = 0;
213 }
214
215 static void vhost_net_tx_err(struct vhost_net *net)
216 {
217         ++net->tx_zcopy_err;
218 }
219
220 static bool vhost_net_tx_select_zcopy(struct vhost_net *net)
221 {
222         /* TX flush waits for outstanding DMAs to be done.
223          * Don't start new DMAs.
224          */
225         return !net->tx_flush &&
226                 net->tx_packets / 64 >= net->tx_zcopy_err;
227 }
228
229 static bool vhost_sock_zcopy(struct socket *sock)
230 {
231         return unlikely(experimental_zcopytx) &&
232                 sock_flag(sock->sk, SOCK_ZEROCOPY);
233 }
234
235 /* In case of DMA done not in order in lower device driver for some reason.
236  * upend_idx is used to track end of used idx, done_idx is used to track head
237  * of used idx. Once lower device DMA done contiguously, we will signal KVM
238  * guest used idx.
239  */
240 static void vhost_zerocopy_signal_used(struct vhost_net *net,
241                                        struct vhost_virtqueue *vq)
242 {
243         struct vhost_net_virtqueue *nvq =
244                 container_of(vq, struct vhost_net_virtqueue, vq);
245         int i, add;
246         int j = 0;
247
248         for (i = nvq->done_idx; i != nvq->upend_idx; i = (i + 1) % UIO_MAXIOV) {
249                 if (vq->heads[i].len == VHOST_DMA_FAILED_LEN)
250                         vhost_net_tx_err(net);
251                 if (VHOST_DMA_IS_DONE(vq->heads[i].len)) {
252                         vq->heads[i].len = VHOST_DMA_CLEAR_LEN;
253                         ++j;
254                 } else
255                         break;
256         }
257         while (j) {
258                 add = min(UIO_MAXIOV - nvq->done_idx, j);
259                 vhost_add_used_and_signal_n(vq->dev, vq,
260                                             &vq->heads[nvq->done_idx], add);
261                 nvq->done_idx = (nvq->done_idx + add) % UIO_MAXIOV;
262                 j -= add;
263         }
264 }
265
266 static void vhost_zerocopy_callback(struct ubuf_info *ubuf, bool success)
267 {
268         struct vhost_net_ubuf_ref *ubufs = ubuf->ctx;
269         struct vhost_virtqueue *vq = ubufs->vq;
270         int cnt;
271
272         rcu_read_lock_bh();
273
274         /* set len to mark this desc buffers done DMA */
275         vq->heads[ubuf->desc].len = success ?
276                 VHOST_DMA_DONE_LEN : VHOST_DMA_FAILED_LEN;
277         cnt = vhost_net_ubuf_put(ubufs);
278
279         /*
280          * Trigger polling thread if guest stopped submitting new buffers:
281          * in this case, the refcount after decrement will eventually reach 1.
282          * We also trigger polling periodically after each 16 packets
283          * (the value 16 here is more or less arbitrary, it's tuned to trigger
284          * less than 10% of times).
285          */
286         if (cnt <= 1 || !(cnt % 16))
287                 vhost_poll_queue(&vq->poll);
288
289         rcu_read_unlock_bh();
290 }
291
292 static inline unsigned long busy_clock(void)
293 {
294         return local_clock() >> 10;
295 }
296
297 static bool vhost_can_busy_poll(struct vhost_dev *dev,
298                                 unsigned long endtime)
299 {
300         return likely(!need_resched()) &&
301                likely(!time_after(busy_clock(), endtime)) &&
302                likely(!signal_pending(current)) &&
303                !vhost_has_work(dev);
304 }
305
306 static void vhost_net_disable_vq(struct vhost_net *n,
307                                  struct vhost_virtqueue *vq)
308 {
309         struct vhost_net_virtqueue *nvq =
310                 container_of(vq, struct vhost_net_virtqueue, vq);
311         struct vhost_poll *poll = n->poll + (nvq - n->vqs);
312         if (!vq->private_data)
313                 return;
314         vhost_poll_stop(poll);
315 }
316
317 static int vhost_net_enable_vq(struct vhost_net *n,
318                                 struct vhost_virtqueue *vq)
319 {
320         struct vhost_net_virtqueue *nvq =
321                 container_of(vq, struct vhost_net_virtqueue, vq);
322         struct vhost_poll *poll = n->poll + (nvq - n->vqs);
323         struct socket *sock;
324
325         sock = vq->private_data;
326         if (!sock)
327                 return 0;
328
329         return vhost_poll_start(poll, sock->file);
330 }
331
332 static int vhost_net_tx_get_vq_desc(struct vhost_net *net,
333                                     struct vhost_virtqueue *vq,
334                                     struct iovec iov[], unsigned int iov_size,
335                                     unsigned int *out_num, unsigned int *in_num)
336 {
337         unsigned long uninitialized_var(endtime);
338         int r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
339                                   out_num, in_num, NULL, NULL);
340
341         if (r == vq->num && vq->busyloop_timeout) {
342                 preempt_disable();
343                 endtime = busy_clock() + vq->busyloop_timeout;
344                 while (vhost_can_busy_poll(vq->dev, endtime) &&
345                        vhost_vq_avail_empty(vq->dev, vq))
346                         cpu_relax();
347                 preempt_enable();
348                 r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
349                                       out_num, in_num, NULL, NULL);
350         }
351
352         return r;
353 }
354
355 static bool vhost_exceeds_maxpend(struct vhost_net *net)
356 {
357         struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
358         struct vhost_virtqueue *vq = &nvq->vq;
359
360         return (nvq->upend_idx + vq->num - VHOST_MAX_PEND) % UIO_MAXIOV
361                 == nvq->done_idx;
362 }
363
364 /* Expects to be always run from workqueue - which acts as
365  * read-size critical section for our kind of RCU. */
366 static void handle_tx(struct vhost_net *net)
367 {
368         struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
369         struct vhost_virtqueue *vq = &nvq->vq;
370         unsigned out, in;
371         int head;
372         struct msghdr msg = {
373                 .msg_name = NULL,
374                 .msg_namelen = 0,
375                 .msg_control = NULL,
376                 .msg_controllen = 0,
377                 .msg_flags = MSG_DONTWAIT,
378         };
379         size_t len, total_len = 0;
380         int err;
381         size_t hdr_size;
382         struct socket *sock;
383         struct vhost_net_ubuf_ref *uninitialized_var(ubufs);
384         bool zcopy, zcopy_used;
385
386         mutex_lock(&vq->mutex);
387         sock = vq->private_data;
388         if (!sock)
389                 goto out;
390
391         if (!vq_iotlb_prefetch(vq))
392                 goto out;
393
394         vhost_disable_notify(&net->dev, vq);
395
396         hdr_size = nvq->vhost_hlen;
397         zcopy = nvq->ubufs;
398
399         for (;;) {
400                 /* Release DMAs done buffers first */
401                 if (zcopy)
402                         vhost_zerocopy_signal_used(net, vq);
403
404                 /* If more outstanding DMAs, queue the work.
405                  * Handle upend_idx wrap around
406                  */
407                 if (unlikely(vhost_exceeds_maxpend(net)))
408                         break;
409
410                 head = vhost_net_tx_get_vq_desc(net, vq, vq->iov,
411                                                 ARRAY_SIZE(vq->iov),
412                                                 &out, &in);
413                 /* On error, stop handling until the next kick. */
414                 if (unlikely(head < 0))
415                         break;
416                 /* Nothing new?  Wait for eventfd to tell us they refilled. */
417                 if (head == vq->num) {
418                         if (unlikely(vhost_enable_notify(&net->dev, vq))) {
419                                 vhost_disable_notify(&net->dev, vq);
420                                 continue;
421                         }
422                         break;
423                 }
424                 if (in) {
425                         vq_err(vq, "Unexpected descriptor format for TX: "
426                                "out %d, int %d\n", out, in);
427                         break;
428                 }
429                 /* Skip header. TODO: support TSO. */
430                 len = iov_length(vq->iov, out);
431                 iov_iter_init(&msg.msg_iter, WRITE, vq->iov, out, len);
432                 iov_iter_advance(&msg.msg_iter, hdr_size);
433                 /* Sanity check */
434                 if (!msg_data_left(&msg)) {
435                         vq_err(vq, "Unexpected header len for TX: "
436                                "%zd expected %zd\n",
437                                len, hdr_size);
438                         break;
439                 }
440                 len = msg_data_left(&msg);
441
442                 zcopy_used = zcopy && len >= VHOST_GOODCOPY_LEN
443                                    && (nvq->upend_idx + 1) % UIO_MAXIOV !=
444                                       nvq->done_idx
445                                    && vhost_net_tx_select_zcopy(net);
446
447                 /* use msg_control to pass vhost zerocopy ubuf info to skb */
448                 if (zcopy_used) {
449                         struct ubuf_info *ubuf;
450                         ubuf = nvq->ubuf_info + nvq->upend_idx;
451
452                         vq->heads[nvq->upend_idx].id = cpu_to_vhost32(vq, head);
453                         vq->heads[nvq->upend_idx].len = VHOST_DMA_IN_PROGRESS;
454                         ubuf->callback = vhost_zerocopy_callback;
455                         ubuf->ctx = nvq->ubufs;
456                         ubuf->desc = nvq->upend_idx;
457                         msg.msg_control = ubuf;
458                         msg.msg_controllen = sizeof(ubuf);
459                         ubufs = nvq->ubufs;
460                         atomic_inc(&ubufs->refcount);
461                         nvq->upend_idx = (nvq->upend_idx + 1) % UIO_MAXIOV;
462                 } else {
463                         msg.msg_control = NULL;
464                         ubufs = NULL;
465                 }
466
467                 total_len += len;
468                 if (total_len < VHOST_NET_WEIGHT &&
469                     !vhost_vq_avail_empty(&net->dev, vq) &&
470                     likely(!vhost_exceeds_maxpend(net))) {
471                         msg.msg_flags |= MSG_MORE;
472                 } else {
473                         msg.msg_flags &= ~MSG_MORE;
474                 }
475
476                 /* TODO: Check specific error and bomb out unless ENOBUFS? */
477                 err = sock->ops->sendmsg(sock, &msg, len);
478                 if (unlikely(err < 0)) {
479                         if (zcopy_used) {
480                                 vhost_net_ubuf_put(ubufs);
481                                 nvq->upend_idx = ((unsigned)nvq->upend_idx - 1)
482                                         % UIO_MAXIOV;
483                         }
484                         vhost_discard_vq_desc(vq, 1);
485                         break;
486                 }
487                 if (err != len)
488                         pr_debug("Truncated TX packet: "
489                                  " len %d != %zd\n", err, len);
490                 if (!zcopy_used)
491                         vhost_add_used_and_signal(&net->dev, vq, head, 0);
492                 else
493                         vhost_zerocopy_signal_used(net, vq);
494                 vhost_net_tx_packet(net);
495                 if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
496                         vhost_poll_queue(&vq->poll);
497                         break;
498                 }
499         }
500 out:
501         mutex_unlock(&vq->mutex);
502 }
503
504 static int peek_head_len(struct sock *sk)
505 {
506         struct socket *sock = sk->sk_socket;
507         struct sk_buff *head;
508         int len = 0;
509         unsigned long flags;
510
511         if (sock->ops->peek_len)
512                 return sock->ops->peek_len(sock);
513
514         spin_lock_irqsave(&sk->sk_receive_queue.lock, flags);
515         head = skb_peek(&sk->sk_receive_queue);
516         if (likely(head)) {
517                 len = head->len;
518                 if (skb_vlan_tag_present(head))
519                         len += VLAN_HLEN;
520         }
521
522         spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags);
523         return len;
524 }
525
526 static int sk_has_rx_data(struct sock *sk)
527 {
528         struct socket *sock = sk->sk_socket;
529
530         if (sock->ops->peek_len)
531                 return sock->ops->peek_len(sock);
532
533         return skb_queue_empty(&sk->sk_receive_queue);
534 }
535
536 static int vhost_net_rx_peek_head_len(struct vhost_net *net, struct sock *sk)
537 {
538         struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
539         struct vhost_virtqueue *vq = &nvq->vq;
540         unsigned long uninitialized_var(endtime);
541         int len = peek_head_len(sk);
542
543         if (!len && vq->busyloop_timeout) {
544                 /* Both tx vq and rx socket were polled here */
545                 mutex_lock(&vq->mutex);
546                 vhost_disable_notify(&net->dev, vq);
547
548                 preempt_disable();
549                 endtime = busy_clock() + vq->busyloop_timeout;
550
551                 while (vhost_can_busy_poll(&net->dev, endtime) &&
552                        !sk_has_rx_data(sk) &&
553                        vhost_vq_avail_empty(&net->dev, vq))
554                         cpu_relax();
555
556                 preempt_enable();
557
558                 if (vhost_enable_notify(&net->dev, vq))
559                         vhost_poll_queue(&vq->poll);
560                 mutex_unlock(&vq->mutex);
561
562                 len = peek_head_len(sk);
563         }
564
565         return len;
566 }
567
568 /* This is a multi-buffer version of vhost_get_desc, that works if
569  *      vq has read descriptors only.
570  * @vq          - the relevant virtqueue
571  * @datalen     - data length we'll be reading
572  * @iovcount    - returned count of io vectors we fill
573  * @log         - vhost log
574  * @log_num     - log offset
575  * @quota       - headcount quota, 1 for big buffer
576  *      returns number of buffer heads allocated, negative on error
577  */
578 static int get_rx_bufs(struct vhost_virtqueue *vq,
579                        struct vring_used_elem *heads,
580                        int datalen,
581                        unsigned *iovcount,
582                        struct vhost_log *log,
583                        unsigned *log_num,
584                        unsigned int quota)
585 {
586         unsigned int out, in;
587         int seg = 0;
588         int headcount = 0;
589         unsigned d;
590         int r, nlogs = 0;
591         /* len is always initialized before use since we are always called with
592          * datalen > 0.
593          */
594         u32 uninitialized_var(len);
595
596         while (datalen > 0 && headcount < quota) {
597                 if (unlikely(seg >= UIO_MAXIOV)) {
598                         r = -ENOBUFS;
599                         goto err;
600                 }
601                 r = vhost_get_vq_desc(vq, vq->iov + seg,
602                                       ARRAY_SIZE(vq->iov) - seg, &out,
603                                       &in, log, log_num);
604                 if (unlikely(r < 0))
605                         goto err;
606
607                 d = r;
608                 if (d == vq->num) {
609                         r = 0;
610                         goto err;
611                 }
612                 if (unlikely(out || in <= 0)) {
613                         vq_err(vq, "unexpected descriptor format for RX: "
614                                 "out %d, in %d\n", out, in);
615                         r = -EINVAL;
616                         goto err;
617                 }
618                 if (unlikely(log)) {
619                         nlogs += *log_num;
620                         log += *log_num;
621                 }
622                 heads[headcount].id = cpu_to_vhost32(vq, d);
623                 len = iov_length(vq->iov + seg, in);
624                 heads[headcount].len = cpu_to_vhost32(vq, len);
625                 datalen -= len;
626                 ++headcount;
627                 seg += in;
628         }
629         heads[headcount - 1].len = cpu_to_vhost32(vq, len + datalen);
630         *iovcount = seg;
631         if (unlikely(log))
632                 *log_num = nlogs;
633
634         /* Detect overrun */
635         if (unlikely(datalen > 0)) {
636                 r = UIO_MAXIOV + 1;
637                 goto err;
638         }
639         return headcount;
640 err:
641         vhost_discard_vq_desc(vq, headcount);
642         return r;
643 }
644
645 /* Expects to be always run from workqueue - which acts as
646  * read-size critical section for our kind of RCU. */
647 static void handle_rx(struct vhost_net *net)
648 {
649         struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
650         struct vhost_virtqueue *vq = &nvq->vq;
651         unsigned uninitialized_var(in), log;
652         struct vhost_log *vq_log;
653         struct msghdr msg = {
654                 .msg_name = NULL,
655                 .msg_namelen = 0,
656                 .msg_control = NULL, /* FIXME: get and handle RX aux data. */
657                 .msg_controllen = 0,
658                 .msg_flags = MSG_DONTWAIT,
659         };
660         struct virtio_net_hdr hdr = {
661                 .flags = 0,
662                 .gso_type = VIRTIO_NET_HDR_GSO_NONE
663         };
664         size_t total_len = 0;
665         int err, mergeable;
666         s16 headcount;
667         size_t vhost_hlen, sock_hlen;
668         size_t vhost_len, sock_len;
669         struct socket *sock;
670         struct iov_iter fixup;
671         __virtio16 num_buffers;
672
673         mutex_lock(&vq->mutex);
674         sock = vq->private_data;
675         if (!sock)
676                 goto out;
677
678         if (!vq_iotlb_prefetch(vq))
679                 goto out;
680
681         vhost_disable_notify(&net->dev, vq);
682         vhost_net_disable_vq(net, vq);
683
684         vhost_hlen = nvq->vhost_hlen;
685         sock_hlen = nvq->sock_hlen;
686
687         vq_log = unlikely(vhost_has_feature(vq, VHOST_F_LOG_ALL)) ?
688                 vq->log : NULL;
689         mergeable = vhost_has_feature(vq, VIRTIO_NET_F_MRG_RXBUF);
690
691         while ((sock_len = vhost_net_rx_peek_head_len(net, sock->sk))) {
692                 sock_len += sock_hlen;
693                 vhost_len = sock_len + vhost_hlen;
694                 headcount = get_rx_bufs(vq, vq->heads, vhost_len,
695                                         &in, vq_log, &log,
696                                         likely(mergeable) ? UIO_MAXIOV : 1);
697                 /* On error, stop handling until the next kick. */
698                 if (unlikely(headcount < 0))
699                         goto out;
700                 /* On overrun, truncate and discard */
701                 if (unlikely(headcount > UIO_MAXIOV)) {
702                         iov_iter_init(&msg.msg_iter, READ, vq->iov, 1, 1);
703                         err = sock->ops->recvmsg(sock, &msg,
704                                                  1, MSG_DONTWAIT | MSG_TRUNC);
705                         pr_debug("Discarded rx packet: len %zd\n", sock_len);
706                         continue;
707                 }
708                 /* OK, now we need to know about added descriptors. */
709                 if (!headcount) {
710                         if (unlikely(vhost_enable_notify(&net->dev, vq))) {
711                                 /* They have slipped one in as we were
712                                  * doing that: check again. */
713                                 vhost_disable_notify(&net->dev, vq);
714                                 continue;
715                         }
716                         /* Nothing new?  Wait for eventfd to tell us
717                          * they refilled. */
718                         goto out;
719                 }
720                 /* We don't need to be notified again. */
721                 iov_iter_init(&msg.msg_iter, READ, vq->iov, in, vhost_len);
722                 fixup = msg.msg_iter;
723                 if (unlikely((vhost_hlen))) {
724                         /* We will supply the header ourselves
725                          * TODO: support TSO.
726                          */
727                         iov_iter_advance(&msg.msg_iter, vhost_hlen);
728                 }
729                 err = sock->ops->recvmsg(sock, &msg,
730                                          sock_len, MSG_DONTWAIT | MSG_TRUNC);
731                 /* Userspace might have consumed the packet meanwhile:
732                  * it's not supposed to do this usually, but might be hard
733                  * to prevent. Discard data we got (if any) and keep going. */
734                 if (unlikely(err != sock_len)) {
735                         pr_debug("Discarded rx packet: "
736                                  " len %d, expected %zd\n", err, sock_len);
737                         vhost_discard_vq_desc(vq, headcount);
738                         continue;
739                 }
740                 /* Supply virtio_net_hdr if VHOST_NET_F_VIRTIO_NET_HDR */
741                 if (unlikely(vhost_hlen)) {
742                         if (copy_to_iter(&hdr, sizeof(hdr),
743                                          &fixup) != sizeof(hdr)) {
744                                 vq_err(vq, "Unable to write vnet_hdr "
745                                        "at addr %p\n", vq->iov->iov_base);
746                                 goto out;
747                         }
748                 } else {
749                         /* Header came from socket; we'll need to patch
750                          * ->num_buffers over if VIRTIO_NET_F_MRG_RXBUF
751                          */
752                         iov_iter_advance(&fixup, sizeof(hdr));
753                 }
754                 /* TODO: Should check and handle checksum. */
755
756                 num_buffers = cpu_to_vhost16(vq, headcount);
757                 if (likely(mergeable) &&
758                     copy_to_iter(&num_buffers, sizeof num_buffers,
759                                  &fixup) != sizeof num_buffers) {
760                         vq_err(vq, "Failed num_buffers write");
761                         vhost_discard_vq_desc(vq, headcount);
762                         goto out;
763                 }
764                 vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
765                                             headcount);
766                 if (unlikely(vq_log))
767                         vhost_log_write(vq, vq_log, log, vhost_len);
768                 total_len += vhost_len;
769                 if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
770                         vhost_poll_queue(&vq->poll);
771                         goto out;
772                 }
773         }
774         vhost_net_enable_vq(net, vq);
775 out:
776         mutex_unlock(&vq->mutex);
777 }
778
779 static void handle_tx_kick(struct vhost_work *work)
780 {
781         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
782                                                   poll.work);
783         struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
784
785         handle_tx(net);
786 }
787
788 static void handle_rx_kick(struct vhost_work *work)
789 {
790         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
791                                                   poll.work);
792         struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
793
794         handle_rx(net);
795 }
796
797 static void handle_tx_net(struct vhost_work *work)
798 {
799         struct vhost_net *net = container_of(work, struct vhost_net,
800                                              poll[VHOST_NET_VQ_TX].work);
801         handle_tx(net);
802 }
803
804 static void handle_rx_net(struct vhost_work *work)
805 {
806         struct vhost_net *net = container_of(work, struct vhost_net,
807                                              poll[VHOST_NET_VQ_RX].work);
808         handle_rx(net);
809 }
810
811 static int vhost_net_open(struct inode *inode, struct file *f)
812 {
813         struct vhost_net *n;
814         struct vhost_dev *dev;
815         struct vhost_virtqueue **vqs;
816         int i;
817
818         n = kmalloc(sizeof *n, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
819         if (!n) {
820                 n = vmalloc(sizeof *n);
821                 if (!n)
822                         return -ENOMEM;
823         }
824         vqs = kmalloc(VHOST_NET_VQ_MAX * sizeof(*vqs), GFP_KERNEL);
825         if (!vqs) {
826                 kvfree(n);
827                 return -ENOMEM;
828         }
829
830         dev = &n->dev;
831         vqs[VHOST_NET_VQ_TX] = &n->vqs[VHOST_NET_VQ_TX].vq;
832         vqs[VHOST_NET_VQ_RX] = &n->vqs[VHOST_NET_VQ_RX].vq;
833         n->vqs[VHOST_NET_VQ_TX].vq.handle_kick = handle_tx_kick;
834         n->vqs[VHOST_NET_VQ_RX].vq.handle_kick = handle_rx_kick;
835         for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
836                 n->vqs[i].ubufs = NULL;
837                 n->vqs[i].ubuf_info = NULL;
838                 n->vqs[i].upend_idx = 0;
839                 n->vqs[i].done_idx = 0;
840                 n->vqs[i].vhost_hlen = 0;
841                 n->vqs[i].sock_hlen = 0;
842         }
843         vhost_dev_init(dev, vqs, VHOST_NET_VQ_MAX);
844
845         vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, POLLOUT, dev);
846         vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, POLLIN, dev);
847
848         f->private_data = n;
849
850         return 0;
851 }
852
853 static struct socket *vhost_net_stop_vq(struct vhost_net *n,
854                                         struct vhost_virtqueue *vq)
855 {
856         struct socket *sock;
857
858         mutex_lock(&vq->mutex);
859         sock = vq->private_data;
860         vhost_net_disable_vq(n, vq);
861         vq->private_data = NULL;
862         mutex_unlock(&vq->mutex);
863         return sock;
864 }
865
866 static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock,
867                            struct socket **rx_sock)
868 {
869         *tx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_TX].vq);
870         *rx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_RX].vq);
871 }
872
873 static void vhost_net_flush_vq(struct vhost_net *n, int index)
874 {
875         vhost_poll_flush(n->poll + index);
876         vhost_poll_flush(&n->vqs[index].vq.poll);
877 }
878
879 static void vhost_net_flush(struct vhost_net *n)
880 {
881         vhost_net_flush_vq(n, VHOST_NET_VQ_TX);
882         vhost_net_flush_vq(n, VHOST_NET_VQ_RX);
883         if (n->vqs[VHOST_NET_VQ_TX].ubufs) {
884                 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
885                 n->tx_flush = true;
886                 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
887                 /* Wait for all lower device DMAs done. */
888                 vhost_net_ubuf_put_and_wait(n->vqs[VHOST_NET_VQ_TX].ubufs);
889                 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
890                 n->tx_flush = false;
891                 atomic_set(&n->vqs[VHOST_NET_VQ_TX].ubufs->refcount, 1);
892                 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
893         }
894 }
895
896 static int vhost_net_release(struct inode *inode, struct file *f)
897 {
898         struct vhost_net *n = f->private_data;
899         struct socket *tx_sock;
900         struct socket *rx_sock;
901
902         vhost_net_stop(n, &tx_sock, &rx_sock);
903         vhost_net_flush(n);
904         vhost_dev_stop(&n->dev);
905         vhost_dev_cleanup(&n->dev, false);
906         vhost_net_vq_reset(n);
907         if (tx_sock)
908                 sockfd_put(tx_sock);
909         if (rx_sock)
910                 sockfd_put(rx_sock);
911         /* Make sure no callbacks are outstanding */
912         synchronize_rcu_bh();
913         /* We do an extra flush before freeing memory,
914          * since jobs can re-queue themselves. */
915         vhost_net_flush(n);
916         kfree(n->dev.vqs);
917         kvfree(n);
918         return 0;
919 }
920
921 static struct socket *get_raw_socket(int fd)
922 {
923         struct {
924                 struct sockaddr_ll sa;
925                 char  buf[MAX_ADDR_LEN];
926         } uaddr;
927         int uaddr_len = sizeof uaddr, r;
928         struct socket *sock = sockfd_lookup(fd, &r);
929
930         if (!sock)
931                 return ERR_PTR(-ENOTSOCK);
932
933         /* Parameter checking */
934         if (sock->sk->sk_type != SOCK_RAW) {
935                 r = -ESOCKTNOSUPPORT;
936                 goto err;
937         }
938
939         r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa,
940                                &uaddr_len, 0);
941         if (r)
942                 goto err;
943
944         if (uaddr.sa.sll_family != AF_PACKET) {
945                 r = -EPFNOSUPPORT;
946                 goto err;
947         }
948         return sock;
949 err:
950         sockfd_put(sock);
951         return ERR_PTR(r);
952 }
953
954 static struct socket *get_tap_socket(int fd)
955 {
956         struct file *file = fget(fd);
957         struct socket *sock;
958
959         if (!file)
960                 return ERR_PTR(-EBADF);
961         sock = tun_get_socket(file);
962         if (!IS_ERR(sock))
963                 return sock;
964         sock = tap_get_socket(file);
965         if (IS_ERR(sock))
966                 fput(file);
967         return sock;
968 }
969
970 static struct socket *get_socket(int fd)
971 {
972         struct socket *sock;
973
974         /* special case to disable backend */
975         if (fd == -1)
976                 return NULL;
977         sock = get_raw_socket(fd);
978         if (!IS_ERR(sock))
979                 return sock;
980         sock = get_tap_socket(fd);
981         if (!IS_ERR(sock))
982                 return sock;
983         return ERR_PTR(-ENOTSOCK);
984 }
985
986 static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
987 {
988         struct socket *sock, *oldsock;
989         struct vhost_virtqueue *vq;
990         struct vhost_net_virtqueue *nvq;
991         struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL;
992         int r;
993
994         mutex_lock(&n->dev.mutex);
995         r = vhost_dev_check_owner(&n->dev);
996         if (r)
997                 goto err;
998
999         if (index >= VHOST_NET_VQ_MAX) {
1000                 r = -ENOBUFS;
1001                 goto err;
1002         }
1003         vq = &n->vqs[index].vq;
1004         nvq = &n->vqs[index];
1005         mutex_lock(&vq->mutex);
1006
1007         /* Verify that ring has been setup correctly. */
1008         if (!vhost_vq_access_ok(vq)) {
1009                 r = -EFAULT;
1010                 goto err_vq;
1011         }
1012         sock = get_socket(fd);
1013         if (IS_ERR(sock)) {
1014                 r = PTR_ERR(sock);
1015                 goto err_vq;
1016         }
1017
1018         /* start polling new socket */
1019         oldsock = vq->private_data;
1020         if (sock != oldsock) {
1021                 ubufs = vhost_net_ubuf_alloc(vq,
1022                                              sock && vhost_sock_zcopy(sock));
1023                 if (IS_ERR(ubufs)) {
1024                         r = PTR_ERR(ubufs);
1025                         goto err_ubufs;
1026                 }
1027
1028                 vhost_net_disable_vq(n, vq);
1029                 vq->private_data = sock;
1030                 r = vhost_vq_init_access(vq);
1031                 if (r)
1032                         goto err_used;
1033                 r = vhost_net_enable_vq(n, vq);
1034                 if (r)
1035                         goto err_used;
1036
1037                 oldubufs = nvq->ubufs;
1038                 nvq->ubufs = ubufs;
1039
1040                 n->tx_packets = 0;
1041                 n->tx_zcopy_err = 0;
1042                 n->tx_flush = false;
1043         }
1044
1045         mutex_unlock(&vq->mutex);
1046
1047         if (oldubufs) {
1048                 vhost_net_ubuf_put_wait_and_free(oldubufs);
1049                 mutex_lock(&vq->mutex);
1050                 vhost_zerocopy_signal_used(n, vq);
1051                 mutex_unlock(&vq->mutex);
1052         }
1053
1054         if (oldsock) {
1055                 vhost_net_flush_vq(n, index);
1056                 sockfd_put(oldsock);
1057         }
1058
1059         mutex_unlock(&n->dev.mutex);
1060         return 0;
1061
1062 err_used:
1063         vq->private_data = oldsock;
1064         vhost_net_enable_vq(n, vq);
1065         if (ubufs)
1066                 vhost_net_ubuf_put_wait_and_free(ubufs);
1067 err_ubufs:
1068         sockfd_put(sock);
1069 err_vq:
1070         mutex_unlock(&vq->mutex);
1071 err:
1072         mutex_unlock(&n->dev.mutex);
1073         return r;
1074 }
1075
1076 static long vhost_net_reset_owner(struct vhost_net *n)
1077 {
1078         struct socket *tx_sock = NULL;
1079         struct socket *rx_sock = NULL;
1080         long err;
1081         struct vhost_umem *umem;
1082
1083         mutex_lock(&n->dev.mutex);
1084         err = vhost_dev_check_owner(&n->dev);
1085         if (err)
1086                 goto done;
1087         umem = vhost_dev_reset_owner_prepare();
1088         if (!umem) {
1089                 err = -ENOMEM;
1090                 goto done;
1091         }
1092         vhost_net_stop(n, &tx_sock, &rx_sock);
1093         vhost_net_flush(n);
1094         vhost_dev_reset_owner(&n->dev, umem);
1095         vhost_net_vq_reset(n);
1096 done:
1097         mutex_unlock(&n->dev.mutex);
1098         if (tx_sock)
1099                 sockfd_put(tx_sock);
1100         if (rx_sock)
1101                 sockfd_put(rx_sock);
1102         return err;
1103 }
1104
1105 static int vhost_net_set_features(struct vhost_net *n, u64 features)
1106 {
1107         size_t vhost_hlen, sock_hlen, hdr_len;
1108         int i;
1109
1110         hdr_len = (features & ((1ULL << VIRTIO_NET_F_MRG_RXBUF) |
1111                                (1ULL << VIRTIO_F_VERSION_1))) ?
1112                         sizeof(struct virtio_net_hdr_mrg_rxbuf) :
1113                         sizeof(struct virtio_net_hdr);
1114         if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) {
1115                 /* vhost provides vnet_hdr */
1116                 vhost_hlen = hdr_len;
1117                 sock_hlen = 0;
1118         } else {
1119                 /* socket provides vnet_hdr */
1120                 vhost_hlen = 0;
1121                 sock_hlen = hdr_len;
1122         }
1123         mutex_lock(&n->dev.mutex);
1124         if ((features & (1 << VHOST_F_LOG_ALL)) &&
1125             !vhost_log_access_ok(&n->dev))
1126                 goto out_unlock;
1127
1128         if ((features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))) {
1129                 if (vhost_init_device_iotlb(&n->dev, true))
1130                         goto out_unlock;
1131         }
1132
1133         for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
1134                 mutex_lock(&n->vqs[i].vq.mutex);
1135                 n->vqs[i].vq.acked_features = features;
1136                 n->vqs[i].vhost_hlen = vhost_hlen;
1137                 n->vqs[i].sock_hlen = sock_hlen;
1138                 mutex_unlock(&n->vqs[i].vq.mutex);
1139         }
1140         mutex_unlock(&n->dev.mutex);
1141         return 0;
1142
1143 out_unlock:
1144         mutex_unlock(&n->dev.mutex);
1145         return -EFAULT;
1146 }
1147
1148 static long vhost_net_set_owner(struct vhost_net *n)
1149 {
1150         int r;
1151
1152         mutex_lock(&n->dev.mutex);
1153         if (vhost_dev_has_owner(&n->dev)) {
1154                 r = -EBUSY;
1155                 goto out;
1156         }
1157         r = vhost_net_set_ubuf_info(n);
1158         if (r)
1159                 goto out;
1160         r = vhost_dev_set_owner(&n->dev);
1161         if (r)
1162                 vhost_net_clear_ubuf_info(n);
1163         vhost_net_flush(n);
1164 out:
1165         mutex_unlock(&n->dev.mutex);
1166         return r;
1167 }
1168
1169 static long vhost_net_ioctl(struct file *f, unsigned int ioctl,
1170                             unsigned long arg)
1171 {
1172         struct vhost_net *n = f->private_data;
1173         void __user *argp = (void __user *)arg;
1174         u64 __user *featurep = argp;
1175         struct vhost_vring_file backend;
1176         u64 features;
1177         int r;
1178
1179         switch (ioctl) {
1180         case VHOST_NET_SET_BACKEND:
1181                 if (copy_from_user(&backend, argp, sizeof backend))
1182                         return -EFAULT;
1183                 return vhost_net_set_backend(n, backend.index, backend.fd);
1184         case VHOST_GET_FEATURES:
1185                 features = VHOST_NET_FEATURES;
1186                 if (copy_to_user(featurep, &features, sizeof features))
1187                         return -EFAULT;
1188                 return 0;
1189         case VHOST_SET_FEATURES:
1190                 if (copy_from_user(&features, featurep, sizeof features))
1191                         return -EFAULT;
1192                 if (features & ~VHOST_NET_FEATURES)
1193                         return -EOPNOTSUPP;
1194                 return vhost_net_set_features(n, features);
1195         case VHOST_RESET_OWNER:
1196                 return vhost_net_reset_owner(n);
1197         case VHOST_SET_OWNER:
1198                 return vhost_net_set_owner(n);
1199         default:
1200                 mutex_lock(&n->dev.mutex);
1201                 r = vhost_dev_ioctl(&n->dev, ioctl, argp);
1202                 if (r == -ENOIOCTLCMD)
1203                         r = vhost_vring_ioctl(&n->dev, ioctl, argp);
1204                 else
1205                         vhost_net_flush(n);
1206                 mutex_unlock(&n->dev.mutex);
1207                 return r;
1208         }
1209 }
1210
1211 #ifdef CONFIG_COMPAT
1212 static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl,
1213                                    unsigned long arg)
1214 {
1215         return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
1216 }
1217 #endif
1218
1219 static ssize_t vhost_net_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
1220 {
1221         struct file *file = iocb->ki_filp;
1222         struct vhost_net *n = file->private_data;
1223         struct vhost_dev *dev = &n->dev;
1224         int noblock = file->f_flags & O_NONBLOCK;
1225
1226         return vhost_chr_read_iter(dev, to, noblock);
1227 }
1228
1229 static ssize_t vhost_net_chr_write_iter(struct kiocb *iocb,
1230                                         struct iov_iter *from)
1231 {
1232         struct file *file = iocb->ki_filp;
1233         struct vhost_net *n = file->private_data;
1234         struct vhost_dev *dev = &n->dev;
1235
1236         return vhost_chr_write_iter(dev, from);
1237 }
1238
1239 static unsigned int vhost_net_chr_poll(struct file *file, poll_table *wait)
1240 {
1241         struct vhost_net *n = file->private_data;
1242         struct vhost_dev *dev = &n->dev;
1243
1244         return vhost_chr_poll(file, dev, wait);
1245 }
1246
1247 static const struct file_operations vhost_net_fops = {
1248         .owner          = THIS_MODULE,
1249         .release        = vhost_net_release,
1250         .read_iter      = vhost_net_chr_read_iter,
1251         .write_iter     = vhost_net_chr_write_iter,
1252         .poll           = vhost_net_chr_poll,
1253         .unlocked_ioctl = vhost_net_ioctl,
1254 #ifdef CONFIG_COMPAT
1255         .compat_ioctl   = vhost_net_compat_ioctl,
1256 #endif
1257         .open           = vhost_net_open,
1258         .llseek         = noop_llseek,
1259 };
1260
1261 static struct miscdevice vhost_net_misc = {
1262         .minor = VHOST_NET_MINOR,
1263         .name = "vhost-net",
1264         .fops = &vhost_net_fops,
1265 };
1266
1267 static int vhost_net_init(void)
1268 {
1269         if (experimental_zcopytx)
1270                 vhost_net_enable_zcopy(VHOST_NET_VQ_TX);
1271         return misc_register(&vhost_net_misc);
1272 }
1273 module_init(vhost_net_init);
1274
1275 static void vhost_net_exit(void)
1276 {
1277         misc_deregister(&vhost_net_misc);
1278 }
1279 module_exit(vhost_net_exit);
1280
1281 MODULE_VERSION("0.0.1");
1282 MODULE_LICENSE("GPL v2");
1283 MODULE_AUTHOR("Michael S. Tsirkin");
1284 MODULE_DESCRIPTION("Host kernel accelerator for virtio net");
1285 MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR);
1286 MODULE_ALIAS("devname:vhost-net");