1 /* Copyright (C) 2009 Red Hat, Inc.
2 * Author: Michael S. Tsirkin <mst@redhat.com>
4 * This work is licensed under the terms of the GNU GPL, version 2.
6 * virtio-net server in host kernel.
9 #include <linux/compat.h>
10 #include <linux/eventfd.h>
11 #include <linux/vhost.h>
12 #include <linux/virtio_net.h>
13 #include <linux/miscdevice.h>
14 #include <linux/module.h>
15 #include <linux/moduleparam.h>
16 #include <linux/mutex.h>
17 #include <linux/workqueue.h>
18 #include <linux/file.h>
19 #include <linux/slab.h>
20 #include <linux/sched/clock.h>
21 #include <linux/sched/signal.h>
22 #include <linux/vmalloc.h>
24 #include <linux/net.h>
25 #include <linux/if_packet.h>
26 #include <linux/if_arp.h>
27 #include <linux/if_tun.h>
28 #include <linux/if_macvlan.h>
29 #include <linux/if_tap.h>
30 #include <linux/if_vlan.h>
31 #include <linux/skb_array.h>
32 #include <linux/skbuff.h>
39 static int experimental_zcopytx = 1;
40 module_param(experimental_zcopytx, int, 0444);
41 MODULE_PARM_DESC(experimental_zcopytx, "Enable Zero Copy TX;"
42 " 1 -Enable; 0 - Disable");
44 /* Max number of bytes transferred before requeueing the job.
45 * Using this limit prevents one virtqueue from starving others. */
46 #define VHOST_NET_WEIGHT 0x80000
48 /* Max number of packets transferred before requeueing the job.
49 * Using this limit prevents one virtqueue from starving others with small
52 #define VHOST_NET_PKT_WEIGHT 256
54 /* MAX number of TX used buffers for outstanding zerocopy */
55 #define VHOST_MAX_PEND 128
56 #define VHOST_GOODCOPY_LEN 256
59 * For transmit, used buffer len is unused; we override it to track buffer
60 * status internally; used for zerocopy tx only.
62 /* Lower device DMA failed */
63 #define VHOST_DMA_FAILED_LEN ((__force __virtio32)3)
64 /* Lower device DMA done */
65 #define VHOST_DMA_DONE_LEN ((__force __virtio32)2)
66 /* Lower device DMA in progress */
67 #define VHOST_DMA_IN_PROGRESS ((__force __virtio32)1)
69 #define VHOST_DMA_CLEAR_LEN ((__force __virtio32)0)
71 #define VHOST_DMA_IS_DONE(len) ((__force u32)(len) >= (__force u32)VHOST_DMA_DONE_LEN)
74 VHOST_NET_FEATURES = VHOST_FEATURES |
75 (1ULL << VHOST_NET_F_VIRTIO_NET_HDR) |
76 (1ULL << VIRTIO_NET_F_MRG_RXBUF) |
77 (1ULL << VIRTIO_F_IOMMU_PLATFORM)
86 struct vhost_net_ubuf_ref {
87 /* refcount follows semantics similar to kref:
88 * 0: object is released
89 * 1: no outstanding ubufs
90 * >1: outstanding ubufs
93 wait_queue_head_t wait;
94 struct vhost_virtqueue *vq;
97 #define VHOST_RX_BATCH 64
98 struct vhost_net_buf {
104 struct vhost_net_virtqueue {
105 struct vhost_virtqueue vq;
108 /* vhost zerocopy support fields below: */
109 /* last used idx for outstanding DMA zerocopy buffers */
111 /* For TX, first used idx for DMA done zerocopy buffers
112 * For RX, number of batched heads
115 /* an array of userspace buffers info */
116 struct ubuf_info *ubuf_info;
117 /* Reference counting for outstanding ubufs.
118 * Protected by vq mutex. Writers must also take device mutex. */
119 struct vhost_net_ubuf_ref *ubufs;
120 struct ptr_ring *rx_ring;
121 struct vhost_net_buf rxq;
125 struct vhost_dev dev;
126 struct vhost_net_virtqueue vqs[VHOST_NET_VQ_MAX];
127 struct vhost_poll poll[VHOST_NET_VQ_MAX];
128 /* Number of TX recently submitted.
129 * Protected by tx vq lock. */
131 /* Number of times zerocopy TX recently failed.
132 * Protected by tx vq lock. */
133 unsigned tx_zcopy_err;
134 /* Flush in progress. Protected by tx vq lock. */
138 static unsigned vhost_net_zcopy_mask __read_mostly;
140 static void *vhost_net_buf_get_ptr(struct vhost_net_buf *rxq)
142 if (rxq->tail != rxq->head)
143 return rxq->queue[rxq->head];
148 static int vhost_net_buf_get_size(struct vhost_net_buf *rxq)
150 return rxq->tail - rxq->head;
153 static int vhost_net_buf_is_empty(struct vhost_net_buf *rxq)
155 return rxq->tail == rxq->head;
158 static void *vhost_net_buf_consume(struct vhost_net_buf *rxq)
160 void *ret = vhost_net_buf_get_ptr(rxq);
165 static int vhost_net_buf_produce(struct vhost_net_virtqueue *nvq)
167 struct vhost_net_buf *rxq = &nvq->rxq;
170 rxq->tail = ptr_ring_consume_batched(nvq->rx_ring, rxq->queue,
175 static void vhost_net_buf_unproduce(struct vhost_net_virtqueue *nvq)
177 struct vhost_net_buf *rxq = &nvq->rxq;
179 if (nvq->rx_ring && !vhost_net_buf_is_empty(rxq)) {
180 ptr_ring_unconsume(nvq->rx_ring, rxq->queue + rxq->head,
181 vhost_net_buf_get_size(rxq),
183 rxq->head = rxq->tail = 0;
187 static int vhost_net_buf_peek_len(void *ptr)
189 if (tun_is_xdp_frame(ptr)) {
190 struct xdp_frame *xdpf = tun_ptr_to_xdp(ptr);
195 return __skb_array_len_with_tag(ptr);
198 static int vhost_net_buf_peek(struct vhost_net_virtqueue *nvq)
200 struct vhost_net_buf *rxq = &nvq->rxq;
202 if (!vhost_net_buf_is_empty(rxq))
205 if (!vhost_net_buf_produce(nvq))
209 return vhost_net_buf_peek_len(vhost_net_buf_get_ptr(rxq));
212 static void vhost_net_buf_init(struct vhost_net_buf *rxq)
214 rxq->head = rxq->tail = 0;
217 static void vhost_net_enable_zcopy(int vq)
219 vhost_net_zcopy_mask |= 0x1 << vq;
222 static struct vhost_net_ubuf_ref *
223 vhost_net_ubuf_alloc(struct vhost_virtqueue *vq, bool zcopy)
225 struct vhost_net_ubuf_ref *ubufs;
226 /* No zero copy backend? Nothing to count. */
229 ubufs = kmalloc(sizeof(*ubufs), GFP_KERNEL);
231 return ERR_PTR(-ENOMEM);
232 atomic_set(&ubufs->refcount, 1);
233 init_waitqueue_head(&ubufs->wait);
238 static int vhost_net_ubuf_put(struct vhost_net_ubuf_ref *ubufs)
240 int r = atomic_sub_return(1, &ubufs->refcount);
242 wake_up(&ubufs->wait);
246 static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
248 vhost_net_ubuf_put(ubufs);
249 wait_event(ubufs->wait, !atomic_read(&ubufs->refcount));
252 static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs)
254 vhost_net_ubuf_put_and_wait(ubufs);
258 static void vhost_net_clear_ubuf_info(struct vhost_net *n)
262 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
263 kfree(n->vqs[i].ubuf_info);
264 n->vqs[i].ubuf_info = NULL;
268 static int vhost_net_set_ubuf_info(struct vhost_net *n)
273 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
274 zcopy = vhost_net_zcopy_mask & (0x1 << i);
277 n->vqs[i].ubuf_info = kmalloc(sizeof(*n->vqs[i].ubuf_info) *
278 UIO_MAXIOV, GFP_KERNEL);
279 if (!n->vqs[i].ubuf_info)
285 vhost_net_clear_ubuf_info(n);
289 static void vhost_net_vq_reset(struct vhost_net *n)
293 vhost_net_clear_ubuf_info(n);
295 for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
296 n->vqs[i].done_idx = 0;
297 n->vqs[i].upend_idx = 0;
298 n->vqs[i].ubufs = NULL;
299 n->vqs[i].vhost_hlen = 0;
300 n->vqs[i].sock_hlen = 0;
301 vhost_net_buf_init(&n->vqs[i].rxq);
306 static void vhost_net_tx_packet(struct vhost_net *net)
309 if (net->tx_packets < 1024)
312 net->tx_zcopy_err = 0;
315 static void vhost_net_tx_err(struct vhost_net *net)
320 static bool vhost_net_tx_select_zcopy(struct vhost_net *net)
322 /* TX flush waits for outstanding DMAs to be done.
323 * Don't start new DMAs.
325 return !net->tx_flush &&
326 net->tx_packets / 64 >= net->tx_zcopy_err;
329 static bool vhost_sock_zcopy(struct socket *sock)
331 return unlikely(experimental_zcopytx) &&
332 sock_flag(sock->sk, SOCK_ZEROCOPY);
335 /* In case of DMA done not in order in lower device driver for some reason.
336 * upend_idx is used to track end of used idx, done_idx is used to track head
337 * of used idx. Once lower device DMA done contiguously, we will signal KVM
340 static void vhost_zerocopy_signal_used(struct vhost_net *net,
341 struct vhost_virtqueue *vq)
343 struct vhost_net_virtqueue *nvq =
344 container_of(vq, struct vhost_net_virtqueue, vq);
348 for (i = nvq->done_idx; i != nvq->upend_idx; i = (i + 1) % UIO_MAXIOV) {
349 if (vq->heads[i].len == VHOST_DMA_FAILED_LEN)
350 vhost_net_tx_err(net);
351 if (VHOST_DMA_IS_DONE(vq->heads[i].len)) {
352 vq->heads[i].len = VHOST_DMA_CLEAR_LEN;
358 add = min(UIO_MAXIOV - nvq->done_idx, j);
359 vhost_add_used_and_signal_n(vq->dev, vq,
360 &vq->heads[nvq->done_idx], add);
361 nvq->done_idx = (nvq->done_idx + add) % UIO_MAXIOV;
366 static void vhost_zerocopy_callback(struct ubuf_info *ubuf, bool success)
368 struct vhost_net_ubuf_ref *ubufs = ubuf->ctx;
369 struct vhost_virtqueue *vq = ubufs->vq;
374 /* set len to mark this desc buffers done DMA */
375 vq->heads[ubuf->desc].len = success ?
376 VHOST_DMA_DONE_LEN : VHOST_DMA_FAILED_LEN;
377 cnt = vhost_net_ubuf_put(ubufs);
380 * Trigger polling thread if guest stopped submitting new buffers:
381 * in this case, the refcount after decrement will eventually reach 1.
382 * We also trigger polling periodically after each 16 packets
383 * (the value 16 here is more or less arbitrary, it's tuned to trigger
384 * less than 10% of times).
386 if (cnt <= 1 || !(cnt % 16))
387 vhost_poll_queue(&vq->poll);
389 rcu_read_unlock_bh();
392 static inline unsigned long busy_clock(void)
394 return local_clock() >> 10;
397 static bool vhost_can_busy_poll(struct vhost_dev *dev,
398 unsigned long endtime)
400 return likely(!need_resched()) &&
401 likely(!time_after(busy_clock(), endtime)) &&
402 likely(!signal_pending(current)) &&
403 !vhost_has_work(dev);
406 static void vhost_net_disable_vq(struct vhost_net *n,
407 struct vhost_virtqueue *vq)
409 struct vhost_net_virtqueue *nvq =
410 container_of(vq, struct vhost_net_virtqueue, vq);
411 struct vhost_poll *poll = n->poll + (nvq - n->vqs);
412 if (!vq->private_data)
414 vhost_poll_stop(poll);
417 static int vhost_net_enable_vq(struct vhost_net *n,
418 struct vhost_virtqueue *vq)
420 struct vhost_net_virtqueue *nvq =
421 container_of(vq, struct vhost_net_virtqueue, vq);
422 struct vhost_poll *poll = n->poll + (nvq - n->vqs);
425 sock = vq->private_data;
429 return vhost_poll_start(poll, sock->file);
432 static int vhost_net_tx_get_vq_desc(struct vhost_net *net,
433 struct vhost_virtqueue *vq,
434 struct iovec iov[], unsigned int iov_size,
435 unsigned int *out_num, unsigned int *in_num)
437 unsigned long uninitialized_var(endtime);
438 int r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
439 out_num, in_num, NULL, NULL);
441 if (r == vq->num && vq->busyloop_timeout) {
443 endtime = busy_clock() + vq->busyloop_timeout;
444 while (vhost_can_busy_poll(vq->dev, endtime) &&
445 vhost_vq_avail_empty(vq->dev, vq))
448 r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
449 out_num, in_num, NULL, NULL);
455 static bool vhost_exceeds_maxpend(struct vhost_net *net)
457 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
458 struct vhost_virtqueue *vq = &nvq->vq;
460 return (nvq->upend_idx + UIO_MAXIOV - nvq->done_idx) % UIO_MAXIOV >
461 min_t(unsigned int, VHOST_MAX_PEND, vq->num >> 2);
464 /* Expects to be always run from workqueue - which acts as
465 * read-size critical section for our kind of RCU. */
466 static void handle_tx(struct vhost_net *net)
468 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
469 struct vhost_virtqueue *vq = &nvq->vq;
472 struct msghdr msg = {
477 .msg_flags = MSG_DONTWAIT,
479 size_t len, total_len = 0;
483 struct vhost_net_ubuf_ref *uninitialized_var(ubufs);
484 bool zcopy, zcopy_used;
487 mutex_lock(&vq->mutex);
488 sock = vq->private_data;
492 if (!vq_iotlb_prefetch(vq))
495 vhost_disable_notify(&net->dev, vq);
496 vhost_net_disable_vq(net, vq);
498 hdr_size = nvq->vhost_hlen;
502 /* Release DMAs done buffers first */
504 vhost_zerocopy_signal_used(net, vq);
507 head = vhost_net_tx_get_vq_desc(net, vq, vq->iov,
510 /* On error, stop handling until the next kick. */
511 if (unlikely(head < 0))
513 /* Nothing new? Wait for eventfd to tell us they refilled. */
514 if (head == vq->num) {
515 if (unlikely(vhost_enable_notify(&net->dev, vq))) {
516 vhost_disable_notify(&net->dev, vq);
522 vq_err(vq, "Unexpected descriptor format for TX: "
523 "out %d, int %d\n", out, in);
526 /* Skip header. TODO: support TSO. */
527 len = iov_length(vq->iov, out);
528 iov_iter_init(&msg.msg_iter, WRITE, vq->iov, out, len);
529 iov_iter_advance(&msg.msg_iter, hdr_size);
531 if (!msg_data_left(&msg)) {
532 vq_err(vq, "Unexpected header len for TX: "
533 "%zd expected %zd\n",
537 len = msg_data_left(&msg);
539 zcopy_used = zcopy && len >= VHOST_GOODCOPY_LEN
540 && !vhost_exceeds_maxpend(net)
541 && vhost_net_tx_select_zcopy(net);
543 /* use msg_control to pass vhost zerocopy ubuf info to skb */
545 struct ubuf_info *ubuf;
546 ubuf = nvq->ubuf_info + nvq->upend_idx;
548 vq->heads[nvq->upend_idx].id = cpu_to_vhost32(vq, head);
549 vq->heads[nvq->upend_idx].len = VHOST_DMA_IN_PROGRESS;
550 ubuf->callback = vhost_zerocopy_callback;
551 ubuf->ctx = nvq->ubufs;
552 ubuf->desc = nvq->upend_idx;
553 refcount_set(&ubuf->refcnt, 1);
554 msg.msg_control = ubuf;
555 msg.msg_controllen = sizeof(ubuf);
557 atomic_inc(&ubufs->refcount);
558 nvq->upend_idx = (nvq->upend_idx + 1) % UIO_MAXIOV;
560 msg.msg_control = NULL;
565 if (total_len < VHOST_NET_WEIGHT &&
566 !vhost_vq_avail_empty(&net->dev, vq) &&
567 likely(!vhost_exceeds_maxpend(net))) {
568 msg.msg_flags |= MSG_MORE;
570 msg.msg_flags &= ~MSG_MORE;
573 /* TODO: Check specific error and bomb out unless ENOBUFS? */
574 err = sock->ops->sendmsg(sock, &msg, len);
575 if (unlikely(err < 0)) {
577 vhost_net_ubuf_put(ubufs);
578 nvq->upend_idx = ((unsigned)nvq->upend_idx - 1)
581 vhost_discard_vq_desc(vq, 1);
582 vhost_net_enable_vq(net, vq);
586 pr_debug("Truncated TX packet: "
587 " len %d != %zd\n", err, len);
589 vhost_add_used_and_signal(&net->dev, vq, head, 0);
591 vhost_zerocopy_signal_used(net, vq);
592 vhost_net_tx_packet(net);
593 if (unlikely(total_len >= VHOST_NET_WEIGHT) ||
594 unlikely(++sent_pkts >= VHOST_NET_PKT_WEIGHT)) {
595 vhost_poll_queue(&vq->poll);
600 mutex_unlock(&vq->mutex);
603 static int peek_head_len(struct vhost_net_virtqueue *rvq, struct sock *sk)
605 struct sk_buff *head;
610 return vhost_net_buf_peek(rvq);
612 spin_lock_irqsave(&sk->sk_receive_queue.lock, flags);
613 head = skb_peek(&sk->sk_receive_queue);
616 if (skb_vlan_tag_present(head))
620 spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags);
624 static int sk_has_rx_data(struct sock *sk)
626 struct socket *sock = sk->sk_socket;
628 if (sock->ops->peek_len)
629 return sock->ops->peek_len(sock);
631 return skb_queue_empty(&sk->sk_receive_queue);
634 static void vhost_rx_signal_used(struct vhost_net_virtqueue *nvq)
636 struct vhost_virtqueue *vq = &nvq->vq;
637 struct vhost_dev *dev = vq->dev;
642 vhost_add_used_and_signal_n(dev, vq, vq->heads, nvq->done_idx);
646 static int vhost_net_rx_peek_head_len(struct vhost_net *net, struct sock *sk)
648 struct vhost_net_virtqueue *rvq = &net->vqs[VHOST_NET_VQ_RX];
649 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
650 struct vhost_virtqueue *vq = &nvq->vq;
651 unsigned long uninitialized_var(endtime);
652 int len = peek_head_len(rvq, sk);
654 if (!len && vq->busyloop_timeout) {
655 /* Flush batched heads first */
656 vhost_rx_signal_used(rvq);
657 /* Both tx vq and rx socket were polled here */
658 mutex_lock_nested(&vq->mutex, 1);
659 vhost_disable_notify(&net->dev, vq);
662 endtime = busy_clock() + vq->busyloop_timeout;
664 while (vhost_can_busy_poll(&net->dev, endtime) &&
665 !sk_has_rx_data(sk) &&
666 vhost_vq_avail_empty(&net->dev, vq))
671 if (!vhost_vq_avail_empty(&net->dev, vq))
672 vhost_poll_queue(&vq->poll);
673 else if (unlikely(vhost_enable_notify(&net->dev, vq))) {
674 vhost_disable_notify(&net->dev, vq);
675 vhost_poll_queue(&vq->poll);
678 mutex_unlock(&vq->mutex);
680 len = peek_head_len(rvq, sk);
686 /* This is a multi-buffer version of vhost_get_desc, that works if
687 * vq has read descriptors only.
688 * @vq - the relevant virtqueue
689 * @datalen - data length we'll be reading
690 * @iovcount - returned count of io vectors we fill
692 * @log_num - log offset
693 * @quota - headcount quota, 1 for big buffer
694 * returns number of buffer heads allocated, negative on error
696 static int get_rx_bufs(struct vhost_virtqueue *vq,
697 struct vring_used_elem *heads,
700 struct vhost_log *log,
704 unsigned int out, in;
709 /* len is always initialized before use since we are always called with
712 u32 uninitialized_var(len);
714 while (datalen > 0 && headcount < quota) {
715 if (unlikely(seg >= UIO_MAXIOV)) {
719 r = vhost_get_vq_desc(vq, vq->iov + seg,
720 ARRAY_SIZE(vq->iov) - seg, &out,
730 if (unlikely(out || in <= 0)) {
731 vq_err(vq, "unexpected descriptor format for RX: "
732 "out %d, in %d\n", out, in);
740 heads[headcount].id = cpu_to_vhost32(vq, d);
741 len = iov_length(vq->iov + seg, in);
742 heads[headcount].len = cpu_to_vhost32(vq, len);
747 heads[headcount - 1].len = cpu_to_vhost32(vq, len + datalen);
753 if (unlikely(datalen > 0)) {
759 vhost_discard_vq_desc(vq, headcount);
763 /* Expects to be always run from workqueue - which acts as
764 * read-size critical section for our kind of RCU. */
765 static void handle_rx(struct vhost_net *net)
767 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
768 struct vhost_virtqueue *vq = &nvq->vq;
769 unsigned uninitialized_var(in), log;
770 struct vhost_log *vq_log;
771 struct msghdr msg = {
774 .msg_control = NULL, /* FIXME: get and handle RX aux data. */
776 .msg_flags = MSG_DONTWAIT,
778 struct virtio_net_hdr hdr = {
780 .gso_type = VIRTIO_NET_HDR_GSO_NONE
782 size_t total_len = 0;
785 size_t vhost_hlen, sock_hlen;
786 size_t vhost_len, sock_len;
788 struct iov_iter fixup;
789 __virtio16 num_buffers;
792 mutex_lock_nested(&vq->mutex, 0);
793 sock = vq->private_data;
797 if (!vq_iotlb_prefetch(vq))
800 vhost_disable_notify(&net->dev, vq);
801 vhost_net_disable_vq(net, vq);
803 vhost_hlen = nvq->vhost_hlen;
804 sock_hlen = nvq->sock_hlen;
806 vq_log = unlikely(vhost_has_feature(vq, VHOST_F_LOG_ALL)) ?
808 mergeable = vhost_has_feature(vq, VIRTIO_NET_F_MRG_RXBUF);
810 while ((sock_len = vhost_net_rx_peek_head_len(net, sock->sk))) {
811 sock_len += sock_hlen;
812 vhost_len = sock_len + vhost_hlen;
813 headcount = get_rx_bufs(vq, vq->heads + nvq->done_idx,
814 vhost_len, &in, vq_log, &log,
815 likely(mergeable) ? UIO_MAXIOV : 1);
816 /* On error, stop handling until the next kick. */
817 if (unlikely(headcount < 0))
819 /* OK, now we need to know about added descriptors. */
821 if (unlikely(vhost_enable_notify(&net->dev, vq))) {
822 /* They have slipped one in as we were
823 * doing that: check again. */
824 vhost_disable_notify(&net->dev, vq);
827 /* Nothing new? Wait for eventfd to tell us
832 msg.msg_control = vhost_net_buf_consume(&nvq->rxq);
833 /* On overrun, truncate and discard */
834 if (unlikely(headcount > UIO_MAXIOV)) {
835 iov_iter_init(&msg.msg_iter, READ, vq->iov, 1, 1);
836 err = sock->ops->recvmsg(sock, &msg,
837 1, MSG_DONTWAIT | MSG_TRUNC);
838 pr_debug("Discarded rx packet: len %zd\n", sock_len);
841 /* We don't need to be notified again. */
842 iov_iter_init(&msg.msg_iter, READ, vq->iov, in, vhost_len);
843 fixup = msg.msg_iter;
844 if (unlikely((vhost_hlen))) {
845 /* We will supply the header ourselves
848 iov_iter_advance(&msg.msg_iter, vhost_hlen);
850 err = sock->ops->recvmsg(sock, &msg,
851 sock_len, MSG_DONTWAIT | MSG_TRUNC);
852 /* Userspace might have consumed the packet meanwhile:
853 * it's not supposed to do this usually, but might be hard
854 * to prevent. Discard data we got (if any) and keep going. */
855 if (unlikely(err != sock_len)) {
856 pr_debug("Discarded rx packet: "
857 " len %d, expected %zd\n", err, sock_len);
858 vhost_discard_vq_desc(vq, headcount);
861 /* Supply virtio_net_hdr if VHOST_NET_F_VIRTIO_NET_HDR */
862 if (unlikely(vhost_hlen)) {
863 if (copy_to_iter(&hdr, sizeof(hdr),
864 &fixup) != sizeof(hdr)) {
865 vq_err(vq, "Unable to write vnet_hdr "
866 "at addr %p\n", vq->iov->iov_base);
870 /* Header came from socket; we'll need to patch
871 * ->num_buffers over if VIRTIO_NET_F_MRG_RXBUF
873 iov_iter_advance(&fixup, sizeof(hdr));
875 /* TODO: Should check and handle checksum. */
877 num_buffers = cpu_to_vhost16(vq, headcount);
878 if (likely(mergeable) &&
879 copy_to_iter(&num_buffers, sizeof num_buffers,
880 &fixup) != sizeof num_buffers) {
881 vq_err(vq, "Failed num_buffers write");
882 vhost_discard_vq_desc(vq, headcount);
885 nvq->done_idx += headcount;
886 if (nvq->done_idx > VHOST_RX_BATCH)
887 vhost_rx_signal_used(nvq);
888 if (unlikely(vq_log))
889 vhost_log_write(vq, vq_log, log, vhost_len);
890 total_len += vhost_len;
891 if (unlikely(total_len >= VHOST_NET_WEIGHT) ||
892 unlikely(++recv_pkts >= VHOST_NET_PKT_WEIGHT)) {
893 vhost_poll_queue(&vq->poll);
897 vhost_net_enable_vq(net, vq);
899 vhost_rx_signal_used(nvq);
900 mutex_unlock(&vq->mutex);
903 static void handle_tx_kick(struct vhost_work *work)
905 struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
907 struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
912 static void handle_rx_kick(struct vhost_work *work)
914 struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
916 struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
921 static void handle_tx_net(struct vhost_work *work)
923 struct vhost_net *net = container_of(work, struct vhost_net,
924 poll[VHOST_NET_VQ_TX].work);
928 static void handle_rx_net(struct vhost_work *work)
930 struct vhost_net *net = container_of(work, struct vhost_net,
931 poll[VHOST_NET_VQ_RX].work);
935 static int vhost_net_open(struct inode *inode, struct file *f)
938 struct vhost_dev *dev;
939 struct vhost_virtqueue **vqs;
943 n = kvmalloc(sizeof *n, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
946 vqs = kmalloc(VHOST_NET_VQ_MAX * sizeof(*vqs), GFP_KERNEL);
952 queue = kmalloc_array(VHOST_RX_BATCH, sizeof(void *),
959 n->vqs[VHOST_NET_VQ_RX].rxq.queue = queue;
962 vqs[VHOST_NET_VQ_TX] = &n->vqs[VHOST_NET_VQ_TX].vq;
963 vqs[VHOST_NET_VQ_RX] = &n->vqs[VHOST_NET_VQ_RX].vq;
964 n->vqs[VHOST_NET_VQ_TX].vq.handle_kick = handle_tx_kick;
965 n->vqs[VHOST_NET_VQ_RX].vq.handle_kick = handle_rx_kick;
966 for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
967 n->vqs[i].ubufs = NULL;
968 n->vqs[i].ubuf_info = NULL;
969 n->vqs[i].upend_idx = 0;
970 n->vqs[i].done_idx = 0;
971 n->vqs[i].vhost_hlen = 0;
972 n->vqs[i].sock_hlen = 0;
973 n->vqs[i].rx_ring = NULL;
974 vhost_net_buf_init(&n->vqs[i].rxq);
976 vhost_dev_init(dev, vqs, VHOST_NET_VQ_MAX);
978 vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, EPOLLOUT, dev);
979 vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, EPOLLIN, dev);
986 static struct socket *vhost_net_stop_vq(struct vhost_net *n,
987 struct vhost_virtqueue *vq)
990 struct vhost_net_virtqueue *nvq =
991 container_of(vq, struct vhost_net_virtqueue, vq);
993 mutex_lock(&vq->mutex);
994 sock = vq->private_data;
995 vhost_net_disable_vq(n, vq);
996 vq->private_data = NULL;
997 vhost_net_buf_unproduce(nvq);
999 mutex_unlock(&vq->mutex);
1003 static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock,
1004 struct socket **rx_sock)
1006 *tx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_TX].vq);
1007 *rx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_RX].vq);
1010 static void vhost_net_flush_vq(struct vhost_net *n, int index)
1012 vhost_poll_flush(n->poll + index);
1013 vhost_poll_flush(&n->vqs[index].vq.poll);
1016 static void vhost_net_flush(struct vhost_net *n)
1018 vhost_net_flush_vq(n, VHOST_NET_VQ_TX);
1019 vhost_net_flush_vq(n, VHOST_NET_VQ_RX);
1020 if (n->vqs[VHOST_NET_VQ_TX].ubufs) {
1021 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1023 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1024 /* Wait for all lower device DMAs done. */
1025 vhost_net_ubuf_put_and_wait(n->vqs[VHOST_NET_VQ_TX].ubufs);
1026 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1027 n->tx_flush = false;
1028 atomic_set(&n->vqs[VHOST_NET_VQ_TX].ubufs->refcount, 1);
1029 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1033 static int vhost_net_release(struct inode *inode, struct file *f)
1035 struct vhost_net *n = f->private_data;
1036 struct socket *tx_sock;
1037 struct socket *rx_sock;
1039 vhost_net_stop(n, &tx_sock, &rx_sock);
1041 vhost_dev_stop(&n->dev);
1042 vhost_dev_cleanup(&n->dev);
1043 vhost_net_vq_reset(n);
1045 sockfd_put(tx_sock);
1047 sockfd_put(rx_sock);
1048 /* Make sure no callbacks are outstanding */
1049 synchronize_rcu_bh();
1050 /* We do an extra flush before freeing memory,
1051 * since jobs can re-queue themselves. */
1053 kfree(n->vqs[VHOST_NET_VQ_RX].rxq.queue);
1059 static struct socket *get_raw_socket(int fd)
1062 struct sockaddr_ll sa;
1063 char buf[MAX_ADDR_LEN];
1066 struct socket *sock = sockfd_lookup(fd, &r);
1069 return ERR_PTR(-ENOTSOCK);
1071 /* Parameter checking */
1072 if (sock->sk->sk_type != SOCK_RAW) {
1073 r = -ESOCKTNOSUPPORT;
1077 r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa, 0);
1081 if (uaddr.sa.sll_family != AF_PACKET) {
1091 static struct ptr_ring *get_tap_ptr_ring(int fd)
1093 struct ptr_ring *ring;
1094 struct file *file = fget(fd);
1098 ring = tun_get_tx_ring(file);
1101 ring = tap_get_ptr_ring(file);
1110 static struct socket *get_tap_socket(int fd)
1112 struct file *file = fget(fd);
1113 struct socket *sock;
1116 return ERR_PTR(-EBADF);
1117 sock = tun_get_socket(file);
1120 sock = tap_get_socket(file);
1126 static struct socket *get_socket(int fd)
1128 struct socket *sock;
1130 /* special case to disable backend */
1133 sock = get_raw_socket(fd);
1136 sock = get_tap_socket(fd);
1139 return ERR_PTR(-ENOTSOCK);
1142 static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
1144 struct socket *sock, *oldsock;
1145 struct vhost_virtqueue *vq;
1146 struct vhost_net_virtqueue *nvq;
1147 struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL;
1150 mutex_lock(&n->dev.mutex);
1151 r = vhost_dev_check_owner(&n->dev);
1155 if (index >= VHOST_NET_VQ_MAX) {
1159 vq = &n->vqs[index].vq;
1160 nvq = &n->vqs[index];
1161 mutex_lock(&vq->mutex);
1163 /* Verify that ring has been setup correctly. */
1164 if (!vhost_vq_access_ok(vq)) {
1168 sock = get_socket(fd);
1174 /* start polling new socket */
1175 oldsock = vq->private_data;
1176 if (sock != oldsock) {
1177 ubufs = vhost_net_ubuf_alloc(vq,
1178 sock && vhost_sock_zcopy(sock));
1179 if (IS_ERR(ubufs)) {
1184 vhost_net_disable_vq(n, vq);
1185 vq->private_data = sock;
1186 vhost_net_buf_unproduce(nvq);
1187 r = vhost_vq_init_access(vq);
1190 r = vhost_net_enable_vq(n, vq);
1193 if (index == VHOST_NET_VQ_RX)
1194 nvq->rx_ring = get_tap_ptr_ring(fd);
1196 oldubufs = nvq->ubufs;
1200 n->tx_zcopy_err = 0;
1201 n->tx_flush = false;
1204 mutex_unlock(&vq->mutex);
1207 vhost_net_ubuf_put_wait_and_free(oldubufs);
1208 mutex_lock(&vq->mutex);
1209 vhost_zerocopy_signal_used(n, vq);
1210 mutex_unlock(&vq->mutex);
1214 vhost_net_flush_vq(n, index);
1215 sockfd_put(oldsock);
1218 mutex_unlock(&n->dev.mutex);
1222 vq->private_data = oldsock;
1223 vhost_net_enable_vq(n, vq);
1225 vhost_net_ubuf_put_wait_and_free(ubufs);
1229 mutex_unlock(&vq->mutex);
1231 mutex_unlock(&n->dev.mutex);
1235 static long vhost_net_reset_owner(struct vhost_net *n)
1237 struct socket *tx_sock = NULL;
1238 struct socket *rx_sock = NULL;
1240 struct vhost_umem *umem;
1242 mutex_lock(&n->dev.mutex);
1243 err = vhost_dev_check_owner(&n->dev);
1246 umem = vhost_dev_reset_owner_prepare();
1251 vhost_net_stop(n, &tx_sock, &rx_sock);
1253 vhost_dev_stop(&n->dev);
1254 vhost_dev_reset_owner(&n->dev, umem);
1255 vhost_net_vq_reset(n);
1257 mutex_unlock(&n->dev.mutex);
1259 sockfd_put(tx_sock);
1261 sockfd_put(rx_sock);
1265 static int vhost_net_set_features(struct vhost_net *n, u64 features)
1267 size_t vhost_hlen, sock_hlen, hdr_len;
1270 hdr_len = (features & ((1ULL << VIRTIO_NET_F_MRG_RXBUF) |
1271 (1ULL << VIRTIO_F_VERSION_1))) ?
1272 sizeof(struct virtio_net_hdr_mrg_rxbuf) :
1273 sizeof(struct virtio_net_hdr);
1274 if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) {
1275 /* vhost provides vnet_hdr */
1276 vhost_hlen = hdr_len;
1279 /* socket provides vnet_hdr */
1281 sock_hlen = hdr_len;
1283 mutex_lock(&n->dev.mutex);
1284 if ((features & (1 << VHOST_F_LOG_ALL)) &&
1285 !vhost_log_access_ok(&n->dev))
1288 if ((features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))) {
1289 if (vhost_init_device_iotlb(&n->dev, true))
1293 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
1294 mutex_lock(&n->vqs[i].vq.mutex);
1295 n->vqs[i].vq.acked_features = features;
1296 n->vqs[i].vhost_hlen = vhost_hlen;
1297 n->vqs[i].sock_hlen = sock_hlen;
1298 mutex_unlock(&n->vqs[i].vq.mutex);
1300 mutex_unlock(&n->dev.mutex);
1304 mutex_unlock(&n->dev.mutex);
1308 static long vhost_net_set_owner(struct vhost_net *n)
1312 mutex_lock(&n->dev.mutex);
1313 if (vhost_dev_has_owner(&n->dev)) {
1317 r = vhost_net_set_ubuf_info(n);
1320 r = vhost_dev_set_owner(&n->dev);
1322 vhost_net_clear_ubuf_info(n);
1325 mutex_unlock(&n->dev.mutex);
1329 static long vhost_net_ioctl(struct file *f, unsigned int ioctl,
1332 struct vhost_net *n = f->private_data;
1333 void __user *argp = (void __user *)arg;
1334 u64 __user *featurep = argp;
1335 struct vhost_vring_file backend;
1340 case VHOST_NET_SET_BACKEND:
1341 if (copy_from_user(&backend, argp, sizeof backend))
1343 return vhost_net_set_backend(n, backend.index, backend.fd);
1344 case VHOST_GET_FEATURES:
1345 features = VHOST_NET_FEATURES;
1346 if (copy_to_user(featurep, &features, sizeof features))
1349 case VHOST_SET_FEATURES:
1350 if (copy_from_user(&features, featurep, sizeof features))
1352 if (features & ~VHOST_NET_FEATURES)
1354 return vhost_net_set_features(n, features);
1355 case VHOST_RESET_OWNER:
1356 return vhost_net_reset_owner(n);
1357 case VHOST_SET_OWNER:
1358 return vhost_net_set_owner(n);
1360 mutex_lock(&n->dev.mutex);
1361 r = vhost_dev_ioctl(&n->dev, ioctl, argp);
1362 if (r == -ENOIOCTLCMD)
1363 r = vhost_vring_ioctl(&n->dev, ioctl, argp);
1366 mutex_unlock(&n->dev.mutex);
1371 #ifdef CONFIG_COMPAT
1372 static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl,
1375 return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
1379 static ssize_t vhost_net_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
1381 struct file *file = iocb->ki_filp;
1382 struct vhost_net *n = file->private_data;
1383 struct vhost_dev *dev = &n->dev;
1384 int noblock = file->f_flags & O_NONBLOCK;
1386 return vhost_chr_read_iter(dev, to, noblock);
1389 static ssize_t vhost_net_chr_write_iter(struct kiocb *iocb,
1390 struct iov_iter *from)
1392 struct file *file = iocb->ki_filp;
1393 struct vhost_net *n = file->private_data;
1394 struct vhost_dev *dev = &n->dev;
1396 return vhost_chr_write_iter(dev, from);
1399 static __poll_t vhost_net_chr_poll(struct file *file, poll_table *wait)
1401 struct vhost_net *n = file->private_data;
1402 struct vhost_dev *dev = &n->dev;
1404 return vhost_chr_poll(file, dev, wait);
1407 static const struct file_operations vhost_net_fops = {
1408 .owner = THIS_MODULE,
1409 .release = vhost_net_release,
1410 .read_iter = vhost_net_chr_read_iter,
1411 .write_iter = vhost_net_chr_write_iter,
1412 .poll = vhost_net_chr_poll,
1413 .unlocked_ioctl = vhost_net_ioctl,
1414 #ifdef CONFIG_COMPAT
1415 .compat_ioctl = vhost_net_compat_ioctl,
1417 .open = vhost_net_open,
1418 .llseek = noop_llseek,
1421 static struct miscdevice vhost_net_misc = {
1422 .minor = VHOST_NET_MINOR,
1423 .name = "vhost-net",
1424 .fops = &vhost_net_fops,
1427 static int vhost_net_init(void)
1429 if (experimental_zcopytx)
1430 vhost_net_enable_zcopy(VHOST_NET_VQ_TX);
1431 return misc_register(&vhost_net_misc);
1433 module_init(vhost_net_init);
1435 static void vhost_net_exit(void)
1437 misc_deregister(&vhost_net_misc);
1439 module_exit(vhost_net_exit);
1441 MODULE_VERSION("0.0.1");
1442 MODULE_LICENSE("GPL v2");
1443 MODULE_AUTHOR("Michael S. Tsirkin");
1444 MODULE_DESCRIPTION("Host kernel accelerator for virtio net");
1445 MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR);
1446 MODULE_ALIAS("devname:vhost-net");