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