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