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