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_NET_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 =
278 kmalloc_array(UIO_MAXIOV,
279 sizeof(*n->vqs[i].ubuf_info),
281 if (!n->vqs[i].ubuf_info)
287 vhost_net_clear_ubuf_info(n);
291 static void vhost_net_vq_reset(struct vhost_net *n)
295 vhost_net_clear_ubuf_info(n);
297 for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
298 n->vqs[i].done_idx = 0;
299 n->vqs[i].upend_idx = 0;
300 n->vqs[i].ubufs = NULL;
301 n->vqs[i].vhost_hlen = 0;
302 n->vqs[i].sock_hlen = 0;
303 vhost_net_buf_init(&n->vqs[i].rxq);
308 static void vhost_net_tx_packet(struct vhost_net *net)
311 if (net->tx_packets < 1024)
314 net->tx_zcopy_err = 0;
317 static void vhost_net_tx_err(struct vhost_net *net)
322 static bool vhost_net_tx_select_zcopy(struct vhost_net *net)
324 /* TX flush waits for outstanding DMAs to be done.
325 * Don't start new DMAs.
327 return !net->tx_flush &&
328 net->tx_packets / 64 >= net->tx_zcopy_err;
331 static bool vhost_sock_zcopy(struct socket *sock)
333 return unlikely(experimental_zcopytx) &&
334 sock_flag(sock->sk, SOCK_ZEROCOPY);
337 /* In case of DMA done not in order in lower device driver for some reason.
338 * upend_idx is used to track end of used idx, done_idx is used to track head
339 * of used idx. Once lower device DMA done contiguously, we will signal KVM
342 static void vhost_zerocopy_signal_used(struct vhost_net *net,
343 struct vhost_virtqueue *vq)
345 struct vhost_net_virtqueue *nvq =
346 container_of(vq, struct vhost_net_virtqueue, vq);
350 for (i = nvq->done_idx; i != nvq->upend_idx; i = (i + 1) % UIO_MAXIOV) {
351 if (vq->heads[i].len == VHOST_DMA_FAILED_LEN)
352 vhost_net_tx_err(net);
353 if (VHOST_DMA_IS_DONE(vq->heads[i].len)) {
354 vq->heads[i].len = VHOST_DMA_CLEAR_LEN;
360 add = min(UIO_MAXIOV - nvq->done_idx, j);
361 vhost_add_used_and_signal_n(vq->dev, vq,
362 &vq->heads[nvq->done_idx], add);
363 nvq->done_idx = (nvq->done_idx + add) % UIO_MAXIOV;
368 static void vhost_zerocopy_callback(struct ubuf_info *ubuf, bool success)
370 struct vhost_net_ubuf_ref *ubufs = ubuf->ctx;
371 struct vhost_virtqueue *vq = ubufs->vq;
376 /* set len to mark this desc buffers done DMA */
377 vq->heads[ubuf->desc].len = success ?
378 VHOST_DMA_DONE_LEN : VHOST_DMA_FAILED_LEN;
379 cnt = vhost_net_ubuf_put(ubufs);
382 * Trigger polling thread if guest stopped submitting new buffers:
383 * in this case, the refcount after decrement will eventually reach 1.
384 * We also trigger polling periodically after each 16 packets
385 * (the value 16 here is more or less arbitrary, it's tuned to trigger
386 * less than 10% of times).
388 if (cnt <= 1 || !(cnt % 16))
389 vhost_poll_queue(&vq->poll);
391 rcu_read_unlock_bh();
394 static inline unsigned long busy_clock(void)
396 return local_clock() >> 10;
399 static bool vhost_can_busy_poll(unsigned long endtime)
401 return likely(!need_resched() && !time_after(busy_clock(), endtime) &&
402 !signal_pending(current));
405 static void vhost_net_disable_vq(struct vhost_net *n,
406 struct vhost_virtqueue *vq)
408 struct vhost_net_virtqueue *nvq =
409 container_of(vq, struct vhost_net_virtqueue, vq);
410 struct vhost_poll *poll = n->poll + (nvq - n->vqs);
411 if (!vq->private_data)
413 vhost_poll_stop(poll);
416 static int vhost_net_enable_vq(struct vhost_net *n,
417 struct vhost_virtqueue *vq)
419 struct vhost_net_virtqueue *nvq =
420 container_of(vq, struct vhost_net_virtqueue, vq);
421 struct vhost_poll *poll = n->poll + (nvq - n->vqs);
424 sock = vq->private_data;
428 return vhost_poll_start(poll, sock->file);
431 static void vhost_net_signal_used(struct vhost_net_virtqueue *nvq)
433 struct vhost_virtqueue *vq = &nvq->vq;
434 struct vhost_dev *dev = vq->dev;
439 vhost_add_used_and_signal_n(dev, vq, vq->heads, nvq->done_idx);
443 static int vhost_net_tx_get_vq_desc(struct vhost_net *net,
444 struct vhost_net_virtqueue *nvq,
445 unsigned int *out_num, unsigned int *in_num,
448 struct vhost_virtqueue *vq = &nvq->vq;
449 unsigned long uninitialized_var(endtime);
450 int r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
451 out_num, in_num, NULL, NULL);
453 if (r == vq->num && vq->busyloop_timeout) {
454 if (!vhost_sock_zcopy(vq->private_data))
455 vhost_net_signal_used(nvq);
457 endtime = busy_clock() + vq->busyloop_timeout;
458 while (vhost_can_busy_poll(endtime)) {
459 if (vhost_has_work(vq->dev)) {
460 *busyloop_intr = true;
463 if (!vhost_vq_avail_empty(vq->dev, vq))
468 r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
469 out_num, in_num, NULL, NULL);
475 static bool vhost_exceeds_maxpend(struct vhost_net *net)
477 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
478 struct vhost_virtqueue *vq = &nvq->vq;
480 return (nvq->upend_idx + UIO_MAXIOV - nvq->done_idx) % UIO_MAXIOV >
481 min_t(unsigned int, VHOST_MAX_PEND, vq->num >> 2);
484 static size_t init_iov_iter(struct vhost_virtqueue *vq, struct iov_iter *iter,
485 size_t hdr_size, int out)
487 /* Skip header. TODO: support TSO. */
488 size_t len = iov_length(vq->iov, out);
490 iov_iter_init(iter, WRITE, vq->iov, out, len);
491 iov_iter_advance(iter, hdr_size);
493 return iov_iter_count(iter);
496 static bool vhost_exceeds_weight(int pkts, int total_len)
498 return total_len >= VHOST_NET_WEIGHT ||
499 pkts >= VHOST_NET_PKT_WEIGHT;
502 static int get_tx_bufs(struct vhost_net *net,
503 struct vhost_net_virtqueue *nvq,
505 unsigned int *out, unsigned int *in,
506 size_t *len, bool *busyloop_intr)
508 struct vhost_virtqueue *vq = &nvq->vq;
511 ret = vhost_net_tx_get_vq_desc(net, nvq, out, in, busyloop_intr);
513 if (ret < 0 || ret == vq->num)
517 vq_err(vq, "Unexpected descriptor format for TX: out %d, int %d\n",
523 *len = init_iov_iter(vq, &msg->msg_iter, nvq->vhost_hlen, *out);
525 vq_err(vq, "Unexpected header len for TX: %zd expected %zd\n",
526 *len, nvq->vhost_hlen);
533 static bool tx_can_batch(struct vhost_virtqueue *vq, size_t total_len)
535 return total_len < VHOST_NET_WEIGHT &&
536 !vhost_vq_avail_empty(vq->dev, vq);
539 static void handle_tx_copy(struct vhost_net *net, struct socket *sock)
541 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
542 struct vhost_virtqueue *vq = &nvq->vq;
545 struct msghdr msg = {
550 .msg_flags = MSG_DONTWAIT,
552 size_t len, total_len = 0;
557 bool busyloop_intr = false;
559 head = get_tx_bufs(net, nvq, &msg, &out, &in, &len,
561 /* On error, stop handling until the next kick. */
562 if (unlikely(head < 0))
564 /* Nothing new? Wait for eventfd to tell us they refilled. */
565 if (head == vq->num) {
566 if (unlikely(busyloop_intr)) {
567 vhost_poll_queue(&vq->poll);
568 } else if (unlikely(vhost_enable_notify(&net->dev,
570 vhost_disable_notify(&net->dev, vq);
576 vq->heads[nvq->done_idx].id = cpu_to_vhost32(vq, head);
577 vq->heads[nvq->done_idx].len = 0;
580 if (tx_can_batch(vq, total_len))
581 msg.msg_flags |= MSG_MORE;
583 msg.msg_flags &= ~MSG_MORE;
585 /* TODO: Check specific error and bomb out unless ENOBUFS? */
586 err = sock->ops->sendmsg(sock, &msg, len);
587 if (unlikely(err < 0)) {
588 vhost_discard_vq_desc(vq, 1);
589 vhost_net_enable_vq(net, vq);
593 pr_debug("Truncated TX packet: len %d != %zd\n",
595 if (++nvq->done_idx >= VHOST_NET_BATCH)
596 vhost_net_signal_used(nvq);
597 if (vhost_exceeds_weight(++sent_pkts, total_len)) {
598 vhost_poll_queue(&vq->poll);
603 vhost_net_signal_used(nvq);
606 static void handle_tx_zerocopy(struct vhost_net *net, struct socket *sock)
608 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
609 struct vhost_virtqueue *vq = &nvq->vq;
612 struct msghdr msg = {
617 .msg_flags = MSG_DONTWAIT,
619 size_t len, total_len = 0;
621 struct vhost_net_ubuf_ref *uninitialized_var(ubufs);
628 /* Release DMAs done buffers first */
629 vhost_zerocopy_signal_used(net, vq);
631 busyloop_intr = false;
632 head = get_tx_bufs(net, nvq, &msg, &out, &in, &len,
634 /* On error, stop handling until the next kick. */
635 if (unlikely(head < 0))
637 /* Nothing new? Wait for eventfd to tell us they refilled. */
638 if (head == vq->num) {
639 if (unlikely(busyloop_intr)) {
640 vhost_poll_queue(&vq->poll);
641 } else if (unlikely(vhost_enable_notify(&net->dev, vq))) {
642 vhost_disable_notify(&net->dev, vq);
648 zcopy_used = len >= VHOST_GOODCOPY_LEN
649 && !vhost_exceeds_maxpend(net)
650 && vhost_net_tx_select_zcopy(net);
652 /* use msg_control to pass vhost zerocopy ubuf info to skb */
654 struct ubuf_info *ubuf;
655 ubuf = nvq->ubuf_info + nvq->upend_idx;
657 vq->heads[nvq->upend_idx].id = cpu_to_vhost32(vq, head);
658 vq->heads[nvq->upend_idx].len = VHOST_DMA_IN_PROGRESS;
659 ubuf->callback = vhost_zerocopy_callback;
660 ubuf->ctx = nvq->ubufs;
661 ubuf->desc = nvq->upend_idx;
662 refcount_set(&ubuf->refcnt, 1);
663 msg.msg_control = ubuf;
664 msg.msg_controllen = sizeof(ubuf);
666 atomic_inc(&ubufs->refcount);
667 nvq->upend_idx = (nvq->upend_idx + 1) % UIO_MAXIOV;
669 msg.msg_control = NULL;
673 if (tx_can_batch(vq, total_len) &&
674 likely(!vhost_exceeds_maxpend(net))) {
675 msg.msg_flags |= MSG_MORE;
677 msg.msg_flags &= ~MSG_MORE;
680 /* TODO: Check specific error and bomb out unless ENOBUFS? */
681 err = sock->ops->sendmsg(sock, &msg, len);
682 if (unlikely(err < 0)) {
684 vhost_net_ubuf_put(ubufs);
685 nvq->upend_idx = ((unsigned)nvq->upend_idx - 1)
688 vhost_discard_vq_desc(vq, 1);
689 vhost_net_enable_vq(net, vq);
693 pr_debug("Truncated TX packet: "
694 " len %d != %zd\n", err, len);
696 vhost_add_used_and_signal(&net->dev, vq, head, 0);
698 vhost_zerocopy_signal_used(net, vq);
699 vhost_net_tx_packet(net);
700 if (unlikely(vhost_exceeds_weight(++sent_pkts, total_len))) {
701 vhost_poll_queue(&vq->poll);
707 /* Expects to be always run from workqueue - which acts as
708 * read-size critical section for our kind of RCU. */
709 static void handle_tx(struct vhost_net *net)
711 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
712 struct vhost_virtqueue *vq = &nvq->vq;
715 mutex_lock(&vq->mutex);
716 sock = vq->private_data;
720 if (!vq_iotlb_prefetch(vq))
723 vhost_disable_notify(&net->dev, vq);
724 vhost_net_disable_vq(net, vq);
726 if (vhost_sock_zcopy(sock))
727 handle_tx_zerocopy(net, sock);
729 handle_tx_copy(net, sock);
732 mutex_unlock(&vq->mutex);
735 static int peek_head_len(struct vhost_net_virtqueue *rvq, struct sock *sk)
737 struct sk_buff *head;
742 return vhost_net_buf_peek(rvq);
744 spin_lock_irqsave(&sk->sk_receive_queue.lock, flags);
745 head = skb_peek(&sk->sk_receive_queue);
748 if (skb_vlan_tag_present(head))
752 spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags);
756 static int sk_has_rx_data(struct sock *sk)
758 struct socket *sock = sk->sk_socket;
760 if (sock->ops->peek_len)
761 return sock->ops->peek_len(sock);
763 return skb_queue_empty(&sk->sk_receive_queue);
766 static int vhost_net_rx_peek_head_len(struct vhost_net *net, struct sock *sk,
769 struct vhost_net_virtqueue *rnvq = &net->vqs[VHOST_NET_VQ_RX];
770 struct vhost_net_virtqueue *tnvq = &net->vqs[VHOST_NET_VQ_TX];
771 struct vhost_virtqueue *rvq = &rnvq->vq;
772 struct vhost_virtqueue *tvq = &tnvq->vq;
773 unsigned long uninitialized_var(endtime);
774 int len = peek_head_len(rnvq, sk);
776 if (!len && tvq->busyloop_timeout) {
777 /* Flush batched heads first */
778 vhost_net_signal_used(rnvq);
779 /* Both tx vq and rx socket were polled here */
780 mutex_lock_nested(&tvq->mutex, 1);
781 vhost_disable_notify(&net->dev, tvq);
784 endtime = busy_clock() + tvq->busyloop_timeout;
786 while (vhost_can_busy_poll(endtime)) {
787 if (vhost_has_work(&net->dev)) {
788 *busyloop_intr = true;
791 if ((sk_has_rx_data(sk) &&
792 !vhost_vq_avail_empty(&net->dev, rvq)) ||
793 !vhost_vq_avail_empty(&net->dev, tvq))
800 if (!vhost_vq_avail_empty(&net->dev, tvq)) {
801 vhost_poll_queue(&tvq->poll);
802 } else if (unlikely(vhost_enable_notify(&net->dev, tvq))) {
803 vhost_disable_notify(&net->dev, tvq);
804 vhost_poll_queue(&tvq->poll);
807 mutex_unlock(&tvq->mutex);
809 len = peek_head_len(rnvq, sk);
815 /* This is a multi-buffer version of vhost_get_desc, that works if
816 * vq has read descriptors only.
817 * @vq - the relevant virtqueue
818 * @datalen - data length we'll be reading
819 * @iovcount - returned count of io vectors we fill
821 * @log_num - log offset
822 * @quota - headcount quota, 1 for big buffer
823 * returns number of buffer heads allocated, negative on error
825 static int get_rx_bufs(struct vhost_virtqueue *vq,
826 struct vring_used_elem *heads,
829 struct vhost_log *log,
833 unsigned int out, in;
838 /* len is always initialized before use since we are always called with
841 u32 uninitialized_var(len);
843 while (datalen > 0 && headcount < quota) {
844 if (unlikely(seg >= UIO_MAXIOV)) {
848 r = vhost_get_vq_desc(vq, vq->iov + seg,
849 ARRAY_SIZE(vq->iov) - seg, &out,
859 if (unlikely(out || in <= 0)) {
860 vq_err(vq, "unexpected descriptor format for RX: "
861 "out %d, in %d\n", out, in);
869 heads[headcount].id = cpu_to_vhost32(vq, d);
870 len = iov_length(vq->iov + seg, in);
871 heads[headcount].len = cpu_to_vhost32(vq, len);
876 heads[headcount - 1].len = cpu_to_vhost32(vq, len + datalen);
882 if (unlikely(datalen > 0)) {
888 vhost_discard_vq_desc(vq, headcount);
892 /* Expects to be always run from workqueue - which acts as
893 * read-size critical section for our kind of RCU. */
894 static void handle_rx(struct vhost_net *net)
896 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
897 struct vhost_virtqueue *vq = &nvq->vq;
898 unsigned uninitialized_var(in), log;
899 struct vhost_log *vq_log;
900 struct msghdr msg = {
903 .msg_control = NULL, /* FIXME: get and handle RX aux data. */
905 .msg_flags = MSG_DONTWAIT,
907 struct virtio_net_hdr hdr = {
909 .gso_type = VIRTIO_NET_HDR_GSO_NONE
911 size_t total_len = 0;
914 size_t vhost_hlen, sock_hlen;
915 size_t vhost_len, sock_len;
916 bool busyloop_intr = false;
918 struct iov_iter fixup;
919 __virtio16 num_buffers;
922 mutex_lock_nested(&vq->mutex, 0);
923 sock = vq->private_data;
927 if (!vq_iotlb_prefetch(vq))
930 vhost_disable_notify(&net->dev, vq);
931 vhost_net_disable_vq(net, vq);
933 vhost_hlen = nvq->vhost_hlen;
934 sock_hlen = nvq->sock_hlen;
936 vq_log = unlikely(vhost_has_feature(vq, VHOST_F_LOG_ALL)) ?
938 mergeable = vhost_has_feature(vq, VIRTIO_NET_F_MRG_RXBUF);
940 while ((sock_len = vhost_net_rx_peek_head_len(net, sock->sk,
942 sock_len += sock_hlen;
943 vhost_len = sock_len + vhost_hlen;
944 headcount = get_rx_bufs(vq, vq->heads + nvq->done_idx,
945 vhost_len, &in, vq_log, &log,
946 likely(mergeable) ? UIO_MAXIOV : 1);
947 /* On error, stop handling until the next kick. */
948 if (unlikely(headcount < 0))
950 /* OK, now we need to know about added descriptors. */
952 if (unlikely(busyloop_intr)) {
953 vhost_poll_queue(&vq->poll);
954 } else if (unlikely(vhost_enable_notify(&net->dev, vq))) {
955 /* They have slipped one in as we were
956 * doing that: check again. */
957 vhost_disable_notify(&net->dev, vq);
960 /* Nothing new? Wait for eventfd to tell us
964 busyloop_intr = false;
966 msg.msg_control = vhost_net_buf_consume(&nvq->rxq);
967 /* On overrun, truncate and discard */
968 if (unlikely(headcount > UIO_MAXIOV)) {
969 iov_iter_init(&msg.msg_iter, READ, vq->iov, 1, 1);
970 err = sock->ops->recvmsg(sock, &msg,
971 1, MSG_DONTWAIT | MSG_TRUNC);
972 pr_debug("Discarded rx packet: len %zd\n", sock_len);
975 /* We don't need to be notified again. */
976 iov_iter_init(&msg.msg_iter, READ, vq->iov, in, vhost_len);
977 fixup = msg.msg_iter;
978 if (unlikely((vhost_hlen))) {
979 /* We will supply the header ourselves
982 iov_iter_advance(&msg.msg_iter, vhost_hlen);
984 err = sock->ops->recvmsg(sock, &msg,
985 sock_len, MSG_DONTWAIT | MSG_TRUNC);
986 /* Userspace might have consumed the packet meanwhile:
987 * it's not supposed to do this usually, but might be hard
988 * to prevent. Discard data we got (if any) and keep going. */
989 if (unlikely(err != sock_len)) {
990 pr_debug("Discarded rx packet: "
991 " len %d, expected %zd\n", err, sock_len);
992 vhost_discard_vq_desc(vq, headcount);
995 /* Supply virtio_net_hdr if VHOST_NET_F_VIRTIO_NET_HDR */
996 if (unlikely(vhost_hlen)) {
997 if (copy_to_iter(&hdr, sizeof(hdr),
998 &fixup) != sizeof(hdr)) {
999 vq_err(vq, "Unable to write vnet_hdr "
1000 "at addr %p\n", vq->iov->iov_base);
1004 /* Header came from socket; we'll need to patch
1005 * ->num_buffers over if VIRTIO_NET_F_MRG_RXBUF
1007 iov_iter_advance(&fixup, sizeof(hdr));
1009 /* TODO: Should check and handle checksum. */
1011 num_buffers = cpu_to_vhost16(vq, headcount);
1012 if (likely(mergeable) &&
1013 copy_to_iter(&num_buffers, sizeof num_buffers,
1014 &fixup) != sizeof num_buffers) {
1015 vq_err(vq, "Failed num_buffers write");
1016 vhost_discard_vq_desc(vq, headcount);
1019 nvq->done_idx += headcount;
1020 if (nvq->done_idx > VHOST_NET_BATCH)
1021 vhost_net_signal_used(nvq);
1022 if (unlikely(vq_log))
1023 vhost_log_write(vq, vq_log, log, vhost_len);
1024 total_len += vhost_len;
1025 if (unlikely(vhost_exceeds_weight(++recv_pkts, total_len))) {
1026 vhost_poll_queue(&vq->poll);
1030 if (unlikely(busyloop_intr))
1031 vhost_poll_queue(&vq->poll);
1033 vhost_net_enable_vq(net, vq);
1035 vhost_net_signal_used(nvq);
1036 mutex_unlock(&vq->mutex);
1039 static void handle_tx_kick(struct vhost_work *work)
1041 struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
1043 struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
1048 static void handle_rx_kick(struct vhost_work *work)
1050 struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
1052 struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
1057 static void handle_tx_net(struct vhost_work *work)
1059 struct vhost_net *net = container_of(work, struct vhost_net,
1060 poll[VHOST_NET_VQ_TX].work);
1064 static void handle_rx_net(struct vhost_work *work)
1066 struct vhost_net *net = container_of(work, struct vhost_net,
1067 poll[VHOST_NET_VQ_RX].work);
1071 static int vhost_net_open(struct inode *inode, struct file *f)
1073 struct vhost_net *n;
1074 struct vhost_dev *dev;
1075 struct vhost_virtqueue **vqs;
1079 n = kvmalloc(sizeof *n, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1082 vqs = kmalloc_array(VHOST_NET_VQ_MAX, sizeof(*vqs), GFP_KERNEL);
1088 queue = kmalloc_array(VHOST_NET_BATCH, sizeof(void *),
1095 n->vqs[VHOST_NET_VQ_RX].rxq.queue = queue;
1098 vqs[VHOST_NET_VQ_TX] = &n->vqs[VHOST_NET_VQ_TX].vq;
1099 vqs[VHOST_NET_VQ_RX] = &n->vqs[VHOST_NET_VQ_RX].vq;
1100 n->vqs[VHOST_NET_VQ_TX].vq.handle_kick = handle_tx_kick;
1101 n->vqs[VHOST_NET_VQ_RX].vq.handle_kick = handle_rx_kick;
1102 for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
1103 n->vqs[i].ubufs = NULL;
1104 n->vqs[i].ubuf_info = NULL;
1105 n->vqs[i].upend_idx = 0;
1106 n->vqs[i].done_idx = 0;
1107 n->vqs[i].vhost_hlen = 0;
1108 n->vqs[i].sock_hlen = 0;
1109 n->vqs[i].rx_ring = NULL;
1110 vhost_net_buf_init(&n->vqs[i].rxq);
1112 vhost_dev_init(dev, vqs, VHOST_NET_VQ_MAX);
1114 vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, EPOLLOUT, dev);
1115 vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, EPOLLIN, dev);
1117 f->private_data = n;
1122 static struct socket *vhost_net_stop_vq(struct vhost_net *n,
1123 struct vhost_virtqueue *vq)
1125 struct socket *sock;
1126 struct vhost_net_virtqueue *nvq =
1127 container_of(vq, struct vhost_net_virtqueue, vq);
1129 mutex_lock(&vq->mutex);
1130 sock = vq->private_data;
1131 vhost_net_disable_vq(n, vq);
1132 vq->private_data = NULL;
1133 vhost_net_buf_unproduce(nvq);
1134 nvq->rx_ring = NULL;
1135 mutex_unlock(&vq->mutex);
1139 static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock,
1140 struct socket **rx_sock)
1142 *tx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_TX].vq);
1143 *rx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_RX].vq);
1146 static void vhost_net_flush_vq(struct vhost_net *n, int index)
1148 vhost_poll_flush(n->poll + index);
1149 vhost_poll_flush(&n->vqs[index].vq.poll);
1152 static void vhost_net_flush(struct vhost_net *n)
1154 vhost_net_flush_vq(n, VHOST_NET_VQ_TX);
1155 vhost_net_flush_vq(n, VHOST_NET_VQ_RX);
1156 if (n->vqs[VHOST_NET_VQ_TX].ubufs) {
1157 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1159 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1160 /* Wait for all lower device DMAs done. */
1161 vhost_net_ubuf_put_and_wait(n->vqs[VHOST_NET_VQ_TX].ubufs);
1162 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1163 n->tx_flush = false;
1164 atomic_set(&n->vqs[VHOST_NET_VQ_TX].ubufs->refcount, 1);
1165 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
1169 static int vhost_net_release(struct inode *inode, struct file *f)
1171 struct vhost_net *n = f->private_data;
1172 struct socket *tx_sock;
1173 struct socket *rx_sock;
1175 vhost_net_stop(n, &tx_sock, &rx_sock);
1177 vhost_dev_stop(&n->dev);
1178 vhost_dev_cleanup(&n->dev);
1179 vhost_net_vq_reset(n);
1181 sockfd_put(tx_sock);
1183 sockfd_put(rx_sock);
1184 /* Make sure no callbacks are outstanding */
1185 synchronize_rcu_bh();
1186 /* We do an extra flush before freeing memory,
1187 * since jobs can re-queue themselves. */
1189 kfree(n->vqs[VHOST_NET_VQ_RX].rxq.queue);
1195 static struct socket *get_raw_socket(int fd)
1198 struct sockaddr_ll sa;
1199 char buf[MAX_ADDR_LEN];
1202 struct socket *sock = sockfd_lookup(fd, &r);
1205 return ERR_PTR(-ENOTSOCK);
1207 /* Parameter checking */
1208 if (sock->sk->sk_type != SOCK_RAW) {
1209 r = -ESOCKTNOSUPPORT;
1213 r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa, 0);
1217 if (uaddr.sa.sll_family != AF_PACKET) {
1227 static struct ptr_ring *get_tap_ptr_ring(int fd)
1229 struct ptr_ring *ring;
1230 struct file *file = fget(fd);
1234 ring = tun_get_tx_ring(file);
1237 ring = tap_get_ptr_ring(file);
1246 static struct socket *get_tap_socket(int fd)
1248 struct file *file = fget(fd);
1249 struct socket *sock;
1252 return ERR_PTR(-EBADF);
1253 sock = tun_get_socket(file);
1256 sock = tap_get_socket(file);
1262 static struct socket *get_socket(int fd)
1264 struct socket *sock;
1266 /* special case to disable backend */
1269 sock = get_raw_socket(fd);
1272 sock = get_tap_socket(fd);
1275 return ERR_PTR(-ENOTSOCK);
1278 static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
1280 struct socket *sock, *oldsock;
1281 struct vhost_virtqueue *vq;
1282 struct vhost_net_virtqueue *nvq;
1283 struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL;
1286 mutex_lock(&n->dev.mutex);
1287 r = vhost_dev_check_owner(&n->dev);
1291 if (index >= VHOST_NET_VQ_MAX) {
1295 vq = &n->vqs[index].vq;
1296 nvq = &n->vqs[index];
1297 mutex_lock(&vq->mutex);
1299 /* Verify that ring has been setup correctly. */
1300 if (!vhost_vq_access_ok(vq)) {
1304 sock = get_socket(fd);
1310 /* start polling new socket */
1311 oldsock = vq->private_data;
1312 if (sock != oldsock) {
1313 ubufs = vhost_net_ubuf_alloc(vq,
1314 sock && vhost_sock_zcopy(sock));
1315 if (IS_ERR(ubufs)) {
1320 vhost_net_disable_vq(n, vq);
1321 vq->private_data = sock;
1322 vhost_net_buf_unproduce(nvq);
1323 r = vhost_vq_init_access(vq);
1326 r = vhost_net_enable_vq(n, vq);
1329 if (index == VHOST_NET_VQ_RX)
1330 nvq->rx_ring = get_tap_ptr_ring(fd);
1332 oldubufs = nvq->ubufs;
1336 n->tx_zcopy_err = 0;
1337 n->tx_flush = false;
1340 mutex_unlock(&vq->mutex);
1343 vhost_net_ubuf_put_wait_and_free(oldubufs);
1344 mutex_lock(&vq->mutex);
1345 vhost_zerocopy_signal_used(n, vq);
1346 mutex_unlock(&vq->mutex);
1350 vhost_net_flush_vq(n, index);
1351 sockfd_put(oldsock);
1354 mutex_unlock(&n->dev.mutex);
1358 vq->private_data = oldsock;
1359 vhost_net_enable_vq(n, vq);
1361 vhost_net_ubuf_put_wait_and_free(ubufs);
1366 mutex_unlock(&vq->mutex);
1368 mutex_unlock(&n->dev.mutex);
1372 static long vhost_net_reset_owner(struct vhost_net *n)
1374 struct socket *tx_sock = NULL;
1375 struct socket *rx_sock = NULL;
1377 struct vhost_umem *umem;
1379 mutex_lock(&n->dev.mutex);
1380 err = vhost_dev_check_owner(&n->dev);
1383 umem = vhost_dev_reset_owner_prepare();
1388 vhost_net_stop(n, &tx_sock, &rx_sock);
1390 vhost_dev_stop(&n->dev);
1391 vhost_dev_reset_owner(&n->dev, umem);
1392 vhost_net_vq_reset(n);
1394 mutex_unlock(&n->dev.mutex);
1396 sockfd_put(tx_sock);
1398 sockfd_put(rx_sock);
1402 static int vhost_net_set_features(struct vhost_net *n, u64 features)
1404 size_t vhost_hlen, sock_hlen, hdr_len;
1407 hdr_len = (features & ((1ULL << VIRTIO_NET_F_MRG_RXBUF) |
1408 (1ULL << VIRTIO_F_VERSION_1))) ?
1409 sizeof(struct virtio_net_hdr_mrg_rxbuf) :
1410 sizeof(struct virtio_net_hdr);
1411 if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) {
1412 /* vhost provides vnet_hdr */
1413 vhost_hlen = hdr_len;
1416 /* socket provides vnet_hdr */
1418 sock_hlen = hdr_len;
1420 mutex_lock(&n->dev.mutex);
1421 if ((features & (1 << VHOST_F_LOG_ALL)) &&
1422 !vhost_log_access_ok(&n->dev))
1425 if ((features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))) {
1426 if (vhost_init_device_iotlb(&n->dev, true))
1430 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
1431 mutex_lock(&n->vqs[i].vq.mutex);
1432 n->vqs[i].vq.acked_features = features;
1433 n->vqs[i].vhost_hlen = vhost_hlen;
1434 n->vqs[i].sock_hlen = sock_hlen;
1435 mutex_unlock(&n->vqs[i].vq.mutex);
1437 mutex_unlock(&n->dev.mutex);
1441 mutex_unlock(&n->dev.mutex);
1445 static long vhost_net_set_owner(struct vhost_net *n)
1449 mutex_lock(&n->dev.mutex);
1450 if (vhost_dev_has_owner(&n->dev)) {
1454 r = vhost_net_set_ubuf_info(n);
1457 r = vhost_dev_set_owner(&n->dev);
1459 vhost_net_clear_ubuf_info(n);
1462 mutex_unlock(&n->dev.mutex);
1466 static long vhost_net_ioctl(struct file *f, unsigned int ioctl,
1469 struct vhost_net *n = f->private_data;
1470 void __user *argp = (void __user *)arg;
1471 u64 __user *featurep = argp;
1472 struct vhost_vring_file backend;
1477 case VHOST_NET_SET_BACKEND:
1478 if (copy_from_user(&backend, argp, sizeof backend))
1480 return vhost_net_set_backend(n, backend.index, backend.fd);
1481 case VHOST_GET_FEATURES:
1482 features = VHOST_NET_FEATURES;
1483 if (copy_to_user(featurep, &features, sizeof features))
1486 case VHOST_SET_FEATURES:
1487 if (copy_from_user(&features, featurep, sizeof features))
1489 if (features & ~VHOST_NET_FEATURES)
1491 return vhost_net_set_features(n, features);
1492 case VHOST_RESET_OWNER:
1493 return vhost_net_reset_owner(n);
1494 case VHOST_SET_OWNER:
1495 return vhost_net_set_owner(n);
1497 mutex_lock(&n->dev.mutex);
1498 r = vhost_dev_ioctl(&n->dev, ioctl, argp);
1499 if (r == -ENOIOCTLCMD)
1500 r = vhost_vring_ioctl(&n->dev, ioctl, argp);
1503 mutex_unlock(&n->dev.mutex);
1508 #ifdef CONFIG_COMPAT
1509 static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl,
1512 return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
1516 static ssize_t vhost_net_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
1518 struct file *file = iocb->ki_filp;
1519 struct vhost_net *n = file->private_data;
1520 struct vhost_dev *dev = &n->dev;
1521 int noblock = file->f_flags & O_NONBLOCK;
1523 return vhost_chr_read_iter(dev, to, noblock);
1526 static ssize_t vhost_net_chr_write_iter(struct kiocb *iocb,
1527 struct iov_iter *from)
1529 struct file *file = iocb->ki_filp;
1530 struct vhost_net *n = file->private_data;
1531 struct vhost_dev *dev = &n->dev;
1533 return vhost_chr_write_iter(dev, from);
1536 static __poll_t vhost_net_chr_poll(struct file *file, poll_table *wait)
1538 struct vhost_net *n = file->private_data;
1539 struct vhost_dev *dev = &n->dev;
1541 return vhost_chr_poll(file, dev, wait);
1544 static const struct file_operations vhost_net_fops = {
1545 .owner = THIS_MODULE,
1546 .release = vhost_net_release,
1547 .read_iter = vhost_net_chr_read_iter,
1548 .write_iter = vhost_net_chr_write_iter,
1549 .poll = vhost_net_chr_poll,
1550 .unlocked_ioctl = vhost_net_ioctl,
1551 #ifdef CONFIG_COMPAT
1552 .compat_ioctl = vhost_net_compat_ioctl,
1554 .open = vhost_net_open,
1555 .llseek = noop_llseek,
1558 static struct miscdevice vhost_net_misc = {
1559 .minor = VHOST_NET_MINOR,
1560 .name = "vhost-net",
1561 .fops = &vhost_net_fops,
1564 static int vhost_net_init(void)
1566 if (experimental_zcopytx)
1567 vhost_net_enable_zcopy(VHOST_NET_VQ_TX);
1568 return misc_register(&vhost_net_misc);
1570 module_init(vhost_net_init);
1572 static void vhost_net_exit(void)
1574 misc_deregister(&vhost_net_misc);
1576 module_exit(vhost_net_exit);
1578 MODULE_VERSION("0.0.1");
1579 MODULE_LICENSE("GPL v2");
1580 MODULE_AUTHOR("Michael S. Tsirkin");
1581 MODULE_DESCRIPTION("Host kernel accelerator for virtio net");
1582 MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR);
1583 MODULE_ALIAS("devname:vhost-net");