Initial commit of vpp code.
[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 <sys/socket.h>
16 #include <sys/un.h>
17 #include <sys/stat.h>
18 #include <sys/vfs.h>
19
20 #include <vlib/vlib.h>
21 #include <vlib/unix/unix.h>
22
23 #include <vnet/vnet.h>
24 #include <vppinfra/vec.h>
25 #include <vppinfra/error.h>
26 #include <vppinfra/format.h>
27
28 #include <vnet/ethernet/ethernet.h>
29 #include <vnet/devices/dpdk/dpdk.h>
30
31 #include <vnet/devices/virtio/vhost-user.h>
32
33 #define VHOST_USER_DEBUG_SOCKET 0
34
35 #if VHOST_USER_DEBUG_SOCKET == 1
36 #define DBG_SOCK(args...) clib_warning(args);
37 #else
38 #define DBG_SOCK(args...)
39 #endif
40
41 /*
42  * DPDK vhost-user functions 
43  */
44
45 /* portions taken from dpdk 
46  *   BSD LICENSE
47  *
48  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
49  *   All rights reserved.
50  *
51  *   Redistribution and use in source and binary forms, with or without
52  *   modification, are permitted provided that the following conditions
53  *   are met:
54  *
55  *     * Redistributions of source code must retain the above copyright
56  *       notice, this list of conditions and the following disclaimer.
57  *     * Redistributions in binary form must reproduce the above copyright
58  *       notice, this list of conditions and the following disclaimer in
59  *       the documentation and/or other materials provided with the
60  *       distribution.
61  *     * Neither the name of Intel Corporation nor the names of its
62  *       contributors may be used to endorse or promote products derived
63  *       from this software without specific prior written permission.
64  *
65  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
66  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
67  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
68  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
69  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
70  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
71  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
72  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
73  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
74  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
75  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
76  */
77
78
79 static uint64_t
80 qva_to_vva(struct virtio_net *dev, uint64_t qemu_va)
81 {
82   struct virtio_memory_regions *region;
83   uint64_t vhost_va = 0;
84   uint32_t regionidx = 0;
85
86   /* Find the region where the address lives. */
87   for (regionidx = 0; regionidx < dev->mem->nregions; regionidx++) {
88     region = &dev->mem->regions[regionidx];
89     if ((qemu_va >= region->userspace_address) &&
90       (qemu_va <= region->userspace_address +
91       region->memory_size)) {
92       vhost_va = qemu_va + region->guest_phys_address +
93         region->address_offset -
94         region->userspace_address;
95       break;
96     }
97   }
98   return vhost_va;
99 }
100
101 static dpdk_device_t *
102 dpdk_vhost_user_device_from_hw_if_index(u32 hw_if_index)
103 {
104   vnet_main_t *vnm = vnet_get_main();
105   dpdk_main_t * dm = &dpdk_main;
106   vnet_hw_interface_t * hi = vnet_get_hw_interface (vnm, hw_if_index);
107   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
108
109   if (xd->dev_type != VNET_DPDK_DEV_VHOST_USER)
110     return 0;
111
112   return xd;
113 }
114
115 static dpdk_device_t *
116 dpdk_vhost_user_device_from_sw_if_index(u32 sw_if_index)
117 {
118   vnet_main_t *vnm = vnet_get_main();
119   vnet_sw_interface_t * sw = vnet_get_sw_interface (vnm, sw_if_index);
120   ASSERT (sw->type == VNET_SW_INTERFACE_TYPE_HARDWARE);
121
122   return dpdk_vhost_user_device_from_hw_if_index(sw->hw_if_index);
123 }
124
125 static inline void * map_guest_mem(dpdk_device_t * xd, u64 addr)
126 {
127   dpdk_vu_intf_t * vui = xd->vu_intf;
128   struct virtio_memory * mem = xd->vu_vhost_dev.mem;
129   int i;
130   for (i=0; i<mem->nregions; i++) {
131     if ((mem->regions[i].guest_phys_address <= addr) &&
132        ((mem->regions[i].guest_phys_address + mem->regions[i].memory_size) > addr)) {
133          return (void *) (vui->region_addr[i] + addr - mem->regions[i].guest_phys_address);
134        }
135   }
136   DBG_SOCK("failed to map guest mem addr %llx", addr);
137   return 0;
138 }
139
140 static clib_error_t *
141 dpdk_create_vhost_user_if_internal (u32 * hw_if_index, u32 if_id)
142 {
143   dpdk_main_t * dm = &dpdk_main;
144   vlib_main_t * vm = vlib_get_main();
145   vlib_thread_main_t * tm = vlib_get_thread_main();
146   vnet_sw_interface_t * sw;
147   clib_error_t * error;
148   dpdk_device_and_queue_t * dq;
149
150   dpdk_device_t * xd = NULL;
151   u8 addr[6];
152   int j;
153
154   vlib_worker_thread_barrier_sync (vm);
155
156   int inactive_cnt = vec_len(dm->vu_inactive_interfaces_device_index);
157   // if there are any inactive ifaces
158   if (inactive_cnt > 0) {
159     // take last
160     u32 vui_idx = dm->vu_inactive_interfaces_device_index[inactive_cnt - 1];
161     if (vec_len(dm->devices) > vui_idx) {
162       xd = vec_elt_at_index (dm->devices, vui_idx);
163       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER) {
164           DBG_SOCK("reusing inactive vhost-user interface sw_if_index %d", xd->vlib_sw_if_index);
165       } else {
166           clib_warning("error: inactive vhost-user interface sw_if_index %d not VHOST_USER type!",
167                   xd->vlib_sw_if_index);
168           // reset so new interface is created
169           xd = NULL;
170       }
171     }
172     // "remove" from inactive list
173     _vec_len(dm->vu_inactive_interfaces_device_index) -= 1;
174   }
175
176   if (xd) {
177       // existing interface used - do not overwrite if_id if not needed
178       if (if_id != (u32)~0)
179           xd->vu_if_id = if_id;
180
181       // reset virtqueues
182       for (j = 0; j < VIRTIO_QNUM; j++)
183         {
184           memset(xd->vu_vhost_dev.virtqueue[j], 0, sizeof(struct vhost_virtqueue));
185         }
186       // reset lockp
187       memset ((void *) xd->lockp, 0, CLIB_CACHE_LINE_BYTES);
188
189       // reset tx vectors
190       for (j = 0; j < tm->n_vlib_mains; j++)
191         {
192           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE,
193                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
194           vec_reset_length (xd->tx_vectors[j]);
195         }
196
197       // reset rx vector
198       for (j = 0; j < xd->rx_q_used; j++)
199         {
200           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
201                                 CLIB_CACHE_LINE_BYTES);
202           vec_reset_length (xd->rx_vectors[j]);
203         }
204   } else {
205       // vui was not retrieved from inactive ifaces - create new
206       vec_add2_aligned (dm->devices, xd, 1, CLIB_CACHE_LINE_BYTES);
207       xd->dev_type = VNET_DPDK_DEV_VHOST_USER;
208       xd->rx_q_used = 1;
209       vec_validate_aligned (xd->rx_vectors, xd->rx_q_used, CLIB_CACHE_LINE_BYTES);
210
211       if (if_id == (u32)~0)
212           xd->vu_if_id = dm->next_vu_if_id++;
213       else
214           xd->vu_if_id = if_id;
215
216       xd->device_index = xd - dm->devices;
217       xd->per_interface_next_index = ~0;
218       xd->vu_intf = NULL;
219
220       xd->vu_vhost_dev.mem = clib_mem_alloc (sizeof(struct virtio_memory) +
221                                              VHOST_MEMORY_MAX_NREGIONS *
222                                              sizeof(struct virtio_memory_regions));
223
224       for (j = 0; j < VIRTIO_QNUM; j++)
225         {
226           xd->vu_vhost_dev.virtqueue[j] = clib_mem_alloc (sizeof(struct vhost_virtqueue));
227           memset(xd->vu_vhost_dev.virtqueue[j], 0, sizeof(struct vhost_virtqueue));
228         }
229
230       xd->lockp = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
231                                           CLIB_CACHE_LINE_BYTES);
232       memset ((void *) xd->lockp, 0, CLIB_CACHE_LINE_BYTES);
233
234       vec_validate_aligned (xd->tx_vectors, tm->n_vlib_mains,
235                             CLIB_CACHE_LINE_BYTES);
236
237       for (j = 0; j < tm->n_vlib_mains; j++)
238         {
239           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE,
240                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
241           vec_reset_length (xd->tx_vectors[j]);
242         }
243
244       // reset rx vector
245       for (j = 0; j < xd->rx_q_used; j++)
246         {
247           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
248                                 CLIB_CACHE_LINE_BYTES);
249           vec_reset_length (xd->rx_vectors[j]);
250         }
251
252       vec_validate_aligned (xd->frames, tm->n_vlib_mains,
253                             CLIB_CACHE_LINE_BYTES);
254
255   }
256   {
257     f64 now = vlib_time_now(vm);
258     u32 rnd;
259     rnd = (u32) (now * 1e6);
260     rnd = random_u32 (&rnd);
261
262     memcpy (addr+2, &rnd, sizeof(rnd));
263     addr[0] = 2;
264     addr[1] = 0xfe;
265   }
266
267   error = ethernet_register_interface
268     (dm->vnet_main,
269      dpdk_device_class.index,
270      xd->device_index,
271      /* ethernet address */ addr,
272      &xd->vlib_hw_if_index,
273      0);
274
275   if (error)
276     return error;
277
278   sw = vnet_get_hw_sw_interface (dm->vnet_main, xd->vlib_hw_if_index);
279   xd->vlib_sw_if_index = sw->sw_if_index;
280
281   if (!xd->vu_intf)
282       xd->vu_intf = clib_mem_alloc (sizeof(*(xd->vu_intf)));
283
284   *hw_if_index = xd->vlib_hw_if_index;
285
286   int cpu = (xd->device_index % dm->input_cpu_count) +
287             dm->input_cpu_first_index;
288
289   vec_add2(dm->devices_by_cpu[cpu], dq, 1);
290   dq->device = xd->device_index;
291   dq->queue_id = 0;
292
293   // start polling if it was not started yet (because of no phys ifaces)
294   if (tm->n_vlib_mains == 1 && dpdk_input_node.state != VLIB_NODE_STATE_POLLING)
295     vlib_node_set_state (vm, dpdk_input_node.index, VLIB_NODE_STATE_POLLING);
296
297   if (tm->n_vlib_mains > 1 && tm->main_thread_is_io_node)
298     vlib_node_set_state (vm, dpdk_io_input_node.index, VLIB_NODE_STATE_POLLING);
299
300   if (tm->n_vlib_mains > 1 && !tm->main_thread_is_io_node)
301     vlib_node_set_state (vlib_mains[cpu], dpdk_input_node.index,
302                          VLIB_NODE_STATE_POLLING);
303
304   vlib_worker_thread_barrier_release (vm);
305   return 0;
306 }
307
308 static clib_error_t *
309 dpdk_vhost_user_get_features(u32 hw_if_index, u64 * features)
310 {
311   *features = rte_vhost_feature_get();
312
313   DBG_SOCK("supported features: 0x%x", *features);
314   return 0;
315 }
316
317 static clib_error_t *
318 dpdk_vhost_user_set_features(u32 hw_if_index, u64 features)
319 {
320   dpdk_device_t * xd;
321   u16 hdr_len = sizeof(struct virtio_net_hdr);
322
323
324   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
325     clib_warning("not a vhost-user interface");
326     return 0;
327   }
328
329   xd->vu_vhost_dev.features = features;
330
331   if (xd->vu_vhost_dev.features & (1 << VIRTIO_NET_F_MRG_RXBUF))
332     hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
333
334   xd->vu_vhost_dev.virtqueue[VIRTIO_RXQ]->vhost_hlen = hdr_len;
335   xd->vu_vhost_dev.virtqueue[VIRTIO_TXQ]->vhost_hlen = hdr_len;
336
337   xd->vu_is_running = 0;
338
339   return 0;
340 }
341
342 static clib_error_t *
343 dpdk_vhost_user_set_mem_table(u32 hw_if_index, vhost_user_memory_t * vum, int fd[])
344 {
345   struct virtio_memory * mem;
346   int i;
347   dpdk_device_t * xd;
348   dpdk_vu_intf_t * vui;
349
350   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
351     clib_warning("not a vhost-user interface");
352     return 0;
353   }
354
355   vui = xd->vu_intf;
356   mem = xd->vu_vhost_dev.mem;
357
358   mem->nregions = vum->nregions;
359
360   for (i=0; i < mem->nregions; i++) {
361     u64 mapped_size, mapped_address;
362
363     mem->regions[i].guest_phys_address     = vum->regions[i].guest_phys_addr;
364     mem->regions[i].guest_phys_address_end = vum->regions[i].guest_phys_addr +
365                                              vum->regions[i].memory_size;
366     mem->regions[i].memory_size            = vum->regions[i].memory_size;
367     mem->regions[i].userspace_address      = vum->regions[i].userspace_addr;
368
369     mapped_size = mem->regions[i].memory_size + vum->regions[i].mmap_offset;
370     mapped_address = (uint64_t)(uintptr_t)mmap(NULL, mapped_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd[i], 0);
371
372     if ((void *)mapped_address == MAP_FAILED)
373     {
374       clib_warning("mmap error");
375       return 0;
376     }
377
378     mapped_address +=  vum->regions[i].mmap_offset;
379     vui->region_addr[i] = mapped_address;
380     vui->region_fd[i] = fd[i];
381     mem->regions[i].address_offset = mapped_address - mem->regions[i].guest_phys_address;
382
383     if (vum->regions[i].guest_phys_addr == 0) {
384       mem->base_address = vum->regions[i].userspace_addr;
385       mem->mapped_address = mem->regions[i].address_offset;
386     }
387   }
388
389   xd->vu_is_running = 0;
390
391   DBG_SOCK("done");
392   return 0;
393 }
394
395 static clib_error_t *
396 dpdk_vhost_user_set_vring_num(u32 hw_if_index, u8 idx, u32 num)
397 {
398   dpdk_device_t * xd;
399   struct vhost_virtqueue *vq;
400
401   DBG_SOCK("idx %u num %u", idx, num);
402
403   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
404     clib_warning("not a vhost-user interface");
405     return 0;
406   }
407   vq = xd->vu_vhost_dev.virtqueue[idx];
408   vq->size = num;
409
410   xd->vu_is_running = 0;
411
412   return 0;
413 }
414
415 static clib_error_t *
416 dpdk_vhost_user_set_vring_addr(u32 hw_if_index, u8 idx, u64 desc, u64 used, u64 avail)
417 {
418   dpdk_device_t * xd;
419   struct vhost_virtqueue *vq;
420
421   DBG_SOCK("idx %u desc 0x%x used 0x%x avail 0x%x", idx, desc, used, avail);
422
423   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
424     clib_warning("not a vhost-user interface");
425     return 0;
426   }
427   vq = xd->vu_vhost_dev.virtqueue[idx];
428
429   vq->desc = (struct vring_desc *) qva_to_vva(&xd->vu_vhost_dev, desc);
430   vq->used = (struct vring_used *) qva_to_vva(&xd->vu_vhost_dev, used);
431   vq->avail = (struct vring_avail *) qva_to_vva(&xd->vu_vhost_dev, avail);
432
433   if (!(vq->desc && vq->used && vq->avail)) {
434     clib_warning("falied to set vring addr");
435   }
436
437   xd->vu_is_running = 0;
438
439   return 0;
440 }
441
442 static clib_error_t *
443 dpdk_vhost_user_get_vring_base(u32 hw_if_index, u8 idx, u32 * num)
444 {
445   dpdk_device_t * xd;
446   struct vhost_virtqueue *vq;
447
448   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
449     clib_warning("not a vhost-user interface");
450     return 0;
451   }
452
453   vq = xd->vu_vhost_dev.virtqueue[idx];
454   *num = vq->last_used_idx;
455
456   DBG_SOCK("idx %u num %u", idx, *num);
457   return 0;
458 }
459
460 static clib_error_t *
461 dpdk_vhost_user_set_vring_base(u32 hw_if_index, u8 idx, u32 num)
462 {
463   dpdk_device_t * xd;
464   struct vhost_virtqueue *vq;
465
466   DBG_SOCK("idx %u num %u", idx, num);
467
468   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
469     clib_warning("not a vhost-user interface");
470     return 0;
471   }
472
473   vq = xd->vu_vhost_dev.virtqueue[idx];
474   vq->last_used_idx = num;
475   vq->last_used_idx_res = num;
476
477   xd->vu_is_running = 0;
478
479   return 0;
480 }
481
482 static clib_error_t *
483 dpdk_vhost_user_set_vring_kick(u32 hw_if_index, u8 idx, int fd)
484 {
485   dpdk_main_t * dm = &dpdk_main;
486   dpdk_device_t * xd;
487   struct vhost_virtqueue *vq, *vq0, *vq1;
488
489   DBG_SOCK("idx %u fd %d", idx, fd);
490
491   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
492     clib_warning("not a vhost-user interface");
493     return 0;
494   }
495
496   vq = xd->vu_vhost_dev.virtqueue[idx];
497   vq->kickfd = fd;
498
499   vq0 = xd->vu_vhost_dev.virtqueue[0];
500   vq1 = xd->vu_vhost_dev.virtqueue[1];
501
502   if (vq0->desc && vq0->avail && vq0->used &&
503       vq1->desc && vq1->avail && vq1->used) {
504     xd->vu_is_running = 1;
505     if (xd->admin_up)
506       vnet_hw_interface_set_flags (dm->vnet_main, xd->vlib_hw_if_index,
507                            VNET_HW_INTERFACE_FLAG_LINK_UP |
508                            ETH_LINK_FULL_DUPLEX );
509   }
510
511   return 0;
512 }
513
514
515 static clib_error_t *
516 dpdk_vhost_user_set_vring_call(u32 hw_if_index, u8 idx, int fd)
517 {
518   dpdk_device_t * xd;
519   struct vhost_virtqueue *vq;
520
521   DBG_SOCK("idx %u fd %d", idx, fd);
522
523   if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_index))) {
524     clib_warning("not a vhost-user interface");
525     return 0;
526   }
527
528   vq = xd->vu_vhost_dev.virtqueue[idx];
529   /* reset callfd to force no interrupts */
530   vq->callfd = -1;
531
532   return 0;
533 }
534
535 u8
536 dpdk_vhost_user_want_interrupt(dpdk_device_t *xd, int idx)
537 {
538     dpdk_vu_intf_t *vui = xd->vu_intf;
539     ASSERT(vui != NULL);
540
541     if (PREDICT_FALSE(vui->num_vrings <= 0))
542         return 0;
543
544     dpdk_vu_vring *vring = &(vui->vrings[idx]);
545     struct vhost_virtqueue *vq = xd->vu_vhost_dev.virtqueue[idx];
546
547     /* return if vm is interested in interrupts */
548     return (vring->callfd > 0) && !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT);
549 }
550
551 void
552 dpdk_vhost_user_send_interrupt(vlib_main_t * vm, dpdk_device_t * xd, int idx)
553 {
554     dpdk_main_t * dm = &dpdk_main;
555     dpdk_vu_intf_t *vui = xd->vu_intf;
556     ASSERT(vui != NULL);
557
558     if (PREDICT_FALSE(vui->num_vrings <= 0))
559         return;
560
561     dpdk_vu_vring *vring = &(vui->vrings[idx]);
562     struct vhost_virtqueue *vq = xd->vu_vhost_dev.virtqueue[idx];
563
564     /* if vm is interested in interrupts */
565     if((vring->callfd > 0) && !(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
566         u64 x = 1;
567         int rv __attribute__((unused));
568         /* $$$$ pay attention to rv */
569         rv = write(vring->callfd, &x, sizeof(x));
570         vring->n_since_last_int = 0;
571         vring->int_deadline = vlib_time_now(vm) + dm->vhost_coalesce_time;
572     }
573 }
574
575 /*
576  * vhost-user interface management functions 
577  */
578
579 // initialize vui with specified attributes
580 static void 
581 dpdk_vhost_user_vui_init(vnet_main_t * vnm,
582                          dpdk_device_t *xd, int sockfd,
583                          const char * sock_filename,
584                          u8 is_server, u64 feature_mask,
585                          u32 * sw_if_index)
586 {
587   dpdk_vu_intf_t *vui = xd->vu_intf;
588   memset(vui, 0, sizeof(*vui));
589
590   vui->unix_fd = sockfd;
591   vui->num_vrings = 2;
592   vui->sock_is_server = is_server;
593   strncpy(vui->sock_filename, sock_filename, ARRAY_LEN(vui->sock_filename)-1);
594   vui->sock_errno = 0;
595   vui->is_up = 0;
596   vui->feature_mask = feature_mask;
597   vui->active = 1;
598   vui->unix_file_index = ~0;
599
600   vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,  0);
601
602   if (sw_if_index)
603       *sw_if_index = xd->vlib_sw_if_index;
604 }
605
606 // register vui and start polling on it
607 static void 
608 dpdk_vhost_user_vui_register(vlib_main_t * vm, dpdk_device_t *xd)
609 {
610   dpdk_main_t * dm = &dpdk_main;
611   dpdk_vu_intf_t *vui = xd->vu_intf;
612
613   hash_set (dm->vu_sw_if_index_by_listener_fd, vui->unix_fd,
614             xd->vlib_sw_if_index);
615 }
616
617 static inline void
618 dpdk_vhost_user_if_disconnect(dpdk_device_t * xd)
619 {
620     dpdk_vu_intf_t *vui = xd->vu_intf;
621     vnet_main_t * vnm = vnet_get_main();
622     dpdk_main_t * dm = &dpdk_main;
623
624     xd->admin_up = 0;
625     vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,  0);
626
627     if (vui->unix_file_index != ~0) {
628         unix_file_del (&unix_main, unix_main.file_pool + vui->unix_file_index);
629         vui->unix_file_index = ~0;
630     }
631
632     hash_unset(dm->vu_sw_if_index_by_sock_fd, vui->unix_fd);
633     hash_unset(dm->vu_sw_if_index_by_listener_fd, vui->unix_fd);
634     close(vui->unix_fd);
635     vui->unix_fd = -1;
636     vui->is_up = 0;
637
638     DBG_SOCK("interface ifindex %d disconnected", xd->vlib_sw_if_index);
639 }
640
641 static clib_error_t * dpdk_vhost_user_callfd_read_ready (unix_file_t * uf)
642 {
643   __attribute__((unused)) int n;
644   u8 buff[8];
645   n = read(uf->file_descriptor, ((char*)&buff), 8);
646   return 0;
647 }
648
649 static clib_error_t * dpdk_vhost_user_socket_read (unix_file_t * uf)
650 {
651   int n;
652   int fd, number_of_fds = 0;
653   int fds[VHOST_MEMORY_MAX_NREGIONS];
654   vhost_user_msg_t msg;
655   struct msghdr mh;
656   struct iovec iov[1];
657   dpdk_main_t * dm = &dpdk_main;
658   dpdk_device_t *xd;
659   dpdk_vu_intf_t *vui;
660   struct cmsghdr *cmsg;
661   uword * p;
662   u8 q;
663   unix_file_t template = {0};
664   vnet_main_t * vnm = vnet_get_main();
665
666   p = hash_get (dm->vu_sw_if_index_by_sock_fd, uf->file_descriptor);
667   if (p == 0) {
668       DBG_SOCK ("FD %d doesn't belong to any interface",
669                     uf->file_descriptor);
670       return 0;
671     }
672   else
673       xd = dpdk_vhost_user_device_from_sw_if_index(p[0]);
674
675   ASSERT(xd != NULL);
676   vui = xd->vu_intf;
677
678   char control[CMSG_SPACE(VHOST_MEMORY_MAX_NREGIONS * sizeof(int))];
679
680   memset(&mh, 0, sizeof(mh));
681   memset(control, 0, sizeof(control));
682
683   /* set the payload */
684   iov[0].iov_base = (void *) &msg;
685   iov[0].iov_len = VHOST_USER_MSG_HDR_SZ;
686
687   mh.msg_iov = iov;
688   mh.msg_iovlen = 1;
689   mh.msg_control = control;
690   mh.msg_controllen = sizeof(control);
691
692   n = recvmsg(uf->file_descriptor, &mh, 0);
693
694   if (n != VHOST_USER_MSG_HDR_SZ)
695     goto close_socket;
696
697   if (mh.msg_flags & MSG_CTRUNC) {
698     goto close_socket;
699   }
700
701   cmsg = CMSG_FIRSTHDR(&mh);
702
703   if (cmsg && (cmsg->cmsg_len > 0) && (cmsg->cmsg_level == SOL_SOCKET) &&
704       (cmsg->cmsg_type == SCM_RIGHTS) &&
705       (cmsg->cmsg_len - CMSG_LEN(0) <= VHOST_MEMORY_MAX_NREGIONS * sizeof(int))) {
706         number_of_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
707         memcpy(fds, CMSG_DATA(cmsg), number_of_fds * sizeof(int));
708   }
709
710   /* version 1, no reply bit set*/
711   if ((msg.flags & 7) != 1) {
712     DBG_SOCK("malformed message received. closing socket");
713     goto close_socket;
714   }
715
716   {
717       int rv __attribute__((unused));
718       /* $$$$ pay attention to rv */
719       rv = read(uf->file_descriptor, ((char*)&msg) + n, msg.size);
720   }
721
722   switch (msg.request) {
723     case VHOST_USER_GET_FEATURES:
724       DBG_SOCK("if %d msg VHOST_USER_GET_FEATURES",
725         xd->vlib_hw_if_index);
726
727       msg.flags |= 4;
728
729       dpdk_vhost_user_get_features(xd->vlib_hw_if_index, &msg.u64);
730       msg.u64 &= vui->feature_mask;
731       msg.size = sizeof(msg.u64);
732       break;
733
734     case VHOST_USER_SET_FEATURES:
735       DBG_SOCK("if %d msg VHOST_USER_SET_FEATURES features 0x%016llx",
736         xd->vlib_hw_if_index, msg.u64);
737
738       dpdk_vhost_user_set_features(xd->vlib_hw_if_index, msg.u64);
739       break;
740
741     case VHOST_USER_SET_MEM_TABLE:
742       DBG_SOCK("if %d msg VHOST_USER_SET_MEM_TABLE nregions %d",
743         xd->vlib_hw_if_index, msg.memory.nregions);
744
745       if ((msg.memory.nregions < 1) ||
746           (msg.memory.nregions > VHOST_MEMORY_MAX_NREGIONS)) {
747
748         DBG_SOCK("number of mem regions must be between 1 and %i",
749           VHOST_MEMORY_MAX_NREGIONS);
750
751         goto close_socket;
752       }
753
754       if (msg.memory.nregions != number_of_fds) {
755         DBG_SOCK("each memory region must have FD");
756         goto close_socket;
757       }
758
759       dpdk_vhost_user_set_mem_table(xd->vlib_hw_if_index, &msg.memory, fds);
760       break;
761
762     case VHOST_USER_SET_VRING_NUM:
763       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_NUM idx %d num %d",
764         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
765
766       if ((msg.state.num > 32768) || /* maximum ring size is 32768 */
767           (msg.state.num == 0) ||    /* it cannot be zero */
768           (msg.state.num % 2))       /* must be power of 2 */
769         goto close_socket;
770
771       dpdk_vhost_user_set_vring_num(xd->vlib_hw_if_index, msg.state.index, msg.state.num);
772       break;
773
774     case VHOST_USER_SET_VRING_ADDR:
775       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_ADDR idx %d",
776         xd->vlib_hw_if_index, msg.state.index);
777
778       dpdk_vhost_user_set_vring_addr(xd->vlib_hw_if_index, msg.state.index,
779                                     msg.addr.desc_user_addr,
780                                     msg.addr.used_user_addr,
781                                     msg.addr.avail_user_addr);
782       break;
783
784     case VHOST_USER_SET_OWNER:
785       DBG_SOCK("if %d msg VHOST_USER_SET_OWNER",
786         xd->vlib_hw_if_index);
787       break;
788
789     case VHOST_USER_RESET_OWNER:
790       DBG_SOCK("if %d msg VHOST_USER_RESET_OWNER",
791         xd->vlib_hw_if_index);
792       break;
793
794     case VHOST_USER_SET_VRING_CALL:
795       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_CALL u64 %d",
796         xd->vlib_hw_if_index, msg.u64);
797
798       q = (u8) (msg.u64 & 0xFF);
799
800       if (!(msg.u64 & 0x100))
801       {
802         if (number_of_fds != 1)
803           goto close_socket;
804
805         /* if there is old fd, delete it */
806         if (vui->vrings[q].callfd) {
807           unix_file_t * uf = pool_elt_at_index (unix_main.file_pool,
808             vui->vrings[q].callfd_idx);
809           unix_file_del (&unix_main, uf);
810         }
811         vui->vrings[q].callfd = fds[0];
812         template.read_function = dpdk_vhost_user_callfd_read_ready;
813         template.file_descriptor = fds[0];
814         vui->vrings[q].callfd_idx = unix_file_add (&unix_main, &template);
815       }
816       else
817         vui->vrings[q].callfd = -1;
818
819       dpdk_vhost_user_set_vring_call(xd->vlib_hw_if_index, q, vui->vrings[q].callfd);
820       break;
821
822     case VHOST_USER_SET_VRING_KICK:
823       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_KICK u64 %d",
824         xd->vlib_hw_if_index, msg.u64);
825
826       q = (u8) (msg.u64 & 0xFF);
827
828       if (!(msg.u64 & 0x100))
829       {
830         if (number_of_fds != 1)
831           goto close_socket;
832
833         vui->vrings[q].kickfd = fds[0];
834       }
835       else
836         vui->vrings[q].kickfd = -1;
837
838       dpdk_vhost_user_set_vring_kick(xd->vlib_hw_if_index, q, vui->vrings[q].kickfd);
839       break;
840
841     case VHOST_USER_SET_VRING_ERR:
842       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_ERR u64 %d",
843         xd->vlib_hw_if_index, msg.u64);
844
845       q = (u8) (msg.u64 & 0xFF);
846
847       if (!(msg.u64 & 0x100))
848       {
849         if (number_of_fds != 1)
850           goto close_socket;
851
852         fd = fds[0];
853       }
854       else
855         fd = -1;
856
857       vui->vrings[q].errfd = fd;
858       break;
859
860     case VHOST_USER_SET_VRING_BASE:
861       DBG_SOCK("if %d msg VHOST_USER_SET_VRING_BASE idx %d num %d",
862         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
863
864       dpdk_vhost_user_set_vring_base(xd->vlib_hw_if_index, msg.state.index, msg.state.num);
865       break;
866
867     case VHOST_USER_GET_VRING_BASE:
868       DBG_SOCK("if %d msg VHOST_USER_GET_VRING_BASE idx %d num %d",
869         xd->vlib_hw_if_index, msg.state.index, msg.state.num);
870
871       msg.flags |= 4;
872       msg.size = sizeof(msg.state);
873
874       dpdk_vhost_user_get_vring_base(xd->vlib_hw_if_index, msg.state.index, &msg.state.num);
875       break;
876
877     case VHOST_USER_NONE:
878       DBG_SOCK("if %d msg VHOST_USER_NONE",
879         xd->vlib_hw_if_index);
880       break;
881
882     case VHOST_USER_SET_LOG_BASE:
883       DBG_SOCK("if %d msg VHOST_USER_SET_LOG_BASE",
884         xd->vlib_hw_if_index);
885       break;
886
887     case VHOST_USER_SET_LOG_FD:
888       DBG_SOCK("if %d msg VHOST_USER_SET_LOG_FD",
889         xd->vlib_hw_if_index);
890       break;
891
892     default:
893       DBG_SOCK("unknown vhost-user message %d received. closing socket",
894         msg.request);
895       goto close_socket;
896   }
897
898   /* if we have pointers to descriptor table, go up*/
899   if (!vui->is_up &&
900       xd->vu_vhost_dev.virtqueue[VHOST_NET_VRING_IDX_TX]->desc &&
901       xd->vu_vhost_dev.virtqueue[VHOST_NET_VRING_IDX_RX]->desc) {
902
903       DBG_SOCK("interface %d connected", xd->vlib_sw_if_index);
904
905       vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index,  VNET_HW_INTERFACE_FLAG_LINK_UP);
906       vui->is_up = 1;
907   }
908
909   /* if we need to reply */
910   if (msg.flags & 4)
911   {
912       n = send(uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
913       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
914         goto close_socket;
915   }
916
917   return 0;
918
919 close_socket:
920   DBG_SOCK("error: close_socket");
921   dpdk_vhost_user_if_disconnect(xd);
922   return 0;
923 }
924
925 static clib_error_t * dpdk_vhost_user_socket_error (unix_file_t * uf)
926 {
927   dpdk_main_t * dm = &dpdk_main;
928   dpdk_device_t *xd;
929   uword * p;
930
931   p = hash_get (dm->vu_sw_if_index_by_sock_fd, uf->file_descriptor);
932   if (p == 0) {
933       DBG_SOCK ("FD %d doesn't belong to any interface",
934                     uf->file_descriptor);
935       return 0;
936     }
937   else
938       xd = dpdk_vhost_user_device_from_sw_if_index(p[0]);
939
940   dpdk_vhost_user_if_disconnect(xd);
941   return 0;
942 }
943
944 static clib_error_t * dpdk_vhost_user_socksvr_accept_ready (unix_file_t * uf)
945 {
946   int client_fd, client_len;
947   struct sockaddr_un client;
948   unix_file_t template = {0};
949   dpdk_main_t * dm = &dpdk_main;
950   dpdk_device_t * xd = NULL;
951   dpdk_vu_intf_t * vui;
952   uword * p;
953
954   p = hash_get (dm->vu_sw_if_index_by_listener_fd,
955                 uf->file_descriptor);
956   if (p == 0) {
957       DBG_SOCK ("fd %d doesn't belong to any interface",
958                     uf->file_descriptor);
959       return 0;
960     }
961
962   xd = dpdk_vhost_user_device_from_sw_if_index(p[0]);
963   ASSERT(xd != NULL);
964   vui = xd->vu_intf;
965
966   client_len = sizeof(client);
967   client_fd = accept (uf->file_descriptor,
968                       (struct sockaddr *)&client,
969                       (socklen_t *)&client_len);
970
971   if (client_fd < 0)
972       return clib_error_return_unix (0, "accept");
973
974   template.read_function = dpdk_vhost_user_socket_read;
975   template.error_function = dpdk_vhost_user_socket_error;
976   template.file_descriptor = client_fd;
977   vui->unix_file_index = unix_file_add (&unix_main, &template);
978
979   vui->client_fd = client_fd;
980   hash_set (dm->vu_sw_if_index_by_sock_fd, vui->client_fd,
981             xd->vlib_sw_if_index);
982
983   return 0;
984 }
985
986 // init server socket on specified sock_filename
987 static int dpdk_vhost_user_init_server_sock(const char * sock_filename, int *sockfd)
988 {
989   int rv = 0, len;
990   struct sockaddr_un un;
991   int fd;
992   /* create listening socket */
993   fd = socket(AF_UNIX, SOCK_STREAM, 0);
994
995   if (fd < 0) {
996     return VNET_API_ERROR_SYSCALL_ERROR_1;
997   }
998
999   un.sun_family = AF_UNIX;
1000   strcpy((char *) un.sun_path, (char *) sock_filename);
1001
1002   /* remove if exists */
1003   unlink( (char *) sock_filename);
1004
1005   len = strlen((char *) un.sun_path) + strlen((char *) sock_filename);
1006
1007   if (bind(fd, (struct sockaddr *) &un, len) == -1) {
1008     rv = VNET_API_ERROR_SYSCALL_ERROR_2;
1009     goto error;
1010   }
1011
1012   if (listen(fd, 1) == -1) {
1013     rv = VNET_API_ERROR_SYSCALL_ERROR_3;
1014     goto error;
1015   }
1016
1017   unix_file_t template = {0};
1018   template.read_function = dpdk_vhost_user_socksvr_accept_ready;
1019   template.file_descriptor = fd;
1020   unix_file_add (&unix_main, &template);
1021   *sockfd = fd;
1022   return rv;
1023
1024 error:
1025   close(fd);
1026   return rv;
1027 }
1028
1029 /*
1030  * vhost-user interface control functions used from vpe api
1031  */
1032
1033 int dpdk_vhost_user_create_if(vnet_main_t * vnm, vlib_main_t * vm,
1034                               const char * sock_filename,
1035                               u8 is_server,
1036                               u32 * sw_if_index,
1037                               u64 feature_mask,
1038                               u8 renumber, u32 custom_dev_instance)
1039 {
1040   dpdk_main_t * dm = &dpdk_main;
1041   dpdk_device_t *xd;
1042   u32 hw_if_idx = ~0;
1043   int sockfd = -1;
1044   int rv = 0;
1045
1046   // using virtio vhost user?
1047   if (dm->use_virtio_vhost) {
1048       return vhost_user_create_if(vnm, vm, sock_filename, is_server,
1049               sw_if_index, feature_mask, renumber, custom_dev_instance);
1050   }
1051
1052   if (is_server) {
1053     if ((rv = dpdk_vhost_user_init_server_sock (sock_filename, &sockfd)) != 0) {
1054         return rv;
1055     }
1056   }
1057
1058   if (renumber) {
1059       // set next vhost-user if id if custom one is higher or equal
1060       if (custom_dev_instance >= dm->next_vu_if_id)
1061           dm->next_vu_if_id = custom_dev_instance + 1;
1062
1063     dpdk_create_vhost_user_if_internal(&hw_if_idx, custom_dev_instance);
1064   } else 
1065     dpdk_create_vhost_user_if_internal(&hw_if_idx, (u32)~0);
1066   DBG_SOCK("dpdk vhost-user interface created hw_if_index %d", hw_if_idx);
1067
1068   xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_idx);
1069   ASSERT(xd != NULL);
1070
1071   dpdk_vhost_user_vui_init (vnm, xd, sockfd, sock_filename, is_server,
1072                             feature_mask, sw_if_index);
1073
1074   dpdk_vhost_user_vui_register (vm, xd);
1075   return rv;
1076 }
1077
1078 int dpdk_vhost_user_modify_if(vnet_main_t * vnm, vlib_main_t * vm,
1079                          const char * sock_filename,
1080                          u8 is_server,
1081                          u32 sw_if_index,
1082                          u64 feature_mask,
1083                          u8 renumber, u32 custom_dev_instance)
1084 {
1085   dpdk_main_t * dm = &dpdk_main;
1086   dpdk_device_t * xd;
1087   dpdk_vu_intf_t * vui = NULL;
1088   u32 sw_if_idx = ~0;
1089   int sockfd = -1;
1090   int rv = 0;
1091
1092   // using virtio vhost user?
1093   if (dm->use_virtio_vhost) {
1094       return vhost_user_modify_if(vnm, vm, sock_filename, is_server,
1095               sw_if_index, feature_mask, renumber, custom_dev_instance);
1096   }
1097
1098   xd = dpdk_vhost_user_device_from_sw_if_index(sw_if_index);
1099
1100   if (xd == NULL)
1101     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
1102
1103   vui = xd->vu_intf;
1104
1105   // interface is inactive
1106   vui->active = 0;
1107   // disconnect interface sockets
1108   dpdk_vhost_user_if_disconnect(xd);
1109
1110   if (is_server) {
1111       if ((rv = dpdk_vhost_user_init_server_sock (sock_filename, &sockfd)) != 0) {
1112           return rv;
1113       }
1114   }
1115
1116   dpdk_vhost_user_vui_init (vnm, xd, sockfd, sock_filename, is_server,
1117                        feature_mask, &sw_if_idx);
1118
1119   if (renumber) {
1120     vnet_interface_name_renumber (sw_if_idx, custom_dev_instance);
1121   }
1122
1123   dpdk_vhost_user_vui_register (vm, xd);
1124
1125   return rv;
1126 }
1127
1128 int dpdk_vhost_user_delete_if(vnet_main_t * vnm, vlib_main_t * vm,
1129                          u32 sw_if_index)
1130 {
1131   dpdk_main_t * dm = &dpdk_main;
1132   dpdk_device_t * xd = NULL;
1133   dpdk_vu_intf_t * vui;
1134   int rv = 0;
1135
1136   // using virtio vhost user?
1137   if (dm->use_virtio_vhost) {
1138       return vhost_user_delete_if(vnm, vm, sw_if_index);
1139   }
1140
1141   xd = dpdk_vhost_user_device_from_sw_if_index(sw_if_index);
1142
1143   if (xd == NULL)
1144     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
1145
1146   vui = xd->vu_intf;
1147
1148   // interface is inactive
1149   vui->active = 0;
1150   // disconnect interface sockets
1151   dpdk_vhost_user_if_disconnect(xd);
1152   // add to inactive interface list
1153   vec_add1 (dm->vu_inactive_interfaces_device_index, xd->device_index);
1154
1155   ethernet_delete_interface (vnm, xd->vlib_hw_if_index);
1156   DBG_SOCK ("deleted (deactivated) vhost-user interface sw_if_index %d", sw_if_index);
1157
1158   return rv;
1159 }
1160
1161 int dpdk_vhost_user_dump_ifs(vnet_main_t * vnm, vlib_main_t * vm, vhost_user_intf_details_t **out_vuids)
1162 {
1163     int rv = 0;
1164     dpdk_main_t * dm = &dpdk_main;
1165     dpdk_device_t * xd;
1166     dpdk_vu_intf_t * vui;
1167     struct virtio_net * vhost_dev;
1168     vhost_user_intf_details_t * r_vuids = NULL;
1169     vhost_user_intf_details_t * vuid = NULL;
1170     u32 * hw_if_indices = 0;
1171     vnet_hw_interface_t * hi;
1172     u8 *s = NULL;
1173     int i;
1174
1175     if (!out_vuids)
1176         return -1;
1177
1178     // using virtio vhost user?
1179     if (dm->use_virtio_vhost) {
1180         return vhost_user_dump_ifs(vnm, vm, out_vuids);
1181     }
1182
1183     vec_foreach (xd, dm->devices) {
1184       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER &&
1185               xd->vu_intf->active)
1186         vec_add1(hw_if_indices, xd->vlib_hw_if_index);
1187     }
1188
1189     for (i = 0; i < vec_len (hw_if_indices); i++) {
1190       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
1191       xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_indices[i]);
1192       if (!xd) {
1193           clib_warning("invalid vhost-user interface hw_if_index %d", hw_if_indices[i]);
1194           continue;
1195       }
1196
1197       vui = xd->vu_intf;
1198       ASSERT(vui != NULL);
1199       vhost_dev = &xd->vu_vhost_dev;
1200       u32 virtio_net_hdr_sz = (vui->num_vrings > 0 ?
1201             vhost_dev->virtqueue[0]->vhost_hlen : 0);
1202
1203       vec_add2(r_vuids, vuid, 1);
1204       vuid->sw_if_index = xd->vlib_sw_if_index;
1205       vuid->virtio_net_hdr_sz = virtio_net_hdr_sz;
1206       vuid->features = vhost_dev->features;
1207       vuid->is_server = vui->sock_is_server;
1208       vuid->num_regions = (vhost_dev->mem != NULL ? vhost_dev->mem->nregions : 0);
1209       vuid->sock_errno = vui->sock_errno;
1210       strncpy((char *)vuid->sock_filename, (char *)vui->sock_filename,
1211               ARRAY_LEN(vuid->sock_filename)-1);
1212
1213       s = format (s, "%v%c", hi->name, 0);
1214
1215       strncpy((char *)vuid->if_name, (char *)s,
1216               ARRAY_LEN(vuid->if_name)-1);
1217       _vec_len(s) = 0;
1218     }
1219
1220     vec_free (s);
1221     vec_free (hw_if_indices);
1222
1223     *out_vuids = r_vuids;
1224
1225     return rv;
1226 }
1227
1228 /*
1229  * Processing functions called from dpdk process fn
1230  */
1231
1232 typedef struct {
1233     struct sockaddr_un sun;
1234     int sockfd;
1235     unix_file_t template;
1236     uword *event_data;
1237 } dpdk_vu_process_state;
1238
1239 void dpdk_vhost_user_process_init (void **ctx)
1240 {
1241     dpdk_vu_process_state *state = clib_mem_alloc (sizeof(dpdk_vu_process_state));
1242     memset(state, 0, sizeof(*state));
1243     state->sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
1244     state->sun.sun_family = AF_UNIX;
1245     state->template.read_function = dpdk_vhost_user_socket_read;
1246     state->template.error_function = dpdk_vhost_user_socket_error;
1247     state->event_data = 0;
1248     *ctx = state;
1249 }
1250
1251 void dpdk_vhost_user_process_cleanup (void *ctx)
1252 {
1253     clib_mem_free(ctx);
1254 }
1255
1256 uword dpdk_vhost_user_process_if (vlib_main_t *vm, dpdk_device_t *xd, void *ctx)
1257 {
1258     dpdk_main_t * dm = &dpdk_main;
1259     dpdk_vu_process_state *state = (dpdk_vu_process_state *)ctx;
1260     dpdk_vu_intf_t *vui = xd->vu_intf;
1261
1262     if (vui->sock_is_server || !vui->active)
1263         return 0;
1264
1265     if (vui->unix_fd == -1) {
1266         /* try to connect */
1267         strncpy(state->sun.sun_path,  (char *) vui->sock_filename, sizeof(state->sun.sun_path) - 1);
1268
1269         if (connect(state->sockfd, (struct sockaddr *) &(state->sun), sizeof(struct sockaddr_un)) == 0) {
1270             vui->sock_errno = 0;
1271             vui->unix_fd = state->sockfd;
1272             state->template.file_descriptor = state->sockfd;
1273             vui->unix_file_index = unix_file_add (&unix_main, &(state->template));
1274             hash_set (dm->vu_sw_if_index_by_sock_fd, state->sockfd, xd->vlib_sw_if_index);
1275
1276             state->sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
1277             if (state->sockfd < 0)
1278                 return -1;
1279         } else {
1280             vui->sock_errno = errno;
1281         }
1282     } else {
1283         /* check if socket is alive */
1284         int error = 0;
1285         socklen_t len = sizeof (error);
1286         int retval = getsockopt(vui->unix_fd, SOL_SOCKET, SO_ERROR, &error, &len);
1287
1288         if (retval)
1289             dpdk_vhost_user_if_disconnect(xd);
1290     }
1291     return 0;
1292 }
1293
1294 /*
1295  * CLI functions
1296  */
1297
1298 static clib_error_t *
1299 dpdk_vhost_user_connect_command_fn (vlib_main_t * vm,
1300                  unformat_input_t * input,
1301                  vlib_cli_command_t * cmd)
1302 {
1303   dpdk_main_t * dm = &dpdk_main;
1304   unformat_input_t _line_input, * line_input = &_line_input;
1305   u8 * sock_filename = NULL;
1306   u32 sw_if_index;
1307   u8 is_server = 0;
1308   u64 feature_mask = (u64)~0;
1309   u8 renumber = 0;
1310   u32 custom_dev_instance = ~0;
1311
1312   if (dm->use_virtio_vhost) {
1313       return vhost_user_connect_command_fn(vm, input, cmd);
1314   }
1315
1316   /* Get a line of input. */
1317   if (! unformat_user (input, unformat_line_input, line_input))
1318     return 0;
1319
1320   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) {
1321     if (unformat (line_input, "socket %s", &sock_filename))
1322       ;
1323     else if (unformat (line_input, "server"))
1324       is_server = 1;
1325     else if (unformat (line_input, "feature-mask 0x%llx", &feature_mask))
1326       ;
1327     else if (unformat (line_input, "renumber %d", &custom_dev_instance)) {
1328         renumber = 1;
1329     }
1330     else
1331       return clib_error_return (0, "unknown input `%U'",
1332                                 format_unformat_error, input);
1333   }
1334   unformat_free (line_input);
1335
1336   vnet_main_t *vnm = vnet_get_main();
1337   if (sock_filename == NULL)
1338       return clib_error_return (0, "missing socket file");
1339
1340   dpdk_vhost_user_create_if(vnm, vm, (char *)sock_filename,
1341                             is_server, &sw_if_index, feature_mask,
1342                             renumber, custom_dev_instance);
1343
1344   vec_free(sock_filename);
1345   return 0;
1346 }
1347
1348 VLIB_CLI_COMMAND (dpdk_vhost_user_connect_command, static) = {
1349     .path = "create vhost-user",
1350     .short_help = "create vhost-user socket <socket-filename> [server] [feature-mask <hex>] [renumber <dev_instance>]",
1351     .function = dpdk_vhost_user_connect_command_fn,
1352 };
1353
1354 static clib_error_t *
1355 dpdk_vhost_user_delete_command_fn (vlib_main_t * vm,
1356                  unformat_input_t * input,
1357                  vlib_cli_command_t * cmd)
1358 {
1359   dpdk_main_t * dm = &dpdk_main;
1360   clib_error_t * error = 0;
1361   unformat_input_t _line_input, * line_input = &_line_input;
1362   u32 sw_if_index = ~0;
1363
1364   if (dm->use_virtio_vhost) {
1365       return vhost_user_delete_command_fn(vm, input, cmd);
1366   }
1367
1368   /* Get a line of input. */
1369   if (! unformat_user (input, unformat_line_input, line_input))
1370     return 0;
1371
1372   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT) {
1373     if (unformat (line_input, "sw_if_index %d", &sw_if_index))
1374       ;
1375     else
1376       return clib_error_return (0, "unknown input `%U'",
1377                                 format_unformat_error, input);
1378   }
1379   unformat_free (line_input);
1380
1381   if (sw_if_index == ~0) {
1382       error = clib_error_return (0, "invalid sw_if_index",
1383                                  format_unformat_error, input);
1384       return error;
1385   }
1386
1387   vnet_main_t *vnm = vnet_get_main();
1388
1389   dpdk_vhost_user_delete_if(vnm, vm, sw_if_index);
1390
1391   return 0;
1392 }
1393
1394 VLIB_CLI_COMMAND (dpdk_vhost_user_delete_command, static) = {
1395     .path = "delete vhost-user",
1396     .short_help = "delete vhost-user sw_if_index <nn>",
1397     .function = dpdk_vhost_user_delete_command_fn,
1398 };
1399
1400 #define foreach_dpdk_vhost_feature      \
1401  _ (VIRTIO_NET_F_MRG_RXBUF)             \
1402  _ (VIRTIO_NET_F_CTRL_VQ)               \
1403  _ (VIRTIO_NET_F_CTRL_RX)
1404
1405 static clib_error_t *
1406 show_dpdk_vhost_user_command_fn (vlib_main_t * vm,
1407                  unformat_input_t * input,
1408                  vlib_cli_command_t * cmd)
1409 {
1410   clib_error_t * error = 0;
1411   dpdk_main_t * dm = &dpdk_main;
1412   vnet_main_t * vnm = vnet_get_main();
1413   dpdk_device_t * xd;
1414   dpdk_vu_intf_t * vui;
1415   struct virtio_net * vhost_dev;
1416   u32 hw_if_index, * hw_if_indices = 0;
1417   vnet_hw_interface_t * hi;
1418   int i, j, q;
1419   int show_descr = 0;
1420   struct virtio_memory * mem;
1421   struct feat_struct { u8 bit; char *str;};
1422   struct feat_struct *feat_entry;
1423
1424   static struct feat_struct feat_array[] = {
1425 #define _(f) { .str = #f, .bit = f, },
1426   foreach_dpdk_vhost_feature
1427 #undef _
1428   { .str = NULL }
1429   };
1430
1431   if (dm->use_virtio_vhost) {
1432     return show_vhost_user_command_fn(vm, input, cmd);
1433   }
1434
1435   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) {
1436     if (unformat (input, "%U", unformat_vnet_hw_interface, vnm, &hw_if_index)) {
1437       vec_add1 (hw_if_indices, hw_if_index);
1438       vlib_cli_output(vm, "add %d", hw_if_index);
1439     }
1440     else if (unformat (input, "descriptors") || unformat (input, "desc") )
1441       show_descr = 1;
1442     else {
1443       error = clib_error_return (0, "unknown input `%U'",
1444                                      format_unformat_error, input);
1445       goto done;
1446     }
1447   }
1448   if (vec_len (hw_if_indices) == 0) {
1449     vec_foreach (xd, dm->devices) {
1450       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER && xd->vu_intf->active)
1451         vec_add1(hw_if_indices, xd->vlib_hw_if_index);
1452     }
1453   }
1454
1455   vlib_cli_output (vm, "DPDK vhost-user interfaces");
1456   vlib_cli_output (vm, "Global:\n  coalesce frames %d time %e\n\n",
1457                    dm->vhost_coalesce_frames, dm->vhost_coalesce_time);
1458
1459   for (i = 0; i < vec_len (hw_if_indices); i++) {
1460     hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
1461
1462     if (!(xd = dpdk_vhost_user_device_from_hw_if_index(hw_if_indices[i]))) {
1463         error = clib_error_return (0, "not dpdk vhost-user interface: '%s'",
1464                                        hi->name);
1465         goto done;
1466     }
1467     vui = xd->vu_intf;
1468     vhost_dev = &xd->vu_vhost_dev;
1469     mem = vhost_dev->mem;
1470     u32 virtio_net_hdr_sz = (vui->num_vrings > 0 ?
1471             vhost_dev->virtqueue[0]->vhost_hlen : 0);
1472
1473     vlib_cli_output (vm, "Interface: %s (ifindex %d)",
1474                          hi->name, hw_if_indices[i]);
1475
1476     vlib_cli_output (vm, "virtio_net_hdr_sz %d\n features (0x%llx): \n",
1477                          virtio_net_hdr_sz, xd->vu_vhost_dev.features);
1478
1479     feat_entry = (struct feat_struct *) &feat_array;
1480     while(feat_entry->str) {
1481       if (xd->vu_vhost_dev.features & (1 << feat_entry->bit))
1482         vlib_cli_output (vm, "   %s (%d)", feat_entry->str, feat_entry->bit);
1483       feat_entry++;
1484     }
1485
1486     vlib_cli_output (vm, "\n");
1487
1488     vlib_cli_output (vm, " socket filename %s type %s errno \"%s\"\n\n",
1489                          vui->sock_filename, vui->sock_is_server ? "server" : "client",
1490                          strerror(vui->sock_errno));
1491
1492     vlib_cli_output (vm, " Memory regions (total %d)\n", mem->nregions);
1493
1494     if (mem->nregions){
1495       vlib_cli_output(vm, " region fd    guest_phys_addr    memory_size        userspace_addr     mmap_offset        mmap_addr\n");
1496       vlib_cli_output(vm, " ====== ===== ================== ================== ================== ================== ==================\n");
1497     }
1498     for (j = 0; j < mem->nregions; j++) {
1499       vlib_cli_output(vm, "  %d     %-5d 0x%016lx 0x%016lx 0x%016lx 0x%016lx 0x%016lx\n", j,
1500         vui->region_fd[j],
1501         mem->regions[j].guest_phys_address,
1502         mem->regions[j].memory_size,
1503         mem->regions[j].userspace_address,
1504         mem->regions[j].address_offset,
1505         vui->region_addr[j]);
1506     }
1507     for (q = 0; q < vui->num_vrings; q++) {
1508       struct vhost_virtqueue *vq = vhost_dev->virtqueue[q];
1509
1510       vlib_cli_output(vm, "\n Virtqueue %d\n", q);
1511
1512       vlib_cli_output(vm, "  qsz %d last_used_idx %d last_used_idx_res %d\n",
1513               vq->size, vq->last_used_idx, vq->last_used_idx_res);
1514
1515       if (vq->avail && vq->used)
1516         vlib_cli_output(vm, "  avail.flags %x avail.idx %d used.flags %x used.idx %d\n",
1517           vq->avail->flags, vq->avail->idx, vq->used->flags, vq->used->idx);
1518
1519       vlib_cli_output(vm, "  kickfd %d callfd %d errfd %d\n",
1520         vui->vrings[q].kickfd,
1521         vui->vrings[q].callfd,
1522         vui->vrings[q].errfd);
1523
1524       if (show_descr) {
1525         vlib_cli_output(vm, "\n  descriptor table:\n");
1526         vlib_cli_output(vm, "   id          addr         len  flags  next      user_addr\n");
1527         vlib_cli_output(vm, "  ===== ================== ===== ====== ===== ==================\n");
1528         for(j = 0; j < vq->size; j++) {
1529           vlib_cli_output(vm, "  %-5d 0x%016lx %-5d 0x%04x %-5d 0x%016lx\n",
1530             j,
1531             vq->desc[j].addr,
1532             vq->desc[j].len,
1533             vq->desc[j].flags,
1534             vq->desc[j].next,
1535             (u64) map_guest_mem(xd, vq->desc[j].addr));}
1536       }
1537     }
1538     vlib_cli_output (vm, "\n");
1539   }
1540 done:
1541   vec_free (hw_if_indices);
1542   return error;
1543 }
1544
1545 VLIB_CLI_COMMAND (show_vhost_user_command, static) = {
1546     .path = "show vhost-user",
1547     .short_help = "show vhost-user interface",
1548     .function = show_dpdk_vhost_user_command_fn,
1549 };
1550