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