Vhost-User: Fix calculate memory region size
[vpp.git] / vnet / vnet / devices / dpdk / vhost_user.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <assert.h>
16 #include <sys/socket.h>
17 #include <sys/un.h>
18 #include <sys/stat.h>
19 #include <sys/vfs.h>
20
21 #include <vlib/vlib.h>
22 #include <vlib/unix/unix.h>
23
24 #include <vnet/vnet.h>
25 #include <vppinfra/vec.h>
26 #include <vppinfra/error.h>
27 #include <vppinfra/format.h>
28
29 #include <vnet/ethernet/ethernet.h>
30 #include <vnet/devices/dpdk/dpdk.h>
31
32 #include <vnet/devices/virtio/vhost-user.h>
33
34 #define VHOST_USER_DEBUG_SOCKET 0
35
36 #if VHOST_USER_DEBUG_SOCKET == 1
37 #define DBG_SOCK(args...) clib_warning(args);
38 #else
39 #define DBG_SOCK(args...)
40 #endif
41
42 #if DPDK_VHOST_USER
43
44 static const char *vhost_message_str[] __attribute__((unused)) = {
45     [VHOST_USER_NONE] = "VHOST_USER_NONE",
46     [VHOST_USER_GET_FEATURES] = "VHOST_USER_GET_FEATURES",
47     [VHOST_USER_SET_FEATURES] = "VHOST_USER_SET_FEATURES",
48     [VHOST_USER_SET_OWNER] = "VHOST_USER_SET_OWNER",
49     [VHOST_USER_RESET_OWNER] = "VHOST_USER_RESET_OWNER",
50     [VHOST_USER_SET_MEM_TABLE] = "VHOST_USER_SET_MEM_TABLE",
51     [VHOST_USER_SET_LOG_BASE] = "VHOST_USER_SET_LOG_BASE",
52     [VHOST_USER_SET_LOG_FD] = "VHOST_USER_SET_LOG_FD",
53     [VHOST_USER_SET_VRING_NUM] = "VHOST_USER_SET_VRING_NUM",
54     [VHOST_USER_SET_VRING_ADDR] = "VHOST_USER_SET_VRING_ADDR",
55     [VHOST_USER_SET_VRING_BASE] = "VHOST_USER_SET_VRING_BASE",
56     [VHOST_USER_GET_VRING_BASE] = "VHOST_USER_GET_VRING_BASE",
57     [VHOST_USER_SET_VRING_KICK] = "VHOST_USER_SET_VRING_KICK",
58     [VHOST_USER_SET_VRING_CALL] = "VHOST_USER_SET_VRING_CALL",
59     [VHOST_USER_SET_VRING_ERR]  = "VHOST_USER_SET_VRING_ERR",
60     [VHOST_USER_GET_PROTOCOL_FEATURES]  = "VHOST_USER_GET_PROTOCOL_FEATURES",
61     [VHOST_USER_SET_PROTOCOL_FEATURES]  = "VHOST_USER_SET_PROTOCOL_FEATURES",
62     [VHOST_USER_GET_QUEUE_NUM]  = "VHOST_USER_GET_QUEUE_NUM",
63     [VHOST_USER_SET_VRING_ENABLE]  = "VHOST_USER_SET_VRING_ENABLE",
64 };
65
66 static int dpdk_vhost_user_set_vring_enable(u32 hw_if_index,
67     u8 idx, int enable);
68
69 /*
70  * DPDK vhost-user functions 
71  */
72
73 /* portions taken from dpdk 
74  *   BSD LICENSE
75  *
76  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
77  *   All rights reserved.
78  *
79  *   Redistribution and use in source and binary forms, with or without
80  *   modification, are permitted provided that the following conditions
81  *   are met:
82  *
83  *     * Redistributions of source code must retain the above copyright
84  *       notice, this list of conditions and the following disclaimer.
85  *     * Redistributions in binary form must reproduce the above copyright
86  *       notice, this list of conditions and the following disclaimer in
87  *       the documentation and/or other materials provided with the
88  *       distribution.
89  *     * Neither the name of Intel Corporation nor the names of its
90  *       contributors may be used to endorse or promote products derived
91  *       from this software without specific prior written permission.
92  *
93  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
94  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
95  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
96  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
97  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
98  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
99  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
100  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
101  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
102  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
103  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
104  */
105
106
107 static uword
108 qva_to_vva(struct virtio_net *dev, uword qemu_va)
109 {
110   struct virtio_memory_regions *region;
111   uword vhost_va = 0;
112   uint32_t regionidx = 0;
113
114   /* Find the region where the address lives. */
115   for (regionidx = 0; regionidx < dev->mem->nregions; regionidx++) {
116     region = &dev->mem->regions[regionidx];
117     if ((qemu_va >= region->userspace_address) &&
118       (qemu_va <= region->userspace_address +
119       region->memory_size)) {
120       vhost_va = qemu_va + region->guest_phys_address +
121         region->address_offset -
122         region->userspace_address;
123       break;
124     }
125   }
126   return vhost_va;
127 }
128
129 static dpdk_device_t *
130 dpdk_vhost_user_device_from_hw_if_index(u32 hw_if_index)
131 {
132   vnet_main_t *vnm = vnet_get_main();
133   dpdk_main_t * dm = &dpdk_main;
134   vnet_hw_interface_t * hi = vnet_get_hw_interface (vnm, hw_if_index);
135   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
136
137   if (xd->dev_type != VNET_DPDK_DEV_VHOST_USER)
138     return 0;
139
140   return xd;
141 }
142
143 static dpdk_device_t *
144 dpdk_vhost_user_device_from_sw_if_index(u32 sw_if_index)
145 {
146   vnet_main_t *vnm = vnet_get_main();
147   vnet_sw_interface_t * sw = vnet_get_sw_interface (vnm, sw_if_index);
148   ASSERT (sw->type == VNET_SW_INTERFACE_TYPE_HARDWARE);
149
150   return dpdk_vhost_user_device_from_hw_if_index(sw->hw_if_index);
151 }
152
153 static void stop_processing_packets(u32 hw_if_index, u8 idx)
154 {
155   dpdk_device_t *xd =
156     dpdk_vhost_user_device_from_hw_if_index(hw_if_index);
157   assert(xd);
158   xd->vu_vhost_dev.virtqueue[idx]->enabled = 0;
159 }
160
161 static void disable_interface(dpdk_device_t * xd)
162 {
163   u8 idx;
164   int numqs = xd->vu_vhost_dev.virt_qp_nb * VIRTIO_QNUM;
165   for (idx = 0;  idx < numqs; idx++)
166     xd->vu_vhost_dev.virtqueue[idx]->enabled = 0;
167
168   xd->vu_is_running = 0;
169 }
170
171 static inline void * map_guest_mem(dpdk_device_t * xd, uword addr)
172 {
173   dpdk_vu_intf_t * vui = xd->vu_intf;
174   struct virtio_memory * mem = xd->vu_vhost_dev.mem;
175   int i;
176   for (i=0; i<mem->nregions; i++) {
177     if ((mem->regions[i].guest_phys_address <= addr) &&
178        ((mem->regions[i].guest_phys_address + mem->regions[i].memory_size) > addr)) {
179          return (void *) ((uword)vui->region_addr[i] + addr - (uword)mem->regions[i].guest_phys_address);
180        }
181   }
182   DBG_SOCK("failed to map guest mem addr %lx", addr);
183   return 0;
184 }
185
186 static clib_error_t *
187 dpdk_create_vhost_user_if_internal (u32 * hw_if_index, u32 if_id, u8 *hwaddr)
188 {
189   dpdk_main_t * dm = &dpdk_main;
190   vlib_main_t * vm = vlib_get_main();
191   vlib_thread_main_t * tm = vlib_get_thread_main();
192   vnet_sw_interface_t * sw;
193   clib_error_t * error;
194   dpdk_device_and_queue_t * dq;
195   int num_qpairs = 1;
196   dpdk_vu_intf_t *vui = NULL;
197
198   num_qpairs = dm->use_rss < 1 ? 1 : tm->n_vlib_mains;
199
200   dpdk_device_t * xd = NULL;
201   u8 addr[6];
202   int j;
203
204   vlib_worker_thread_barrier_sync (vm);
205
206   int inactive_cnt = vec_len(dm->vu_inactive_interfaces_device_index);
207   // if there are any inactive ifaces
208   if (inactive_cnt > 0) {
209     // take last
210     u32 vui_idx = dm->vu_inactive_interfaces_device_index[inactive_cnt - 1];
211     if (vec_len(dm->devices) > vui_idx) {
212       xd = vec_elt_at_index (dm->devices, vui_idx);
213       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER) {
214           DBG_SOCK("reusing inactive vhost-user interface sw_if_index %d", xd->vlib_sw_if_index);
215       } else {
216           clib_warning("error: inactive vhost-user interface sw_if_index %d not VHOST_USER type!",
217                   xd->vlib_sw_if_index);
218           // reset so new interface is created
219           xd = NULL;
220       }
221     }
222     // "remove" from inactive list
223     _vec_len(dm->vu_inactive_interfaces_device_index) -= 1;
224   }
225
226   if (xd) {
227       // existing interface used - do not overwrite if_id if not needed
228       if (if_id != (u32)~0)
229           xd->vu_if_id = if_id;
230
231       // reset virtqueues
232       vui = xd->vu_intf;
233       for (j = 0; j < num_qpairs * VIRTIO_QNUM; j++) {
234           memset(xd->vu_vhost_dev.virtqueue[j], 0, sizeof(struct vhost_virtqueue));
235           xd->vu_vhost_dev.virtqueue[j]->kickfd = -1; 
236           xd->vu_vhost_dev.virtqueue[j]->callfd = -1; 
237           xd->vu_vhost_dev.virtqueue[j]->backend = -1; 
238           vui->vrings[j].packets = 0;
239           vui->vrings[j].bytes = 0;
240        }
241
242       // reset lockp
243       dpdk_device_lock_free(xd);
244       dpdk_device_lock_init(xd);
245
246       // reset tx vectors
247       for (j = 0; j < tm->n_vlib_mains; j++)
248         {
249           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE,
250                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
251           vec_reset_length (xd->tx_vectors[j]);
252         }
253
254       // reset rx vector
255       for (j = 0; j < xd->rx_q_used; j++)
256         {
257           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
258                                 CLIB_CACHE_LINE_BYTES);
259           vec_reset_length (xd->rx_vectors[j]);
260         }
261   } else {
262       // vui was not retrieved from inactive ifaces - create new
263       vec_add2_aligned (dm->devices, xd, 1, CLIB_CACHE_LINE_BYTES);
264       xd->dev_type = VNET_DPDK_DEV_VHOST_USER;
265       xd->rx_q_used = num_qpairs;
266       xd->tx_q_used = num_qpairs;
267       xd->vu_vhost_dev.virt_qp_nb = num_qpairs;
268
269       vec_validate_aligned (xd->rx_vectors, xd->rx_q_used, CLIB_CACHE_LINE_BYTES);
270
271       if (if_id == (u32)~0)
272           xd->vu_if_id = dm->next_vu_if_id++;
273       else
274           xd->vu_if_id = if_id;
275
276       xd->device_index = xd - dm->devices;
277       xd->per_interface_next_index = ~0;
278       xd->vu_intf = clib_mem_alloc (sizeof(*(xd->vu_intf)));
279
280       xd->vu_vhost_dev.mem = clib_mem_alloc (sizeof(struct virtio_memory) +
281                                              VHOST_MEMORY_MAX_NREGIONS *
282                                              sizeof(struct virtio_memory_regions));
283
284       /* Will be set when guest sends VHOST_USER_SET_MEM_TABLE cmd */
285       xd->vu_vhost_dev.mem->nregions = 0;
286
287       /* 
288        * New virtqueue structure is an array of VHOST_MAX_QUEUE_PAIRS * 2
289        * We need to allocate numq pairs.
290        */
291       vui = xd->vu_intf;
292       for (j = 0; j < num_qpairs * VIRTIO_QNUM; j++) {
293           xd->vu_vhost_dev.virtqueue[j] = clib_mem_alloc (sizeof(struct vhost_virtqueue));
294           memset(xd->vu_vhost_dev.virtqueue[j], 0, sizeof(struct vhost_virtqueue));
295           xd->vu_vhost_dev.virtqueue[j]->kickfd = -1; 
296           xd->vu_vhost_dev.virtqueue[j]->callfd = -1; 
297           xd->vu_vhost_dev.virtqueue[j]->backend = -1; 
298           vui->vrings[j].packets = 0;
299           vui->vrings[j].bytes = 0;
300       }
301
302       dpdk_device_lock_init(xd);
303
304       DBG_SOCK("tm->n_vlib_mains: %d. TX %d, RX: %d, num_qpairs: %d, Lock: %p",
305         tm->n_vlib_mains, xd->tx_q_used, xd->rx_q_used, num_qpairs, xd->lockp);
306
307       vec_validate_aligned (xd->tx_vectors, tm->n_vlib_mains,
308                             CLIB_CACHE_LINE_BYTES);
309
310       for (j = 0; j < tm->n_vlib_mains; j++)
311         {
312           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE,
313                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
314           vec_reset_length (xd->tx_vectors[j]);
315         }
316
317       // reset rx vector
318       for (j = 0; j < xd->rx_q_used; j++)
319         {
320           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
321                                 CLIB_CACHE_LINE_BYTES);
322           vec_reset_length (xd->rx_vectors[j]);
323         }
324
325   }
326   /*
327    * Generate random MAC address for the interface
328    */
329   if (hwaddr) {
330     clib_memcpy(addr, hwaddr, sizeof(addr));
331   } else {
332     f64 now = vlib_time_now(vm);
333     u32 rnd;
334     rnd = (u32) (now * 1e6);
335     rnd = random_u32 (&rnd);
336
337     clib_memcpy (addr+2, &rnd, sizeof(rnd));
338     addr[0] = 2;
339     addr[1] = 0xfe;
340   }
341
342   error = ethernet_register_interface
343     (dm->vnet_main,
344      dpdk_device_class.index,
345      xd->device_index,
346      /* ethernet address */ addr,
347      &xd->vlib_hw_if_index,
348      0);
349
350   if (error)
351     return error;
352
353   sw = vnet_get_hw_sw_interface (dm->vnet_main, xd->vlib_hw_if_index);
354   xd->vlib_sw_if_index = sw->sw_if_index;
355
356   *hw_if_index = xd->vlib_hw_if_index;
357
358   DBG_SOCK("xd->device_index: %d, dm->input_cpu_count: %d, "
359     "dm->input_cpu_first_index: %d\n", xd->device_index,
360     dm->input_cpu_count, dm->input_cpu_first_index);
361
362   int q, next_cpu = 0;
363   for (q = 0; q < num_qpairs; q++) {
364       int cpu = dm->input_cpu_first_index +
365         (next_cpu % dm->input_cpu_count);
366
367       unsigned lcore = vlib_worker_threads[cpu].dpdk_lcore_id;
368       vec_validate(xd->cpu_socket_id_by_queue, q);
369       xd->cpu_socket_id_by_queue[q] = rte_lcore_to_socket_id(lcore);
370
371       vec_add2(dm->devices_by_cpu[cpu], dq, 1);
372       dq->device = xd->device_index;
373       dq->queue_id = q;
374       DBG_SOCK("CPU for %d = %d. QID: %d", *hw_if_index, cpu, dq->queue_id);
375
376       // start polling if it was not started yet (because of no phys ifaces)
377       if (tm->n_vlib_mains == 1 && dpdk_input_node.state != VLIB_NODE_STATE_POLLING)
378         vlib_node_set_state (vm, dpdk_input_node.index, VLIB_NODE_STATE_POLLING);
379
380       if (tm->n_vlib_mains > 1)
381         vlib_node_set_state (vlib_mains[cpu], dpdk_input_node.index,
382                              VLIB_NODE_STATE_POLLING);
383       next_cpu++;
384   }
385
386   vlib_worker_thread_barrier_release (vm);
387   return 0;
388 }
389
390 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
391 static long get_huge_page_size(int fd)
392 {
393   struct statfs s;
394   fstatfs(fd, &s);
395   return s.f_bsize;
396 }
397 #endif
398
399 static clib_error_t *
400 dpdk_vhost_user_set_protocol_features(u32 hw_if_index, u64 prot_features)
401 {
402   dpdk_device_t * xd;
403   xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index);
404   assert(xd);
405   xd->vu_vhost_dev.protocol_features = prot_features;
406   return 0;
407 }
408
409 static clib_error_t *
410 dpdk_vhost_user_get_features(u32 hw_if_index, u64 * features)
411 {
412   *features = rte_vhost_feature_get();
413
414 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
415 #define OFFLOAD_FEATURES ((1ULL << VIRTIO_NET_F_HOST_TSO4) | \
416                 (1ULL << VIRTIO_NET_F_HOST_TSO6) | \
417                 (1ULL << VIRTIO_NET_F_CSUM)    | \
418                 (1ULL << VIRTIO_NET_F_GUEST_CSUM) | \
419                 (1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
420                 (1ULL << VIRTIO_NET_F_GUEST_TSO6))
421
422   /* These are not suppoted as bridging/tunneling VHOST
423    * interfaces with hardware interfaces/drivers that does
424    * not support offloading breaks L4 traffic.
425    */
426   *features &= (~OFFLOAD_FEATURES);
427 #endif
428
429   DBG_SOCK("supported features: 0x%lx", *features);
430   return 0;
431 }
432
433 static clib_error_t *
434 dpdk_vhost_user_set_features(u32 hw_if_index, u64 features)
435 {
436   dpdk_device_t * xd;
437   u16 hdr_len = sizeof(struct virtio_net_hdr);
438
439
440   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
441     clib_warning("not a vhost-user interface");
442     return 0;
443   }
444
445   xd->vu_vhost_dev.features = features;
446
447   if (xd->vu_vhost_dev.features & (1 << VIRTIO_NET_F_MRG_RXBUF))
448     hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
449
450   int numqs = VIRTIO_QNUM;
451   u8 idx;
452   int prot_feature = features &
453         (1ULL << VHOST_USER_F_PROTOCOL_FEATURES);
454   numqs = xd->vu_vhost_dev.virt_qp_nb * VIRTIO_QNUM;
455   for (idx = 0; idx < numqs; idx++) {
456       xd->vu_vhost_dev.virtqueue[idx]->vhost_hlen = hdr_len;
457       /*
458        * Spec says, if F_PROTOCOL_FEATURE is not set by the
459        * slave, then all the vrings should start off as
460        * enabled. If slave negotiates F_PROTOCOL_FEATURE, then
461        * slave is responsible to enable it.
462        */
463       if (! prot_feature)
464           dpdk_vhost_user_set_vring_enable(hw_if_index, idx, 1);
465   }
466
467   return 0;
468 }
469
470 static clib_error_t *
471 dpdk_vhost_user_set_mem_table(u32 hw_if_index, vhost_user_memory_t * vum, int fd[])
472 {
473   struct virtio_memory * mem;
474   int i;
475   dpdk_device_t * xd;
476   dpdk_vu_intf_t * vui;
477
478   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
479     clib_warning("not a vhost-user interface");
480     return 0;
481   }
482
483   vui = xd->vu_intf;
484   mem = xd->vu_vhost_dev.mem;
485
486   mem->nregions = vum->nregions;
487
488   for (i=0; i < mem->nregions; i++) {
489     u64 mapped_size, mapped_address;
490
491     mem->regions[i].guest_phys_address     = vum->regions[i].guest_phys_addr;
492     mem->regions[i].guest_phys_address_end = vum->regions[i].guest_phys_addr +
493                                              vum->regions[i].memory_size;
494     mem->regions[i].memory_size            = vum->regions[i].memory_size;
495     mem->regions[i].userspace_address      = vum->regions[i].userspace_addr;
496
497     mapped_size = mem->regions[i].memory_size + vum->regions[i].mmap_offset;
498     mapped_address = pointer_to_uword(mmap(NULL, mapped_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd[i], 0));
499
500     if (uword_to_pointer(mapped_address, void*) == MAP_FAILED)
501     {
502       clib_warning("mmap error");
503       return 0;
504     }
505
506     mapped_address +=  vum->regions[i].mmap_offset;
507     vui->region_addr[i] = mapped_address;
508     vui->region_fd[i] = fd[i];
509     vui->region_offset[i] = vum->regions[i].mmap_offset;
510     mem->regions[i].address_offset = mapped_address - mem->regions[i].guest_phys_address;
511
512     DBG_SOCK("map memory region %d addr 0x%lx off 0x%lx len 0x%lx",
513       i, vui->region_addr[i], vui->region_offset[i], mapped_size);
514
515     if (vum->regions[i].guest_phys_addr == 0) {
516       mem->base_address = vum->regions[i].userspace_addr;
517       mem->mapped_address = mem->regions[i].address_offset;
518     }
519   }
520
521   disable_interface(xd);
522   return 0;
523 }
524
525 static clib_error_t *
526 dpdk_vhost_user_set_vring_num(u32 hw_if_index, u8 idx, u32 num)
527 {
528   dpdk_device_t * xd;
529   struct vhost_virtqueue *vq;
530
531   DBG_SOCK("idx %u num %u", idx, num);
532
533   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
534     clib_warning("not a vhost-user interface");
535     return 0;
536   }
537   vq = xd->vu_vhost_dev.virtqueue[idx];
538   vq->size = num;
539
540   stop_processing_packets(hw_if_index, idx);
541
542   return 0;
543 }
544
545 static clib_error_t *
546 dpdk_vhost_user_set_vring_addr(u32 hw_if_index, u8 idx, uword desc, \
547     uword used, uword avail, uword log)
548 {
549   dpdk_device_t * xd;
550   struct vhost_virtqueue *vq;
551
552   DBG_SOCK("idx %u desc 0x%lx used 0x%lx avail 0x%lx log 0x%lx",
553     idx, desc, used, avail, log);
554
555   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
556     clib_warning("not a vhost-user interface");
557     return 0;
558   }
559   vq = xd->vu_vhost_dev.virtqueue[idx];
560
561   vq->desc = (struct vring_desc *) qva_to_vva(&xd->vu_vhost_dev, desc);
562   vq->used = (struct vring_used *) qva_to_vva(&xd->vu_vhost_dev, used);
563   vq->avail = (struct vring_avail *) qva_to_vva(&xd->vu_vhost_dev, avail);
564 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
565   vq->log_guest_addr = log;
566 #endif
567
568   if (!(vq->desc && vq->used && vq->avail)) {
569     clib_warning("falied to set vring addr");
570   }
571
572   if (vq->last_used_idx != vq->used->idx) {
573     clib_warning("last_used_idx (%u) and vq->used->idx (%u) mismatches; "
574                  "some packets maybe resent for Tx and dropped for Rx",
575                  vq->last_used_idx, vq->used->idx);
576       vq->last_used_idx     = vq->used->idx;
577       vq->last_used_idx_res = vq->used->idx;
578   }
579
580   /*
581    * Inform the guest that there is no need to inform (kick) the
582    * host when it adds buffers. kick results in vmexit and will
583    * incur performance degradation.
584    *
585    * The below function sets a flag in used table. Therefore,
586    * should be initialized after initializing vq->used.
587    */
588   rte_vhost_enable_guest_notification(&xd->vu_vhost_dev, idx, 0);
589   stop_processing_packets(hw_if_index, idx);
590
591   return 0;
592 }
593
594 static clib_error_t *
595 dpdk_vhost_user_get_vring_base(u32 hw_if_index, u8 idx, u32 * num)
596 {
597   dpdk_device_t * xd;
598   struct vhost_virtqueue *vq;
599
600   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
601     clib_warning("not a vhost-user interface");
602     return 0;
603   }
604
605   vq = xd->vu_vhost_dev.virtqueue[idx];
606   *num = vq->last_used_idx;
607
608 /*
609  * From spec:
610  * Client must start ring upon receiving a kick
611  * (that is, detecting that file descriptor is readable)
612  * on the descriptor specified by VHOST_USER_SET_VRING_KICK,
613  * and stop ring upon receiving VHOST_USER_GET_VRING_BASE.
614  */
615   DBG_SOCK("Stopping vring Q %u of device %d", idx, hw_if_index);
616   dpdk_vu_intf_t *vui = xd->vu_intf;
617   vui->vrings[idx].enabled = 0; /* Reset local copy */
618   vui->vrings[idx].callfd = -1; /* Reset FD */
619   vq->enabled = 0;
620   vq->desc = NULL;
621   vq->used = NULL;
622   vq->avail = NULL;
623 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
624   vq->log_guest_addr = 0;
625 #endif
626
627   /* Check if all Qs are disabled */
628   int numqs = xd->vu_vhost_dev.virt_qp_nb * VIRTIO_QNUM;
629   for (idx = 0;  idx < numqs; idx++) {
630     if (xd->vu_vhost_dev.virtqueue[idx]->enabled)
631         break;
632   }
633
634   /* If all vrings are disabed then disable device */
635   if (idx == numqs)  {
636       DBG_SOCK("Device %d disabled", hw_if_index);
637       xd->vu_is_running = 0;
638   }
639
640   return 0;
641 }
642
643 static clib_error_t *
644 dpdk_vhost_user_set_vring_base(u32 hw_if_index, u8 idx, u32 num)
645 {
646   dpdk_device_t * xd;
647   struct vhost_virtqueue *vq;
648
649   DBG_SOCK("idx %u num %u", idx, num);
650
651   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
652     clib_warning("not a vhost-user interface");
653     return 0;
654   }
655
656   vq = xd->vu_vhost_dev.virtqueue[idx];
657   vq->last_used_idx = num;
658   vq->last_used_idx_res = num;
659
660   stop_processing_packets(hw_if_index, idx);
661
662   return 0;
663 }
664
665 static clib_error_t *
666 dpdk_vhost_user_set_vring_kick(u32 hw_if_index, u8 idx, int fd)
667 {
668   dpdk_main_t * dm = &dpdk_main;
669   dpdk_device_t * xd;
670   dpdk_vu_vring *vring;
671   struct vhost_virtqueue *vq0, *vq1, *vq;
672   int index, vu_is_running = 0;
673
674   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
675     clib_warning("not a vhost-user interface");
676     return 0;
677   }
678
679   vq = xd->vu_vhost_dev.virtqueue[idx];
680   vq->kickfd = fd;
681
682   vring = &xd->vu_intf->vrings[idx];
683   vq->enabled = (vq->desc && vq->avail && vq->used && vring->enabled) ? 1 : 0;
684
685   /*
686    * Set xd->vu_is_running if at least one pair of
687    * RX/TX queues are enabled.
688    */
689   int numqs = VIRTIO_QNUM;
690   numqs = xd->vu_vhost_dev.virt_qp_nb * VIRTIO_QNUM;
691
692   for (index = 0; index < numqs; index += 2) {
693     vq0 = xd->vu_vhost_dev.virtqueue[index]; /* RX */
694     vq1 = xd->vu_vhost_dev.virtqueue[index + 1]; /* TX */
695     if (vq0->enabled && vq1->enabled)
696     {
697         vu_is_running = 1;
698         break;
699     }
700   }
701   DBG_SOCK("SET_VRING_KICK - idx %d, running %d, fd: %d",
702     idx, vu_is_running, fd);
703
704   xd->vu_is_running = vu_is_running;
705   if (xd->vu_is_running && xd->admin_up) {
706     vnet_hw_interface_set_flags (dm->vnet_main,
707       xd->vlib_hw_if_index, VNET_HW_INTERFACE_FLAG_LINK_UP |
708       ETH_LINK_FULL_DUPLEX );
709   }
710
711   return 0;
712 }
713
714 static int
715 dpdk_vhost_user_set_vring_enable(u32 hw_if_index, u8 idx, int enable)
716 {
717   dpdk_device_t * xd;
718   struct vhost_virtqueue *vq;
719   dpdk_vu_intf_t *vui;
720
721   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
722     clib_warning("not a vhost-user interface");
723     return 0;
724   }
725
726   vui = xd->vu_intf;
727   /*
728    * Guest vhost driver wrongly enables queue before
729    * setting the vring address. Therefore, save a
730    * local copy. Reflect it in vq structure if addresses
731    * are set. If not, vq will be enabled when vring
732    * is kicked.
733    */
734   vui->vrings[idx].enabled = enable; /* Save local copy */
735
736   int numqs = xd->vu_vhost_dev.virt_qp_nb * VIRTIO_QNUM;
737   while (numqs--) {
738     if (! vui->vrings[numqs].enabled)
739         break;
740   }
741
742   if (numqs == -1) /* All Qs are enabled */
743     xd->need_txlock = 0;
744   else
745     xd->need_txlock = 1;
746
747   vq = xd->vu_vhost_dev.virtqueue[idx];
748   if (vq->desc && vq->avail && vq->used)
749     xd->vu_vhost_dev.virtqueue[idx]->enabled = enable;
750
751   return 0;
752 }
753
754 static clib_error_t * dpdk_vhost_user_callfd_read_ready (unix_file_t * uf)
755 {
756   __attribute__((unused)) int n;
757   u8 buff[8];
758   n = read(uf->file_descriptor, ((char*)&buff), 8);
759   return 0;
760 }
761
762 static clib_error_t *
763 dpdk_vhost_user_set_vring_call(u32 hw_if_index, u8 idx, int fd)
764 {
765   dpdk_device_t * xd;
766   struct vhost_virtqueue *vq;
767   unix_file_t template = {0};
768
769   DBG_SOCK("SET_VRING_CALL - idx %d, fd %d", idx, fd);
770
771   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
772     clib_warning("not a vhost-user interface");
773     return 0;
774   }
775
776   dpdk_vu_intf_t *vui = xd->vu_intf;
777
778   /* if there is old fd, delete it */
779   if (vui->vrings[idx].callfd > 0) {
780     unix_file_t * uf = pool_elt_at_index (unix_main.file_pool,
781       vui->vrings[idx].callfd_idx);
782     unix_file_del (&unix_main, uf);
783   }
784   vui->vrings[idx].callfd = fd;
785   template.read_function = dpdk_vhost_user_callfd_read_ready;
786   template.file_descriptor = fd;
787   vui->vrings[idx].callfd_idx = unix_file_add (&unix_main, &template);
788
789   vq = xd->vu_vhost_dev.virtqueue[idx];
790   vq->callfd = -1; /* We use locally saved vring->callfd; */
791
792   return 0;
793 }
794
795 u8
796 dpdk_vhost_user_want_interrupt(dpdk_device_t *xd, int idx)
797 {
798     dpdk_vu_intf_t *vui = xd->vu_intf;
799     ASSERT(vui != NULL);
800
801     if (PREDICT_FALSE(vui->num_vrings <= 0))
802         return 0;
803
804     dpdk_vu_vring *vring = &(vui->vrings[idx]);
805     struct vhost_virtqueue *vq = xd->vu_vhost_dev.virtqueue[idx];
806
807     /* return if vm is interested in interrupts */
808     return (vring->callfd > 0) && !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT);
809 }
810
811 void
812 dpdk_vhost_user_send_interrupt(vlib_main_t * vm, dpdk_device_t * xd, int idx)
813 {
814     dpdk_main_t * dm = &dpdk_main;
815     dpdk_vu_intf_t *vui = xd->vu_intf;
816     ASSERT(vui != NULL);
817
818     if (PREDICT_FALSE(vui->num_vrings <= 0))
819         return;
820
821     dpdk_vu_vring *vring = &(vui->vrings[idx]);
822     struct vhost_virtqueue *vq = xd->vu_vhost_dev.virtqueue[idx];
823
824     /* if vm is interested in interrupts */
825     if((vring->callfd > 0) && !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
826         eventfd_write(vring->callfd, (eventfd_t)1);
827         vring->n_since_last_int = 0;
828         vring->int_deadline = vlib_time_now(vm) + dm->conf->vhost_coalesce_time;
829     }
830 }
831
832 /*
833  * vhost-user interface management functions 
834  */
835
836 // initialize vui with specified attributes
837 static void 
838 dpdk_vhost_user_vui_init(vnet_main_t * vnm,
839                          dpdk_device_t *xd, int sockfd,
840                          const char * sock_filename,
841                          u8 is_server, u64 feature_mask,
842                          u32 * sw_if_index)
843 {
844   dpdk_vu_intf_t *vui = xd->vu_intf;
845   memset(vui, 0, sizeof(*vui));
846
847   vui->unix_fd = sockfd;
848   vui->num_vrings = xd->vu_vhost_dev.virt_qp_nb * VIRTIO_QNUM;
849   DBG_SOCK("dpdk_vhost_user_vui_init VRINGS: %d", vui->num_vrings);
850   vui->sock_is_server = is_server;
851   strncpy(vui->sock_filename, sock_filename, ARRAY_LEN(vui->sock_filename)-1);
852   vui->sock_errno = 0;
853   vui->is_up = 0;
854   vui->feature_mask = feature_mask;
855   vui->active = 1;
856   vui->unix_file_index = ~0;
857
858   vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,  0);
859
860   if (sw_if_index)
861       *sw_if_index = xd->vlib_sw_if_index;
862 }
863
864 // register vui and start polling on it
865 static void 
866 dpdk_vhost_user_vui_register(vlib_main_t * vm, dpdk_device_t *xd)
867 {
868   dpdk_main_t * dm = &dpdk_main;
869   dpdk_vu_intf_t *vui = xd->vu_intf;
870
871   hash_set (dm->vu_sw_if_index_by_listener_fd, vui->unix_fd,
872             xd->vlib_sw_if_index);
873 }
874
875 static void dpdk_unmap_all_mem_regions(dpdk_device_t * xd)
876 {
877   int i, r;
878   dpdk_vu_intf_t *vui = xd->vu_intf;
879   struct virtio_memory * mem = xd->vu_vhost_dev.mem;
880
881   for (i=0; i<mem->nregions; i++) {
882     if (vui->region_addr[i] != -1) {
883
884       long page_sz = get_huge_page_size(vui->region_fd[i]);
885
886       ssize_t map_sz = RTE_ALIGN_CEIL(mem->regions[i].memory_size +
887         vui->region_offset[i], page_sz);
888
889       r = munmap((void *)(vui->region_addr[i] - vui->region_offset[i]), map_sz);
890
891       DBG_SOCK("unmap memory region %d addr 0x%lx off 0x%lx len 0x%lx page_sz 0x%x",
892         i, vui->region_addr[i], vui->region_offset[i], map_sz, page_sz);
893
894       vui->region_addr[i]= -1;
895
896       if (r == -1) {
897         clib_unix_warning("failed to unmap memory region");
898       }
899       close(vui->region_fd[i]);
900     }
901   }
902   mem->nregions = 0;
903 }
904
905 static inline void
906 dpdk_vhost_user_if_disconnect(dpdk_device_t * xd)
907 {
908     dpdk_vu_intf_t *vui = xd->vu_intf;
909     vnet_main_t * vnm = vnet_get_main();
910     dpdk_main_t * dm = &dpdk_main;
911     struct vhost_virtqueue *vq;
912     int q;
913
914     xd->admin_up = 0;
915     vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,  0);
916
917     if (vui->unix_file_index != ~0) {
918         unix_file_del (&unix_main, unix_main.file_pool + vui->unix_file_index);
919         vui->unix_file_index = ~0;
920     }
921
922     hash_unset(dm->vu_sw_if_index_by_sock_fd, vui->unix_fd);
923     hash_unset(dm->vu_sw_if_index_by_listener_fd, vui->unix_fd);
924     close(vui->unix_fd);
925     vui->unix_fd = -1;
926     vui->is_up = 0;
927
928     for (q = 0; q < vui->num_vrings; q++) {
929         vq = xd->vu_vhost_dev.virtqueue[q];
930         vui->vrings[q].enabled = 0; /* Reset local copy */
931         vui->vrings[q].callfd = -1; /* Reset FD */
932         vq->enabled = 0;
933 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
934         vq->log_guest_addr = 0;
935 #endif
936         vq->desc = NULL;
937         vq->used = NULL;
938         vq->avail = NULL;
939     }
940     xd->vu_is_running = 0;
941
942     dpdk_unmap_all_mem_regions(xd);
943     DBG_SOCK("interface ifindex %d disconnected", xd->vlib_sw_if_index);
944 }
945
946 static clib_error_t * dpdk_vhost_user_socket_read (unix_file_t * uf)
947 {
948   int n;
949   int fd, number_of_fds = 0;
950   int fds[VHOST_MEMORY_MAX_NREGIONS];
951   vhost_user_msg_t msg;
952   struct msghdr mh;
953   struct iovec iov[1];
954   dpdk_main_t * dm = &dpdk_main;
955   dpdk_device_t *xd;
956   dpdk_vu_intf_t *vui;
957   struct cmsghdr *cmsg;
958   uword * p;
959   u8 q;
960   vnet_main_t * vnm = vnet_get_main();
961
962   p = hash_get (dm->vu_sw_if_index_by_sock_fd, uf->file_descriptor);
963   if (p == 0) {
964       DBG_SOCK ("FD %d doesn't belong to any interface",
965                     uf->file_descriptor);
966       return 0;
967     }
968   else
969       xd = dpdk_vhost_user_device_from_sw_if_index(p[0]);
970
971   ASSERT(xd != NULL);
972   vui = xd->vu_intf;
973
974   char control[CMSG_SPACE(VHOST_MEMORY_MAX_NREGIONS * sizeof(int))];
975
976   memset(&mh, 0, sizeof(mh));
977   memset(control, 0, sizeof(control));
978
979   /* set the payload */
980   iov[0].iov_base = (void *) &msg;
981   iov[0].iov_len = VHOST_USER_MSG_HDR_SZ;
982
983   mh.msg_iov = iov;
984   mh.msg_iovlen = 1;
985   mh.msg_control = control;
986   mh.msg_controllen = sizeof(control);
987
988   n = recvmsg(uf->file_descriptor, &mh, 0);
989
990   if (n != VHOST_USER_MSG_HDR_SZ)
991     goto close_socket;
992
993   if (mh.msg_flags & MSG_CTRUNC) {
994     goto close_socket;
995   }
996
997   cmsg = CMSG_FIRSTHDR(&mh);
998
999   if (cmsg && (cmsg->cmsg_len > 0) && (cmsg->cmsg_level == SOL_SOCKET) &&
1000       (cmsg->cmsg_type == SCM_RIGHTS) &&
1001       (cmsg->cmsg_len - CMSG_LEN(0) <= VHOST_MEMORY_MAX_NREGIONS * sizeof(int))) {
1002         number_of_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1003         clib_memcpy(fds, CMSG_DATA(cmsg), number_of_fds * sizeof(int));
1004   }
1005
1006   /* version 1, no reply bit set*/
1007   if ((msg.flags & 7) != 1) {
1008     DBG_SOCK("malformed message received. closing socket");
1009     goto close_socket;
1010   }
1011
1012   {
1013       int rv __attribute__((unused));
1014       /* $$$$ pay attention to rv */
1015       rv = read(uf->file_descriptor, ((char*)&msg) + n, msg.size);
1016   }
1017
1018   DBG_SOCK("VPP VHOST message %s", vhost_message_str[msg.request]);
1019   switch (msg.request) {
1020     case VHOST_USER_GET_FEATURES:
1021       DBG_SOCK("if %d msg VHOST_USER_GET_FEATURES",
1022         xd->vlib_hw_if_index);
1023
1024       msg.flags |= VHOST_USER_REPLY_MASK;
1025
1026       dpdk_vhost_user_get_features(xd->vlib_hw_if_index, &msg.u64);
1027       msg.u64 &= vui->feature_mask;
1028       msg.size = sizeof(msg.u64);
1029       break;
1030
1031     case VHOST_USER_SET_FEATURES:
1032       DBG_SOCK("if %d msg VHOST_USER_SET_FEATURES features 0x%016lx",
1033         xd->vlib_hw_if_index, msg.u64);
1034
1035       dpdk_vhost_user_set_features(xd->vlib_hw_if_index, msg.u64);
1036       break;
1037
1038     case VHOST_USER_SET_MEM_TABLE:
1039       DBG_SOCK("if %d msg VHOST_USER_SET_MEM_TABLE nregions %d",
1040         xd->vlib_hw_if_index, msg.memory.nregions);
1041
1042       if ((msg.memory.nregions < 1) ||
1043           (msg.memory.nregions > VHOST_MEMORY_MAX_NREGIONS)) {
1044
1045         DBG_SOCK("number of mem regions must be between 1 and %i",
1046           VHOST_MEMORY_MAX_NREGIONS);
1047
1048         goto close_socket;
1049       }
1050
1051       if (msg.memory.nregions != number_of_fds) {
1052         DBG_SOCK("each memory region must have FD");
1053         goto close_socket;
1054       }
1055
1056       dpdk_vhost_user_set_mem_table(xd->vlib_hw_if_index, &msg.memory, fds);
1057       break;
1058
1059     case VHOST_USER_SET_VRING_NUM:
1060       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_NUM idx %d num %d",
1061         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1062
1063       if ((msg.state.num > 32768) || /* maximum ring size is 32768 */
1064           (msg.state.num == 0) ||    /* it cannot be zero */
1065           (msg.state.num % 2))       /* must be power of 2 */
1066         goto close_socket;
1067
1068       dpdk_vhost_user_set_vring_num(xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1069       break;
1070
1071     case VHOST_USER_SET_VRING_ADDR:
1072       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_ADDR idx %d",
1073         xd->vlib_hw_if_index, msg.state.index);
1074
1075       dpdk_vhost_user_set_vring_addr(xd->vlib_hw_if_index, msg.state.index,
1076                                     msg.addr.desc_user_addr,
1077                                     msg.addr.used_user_addr,
1078                                     msg.addr.avail_user_addr,
1079                                     msg.addr.log_guest_addr);
1080       break;
1081
1082     case VHOST_USER_SET_OWNER:
1083       DBG_SOCK("if %d msg VHOST_USER_SET_OWNER",
1084         xd->vlib_hw_if_index);
1085       break;
1086
1087     case VHOST_USER_RESET_OWNER:
1088       DBG_SOCK("if %d msg VHOST_USER_RESET_OWNER",
1089         xd->vlib_hw_if_index);
1090       break;
1091
1092     case VHOST_USER_SET_VRING_CALL:
1093       q = (u8) (msg.u64 & 0xFF);
1094
1095       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_CALL u64 %lx, idx: %d",
1096         xd->vlib_hw_if_index, msg.u64, q);
1097
1098       if (!(msg.u64 & 0x100))
1099       {
1100         if (number_of_fds != 1)
1101           goto close_socket;
1102         fd = fds[0];
1103       } else {
1104         fd = -1;
1105       }
1106       dpdk_vhost_user_set_vring_call(xd->vlib_hw_if_index, q, fd);
1107
1108       break;
1109
1110     case VHOST_USER_SET_VRING_KICK:
1111
1112       q = (u8) (msg.u64 & 0xFF);
1113
1114       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_KICK u64 %lx, idx: %d",
1115         xd->vlib_hw_if_index, msg.u64, q);
1116
1117       if (!(msg.u64 & 0x100))
1118       {
1119         if (number_of_fds != 1)
1120           goto close_socket;
1121
1122         vui->vrings[q].kickfd = fds[0];
1123       }
1124       else
1125         vui->vrings[q].kickfd = -1;
1126
1127       dpdk_vhost_user_set_vring_kick(xd->vlib_hw_if_index, q, vui->vrings[q].kickfd);
1128       break;
1129
1130     case VHOST_USER_SET_VRING_ERR:
1131
1132       q = (u8) (msg.u64 & 0xFF);
1133
1134       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_ERR u64 %lx, idx: %d",
1135         xd->vlib_hw_if_index, msg.u64, q);
1136
1137       if (!(msg.u64 & 0x100))
1138       {
1139         if (number_of_fds != 1)
1140           goto close_socket;
1141
1142         fd = fds[0];
1143       }
1144       else
1145         fd = -1;
1146
1147       vui->vrings[q].errfd = fd;
1148       break;
1149
1150     case VHOST_USER_SET_VRING_BASE:
1151       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_BASE idx %d num %d",
1152         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1153
1154       dpdk_vhost_user_set_vring_base(xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1155       break;
1156
1157     case VHOST_USER_GET_VRING_BASE:
1158       DBG_SOCK("if %d msg VHOST_USER_GET_VRING_BASE idx %d num %d",
1159         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1160
1161       msg.flags |= VHOST_USER_REPLY_MASK;
1162       msg.size = sizeof(msg.state);
1163
1164       dpdk_vhost_user_get_vring_base(xd->vlib_hw_if_index, msg.state.index, &msg.state.num);
1165       break;
1166
1167     case VHOST_USER_NONE:
1168       DBG_SOCK("if %d msg VHOST_USER_NONE",
1169         xd->vlib_hw_if_index);
1170       break;
1171
1172     case VHOST_USER_SET_LOG_BASE:
1173 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
1174       DBG_SOCK("if %d msg VHOST_USER_SET_LOG_BASE",
1175         xd->vlib_hw_if_index);
1176
1177       if (msg.size != sizeof(msg.log)) {
1178         DBG_SOCK("invalid msg size for VHOST_USER_SET_LOG_BASE: %u instead of %lu",
1179                  msg.size, sizeof(msg.log));
1180         goto close_socket;
1181       }
1182
1183       if (!(xd->vu_vhost_dev.protocol_features & (1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD))) {
1184         DBG_SOCK("VHOST_USER_PROTOCOL_F_LOG_SHMFD not set but VHOST_USER_SET_LOG_BASE received");
1185         goto close_socket;
1186       }
1187
1188       fd = fds[0];
1189       /* align size to 2M page */
1190       long page_sz = get_huge_page_size(fd);
1191       ssize_t map_sz = RTE_ALIGN_CEIL(msg.log.size + msg.log.offset, page_sz);
1192
1193       void *addr = mmap(0, map_sz, PROT_READ | PROT_WRITE,
1194                                 MAP_SHARED, fd, 0);
1195
1196       DBG_SOCK("map log region addr 0 len 0x%lx off 0x%lx fd %d mapped %p",
1197                map_sz, msg.log.offset, fd, addr);
1198
1199       if (addr == MAP_FAILED) {
1200         clib_warning("failed to map memory. errno is %d", errno);
1201         goto close_socket;
1202       }
1203
1204       xd->vu_vhost_dev.log_base += pointer_to_uword(addr) + msg.log.offset;
1205       xd->vu_vhost_dev.log_size = msg.log.size;
1206       msg.flags |= VHOST_USER_REPLY_MASK;
1207       msg.size = sizeof(msg.u64);
1208 #else
1209       DBG_SOCK("if %d msg VHOST_USER_SET_LOG_BASE Not-Implemented",
1210         xd->vlib_hw_if_index);
1211 #endif
1212       break;
1213
1214     case VHOST_USER_SET_LOG_FD:
1215       DBG_SOCK("if %d msg VHOST_USER_SET_LOG_FD",
1216         xd->vlib_hw_if_index);
1217       break;
1218
1219     case VHOST_USER_GET_PROTOCOL_FEATURES:
1220       DBG_SOCK("if %d msg VHOST_USER_GET_PROTOCOL_FEATURES",
1221         xd->vlib_hw_if_index);
1222
1223       msg.flags |= VHOST_USER_REPLY_MASK;
1224       msg.u64 = VHOST_USER_PROTOCOL_FEATURES;
1225       DBG_SOCK("VHOST_USER_PROTOCOL_FEATURES: %llx", VHOST_USER_PROTOCOL_FEATURES);
1226       msg.size = sizeof(msg.u64);
1227       break;
1228
1229     case VHOST_USER_SET_PROTOCOL_FEATURES:
1230       DBG_SOCK("if %d msg VHOST_USER_SET_PROTOCOL_FEATURES",
1231         xd->vlib_hw_if_index);
1232
1233       DBG_SOCK("VHOST_USER_SET_PROTOCOL_FEATURES: 0x%lx",
1234         msg.u64);
1235       dpdk_vhost_user_set_protocol_features(xd->vlib_hw_if_index,
1236         msg.u64);
1237       break;
1238
1239     case VHOST_USER_SET_VRING_ENABLE:
1240       DBG_SOCK("%d VPP VHOST_USER_SET_VRING_ENABLE IDX: %d, Enable: %d",
1241         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1242       dpdk_vhost_user_set_vring_enable
1243         (xd->vlib_hw_if_index, msg.state.index, msg.state.num);
1244       break;
1245
1246     case VHOST_USER_GET_QUEUE_NUM:
1247       DBG_SOCK("if %d msg VHOST_USER_GET_QUEUE_NUM:",
1248         xd->vlib_hw_if_index);
1249
1250       msg.flags |= VHOST_USER_REPLY_MASK;
1251       msg.u64 = xd->vu_vhost_dev.virt_qp_nb;
1252       msg.size = sizeof(msg.u64);
1253       break;
1254
1255     default:
1256       DBG_SOCK("unknown vhost-user message %d received. closing socket",
1257         msg.request);
1258       goto close_socket;
1259   }
1260
1261   /* if we have pointers to descriptor table, go up*/
1262   if (!vui->is_up &&
1263       xd->vu_vhost_dev.virtqueue[VHOST_NET_VRING_IDX_TX]->desc &&
1264       xd->vu_vhost_dev.virtqueue[VHOST_NET_VRING_IDX_RX]->desc) {
1265
1266       DBG_SOCK("interface %d connected", xd->vlib_sw_if_index);
1267
1268       vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,  VNET_HW_INTERFACE_FLAG_LINK_UP);
1269       vui->is_up = 1;
1270       xd->admin_up = 1;
1271   }
1272
1273   /* if we need to reply */
1274   if (msg.flags & VHOST_USER_REPLY_MASK)
1275   {
1276       n = send(uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
1277       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
1278         goto close_socket;
1279   }
1280
1281   return 0;
1282
1283 close_socket:
1284   DBG_SOCK("error: close_socket");
1285   dpdk_vhost_user_if_disconnect(xd);
1286   return 0;
1287 }
1288
1289 static clib_error_t * dpdk_vhost_user_socket_error (unix_file_t * uf)
1290 {
1291   dpdk_main_t * dm = &dpdk_main;
1292   dpdk_device_t *xd;
1293   uword * p;
1294
1295   p = hash_get (dm->vu_sw_if_index_by_sock_fd, uf->file_descriptor);
1296   if (p == 0) {
1297       DBG_SOCK ("FD %d doesn't belong to any interface",
1298                     uf->file_descriptor);
1299       return 0;
1300     }
1301   else
1302       xd = dpdk_vhost_user_device_from_sw_if_index(p[0]);
1303
1304   dpdk_vhost_user_if_disconnect(xd);
1305   return 0;
1306 }
1307
1308 static clib_error_t * dpdk_vhost_user_socksvr_accept_ready (unix_file_t * uf)
1309 {
1310   int client_fd, client_len;
1311   struct sockaddr_un client;
1312   unix_file_t template = {0};
1313   dpdk_main_t * dm = &dpdk_main;
1314   dpdk_device_t * xd = NULL;
1315   dpdk_vu_intf_t * vui;
1316   uword * p;
1317
1318   p = hash_get (dm->vu_sw_if_index_by_listener_fd,
1319                 uf->file_descriptor);
1320   if (p == 0) {
1321       DBG_SOCK ("fd %d doesn't belong to any interface",
1322                     uf->file_descriptor);
1323       return 0;
1324     }
1325
1326   xd = dpdk_vhost_user_device_from_sw_if_index(p[0]);
1327   ASSERT(xd != NULL);
1328   vui = xd->vu_intf;
1329
1330   client_len = sizeof(client);
1331   client_fd = accept (uf->file_descriptor,
1332                       (struct sockaddr *)&client,
1333                       (socklen_t *)&client_len);
1334
1335   if (client_fd < 0)
1336       return clib_error_return_unix (0, "accept");
1337
1338   template.read_function = dpdk_vhost_user_socket_read;
1339   template.error_function = dpdk_vhost_user_socket_error;
1340   template.file_descriptor = client_fd;
1341   vui->unix_file_index = unix_file_add (&unix_main, &template);
1342
1343   vui->client_fd = client_fd;
1344   hash_set (dm->vu_sw_if_index_by_sock_fd, vui->client_fd,
1345             xd->vlib_sw_if_index);
1346
1347   return 0;
1348 }
1349
1350 // init server socket on specified sock_filename
1351 static int dpdk_vhost_user_init_server_sock(const char * sock_filename, int *sockfd)
1352 {
1353   int rv = 0;
1354   struct sockaddr_un un = {};
1355   int fd;
1356   /* create listening socket */
1357   fd = socket(AF_UNIX, SOCK_STREAM, 0);
1358
1359   if (fd < 0) {
1360     return VNET_API_ERROR_SYSCALL_ERROR_1;
1361   }
1362
1363   un.sun_family = AF_UNIX;
1364   strcpy((char *) un.sun_path, (char *) sock_filename);
1365
1366   /* remove if exists */
1367   unlink( (char *) sock_filename);
1368
1369   if (bind(fd, (struct sockaddr *) &un, sizeof(un)) == -1) {
1370     rv = VNET_API_ERROR_SYSCALL_ERROR_2;
1371     goto error;
1372   }
1373
1374   if (listen(fd, 1) == -1) {
1375     rv = VNET_API_ERROR_SYSCALL_ERROR_3;
1376     goto error;
1377   }
1378
1379   unix_file_t template = {0};
1380   template.read_function = dpdk_vhost_user_socksvr_accept_ready;
1381   template.file_descriptor = fd;
1382   unix_file_add (&unix_main, &template);
1383   *sockfd = fd;
1384   return rv;
1385
1386 error:
1387   close(fd);
1388   return rv;
1389 }
1390
1391 /*
1392  * vhost-user interface control functions used from vpe api
1393  */
1394
1395 int dpdk_vhost_user_create_if(vnet_main_t * vnm, vlib_main_t * vm,
1396                               const char * sock_filename,
1397                               u8 is_server,
1398                               u32 * sw_if_index,
1399                               u64 feature_mask,
1400                               u8 renumber, u32 custom_dev_instance,
1401                               u8 *hwaddr)
1402 {
1403   dpdk_main_t * dm = &dpdk_main;
1404   dpdk_device_t *xd;
1405   u32 hw_if_idx = ~0;
1406   int sockfd = -1;
1407   int rv = 0;
1408
1409   // using virtio vhost user?
1410   if (dm->conf->use_virtio_vhost) {
1411       return vhost_user_create_if(vnm, vm, sock_filename, is_server,
1412               sw_if_index, feature_mask, renumber, custom_dev_instance, hwaddr);
1413   }
1414
1415   if (is_server) {
1416     if ((rv = dpdk_vhost_user_init_server_sock (sock_filename, &sockfd)) != 0) {
1417         return rv;
1418     }
1419   }
1420
1421   if (renumber) {
1422       // set next vhost-user if id if custom one is higher or equal
1423       if (custom_dev_instance >= dm->next_vu_if_id)
1424           dm->next_vu_if_id = custom_dev_instance + 1;
1425
1426     dpdk_create_vhost_user_if_internal(&hw_if_idx, custom_dev_instance, hwaddr);
1427   } else 
1428     dpdk_create_vhost_user_if_internal(&hw_if_idx, (u32)~0, hwaddr);
1429   DBG_SOCK("dpdk vhost-user interface created hw_if_index %d", hw_if_idx);
1430
1431   xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_idx);
1432   ASSERT(xd != NULL);
1433
1434   dpdk_vhost_user_vui_init (vnm, xd, sockfd, sock_filename, is_server,
1435                             feature_mask, sw_if_index);
1436
1437   dpdk_vhost_user_vui_register (vm, xd);
1438   return rv;
1439 }
1440
1441 int dpdk_vhost_user_modify_if(vnet_main_t * vnm, vlib_main_t * vm,
1442                          const char * sock_filename,
1443                          u8 is_server,
1444                          u32 sw_if_index,
1445                          u64 feature_mask,
1446                          u8 renumber, u32 custom_dev_instance)
1447 {
1448   dpdk_main_t * dm = &dpdk_main;
1449   dpdk_device_t * xd;
1450   dpdk_vu_intf_t * vui = NULL;
1451   u32 sw_if_idx = ~0;
1452   int sockfd = -1;
1453   int rv = 0;
1454
1455   // using virtio vhost user?
1456   if (dm->conf->use_virtio_vhost) {
1457       return vhost_user_modify_if(vnm, vm, sock_filename, is_server,
1458               sw_if_index, feature_mask, renumber, custom_dev_instance);
1459   }
1460
1461   xd = dpdk_vhost_user_device_from_sw_if_index(sw_if_index);
1462
1463   if (xd == NULL)
1464     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
1465
1466   vui = xd->vu_intf;
1467
1468   // interface is inactive
1469   vui->active = 0;
1470   // disconnect interface sockets
1471   dpdk_vhost_user_if_disconnect(xd);
1472
1473   if (is_server) {
1474       if ((rv = dpdk_vhost_user_init_server_sock (sock_filename, &sockfd)) != 0) {
1475           return rv;
1476       }
1477   }
1478
1479   dpdk_vhost_user_vui_init (vnm, xd, sockfd, sock_filename, is_server,
1480                        feature_mask, &sw_if_idx);
1481
1482   if (renumber) {
1483     vnet_interface_name_renumber (sw_if_idx, custom_dev_instance);
1484   }
1485
1486   dpdk_vhost_user_vui_register (vm, xd);
1487
1488   return rv;
1489 }
1490
1491 int dpdk_vhost_user_delete_if(vnet_main_t * vnm, vlib_main_t * vm,
1492                          u32 sw_if_index)
1493 {
1494   dpdk_main_t * dm = &dpdk_main;
1495   dpdk_device_t * xd = NULL;
1496   dpdk_vu_intf_t * vui;
1497   int rv = 0;
1498
1499   // using virtio vhost user?
1500   if (dm->conf->use_virtio_vhost) {
1501       return vhost_user_delete_if(vnm, vm, sw_if_index);
1502   }
1503
1504   xd = dpdk_vhost_user_device_from_sw_if_index(sw_if_index);
1505
1506   if (xd == NULL)
1507     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
1508
1509   vui = xd->vu_intf;
1510
1511   // interface is inactive
1512   vui->active = 0;
1513   // disconnect interface sockets
1514   dpdk_vhost_user_if_disconnect(xd);
1515   // add to inactive interface list
1516   vec_add1 (dm->vu_inactive_interfaces_device_index, xd->device_index);
1517
1518   ethernet_delete_interface (vnm, xd->vlib_hw_if_index);
1519   DBG_SOCK ("deleted (deactivated) vhost-user interface sw_if_index %d", sw_if_index);
1520
1521   return rv;
1522 }
1523
1524 int dpdk_vhost_user_dump_ifs(vnet_main_t * vnm, vlib_main_t * vm, vhost_user_intf_details_t **out_vuids)
1525 {
1526     int rv = 0;
1527     dpdk_main_t * dm = &dpdk_main;
1528     dpdk_device_t * xd;
1529     dpdk_vu_intf_t * vui;
1530     struct virtio_net * vhost_dev;
1531     vhost_user_intf_details_t * r_vuids = NULL;
1532     vhost_user_intf_details_t * vuid = NULL;
1533     u32 * hw_if_indices = 0;
1534     vnet_hw_interface_t * hi;
1535     u8 *s = NULL;
1536     int i;
1537
1538     if (!out_vuids)
1539         return -1;
1540
1541     // using virtio vhost user?
1542     if (dm->conf->use_virtio_vhost) {
1543         return vhost_user_dump_ifs(vnm, vm, out_vuids);
1544     }
1545
1546     vec_foreach (xd, dm->devices) {
1547       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER &&
1548               xd->vu_intf->active)
1549         vec_add1(hw_if_indices, xd->vlib_hw_if_index);
1550     }
1551
1552     for (i = 0; i < vec_len (hw_if_indices); i++) {
1553       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
1554       xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_indices[i]);
1555       if (!xd) {
1556           clib_warning("invalid vhost-user interface hw_if_index %d", hw_if_indices[i]);
1557           continue;
1558       }
1559
1560       vui = xd->vu_intf;
1561       ASSERT(vui != NULL);
1562       vhost_dev = &xd->vu_vhost_dev;
1563       u32 virtio_net_hdr_sz = (vui->num_vrings > 0 ?
1564             vhost_dev->virtqueue[0]->vhost_hlen : 0);
1565
1566       vec_add2(r_vuids, vuid, 1);
1567       vuid->sw_if_index = xd->vlib_sw_if_index;
1568       vuid->virtio_net_hdr_sz = virtio_net_hdr_sz;
1569       vuid->features = vhost_dev->features;
1570       vuid->is_server = vui->sock_is_server;
1571       vuid->num_regions = (vhost_dev->mem != NULL ? vhost_dev->mem->nregions : 0);
1572       vuid->sock_errno = vui->sock_errno;
1573       strncpy((char *)vuid->sock_filename, (char *)vui->sock_filename,
1574               ARRAY_LEN(vuid->sock_filename)-1);
1575
1576       s = format (s, "%v%c", hi->name, 0);
1577
1578       strncpy((char *)vuid->if_name, (char *)s,
1579               ARRAY_LEN(vuid->if_name)-1);
1580       _vec_len(s) = 0;
1581     }
1582
1583     vec_free (s);
1584     vec_free (hw_if_indices);
1585
1586     *out_vuids = r_vuids;
1587
1588     return rv;
1589 }
1590
1591 /*
1592  * Processing functions called from dpdk process fn
1593  */
1594
1595 typedef struct {
1596     struct sockaddr_un sun;
1597     int sockfd;
1598     unix_file_t template;
1599     uword *event_data;
1600 } dpdk_vu_process_state;
1601
1602 void dpdk_vhost_user_process_init (void **ctx)
1603 {
1604     dpdk_vu_process_state *state = clib_mem_alloc (sizeof(dpdk_vu_process_state));
1605     memset(state, 0, sizeof(*state));
1606     state->sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
1607     state->sun.sun_family = AF_UNIX;
1608     state->template.read_function = dpdk_vhost_user_socket_read;
1609     state->template.error_function = dpdk_vhost_user_socket_error;
1610     state->event_data = 0;
1611     *ctx = state;
1612 }
1613
1614 void dpdk_vhost_user_process_cleanup (void *ctx)
1615 {
1616     clib_mem_free(ctx);
1617 }
1618
1619 uword dpdk_vhost_user_process_if (vlib_main_t *vm, dpdk_device_t *xd, void *ctx)
1620 {
1621     dpdk_main_t * dm = &dpdk_main;
1622     dpdk_vu_process_state *state = (dpdk_vu_process_state *)ctx;
1623     dpdk_vu_intf_t *vui = xd->vu_intf;
1624
1625     if (vui->sock_is_server || !vui->active)
1626         return 0;
1627
1628     if (vui->unix_fd == -1) {
1629         /* try to connect */
1630         strncpy(state->sun.sun_path,  (char *) vui->sock_filename, sizeof(state->sun.sun_path) - 1);
1631
1632         if (connect(state->sockfd, (struct sockaddr *) &(state->sun), sizeof(struct sockaddr_un)) == 0) {
1633             vui->sock_errno = 0;
1634             vui->unix_fd = state->sockfd;
1635             state->template.file_descriptor = state->sockfd;
1636             vui->unix_file_index = unix_file_add (&unix_main, &(state->template));
1637             hash_set (dm->vu_sw_if_index_by_sock_fd, state->sockfd, xd->vlib_sw_if_index);
1638
1639             state->sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
1640             if (state->sockfd < 0)
1641                 return -1;
1642         } else {
1643             vui->sock_errno = errno;
1644         }
1645     } else {
1646         /* check if socket is alive */
1647         int error = 0;
1648         socklen_t len = sizeof (error);
1649         int retval = getsockopt(vui->unix_fd, SOL_SOCKET, SO_ERROR, &error, &len);
1650
1651         if (retval)
1652             dpdk_vhost_user_if_disconnect(xd);
1653     }
1654     return 0;
1655 }
1656
1657 /*
1658  * CLI functions
1659  */
1660
1661 static clib_error_t *
1662 dpdk_vhost_user_connect_command_fn (vlib_main_t * vm,
1663                  unformat_input_t * input,
1664                  vlib_cli_command_t * cmd)
1665 {
1666   dpdk_main_t * dm = &dpdk_main;
1667   unformat_input_t _line_input, * line_input = &_line_input;
1668   u8 * sock_filename = NULL;
1669   u32 sw_if_index;
1670   u8 is_server = 0;
1671   u64 feature_mask = (u64)~0;
1672   u8 renumber = 0;
1673   u32 custom_dev_instance = ~0;
1674   u8 hwaddr[6];
1675   u8 *hw = NULL;
1676
1677   if (dm->conf->use_virtio_vhost) {
1678       return vhost_user_connect_command_fn(vm, input, cmd);
1679   }
1680
1681   /* Get a line of input. */
1682   if (! unformat_user (input, unformat_line_input, line_input))
1683     return 0;
1684
1685   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) {
1686     if (unformat (line_input, "socket %s", &sock_filename))
1687       ;
1688     else if (unformat (line_input, "server"))
1689       is_server = 1;
1690     else if (unformat (line_input, "feature-mask 0x%llx", &feature_mask))
1691       ;
1692     else if (unformat (line_input, "hwaddr %U", unformat_ethernet_address, hwaddr))
1693       hw = hwaddr;
1694     else if (unformat (line_input, "renumber %d", &custom_dev_instance)) {
1695         renumber = 1;
1696     }
1697     else
1698       return clib_error_return (0, "unknown input `%U'",
1699                                 format_unformat_error, input);
1700   }
1701   unformat_free (line_input);
1702
1703   vnet_main_t *vnm = vnet_get_main();
1704   if (sock_filename == NULL)
1705       return clib_error_return (0, "missing socket file");
1706
1707   dpdk_vhost_user_create_if(vnm, vm, (char *)sock_filename,
1708                             is_server, &sw_if_index, feature_mask,
1709                             renumber, custom_dev_instance, hw);
1710
1711   vec_free(sock_filename);
1712   vlib_cli_output(vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main(), sw_if_index);
1713   return 0;
1714 }
1715
1716 VLIB_CLI_COMMAND (dpdk_vhost_user_connect_command, static) = {
1717     .path = "create vhost-user",
1718     .short_help = "create vhost-user socket <socket-filename> [server] [feature-mask <hex>] [renumber <dev_instance>]",
1719     .function = dpdk_vhost_user_connect_command_fn,
1720 };
1721
1722 static clib_error_t *
1723 dpdk_vhost_user_delete_command_fn (vlib_main_t * vm,
1724                  unformat_input_t * input,
1725                  vlib_cli_command_t * cmd)
1726 {
1727   dpdk_main_t * dm = &dpdk_main;
1728   clib_error_t * error = 0;
1729   unformat_input_t _line_input, * line_input = &_line_input;
1730   u32 sw_if_index = ~0;
1731
1732   if (dm->conf->use_virtio_vhost) {
1733       return vhost_user_delete_command_fn(vm, input, cmd);
1734   }
1735
1736   /* Get a line of input. */
1737   if (! unformat_user (input, unformat_line_input, line_input))
1738     return 0;
1739
1740   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) {
1741     if (unformat (line_input, "sw_if_index %d", &sw_if_index))
1742       ;
1743     else
1744       return clib_error_return (0, "unknown input `%U'",
1745                                 format_unformat_error, input);
1746   }
1747   unformat_free (line_input);
1748
1749   if (sw_if_index == ~0) {
1750       error = clib_error_return (0, "invalid sw_if_index",
1751                                  format_unformat_error, input);
1752       return error;
1753   }
1754
1755   vnet_main_t *vnm = vnet_get_main();
1756
1757   dpdk_vhost_user_delete_if(vnm, vm, sw_if_index);
1758
1759   return 0;
1760 }
1761
1762 VLIB_CLI_COMMAND (dpdk_vhost_user_delete_command, static) = {
1763     .path = "delete vhost-user",
1764     .short_help = "delete vhost-user sw_if_index <nn>",
1765     .function = dpdk_vhost_user_delete_command_fn,
1766 };
1767
1768 #define foreach_dpdk_vhost_feature      \
1769  _ (VIRTIO_NET_F_MRG_RXBUF)             \
1770  _ (VIRTIO_NET_F_CTRL_VQ)               \
1771  _ (VIRTIO_NET_F_CTRL_RX)
1772
1773 static clib_error_t *
1774 show_dpdk_vhost_user_command_fn (vlib_main_t * vm,
1775                  unformat_input_t * input,
1776                  vlib_cli_command_t * cmd)
1777 {
1778   clib_error_t * error = 0;
1779   dpdk_main_t * dm = &dpdk_main;
1780   vnet_main_t * vnm = vnet_get_main();
1781   dpdk_device_t * xd;
1782   dpdk_vu_intf_t * vui;
1783   struct virtio_net * vhost_dev;
1784   u32 hw_if_index, * hw_if_indices = 0;
1785   vnet_hw_interface_t * hi;
1786   int i, j, q;
1787   int show_descr = 0;
1788   struct virtio_memory * mem;
1789   struct feat_struct { u8 bit; char *str;};
1790   struct feat_struct *feat_entry;
1791
1792   static struct feat_struct feat_array[] = {
1793 #define _(f) { .str = #f, .bit = f, },
1794   foreach_dpdk_vhost_feature
1795 #undef _
1796   { .str = NULL }
1797   };
1798
1799   if (dm->conf->use_virtio_vhost) {
1800     return show_vhost_user_command_fn(vm, input, cmd);
1801   }
1802
1803   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) {
1804     if (unformat (input, "%U", unformat_vnet_hw_interface, vnm, &hw_if_index)) {
1805       vec_add1 (hw_if_indices, hw_if_index);
1806       vlib_cli_output(vm, "add %d", hw_if_index);
1807     }
1808     else if (unformat (input, "descriptors") || unformat (input, "desc") )
1809       show_descr = 1;
1810     else {
1811       error = clib_error_return (0, "unknown input `%U'",
1812                                      format_unformat_error, input);
1813       goto done;
1814     }
1815   }
1816   if (vec_len (hw_if_indices) == 0) {
1817     vec_foreach (xd, dm->devices) {
1818       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER && xd->vu_intf->active)
1819         vec_add1(hw_if_indices, xd->vlib_hw_if_index);
1820     }
1821   }
1822
1823   vlib_cli_output (vm, "DPDK vhost-user interfaces");
1824   vlib_cli_output (vm, "Global:\n  coalesce frames %d time %e\n\n",
1825                    dm->conf->vhost_coalesce_frames, dm->conf->vhost_coalesce_time);
1826
1827   for (i = 0; i < vec_len (hw_if_indices); i++) {
1828     hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
1829
1830     if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_indices[i]))) {
1831         error = clib_error_return (0, "not dpdk vhost-user interface: '%s'",
1832                                        hi->name);
1833         goto done;
1834     }
1835     vui = xd->vu_intf;
1836     vhost_dev = &xd->vu_vhost_dev;
1837     mem = vhost_dev->mem;
1838     u32 virtio_net_hdr_sz = (vui->num_vrings > 0 ?
1839             vhost_dev->virtqueue[0]->vhost_hlen : 0);
1840
1841     vlib_cli_output (vm, "Interface: %v (ifindex %d)",
1842                          hi->name, hw_if_indices[i]);
1843
1844     vlib_cli_output (vm, "virtio_net_hdr_sz %d\n features (0x%llx): \n",
1845                          virtio_net_hdr_sz, xd->vu_vhost_dev.features);
1846
1847     feat_entry = (struct feat_struct *) &feat_array;
1848     while(feat_entry->str) {
1849       if (xd->vu_vhost_dev.features & (1 << feat_entry->bit))
1850         vlib_cli_output (vm, "   %s (%d)", feat_entry->str, feat_entry->bit);
1851       feat_entry++;
1852     }
1853
1854     vlib_cli_output (vm, "\n");
1855
1856     vlib_cli_output (vm, " socket filename %s type %s errno \"%s\"\n\n",
1857                          vui->sock_filename, vui->sock_is_server ? "server" : "client",
1858                          strerror(vui->sock_errno));
1859
1860     vlib_cli_output (vm, " Memory regions (total %d)\n", mem->nregions);
1861
1862     if (mem->nregions){
1863       vlib_cli_output(vm, " region fd    guest_phys_addr    memory_size        userspace_addr     mmap_offset        mmap_addr\n");
1864       vlib_cli_output(vm, " ====== ===== ================== ================== ================== ================== ==================\n");
1865     }
1866     for (j = 0; j < mem->nregions; j++) {
1867       vlib_cli_output(vm, "  %d     %-5d 0x%016lx 0x%016lx 0x%016lx 0x%016lx 0x%016lx\n", j,
1868         vui->region_fd[j],
1869         mem->regions[j].guest_phys_address,
1870         mem->regions[j].memory_size,
1871         mem->regions[j].userspace_address,
1872         mem->regions[j].address_offset,
1873         vui->region_addr[j]);
1874     }
1875     for (q = 0; q < vui->num_vrings; q++) {
1876       struct vhost_virtqueue *vq = vhost_dev->virtqueue[q];
1877       const char *qtype = (q & 1) ? "TX" : "RX";
1878
1879       vlib_cli_output(vm, "\n Virtqueue %d (%s)\n", q/2, qtype);
1880
1881       vlib_cli_output(vm, "  qsz %d last_used_idx %d last_used_idx_res %d\n",
1882               vq->size, vq->last_used_idx, vq->last_used_idx_res);
1883
1884       if (vq->avail && vq->used)
1885         vlib_cli_output(vm, "  avail.flags %x avail.idx %d used.flags %x used.idx %d\n",
1886           vq->avail->flags, vq->avail->idx, vq->used->flags, vq->used->idx);
1887
1888       vlib_cli_output(vm, "  kickfd %d callfd %d errfd %d enabled %d\n",
1889         vq->kickfd, vq->callfd, vui->vrings[q].errfd, vq->enabled);
1890
1891       if (show_descr && vq->enabled) {
1892         vlib_cli_output(vm, "\n  descriptor table:\n");
1893         vlib_cli_output(vm, "   id          addr         len  flags  next      user_addr\n");
1894         vlib_cli_output(vm, "  ===== ================== ===== ====== ===== ==================\n");
1895         for(j = 0; j < vq->size; j++) {
1896           vlib_cli_output(vm, "  %-5d 0x%016lx %-5d 0x%04x %-5d 0x%016lx\n",
1897             j,
1898             vq->desc[j].addr,
1899             vq->desc[j].len,
1900             vq->desc[j].flags,
1901             vq->desc[j].next,
1902             pointer_to_uword(map_guest_mem(xd, vq->desc[j].addr)));}
1903       }
1904     }
1905     vlib_cli_output (vm, "\n");
1906   }
1907 done:
1908   vec_free (hw_if_indices);
1909   return error;
1910 }
1911
1912 VLIB_CLI_COMMAND (show_vhost_user_command, static) = {
1913     .path = "show vhost-user",
1914     .short_help = "show vhost-user interface",
1915     .function = show_dpdk_vhost_user_command_fn,
1916 };
1917 #endif