xref: /dpdk/lib/vhost/vhost_user.c (revision 72206323a5dd3182b13f61b25a64abdddfee595c)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation
3  */
4 
5 /* Security model
6  * --------------
7  * The vhost-user protocol connection is an external interface, so it must be
8  * robust against invalid inputs.
9  *
10  * This is important because the vhost-user master is only one step removed
11  * from the guest.  Malicious guests that have escaped will then launch further
12  * attacks from the vhost-user master.
13  *
14  * Even in deployments where guests are trusted, a bug in the vhost-user master
15  * can still cause invalid messages to be sent.  Such messages must not
16  * compromise the stability of the DPDK application by causing crashes, memory
17  * corruption, or other problematic behavior.
18  *
19  * Do not assume received VhostUserMsg fields contain sensible values!
20  */
21 
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/ioctl.h>
29 #include <sys/mman.h>
30 #include <sys/stat.h>
31 #include <sys/syscall.h>
32 #ifdef RTE_LIBRTE_VHOST_NUMA
33 #include <numaif.h>
34 #endif
35 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
36 #include <linux/userfaultfd.h>
37 #endif
38 #ifdef F_ADD_SEALS /* if file sealing is supported, so is memfd */
39 #include <linux/memfd.h>
40 #define MEMFD_SUPPORTED
41 #endif
42 
43 #include <rte_common.h>
44 #include <rte_malloc.h>
45 #include <rte_log.h>
46 #include <rte_vfio.h>
47 #include <rte_errno.h>
48 
49 #include "iotlb.h"
50 #include "vhost.h"
51 #include "vhost_user.h"
52 
53 #define VIRTIO_MIN_MTU 68
54 #define VIRTIO_MAX_MTU 65535
55 
56 #define INFLIGHT_ALIGNMENT	64
57 #define INFLIGHT_VERSION	0x1
58 
59 typedef struct vhost_message_handler {
60 	const char *description;
61 	int (*callback)(struct virtio_net **pdev, struct vhu_msg_context *ctx,
62 		int main_fd);
63 	bool accepts_fd;
64 } vhost_message_handler_t;
65 static vhost_message_handler_t vhost_message_handlers[];
66 
67 static int send_vhost_reply(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx);
68 static int read_vhost_message(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx);
69 
70 static void
71 close_msg_fds(struct vhu_msg_context *ctx)
72 {
73 	int i;
74 
75 	for (i = 0; i < ctx->fd_num; i++) {
76 		int fd = ctx->fds[i];
77 
78 		if (fd == -1)
79 			continue;
80 
81 		ctx->fds[i] = -1;
82 		close(fd);
83 	}
84 }
85 
86 /*
87  * Ensure the expected number of FDs is received,
88  * close all FDs and return an error if this is not the case.
89  */
90 static int
91 validate_msg_fds(struct virtio_net *dev, struct vhu_msg_context *ctx, int expected_fds)
92 {
93 	if (ctx->fd_num == expected_fds)
94 		return 0;
95 
96 	VHOST_LOG_CONFIG(dev->ifname, ERR,
97 		"expect %d FDs for request %s, received %d\n",
98 		expected_fds, vhost_message_handlers[ctx->msg.request.master].description,
99 		ctx->fd_num);
100 
101 	close_msg_fds(ctx);
102 
103 	return -1;
104 }
105 
106 static uint64_t
107 get_blk_size(int fd)
108 {
109 	struct stat stat;
110 	int ret;
111 
112 	ret = fstat(fd, &stat);
113 	return ret == -1 ? (uint64_t)-1 : (uint64_t)stat.st_blksize;
114 }
115 
116 static void
117 async_dma_map(struct virtio_net *dev, bool do_map)
118 {
119 	int ret = 0;
120 	uint32_t i;
121 	struct guest_page *page;
122 
123 	if (do_map) {
124 		for (i = 0; i < dev->nr_guest_pages; i++) {
125 			page = &dev->guest_pages[i];
126 			ret = rte_vfio_container_dma_map(RTE_VFIO_DEFAULT_CONTAINER_FD,
127 							 page->host_user_addr,
128 							 page->host_iova,
129 							 page->size);
130 			if (ret) {
131 				/*
132 				 * DMA device may bind with kernel driver, in this case,
133 				 * we don't need to program IOMMU manually. However, if no
134 				 * device is bound with vfio/uio in DPDK, and vfio kernel
135 				 * module is loaded, the API will still be called and return
136 				 * with ENODEV.
137 				 *
138 				 * DPDK vfio only returns ENODEV in very similar situations
139 				 * (vfio either unsupported, or supported but no devices found).
140 				 * Either way, no mappings could be performed. We treat it as
141 				 * normal case in async path. This is a workaround.
142 				 */
143 				if (rte_errno == ENODEV)
144 					return;
145 
146 				/* DMA mapping errors won't stop VHOST_USER_SET_MEM_TABLE. */
147 				VHOST_LOG_CONFIG(dev->ifname, ERR, "DMA engine map failed\n");
148 			}
149 		}
150 
151 	} else {
152 		for (i = 0; i < dev->nr_guest_pages; i++) {
153 			page = &dev->guest_pages[i];
154 			ret = rte_vfio_container_dma_unmap(RTE_VFIO_DEFAULT_CONTAINER_FD,
155 							   page->host_user_addr,
156 							   page->host_iova,
157 							   page->size);
158 			if (ret) {
159 				/* like DMA map, ignore the kernel driver case when unmap. */
160 				if (rte_errno == EINVAL)
161 					return;
162 
163 				VHOST_LOG_CONFIG(dev->ifname, ERR, "DMA engine unmap failed\n");
164 			}
165 		}
166 	}
167 }
168 
169 static void
170 free_mem_region(struct virtio_net *dev)
171 {
172 	uint32_t i;
173 	struct rte_vhost_mem_region *reg;
174 
175 	if (!dev || !dev->mem)
176 		return;
177 
178 	if (dev->async_copy && rte_vfio_is_enabled("vfio"))
179 		async_dma_map(dev, false);
180 
181 	for (i = 0; i < dev->mem->nregions; i++) {
182 		reg = &dev->mem->regions[i];
183 		if (reg->host_user_addr) {
184 			munmap(reg->mmap_addr, reg->mmap_size);
185 			close(reg->fd);
186 		}
187 	}
188 }
189 
190 void
191 vhost_backend_cleanup(struct virtio_net *dev)
192 {
193 	struct rte_vdpa_device *vdpa_dev;
194 
195 	vdpa_dev = dev->vdpa_dev;
196 	if (vdpa_dev && vdpa_dev->ops->dev_cleanup != NULL)
197 		vdpa_dev->ops->dev_cleanup(dev->vid);
198 
199 	if (dev->mem) {
200 		free_mem_region(dev);
201 		rte_free(dev->mem);
202 		dev->mem = NULL;
203 	}
204 
205 	rte_free(dev->guest_pages);
206 	dev->guest_pages = NULL;
207 
208 	if (dev->log_addr) {
209 		munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
210 		dev->log_addr = 0;
211 	}
212 
213 	if (dev->inflight_info) {
214 		if (dev->inflight_info->addr) {
215 			munmap(dev->inflight_info->addr,
216 			       dev->inflight_info->size);
217 			dev->inflight_info->addr = NULL;
218 		}
219 
220 		if (dev->inflight_info->fd >= 0) {
221 			close(dev->inflight_info->fd);
222 			dev->inflight_info->fd = -1;
223 		}
224 
225 		rte_free(dev->inflight_info);
226 		dev->inflight_info = NULL;
227 	}
228 
229 	if (dev->slave_req_fd >= 0) {
230 		close(dev->slave_req_fd);
231 		dev->slave_req_fd = -1;
232 	}
233 
234 	if (dev->postcopy_ufd >= 0) {
235 		close(dev->postcopy_ufd);
236 		dev->postcopy_ufd = -1;
237 	}
238 
239 	dev->postcopy_listening = 0;
240 }
241 
242 static void
243 vhost_user_notify_queue_state(struct virtio_net *dev, uint16_t index,
244 			      int enable)
245 {
246 	struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
247 	struct vhost_virtqueue *vq = dev->virtqueue[index];
248 
249 	/* Configure guest notifications on enable */
250 	if (enable && vq->notif_enable != VIRTIO_UNINITIALIZED_NOTIF)
251 		vhost_enable_guest_notification(dev, vq, vq->notif_enable);
252 
253 	if (vdpa_dev && vdpa_dev->ops->set_vring_state)
254 		vdpa_dev->ops->set_vring_state(dev->vid, index, enable);
255 
256 	if (dev->notify_ops->vring_state_changed)
257 		dev->notify_ops->vring_state_changed(dev->vid,
258 				index, enable);
259 }
260 
261 /*
262  * This function just returns success at the moment unless
263  * the device hasn't been initialised.
264  */
265 static int
266 vhost_user_set_owner(struct virtio_net **pdev __rte_unused,
267 			struct vhu_msg_context *ctx __rte_unused,
268 			int main_fd __rte_unused)
269 {
270 	return RTE_VHOST_MSG_RESULT_OK;
271 }
272 
273 static int
274 vhost_user_reset_owner(struct virtio_net **pdev,
275 			struct vhu_msg_context *ctx __rte_unused,
276 			int main_fd __rte_unused)
277 {
278 	struct virtio_net *dev = *pdev;
279 
280 	vhost_destroy_device_notify(dev);
281 
282 	cleanup_device(dev, 0);
283 	reset_device(dev);
284 	return RTE_VHOST_MSG_RESULT_OK;
285 }
286 
287 /*
288  * The features that we support are requested.
289  */
290 static int
291 vhost_user_get_features(struct virtio_net **pdev,
292 			struct vhu_msg_context *ctx,
293 			int main_fd __rte_unused)
294 {
295 	struct virtio_net *dev = *pdev;
296 	uint64_t features = 0;
297 
298 	rte_vhost_driver_get_features(dev->ifname, &features);
299 
300 	ctx->msg.payload.u64 = features;
301 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
302 	ctx->fd_num = 0;
303 
304 	return RTE_VHOST_MSG_RESULT_REPLY;
305 }
306 
307 /*
308  * The queue number that we support are requested.
309  */
310 static int
311 vhost_user_get_queue_num(struct virtio_net **pdev,
312 			struct vhu_msg_context *ctx,
313 			int main_fd __rte_unused)
314 {
315 	struct virtio_net *dev = *pdev;
316 	uint32_t queue_num = 0;
317 
318 	rte_vhost_driver_get_queue_num(dev->ifname, &queue_num);
319 
320 	ctx->msg.payload.u64 = (uint64_t)queue_num;
321 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
322 	ctx->fd_num = 0;
323 
324 	return RTE_VHOST_MSG_RESULT_REPLY;
325 }
326 
327 /*
328  * We receive the negotiated features supported by us and the virtio device.
329  */
330 static int
331 vhost_user_set_features(struct virtio_net **pdev,
332 			struct vhu_msg_context *ctx,
333 			int main_fd __rte_unused)
334 {
335 	struct virtio_net *dev = *pdev;
336 	uint64_t features = ctx->msg.payload.u64;
337 	uint64_t vhost_features = 0;
338 	struct rte_vdpa_device *vdpa_dev;
339 
340 	rte_vhost_driver_get_features(dev->ifname, &vhost_features);
341 	if (features & ~vhost_features) {
342 		VHOST_LOG_CONFIG(dev->ifname, ERR, "received invalid negotiated features.\n");
343 		dev->flags |= VIRTIO_DEV_FEATURES_FAILED;
344 		dev->status &= ~VIRTIO_DEVICE_STATUS_FEATURES_OK;
345 
346 		return RTE_VHOST_MSG_RESULT_ERR;
347 	}
348 
349 	if (dev->flags & VIRTIO_DEV_RUNNING) {
350 		if (dev->features == features)
351 			return RTE_VHOST_MSG_RESULT_OK;
352 
353 		/*
354 		 * Error out if master tries to change features while device is
355 		 * in running state. The exception being VHOST_F_LOG_ALL, which
356 		 * is enabled when the live-migration starts.
357 		 */
358 		if ((dev->features ^ features) & ~(1ULL << VHOST_F_LOG_ALL)) {
359 			VHOST_LOG_CONFIG(dev->ifname, ERR,
360 				"features changed while device is running.\n");
361 			return RTE_VHOST_MSG_RESULT_ERR;
362 		}
363 
364 		if (dev->notify_ops->features_changed)
365 			dev->notify_ops->features_changed(dev->vid, features);
366 	}
367 
368 	dev->features = features;
369 	if (dev->features &
370 		((1ULL << VIRTIO_NET_F_MRG_RXBUF) |
371 		 (1ULL << VIRTIO_F_VERSION_1) |
372 		 (1ULL << VIRTIO_F_RING_PACKED))) {
373 		dev->vhost_hlen = sizeof(struct virtio_net_hdr_mrg_rxbuf);
374 	} else {
375 		dev->vhost_hlen = sizeof(struct virtio_net_hdr);
376 	}
377 	VHOST_LOG_CONFIG(dev->ifname, INFO,
378 		"negotiated Virtio features: 0x%" PRIx64 "\n",
379 		dev->features);
380 	VHOST_LOG_CONFIG(dev->ifname, DEBUG,
381 		"mergeable RX buffers %s, virtio 1 %s\n",
382 		(dev->features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ? "on" : "off",
383 		(dev->features & (1ULL << VIRTIO_F_VERSION_1)) ? "on" : "off");
384 
385 	if ((dev->flags & VIRTIO_DEV_BUILTIN_VIRTIO_NET) &&
386 	    !(dev->features & (1ULL << VIRTIO_NET_F_MQ))) {
387 		/*
388 		 * Remove all but first queue pair if MQ hasn't been
389 		 * negotiated. This is safe because the device is not
390 		 * running at this stage.
391 		 */
392 		while (dev->nr_vring > 2) {
393 			struct vhost_virtqueue *vq;
394 
395 			vq = dev->virtqueue[--dev->nr_vring];
396 			if (!vq)
397 				continue;
398 
399 			dev->virtqueue[dev->nr_vring] = NULL;
400 			cleanup_vq(vq, 1);
401 			cleanup_vq_inflight(dev, vq);
402 			free_vq(dev, vq);
403 		}
404 	}
405 
406 	vdpa_dev = dev->vdpa_dev;
407 	if (vdpa_dev)
408 		vdpa_dev->ops->set_features(dev->vid);
409 
410 	dev->flags &= ~VIRTIO_DEV_FEATURES_FAILED;
411 	return RTE_VHOST_MSG_RESULT_OK;
412 }
413 
414 /*
415  * The virtio device sends us the size of the descriptor ring.
416  */
417 static int
418 vhost_user_set_vring_num(struct virtio_net **pdev,
419 			struct vhu_msg_context *ctx,
420 			int main_fd __rte_unused)
421 {
422 	struct virtio_net *dev = *pdev;
423 	struct vhost_virtqueue *vq = dev->virtqueue[ctx->msg.payload.state.index];
424 
425 	if (ctx->msg.payload.state.num > 32768) {
426 		VHOST_LOG_CONFIG(dev->ifname, ERR,
427 			"invalid virtqueue size %u\n",
428 			ctx->msg.payload.state.num);
429 		return RTE_VHOST_MSG_RESULT_ERR;
430 	}
431 
432 	vq->size = ctx->msg.payload.state.num;
433 
434 	/* VIRTIO 1.0, 2.4 Virtqueues says:
435 	 *
436 	 *   Queue Size value is always a power of 2. The maximum Queue Size
437 	 *   value is 32768.
438 	 *
439 	 * VIRTIO 1.1 2.7 Virtqueues says:
440 	 *
441 	 *   Packed virtqueues support up to 2^15 entries each.
442 	 */
443 	if (!vq_is_packed(dev)) {
444 		if (vq->size & (vq->size - 1)) {
445 			VHOST_LOG_CONFIG(dev->ifname, ERR,
446 				"invalid virtqueue size %u\n",
447 				vq->size);
448 			return RTE_VHOST_MSG_RESULT_ERR;
449 		}
450 	}
451 
452 	if (vq_is_packed(dev)) {
453 		rte_free(vq->shadow_used_packed);
454 		vq->shadow_used_packed = rte_malloc_socket(NULL,
455 				vq->size *
456 				sizeof(struct vring_used_elem_packed),
457 				RTE_CACHE_LINE_SIZE, vq->numa_node);
458 		if (!vq->shadow_used_packed) {
459 			VHOST_LOG_CONFIG(dev->ifname, ERR,
460 				"failed to allocate memory for shadow used ring.\n");
461 			return RTE_VHOST_MSG_RESULT_ERR;
462 		}
463 
464 	} else {
465 		rte_free(vq->shadow_used_split);
466 
467 		vq->shadow_used_split = rte_malloc_socket(NULL,
468 				vq->size * sizeof(struct vring_used_elem),
469 				RTE_CACHE_LINE_SIZE, vq->numa_node);
470 
471 		if (!vq->shadow_used_split) {
472 			VHOST_LOG_CONFIG(dev->ifname, ERR,
473 				"failed to allocate memory for vq internal data.\n");
474 			return RTE_VHOST_MSG_RESULT_ERR;
475 		}
476 	}
477 
478 	rte_free(vq->batch_copy_elems);
479 	vq->batch_copy_elems = rte_malloc_socket(NULL,
480 				vq->size * sizeof(struct batch_copy_elem),
481 				RTE_CACHE_LINE_SIZE, vq->numa_node);
482 	if (!vq->batch_copy_elems) {
483 		VHOST_LOG_CONFIG(dev->ifname, ERR,
484 			"failed to allocate memory for batching copy.\n");
485 		return RTE_VHOST_MSG_RESULT_ERR;
486 	}
487 
488 	return RTE_VHOST_MSG_RESULT_OK;
489 }
490 
491 /*
492  * Reallocate virtio_dev, vhost_virtqueue and related data structures to
493  * make them on the same numa node as the memory of vring descriptor.
494  */
495 #ifdef RTE_LIBRTE_VHOST_NUMA
496 static struct virtio_net*
497 numa_realloc(struct virtio_net *dev, int index)
498 {
499 	int node, dev_node;
500 	struct virtio_net *old_dev;
501 	struct vhost_virtqueue *vq;
502 	struct batch_copy_elem *bce;
503 	struct guest_page *gp;
504 	struct rte_vhost_memory *mem;
505 	size_t mem_size;
506 	int ret;
507 
508 	old_dev = dev;
509 	vq = dev->virtqueue[index];
510 
511 	/*
512 	 * If VQ is ready, it is too late to reallocate, it certainly already
513 	 * happened anyway on VHOST_USER_SET_VRING_ADRR.
514 	 */
515 	if (vq->ready)
516 		return dev;
517 
518 	ret = get_mempolicy(&node, NULL, 0, vq->desc, MPOL_F_NODE | MPOL_F_ADDR);
519 	if (ret) {
520 		VHOST_LOG_CONFIG(dev->ifname, ERR,
521 			"unable to get virtqueue %d numa information.\n",
522 			index);
523 		return dev;
524 	}
525 
526 	if (node == vq->numa_node)
527 		goto out_dev_realloc;
528 
529 	vq = rte_realloc_socket(vq, sizeof(*vq), 0, node);
530 	if (!vq) {
531 		VHOST_LOG_CONFIG(dev->ifname, ERR,
532 			"failed to realloc virtqueue %d on node %d\n",
533 			index, node);
534 		return dev;
535 	}
536 
537 	if (vq != dev->virtqueue[index]) {
538 		VHOST_LOG_CONFIG(dev->ifname, INFO, "reallocated virtqueue on node %d\n", node);
539 		dev->virtqueue[index] = vq;
540 		vhost_user_iotlb_init(dev, index);
541 	}
542 
543 	if (vq_is_packed(dev)) {
544 		struct vring_used_elem_packed *sup;
545 
546 		sup = rte_realloc_socket(vq->shadow_used_packed, vq->size * sizeof(*sup),
547 				RTE_CACHE_LINE_SIZE, node);
548 		if (!sup) {
549 			VHOST_LOG_CONFIG(dev->ifname, ERR,
550 				"failed to realloc shadow packed on node %d\n",
551 				node);
552 			return dev;
553 		}
554 		vq->shadow_used_packed = sup;
555 	} else {
556 		struct vring_used_elem *sus;
557 
558 		sus = rte_realloc_socket(vq->shadow_used_split, vq->size * sizeof(*sus),
559 				RTE_CACHE_LINE_SIZE, node);
560 		if (!sus) {
561 			VHOST_LOG_CONFIG(dev->ifname, ERR,
562 				"failed to realloc shadow split on node %d\n",
563 				node);
564 			return dev;
565 		}
566 		vq->shadow_used_split = sus;
567 	}
568 
569 	bce = rte_realloc_socket(vq->batch_copy_elems, vq->size * sizeof(*bce),
570 			RTE_CACHE_LINE_SIZE, node);
571 	if (!bce) {
572 		VHOST_LOG_CONFIG(dev->ifname, ERR,
573 			"failed to realloc batch copy elem on node %d\n",
574 			node);
575 		return dev;
576 	}
577 	vq->batch_copy_elems = bce;
578 
579 	if (vq->log_cache) {
580 		struct log_cache_entry *lc;
581 
582 		lc = rte_realloc_socket(vq->log_cache, sizeof(*lc) * VHOST_LOG_CACHE_NR, 0, node);
583 		if (!lc) {
584 			VHOST_LOG_CONFIG(dev->ifname, ERR,
585 				"failed to realloc log cache on node %d\n",
586 				node);
587 			return dev;
588 		}
589 		vq->log_cache = lc;
590 	}
591 
592 	if (vq->resubmit_inflight) {
593 		struct rte_vhost_resubmit_info *ri;
594 
595 		ri = rte_realloc_socket(vq->resubmit_inflight, sizeof(*ri), 0, node);
596 		if (!ri) {
597 			VHOST_LOG_CONFIG(dev->ifname, ERR,
598 				"failed to realloc resubmit inflight on node %d\n",
599 				node);
600 			return dev;
601 		}
602 		vq->resubmit_inflight = ri;
603 
604 		if (ri->resubmit_list) {
605 			struct rte_vhost_resubmit_desc *rd;
606 
607 			rd = rte_realloc_socket(ri->resubmit_list, sizeof(*rd) * ri->resubmit_num,
608 					0, node);
609 			if (!rd) {
610 				VHOST_LOG_CONFIG(dev->ifname, ERR,
611 					"failed to realloc resubmit list on node %d\n",
612 					node);
613 				return dev;
614 			}
615 			ri->resubmit_list = rd;
616 		}
617 	}
618 
619 	vq->numa_node = node;
620 
621 out_dev_realloc:
622 
623 	if (dev->flags & VIRTIO_DEV_RUNNING)
624 		return dev;
625 
626 	ret = get_mempolicy(&dev_node, NULL, 0, dev, MPOL_F_NODE | MPOL_F_ADDR);
627 	if (ret) {
628 		VHOST_LOG_CONFIG(dev->ifname, ERR, "unable to get numa information.\n");
629 		return dev;
630 	}
631 
632 	if (dev_node == node)
633 		return dev;
634 
635 	dev = rte_realloc_socket(old_dev, sizeof(*dev), 0, node);
636 	if (!dev) {
637 		VHOST_LOG_CONFIG(old_dev->ifname, ERR, "failed to realloc dev on node %d\n", node);
638 		return old_dev;
639 	}
640 
641 	VHOST_LOG_CONFIG(dev->ifname, INFO, "reallocated device on node %d\n", node);
642 	vhost_devices[dev->vid] = dev;
643 
644 	mem_size = sizeof(struct rte_vhost_memory) +
645 		sizeof(struct rte_vhost_mem_region) * dev->mem->nregions;
646 	mem = rte_realloc_socket(dev->mem, mem_size, 0, node);
647 	if (!mem) {
648 		VHOST_LOG_CONFIG(dev->ifname, ERR,
649 			"failed to realloc mem table on node %d\n",
650 			node);
651 		return dev;
652 	}
653 	dev->mem = mem;
654 
655 	gp = rte_realloc_socket(dev->guest_pages, dev->max_guest_pages * sizeof(*gp),
656 			RTE_CACHE_LINE_SIZE, node);
657 	if (!gp) {
658 		VHOST_LOG_CONFIG(dev->ifname, ERR,
659 			"failed to realloc guest pages on node %d\n",
660 			node);
661 		return dev;
662 	}
663 	dev->guest_pages = gp;
664 
665 	return dev;
666 }
667 #else
668 static struct virtio_net*
669 numa_realloc(struct virtio_net *dev, int index __rte_unused)
670 {
671 	return dev;
672 }
673 #endif
674 
675 /* Converts QEMU virtual address to Vhost virtual address. */
676 static uint64_t
677 qva_to_vva(struct virtio_net *dev, uint64_t qva, uint64_t *len)
678 {
679 	struct rte_vhost_mem_region *r;
680 	uint32_t i;
681 
682 	if (unlikely(!dev || !dev->mem))
683 		goto out_error;
684 
685 	/* Find the region where the address lives. */
686 	for (i = 0; i < dev->mem->nregions; i++) {
687 		r = &dev->mem->regions[i];
688 
689 		if (qva >= r->guest_user_addr &&
690 		    qva <  r->guest_user_addr + r->size) {
691 
692 			if (unlikely(*len > r->guest_user_addr + r->size - qva))
693 				*len = r->guest_user_addr + r->size - qva;
694 
695 			return qva - r->guest_user_addr +
696 			       r->host_user_addr;
697 		}
698 	}
699 out_error:
700 	*len = 0;
701 
702 	return 0;
703 }
704 
705 
706 /*
707  * Converts ring address to Vhost virtual address.
708  * If IOMMU is enabled, the ring address is a guest IO virtual address,
709  * else it is a QEMU virtual address.
710  */
711 static uint64_t
712 ring_addr_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
713 		uint64_t ra, uint64_t *size)
714 {
715 	if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM)) {
716 		uint64_t vva;
717 
718 		vhost_user_iotlb_rd_lock(vq);
719 		vva = vhost_iova_to_vva(dev, vq, ra,
720 					size, VHOST_ACCESS_RW);
721 		vhost_user_iotlb_rd_unlock(vq);
722 
723 		return vva;
724 	}
725 
726 	return qva_to_vva(dev, ra, size);
727 }
728 
729 static uint64_t
730 log_addr_to_gpa(struct virtio_net *dev, struct vhost_virtqueue *vq)
731 {
732 	uint64_t log_gpa;
733 
734 	vhost_user_iotlb_rd_lock(vq);
735 	log_gpa = translate_log_addr(dev, vq, vq->ring_addrs.log_guest_addr);
736 	vhost_user_iotlb_rd_unlock(vq);
737 
738 	return log_gpa;
739 }
740 
741 static struct virtio_net *
742 translate_ring_addresses(struct virtio_net *dev, int vq_index)
743 {
744 	struct vhost_virtqueue *vq = dev->virtqueue[vq_index];
745 	struct vhost_vring_addr *addr = &vq->ring_addrs;
746 	uint64_t len, expected_len;
747 
748 	if (addr->flags & (1 << VHOST_VRING_F_LOG)) {
749 		vq->log_guest_addr =
750 			log_addr_to_gpa(dev, vq);
751 		if (vq->log_guest_addr == 0) {
752 			VHOST_LOG_CONFIG(dev->ifname, DEBUG, "failed to map log_guest_addr.\n");
753 			return dev;
754 		}
755 	}
756 
757 	if (vq_is_packed(dev)) {
758 		len = sizeof(struct vring_packed_desc) * vq->size;
759 		vq->desc_packed = (struct vring_packed_desc *)(uintptr_t)
760 			ring_addr_to_vva(dev, vq, addr->desc_user_addr, &len);
761 		if (vq->desc_packed == NULL ||
762 				len != sizeof(struct vring_packed_desc) *
763 				vq->size) {
764 			VHOST_LOG_CONFIG(dev->ifname, DEBUG, "failed to map desc_packed ring.\n");
765 			return dev;
766 		}
767 
768 		dev = numa_realloc(dev, vq_index);
769 		vq = dev->virtqueue[vq_index];
770 		addr = &vq->ring_addrs;
771 
772 		len = sizeof(struct vring_packed_desc_event);
773 		vq->driver_event = (struct vring_packed_desc_event *)
774 					(uintptr_t)ring_addr_to_vva(dev,
775 					vq, addr->avail_user_addr, &len);
776 		if (vq->driver_event == NULL ||
777 				len != sizeof(struct vring_packed_desc_event)) {
778 			VHOST_LOG_CONFIG(dev->ifname, DEBUG,
779 				"failed to find driver area address.\n");
780 			return dev;
781 		}
782 
783 		len = sizeof(struct vring_packed_desc_event);
784 		vq->device_event = (struct vring_packed_desc_event *)
785 					(uintptr_t)ring_addr_to_vva(dev,
786 					vq, addr->used_user_addr, &len);
787 		if (vq->device_event == NULL ||
788 				len != sizeof(struct vring_packed_desc_event)) {
789 			VHOST_LOG_CONFIG(dev->ifname, DEBUG,
790 				"failed to find device area address.\n");
791 			return dev;
792 		}
793 
794 		vq->access_ok = true;
795 		return dev;
796 	}
797 
798 	/* The addresses are converted from QEMU virtual to Vhost virtual. */
799 	if (vq->desc && vq->avail && vq->used)
800 		return dev;
801 
802 	len = sizeof(struct vring_desc) * vq->size;
803 	vq->desc = (struct vring_desc *)(uintptr_t)ring_addr_to_vva(dev,
804 			vq, addr->desc_user_addr, &len);
805 	if (vq->desc == 0 || len != sizeof(struct vring_desc) * vq->size) {
806 		VHOST_LOG_CONFIG(dev->ifname, DEBUG, "failed to map desc ring.\n");
807 		return dev;
808 	}
809 
810 	dev = numa_realloc(dev, vq_index);
811 	vq = dev->virtqueue[vq_index];
812 	addr = &vq->ring_addrs;
813 
814 	len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
815 	if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))
816 		len += sizeof(uint16_t);
817 	expected_len = len;
818 	vq->avail = (struct vring_avail *)(uintptr_t)ring_addr_to_vva(dev,
819 			vq, addr->avail_user_addr, &len);
820 	if (vq->avail == 0 || len != expected_len) {
821 		VHOST_LOG_CONFIG(dev->ifname, DEBUG, "failed to map avail ring.\n");
822 		return dev;
823 	}
824 
825 	len = sizeof(struct vring_used) +
826 		sizeof(struct vring_used_elem) * vq->size;
827 	if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))
828 		len += sizeof(uint16_t);
829 	expected_len = len;
830 	vq->used = (struct vring_used *)(uintptr_t)ring_addr_to_vva(dev,
831 			vq, addr->used_user_addr, &len);
832 	if (vq->used == 0 || len != expected_len) {
833 		VHOST_LOG_CONFIG(dev->ifname, DEBUG, "failed to map used ring.\n");
834 		return dev;
835 	}
836 
837 	if (vq->last_used_idx != vq->used->idx) {
838 		VHOST_LOG_CONFIG(dev->ifname, WARNING,
839 			"last_used_idx (%u) and vq->used->idx (%u) mismatches;\n",
840 			vq->last_used_idx, vq->used->idx);
841 		vq->last_used_idx  = vq->used->idx;
842 		vq->last_avail_idx = vq->used->idx;
843 		VHOST_LOG_CONFIG(dev->ifname, WARNING,
844 			"some packets maybe resent for Tx and dropped for Rx\n");
845 	}
846 
847 	vq->access_ok = true;
848 
849 	VHOST_LOG_CONFIG(dev->ifname, DEBUG, "mapped address desc: %p\n", vq->desc);
850 	VHOST_LOG_CONFIG(dev->ifname, DEBUG, "mapped address avail: %p\n", vq->avail);
851 	VHOST_LOG_CONFIG(dev->ifname, DEBUG, "mapped address used: %p\n", vq->used);
852 	VHOST_LOG_CONFIG(dev->ifname, DEBUG, "log_guest_addr: %" PRIx64 "\n", vq->log_guest_addr);
853 
854 	return dev;
855 }
856 
857 /*
858  * The virtio device sends us the desc, used and avail ring addresses.
859  * This function then converts these to our address space.
860  */
861 static int
862 vhost_user_set_vring_addr(struct virtio_net **pdev,
863 			struct vhu_msg_context *ctx,
864 			int main_fd __rte_unused)
865 {
866 	struct virtio_net *dev = *pdev;
867 	struct vhost_virtqueue *vq;
868 	struct vhost_vring_addr *addr = &ctx->msg.payload.addr;
869 	bool access_ok;
870 
871 	if (dev->mem == NULL)
872 		return RTE_VHOST_MSG_RESULT_ERR;
873 
874 	/* addr->index refers to the queue index. The txq 1, rxq is 0. */
875 	vq = dev->virtqueue[ctx->msg.payload.addr.index];
876 
877 	access_ok = vq->access_ok;
878 
879 	/*
880 	 * Rings addresses should not be interpreted as long as the ring is not
881 	 * started and enabled
882 	 */
883 	memcpy(&vq->ring_addrs, addr, sizeof(*addr));
884 
885 	vring_invalidate(dev, vq);
886 
887 	if ((vq->enabled && (dev->features &
888 				(1ULL << VHOST_USER_F_PROTOCOL_FEATURES))) ||
889 			access_ok) {
890 		dev = translate_ring_addresses(dev, ctx->msg.payload.addr.index);
891 		if (!dev)
892 			return RTE_VHOST_MSG_RESULT_ERR;
893 
894 		*pdev = dev;
895 	}
896 
897 	return RTE_VHOST_MSG_RESULT_OK;
898 }
899 
900 /*
901  * The virtio device sends us the available ring last used index.
902  */
903 static int
904 vhost_user_set_vring_base(struct virtio_net **pdev,
905 			struct vhu_msg_context *ctx,
906 			int main_fd __rte_unused)
907 {
908 	struct virtio_net *dev = *pdev;
909 	struct vhost_virtqueue *vq = dev->virtqueue[ctx->msg.payload.state.index];
910 	uint64_t val = ctx->msg.payload.state.num;
911 
912 	if (vq_is_packed(dev)) {
913 		/*
914 		 * Bit[0:14]: avail index
915 		 * Bit[15]: avail wrap counter
916 		 */
917 		vq->last_avail_idx = val & 0x7fff;
918 		vq->avail_wrap_counter = !!(val & (0x1 << 15));
919 		/*
920 		 * Set used index to same value as available one, as
921 		 * their values should be the same since ring processing
922 		 * was stopped at get time.
923 		 */
924 		vq->last_used_idx = vq->last_avail_idx;
925 		vq->used_wrap_counter = vq->avail_wrap_counter;
926 	} else {
927 		vq->last_used_idx = ctx->msg.payload.state.num;
928 		vq->last_avail_idx = ctx->msg.payload.state.num;
929 	}
930 
931 	VHOST_LOG_CONFIG(dev->ifname, INFO,
932 		"vring base idx:%u last_used_idx:%u last_avail_idx:%u.\n",
933 		ctx->msg.payload.state.index, vq->last_used_idx, vq->last_avail_idx);
934 
935 	return RTE_VHOST_MSG_RESULT_OK;
936 }
937 
938 static int
939 add_one_guest_page(struct virtio_net *dev, uint64_t guest_phys_addr,
940 		   uint64_t host_iova, uint64_t host_user_addr, uint64_t size)
941 {
942 	struct guest_page *page, *last_page;
943 	struct guest_page *old_pages;
944 
945 	if (dev->nr_guest_pages == dev->max_guest_pages) {
946 		dev->max_guest_pages *= 2;
947 		old_pages = dev->guest_pages;
948 		dev->guest_pages = rte_realloc(dev->guest_pages,
949 					dev->max_guest_pages * sizeof(*page),
950 					RTE_CACHE_LINE_SIZE);
951 		if (dev->guest_pages == NULL) {
952 			VHOST_LOG_CONFIG(dev->ifname, ERR, "cannot realloc guest_pages\n");
953 			rte_free(old_pages);
954 			return -1;
955 		}
956 	}
957 
958 	if (dev->nr_guest_pages > 0) {
959 		last_page = &dev->guest_pages[dev->nr_guest_pages - 1];
960 		/* merge if the two pages are continuous */
961 		if (host_iova == last_page->host_iova + last_page->size &&
962 		    guest_phys_addr == last_page->guest_phys_addr + last_page->size &&
963 		    host_user_addr == last_page->host_user_addr + last_page->size) {
964 			last_page->size += size;
965 			return 0;
966 		}
967 	}
968 
969 	page = &dev->guest_pages[dev->nr_guest_pages++];
970 	page->guest_phys_addr = guest_phys_addr;
971 	page->host_iova  = host_iova;
972 	page->host_user_addr = host_user_addr;
973 	page->size = size;
974 
975 	return 0;
976 }
977 
978 static int
979 add_guest_pages(struct virtio_net *dev, struct rte_vhost_mem_region *reg,
980 		uint64_t page_size)
981 {
982 	uint64_t reg_size = reg->size;
983 	uint64_t host_user_addr  = reg->host_user_addr;
984 	uint64_t guest_phys_addr = reg->guest_phys_addr;
985 	uint64_t host_iova;
986 	uint64_t size;
987 
988 	host_iova = rte_mem_virt2iova((void *)(uintptr_t)host_user_addr);
989 	size = page_size - (guest_phys_addr & (page_size - 1));
990 	size = RTE_MIN(size, reg_size);
991 
992 	if (add_one_guest_page(dev, guest_phys_addr, host_iova,
993 			       host_user_addr, size) < 0)
994 		return -1;
995 
996 	host_user_addr  += size;
997 	guest_phys_addr += size;
998 	reg_size -= size;
999 
1000 	while (reg_size > 0) {
1001 		size = RTE_MIN(reg_size, page_size);
1002 		host_iova = rte_mem_virt2iova((void *)(uintptr_t)
1003 						  host_user_addr);
1004 		if (add_one_guest_page(dev, guest_phys_addr, host_iova,
1005 				       host_user_addr, size) < 0)
1006 			return -1;
1007 
1008 		host_user_addr  += size;
1009 		guest_phys_addr += size;
1010 		reg_size -= size;
1011 	}
1012 
1013 	/* sort guest page array if over binary search threshold */
1014 	if (dev->nr_guest_pages >= VHOST_BINARY_SEARCH_THRESH) {
1015 		qsort((void *)dev->guest_pages, dev->nr_guest_pages,
1016 			sizeof(struct guest_page), guest_page_addrcmp);
1017 	}
1018 
1019 	return 0;
1020 }
1021 
1022 #ifdef RTE_LIBRTE_VHOST_DEBUG
1023 /* TODO: enable it only in debug mode? */
1024 static void
1025 dump_guest_pages(struct virtio_net *dev)
1026 {
1027 	uint32_t i;
1028 	struct guest_page *page;
1029 
1030 	for (i = 0; i < dev->nr_guest_pages; i++) {
1031 		page = &dev->guest_pages[i];
1032 
1033 		VHOST_LOG_CONFIG(dev->ifname, INFO, "guest physical page region %u\n", i);
1034 		VHOST_LOG_CONFIG(dev->ifname, INFO, "\tguest_phys_addr: %" PRIx64 "\n",
1035 			page->guest_phys_addr);
1036 		VHOST_LOG_CONFIG(dev->ifname, INFO, "\thost_iova : %" PRIx64 "\n",
1037 			page->host_iova);
1038 		VHOST_LOG_CONFIG(dev->ifname, INFO, "\tsize           : %" PRIx64 "\n",
1039 			page->size);
1040 	}
1041 }
1042 #else
1043 #define dump_guest_pages(dev)
1044 #endif
1045 
1046 static bool
1047 vhost_memory_changed(struct VhostUserMemory *new,
1048 		     struct rte_vhost_memory *old)
1049 {
1050 	uint32_t i;
1051 
1052 	if (new->nregions != old->nregions)
1053 		return true;
1054 
1055 	for (i = 0; i < new->nregions; ++i) {
1056 		VhostUserMemoryRegion *new_r = &new->regions[i];
1057 		struct rte_vhost_mem_region *old_r = &old->regions[i];
1058 
1059 		if (new_r->guest_phys_addr != old_r->guest_phys_addr)
1060 			return true;
1061 		if (new_r->memory_size != old_r->size)
1062 			return true;
1063 		if (new_r->userspace_addr != old_r->guest_user_addr)
1064 			return true;
1065 	}
1066 
1067 	return false;
1068 }
1069 
1070 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
1071 static int
1072 vhost_user_postcopy_region_register(struct virtio_net *dev,
1073 		struct rte_vhost_mem_region *reg)
1074 {
1075 	struct uffdio_register reg_struct;
1076 
1077 	/*
1078 	 * Let's register all the mmapped area to ensure
1079 	 * alignment on page boundary.
1080 	 */
1081 	reg_struct.range.start = (uint64_t)(uintptr_t)reg->mmap_addr;
1082 	reg_struct.range.len = reg->mmap_size;
1083 	reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
1084 
1085 	if (ioctl(dev->postcopy_ufd, UFFDIO_REGISTER,
1086 				&reg_struct)) {
1087 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1088 			"failed to register ufd for region "
1089 			"%" PRIx64 " - %" PRIx64 " (ufd = %d) %s\n",
1090 			(uint64_t)reg_struct.range.start,
1091 			(uint64_t)reg_struct.range.start +
1092 			(uint64_t)reg_struct.range.len - 1,
1093 			dev->postcopy_ufd,
1094 			strerror(errno));
1095 		return -1;
1096 	}
1097 
1098 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1099 		"\t userfaultfd registered for range : %" PRIx64 " - %" PRIx64 "\n",
1100 		(uint64_t)reg_struct.range.start,
1101 		(uint64_t)reg_struct.range.start +
1102 		(uint64_t)reg_struct.range.len - 1);
1103 
1104 	return 0;
1105 }
1106 #else
1107 static int
1108 vhost_user_postcopy_region_register(struct virtio_net *dev __rte_unused,
1109 		struct rte_vhost_mem_region *reg __rte_unused)
1110 {
1111 	return -1;
1112 }
1113 #endif
1114 
1115 static int
1116 vhost_user_postcopy_register(struct virtio_net *dev, int main_fd,
1117 		struct vhu_msg_context *ctx)
1118 {
1119 	struct VhostUserMemory *memory;
1120 	struct rte_vhost_mem_region *reg;
1121 	struct vhu_msg_context ack_ctx;
1122 	uint32_t i;
1123 
1124 	if (!dev->postcopy_listening)
1125 		return 0;
1126 
1127 	/*
1128 	 * We haven't a better way right now than sharing
1129 	 * DPDK's virtual address with Qemu, so that Qemu can
1130 	 * retrieve the region offset when handling userfaults.
1131 	 */
1132 	memory = &ctx->msg.payload.memory;
1133 	for (i = 0; i < memory->nregions; i++) {
1134 		reg = &dev->mem->regions[i];
1135 		memory->regions[i].userspace_addr = reg->host_user_addr;
1136 	}
1137 
1138 	/* Send the addresses back to qemu */
1139 	ctx->fd_num = 0;
1140 	send_vhost_reply(dev, main_fd, ctx);
1141 
1142 	/* Wait for qemu to acknowledge it got the addresses
1143 	 * we've got to wait before we're allowed to generate faults.
1144 	 */
1145 	if (read_vhost_message(dev, main_fd, &ack_ctx) <= 0) {
1146 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1147 			"failed to read qemu ack on postcopy set-mem-table\n");
1148 		return -1;
1149 	}
1150 
1151 	if (validate_msg_fds(dev, &ack_ctx, 0) != 0)
1152 		return -1;
1153 
1154 	if (ack_ctx.msg.request.master != VHOST_USER_SET_MEM_TABLE) {
1155 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1156 			"bad qemu ack on postcopy set-mem-table (%d)\n",
1157 			ack_ctx.msg.request.master);
1158 		return -1;
1159 	}
1160 
1161 	/* Now userfault register and we can use the memory */
1162 	for (i = 0; i < memory->nregions; i++) {
1163 		reg = &dev->mem->regions[i];
1164 		if (vhost_user_postcopy_region_register(dev, reg) < 0)
1165 			return -1;
1166 	}
1167 
1168 	return 0;
1169 }
1170 
1171 static int
1172 vhost_user_mmap_region(struct virtio_net *dev,
1173 		struct rte_vhost_mem_region *region,
1174 		uint64_t mmap_offset)
1175 {
1176 	void *mmap_addr;
1177 	uint64_t mmap_size;
1178 	uint64_t alignment;
1179 	int populate;
1180 
1181 	/* Check for memory_size + mmap_offset overflow */
1182 	if (mmap_offset >= -region->size) {
1183 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1184 			"mmap_offset (%#"PRIx64") and memory_size (%#"PRIx64") overflow\n",
1185 			mmap_offset, region->size);
1186 		return -1;
1187 	}
1188 
1189 	mmap_size = region->size + mmap_offset;
1190 
1191 	/* mmap() without flag of MAP_ANONYMOUS, should be called with length
1192 	 * argument aligned with hugepagesz at older longterm version Linux,
1193 	 * like 2.6.32 and 3.2.72, or mmap() will fail with EINVAL.
1194 	 *
1195 	 * To avoid failure, make sure in caller to keep length aligned.
1196 	 */
1197 	alignment = get_blk_size(region->fd);
1198 	if (alignment == (uint64_t)-1) {
1199 		VHOST_LOG_CONFIG(dev->ifname, ERR, "couldn't get hugepage size through fstat\n");
1200 		return -1;
1201 	}
1202 	mmap_size = RTE_ALIGN_CEIL(mmap_size, alignment);
1203 	if (mmap_size == 0) {
1204 		/*
1205 		 * It could happen if initial mmap_size + alignment overflows
1206 		 * the sizeof uint64, which could happen if either mmap_size or
1207 		 * alignment value is wrong.
1208 		 *
1209 		 * mmap() kernel implementation would return an error, but
1210 		 * better catch it before and provide useful info in the logs.
1211 		 */
1212 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1213 			"mmap size (0x%" PRIx64 ") or alignment (0x%" PRIx64 ") is invalid\n",
1214 			region->size + mmap_offset, alignment);
1215 		return -1;
1216 	}
1217 
1218 	populate = dev->async_copy ? MAP_POPULATE : 0;
1219 	mmap_addr = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE,
1220 			MAP_SHARED | populate, region->fd, 0);
1221 
1222 	if (mmap_addr == MAP_FAILED) {
1223 		VHOST_LOG_CONFIG(dev->ifname, ERR, "mmap failed (%s).\n", strerror(errno));
1224 		return -1;
1225 	}
1226 
1227 	region->mmap_addr = mmap_addr;
1228 	region->mmap_size = mmap_size;
1229 	region->host_user_addr = (uint64_t)(uintptr_t)mmap_addr + mmap_offset;
1230 
1231 	if (dev->async_copy) {
1232 		if (add_guest_pages(dev, region, alignment) < 0) {
1233 			VHOST_LOG_CONFIG(dev->ifname, ERR,
1234 				"adding guest pages to region failed.\n");
1235 			return -1;
1236 		}
1237 	}
1238 
1239 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1240 		"guest memory region size: 0x%" PRIx64 "\n",
1241 		region->size);
1242 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1243 		"\t guest physical addr: 0x%" PRIx64 "\n",
1244 		region->guest_phys_addr);
1245 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1246 		"\t guest virtual  addr: 0x%" PRIx64 "\n",
1247 		region->guest_user_addr);
1248 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1249 		"\t host  virtual  addr: 0x%" PRIx64 "\n",
1250 		region->host_user_addr);
1251 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1252 		"\t mmap addr : 0x%" PRIx64 "\n",
1253 		(uint64_t)(uintptr_t)mmap_addr);
1254 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1255 		"\t mmap size : 0x%" PRIx64 "\n",
1256 		mmap_size);
1257 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1258 		"\t mmap align: 0x%" PRIx64 "\n",
1259 		alignment);
1260 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1261 		"\t mmap off  : 0x%" PRIx64 "\n",
1262 		mmap_offset);
1263 
1264 	return 0;
1265 }
1266 
1267 static int
1268 vhost_user_set_mem_table(struct virtio_net **pdev,
1269 			struct vhu_msg_context *ctx,
1270 			int main_fd)
1271 {
1272 	struct virtio_net *dev = *pdev;
1273 	struct VhostUserMemory *memory = &ctx->msg.payload.memory;
1274 	struct rte_vhost_mem_region *reg;
1275 	int numa_node = SOCKET_ID_ANY;
1276 	uint64_t mmap_offset;
1277 	uint32_t i;
1278 	bool async_notify = false;
1279 
1280 	if (validate_msg_fds(dev, ctx, memory->nregions) != 0)
1281 		return RTE_VHOST_MSG_RESULT_ERR;
1282 
1283 	if (memory->nregions > VHOST_MEMORY_MAX_NREGIONS) {
1284 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1285 			"too many memory regions (%u)\n",
1286 			memory->nregions);
1287 		goto close_msg_fds;
1288 	}
1289 
1290 	if (dev->mem && !vhost_memory_changed(memory, dev->mem)) {
1291 		VHOST_LOG_CONFIG(dev->ifname, INFO, "memory regions not changed\n");
1292 
1293 		close_msg_fds(ctx);
1294 
1295 		return RTE_VHOST_MSG_RESULT_OK;
1296 	}
1297 
1298 	if (dev->mem) {
1299 		if (dev->flags & VIRTIO_DEV_VDPA_CONFIGURED) {
1300 			struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
1301 
1302 			if (vdpa_dev && vdpa_dev->ops->dev_close)
1303 				vdpa_dev->ops->dev_close(dev->vid);
1304 			dev->flags &= ~VIRTIO_DEV_VDPA_CONFIGURED;
1305 		}
1306 
1307 		/* notify the vhost application to stop DMA transfers */
1308 		if (dev->async_copy && dev->notify_ops->vring_state_changed) {
1309 			for (i = 0; i < dev->nr_vring; i++) {
1310 				dev->notify_ops->vring_state_changed(dev->vid,
1311 						i, 0);
1312 			}
1313 			async_notify = true;
1314 		}
1315 
1316 		free_mem_region(dev);
1317 		rte_free(dev->mem);
1318 		dev->mem = NULL;
1319 	}
1320 
1321 	/* Flush IOTLB cache as previous HVAs are now invalid */
1322 	if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))
1323 		for (i = 0; i < dev->nr_vring; i++)
1324 			vhost_user_iotlb_flush_all(dev->virtqueue[i]);
1325 
1326 	/*
1327 	 * If VQ 0 has already been allocated, try to allocate on the same
1328 	 * NUMA node. It can be reallocated later in numa_realloc().
1329 	 */
1330 	if (dev->nr_vring > 0)
1331 		numa_node = dev->virtqueue[0]->numa_node;
1332 
1333 	dev->nr_guest_pages = 0;
1334 	if (dev->guest_pages == NULL) {
1335 		dev->max_guest_pages = 8;
1336 		dev->guest_pages = rte_zmalloc_socket(NULL,
1337 					dev->max_guest_pages *
1338 					sizeof(struct guest_page),
1339 					RTE_CACHE_LINE_SIZE,
1340 					numa_node);
1341 		if (dev->guest_pages == NULL) {
1342 			VHOST_LOG_CONFIG(dev->ifname, ERR,
1343 				"failed to allocate memory for dev->guest_pages\n");
1344 			goto close_msg_fds;
1345 		}
1346 	}
1347 
1348 	dev->mem = rte_zmalloc_socket("vhost-mem-table", sizeof(struct rte_vhost_memory) +
1349 		sizeof(struct rte_vhost_mem_region) * memory->nregions, 0, numa_node);
1350 	if (dev->mem == NULL) {
1351 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to allocate memory for dev->mem\n");
1352 		goto free_guest_pages;
1353 	}
1354 
1355 	for (i = 0; i < memory->nregions; i++) {
1356 		reg = &dev->mem->regions[i];
1357 
1358 		reg->guest_phys_addr = memory->regions[i].guest_phys_addr;
1359 		reg->guest_user_addr = memory->regions[i].userspace_addr;
1360 		reg->size            = memory->regions[i].memory_size;
1361 		reg->fd              = ctx->fds[i];
1362 
1363 		/*
1364 		 * Assign invalid file descriptor value to avoid double
1365 		 * closing on error path.
1366 		 */
1367 		ctx->fds[i] = -1;
1368 
1369 		mmap_offset = memory->regions[i].mmap_offset;
1370 
1371 		if (vhost_user_mmap_region(dev, reg, mmap_offset) < 0) {
1372 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to mmap region %u\n", i);
1373 			goto free_mem_table;
1374 		}
1375 
1376 		dev->mem->nregions++;
1377 	}
1378 
1379 	if (dev->async_copy && rte_vfio_is_enabled("vfio"))
1380 		async_dma_map(dev, true);
1381 
1382 	if (vhost_user_postcopy_register(dev, main_fd, ctx) < 0)
1383 		goto free_mem_table;
1384 
1385 	for (i = 0; i < dev->nr_vring; i++) {
1386 		struct vhost_virtqueue *vq = dev->virtqueue[i];
1387 
1388 		if (!vq)
1389 			continue;
1390 
1391 		if (vq->desc || vq->avail || vq->used) {
1392 			/*
1393 			 * If the memory table got updated, the ring addresses
1394 			 * need to be translated again as virtual addresses have
1395 			 * changed.
1396 			 */
1397 			vring_invalidate(dev, vq);
1398 
1399 			dev = translate_ring_addresses(dev, i);
1400 			if (!dev) {
1401 				dev = *pdev;
1402 				goto free_mem_table;
1403 			}
1404 
1405 			*pdev = dev;
1406 		}
1407 	}
1408 
1409 	dump_guest_pages(dev);
1410 
1411 	if (async_notify) {
1412 		for (i = 0; i < dev->nr_vring; i++)
1413 			dev->notify_ops->vring_state_changed(dev->vid, i, 1);
1414 	}
1415 
1416 	return RTE_VHOST_MSG_RESULT_OK;
1417 
1418 free_mem_table:
1419 	free_mem_region(dev);
1420 	rte_free(dev->mem);
1421 	dev->mem = NULL;
1422 
1423 free_guest_pages:
1424 	rte_free(dev->guest_pages);
1425 	dev->guest_pages = NULL;
1426 close_msg_fds:
1427 	close_msg_fds(ctx);
1428 	return RTE_VHOST_MSG_RESULT_ERR;
1429 }
1430 
1431 static bool
1432 vq_is_ready(struct virtio_net *dev, struct vhost_virtqueue *vq)
1433 {
1434 	bool rings_ok;
1435 
1436 	if (!vq)
1437 		return false;
1438 
1439 	if (vq_is_packed(dev))
1440 		rings_ok = vq->desc_packed && vq->driver_event &&
1441 			vq->device_event;
1442 	else
1443 		rings_ok = vq->desc && vq->avail && vq->used;
1444 
1445 	return rings_ok &&
1446 	       vq->kickfd != VIRTIO_UNINITIALIZED_EVENTFD &&
1447 	       vq->callfd != VIRTIO_UNINITIALIZED_EVENTFD &&
1448 	       vq->enabled;
1449 }
1450 
1451 #define VIRTIO_BUILTIN_NUM_VQS_TO_BE_READY 2u
1452 
1453 static int
1454 virtio_is_ready(struct virtio_net *dev)
1455 {
1456 	struct vhost_virtqueue *vq;
1457 	uint32_t i, nr_vring = dev->nr_vring;
1458 
1459 	if (dev->flags & VIRTIO_DEV_READY)
1460 		return 1;
1461 
1462 	if (!dev->nr_vring)
1463 		return 0;
1464 
1465 	if (dev->flags & VIRTIO_DEV_BUILTIN_VIRTIO_NET) {
1466 		nr_vring = VIRTIO_BUILTIN_NUM_VQS_TO_BE_READY;
1467 
1468 		if (dev->nr_vring < nr_vring)
1469 			return 0;
1470 	}
1471 
1472 	for (i = 0; i < nr_vring; i++) {
1473 		vq = dev->virtqueue[i];
1474 
1475 		if (!vq_is_ready(dev, vq))
1476 			return 0;
1477 	}
1478 
1479 	/* If supported, ensure the frontend is really done with config */
1480 	if (dev->protocol_features & (1ULL << VHOST_USER_PROTOCOL_F_STATUS))
1481 		if (!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER_OK))
1482 			return 0;
1483 
1484 	dev->flags |= VIRTIO_DEV_READY;
1485 
1486 	if (!(dev->flags & VIRTIO_DEV_RUNNING))
1487 		VHOST_LOG_CONFIG(dev->ifname, INFO, "virtio is now ready for processing.\n");
1488 	return 1;
1489 }
1490 
1491 static void *
1492 inflight_mem_alloc(struct virtio_net *dev, const char *name, size_t size, int *fd)
1493 {
1494 	void *ptr;
1495 	int mfd = -1;
1496 	char fname[20] = "/tmp/memfd-XXXXXX";
1497 
1498 	*fd = -1;
1499 #ifdef MEMFD_SUPPORTED
1500 	mfd = memfd_create(name, MFD_CLOEXEC);
1501 #else
1502 	RTE_SET_USED(name);
1503 #endif
1504 	if (mfd == -1) {
1505 		mfd = mkstemp(fname);
1506 		if (mfd == -1) {
1507 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to get inflight buffer fd\n");
1508 			return NULL;
1509 		}
1510 
1511 		unlink(fname);
1512 	}
1513 
1514 	if (ftruncate(mfd, size) == -1) {
1515 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to alloc inflight buffer\n");
1516 		close(mfd);
1517 		return NULL;
1518 	}
1519 
1520 	ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, mfd, 0);
1521 	if (ptr == MAP_FAILED) {
1522 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to mmap inflight buffer\n");
1523 		close(mfd);
1524 		return NULL;
1525 	}
1526 
1527 	*fd = mfd;
1528 	return ptr;
1529 }
1530 
1531 static uint32_t
1532 get_pervq_shm_size_split(uint16_t queue_size)
1533 {
1534 	return RTE_ALIGN_MUL_CEIL(sizeof(struct rte_vhost_inflight_desc_split) *
1535 				  queue_size + sizeof(uint64_t) +
1536 				  sizeof(uint16_t) * 4, INFLIGHT_ALIGNMENT);
1537 }
1538 
1539 static uint32_t
1540 get_pervq_shm_size_packed(uint16_t queue_size)
1541 {
1542 	return RTE_ALIGN_MUL_CEIL(sizeof(struct rte_vhost_inflight_desc_packed)
1543 				  * queue_size + sizeof(uint64_t) +
1544 				  sizeof(uint16_t) * 6 + sizeof(uint8_t) * 9,
1545 				  INFLIGHT_ALIGNMENT);
1546 }
1547 
1548 static int
1549 vhost_user_get_inflight_fd(struct virtio_net **pdev,
1550 			   struct vhu_msg_context *ctx,
1551 			   int main_fd __rte_unused)
1552 {
1553 	struct rte_vhost_inflight_info_packed *inflight_packed;
1554 	uint64_t pervq_inflight_size, mmap_size;
1555 	uint16_t num_queues, queue_size;
1556 	struct virtio_net *dev = *pdev;
1557 	int fd, i, j;
1558 	int numa_node = SOCKET_ID_ANY;
1559 	void *addr;
1560 
1561 	if (ctx->msg.size != sizeof(ctx->msg.payload.inflight)) {
1562 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1563 			"invalid get_inflight_fd message size is %d\n",
1564 			ctx->msg.size);
1565 		return RTE_VHOST_MSG_RESULT_ERR;
1566 	}
1567 
1568 	/*
1569 	 * If VQ 0 has already been allocated, try to allocate on the same
1570 	 * NUMA node. It can be reallocated later in numa_realloc().
1571 	 */
1572 	if (dev->nr_vring > 0)
1573 		numa_node = dev->virtqueue[0]->numa_node;
1574 
1575 	if (dev->inflight_info == NULL) {
1576 		dev->inflight_info = rte_zmalloc_socket("inflight_info",
1577 				sizeof(struct inflight_mem_info), 0, numa_node);
1578 		if (!dev->inflight_info) {
1579 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to alloc dev inflight area\n");
1580 			return RTE_VHOST_MSG_RESULT_ERR;
1581 		}
1582 		dev->inflight_info->fd = -1;
1583 	}
1584 
1585 	num_queues = ctx->msg.payload.inflight.num_queues;
1586 	queue_size = ctx->msg.payload.inflight.queue_size;
1587 
1588 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1589 		"get_inflight_fd num_queues: %u\n",
1590 		ctx->msg.payload.inflight.num_queues);
1591 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1592 		"get_inflight_fd queue_size: %u\n",
1593 		ctx->msg.payload.inflight.queue_size);
1594 
1595 	if (vq_is_packed(dev))
1596 		pervq_inflight_size = get_pervq_shm_size_packed(queue_size);
1597 	else
1598 		pervq_inflight_size = get_pervq_shm_size_split(queue_size);
1599 
1600 	mmap_size = num_queues * pervq_inflight_size;
1601 	addr = inflight_mem_alloc(dev, "vhost-inflight", mmap_size, &fd);
1602 	if (!addr) {
1603 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to alloc vhost inflight area\n");
1604 			ctx->msg.payload.inflight.mmap_size = 0;
1605 		return RTE_VHOST_MSG_RESULT_ERR;
1606 	}
1607 	memset(addr, 0, mmap_size);
1608 
1609 	if (dev->inflight_info->addr) {
1610 		munmap(dev->inflight_info->addr, dev->inflight_info->size);
1611 		dev->inflight_info->addr = NULL;
1612 	}
1613 
1614 	if (dev->inflight_info->fd >= 0) {
1615 		close(dev->inflight_info->fd);
1616 		dev->inflight_info->fd = -1;
1617 	}
1618 
1619 	dev->inflight_info->addr = addr;
1620 	dev->inflight_info->size = ctx->msg.payload.inflight.mmap_size = mmap_size;
1621 	dev->inflight_info->fd = ctx->fds[0] = fd;
1622 	ctx->msg.payload.inflight.mmap_offset = 0;
1623 	ctx->fd_num = 1;
1624 
1625 	if (vq_is_packed(dev)) {
1626 		for (i = 0; i < num_queues; i++) {
1627 			inflight_packed =
1628 				(struct rte_vhost_inflight_info_packed *)addr;
1629 			inflight_packed->used_wrap_counter = 1;
1630 			inflight_packed->old_used_wrap_counter = 1;
1631 			for (j = 0; j < queue_size; j++)
1632 				inflight_packed->desc[j].next = j + 1;
1633 			addr = (void *)((char *)addr + pervq_inflight_size);
1634 		}
1635 	}
1636 
1637 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1638 		"send inflight mmap_size: %"PRIu64"\n",
1639 		ctx->msg.payload.inflight.mmap_size);
1640 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1641 		"send inflight mmap_offset: %"PRIu64"\n",
1642 		ctx->msg.payload.inflight.mmap_offset);
1643 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1644 		"send inflight fd: %d\n", ctx->fds[0]);
1645 
1646 	return RTE_VHOST_MSG_RESULT_REPLY;
1647 }
1648 
1649 static int
1650 vhost_user_set_inflight_fd(struct virtio_net **pdev,
1651 			   struct vhu_msg_context *ctx,
1652 			   int main_fd __rte_unused)
1653 {
1654 	uint64_t mmap_size, mmap_offset;
1655 	uint16_t num_queues, queue_size;
1656 	struct virtio_net *dev = *pdev;
1657 	uint32_t pervq_inflight_size;
1658 	struct vhost_virtqueue *vq;
1659 	void *addr;
1660 	int fd, i;
1661 	int numa_node = SOCKET_ID_ANY;
1662 
1663 	if (validate_msg_fds(dev, ctx, 1) != 0)
1664 		return RTE_VHOST_MSG_RESULT_ERR;
1665 
1666 	fd = ctx->fds[0];
1667 	if (ctx->msg.size != sizeof(ctx->msg.payload.inflight) || fd < 0) {
1668 		VHOST_LOG_CONFIG(dev->ifname, ERR,
1669 			"invalid set_inflight_fd message size is %d,fd is %d\n",
1670 			ctx->msg.size, fd);
1671 		return RTE_VHOST_MSG_RESULT_ERR;
1672 	}
1673 
1674 	mmap_size = ctx->msg.payload.inflight.mmap_size;
1675 	mmap_offset = ctx->msg.payload.inflight.mmap_offset;
1676 	num_queues = ctx->msg.payload.inflight.num_queues;
1677 	queue_size = ctx->msg.payload.inflight.queue_size;
1678 
1679 	if (vq_is_packed(dev))
1680 		pervq_inflight_size = get_pervq_shm_size_packed(queue_size);
1681 	else
1682 		pervq_inflight_size = get_pervq_shm_size_split(queue_size);
1683 
1684 	VHOST_LOG_CONFIG(dev->ifname, INFO, "set_inflight_fd mmap_size: %"PRIu64"\n", mmap_size);
1685 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1686 		"set_inflight_fd mmap_offset: %"PRIu64"\n",
1687 		mmap_offset);
1688 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1689 		"set_inflight_fd num_queues: %u\n",
1690 		num_queues);
1691 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1692 		"set_inflight_fd queue_size: %u\n",
1693 		queue_size);
1694 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1695 		"set_inflight_fd fd: %d\n",
1696 		fd);
1697 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1698 		"set_inflight_fd pervq_inflight_size: %d\n",
1699 		pervq_inflight_size);
1700 
1701 	/*
1702 	 * If VQ 0 has already been allocated, try to allocate on the same
1703 	 * NUMA node. It can be reallocated later in numa_realloc().
1704 	 */
1705 	if (dev->nr_vring > 0)
1706 		numa_node = dev->virtqueue[0]->numa_node;
1707 
1708 	if (!dev->inflight_info) {
1709 		dev->inflight_info = rte_zmalloc_socket("inflight_info",
1710 				sizeof(struct inflight_mem_info), 0, numa_node);
1711 		if (dev->inflight_info == NULL) {
1712 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to alloc dev inflight area\n");
1713 			return RTE_VHOST_MSG_RESULT_ERR;
1714 		}
1715 		dev->inflight_info->fd = -1;
1716 	}
1717 
1718 	if (dev->inflight_info->addr) {
1719 		munmap(dev->inflight_info->addr, dev->inflight_info->size);
1720 		dev->inflight_info->addr = NULL;
1721 	}
1722 
1723 	addr = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
1724 		    fd, mmap_offset);
1725 	if (addr == MAP_FAILED) {
1726 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to mmap share memory.\n");
1727 		return RTE_VHOST_MSG_RESULT_ERR;
1728 	}
1729 
1730 	if (dev->inflight_info->fd >= 0) {
1731 		close(dev->inflight_info->fd);
1732 		dev->inflight_info->fd = -1;
1733 	}
1734 
1735 	dev->inflight_info->fd = fd;
1736 	dev->inflight_info->addr = addr;
1737 	dev->inflight_info->size = mmap_size;
1738 
1739 	for (i = 0; i < num_queues; i++) {
1740 		vq = dev->virtqueue[i];
1741 		if (!vq)
1742 			continue;
1743 
1744 		if (vq_is_packed(dev)) {
1745 			vq->inflight_packed = addr;
1746 			vq->inflight_packed->desc_num = queue_size;
1747 		} else {
1748 			vq->inflight_split = addr;
1749 			vq->inflight_split->desc_num = queue_size;
1750 		}
1751 		addr = (void *)((char *)addr + pervq_inflight_size);
1752 	}
1753 
1754 	return RTE_VHOST_MSG_RESULT_OK;
1755 }
1756 
1757 static int
1758 vhost_user_set_vring_call(struct virtio_net **pdev,
1759 			struct vhu_msg_context *ctx,
1760 			int main_fd __rte_unused)
1761 {
1762 	struct virtio_net *dev = *pdev;
1763 	struct vhost_vring_file file;
1764 	struct vhost_virtqueue *vq;
1765 	int expected_fds;
1766 
1767 	expected_fds = (ctx->msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1768 	if (validate_msg_fds(dev, ctx, expected_fds) != 0)
1769 		return RTE_VHOST_MSG_RESULT_ERR;
1770 
1771 	file.index = ctx->msg.payload.u64 & VHOST_USER_VRING_IDX_MASK;
1772 	if (ctx->msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK)
1773 		file.fd = VIRTIO_INVALID_EVENTFD;
1774 	else
1775 		file.fd = ctx->fds[0];
1776 	VHOST_LOG_CONFIG(dev->ifname, INFO,
1777 		"vring call idx:%d file:%d\n",
1778 		file.index, file.fd);
1779 
1780 	vq = dev->virtqueue[file.index];
1781 
1782 	if (vq->ready) {
1783 		vq->ready = false;
1784 		vhost_user_notify_queue_state(dev, file.index, 0);
1785 	}
1786 
1787 	if (vq->callfd >= 0)
1788 		close(vq->callfd);
1789 
1790 	vq->callfd = file.fd;
1791 
1792 	return RTE_VHOST_MSG_RESULT_OK;
1793 }
1794 
1795 static int vhost_user_set_vring_err(struct virtio_net **pdev,
1796 			struct vhu_msg_context *ctx,
1797 			int main_fd __rte_unused)
1798 {
1799 	struct virtio_net *dev = *pdev;
1800 	int expected_fds;
1801 
1802 	expected_fds = (ctx->msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
1803 	if (validate_msg_fds(dev, ctx, expected_fds) != 0)
1804 		return RTE_VHOST_MSG_RESULT_ERR;
1805 
1806 	if (!(ctx->msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK))
1807 		close(ctx->fds[0]);
1808 	VHOST_LOG_CONFIG(dev->ifname, INFO, "not implemented\n");
1809 
1810 	return RTE_VHOST_MSG_RESULT_OK;
1811 }
1812 
1813 static int
1814 resubmit_desc_compare(const void *a, const void *b)
1815 {
1816 	const struct rte_vhost_resubmit_desc *desc0 = a;
1817 	const struct rte_vhost_resubmit_desc *desc1 = b;
1818 
1819 	if (desc1->counter > desc0->counter)
1820 		return 1;
1821 
1822 	return -1;
1823 }
1824 
1825 static int
1826 vhost_check_queue_inflights_split(struct virtio_net *dev,
1827 				  struct vhost_virtqueue *vq)
1828 {
1829 	uint16_t i;
1830 	uint16_t resubmit_num = 0, last_io, num;
1831 	struct vring_used *used = vq->used;
1832 	struct rte_vhost_resubmit_info *resubmit;
1833 	struct rte_vhost_inflight_info_split *inflight_split;
1834 
1835 	if (!(dev->protocol_features &
1836 	    (1ULL << VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)))
1837 		return RTE_VHOST_MSG_RESULT_OK;
1838 
1839 	/* The frontend may still not support the inflight feature
1840 	 * although we negotiate the protocol feature.
1841 	 */
1842 	if ((!vq->inflight_split))
1843 		return RTE_VHOST_MSG_RESULT_OK;
1844 
1845 	if (!vq->inflight_split->version) {
1846 		vq->inflight_split->version = INFLIGHT_VERSION;
1847 		return RTE_VHOST_MSG_RESULT_OK;
1848 	}
1849 
1850 	if (vq->resubmit_inflight)
1851 		return RTE_VHOST_MSG_RESULT_OK;
1852 
1853 	inflight_split = vq->inflight_split;
1854 	vq->global_counter = 0;
1855 	last_io = inflight_split->last_inflight_io;
1856 
1857 	if (inflight_split->used_idx != used->idx) {
1858 		inflight_split->desc[last_io].inflight = 0;
1859 		rte_atomic_thread_fence(__ATOMIC_SEQ_CST);
1860 		inflight_split->used_idx = used->idx;
1861 	}
1862 
1863 	for (i = 0; i < inflight_split->desc_num; i++) {
1864 		if (inflight_split->desc[i].inflight == 1)
1865 			resubmit_num++;
1866 	}
1867 
1868 	vq->last_avail_idx += resubmit_num;
1869 
1870 	if (resubmit_num) {
1871 		resubmit = rte_zmalloc_socket("resubmit", sizeof(struct rte_vhost_resubmit_info),
1872 				0, vq->numa_node);
1873 		if (!resubmit) {
1874 			VHOST_LOG_CONFIG(dev->ifname, ERR,
1875 				"failed to allocate memory for resubmit info.\n");
1876 			return RTE_VHOST_MSG_RESULT_ERR;
1877 		}
1878 
1879 		resubmit->resubmit_list = rte_zmalloc_socket("resubmit_list",
1880 				resubmit_num * sizeof(struct rte_vhost_resubmit_desc),
1881 				0, vq->numa_node);
1882 		if (!resubmit->resubmit_list) {
1883 			VHOST_LOG_CONFIG(dev->ifname, ERR,
1884 					"failed to allocate memory for inflight desc.\n");
1885 			rte_free(resubmit);
1886 			return RTE_VHOST_MSG_RESULT_ERR;
1887 		}
1888 
1889 		num = 0;
1890 		for (i = 0; i < vq->inflight_split->desc_num; i++) {
1891 			if (vq->inflight_split->desc[i].inflight == 1) {
1892 				resubmit->resubmit_list[num].index = i;
1893 				resubmit->resubmit_list[num].counter =
1894 					inflight_split->desc[i].counter;
1895 				num++;
1896 			}
1897 		}
1898 		resubmit->resubmit_num = num;
1899 
1900 		if (resubmit->resubmit_num > 1)
1901 			qsort(resubmit->resubmit_list, resubmit->resubmit_num,
1902 			      sizeof(struct rte_vhost_resubmit_desc),
1903 			      resubmit_desc_compare);
1904 
1905 		vq->global_counter = resubmit->resubmit_list[0].counter + 1;
1906 		vq->resubmit_inflight = resubmit;
1907 	}
1908 
1909 	return RTE_VHOST_MSG_RESULT_OK;
1910 }
1911 
1912 static int
1913 vhost_check_queue_inflights_packed(struct virtio_net *dev,
1914 				   struct vhost_virtqueue *vq)
1915 {
1916 	uint16_t i;
1917 	uint16_t resubmit_num = 0, old_used_idx, num;
1918 	struct rte_vhost_resubmit_info *resubmit;
1919 	struct rte_vhost_inflight_info_packed *inflight_packed;
1920 
1921 	if (!(dev->protocol_features &
1922 	    (1ULL << VHOST_USER_PROTOCOL_F_INFLIGHT_SHMFD)))
1923 		return RTE_VHOST_MSG_RESULT_OK;
1924 
1925 	/* The frontend may still not support the inflight feature
1926 	 * although we negotiate the protocol feature.
1927 	 */
1928 	if ((!vq->inflight_packed))
1929 		return RTE_VHOST_MSG_RESULT_OK;
1930 
1931 	if (!vq->inflight_packed->version) {
1932 		vq->inflight_packed->version = INFLIGHT_VERSION;
1933 		return RTE_VHOST_MSG_RESULT_OK;
1934 	}
1935 
1936 	if (vq->resubmit_inflight)
1937 		return RTE_VHOST_MSG_RESULT_OK;
1938 
1939 	inflight_packed = vq->inflight_packed;
1940 	vq->global_counter = 0;
1941 	old_used_idx = inflight_packed->old_used_idx;
1942 
1943 	if (inflight_packed->used_idx != old_used_idx) {
1944 		if (inflight_packed->desc[old_used_idx].inflight == 0) {
1945 			inflight_packed->old_used_idx =
1946 				inflight_packed->used_idx;
1947 			inflight_packed->old_used_wrap_counter =
1948 				inflight_packed->used_wrap_counter;
1949 			inflight_packed->old_free_head =
1950 				inflight_packed->free_head;
1951 		} else {
1952 			inflight_packed->used_idx =
1953 				inflight_packed->old_used_idx;
1954 			inflight_packed->used_wrap_counter =
1955 				inflight_packed->old_used_wrap_counter;
1956 			inflight_packed->free_head =
1957 				inflight_packed->old_free_head;
1958 		}
1959 	}
1960 
1961 	for (i = 0; i < inflight_packed->desc_num; i++) {
1962 		if (inflight_packed->desc[i].inflight == 1)
1963 			resubmit_num++;
1964 	}
1965 
1966 	if (resubmit_num) {
1967 		resubmit = rte_zmalloc_socket("resubmit", sizeof(struct rte_vhost_resubmit_info),
1968 				0, vq->numa_node);
1969 		if (resubmit == NULL) {
1970 			VHOST_LOG_CONFIG(dev->ifname, ERR,
1971 				"failed to allocate memory for resubmit info.\n");
1972 			return RTE_VHOST_MSG_RESULT_ERR;
1973 		}
1974 
1975 		resubmit->resubmit_list = rte_zmalloc_socket("resubmit_list",
1976 				resubmit_num * sizeof(struct rte_vhost_resubmit_desc),
1977 				0, vq->numa_node);
1978 		if (resubmit->resubmit_list == NULL) {
1979 			VHOST_LOG_CONFIG(dev->ifname, ERR,
1980 				"failed to allocate memory for resubmit desc.\n");
1981 			rte_free(resubmit);
1982 			return RTE_VHOST_MSG_RESULT_ERR;
1983 		}
1984 
1985 		num = 0;
1986 		for (i = 0; i < inflight_packed->desc_num; i++) {
1987 			if (vq->inflight_packed->desc[i].inflight == 1) {
1988 				resubmit->resubmit_list[num].index = i;
1989 				resubmit->resubmit_list[num].counter =
1990 					inflight_packed->desc[i].counter;
1991 				num++;
1992 			}
1993 		}
1994 		resubmit->resubmit_num = num;
1995 
1996 		if (resubmit->resubmit_num > 1)
1997 			qsort(resubmit->resubmit_list, resubmit->resubmit_num,
1998 			      sizeof(struct rte_vhost_resubmit_desc),
1999 			      resubmit_desc_compare);
2000 
2001 		vq->global_counter = resubmit->resubmit_list[0].counter + 1;
2002 		vq->resubmit_inflight = resubmit;
2003 	}
2004 
2005 	return RTE_VHOST_MSG_RESULT_OK;
2006 }
2007 
2008 static int
2009 vhost_user_set_vring_kick(struct virtio_net **pdev,
2010 			struct vhu_msg_context *ctx,
2011 			int main_fd __rte_unused)
2012 {
2013 	struct virtio_net *dev = *pdev;
2014 	struct vhost_vring_file file;
2015 	struct vhost_virtqueue *vq;
2016 	int expected_fds;
2017 
2018 	expected_fds = (ctx->msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK) ? 0 : 1;
2019 	if (validate_msg_fds(dev, ctx, expected_fds) != 0)
2020 		return RTE_VHOST_MSG_RESULT_ERR;
2021 
2022 	file.index = ctx->msg.payload.u64 & VHOST_USER_VRING_IDX_MASK;
2023 	if (ctx->msg.payload.u64 & VHOST_USER_VRING_NOFD_MASK)
2024 		file.fd = VIRTIO_INVALID_EVENTFD;
2025 	else
2026 		file.fd = ctx->fds[0];
2027 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2028 		"vring kick idx:%d file:%d\n",
2029 		file.index, file.fd);
2030 
2031 	/* Interpret ring addresses only when ring is started. */
2032 	dev = translate_ring_addresses(dev, file.index);
2033 	if (!dev) {
2034 		if (file.fd != VIRTIO_INVALID_EVENTFD)
2035 			close(file.fd);
2036 
2037 		return RTE_VHOST_MSG_RESULT_ERR;
2038 	}
2039 
2040 	*pdev = dev;
2041 
2042 	vq = dev->virtqueue[file.index];
2043 
2044 	/*
2045 	 * When VHOST_USER_F_PROTOCOL_FEATURES is not negotiated,
2046 	 * the ring starts already enabled. Otherwise, it is enabled via
2047 	 * the SET_VRING_ENABLE message.
2048 	 */
2049 	if (!(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES))) {
2050 		vq->enabled = true;
2051 	}
2052 
2053 	if (vq->ready) {
2054 		vq->ready = false;
2055 		vhost_user_notify_queue_state(dev, file.index, 0);
2056 	}
2057 
2058 	if (vq->kickfd >= 0)
2059 		close(vq->kickfd);
2060 	vq->kickfd = file.fd;
2061 
2062 	if (vq_is_packed(dev)) {
2063 		if (vhost_check_queue_inflights_packed(dev, vq)) {
2064 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2065 				"failed to inflights for vq: %d\n",
2066 				file.index);
2067 			return RTE_VHOST_MSG_RESULT_ERR;
2068 		}
2069 	} else {
2070 		if (vhost_check_queue_inflights_split(dev, vq)) {
2071 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2072 				"failed to inflights for vq: %d\n",
2073 				file.index);
2074 			return RTE_VHOST_MSG_RESULT_ERR;
2075 		}
2076 	}
2077 
2078 	return RTE_VHOST_MSG_RESULT_OK;
2079 }
2080 
2081 /*
2082  * when virtio is stopped, qemu will send us the GET_VRING_BASE message.
2083  */
2084 static int
2085 vhost_user_get_vring_base(struct virtio_net **pdev,
2086 			struct vhu_msg_context *ctx,
2087 			int main_fd __rte_unused)
2088 {
2089 	struct virtio_net *dev = *pdev;
2090 	struct vhost_virtqueue *vq = dev->virtqueue[ctx->msg.payload.state.index];
2091 	uint64_t val;
2092 
2093 	/* We have to stop the queue (virtio) if it is running. */
2094 	vhost_destroy_device_notify(dev);
2095 
2096 	dev->flags &= ~VIRTIO_DEV_READY;
2097 	dev->flags &= ~VIRTIO_DEV_VDPA_CONFIGURED;
2098 
2099 	/* Here we are safe to get the indexes */
2100 	if (vq_is_packed(dev)) {
2101 		/*
2102 		 * Bit[0:14]: avail index
2103 		 * Bit[15]: avail wrap counter
2104 		 */
2105 		val = vq->last_avail_idx & 0x7fff;
2106 		val |= vq->avail_wrap_counter << 15;
2107 		ctx->msg.payload.state.num = val;
2108 	} else {
2109 		ctx->msg.payload.state.num = vq->last_avail_idx;
2110 	}
2111 
2112 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2113 		"vring base idx:%d file:%d\n",
2114 		ctx->msg.payload.state.index, ctx->msg.payload.state.num);
2115 	/*
2116 	 * Based on current qemu vhost-user implementation, this message is
2117 	 * sent and only sent in vhost_vring_stop.
2118 	 * TODO: cleanup the vring, it isn't usable since here.
2119 	 */
2120 	if (vq->kickfd >= 0)
2121 		close(vq->kickfd);
2122 
2123 	vq->kickfd = VIRTIO_UNINITIALIZED_EVENTFD;
2124 
2125 	if (vq->callfd >= 0)
2126 		close(vq->callfd);
2127 
2128 	vq->callfd = VIRTIO_UNINITIALIZED_EVENTFD;
2129 
2130 	vq->signalled_used_valid = false;
2131 
2132 	if (vq_is_packed(dev)) {
2133 		rte_free(vq->shadow_used_packed);
2134 		vq->shadow_used_packed = NULL;
2135 	} else {
2136 		rte_free(vq->shadow_used_split);
2137 		vq->shadow_used_split = NULL;
2138 	}
2139 
2140 	rte_free(vq->batch_copy_elems);
2141 	vq->batch_copy_elems = NULL;
2142 
2143 	rte_free(vq->log_cache);
2144 	vq->log_cache = NULL;
2145 
2146 	ctx->msg.size = sizeof(ctx->msg.payload.state);
2147 	ctx->fd_num = 0;
2148 
2149 	vhost_user_iotlb_flush_all(vq);
2150 
2151 	vring_invalidate(dev, vq);
2152 
2153 	return RTE_VHOST_MSG_RESULT_REPLY;
2154 }
2155 
2156 /*
2157  * when virtio queues are ready to work, qemu will send us to
2158  * enable the virtio queue pair.
2159  */
2160 static int
2161 vhost_user_set_vring_enable(struct virtio_net **pdev,
2162 			struct vhu_msg_context *ctx,
2163 			int main_fd __rte_unused)
2164 {
2165 	struct virtio_net *dev = *pdev;
2166 	bool enable = !!ctx->msg.payload.state.num;
2167 	int index = (int)ctx->msg.payload.state.index;
2168 
2169 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2170 		"set queue enable: %d to qp idx: %d\n",
2171 		enable, index);
2172 
2173 	if (enable && dev->virtqueue[index]->async) {
2174 		if (dev->virtqueue[index]->async->pkts_inflight_n) {
2175 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2176 				"failed to enable vring. Inflight packets must be completed first\n");
2177 			return RTE_VHOST_MSG_RESULT_ERR;
2178 		}
2179 	}
2180 
2181 	dev->virtqueue[index]->enabled = enable;
2182 
2183 	return RTE_VHOST_MSG_RESULT_OK;
2184 }
2185 
2186 static int
2187 vhost_user_get_protocol_features(struct virtio_net **pdev,
2188 			struct vhu_msg_context *ctx,
2189 			int main_fd __rte_unused)
2190 {
2191 	struct virtio_net *dev = *pdev;
2192 	uint64_t features, protocol_features;
2193 
2194 	rte_vhost_driver_get_features(dev->ifname, &features);
2195 	rte_vhost_driver_get_protocol_features(dev->ifname, &protocol_features);
2196 
2197 	ctx->msg.payload.u64 = protocol_features;
2198 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
2199 	ctx->fd_num = 0;
2200 
2201 	return RTE_VHOST_MSG_RESULT_REPLY;
2202 }
2203 
2204 static int
2205 vhost_user_set_protocol_features(struct virtio_net **pdev,
2206 			struct vhu_msg_context *ctx,
2207 			int main_fd __rte_unused)
2208 {
2209 	struct virtio_net *dev = *pdev;
2210 	uint64_t protocol_features = ctx->msg.payload.u64;
2211 	uint64_t slave_protocol_features = 0;
2212 
2213 	rte_vhost_driver_get_protocol_features(dev->ifname,
2214 			&slave_protocol_features);
2215 	if (protocol_features & ~slave_protocol_features) {
2216 		VHOST_LOG_CONFIG(dev->ifname, ERR, "received invalid protocol features.\n");
2217 		return RTE_VHOST_MSG_RESULT_ERR;
2218 	}
2219 
2220 	dev->protocol_features = protocol_features;
2221 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2222 		"negotiated Vhost-user protocol features: 0x%" PRIx64 "\n",
2223 		dev->protocol_features);
2224 
2225 	return RTE_VHOST_MSG_RESULT_OK;
2226 }
2227 
2228 static int
2229 vhost_user_set_log_base(struct virtio_net **pdev,
2230 			struct vhu_msg_context *ctx,
2231 			int main_fd __rte_unused)
2232 {
2233 	struct virtio_net *dev = *pdev;
2234 	int fd = ctx->fds[0];
2235 	uint64_t size, off;
2236 	void *addr;
2237 	uint32_t i;
2238 
2239 	if (validate_msg_fds(dev, ctx, 1) != 0)
2240 		return RTE_VHOST_MSG_RESULT_ERR;
2241 
2242 	if (fd < 0) {
2243 		VHOST_LOG_CONFIG(dev->ifname, ERR, "invalid log fd: %d\n", fd);
2244 		return RTE_VHOST_MSG_RESULT_ERR;
2245 	}
2246 
2247 	if (ctx->msg.size != sizeof(VhostUserLog)) {
2248 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2249 			"invalid log base msg size: %"PRId32" != %d\n",
2250 			ctx->msg.size, (int)sizeof(VhostUserLog));
2251 		goto close_msg_fds;
2252 	}
2253 
2254 	size = ctx->msg.payload.log.mmap_size;
2255 	off  = ctx->msg.payload.log.mmap_offset;
2256 
2257 	/* Check for mmap size and offset overflow. */
2258 	if (off >= -size) {
2259 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2260 			"log offset %#"PRIx64" and log size %#"PRIx64" overflow\n",
2261 			off, size);
2262 		goto close_msg_fds;
2263 	}
2264 
2265 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2266 		"log mmap size: %"PRId64", offset: %"PRId64"\n",
2267 		size, off);
2268 
2269 	/*
2270 	 * mmap from 0 to workaround a hugepage mmap bug: mmap will
2271 	 * fail when offset is not page size aligned.
2272 	 */
2273 	addr = mmap(0, size + off, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2274 	close(fd);
2275 	if (addr == MAP_FAILED) {
2276 		VHOST_LOG_CONFIG(dev->ifname, ERR, "mmap log base failed!\n");
2277 		return RTE_VHOST_MSG_RESULT_ERR;
2278 	}
2279 
2280 	/*
2281 	 * Free previously mapped log memory on occasionally
2282 	 * multiple VHOST_USER_SET_LOG_BASE.
2283 	 */
2284 	if (dev->log_addr) {
2285 		munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
2286 	}
2287 	dev->log_addr = (uint64_t)(uintptr_t)addr;
2288 	dev->log_base = dev->log_addr + off;
2289 	dev->log_size = size;
2290 
2291 	for (i = 0; i < dev->nr_vring; i++) {
2292 		struct vhost_virtqueue *vq = dev->virtqueue[i];
2293 
2294 		rte_free(vq->log_cache);
2295 		vq->log_cache = NULL;
2296 		vq->log_cache_nb_elem = 0;
2297 		vq->log_cache = rte_malloc_socket("vq log cache",
2298 				sizeof(struct log_cache_entry) * VHOST_LOG_CACHE_NR,
2299 				0, vq->numa_node);
2300 		/*
2301 		 * If log cache alloc fail, don't fail migration, but no
2302 		 * caching will be done, which will impact performance
2303 		 */
2304 		if (!vq->log_cache)
2305 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2306 				"failed to allocate VQ logging cache\n");
2307 	}
2308 
2309 	/*
2310 	 * The spec is not clear about it (yet), but QEMU doesn't expect
2311 	 * any payload in the reply.
2312 	 */
2313 	ctx->msg.size = 0;
2314 	ctx->fd_num = 0;
2315 
2316 	return RTE_VHOST_MSG_RESULT_REPLY;
2317 
2318 close_msg_fds:
2319 	close_msg_fds(ctx);
2320 	return RTE_VHOST_MSG_RESULT_ERR;
2321 }
2322 
2323 static int vhost_user_set_log_fd(struct virtio_net **pdev,
2324 			struct vhu_msg_context *ctx,
2325 			int main_fd __rte_unused)
2326 {
2327 	struct virtio_net *dev = *pdev;
2328 
2329 	if (validate_msg_fds(dev, ctx, 1) != 0)
2330 		return RTE_VHOST_MSG_RESULT_ERR;
2331 
2332 	close(ctx->fds[0]);
2333 	VHOST_LOG_CONFIG(dev->ifname, INFO, "not implemented.\n");
2334 
2335 	return RTE_VHOST_MSG_RESULT_OK;
2336 }
2337 
2338 /*
2339  * An rarp packet is constructed and broadcasted to notify switches about
2340  * the new location of the migrated VM, so that packets from outside will
2341  * not be lost after migration.
2342  *
2343  * However, we don't actually "send" a rarp packet here, instead, we set
2344  * a flag 'broadcast_rarp' to let rte_vhost_dequeue_burst() inject it.
2345  */
2346 static int
2347 vhost_user_send_rarp(struct virtio_net **pdev,
2348 			struct vhu_msg_context *ctx,
2349 			int main_fd __rte_unused)
2350 {
2351 	struct virtio_net *dev = *pdev;
2352 	uint8_t *mac = (uint8_t *)&ctx->msg.payload.u64;
2353 	struct rte_vdpa_device *vdpa_dev;
2354 
2355 	VHOST_LOG_CONFIG(dev->ifname, DEBUG,
2356 		"MAC: " RTE_ETHER_ADDR_PRT_FMT "\n",
2357 		mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2358 	memcpy(dev->mac.addr_bytes, mac, 6);
2359 
2360 	/*
2361 	 * Set the flag to inject a RARP broadcast packet at
2362 	 * rte_vhost_dequeue_burst().
2363 	 *
2364 	 * __ATOMIC_RELEASE ordering is for making sure the mac is
2365 	 * copied before the flag is set.
2366 	 */
2367 	__atomic_store_n(&dev->broadcast_rarp, 1, __ATOMIC_RELEASE);
2368 	vdpa_dev = dev->vdpa_dev;
2369 	if (vdpa_dev && vdpa_dev->ops->migration_done)
2370 		vdpa_dev->ops->migration_done(dev->vid);
2371 
2372 	return RTE_VHOST_MSG_RESULT_OK;
2373 }
2374 
2375 static int
2376 vhost_user_net_set_mtu(struct virtio_net **pdev,
2377 			struct vhu_msg_context *ctx,
2378 			int main_fd __rte_unused)
2379 {
2380 	struct virtio_net *dev = *pdev;
2381 
2382 	if (ctx->msg.payload.u64 < VIRTIO_MIN_MTU ||
2383 			ctx->msg.payload.u64 > VIRTIO_MAX_MTU) {
2384 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2385 			"invalid MTU size (%"PRIu64")\n",
2386 			ctx->msg.payload.u64);
2387 
2388 		return RTE_VHOST_MSG_RESULT_ERR;
2389 	}
2390 
2391 	dev->mtu = ctx->msg.payload.u64;
2392 
2393 	return RTE_VHOST_MSG_RESULT_OK;
2394 }
2395 
2396 static int
2397 vhost_user_set_req_fd(struct virtio_net **pdev,
2398 			struct vhu_msg_context *ctx,
2399 			int main_fd __rte_unused)
2400 {
2401 	struct virtio_net *dev = *pdev;
2402 	int fd = ctx->fds[0];
2403 
2404 	if (validate_msg_fds(dev, ctx, 1) != 0)
2405 		return RTE_VHOST_MSG_RESULT_ERR;
2406 
2407 	if (fd < 0) {
2408 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2409 			"invalid file descriptor for slave channel (%d)\n", fd);
2410 		return RTE_VHOST_MSG_RESULT_ERR;
2411 	}
2412 
2413 	if (dev->slave_req_fd >= 0)
2414 		close(dev->slave_req_fd);
2415 
2416 	dev->slave_req_fd = fd;
2417 
2418 	return RTE_VHOST_MSG_RESULT_OK;
2419 }
2420 
2421 static int
2422 is_vring_iotlb_split(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2423 {
2424 	struct vhost_vring_addr *ra;
2425 	uint64_t start, end, len;
2426 
2427 	start = imsg->iova;
2428 	end = start + imsg->size;
2429 
2430 	ra = &vq->ring_addrs;
2431 	len = sizeof(struct vring_desc) * vq->size;
2432 	if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2433 		return 1;
2434 
2435 	len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
2436 	if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2437 		return 1;
2438 
2439 	len = sizeof(struct vring_used) +
2440 	       sizeof(struct vring_used_elem) * vq->size;
2441 	if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2442 		return 1;
2443 
2444 	if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2445 		len = sizeof(uint64_t);
2446 		if (ra->log_guest_addr < end &&
2447 		    (ra->log_guest_addr + len) > start)
2448 			return 1;
2449 	}
2450 
2451 	return 0;
2452 }
2453 
2454 static int
2455 is_vring_iotlb_packed(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2456 {
2457 	struct vhost_vring_addr *ra;
2458 	uint64_t start, end, len;
2459 
2460 	start = imsg->iova;
2461 	end = start + imsg->size;
2462 
2463 	ra = &vq->ring_addrs;
2464 	len = sizeof(struct vring_packed_desc) * vq->size;
2465 	if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2466 		return 1;
2467 
2468 	len = sizeof(struct vring_packed_desc_event);
2469 	if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2470 		return 1;
2471 
2472 	len = sizeof(struct vring_packed_desc_event);
2473 	if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2474 		return 1;
2475 
2476 	if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2477 		len = sizeof(uint64_t);
2478 		if (ra->log_guest_addr < end &&
2479 		    (ra->log_guest_addr + len) > start)
2480 			return 1;
2481 	}
2482 
2483 	return 0;
2484 }
2485 
2486 static int is_vring_iotlb(struct virtio_net *dev,
2487 			  struct vhost_virtqueue *vq,
2488 			  struct vhost_iotlb_msg *imsg)
2489 {
2490 	if (vq_is_packed(dev))
2491 		return is_vring_iotlb_packed(vq, imsg);
2492 	else
2493 		return is_vring_iotlb_split(vq, imsg);
2494 }
2495 
2496 static int
2497 vhost_user_get_config(struct virtio_net **pdev,
2498 			struct vhu_msg_context *ctx,
2499 			int main_fd __rte_unused)
2500 {
2501 	struct virtio_net *dev = *pdev;
2502 	struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
2503 	int ret = 0;
2504 
2505 	if (validate_msg_fds(dev, ctx, 0) != 0)
2506 		return RTE_VHOST_MSG_RESULT_ERR;
2507 
2508 	if (!vdpa_dev) {
2509 		VHOST_LOG_CONFIG(dev->ifname, ERR, "is not vDPA device!\n");
2510 		return RTE_VHOST_MSG_RESULT_ERR;
2511 	}
2512 
2513 	if (vdpa_dev->ops->get_config) {
2514 		ret = vdpa_dev->ops->get_config(dev->vid,
2515 					   ctx->msg.payload.cfg.region,
2516 					   ctx->msg.payload.cfg.size);
2517 		if (ret != 0) {
2518 			ctx->msg.size = 0;
2519 			VHOST_LOG_CONFIG(dev->ifname, ERR, "get_config() return error!\n");
2520 		}
2521 	} else {
2522 		VHOST_LOG_CONFIG(dev->ifname, ERR, "get_config() not supported!\n");
2523 	}
2524 
2525 	return RTE_VHOST_MSG_RESULT_REPLY;
2526 }
2527 
2528 static int
2529 vhost_user_set_config(struct virtio_net **pdev,
2530 			struct vhu_msg_context *ctx,
2531 			int main_fd __rte_unused)
2532 {
2533 	struct virtio_net *dev = *pdev;
2534 	struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
2535 	int ret = 0;
2536 
2537 	if (validate_msg_fds(dev, ctx, 0) != 0)
2538 		return RTE_VHOST_MSG_RESULT_ERR;
2539 
2540 	if (ctx->msg.payload.cfg.size > VHOST_USER_MAX_CONFIG_SIZE) {
2541 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2542 			"vhost_user_config size: %"PRIu32", should not be larger than %d\n",
2543 			ctx->msg.payload.cfg.size, VHOST_USER_MAX_CONFIG_SIZE);
2544 		goto out;
2545 	}
2546 
2547 	if (!vdpa_dev) {
2548 		VHOST_LOG_CONFIG(dev->ifname, ERR, "is not vDPA device!\n");
2549 		goto out;
2550 	}
2551 
2552 	if (vdpa_dev->ops->set_config) {
2553 		ret = vdpa_dev->ops->set_config(dev->vid,
2554 			ctx->msg.payload.cfg.region,
2555 			ctx->msg.payload.cfg.offset,
2556 			ctx->msg.payload.cfg.size,
2557 			ctx->msg.payload.cfg.flags);
2558 		if (ret)
2559 			VHOST_LOG_CONFIG(dev->ifname, ERR, "set_config() return error!\n");
2560 	} else {
2561 		VHOST_LOG_CONFIG(dev->ifname, ERR, "set_config() not supported!\n");
2562 	}
2563 
2564 	return RTE_VHOST_MSG_RESULT_OK;
2565 
2566 out:
2567 	return RTE_VHOST_MSG_RESULT_ERR;
2568 }
2569 
2570 static int
2571 vhost_user_iotlb_msg(struct virtio_net **pdev,
2572 			struct vhu_msg_context *ctx,
2573 			int main_fd __rte_unused)
2574 {
2575 	struct virtio_net *dev = *pdev;
2576 	struct vhost_iotlb_msg *imsg = &ctx->msg.payload.iotlb;
2577 	uint16_t i;
2578 	uint64_t vva, len;
2579 
2580 	switch (imsg->type) {
2581 	case VHOST_IOTLB_UPDATE:
2582 		len = imsg->size;
2583 		vva = qva_to_vva(dev, imsg->uaddr, &len);
2584 		if (!vva)
2585 			return RTE_VHOST_MSG_RESULT_ERR;
2586 
2587 		for (i = 0; i < dev->nr_vring; i++) {
2588 			struct vhost_virtqueue *vq = dev->virtqueue[i];
2589 
2590 			if (!vq)
2591 				continue;
2592 
2593 			vhost_user_iotlb_cache_insert(dev, vq, imsg->iova, vva,
2594 					len, imsg->perm);
2595 
2596 			if (is_vring_iotlb(dev, vq, imsg)) {
2597 				rte_spinlock_lock(&vq->access_lock);
2598 				*pdev = dev = translate_ring_addresses(dev, i);
2599 				rte_spinlock_unlock(&vq->access_lock);
2600 			}
2601 		}
2602 		break;
2603 	case VHOST_IOTLB_INVALIDATE:
2604 		for (i = 0; i < dev->nr_vring; i++) {
2605 			struct vhost_virtqueue *vq = dev->virtqueue[i];
2606 
2607 			if (!vq)
2608 				continue;
2609 
2610 			vhost_user_iotlb_cache_remove(vq, imsg->iova,
2611 					imsg->size);
2612 
2613 			if (is_vring_iotlb(dev, vq, imsg)) {
2614 				rte_spinlock_lock(&vq->access_lock);
2615 				vring_invalidate(dev, vq);
2616 				rte_spinlock_unlock(&vq->access_lock);
2617 			}
2618 		}
2619 		break;
2620 	default:
2621 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2622 			"invalid IOTLB message type (%d)\n",
2623 			imsg->type);
2624 		return RTE_VHOST_MSG_RESULT_ERR;
2625 	}
2626 
2627 	return RTE_VHOST_MSG_RESULT_OK;
2628 }
2629 
2630 static int
2631 vhost_user_set_postcopy_advise(struct virtio_net **pdev,
2632 			struct vhu_msg_context *ctx,
2633 			int main_fd __rte_unused)
2634 {
2635 	struct virtio_net *dev = *pdev;
2636 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
2637 	struct uffdio_api api_struct;
2638 
2639 	dev->postcopy_ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
2640 
2641 	if (dev->postcopy_ufd == -1) {
2642 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2643 			"userfaultfd not available: %s\n",
2644 			strerror(errno));
2645 		return RTE_VHOST_MSG_RESULT_ERR;
2646 	}
2647 	api_struct.api = UFFD_API;
2648 	api_struct.features = 0;
2649 	if (ioctl(dev->postcopy_ufd, UFFDIO_API, &api_struct)) {
2650 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2651 			"UFFDIO_API ioctl failure: %s\n",
2652 			strerror(errno));
2653 		close(dev->postcopy_ufd);
2654 		dev->postcopy_ufd = -1;
2655 		return RTE_VHOST_MSG_RESULT_ERR;
2656 	}
2657 	ctx->fds[0] = dev->postcopy_ufd;
2658 	ctx->fd_num = 1;
2659 
2660 	return RTE_VHOST_MSG_RESULT_REPLY;
2661 #else
2662 	dev->postcopy_ufd = -1;
2663 	ctx->fd_num = 0;
2664 
2665 	return RTE_VHOST_MSG_RESULT_ERR;
2666 #endif
2667 }
2668 
2669 static int
2670 vhost_user_set_postcopy_listen(struct virtio_net **pdev,
2671 			struct vhu_msg_context *ctx __rte_unused,
2672 			int main_fd __rte_unused)
2673 {
2674 	struct virtio_net *dev = *pdev;
2675 
2676 	if (dev->mem && dev->mem->nregions) {
2677 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2678 			"regions already registered at postcopy-listen\n");
2679 		return RTE_VHOST_MSG_RESULT_ERR;
2680 	}
2681 	dev->postcopy_listening = 1;
2682 
2683 	return RTE_VHOST_MSG_RESULT_OK;
2684 }
2685 
2686 static int
2687 vhost_user_postcopy_end(struct virtio_net **pdev,
2688 			struct vhu_msg_context *ctx,
2689 			int main_fd __rte_unused)
2690 {
2691 	struct virtio_net *dev = *pdev;
2692 
2693 	dev->postcopy_listening = 0;
2694 	if (dev->postcopy_ufd >= 0) {
2695 		close(dev->postcopy_ufd);
2696 		dev->postcopy_ufd = -1;
2697 	}
2698 
2699 	ctx->msg.payload.u64 = 0;
2700 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
2701 	ctx->fd_num = 0;
2702 
2703 	return RTE_VHOST_MSG_RESULT_REPLY;
2704 }
2705 
2706 static int
2707 vhost_user_get_status(struct virtio_net **pdev,
2708 		      struct vhu_msg_context *ctx,
2709 		      int main_fd __rte_unused)
2710 {
2711 	struct virtio_net *dev = *pdev;
2712 
2713 	ctx->msg.payload.u64 = dev->status;
2714 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
2715 	ctx->fd_num = 0;
2716 
2717 	return RTE_VHOST_MSG_RESULT_REPLY;
2718 }
2719 
2720 static int
2721 vhost_user_set_status(struct virtio_net **pdev,
2722 			struct vhu_msg_context *ctx,
2723 			int main_fd __rte_unused)
2724 {
2725 	struct virtio_net *dev = *pdev;
2726 
2727 	/* As per Virtio specification, the device status is 8bits long */
2728 	if (ctx->msg.payload.u64 > UINT8_MAX) {
2729 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2730 			"invalid VHOST_USER_SET_STATUS payload 0x%" PRIx64 "\n",
2731 			ctx->msg.payload.u64);
2732 		return RTE_VHOST_MSG_RESULT_ERR;
2733 	}
2734 
2735 	dev->status = ctx->msg.payload.u64;
2736 
2737 	if ((dev->status & VIRTIO_DEVICE_STATUS_FEATURES_OK) &&
2738 	    (dev->flags & VIRTIO_DEV_FEATURES_FAILED)) {
2739 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2740 			"FEATURES_OK bit is set but feature negotiation failed\n");
2741 		/*
2742 		 * Clear the bit to let the driver know about the feature
2743 		 * negotiation failure
2744 		 */
2745 		dev->status &= ~VIRTIO_DEVICE_STATUS_FEATURES_OK;
2746 	}
2747 
2748 	VHOST_LOG_CONFIG(dev->ifname, INFO, "new device status(0x%08x):\n", dev->status);
2749 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2750 		"\t-RESET: %u\n",
2751 		(dev->status == VIRTIO_DEVICE_STATUS_RESET));
2752 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2753 		"\t-ACKNOWLEDGE: %u\n",
2754 		!!(dev->status & VIRTIO_DEVICE_STATUS_ACK));
2755 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2756 		"\t-DRIVER: %u\n",
2757 		!!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER));
2758 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2759 		"\t-FEATURES_OK: %u\n",
2760 		!!(dev->status & VIRTIO_DEVICE_STATUS_FEATURES_OK));
2761 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2762 		"\t-DRIVER_OK: %u\n",
2763 		!!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER_OK));
2764 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2765 		"\t-DEVICE_NEED_RESET: %u\n",
2766 		!!(dev->status & VIRTIO_DEVICE_STATUS_DEV_NEED_RESET));
2767 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2768 		"\t-FAILED: %u\n",
2769 		!!(dev->status & VIRTIO_DEVICE_STATUS_FAILED));
2770 
2771 	return RTE_VHOST_MSG_RESULT_OK;
2772 }
2773 
2774 #define VHOST_MESSAGE_HANDLERS \
2775 VHOST_MESSAGE_HANDLER(VHOST_USER_NONE, NULL, false) \
2776 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_FEATURES, vhost_user_get_features, false) \
2777 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_FEATURES, vhost_user_set_features, false) \
2778 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_OWNER, vhost_user_set_owner, false) \
2779 VHOST_MESSAGE_HANDLER(VHOST_USER_RESET_OWNER, vhost_user_reset_owner, false) \
2780 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_MEM_TABLE, vhost_user_set_mem_table, true) \
2781 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_LOG_BASE, vhost_user_set_log_base, true) \
2782 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_LOG_FD, vhost_user_set_log_fd, true) \
2783 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_NUM, vhost_user_set_vring_num, false) \
2784 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_ADDR, vhost_user_set_vring_addr, false) \
2785 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_BASE, vhost_user_set_vring_base, false) \
2786 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_VRING_BASE, vhost_user_get_vring_base, false) \
2787 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_KICK, vhost_user_set_vring_kick, true) \
2788 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_CALL, vhost_user_set_vring_call, true) \
2789 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_ERR, vhost_user_set_vring_err, true) \
2790 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_PROTOCOL_FEATURES, vhost_user_get_protocol_features, false) \
2791 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_PROTOCOL_FEATURES, vhost_user_set_protocol_features, false) \
2792 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_QUEUE_NUM, vhost_user_get_queue_num, false) \
2793 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_ENABLE, vhost_user_set_vring_enable, false) \
2794 VHOST_MESSAGE_HANDLER(VHOST_USER_SEND_RARP, vhost_user_send_rarp, false) \
2795 VHOST_MESSAGE_HANDLER(VHOST_USER_NET_SET_MTU, vhost_user_net_set_mtu, false) \
2796 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_SLAVE_REQ_FD, vhost_user_set_req_fd, true) \
2797 VHOST_MESSAGE_HANDLER(VHOST_USER_IOTLB_MSG, vhost_user_iotlb_msg, false) \
2798 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_CONFIG, vhost_user_get_config, false) \
2799 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_CONFIG, vhost_user_set_config, false) \
2800 VHOST_MESSAGE_HANDLER(VHOST_USER_POSTCOPY_ADVISE, vhost_user_set_postcopy_advise, false) \
2801 VHOST_MESSAGE_HANDLER(VHOST_USER_POSTCOPY_LISTEN, vhost_user_set_postcopy_listen, false) \
2802 VHOST_MESSAGE_HANDLER(VHOST_USER_POSTCOPY_END, vhost_user_postcopy_end, false) \
2803 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_INFLIGHT_FD, vhost_user_get_inflight_fd, false) \
2804 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_INFLIGHT_FD, vhost_user_set_inflight_fd, true) \
2805 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_STATUS, vhost_user_set_status, false) \
2806 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_STATUS, vhost_user_get_status, false)
2807 
2808 #define VHOST_MESSAGE_HANDLER(id, handler, accepts_fd) \
2809 	[id] = { #id, handler, accepts_fd },
2810 static vhost_message_handler_t vhost_message_handlers[] = {
2811 	VHOST_MESSAGE_HANDLERS
2812 };
2813 #undef VHOST_MESSAGE_HANDLER
2814 
2815 /* return bytes# of read on success or negative val on failure. */
2816 static int
2817 read_vhost_message(struct virtio_net *dev, int sockfd, struct  vhu_msg_context *ctx)
2818 {
2819 	int ret;
2820 
2821 	ret = read_fd_message(dev->ifname, sockfd, (char *)&ctx->msg, VHOST_USER_HDR_SIZE,
2822 		ctx->fds, VHOST_MEMORY_MAX_NREGIONS, &ctx->fd_num);
2823 	if (ret <= 0) {
2824 		return ret;
2825 	} else if (ret != VHOST_USER_HDR_SIZE) {
2826 		VHOST_LOG_CONFIG(dev->ifname, ERR, "Unexpected header size read\n");
2827 		close_msg_fds(ctx);
2828 		return -1;
2829 	}
2830 
2831 	if (ctx->msg.size) {
2832 		if (ctx->msg.size > sizeof(ctx->msg.payload)) {
2833 			VHOST_LOG_CONFIG(dev->ifname, ERR, "invalid msg size: %d\n",
2834 				ctx->msg.size);
2835 			return -1;
2836 		}
2837 		ret = read(sockfd, &ctx->msg.payload, ctx->msg.size);
2838 		if (ret <= 0)
2839 			return ret;
2840 		if (ret != (int)ctx->msg.size) {
2841 			VHOST_LOG_CONFIG(dev->ifname, ERR, "read control message failed\n");
2842 			return -1;
2843 		}
2844 	}
2845 
2846 	return ret;
2847 }
2848 
2849 static int
2850 send_vhost_message(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx)
2851 {
2852 	if (!ctx)
2853 		return 0;
2854 
2855 	return send_fd_message(dev->ifname, sockfd, (char *)&ctx->msg,
2856 		VHOST_USER_HDR_SIZE + ctx->msg.size, ctx->fds, ctx->fd_num);
2857 }
2858 
2859 static int
2860 send_vhost_reply(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx)
2861 {
2862 	if (!ctx)
2863 		return 0;
2864 
2865 	ctx->msg.flags &= ~VHOST_USER_VERSION_MASK;
2866 	ctx->msg.flags &= ~VHOST_USER_NEED_REPLY;
2867 	ctx->msg.flags |= VHOST_USER_VERSION;
2868 	ctx->msg.flags |= VHOST_USER_REPLY_MASK;
2869 
2870 	return send_vhost_message(dev, sockfd, ctx);
2871 }
2872 
2873 static int
2874 send_vhost_slave_message(struct virtio_net *dev,
2875 		struct vhu_msg_context *ctx)
2876 {
2877 	int ret;
2878 
2879 	if (ctx->msg.flags & VHOST_USER_NEED_REPLY)
2880 		rte_spinlock_lock(&dev->slave_req_lock);
2881 
2882 	ret = send_vhost_message(dev, dev->slave_req_fd, ctx);
2883 	if (ret < 0 && (ctx->msg.flags & VHOST_USER_NEED_REPLY))
2884 		rte_spinlock_unlock(&dev->slave_req_lock);
2885 
2886 	return ret;
2887 }
2888 
2889 /*
2890  * Allocate a queue pair if it hasn't been allocated yet
2891  */
2892 static int
2893 vhost_user_check_and_alloc_queue_pair(struct virtio_net *dev,
2894 			struct vhu_msg_context *ctx)
2895 {
2896 	uint32_t vring_idx;
2897 
2898 	switch (ctx->msg.request.master) {
2899 	case VHOST_USER_SET_VRING_KICK:
2900 	case VHOST_USER_SET_VRING_CALL:
2901 	case VHOST_USER_SET_VRING_ERR:
2902 		vring_idx = ctx->msg.payload.u64 & VHOST_USER_VRING_IDX_MASK;
2903 		break;
2904 	case VHOST_USER_SET_VRING_NUM:
2905 	case VHOST_USER_SET_VRING_BASE:
2906 	case VHOST_USER_GET_VRING_BASE:
2907 	case VHOST_USER_SET_VRING_ENABLE:
2908 		vring_idx = ctx->msg.payload.state.index;
2909 		break;
2910 	case VHOST_USER_SET_VRING_ADDR:
2911 		vring_idx = ctx->msg.payload.addr.index;
2912 		break;
2913 	case VHOST_USER_SET_INFLIGHT_FD:
2914 		vring_idx = ctx->msg.payload.inflight.num_queues - 1;
2915 		break;
2916 	default:
2917 		return 0;
2918 	}
2919 
2920 	if (vring_idx >= VHOST_MAX_VRING) {
2921 		VHOST_LOG_CONFIG(dev->ifname, ERR, "invalid vring index: %u\n", vring_idx);
2922 		return -1;
2923 	}
2924 
2925 	if (dev->virtqueue[vring_idx])
2926 		return 0;
2927 
2928 	return alloc_vring_queue(dev, vring_idx);
2929 }
2930 
2931 static void
2932 vhost_user_lock_all_queue_pairs(struct virtio_net *dev)
2933 {
2934 	unsigned int i = 0;
2935 	unsigned int vq_num = 0;
2936 
2937 	while (vq_num < dev->nr_vring) {
2938 		struct vhost_virtqueue *vq = dev->virtqueue[i];
2939 
2940 		if (vq) {
2941 			rte_spinlock_lock(&vq->access_lock);
2942 			vq_num++;
2943 		}
2944 		i++;
2945 	}
2946 }
2947 
2948 static void
2949 vhost_user_unlock_all_queue_pairs(struct virtio_net *dev)
2950 {
2951 	unsigned int i = 0;
2952 	unsigned int vq_num = 0;
2953 
2954 	while (vq_num < dev->nr_vring) {
2955 		struct vhost_virtqueue *vq = dev->virtqueue[i];
2956 
2957 		if (vq) {
2958 			rte_spinlock_unlock(&vq->access_lock);
2959 			vq_num++;
2960 		}
2961 		i++;
2962 	}
2963 }
2964 
2965 int
2966 vhost_user_msg_handler(int vid, int fd)
2967 {
2968 	struct virtio_net *dev;
2969 	struct vhu_msg_context ctx;
2970 	vhost_message_handler_t *msg_handler;
2971 	struct rte_vdpa_device *vdpa_dev;
2972 	int ret;
2973 	int unlock_required = 0;
2974 	bool handled;
2975 	uint32_t vdpa_type = 0;
2976 	uint32_t request;
2977 	uint32_t i;
2978 
2979 	dev = get_device(vid);
2980 	if (dev == NULL)
2981 		return -1;
2982 
2983 	if (!dev->notify_ops) {
2984 		dev->notify_ops = vhost_driver_callback_get(dev->ifname);
2985 		if (!dev->notify_ops) {
2986 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2987 				"failed to get callback ops for driver\n");
2988 			return -1;
2989 		}
2990 	}
2991 
2992 	ret = read_vhost_message(dev, fd, &ctx);
2993 	if (ret <= 0) {
2994 		if (ret < 0)
2995 			VHOST_LOG_CONFIG(dev->ifname, ERR, "vhost read message failed\n");
2996 		else
2997 			VHOST_LOG_CONFIG(dev->ifname, INFO, "vhost peer closed\n");
2998 
2999 		return -1;
3000 	}
3001 
3002 	request = ctx.msg.request.master;
3003 	if (request > VHOST_USER_NONE && request < RTE_DIM(vhost_message_handlers))
3004 		msg_handler = &vhost_message_handlers[request];
3005 	else
3006 		msg_handler = NULL;
3007 
3008 	if (msg_handler != NULL && msg_handler->description != NULL) {
3009 		if (request != VHOST_USER_IOTLB_MSG)
3010 			VHOST_LOG_CONFIG(dev->ifname, INFO,
3011 				"read message %s\n",
3012 				msg_handler->description);
3013 		else
3014 			VHOST_LOG_CONFIG(dev->ifname, DEBUG,
3015 				"read message %s\n",
3016 				msg_handler->description);
3017 	} else {
3018 		VHOST_LOG_CONFIG(dev->ifname, DEBUG, "external request %d\n", request);
3019 	}
3020 
3021 	ret = vhost_user_check_and_alloc_queue_pair(dev, &ctx);
3022 	if (ret < 0) {
3023 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to alloc queue\n");
3024 		return -1;
3025 	}
3026 
3027 	/*
3028 	 * Note: we don't lock all queues on VHOST_USER_GET_VRING_BASE
3029 	 * and VHOST_USER_RESET_OWNER, since it is sent when virtio stops
3030 	 * and device is destroyed. destroy_device waits for queues to be
3031 	 * inactive, so it is safe. Otherwise taking the access_lock
3032 	 * would cause a dead lock.
3033 	 */
3034 	switch (request) {
3035 	case VHOST_USER_SET_FEATURES:
3036 	case VHOST_USER_SET_PROTOCOL_FEATURES:
3037 	case VHOST_USER_SET_OWNER:
3038 	case VHOST_USER_SET_MEM_TABLE:
3039 	case VHOST_USER_SET_LOG_BASE:
3040 	case VHOST_USER_SET_LOG_FD:
3041 	case VHOST_USER_SET_VRING_NUM:
3042 	case VHOST_USER_SET_VRING_ADDR:
3043 	case VHOST_USER_SET_VRING_BASE:
3044 	case VHOST_USER_SET_VRING_KICK:
3045 	case VHOST_USER_SET_VRING_CALL:
3046 	case VHOST_USER_SET_VRING_ERR:
3047 	case VHOST_USER_SET_VRING_ENABLE:
3048 	case VHOST_USER_SEND_RARP:
3049 	case VHOST_USER_NET_SET_MTU:
3050 	case VHOST_USER_SET_SLAVE_REQ_FD:
3051 		if (!(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED)) {
3052 			vhost_user_lock_all_queue_pairs(dev);
3053 			unlock_required = 1;
3054 		}
3055 		break;
3056 	default:
3057 		break;
3058 
3059 	}
3060 
3061 	handled = false;
3062 	if (dev->extern_ops.pre_msg_handle) {
3063 		RTE_BUILD_BUG_ON(offsetof(struct vhu_msg_context, msg) != 0);
3064 		ret = (*dev->extern_ops.pre_msg_handle)(dev->vid, &ctx);
3065 		switch (ret) {
3066 		case RTE_VHOST_MSG_RESULT_REPLY:
3067 			send_vhost_reply(dev, fd, &ctx);
3068 			/* Fall-through */
3069 		case RTE_VHOST_MSG_RESULT_ERR:
3070 		case RTE_VHOST_MSG_RESULT_OK:
3071 			handled = true;
3072 			goto skip_to_post_handle;
3073 		case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
3074 		default:
3075 			break;
3076 		}
3077 	}
3078 
3079 	if (msg_handler == NULL || msg_handler->callback == NULL)
3080 		goto skip_to_post_handle;
3081 
3082 	if (!msg_handler->accepts_fd && validate_msg_fds(dev, &ctx, 0) != 0) {
3083 		ret = RTE_VHOST_MSG_RESULT_ERR;
3084 	} else {
3085 		ret = msg_handler->callback(&dev, &ctx, fd);
3086 	}
3087 
3088 	switch (ret) {
3089 	case RTE_VHOST_MSG_RESULT_ERR:
3090 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3091 			"processing %s failed.\n",
3092 			msg_handler->description);
3093 		handled = true;
3094 		break;
3095 	case RTE_VHOST_MSG_RESULT_OK:
3096 		VHOST_LOG_CONFIG(dev->ifname, DEBUG,
3097 			"processing %s succeeded.\n",
3098 			msg_handler->description);
3099 		handled = true;
3100 		break;
3101 	case RTE_VHOST_MSG_RESULT_REPLY:
3102 		VHOST_LOG_CONFIG(dev->ifname, DEBUG,
3103 			"processing %s succeeded and needs reply.\n",
3104 			msg_handler->description);
3105 		send_vhost_reply(dev, fd, &ctx);
3106 		handled = true;
3107 		break;
3108 	default:
3109 		break;
3110 	}
3111 
3112 skip_to_post_handle:
3113 	if (ret != RTE_VHOST_MSG_RESULT_ERR &&
3114 			dev->extern_ops.post_msg_handle) {
3115 		RTE_BUILD_BUG_ON(offsetof(struct vhu_msg_context, msg) != 0);
3116 		ret = (*dev->extern_ops.post_msg_handle)(dev->vid, &ctx);
3117 		switch (ret) {
3118 		case RTE_VHOST_MSG_RESULT_REPLY:
3119 			send_vhost_reply(dev, fd, &ctx);
3120 			/* Fall-through */
3121 		case RTE_VHOST_MSG_RESULT_ERR:
3122 		case RTE_VHOST_MSG_RESULT_OK:
3123 			handled = true;
3124 		case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
3125 		default:
3126 			break;
3127 		}
3128 	}
3129 
3130 	/* If message was not handled at this stage, treat it as an error */
3131 	if (!handled) {
3132 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3133 			"vhost message (req: %d) was not handled.\n",
3134 			request);
3135 		close_msg_fds(&ctx);
3136 		ret = RTE_VHOST_MSG_RESULT_ERR;
3137 	}
3138 
3139 	/*
3140 	 * If the request required a reply that was already sent,
3141 	 * this optional reply-ack won't be sent as the
3142 	 * VHOST_USER_NEED_REPLY was cleared in send_vhost_reply().
3143 	 */
3144 	if (ctx.msg.flags & VHOST_USER_NEED_REPLY) {
3145 		ctx.msg.payload.u64 = ret == RTE_VHOST_MSG_RESULT_ERR;
3146 		ctx.msg.size = sizeof(ctx.msg.payload.u64);
3147 		ctx.fd_num = 0;
3148 		send_vhost_reply(dev, fd, &ctx);
3149 	} else if (ret == RTE_VHOST_MSG_RESULT_ERR) {
3150 		VHOST_LOG_CONFIG(dev->ifname, ERR, "vhost message handling failed.\n");
3151 		ret = -1;
3152 		goto unlock;
3153 	}
3154 
3155 	ret = 0;
3156 	for (i = 0; i < dev->nr_vring; i++) {
3157 		struct vhost_virtqueue *vq = dev->virtqueue[i];
3158 		bool cur_ready = vq_is_ready(dev, vq);
3159 
3160 		if (cur_ready != (vq && vq->ready)) {
3161 			vq->ready = cur_ready;
3162 			vhost_user_notify_queue_state(dev, i, cur_ready);
3163 		}
3164 	}
3165 
3166 unlock:
3167 	if (unlock_required)
3168 		vhost_user_unlock_all_queue_pairs(dev);
3169 
3170 	if (ret != 0 || !virtio_is_ready(dev))
3171 		goto out;
3172 
3173 	/*
3174 	 * Virtio is now ready. If not done already, it is time
3175 	 * to notify the application it can process the rings and
3176 	 * configure the vDPA device if present.
3177 	 */
3178 
3179 	if (!(dev->flags & VIRTIO_DEV_RUNNING)) {
3180 		if (dev->notify_ops->new_device(dev->vid) == 0)
3181 			dev->flags |= VIRTIO_DEV_RUNNING;
3182 	}
3183 
3184 	vdpa_dev = dev->vdpa_dev;
3185 	if (!vdpa_dev)
3186 		goto out;
3187 
3188 	if (vdpa_dev->ops->get_dev_type) {
3189 		ret = vdpa_dev->ops->get_dev_type(vdpa_dev, &vdpa_type);
3190 		if (ret) {
3191 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to get vdpa dev type.\n");
3192 			ret = -1;
3193 			goto out;
3194 		}
3195 	} else {
3196 		vdpa_type = RTE_VHOST_VDPA_DEVICE_TYPE_NET;
3197 	}
3198 	if (vdpa_type == RTE_VHOST_VDPA_DEVICE_TYPE_BLK
3199 		&& request != VHOST_USER_SET_VRING_CALL)
3200 		goto out;
3201 
3202 	if (!(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED)) {
3203 		if (vdpa_dev->ops->dev_conf(dev->vid))
3204 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to configure vDPA device\n");
3205 		else
3206 			dev->flags |= VIRTIO_DEV_VDPA_CONFIGURED;
3207 	}
3208 
3209 out:
3210 	return ret;
3211 }
3212 
3213 static int process_slave_message_reply(struct virtio_net *dev,
3214 				       const struct vhu_msg_context *ctx)
3215 {
3216 	struct vhu_msg_context msg_reply;
3217 	int ret;
3218 
3219 	if ((ctx->msg.flags & VHOST_USER_NEED_REPLY) == 0)
3220 		return 0;
3221 
3222 	ret = read_vhost_message(dev, dev->slave_req_fd, &msg_reply);
3223 	if (ret <= 0) {
3224 		if (ret < 0)
3225 			VHOST_LOG_CONFIG(dev->ifname, ERR,
3226 				"vhost read slave message reply failed\n");
3227 		else
3228 			VHOST_LOG_CONFIG(dev->ifname, INFO, "vhost peer closed\n");
3229 		ret = -1;
3230 		goto out;
3231 	}
3232 
3233 	ret = 0;
3234 	if (msg_reply.msg.request.slave != ctx->msg.request.slave) {
3235 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3236 			"received unexpected msg type (%u), expected %u\n",
3237 			msg_reply.msg.request.slave, ctx->msg.request.slave);
3238 		ret = -1;
3239 		goto out;
3240 	}
3241 
3242 	ret = msg_reply.msg.payload.u64 ? -1 : 0;
3243 
3244 out:
3245 	rte_spinlock_unlock(&dev->slave_req_lock);
3246 	return ret;
3247 }
3248 
3249 int
3250 vhost_user_iotlb_miss(struct virtio_net *dev, uint64_t iova, uint8_t perm)
3251 {
3252 	int ret;
3253 	struct vhu_msg_context ctx = {
3254 		.msg = {
3255 			.request.slave = VHOST_USER_SLAVE_IOTLB_MSG,
3256 			.flags = VHOST_USER_VERSION,
3257 			.size = sizeof(ctx.msg.payload.iotlb),
3258 			.payload.iotlb = {
3259 				.iova = iova,
3260 				.perm = perm,
3261 				.type = VHOST_IOTLB_MISS,
3262 			},
3263 		},
3264 	};
3265 
3266 	ret = send_vhost_message(dev, dev->slave_req_fd, &ctx);
3267 	if (ret < 0) {
3268 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3269 			"failed to send IOTLB miss message (%d)\n",
3270 			ret);
3271 		return ret;
3272 	}
3273 
3274 	return 0;
3275 }
3276 
3277 static int
3278 vhost_user_slave_config_change(struct virtio_net *dev, bool need_reply)
3279 {
3280 	int ret;
3281 	struct vhu_msg_context ctx = {
3282 		.msg = {
3283 			.request.slave = VHOST_USER_SLAVE_CONFIG_CHANGE_MSG,
3284 			.flags = VHOST_USER_VERSION,
3285 			.size = 0,
3286 		}
3287 	};
3288 
3289 	if (need_reply)
3290 		ctx.msg.flags |= VHOST_USER_NEED_REPLY;
3291 
3292 	ret = send_vhost_slave_message(dev, &ctx);
3293 	if (ret < 0) {
3294 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to send config change (%d)\n", ret);
3295 		return ret;
3296 	}
3297 
3298 	return process_slave_message_reply(dev, &ctx);
3299 }
3300 
3301 int
3302 rte_vhost_slave_config_change(int vid, bool need_reply)
3303 {
3304 	struct virtio_net *dev;
3305 
3306 	dev = get_device(vid);
3307 	if (!dev)
3308 		return -ENODEV;
3309 
3310 	return vhost_user_slave_config_change(dev, need_reply);
3311 }
3312 
3313 static int vhost_user_slave_set_vring_host_notifier(struct virtio_net *dev,
3314 						    int index, int fd,
3315 						    uint64_t offset,
3316 						    uint64_t size)
3317 {
3318 	int ret;
3319 	struct vhu_msg_context ctx = {
3320 		.msg = {
3321 			.request.slave = VHOST_USER_SLAVE_VRING_HOST_NOTIFIER_MSG,
3322 			.flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY,
3323 			.size = sizeof(ctx.msg.payload.area),
3324 			.payload.area = {
3325 				.u64 = index & VHOST_USER_VRING_IDX_MASK,
3326 				.size = size,
3327 				.offset = offset,
3328 			},
3329 		},
3330 	};
3331 
3332 	if (fd < 0)
3333 		ctx.msg.payload.area.u64 |= VHOST_USER_VRING_NOFD_MASK;
3334 	else {
3335 		ctx.fds[0] = fd;
3336 		ctx.fd_num = 1;
3337 	}
3338 
3339 	ret = send_vhost_slave_message(dev, &ctx);
3340 	if (ret < 0) {
3341 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to set host notifier (%d)\n", ret);
3342 		return ret;
3343 	}
3344 
3345 	return process_slave_message_reply(dev, &ctx);
3346 }
3347 
3348 int rte_vhost_host_notifier_ctrl(int vid, uint16_t qid, bool enable)
3349 {
3350 	struct virtio_net *dev;
3351 	struct rte_vdpa_device *vdpa_dev;
3352 	int vfio_device_fd, ret = 0;
3353 	uint64_t offset, size;
3354 	unsigned int i, q_start, q_last;
3355 
3356 	dev = get_device(vid);
3357 	if (!dev)
3358 		return -ENODEV;
3359 
3360 	vdpa_dev = dev->vdpa_dev;
3361 	if (vdpa_dev == NULL)
3362 		return -ENODEV;
3363 
3364 	if (!(dev->features & (1ULL << VIRTIO_F_VERSION_1)) ||
3365 	    !(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES)) ||
3366 	    !(dev->protocol_features &
3367 			(1ULL << VHOST_USER_PROTOCOL_F_SLAVE_REQ)) ||
3368 	    !(dev->protocol_features &
3369 			(1ULL << VHOST_USER_PROTOCOL_F_SLAVE_SEND_FD)) ||
3370 	    !(dev->protocol_features &
3371 			(1ULL << VHOST_USER_PROTOCOL_F_HOST_NOTIFIER)))
3372 		return -ENOTSUP;
3373 
3374 	if (qid == RTE_VHOST_QUEUE_ALL) {
3375 		q_start = 0;
3376 		q_last = dev->nr_vring - 1;
3377 	} else {
3378 		if (qid >= dev->nr_vring)
3379 			return -EINVAL;
3380 		q_start = qid;
3381 		q_last = qid;
3382 	}
3383 
3384 	RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_vfio_device_fd, -ENOTSUP);
3385 	RTE_FUNC_PTR_OR_ERR_RET(vdpa_dev->ops->get_notify_area, -ENOTSUP);
3386 
3387 	vfio_device_fd = vdpa_dev->ops->get_vfio_device_fd(vid);
3388 	if (vfio_device_fd < 0)
3389 		return -ENOTSUP;
3390 
3391 	if (enable) {
3392 		for (i = q_start; i <= q_last; i++) {
3393 			if (vdpa_dev->ops->get_notify_area(vid, i, &offset,
3394 					&size) < 0) {
3395 				ret = -ENOTSUP;
3396 				goto disable;
3397 			}
3398 
3399 			if (vhost_user_slave_set_vring_host_notifier(dev, i,
3400 					vfio_device_fd, offset, size) < 0) {
3401 				ret = -EFAULT;
3402 				goto disable;
3403 			}
3404 		}
3405 	} else {
3406 disable:
3407 		for (i = q_start; i <= q_last; i++) {
3408 			vhost_user_slave_set_vring_host_notifier(dev, i, -1,
3409 					0, 0);
3410 		}
3411 	}
3412 
3413 	return ret;
3414 }
3415