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