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