vhost: simplify async copy completion
[dpdk.git] / lib / librte_vhost / vhost.h
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation
3  */
4
5 #ifndef _VHOST_NET_CDEV_H_
6 #define _VHOST_NET_CDEV_H_
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdbool.h>
10 #include <sys/types.h>
11 #include <sys/queue.h>
12 #include <unistd.h>
13 #include <linux/vhost.h>
14 #include <linux/virtio_net.h>
15 #include <sys/socket.h>
16 #include <linux/if.h>
17
18 #include <rte_log.h>
19 #include <rte_ether.h>
20 #include <rte_rwlock.h>
21 #include <rte_malloc.h>
22
23 #include "rte_vhost.h"
24 #include "rte_vdpa.h"
25 #include "rte_vdpa_dev.h"
26
27 #include "rte_vhost_async.h"
28
29 /* Used to indicate that the device is running on a data core */
30 #define VIRTIO_DEV_RUNNING 1
31 /* Used to indicate that the device is ready to operate */
32 #define VIRTIO_DEV_READY 2
33 /* Used to indicate that the built-in vhost net device backend is enabled */
34 #define VIRTIO_DEV_BUILTIN_VIRTIO_NET 4
35 /* Used to indicate that the device has its own data path and configured */
36 #define VIRTIO_DEV_VDPA_CONFIGURED 8
37 /* Used to indicate that the feature negotiation failed */
38 #define VIRTIO_DEV_FEATURES_FAILED 16
39
40 /* Backend value set by guest. */
41 #define VIRTIO_DEV_STOPPED -1
42
43 #define BUF_VECTOR_MAX 256
44
45 #define VHOST_LOG_CACHE_NR 32
46
47 #define MAX_PKT_BURST 32
48
49 #define VHOST_MAX_ASYNC_IT (MAX_PKT_BURST * 2)
50 #define VHOST_MAX_ASYNC_VEC (BUF_VECTOR_MAX * 2)
51
52 #define PACKED_DESC_ENQUEUE_USED_FLAG(w)        \
53         ((w) ? (VRING_DESC_F_AVAIL | VRING_DESC_F_USED | VRING_DESC_F_WRITE) : \
54                 VRING_DESC_F_WRITE)
55 #define PACKED_DESC_DEQUEUE_USED_FLAG(w)        \
56         ((w) ? (VRING_DESC_F_AVAIL | VRING_DESC_F_USED) : 0x0)
57 #define PACKED_DESC_SINGLE_DEQUEUE_FLAG (VRING_DESC_F_NEXT | \
58                                          VRING_DESC_F_INDIRECT)
59
60 #define PACKED_BATCH_SIZE (RTE_CACHE_LINE_SIZE / \
61                             sizeof(struct vring_packed_desc))
62 #define PACKED_BATCH_MASK (PACKED_BATCH_SIZE - 1)
63
64 #ifdef VHOST_GCC_UNROLL_PRAGMA
65 #define vhost_for_each_try_unroll(iter, val, size) _Pragma("GCC unroll 4") \
66         for (iter = val; iter < size; iter++)
67 #endif
68
69 #ifdef VHOST_CLANG_UNROLL_PRAGMA
70 #define vhost_for_each_try_unroll(iter, val, size) _Pragma("unroll 4") \
71         for (iter = val; iter < size; iter++)
72 #endif
73
74 #ifdef VHOST_ICC_UNROLL_PRAGMA
75 #define vhost_for_each_try_unroll(iter, val, size) _Pragma("unroll (4)") \
76         for (iter = val; iter < size; iter++)
77 #endif
78
79 #ifndef vhost_for_each_try_unroll
80 #define vhost_for_each_try_unroll(iter, val, num) \
81         for (iter = val; iter < num; iter++)
82 #endif
83
84 /**
85  * Structure contains buffer address, length and descriptor index
86  * from vring to do scatter RX.
87  */
88 struct buf_vector {
89         uint64_t buf_iova;
90         uint64_t buf_addr;
91         uint32_t buf_len;
92         uint32_t desc_idx;
93 };
94
95 /*
96  * Structure contains the info for each batched memory copy.
97  */
98 struct batch_copy_elem {
99         void *dst;
100         void *src;
101         uint32_t len;
102         uint64_t log_addr;
103 };
104
105 /*
106  * Structure that contains the info for batched dirty logging.
107  */
108 struct log_cache_entry {
109         uint32_t offset;
110         unsigned long val;
111 };
112
113 struct vring_used_elem_packed {
114         uint16_t id;
115         uint16_t flags;
116         uint32_t len;
117         uint32_t count;
118 };
119
120 /**
121  * Structure contains variables relevant to RX/TX virtqueues.
122  */
123 struct vhost_virtqueue {
124         union {
125                 struct vring_desc       *desc;
126                 struct vring_packed_desc   *desc_packed;
127         };
128         union {
129                 struct vring_avail      *avail;
130                 struct vring_packed_desc_event *driver_event;
131         };
132         union {
133                 struct vring_used       *used;
134                 struct vring_packed_desc_event *device_event;
135         };
136         uint32_t                size;
137
138         uint16_t                last_avail_idx;
139         uint16_t                last_used_idx;
140         /* Last used index we notify to front end. */
141         uint16_t                signalled_used;
142         bool                    signalled_used_valid;
143 #define VIRTIO_INVALID_EVENTFD          (-1)
144 #define VIRTIO_UNINITIALIZED_EVENTFD    (-2)
145
146         /* Backend value to determine if device should started/stopped */
147         int                     backend;
148         int                     enabled;
149         int                     access_ok;
150         int                     ready;
151         int                     notif_enable;
152 #define VIRTIO_UNINITIALIZED_NOTIF      (-1)
153
154         rte_spinlock_t          access_lock;
155
156         /* Used to notify the guest (trigger interrupt) */
157         int                     callfd;
158         /* Currently unused as polling mode is enabled */
159         int                     kickfd;
160
161         /* Physical address of used ring, for logging */
162         uint64_t                log_guest_addr;
163
164         /* inflight share memory info */
165         union {
166                 struct rte_vhost_inflight_info_split *inflight_split;
167                 struct rte_vhost_inflight_info_packed *inflight_packed;
168         };
169         struct rte_vhost_resubmit_info *resubmit_inflight;
170         uint64_t                global_counter;
171
172         union {
173                 struct vring_used_elem  *shadow_used_split;
174                 struct vring_used_elem_packed *shadow_used_packed;
175         };
176         uint16_t                shadow_used_idx;
177         /* Record packed ring enqueue latest desc cache aligned index */
178         uint16_t                shadow_aligned_idx;
179         /* Record packed ring first dequeue desc index */
180         uint16_t                shadow_last_used_idx;
181         struct vhost_vring_addr ring_addrs;
182
183         struct batch_copy_elem  *batch_copy_elems;
184         uint16_t                batch_copy_nb_elems;
185         bool                    used_wrap_counter;
186         bool                    avail_wrap_counter;
187
188         struct log_cache_entry log_cache[VHOST_LOG_CACHE_NR];
189         uint16_t log_cache_nb_elem;
190
191         rte_rwlock_t    iotlb_lock;
192         rte_rwlock_t    iotlb_pending_lock;
193         struct rte_mempool *iotlb_pool;
194         TAILQ_HEAD(, vhost_iotlb_entry) iotlb_list;
195         int                             iotlb_cache_nr;
196         TAILQ_HEAD(, vhost_iotlb_entry) iotlb_pending_list;
197
198         /* operation callbacks for async dma */
199         struct rte_vhost_async_channel_ops      async_ops;
200
201         struct rte_vhost_iov_iter it_pool[VHOST_MAX_ASYNC_IT];
202         struct iovec vec_pool[VHOST_MAX_ASYNC_VEC];
203
204         /* async data transfer status */
205         uintptr_t       **async_pkts_pending;
206         struct async_inflight_info *async_pkts_info;
207         uint16_t        async_pkts_idx;
208         uint16_t        async_pkts_inflight_n;
209         uint16_t        async_last_pkts_n;
210
211         /* vq async features */
212         bool            async_inorder;
213         bool            async_registered;
214         uint16_t        async_threshold;
215 } __rte_cache_aligned;
216
217 /* Virtio device status as per Virtio specification */
218 #define VIRTIO_DEVICE_STATUS_RESET              0x00
219 #define VIRTIO_DEVICE_STATUS_ACK                0x01
220 #define VIRTIO_DEVICE_STATUS_DRIVER             0x02
221 #define VIRTIO_DEVICE_STATUS_DRIVER_OK          0x04
222 #define VIRTIO_DEVICE_STATUS_FEATURES_OK        0x08
223 #define VIRTIO_DEVICE_STATUS_DEV_NEED_RESET     0x40
224 #define VIRTIO_DEVICE_STATUS_FAILED             0x80
225
226 #define VHOST_MAX_VRING                 0x100
227 #define VHOST_MAX_QUEUE_PAIRS           0x80
228
229 /* Declare IOMMU related bits for older kernels */
230 #ifndef VIRTIO_F_IOMMU_PLATFORM
231
232 #define VIRTIO_F_IOMMU_PLATFORM 33
233
234 struct vhost_iotlb_msg {
235         __u64 iova;
236         __u64 size;
237         __u64 uaddr;
238 #define VHOST_ACCESS_RO      0x1
239 #define VHOST_ACCESS_WO      0x2
240 #define VHOST_ACCESS_RW      0x3
241         __u8 perm;
242 #define VHOST_IOTLB_MISS           1
243 #define VHOST_IOTLB_UPDATE         2
244 #define VHOST_IOTLB_INVALIDATE     3
245 #define VHOST_IOTLB_ACCESS_FAIL    4
246         __u8 type;
247 };
248
249 #define VHOST_IOTLB_MSG 0x1
250
251 struct vhost_msg {
252         int type;
253         union {
254                 struct vhost_iotlb_msg iotlb;
255                 __u8 padding[64];
256         };
257 };
258 #endif
259
260 /*
261  * Define virtio 1.0 for older kernels
262  */
263 #ifndef VIRTIO_F_VERSION_1
264  #define VIRTIO_F_VERSION_1 32
265 #endif
266
267 /* Declare packed ring related bits for older kernels */
268 #ifndef VIRTIO_F_RING_PACKED
269
270 #define VIRTIO_F_RING_PACKED 34
271
272 struct vring_packed_desc {
273         uint64_t addr;
274         uint32_t len;
275         uint16_t id;
276         uint16_t flags;
277 };
278
279 struct vring_packed_desc_event {
280         uint16_t off_wrap;
281         uint16_t flags;
282 };
283 #endif
284
285 /*
286  * Declare below packed ring defines unconditionally
287  * as Kernel header might use different names.
288  */
289 #define VRING_DESC_F_AVAIL      (1ULL << 7)
290 #define VRING_DESC_F_USED       (1ULL << 15)
291
292 #define VRING_EVENT_F_ENABLE 0x0
293 #define VRING_EVENT_F_DISABLE 0x1
294 #define VRING_EVENT_F_DESC 0x2
295
296 /*
297  * Available and used descs are in same order
298  */
299 #ifndef VIRTIO_F_IN_ORDER
300 #define VIRTIO_F_IN_ORDER      35
301 #endif
302
303 /* Features supported by this builtin vhost-user net driver. */
304 #define VIRTIO_NET_SUPPORTED_FEATURES ((1ULL << VIRTIO_NET_F_MRG_RXBUF) | \
305                                 (1ULL << VIRTIO_F_ANY_LAYOUT) | \
306                                 (1ULL << VIRTIO_NET_F_CTRL_VQ) | \
307                                 (1ULL << VIRTIO_NET_F_CTRL_RX) | \
308                                 (1ULL << VIRTIO_NET_F_GUEST_ANNOUNCE) | \
309                                 (1ULL << VIRTIO_NET_F_MQ)      | \
310                                 (1ULL << VIRTIO_F_VERSION_1)   | \
311                                 (1ULL << VHOST_F_LOG_ALL)      | \
312                                 (1ULL << VHOST_USER_F_PROTOCOL_FEATURES) | \
313                                 (1ULL << VIRTIO_NET_F_GSO) | \
314                                 (1ULL << VIRTIO_NET_F_HOST_TSO4) | \
315                                 (1ULL << VIRTIO_NET_F_HOST_TSO6) | \
316                                 (1ULL << VIRTIO_NET_F_HOST_UFO) | \
317                                 (1ULL << VIRTIO_NET_F_HOST_ECN) | \
318                                 (1ULL << VIRTIO_NET_F_CSUM)    | \
319                                 (1ULL << VIRTIO_NET_F_GUEST_CSUM) | \
320                                 (1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
321                                 (1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
322                                 (1ULL << VIRTIO_NET_F_GUEST_UFO) | \
323                                 (1ULL << VIRTIO_NET_F_GUEST_ECN) | \
324                                 (1ULL << VIRTIO_RING_F_INDIRECT_DESC) | \
325                                 (1ULL << VIRTIO_RING_F_EVENT_IDX) | \
326                                 (1ULL << VIRTIO_NET_F_MTU)  | \
327                                 (1ULL << VIRTIO_F_IN_ORDER) | \
328                                 (1ULL << VIRTIO_F_IOMMU_PLATFORM) | \
329                                 (1ULL << VIRTIO_F_RING_PACKED))
330
331
332 struct guest_page {
333         uint64_t guest_phys_addr;
334         uint64_t host_phys_addr;
335         uint64_t size;
336 };
337
338 struct inflight_mem_info {
339         int             fd;
340         void            *addr;
341         uint64_t        size;
342 };
343
344 /**
345  * Device structure contains all configuration information relating
346  * to the device.
347  */
348 struct virtio_net {
349         /* Frontend (QEMU) memory and memory region information */
350         struct rte_vhost_memory *mem;
351         uint64_t                features;
352         uint64_t                protocol_features;
353         int                     vid;
354         uint32_t                flags;
355         uint16_t                vhost_hlen;
356         /* to tell if we need broadcast rarp packet */
357         int16_t                 broadcast_rarp;
358         uint32_t                nr_vring;
359         int                     async_copy;
360         int                     extbuf;
361         int                     linearbuf;
362         struct vhost_virtqueue  *virtqueue[VHOST_MAX_QUEUE_PAIRS * 2];
363         struct inflight_mem_info *inflight_info;
364 #define IF_NAME_SZ (PATH_MAX > IFNAMSIZ ? PATH_MAX : IFNAMSIZ)
365         char                    ifname[IF_NAME_SZ];
366         uint64_t                log_size;
367         uint64_t                log_base;
368         uint64_t                log_addr;
369         struct rte_ether_addr   mac;
370         uint16_t                mtu;
371         uint8_t                 status;
372
373         struct vhost_device_ops const *notify_ops;
374
375         uint32_t                nr_guest_pages;
376         uint32_t                max_guest_pages;
377         struct guest_page       *guest_pages;
378
379         int                     slave_req_fd;
380         rte_spinlock_t          slave_req_lock;
381
382         int                     postcopy_ufd;
383         int                     postcopy_listening;
384
385         struct rte_vdpa_device *vdpa_dev;
386
387         /* context data for the external message handlers */
388         void                    *extern_data;
389         /* pre and post vhost user message handlers for the device */
390         struct rte_vhost_user_extern_ops extern_ops;
391 } __rte_cache_aligned;
392
393 static __rte_always_inline bool
394 vq_is_packed(struct virtio_net *dev)
395 {
396         return dev->features & (1ull << VIRTIO_F_RING_PACKED);
397 }
398
399 static inline bool
400 desc_is_avail(struct vring_packed_desc *desc, bool wrap_counter)
401 {
402         uint16_t flags = __atomic_load_n(&desc->flags, __ATOMIC_ACQUIRE);
403
404         return wrap_counter == !!(flags & VRING_DESC_F_AVAIL) &&
405                 wrap_counter != !!(flags & VRING_DESC_F_USED);
406 }
407
408 static inline void
409 vq_inc_last_used_packed(struct vhost_virtqueue *vq, uint16_t num)
410 {
411         vq->last_used_idx += num;
412         if (vq->last_used_idx >= vq->size) {
413                 vq->used_wrap_counter ^= 1;
414                 vq->last_used_idx -= vq->size;
415         }
416 }
417
418 static inline void
419 vq_inc_last_avail_packed(struct vhost_virtqueue *vq, uint16_t num)
420 {
421         vq->last_avail_idx += num;
422         if (vq->last_avail_idx >= vq->size) {
423                 vq->avail_wrap_counter ^= 1;
424                 vq->last_avail_idx -= vq->size;
425         }
426 }
427
428 void __vhost_log_cache_write(struct virtio_net *dev,
429                 struct vhost_virtqueue *vq,
430                 uint64_t addr, uint64_t len);
431 void __vhost_log_cache_write_iova(struct virtio_net *dev,
432                 struct vhost_virtqueue *vq,
433                 uint64_t iova, uint64_t len);
434 void __vhost_log_cache_sync(struct virtio_net *dev,
435                 struct vhost_virtqueue *vq);
436 void __vhost_log_write(struct virtio_net *dev, uint64_t addr, uint64_t len);
437 void __vhost_log_write_iova(struct virtio_net *dev, struct vhost_virtqueue *vq,
438                             uint64_t iova, uint64_t len);
439
440 static __rte_always_inline void
441 vhost_log_write(struct virtio_net *dev, uint64_t addr, uint64_t len)
442 {
443         if (unlikely(dev->features & (1ULL << VHOST_F_LOG_ALL)))
444                 __vhost_log_write(dev, addr, len);
445 }
446
447 static __rte_always_inline void
448 vhost_log_cache_sync(struct virtio_net *dev, struct vhost_virtqueue *vq)
449 {
450         if (unlikely(dev->features & (1ULL << VHOST_F_LOG_ALL)))
451                 __vhost_log_cache_sync(dev, vq);
452 }
453
454 static __rte_always_inline void
455 vhost_log_cache_write(struct virtio_net *dev, struct vhost_virtqueue *vq,
456                         uint64_t addr, uint64_t len)
457 {
458         if (unlikely(dev->features & (1ULL << VHOST_F_LOG_ALL)))
459                 __vhost_log_cache_write(dev, vq, addr, len);
460 }
461
462 static __rte_always_inline void
463 vhost_log_cache_used_vring(struct virtio_net *dev, struct vhost_virtqueue *vq,
464                         uint64_t offset, uint64_t len)
465 {
466         if (unlikely(dev->features & (1ULL << VHOST_F_LOG_ALL))) {
467                 if (unlikely(vq->log_guest_addr == 0))
468                         return;
469                 __vhost_log_cache_write(dev, vq, vq->log_guest_addr + offset,
470                                         len);
471         }
472 }
473
474 static __rte_always_inline void
475 vhost_log_used_vring(struct virtio_net *dev, struct vhost_virtqueue *vq,
476                      uint64_t offset, uint64_t len)
477 {
478         if (unlikely(dev->features & (1ULL << VHOST_F_LOG_ALL))) {
479                 if (unlikely(vq->log_guest_addr == 0))
480                         return;
481                 __vhost_log_write(dev, vq->log_guest_addr + offset, len);
482         }
483 }
484
485 static __rte_always_inline void
486 vhost_log_cache_write_iova(struct virtio_net *dev, struct vhost_virtqueue *vq,
487                            uint64_t iova, uint64_t len)
488 {
489         if (likely(!(dev->features & (1ULL << VHOST_F_LOG_ALL))))
490                 return;
491
492         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))
493                 __vhost_log_cache_write_iova(dev, vq, iova, len);
494         else
495                 __vhost_log_cache_write(dev, vq, iova, len);
496 }
497
498 static __rte_always_inline void
499 vhost_log_write_iova(struct virtio_net *dev, struct vhost_virtqueue *vq,
500                            uint64_t iova, uint64_t len)
501 {
502         if (likely(!(dev->features & (1ULL << VHOST_F_LOG_ALL))))
503                 return;
504
505         if (dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM))
506                 __vhost_log_write_iova(dev, vq, iova, len);
507         else
508                 __vhost_log_write(dev, iova, len);
509 }
510
511 extern int vhost_config_log_level;
512 extern int vhost_data_log_level;
513
514 #define VHOST_LOG_CONFIG(level, fmt, args...)                   \
515         rte_log(RTE_LOG_ ## level, vhost_config_log_level,      \
516                 "VHOST_CONFIG: " fmt, ##args)
517
518 #define VHOST_LOG_DATA(level, fmt, args...) \
519         (void)((RTE_LOG_ ## level <= RTE_LOG_DP_LEVEL) ?        \
520          rte_log(RTE_LOG_ ## level,  vhost_data_log_level,      \
521                 "VHOST_DATA : " fmt, ##args) :                  \
522          0)
523
524 #ifdef RTE_LIBRTE_VHOST_DEBUG
525 #define VHOST_MAX_PRINT_BUFF 6072
526 #define PRINT_PACKET(device, addr, size, header) do { \
527         char *pkt_addr = (char *)(addr); \
528         unsigned int index; \
529         char packet[VHOST_MAX_PRINT_BUFF]; \
530         \
531         if ((header)) \
532                 snprintf(packet, VHOST_MAX_PRINT_BUFF, "(%d) Header size %d: ", (device->vid), (size)); \
533         else \
534                 snprintf(packet, VHOST_MAX_PRINT_BUFF, "(%d) Packet size %d: ", (device->vid), (size)); \
535         for (index = 0; index < (size); index++) { \
536                 snprintf(packet + strnlen(packet, VHOST_MAX_PRINT_BUFF), VHOST_MAX_PRINT_BUFF - strnlen(packet, VHOST_MAX_PRINT_BUFF), \
537                         "%02hhx ", pkt_addr[index]); \
538         } \
539         snprintf(packet + strnlen(packet, VHOST_MAX_PRINT_BUFF), VHOST_MAX_PRINT_BUFF - strnlen(packet, VHOST_MAX_PRINT_BUFF), "\n"); \
540         \
541         VHOST_LOG_DATA(DEBUG, "%s", packet); \
542 } while (0)
543 #else
544 #define PRINT_PACKET(device, addr, size, header) do {} while (0)
545 #endif
546
547 #define MAX_VHOST_DEVICE        1024
548 extern struct virtio_net *vhost_devices[MAX_VHOST_DEVICE];
549
550 #define VHOST_BINARY_SEARCH_THRESH 256
551
552 static __rte_always_inline int guest_page_addrcmp(const void *p1,
553                                                 const void *p2)
554 {
555         const struct guest_page *page1 = (const struct guest_page *)p1;
556         const struct guest_page *page2 = (const struct guest_page *)p2;
557
558         if (page1->guest_phys_addr > page2->guest_phys_addr)
559                 return 1;
560         if (page1->guest_phys_addr < page2->guest_phys_addr)
561                 return -1;
562
563         return 0;
564 }
565
566 /* Convert guest physical address to host physical address */
567 static __rte_always_inline rte_iova_t
568 gpa_to_hpa(struct virtio_net *dev, uint64_t gpa, uint64_t size)
569 {
570         uint32_t i;
571         struct guest_page *page;
572         struct guest_page key;
573
574         if (dev->nr_guest_pages >= VHOST_BINARY_SEARCH_THRESH) {
575                 key.guest_phys_addr = gpa;
576                 page = bsearch(&key, dev->guest_pages, dev->nr_guest_pages,
577                                sizeof(struct guest_page), guest_page_addrcmp);
578                 if (page) {
579                         if (gpa + size < page->guest_phys_addr + page->size)
580                                 return gpa - page->guest_phys_addr +
581                                         page->host_phys_addr;
582                 }
583         } else {
584                 for (i = 0; i < dev->nr_guest_pages; i++) {
585                         page = &dev->guest_pages[i];
586
587                         if (gpa >= page->guest_phys_addr &&
588                             gpa + size < page->guest_phys_addr +
589                             page->size)
590                                 return gpa - page->guest_phys_addr +
591                                        page->host_phys_addr;
592                 }
593         }
594
595         return 0;
596 }
597
598 static __rte_always_inline rte_iova_t
599 gpa_to_first_hpa(struct virtio_net *dev, uint64_t gpa,
600         uint64_t gpa_size, uint64_t *hpa_size)
601 {
602         uint32_t i;
603         struct guest_page *page;
604         struct guest_page key;
605
606         *hpa_size = gpa_size;
607         if (dev->nr_guest_pages >= VHOST_BINARY_SEARCH_THRESH) {
608                 key.guest_phys_addr = gpa & ~(dev->guest_pages[0].size - 1);
609                 page = bsearch(&key, dev->guest_pages, dev->nr_guest_pages,
610                                sizeof(struct guest_page), guest_page_addrcmp);
611                 if (page) {
612                         if (gpa + gpa_size <=
613                                         page->guest_phys_addr + page->size) {
614                                 return gpa - page->guest_phys_addr +
615                                         page->host_phys_addr;
616                         } else if (gpa < page->guest_phys_addr +
617                                                 page->size) {
618                                 *hpa_size = page->guest_phys_addr +
619                                         page->size - gpa;
620                                 return gpa - page->guest_phys_addr +
621                                         page->host_phys_addr;
622                         }
623                 }
624         } else {
625                 for (i = 0; i < dev->nr_guest_pages; i++) {
626                         page = &dev->guest_pages[i];
627
628                         if (gpa >= page->guest_phys_addr) {
629                                 if (gpa + gpa_size <=
630                                         page->guest_phys_addr + page->size) {
631                                         return gpa - page->guest_phys_addr +
632                                                 page->host_phys_addr;
633                                 } else if (gpa < page->guest_phys_addr +
634                                                         page->size) {
635                                         *hpa_size = page->guest_phys_addr +
636                                                 page->size - gpa;
637                                         return gpa - page->guest_phys_addr +
638                                                 page->host_phys_addr;
639                                 }
640                         }
641                 }
642         }
643
644         *hpa_size = 0;
645         return 0;
646 }
647
648 static __rte_always_inline uint64_t
649 hva_to_gpa(struct virtio_net *dev, uint64_t vva, uint64_t len)
650 {
651         struct rte_vhost_mem_region *r;
652         uint32_t i;
653
654         if (unlikely(!dev || !dev->mem))
655                 return 0;
656
657         for (i = 0; i < dev->mem->nregions; i++) {
658                 r = &dev->mem->regions[i];
659
660                 if (vva >= r->host_user_addr &&
661                     vva + len <  r->host_user_addr + r->size) {
662                         return r->guest_phys_addr + vva - r->host_user_addr;
663                 }
664         }
665         return 0;
666 }
667
668 static __rte_always_inline struct virtio_net *
669 get_device(int vid)
670 {
671         struct virtio_net *dev = vhost_devices[vid];
672
673         if (unlikely(!dev)) {
674                 VHOST_LOG_CONFIG(ERR,
675                         "(%d) device not found.\n", vid);
676         }
677
678         return dev;
679 }
680
681 int vhost_new_device(void);
682 void cleanup_device(struct virtio_net *dev, int destroy);
683 void reset_device(struct virtio_net *dev);
684 void vhost_destroy_device(int);
685 void vhost_destroy_device_notify(struct virtio_net *dev);
686
687 void cleanup_vq(struct vhost_virtqueue *vq, int destroy);
688 void cleanup_vq_inflight(struct virtio_net *dev, struct vhost_virtqueue *vq);
689 void free_vq(struct virtio_net *dev, struct vhost_virtqueue *vq);
690
691 int alloc_vring_queue(struct virtio_net *dev, uint32_t vring_idx);
692
693 void vhost_attach_vdpa_device(int vid, struct rte_vdpa_device *dev);
694
695 void vhost_set_ifname(int, const char *if_name, unsigned int if_len);
696 void vhost_set_builtin_virtio_net(int vid, bool enable);
697 void vhost_enable_extbuf(int vid);
698 void vhost_enable_linearbuf(int vid);
699 int vhost_enable_guest_notification(struct virtio_net *dev,
700                 struct vhost_virtqueue *vq, int enable);
701
702 struct vhost_device_ops const *vhost_driver_callback_get(const char *path);
703
704 /*
705  * Backend-specific cleanup.
706  *
707  * TODO: fix it; we have one backend now
708  */
709 void vhost_backend_cleanup(struct virtio_net *dev);
710
711 uint64_t __vhost_iova_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
712                         uint64_t iova, uint64_t *len, uint8_t perm);
713 void *vhost_alloc_copy_ind_table(struct virtio_net *dev,
714                         struct vhost_virtqueue *vq,
715                         uint64_t desc_addr, uint64_t desc_len);
716 int vring_translate(struct virtio_net *dev, struct vhost_virtqueue *vq);
717 uint64_t translate_log_addr(struct virtio_net *dev, struct vhost_virtqueue *vq,
718                 uint64_t log_addr);
719 void vring_invalidate(struct virtio_net *dev, struct vhost_virtqueue *vq);
720
721 static __rte_always_inline uint64_t
722 vhost_iova_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
723                         uint64_t iova, uint64_t *len, uint8_t perm)
724 {
725         if (!(dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM)))
726                 return rte_vhost_va_from_guest_pa(dev->mem, iova, len);
727
728         return __vhost_iova_to_vva(dev, vq, iova, len, perm);
729 }
730
731 #define vhost_avail_event(vr) \
732         (*(volatile uint16_t*)&(vr)->used->ring[(vr)->size])
733 #define vhost_used_event(vr) \
734         (*(volatile uint16_t*)&(vr)->avail->ring[(vr)->size])
735
736 /*
737  * The following is used with VIRTIO_RING_F_EVENT_IDX.
738  * Assuming a given event_idx value from the other size, if we have
739  * just incremented index from old to new_idx, should we trigger an
740  * event?
741  */
742 static __rte_always_inline int
743 vhost_need_event(uint16_t event_idx, uint16_t new_idx, uint16_t old)
744 {
745         return (uint16_t)(new_idx - event_idx - 1) < (uint16_t)(new_idx - old);
746 }
747
748 static __rte_always_inline void
749 vhost_vring_call_split(struct virtio_net *dev, struct vhost_virtqueue *vq)
750 {
751         /* Flush used->idx update before we read avail->flags. */
752         rte_smp_mb();
753
754         /* Don't kick guest if we don't reach index specified by guest. */
755         if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX)) {
756                 uint16_t old = vq->signalled_used;
757                 uint16_t new = vq->async_pkts_inflight_n ?
758                                         vq->used->idx:vq->last_used_idx;
759                 bool signalled_used_valid = vq->signalled_used_valid;
760
761                 vq->signalled_used = new;
762                 vq->signalled_used_valid = true;
763
764                 VHOST_LOG_DATA(DEBUG, "%s: used_event_idx=%d, old=%d, new=%d\n",
765                         __func__,
766                         vhost_used_event(vq),
767                         old, new);
768
769                 if ((vhost_need_event(vhost_used_event(vq), new, old) &&
770                                         (vq->callfd >= 0)) ||
771                                 unlikely(!signalled_used_valid)) {
772                         eventfd_write(vq->callfd, (eventfd_t) 1);
773                         if (dev->notify_ops->guest_notified)
774                                 dev->notify_ops->guest_notified(dev->vid);
775                 }
776         } else {
777                 /* Kick the guest if necessary. */
778                 if (!(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT)
779                                 && (vq->callfd >= 0)) {
780                         eventfd_write(vq->callfd, (eventfd_t)1);
781                         if (dev->notify_ops->guest_notified)
782                                 dev->notify_ops->guest_notified(dev->vid);
783                 }
784         }
785 }
786
787 static __rte_always_inline void
788 vhost_vring_call_packed(struct virtio_net *dev, struct vhost_virtqueue *vq)
789 {
790         uint16_t old, new, off, off_wrap;
791         bool signalled_used_valid, kick = false;
792
793         /* Flush used desc update. */
794         rte_smp_mb();
795
796         if (!(dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX))) {
797                 if (vq->driver_event->flags !=
798                                 VRING_EVENT_F_DISABLE)
799                         kick = true;
800                 goto kick;
801         }
802
803         old = vq->signalled_used;
804         new = vq->last_used_idx;
805         vq->signalled_used = new;
806         signalled_used_valid = vq->signalled_used_valid;
807         vq->signalled_used_valid = true;
808
809         if (vq->driver_event->flags != VRING_EVENT_F_DESC) {
810                 if (vq->driver_event->flags != VRING_EVENT_F_DISABLE)
811                         kick = true;
812                 goto kick;
813         }
814
815         if (unlikely(!signalled_used_valid)) {
816                 kick = true;
817                 goto kick;
818         }
819
820         rte_smp_rmb();
821
822         off_wrap = vq->driver_event->off_wrap;
823         off = off_wrap & ~(1 << 15);
824
825         if (new <= old)
826                 old -= vq->size;
827
828         if (vq->used_wrap_counter != off_wrap >> 15)
829                 off -= vq->size;
830
831         if (vhost_need_event(off, new, old))
832                 kick = true;
833 kick:
834         if (kick) {
835                 eventfd_write(vq->callfd, (eventfd_t)1);
836                 if (dev->notify_ops->guest_notified)
837                         dev->notify_ops->guest_notified(dev->vid);
838         }
839 }
840
841 static __rte_always_inline void
842 free_ind_table(void *idesc)
843 {
844         rte_free(idesc);
845 }
846
847 static __rte_always_inline void
848 restore_mbuf(struct rte_mbuf *m)
849 {
850         uint32_t mbuf_size, priv_size;
851
852         while (m) {
853                 priv_size = rte_pktmbuf_priv_size(m->pool);
854                 mbuf_size = sizeof(struct rte_mbuf) + priv_size;
855                 /* start of buffer is after mbuf structure and priv data */
856
857                 m->buf_addr = (char *)m + mbuf_size;
858                 m->buf_iova = rte_mempool_virt2iova(m) + mbuf_size;
859                 m = m->next;
860         }
861 }
862
863 static __rte_always_inline bool
864 mbuf_is_consumed(struct rte_mbuf *m)
865 {
866         while (m) {
867                 if (rte_mbuf_refcnt_read(m) > 1)
868                         return false;
869                 m = m->next;
870         }
871
872         return true;
873 }
874
875 #endif /* _VHOST_NET_CDEV_H_ */