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