misc: remove GNU Indent directives
[vpp.git] / src / plugins / vhost / vhost_user.c
1 /*
2  *------------------------------------------------------------------
3  * vhost.c - vhost-user
4  *
5  * Copyright (c) 2014-2018 Cisco and/or its affiliates.
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at:
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *------------------------------------------------------------------
18  */
19
20 #include <fcntl.h>              /* for open */
21 #include <sys/ioctl.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/uio.h>            /* for iovec */
27 #include <netinet/in.h>
28 #include <sys/vfs.h>
29
30 #include <linux/if_arp.h>
31 #include <linux/if_tun.h>
32
33 #include <vlib/vlib.h>
34 #include <vlib/unix/unix.h>
35
36 #include <vnet/ethernet/ethernet.h>
37 #include <vnet/devices/devices.h>
38 #include <vnet/feature/feature.h>
39 #include <vnet/interface/rx_queue_funcs.h>
40 #include <vnet/interface/tx_queue_funcs.h>
41
42 #include <vhost/vhost_user.h>
43 #include <vhost/vhost_user_inline.h>
44
45 /**
46  * @file
47  * @brief vHost User Device Driver.
48  *
49  * This file contains the source code for vHost User interface.
50  */
51
52
53 vlib_node_registration_t vhost_user_send_interrupt_node;
54
55 vhost_user_main_t vhost_user_main = {
56   .mtu_bytes = 1518,
57 };
58
59 VNET_HW_INTERFACE_CLASS (vhost_interface_class, static) = {
60   .name = "vhost-user",
61 };
62
63 static long
64 get_huge_page_size (int fd)
65 {
66   struct statfs s;
67   fstatfs (fd, &s);
68   return s.f_bsize;
69 }
70
71 static void
72 unmap_all_mem_regions (vhost_user_intf_t * vui)
73 {
74   int i, r, q;
75   vhost_user_vring_t *vq;
76
77   for (i = 0; i < vui->nregions; i++)
78     {
79       if (vui->region_mmap_addr[i] != MAP_FAILED)
80         {
81
82           long page_sz = get_huge_page_size (vui->region_mmap_fd[i]);
83
84           ssize_t map_sz = (vui->regions[i].memory_size +
85                             vui->regions[i].mmap_offset +
86                             page_sz - 1) & ~(page_sz - 1);
87
88           r =
89             munmap (vui->region_mmap_addr[i] - vui->regions[i].mmap_offset,
90                     map_sz);
91
92           vu_log_debug (vui, "unmap memory region %d addr 0x%lx len 0x%lx "
93                         "page_sz 0x%x", i, vui->region_mmap_addr[i], map_sz,
94                         page_sz);
95
96           vui->region_mmap_addr[i] = MAP_FAILED;
97
98           if (r == -1)
99             {
100               vu_log_err (vui, "failed to unmap memory region (errno %d)",
101                           errno);
102             }
103           close (vui->region_mmap_fd[i]);
104         }
105     }
106   vui->nregions = 0;
107
108   FOR_ALL_VHOST_RX_TXQ (q, vui)
109   {
110     vq = &vui->vrings[q];
111     vq->avail = 0;
112     vq->used = 0;
113     vq->desc = 0;
114   }
115 }
116
117 static_always_inline void
118 vhost_user_tx_thread_placement (vhost_user_intf_t *vui, u32 qid)
119 {
120   vnet_main_t *vnm = vnet_get_main ();
121   vhost_user_vring_t *rxvq = &vui->vrings[qid];
122   u32 q = qid >> 1, rxvq_count;
123
124   ASSERT ((qid & 1) == 0);
125   if (!rxvq->started || !rxvq->enabled)
126     return;
127
128   rxvq_count = (qid >> 1) + 1;
129   if (rxvq->queue_index == ~0)
130     {
131       rxvq->queue_index =
132         vnet_hw_if_register_tx_queue (vnm, vui->hw_if_index, q);
133       rxvq->qid = q;
134     }
135
136   FOR_ALL_VHOST_RXQ (q, vui)
137   {
138     vhost_user_vring_t *rxvq = &vui->vrings[q];
139     u32 qi = rxvq->queue_index;
140
141     if (rxvq->queue_index == ~0)
142       break;
143     for (u32 i = 0; i < vlib_get_n_threads (); i++)
144       vnet_hw_if_tx_queue_unassign_thread (vnm, qi, i);
145   }
146
147   for (u32 i = 0; i < vlib_get_n_threads (); i++)
148     {
149       vhost_user_vring_t *rxvq =
150         &vui->vrings[VHOST_VRING_IDX_RX (i % rxvq_count)];
151       u32 qi = rxvq->queue_index;
152
153       vnet_hw_if_tx_queue_assign_thread (vnm, qi, i);
154     }
155
156   vnet_hw_if_update_runtime_data (vnm, vui->hw_if_index);
157 }
158
159 /**
160  * @brief Unassign existing interface/queue to thread mappings and re-assign
161  * new interface/queue to thread mappings
162  */
163 static_always_inline void
164 vhost_user_rx_thread_placement (vhost_user_intf_t * vui, u32 qid)
165 {
166   vhost_user_vring_t *txvq = &vui->vrings[qid];
167   vnet_main_t *vnm = vnet_get_main ();
168   int rv;
169   u32 q = qid >> 1;
170   vhost_user_main_t *vum = &vhost_user_main;
171
172   ASSERT ((qid & 1) == 1);      // should be odd
173   // Assign new queue mappings for the interface
174   if (txvq->queue_index != ~0)
175     return;
176   vnet_hw_if_set_input_node (vnm, vui->hw_if_index,
177                              vhost_user_input_node.index);
178   txvq->queue_index = vnet_hw_if_register_rx_queue (vnm, vui->hw_if_index, q,
179                                                     VNET_HW_IF_RXQ_THREAD_ANY);
180   txvq->thread_index =
181     vnet_hw_if_get_rx_queue_thread_index (vnm, txvq->queue_index);
182
183   if (txvq->mode == VNET_HW_IF_RX_MODE_UNKNOWN)
184     /* Set polling as the default */
185     txvq->mode = VNET_HW_IF_RX_MODE_POLLING;
186   if (txvq->mode == VNET_HW_IF_RX_MODE_POLLING)
187     {
188       vhost_cpu_t *cpu = vec_elt_at_index (vum->cpus, txvq->thread_index);
189       /* Keep a polling queue count for each thread */
190       cpu->polling_q_count++;
191     }
192   txvq->qid = q;
193   rv = vnet_hw_if_set_rx_queue_mode (vnm, txvq->queue_index, txvq->mode);
194   if (rv)
195     vu_log_warn (vui, "unable to set rx mode for interface %d, "
196                  "queue %d: rc=%d", vui->hw_if_index, q, rv);
197   vnet_hw_if_update_runtime_data (vnm, vui->hw_if_index);
198 }
199
200 /** @brief Returns whether at least one TX and one RX vring are enabled */
201 static_always_inline int
202 vhost_user_intf_ready (vhost_user_intf_t * vui)
203 {
204   int i, found[2] = { };        //RX + TX
205
206   for (i = 0; i < vui->num_qid; i++)
207     if (vui->vrings[i].started && vui->vrings[i].enabled)
208       found[i & 1] = 1;
209
210   return found[0] && found[1];
211 }
212
213 static_always_inline void
214 vhost_user_update_iface_state (vhost_user_intf_t * vui)
215 {
216   /* if we have pointers to descriptor table, go up */
217   int is_ready = vhost_user_intf_ready (vui);
218   if (is_ready != vui->is_ready)
219     {
220       vu_log_debug (vui, "interface %d %s", vui->sw_if_index,
221                     is_ready ? "ready" : "down");
222       if (vui->admin_up)
223         vnet_hw_interface_set_flags (vnet_get_main (), vui->hw_if_index,
224                                      is_ready ? VNET_HW_INTERFACE_FLAG_LINK_UP
225                                      : 0);
226       vui->is_ready = is_ready;
227     }
228 }
229
230 static clib_error_t *
231 vhost_user_callfd_read_ready (clib_file_t * uf)
232 {
233   __attribute__ ((unused)) int n;
234   u8 buff[8];
235
236   n = read (uf->file_descriptor, ((char *) &buff), 8);
237
238   return 0;
239 }
240
241 static_always_inline void
242 vhost_user_thread_placement (vhost_user_intf_t * vui, u32 qid)
243 {
244   if (qid & 1)                  // RX is odd, TX is even
245     {
246       if (vui->vrings[qid].queue_index == ~0)
247         vhost_user_rx_thread_placement (vui, qid);
248     }
249   else
250     vhost_user_tx_thread_placement (vui, qid);
251 }
252
253 static clib_error_t *
254 vhost_user_kickfd_read_ready (clib_file_t * uf)
255 {
256   __attribute__ ((unused)) ssize_t n;
257   u8 buff[8];
258   vhost_user_main_t *vum = &vhost_user_main;
259   vhost_user_intf_t *vui =
260     pool_elt_at_index (vum->vhost_user_interfaces, uf->private_data >> 8);
261   u32 qid = uf->private_data & 0xff;
262   u32 is_txq = qid & 1;
263   vhost_user_vring_t *vq = &vui->vrings[qid];
264   vnet_main_t *vnm = vnet_get_main ();
265
266   n = read (uf->file_descriptor, buff, 8);
267   if (vq->started == 0)
268     {
269       vq->started = 1;
270       vhost_user_thread_placement (vui, qid);
271       vhost_user_update_iface_state (vui);
272       if (is_txq)
273         vnet_hw_if_set_rx_queue_file_index (vnm, vq->queue_index,
274                                             vq->kickfd_idx);
275     }
276
277   if (is_txq && (vq->mode != VNET_HW_IF_RX_MODE_POLLING) &&
278       vhost_user_intf_ready (vui))
279     {
280       vhost_cpu_t *cpu = vec_elt_at_index (vum->cpus, vq->thread_index);
281       /*
282        * If the thread has more than 1 queue and the other queue is in polling
283        * mode, there is no need to trigger an interrupt
284        */
285       if (cpu->polling_q_count == 0)
286         vnet_hw_if_rx_queue_set_int_pending (vnm, vq->queue_index);
287     }
288
289   return 0;
290 }
291
292 static_always_inline void
293 vhost_user_vring_init (vhost_user_intf_t * vui, u32 qid)
294 {
295   vhost_user_vring_t *vring = &vui->vrings[qid];
296
297   clib_memset (vring, 0, sizeof (*vring));
298   vring->kickfd_idx = ~0;
299   vring->callfd_idx = ~0;
300   vring->errfd = -1;
301   vring->qid = -1;
302   vring->queue_index = ~0;
303   vring->thread_index = ~0;
304   vring->mode = VNET_HW_IF_RX_MODE_POLLING;
305
306   clib_spinlock_init (&vring->vring_lock);
307
308   /*
309    * We have a bug with some qemu 2.5, and this may be a fix.
310    * Feel like interpretation holy text, but this is from vhost-user.txt.
311    * "
312    * One queue pair is enabled initially. More queues are enabled
313    * dynamically, by sending message VHOST_USER_SET_VRING_ENABLE.
314    * "
315    * Don't know who's right, but this is what DPDK does.
316    */
317   if (qid == 0 || qid == 1)
318     vring->enabled = 1;
319 }
320
321 static_always_inline void
322 vhost_user_vring_close (vhost_user_intf_t * vui, u32 qid)
323 {
324   vhost_user_vring_t *vring = &vui->vrings[qid];
325
326   if (vring->kickfd_idx != ~0)
327     {
328       clib_file_t *uf = pool_elt_at_index (file_main.file_pool,
329                                            vring->kickfd_idx);
330       clib_file_del (&file_main, uf);
331       vring->kickfd_idx = ~0;
332     }
333   if (vring->callfd_idx != ~0)
334     {
335       clib_file_t *uf = pool_elt_at_index (file_main.file_pool,
336                                            vring->callfd_idx);
337       clib_file_del (&file_main, uf);
338       vring->callfd_idx = ~0;
339     }
340   if (vring->errfd != -1)
341     {
342       close (vring->errfd);
343       vring->errfd = -1;
344     }
345
346   clib_spinlock_free (&vring->vring_lock);
347
348   // save the needed information in vrings prior to being wiped out
349   u16 q = vui->vrings[qid].qid;
350   u32 queue_index = vui->vrings[qid].queue_index;
351   u32 mode = vui->vrings[qid].mode;
352   u32 thread_index = vui->vrings[qid].thread_index;
353   vhost_user_vring_init (vui, qid);
354   vui->vrings[qid].qid = q;
355   vui->vrings[qid].queue_index = queue_index;
356   vui->vrings[qid].mode = mode;
357   vui->vrings[qid].thread_index = thread_index;
358 }
359
360 static_always_inline void
361 vhost_user_if_disconnect (vhost_user_intf_t * vui)
362 {
363   vnet_main_t *vnm = vnet_get_main ();
364   int q;
365
366   vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
367
368   if (vui->clib_file_index != ~0)
369     {
370       clib_file_del (&file_main, file_main.file_pool + vui->clib_file_index);
371       vui->clib_file_index = ~0;
372     }
373
374   vui->is_ready = 0;
375
376   FOR_ALL_VHOST_RX_TXQ (q, vui) { vhost_user_vring_close (vui, q); }
377
378   unmap_all_mem_regions (vui);
379   vu_log_debug (vui, "interface ifindex %d disconnected", vui->sw_if_index);
380 }
381
382 void
383 vhost_user_set_operation_mode (vhost_user_intf_t *vui,
384                                vhost_user_vring_t *txvq)
385 {
386   if (vhost_user_is_packed_ring_supported (vui))
387     {
388       if (txvq->used_event)
389         {
390           if (txvq->mode == VNET_HW_IF_RX_MODE_POLLING)
391             txvq->used_event->flags = VRING_EVENT_F_DISABLE;
392           else
393             txvq->used_event->flags = 0;
394         }
395     }
396   else
397     {
398       if (txvq->used)
399         {
400           if (txvq->mode == VNET_HW_IF_RX_MODE_POLLING)
401             txvq->used->flags = VRING_USED_F_NO_NOTIFY;
402           else
403             txvq->used->flags = 0;
404         }
405     }
406 }
407
408 static clib_error_t *
409 vhost_user_socket_read (clib_file_t * uf)
410 {
411   int n, i, j;
412   int fd, number_of_fds = 0;
413   int fds[VHOST_MEMORY_MAX_NREGIONS];
414   vhost_user_msg_t msg;
415   struct msghdr mh;
416   struct iovec iov[1];
417   vhost_user_main_t *vum = &vhost_user_main;
418   vhost_user_intf_t *vui;
419   struct cmsghdr *cmsg;
420   u8 q;
421   clib_file_t template = { 0 };
422   vnet_main_t *vnm = vnet_get_main ();
423   vlib_main_t *vm = vlib_get_main ();
424
425   vui = pool_elt_at_index (vum->vhost_user_interfaces, uf->private_data);
426
427   char control[CMSG_SPACE (VHOST_MEMORY_MAX_NREGIONS * sizeof (int))];
428
429   clib_memset (&mh, 0, sizeof (mh));
430   clib_memset (control, 0, sizeof (control));
431
432   for (i = 0; i < VHOST_MEMORY_MAX_NREGIONS; i++)
433     fds[i] = -1;
434
435   /* set the payload */
436   iov[0].iov_base = (void *) &msg;
437   iov[0].iov_len = VHOST_USER_MSG_HDR_SZ;
438
439   mh.msg_iov = iov;
440   mh.msg_iovlen = 1;
441   mh.msg_control = control;
442   mh.msg_controllen = sizeof (control);
443
444   n = recvmsg (uf->file_descriptor, &mh, 0);
445
446   if (n != VHOST_USER_MSG_HDR_SZ)
447     {
448       if (n == -1)
449         {
450           vu_log_debug (vui, "recvmsg returned error %d %s", errno,
451                         strerror (errno));
452         }
453       else
454         {
455           vu_log_debug (vui, "n (%d) != VHOST_USER_MSG_HDR_SZ (%d)",
456                         n, VHOST_USER_MSG_HDR_SZ);
457         }
458       goto close_socket;
459     }
460
461   if (mh.msg_flags & MSG_CTRUNC)
462     {
463       vu_log_debug (vui, "MSG_CTRUNC is set");
464       goto close_socket;
465     }
466
467   cmsg = CMSG_FIRSTHDR (&mh);
468
469   if (cmsg && (cmsg->cmsg_len > 0) && (cmsg->cmsg_level == SOL_SOCKET) &&
470       (cmsg->cmsg_type == SCM_RIGHTS) &&
471       (cmsg->cmsg_len - CMSG_LEN (0) <=
472        VHOST_MEMORY_MAX_NREGIONS * sizeof (int)))
473     {
474       number_of_fds = (cmsg->cmsg_len - CMSG_LEN (0)) / sizeof (int);
475       clib_memcpy_fast (fds, CMSG_DATA (cmsg), number_of_fds * sizeof (int));
476     }
477
478   /* version 1, no reply bit set */
479   if ((msg.flags & 7) != 1)
480     {
481       vu_log_debug (vui, "malformed message received. closing socket");
482       goto close_socket;
483     }
484
485   {
486     int rv;
487     rv =
488       read (uf->file_descriptor, ((char *) &msg) + VHOST_USER_MSG_HDR_SZ,
489             msg.size);
490     if (rv < 0)
491       {
492         vu_log_debug (vui, "read failed %s", strerror (errno));
493         goto close_socket;
494       }
495     else if (rv != msg.size)
496       {
497         vu_log_debug (vui, "message too short (read %dB should be %dB)", rv,
498                       msg.size);
499         goto close_socket;
500       }
501   }
502
503   switch (msg.request)
504     {
505     case VHOST_USER_GET_FEATURES:
506       msg.flags |= 4;
507       msg.u64 = VIRTIO_FEATURE (VIRTIO_NET_F_MRG_RXBUF) |
508         VIRTIO_FEATURE (VIRTIO_NET_F_CTRL_VQ) |
509         VIRTIO_FEATURE (VIRTIO_F_ANY_LAYOUT) |
510         VIRTIO_FEATURE (VIRTIO_RING_F_INDIRECT_DESC) |
511         VIRTIO_FEATURE (VHOST_F_LOG_ALL) |
512         VIRTIO_FEATURE (VIRTIO_NET_F_GUEST_ANNOUNCE) |
513         VIRTIO_FEATURE (VIRTIO_NET_F_MQ) |
514         VIRTIO_FEATURE (VHOST_USER_F_PROTOCOL_FEATURES) |
515         VIRTIO_FEATURE (VIRTIO_F_VERSION_1);
516       msg.u64 &= vui->feature_mask;
517
518       if (vui->enable_event_idx)
519         msg.u64 |= VIRTIO_FEATURE (VIRTIO_RING_F_EVENT_IDX);
520       if (vui->enable_gso)
521         msg.u64 |= FEATURE_VIRTIO_NET_F_HOST_GUEST_TSO_FEATURE_BITS;
522       if (vui->enable_packed)
523         msg.u64 |= VIRTIO_FEATURE (VIRTIO_F_RING_PACKED);
524
525       msg.size = sizeof (msg.u64);
526       vu_log_debug (vui, "if %d msg VHOST_USER_GET_FEATURES - reply "
527                     "0x%016llx", vui->hw_if_index, msg.u64);
528       n =
529         send (uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
530       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
531         {
532           vu_log_debug (vui, "could not send message response");
533           goto close_socket;
534         }
535       break;
536
537     case VHOST_USER_SET_FEATURES:
538       vu_log_debug (vui, "if %d msg VHOST_USER_SET_FEATURES features "
539                     "0x%016llx", vui->hw_if_index, msg.u64);
540
541       vui->features = msg.u64;
542
543       if (vui->features &
544           (VIRTIO_FEATURE (VIRTIO_NET_F_MRG_RXBUF) |
545            VIRTIO_FEATURE (VIRTIO_F_VERSION_1)))
546         vui->virtio_net_hdr_sz = 12;
547       else
548         vui->virtio_net_hdr_sz = 10;
549
550       vui->is_any_layout =
551         (vui->features & VIRTIO_FEATURE (VIRTIO_F_ANY_LAYOUT)) ? 1 : 0;
552
553       ASSERT (vui->virtio_net_hdr_sz < VLIB_BUFFER_PRE_DATA_SIZE);
554       if (vui->enable_gso &&
555           ((vui->features & FEATURE_VIRTIO_NET_F_HOST_GUEST_TSO_FEATURE_BITS)
556            == FEATURE_VIRTIO_NET_F_HOST_GUEST_TSO_FEATURE_BITS))
557         {
558           vnet_hw_if_set_caps (vnm, vui->hw_if_index,
559                                VNET_HW_IF_CAP_TCP_GSO |
560                                  VNET_HW_IF_CAP_TX_TCP_CKSUM |
561                                  VNET_HW_IF_CAP_TX_UDP_CKSUM);
562         }
563       else
564         {
565           vnet_hw_if_unset_caps (vnm, vui->hw_if_index,
566                                  VNET_HW_IF_CAP_TCP_GSO |
567                                    VNET_HW_IF_CAP_L4_TX_CKSUM);
568         }
569       vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
570       vui->is_ready = 0;
571       vhost_user_update_iface_state (vui);
572       break;
573
574     case VHOST_USER_SET_MEM_TABLE:
575       vu_log_debug (vui, "if %d msg VHOST_USER_SET_MEM_TABLE nregions %d",
576                     vui->hw_if_index, msg.memory.nregions);
577
578       if ((msg.memory.nregions < 1) ||
579           (msg.memory.nregions > VHOST_MEMORY_MAX_NREGIONS))
580         {
581           vu_log_debug (vui, "number of mem regions must be between 1 and %i",
582                         VHOST_MEMORY_MAX_NREGIONS);
583           goto close_socket;
584         }
585
586       if (msg.memory.nregions != number_of_fds)
587         {
588           vu_log_debug (vui, "each memory region must have FD");
589           goto close_socket;
590         }
591
592       /* Do the mmap without barrier sync */
593       void *region_mmap_addr[VHOST_MEMORY_MAX_NREGIONS];
594       for (i = 0; i < msg.memory.nregions; i++)
595         {
596           long page_sz = get_huge_page_size (fds[i]);
597
598           /* align size to page */
599           ssize_t map_sz = (msg.memory.regions[i].memory_size +
600                             msg.memory.regions[i].mmap_offset +
601                             page_sz - 1) & ~(page_sz - 1);
602
603           region_mmap_addr[i] = mmap (0, map_sz, PROT_READ | PROT_WRITE,
604                                       MAP_SHARED, fds[i], 0);
605           if (region_mmap_addr[i] == MAP_FAILED)
606             {
607               vu_log_err (vui, "failed to map memory. errno is %d", errno);
608               for (j = 0; j < i; j++)
609                 munmap (region_mmap_addr[j], map_sz);
610               goto close_socket;
611             }
612           vu_log_debug (vui, "map memory region %d addr 0 len 0x%lx fd %d "
613                         "mapped 0x%lx page_sz 0x%x", i, map_sz, fds[i],
614                         region_mmap_addr[i], page_sz);
615         }
616
617       vlib_worker_thread_barrier_sync (vm);
618       unmap_all_mem_regions (vui);
619       for (i = 0; i < msg.memory.nregions; i++)
620         {
621           clib_memcpy_fast (&(vui->regions[i]), &msg.memory.regions[i],
622                             sizeof (vhost_user_memory_region_t));
623
624           vui->region_mmap_addr[i] = region_mmap_addr[i];
625           vui->region_guest_addr_lo[i] = vui->regions[i].guest_phys_addr;
626           vui->region_guest_addr_hi[i] = vui->regions[i].guest_phys_addr +
627             vui->regions[i].memory_size;
628
629           vui->region_mmap_addr[i] += vui->regions[i].mmap_offset;
630           vui->region_mmap_fd[i] = fds[i];
631
632           vui->nregions++;
633         }
634
635       /*
636        * Re-compute desc, used, and avail descriptor table if vring address
637        * is set.
638        */
639       FOR_ALL_VHOST_RX_TXQ (q, vui)
640       {
641         if (vui->vrings[q].desc_user_addr && vui->vrings[q].used_user_addr &&
642             vui->vrings[q].avail_user_addr)
643           {
644             vui->vrings[q].desc =
645               map_user_mem (vui, vui->vrings[q].desc_user_addr);
646             vui->vrings[q].used =
647               map_user_mem (vui, vui->vrings[q].used_user_addr);
648             vui->vrings[q].avail =
649               map_user_mem (vui, vui->vrings[q].avail_user_addr);
650           }
651       }
652       vlib_worker_thread_barrier_release (vm);
653       break;
654
655     case VHOST_USER_SET_VRING_NUM:
656       vu_log_debug (vui, "if %d msg VHOST_USER_SET_VRING_NUM idx %d num %d",
657                     vui->hw_if_index, msg.state.index, msg.state.num);
658
659       if ((msg.state.num > 32768) ||    /* maximum ring size is 32768 */
660           (msg.state.num == 0) ||       /* it cannot be zero */
661           ((msg.state.num - 1) & msg.state.num) ||      /* must be power of 2 */
662           (msg.state.index >= vui->num_qid))
663         {
664           vu_log_debug (vui, "invalid VHOST_USER_SET_VRING_NUM: msg.state.num"
665                         " %d, msg.state.index %d, curruent max q %d",
666                         msg.state.num, msg.state.index, vui->num_qid);
667           goto close_socket;
668         }
669       vui->vrings[msg.state.index].qsz_mask = msg.state.num - 1;
670       break;
671
672     case VHOST_USER_SET_VRING_ADDR:
673       vu_log_debug (vui, "if %d msg VHOST_USER_SET_VRING_ADDR idx %d",
674                     vui->hw_if_index, msg.state.index);
675
676       if (msg.state.index >= vui->num_qid)
677         {
678           vu_log_debug (vui, "invalid vring index VHOST_USER_SET_VRING_ADDR:"
679                         " %u >= %u", msg.state.index, vui->num_qid);
680           goto close_socket;
681         }
682
683       if (msg.size < sizeof (msg.addr))
684         {
685           vu_log_debug (vui, "vhost message is too short (%d < %d)",
686                         msg.size, sizeof (msg.addr));
687           goto close_socket;
688         }
689
690       vnet_virtio_vring_desc_t *desc =
691         map_user_mem (vui, msg.addr.desc_user_addr);
692       vnet_virtio_vring_used_t *used =
693         map_user_mem (vui, msg.addr.used_user_addr);
694       vnet_virtio_vring_avail_t *avail =
695         map_user_mem (vui, msg.addr.avail_user_addr);
696
697       if ((desc == NULL) || (used == NULL) || (avail == NULL))
698         {
699           vu_log_debug (vui, "failed to map user memory for hw_if_index %d",
700                         vui->hw_if_index);
701           goto close_socket;
702         }
703
704       vui->vrings[msg.state.index].desc_user_addr = msg.addr.desc_user_addr;
705       vui->vrings[msg.state.index].used_user_addr = msg.addr.used_user_addr;
706       vui->vrings[msg.state.index].avail_user_addr = msg.addr.avail_user_addr;
707
708       vlib_worker_thread_barrier_sync (vm);
709       vui->vrings[msg.state.index].desc = desc;
710       vui->vrings[msg.state.index].used = used;
711       vui->vrings[msg.state.index].avail = avail;
712
713       vui->vrings[msg.state.index].log_guest_addr = msg.addr.log_guest_addr;
714       vui->vrings[msg.state.index].log_used =
715         (msg.addr.flags & (1 << VHOST_VRING_F_LOG)) ? 1 : 0;
716
717       /* Spec says: If VHOST_USER_F_PROTOCOL_FEATURES has not been negotiated,
718          the ring is initialized in an enabled state. */
719       if (!(vui->features & VIRTIO_FEATURE (VHOST_USER_F_PROTOCOL_FEATURES)))
720         vui->vrings[msg.state.index].enabled = 1;
721
722       vui->vrings[msg.state.index].last_used_idx =
723         vui->vrings[msg.state.index].last_avail_idx =
724         vui->vrings[msg.state.index].used->idx;
725       vui->vrings[msg.state.index].last_kick =
726         vui->vrings[msg.state.index].last_used_idx;
727
728       /* tell driver that we want interrupts or not */
729       vhost_user_set_operation_mode (vui, &vui->vrings[msg.state.index]);
730       vlib_worker_thread_barrier_release (vm);
731       vhost_user_update_iface_state (vui);
732       break;
733
734     case VHOST_USER_SET_OWNER:
735       vu_log_debug (vui, "if %d msg VHOST_USER_SET_OWNER", vui->hw_if_index);
736       break;
737
738     case VHOST_USER_RESET_OWNER:
739       vu_log_debug (vui, "if %d msg VHOST_USER_RESET_OWNER",
740                     vui->hw_if_index);
741       break;
742
743     case VHOST_USER_SET_VRING_CALL:
744       vu_log_debug (vui, "if %d msg VHOST_USER_SET_VRING_CALL %d",
745                     vui->hw_if_index, msg.u64);
746
747       q = (u8) (msg.u64 & 0xFF);
748       if (vui->num_qid > q)
749         {
750           /* if there is old fd, delete and close it */
751           if (vui->vrings[q].callfd_idx != ~0)
752             {
753               clib_file_t *uf = pool_elt_at_index (file_main.file_pool,
754                                                    vui->vrings[q].callfd_idx);
755               clib_file_del (&file_main, uf);
756               vui->vrings[q].callfd_idx = ~0;
757             }
758         }
759       else if (vec_len (vui->vrings) > q)
760         {
761           /* grow vrings by pair (RX + TX) */
762           vui->num_qid = (q & 1) ? (q + 1) : (q + 2);
763         }
764       else
765         {
766           u32 i, new_max_q, old_max_q = vec_len (vui->vrings);
767
768           /*
769            * Double the array size if it is less than 64 entries.
770            * Slow down thereafter.
771            */
772           if (vec_len (vui->vrings) < (VHOST_VRING_INIT_MQ_PAIR_SZ << 3))
773             new_max_q = vec_len (vui->vrings) << 1;
774           else
775             new_max_q = vec_len (vui->vrings) +
776               (VHOST_VRING_INIT_MQ_PAIR_SZ << 2);
777           if (new_max_q > (VHOST_VRING_MAX_MQ_PAIR_SZ << 1))
778             new_max_q = (VHOST_VRING_MAX_MQ_PAIR_SZ << 1);
779
780           /* sync with the worker threads, vrings may move due to realloc */
781           vlib_worker_thread_barrier_sync (vm);
782           vec_validate_aligned (vui->vrings, new_max_q - 1,
783                                 CLIB_CACHE_LINE_BYTES);
784           vlib_worker_thread_barrier_release (vm);
785
786           for (i = old_max_q; i < vec_len (vui->vrings); i++)
787             vhost_user_vring_init (vui, i);
788
789           /* grow vrings by pair (RX + TX) */
790           vui->num_qid = (q & 1) ? (q + 1) : (q + 2);
791         }
792
793       if (!(msg.u64 & VHOST_USER_VRING_NOFD_MASK))
794         {
795           if (number_of_fds != 1)
796             {
797               vu_log_debug (vui, "More than one fd received !");
798               goto close_socket;
799             }
800
801           template.read_function = vhost_user_callfd_read_ready;
802           template.file_descriptor = fds[0];
803           template.private_data =
804             ((vui - vhost_user_main.vhost_user_interfaces) << 8) + q;
805           template.description = format (0, "vhost user");
806           vui->vrings[q].callfd_idx = clib_file_add (&file_main, &template);
807         }
808       else
809         vui->vrings[q].callfd_idx = ~0;
810       break;
811
812     case VHOST_USER_SET_VRING_KICK:
813       vu_log_debug (vui, "if %d msg VHOST_USER_SET_VRING_KICK %d",
814                     vui->hw_if_index, msg.u64);
815
816       q = (u8) (msg.u64 & 0xFF);
817       if (q >= vui->num_qid)
818         {
819           vu_log_debug (vui, "invalid vring index VHOST_USER_SET_VRING_KICK:"
820                         " %u >= %u", q, vui->num_qid);
821           goto close_socket;
822         }
823
824       if (vui->vrings[q].kickfd_idx != ~0)
825         {
826           clib_file_t *uf = pool_elt_at_index (file_main.file_pool,
827                                                vui->vrings[q].kickfd_idx);
828           clib_file_del (&file_main, uf);
829           vui->vrings[q].kickfd_idx = ~0;
830         }
831
832       if (!(msg.u64 & VHOST_USER_VRING_NOFD_MASK))
833         {
834           if (number_of_fds != 1)
835             {
836               vu_log_debug (vui, "More than one fd received !");
837               goto close_socket;
838             }
839
840           template.read_function = vhost_user_kickfd_read_ready;
841           template.file_descriptor = fds[0];
842           template.private_data =
843             (((uword) (vui - vhost_user_main.vhost_user_interfaces)) << 8) +
844             q;
845           vui->vrings[q].kickfd_idx = clib_file_add (&file_main, &template);
846         }
847       else
848         {
849           //When no kickfd is set, the queue is initialized as started
850           vui->vrings[q].kickfd_idx = ~0;
851           vui->vrings[q].started = 1;
852           vhost_user_thread_placement (vui, q);
853         }
854       vhost_user_update_iface_state (vui);
855       break;
856
857     case VHOST_USER_SET_VRING_ERR:
858       vu_log_debug (vui, "if %d msg VHOST_USER_SET_VRING_ERR %d",
859                     vui->hw_if_index, msg.u64);
860
861       q = (u8) (msg.u64 & 0xFF);
862       if (q >= vui->num_qid)
863         {
864           vu_log_debug (vui, "invalid vring index VHOST_USER_SET_VRING_ERR:"
865                         " %u >= %u", q, vui->num_qid);
866           goto close_socket;
867         }
868
869       if (vui->vrings[q].errfd != -1)
870         close (vui->vrings[q].errfd);
871
872       if (!(msg.u64 & VHOST_USER_VRING_NOFD_MASK))
873         {
874           if (number_of_fds != 1)
875             goto close_socket;
876
877           vui->vrings[q].errfd = fds[0];
878         }
879       else
880         vui->vrings[q].errfd = -1;
881       break;
882
883     case VHOST_USER_SET_VRING_BASE:
884       vu_log_debug (vui,
885                     "if %d msg VHOST_USER_SET_VRING_BASE idx %d num 0x%x",
886                     vui->hw_if_index, msg.state.index, msg.state.num);
887       if (msg.state.index >= vui->num_qid)
888         {
889           vu_log_debug (vui, "invalid vring index VHOST_USER_SET_VRING_ADDR:"
890                         " %u >= %u", msg.state.index, vui->num_qid);
891           goto close_socket;
892         }
893       vlib_worker_thread_barrier_sync (vm);
894       vui->vrings[msg.state.index].last_avail_idx = msg.state.num;
895       if (vhost_user_is_packed_ring_supported (vui))
896         {
897           /*
898            *  0                   1                   2                   3
899            *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
900            * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
901            * |    last avail idx           | |     last used idx           | |
902            * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
903            *                                ^                               ^
904            *                                |                               |
905            *                         avail wrap counter       used wrap counter
906            */
907           /* last avail idx at bit 0-14. */
908           vui->vrings[msg.state.index].last_avail_idx =
909             msg.state.num & 0x7fff;
910           /* avail wrap counter at bit 15 */
911           vui->vrings[msg.state.index].avail_wrap_counter =
912             ! !(msg.state.num & (1 << 15));
913
914           /*
915            * Although last_used_idx is passed in the upper 16 bits in qemu
916            * implementation, in practice, last_avail_idx and last_used_idx are
917            * usually the same. As a result, DPDK does not bother to pass us
918            * last_used_idx. The spec is not clear on thex coding. I figured it
919            * out by reading the qemu code. So let's just read last_avail_idx
920            * and set last_used_idx equals to last_avail_idx.
921            */
922           vui->vrings[msg.state.index].last_used_idx =
923             vui->vrings[msg.state.index].last_avail_idx;
924           vui->vrings[msg.state.index].last_kick =
925             vui->vrings[msg.state.index].last_used_idx;
926           vui->vrings[msg.state.index].used_wrap_counter =
927             vui->vrings[msg.state.index].avail_wrap_counter;
928
929           if (vui->vrings[msg.state.index].avail_wrap_counter == 1)
930             vui->vrings[msg.state.index].avail_wrap_counter =
931               VRING_DESC_F_AVAIL;
932         }
933       vlib_worker_thread_barrier_release (vm);
934       break;
935
936     case VHOST_USER_GET_VRING_BASE:
937       if (msg.state.index >= vui->num_qid)
938         {
939           vu_log_debug (vui, "invalid vring index VHOST_USER_GET_VRING_BASE:"
940                         " %u >= %u", msg.state.index, vui->num_qid);
941           goto close_socket;
942         }
943
944       /* protection is needed to prevent rx/tx from changing last_avail_idx */
945       vlib_worker_thread_barrier_sync (vm);
946       /*
947        * Copy last_avail_idx from the vring before closing it because
948        * closing the vring also initializes the vring last_avail_idx
949        */
950       msg.state.num = vui->vrings[msg.state.index].last_avail_idx;
951       if (vhost_user_is_packed_ring_supported (vui))
952         {
953           msg.state.num =
954             (vui->vrings[msg.state.index].last_avail_idx & 0x7fff) |
955             (! !vui->vrings[msg.state.index].avail_wrap_counter << 15);
956           msg.state.num |=
957             ((vui->vrings[msg.state.index].last_used_idx & 0x7fff) |
958              (! !vui->vrings[msg.state.index].used_wrap_counter << 15)) << 16;
959         }
960       msg.flags |= 4;
961       msg.size = sizeof (msg.state);
962
963       /*
964        * Spec says: Client must [...] stop ring upon receiving
965        * VHOST_USER_GET_VRING_BASE
966        */
967       vhost_user_vring_close (vui, msg.state.index);
968       vlib_worker_thread_barrier_release (vm);
969       vu_log_debug (vui,
970                     "if %d msg VHOST_USER_GET_VRING_BASE idx %d num 0x%x",
971                     vui->hw_if_index, msg.state.index, msg.state.num);
972       n =
973         send (uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
974       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
975         {
976           vu_log_debug (vui, "could not send message response");
977           goto close_socket;
978         }
979       vhost_user_update_iface_state (vui);
980       break;
981
982     case VHOST_USER_NONE:
983       vu_log_debug (vui, "if %d msg VHOST_USER_NONE", vui->hw_if_index);
984       break;
985
986     case VHOST_USER_SET_LOG_BASE:
987       vu_log_debug (vui, "if %d msg VHOST_USER_SET_LOG_BASE",
988                     vui->hw_if_index);
989
990       if (msg.size != sizeof (msg.log))
991         {
992           vu_log_debug (vui, "invalid msg size for VHOST_USER_SET_LOG_BASE:"
993                         " %d instead of %d", msg.size, sizeof (msg.log));
994           goto close_socket;
995         }
996
997       if (!(vui->protocol_features & (1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD)))
998         {
999           vu_log_debug (vui, "VHOST_USER_PROTOCOL_F_LOG_SHMFD not set but "
1000                         "VHOST_USER_SET_LOG_BASE received");
1001           goto close_socket;
1002         }
1003
1004       fd = fds[0];
1005       /* align size to page */
1006       long page_sz = get_huge_page_size (fd);
1007       ssize_t map_sz =
1008         (msg.log.size + msg.log.offset + page_sz - 1) & ~(page_sz - 1);
1009
1010       void *log_base_addr = mmap (0, map_sz, PROT_READ | PROT_WRITE,
1011                                   MAP_SHARED, fd, 0);
1012
1013       vu_log_debug (vui, "map log region addr 0 len 0x%lx off 0x%lx fd %d "
1014                     "mapped 0x%lx", map_sz, msg.log.offset, fd,
1015                     log_base_addr);
1016
1017       if (log_base_addr == MAP_FAILED)
1018         {
1019           vu_log_err (vui, "failed to map memory. errno is %d", errno);
1020           goto close_socket;
1021         }
1022
1023       vlib_worker_thread_barrier_sync (vm);
1024       vui->log_base_addr = log_base_addr;
1025       vui->log_base_addr += msg.log.offset;
1026       vui->log_size = msg.log.size;
1027       vlib_worker_thread_barrier_release (vm);
1028
1029       msg.flags |= 4;
1030       msg.size = sizeof (msg.u64);
1031       n =
1032         send (uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
1033       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
1034         {
1035           vu_log_debug (vui, "could not send message response");
1036           goto close_socket;
1037         }
1038       break;
1039
1040     case VHOST_USER_SET_LOG_FD:
1041       vu_log_debug (vui, "if %d msg VHOST_USER_SET_LOG_FD", vui->hw_if_index);
1042       break;
1043
1044     case VHOST_USER_GET_PROTOCOL_FEATURES:
1045       msg.flags |= 4;
1046       msg.u64 = (1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD) |
1047         (1 << VHOST_USER_PROTOCOL_F_MQ);
1048       msg.size = sizeof (msg.u64);
1049       vu_log_debug (vui, "if %d msg VHOST_USER_GET_PROTOCOL_FEATURES - "
1050                     "reply 0x%016llx", vui->hw_if_index, msg.u64);
1051       n =
1052         send (uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
1053       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
1054         {
1055           vu_log_debug (vui, "could not send message response");
1056           goto close_socket;
1057         }
1058       break;
1059
1060     case VHOST_USER_SET_PROTOCOL_FEATURES:
1061       vu_log_debug (vui, "if %d msg VHOST_USER_SET_PROTOCOL_FEATURES "
1062                     "features 0x%016llx", vui->hw_if_index, msg.u64);
1063       vui->protocol_features = msg.u64;
1064       break;
1065
1066     case VHOST_USER_GET_QUEUE_NUM:
1067       msg.flags |= 4;
1068       msg.u64 = VHOST_VRING_MAX_MQ_PAIR_SZ;
1069       msg.size = sizeof (msg.u64);
1070       vu_log_debug (vui, "if %d msg VHOST_USER_GET_QUEUE_NUM - reply %d",
1071                     vui->hw_if_index, msg.u64);
1072       n =
1073         send (uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
1074       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
1075         {
1076           vu_log_debug (vui, "could not send message response");
1077           goto close_socket;
1078         }
1079       break;
1080
1081     case VHOST_USER_SET_VRING_ENABLE:
1082       vu_log_debug (vui, "if %d VHOST_USER_SET_VRING_ENABLE: %s queue %d",
1083                     vui->hw_if_index, msg.state.num ? "enable" : "disable",
1084                     msg.state.index);
1085       if (msg.state.index >= vui->num_qid)
1086         {
1087           vu_log_debug (vui, "invalid vring idx VHOST_USER_SET_VRING_ENABLE:"
1088                         " %u >= %u", msg.state.index, vui->num_qid);
1089           goto close_socket;
1090         }
1091
1092       vui->vrings[msg.state.index].enabled = msg.state.num;
1093       vhost_user_thread_placement (vui, msg.state.index);
1094       vhost_user_update_iface_state (vui);
1095       break;
1096
1097     default:
1098       vu_log_debug (vui, "unknown vhost-user message %d received. "
1099                     "closing socket", msg.request);
1100       goto close_socket;
1101     }
1102
1103   return 0;
1104
1105 close_socket:
1106   vlib_worker_thread_barrier_sync (vm);
1107   vhost_user_if_disconnect (vui);
1108   vlib_worker_thread_barrier_release (vm);
1109   vhost_user_update_iface_state (vui);
1110   return 0;
1111 }
1112
1113 static clib_error_t *
1114 vhost_user_socket_error (clib_file_t * uf)
1115 {
1116   vlib_main_t *vm = vlib_get_main ();
1117   vhost_user_main_t *vum = &vhost_user_main;
1118   vhost_user_intf_t *vui =
1119     pool_elt_at_index (vum->vhost_user_interfaces, uf->private_data);
1120
1121   vu_log_debug (vui, "socket error on if %d", vui->sw_if_index);
1122   vlib_worker_thread_barrier_sync (vm);
1123   vhost_user_if_disconnect (vui);
1124   vlib_worker_thread_barrier_release (vm);
1125   return 0;
1126 }
1127
1128 static clib_error_t *
1129 vhost_user_socksvr_accept_ready (clib_file_t * uf)
1130 {
1131   int client_fd, client_len;
1132   struct sockaddr_un client;
1133   clib_file_t template = { 0 };
1134   vhost_user_main_t *vum = &vhost_user_main;
1135   vhost_user_intf_t *vui;
1136
1137   vui = pool_elt_at_index (vum->vhost_user_interfaces, uf->private_data);
1138
1139   client_len = sizeof (client);
1140   client_fd = accept (uf->file_descriptor,
1141                       (struct sockaddr *) &client,
1142                       (socklen_t *) & client_len);
1143
1144   if (client_fd < 0)
1145     return clib_error_return_unix (0, "accept");
1146
1147   if (vui->clib_file_index != ~0)
1148     {
1149       vu_log_debug (vui, "Close client socket for vhost interface %d, fd %d",
1150                     vui->sw_if_index, UNIX_GET_FD (vui->clib_file_index));
1151       clib_file_del (&file_main, file_main.file_pool + vui->clib_file_index);
1152     }
1153
1154   vu_log_debug (vui, "New client socket for vhost interface %d, fd %d",
1155                 vui->sw_if_index, client_fd);
1156   template.read_function = vhost_user_socket_read;
1157   template.error_function = vhost_user_socket_error;
1158   template.file_descriptor = client_fd;
1159   template.private_data = vui - vhost_user_main.vhost_user_interfaces;
1160   template.description = format (0, "vhost interface %d", vui->sw_if_index);
1161   vui->clib_file_index = clib_file_add (&file_main, &template);
1162   vui->num_qid = 2;
1163   return 0;
1164 }
1165
1166 static clib_error_t *
1167 vhost_user_init (vlib_main_t * vm)
1168 {
1169   vhost_user_main_t *vum = &vhost_user_main;
1170   vlib_thread_main_t *tm = vlib_get_thread_main ();
1171
1172   vum->log_default = vlib_log_register_class ("vhost-user", 0);
1173
1174   vum->coalesce_frames = 32;
1175   vum->coalesce_time = 1e-3;
1176
1177   vec_validate (vum->cpus, tm->n_vlib_mains - 1);
1178
1179   vhost_cpu_t *cpu;
1180   vec_foreach (cpu, vum->cpus)
1181   {
1182     /* This is actually not necessary as validate already zeroes it
1183      * Just keeping the loop here for later because I am lazy. */
1184     cpu->rx_buffers_len = 0;
1185   }
1186
1187   vum->random = random_default_seed ();
1188
1189   mhash_init_c_string (&vum->if_index_by_sock_name, sizeof (uword));
1190
1191   return 0;
1192 }
1193
1194 VLIB_INIT_FUNCTION (vhost_user_init) =
1195 {
1196   .runs_after = VLIB_INITS("ip4_init"),
1197 };
1198
1199 static uword
1200 vhost_user_send_interrupt_process (vlib_main_t * vm,
1201                                    vlib_node_runtime_t * rt, vlib_frame_t * f)
1202 {
1203   vhost_user_intf_t *vui;
1204   f64 timeout = 3153600000.0 /* 100 years */ ;
1205   uword event_type, *event_data = 0;
1206   vhost_user_main_t *vum = &vhost_user_main;
1207   u16 qid;
1208   f64 now, poll_time_remaining;
1209   f64 next_timeout;
1210   u8 stop_timer = 0;
1211
1212   while (1)
1213     {
1214       poll_time_remaining =
1215         vlib_process_wait_for_event_or_clock (vm, timeout);
1216       event_type = vlib_process_get_events (vm, &event_data);
1217       vec_reset_length (event_data);
1218
1219       /*
1220        * Use the remaining timeout if it is less than coalesce time to avoid
1221        * resetting the existing timer in the middle of expiration
1222        */
1223       timeout = poll_time_remaining;
1224       if (vlib_process_suspend_time_is_zero (timeout) ||
1225           (timeout > vum->coalesce_time))
1226         timeout = vum->coalesce_time;
1227
1228       now = vlib_time_now (vm);
1229       switch (event_type)
1230         {
1231         case VHOST_USER_EVENT_STOP_TIMER:
1232           stop_timer = 1;
1233           break;
1234
1235         case VHOST_USER_EVENT_START_TIMER:
1236           stop_timer = 0;
1237           timeout = 1e-3;
1238           if (!vlib_process_suspend_time_is_zero (poll_time_remaining))
1239             break;
1240           /* fall through */
1241
1242         case ~0:
1243           pool_foreach (vui, vum->vhost_user_interfaces) {
1244               next_timeout = timeout;
1245               FOR_ALL_VHOST_RX_TXQ (qid, vui)
1246               {
1247                 vhost_user_vring_t *vq = &vui->vrings[qid];
1248
1249                 if (vq->started == 0)
1250                   continue;
1251                 if (vq->n_since_last_int)
1252                   {
1253                     if (now >= vq->int_deadline)
1254                       vhost_user_send_call (vm, vui, vq);
1255                     else
1256                       next_timeout = vq->int_deadline - now;
1257                   }
1258
1259                 if ((next_timeout < timeout) && (next_timeout > 0.0))
1260                   timeout = next_timeout;
1261               }
1262           }
1263           break;
1264
1265         default:
1266           clib_warning ("BUG: unhandled event type %d", event_type);
1267           break;
1268         }
1269       /* No less than 1 millisecond */
1270       if (timeout < 1e-3)
1271         timeout = 1e-3;
1272       if (stop_timer)
1273         timeout = 3153600000.0;
1274     }
1275   return 0;
1276 }
1277
1278 VLIB_REGISTER_NODE (vhost_user_send_interrupt_node) = {
1279     .function = vhost_user_send_interrupt_process,
1280     .type = VLIB_NODE_TYPE_PROCESS,
1281     .name = "vhost-user-send-interrupt-process",
1282 };
1283
1284 static uword
1285 vhost_user_process (vlib_main_t * vm,
1286                     vlib_node_runtime_t * rt, vlib_frame_t * f)
1287 {
1288   vhost_user_main_t *vum = &vhost_user_main;
1289   vhost_user_intf_t *vui;
1290   struct sockaddr_un sun;
1291   int sockfd;
1292   clib_file_t template = { 0 };
1293   f64 timeout = 3153600000.0 /* 100 years */ ;
1294   uword *event_data = 0;
1295
1296   sockfd = -1;
1297   sun.sun_family = AF_UNIX;
1298   template.read_function = vhost_user_socket_read;
1299   template.error_function = vhost_user_socket_error;
1300
1301   while (1)
1302     {
1303       vlib_process_wait_for_event_or_clock (vm, timeout);
1304       vlib_process_get_events (vm, &event_data);
1305       vec_reset_length (event_data);
1306
1307       timeout = 3.0;
1308
1309       pool_foreach (vui, vum->vhost_user_interfaces) {
1310
1311           if (vui->unix_server_index == ~0) { //Nothing to do for server sockets
1312               if (vui->clib_file_index == ~0)
1313                 {
1314                   if ((sockfd < 0) &&
1315                       ((sockfd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0))
1316                     {
1317                       /*
1318                        * 1st time error or new error for this interface,
1319                        * spit out the message and record the error
1320                        */
1321                       if (!vui->sock_errno || (vui->sock_errno != errno))
1322                         {
1323                           clib_unix_warning
1324                             ("Error: Could not open unix socket for %s",
1325                              vui->sock_filename);
1326                           vui->sock_errno = errno;
1327                         }
1328                       continue;
1329                     }
1330
1331                   /* try to connect */
1332                   strncpy (sun.sun_path, (char *) vui->sock_filename,
1333                            sizeof (sun.sun_path) - 1);
1334                   sun.sun_path[sizeof (sun.sun_path) - 1] = 0;
1335
1336                   /* Avoid hanging VPP if the other end does not accept */
1337                   if (fcntl(sockfd, F_SETFL, O_NONBLOCK) < 0)
1338                       clib_unix_warning ("fcntl");
1339
1340                   if (connect (sockfd, (struct sockaddr *) &sun,
1341                                sizeof (struct sockaddr_un)) == 0)
1342                     {
1343                       /* Set the socket to blocking as it was before */
1344                       if (fcntl(sockfd, F_SETFL, 0) < 0)
1345                         clib_unix_warning ("fcntl2");
1346
1347                       vui->sock_errno = 0;
1348                       template.file_descriptor = sockfd;
1349                       template.private_data =
1350                           vui - vhost_user_main.vhost_user_interfaces;
1351                       template.description = format (0, "vhost user process");
1352                       vui->clib_file_index = clib_file_add (&file_main, &template);
1353                       vui->num_qid = 2;
1354
1355                       /* This sockfd is considered consumed */
1356                       sockfd = -1;
1357                     }
1358                   else
1359                     {
1360                       vui->sock_errno = errno;
1361                     }
1362                 }
1363               else
1364                 {
1365                   /* check if socket is alive */
1366                   int error = 0;
1367                   socklen_t len = sizeof (error);
1368                   int fd = UNIX_GET_FD(vui->clib_file_index);
1369                   int retval =
1370                       getsockopt (fd, SOL_SOCKET, SO_ERROR, &error, &len);
1371
1372                   if (retval)
1373                     {
1374                       vu_log_debug (vui, "getsockopt returned %d", retval);
1375                       vhost_user_if_disconnect (vui);
1376                     }
1377                 }
1378           }
1379       }
1380     }
1381   return 0;
1382 }
1383
1384 VLIB_REGISTER_NODE (vhost_user_process_node,static) = {
1385     .function = vhost_user_process,
1386     .type = VLIB_NODE_TYPE_PROCESS,
1387     .name = "vhost-user-process",
1388 };
1389
1390 /**
1391  * Disables and reset interface structure.
1392  * It can then be either init again, or removed from used interfaces.
1393  */
1394 static void
1395 vhost_user_term_if (vhost_user_intf_t * vui)
1396 {
1397   int q;
1398   vhost_user_main_t *vum = &vhost_user_main;
1399
1400   // disconnect interface sockets
1401   vhost_user_if_disconnect (vui);
1402   vhost_user_update_gso_interface_count (vui, 0 /* delete */ );
1403   vhost_user_update_iface_state (vui);
1404
1405   for (q = 0; q < vec_len (vui->vrings); q++)
1406     clib_spinlock_free (&vui->vrings[q].vring_lock);
1407
1408   if (vui->unix_server_index != ~0)
1409     {
1410       //Close server socket
1411       clib_file_t *uf = pool_elt_at_index (file_main.file_pool,
1412                                            vui->unix_server_index);
1413       clib_file_del (&file_main, uf);
1414       vui->unix_server_index = ~0;
1415       unlink (vui->sock_filename);
1416     }
1417
1418   mhash_unset (&vum->if_index_by_sock_name, vui->sock_filename,
1419                &vui->if_index);
1420 }
1421
1422 int
1423 vhost_user_delete_if (vnet_main_t * vnm, vlib_main_t * vm, u32 sw_if_index)
1424 {
1425   vhost_user_main_t *vum = &vhost_user_main;
1426   vhost_user_intf_t *vui;
1427   int rv = 0;
1428   vnet_hw_interface_t *hwif;
1429   u16 qid;
1430
1431   if (!
1432       (hwif =
1433        vnet_get_sup_hw_interface_api_visible_or_null (vnm, sw_if_index))
1434       || hwif->dev_class_index != vhost_user_device_class.index)
1435     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
1436
1437   vui = pool_elt_at_index (vum->vhost_user_interfaces, hwif->dev_instance);
1438
1439   vu_log_debug (vui, "Deleting vhost-user interface %s (instance %d)",
1440                 hwif->name, hwif->dev_instance);
1441
1442   FOR_ALL_VHOST_TXQ (qid, vui)
1443   {
1444     vhost_user_vring_t *txvq = &vui->vrings[qid];
1445
1446     if ((txvq->mode == VNET_HW_IF_RX_MODE_POLLING) &&
1447         (txvq->thread_index != ~0))
1448       {
1449         vhost_cpu_t *cpu = vec_elt_at_index (vum->cpus, txvq->thread_index);
1450         ASSERT (cpu->polling_q_count != 0);
1451         cpu->polling_q_count--;
1452       }
1453
1454     if ((vum->ifq_count > 0) &&
1455         ((txvq->mode == VNET_HW_IF_RX_MODE_INTERRUPT) ||
1456          (txvq->mode == VNET_HW_IF_RX_MODE_ADAPTIVE)))
1457       {
1458         vum->ifq_count--;
1459         // Stop the timer if there is no more interrupt interface/queue
1460         if (vum->ifq_count == 0)
1461           {
1462             vlib_process_signal_event (vm,
1463                                        vhost_user_send_interrupt_node.index,
1464                                        VHOST_USER_EVENT_STOP_TIMER, 0);
1465             break;
1466           }
1467       }
1468   }
1469
1470   // Disable and reset interface
1471   vhost_user_term_if (vui);
1472
1473   // Reset renumbered iface
1474   if (hwif->dev_instance <
1475       vec_len (vum->show_dev_instance_by_real_dev_instance))
1476     vum->show_dev_instance_by_real_dev_instance[hwif->dev_instance] = ~0;
1477
1478   // Delete ethernet interface
1479   ethernet_delete_interface (vnm, vui->hw_if_index);
1480
1481   // free vrings
1482   vec_free (vui->vrings);
1483
1484   // Back to pool
1485   pool_put (vum->vhost_user_interfaces, vui);
1486
1487   return rv;
1488 }
1489
1490 static clib_error_t *
1491 vhost_user_exit (vlib_main_t * vm)
1492 {
1493   vnet_main_t *vnm = vnet_get_main ();
1494   vhost_user_main_t *vum = &vhost_user_main;
1495   vhost_user_intf_t *vui;
1496
1497   vlib_worker_thread_barrier_sync (vlib_get_main ());
1498   pool_foreach (vui, vum->vhost_user_interfaces) {
1499       vhost_user_delete_if (vnm, vm, vui->sw_if_index);
1500   }
1501   vlib_worker_thread_barrier_release (vlib_get_main ());
1502   return 0;
1503 }
1504
1505 VLIB_MAIN_LOOP_EXIT_FUNCTION (vhost_user_exit);
1506
1507 /**
1508  * Open server unix socket on specified sock_filename.
1509  */
1510 static int
1511 vhost_user_init_server_sock (const char *sock_filename, int *sock_fd)
1512 {
1513   int rv = 0;
1514   struct sockaddr_un un = { };
1515   int fd;
1516   /* create listening socket */
1517   if ((fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1518     return VNET_API_ERROR_SYSCALL_ERROR_1;
1519
1520   un.sun_family = AF_UNIX;
1521   strncpy ((char *) un.sun_path, (char *) sock_filename,
1522            sizeof (un.sun_path) - 1);
1523
1524   /* remove if exists */
1525   unlink ((char *) sock_filename);
1526
1527   if (bind (fd, (struct sockaddr *) &un, sizeof (un)) == -1)
1528     {
1529       rv = VNET_API_ERROR_SYSCALL_ERROR_2;
1530       goto error;
1531     }
1532
1533   if (listen (fd, 1) == -1)
1534     {
1535       rv = VNET_API_ERROR_SYSCALL_ERROR_3;
1536       goto error;
1537     }
1538
1539   *sock_fd = fd;
1540   return 0;
1541
1542 error:
1543   close (fd);
1544   return rv;
1545 }
1546
1547 /**
1548  * Create ethernet interface for vhost user interface.
1549  */
1550 static void
1551 vhost_user_create_ethernet (vnet_main_t *vnm, vlib_main_t *vm,
1552                             vhost_user_intf_t *vui,
1553                             vhost_user_create_if_args_t *args)
1554 {
1555   vhost_user_main_t *vum = &vhost_user_main;
1556   vnet_eth_interface_registration_t eir = {};
1557   u8 hwaddr[6];
1558
1559   /* create hw and sw interface */
1560   if (args->use_custom_mac)
1561     {
1562       clib_memcpy (hwaddr, args->hwaddr, 6);
1563     }
1564   else
1565     {
1566       random_u32 (&vum->random);
1567       clib_memcpy (hwaddr + 2, &vum->random, sizeof (vum->random));
1568       hwaddr[0] = 2;
1569       hwaddr[1] = 0xfe;
1570     }
1571
1572   eir.dev_class_index = vhost_user_device_class.index;
1573   eir.dev_instance = vui - vum->vhost_user_interfaces /* device instance */,
1574   eir.address = hwaddr;
1575   vui->hw_if_index = vnet_eth_register_interface (vnm, &eir);
1576 }
1577
1578 /*
1579  *  Initialize vui with specified attributes
1580  */
1581 static void
1582 vhost_user_vui_init (vnet_main_t * vnm, vhost_user_intf_t * vui,
1583                      int server_sock_fd, vhost_user_create_if_args_t * args,
1584                      u32 * sw_if_index)
1585 {
1586   vnet_sw_interface_t *sw;
1587   int q;
1588   vhost_user_main_t *vum = &vhost_user_main;
1589
1590   sw = vnet_get_hw_sw_interface (vnm, vui->hw_if_index);
1591   if (server_sock_fd != -1)
1592     {
1593       clib_file_t template = { 0 };
1594       template.read_function = vhost_user_socksvr_accept_ready;
1595       template.file_descriptor = server_sock_fd;
1596       template.private_data = vui - vum->vhost_user_interfaces; //hw index
1597       template.description = format (0, "vhost user %d", sw);
1598       vui->unix_server_index = clib_file_add (&file_main, &template);
1599     }
1600   else
1601     {
1602       vui->unix_server_index = ~0;
1603     }
1604
1605   vui->sw_if_index = sw->sw_if_index;
1606   strncpy (vui->sock_filename, args->sock_filename,
1607            ARRAY_LEN (vui->sock_filename) - 1);
1608   vui->sock_errno = 0;
1609   vui->is_ready = 0;
1610   vui->feature_mask = args->feature_mask;
1611   vui->clib_file_index = ~0;
1612   vui->log_base_addr = 0;
1613   vui->if_index = vui - vum->vhost_user_interfaces;
1614   vui->enable_gso = args->enable_gso;
1615   vui->enable_event_idx = args->enable_event_idx;
1616   vui->enable_packed = args->enable_packed;
1617   /*
1618    * enable_gso takes precedence over configurable feature mask if there
1619    * is a clash.
1620    *   if feature mask disables gso, but enable_gso is configured,
1621    *     then gso is enable
1622    *   if feature mask enables gso, but enable_gso is not configured,
1623    *     then gso is enable
1624    *
1625    * if gso is enable via feature mask, it must enable both host and guest
1626    * gso feature mask, we don't support one sided GSO or partial GSO.
1627    */
1628   if ((vui->enable_gso == 0) &&
1629       ((args->feature_mask & FEATURE_VIRTIO_NET_F_HOST_GUEST_TSO_FEATURE_BITS)
1630        == (FEATURE_VIRTIO_NET_F_HOST_GUEST_TSO_FEATURE_BITS)))
1631     vui->enable_gso = 1;
1632   vhost_user_update_gso_interface_count (vui, 1 /* add */ );
1633   mhash_set_mem (&vum->if_index_by_sock_name, vui->sock_filename,
1634                  &vui->if_index, 0);
1635
1636   vec_validate_aligned (vui->vrings, (VHOST_VRING_INIT_MQ_PAIR_SZ << 1) - 1,
1637                         CLIB_CACHE_LINE_BYTES);
1638   vui->num_qid = 2;
1639   for (q = 0; q < vec_len (vui->vrings); q++)
1640     vhost_user_vring_init (vui, q);
1641
1642   vnet_hw_if_set_caps (vnm, vui->hw_if_index, VNET_HW_IF_CAP_INT_MODE);
1643   vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
1644
1645   if (sw_if_index)
1646     *sw_if_index = vui->sw_if_index;
1647 }
1648
1649 int
1650 vhost_user_create_if (vnet_main_t * vnm, vlib_main_t * vm,
1651                       vhost_user_create_if_args_t * args)
1652 {
1653   vhost_user_intf_t *vui = NULL;
1654   u32 sw_if_idx = ~0;
1655   int rv = 0;
1656   int server_sock_fd = -1;
1657   vhost_user_main_t *vum = &vhost_user_main;
1658   uword *if_index;
1659
1660   if (args->sock_filename == NULL || !(strlen (args->sock_filename) > 0))
1661     {
1662       return VNET_API_ERROR_INVALID_ARGUMENT;
1663     }
1664
1665   if_index = mhash_get (&vum->if_index_by_sock_name,
1666                         (void *) args->sock_filename);
1667   if (if_index)
1668     {
1669       vui = &vum->vhost_user_interfaces[*if_index];
1670       args->sw_if_index = vui->sw_if_index;
1671       return VNET_API_ERROR_IF_ALREADY_EXISTS;
1672     }
1673
1674   if (args->is_server)
1675     {
1676       if ((rv =
1677            vhost_user_init_server_sock (args->sock_filename,
1678                                         &server_sock_fd)) != 0)
1679         {
1680           return rv;
1681         }
1682     }
1683
1684   /* Protect the uninitialized vui from being dispatched by rx/tx */
1685   vlib_worker_thread_barrier_sync (vm);
1686   pool_get (vhost_user_main.vhost_user_interfaces, vui);
1687   vhost_user_create_ethernet (vnm, vm, vui, args);
1688   vlib_worker_thread_barrier_release (vm);
1689
1690   vhost_user_vui_init (vnm, vui, server_sock_fd, args, &sw_if_idx);
1691   vnet_sw_interface_set_mtu (vnm, vui->sw_if_index, 9000);
1692   vhost_user_rx_thread_placement (vui, 1);
1693
1694   if (args->renumber)
1695     vnet_interface_name_renumber (sw_if_idx, args->custom_dev_instance);
1696
1697   args->sw_if_index = sw_if_idx;
1698
1699   // Process node must connect
1700   vlib_process_signal_event (vm, vhost_user_process_node.index, 0, 0);
1701
1702   return rv;
1703 }
1704
1705 int
1706 vhost_user_modify_if (vnet_main_t * vnm, vlib_main_t * vm,
1707                       vhost_user_create_if_args_t * args)
1708 {
1709   vhost_user_main_t *vum = &vhost_user_main;
1710   vhost_user_intf_t *vui = NULL;
1711   u32 sw_if_idx = ~0;
1712   int server_sock_fd = -1;
1713   int rv = 0;
1714   vnet_hw_interface_t *hwif;
1715   uword *if_index;
1716
1717   if (!(hwif = vnet_get_sup_hw_interface_api_visible_or_null (vnm,
1718                                                               args->sw_if_index))
1719       || hwif->dev_class_index != vhost_user_device_class.index)
1720     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
1721
1722   if (args->sock_filename == NULL || !(strlen (args->sock_filename) > 0))
1723     return VNET_API_ERROR_INVALID_ARGUMENT;
1724
1725   vui = vec_elt_at_index (vum->vhost_user_interfaces, hwif->dev_instance);
1726
1727   /*
1728    * Disallow changing the interface to have the same path name
1729    * as other interface
1730    */
1731   if_index = mhash_get (&vum->if_index_by_sock_name,
1732                         (void *) args->sock_filename);
1733   if (if_index && (*if_index != vui->if_index))
1734     return VNET_API_ERROR_IF_ALREADY_EXISTS;
1735
1736   // First try to open server socket
1737   if (args->is_server)
1738     if ((rv = vhost_user_init_server_sock (args->sock_filename,
1739                                            &server_sock_fd)) != 0)
1740       return rv;
1741
1742   vhost_user_term_if (vui);
1743   vhost_user_vui_init (vnm, vui, server_sock_fd, args, &sw_if_idx);
1744
1745   if (args->renumber)
1746     vnet_interface_name_renumber (sw_if_idx, args->custom_dev_instance);
1747
1748   // Process node must connect
1749   vlib_process_signal_event (vm, vhost_user_process_node.index, 0, 0);
1750
1751   return rv;
1752 }
1753
1754 clib_error_t *
1755 vhost_user_connect_command_fn (vlib_main_t * vm,
1756                                unformat_input_t * input,
1757                                vlib_cli_command_t * cmd)
1758 {
1759   vnet_main_t *vnm = vnet_get_main ();
1760   unformat_input_t _line_input, *line_input = &_line_input;
1761   clib_error_t *error = NULL;
1762   vhost_user_create_if_args_t args = { 0 };
1763   int rv;
1764
1765   /* Get a line of input. */
1766   if (!unformat_user (input, unformat_line_input, line_input))
1767     return 0;
1768
1769   args.feature_mask = (u64) ~ (0ULL);
1770   args.custom_dev_instance = ~0;
1771   /* GSO feature is disable by default */
1772   args.feature_mask &= ~FEATURE_VIRTIO_NET_F_HOST_GUEST_TSO_FEATURE_BITS;
1773   /* packed-ring feature is disable by default */
1774   args.feature_mask &= ~VIRTIO_FEATURE (VIRTIO_F_RING_PACKED);
1775   /* event_idx feature is disable by default */
1776   args.feature_mask &= ~VIRTIO_FEATURE (VIRTIO_RING_F_EVENT_IDX);
1777
1778   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1779     {
1780       if (unformat (line_input, "socket %s", &args.sock_filename))
1781         ;
1782       else if (unformat (line_input, "server"))
1783         args.is_server = 1;
1784       else if (unformat (line_input, "gso"))
1785         args.enable_gso = 1;
1786       else if (unformat (line_input, "packed"))
1787         args.enable_packed = 1;
1788       else if (unformat (line_input, "event-idx"))
1789         args.enable_event_idx = 1;
1790       else if (unformat (line_input, "feature-mask 0x%llx",
1791                          &args.feature_mask))
1792         ;
1793       else if (unformat (line_input, "hwaddr %U", unformat_ethernet_address,
1794                          args.hwaddr))
1795         args.use_custom_mac = 1;
1796       else if (unformat (line_input, "renumber %d",
1797                          &args.custom_dev_instance))
1798         args.renumber = 1;
1799       else
1800         {
1801           error = clib_error_return (0, "unknown input `%U'",
1802                                      format_unformat_error, line_input);
1803           goto done;
1804         }
1805     }
1806
1807   if ((rv = vhost_user_create_if (vnm, vm, &args)))
1808     {
1809       error = clib_error_return (0, "vhost_user_create_if returned %d", rv);
1810       goto done;
1811     }
1812
1813   vlib_cli_output (vm, "%U\n", format_vnet_sw_if_index_name, vnm,
1814                    args.sw_if_index);
1815
1816 done:
1817   vec_free (args.sock_filename);
1818   unformat_free (line_input);
1819
1820   return error;
1821 }
1822
1823 clib_error_t *
1824 vhost_user_delete_command_fn (vlib_main_t * vm,
1825                               unformat_input_t * input,
1826                               vlib_cli_command_t * cmd)
1827 {
1828   unformat_input_t _line_input, *line_input = &_line_input;
1829   u32 sw_if_index = ~0;
1830   vnet_main_t *vnm = vnet_get_main ();
1831   clib_error_t *error = NULL;
1832
1833   /* Get a line of input. */
1834   if (!unformat_user (input, unformat_line_input, line_input))
1835     return 0;
1836
1837   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1838     {
1839       if (unformat (line_input, "sw_if_index %d", &sw_if_index))
1840         ;
1841       else if (unformat
1842                (line_input, "%U", unformat_vnet_sw_interface, vnm,
1843                 &sw_if_index))
1844         {
1845           vnet_hw_interface_t *hwif =
1846             vnet_get_sup_hw_interface_api_visible_or_null (vnm, sw_if_index);
1847           if (hwif == NULL ||
1848               vhost_user_device_class.index != hwif->dev_class_index)
1849             {
1850               error = clib_error_return (0, "Not a vhost interface");
1851               goto done;
1852             }
1853         }
1854       else
1855         {
1856           error = clib_error_return (0, "unknown input `%U'",
1857                                      format_unformat_error, line_input);
1858           goto done;
1859         }
1860     }
1861
1862   vhost_user_delete_if (vnm, vm, sw_if_index);
1863
1864 done:
1865   unformat_free (line_input);
1866
1867   return error;
1868 }
1869
1870 int
1871 vhost_user_dump_ifs (vnet_main_t * vnm, vlib_main_t * vm,
1872                      vhost_user_intf_details_t ** out_vuids)
1873 {
1874   int rv = 0;
1875   vhost_user_main_t *vum = &vhost_user_main;
1876   vhost_user_intf_t *vui;
1877   vhost_user_intf_details_t *r_vuids = NULL;
1878   vhost_user_intf_details_t *vuid = NULL;
1879   u32 *hw_if_indices = 0;
1880   vnet_hw_interface_t *hi;
1881   int i;
1882
1883   if (!out_vuids)
1884     return -1;
1885
1886   pool_foreach (vui, vum->vhost_user_interfaces)
1887     vec_add1 (hw_if_indices, vui->hw_if_index);
1888
1889   for (i = 0; i < vec_len (hw_if_indices); i++)
1890     {
1891       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
1892       vui = pool_elt_at_index (vum->vhost_user_interfaces, hi->dev_instance);
1893
1894       vec_add2 (r_vuids, vuid, 1);
1895       vuid->sw_if_index = vui->sw_if_index;
1896       vuid->virtio_net_hdr_sz = vui->virtio_net_hdr_sz;
1897       vuid->features = vui->features;
1898       vuid->num_regions = vui->nregions;
1899       vuid->is_server = vui->unix_server_index != ~0;
1900       vuid->sock_errno = vui->sock_errno;
1901       snprintf ((char *) vuid->sock_filename, sizeof (vuid->sock_filename),
1902                 "%s", vui->sock_filename);
1903       memcpy_s (vuid->if_name, sizeof (vuid->if_name), hi->name,
1904                 clib_min (vec_len (hi->name), sizeof (vuid->if_name) - 1));
1905       vuid->if_name[sizeof (vuid->if_name) - 1] = 0;
1906     }
1907
1908   vec_free (hw_if_indices);
1909
1910   *out_vuids = r_vuids;
1911
1912   return rv;
1913 }
1914
1915 static u8 *
1916 format_vhost_user_desc (u8 * s, va_list * args)
1917 {
1918   char *fmt = va_arg (*args, char *);
1919   vhost_user_intf_t *vui = va_arg (*args, vhost_user_intf_t *);
1920   vnet_virtio_vring_desc_t *desc_table =
1921     va_arg (*args, vnet_virtio_vring_desc_t *);
1922   int idx = va_arg (*args, int);
1923   u32 *mem_hint = va_arg (*args, u32 *);
1924
1925   s = format (s, fmt, idx, desc_table[idx].addr, desc_table[idx].len,
1926               desc_table[idx].flags, desc_table[idx].next,
1927               pointer_to_uword (map_guest_mem (vui, desc_table[idx].addr,
1928                                                mem_hint)));
1929   return s;
1930 }
1931
1932 static void
1933 vhost_user_show_fds (vlib_main_t * vm, vhost_user_vring_t * vq)
1934 {
1935   int kickfd = UNIX_GET_FD (vq->kickfd_idx);
1936   int callfd = UNIX_GET_FD (vq->callfd_idx);
1937
1938   vlib_cli_output (vm, "  kickfd %d callfd %d errfd %d\n", kickfd, callfd,
1939                    vq->errfd);
1940 }
1941
1942 static void
1943 vhost_user_show_desc (vlib_main_t * vm, vhost_user_intf_t * vui, int q,
1944                       int show_descr, int show_verbose)
1945 {
1946   int j;
1947   u32 mem_hint = 0;
1948   u32 idx;
1949   u32 n_entries;
1950   vnet_virtio_vring_desc_t *desc_table;
1951   vhost_user_vring_t *vq = &vui->vrings[q];
1952
1953   if (vq->avail && vq->used)
1954     vlib_cli_output (vm,
1955                      "  avail.flags %x avail event idx %u avail.idx %d "
1956                      "used.flags %x used event idx %u used.idx %d\n",
1957                      vq->avail->flags, vhost_user_avail_event_idx (vq),
1958                      vq->avail->idx, vq->used->flags,
1959                      vhost_user_used_event_idx (vq), vq->used->idx);
1960
1961   vhost_user_show_fds (vm, vq);
1962
1963   if (show_descr)
1964     {
1965       vlib_cli_output (vm, "\n  descriptor table:\n");
1966       vlib_cli_output (vm,
1967                        "  slot         addr         len  flags  next      "
1968                        "user_addr\n");
1969       vlib_cli_output (vm,
1970                        "  ===== ================== ===== ====== ===== "
1971                        "==================\n");
1972       for (j = 0; j < vq->qsz_mask + 1; j++)
1973         {
1974           desc_table = vq->desc;
1975           vlib_cli_output (vm, "%U", format_vhost_user_desc,
1976                            "  %-5d 0x%016lx %-5d 0x%04x %-5d 0x%016lx\n", vui,
1977                            desc_table, j, &mem_hint);
1978           if (show_verbose && (desc_table[j].flags & VRING_DESC_F_INDIRECT))
1979             {
1980               n_entries =
1981                 desc_table[j].len / sizeof (vnet_virtio_vring_desc_t);
1982               desc_table = map_guest_mem (vui, desc_table[j].addr, &mem_hint);
1983               if (desc_table)
1984                 {
1985                   for (idx = 0; idx < clib_min (20, n_entries); idx++)
1986                     {
1987                       vlib_cli_output
1988                         (vm, "%U", format_vhost_user_desc,
1989                          ">  %-4u 0x%016lx %-5u 0x%04x %-5u 0x%016lx\n", vui,
1990                          desc_table, idx, &mem_hint);
1991                     }
1992                   if (n_entries >= 20)
1993                     vlib_cli_output (vm, "Skip displaying entries 20...%u\n",
1994                                      n_entries);
1995                 }
1996             }
1997         }
1998     }
1999 }
2000
2001 static u8 *
2002 format_vhost_user_packed_desc (u8 * s, va_list * args)
2003 {
2004   char *fmt = va_arg (*args, char *);
2005   vhost_user_intf_t *vui = va_arg (*args, vhost_user_intf_t *);
2006   vnet_virtio_vring_packed_desc_t *desc_table =
2007     va_arg (*args, vnet_virtio_vring_packed_desc_t *);
2008   int idx = va_arg (*args, int);
2009   u32 *mem_hint = va_arg (*args, u32 *);
2010
2011   s = format (s, fmt, idx, desc_table[idx].addr, desc_table[idx].len,
2012               desc_table[idx].flags, desc_table[idx].id,
2013               pointer_to_uword (map_guest_mem (vui, desc_table[idx].addr,
2014                                                mem_hint)));
2015   return s;
2016 }
2017
2018 static u8 *
2019 format_vhost_user_event_idx_flags (u8 * s, va_list * args)
2020 {
2021   u32 flags = va_arg (*args, u32);
2022   typedef struct
2023   {
2024     u8 value;
2025     char *str;
2026   } event_idx_flags;
2027   static event_idx_flags event_idx_array[] = {
2028 #define _(s,v) { .str = #s, .value = v, },
2029     foreach_virtio_event_idx_flags
2030 #undef _
2031   };
2032   u32 num_entries = sizeof (event_idx_array) / sizeof (event_idx_flags);
2033
2034   if (flags < num_entries)
2035     s = format (s, "%s", event_idx_array[flags].str);
2036   else
2037     s = format (s, "%u", flags);
2038   return s;
2039 }
2040
2041 static void
2042 vhost_user_show_desc_packed (vlib_main_t * vm, vhost_user_intf_t * vui, int q,
2043                              int show_descr, int show_verbose)
2044 {
2045   int j;
2046   u32 mem_hint = 0;
2047   u32 idx;
2048   u32 n_entries;
2049   vnet_virtio_vring_packed_desc_t *desc_table;
2050   vhost_user_vring_t *vq = &vui->vrings[q];
2051   u16 off_wrap, event_idx;
2052
2053   off_wrap = vq->avail_event->off_wrap;
2054   event_idx = off_wrap & 0x7fff;
2055   vlib_cli_output (vm, "  avail_event.flags %U avail_event.off_wrap %u "
2056                    "avail event idx %u\n", format_vhost_user_event_idx_flags,
2057                    (u32) vq->avail_event->flags, off_wrap, event_idx);
2058
2059   off_wrap = vq->used_event->off_wrap;
2060   event_idx = off_wrap & 0x7fff;
2061   vlib_cli_output (vm, "  used_event.flags %U used_event.off_wrap %u "
2062                    "used event idx %u\n", format_vhost_user_event_idx_flags,
2063                    (u32) vq->used_event->flags, off_wrap, event_idx);
2064
2065   vlib_cli_output (vm, "  avail wrap counter %u, used wrap counter %u\n",
2066                    vq->avail_wrap_counter, vq->used_wrap_counter);
2067
2068   vhost_user_show_fds (vm, vq);
2069
2070   if (show_descr)
2071     {
2072       vlib_cli_output (vm, "\n  descriptor table:\n");
2073       vlib_cli_output (vm,
2074                        "  slot         addr         len  flags  id    "
2075                        "user_addr\n");
2076       vlib_cli_output (vm,
2077                        "  ===== ================== ===== ====== ===== "
2078                        "==================\n");
2079       for (j = 0; j < vq->qsz_mask + 1; j++)
2080         {
2081           desc_table = vq->packed_desc;
2082           vlib_cli_output (vm, "%U", format_vhost_user_packed_desc,
2083                            "  %-5u 0x%016lx %-5u 0x%04x %-5u 0x%016lx\n", vui,
2084                            desc_table, j, &mem_hint);
2085           if (show_verbose && (desc_table[j].flags & VRING_DESC_F_INDIRECT))
2086             {
2087               n_entries = desc_table[j].len >> 4;
2088               desc_table = map_guest_mem (vui, desc_table[j].addr, &mem_hint);
2089               if (desc_table)
2090                 {
2091                   for (idx = 0; idx < clib_min (20, n_entries); idx++)
2092                     {
2093                       vlib_cli_output
2094                         (vm, "%U", format_vhost_user_packed_desc,
2095                          ">  %-4u 0x%016lx %-5u 0x%04x %-5u 0x%016lx\n", vui,
2096                          desc_table, idx, &mem_hint);
2097                     }
2098                   if (n_entries >= 20)
2099                     vlib_cli_output (vm, "Skip displaying entries 20...%u\n",
2100                                      n_entries);
2101                 }
2102             }
2103         }
2104     }
2105 }
2106
2107 clib_error_t *
2108 show_vhost_user_command_fn (vlib_main_t * vm,
2109                             unformat_input_t * input,
2110                             vlib_cli_command_t * cmd)
2111 {
2112   clib_error_t *error = 0;
2113   vnet_main_t *vnm = vnet_get_main ();
2114   vhost_user_main_t *vum = &vhost_user_main;
2115   vhost_user_intf_t *vui;
2116   u32 hw_if_index, *hw_if_indices = 0;
2117   vnet_hw_interface_t *hi;
2118   u16 qid;
2119   int i, j, q;
2120   int show_descr = 0;
2121   int show_verbose = 0;
2122   struct feat_struct
2123   {
2124     u8 bit;
2125     char *str;
2126   };
2127   struct feat_struct *feat_entry;
2128
2129   static struct feat_struct feat_array[] = {
2130 #define _(s,b) { .str = #s, .bit = b, },
2131     foreach_virtio_net_features
2132 #undef _
2133     {.str = NULL}
2134   };
2135
2136 #define foreach_protocol_feature \
2137   _(VHOST_USER_PROTOCOL_F_MQ) \
2138   _(VHOST_USER_PROTOCOL_F_LOG_SHMFD)
2139
2140   static struct feat_struct proto_feat_array[] = {
2141 #define _(s) { .str = #s, .bit = s},
2142     foreach_protocol_feature
2143 #undef _
2144     {.str = NULL}
2145   };
2146
2147   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2148     {
2149       if (unformat
2150           (input, "%U", unformat_vnet_hw_interface, vnm, &hw_if_index))
2151         {
2152           hi = vnet_get_hw_interface (vnm, hw_if_index);
2153           if (vhost_user_device_class.index != hi->dev_class_index)
2154             {
2155               error = clib_error_return (0, "unknown input `%U'",
2156                                          format_unformat_error, input);
2157               goto done;
2158             }
2159           vec_add1 (hw_if_indices, hw_if_index);
2160         }
2161       else if (unformat (input, "descriptors") || unformat (input, "desc"))
2162         show_descr = 1;
2163       else if (unformat (input, "verbose"))
2164         show_verbose = 1;
2165       else
2166         {
2167           error = clib_error_return (0, "unknown input `%U'",
2168                                      format_unformat_error, input);
2169           goto done;
2170         }
2171     }
2172   if (vec_len (hw_if_indices) == 0)
2173     {
2174       pool_foreach (vui, vum->vhost_user_interfaces)
2175         vec_add1 (hw_if_indices, vui->hw_if_index);
2176     }
2177   vlib_cli_output (vm, "Virtio vhost-user interfaces");
2178   vlib_cli_output (vm, "Global:\n  coalesce frames %d time %e",
2179                    vum->coalesce_frames, vum->coalesce_time);
2180   vlib_cli_output (vm, "  Number of rx virtqueues in interrupt mode: %d",
2181                    vum->ifq_count);
2182   vlib_cli_output (vm, "  Number of GSO interfaces: %d", vum->gso_count);
2183   for (u32 tid = 0; tid <= vlib_num_workers (); tid++)
2184     {
2185       vhost_cpu_t *cpu = vec_elt_at_index (vum->cpus, tid);
2186       vlib_cli_output (vm, "  Thread %u: Polling queue count %u", tid,
2187                        cpu->polling_q_count);
2188     }
2189
2190   for (i = 0; i < vec_len (hw_if_indices); i++)
2191     {
2192       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
2193       vui = pool_elt_at_index (vum->vhost_user_interfaces, hi->dev_instance);
2194       vlib_cli_output (vm, "Interface: %U (ifindex %d)",
2195                        format_vnet_hw_if_index_name, vnm, hw_if_indices[i],
2196                        hw_if_indices[i]);
2197       vlib_cli_output (vm, "  Number of qids %u", vui->num_qid);
2198       if (vui->enable_gso)
2199         vlib_cli_output (vm, "  GSO enable");
2200       if (vui->enable_packed)
2201         vlib_cli_output (vm, "  Packed ring enable");
2202       if (vui->enable_event_idx)
2203         vlib_cli_output (vm, "  Event index enable");
2204
2205       vlib_cli_output (vm, "virtio_net_hdr_sz %d\n"
2206                        " features mask (0x%llx): \n"
2207                        " features (0x%llx): \n",
2208                        vui->virtio_net_hdr_sz, vui->feature_mask,
2209                        vui->features);
2210
2211       feat_entry = (struct feat_struct *) &feat_array;
2212       while (feat_entry->str)
2213         {
2214           if (vui->features & (1ULL << feat_entry->bit))
2215             vlib_cli_output (vm, "   %s (%d)", feat_entry->str,
2216                              feat_entry->bit);
2217           feat_entry++;
2218         }
2219
2220       vlib_cli_output (vm, "  protocol features (0x%llx)",
2221                        vui->protocol_features);
2222       feat_entry = (struct feat_struct *) &proto_feat_array;
2223       while (feat_entry->str)
2224         {
2225           if (vui->protocol_features & (1ULL << feat_entry->bit))
2226             vlib_cli_output (vm, "   %s (%d)", feat_entry->str,
2227                              feat_entry->bit);
2228           feat_entry++;
2229         }
2230
2231       vlib_cli_output (vm, "\n");
2232
2233       vlib_cli_output (vm, " socket filename %s type %s errno \"%s\"\n\n",
2234                        vui->sock_filename,
2235                        (vui->unix_server_index != ~0) ? "server" : "client",
2236                        strerror (vui->sock_errno));
2237
2238       vlib_cli_output (vm, " rx placement: ");
2239
2240       FOR_ALL_VHOST_TXQ (qid, vui)
2241       {
2242         vhost_user_vring_t *txvq = &vui->vrings[qid];
2243
2244         if (txvq->qid == -1)
2245           continue;
2246         vlib_cli_output (vm, "   thread %d on vring %d, %U\n",
2247                          txvq->thread_index, qid, format_vnet_hw_if_rx_mode,
2248                          txvq->mode);
2249       }
2250
2251       vlib_cli_output (vm, " tx placement\n");
2252
2253       FOR_ALL_VHOST_RXQ (qid, vui)
2254       {
2255         vhost_user_vring_t *rxvq = &vui->vrings[qid];
2256         vnet_hw_if_tx_queue_t *txq;
2257
2258         if (rxvq->queue_index == ~0)
2259           continue;
2260         txq = vnet_hw_if_get_tx_queue (vnm, rxvq->queue_index);
2261         if (txq->threads)
2262           vlib_cli_output (vm, "   threads %U on vring %u: %s\n",
2263                            format_bitmap_list, txq->threads, qid,
2264                            txq->shared_queue ? "spin-lock" : "lock-free");
2265       }
2266
2267       vlib_cli_output (vm, "\n");
2268
2269       vlib_cli_output (vm, " Memory regions (total %d)\n", vui->nregions);
2270
2271       if (vui->nregions)
2272         {
2273           vlib_cli_output (vm,
2274                            " region fd    guest_phys_addr    memory_size        userspace_addr     mmap_offset        mmap_addr\n");
2275           vlib_cli_output (vm,
2276                            " ====== ===== ================== ================== ================== ================== ==================\n");
2277         }
2278       for (j = 0; j < vui->nregions; j++)
2279         {
2280           vlib_cli_output (vm,
2281                            "  %d     %-5d 0x%016lx 0x%016lx 0x%016lx 0x%016lx 0x%016lx\n",
2282                            j, vui->region_mmap_fd[j],
2283                            vui->regions[j].guest_phys_addr,
2284                            vui->regions[j].memory_size,
2285                            vui->regions[j].userspace_addr,
2286                            vui->regions[j].mmap_offset,
2287                            pointer_to_uword (vui->region_mmap_addr[j]));
2288         }
2289       FOR_ALL_VHOST_RX_TXQ (q, vui)
2290       {
2291         if (!vui->vrings[q].started)
2292           continue;
2293
2294         vlib_cli_output (vm, "\n Virtqueue %d (%s%s)\n", q,
2295                          (q & 1) ? "RX" : "TX",
2296                          vui->vrings[q].enabled ? "" : " disabled");
2297         vlib_cli_output (vm, "  global %s queue index %u\n",
2298                          (q & 1) ? "RX" : "TX", vui->vrings[q].queue_index);
2299
2300         vlib_cli_output (
2301           vm,
2302           "  qsz %d last_avail_idx %d last_used_idx %d"
2303           " last_kick %u\n",
2304           vui->vrings[q].qsz_mask + 1, vui->vrings[q].last_avail_idx,
2305           vui->vrings[q].last_used_idx, vui->vrings[q].last_kick);
2306
2307         if (vhost_user_is_packed_ring_supported (vui))
2308           vhost_user_show_desc_packed (vm, vui, q, show_descr, show_verbose);
2309         else
2310           vhost_user_show_desc (vm, vui, q, show_descr, show_verbose);
2311       }
2312       vlib_cli_output (vm, "\n");
2313     }
2314 done:
2315   vec_free (hw_if_indices);
2316   return error;
2317 }
2318
2319 /*
2320  * CLI functions
2321  */
2322
2323 /*?
2324  * Create a vHost User interface. Once created, a new virtual interface
2325  * will exist with the name '<em>VirtualEthernet0/0/x</em>', where '<em>x</em>'
2326  * is the next free index.
2327  *
2328  * There are several parameters associated with a vHost interface:
2329  *
2330  * - <b>socket <socket-filename></b> - Name of the linux socket used by
2331  * hypervisor and VPP to manage the vHost interface. If in <em>server</em>
2332  * mode, VPP will create the socket if it does not already exist. If in
2333  * <em>client</em> mode, hypervisor will create the socket if it does not
2334  * already exist. The VPP code is indifferent to the file location. However,
2335  * if SELinux is enabled, then the socket needs to be created in
2336  * <em>/var/run/vpp/</em>.
2337  *
2338  * - <b>server</b> - Optional flag to indicate that VPP should be the server
2339  * for the linux socket. If not provided, VPP will be the client. In
2340  * <em>server</em> mode, the VM can be reset without tearing down the vHost
2341  * Interface. In <em>client</em> mode, VPP can be reset without bringing down
2342  * the VM and tearing down the vHost Interface.
2343  *
2344  * - <b>feature-mask <hex></b> - Optional virtio/vhost feature set negotiated
2345  * at startup. <b>This is intended for degugging only.</b> It is recommended
2346  * that this parameter not be used except by experienced users. By default,
2347  * all supported features will be advertised. Otherwise, provide the set of
2348  * features desired.
2349  *   - 0x000008000 (15) - VIRTIO_NET_F_MRG_RXBUF
2350  *   - 0x000020000 (17) - VIRTIO_NET_F_CTRL_VQ
2351  *   - 0x000200000 (21) - VIRTIO_NET_F_GUEST_ANNOUNCE
2352  *   - 0x000400000 (22) - VIRTIO_NET_F_MQ
2353  *   - 0x004000000 (26) - VHOST_F_LOG_ALL
2354  *   - 0x008000000 (27) - VIRTIO_F_ANY_LAYOUT
2355  *   - 0x010000000 (28) - VIRTIO_F_INDIRECT_DESC
2356  *   - 0x040000000 (30) - VHOST_USER_F_PROTOCOL_FEATURES
2357  *   - 0x100000000 (32) - VIRTIO_F_VERSION_1
2358  *
2359  * - <b>hwaddr <mac-addr></b> - Optional ethernet address, can be in either
2360  * X:X:X:X:X:X unix or X.X.X cisco format.
2361  *
2362  * - <b>renumber <dev_instance></b> - Optional parameter which allows the
2363  * instance in the name to be specified. If instance already exists, name
2364  * will be used anyway and multiple instances will have the same name. Use
2365  * with caution.
2366  *
2367  * @cliexpar
2368  * Example of how to create a vhost interface with VPP as the client and all
2369  * features enabled:
2370  * @cliexstart{create vhost-user socket /var/run/vpp/vhost1.sock}
2371  * VirtualEthernet0/0/0
2372  * @cliexend
2373  * Example of how to create a vhost interface with VPP as the server and with
2374  * just multiple queues enabled:
2375  * @cliexstart{create vhost-user socket /var/run/vpp/vhost2.sock server
2376  * feature-mask 0x40400000}
2377  * VirtualEthernet0/0/1
2378  * @cliexend
2379  * Once the vHost interface is created, enable the interface using:
2380  * @cliexcmd{set interface state VirtualEthernet0/0/0 up}
2381 ?*/
2382 VLIB_CLI_COMMAND (vhost_user_connect_command, static) = {
2383     .path = "create vhost-user",
2384     .short_help = "create vhost-user socket <socket-filename> [server] "
2385     "[feature-mask <hex>] [hwaddr <mac-addr>] [renumber <dev_instance>] [gso] "
2386     "[packed] [event-idx]",
2387     .function = vhost_user_connect_command_fn,
2388     .is_mp_safe = 1,
2389 };
2390
2391 /*?
2392  * Delete a vHost User interface using the interface name or the
2393  * software interface index. Use the '<em>show interface</em>'
2394  * command to determine the software interface index. On deletion,
2395  * the linux socket will not be deleted.
2396  *
2397  * @cliexpar
2398  * Example of how to delete a vhost interface by name:
2399  * @cliexcmd{delete vhost-user VirtualEthernet0/0/1}
2400  * Example of how to delete a vhost interface by software interface index:
2401  * @cliexcmd{delete vhost-user sw_if_index 1}
2402 ?*/
2403 VLIB_CLI_COMMAND (vhost_user_delete_command, static) = {
2404     .path = "delete vhost-user",
2405     .short_help = "delete vhost-user {<interface> | sw_if_index <sw_idx>}",
2406     .function = vhost_user_delete_command_fn,
2407 };
2408
2409 /*?
2410  * Display the attributes of a single vHost User interface (provide interface
2411  * name), multiple vHost User interfaces (provide a list of interface names
2412  * separated by spaces) or all Vhost User interfaces (omit an interface name
2413  * to display all vHost interfaces).
2414  *
2415  * @cliexpar
2416  * @parblock
2417  * Example of how to display a vhost interface:
2418  * @cliexstart{show vhost-user VirtualEthernet0/0/0}
2419  * Virtio vhost-user interfaces
2420  * Global:
2421  *   coalesce frames 32 time 1e-3
2422  * Interface: VirtualEthernet0/0/0 (ifindex 1)
2423  * virtio_net_hdr_sz 12
2424  *  features mask (0xffffffffffffffff):
2425  *  features (0x50408000):
2426  *    VIRTIO_NET_F_MRG_RXBUF (15)
2427  *    VIRTIO_NET_F_MQ (22)
2428  *    VIRTIO_F_INDIRECT_DESC (28)
2429  *    VHOST_USER_F_PROTOCOL_FEATURES (30)
2430  *   protocol features (0x3)
2431  *    VHOST_USER_PROTOCOL_F_MQ (0)
2432  *    VHOST_USER_PROTOCOL_F_LOG_SHMFD (1)
2433  *
2434  *  socket filename /var/run/vpp/vhost1.sock type client errno "Success"
2435  *
2436  * rx placement:
2437  *    thread 1 on vring 1
2438  *    thread 1 on vring 5
2439  *    thread 2 on vring 3
2440  *    thread 2 on vring 7
2441  *  tx placement: spin-lock
2442  *    thread 0 on vring 0
2443  *    thread 1 on vring 2
2444  *    thread 2 on vring 0
2445  *
2446  * Memory regions (total 2)
2447  * region fd guest_phys_addr memory_size userspace_addr mmap_offset mmap_addr
2448  * ====== == =============== =========== ============== =========== ==========
2449  *   0    60  0x00000000     0x000a0000  0xaac00000     0x00000000  0x2b400000
2450  *   1    61  0x000c0000     0x3ff40000  0xaacc0000     0x000c0000  0xabcc0000
2451  *
2452  *  Virtqueue 0 (TX)
2453  *   qsz 256 last_avail_idx 0 last_used_idx 0
2454  *   avail.flags 1 avail.idx 128 used.flags 1 used.idx 0
2455  *   kickfd 62 callfd 64 errfd -1
2456  *
2457  *  Virtqueue 1 (RX)
2458  *   qsz 256 last_avail_idx 0 last_used_idx 0
2459  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
2460  *   kickfd 65 callfd 66 errfd -1
2461  *
2462  *  Virtqueue 2 (TX)
2463  *   qsz 256 last_avail_idx 0 last_used_idx 0
2464  *   avail.flags 1 avail.idx 128 used.flags 1 used.idx 0
2465  *   kickfd 63 callfd 70 errfd -1
2466  *
2467  *  Virtqueue 3 (RX)
2468  *   qsz 256 last_avail_idx 0 last_used_idx 0
2469  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
2470  *   kickfd 72 callfd 74 errfd -1
2471  *
2472  *  Virtqueue 4 (TX disabled)
2473  *   qsz 256 last_avail_idx 0 last_used_idx 0
2474  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
2475  *   kickfd 76 callfd 78 errfd -1
2476  *
2477  *  Virtqueue 5 (RX disabled)
2478  *   qsz 256 last_avail_idx 0 last_used_idx 0
2479  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
2480  *   kickfd 80 callfd 82 errfd -1
2481  *
2482  *  Virtqueue 6 (TX disabled)
2483  *   qsz 256 last_avail_idx 0 last_used_idx 0
2484  *  avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
2485  *   kickfd 84 callfd 86 errfd -1
2486  *
2487  *  Virtqueue 7 (RX disabled)
2488  *   qsz 256 last_avail_idx 0 last_used_idx 0
2489  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
2490  *   kickfd 88 callfd 90 errfd -1
2491  *
2492  * @cliexend
2493  *
2494  * The optional '<em>descriptors</em>' parameter will display the same output
2495  * as the previous example but will include the descriptor table for each
2496  * queue.
2497  * The output is truncated below:
2498  * @cliexstart{show vhost-user VirtualEthernet0/0/0 descriptors}
2499  * Virtio vhost-user interfaces
2500  * Global:
2501  *   coalesce frames 32 time 1e-3
2502  * Interface: VirtualEthernet0/0/0 (ifindex 1)
2503  * virtio_net_hdr_sz 12
2504  *  features mask (0xffffffffffffffff):
2505  *  features (0x50408000):
2506  *    VIRTIO_NET_F_MRG_RXBUF (15)
2507  *    VIRTIO_NET_F_MQ (22)
2508  * :
2509  *  Virtqueue 0 (TX)
2510  *   qsz 256 last_avail_idx 0 last_used_idx 0
2511  *   avail.flags 1 avail.idx 128 used.flags 1 used.idx 0
2512  *   kickfd 62 callfd 64 errfd -1
2513  *
2514  *   descriptor table:
2515  *    id          addr         len  flags  next      user_addr
2516  *   ===== ================== ===== ====== ===== ==================
2517  *   0     0x0000000010b6e974 2060  0x0002 1     0x00002aabbc76e974
2518  *   1     0x0000000010b6e034 2060  0x0002 2     0x00002aabbc76e034
2519  *   2     0x0000000010b6d6f4 2060  0x0002 3     0x00002aabbc76d6f4
2520  *   3     0x0000000010b6cdb4 2060  0x0002 4     0x00002aabbc76cdb4
2521  *   4     0x0000000010b6c474 2060  0x0002 5     0x00002aabbc76c474
2522  *   5     0x0000000010b6bb34 2060  0x0002 6     0x00002aabbc76bb34
2523  *   6     0x0000000010b6b1f4 2060  0x0002 7     0x00002aabbc76b1f4
2524  *   7     0x0000000010b6a8b4 2060  0x0002 8     0x00002aabbc76a8b4
2525  *   8     0x0000000010b69f74 2060  0x0002 9     0x00002aabbc769f74
2526  *   9     0x0000000010b69634 2060  0x0002 10    0x00002aabbc769634
2527  *   10    0x0000000010b68cf4 2060  0x0002 11    0x00002aabbc768cf4
2528  * :
2529  *   249   0x0000000000000000 0     0x0000 250   0x00002aab2b400000
2530  *   250   0x0000000000000000 0     0x0000 251   0x00002aab2b400000
2531  *   251   0x0000000000000000 0     0x0000 252   0x00002aab2b400000
2532  *   252   0x0000000000000000 0     0x0000 253   0x00002aab2b400000
2533  *   253   0x0000000000000000 0     0x0000 254   0x00002aab2b400000
2534  *   254   0x0000000000000000 0     0x0000 255   0x00002aab2b400000
2535  *   255   0x0000000000000000 0     0x0000 32768 0x00002aab2b400000
2536  *
2537  *  Virtqueue 1 (RX)
2538  *   qsz 256 last_avail_idx 0 last_used_idx 0
2539  * :
2540  * @cliexend
2541  * @endparblock
2542 ?*/
2543 VLIB_CLI_COMMAND (show_vhost_user_command, static) = {
2544     .path = "show vhost-user",
2545     .short_help = "show vhost-user [<interface> [<interface> [..]]] "
2546     "[[descriptors] [verbose]]",
2547     .function = show_vhost_user_command_fn,
2548 };
2549
2550
2551 static clib_error_t *
2552 vhost_user_config (vlib_main_t * vm, unformat_input_t * input)
2553 {
2554   vhost_user_main_t *vum = &vhost_user_main;
2555
2556   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2557     {
2558       if (unformat (input, "coalesce-frames %d", &vum->coalesce_frames))
2559         ;
2560       else if (unformat (input, "coalesce-time %f", &vum->coalesce_time))
2561         ;
2562       else if (unformat (input, "dont-dump-memory"))
2563         vum->dont_dump_vhost_user_memory = 1;
2564       else
2565         return clib_error_return (0, "unknown input `%U'",
2566                                   format_unformat_error, input);
2567     }
2568
2569   return 0;
2570 }
2571
2572 /* vhost-user { ... } configuration. */
2573 VLIB_CONFIG_FUNCTION (vhost_user_config, "vhost-user");
2574
2575 void
2576 vhost_user_unmap_all (void)
2577 {
2578   vhost_user_main_t *vum = &vhost_user_main;
2579   vhost_user_intf_t *vui;
2580
2581   if (vum->dont_dump_vhost_user_memory)
2582     {
2583       pool_foreach (vui, vum->vhost_user_interfaces)
2584         unmap_all_mem_regions (vui);
2585     }
2586 }
2587
2588 /*
2589  * fd.io coding-style-patch-verification: ON
2590  *
2591  * Local Variables:
2592  * eval: (c-set-style "gnu")
2593  * End:
2594  */