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