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