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