xref: /kvmtool/virtio/net.c (revision 8ed60bbe615309b2220b4c36db7a50e3f9a9d4b0)
1 #include "kvm/virtio-pci-dev.h"
2 #include "kvm/virtio-net.h"
3 #include "kvm/virtio.h"
4 #include "kvm/types.h"
5 #include "kvm/mutex.h"
6 #include "kvm/util.h"
7 #include "kvm/kvm.h"
8 #include "kvm/irq.h"
9 #include "kvm/uip.h"
10 #include "kvm/guest_compat.h"
11 #include "kvm/iovec.h"
12 
13 #include <linux/vhost.h>
14 #include <linux/virtio_net.h>
15 #include <linux/if_tun.h>
16 #include <linux/types.h>
17 
18 #include <arpa/inet.h>
19 #include <net/if.h>
20 
21 #include <unistd.h>
22 #include <fcntl.h>
23 
24 #include <sys/socket.h>
25 #include <sys/ioctl.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <sys/eventfd.h>
29 
30 #define VIRTIO_NET_QUEUE_SIZE		256
31 #define VIRTIO_NET_NUM_QUEUES		8
32 
33 struct net_dev;
34 
35 struct net_dev_operations {
36 	int (*rx)(struct iovec *iov, u16 in, struct net_dev *ndev);
37 	int (*tx)(struct iovec *iov, u16 in, struct net_dev *ndev);
38 };
39 
40 struct net_dev {
41 	struct mutex			mutex;
42 	struct virtio_device		vdev;
43 	struct list_head		list;
44 
45 	struct virt_queue		vqs[VIRTIO_NET_NUM_QUEUES * 2 + 1];
46 	struct virtio_net_config	config;
47 	u32				features, rx_vqs, tx_vqs, queue_pairs;
48 
49 	pthread_t			io_thread[VIRTIO_NET_NUM_QUEUES * 2 + 1];
50 	struct mutex			io_lock[VIRTIO_NET_NUM_QUEUES * 2 + 1];
51 	pthread_cond_t			io_cond[VIRTIO_NET_NUM_QUEUES * 2 + 1];
52 
53 	int				vhost_fd;
54 	int				tap_fd;
55 	char				tap_name[IFNAMSIZ];
56 
57 	int				mode;
58 
59 	struct uip_info			info;
60 	struct net_dev_operations	*ops;
61 	struct kvm			*kvm;
62 
63 	struct virtio_net_params	*params;
64 };
65 
66 static LIST_HEAD(ndevs);
67 static int compat_id = -1;
68 
69 #define MAX_PACKET_SIZE 65550
70 
71 static bool has_virtio_feature(struct net_dev *ndev, u32 feature)
72 {
73 	return ndev->features & (1 << feature);
74 }
75 
76 static void virtio_net_fix_tx_hdr(struct virtio_net_hdr *hdr, struct net_dev *ndev)
77 {
78 	hdr->hdr_len		= virtio_guest_to_host_u16(&ndev->vdev, hdr->hdr_len);
79 	hdr->gso_size		= virtio_guest_to_host_u16(&ndev->vdev, hdr->gso_size);
80 	hdr->csum_start		= virtio_guest_to_host_u16(&ndev->vdev, hdr->csum_start);
81 	hdr->csum_offset	= virtio_guest_to_host_u16(&ndev->vdev, hdr->csum_offset);
82 }
83 
84 static void virtio_net_fix_rx_hdr(struct virtio_net_hdr_mrg_rxbuf *hdr, struct net_dev *ndev)
85 {
86 	hdr->hdr.hdr_len	= virtio_host_to_guest_u16(&ndev->vdev, hdr->hdr.hdr_len);
87 	hdr->hdr.gso_size	= virtio_host_to_guest_u16(&ndev->vdev, hdr->hdr.gso_size);
88 	hdr->hdr.csum_start	= virtio_host_to_guest_u16(&ndev->vdev, hdr->hdr.csum_start);
89 	hdr->hdr.csum_offset	= virtio_host_to_guest_u16(&ndev->vdev, hdr->hdr.csum_offset);
90 	if (has_virtio_feature(ndev, VIRTIO_NET_F_MRG_RXBUF))
91 		hdr->num_buffers	= virtio_host_to_guest_u16(&ndev->vdev, hdr->num_buffers);
92 }
93 
94 static void *virtio_net_rx_thread(void *p)
95 {
96 	struct iovec iov[VIRTIO_NET_QUEUE_SIZE];
97 	struct virt_queue *vq;
98 	struct kvm *kvm;
99 	struct net_dev *ndev = p;
100 	u16 out, in;
101 	u16 head;
102 	int len, copied;
103 	u32 id;
104 
105 	mutex_lock(&ndev->mutex);
106 	id = ndev->rx_vqs++ * 2;
107 	mutex_unlock(&ndev->mutex);
108 
109 	kvm__set_thread_name("virtio-net-rx");
110 
111 	kvm = ndev->kvm;
112 	vq = &ndev->vqs[id];
113 
114 	while (1) {
115 		mutex_lock(&ndev->io_lock[id]);
116 		if (!virt_queue__available(vq))
117 			pthread_cond_wait(&ndev->io_cond[id], &ndev->io_lock[id].mutex);
118 		mutex_unlock(&ndev->io_lock[id]);
119 
120 		while (virt_queue__available(vq)) {
121 			unsigned char buffer[MAX_PACKET_SIZE + sizeof(struct virtio_net_hdr_mrg_rxbuf)];
122 			struct iovec dummy_iov = {
123 				.iov_base = buffer,
124 				.iov_len  = sizeof(buffer),
125 			};
126 			struct virtio_net_hdr_mrg_rxbuf *hdr;
127 			int i;
128 
129 			len = ndev->ops->rx(&dummy_iov, 1, ndev);
130 			if (len < 0) {
131 				pr_warning("%s: rx on vq %u failed (%d), exiting thread\n",
132 						__func__, id, len);
133 				goto out_err;
134 			}
135 
136 			copied = i = 0;
137 			head = virt_queue__get_iov(vq, iov, &out, &in, kvm);
138 			hdr = iov[0].iov_base;
139 			while (copied < len) {
140 				size_t iovsize = min_t(size_t, len - copied, iov_size(iov, in));
141 
142 				memcpy_toiovec(iov, buffer + copied, iovsize);
143 				copied += iovsize;
144 				if (i++ == 0)
145 					virtio_net_fix_rx_hdr(hdr, ndev);
146 				if (has_virtio_feature(ndev, VIRTIO_NET_F_MRG_RXBUF)) {
147 					u16 num_buffers = virtio_guest_to_host_u16(vq, hdr->num_buffers);
148 					hdr->num_buffers = virtio_host_to_guest_u16(vq, num_buffers + 1);
149 				}
150 				virt_queue__set_used_elem(vq, head, iovsize);
151 				if (copied == len)
152 					break;
153 				while (!virt_queue__available(vq))
154 					sleep(0);
155 				head = virt_queue__get_iov(vq, iov, &out, &in, kvm);
156 			}
157 			/* We should interrupt guest right now, otherwise latency is huge. */
158 			if (virtio_queue__should_signal(vq))
159 				ndev->vdev.ops->signal_vq(kvm, &ndev->vdev, id);
160 		}
161 	}
162 
163 out_err:
164 	pthread_exit(NULL);
165 	return NULL;
166 
167 }
168 
169 static void *virtio_net_tx_thread(void *p)
170 {
171 	struct iovec iov[VIRTIO_NET_QUEUE_SIZE];
172 	struct virt_queue *vq;
173 	struct kvm *kvm;
174 	struct net_dev *ndev = p;
175 	u16 out, in;
176 	u16 head;
177 	int len;
178 	u32 id;
179 
180 	mutex_lock(&ndev->mutex);
181 	id = ndev->tx_vqs++ * 2 + 1;
182 	mutex_unlock(&ndev->mutex);
183 
184 	kvm__set_thread_name("virtio-net-tx");
185 
186 	kvm = ndev->kvm;
187 	vq = &ndev->vqs[id];
188 
189 	while (1) {
190 		mutex_lock(&ndev->io_lock[id]);
191 		if (!virt_queue__available(vq))
192 			pthread_cond_wait(&ndev->io_cond[id], &ndev->io_lock[id].mutex);
193 		mutex_unlock(&ndev->io_lock[id]);
194 
195 		while (virt_queue__available(vq)) {
196 			struct virtio_net_hdr *hdr;
197 			head = virt_queue__get_iov(vq, iov, &out, &in, kvm);
198 			hdr = iov[0].iov_base;
199 			virtio_net_fix_tx_hdr(hdr, ndev);
200 			len = ndev->ops->tx(iov, out, ndev);
201 			if (len < 0) {
202 				pr_warning("%s: tx on vq %u failed (%d)\n",
203 						__func__, id, errno);
204 				goto out_err;
205 			}
206 
207 			virt_queue__set_used_elem(vq, head, len);
208 		}
209 
210 		if (virtio_queue__should_signal(vq))
211 			ndev->vdev.ops->signal_vq(kvm, &ndev->vdev, id);
212 	}
213 
214 out_err:
215 	pthread_exit(NULL);
216 	return NULL;
217 }
218 
219 static virtio_net_ctrl_ack virtio_net_handle_mq(struct kvm* kvm, struct net_dev *ndev, struct virtio_net_ctrl_hdr *ctrl)
220 {
221 	/* Not much to do here */
222 	return VIRTIO_NET_OK;
223 }
224 
225 static void *virtio_net_ctrl_thread(void *p)
226 {
227 	struct iovec iov[VIRTIO_NET_QUEUE_SIZE];
228 	u16 out, in, head;
229 	struct net_dev *ndev = p;
230 	struct kvm *kvm = ndev->kvm;
231 	u32 id = ndev->queue_pairs * 2;
232 	struct virt_queue *vq = &ndev->vqs[id];
233 	struct virtio_net_ctrl_hdr *ctrl;
234 	virtio_net_ctrl_ack *ack;
235 
236 	while (1) {
237 		mutex_lock(&ndev->io_lock[id]);
238 		if (!virt_queue__available(vq))
239 			pthread_cond_wait(&ndev->io_cond[id], &ndev->io_lock[id].mutex);
240 		mutex_unlock(&ndev->io_lock[id]);
241 
242 		while (virt_queue__available(vq)) {
243 			head = virt_queue__get_iov(&ndev->vqs[id], iov, &out, &in, kvm);
244 			ctrl = iov[0].iov_base;
245 			ack = iov[out].iov_base;
246 
247 			switch (ctrl->class) {
248 			case VIRTIO_NET_CTRL_MQ:
249 				*ack = virtio_net_handle_mq(kvm, ndev, ctrl);
250 				break;
251 			default:
252 				*ack = VIRTIO_NET_ERR;
253 				break;
254 			}
255 			virt_queue__set_used_elem(&ndev->vqs[id], head, iov[out].iov_len);
256 		}
257 
258 		if (virtio_queue__should_signal(&ndev->vqs[id]))
259 			ndev->vdev.ops->signal_vq(kvm, &ndev->vdev, id);
260 	}
261 
262 	pthread_exit(NULL);
263 
264 	return NULL;
265 }
266 
267 static void virtio_net_handle_callback(struct kvm *kvm, struct net_dev *ndev, int queue)
268 {
269 	if ((u32)queue >= (ndev->queue_pairs * 2 + 1)) {
270 		pr_warning("Unknown queue index %u", queue);
271 		return;
272 	}
273 
274 	mutex_lock(&ndev->io_lock[queue]);
275 	pthread_cond_signal(&ndev->io_cond[queue]);
276 	mutex_unlock(&ndev->io_lock[queue]);
277 }
278 
279 static bool virtio_net__tap_init(struct net_dev *ndev)
280 {
281 	int sock = socket(AF_INET, SOCK_STREAM, 0);
282 	int pid, status, offload, hdr_len;
283 	struct sockaddr_in sin = {0};
284 	struct ifreq ifr;
285 	const struct virtio_net_params *params = ndev->params;
286 	bool skipconf = !!params->tapif;
287 
288 	/* Did the user already gave us the FD? */
289 	if (params->fd) {
290 		ndev->tap_fd = params->fd;
291 		return 1;
292 	}
293 
294 	ndev->tap_fd = open("/dev/net/tun", O_RDWR);
295 	if (ndev->tap_fd < 0) {
296 		pr_warning("Unable to open /dev/net/tun");
297 		goto fail;
298 	}
299 
300 	memset(&ifr, 0, sizeof(ifr));
301 	ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
302 	if (params->tapif)
303 		strncpy(ifr.ifr_name, params->tapif, sizeof(ifr.ifr_name));
304 	if (ioctl(ndev->tap_fd, TUNSETIFF, &ifr) < 0) {
305 		pr_warning("Config tap device error. Are you root?");
306 		goto fail;
307 	}
308 
309 	strncpy(ndev->tap_name, ifr.ifr_name, sizeof(ndev->tap_name));
310 
311 	if (ioctl(ndev->tap_fd, TUNSETNOCSUM, 1) < 0) {
312 		pr_warning("Config tap device TUNSETNOCSUM error");
313 		goto fail;
314 	}
315 
316 	hdr_len = has_virtio_feature(ndev, VIRTIO_NET_F_MRG_RXBUF) ?
317 			sizeof(struct virtio_net_hdr_mrg_rxbuf) :
318 			sizeof(struct virtio_net_hdr);
319 	if (ioctl(ndev->tap_fd, TUNSETVNETHDRSZ, &hdr_len) < 0)
320 		pr_warning("Config tap device TUNSETVNETHDRSZ error");
321 
322 	offload = TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 | TUN_F_UFO;
323 	if (ioctl(ndev->tap_fd, TUNSETOFFLOAD, offload) < 0) {
324 		pr_warning("Config tap device TUNSETOFFLOAD error");
325 		goto fail;
326 	}
327 
328 	if (strcmp(params->script, "none")) {
329 		pid = fork();
330 		if (pid == 0) {
331 			execl(params->script, params->script, ndev->tap_name, NULL);
332 			_exit(1);
333 		} else {
334 			waitpid(pid, &status, 0);
335 			if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
336 				pr_warning("Fail to setup tap by %s", params->script);
337 				goto fail;
338 			}
339 		}
340 	} else if (!skipconf) {
341 		memset(&ifr, 0, sizeof(ifr));
342 		strncpy(ifr.ifr_name, ndev->tap_name, sizeof(ndev->tap_name));
343 		sin.sin_addr.s_addr = inet_addr(params->host_ip);
344 		memcpy(&(ifr.ifr_addr), &sin, sizeof(ifr.ifr_addr));
345 		ifr.ifr_addr.sa_family = AF_INET;
346 		if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) {
347 			pr_warning("Could not set ip address on tap device");
348 			goto fail;
349 		}
350 	}
351 
352 	if (!skipconf) {
353 		memset(&ifr, 0, sizeof(ifr));
354 		strncpy(ifr.ifr_name, ndev->tap_name, sizeof(ndev->tap_name));
355 		ioctl(sock, SIOCGIFFLAGS, &ifr);
356 		ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
357 		if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0)
358 			pr_warning("Could not bring tap device up");
359 	}
360 
361 	close(sock);
362 
363 	return 1;
364 
365 fail:
366 	if (sock >= 0)
367 		close(sock);
368 	if (ndev->tap_fd >= 0)
369 		close(ndev->tap_fd);
370 
371 	return 0;
372 }
373 
374 static inline int tap_ops_tx(struct iovec *iov, u16 out, struct net_dev *ndev)
375 {
376 	return writev(ndev->tap_fd, iov, out);
377 }
378 
379 static inline int tap_ops_rx(struct iovec *iov, u16 in, struct net_dev *ndev)
380 {
381 	return readv(ndev->tap_fd, iov, in);
382 }
383 
384 static inline int uip_ops_tx(struct iovec *iov, u16 out, struct net_dev *ndev)
385 {
386 	return uip_tx(iov, out, &ndev->info);
387 }
388 
389 static inline int uip_ops_rx(struct iovec *iov, u16 in, struct net_dev *ndev)
390 {
391 	return uip_rx(iov, in, &ndev->info);
392 }
393 
394 static struct net_dev_operations tap_ops = {
395 	.rx	= tap_ops_rx,
396 	.tx	= tap_ops_tx,
397 };
398 
399 static struct net_dev_operations uip_ops = {
400 	.rx	= uip_ops_rx,
401 	.tx	= uip_ops_tx,
402 };
403 
404 static u8 *get_config(struct kvm *kvm, void *dev)
405 {
406 	struct net_dev *ndev = dev;
407 
408 	return ((u8 *)(&ndev->config));
409 }
410 
411 static u32 get_host_features(struct kvm *kvm, void *dev)
412 {
413 	struct net_dev *ndev = dev;
414 
415 	return 1UL << VIRTIO_NET_F_MAC
416 		| 1UL << VIRTIO_NET_F_CSUM
417 		| 1UL << VIRTIO_NET_F_HOST_UFO
418 		| 1UL << VIRTIO_NET_F_HOST_TSO4
419 		| 1UL << VIRTIO_NET_F_HOST_TSO6
420 		| 1UL << VIRTIO_NET_F_GUEST_UFO
421 		| 1UL << VIRTIO_NET_F_GUEST_TSO4
422 		| 1UL << VIRTIO_NET_F_GUEST_TSO6
423 		| 1UL << VIRTIO_RING_F_EVENT_IDX
424 		| 1UL << VIRTIO_RING_F_INDIRECT_DESC
425 		| 1UL << VIRTIO_NET_F_CTRL_VQ
426 		| 1UL << VIRTIO_NET_F_MRG_RXBUF
427 		| 1UL << (ndev->queue_pairs > 1 ? VIRTIO_NET_F_MQ : 0);
428 }
429 
430 static int virtio_net__vhost_set_features(struct net_dev *ndev)
431 {
432 	u64 features = 1UL << VIRTIO_RING_F_EVENT_IDX;
433 	u64 vhost_features;
434 
435 	if (ioctl(ndev->vhost_fd, VHOST_GET_FEATURES, &vhost_features) != 0)
436 		die_perror("VHOST_GET_FEATURES failed");
437 
438 	/* make sure both side support mergable rx buffers */
439 	if (vhost_features & 1UL << VIRTIO_NET_F_MRG_RXBUF &&
440 			has_virtio_feature(ndev, VIRTIO_NET_F_MRG_RXBUF))
441 		features |= 1UL << VIRTIO_NET_F_MRG_RXBUF;
442 
443 	return ioctl(ndev->vhost_fd, VHOST_SET_FEATURES, &features);
444 }
445 
446 static void set_guest_features(struct kvm *kvm, void *dev, u32 features)
447 {
448 	struct net_dev *ndev = dev;
449 	struct virtio_net_config *conf = &ndev->config;
450 
451 	ndev->features = features;
452 
453 	conf->status = virtio_host_to_guest_u16(&ndev->vdev, conf->status);
454 	conf->max_virtqueue_pairs = virtio_host_to_guest_u16(&ndev->vdev,
455 							     conf->max_virtqueue_pairs);
456 
457 	if (ndev->mode == NET_MODE_TAP) {
458 		if (!virtio_net__tap_init(ndev))
459 			die_perror("You have requested a TAP device, but creation of one has failed because");
460 		if (ndev->vhost_fd &&
461 				virtio_net__vhost_set_features(ndev) != 0)
462 			die_perror("VHOST_SET_FEATURES failed");
463 	} else {
464 		ndev->info.vnet_hdr_len = has_virtio_feature(ndev, VIRTIO_NET_F_MRG_RXBUF) ?
465 						sizeof(struct virtio_net_hdr_mrg_rxbuf) :
466 						sizeof(struct virtio_net_hdr);
467 		uip_init(&ndev->info);
468 	}
469 }
470 
471 static bool is_ctrl_vq(struct net_dev *ndev, u32 vq)
472 {
473 	return vq == (u32)(ndev->queue_pairs * 2);
474 }
475 
476 static int init_vq(struct kvm *kvm, void *dev, u32 vq, u32 page_size, u32 align,
477 		   u32 pfn)
478 {
479 	struct vhost_vring_state state = { .index = vq };
480 	struct vhost_vring_addr addr;
481 	struct net_dev *ndev = dev;
482 	struct virt_queue *queue;
483 	void *p;
484 	int r;
485 
486 	compat__remove_message(compat_id);
487 
488 	queue		= &ndev->vqs[vq];
489 	queue->pfn	= pfn;
490 	p		= virtio_get_vq(kvm, queue->pfn, page_size);
491 
492 	vring_init(&queue->vring, VIRTIO_NET_QUEUE_SIZE, p, align);
493 	virtio_init_device_vq(&ndev->vdev, queue);
494 
495 	mutex_init(&ndev->io_lock[vq]);
496 	pthread_cond_init(&ndev->io_cond[vq], NULL);
497 	if (is_ctrl_vq(ndev, vq)) {
498 		pthread_create(&ndev->io_thread[vq], NULL, virtio_net_ctrl_thread, ndev);
499 
500 		return 0;
501 	} else if (ndev->vhost_fd == 0 ) {
502 		if (vq & 1)
503 			pthread_create(&ndev->io_thread[vq], NULL, virtio_net_tx_thread, ndev);
504 		else
505 			pthread_create(&ndev->io_thread[vq], NULL, virtio_net_rx_thread, ndev);
506 
507 		return 0;
508 	}
509 
510 	if (queue->endian != VIRTIO_ENDIAN_HOST)
511 		die_perror("VHOST requires VIRTIO_ENDIAN_HOST");
512 
513 	state.num = queue->vring.num;
514 	r = ioctl(ndev->vhost_fd, VHOST_SET_VRING_NUM, &state);
515 	if (r < 0)
516 		die_perror("VHOST_SET_VRING_NUM failed");
517 	state.num = 0;
518 	r = ioctl(ndev->vhost_fd, VHOST_SET_VRING_BASE, &state);
519 	if (r < 0)
520 		die_perror("VHOST_SET_VRING_BASE failed");
521 
522 	addr = (struct vhost_vring_addr) {
523 		.index = vq,
524 		.desc_user_addr = (u64)(unsigned long)queue->vring.desc,
525 		.avail_user_addr = (u64)(unsigned long)queue->vring.avail,
526 		.used_user_addr = (u64)(unsigned long)queue->vring.used,
527 	};
528 
529 	r = ioctl(ndev->vhost_fd, VHOST_SET_VRING_ADDR, &addr);
530 	if (r < 0)
531 		die_perror("VHOST_SET_VRING_ADDR failed");
532 
533 	return 0;
534 }
535 
536 static void notify_vq_gsi(struct kvm *kvm, void *dev, u32 vq, u32 gsi)
537 {
538 	struct net_dev *ndev = dev;
539 	struct kvm_irqfd irq;
540 	struct vhost_vring_file file;
541 	int r;
542 
543 	if (ndev->vhost_fd == 0)
544 		return;
545 
546 	irq = (struct kvm_irqfd) {
547 		.gsi	= gsi,
548 		.fd	= eventfd(0, 0),
549 	};
550 	file = (struct vhost_vring_file) {
551 		.index	= vq,
552 		.fd	= irq.fd,
553 	};
554 
555 	r = ioctl(kvm->vm_fd, KVM_IRQFD, &irq);
556 	if (r < 0)
557 		die_perror("KVM_IRQFD failed");
558 
559 	r = ioctl(ndev->vhost_fd, VHOST_SET_VRING_CALL, &file);
560 	if (r < 0)
561 		die_perror("VHOST_SET_VRING_CALL failed");
562 	file.fd = ndev->tap_fd;
563 	r = ioctl(ndev->vhost_fd, VHOST_NET_SET_BACKEND, &file);
564 	if (r != 0)
565 		die("VHOST_NET_SET_BACKEND failed %d", errno);
566 
567 }
568 
569 static void notify_vq_eventfd(struct kvm *kvm, void *dev, u32 vq, u32 efd)
570 {
571 	struct net_dev *ndev = dev;
572 	struct vhost_vring_file file = {
573 		.index	= vq,
574 		.fd	= efd,
575 	};
576 	int r;
577 
578 	if (ndev->vhost_fd == 0 || is_ctrl_vq(ndev, vq))
579 		return;
580 
581 	r = ioctl(ndev->vhost_fd, VHOST_SET_VRING_KICK, &file);
582 	if (r < 0)
583 		die_perror("VHOST_SET_VRING_KICK failed");
584 }
585 
586 static int notify_vq(struct kvm *kvm, void *dev, u32 vq)
587 {
588 	struct net_dev *ndev = dev;
589 
590 	virtio_net_handle_callback(kvm, ndev, vq);
591 
592 	return 0;
593 }
594 
595 static int get_pfn_vq(struct kvm *kvm, void *dev, u32 vq)
596 {
597 	struct net_dev *ndev = dev;
598 
599 	return ndev->vqs[vq].pfn;
600 }
601 
602 static int get_size_vq(struct kvm *kvm, void *dev, u32 vq)
603 {
604 	/* FIXME: dynamic */
605 	return VIRTIO_NET_QUEUE_SIZE;
606 }
607 
608 static int set_size_vq(struct kvm *kvm, void *dev, u32 vq, int size)
609 {
610 	/* FIXME: dynamic */
611 	return size;
612 }
613 
614 static struct virtio_ops net_dev_virtio_ops = (struct virtio_ops) {
615 	.get_config		= get_config,
616 	.get_host_features	= get_host_features,
617 	.set_guest_features	= set_guest_features,
618 	.init_vq		= init_vq,
619 	.get_pfn_vq		= get_pfn_vq,
620 	.get_size_vq		= get_size_vq,
621 	.set_size_vq		= set_size_vq,
622 	.notify_vq		= notify_vq,
623 	.notify_vq_gsi		= notify_vq_gsi,
624 	.notify_vq_eventfd	= notify_vq_eventfd,
625 };
626 
627 static void virtio_net__vhost_init(struct kvm *kvm, struct net_dev *ndev)
628 {
629 	struct vhost_memory *mem;
630 	int r;
631 
632 	ndev->vhost_fd = open("/dev/vhost-net", O_RDWR);
633 	if (ndev->vhost_fd < 0)
634 		die_perror("Failed openning vhost-net device");
635 
636 	mem = calloc(1, sizeof(*mem) + sizeof(struct vhost_memory_region));
637 	if (mem == NULL)
638 		die("Failed allocating memory for vhost memory map");
639 
640 	mem->nregions = 1;
641 	mem->regions[0] = (struct vhost_memory_region) {
642 		.guest_phys_addr	= 0,
643 		.memory_size		= kvm->ram_size,
644 		.userspace_addr		= (unsigned long)kvm->ram_start,
645 	};
646 
647 	r = ioctl(ndev->vhost_fd, VHOST_SET_OWNER);
648 	if (r != 0)
649 		die_perror("VHOST_SET_OWNER failed");
650 
651 	r = ioctl(ndev->vhost_fd, VHOST_SET_MEM_TABLE, mem);
652 	if (r != 0)
653 		die_perror("VHOST_SET_MEM_TABLE failed");
654 
655 	ndev->vdev.use_vhost = true;
656 
657 	free(mem);
658 }
659 
660 static inline void str_to_mac(const char *str, char *mac)
661 {
662 	sscanf(str, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
663 		mac, mac+1, mac+2, mac+3, mac+4, mac+5);
664 }
665 static int set_net_param(struct kvm *kvm, struct virtio_net_params *p,
666 			const char *param, const char *val)
667 {
668 	if (strcmp(param, "guest_mac") == 0) {
669 		str_to_mac(val, p->guest_mac);
670 	} else if (strcmp(param, "mode") == 0) {
671 		if (!strncmp(val, "user", 4)) {
672 			int i;
673 
674 			for (i = 0; i < kvm->cfg.num_net_devices; i++)
675 				if (kvm->cfg.net_params[i].mode == NET_MODE_USER)
676 					die("Only one usermode network device allowed at a time");
677 			p->mode = NET_MODE_USER;
678 		} else if (!strncmp(val, "tap", 3)) {
679 			p->mode = NET_MODE_TAP;
680 		} else if (!strncmp(val, "none", 4)) {
681 			kvm->cfg.no_net = 1;
682 			return -1;
683 		} else
684 			die("Unknown network mode %s, please use user, tap or none", kvm->cfg.network);
685 	} else if (strcmp(param, "script") == 0) {
686 		p->script = strdup(val);
687 	} else if (strcmp(param, "guest_ip") == 0) {
688 		p->guest_ip = strdup(val);
689 	} else if (strcmp(param, "host_ip") == 0) {
690 		p->host_ip = strdup(val);
691 	} else if (strcmp(param, "trans") == 0) {
692 		p->trans = strdup(val);
693 	} else if (strcmp(param, "tapif") == 0) {
694 		p->tapif = strdup(val);
695 	} else if (strcmp(param, "vhost") == 0) {
696 		p->vhost = atoi(val);
697 	} else if (strcmp(param, "fd") == 0) {
698 		p->fd = atoi(val);
699 	} else if (strcmp(param, "mq") == 0) {
700 		p->mq = atoi(val);
701 	} else
702 		die("Unknown network parameter %s", param);
703 
704 	return 0;
705 }
706 
707 int netdev_parser(const struct option *opt, const char *arg, int unset)
708 {
709 	struct virtio_net_params p;
710 	char *buf = NULL, *cmd = NULL, *cur = NULL;
711 	bool on_cmd = true;
712 	struct kvm *kvm = opt->ptr;
713 
714 	if (arg) {
715 		buf = strdup(arg);
716 		if (buf == NULL)
717 			die("Failed allocating new net buffer");
718 		cur = strtok(buf, ",=");
719 	}
720 
721 	p = (struct virtio_net_params) {
722 		.guest_ip	= DEFAULT_GUEST_ADDR,
723 		.host_ip	= DEFAULT_HOST_ADDR,
724 		.script		= DEFAULT_SCRIPT,
725 		.mode		= NET_MODE_TAP,
726 	};
727 
728 	str_to_mac(DEFAULT_GUEST_MAC, p.guest_mac);
729 	p.guest_mac[5] += kvm->cfg.num_net_devices;
730 
731 	while (cur) {
732 		if (on_cmd) {
733 			cmd = cur;
734 		} else {
735 			if (set_net_param(kvm, &p, cmd, cur) < 0)
736 				goto done;
737 		}
738 		on_cmd = !on_cmd;
739 
740 		cur = strtok(NULL, ",=");
741 	};
742 
743 	kvm->cfg.num_net_devices++;
744 
745 	kvm->cfg.net_params = realloc(kvm->cfg.net_params, kvm->cfg.num_net_devices * sizeof(*kvm->cfg.net_params));
746 	if (kvm->cfg.net_params == NULL)
747 		die("Failed adding new network device");
748 
749 	kvm->cfg.net_params[kvm->cfg.num_net_devices - 1] = p;
750 
751 done:
752 	free(buf);
753 	return 0;
754 }
755 
756 static int virtio_net__init_one(struct virtio_net_params *params)
757 {
758 	int i, err;
759 	struct net_dev *ndev;
760 	struct virtio_ops *ops;
761 
762 	ndev = calloc(1, sizeof(struct net_dev));
763 	if (ndev == NULL)
764 		return -ENOMEM;
765 
766 	ops = malloc(sizeof(*ops));
767 	if (ops == NULL) {
768 		err = -ENOMEM;
769 		goto err_free_ndev;
770 	}
771 
772 	list_add_tail(&ndev->list, &ndevs);
773 
774 	ndev->kvm = params->kvm;
775 	ndev->params = params;
776 
777 	mutex_init(&ndev->mutex);
778 	ndev->queue_pairs = max(1, min(VIRTIO_NET_NUM_QUEUES, params->mq));
779 	ndev->config.status = VIRTIO_NET_S_LINK_UP;
780 	if (ndev->queue_pairs > 1)
781 		ndev->config.max_virtqueue_pairs = ndev->queue_pairs;
782 
783 	for (i = 0 ; i < 6 ; i++) {
784 		ndev->config.mac[i]		= params->guest_mac[i];
785 		ndev->info.guest_mac.addr[i]	= params->guest_mac[i];
786 		ndev->info.host_mac.addr[i]	= params->host_mac[i];
787 	}
788 
789 	ndev->mode = params->mode;
790 	if (ndev->mode == NET_MODE_TAP) {
791 		ndev->ops = &tap_ops;
792 	} else {
793 		ndev->info.host_ip		= ntohl(inet_addr(params->host_ip));
794 		ndev->info.guest_ip		= ntohl(inet_addr(params->guest_ip));
795 		ndev->info.guest_netmask	= ntohl(inet_addr("255.255.255.0"));
796 		ndev->info.buf_nr		= 20,
797 		ndev->ops = &uip_ops;
798 		uip_static_init(&ndev->info);
799 	}
800 
801 	*ops = net_dev_virtio_ops;
802 	if (params->trans && strcmp(params->trans, "mmio") == 0)
803 		virtio_init(params->kvm, ndev, &ndev->vdev, ops, VIRTIO_MMIO,
804 			    PCI_DEVICE_ID_VIRTIO_NET, VIRTIO_ID_NET, PCI_CLASS_NET);
805 	else
806 		virtio_init(params->kvm, ndev, &ndev->vdev, ops, VIRTIO_PCI,
807 			    PCI_DEVICE_ID_VIRTIO_NET, VIRTIO_ID_NET, PCI_CLASS_NET);
808 
809 	if (params->vhost)
810 		virtio_net__vhost_init(params->kvm, ndev);
811 
812 	if (compat_id == -1)
813 		compat_id = virtio_compat_add_message("virtio-net", "CONFIG_VIRTIO_NET");
814 
815 	return 0;
816 
817 err_free_ndev:
818 	free(ndev);
819 	return err;
820 }
821 
822 int virtio_net__init(struct kvm *kvm)
823 {
824 	int i;
825 
826 	for (i = 0; i < kvm->cfg.num_net_devices; i++) {
827 		kvm->cfg.net_params[i].kvm = kvm;
828 		virtio_net__init_one(&kvm->cfg.net_params[i]);
829 	}
830 
831 	if (kvm->cfg.num_net_devices == 0 && kvm->cfg.no_net == 0) {
832 		static struct virtio_net_params net_params;
833 
834 		net_params = (struct virtio_net_params) {
835 			.guest_ip	= kvm->cfg.guest_ip,
836 			.host_ip	= kvm->cfg.host_ip,
837 			.kvm		= kvm,
838 			.script		= kvm->cfg.script,
839 			.mode		= NET_MODE_USER,
840 		};
841 		str_to_mac(kvm->cfg.guest_mac, net_params.guest_mac);
842 		str_to_mac(kvm->cfg.host_mac, net_params.host_mac);
843 
844 		virtio_net__init_one(&net_params);
845 	}
846 
847 	return 0;
848 }
849 virtio_dev_init(virtio_net__init);
850 
851 int virtio_net__exit(struct kvm *kvm)
852 {
853 	return 0;
854 }
855 virtio_dev_exit(virtio_net__exit);
856