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/vmalloc.h>
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>
33 static int experimental_zcopytx = 0;
34 module_param(experimental_zcopytx, int, 0444);
35 MODULE_PARM_DESC(experimental_zcopytx, "Enable Zero Copy TX;"
36 " 1 -Enable; 0 - Disable");
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
42 /* Max number of packets transferred before requeueing the job.
43 * Using this limit prevents one virtqueue from starving others with small
46 #define VHOST_NET_PKT_WEIGHT 256
48 /* MAX number of TX used buffers for outstanding zerocopy */
49 #define VHOST_MAX_PEND 128
50 #define VHOST_GOODCOPY_LEN 256
53 * For transmit, used buffer len is unused; we override it to track buffer
54 * status internally; used for zerocopy tx only.
56 /* Lower device DMA failed */
57 #define VHOST_DMA_FAILED_LEN ((__force __virtio32)3)
58 /* Lower device DMA done */
59 #define VHOST_DMA_DONE_LEN ((__force __virtio32)2)
60 /* Lower device DMA in progress */
61 #define VHOST_DMA_IN_PROGRESS ((__force __virtio32)1)
63 #define VHOST_DMA_CLEAR_LEN ((__force __virtio32)0)
65 #define VHOST_DMA_IS_DONE(len) ((__force u32)(len) >= (__force u32)VHOST_DMA_DONE_LEN)
68 VHOST_NET_FEATURES = VHOST_FEATURES |
69 (1ULL << VHOST_NET_F_VIRTIO_NET_HDR) |
70 (1ULL << VIRTIO_NET_F_MRG_RXBUF) |
71 (1ULL << VIRTIO_F_IOMMU_PLATFORM)
80 struct vhost_net_ubuf_ref {
81 /* refcount follows semantics similar to kref:
82 * 0: object is released
83 * 1: no outstanding ubufs
84 * >1: outstanding ubufs
87 wait_queue_head_t wait;
88 struct vhost_virtqueue *vq;
91 struct vhost_net_virtqueue {
92 struct vhost_virtqueue vq;
95 /* vhost zerocopy support fields below: */
96 /* last used idx for outstanding DMA zerocopy buffers */
98 /* first used idx for DMA done zerocopy buffers */
100 /* an array of userspace buffers info */
101 struct ubuf_info *ubuf_info;
102 /* Reference counting for outstanding ubufs.
103 * Protected by vq mutex. Writers must also take device mutex. */
104 struct vhost_net_ubuf_ref *ubufs;
108 struct vhost_dev dev;
109 struct vhost_net_virtqueue vqs[VHOST_NET_VQ_MAX];
110 struct vhost_poll poll[VHOST_NET_VQ_MAX];
111 /* Number of TX recently submitted.
112 * Protected by tx vq lock. */
114 /* Number of times zerocopy TX recently failed.
115 * Protected by tx vq lock. */
116 unsigned tx_zcopy_err;
117 /* Flush in progress. Protected by tx vq lock. */
121 static unsigned vhost_net_zcopy_mask __read_mostly;
123 static void vhost_net_enable_zcopy(int vq)
125 vhost_net_zcopy_mask |= 0x1 << vq;
128 static struct vhost_net_ubuf_ref *
129 vhost_net_ubuf_alloc(struct vhost_virtqueue *vq, bool zcopy)
131 struct vhost_net_ubuf_ref *ubufs;
132 /* No zero copy backend? Nothing to count. */
135 ubufs = kmalloc(sizeof(*ubufs), GFP_KERNEL);
137 return ERR_PTR(-ENOMEM);
138 atomic_set(&ubufs->refcount, 1);
139 init_waitqueue_head(&ubufs->wait);
144 static int vhost_net_ubuf_put(struct vhost_net_ubuf_ref *ubufs)
146 int r = atomic_sub_return(1, &ubufs->refcount);
148 wake_up(&ubufs->wait);
152 static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
154 vhost_net_ubuf_put(ubufs);
155 wait_event(ubufs->wait, !atomic_read(&ubufs->refcount));
158 static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs)
160 vhost_net_ubuf_put_and_wait(ubufs);
164 static void vhost_net_clear_ubuf_info(struct vhost_net *n)
168 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
169 kfree(n->vqs[i].ubuf_info);
170 n->vqs[i].ubuf_info = NULL;
174 static int vhost_net_set_ubuf_info(struct vhost_net *n)
179 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
180 zcopy = vhost_net_zcopy_mask & (0x1 << i);
183 n->vqs[i].ubuf_info = kmalloc(sizeof(*n->vqs[i].ubuf_info) *
184 UIO_MAXIOV, GFP_KERNEL);
185 if (!n->vqs[i].ubuf_info)
191 vhost_net_clear_ubuf_info(n);
195 static void vhost_net_vq_reset(struct vhost_net *n)
199 vhost_net_clear_ubuf_info(n);
201 for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
202 n->vqs[i].done_idx = 0;
203 n->vqs[i].upend_idx = 0;
204 n->vqs[i].ubufs = NULL;
205 n->vqs[i].vhost_hlen = 0;
206 n->vqs[i].sock_hlen = 0;
211 static void vhost_net_tx_packet(struct vhost_net *net)
214 if (net->tx_packets < 1024)
217 net->tx_zcopy_err = 0;
220 static void vhost_net_tx_err(struct vhost_net *net)
225 static bool vhost_net_tx_select_zcopy(struct vhost_net *net)
227 /* TX flush waits for outstanding DMAs to be done.
228 * Don't start new DMAs.
230 return !net->tx_flush &&
231 net->tx_packets / 64 >= net->tx_zcopy_err;
234 static bool vhost_sock_zcopy(struct socket *sock)
236 return unlikely(experimental_zcopytx) &&
237 sock_flag(sock->sk, SOCK_ZEROCOPY);
240 /* In case of DMA done not in order in lower device driver for some reason.
241 * upend_idx is used to track end of used idx, done_idx is used to track head
242 * of used idx. Once lower device DMA done contiguously, we will signal KVM
245 static void vhost_zerocopy_signal_used(struct vhost_net *net,
246 struct vhost_virtqueue *vq)
248 struct vhost_net_virtqueue *nvq =
249 container_of(vq, struct vhost_net_virtqueue, vq);
253 for (i = nvq->done_idx; i != nvq->upend_idx; i = (i + 1) % UIO_MAXIOV) {
254 if (vq->heads[i].len == VHOST_DMA_FAILED_LEN)
255 vhost_net_tx_err(net);
256 if (VHOST_DMA_IS_DONE(vq->heads[i].len)) {
257 vq->heads[i].len = VHOST_DMA_CLEAR_LEN;
263 add = min(UIO_MAXIOV - nvq->done_idx, j);
264 vhost_add_used_and_signal_n(vq->dev, vq,
265 &vq->heads[nvq->done_idx], add);
266 nvq->done_idx = (nvq->done_idx + add) % UIO_MAXIOV;
271 static void vhost_zerocopy_callback(struct ubuf_info *ubuf, bool success)
273 struct vhost_net_ubuf_ref *ubufs = ubuf->ctx;
274 struct vhost_virtqueue *vq = ubufs->vq;
279 /* set len to mark this desc buffers done DMA */
280 vq->heads[ubuf->desc].len = success ?
281 VHOST_DMA_DONE_LEN : VHOST_DMA_FAILED_LEN;
282 cnt = vhost_net_ubuf_put(ubufs);
285 * Trigger polling thread if guest stopped submitting new buffers:
286 * in this case, the refcount after decrement will eventually reach 1.
287 * We also trigger polling periodically after each 16 packets
288 * (the value 16 here is more or less arbitrary, it's tuned to trigger
289 * less than 10% of times).
291 if (cnt <= 1 || !(cnt % 16))
292 vhost_poll_queue(&vq->poll);
294 rcu_read_unlock_bh();
297 static inline unsigned long busy_clock(void)
299 return local_clock() >> 10;
302 static bool vhost_can_busy_poll(struct vhost_dev *dev,
303 unsigned long endtime)
305 return likely(!need_resched()) &&
306 likely(!time_after(busy_clock(), endtime)) &&
307 likely(!signal_pending(current)) &&
308 !vhost_has_work(dev);
311 static void vhost_net_disable_vq(struct vhost_net *n,
312 struct vhost_virtqueue *vq)
314 struct vhost_net_virtqueue *nvq =
315 container_of(vq, struct vhost_net_virtqueue, vq);
316 struct vhost_poll *poll = n->poll + (nvq - n->vqs);
317 if (!vq->private_data)
319 vhost_poll_stop(poll);
322 static int vhost_net_enable_vq(struct vhost_net *n,
323 struct vhost_virtqueue *vq)
325 struct vhost_net_virtqueue *nvq =
326 container_of(vq, struct vhost_net_virtqueue, vq);
327 struct vhost_poll *poll = n->poll + (nvq - n->vqs);
330 sock = vq->private_data;
334 return vhost_poll_start(poll, sock->file);
337 static int vhost_net_tx_get_vq_desc(struct vhost_net *net,
338 struct vhost_virtqueue *vq,
339 struct iovec iov[], unsigned int iov_size,
340 unsigned int *out_num, unsigned int *in_num)
342 unsigned long uninitialized_var(endtime);
343 int r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
344 out_num, in_num, NULL, NULL);
346 if (r == vq->num && vq->busyloop_timeout) {
348 endtime = busy_clock() + vq->busyloop_timeout;
349 while (vhost_can_busy_poll(vq->dev, endtime) &&
350 vhost_vq_avail_empty(vq->dev, vq))
351 cpu_relax_lowlatency();
353 r = vhost_get_vq_desc(vq, vq->iov, ARRAY_SIZE(vq->iov),
354 out_num, in_num, NULL, NULL);
360 /* Expects to be always run from workqueue - which acts as
361 * read-size critical section for our kind of RCU. */
362 static void handle_tx(struct vhost_net *net)
364 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
365 struct vhost_virtqueue *vq = &nvq->vq;
368 struct msghdr msg = {
373 .msg_flags = MSG_DONTWAIT,
375 size_t len, total_len = 0;
379 struct vhost_net_ubuf_ref *uninitialized_var(ubufs);
380 struct ubuf_info *ubuf;
381 bool zcopy, zcopy_used;
384 mutex_lock(&vq->mutex);
385 sock = vq->private_data;
389 if (!vq_iotlb_prefetch(vq))
392 vhost_disable_notify(&net->dev, vq);
394 hdr_size = nvq->vhost_hlen;
398 /* Release DMAs done buffers first */
400 vhost_zerocopy_signal_used(net, vq);
402 /* If more outstanding DMAs, queue the work.
403 * Handle upend_idx wrap around
405 if (unlikely((nvq->upend_idx + vq->num - VHOST_MAX_PEND)
406 % UIO_MAXIOV == nvq->done_idx))
409 head = vhost_net_tx_get_vq_desc(net, vq, vq->iov,
412 /* On error, stop handling until the next kick. */
413 if (unlikely(head < 0))
415 /* Nothing new? Wait for eventfd to tell us they refilled. */
416 if (head == vq->num) {
417 if (unlikely(vhost_enable_notify(&net->dev, vq))) {
418 vhost_disable_notify(&net->dev, vq);
424 vq_err(vq, "Unexpected descriptor format for TX: "
425 "out %d, int %d\n", out, in);
428 /* Skip header. TODO: support TSO. */
429 len = iov_length(vq->iov, out);
430 iov_iter_init(&msg.msg_iter, WRITE, vq->iov, out, len);
431 iov_iter_advance(&msg.msg_iter, hdr_size);
433 if (!msg_data_left(&msg)) {
434 vq_err(vq, "Unexpected header len for TX: "
435 "%zd expected %zd\n",
439 len = msg_data_left(&msg);
441 zcopy_used = zcopy && len >= VHOST_GOODCOPY_LEN
442 && (nvq->upend_idx + 1) % UIO_MAXIOV !=
444 && vhost_net_tx_select_zcopy(net);
446 /* use msg_control to pass vhost zerocopy ubuf info to skb */
448 ubuf = nvq->ubuf_info + nvq->upend_idx;
449 vq->heads[nvq->upend_idx].id = cpu_to_vhost32(vq, head);
450 vq->heads[nvq->upend_idx].len = VHOST_DMA_IN_PROGRESS;
451 ubuf->callback = vhost_zerocopy_callback;
452 ubuf->ctx = nvq->ubufs;
453 ubuf->desc = nvq->upend_idx;
454 msg.msg_control = ubuf;
455 msg.msg_controllen = sizeof(ubuf);
457 atomic_inc(&ubufs->refcount);
458 nvq->upend_idx = (nvq->upend_idx + 1) % UIO_MAXIOV;
460 msg.msg_control = NULL;
463 /* TODO: Check specific error and bomb out unless ENOBUFS? */
464 err = sock->ops->sendmsg(sock, &msg, len);
465 if (unlikely(err < 0)) {
467 if (vq->heads[ubuf->desc].len == VHOST_DMA_IN_PROGRESS)
468 vhost_net_ubuf_put(ubufs);
469 nvq->upend_idx = ((unsigned)nvq->upend_idx - 1)
472 vhost_discard_vq_desc(vq, 1);
476 pr_debug("Truncated TX packet: "
477 " len %d != %zd\n", err, len);
479 vhost_add_used_and_signal(&net->dev, vq, head, 0);
481 vhost_zerocopy_signal_used(net, vq);
483 vhost_net_tx_packet(net);
484 } while (likely(!vhost_exceeds_weight(vq, ++sent_pkts, total_len)));
486 mutex_unlock(&vq->mutex);
489 static int peek_head_len(struct sock *sk)
491 struct socket *sock = sk->sk_socket;
492 struct sk_buff *head;
496 if (sock->ops->peek_len)
497 return sock->ops->peek_len(sock);
499 spin_lock_irqsave(&sk->sk_receive_queue.lock, flags);
500 head = skb_peek(&sk->sk_receive_queue);
503 if (skb_vlan_tag_present(head))
507 spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags);
511 static int sk_has_rx_data(struct sock *sk)
513 struct socket *sock = sk->sk_socket;
515 if (sock->ops->peek_len)
516 return sock->ops->peek_len(sock);
518 return skb_queue_empty(&sk->sk_receive_queue);
521 static int vhost_net_rx_peek_head_len(struct vhost_net *net, struct sock *sk)
523 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX];
524 struct vhost_virtqueue *vq = &nvq->vq;
525 unsigned long uninitialized_var(endtime);
526 int len = peek_head_len(sk);
528 if (!len && vq->busyloop_timeout) {
529 /* Both tx vq and rx socket were polled here */
530 mutex_lock_nested(&vq->mutex, 1);
531 vhost_disable_notify(&net->dev, vq);
534 endtime = busy_clock() + vq->busyloop_timeout;
536 while (vhost_can_busy_poll(&net->dev, endtime) &&
537 !sk_has_rx_data(sk) &&
538 vhost_vq_avail_empty(&net->dev, vq))
539 cpu_relax_lowlatency();
543 if (!vhost_vq_avail_empty(&net->dev, vq))
544 vhost_poll_queue(&vq->poll);
545 else if (unlikely(vhost_enable_notify(&net->dev, vq))) {
546 vhost_disable_notify(&net->dev, vq);
547 vhost_poll_queue(&vq->poll);
550 mutex_unlock(&vq->mutex);
552 len = peek_head_len(sk);
558 /* This is a multi-buffer version of vhost_get_desc, that works if
559 * vq has read descriptors only.
560 * @vq - the relevant virtqueue
561 * @datalen - data length we'll be reading
562 * @iovcount - returned count of io vectors we fill
564 * @log_num - log offset
565 * @quota - headcount quota, 1 for big buffer
566 * returns number of buffer heads allocated, negative on error
568 static int get_rx_bufs(struct vhost_virtqueue *vq,
569 struct vring_used_elem *heads,
572 struct vhost_log *log,
576 unsigned int out, in;
581 /* len is always initialized before use since we are always called with
584 u32 uninitialized_var(len);
586 while (datalen > 0 && headcount < quota) {
587 if (unlikely(seg >= UIO_MAXIOV)) {
591 r = vhost_get_vq_desc(vq, vq->iov + seg,
592 ARRAY_SIZE(vq->iov) - seg, &out,
602 if (unlikely(out || in <= 0)) {
603 vq_err(vq, "unexpected descriptor format for RX: "
604 "out %d, in %d\n", out, in);
612 heads[headcount].id = cpu_to_vhost32(vq, d);
613 len = iov_length(vq->iov + seg, in);
614 heads[headcount].len = cpu_to_vhost32(vq, len);
619 heads[headcount - 1].len = cpu_to_vhost32(vq, len + datalen);
625 if (unlikely(datalen > 0)) {
631 vhost_discard_vq_desc(vq, headcount);
635 /* Expects to be always run from workqueue - which acts as
636 * read-size critical section for our kind of RCU. */
637 static void handle_rx(struct vhost_net *net)
639 struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX];
640 struct vhost_virtqueue *vq = &nvq->vq;
641 unsigned uninitialized_var(in), log;
642 struct vhost_log *vq_log;
643 struct msghdr msg = {
646 .msg_control = NULL, /* FIXME: get and handle RX aux data. */
648 .msg_flags = MSG_DONTWAIT,
650 struct virtio_net_hdr hdr = {
652 .gso_type = VIRTIO_NET_HDR_GSO_NONE
654 size_t total_len = 0;
657 size_t vhost_hlen, sock_hlen;
658 size_t vhost_len, sock_len;
660 struct iov_iter fixup;
661 __virtio16 num_buffers;
664 mutex_lock_nested(&vq->mutex, 0);
665 sock = vq->private_data;
669 if (!vq_iotlb_prefetch(vq))
672 vhost_disable_notify(&net->dev, vq);
673 vhost_net_disable_vq(net, vq);
675 vhost_hlen = nvq->vhost_hlen;
676 sock_hlen = nvq->sock_hlen;
678 vq_log = unlikely(vhost_has_feature(vq, VHOST_F_LOG_ALL)) ?
680 mergeable = vhost_has_feature(vq, VIRTIO_NET_F_MRG_RXBUF);
683 sock_len = vhost_net_rx_peek_head_len(net, sock->sk);
686 sock_len += sock_hlen;
687 vhost_len = sock_len + vhost_hlen;
688 headcount = get_rx_bufs(vq, vq->heads, vhost_len,
690 likely(mergeable) ? UIO_MAXIOV : 1);
691 /* On error, stop handling until the next kick. */
692 if (unlikely(headcount < 0))
694 /* On overrun, truncate and discard */
695 if (unlikely(headcount > UIO_MAXIOV)) {
696 iov_iter_init(&msg.msg_iter, READ, vq->iov, 1, 1);
697 err = sock->ops->recvmsg(sock, &msg,
698 1, MSG_DONTWAIT | MSG_TRUNC);
699 pr_debug("Discarded rx packet: len %zd\n", sock_len);
702 /* OK, now we need to know about added descriptors. */
704 if (unlikely(vhost_enable_notify(&net->dev, vq))) {
705 /* They have slipped one in as we were
706 * doing that: check again. */
707 vhost_disable_notify(&net->dev, vq);
710 /* Nothing new? Wait for eventfd to tell us
714 /* We don't need to be notified again. */
715 iov_iter_init(&msg.msg_iter, READ, vq->iov, in, vhost_len);
716 fixup = msg.msg_iter;
717 if (unlikely((vhost_hlen))) {
718 /* We will supply the header ourselves
721 iov_iter_advance(&msg.msg_iter, vhost_hlen);
723 err = sock->ops->recvmsg(sock, &msg,
724 sock_len, MSG_DONTWAIT | MSG_TRUNC);
725 /* Userspace might have consumed the packet meanwhile:
726 * it's not supposed to do this usually, but might be hard
727 * to prevent. Discard data we got (if any) and keep going. */
728 if (unlikely(err != sock_len)) {
729 pr_debug("Discarded rx packet: "
730 " len %d, expected %zd\n", err, sock_len);
731 vhost_discard_vq_desc(vq, headcount);
734 /* Supply virtio_net_hdr if VHOST_NET_F_VIRTIO_NET_HDR */
735 if (unlikely(vhost_hlen)) {
736 if (copy_to_iter(&hdr, sizeof(hdr),
737 &fixup) != sizeof(hdr)) {
738 vq_err(vq, "Unable to write vnet_hdr "
739 "at addr %p\n", vq->iov->iov_base);
743 /* Header came from socket; we'll need to patch
744 * ->num_buffers over if VIRTIO_NET_F_MRG_RXBUF
746 iov_iter_advance(&fixup, sizeof(hdr));
748 /* TODO: Should check and handle checksum. */
750 num_buffers = cpu_to_vhost16(vq, headcount);
751 if (likely(mergeable) &&
752 copy_to_iter(&num_buffers, sizeof num_buffers,
753 &fixup) != sizeof num_buffers) {
754 vq_err(vq, "Failed num_buffers write");
755 vhost_discard_vq_desc(vq, headcount);
758 vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
760 if (unlikely(vq_log))
761 vhost_log_write(vq, vq_log, log, vhost_len,
763 total_len += vhost_len;
764 } while (likely(!vhost_exceeds_weight(vq, ++recv_pkts, total_len)));
767 vhost_net_enable_vq(net, vq);
769 mutex_unlock(&vq->mutex);
772 static void handle_tx_kick(struct vhost_work *work)
774 struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
776 struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
781 static void handle_rx_kick(struct vhost_work *work)
783 struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
785 struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
790 static void handle_tx_net(struct vhost_work *work)
792 struct vhost_net *net = container_of(work, struct vhost_net,
793 poll[VHOST_NET_VQ_TX].work);
797 static void handle_rx_net(struct vhost_work *work)
799 struct vhost_net *net = container_of(work, struct vhost_net,
800 poll[VHOST_NET_VQ_RX].work);
804 static int vhost_net_open(struct inode *inode, struct file *f)
807 struct vhost_dev *dev;
808 struct vhost_virtqueue **vqs;
811 n = kmalloc(sizeof *n, GFP_KERNEL | __GFP_NOWARN | __GFP_REPEAT);
813 n = vmalloc(sizeof *n);
817 vqs = kmalloc(VHOST_NET_VQ_MAX * sizeof(*vqs), GFP_KERNEL);
824 vqs[VHOST_NET_VQ_TX] = &n->vqs[VHOST_NET_VQ_TX].vq;
825 vqs[VHOST_NET_VQ_RX] = &n->vqs[VHOST_NET_VQ_RX].vq;
826 n->vqs[VHOST_NET_VQ_TX].vq.handle_kick = handle_tx_kick;
827 n->vqs[VHOST_NET_VQ_RX].vq.handle_kick = handle_rx_kick;
828 for (i = 0; i < VHOST_NET_VQ_MAX; i++) {
829 n->vqs[i].ubufs = NULL;
830 n->vqs[i].ubuf_info = NULL;
831 n->vqs[i].upend_idx = 0;
832 n->vqs[i].done_idx = 0;
833 n->vqs[i].vhost_hlen = 0;
834 n->vqs[i].sock_hlen = 0;
836 vhost_dev_init(dev, vqs, VHOST_NET_VQ_MAX,
837 VHOST_NET_PKT_WEIGHT, VHOST_NET_WEIGHT);
839 vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, POLLOUT, dev);
840 vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, POLLIN, dev);
847 static struct socket *vhost_net_stop_vq(struct vhost_net *n,
848 struct vhost_virtqueue *vq)
852 mutex_lock(&vq->mutex);
853 sock = vq->private_data;
854 vhost_net_disable_vq(n, vq);
855 vq->private_data = NULL;
856 mutex_unlock(&vq->mutex);
860 static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock,
861 struct socket **rx_sock)
863 *tx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_TX].vq);
864 *rx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_RX].vq);
867 static void vhost_net_flush_vq(struct vhost_net *n, int index)
869 vhost_poll_flush(n->poll + index);
870 vhost_poll_flush(&n->vqs[index].vq.poll);
873 static void vhost_net_flush(struct vhost_net *n)
875 vhost_net_flush_vq(n, VHOST_NET_VQ_TX);
876 vhost_net_flush_vq(n, VHOST_NET_VQ_RX);
877 if (n->vqs[VHOST_NET_VQ_TX].ubufs) {
878 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
880 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
881 /* Wait for all lower device DMAs done. */
882 vhost_net_ubuf_put_and_wait(n->vqs[VHOST_NET_VQ_TX].ubufs);
883 mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
885 atomic_set(&n->vqs[VHOST_NET_VQ_TX].ubufs->refcount, 1);
886 mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex);
890 static int vhost_net_release(struct inode *inode, struct file *f)
892 struct vhost_net *n = f->private_data;
893 struct socket *tx_sock;
894 struct socket *rx_sock;
896 vhost_net_stop(n, &tx_sock, &rx_sock);
898 vhost_dev_stop(&n->dev);
899 vhost_dev_cleanup(&n->dev, false);
900 vhost_net_vq_reset(n);
905 /* Make sure no callbacks are outstanding */
906 synchronize_rcu_bh();
907 /* We do an extra flush before freeing memory,
908 * since jobs can re-queue themselves. */
915 static struct socket *get_raw_socket(int fd)
918 struct socket *sock = sockfd_lookup(fd, &r);
921 return ERR_PTR(-ENOTSOCK);
923 /* Parameter checking */
924 if (sock->sk->sk_type != SOCK_RAW) {
925 r = -ESOCKTNOSUPPORT;
929 if (sock->sk->sk_family != AF_PACKET) {
939 static struct socket *get_tap_socket(int fd)
941 struct file *file = fget(fd);
945 return ERR_PTR(-EBADF);
946 sock = tun_get_socket(file);
949 sock = macvtap_get_socket(file);
955 static struct socket *get_socket(int fd)
959 /* special case to disable backend */
962 sock = get_raw_socket(fd);
965 sock = get_tap_socket(fd);
968 return ERR_PTR(-ENOTSOCK);
971 static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
973 struct socket *sock, *oldsock;
974 struct vhost_virtqueue *vq;
975 struct vhost_net_virtqueue *nvq;
976 struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL;
979 mutex_lock(&n->dev.mutex);
980 r = vhost_dev_check_owner(&n->dev);
984 if (index >= VHOST_NET_VQ_MAX) {
988 vq = &n->vqs[index].vq;
989 nvq = &n->vqs[index];
990 mutex_lock(&vq->mutex);
992 /* Verify that ring has been setup correctly. */
993 if (!vhost_vq_access_ok(vq)) {
997 sock = get_socket(fd);
1003 /* start polling new socket */
1004 oldsock = vq->private_data;
1005 if (sock != oldsock) {
1006 ubufs = vhost_net_ubuf_alloc(vq,
1007 sock && vhost_sock_zcopy(sock));
1008 if (IS_ERR(ubufs)) {
1013 vhost_net_disable_vq(n, vq);
1014 vq->private_data = sock;
1015 r = vhost_vq_init_access(vq);
1018 r = vhost_net_enable_vq(n, vq);
1022 oldubufs = nvq->ubufs;
1026 n->tx_zcopy_err = 0;
1027 n->tx_flush = false;
1030 mutex_unlock(&vq->mutex);
1033 vhost_net_ubuf_put_wait_and_free(oldubufs);
1034 mutex_lock(&vq->mutex);
1035 vhost_zerocopy_signal_used(n, vq);
1036 mutex_unlock(&vq->mutex);
1040 vhost_net_flush_vq(n, index);
1041 sockfd_put(oldsock);
1044 mutex_unlock(&n->dev.mutex);
1048 vq->private_data = oldsock;
1049 vhost_net_enable_vq(n, vq);
1051 vhost_net_ubuf_put_wait_and_free(ubufs);
1056 mutex_unlock(&vq->mutex);
1058 mutex_unlock(&n->dev.mutex);
1062 static long vhost_net_reset_owner(struct vhost_net *n)
1064 struct socket *tx_sock = NULL;
1065 struct socket *rx_sock = NULL;
1067 struct vhost_umem *umem;
1069 mutex_lock(&n->dev.mutex);
1070 err = vhost_dev_check_owner(&n->dev);
1073 umem = vhost_dev_reset_owner_prepare();
1078 vhost_net_stop(n, &tx_sock, &rx_sock);
1080 vhost_dev_stop(&n->dev);
1081 vhost_dev_reset_owner(&n->dev, umem);
1082 vhost_net_vq_reset(n);
1084 mutex_unlock(&n->dev.mutex);
1086 sockfd_put(tx_sock);
1088 sockfd_put(rx_sock);
1092 static int vhost_net_set_features(struct vhost_net *n, u64 features)
1094 size_t vhost_hlen, sock_hlen, hdr_len;
1097 hdr_len = (features & ((1ULL << VIRTIO_NET_F_MRG_RXBUF) |
1098 (1ULL << VIRTIO_F_VERSION_1))) ?
1099 sizeof(struct virtio_net_hdr_mrg_rxbuf) :
1100 sizeof(struct virtio_net_hdr);
1101 if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) {
1102 /* vhost provides vnet_hdr */
1103 vhost_hlen = hdr_len;
1106 /* socket provides vnet_hdr */
1108 sock_hlen = hdr_len;
1110 mutex_lock(&n->dev.mutex);
1111 if ((features & (1 << VHOST_F_LOG_ALL)) &&
1112 !vhost_log_access_ok(&n->dev))
1115 if ((features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))) {
1116 if (vhost_init_device_iotlb(&n->dev, true))
1120 for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
1121 mutex_lock(&n->vqs[i].vq.mutex);
1122 n->vqs[i].vq.acked_features = features;
1123 n->vqs[i].vhost_hlen = vhost_hlen;
1124 n->vqs[i].sock_hlen = sock_hlen;
1125 mutex_unlock(&n->vqs[i].vq.mutex);
1127 mutex_unlock(&n->dev.mutex);
1131 mutex_unlock(&n->dev.mutex);
1135 static long vhost_net_set_owner(struct vhost_net *n)
1139 mutex_lock(&n->dev.mutex);
1140 if (vhost_dev_has_owner(&n->dev)) {
1144 r = vhost_net_set_ubuf_info(n);
1147 r = vhost_dev_set_owner(&n->dev);
1149 vhost_net_clear_ubuf_info(n);
1152 mutex_unlock(&n->dev.mutex);
1156 static long vhost_net_ioctl(struct file *f, unsigned int ioctl,
1159 struct vhost_net *n = f->private_data;
1160 void __user *argp = (void __user *)arg;
1161 u64 __user *featurep = argp;
1162 struct vhost_vring_file backend;
1167 case VHOST_NET_SET_BACKEND:
1168 if (copy_from_user(&backend, argp, sizeof backend))
1170 return vhost_net_set_backend(n, backend.index, backend.fd);
1171 case VHOST_GET_FEATURES:
1172 features = VHOST_NET_FEATURES;
1173 if (copy_to_user(featurep, &features, sizeof features))
1176 case VHOST_SET_FEATURES:
1177 if (copy_from_user(&features, featurep, sizeof features))
1179 if (features & ~VHOST_NET_FEATURES)
1181 return vhost_net_set_features(n, features);
1182 case VHOST_RESET_OWNER:
1183 return vhost_net_reset_owner(n);
1184 case VHOST_SET_OWNER:
1185 return vhost_net_set_owner(n);
1187 mutex_lock(&n->dev.mutex);
1188 r = vhost_dev_ioctl(&n->dev, ioctl, argp);
1189 if (r == -ENOIOCTLCMD)
1190 r = vhost_vring_ioctl(&n->dev, ioctl, argp);
1193 mutex_unlock(&n->dev.mutex);
1198 #ifdef CONFIG_COMPAT
1199 static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl,
1202 return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
1206 static ssize_t vhost_net_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
1208 struct file *file = iocb->ki_filp;
1209 struct vhost_net *n = file->private_data;
1210 struct vhost_dev *dev = &n->dev;
1211 int noblock = file->f_flags & O_NONBLOCK;
1213 return vhost_chr_read_iter(dev, to, noblock);
1216 static ssize_t vhost_net_chr_write_iter(struct kiocb *iocb,
1217 struct iov_iter *from)
1219 struct file *file = iocb->ki_filp;
1220 struct vhost_net *n = file->private_data;
1221 struct vhost_dev *dev = &n->dev;
1223 return vhost_chr_write_iter(dev, from);
1226 static unsigned int vhost_net_chr_poll(struct file *file, poll_table *wait)
1228 struct vhost_net *n = file->private_data;
1229 struct vhost_dev *dev = &n->dev;
1231 return vhost_chr_poll(file, dev, wait);
1234 static const struct file_operations vhost_net_fops = {
1235 .owner = THIS_MODULE,
1236 .release = vhost_net_release,
1237 .read_iter = vhost_net_chr_read_iter,
1238 .write_iter = vhost_net_chr_write_iter,
1239 .poll = vhost_net_chr_poll,
1240 .unlocked_ioctl = vhost_net_ioctl,
1241 #ifdef CONFIG_COMPAT
1242 .compat_ioctl = vhost_net_compat_ioctl,
1244 .open = vhost_net_open,
1245 .llseek = noop_llseek,
1248 static struct miscdevice vhost_net_misc = {
1249 .minor = VHOST_NET_MINOR,
1250 .name = "vhost-net",
1251 .fops = &vhost_net_fops,
1254 static int vhost_net_init(void)
1256 if (experimental_zcopytx)
1257 vhost_net_enable_zcopy(VHOST_NET_VQ_TX);
1258 return misc_register(&vhost_net_misc);
1260 module_init(vhost_net_init);
1262 static void vhost_net_exit(void)
1264 misc_deregister(&vhost_net_misc);
1266 module_exit(vhost_net_exit);
1268 MODULE_VERSION("0.0.1");
1269 MODULE_LICENSE("GPL v2");
1270 MODULE_AUTHOR("Michael S. Tsirkin");
1271 MODULE_DESCRIPTION("Host kernel accelerator for virtio net");
1272 MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR);
1273 MODULE_ALIAS("devname:vhost-net");