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