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;
34 module_param(experimental_zcopytx, int, 0444);
35 MODULE_PARM_DESC(experimental_zcopytx, "Enable Experimental Zero Copy TX");
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 enum {
46 	VHOST_NET_VQ_RX = 0,
47 	VHOST_NET_VQ_TX = 1,
48 	VHOST_NET_VQ_MAX = 2,
49 };
50 
51 enum vhost_net_poll_state {
52 	VHOST_NET_POLL_DISABLED = 0,
53 	VHOST_NET_POLL_STARTED = 1,
54 	VHOST_NET_POLL_STOPPED = 2,
55 };
56 
57 struct vhost_net {
58 	struct vhost_dev dev;
59 	struct vhost_virtqueue vqs[VHOST_NET_VQ_MAX];
60 	struct vhost_poll poll[VHOST_NET_VQ_MAX];
61 	/* Tells us whether we are polling a socket for TX.
62 	 * We only do this when socket buffer fills up.
63 	 * Protected by tx vq lock. */
64 	enum vhost_net_poll_state tx_poll_state;
65 };
66 
vhost_sock_zcopy(struct socket * sock)67 static bool vhost_sock_zcopy(struct socket *sock)
68 {
69 	return unlikely(experimental_zcopytx) &&
70 		sock_flag(sock->sk, SOCK_ZEROCOPY);
71 }
72 
73 /* Pop first len bytes from iovec. Return number of segments used. */
move_iovec_hdr(struct iovec * from,struct iovec * to,size_t len,int iov_count)74 static int move_iovec_hdr(struct iovec *from, struct iovec *to,
75 			  size_t len, int iov_count)
76 {
77 	int seg = 0;
78 	size_t size;
79 
80 	while (len && seg < iov_count) {
81 		size = min(from->iov_len, len);
82 		to->iov_base = from->iov_base;
83 		to->iov_len = size;
84 		from->iov_len -= size;
85 		from->iov_base += size;
86 		len -= size;
87 		++from;
88 		++to;
89 		++seg;
90 	}
91 	return seg;
92 }
93 /* Copy iovec entries for len bytes from iovec. */
copy_iovec_hdr(const struct iovec * from,struct iovec * to,size_t len,int iovcount)94 static void copy_iovec_hdr(const struct iovec *from, struct iovec *to,
95 			   size_t len, int iovcount)
96 {
97 	int seg = 0;
98 	size_t size;
99 
100 	while (len && seg < iovcount) {
101 		size = min(from->iov_len, len);
102 		to->iov_base = from->iov_base;
103 		to->iov_len = size;
104 		len -= size;
105 		++from;
106 		++to;
107 		++seg;
108 	}
109 }
110 
111 /* Caller must have TX VQ lock */
tx_poll_stop(struct vhost_net * net)112 static void tx_poll_stop(struct vhost_net *net)
113 {
114 	if (likely(net->tx_poll_state != VHOST_NET_POLL_STARTED))
115 		return;
116 	vhost_poll_stop(net->poll + VHOST_NET_VQ_TX);
117 	net->tx_poll_state = VHOST_NET_POLL_STOPPED;
118 }
119 
120 /* Caller must have TX VQ lock */
tx_poll_start(struct vhost_net * net,struct socket * sock)121 static void tx_poll_start(struct vhost_net *net, struct socket *sock)
122 {
123 	if (unlikely(net->tx_poll_state != VHOST_NET_POLL_STOPPED))
124 		return;
125 	vhost_poll_start(net->poll + VHOST_NET_VQ_TX, sock->file);
126 	net->tx_poll_state = VHOST_NET_POLL_STARTED;
127 }
128 
129 /* Expects to be always run from workqueue - which acts as
130  * read-size critical section for our kind of RCU. */
handle_tx(struct vhost_net * net)131 static void handle_tx(struct vhost_net *net)
132 {
133 	struct vhost_virtqueue *vq = &net->dev.vqs[VHOST_NET_VQ_TX];
134 	unsigned out, in, s;
135 	int head;
136 	struct msghdr msg = {
137 		.msg_name = NULL,
138 		.msg_namelen = 0,
139 		.msg_control = NULL,
140 		.msg_controllen = 0,
141 		.msg_iov = vq->iov,
142 		.msg_flags = MSG_DONTWAIT,
143 	};
144 	size_t len, total_len = 0;
145 	int err, wmem;
146 	size_t hdr_size;
147 	struct socket *sock;
148 	struct vhost_ubuf_ref *uninitialized_var(ubufs);
149 	bool zcopy;
150 
151 	/* TODO: check that we are running from vhost_worker? */
152 	sock = rcu_dereference_check(vq->private_data, 1);
153 	if (!sock)
154 		return;
155 
156 	wmem = atomic_read(&sock->sk->sk_wmem_alloc);
157 	if (wmem >= sock->sk->sk_sndbuf) {
158 		mutex_lock(&vq->mutex);
159 		tx_poll_start(net, sock);
160 		mutex_unlock(&vq->mutex);
161 		return;
162 	}
163 
164 	mutex_lock(&vq->mutex);
165 	vhost_disable_notify(&net->dev, vq);
166 
167 	if (wmem < sock->sk->sk_sndbuf / 2)
168 		tx_poll_stop(net);
169 	hdr_size = vq->vhost_hlen;
170 	zcopy = vhost_sock_zcopy(sock);
171 
172 	for (;;) {
173 		/* Release DMAs done buffers first */
174 		if (zcopy)
175 			vhost_zerocopy_signal_used(vq);
176 
177 		head = vhost_get_vq_desc(&net->dev, vq, vq->iov,
178 					 ARRAY_SIZE(vq->iov),
179 					 &out, &in,
180 					 NULL, NULL);
181 		/* On error, stop handling until the next kick. */
182 		if (unlikely(head < 0))
183 			break;
184 		/* Nothing new?  Wait for eventfd to tell us they refilled. */
185 		if (head == vq->num) {
186 			int num_pends;
187 
188 			wmem = atomic_read(&sock->sk->sk_wmem_alloc);
189 			if (wmem >= sock->sk->sk_sndbuf * 3 / 4) {
190 				tx_poll_start(net, sock);
191 				set_bit(SOCK_ASYNC_NOSPACE, &sock->flags);
192 				break;
193 			}
194 			/* If more outstanding DMAs, queue the work.
195 			 * Handle upend_idx wrap around
196 			 */
197 			num_pends = likely(vq->upend_idx >= vq->done_idx) ?
198 				    (vq->upend_idx - vq->done_idx) :
199 				    (vq->upend_idx + UIO_MAXIOV - vq->done_idx);
200 			if (unlikely(num_pends > VHOST_MAX_PEND)) {
201 				tx_poll_start(net, sock);
202 				set_bit(SOCK_ASYNC_NOSPACE, &sock->flags);
203 				break;
204 			}
205 			if (unlikely(vhost_enable_notify(&net->dev, vq))) {
206 				vhost_disable_notify(&net->dev, vq);
207 				continue;
208 			}
209 			break;
210 		}
211 		if (in) {
212 			vq_err(vq, "Unexpected descriptor format for TX: "
213 			       "out %d, int %d\n", out, in);
214 			break;
215 		}
216 		/* Skip header. TODO: support TSO. */
217 		s = move_iovec_hdr(vq->iov, vq->hdr, hdr_size, out);
218 		msg.msg_iovlen = out;
219 		len = iov_length(vq->iov, out);
220 		/* Sanity check */
221 		if (!len) {
222 			vq_err(vq, "Unexpected header len for TX: "
223 			       "%zd expected %zd\n",
224 			       iov_length(vq->hdr, s), hdr_size);
225 			break;
226 		}
227 		/* use msg_control to pass vhost zerocopy ubuf info to skb */
228 		if (zcopy) {
229 			vq->heads[vq->upend_idx].id = head;
230 			if (len < VHOST_GOODCOPY_LEN) {
231 				/* copy don't need to wait for DMA done */
232 				vq->heads[vq->upend_idx].len =
233 							VHOST_DMA_DONE_LEN;
234 				msg.msg_control = NULL;
235 				msg.msg_controllen = 0;
236 				ubufs = NULL;
237 			} else {
238 				struct ubuf_info *ubuf;
239 				ubuf = vq->ubuf_info + vq->upend_idx;
240 
241 				vq->heads[vq->upend_idx].len = len;
242 				ubuf->callback = vhost_zerocopy_callback;
243 				ubuf->ctx = vq->ubufs;
244 				ubuf->desc = vq->upend_idx;
245 				msg.msg_control = ubuf;
246 				msg.msg_controllen = sizeof(ubuf);
247 				ubufs = vq->ubufs;
248 				kref_get(&ubufs->kref);
249 			}
250 			vq->upend_idx = (vq->upend_idx + 1) % UIO_MAXIOV;
251 		}
252 		/* TODO: Check specific error and bomb out unless ENOBUFS? */
253 		err = sock->ops->sendmsg(NULL, sock, &msg, len);
254 		if (unlikely(err < 0)) {
255 			if (zcopy) {
256 				if (ubufs)
257 					vhost_ubuf_put(ubufs);
258 				vq->upend_idx = ((unsigned)vq->upend_idx - 1) %
259 					UIO_MAXIOV;
260 			}
261 			vhost_discard_vq_desc(vq, 1);
262 			tx_poll_start(net, sock);
263 			break;
264 		}
265 		if (err != len)
266 			pr_debug("Truncated TX packet: "
267 				 " len %d != %zd\n", err, len);
268 		if (!zcopy)
269 			vhost_add_used_and_signal(&net->dev, vq, head, 0);
270 		total_len += len;
271 		if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
272 			vhost_poll_queue(&vq->poll);
273 			break;
274 		}
275 	}
276 
277 	mutex_unlock(&vq->mutex);
278 }
279 
peek_head_len(struct sock * sk)280 static int peek_head_len(struct sock *sk)
281 {
282 	struct sk_buff *head;
283 	int len = 0;
284 	unsigned long flags;
285 
286 	spin_lock_irqsave(&sk->sk_receive_queue.lock, flags);
287 	head = skb_peek(&sk->sk_receive_queue);
288 	if (likely(head)) {
289 		len = head->len;
290 		if (vlan_tx_tag_present(head))
291 			len += VLAN_HLEN;
292 	}
293 
294 	spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags);
295 	return len;
296 }
297 
298 /* This is a multi-buffer version of vhost_get_desc, that works if
299  *	vq has read descriptors only.
300  * @vq		- the relevant virtqueue
301  * @datalen	- data length we'll be reading
302  * @iovcount	- returned count of io vectors we fill
303  * @log		- vhost log
304  * @log_num	- log offset
305  * @quota       - headcount quota, 1 for big buffer
306  *	returns number of buffer heads allocated, negative on error
307  */
get_rx_bufs(struct vhost_virtqueue * vq,struct vring_used_elem * heads,int datalen,unsigned * iovcount,struct vhost_log * log,unsigned * log_num,unsigned int quota)308 static int get_rx_bufs(struct vhost_virtqueue *vq,
309 		       struct vring_used_elem *heads,
310 		       int datalen,
311 		       unsigned *iovcount,
312 		       struct vhost_log *log,
313 		       unsigned *log_num,
314 		       unsigned int quota)
315 {
316 	unsigned int out, in;
317 	int seg = 0;
318 	int headcount = 0;
319 	unsigned d;
320 	int r, nlogs = 0;
321 
322 	while (datalen > 0 && headcount < quota) {
323 		if (unlikely(seg >= UIO_MAXIOV)) {
324 			r = -ENOBUFS;
325 			goto err;
326 		}
327 		r = vhost_get_vq_desc(vq->dev, vq, vq->iov + seg,
328 				      ARRAY_SIZE(vq->iov) - seg, &out,
329 				      &in, log, log_num);
330 		if (unlikely(r < 0))
331 			goto err;
332 
333 		d = r;
334 		if (d == vq->num) {
335 			r = 0;
336 			goto err;
337 		}
338 		if (unlikely(out || in <= 0)) {
339 			vq_err(vq, "unexpected descriptor format for RX: "
340 				"out %d, in %d\n", out, in);
341 			r = -EINVAL;
342 			goto err;
343 		}
344 		if (unlikely(log)) {
345 			nlogs += *log_num;
346 			log += *log_num;
347 		}
348 		heads[headcount].id = d;
349 		heads[headcount].len = iov_length(vq->iov + seg, in);
350 		datalen -= heads[headcount].len;
351 		++headcount;
352 		seg += in;
353 	}
354 	heads[headcount - 1].len += datalen;
355 	*iovcount = seg;
356 	if (unlikely(log))
357 		*log_num = nlogs;
358 
359 	/* Detect overrun */
360 	if (unlikely(datalen > 0)) {
361 		r = UIO_MAXIOV + 1;
362 		goto err;
363 	}
364 	return headcount;
365 err:
366 	vhost_discard_vq_desc(vq, headcount);
367 	return r;
368 }
369 
370 /* Expects to be always run from workqueue - which acts as
371  * read-size critical section for our kind of RCU. */
handle_rx(struct vhost_net * net)372 static void handle_rx(struct vhost_net *net)
373 {
374 	struct vhost_virtqueue *vq = &net->dev.vqs[VHOST_NET_VQ_RX];
375 	unsigned uninitialized_var(in), log;
376 	struct vhost_log *vq_log;
377 	struct msghdr msg = {
378 		.msg_name = NULL,
379 		.msg_namelen = 0,
380 		.msg_control = NULL, /* FIXME: get and handle RX aux data. */
381 		.msg_controllen = 0,
382 		.msg_iov = vq->iov,
383 		.msg_flags = MSG_DONTWAIT,
384 	};
385 	struct virtio_net_hdr_mrg_rxbuf hdr = {
386 		.hdr.flags = 0,
387 		.hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE
388 	};
389 	size_t total_len = 0;
390 	int err, mergeable;
391 	s16 headcount;
392 	size_t vhost_hlen, sock_hlen;
393 	size_t vhost_len, sock_len;
394 	/* TODO: check that we are running from vhost_worker? */
395 	struct socket *sock = rcu_dereference_check(vq->private_data, 1);
396 
397 	if (!sock)
398 		return;
399 
400 	mutex_lock(&vq->mutex);
401 	vhost_disable_notify(&net->dev, vq);
402 	vhost_hlen = vq->vhost_hlen;
403 	sock_hlen = vq->sock_hlen;
404 
405 	vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ?
406 		vq->log : NULL;
407 	mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF);
408 
409 	while ((sock_len = peek_head_len(sock->sk))) {
410 		sock_len += sock_hlen;
411 		vhost_len = sock_len + vhost_hlen;
412 		headcount = get_rx_bufs(vq, vq->heads, vhost_len,
413 					&in, vq_log, &log,
414 					likely(mergeable) ? UIO_MAXIOV : 1);
415 		/* On error, stop handling until the next kick. */
416 		if (unlikely(headcount < 0))
417 			break;
418 		/* On overrun, truncate and discard */
419 		if (unlikely(headcount > UIO_MAXIOV)) {
420 			msg.msg_iovlen = 1;
421 			err = sock->ops->recvmsg(NULL, sock, &msg,
422 						 1, MSG_DONTWAIT | MSG_TRUNC);
423 			pr_debug("Discarded rx packet: len %zd\n", sock_len);
424 			continue;
425 		}
426 		/* OK, now we need to know about added descriptors. */
427 		if (!headcount) {
428 			if (unlikely(vhost_enable_notify(&net->dev, vq))) {
429 				/* They have slipped one in as we were
430 				 * doing that: check again. */
431 				vhost_disable_notify(&net->dev, vq);
432 				continue;
433 			}
434 			/* Nothing new?  Wait for eventfd to tell us
435 			 * they refilled. */
436 			break;
437 		}
438 		/* We don't need to be notified again. */
439 		if (unlikely((vhost_hlen)))
440 			/* Skip header. TODO: support TSO. */
441 			move_iovec_hdr(vq->iov, vq->hdr, vhost_hlen, in);
442 		else
443 			/* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF:
444 			 * needed because recvmsg can modify msg_iov. */
445 			copy_iovec_hdr(vq->iov, vq->hdr, sock_hlen, in);
446 		msg.msg_iovlen = in;
447 		err = sock->ops->recvmsg(NULL, sock, &msg,
448 					 sock_len, MSG_DONTWAIT | MSG_TRUNC);
449 		/* Userspace might have consumed the packet meanwhile:
450 		 * it's not supposed to do this usually, but might be hard
451 		 * to prevent. Discard data we got (if any) and keep going. */
452 		if (unlikely(err != sock_len)) {
453 			pr_debug("Discarded rx packet: "
454 				 " len %d, expected %zd\n", err, sock_len);
455 			vhost_discard_vq_desc(vq, headcount);
456 			continue;
457 		}
458 		if (unlikely(vhost_hlen) &&
459 		    memcpy_toiovecend(vq->hdr, (unsigned char *)&hdr, 0,
460 				      vhost_hlen)) {
461 			vq_err(vq, "Unable to write vnet_hdr at addr %p\n",
462 			       vq->iov->iov_base);
463 			break;
464 		}
465 		/* TODO: Should check and handle checksum. */
466 		if (likely(mergeable) &&
467 		    memcpy_toiovecend(vq->hdr, (unsigned char *)&headcount,
468 				      offsetof(typeof(hdr), num_buffers),
469 				      sizeof hdr.num_buffers)) {
470 			vq_err(vq, "Failed num_buffers write");
471 			vhost_discard_vq_desc(vq, headcount);
472 			break;
473 		}
474 		vhost_add_used_and_signal_n(&net->dev, vq, vq->heads,
475 					    headcount);
476 		if (unlikely(vq_log))
477 			vhost_log_write(vq, vq_log, log, vhost_len);
478 		total_len += vhost_len;
479 		if (unlikely(total_len >= VHOST_NET_WEIGHT)) {
480 			vhost_poll_queue(&vq->poll);
481 			break;
482 		}
483 	}
484 
485 	mutex_unlock(&vq->mutex);
486 }
487 
handle_tx_kick(struct vhost_work * work)488 static void handle_tx_kick(struct vhost_work *work)
489 {
490 	struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
491 						  poll.work);
492 	struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
493 
494 	handle_tx(net);
495 }
496 
handle_rx_kick(struct vhost_work * work)497 static void handle_rx_kick(struct vhost_work *work)
498 {
499 	struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
500 						  poll.work);
501 	struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev);
502 
503 	handle_rx(net);
504 }
505 
handle_tx_net(struct vhost_work * work)506 static void handle_tx_net(struct vhost_work *work)
507 {
508 	struct vhost_net *net = container_of(work, struct vhost_net,
509 					     poll[VHOST_NET_VQ_TX].work);
510 	handle_tx(net);
511 }
512 
handle_rx_net(struct vhost_work * work)513 static void handle_rx_net(struct vhost_work *work)
514 {
515 	struct vhost_net *net = container_of(work, struct vhost_net,
516 					     poll[VHOST_NET_VQ_RX].work);
517 	handle_rx(net);
518 }
519 
vhost_net_open(struct inode * inode,struct file * f)520 static int vhost_net_open(struct inode *inode, struct file *f)
521 {
522 	struct vhost_net *n = kmalloc(sizeof *n, GFP_KERNEL);
523 	struct vhost_dev *dev;
524 	int r;
525 
526 	if (!n)
527 		return -ENOMEM;
528 
529 	dev = &n->dev;
530 	n->vqs[VHOST_NET_VQ_TX].handle_kick = handle_tx_kick;
531 	n->vqs[VHOST_NET_VQ_RX].handle_kick = handle_rx_kick;
532 	r = vhost_dev_init(dev, n->vqs, VHOST_NET_VQ_MAX);
533 	if (r < 0) {
534 		kfree(n);
535 		return r;
536 	}
537 
538 	vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, POLLOUT, dev);
539 	vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, POLLIN, dev);
540 	n->tx_poll_state = VHOST_NET_POLL_DISABLED;
541 
542 	f->private_data = n;
543 
544 	return 0;
545 }
546 
vhost_net_disable_vq(struct vhost_net * n,struct vhost_virtqueue * vq)547 static void vhost_net_disable_vq(struct vhost_net *n,
548 				 struct vhost_virtqueue *vq)
549 {
550 	if (!vq->private_data)
551 		return;
552 	if (vq == n->vqs + VHOST_NET_VQ_TX) {
553 		tx_poll_stop(n);
554 		n->tx_poll_state = VHOST_NET_POLL_DISABLED;
555 	} else
556 		vhost_poll_stop(n->poll + VHOST_NET_VQ_RX);
557 }
558 
vhost_net_enable_vq(struct vhost_net * n,struct vhost_virtqueue * vq)559 static void vhost_net_enable_vq(struct vhost_net *n,
560 				struct vhost_virtqueue *vq)
561 {
562 	struct socket *sock;
563 
564 	sock = rcu_dereference_protected(vq->private_data,
565 					 lockdep_is_held(&vq->mutex));
566 	if (!sock)
567 		return;
568 	if (vq == n->vqs + VHOST_NET_VQ_TX) {
569 		n->tx_poll_state = VHOST_NET_POLL_STOPPED;
570 		tx_poll_start(n, sock);
571 	} else
572 		vhost_poll_start(n->poll + VHOST_NET_VQ_RX, sock->file);
573 }
574 
vhost_net_stop_vq(struct vhost_net * n,struct vhost_virtqueue * vq)575 static struct socket *vhost_net_stop_vq(struct vhost_net *n,
576 					struct vhost_virtqueue *vq)
577 {
578 	struct socket *sock;
579 
580 	mutex_lock(&vq->mutex);
581 	sock = rcu_dereference_protected(vq->private_data,
582 					 lockdep_is_held(&vq->mutex));
583 	vhost_net_disable_vq(n, vq);
584 	rcu_assign_pointer(vq->private_data, NULL);
585 	mutex_unlock(&vq->mutex);
586 	return sock;
587 }
588 
vhost_net_stop(struct vhost_net * n,struct socket ** tx_sock,struct socket ** rx_sock)589 static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock,
590 			   struct socket **rx_sock)
591 {
592 	*tx_sock = vhost_net_stop_vq(n, n->vqs + VHOST_NET_VQ_TX);
593 	*rx_sock = vhost_net_stop_vq(n, n->vqs + VHOST_NET_VQ_RX);
594 }
595 
vhost_net_flush_vq(struct vhost_net * n,int index)596 static void vhost_net_flush_vq(struct vhost_net *n, int index)
597 {
598 	vhost_poll_flush(n->poll + index);
599 	vhost_poll_flush(&n->dev.vqs[index].poll);
600 }
601 
vhost_net_flush(struct vhost_net * n)602 static void vhost_net_flush(struct vhost_net *n)
603 {
604 	vhost_net_flush_vq(n, VHOST_NET_VQ_TX);
605 	vhost_net_flush_vq(n, VHOST_NET_VQ_RX);
606 }
607 
vhost_net_release(struct inode * inode,struct file * f)608 static int vhost_net_release(struct inode *inode, struct file *f)
609 {
610 	struct vhost_net *n = f->private_data;
611 	struct socket *tx_sock;
612 	struct socket *rx_sock;
613 
614 	vhost_net_stop(n, &tx_sock, &rx_sock);
615 	vhost_net_flush(n);
616 	vhost_dev_cleanup(&n->dev, false);
617 	if (tx_sock)
618 		fput(tx_sock->file);
619 	if (rx_sock)
620 		fput(rx_sock->file);
621 	/* We do an extra flush before freeing memory,
622 	 * since jobs can re-queue themselves. */
623 	vhost_net_flush(n);
624 	kfree(n);
625 	return 0;
626 }
627 
get_raw_socket(int fd)628 static struct socket *get_raw_socket(int fd)
629 {
630 	struct {
631 		struct sockaddr_ll sa;
632 		char  buf[MAX_ADDR_LEN];
633 	} uaddr;
634 	int uaddr_len = sizeof uaddr, r;
635 	struct socket *sock = sockfd_lookup(fd, &r);
636 
637 	if (!sock)
638 		return ERR_PTR(-ENOTSOCK);
639 
640 	/* Parameter checking */
641 	if (sock->sk->sk_type != SOCK_RAW) {
642 		r = -ESOCKTNOSUPPORT;
643 		goto err;
644 	}
645 
646 	r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa,
647 			       &uaddr_len, 0);
648 	if (r)
649 		goto err;
650 
651 	if (uaddr.sa.sll_family != AF_PACKET) {
652 		r = -EPFNOSUPPORT;
653 		goto err;
654 	}
655 	return sock;
656 err:
657 	fput(sock->file);
658 	return ERR_PTR(r);
659 }
660 
get_tap_socket(int fd)661 static struct socket *get_tap_socket(int fd)
662 {
663 	struct file *file = fget(fd);
664 	struct socket *sock;
665 
666 	if (!file)
667 		return ERR_PTR(-EBADF);
668 	sock = tun_get_socket(file);
669 	if (!IS_ERR(sock))
670 		return sock;
671 	sock = macvtap_get_socket(file);
672 	if (IS_ERR(sock))
673 		fput(file);
674 	return sock;
675 }
676 
get_socket(int fd)677 static struct socket *get_socket(int fd)
678 {
679 	struct socket *sock;
680 
681 	/* special case to disable backend */
682 	if (fd == -1)
683 		return NULL;
684 	sock = get_raw_socket(fd);
685 	if (!IS_ERR(sock))
686 		return sock;
687 	sock = get_tap_socket(fd);
688 	if (!IS_ERR(sock))
689 		return sock;
690 	return ERR_PTR(-ENOTSOCK);
691 }
692 
vhost_net_set_backend(struct vhost_net * n,unsigned index,int fd)693 static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
694 {
695 	struct socket *sock, *oldsock;
696 	struct vhost_virtqueue *vq;
697 	struct vhost_ubuf_ref *ubufs, *oldubufs = NULL;
698 	int r;
699 
700 	mutex_lock(&n->dev.mutex);
701 	r = vhost_dev_check_owner(&n->dev);
702 	if (r)
703 		goto err;
704 
705 	if (index >= VHOST_NET_VQ_MAX) {
706 		r = -ENOBUFS;
707 		goto err;
708 	}
709 	vq = n->vqs + index;
710 	mutex_lock(&vq->mutex);
711 
712 	/* Verify that ring has been setup correctly. */
713 	if (!vhost_vq_access_ok(vq)) {
714 		r = -EFAULT;
715 		goto err_vq;
716 	}
717 	sock = get_socket(fd);
718 	if (IS_ERR(sock)) {
719 		r = PTR_ERR(sock);
720 		goto err_vq;
721 	}
722 
723 	/* start polling new socket */
724 	oldsock = rcu_dereference_protected(vq->private_data,
725 					    lockdep_is_held(&vq->mutex));
726 	if (sock != oldsock) {
727 		ubufs = vhost_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock));
728 		if (IS_ERR(ubufs)) {
729 			r = PTR_ERR(ubufs);
730 			goto err_ubufs;
731 		}
732 		oldubufs = vq->ubufs;
733 		vq->ubufs = ubufs;
734 		vhost_net_disable_vq(n, vq);
735 		rcu_assign_pointer(vq->private_data, sock);
736 		vhost_net_enable_vq(n, vq);
737 
738 		r = vhost_init_used(vq);
739 		if (r)
740 			goto err_vq;
741 	}
742 
743 	mutex_unlock(&vq->mutex);
744 
745 	if (oldubufs) {
746 		vhost_ubuf_put_and_wait(oldubufs);
747 		mutex_lock(&vq->mutex);
748 		vhost_zerocopy_signal_used(vq);
749 		mutex_unlock(&vq->mutex);
750 	}
751 
752 	if (oldsock) {
753 		vhost_net_flush_vq(n, index);
754 		fput(oldsock->file);
755 	}
756 
757 	mutex_unlock(&n->dev.mutex);
758 	return 0;
759 
760 err_ubufs:
761 	fput(sock->file);
762 err_vq:
763 	mutex_unlock(&vq->mutex);
764 err:
765 	mutex_unlock(&n->dev.mutex);
766 	return r;
767 }
768 
vhost_net_reset_owner(struct vhost_net * n)769 static long vhost_net_reset_owner(struct vhost_net *n)
770 {
771 	struct socket *tx_sock = NULL;
772 	struct socket *rx_sock = NULL;
773 	long err;
774 
775 	mutex_lock(&n->dev.mutex);
776 	err = vhost_dev_check_owner(&n->dev);
777 	if (err)
778 		goto done;
779 	vhost_net_stop(n, &tx_sock, &rx_sock);
780 	vhost_net_flush(n);
781 	err = vhost_dev_reset_owner(&n->dev);
782 done:
783 	mutex_unlock(&n->dev.mutex);
784 	if (tx_sock)
785 		fput(tx_sock->file);
786 	if (rx_sock)
787 		fput(rx_sock->file);
788 	return err;
789 }
790 
vhost_net_set_features(struct vhost_net * n,u64 features)791 static int vhost_net_set_features(struct vhost_net *n, u64 features)
792 {
793 	size_t vhost_hlen, sock_hlen, hdr_len;
794 	int i;
795 
796 	hdr_len = (features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ?
797 			sizeof(struct virtio_net_hdr_mrg_rxbuf) :
798 			sizeof(struct virtio_net_hdr);
799 	if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) {
800 		/* vhost provides vnet_hdr */
801 		vhost_hlen = hdr_len;
802 		sock_hlen = 0;
803 	} else {
804 		/* socket provides vnet_hdr */
805 		vhost_hlen = 0;
806 		sock_hlen = hdr_len;
807 	}
808 	mutex_lock(&n->dev.mutex);
809 	if ((features & (1 << VHOST_F_LOG_ALL)) &&
810 	    !vhost_log_access_ok(&n->dev)) {
811 		mutex_unlock(&n->dev.mutex);
812 		return -EFAULT;
813 	}
814 	n->dev.acked_features = features;
815 	smp_wmb();
816 	for (i = 0; i < VHOST_NET_VQ_MAX; ++i) {
817 		mutex_lock(&n->vqs[i].mutex);
818 		n->vqs[i].vhost_hlen = vhost_hlen;
819 		n->vqs[i].sock_hlen = sock_hlen;
820 		mutex_unlock(&n->vqs[i].mutex);
821 	}
822 	vhost_net_flush(n);
823 	mutex_unlock(&n->dev.mutex);
824 	return 0;
825 }
826 
vhost_net_ioctl(struct file * f,unsigned int ioctl,unsigned long arg)827 static long vhost_net_ioctl(struct file *f, unsigned int ioctl,
828 			    unsigned long arg)
829 {
830 	struct vhost_net *n = f->private_data;
831 	void __user *argp = (void __user *)arg;
832 	u64 __user *featurep = argp;
833 	struct vhost_vring_file backend;
834 	u64 features;
835 	int r;
836 
837 	switch (ioctl) {
838 	case VHOST_NET_SET_BACKEND:
839 		if (copy_from_user(&backend, argp, sizeof backend))
840 			return -EFAULT;
841 		return vhost_net_set_backend(n, backend.index, backend.fd);
842 	case VHOST_GET_FEATURES:
843 		features = VHOST_FEATURES;
844 		if (copy_to_user(featurep, &features, sizeof features))
845 			return -EFAULT;
846 		return 0;
847 	case VHOST_SET_FEATURES:
848 		if (copy_from_user(&features, featurep, sizeof features))
849 			return -EFAULT;
850 		if (features & ~VHOST_FEATURES)
851 			return -EOPNOTSUPP;
852 		return vhost_net_set_features(n, features);
853 	case VHOST_RESET_OWNER:
854 		return vhost_net_reset_owner(n);
855 	default:
856 		mutex_lock(&n->dev.mutex);
857 		r = vhost_dev_ioctl(&n->dev, ioctl, arg);
858 		vhost_net_flush(n);
859 		mutex_unlock(&n->dev.mutex);
860 		return r;
861 	}
862 }
863 
864 #ifdef CONFIG_COMPAT
vhost_net_compat_ioctl(struct file * f,unsigned int ioctl,unsigned long arg)865 static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl,
866 				   unsigned long arg)
867 {
868 	return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg));
869 }
870 #endif
871 
872 static const struct file_operations vhost_net_fops = {
873 	.owner          = THIS_MODULE,
874 	.release        = vhost_net_release,
875 	.unlocked_ioctl = vhost_net_ioctl,
876 #ifdef CONFIG_COMPAT
877 	.compat_ioctl   = vhost_net_compat_ioctl,
878 #endif
879 	.open           = vhost_net_open,
880 	.llseek		= noop_llseek,
881 };
882 
883 static struct miscdevice vhost_net_misc = {
884 	.minor = VHOST_NET_MINOR,
885 	.name = "vhost-net",
886 	.fops = &vhost_net_fops,
887 };
888 
vhost_net_init(void)889 static int vhost_net_init(void)
890 {
891 	if (experimental_zcopytx)
892 		vhost_enable_zcopy(VHOST_NET_VQ_TX);
893 	return misc_register(&vhost_net_misc);
894 }
895 module_init(vhost_net_init);
896 
vhost_net_exit(void)897 static void vhost_net_exit(void)
898 {
899 	misc_deregister(&vhost_net_misc);
900 }
901 module_exit(vhost_net_exit);
902 
903 MODULE_VERSION("0.0.1");
904 MODULE_LICENSE("GPL v2");
905 MODULE_AUTHOR("Michael S. Tsirkin");
906 MODULE_DESCRIPTION("Host kernel accelerator for virtio net");
907 MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR);
908 MODULE_ALIAS("devname:vhost-net");
909