vhost: use buffer vectors in dequeue path
[dpdk.git] / lib / librte_vhost / vhost.h
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation
3  */
4
5 #ifndef _VHOST_NET_CDEV_H_
6 #define _VHOST_NET_CDEV_H_
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdbool.h>
10 #include <sys/types.h>
11 #include <sys/queue.h>
12 #include <unistd.h>
13 #include <linux/vhost.h>
14 #include <linux/virtio_net.h>
15 #include <sys/socket.h>
16 #include <linux/if.h>
17
18 #include <rte_log.h>
19 #include <rte_ether.h>
20 #include <rte_rwlock.h>
21
22 #include "rte_vhost.h"
23 #include "rte_vdpa.h"
24
25 /* Used to indicate that the device is running on a data core */
26 #define VIRTIO_DEV_RUNNING 1
27 /* Used to indicate that the device is ready to operate */
28 #define VIRTIO_DEV_READY 2
29 /* Used to indicate that the built-in vhost net device backend is enabled */
30 #define VIRTIO_DEV_BUILTIN_VIRTIO_NET 4
31 /* Used to indicate that the device has its own data path and configured */
32 #define VIRTIO_DEV_VDPA_CONFIGURED 8
33
34 /* Backend value set by guest. */
35 #define VIRTIO_DEV_STOPPED -1
36
37 #define BUF_VECTOR_MAX 256
38
39 #define VHOST_LOG_CACHE_NR 32
40
41 /**
42  * Structure contains buffer address, length and descriptor index
43  * from vring to do scatter RX.
44  */
45 struct buf_vector {
46         uint64_t buf_iova;
47         uint64_t buf_addr;
48         uint32_t buf_len;
49         uint32_t desc_idx;
50 };
51
52 /*
53  * A structure to hold some fields needed in zero copy code path,
54  * mainly for associating an mbuf with the right desc_idx.
55  */
56 struct zcopy_mbuf {
57         struct rte_mbuf *mbuf;
58         uint32_t desc_idx;
59         uint16_t in_use;
60
61         TAILQ_ENTRY(zcopy_mbuf) next;
62 };
63 TAILQ_HEAD(zcopy_mbuf_list, zcopy_mbuf);
64
65 /*
66  * Structure contains the info for each batched memory copy.
67  */
68 struct batch_copy_elem {
69         void *dst;
70         void *src;
71         uint32_t len;
72         uint64_t log_addr;
73 };
74
75 /*
76  * Structure that contains the info for batched dirty logging.
77  */
78 struct log_cache_entry {
79         uint32_t offset;
80         unsigned long val;
81 };
82
83 /**
84  * Structure contains variables relevant to RX/TX virtqueues.
85  */
86 struct vhost_virtqueue {
87         struct vring_desc       *desc;
88         struct vring_avail      *avail;
89         struct vring_used       *used;
90         uint32_t                size;
91
92         uint16_t                last_avail_idx;
93         uint16_t                last_used_idx;
94         /* Last used index we notify to front end. */
95         uint16_t                signalled_used;
96 #define VIRTIO_INVALID_EVENTFD          (-1)
97 #define VIRTIO_UNINITIALIZED_EVENTFD    (-2)
98
99         /* Backend value to determine if device should started/stopped */
100         int                     backend;
101         int                     enabled;
102         int                     access_ok;
103         rte_spinlock_t          access_lock;
104
105         /* Used to notify the guest (trigger interrupt) */
106         int                     callfd;
107         /* Currently unused as polling mode is enabled */
108         int                     kickfd;
109
110         /* Physical address of used ring, for logging */
111         uint64_t                log_guest_addr;
112
113         uint16_t                nr_zmbuf;
114         uint16_t                zmbuf_size;
115         uint16_t                last_zmbuf_idx;
116         struct zcopy_mbuf       *zmbufs;
117         struct zcopy_mbuf_list  zmbuf_list;
118
119         struct vring_used_elem  *shadow_used_ring;
120         uint16_t                shadow_used_idx;
121         struct vhost_vring_addr ring_addrs;
122
123         struct batch_copy_elem  *batch_copy_elems;
124         uint16_t                batch_copy_nb_elems;
125
126         struct log_cache_entry log_cache[VHOST_LOG_CACHE_NR];
127         uint16_t log_cache_nb_elem;
128
129         rte_rwlock_t    iotlb_lock;
130         rte_rwlock_t    iotlb_pending_lock;
131         struct rte_mempool *iotlb_pool;
132         TAILQ_HEAD(, vhost_iotlb_entry) iotlb_list;
133         int                             iotlb_cache_nr;
134         TAILQ_HEAD(, vhost_iotlb_entry) iotlb_pending_list;
135 } __rte_cache_aligned;
136
137 /* Old kernels have no such macros defined */
138 #ifndef VIRTIO_NET_F_GUEST_ANNOUNCE
139  #define VIRTIO_NET_F_GUEST_ANNOUNCE 21
140 #endif
141
142 #ifndef VIRTIO_NET_F_MQ
143  #define VIRTIO_NET_F_MQ                22
144 #endif
145
146 #define VHOST_MAX_VRING                 0x100
147 #define VHOST_MAX_QUEUE_PAIRS           0x80
148
149 #ifndef VIRTIO_NET_F_MTU
150  #define VIRTIO_NET_F_MTU 3
151 #endif
152
153 #ifndef VIRTIO_F_ANY_LAYOUT
154  #define VIRTIO_F_ANY_LAYOUT            27
155 #endif
156
157 /* Declare IOMMU related bits for older kernels */
158 #ifndef VIRTIO_F_IOMMU_PLATFORM
159
160 #define VIRTIO_F_IOMMU_PLATFORM 33
161
162 struct vhost_iotlb_msg {
163         __u64 iova;
164         __u64 size;
165         __u64 uaddr;
166 #define VHOST_ACCESS_RO      0x1
167 #define VHOST_ACCESS_WO      0x2
168 #define VHOST_ACCESS_RW      0x3
169         __u8 perm;
170 #define VHOST_IOTLB_MISS           1
171 #define VHOST_IOTLB_UPDATE         2
172 #define VHOST_IOTLB_INVALIDATE     3
173 #define VHOST_IOTLB_ACCESS_FAIL    4
174         __u8 type;
175 };
176
177 #define VHOST_IOTLB_MSG 0x1
178
179 struct vhost_msg {
180         int type;
181         union {
182                 struct vhost_iotlb_msg iotlb;
183                 __u8 padding[64];
184         };
185 };
186 #endif
187
188 /*
189  * Define virtio 1.0 for older kernels
190  */
191 #ifndef VIRTIO_F_VERSION_1
192  #define VIRTIO_F_VERSION_1 32
193 #endif
194
195 /*
196  * Available and used descs are in same order
197  */
198 #ifndef VIRTIO_F_IN_ORDER
199 #define VIRTIO_F_IN_ORDER      35
200 #endif
201
202 /* Features supported by this builtin vhost-user net driver. */
203 #define VIRTIO_NET_SUPPORTED_FEATURES ((1ULL << VIRTIO_NET_F_MRG_RXBUF) | \
204                                 (1ULL << VIRTIO_F_ANY_LAYOUT) | \
205                                 (1ULL << VIRTIO_NET_F_CTRL_VQ) | \
206                                 (1ULL << VIRTIO_NET_F_CTRL_RX) | \
207                                 (1ULL << VIRTIO_NET_F_GUEST_ANNOUNCE) | \
208                                 (1ULL << VIRTIO_NET_F_MQ)      | \
209                                 (1ULL << VIRTIO_F_VERSION_1)   | \
210                                 (1ULL << VHOST_F_LOG_ALL)      | \
211                                 (1ULL << VHOST_USER_F_PROTOCOL_FEATURES) | \
212                                 (1ULL << VIRTIO_NET_F_GSO) | \
213                                 (1ULL << VIRTIO_NET_F_HOST_TSO4) | \
214                                 (1ULL << VIRTIO_NET_F_HOST_TSO6) | \
215                                 (1ULL << VIRTIO_NET_F_HOST_UFO) | \
216                                 (1ULL << VIRTIO_NET_F_HOST_ECN) | \
217                                 (1ULL << VIRTIO_NET_F_CSUM)    | \
218                                 (1ULL << VIRTIO_NET_F_GUEST_CSUM) | \
219                                 (1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
220                                 (1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
221                                 (1ULL << VIRTIO_NET_F_GUEST_UFO) | \
222                                 (1ULL << VIRTIO_NET_F_GUEST_ECN) | \
223                                 (1ULL << VIRTIO_RING_F_INDIRECT_DESC) | \
224                                 (1ULL << VIRTIO_RING_F_EVENT_IDX) | \
225                                 (1ULL << VIRTIO_NET_F_MTU)  | \
226                                 (1ULL << VIRTIO_F_IN_ORDER) | \
227                                 (1ULL << VIRTIO_F_IOMMU_PLATFORM))
228
229
230 struct guest_page {
231         uint64_t guest_phys_addr;
232         uint64_t host_phys_addr;
233         uint64_t size;
234 };
235
236 /**
237  * function prototype for the vhost backend to handler specific vhost user
238  * messages prior to the master message handling
239  *
240  * @param vid
241  *  vhost device id
242  * @param msg
243  *  Message pointer.
244  * @param require_reply
245  *  If the handler requires sending a reply, this varaible shall be written 1,
246  *  otherwise 0.
247  * @param skip_master
248  *  If the handler requires skipping the master message handling, this variable
249  *  shall be written 1, otherwise 0.
250  * @return
251  *  0 on success, -1 on failure
252  */
253 typedef int (*vhost_msg_pre_handle)(int vid, void *msg,
254                 uint32_t *require_reply, uint32_t *skip_master);
255
256 /**
257  * function prototype for the vhost backend to handler specific vhost user
258  * messages after the master message handling is done
259  *
260  * @param vid
261  *  vhost device id
262  * @param msg
263  *  Message pointer.
264  * @param require_reply
265  *  If the handler requires sending a reply, this varaible shall be written 1,
266  *  otherwise 0.
267  * @return
268  *  0 on success, -1 on failure
269  */
270 typedef int (*vhost_msg_post_handle)(int vid, void *msg,
271                 uint32_t *require_reply);
272
273 /**
274  * pre and post vhost user message handlers
275  */
276 struct vhost_user_extern_ops {
277         vhost_msg_pre_handle pre_msg_handle;
278         vhost_msg_post_handle post_msg_handle;
279 };
280
281 /**
282  * Device structure contains all configuration information relating
283  * to the device.
284  */
285 struct virtio_net {
286         /* Frontend (QEMU) memory and memory region information */
287         struct rte_vhost_memory *mem;
288         uint64_t                features;
289         uint64_t                protocol_features;
290         int                     vid;
291         uint32_t                flags;
292         uint16_t                vhost_hlen;
293         /* to tell if we need broadcast rarp packet */
294         rte_atomic16_t          broadcast_rarp;
295         uint32_t                nr_vring;
296         int                     dequeue_zero_copy;
297         struct vhost_virtqueue  *virtqueue[VHOST_MAX_QUEUE_PAIRS * 2];
298 #define IF_NAME_SZ (PATH_MAX > IFNAMSIZ ? PATH_MAX : IFNAMSIZ)
299         char                    ifname[IF_NAME_SZ];
300         uint64_t                log_size;
301         uint64_t                log_base;
302         uint64_t                log_addr;
303         struct ether_addr       mac;
304         uint16_t                mtu;
305
306         struct vhost_device_ops const *notify_ops;
307
308         uint32_t                nr_guest_pages;
309         uint32_t                max_guest_pages;
310         struct guest_page       *guest_pages;
311
312         int                     slave_req_fd;
313         rte_spinlock_t          slave_req_lock;
314
315         /*
316          * Device id to identify a specific backend device.
317          * It's set to -1 for the default software implementation.
318          */
319         int                     vdpa_dev_id;
320
321         /* private data for virtio device */
322         void                    *extern_data;
323         /* pre and post vhost user message handlers for the device */
324         struct vhost_user_extern_ops extern_ops;
325 } __rte_cache_aligned;
326
327 #define VHOST_LOG_PAGE  4096
328
329 /*
330  * Atomically set a bit in memory.
331  */
332 static __rte_always_inline void
333 vhost_set_bit(unsigned int nr, volatile uint8_t *addr)
334 {
335 #if defined(RTE_TOOLCHAIN_GCC) && (GCC_VERSION < 70100)
336         /*
337          * __sync_ built-ins are deprecated, but __atomic_ ones
338          * are sub-optimized in older GCC versions.
339          */
340         __sync_fetch_and_or_1(addr, (1U << nr));
341 #else
342         __atomic_fetch_or(addr, (1U << nr), __ATOMIC_RELAXED);
343 #endif
344 }
345
346 static __rte_always_inline void
347 vhost_log_page(uint8_t *log_base, uint64_t page)
348 {
349         vhost_set_bit(page % 8, &log_base[page / 8]);
350 }
351
352 static __rte_always_inline void
353 vhost_log_write(struct virtio_net *dev, uint64_t addr, uint64_t len)
354 {
355         uint64_t page;
356
357         if (likely(((dev->features & (1ULL << VHOST_F_LOG_ALL)) == 0) ||
358                    !dev->log_base || !len))
359                 return;
360
361         if (unlikely(dev->log_size <= ((addr + len - 1) / VHOST_LOG_PAGE / 8)))
362                 return;
363
364         /* To make sure guest memory updates are committed before logging */
365         rte_smp_wmb();
366
367         page = addr / VHOST_LOG_PAGE;
368         while (page * VHOST_LOG_PAGE < addr + len) {
369                 vhost_log_page((uint8_t *)(uintptr_t)dev->log_base, page);
370                 page += 1;
371         }
372 }
373
374 static __rte_always_inline void
375 vhost_log_cache_sync(struct virtio_net *dev, struct vhost_virtqueue *vq)
376 {
377         unsigned long *log_base;
378         int i;
379
380         if (likely(((dev->features & (1ULL << VHOST_F_LOG_ALL)) == 0) ||
381                    !dev->log_base))
382                 return;
383
384         log_base = (unsigned long *)(uintptr_t)dev->log_base;
385
386         /*
387          * It is expected a write memory barrier has been issued
388          * before this function is called.
389          */
390
391         for (i = 0; i < vq->log_cache_nb_elem; i++) {
392                 struct log_cache_entry *elem = vq->log_cache + i;
393
394 #if defined(RTE_TOOLCHAIN_GCC) && (GCC_VERSION < 70100)
395                 /*
396                  * '__sync' builtins are deprecated, but '__atomic' ones
397                  * are sub-optimized in older GCC versions.
398                  */
399                 __sync_fetch_and_or(log_base + elem->offset, elem->val);
400 #else
401                 __atomic_fetch_or(log_base + elem->offset, elem->val,
402                                 __ATOMIC_RELAXED);
403 #endif
404         }
405
406         rte_smp_wmb();
407
408         vq->log_cache_nb_elem = 0;
409 }
410
411 static __rte_always_inline void
412 vhost_log_cache_page(struct virtio_net *dev, struct vhost_virtqueue *vq,
413                         uint64_t page)
414 {
415         uint32_t bit_nr = page % (sizeof(unsigned long) << 3);
416         uint32_t offset = page / (sizeof(unsigned long) << 3);
417         int i;
418
419         for (i = 0; i < vq->log_cache_nb_elem; i++) {
420                 struct log_cache_entry *elem = vq->log_cache + i;
421
422                 if (elem->offset == offset) {
423                         elem->val |= (1UL << bit_nr);
424                         return;
425                 }
426         }
427
428         if (unlikely(i >= VHOST_LOG_CACHE_NR)) {
429                 /*
430                  * No more room for a new log cache entry,
431                  * so write the dirty log map directly.
432                  */
433                 rte_smp_wmb();
434                 vhost_log_page((uint8_t *)(uintptr_t)dev->log_base, page);
435
436                 return;
437         }
438
439         vq->log_cache[i].offset = offset;
440         vq->log_cache[i].val = (1UL << bit_nr);
441         vq->log_cache_nb_elem++;
442 }
443
444 static __rte_always_inline void
445 vhost_log_cache_write(struct virtio_net *dev, struct vhost_virtqueue *vq,
446                         uint64_t addr, uint64_t len)
447 {
448         uint64_t page;
449
450         if (likely(((dev->features & (1ULL << VHOST_F_LOG_ALL)) == 0) ||
451                    !dev->log_base || !len))
452                 return;
453
454         if (unlikely(dev->log_size <= ((addr + len - 1) / VHOST_LOG_PAGE / 8)))
455                 return;
456
457         page = addr / VHOST_LOG_PAGE;
458         while (page * VHOST_LOG_PAGE < addr + len) {
459                 vhost_log_cache_page(dev, vq, page);
460                 page += 1;
461         }
462 }
463
464 static __rte_always_inline void
465 vhost_log_cache_used_vring(struct virtio_net *dev, struct vhost_virtqueue *vq,
466                         uint64_t offset, uint64_t len)
467 {
468         vhost_log_cache_write(dev, vq, vq->log_guest_addr + offset, len);
469 }
470
471 static __rte_always_inline void
472 vhost_log_used_vring(struct virtio_net *dev, struct vhost_virtqueue *vq,
473                      uint64_t offset, uint64_t len)
474 {
475         vhost_log_write(dev, vq->log_guest_addr + offset, len);
476 }
477
478 /* Macros for printing using RTE_LOG */
479 #define RTE_LOGTYPE_VHOST_CONFIG RTE_LOGTYPE_USER1
480 #define RTE_LOGTYPE_VHOST_DATA   RTE_LOGTYPE_USER1
481
482 #ifdef RTE_LIBRTE_VHOST_DEBUG
483 #define VHOST_MAX_PRINT_BUFF 6072
484 #define VHOST_LOG_DEBUG(log_type, fmt, args...) \
485         RTE_LOG(DEBUG, log_type, fmt, ##args)
486 #define PRINT_PACKET(device, addr, size, header) do { \
487         char *pkt_addr = (char *)(addr); \
488         unsigned int index; \
489         char packet[VHOST_MAX_PRINT_BUFF]; \
490         \
491         if ((header)) \
492                 snprintf(packet, VHOST_MAX_PRINT_BUFF, "(%d) Header size %d: ", (device->vid), (size)); \
493         else \
494                 snprintf(packet, VHOST_MAX_PRINT_BUFF, "(%d) Packet size %d: ", (device->vid), (size)); \
495         for (index = 0; index < (size); index++) { \
496                 snprintf(packet + strnlen(packet, VHOST_MAX_PRINT_BUFF), VHOST_MAX_PRINT_BUFF - strnlen(packet, VHOST_MAX_PRINT_BUFF), \
497                         "%02hhx ", pkt_addr[index]); \
498         } \
499         snprintf(packet + strnlen(packet, VHOST_MAX_PRINT_BUFF), VHOST_MAX_PRINT_BUFF - strnlen(packet, VHOST_MAX_PRINT_BUFF), "\n"); \
500         \
501         VHOST_LOG_DEBUG(VHOST_DATA, "%s", packet); \
502 } while (0)
503 #else
504 #define VHOST_LOG_DEBUG(log_type, fmt, args...) do {} while (0)
505 #define PRINT_PACKET(device, addr, size, header) do {} while (0)
506 #endif
507
508 extern uint64_t VHOST_FEATURES;
509 #define MAX_VHOST_DEVICE        1024
510 extern struct virtio_net *vhost_devices[MAX_VHOST_DEVICE];
511
512 /* Convert guest physical address to host physical address */
513 static __rte_always_inline rte_iova_t
514 gpa_to_hpa(struct virtio_net *dev, uint64_t gpa, uint64_t size)
515 {
516         uint32_t i;
517         struct guest_page *page;
518
519         for (i = 0; i < dev->nr_guest_pages; i++) {
520                 page = &dev->guest_pages[i];
521
522                 if (gpa >= page->guest_phys_addr &&
523                     gpa + size < page->guest_phys_addr + page->size) {
524                         return gpa - page->guest_phys_addr +
525                                page->host_phys_addr;
526                 }
527         }
528
529         return 0;
530 }
531
532 static __rte_always_inline struct virtio_net *
533 get_device(int vid)
534 {
535         struct virtio_net *dev = vhost_devices[vid];
536
537         if (unlikely(!dev)) {
538                 RTE_LOG(ERR, VHOST_CONFIG,
539                         "(%d) device not found.\n", vid);
540         }
541
542         return dev;
543 }
544
545 int vhost_new_device(void);
546 void cleanup_device(struct virtio_net *dev, int destroy);
547 void reset_device(struct virtio_net *dev);
548 void vhost_destroy_device(int);
549 void vhost_destroy_device_notify(struct virtio_net *dev);
550
551 void cleanup_vq(struct vhost_virtqueue *vq, int destroy);
552 void free_vq(struct vhost_virtqueue *vq);
553
554 int alloc_vring_queue(struct virtio_net *dev, uint32_t vring_idx);
555
556 void vhost_attach_vdpa_device(int vid, int did);
557 void vhost_detach_vdpa_device(int vid);
558
559 void vhost_set_ifname(int, const char *if_name, unsigned int if_len);
560 void vhost_enable_dequeue_zero_copy(int vid);
561 void vhost_set_builtin_virtio_net(int vid, bool enable);
562
563 struct vhost_device_ops const *vhost_driver_callback_get(const char *path);
564
565 /*
566  * Backend-specific cleanup.
567  *
568  * TODO: fix it; we have one backend now
569  */
570 void vhost_backend_cleanup(struct virtio_net *dev);
571
572 uint64_t __vhost_iova_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
573                         uint64_t iova, uint64_t *len, uint8_t perm);
574 int vring_translate(struct virtio_net *dev, struct vhost_virtqueue *vq);
575 void vring_invalidate(struct virtio_net *dev, struct vhost_virtqueue *vq);
576
577 static __rte_always_inline uint64_t
578 vhost_iova_to_vva(struct virtio_net *dev, struct vhost_virtqueue *vq,
579                         uint64_t iova, uint64_t *len, uint8_t perm)
580 {
581         if (!(dev->features & (1ULL << VIRTIO_F_IOMMU_PLATFORM)))
582                 return rte_vhost_va_from_guest_pa(dev->mem, iova, len);
583
584         return __vhost_iova_to_vva(dev, vq, iova, len, perm);
585 }
586
587 #define vhost_used_event(vr) \
588         (*(volatile uint16_t*)&(vr)->avail->ring[(vr)->size])
589
590 /*
591  * The following is used with VIRTIO_RING_F_EVENT_IDX.
592  * Assuming a given event_idx value from the other size, if we have
593  * just incremented index from old to new_idx, should we trigger an
594  * event?
595  */
596 static __rte_always_inline int
597 vhost_need_event(uint16_t event_idx, uint16_t new_idx, uint16_t old)
598 {
599         return (uint16_t)(new_idx - event_idx - 1) < (uint16_t)(new_idx - old);
600 }
601
602 static __rte_always_inline void
603 vhost_vring_call(struct virtio_net *dev, struct vhost_virtqueue *vq)
604 {
605         /* Flush used->idx update before we read avail->flags. */
606         rte_smp_mb();
607
608         /* Don't kick guest if we don't reach index specified by guest. */
609         if (dev->features & (1ULL << VIRTIO_RING_F_EVENT_IDX)) {
610                 uint16_t old = vq->signalled_used;
611                 uint16_t new = vq->last_used_idx;
612
613                 VHOST_LOG_DEBUG(VHOST_DATA, "%s: used_event_idx=%d, old=%d, new=%d\n",
614                         __func__,
615                         vhost_used_event(vq),
616                         old, new);
617                 if (vhost_need_event(vhost_used_event(vq), new, old)
618                         && (vq->callfd >= 0)) {
619                         vq->signalled_used = vq->last_used_idx;
620                         eventfd_write(vq->callfd, (eventfd_t) 1);
621                 }
622         } else {
623                 /* Kick the guest if necessary. */
624                 if (!(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT)
625                                 && (vq->callfd >= 0))
626                         eventfd_write(vq->callfd, (eventfd_t)1);
627         }
628 }
629
630 #endif /* _VHOST_NET_CDEV_H_ */