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