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