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