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