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