xref: /dpdk/lib/vhost/vhost_user.c (revision 09442498ef736d0a96632cf8b8c15d8ca78a6468)
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, INFO, "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 	bool enable = !!ctx->msg.payload.state.num;
2172 	int index = (int)ctx->msg.payload.state.index;
2173 
2174 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2175 		"set queue enable: %d to qp idx: %d\n",
2176 		enable, index);
2177 
2178 	if (enable && dev->virtqueue[index]->async) {
2179 		if (dev->virtqueue[index]->async->pkts_inflight_n) {
2180 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2181 				"failed to enable vring. Inflight packets must be completed first\n");
2182 			return RTE_VHOST_MSG_RESULT_ERR;
2183 		}
2184 	}
2185 
2186 	dev->virtqueue[index]->enabled = enable;
2187 
2188 	return RTE_VHOST_MSG_RESULT_OK;
2189 }
2190 
2191 static int
2192 vhost_user_get_protocol_features(struct virtio_net **pdev,
2193 			struct vhu_msg_context *ctx,
2194 			int main_fd __rte_unused)
2195 {
2196 	struct virtio_net *dev = *pdev;
2197 	uint64_t features, protocol_features;
2198 
2199 	rte_vhost_driver_get_features(dev->ifname, &features);
2200 	rte_vhost_driver_get_protocol_features(dev->ifname, &protocol_features);
2201 
2202 	ctx->msg.payload.u64 = protocol_features;
2203 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
2204 	ctx->fd_num = 0;
2205 
2206 	return RTE_VHOST_MSG_RESULT_REPLY;
2207 }
2208 
2209 static int
2210 vhost_user_set_protocol_features(struct virtio_net **pdev,
2211 			struct vhu_msg_context *ctx,
2212 			int main_fd __rte_unused)
2213 {
2214 	struct virtio_net *dev = *pdev;
2215 	uint64_t protocol_features = ctx->msg.payload.u64;
2216 	uint64_t slave_protocol_features = 0;
2217 
2218 	rte_vhost_driver_get_protocol_features(dev->ifname,
2219 			&slave_protocol_features);
2220 	if (protocol_features & ~slave_protocol_features) {
2221 		VHOST_LOG_CONFIG(dev->ifname, ERR, "received invalid protocol features.\n");
2222 		return RTE_VHOST_MSG_RESULT_ERR;
2223 	}
2224 
2225 	dev->protocol_features = protocol_features;
2226 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2227 		"negotiated Vhost-user protocol features: 0x%" PRIx64 "\n",
2228 		dev->protocol_features);
2229 
2230 	return RTE_VHOST_MSG_RESULT_OK;
2231 }
2232 
2233 static int
2234 vhost_user_set_log_base(struct virtio_net **pdev,
2235 			struct vhu_msg_context *ctx,
2236 			int main_fd __rte_unused)
2237 {
2238 	struct virtio_net *dev = *pdev;
2239 	int fd = ctx->fds[0];
2240 	uint64_t size, off;
2241 	void *addr;
2242 	uint32_t i;
2243 
2244 	if (validate_msg_fds(dev, ctx, 1) != 0)
2245 		return RTE_VHOST_MSG_RESULT_ERR;
2246 
2247 	if (fd < 0) {
2248 		VHOST_LOG_CONFIG(dev->ifname, ERR, "invalid log fd: %d\n", fd);
2249 		return RTE_VHOST_MSG_RESULT_ERR;
2250 	}
2251 
2252 	if (ctx->msg.size != sizeof(VhostUserLog)) {
2253 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2254 			"invalid log base msg size: %"PRId32" != %d\n",
2255 			ctx->msg.size, (int)sizeof(VhostUserLog));
2256 		goto close_msg_fds;
2257 	}
2258 
2259 	size = ctx->msg.payload.log.mmap_size;
2260 	off  = ctx->msg.payload.log.mmap_offset;
2261 
2262 	/* Check for mmap size and offset overflow. */
2263 	if (off >= -size) {
2264 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2265 			"log offset %#"PRIx64" and log size %#"PRIx64" overflow\n",
2266 			off, size);
2267 		goto close_msg_fds;
2268 	}
2269 
2270 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2271 		"log mmap size: %"PRId64", offset: %"PRId64"\n",
2272 		size, off);
2273 
2274 	/*
2275 	 * mmap from 0 to workaround a hugepage mmap bug: mmap will
2276 	 * fail when offset is not page size aligned.
2277 	 */
2278 	addr = mmap(0, size + off, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
2279 	close(fd);
2280 	if (addr == MAP_FAILED) {
2281 		VHOST_LOG_CONFIG(dev->ifname, ERR, "mmap log base failed!\n");
2282 		return RTE_VHOST_MSG_RESULT_ERR;
2283 	}
2284 
2285 	/*
2286 	 * Free previously mapped log memory on occasionally
2287 	 * multiple VHOST_USER_SET_LOG_BASE.
2288 	 */
2289 	if (dev->log_addr) {
2290 		munmap((void *)(uintptr_t)dev->log_addr, dev->log_size);
2291 	}
2292 	dev->log_addr = (uint64_t)(uintptr_t)addr;
2293 	dev->log_base = dev->log_addr + off;
2294 	dev->log_size = size;
2295 	mem_set_dump(addr, size, false);
2296 
2297 	for (i = 0; i < dev->nr_vring; i++) {
2298 		struct vhost_virtqueue *vq = dev->virtqueue[i];
2299 
2300 		rte_free(vq->log_cache);
2301 		vq->log_cache = NULL;
2302 		vq->log_cache_nb_elem = 0;
2303 		vq->log_cache = rte_malloc_socket("vq log cache",
2304 				sizeof(struct log_cache_entry) * VHOST_LOG_CACHE_NR,
2305 				0, vq->numa_node);
2306 		/*
2307 		 * If log cache alloc fail, don't fail migration, but no
2308 		 * caching will be done, which will impact performance
2309 		 */
2310 		if (!vq->log_cache)
2311 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2312 				"failed to allocate VQ logging cache\n");
2313 	}
2314 
2315 	/*
2316 	 * The spec is not clear about it (yet), but QEMU doesn't expect
2317 	 * any payload in the reply.
2318 	 */
2319 	ctx->msg.size = 0;
2320 	ctx->fd_num = 0;
2321 
2322 	return RTE_VHOST_MSG_RESULT_REPLY;
2323 
2324 close_msg_fds:
2325 	close_msg_fds(ctx);
2326 	return RTE_VHOST_MSG_RESULT_ERR;
2327 }
2328 
2329 static int vhost_user_set_log_fd(struct virtio_net **pdev,
2330 			struct vhu_msg_context *ctx,
2331 			int main_fd __rte_unused)
2332 {
2333 	struct virtio_net *dev = *pdev;
2334 
2335 	if (validate_msg_fds(dev, ctx, 1) != 0)
2336 		return RTE_VHOST_MSG_RESULT_ERR;
2337 
2338 	close(ctx->fds[0]);
2339 	VHOST_LOG_CONFIG(dev->ifname, INFO, "not implemented.\n");
2340 
2341 	return RTE_VHOST_MSG_RESULT_OK;
2342 }
2343 
2344 /*
2345  * An rarp packet is constructed and broadcasted to notify switches about
2346  * the new location of the migrated VM, so that packets from outside will
2347  * not be lost after migration.
2348  *
2349  * However, we don't actually "send" a rarp packet here, instead, we set
2350  * a flag 'broadcast_rarp' to let rte_vhost_dequeue_burst() inject it.
2351  */
2352 static int
2353 vhost_user_send_rarp(struct virtio_net **pdev,
2354 			struct vhu_msg_context *ctx,
2355 			int main_fd __rte_unused)
2356 {
2357 	struct virtio_net *dev = *pdev;
2358 	uint8_t *mac = (uint8_t *)&ctx->msg.payload.u64;
2359 	struct rte_vdpa_device *vdpa_dev;
2360 
2361 	VHOST_LOG_CONFIG(dev->ifname, DEBUG,
2362 		"MAC: " RTE_ETHER_ADDR_PRT_FMT "\n",
2363 		mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2364 	memcpy(dev->mac.addr_bytes, mac, 6);
2365 
2366 	/*
2367 	 * Set the flag to inject a RARP broadcast packet at
2368 	 * rte_vhost_dequeue_burst().
2369 	 *
2370 	 * __ATOMIC_RELEASE ordering is for making sure the mac is
2371 	 * copied before the flag is set.
2372 	 */
2373 	__atomic_store_n(&dev->broadcast_rarp, 1, __ATOMIC_RELEASE);
2374 	vdpa_dev = dev->vdpa_dev;
2375 	if (vdpa_dev && vdpa_dev->ops->migration_done)
2376 		vdpa_dev->ops->migration_done(dev->vid);
2377 
2378 	return RTE_VHOST_MSG_RESULT_OK;
2379 }
2380 
2381 static int
2382 vhost_user_net_set_mtu(struct virtio_net **pdev,
2383 			struct vhu_msg_context *ctx,
2384 			int main_fd __rte_unused)
2385 {
2386 	struct virtio_net *dev = *pdev;
2387 
2388 	if (ctx->msg.payload.u64 < VIRTIO_MIN_MTU ||
2389 			ctx->msg.payload.u64 > VIRTIO_MAX_MTU) {
2390 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2391 			"invalid MTU size (%"PRIu64")\n",
2392 			ctx->msg.payload.u64);
2393 
2394 		return RTE_VHOST_MSG_RESULT_ERR;
2395 	}
2396 
2397 	dev->mtu = ctx->msg.payload.u64;
2398 
2399 	return RTE_VHOST_MSG_RESULT_OK;
2400 }
2401 
2402 static int
2403 vhost_user_set_req_fd(struct virtio_net **pdev,
2404 			struct vhu_msg_context *ctx,
2405 			int main_fd __rte_unused)
2406 {
2407 	struct virtio_net *dev = *pdev;
2408 	int fd = ctx->fds[0];
2409 
2410 	if (validate_msg_fds(dev, ctx, 1) != 0)
2411 		return RTE_VHOST_MSG_RESULT_ERR;
2412 
2413 	if (fd < 0) {
2414 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2415 			"invalid file descriptor for slave channel (%d)\n", fd);
2416 		return RTE_VHOST_MSG_RESULT_ERR;
2417 	}
2418 
2419 	if (dev->slave_req_fd >= 0)
2420 		close(dev->slave_req_fd);
2421 
2422 	dev->slave_req_fd = fd;
2423 
2424 	return RTE_VHOST_MSG_RESULT_OK;
2425 }
2426 
2427 static int
2428 is_vring_iotlb_split(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2429 {
2430 	struct vhost_vring_addr *ra;
2431 	uint64_t start, end, len;
2432 
2433 	start = imsg->iova;
2434 	end = start + imsg->size;
2435 
2436 	ra = &vq->ring_addrs;
2437 	len = sizeof(struct vring_desc) * vq->size;
2438 	if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2439 		return 1;
2440 
2441 	len = sizeof(struct vring_avail) + sizeof(uint16_t) * vq->size;
2442 	if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2443 		return 1;
2444 
2445 	len = sizeof(struct vring_used) +
2446 	       sizeof(struct vring_used_elem) * vq->size;
2447 	if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2448 		return 1;
2449 
2450 	if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2451 		len = sizeof(uint64_t);
2452 		if (ra->log_guest_addr < end &&
2453 		    (ra->log_guest_addr + len) > start)
2454 			return 1;
2455 	}
2456 
2457 	return 0;
2458 }
2459 
2460 static int
2461 is_vring_iotlb_packed(struct vhost_virtqueue *vq, struct vhost_iotlb_msg *imsg)
2462 {
2463 	struct vhost_vring_addr *ra;
2464 	uint64_t start, end, len;
2465 
2466 	start = imsg->iova;
2467 	end = start + imsg->size;
2468 
2469 	ra = &vq->ring_addrs;
2470 	len = sizeof(struct vring_packed_desc) * vq->size;
2471 	if (ra->desc_user_addr < end && (ra->desc_user_addr + len) > start)
2472 		return 1;
2473 
2474 	len = sizeof(struct vring_packed_desc_event);
2475 	if (ra->avail_user_addr < end && (ra->avail_user_addr + len) > start)
2476 		return 1;
2477 
2478 	len = sizeof(struct vring_packed_desc_event);
2479 	if (ra->used_user_addr < end && (ra->used_user_addr + len) > start)
2480 		return 1;
2481 
2482 	if (ra->flags & (1 << VHOST_VRING_F_LOG)) {
2483 		len = sizeof(uint64_t);
2484 		if (ra->log_guest_addr < end &&
2485 		    (ra->log_guest_addr + len) > start)
2486 			return 1;
2487 	}
2488 
2489 	return 0;
2490 }
2491 
2492 static int is_vring_iotlb(struct virtio_net *dev,
2493 			  struct vhost_virtqueue *vq,
2494 			  struct vhost_iotlb_msg *imsg)
2495 {
2496 	if (vq_is_packed(dev))
2497 		return is_vring_iotlb_packed(vq, imsg);
2498 	else
2499 		return is_vring_iotlb_split(vq, imsg);
2500 }
2501 
2502 static int
2503 vhost_user_get_config(struct virtio_net **pdev,
2504 			struct vhu_msg_context *ctx,
2505 			int main_fd __rte_unused)
2506 {
2507 	struct virtio_net *dev = *pdev;
2508 	struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
2509 	int ret = 0;
2510 
2511 	if (validate_msg_fds(dev, ctx, 0) != 0)
2512 		return RTE_VHOST_MSG_RESULT_ERR;
2513 
2514 	if (!vdpa_dev) {
2515 		VHOST_LOG_CONFIG(dev->ifname, ERR, "is not vDPA device!\n");
2516 		return RTE_VHOST_MSG_RESULT_ERR;
2517 	}
2518 
2519 	if (vdpa_dev->ops->get_config) {
2520 		ret = vdpa_dev->ops->get_config(dev->vid,
2521 					   ctx->msg.payload.cfg.region,
2522 					   ctx->msg.payload.cfg.size);
2523 		if (ret != 0) {
2524 			ctx->msg.size = 0;
2525 			VHOST_LOG_CONFIG(dev->ifname, ERR, "get_config() return error!\n");
2526 		}
2527 	} else {
2528 		VHOST_LOG_CONFIG(dev->ifname, ERR, "get_config() not supported!\n");
2529 	}
2530 
2531 	return RTE_VHOST_MSG_RESULT_REPLY;
2532 }
2533 
2534 static int
2535 vhost_user_set_config(struct virtio_net **pdev,
2536 			struct vhu_msg_context *ctx,
2537 			int main_fd __rte_unused)
2538 {
2539 	struct virtio_net *dev = *pdev;
2540 	struct rte_vdpa_device *vdpa_dev = dev->vdpa_dev;
2541 	int ret = 0;
2542 
2543 	if (validate_msg_fds(dev, ctx, 0) != 0)
2544 		return RTE_VHOST_MSG_RESULT_ERR;
2545 
2546 	if (ctx->msg.payload.cfg.size > VHOST_USER_MAX_CONFIG_SIZE) {
2547 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2548 			"vhost_user_config size: %"PRIu32", should not be larger than %d\n",
2549 			ctx->msg.payload.cfg.size, VHOST_USER_MAX_CONFIG_SIZE);
2550 		goto out;
2551 	}
2552 
2553 	if (!vdpa_dev) {
2554 		VHOST_LOG_CONFIG(dev->ifname, ERR, "is not vDPA device!\n");
2555 		goto out;
2556 	}
2557 
2558 	if (vdpa_dev->ops->set_config) {
2559 		ret = vdpa_dev->ops->set_config(dev->vid,
2560 			ctx->msg.payload.cfg.region,
2561 			ctx->msg.payload.cfg.offset,
2562 			ctx->msg.payload.cfg.size,
2563 			ctx->msg.payload.cfg.flags);
2564 		if (ret)
2565 			VHOST_LOG_CONFIG(dev->ifname, ERR, "set_config() return error!\n");
2566 	} else {
2567 		VHOST_LOG_CONFIG(dev->ifname, ERR, "set_config() not supported!\n");
2568 	}
2569 
2570 	return RTE_VHOST_MSG_RESULT_OK;
2571 
2572 out:
2573 	return RTE_VHOST_MSG_RESULT_ERR;
2574 }
2575 
2576 static int
2577 vhost_user_iotlb_msg(struct virtio_net **pdev,
2578 			struct vhu_msg_context *ctx,
2579 			int main_fd __rte_unused)
2580 {
2581 	struct virtio_net *dev = *pdev;
2582 	struct vhost_iotlb_msg *imsg = &ctx->msg.payload.iotlb;
2583 	uint16_t i;
2584 	uint64_t vva, len;
2585 
2586 	switch (imsg->type) {
2587 	case VHOST_IOTLB_UPDATE:
2588 		len = imsg->size;
2589 		vva = qva_to_vva(dev, imsg->uaddr, &len);
2590 		if (!vva)
2591 			return RTE_VHOST_MSG_RESULT_ERR;
2592 
2593 		for (i = 0; i < dev->nr_vring; i++) {
2594 			struct vhost_virtqueue *vq = dev->virtqueue[i];
2595 
2596 			if (!vq)
2597 				continue;
2598 
2599 			vhost_user_iotlb_cache_insert(dev, vq, imsg->iova, vva,
2600 					len, imsg->perm);
2601 
2602 			if (is_vring_iotlb(dev, vq, imsg)) {
2603 				rte_spinlock_lock(&vq->access_lock);
2604 				translate_ring_addresses(&dev, &vq);
2605 				*pdev = dev;
2606 				rte_spinlock_unlock(&vq->access_lock);
2607 			}
2608 		}
2609 		break;
2610 	case VHOST_IOTLB_INVALIDATE:
2611 		for (i = 0; i < dev->nr_vring; i++) {
2612 			struct vhost_virtqueue *vq = dev->virtqueue[i];
2613 
2614 			if (!vq)
2615 				continue;
2616 
2617 			vhost_user_iotlb_cache_remove(vq, imsg->iova,
2618 					imsg->size);
2619 
2620 			if (is_vring_iotlb(dev, vq, imsg)) {
2621 				rte_spinlock_lock(&vq->access_lock);
2622 				vring_invalidate(dev, vq);
2623 				rte_spinlock_unlock(&vq->access_lock);
2624 			}
2625 		}
2626 		break;
2627 	default:
2628 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2629 			"invalid IOTLB message type (%d)\n",
2630 			imsg->type);
2631 		return RTE_VHOST_MSG_RESULT_ERR;
2632 	}
2633 
2634 	return RTE_VHOST_MSG_RESULT_OK;
2635 }
2636 
2637 static int
2638 vhost_user_set_postcopy_advise(struct virtio_net **pdev,
2639 			struct vhu_msg_context *ctx,
2640 			int main_fd __rte_unused)
2641 {
2642 	struct virtio_net *dev = *pdev;
2643 #ifdef RTE_LIBRTE_VHOST_POSTCOPY
2644 	struct uffdio_api api_struct;
2645 
2646 	dev->postcopy_ufd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
2647 
2648 	if (dev->postcopy_ufd == -1) {
2649 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2650 			"userfaultfd not available: %s\n",
2651 			strerror(errno));
2652 		return RTE_VHOST_MSG_RESULT_ERR;
2653 	}
2654 	api_struct.api = UFFD_API;
2655 	api_struct.features = 0;
2656 	if (ioctl(dev->postcopy_ufd, UFFDIO_API, &api_struct)) {
2657 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2658 			"UFFDIO_API ioctl failure: %s\n",
2659 			strerror(errno));
2660 		close(dev->postcopy_ufd);
2661 		dev->postcopy_ufd = -1;
2662 		return RTE_VHOST_MSG_RESULT_ERR;
2663 	}
2664 	ctx->fds[0] = dev->postcopy_ufd;
2665 	ctx->fd_num = 1;
2666 
2667 	return RTE_VHOST_MSG_RESULT_REPLY;
2668 #else
2669 	dev->postcopy_ufd = -1;
2670 	ctx->fd_num = 0;
2671 
2672 	return RTE_VHOST_MSG_RESULT_ERR;
2673 #endif
2674 }
2675 
2676 static int
2677 vhost_user_set_postcopy_listen(struct virtio_net **pdev,
2678 			struct vhu_msg_context *ctx __rte_unused,
2679 			int main_fd __rte_unused)
2680 {
2681 	struct virtio_net *dev = *pdev;
2682 
2683 	if (dev->mem && dev->mem->nregions) {
2684 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2685 			"regions already registered at postcopy-listen\n");
2686 		return RTE_VHOST_MSG_RESULT_ERR;
2687 	}
2688 	dev->postcopy_listening = 1;
2689 
2690 	return RTE_VHOST_MSG_RESULT_OK;
2691 }
2692 
2693 static int
2694 vhost_user_postcopy_end(struct virtio_net **pdev,
2695 			struct vhu_msg_context *ctx,
2696 			int main_fd __rte_unused)
2697 {
2698 	struct virtio_net *dev = *pdev;
2699 
2700 	dev->postcopy_listening = 0;
2701 	if (dev->postcopy_ufd >= 0) {
2702 		close(dev->postcopy_ufd);
2703 		dev->postcopy_ufd = -1;
2704 	}
2705 
2706 	ctx->msg.payload.u64 = 0;
2707 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
2708 	ctx->fd_num = 0;
2709 
2710 	return RTE_VHOST_MSG_RESULT_REPLY;
2711 }
2712 
2713 static int
2714 vhost_user_get_status(struct virtio_net **pdev,
2715 		      struct vhu_msg_context *ctx,
2716 		      int main_fd __rte_unused)
2717 {
2718 	struct virtio_net *dev = *pdev;
2719 
2720 	ctx->msg.payload.u64 = dev->status;
2721 	ctx->msg.size = sizeof(ctx->msg.payload.u64);
2722 	ctx->fd_num = 0;
2723 
2724 	return RTE_VHOST_MSG_RESULT_REPLY;
2725 }
2726 
2727 static int
2728 vhost_user_set_status(struct virtio_net **pdev,
2729 			struct vhu_msg_context *ctx,
2730 			int main_fd __rte_unused)
2731 {
2732 	struct virtio_net *dev = *pdev;
2733 
2734 	/* As per Virtio specification, the device status is 8bits long */
2735 	if (ctx->msg.payload.u64 > UINT8_MAX) {
2736 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2737 			"invalid VHOST_USER_SET_STATUS payload 0x%" PRIx64 "\n",
2738 			ctx->msg.payload.u64);
2739 		return RTE_VHOST_MSG_RESULT_ERR;
2740 	}
2741 
2742 	dev->status = ctx->msg.payload.u64;
2743 
2744 	if ((dev->status & VIRTIO_DEVICE_STATUS_FEATURES_OK) &&
2745 	    (dev->flags & VIRTIO_DEV_FEATURES_FAILED)) {
2746 		VHOST_LOG_CONFIG(dev->ifname, ERR,
2747 			"FEATURES_OK bit is set but feature negotiation failed\n");
2748 		/*
2749 		 * Clear the bit to let the driver know about the feature
2750 		 * negotiation failure
2751 		 */
2752 		dev->status &= ~VIRTIO_DEVICE_STATUS_FEATURES_OK;
2753 	}
2754 
2755 	VHOST_LOG_CONFIG(dev->ifname, INFO, "new device status(0x%08x):\n", dev->status);
2756 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2757 		"\t-RESET: %u\n",
2758 		(dev->status == VIRTIO_DEVICE_STATUS_RESET));
2759 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2760 		"\t-ACKNOWLEDGE: %u\n",
2761 		!!(dev->status & VIRTIO_DEVICE_STATUS_ACK));
2762 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2763 		"\t-DRIVER: %u\n",
2764 		!!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER));
2765 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2766 		"\t-FEATURES_OK: %u\n",
2767 		!!(dev->status & VIRTIO_DEVICE_STATUS_FEATURES_OK));
2768 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2769 		"\t-DRIVER_OK: %u\n",
2770 		!!(dev->status & VIRTIO_DEVICE_STATUS_DRIVER_OK));
2771 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2772 		"\t-DEVICE_NEED_RESET: %u\n",
2773 		!!(dev->status & VIRTIO_DEVICE_STATUS_DEV_NEED_RESET));
2774 	VHOST_LOG_CONFIG(dev->ifname, INFO,
2775 		"\t-FAILED: %u\n",
2776 		!!(dev->status & VIRTIO_DEVICE_STATUS_FAILED));
2777 
2778 	return RTE_VHOST_MSG_RESULT_OK;
2779 }
2780 
2781 #define VHOST_MESSAGE_HANDLERS \
2782 VHOST_MESSAGE_HANDLER(VHOST_USER_NONE, NULL, false) \
2783 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_FEATURES, vhost_user_get_features, false) \
2784 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_FEATURES, vhost_user_set_features, false) \
2785 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_OWNER, vhost_user_set_owner, false) \
2786 VHOST_MESSAGE_HANDLER(VHOST_USER_RESET_OWNER, vhost_user_reset_owner, false) \
2787 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_MEM_TABLE, vhost_user_set_mem_table, true) \
2788 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_LOG_BASE, vhost_user_set_log_base, true) \
2789 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_LOG_FD, vhost_user_set_log_fd, true) \
2790 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_NUM, vhost_user_set_vring_num, false) \
2791 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_ADDR, vhost_user_set_vring_addr, false) \
2792 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_BASE, vhost_user_set_vring_base, false) \
2793 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_VRING_BASE, vhost_user_get_vring_base, false) \
2794 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_KICK, vhost_user_set_vring_kick, true) \
2795 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_CALL, vhost_user_set_vring_call, true) \
2796 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_ERR, vhost_user_set_vring_err, true) \
2797 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_PROTOCOL_FEATURES, vhost_user_get_protocol_features, false) \
2798 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_PROTOCOL_FEATURES, vhost_user_set_protocol_features, false) \
2799 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_QUEUE_NUM, vhost_user_get_queue_num, false) \
2800 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_VRING_ENABLE, vhost_user_set_vring_enable, false) \
2801 VHOST_MESSAGE_HANDLER(VHOST_USER_SEND_RARP, vhost_user_send_rarp, false) \
2802 VHOST_MESSAGE_HANDLER(VHOST_USER_NET_SET_MTU, vhost_user_net_set_mtu, false) \
2803 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_SLAVE_REQ_FD, vhost_user_set_req_fd, true) \
2804 VHOST_MESSAGE_HANDLER(VHOST_USER_IOTLB_MSG, vhost_user_iotlb_msg, false) \
2805 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_CONFIG, vhost_user_get_config, false) \
2806 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_CONFIG, vhost_user_set_config, false) \
2807 VHOST_MESSAGE_HANDLER(VHOST_USER_POSTCOPY_ADVISE, vhost_user_set_postcopy_advise, false) \
2808 VHOST_MESSAGE_HANDLER(VHOST_USER_POSTCOPY_LISTEN, vhost_user_set_postcopy_listen, false) \
2809 VHOST_MESSAGE_HANDLER(VHOST_USER_POSTCOPY_END, vhost_user_postcopy_end, false) \
2810 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_INFLIGHT_FD, vhost_user_get_inflight_fd, false) \
2811 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_INFLIGHT_FD, vhost_user_set_inflight_fd, true) \
2812 VHOST_MESSAGE_HANDLER(VHOST_USER_SET_STATUS, vhost_user_set_status, false) \
2813 VHOST_MESSAGE_HANDLER(VHOST_USER_GET_STATUS, vhost_user_get_status, false)
2814 
2815 #define VHOST_MESSAGE_HANDLER(id, handler, accepts_fd) \
2816 	[id] = { #id, handler, accepts_fd },
2817 static vhost_message_handler_t vhost_message_handlers[] = {
2818 	VHOST_MESSAGE_HANDLERS
2819 };
2820 #undef VHOST_MESSAGE_HANDLER
2821 
2822 /* return bytes# of read on success or negative val on failure. */
2823 static int
2824 read_vhost_message(struct virtio_net *dev, int sockfd, struct  vhu_msg_context *ctx)
2825 {
2826 	int ret;
2827 
2828 	ret = read_fd_message(dev->ifname, sockfd, (char *)&ctx->msg, VHOST_USER_HDR_SIZE,
2829 		ctx->fds, VHOST_MEMORY_MAX_NREGIONS, &ctx->fd_num);
2830 	if (ret <= 0) {
2831 		return ret;
2832 	} else if (ret != VHOST_USER_HDR_SIZE) {
2833 		VHOST_LOG_CONFIG(dev->ifname, ERR, "Unexpected header size read\n");
2834 		close_msg_fds(ctx);
2835 		return -1;
2836 	}
2837 
2838 	if (ctx->msg.size) {
2839 		if (ctx->msg.size > sizeof(ctx->msg.payload)) {
2840 			VHOST_LOG_CONFIG(dev->ifname, ERR, "invalid msg size: %d\n",
2841 				ctx->msg.size);
2842 			return -1;
2843 		}
2844 		ret = read(sockfd, &ctx->msg.payload, ctx->msg.size);
2845 		if (ret <= 0)
2846 			return ret;
2847 		if (ret != (int)ctx->msg.size) {
2848 			VHOST_LOG_CONFIG(dev->ifname, ERR, "read control message failed\n");
2849 			return -1;
2850 		}
2851 	}
2852 
2853 	return ret;
2854 }
2855 
2856 static int
2857 send_vhost_message(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx)
2858 {
2859 	if (!ctx)
2860 		return 0;
2861 
2862 	return send_fd_message(dev->ifname, sockfd, (char *)&ctx->msg,
2863 		VHOST_USER_HDR_SIZE + ctx->msg.size, ctx->fds, ctx->fd_num);
2864 }
2865 
2866 static int
2867 send_vhost_reply(struct virtio_net *dev, int sockfd, struct vhu_msg_context *ctx)
2868 {
2869 	if (!ctx)
2870 		return 0;
2871 
2872 	ctx->msg.flags &= ~VHOST_USER_VERSION_MASK;
2873 	ctx->msg.flags &= ~VHOST_USER_NEED_REPLY;
2874 	ctx->msg.flags |= VHOST_USER_VERSION;
2875 	ctx->msg.flags |= VHOST_USER_REPLY_MASK;
2876 
2877 	return send_vhost_message(dev, sockfd, ctx);
2878 }
2879 
2880 static int
2881 send_vhost_slave_message(struct virtio_net *dev,
2882 		struct vhu_msg_context *ctx)
2883 {
2884 	int ret;
2885 
2886 	if (ctx->msg.flags & VHOST_USER_NEED_REPLY)
2887 		rte_spinlock_lock(&dev->slave_req_lock);
2888 
2889 	ret = send_vhost_message(dev, dev->slave_req_fd, ctx);
2890 	if (ret < 0 && (ctx->msg.flags & VHOST_USER_NEED_REPLY))
2891 		rte_spinlock_unlock(&dev->slave_req_lock);
2892 
2893 	return ret;
2894 }
2895 
2896 /*
2897  * Allocate a queue pair if it hasn't been allocated yet
2898  */
2899 static int
2900 vhost_user_check_and_alloc_queue_pair(struct virtio_net *dev,
2901 			struct vhu_msg_context *ctx)
2902 {
2903 	uint32_t vring_idx;
2904 
2905 	switch (ctx->msg.request.master) {
2906 	case VHOST_USER_SET_VRING_KICK:
2907 	case VHOST_USER_SET_VRING_CALL:
2908 	case VHOST_USER_SET_VRING_ERR:
2909 		vring_idx = ctx->msg.payload.u64 & VHOST_USER_VRING_IDX_MASK;
2910 		break;
2911 	case VHOST_USER_SET_VRING_NUM:
2912 	case VHOST_USER_SET_VRING_BASE:
2913 	case VHOST_USER_GET_VRING_BASE:
2914 	case VHOST_USER_SET_VRING_ENABLE:
2915 		vring_idx = ctx->msg.payload.state.index;
2916 		break;
2917 	case VHOST_USER_SET_VRING_ADDR:
2918 		vring_idx = ctx->msg.payload.addr.index;
2919 		break;
2920 	case VHOST_USER_SET_INFLIGHT_FD:
2921 		vring_idx = ctx->msg.payload.inflight.num_queues - 1;
2922 		break;
2923 	default:
2924 		return 0;
2925 	}
2926 
2927 	if (vring_idx >= VHOST_MAX_VRING) {
2928 		VHOST_LOG_CONFIG(dev->ifname, ERR, "invalid vring index: %u\n", vring_idx);
2929 		return -1;
2930 	}
2931 
2932 	if (dev->virtqueue[vring_idx])
2933 		return 0;
2934 
2935 	return alloc_vring_queue(dev, vring_idx);
2936 }
2937 
2938 static void
2939 vhost_user_lock_all_queue_pairs(struct virtio_net *dev)
2940 {
2941 	unsigned int i = 0;
2942 	unsigned int vq_num = 0;
2943 
2944 	while (vq_num < dev->nr_vring) {
2945 		struct vhost_virtqueue *vq = dev->virtqueue[i];
2946 
2947 		if (vq) {
2948 			rte_spinlock_lock(&vq->access_lock);
2949 			vq_num++;
2950 		}
2951 		i++;
2952 	}
2953 }
2954 
2955 static void
2956 vhost_user_unlock_all_queue_pairs(struct virtio_net *dev)
2957 {
2958 	unsigned int i = 0;
2959 	unsigned int vq_num = 0;
2960 
2961 	while (vq_num < dev->nr_vring) {
2962 		struct vhost_virtqueue *vq = dev->virtqueue[i];
2963 
2964 		if (vq) {
2965 			rte_spinlock_unlock(&vq->access_lock);
2966 			vq_num++;
2967 		}
2968 		i++;
2969 	}
2970 }
2971 
2972 int
2973 vhost_user_msg_handler(int vid, int fd)
2974 {
2975 	struct virtio_net *dev;
2976 	struct vhu_msg_context ctx;
2977 	vhost_message_handler_t *msg_handler;
2978 	struct rte_vdpa_device *vdpa_dev;
2979 	int msg_result = RTE_VHOST_MSG_RESULT_OK;
2980 	int ret;
2981 	int unlock_required = 0;
2982 	bool handled;
2983 	uint32_t request;
2984 	uint32_t i;
2985 	uint16_t blk_call_fd;
2986 
2987 	dev = get_device(vid);
2988 	if (dev == NULL)
2989 		return -1;
2990 
2991 	if (!dev->notify_ops) {
2992 		dev->notify_ops = vhost_driver_callback_get(dev->ifname);
2993 		if (!dev->notify_ops) {
2994 			VHOST_LOG_CONFIG(dev->ifname, ERR,
2995 				"failed to get callback ops for driver\n");
2996 			return -1;
2997 		}
2998 	}
2999 
3000 	ret = read_vhost_message(dev, fd, &ctx);
3001 	if (ret <= 0) {
3002 		if (ret < 0)
3003 			VHOST_LOG_CONFIG(dev->ifname, ERR, "vhost read message failed\n");
3004 		else
3005 			VHOST_LOG_CONFIG(dev->ifname, INFO, "vhost peer closed\n");
3006 
3007 		return -1;
3008 	}
3009 
3010 	request = ctx.msg.request.master;
3011 	if (request > VHOST_USER_NONE && request < RTE_DIM(vhost_message_handlers))
3012 		msg_handler = &vhost_message_handlers[request];
3013 	else
3014 		msg_handler = NULL;
3015 
3016 	if (msg_handler != NULL && msg_handler->description != NULL) {
3017 		if (request != VHOST_USER_IOTLB_MSG)
3018 			VHOST_LOG_CONFIG(dev->ifname, INFO,
3019 				"read message %s\n",
3020 				msg_handler->description);
3021 		else
3022 			VHOST_LOG_CONFIG(dev->ifname, DEBUG,
3023 				"read message %s\n",
3024 				msg_handler->description);
3025 	} else {
3026 		VHOST_LOG_CONFIG(dev->ifname, DEBUG, "external request %d\n", request);
3027 	}
3028 
3029 	ret = vhost_user_check_and_alloc_queue_pair(dev, &ctx);
3030 	if (ret < 0) {
3031 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to alloc queue\n");
3032 		return -1;
3033 	}
3034 
3035 	/*
3036 	 * Note: we don't lock all queues on VHOST_USER_GET_VRING_BASE
3037 	 * and VHOST_USER_RESET_OWNER, since it is sent when virtio stops
3038 	 * and device is destroyed. destroy_device waits for queues to be
3039 	 * inactive, so it is safe. Otherwise taking the access_lock
3040 	 * would cause a dead lock.
3041 	 */
3042 	switch (request) {
3043 	case VHOST_USER_SET_FEATURES:
3044 	case VHOST_USER_SET_PROTOCOL_FEATURES:
3045 	case VHOST_USER_SET_OWNER:
3046 	case VHOST_USER_SET_MEM_TABLE:
3047 	case VHOST_USER_SET_LOG_BASE:
3048 	case VHOST_USER_SET_LOG_FD:
3049 	case VHOST_USER_SET_VRING_NUM:
3050 	case VHOST_USER_SET_VRING_ADDR:
3051 	case VHOST_USER_SET_VRING_BASE:
3052 	case VHOST_USER_SET_VRING_KICK:
3053 	case VHOST_USER_SET_VRING_CALL:
3054 	case VHOST_USER_SET_VRING_ERR:
3055 	case VHOST_USER_SET_VRING_ENABLE:
3056 	case VHOST_USER_SEND_RARP:
3057 	case VHOST_USER_NET_SET_MTU:
3058 	case VHOST_USER_SET_SLAVE_REQ_FD:
3059 		if (!(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED)) {
3060 			vhost_user_lock_all_queue_pairs(dev);
3061 			unlock_required = 1;
3062 		}
3063 		break;
3064 	default:
3065 		break;
3066 
3067 	}
3068 
3069 	handled = false;
3070 	if (dev->extern_ops.pre_msg_handle) {
3071 		RTE_BUILD_BUG_ON(offsetof(struct vhu_msg_context, msg) != 0);
3072 		msg_result = (*dev->extern_ops.pre_msg_handle)(dev->vid, &ctx);
3073 		switch (msg_result) {
3074 		case RTE_VHOST_MSG_RESULT_REPLY:
3075 			send_vhost_reply(dev, fd, &ctx);
3076 			/* Fall-through */
3077 		case RTE_VHOST_MSG_RESULT_ERR:
3078 		case RTE_VHOST_MSG_RESULT_OK:
3079 			handled = true;
3080 			goto skip_to_post_handle;
3081 		case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
3082 		default:
3083 			break;
3084 		}
3085 	}
3086 
3087 	if (msg_handler == NULL || msg_handler->callback == NULL)
3088 		goto skip_to_post_handle;
3089 
3090 	if (!msg_handler->accepts_fd && validate_msg_fds(dev, &ctx, 0) != 0) {
3091 		msg_result = RTE_VHOST_MSG_RESULT_ERR;
3092 	} else {
3093 		msg_result = msg_handler->callback(&dev, &ctx, fd);
3094 	}
3095 
3096 	switch (msg_result) {
3097 	case RTE_VHOST_MSG_RESULT_ERR:
3098 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3099 			"processing %s failed.\n",
3100 			msg_handler->description);
3101 		handled = true;
3102 		break;
3103 	case RTE_VHOST_MSG_RESULT_OK:
3104 		VHOST_LOG_CONFIG(dev->ifname, DEBUG,
3105 			"processing %s succeeded.\n",
3106 			msg_handler->description);
3107 		handled = true;
3108 		break;
3109 	case RTE_VHOST_MSG_RESULT_REPLY:
3110 		VHOST_LOG_CONFIG(dev->ifname, DEBUG,
3111 			"processing %s succeeded and needs reply.\n",
3112 			msg_handler->description);
3113 		send_vhost_reply(dev, fd, &ctx);
3114 		handled = true;
3115 		break;
3116 	default:
3117 		break;
3118 	}
3119 
3120 skip_to_post_handle:
3121 	if (msg_result != RTE_VHOST_MSG_RESULT_ERR &&
3122 			dev->extern_ops.post_msg_handle) {
3123 		RTE_BUILD_BUG_ON(offsetof(struct vhu_msg_context, msg) != 0);
3124 		msg_result = (*dev->extern_ops.post_msg_handle)(dev->vid, &ctx);
3125 		switch (msg_result) {
3126 		case RTE_VHOST_MSG_RESULT_REPLY:
3127 			send_vhost_reply(dev, fd, &ctx);
3128 			/* Fall-through */
3129 		case RTE_VHOST_MSG_RESULT_ERR:
3130 		case RTE_VHOST_MSG_RESULT_OK:
3131 			handled = true;
3132 		case RTE_VHOST_MSG_RESULT_NOT_HANDLED:
3133 		default:
3134 			break;
3135 		}
3136 	}
3137 
3138 	/* If message was not handled at this stage, treat it as an error */
3139 	if (!handled) {
3140 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3141 			"vhost message (req: %d) was not handled.\n",
3142 			request);
3143 		close_msg_fds(&ctx);
3144 		msg_result = RTE_VHOST_MSG_RESULT_ERR;
3145 	}
3146 
3147 	/*
3148 	 * If the request required a reply that was already sent,
3149 	 * this optional reply-ack won't be sent as the
3150 	 * VHOST_USER_NEED_REPLY was cleared in send_vhost_reply().
3151 	 */
3152 	if (ctx.msg.flags & VHOST_USER_NEED_REPLY) {
3153 		ctx.msg.payload.u64 = msg_result == RTE_VHOST_MSG_RESULT_ERR;
3154 		ctx.msg.size = sizeof(ctx.msg.payload.u64);
3155 		ctx.fd_num = 0;
3156 		send_vhost_reply(dev, fd, &ctx);
3157 	} else if (msg_result == RTE_VHOST_MSG_RESULT_ERR) {
3158 		VHOST_LOG_CONFIG(dev->ifname, ERR, "vhost message handling failed.\n");
3159 		ret = -1;
3160 		goto unlock;
3161 	}
3162 
3163 	for (i = 0; i < dev->nr_vring; i++) {
3164 		struct vhost_virtqueue *vq = dev->virtqueue[i];
3165 		bool cur_ready = vq_is_ready(dev, vq);
3166 
3167 		if (cur_ready != (vq && vq->ready)) {
3168 			vq->ready = cur_ready;
3169 			vhost_user_notify_queue_state(dev, vq, cur_ready);
3170 		}
3171 	}
3172 
3173 unlock:
3174 	if (unlock_required)
3175 		vhost_user_unlock_all_queue_pairs(dev);
3176 
3177 	if (ret != 0 || !virtio_is_ready(dev))
3178 		goto out;
3179 
3180 	/*
3181 	 * Virtio is now ready. If not done already, it is time
3182 	 * to notify the application it can process the rings and
3183 	 * configure the vDPA device if present.
3184 	 */
3185 
3186 	if (!(dev->flags & VIRTIO_DEV_RUNNING)) {
3187 		if (dev->notify_ops->new_device(dev->vid) == 0)
3188 			dev->flags |= VIRTIO_DEV_RUNNING;
3189 	}
3190 
3191 	vdpa_dev = dev->vdpa_dev;
3192 	if (!vdpa_dev)
3193 		goto out;
3194 
3195 	if (vdpa_dev->type == RTE_VHOST_VDPA_DEVICE_TYPE_BLK) {
3196 		if (request == VHOST_USER_SET_VRING_CALL) {
3197 			blk_call_fd = ctx.msg.payload.u64 & VHOST_USER_VRING_IDX_MASK;
3198 			if (blk_call_fd != dev->nr_vring - 1)
3199 				goto out;
3200 		} else {
3201 			goto out;
3202 		}
3203 	}
3204 
3205 	if (!(dev->flags & VIRTIO_DEV_VDPA_CONFIGURED)) {
3206 		if (vdpa_dev->ops->dev_conf(dev->vid))
3207 			VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to configure vDPA device\n");
3208 		else
3209 			dev->flags |= VIRTIO_DEV_VDPA_CONFIGURED;
3210 	}
3211 
3212 out:
3213 	return ret;
3214 }
3215 
3216 static int process_slave_message_reply(struct virtio_net *dev,
3217 				       const struct vhu_msg_context *ctx)
3218 {
3219 	struct vhu_msg_context msg_reply;
3220 	int ret;
3221 
3222 	if ((ctx->msg.flags & VHOST_USER_NEED_REPLY) == 0)
3223 		return 0;
3224 
3225 	ret = read_vhost_message(dev, dev->slave_req_fd, &msg_reply);
3226 	if (ret <= 0) {
3227 		if (ret < 0)
3228 			VHOST_LOG_CONFIG(dev->ifname, ERR,
3229 				"vhost read slave message reply failed\n");
3230 		else
3231 			VHOST_LOG_CONFIG(dev->ifname, INFO, "vhost peer closed\n");
3232 		ret = -1;
3233 		goto out;
3234 	}
3235 
3236 	ret = 0;
3237 	if (msg_reply.msg.request.slave != ctx->msg.request.slave) {
3238 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3239 			"received unexpected msg type (%u), expected %u\n",
3240 			msg_reply.msg.request.slave, ctx->msg.request.slave);
3241 		ret = -1;
3242 		goto out;
3243 	}
3244 
3245 	ret = msg_reply.msg.payload.u64 ? -1 : 0;
3246 
3247 out:
3248 	rte_spinlock_unlock(&dev->slave_req_lock);
3249 	return ret;
3250 }
3251 
3252 int
3253 vhost_user_iotlb_miss(struct virtio_net *dev, uint64_t iova, uint8_t perm)
3254 {
3255 	int ret;
3256 	struct vhu_msg_context ctx = {
3257 		.msg = {
3258 			.request.slave = VHOST_USER_SLAVE_IOTLB_MSG,
3259 			.flags = VHOST_USER_VERSION,
3260 			.size = sizeof(ctx.msg.payload.iotlb),
3261 			.payload.iotlb = {
3262 				.iova = iova,
3263 				.perm = perm,
3264 				.type = VHOST_IOTLB_MISS,
3265 			},
3266 		},
3267 	};
3268 
3269 	ret = send_vhost_message(dev, dev->slave_req_fd, &ctx);
3270 	if (ret < 0) {
3271 		VHOST_LOG_CONFIG(dev->ifname, ERR,
3272 			"failed to send IOTLB miss message (%d)\n",
3273 			ret);
3274 		return ret;
3275 	}
3276 
3277 	return 0;
3278 }
3279 
3280 static int
3281 vhost_user_slave_config_change(struct virtio_net *dev, bool need_reply)
3282 {
3283 	int ret;
3284 	struct vhu_msg_context ctx = {
3285 		.msg = {
3286 			.request.slave = VHOST_USER_SLAVE_CONFIG_CHANGE_MSG,
3287 			.flags = VHOST_USER_VERSION,
3288 			.size = 0,
3289 		}
3290 	};
3291 
3292 	if (need_reply)
3293 		ctx.msg.flags |= VHOST_USER_NEED_REPLY;
3294 
3295 	ret = send_vhost_slave_message(dev, &ctx);
3296 	if (ret < 0) {
3297 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to send config change (%d)\n", ret);
3298 		return ret;
3299 	}
3300 
3301 	return process_slave_message_reply(dev, &ctx);
3302 }
3303 
3304 int
3305 rte_vhost_slave_config_change(int vid, bool need_reply)
3306 {
3307 	struct virtio_net *dev;
3308 
3309 	dev = get_device(vid);
3310 	if (!dev)
3311 		return -ENODEV;
3312 
3313 	return vhost_user_slave_config_change(dev, need_reply);
3314 }
3315 
3316 static int vhost_user_slave_set_vring_host_notifier(struct virtio_net *dev,
3317 						    int index, int fd,
3318 						    uint64_t offset,
3319 						    uint64_t size)
3320 {
3321 	int ret;
3322 	struct vhu_msg_context ctx = {
3323 		.msg = {
3324 			.request.slave = VHOST_USER_SLAVE_VRING_HOST_NOTIFIER_MSG,
3325 			.flags = VHOST_USER_VERSION | VHOST_USER_NEED_REPLY,
3326 			.size = sizeof(ctx.msg.payload.area),
3327 			.payload.area = {
3328 				.u64 = index & VHOST_USER_VRING_IDX_MASK,
3329 				.size = size,
3330 				.offset = offset,
3331 			},
3332 		},
3333 	};
3334 
3335 	if (fd < 0)
3336 		ctx.msg.payload.area.u64 |= VHOST_USER_VRING_NOFD_MASK;
3337 	else {
3338 		ctx.fds[0] = fd;
3339 		ctx.fd_num = 1;
3340 	}
3341 
3342 	ret = send_vhost_slave_message(dev, &ctx);
3343 	if (ret < 0) {
3344 		VHOST_LOG_CONFIG(dev->ifname, ERR, "failed to set host notifier (%d)\n", ret);
3345 		return ret;
3346 	}
3347 
3348 	return process_slave_message_reply(dev, &ctx);
3349 }
3350 
3351 int rte_vhost_host_notifier_ctrl(int vid, uint16_t qid, bool enable)
3352 {
3353 	struct virtio_net *dev;
3354 	struct rte_vdpa_device *vdpa_dev;
3355 	int vfio_device_fd, ret = 0;
3356 	uint64_t offset, size;
3357 	unsigned int i, q_start, q_last;
3358 
3359 	dev = get_device(vid);
3360 	if (!dev)
3361 		return -ENODEV;
3362 
3363 	vdpa_dev = dev->vdpa_dev;
3364 	if (vdpa_dev == NULL)
3365 		return -ENODEV;
3366 
3367 	if (!(dev->features & (1ULL << VIRTIO_F_VERSION_1)) ||
3368 	    !(dev->features & (1ULL << VHOST_USER_F_PROTOCOL_FEATURES)) ||
3369 	    !(dev->protocol_features &
3370 			(1ULL << VHOST_USER_PROTOCOL_F_SLAVE_REQ)) ||
3371 	    !(dev->protocol_features &
3372 			(1ULL << VHOST_USER_PROTOCOL_F_SLAVE_SEND_FD)) ||
3373 	    !(dev->protocol_features &
3374 			(1ULL << VHOST_USER_PROTOCOL_F_HOST_NOTIFIER)))
3375 		return -ENOTSUP;
3376 
3377 	if (qid == RTE_VHOST_QUEUE_ALL) {
3378 		q_start = 0;
3379 		q_last = dev->nr_vring - 1;
3380 	} else {
3381 		if (qid >= dev->nr_vring)
3382 			return -EINVAL;
3383 		q_start = qid;
3384 		q_last = qid;
3385 	}
3386 
3387 	if (vdpa_dev->ops->get_vfio_device_fd == NULL)
3388 		return -ENOTSUP;
3389 	if (vdpa_dev->ops->get_notify_area == NULL)
3390 		return -ENOTSUP;
3391 
3392 	vfio_device_fd = vdpa_dev->ops->get_vfio_device_fd(vid);
3393 	if (vfio_device_fd < 0)
3394 		return -ENOTSUP;
3395 
3396 	if (enable) {
3397 		for (i = q_start; i <= q_last; i++) {
3398 			if (vdpa_dev->ops->get_notify_area(vid, i, &offset,
3399 					&size) < 0) {
3400 				ret = -ENOTSUP;
3401 				goto disable;
3402 			}
3403 
3404 			if (vhost_user_slave_set_vring_host_notifier(dev, i,
3405 					vfio_device_fd, offset, size) < 0) {
3406 				ret = -EFAULT;
3407 				goto disable;
3408 			}
3409 		}
3410 	} else {
3411 disable:
3412 		for (i = q_start; i <= q_last; i++) {
3413 			vhost_user_slave_set_vring_host_notifier(dev, i, -1,
3414 					0, 0);
3415 		}
3416 	}
3417 
3418 	return ret;
3419 }
3420