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