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