]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/vhost/net.c
Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/jesse/openvswitch
[karo-tx-linux.git] / drivers / vhost / net.c
1 /* Copyright (C) 2009 Red Hat, Inc.
2  * Author: Michael S. Tsirkin <mst@redhat.com>
3  *
4  * This work is licensed under the terms of the GNU GPL, version 2.
5  *
6  * virtio-net server in host kernel.
7  */
8
9 #include <linux/compat.h>
10 #include <linux/eventfd.h>
11 #include <linux/vhost.h>
12 #include <linux/virtio_net.h>
13 #include <linux/miscdevice.h>
14 #include <linux/module.h>
15 #include <linux/moduleparam.h>
16 #include <linux/mutex.h>
17 #include <linux/workqueue.h>
18 #include <linux/rcupdate.h>
19 #include <linux/file.h>
20 #include <linux/slab.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    3
52 /* Lower device DMA done */
53 #define VHOST_DMA_DONE_LEN      2
54 /* Lower device DMA in progress */
55 #define VHOST_DMA_IN_PROGRESS   1
56 /* Buffer unused */
57 #define VHOST_DMA_CLEAR_LEN     0
58
59 #define VHOST_DMA_IS_DONE(len) ((len) >= VHOST_DMA_DONE_LEN)
60
61 enum {
62         VHOST_NET_VQ_RX = 0,
63         VHOST_NET_VQ_TX = 1,
64         VHOST_NET_VQ_MAX = 2,
65 };
66
67 struct vhost_net {
68         struct vhost_dev dev;
69         struct vhost_virtqueue vqs[VHOST_NET_VQ_MAX];
70         struct vhost_poll poll[VHOST_NET_VQ_MAX];
71         /* Number of TX recently submitted.
72          * Protected by tx vq lock. */
73         unsigned tx_packets;
74         /* Number of times zerocopy TX recently failed.
75          * Protected by tx vq lock. */
76         unsigned tx_zcopy_err;
77         /* Flush in progress. Protected by tx vq lock. */
78         bool tx_flush;
79 };
80
81 static void vhost_net_tx_packet(struct vhost_net *net)
82 {
83         ++net->tx_packets;
84         if (net->tx_packets < 1024)
85                 return;
86         net->tx_packets = 0;
87         net->tx_zcopy_err = 0;
88 }
89
90 static void vhost_net_tx_err(struct vhost_net *net)
91 {
92         ++net->tx_zcopy_err;
93 }
94
95 static bool vhost_net_tx_select_zcopy(struct vhost_net *net)
96 {
97         /* TX flush waits for outstanding DMAs to be done.
98          * Don't start new DMAs.
99          */
100         return !net->tx_flush &&
101                 net->tx_packets / 64 >= net->tx_zcopy_err;
102 }
103
104 static bool vhost_sock_zcopy(struct socket *sock)
105 {
106         return unlikely(experimental_zcopytx) &&
107                 sock_flag(sock->sk, SOCK_ZEROCOPY);
108 }
109
110 /* Pop first len bytes from iovec. Return number of segments used. */
111 static int move_iovec_hdr(struct iovec *from, struct iovec *to,
112                           size_t len, int iov_count)
113 {
114         int seg = 0;
115         size_t size;
116
117         while (len && seg < iov_count) {
118                 size = min(from->iov_len, len);
119                 to->iov_base = from->iov_base;
120                 to->iov_len = size;
121                 from->iov_len -= size;
122                 from->iov_base += size;
123                 len -= size;
124                 ++from;
125                 ++to;
126                 ++seg;
127         }
128         return seg;
129 }
130 /* Copy iovec entries for len bytes from iovec. */
131 static void copy_iovec_hdr(const struct iovec *from, struct iovec *to,
132                            size_t len, int iovcount)
133 {
134         int seg = 0;
135         size_t size;
136
137         while (len && seg < iovcount) {
138                 size = min(from->iov_len, len);
139                 to->iov_base = from->iov_base;
140                 to->iov_len = size;
141                 len -= size;
142                 ++from;
143                 ++to;
144                 ++seg;
145         }
146 }
147
148 /* In case of DMA done not in order in lower device driver for some reason.
149  * upend_idx is used to track end of used idx, done_idx is used to track head
150  * of used idx. Once lower device DMA done contiguously, we will signal KVM
151  * guest used idx.
152  */
153 static int vhost_zerocopy_signal_used(struct vhost_net *net,
154                                       struct vhost_virtqueue *vq)
155 {
156         int i;
157         int j = 0;
158
159         for (i = vq->done_idx; i != vq->upend_idx; i = (i + 1) % UIO_MAXIOV) {
160                 if (vq->heads[i].len == VHOST_DMA_FAILED_LEN)
161                         vhost_net_tx_err(net);
162                 if (VHOST_DMA_IS_DONE(vq->heads[i].len)) {
163                         vq->heads[i].len = VHOST_DMA_CLEAR_LEN;
164                         vhost_add_used_and_signal(vq->dev, vq,
165                                                   vq->heads[i].id, 0);
166                         ++j;
167                 } else
168                         break;
169         }
170         if (j)
171                 vq->done_idx = i;
172         return j;
173 }
174
175 static void vhost_zerocopy_callback(struct ubuf_info *ubuf, bool success)
176 {
177         struct vhost_ubuf_ref *ubufs = ubuf->ctx;
178         struct vhost_virtqueue *vq = ubufs->vq;
179         int cnt = atomic_read(&ubufs->kref.refcount);
180
181         /*
182          * Trigger polling thread if guest stopped submitting new buffers:
183          * in this case, the refcount after decrement will eventually reach 1
184          * so here it is 2.
185          * We also trigger polling periodically after each 16 packets
186          * (the value 16 here is more or less arbitrary, it's tuned to trigger
187          * less than 10% of times).
188          */
189         if (cnt <= 2 || !(cnt % 16))
190                 vhost_poll_queue(&vq->poll);
191         /* set len to mark this desc buffers done DMA */
192         vq->heads[ubuf->desc].len = success ?
193                 VHOST_DMA_DONE_LEN : VHOST_DMA_FAILED_LEN;
194         vhost_ubuf_put(ubufs);
195 }
196
197 /* Expects to be always run from workqueue - which acts as
198  * read-size critical section for our kind of RCU. */
199 static void handle_tx(struct vhost_net *net)
200 {
201         struct vhost_virtqueue *vq = &net->dev.vqs[VHOST_NET_VQ_TX];
202         unsigned out, in, s;
203         int head;
204         struct msghdr msg = {
205                 .msg_name = NULL,
206                 .msg_namelen = 0,
207                 .msg_control = NULL,
208                 .msg_controllen = 0,
209                 .msg_iov = vq->iov,
210                 .msg_flags = MSG_DONTWAIT,
211         };
212         size_t len, total_len = 0;
213         int err;
214         size_t hdr_size;
215         struct socket *sock;
216         struct vhost_ubuf_ref *uninitialized_var(ubufs);
217         bool zcopy, zcopy_used;
218
219         /* TODO: check that we are running from vhost_worker? */
220         sock = rcu_dereference_check(vq->private_data, 1);
221         if (!sock)
222                 return;
223
224         mutex_lock(&vq->mutex);
225         vhost_disable_notify(&net->dev, vq);
226
227         hdr_size = vq->vhost_hlen;
228         zcopy = vq->ubufs;
229
230         for (;;) {
231                 /* Release DMAs done buffers first */
232                 if (zcopy)
233                         vhost_zerocopy_signal_used(net, vq);
234
235                 head = vhost_get_vq_desc(&net->dev, vq, vq->iov,
236                                          ARRAY_SIZE(vq->iov),
237                                          &out, &in,
238                                          NULL, NULL);
239                 /* On error, stop handling until the next kick. */
240                 if (unlikely(head < 0))
241                         break;
242                 /* Nothing new?  Wait for eventfd to tell us they refilled. */
243                 if (head == vq->num) {
244                         int num_pends;
245
246                         /* If more outstanding DMAs, queue the work.
247                          * Handle upend_idx wrap around
248                          */
249                         num_pends = likely(vq->upend_idx >= vq->done_idx) ?
250                                     (vq->upend_idx - vq->done_idx) :
251                                     (vq->upend_idx + UIO_MAXIOV - vq->done_idx);
252                         if (unlikely(num_pends > VHOST_MAX_PEND))
253                                 break;
254                         if (unlikely(vhost_enable_notify(&net->dev, vq))) {
255                                 vhost_disable_notify(&net->dev, vq);
256                                 continue;
257                         }
258                         break;
259                 }
260                 if (in) {
261                         vq_err(vq, "Unexpected descriptor format for TX: "
262                                "out %d, int %d\n", out, in);
263                         break;
264                 }
265                 /* Skip header. TODO: support TSO. */
266                 s = move_iovec_hdr(vq->iov, vq->hdr, hdr_size, out);
267                 msg.msg_iovlen = out;
268                 len = iov_length(vq->iov, out);
269                 /* Sanity check */
270                 if (!len) {
271                         vq_err(vq, "Unexpected header len for TX: "
272                                "%zd expected %zd\n",
273                                iov_length(vq->hdr, s), hdr_size);
274                         break;
275                 }
276                 zcopy_used = zcopy && (len >= VHOST_GOODCOPY_LEN ||
277                                        vq->upend_idx != vq->done_idx);
278
279                 /* use msg_control to pass vhost zerocopy ubuf info to skb */
280                 if (zcopy_used) {
281                         vq->heads[vq->upend_idx].id = head;
282                         if (!vhost_net_tx_select_zcopy(net) ||
283                             len < VHOST_GOODCOPY_LEN) {
284                                 /* copy don't need to wait for DMA done */
285                                 vq->heads[vq->upend_idx].len =
286                                                         VHOST_DMA_DONE_LEN;
287                                 msg.msg_control = NULL;
288                                 msg.msg_controllen = 0;
289                                 ubufs = NULL;
290                         } else {
291                                 struct ubuf_info *ubuf;
292                                 ubuf = vq->ubuf_info + vq->upend_idx;
293
294                                 vq->heads[vq->upend_idx].len =
295                                         VHOST_DMA_IN_PROGRESS;
296                                 ubuf->callback = vhost_zerocopy_callback;
297                                 ubuf->ctx = vq->ubufs;
298                                 ubuf->desc = vq->upend_idx;
299                                 msg.msg_control = ubuf;
300                                 msg.msg_controllen = sizeof(ubuf);
301                                 ubufs = vq->ubufs;
302                                 kref_get(&ubufs->kref);
303                         }
304                         vq->upend_idx = (vq->upend_idx + 1) % UIO_MAXIOV;
305                 }
306                 /* TODO: Check specific error and bomb out unless ENOBUFS? */
307                 err = sock->ops->sendmsg(NULL, sock, &msg, len);
308                 if (unlikely(err < 0)) {
309                         if (zcopy_used) {
310                                 if (ubufs)
311                                         vhost_ubuf_put(ubufs);
312                                 vq->upend_idx = ((unsigned)vq->upend_idx - 1) %
313                                         UIO_MAXIOV;
314                         }
315                         vhost_discard_vq_desc(vq, 1);
316                         break;
317                 }
318                 if (err != len)
319                         pr_debug("Truncated TX packet: "
320                                  " len %d != %zd\n", err, len);
321                 if (!zcopy_used)
322                         vhost_add_used_and_signal(&net->dev, vq, head, 0);
323                 else
324                         vhost_zerocopy_signal_used(net, vq);
325                 total_len += len;
326                 vhost_net_tx_packet(net);
327                 if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
328                         vhost_poll_queue(&vq->poll);
329                         break;
330                 }
331         }
332
333         mutex_unlock(&vq->mutex);
334 }
335
336 static int peek_head_len(struct sock *sk)
337 {
338         struct sk_buff *head;
339         int len = 0;
340         unsigned long flags;
341
342         spin_lock_irqsave(&sk->sk_receive_queue.lock, flags);
343         head = skb_peek(&sk->sk_receive_queue);
344         if (likely(head)) {
345                 len = head->len;
346                 if (vlan_tx_tag_present(head))
347                         len += VLAN_HLEN;
348         }
349
350         spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags);
351         return len;
352 }
353
354 /* This is a multi-buffer version of vhost_get_desc, that works if
355  *      vq has read descriptors only.
356  * @vq          - the relevant virtqueue
357  * @datalen     - data length we'll be reading
358  * @iovcount    - returned count of io vectors we fill
359  * @log         - vhost log
360  * @log_num     - log offset
361  * @quota       - headcount quota, 1 for big buffer
362  *      returns number of buffer heads allocated, negative on error
363  */
364 static int get_rx_bufs(struct vhost_virtqueue *vq,
365                        struct vring_used_elem *heads,
366                        int datalen,
367                        unsigned *iovcount,
368                        struct vhost_log *log,
369                        unsigned *log_num,
370                        unsigned int quota)
371 {
372         unsigned int out, in;
373         int seg = 0;
374         int headcount = 0;
375         unsigned d;
376         int r, nlogs = 0;
377
378         while (datalen > 0 && headcount < quota) {
379                 if (unlikely(seg >= UIO_MAXIOV)) {
380                         r = -ENOBUFS;
381                         goto err;
382                 }
383                 d = vhost_get_vq_desc(vq->dev, vq, vq->iov + seg,
384                                       ARRAY_SIZE(vq->iov) - seg, &out,
385                                       &in, log, log_num);
386                 if (d == vq->num) {
387                         r = 0;
388                         goto err;
389                 }
390                 if (unlikely(out || in <= 0)) {
391                         vq_err(vq, "unexpected descriptor format for RX: "
392                                 "out %d, in %d\n", out, in);
393                         r = -EINVAL;
394                         goto err;
395                 }
396                 if (unlikely(log)) {
397                         nlogs += *log_num;
398                         log += *log_num;
399                 }
400                 heads[headcount].id = d;
401                 heads[headcount].len = iov_length(vq->iov + seg, in);
402                 datalen -= heads[headcount].len;
403                 ++headcount;
404                 seg += in;
405         }
406         heads[headcount - 1].len += datalen;
407         *iovcount = seg;
408         if (unlikely(log))
409                 *log_num = nlogs;
410         return headcount;
411 err:
412         vhost_discard_vq_desc(vq, headcount);
413         return r;
414 }
415
416 /* Expects to be always run from workqueue - which acts as
417  * read-size critical section for our kind of RCU. */
418 static void handle_rx(struct vhost_net *net)
419 {
420         struct vhost_virtqueue *vq = &net->dev.vqs[VHOST_NET_VQ_RX];
421         unsigned uninitialized_var(in), log;
422         struct vhost_log *vq_log;
423         struct msghdr msg = {
424                 .msg_name = NULL,
425                 .msg_namelen = 0,
426                 .msg_control = NULL, /* FIXME: get and handle RX aux data. */
427                 .msg_controllen = 0,
428                 .msg_iov = vq->iov,
429                 .msg_flags = MSG_DONTWAIT,
430         };
431         struct virtio_net_hdr_mrg_rxbuf hdr = {
432                 .hdr.flags = 0,
433                 .hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE
434         };
435         size_t total_len = 0;
436         int err, mergeable;
437         s16 headcount;
438         size_t vhost_hlen, sock_hlen;
439         size_t vhost_len, sock_len;
440         /* TODO: check that we are running from vhost_worker? */
441         struct socket *sock = rcu_dereference_check(vq->private_data, 1);
442
443         if (!sock)
444                 return;
445
446         mutex_lock(&vq->mutex);
447         vhost_disable_notify(&net->dev, vq);
448         vhost_hlen = vq->vhost_hlen;
449         sock_hlen = vq->sock_hlen;
450
451         vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ?
452                 vq->log : NULL;
453         mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF);
454
455         while ((sock_len = peek_head_len(sock->sk))) {
456                 sock_len += sock_hlen;
457                 vhost_len = sock_len + vhost_hlen;
458                 headcount = get_rx_bufs(vq, vq->heads, vhost_len,
459                                         &in, vq_log, &log,
460                                         likely(mergeable) ? UIO_MAXIOV : 1);
461                 /* On error, stop handling until the next kick. */
462                 if (unlikely(headcount < 0))
463                         break;
464                 /* OK, now we need to know about added descriptors. */
465                 if (!headcount) {
466                         if (unlikely(vhost_enable_notify(&net->dev, vq))) {
467                                 /* They have slipped one in as we were
468                                  * doing that: check again. */
469                                 vhost_disable_notify(&net->dev, vq);
470                                 continue;
471                         }
472                         /* Nothing new?  Wait for eventfd to tell us
473                          * they refilled. */
474                         break;
475                 }
476                 /* We don't need to be notified again. */
477                 if (unlikely((vhost_hlen)))
478                         /* Skip header. TODO: support TSO. */
479                         move_iovec_hdr(vq->iov, vq->hdr, vhost_hlen, in);
480                 else
481                         /* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF:
482                          * needed because recvmsg can modify msg_iov. */
483                         copy_iovec_hdr(vq->iov, vq->hdr, sock_hlen, in);
484                 msg.msg_iovlen = in;
485                 err = sock->ops->recvmsg(NULL, sock, &msg,
486                                          sock_len, MSG_DONTWAIT | MSG_TRUNC);
487                 /* Userspace might have consumed the packet meanwhile:
488                  * it's not supposed to do this usually, but might be hard
489                  * to prevent. Discard data we got (if any) and keep going. */
490                 if (unlikely(err != sock_len)) {
491                         pr_debug("Discarded rx packet: "
492                                  " len %d, expected %zd\n", err, sock_len);
493                         vhost_discard_vq_desc(vq, headcount);
494                         continue;
495                 }
496                 if (unlikely(vhost_hlen) &&
497                     memcpy_toiovecend(vq->hdr, (unsigned char *)&hdr, 0,
498                                       vhost_hlen)) {
499                         vq_err(vq, "Unable to write vnet_hdr at addr %p\n",
500                                vq->iov->iov_base);
501                         break;
502                 }
503                 /* TODO: Should check and handle checksum. */
504                 if (likely(mergeable) &&
505                     memcpy_toiovecend(vq->hdr, (unsigned char *)&headcount,
506                                       offsetof(typeof(hdr), num_buffers),
507                                       sizeof hdr.num_buffers)) {
508                         vq_err(vq, "Failed num_buffers write");
509                         vhost_discard_vq_desc(vq, headcount);
510                         break;
511                 }
512                 vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
513                                             headcount);
514                 if (unlikely(vq_log))
515                         vhost_log_write(vq, vq_log, log, vhost_len);
516                 total_len += vhost_len;
517                 if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
518                         vhost_poll_queue(&vq->poll);
519                         break;
520                 }
521         }
522
523         mutex_unlock(&vq->mutex);
524 }
525
526 static void handle_tx_kick(struct vhost_work *work)
527 {
528         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
529                                                   poll.work);
530         struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
531
532         handle_tx(net);
533 }
534
535 static void handle_rx_kick(struct vhost_work *work)
536 {
537         struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
538                                                   poll.work);
539         struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
540
541         handle_rx(net);
542 }
543
544 static void handle_tx_net(struct vhost_work *work)
545 {
546         struct vhost_net *net = container_of(work, struct vhost_net,
547                                              poll[VHOST_NET_VQ_TX].work);
548         handle_tx(net);
549 }
550
551 static void handle_rx_net(struct vhost_work *work)
552 {
553         struct vhost_net *net = container_of(work, struct vhost_net,
554                                              poll[VHOST_NET_VQ_RX].work);
555         handle_rx(net);
556 }
557
558 static int vhost_net_open(struct inode *inode, struct file *f)
559 {
560         struct vhost_net *n = kmalloc(sizeof *n, GFP_KERNEL);
561         struct vhost_dev *dev;
562         int r;
563
564         if (!n)
565                 return -ENOMEM;
566
567         dev = &n->dev;
568         n->vqs[VHOST_NET_VQ_TX].handle_kick = handle_tx_kick;
569         n->vqs[VHOST_NET_VQ_RX].handle_kick = handle_rx_kick;
570         r = vhost_dev_init(dev, n->vqs, VHOST_NET_VQ_MAX);
571         if (r < 0) {
572                 kfree(n);
573                 return r;
574         }
575
576         vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, POLLOUT, dev);
577         vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, POLLIN, dev);
578
579         f->private_data = n;
580
581         return 0;
582 }
583
584 static void vhost_net_disable_vq(struct vhost_net *n,
585                                  struct vhost_virtqueue *vq)
586 {
587         struct vhost_poll *poll = n->poll + (vq - n->vqs);
588         if (!vq->private_data)
589                 return;
590         vhost_poll_stop(poll);
591 }
592
593 static int vhost_net_enable_vq(struct vhost_net *n,
594                                 struct vhost_virtqueue *vq)
595 {
596         struct vhost_poll *poll = n->poll + (vq - n->vqs);
597         struct socket *sock;
598
599         sock = rcu_dereference_protected(vq->private_data,
600                                          lockdep_is_held(&vq->mutex));
601         if (!sock)
602                 return 0;
603
604         return vhost_poll_start(poll, sock->file);
605 }
606
607 static struct socket *vhost_net_stop_vq(struct vhost_net *n,
608                                         struct vhost_virtqueue *vq)
609 {
610         struct socket *sock;
611
612         mutex_lock(&vq->mutex);
613         sock = rcu_dereference_protected(vq->private_data,
614                                          lockdep_is_held(&vq->mutex));
615         vhost_net_disable_vq(n, vq);
616         rcu_assign_pointer(vq->private_data, NULL);
617         mutex_unlock(&vq->mutex);
618         return sock;
619 }
620
621 static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock,
622                            struct socket **rx_sock)
623 {
624         *tx_sock = vhost_net_stop_vq(n, n->vqs + VHOST_NET_VQ_TX);
625         *rx_sock = vhost_net_stop_vq(n, n->vqs + VHOST_NET_VQ_RX);
626 }
627
628 static void vhost_net_flush_vq(struct vhost_net *n, int index)
629 {
630         vhost_poll_flush(n->poll + index);
631         vhost_poll_flush(&n->dev.vqs[index].poll);
632 }
633
634 static void vhost_net_flush(struct vhost_net *n)
635 {
636         vhost_net_flush_vq(n, VHOST_NET_VQ_TX);
637         vhost_net_flush_vq(n, VHOST_NET_VQ_RX);
638         if (n->dev.vqs[VHOST_NET_VQ_TX].ubufs) {
639                 mutex_lock(&n->dev.vqs[VHOST_NET_VQ_TX].mutex);
640                 n->tx_flush = true;
641                 mutex_unlock(&n->dev.vqs[VHOST_NET_VQ_TX].mutex);
642                 /* Wait for all lower device DMAs done. */
643                 vhost_ubuf_put_and_wait(n->dev.vqs[VHOST_NET_VQ_TX].ubufs);
644                 mutex_lock(&n->dev.vqs[VHOST_NET_VQ_TX].mutex);
645                 n->tx_flush = false;
646                 kref_init(&n->dev.vqs[VHOST_NET_VQ_TX].ubufs->kref);
647                 mutex_unlock(&n->dev.vqs[VHOST_NET_VQ_TX].mutex);
648         }
649 }
650
651 static int vhost_net_release(struct inode *inode, struct file *f)
652 {
653         struct vhost_net *n = f->private_data;
654         struct socket *tx_sock;
655         struct socket *rx_sock;
656
657         vhost_net_stop(n, &tx_sock, &rx_sock);
658         vhost_net_flush(n);
659         vhost_dev_stop(&n->dev);
660         vhost_dev_cleanup(&n->dev, false);
661         if (tx_sock)
662                 fput(tx_sock->file);
663         if (rx_sock)
664                 fput(rx_sock->file);
665         /* We do an extra flush before freeing memory,
666          * since jobs can re-queue themselves. */
667         vhost_net_flush(n);
668         kfree(n);
669         return 0;
670 }
671
672 static struct socket *get_raw_socket(int fd)
673 {
674         struct {
675                 struct sockaddr_ll sa;
676                 char  buf[MAX_ADDR_LEN];
677         } uaddr;
678         int uaddr_len = sizeof uaddr, r;
679         struct socket *sock = sockfd_lookup(fd, &r);
680
681         if (!sock)
682                 return ERR_PTR(-ENOTSOCK);
683
684         /* Parameter checking */
685         if (sock->sk->sk_type != SOCK_RAW) {
686                 r = -ESOCKTNOSUPPORT;
687                 goto err;
688         }
689
690         r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa,
691                                &uaddr_len, 0);
692         if (r)
693                 goto err;
694
695         if (uaddr.sa.sll_family != AF_PACKET) {
696                 r = -EPFNOSUPPORT;
697                 goto err;
698         }
699         return sock;
700 err:
701         fput(sock->file);
702         return ERR_PTR(r);
703 }
704
705 static struct socket *get_tap_socket(int fd)
706 {
707         struct file *file = fget(fd);
708         struct socket *sock;
709
710         if (!file)
711                 return ERR_PTR(-EBADF);
712         sock = tun_get_socket(file);
713         if (!IS_ERR(sock))
714                 return sock;
715         sock = macvtap_get_socket(file);
716         if (IS_ERR(sock))
717                 fput(file);
718         return sock;
719 }
720
721 static struct socket *get_socket(int fd)
722 {
723         struct socket *sock;
724
725         /* special case to disable backend */
726         if (fd == -1)
727                 return NULL;
728         sock = get_raw_socket(fd);
729         if (!IS_ERR(sock))
730                 return sock;
731         sock = get_tap_socket(fd);
732         if (!IS_ERR(sock))
733                 return sock;
734         return ERR_PTR(-ENOTSOCK);
735 }
736
737 static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
738 {
739         struct socket *sock, *oldsock;
740         struct vhost_virtqueue *vq;
741         struct vhost_ubuf_ref *ubufs, *oldubufs = NULL;
742         int r;
743
744         mutex_lock(&n->dev.mutex);
745         r = vhost_dev_check_owner(&n->dev);
746         if (r)
747                 goto err;
748
749         if (index >= VHOST_NET_VQ_MAX) {
750                 r = -ENOBUFS;
751                 goto err;
752         }
753         vq = n->vqs + index;
754         mutex_lock(&vq->mutex);
755
756         /* Verify that ring has been setup correctly. */
757         if (!vhost_vq_access_ok(vq)) {
758                 r = -EFAULT;
759                 goto err_vq;
760         }
761         sock = get_socket(fd);
762         if (IS_ERR(sock)) {
763                 r = PTR_ERR(sock);
764                 goto err_vq;
765         }
766
767         /* start polling new socket */
768         oldsock = rcu_dereference_protected(vq->private_data,
769                                             lockdep_is_held(&vq->mutex));
770         if (sock != oldsock) {
771                 ubufs = vhost_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock));
772                 if (IS_ERR(ubufs)) {
773                         r = PTR_ERR(ubufs);
774                         goto err_ubufs;
775                 }
776
777                 vhost_net_disable_vq(n, vq);
778                 rcu_assign_pointer(vq->private_data, sock);
779                 r = vhost_init_used(vq);
780                 if (r)
781                         goto err_used;
782                 r = vhost_net_enable_vq(n, vq);
783                 if (r)
784                         goto err_used;
785
786                 oldubufs = vq->ubufs;
787                 vq->ubufs = ubufs;
788
789                 n->tx_packets = 0;
790                 n->tx_zcopy_err = 0;
791                 n->tx_flush = false;
792         }
793
794         mutex_unlock(&vq->mutex);
795
796         if (oldubufs) {
797                 vhost_ubuf_put_and_wait(oldubufs);
798                 mutex_lock(&vq->mutex);
799                 vhost_zerocopy_signal_used(n, vq);
800                 mutex_unlock(&vq->mutex);
801         }
802
803         if (oldsock) {
804                 vhost_net_flush_vq(n, index);
805                 fput(oldsock->file);
806         }
807
808         mutex_unlock(&n->dev.mutex);
809         return 0;
810
811 err_used:
812         rcu_assign_pointer(vq->private_data, oldsock);
813         vhost_net_enable_vq(n, vq);
814         if (ubufs)
815                 vhost_ubuf_put_and_wait(ubufs);
816 err_ubufs:
817         fput(sock->file);
818 err_vq:
819         mutex_unlock(&vq->mutex);
820 err:
821         mutex_unlock(&n->dev.mutex);
822         return r;
823 }
824
825 static long vhost_net_reset_owner(struct vhost_net *n)
826 {
827         struct socket *tx_sock = NULL;
828         struct socket *rx_sock = NULL;
829         long err;
830
831         mutex_lock(&n->dev.mutex);
832         err = vhost_dev_check_owner(&n->dev);
833         if (err)
834                 goto done;
835         vhost_net_stop(n, &tx_sock, &rx_sock);
836         vhost_net_flush(n);
837         err = vhost_dev_reset_owner(&n->dev);
838 done:
839         mutex_unlock(&n->dev.mutex);
840         if (tx_sock)
841                 fput(tx_sock->file);
842         if (rx_sock)
843                 fput(rx_sock->file);
844         return err;
845 }
846
847 static int vhost_net_set_features(struct vhost_net *n, u64 features)
848 {
849         size_t vhost_hlen, sock_hlen, hdr_len;
850         int i;
851
852         hdr_len = (features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ?
853                         sizeof(struct virtio_net_hdr_mrg_rxbuf) :
854                         sizeof(struct virtio_net_hdr);
855         if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) {
856                 /* vhost provides vnet_hdr */
857                 vhost_hlen = hdr_len;
858                 sock_hlen = 0;
859         } else {
860                 /* socket provides vnet_hdr */
861                 vhost_hlen = 0;
862                 sock_hlen = hdr_len;
863         }
864         mutex_lock(&n->dev.mutex);
865         if ((features & (1 << VHOST_F_LOG_ALL)) &&
866             !vhost_log_access_ok(&n->dev)) {
867                 mutex_unlock(&n->dev.mutex);
868                 return -EFAULT;
869         }
870         n->dev.acked_features = features;
871         smp_wmb();
872         for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
873                 mutex_lock(&n->vqs[i].mutex);
874                 n->vqs[i].vhost_hlen = vhost_hlen;
875                 n->vqs[i].sock_hlen = sock_hlen;
876                 mutex_unlock(&n->vqs[i].mutex);
877         }
878         vhost_net_flush(n);
879         mutex_unlock(&n->dev.mutex);
880         return 0;
881 }
882
883 static long vhost_net_ioctl(struct file *f, unsigned int ioctl,
884                             unsigned long arg)
885 {
886         struct vhost_net *n = f->private_data;
887         void __user *argp = (void __user *)arg;
888         u64 __user *featurep = argp;
889         struct vhost_vring_file backend;
890         u64 features;
891         int r;
892
893         switch (ioctl) {
894         case VHOST_NET_SET_BACKEND:
895                 if (copy_from_user(&backend, argp, sizeof backend))
896                         return -EFAULT;
897                 return vhost_net_set_backend(n, backend.index, backend.fd);
898         case VHOST_GET_FEATURES:
899                 features = VHOST_NET_FEATURES;
900                 if (copy_to_user(featurep, &features, sizeof features))
901                         return -EFAULT;
902                 return 0;
903         case VHOST_SET_FEATURES:
904                 if (copy_from_user(&features, featurep, sizeof features))
905                         return -EFAULT;
906                 if (features & ~VHOST_NET_FEATURES)
907                         return -EOPNOTSUPP;
908                 return vhost_net_set_features(n, features);
909         case VHOST_RESET_OWNER:
910                 return vhost_net_reset_owner(n);
911         default:
912                 mutex_lock(&n->dev.mutex);
913                 r = vhost_dev_ioctl(&n->dev, ioctl, argp);
914                 if (r == -ENOIOCTLCMD)
915                         r = vhost_vring_ioctl(&n->dev, ioctl, argp);
916                 else
917                         vhost_net_flush(n);
918                 mutex_unlock(&n->dev.mutex);
919                 return r;
920         }
921 }
922
923 #ifdef CONFIG_COMPAT
924 static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl,
925                                    unsigned long arg)
926 {
927         return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
928 }
929 #endif
930
931 static const struct file_operations vhost_net_fops = {
932         .owner          = THIS_MODULE,
933         .release        = vhost_net_release,
934         .unlocked_ioctl = vhost_net_ioctl,
935 #ifdef CONFIG_COMPAT
936         .compat_ioctl   = vhost_net_compat_ioctl,
937 #endif
938         .open           = vhost_net_open,
939         .llseek         = noop_llseek,
940 };
941
942 static struct miscdevice vhost_net_misc = {
943         .minor = VHOST_NET_MINOR,
944         .name = "vhost-net",
945         .fops = &vhost_net_fops,
946 };
947
948 static int vhost_net_init(void)
949 {
950         if (experimental_zcopytx)
951                 vhost_enable_zcopy(VHOST_NET_VQ_TX);
952         return misc_register(&vhost_net_misc);
953 }
954 module_init(vhost_net_init);
955
956 static void vhost_net_exit(void)
957 {
958         misc_deregister(&vhost_net_misc);
959 }
960 module_exit(vhost_net_exit);
961
962 MODULE_VERSION("0.0.1");
963 MODULE_LICENSE("GPL v2");
964 MODULE_AUTHOR("Michael S. Tsirkin");
965 MODULE_DESCRIPTION("Host kernel accelerator for virtio net");
966 MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR);
967 MODULE_ALIAS("devname:vhost-net");