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