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