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