6a7bbc16f7e5d13f991d81871f9d483aaf53bf9b
[vpp.git] / vnet / vnet / devices / virtio / vhost-user.c
1 /*
2  *------------------------------------------------------------------
3  * vhost.c - vhost-user
4  *
5  * Copyright (c) 2014 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
44 /**
45  * @file
46  * @brief vHost User Device Driver.
47  *
48  * This file contains the source code for vHost User interface.
49  */
50
51
52 #define VHOST_USER_DEBUG_SOCKET 0
53 #define VHOST_DEBUG_VQ 0
54
55 #if VHOST_USER_DEBUG_SOCKET == 1
56 #define DBG_SOCK(args...) clib_warning(args);
57 #else
58 #define DBG_SOCK(args...)
59 #endif
60
61 #if VHOST_DEBUG_VQ == 1
62 #define DBG_VQ(args...) clib_warning(args);
63 #else
64 #define DBG_VQ(args...)
65 #endif
66
67 #define foreach_virtio_trace_flags \
68   _ (SIMPLE_CHAINED, 0, "Simple descriptor chaining") \
69   _ (SINGLE_DESC,  1, "Single descriptor packet") \
70   _ (INDIRECT, 2, "Indirect descriptor") \
71   _ (MAP_ERROR, 4, "Memory mapping error")
72
73 typedef enum
74 {
75 #define _(n,i,s) VIRTIO_TRACE_F_##n,
76   foreach_virtio_trace_flags
77 #undef _
78 } virtio_trace_flag_t;
79
80 vlib_node_registration_t vhost_user_input_node;
81
82 #define foreach_vhost_user_tx_func_error      \
83   _(NONE, "no error")  \
84   _(NOT_READY, "vhost user state error")  \
85   _(PKT_DROP_NOBUF, "tx packet drops (no available descriptors)")  \
86   _(PKT_DROP_NOMRG, "tx packet drops (cannot merge descriptors)")  \
87   _(MMAP_FAIL, "mmap failure") \
88   _(INDIRECT_OVERFLOW, "indirect descriptor table overflow")
89
90 typedef enum
91 {
92 #define _(f,s) VHOST_USER_TX_FUNC_ERROR_##f,
93   foreach_vhost_user_tx_func_error
94 #undef _
95     VHOST_USER_TX_FUNC_N_ERROR,
96 } vhost_user_tx_func_error_t;
97
98 static char *vhost_user_tx_func_error_strings[] = {
99 #define _(n,s) s,
100   foreach_vhost_user_tx_func_error
101 #undef _
102 };
103
104 #define foreach_vhost_user_input_func_error      \
105   _(NO_ERROR, "no error")  \
106   _(NO_BUFFER, "no available buffer")  \
107   _(MMAP_FAIL, "mmap failure")  \
108   _(INDIRECT_OVERFLOW, "indirect descriptor overflows table")  \
109   _(UNDERSIZED_FRAME, "undersized ethernet frame received (< 14 bytes)") \
110   _(FULL_RX_QUEUE, "full rx queue (possible driver tx drop)")
111
112 typedef enum
113 {
114 #define _(f,s) VHOST_USER_INPUT_FUNC_ERROR_##f,
115   foreach_vhost_user_input_func_error
116 #undef _
117     VHOST_USER_INPUT_FUNC_N_ERROR,
118 } vhost_user_input_func_error_t;
119
120 static char *vhost_user_input_func_error_strings[] = {
121 #define _(n,s) s,
122   foreach_vhost_user_input_func_error
123 #undef _
124 };
125
126 /* *INDENT-OFF* */
127 static vhost_user_main_t vhost_user_main = {
128   .mtu_bytes = 1518,
129 };
130
131 VNET_HW_INTERFACE_CLASS (vhost_interface_class, static) = {
132   .name = "vhost-user",
133 };
134 /* *INDENT-ON* */
135
136 static u8 *
137 format_vhost_user_interface_name (u8 * s, va_list * args)
138 {
139   u32 i = va_arg (*args, u32);
140   u32 show_dev_instance = ~0;
141   vhost_user_main_t *vum = &vhost_user_main;
142
143   if (i < vec_len (vum->show_dev_instance_by_real_dev_instance))
144     show_dev_instance = vum->show_dev_instance_by_real_dev_instance[i];
145
146   if (show_dev_instance != ~0)
147     i = show_dev_instance;
148
149   s = format (s, "VirtualEthernet0/0/%d", i);
150   return s;
151 }
152
153 static int
154 vhost_user_name_renumber (vnet_hw_interface_t * hi, u32 new_dev_instance)
155 {
156   vhost_user_main_t *vum = &vhost_user_main;
157
158   vec_validate_init_empty (vum->show_dev_instance_by_real_dev_instance,
159                            hi->dev_instance, ~0);
160
161   vum->show_dev_instance_by_real_dev_instance[hi->dev_instance] =
162     new_dev_instance;
163
164   DBG_SOCK ("renumbered vhost-user interface dev_instance %d to %d",
165             hi->dev_instance, new_dev_instance);
166
167   return 0;
168 }
169
170 static_always_inline void *
171 map_guest_mem (vhost_user_intf_t * vui, uword addr, u32 * hint)
172 {
173   int i = *hint;
174   if (PREDICT_TRUE ((vui->regions[i].guest_phys_addr <= addr) &&
175                     ((vui->regions[i].guest_phys_addr +
176                       vui->regions[i].memory_size) > addr)))
177     {
178       return (void *) (vui->region_mmap_addr[i] + addr -
179                        vui->regions[i].guest_phys_addr);
180     }
181 #if __SSE4_2__
182   __m128i rl, rh, al, ah, r;
183   al = _mm_set1_epi64x (addr + 1);
184   ah = _mm_set1_epi64x (addr);
185
186   rl = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_lo[0]);
187   rl = _mm_cmpgt_epi64 (al, rl);
188   rh = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_hi[0]);
189   rh = _mm_cmpgt_epi64 (rh, ah);
190   r = _mm_and_si128 (rl, rh);
191
192   rl = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_lo[2]);
193   rl = _mm_cmpgt_epi64 (al, rl);
194   rh = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_hi[2]);
195   rh = _mm_cmpgt_epi64 (rh, ah);
196   r = _mm_blend_epi16 (r, _mm_and_si128 (rl, rh), 0x22);
197
198   rl = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_lo[4]);
199   rl = _mm_cmpgt_epi64 (al, rl);
200   rh = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_hi[4]);
201   rh = _mm_cmpgt_epi64 (rh, ah);
202   r = _mm_blend_epi16 (r, _mm_and_si128 (rl, rh), 0x44);
203
204   rl = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_lo[6]);
205   rl = _mm_cmpgt_epi64 (al, rl);
206   rh = _mm_loadu_si128 ((__m128i *) & vui->region_guest_addr_hi[6]);
207   rh = _mm_cmpgt_epi64 (rh, ah);
208   r = _mm_blend_epi16 (r, _mm_and_si128 (rl, rh), 0x88);
209
210   r = _mm_shuffle_epi8 (r, _mm_set_epi64x (0, 0x0e060c040a020800));
211   i = __builtin_ctzll (_mm_movemask_epi8 (r));
212
213   if (i < vui->nregions)
214     {
215       *hint = i;
216       return (void *) (vui->region_mmap_addr[i] + addr -
217                        vui->regions[i].guest_phys_addr);
218     }
219
220 #else
221   for (i = 0; i < vui->nregions; i++)
222     {
223       if ((vui->regions[i].guest_phys_addr <= addr) &&
224           ((vui->regions[i].guest_phys_addr + vui->regions[i].memory_size) >
225            addr))
226         {
227           *hint = i;
228           return (void *) (vui->region_mmap_addr[i] + addr -
229                            vui->regions[i].guest_phys_addr);
230         }
231     }
232 #endif
233   DBG_VQ ("failed to map guest mem addr %llx", addr);
234   *hint = 0;
235   return 0;
236 }
237
238 static inline void *
239 map_user_mem (vhost_user_intf_t * vui, uword addr)
240 {
241   int i;
242   for (i = 0; i < vui->nregions; i++)
243     {
244       if ((vui->regions[i].userspace_addr <= addr) &&
245           ((vui->regions[i].userspace_addr + vui->regions[i].memory_size) >
246            addr))
247         {
248           return (void *) (vui->region_mmap_addr[i] + addr -
249                            vui->regions[i].userspace_addr);
250         }
251     }
252   return 0;
253 }
254
255 static long
256 get_huge_page_size (int fd)
257 {
258   struct statfs s;
259   fstatfs (fd, &s);
260   return s.f_bsize;
261 }
262
263 static void
264 unmap_all_mem_regions (vhost_user_intf_t * vui)
265 {
266   int i, r;
267   for (i = 0; i < vui->nregions; i++)
268     {
269       if (vui->region_mmap_addr[i] != (void *) -1)
270         {
271
272           long page_sz = get_huge_page_size (vui->region_mmap_fd[i]);
273
274           ssize_t map_sz = (vui->regions[i].memory_size +
275                             vui->regions[i].mmap_offset +
276                             page_sz) & ~(page_sz - 1);
277
278           r =
279             munmap (vui->region_mmap_addr[i] - vui->regions[i].mmap_offset,
280                     map_sz);
281
282           DBG_SOCK
283             ("unmap memory region %d addr 0x%lx len 0x%lx page_sz 0x%x", i,
284              vui->region_mmap_addr[i], map_sz, page_sz);
285
286           vui->region_mmap_addr[i] = (void *) -1;
287
288           if (r == -1)
289             {
290               clib_warning ("failed to unmap memory region (errno %d)",
291                             errno);
292             }
293           close (vui->region_mmap_fd[i]);
294         }
295     }
296   vui->nregions = 0;
297 }
298
299 static void
300 vhost_user_tx_thread_placement (vhost_user_intf_t * vui)
301 {
302   //Let's try to assign one queue to each thread
303   u32 qid = 0;
304   u32 cpu_index = 0;
305   vui->use_tx_spinlock = 0;
306   while (1)
307     {
308       for (qid = 0; qid < VHOST_VRING_MAX_N / 2; qid++)
309         {
310           vhost_user_vring_t *rxvq = &vui->vrings[VHOST_VRING_IDX_RX (qid)];
311           if (!rxvq->started || !rxvq->enabled)
312             continue;
313
314           vui->per_cpu_tx_qid[cpu_index] = qid;
315           cpu_index++;
316           if (cpu_index == vlib_get_thread_main ()->n_vlib_mains)
317             return;
318         }
319       //We need to loop, meaning the spinlock has to be used
320       vui->use_tx_spinlock = 1;
321       if (cpu_index == 0)
322         {
323           //Could not find a single valid one
324           for (cpu_index = 0;
325                cpu_index < vlib_get_thread_main ()->n_vlib_mains; cpu_index++)
326             {
327               vui->per_cpu_tx_qid[cpu_index] = 0;
328             }
329           return;
330         }
331     }
332 }
333
334 static void
335 vhost_user_rx_thread_placement ()
336 {
337   vhost_user_main_t *vum = &vhost_user_main;
338   vhost_user_intf_t *vui;
339   vhost_cpu_t *vhc;
340   u32 *workers = 0;
341
342   //Let's list all workers cpu indexes
343   u32 i;
344   for (i = vum->input_cpu_first_index;
345        i < vum->input_cpu_first_index + vum->input_cpu_count; i++)
346     {
347       vlib_node_set_state (vlib_mains ? vlib_mains[i] : &vlib_global_main,
348                            vhost_user_input_node.index,
349                            VLIB_NODE_STATE_DISABLED);
350       vec_add1 (workers, i);
351     }
352
353   vec_foreach (vhc, vum->cpus)
354   {
355     vec_reset_length (vhc->rx_queues);
356   }
357
358   i = 0;
359   vec_foreach (vui, vum->vhost_user_interfaces)
360   {
361     if (!vui->active)
362       continue;
363
364     u32 *vui_workers = vec_len (vui->workers) ? vui->workers : workers;
365     u32 qid;
366     for (qid = 0; qid < VHOST_VRING_MAX_N / 2; qid++)
367       {
368         vhost_user_vring_t *txvq = &vui->vrings[VHOST_VRING_IDX_TX (qid)];
369         if (!txvq->started)
370           continue;
371
372         i %= vec_len (vui_workers);
373         u32 cpu_index = vui_workers[i];
374         i++;
375         vhc = &vum->cpus[cpu_index];
376
377         vhost_iface_and_queue_t iaq = {
378           .qid = qid,
379           .vhost_iface_index = vui - vum->vhost_user_interfaces,
380         };
381         vec_add1 (vhc->rx_queues, iaq);
382         vlib_node_set_state (vlib_mains ? vlib_mains[cpu_index] :
383                              &vlib_global_main, vhost_user_input_node.index,
384                              VLIB_NODE_STATE_POLLING);
385       }
386   }
387 }
388
389 static int
390 vhost_user_thread_placement (u32 sw_if_index, u32 worker_thread_index, u8 del)
391 {
392   vhost_user_main_t *vum = &vhost_user_main;
393   vhost_user_intf_t *vui;
394   vnet_hw_interface_t *hw;
395
396   if (worker_thread_index < vum->input_cpu_first_index ||
397       worker_thread_index >=
398       vum->input_cpu_first_index + vum->input_cpu_count)
399     return -1;
400
401   if (!(hw = vnet_get_sup_hw_interface (vnet_get_main (), sw_if_index)))
402     return -2;
403
404   vui = vec_elt_at_index (vum->vhost_user_interfaces, hw->dev_instance);
405   u32 found = ~0, *w;
406   vec_foreach (w, vui->workers)
407   {
408     if (*w == worker_thread_index)
409       {
410         found = w - vui->workers;
411         break;
412       }
413   }
414
415   if (del)
416     {
417       if (found == ~0)
418         return -3;
419       vec_del1 (vui->workers, found);
420     }
421   else if (found == ~0)
422     {
423       vec_add1 (vui->workers, worker_thread_index);
424     }
425
426   vhost_user_rx_thread_placement ();
427   return 0;
428 }
429
430 /** @brief Returns whether at least one TX and one RX vring are enabled */
431 int
432 vhost_user_intf_ready (vhost_user_intf_t * vui)
433 {
434   int i, found[2] = { };        //RX + TX
435
436   for (i = 0; i < VHOST_VRING_MAX_N; i++)
437     if (vui->vrings[i].started && vui->vrings[i].enabled)
438       found[i & 1] = 1;
439
440   return found[0] && found[1];
441 }
442
443 static void
444 vhost_user_update_iface_state (vhost_user_intf_t * vui)
445 {
446   /* if we have pointers to descriptor table, go up */
447   int is_up = vhost_user_intf_ready (vui);
448   if (is_up != vui->is_up)
449     {
450       DBG_SOCK ("interface %d %s", vui->sw_if_index,
451                 is_up ? "ready" : "down");
452       vnet_hw_interface_set_flags (vnet_get_main (), vui->hw_if_index,
453                                    is_up ? VNET_HW_INTERFACE_FLAG_LINK_UP :
454                                    0);
455       vui->is_up = is_up;
456     }
457   vhost_user_rx_thread_placement ();
458   vhost_user_tx_thread_placement (vui);
459 }
460
461 static clib_error_t *
462 vhost_user_callfd_read_ready (unix_file_t * uf)
463 {
464   __attribute__ ((unused)) int n;
465   u8 buff[8];
466   n = read (uf->file_descriptor, ((char *) &buff), 8);
467   return 0;
468 }
469
470 static clib_error_t *
471 vhost_user_kickfd_read_ready (unix_file_t * uf)
472 {
473   __attribute__ ((unused)) int n;
474   u8 buff[8];
475   vhost_user_intf_t *vui =
476     vec_elt_at_index (vhost_user_main.vhost_user_interfaces,
477                       uf->private_data >> 8);
478   u32 qid = uf->private_data & 0xff;
479   n = read (uf->file_descriptor, ((char *) &buff), 8);
480   DBG_SOCK ("if %d KICK queue %d", uf->private_data >> 8, qid);
481
482   vlib_worker_thread_barrier_sync (vlib_get_main ());
483   vui->vrings[qid].started = 1;
484   vhost_user_update_iface_state (vui);
485   vlib_worker_thread_barrier_release (vlib_get_main ());
486   return 0;
487 }
488
489 /**
490  * @brief Try once to lock the vring
491  * @return 0 on success, non-zero on failure.
492  */
493 static inline int
494 vhost_user_vring_try_lock (vhost_user_intf_t * vui, u32 qid)
495 {
496   return __sync_lock_test_and_set (vui->vring_locks[qid], 1);
497 }
498
499 /**
500  * @brief Spin until the vring is successfully locked
501  */
502 static inline void
503 vhost_user_vring_lock (vhost_user_intf_t * vui, u32 qid)
504 {
505   while (vhost_user_vring_try_lock (vui, qid))
506     ;
507 }
508
509 /**
510  * @brief Unlock the vring lock
511  */
512 static inline void
513 vhost_user_vring_unlock (vhost_user_intf_t * vui, u32 qid)
514 {
515   *vui->vring_locks[qid] = 0;
516 }
517
518 static inline void
519 vhost_user_vring_init (vhost_user_intf_t * vui, u32 qid)
520 {
521   vhost_user_vring_t *vring = &vui->vrings[qid];
522   memset (vring, 0, sizeof (*vring));
523   vring->kickfd = -1;
524   vring->callfd = -1;
525   vring->errfd = -1;
526
527   /*
528    * We have a bug with some qemu 2.5, and this may be a fix.
529    * Feel like interpretation holy text, but this is from vhost-user.txt.
530    * "
531    * One queue pair is enabled initially. More queues are enabled
532    * dynamically, by sending message VHOST_USER_SET_VRING_ENABLE.
533    * "
534    * Don't know who's right, but this is what DPDK does.
535    */
536   if (qid == 0 || qid == 1)
537     vring->enabled = 1;
538 }
539
540 static inline void
541 vhost_user_vring_close (vhost_user_intf_t * vui, u32 qid)
542 {
543   vhost_user_vring_t *vring = &vui->vrings[qid];
544   if (vring->kickfd != -1)
545     {
546       unix_file_t *uf = pool_elt_at_index (unix_main.file_pool,
547                                            vring->kickfd_idx);
548       unix_file_del (&unix_main, uf);
549     }
550   if (vring->callfd != -1)
551     {
552       unix_file_t *uf = pool_elt_at_index (unix_main.file_pool,
553                                            vring->callfd_idx);
554       unix_file_del (&unix_main, uf);
555     }
556   if (vring->errfd != -1)
557     close (vring->errfd);
558   vhost_user_vring_init (vui, qid);
559 }
560
561 static inline void
562 vhost_user_if_disconnect (vhost_user_intf_t * vui)
563 {
564   vhost_user_main_t *vum = &vhost_user_main;
565   vnet_main_t *vnm = vnet_get_main ();
566   int q;
567
568   vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
569
570   if (vui->unix_file_index != ~0)
571     {
572       unix_file_del (&unix_main, unix_main.file_pool + vui->unix_file_index);
573       vui->unix_file_index = ~0;
574     }
575   else
576     close (vui->unix_fd);
577
578   hash_unset (vum->vhost_user_interface_index_by_sock_fd, vui->unix_fd);
579   hash_unset (vum->vhost_user_interface_index_by_listener_fd, vui->unix_fd);
580   vui->unix_fd = -1;
581   vui->is_up = 0;
582
583   for (q = 0; q < VHOST_VRING_MAX_N; q++)
584     vhost_user_vring_close (vui, q);
585
586   unmap_all_mem_regions (vui);
587   DBG_SOCK ("interface ifindex %d disconnected", vui->sw_if_index);
588 }
589
590 #define VHOST_LOG_PAGE 0x1000
591 always_inline void
592 vhost_user_log_dirty_pages (vhost_user_intf_t * vui, u64 addr, u64 len)
593 {
594   if (PREDICT_TRUE (vui->log_base_addr == 0
595                     || !(vui->features & (1 << FEAT_VHOST_F_LOG_ALL))))
596     {
597       return;
598     }
599   if (PREDICT_FALSE ((addr + len - 1) / VHOST_LOG_PAGE / 8 >= vui->log_size))
600     {
601       DBG_SOCK ("vhost_user_log_dirty_pages(): out of range\n");
602       return;
603     }
604
605   CLIB_MEMORY_BARRIER ();
606   u64 page = addr / VHOST_LOG_PAGE;
607   while (page * VHOST_LOG_PAGE < addr + len)
608     {
609       ((u8 *) vui->log_base_addr)[page / 8] |= 1 << page % 8;
610       page++;
611     }
612 }
613
614 #define vhost_user_log_dirty_ring(vui, vq, member) \
615   if (PREDICT_FALSE(vq->log_used)) { \
616     vhost_user_log_dirty_pages(vui, vq->log_guest_addr + STRUCT_OFFSET_OF(vring_used_t, member), \
617                              sizeof(vq->used->member)); \
618   }
619
620 static clib_error_t *
621 vhost_user_socket_read (unix_file_t * uf)
622 {
623   int n, i;
624   int fd, number_of_fds = 0;
625   int fds[VHOST_MEMORY_MAX_NREGIONS];
626   vhost_user_msg_t msg;
627   struct msghdr mh;
628   struct iovec iov[1];
629   vhost_user_main_t *vum = &vhost_user_main;
630   vhost_user_intf_t *vui;
631   struct cmsghdr *cmsg;
632   uword *p;
633   u8 q;
634   unix_file_t template = { 0 };
635   vnet_main_t *vnm = vnet_get_main ();
636
637   p = hash_get (vum->vhost_user_interface_index_by_sock_fd,
638                 uf->file_descriptor);
639   if (p == 0)
640     {
641       DBG_SOCK ("FD %d doesn't belong to any interface", uf->file_descriptor);
642       return 0;
643     }
644   else
645     vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
646
647   char control[CMSG_SPACE (VHOST_MEMORY_MAX_NREGIONS * sizeof (int))];
648
649   memset (&mh, 0, sizeof (mh));
650   memset (control, 0, sizeof (control));
651
652   for (i = 0; i < VHOST_MEMORY_MAX_NREGIONS; i++)
653     fds[i] = -1;
654
655   /* set the payload */
656   iov[0].iov_base = (void *) &msg;
657   iov[0].iov_len = VHOST_USER_MSG_HDR_SZ;
658
659   mh.msg_iov = iov;
660   mh.msg_iovlen = 1;
661   mh.msg_control = control;
662   mh.msg_controllen = sizeof (control);
663
664   n = recvmsg (uf->file_descriptor, &mh, 0);
665
666   /* Stop workers to avoid end of the world */
667   vlib_worker_thread_barrier_sync (vlib_get_main ());
668
669   if (n != VHOST_USER_MSG_HDR_SZ)
670     {
671       if (n == -1)
672         {
673           DBG_SOCK ("recvmsg returned error %d %s", errno, strerror (errno));
674         }
675       else
676         {
677           DBG_SOCK ("n (%d) != VHOST_USER_MSG_HDR_SZ (%d)",
678                     n, VHOST_USER_MSG_HDR_SZ);
679         }
680       goto close_socket;
681     }
682
683   if (mh.msg_flags & MSG_CTRUNC)
684     {
685       DBG_SOCK ("MSG_CTRUNC is set");
686       goto close_socket;
687     }
688
689   cmsg = CMSG_FIRSTHDR (&mh);
690
691   if (cmsg && (cmsg->cmsg_len > 0) && (cmsg->cmsg_level == SOL_SOCKET) &&
692       (cmsg->cmsg_type == SCM_RIGHTS) &&
693       (cmsg->cmsg_len - CMSG_LEN (0) <=
694        VHOST_MEMORY_MAX_NREGIONS * sizeof (int)))
695     {
696       number_of_fds = (cmsg->cmsg_len - CMSG_LEN (0)) / sizeof (int);
697       clib_memcpy (fds, CMSG_DATA (cmsg), number_of_fds * sizeof (int));
698     }
699
700   /* version 1, no reply bit set */
701   if ((msg.flags & 7) != 1)
702     {
703       DBG_SOCK ("malformed message received. closing socket");
704       goto close_socket;
705     }
706
707   {
708     int rv;
709     rv =
710       read (uf->file_descriptor, ((char *) &msg) + VHOST_USER_MSG_HDR_SZ,
711             msg.size);
712     if (rv < 0)
713       {
714         DBG_SOCK ("read failed %s", strerror (errno));
715         goto close_socket;
716       }
717     else if (rv != msg.size)
718       {
719         DBG_SOCK ("message too short (read %dB should be %dB)", rv, msg.size);
720         goto close_socket;
721       }
722   }
723
724   switch (msg.request)
725     {
726     case VHOST_USER_GET_FEATURES:
727       msg.flags |= 4;
728       msg.u64 = (1ULL << FEAT_VIRTIO_NET_F_MRG_RXBUF) |
729         (1ULL << FEAT_VIRTIO_NET_F_CTRL_VQ) |
730         (1ULL << FEAT_VIRTIO_F_ANY_LAYOUT) |
731         (1ULL << FEAT_VIRTIO_F_INDIRECT_DESC) |
732         (1ULL << FEAT_VHOST_F_LOG_ALL) |
733         (1ULL << FEAT_VIRTIO_NET_F_GUEST_ANNOUNCE) |
734         (1ULL << FEAT_VIRTIO_NET_F_MQ) |
735         (1ULL << FEAT_VHOST_USER_F_PROTOCOL_FEATURES) |
736         (1ULL << FEAT_VIRTIO_F_VERSION_1);
737       msg.u64 &= vui->feature_mask;
738       msg.size = sizeof (msg.u64);
739       DBG_SOCK ("if %d msg VHOST_USER_GET_FEATURES - reply 0x%016llx",
740                 vui->hw_if_index, msg.u64);
741       break;
742
743     case VHOST_USER_SET_FEATURES:
744       DBG_SOCK ("if %d msg VHOST_USER_SET_FEATURES features 0x%016llx",
745                 vui->hw_if_index, msg.u64);
746
747       vui->features = msg.u64;
748
749       if (vui->features &
750           ((1 << FEAT_VIRTIO_NET_F_MRG_RXBUF) |
751            (1ULL << FEAT_VIRTIO_F_VERSION_1)))
752         vui->virtio_net_hdr_sz = 12;
753       else
754         vui->virtio_net_hdr_sz = 10;
755
756       vui->is_any_layout =
757         (vui->features & (1 << FEAT_VIRTIO_F_ANY_LAYOUT)) ? 1 : 0;
758
759       ASSERT (vui->virtio_net_hdr_sz < VLIB_BUFFER_PRE_DATA_SIZE);
760       vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
761       vui->is_up = 0;
762
763       /*for (q = 0; q < VHOST_VRING_MAX_N; q++)
764          vhost_user_vring_close(&vui->vrings[q]); */
765
766       break;
767
768     case VHOST_USER_SET_MEM_TABLE:
769       DBG_SOCK ("if %d msg VHOST_USER_SET_MEM_TABLE nregions %d",
770                 vui->hw_if_index, msg.memory.nregions);
771
772       if ((msg.memory.nregions < 1) ||
773           (msg.memory.nregions > VHOST_MEMORY_MAX_NREGIONS))
774         {
775
776           DBG_SOCK ("number of mem regions must be between 1 and %i",
777                     VHOST_MEMORY_MAX_NREGIONS);
778
779           goto close_socket;
780         }
781
782       if (msg.memory.nregions != number_of_fds)
783         {
784           DBG_SOCK ("each memory region must have FD");
785           goto close_socket;
786         }
787       unmap_all_mem_regions (vui);
788       for (i = 0; i < msg.memory.nregions; i++)
789         {
790           clib_memcpy (&(vui->regions[i]), &msg.memory.regions[i],
791                        sizeof (vhost_user_memory_region_t));
792
793           long page_sz = get_huge_page_size (fds[i]);
794
795           /* align size to 2M page */
796           ssize_t map_sz = (vui->regions[i].memory_size +
797                             vui->regions[i].mmap_offset +
798                             page_sz) & ~(page_sz - 1);
799
800           vui->region_mmap_addr[i] = mmap (0, map_sz, PROT_READ | PROT_WRITE,
801                                            MAP_SHARED, fds[i], 0);
802           vui->region_guest_addr_lo[i] = vui->regions[i].guest_phys_addr;
803           vui->region_guest_addr_hi[i] = vui->regions[i].guest_phys_addr +
804             vui->regions[i].memory_size;
805
806           DBG_SOCK
807             ("map memory region %d addr 0 len 0x%lx fd %d mapped 0x%lx "
808              "page_sz 0x%x", i, map_sz, fds[i], vui->region_mmap_addr[i],
809              page_sz);
810
811           if (vui->region_mmap_addr[i] == MAP_FAILED)
812             {
813               clib_warning ("failed to map memory. errno is %d", errno);
814               goto close_socket;
815             }
816           vui->region_mmap_addr[i] += vui->regions[i].mmap_offset;
817           vui->region_mmap_fd[i] = fds[i];
818         }
819       vui->nregions = msg.memory.nregions;
820       break;
821
822     case VHOST_USER_SET_VRING_NUM:
823       DBG_SOCK ("if %d msg VHOST_USER_SET_VRING_NUM idx %d num %d",
824                 vui->hw_if_index, msg.state.index, msg.state.num);
825
826       if ((msg.state.num > 32768) ||    /* maximum ring size is 32768 */
827           (msg.state.num == 0) ||       /* it cannot be zero */
828           ((msg.state.num - 1) & msg.state.num))        /* must be power of 2 */
829         goto close_socket;
830       vui->vrings[msg.state.index].qsz = msg.state.num;
831       break;
832
833     case VHOST_USER_SET_VRING_ADDR:
834       DBG_SOCK ("if %d msg VHOST_USER_SET_VRING_ADDR idx %d",
835                 vui->hw_if_index, msg.state.index);
836
837       if (msg.state.index >= VHOST_VRING_MAX_N)
838         {
839           DBG_SOCK ("invalid vring index VHOST_USER_SET_VRING_ADDR:"
840                     " %d >= %d", msg.state.index, VHOST_VRING_MAX_N);
841           goto close_socket;
842         }
843
844       if (msg.size < sizeof (msg.addr))
845         {
846           DBG_SOCK ("vhost message is too short (%d < %d)",
847                     msg.size, sizeof (msg.addr));
848           goto close_socket;
849         }
850
851       vui->vrings[msg.state.index].desc = (vring_desc_t *)
852         map_user_mem (vui, msg.addr.desc_user_addr);
853       vui->vrings[msg.state.index].used = (vring_used_t *)
854         map_user_mem (vui, msg.addr.used_user_addr);
855       vui->vrings[msg.state.index].avail = (vring_avail_t *)
856         map_user_mem (vui, msg.addr.avail_user_addr);
857
858       if ((vui->vrings[msg.state.index].desc == NULL) ||
859           (vui->vrings[msg.state.index].used == NULL) ||
860           (vui->vrings[msg.state.index].avail == NULL))
861         {
862           DBG_SOCK ("failed to map user memory for hw_if_index %d",
863                     vui->hw_if_index);
864           goto close_socket;
865         }
866
867       vui->vrings[msg.state.index].log_guest_addr = msg.addr.log_guest_addr;
868       vui->vrings[msg.state.index].log_used =
869         (msg.addr.flags & (1 << VHOST_VRING_F_LOG)) ? 1 : 0;
870
871       /* Spec says: If VHOST_USER_F_PROTOCOL_FEATURES has not been negotiated,
872          the ring is initialized in an enabled state. */
873       if (!(vui->features & (1 << FEAT_VHOST_USER_F_PROTOCOL_FEATURES)))
874         {
875           vui->vrings[msg.state.index].enabled = 1;
876         }
877
878       vui->vrings[msg.state.index].last_used_idx =
879         vui->vrings[msg.state.index].last_avail_idx =
880         vui->vrings[msg.state.index].used->idx;
881
882       /* tell driver that we don't want interrupts */
883       vui->vrings[msg.state.index].used->flags = VRING_USED_F_NO_NOTIFY;
884       break;
885
886     case VHOST_USER_SET_OWNER:
887       DBG_SOCK ("if %d msg VHOST_USER_SET_OWNER", vui->hw_if_index);
888       break;
889
890     case VHOST_USER_RESET_OWNER:
891       DBG_SOCK ("if %d msg VHOST_USER_RESET_OWNER", vui->hw_if_index);
892       break;
893
894     case VHOST_USER_SET_VRING_CALL:
895       DBG_SOCK ("if %d msg VHOST_USER_SET_VRING_CALL u64 %d",
896                 vui->hw_if_index, msg.u64);
897
898       q = (u8) (msg.u64 & 0xFF);
899
900       /* if there is old fd, delete and close it */
901       if (vui->vrings[q].callfd != -1)
902         {
903           unix_file_t *uf = pool_elt_at_index (unix_main.file_pool,
904                                                vui->vrings[q].callfd_idx);
905           unix_file_del (&unix_main, uf);
906         }
907
908       if (!(msg.u64 & 0x100))
909         {
910           if (number_of_fds != 1)
911             {
912               DBG_SOCK ("More than one fd received !");
913               goto close_socket;
914             }
915
916           vui->vrings[q].callfd = fds[0];
917           template.read_function = vhost_user_callfd_read_ready;
918           template.file_descriptor = fds[0];
919           vui->vrings[q].callfd_idx = unix_file_add (&unix_main, &template);
920         }
921       else
922         vui->vrings[q].callfd = -1;
923       break;
924
925     case VHOST_USER_SET_VRING_KICK:
926       DBG_SOCK ("if %d msg VHOST_USER_SET_VRING_KICK u64 %d",
927                 vui->hw_if_index, msg.u64);
928
929       q = (u8) (msg.u64 & 0xFF);
930
931       if (vui->vrings[q].kickfd != -1)
932         {
933           unix_file_t *uf = pool_elt_at_index (unix_main.file_pool,
934                                                vui->vrings[q].kickfd);
935           unix_file_del (&unix_main, uf);
936         }
937
938       if (!(msg.u64 & 0x100))
939         {
940           if (number_of_fds != 1)
941             {
942               DBG_SOCK ("More than one fd received !");
943               goto close_socket;
944             }
945
946           if (vui->vrings[q].kickfd > -1)
947             close (vui->vrings[q].kickfd);
948
949           vui->vrings[q].kickfd = fds[0];
950           template.read_function = vhost_user_kickfd_read_ready;
951           template.file_descriptor = fds[0];
952           template.private_data =
953             ((vui - vhost_user_main.vhost_user_interfaces) << 8) + q;
954           vui->vrings[q].kickfd_idx = unix_file_add (&unix_main, &template);
955         }
956       else
957         {
958           vui->vrings[q].kickfd = -1;
959           vui->vrings[q].started = 1;
960         }
961
962       //TODO: When kickfd is specified, 'started' is set when the first kick
963       //is received.
964       break;
965
966     case VHOST_USER_SET_VRING_ERR:
967       DBG_SOCK ("if %d msg VHOST_USER_SET_VRING_ERR u64 %d",
968                 vui->hw_if_index, msg.u64);
969
970       q = (u8) (msg.u64 & 0xFF);
971
972       if (vui->vrings[q].errfd != -1)
973         close (vui->vrings[q].errfd);
974
975       if (!(msg.u64 & 0x100))
976         {
977           if (number_of_fds != 1)
978             goto close_socket;
979
980           vui->vrings[q].errfd = fds[0];
981         }
982       else
983         vui->vrings[q].errfd = -1;
984
985       break;
986
987     case VHOST_USER_SET_VRING_BASE:
988       DBG_SOCK ("if %d msg VHOST_USER_SET_VRING_BASE idx %d num %d",
989                 vui->hw_if_index, msg.state.index, msg.state.num);
990
991       vui->vrings[msg.state.index].last_avail_idx = msg.state.num;
992       break;
993
994     case VHOST_USER_GET_VRING_BASE:
995       DBG_SOCK ("if %d msg VHOST_USER_GET_VRING_BASE idx %d num %d",
996                 vui->hw_if_index, msg.state.index, msg.state.num);
997
998       if (msg.state.index >= VHOST_VRING_MAX_N)
999         {
1000           DBG_SOCK ("invalid vring index VHOST_USER_GET_VRING_BASE:"
1001                     " %d >= %d", msg.state.index, VHOST_VRING_MAX_N);
1002           goto close_socket;
1003         }
1004
1005       /* Spec says: Client must [...] stop ring upon receiving VHOST_USER_GET_VRING_BASE. */
1006       vhost_user_vring_close (vui, msg.state.index);
1007
1008       msg.state.num = vui->vrings[msg.state.index].last_avail_idx;
1009       msg.flags |= 4;
1010       msg.size = sizeof (msg.state);
1011       break;
1012
1013     case VHOST_USER_NONE:
1014       DBG_SOCK ("if %d msg VHOST_USER_NONE", vui->hw_if_index);
1015
1016       break;
1017
1018     case VHOST_USER_SET_LOG_BASE:
1019       {
1020         DBG_SOCK ("if %d msg VHOST_USER_SET_LOG_BASE", vui->hw_if_index);
1021
1022         if (msg.size != sizeof (msg.log))
1023           {
1024             DBG_SOCK
1025               ("invalid msg size for VHOST_USER_SET_LOG_BASE: %d instead of %d",
1026                msg.size, sizeof (msg.log));
1027             goto close_socket;
1028           }
1029
1030         if (!
1031             (vui->protocol_features & (1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD)))
1032           {
1033             DBG_SOCK
1034               ("VHOST_USER_PROTOCOL_F_LOG_SHMFD not set but VHOST_USER_SET_LOG_BASE received");
1035             goto close_socket;
1036           }
1037
1038         fd = fds[0];
1039         /* align size to 2M page */
1040         long page_sz = get_huge_page_size (fd);
1041         ssize_t map_sz =
1042           (msg.log.size + msg.log.offset + page_sz) & ~(page_sz - 1);
1043
1044         vui->log_base_addr = mmap (0, map_sz, PROT_READ | PROT_WRITE,
1045                                    MAP_SHARED, fd, 0);
1046
1047         DBG_SOCK
1048           ("map log region addr 0 len 0x%lx off 0x%lx fd %d mapped 0x%lx",
1049            map_sz, msg.log.offset, fd, vui->log_base_addr);
1050
1051         if (vui->log_base_addr == MAP_FAILED)
1052           {
1053             clib_warning ("failed to map memory. errno is %d", errno);
1054             goto close_socket;
1055           }
1056
1057         vui->log_base_addr += msg.log.offset;
1058         vui->log_size = msg.log.size;
1059
1060         msg.flags |= 4;
1061         msg.size = sizeof (msg.u64);
1062
1063         break;
1064       }
1065
1066     case VHOST_USER_SET_LOG_FD:
1067       DBG_SOCK ("if %d msg VHOST_USER_SET_LOG_FD", vui->hw_if_index);
1068
1069       break;
1070
1071     case VHOST_USER_GET_PROTOCOL_FEATURES:
1072       DBG_SOCK ("if %d msg VHOST_USER_GET_PROTOCOL_FEATURES",
1073                 vui->hw_if_index);
1074
1075       msg.flags |= 4;
1076       msg.u64 = (1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD) |
1077         (1 << VHOST_USER_PROTOCOL_F_MQ);
1078       msg.size = sizeof (msg.u64);
1079       break;
1080
1081     case VHOST_USER_SET_PROTOCOL_FEATURES:
1082       DBG_SOCK ("if %d msg VHOST_USER_SET_PROTOCOL_FEATURES features 0x%lx",
1083                 vui->hw_if_index, msg.u64);
1084
1085       vui->protocol_features = msg.u64;
1086
1087       break;
1088
1089     case VHOST_USER_GET_QUEUE_NUM:
1090       DBG_SOCK ("if %d msg VHOST_USER_GET_QUEUE_NUM", vui->hw_if_index);
1091       msg.flags |= 4;
1092       msg.u64 = VHOST_VRING_MAX_N;
1093       msg.size = sizeof (msg.u64);
1094       break;
1095
1096     case VHOST_USER_SET_VRING_ENABLE:
1097       DBG_SOCK ("if %d VHOST_USER_SET_VRING_ENABLE: %s queue %d",
1098                 vui->hw_if_index, msg.state.num ? "enable" : "disable",
1099                 msg.state.index);
1100       if (msg.state.index >= VHOST_VRING_MAX_N)
1101         {
1102           DBG_SOCK ("invalid vring index VHOST_USER_SET_VRING_ENABLE:"
1103                     " %d >= %d", msg.state.index, VHOST_VRING_MAX_N);
1104           goto close_socket;
1105         }
1106
1107       vui->vrings[msg.state.index].enabled = msg.state.num;
1108       break;
1109
1110     default:
1111       DBG_SOCK ("unknown vhost-user message %d received. closing socket",
1112                 msg.request);
1113       goto close_socket;
1114     }
1115
1116   /* if we need to reply */
1117   if (msg.flags & 4)
1118     {
1119       n =
1120         send (uf->file_descriptor, &msg, VHOST_USER_MSG_HDR_SZ + msg.size, 0);
1121       if (n != (msg.size + VHOST_USER_MSG_HDR_SZ))
1122         {
1123           DBG_SOCK ("could not send message response");
1124           goto close_socket;
1125         }
1126     }
1127
1128   vhost_user_update_iface_state (vui);
1129   vlib_worker_thread_barrier_release (vlib_get_main ());
1130   return 0;
1131
1132 close_socket:
1133   vhost_user_if_disconnect (vui);
1134   vhost_user_update_iface_state (vui);
1135   vlib_worker_thread_barrier_release (vlib_get_main ());
1136   return 0;
1137 }
1138
1139 static clib_error_t *
1140 vhost_user_socket_error (unix_file_t * uf)
1141 {
1142   vlib_main_t *vm = vlib_get_main ();
1143   vhost_user_main_t *vum = &vhost_user_main;
1144   vhost_user_intf_t *vui;
1145   uword *p;
1146
1147   p = hash_get (vum->vhost_user_interface_index_by_sock_fd,
1148                 uf->file_descriptor);
1149   if (p == 0)
1150     {
1151       DBG_SOCK ("fd %d doesn't belong to any interface", uf->file_descriptor);
1152       return 0;
1153     }
1154   else
1155     vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
1156
1157   DBG_SOCK ("socket error on if %d", vui->sw_if_index);
1158   vlib_worker_thread_barrier_sync (vm);
1159   vhost_user_if_disconnect (vui);
1160   vhost_user_rx_thread_placement ();
1161   vlib_worker_thread_barrier_release (vm);
1162   return 0;
1163 }
1164
1165 static clib_error_t *
1166 vhost_user_socksvr_accept_ready (unix_file_t * uf)
1167 {
1168   int client_fd, client_len;
1169   struct sockaddr_un client;
1170   unix_file_t template = { 0 };
1171   vhost_user_main_t *vum = &vhost_user_main;
1172   vhost_user_intf_t *vui;
1173   uword *p;
1174
1175   p = hash_get (vum->vhost_user_interface_index_by_listener_fd,
1176                 uf->file_descriptor);
1177   if (p == 0)
1178     {
1179       DBG_SOCK ("fd %d doesn't belong to any interface", uf->file_descriptor);
1180       return 0;
1181     }
1182   else
1183     vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
1184
1185   client_len = sizeof (client);
1186   client_fd = accept (uf->file_descriptor,
1187                       (struct sockaddr *) &client,
1188                       (socklen_t *) & client_len);
1189
1190   if (client_fd < 0)
1191     return clib_error_return_unix (0, "accept");
1192
1193   DBG_SOCK ("New client socket for vhost interface %d", vui->sw_if_index);
1194   template.read_function = vhost_user_socket_read;
1195   template.error_function = vhost_user_socket_error;
1196   template.file_descriptor = client_fd;
1197   vui->unix_file_index = unix_file_add (&unix_main, &template);
1198
1199   vui->client_fd = client_fd;
1200   hash_set (vum->vhost_user_interface_index_by_sock_fd, vui->client_fd,
1201             vui - vum->vhost_user_interfaces);
1202
1203   return 0;
1204 }
1205
1206 static clib_error_t *
1207 vhost_user_init (vlib_main_t * vm)
1208 {
1209   clib_error_t *error;
1210   vhost_user_main_t *vum = &vhost_user_main;
1211   vlib_thread_main_t *tm = vlib_get_thread_main ();
1212   vlib_thread_registration_t *tr;
1213   uword *p;
1214
1215   error = vlib_call_init_function (vm, ip4_init);
1216   if (error)
1217     return error;
1218
1219   vum->vhost_user_interface_index_by_listener_fd =
1220     hash_create (0, sizeof (uword));
1221   vum->vhost_user_interface_index_by_sock_fd =
1222     hash_create (0, sizeof (uword));
1223   vum->vhost_user_interface_index_by_sw_if_index =
1224     hash_create (0, sizeof (uword));
1225   vum->coalesce_frames = 32;
1226   vum->coalesce_time = 1e-3;
1227
1228   vec_validate_aligned (vum->rx_buffers, tm->n_vlib_mains - 1,
1229                         CLIB_CACHE_LINE_BYTES);
1230   vec_validate (vum->cpus, tm->n_vlib_mains - 1);
1231
1232   /* find out which cpus will be used for input */
1233   vum->input_cpu_first_index = 0;
1234   vum->input_cpu_count = 1;
1235   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
1236   tr = p ? (vlib_thread_registration_t *) p[0] : 0;
1237
1238   if (tr && tr->count > 0)
1239     {
1240       vum->input_cpu_first_index = tr->first_index;
1241       vum->input_cpu_count = tr->count;
1242     }
1243
1244   return 0;
1245 }
1246
1247 VLIB_INIT_FUNCTION (vhost_user_init);
1248
1249 static clib_error_t *
1250 vhost_user_exit (vlib_main_t * vm)
1251 {
1252   /* TODO cleanup */
1253   return 0;
1254 }
1255
1256 VLIB_MAIN_LOOP_EXIT_FUNCTION (vhost_user_exit);
1257
1258 typedef struct
1259 {
1260   u16 qid; /** The interface queue index (Not the virtio vring idx) */
1261   u16 device_index; /** The device index */
1262   u32 virtio_ring_flags; /** Runtime queue flags  **/
1263   u16 first_desc_len; /** Length of the first data descriptor **/
1264   virtio_net_hdr_mrg_rxbuf_t hdr; /** Virtio header **/
1265 } vhost_trace_t;
1266
1267 static u8 *
1268 format_vhost_trace (u8 * s, va_list * va)
1269 {
1270   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*va, vlib_main_t *);
1271   CLIB_UNUSED (vlib_node_t * node) = va_arg (*va, vlib_node_t *);
1272   CLIB_UNUSED (vnet_main_t * vnm) = vnet_get_main ();
1273   vhost_user_main_t *vum = &vhost_user_main;
1274   vhost_trace_t *t = va_arg (*va, vhost_trace_t *);
1275   vhost_user_intf_t *vui = vec_elt_at_index (vum->vhost_user_interfaces,
1276                                              t->device_index);
1277
1278   vnet_sw_interface_t *sw = vnet_get_sw_interface (vnm, vui->sw_if_index);
1279
1280   uword indent = format_get_indent (s);
1281
1282   s = format (s, "%U %U queue %d\n", format_white_space, indent,
1283               format_vnet_sw_interface_name, vnm, sw, t->qid);
1284
1285   s = format (s, "%U virtio flags:\n", format_white_space, indent);
1286 #define _(n,i,st) \
1287           if (t->virtio_ring_flags & (1 << VIRTIO_TRACE_F_##n)) \
1288             s = format (s, "%U  %s %s\n", format_white_space, indent, #n, st);
1289   foreach_virtio_trace_flags
1290 #undef _
1291     s = format (s, "%U virtio_net_hdr first_desc_len %u\n",
1292                 format_white_space, indent, t->first_desc_len);
1293
1294   s = format (s, "%U   flags 0x%02x gso_type %u\n",
1295               format_white_space, indent,
1296               t->hdr.hdr.flags, t->hdr.hdr.gso_type);
1297
1298   if (vui->virtio_net_hdr_sz == 12)
1299     s = format (s, "%U   num_buff %u",
1300                 format_white_space, indent, t->hdr.num_buffers);
1301
1302   return s;
1303 }
1304
1305 void
1306 vhost_user_rx_trace (vhost_trace_t * t,
1307                      vhost_user_intf_t * vui, u16 qid,
1308                      vlib_buffer_t * b, vhost_user_vring_t * txvq)
1309 {
1310   vhost_user_main_t *vum = &vhost_user_main;
1311   u32 qsz_mask = txvq->qsz - 1;
1312   u32 last_avail_idx = txvq->last_avail_idx;
1313   u32 desc_current = txvq->avail->ring[last_avail_idx & qsz_mask];
1314   vring_desc_t *hdr_desc = 0;
1315   virtio_net_hdr_mrg_rxbuf_t *hdr;
1316   u32 hint = 0;
1317
1318   memset (t, 0, sizeof (*t));
1319   t->device_index = vui - vum->vhost_user_interfaces;
1320   t->qid = qid;
1321
1322   hdr_desc = &txvq->desc[desc_current];
1323   if (txvq->desc[desc_current].flags & VIRTQ_DESC_F_INDIRECT)
1324     {
1325       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_INDIRECT;
1326       //Header is the first here
1327       hdr_desc = map_guest_mem (vui, txvq->desc[desc_current].addr, &hint);
1328     }
1329   if (txvq->desc[desc_current].flags & VIRTQ_DESC_F_NEXT)
1330     {
1331       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_SIMPLE_CHAINED;
1332     }
1333   if (!(txvq->desc[desc_current].flags & VIRTQ_DESC_F_NEXT) &&
1334       !(txvq->desc[desc_current].flags & VIRTQ_DESC_F_INDIRECT))
1335     {
1336       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_SINGLE_DESC;
1337     }
1338
1339   t->first_desc_len = hdr_desc ? hdr_desc->len : 0;
1340
1341   if (!hdr_desc || !(hdr = map_guest_mem (vui, hdr_desc->addr, &hint)))
1342     {
1343       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_MAP_ERROR;
1344     }
1345   else
1346     {
1347       u32 len = vui->virtio_net_hdr_sz;
1348       memcpy (&t->hdr, hdr, len > hdr_desc->len ? hdr_desc->len : len);
1349     }
1350 }
1351
1352 static inline void
1353 vhost_user_send_call (vlib_main_t * vm, vhost_user_vring_t * vq)
1354 {
1355   vhost_user_main_t *vum = &vhost_user_main;
1356   u64 x = 1;
1357   int rv __attribute__ ((unused));
1358   /* $$$$ pay attention to rv */
1359   rv = write (vq->callfd, &x, sizeof (x));
1360   vq->n_since_last_int = 0;
1361   vq->int_deadline = vlib_time_now (vm) + vum->coalesce_time;
1362 }
1363
1364
1365 static u32
1366 vhost_user_if_input (vlib_main_t * vm,
1367                      vhost_user_main_t * vum,
1368                      vhost_user_intf_t * vui,
1369                      u16 qid, vlib_node_runtime_t * node)
1370 {
1371   vhost_user_vring_t *txvq = &vui->vrings[VHOST_VRING_IDX_TX (qid)];
1372   vhost_user_vring_t *rxvq = &vui->vrings[VHOST_VRING_IDX_RX (qid)];
1373   uword n_rx_packets = 0, n_rx_bytes = 0;
1374   uword n_left;
1375   u32 n_left_to_next, *to_next;
1376   u32 next_index = 0;
1377   u32 next0;
1378   uword n_trace = vlib_get_trace_count (vm, node);
1379   u16 qsz_mask;
1380   u32 cpu_index, rx_len, drops, flush;
1381   f64 now = vlib_time_now (vm);
1382   u32 map_guest_hint_desc = 0;
1383   u32 map_guest_hint_indirect = 0;
1384   u32 *map_guest_hint_p = &map_guest_hint_desc;
1385
1386   /* do we have pending interrupts ? */
1387   if ((txvq->n_since_last_int) && (txvq->int_deadline < now))
1388     vhost_user_send_call (vm, txvq);
1389
1390   if ((rxvq->n_since_last_int) && (rxvq->int_deadline < now))
1391     vhost_user_send_call (vm, rxvq);
1392
1393   if (PREDICT_FALSE (txvq->avail->flags & 0xFFFE))
1394     return 0;
1395
1396   n_left = (u16) (txvq->avail->idx - txvq->last_avail_idx);
1397
1398   /* nothing to do */
1399   if (PREDICT_FALSE (n_left == 0))
1400     return 0;
1401
1402   if (PREDICT_FALSE (!vui->admin_up || !(txvq->enabled)))
1403     {
1404       /*
1405        * Discard input packet if interface is admin down or vring is not
1406        * enabled.
1407        * "For example, for a networking device, in the disabled state
1408        * client must not supply any new RX packets, but must process
1409        * and discard any TX packets."
1410        */
1411
1412       txvq->last_avail_idx = txvq->last_used_idx = txvq->avail->idx;
1413       CLIB_MEMORY_BARRIER ();
1414       txvq->used->idx = txvq->last_used_idx;
1415       vhost_user_log_dirty_ring (vui, txvq, idx);
1416       vhost_user_send_call (vm, txvq);
1417       return 0;
1418     }
1419
1420   if (PREDICT_FALSE (n_left == txvq->qsz))
1421     {
1422       //Informational error logging when VPP is not receiving packets fast enough
1423       vlib_error_count (vm, node->node_index,
1424                         VHOST_USER_INPUT_FUNC_ERROR_FULL_RX_QUEUE, 1);
1425     }
1426
1427   qsz_mask = txvq->qsz - 1;
1428   cpu_index = os_get_cpu_number ();
1429   drops = 0;
1430   flush = 0;
1431
1432   if (n_left > VLIB_FRAME_SIZE)
1433     n_left = VLIB_FRAME_SIZE;
1434
1435   /* Allocate some buffers.
1436    * Note that buffers that are chained for jumbo
1437    * frames are allocated separately using a slower path.
1438    * The idea is to be certain to have enough buffers at least
1439    * to cycle through the descriptors without having to check for errors.
1440    * For jumbo frames, the bottleneck is memory copy anyway.
1441    */
1442   if (PREDICT_FALSE (!vum->rx_buffers[cpu_index]))
1443     {
1444       vec_alloc (vum->rx_buffers[cpu_index], 2 * VLIB_FRAME_SIZE);
1445
1446       if (PREDICT_FALSE (!vum->rx_buffers[cpu_index]))
1447         flush = n_left;         //Drop all input
1448     }
1449
1450   if (PREDICT_FALSE (_vec_len (vum->rx_buffers[cpu_index]) < n_left))
1451     {
1452       u32 curr_len = _vec_len (vum->rx_buffers[cpu_index]);
1453       _vec_len (vum->rx_buffers[cpu_index]) +=
1454         vlib_buffer_alloc_from_free_list (vm,
1455                                           vum->rx_buffers[cpu_index] +
1456                                           curr_len,
1457                                           2 * VLIB_FRAME_SIZE - curr_len,
1458                                           VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX);
1459
1460       if (PREDICT_FALSE (n_left > _vec_len (vum->rx_buffers[cpu_index])))
1461         flush = n_left - _vec_len (vum->rx_buffers[cpu_index]);
1462     }
1463
1464   if (PREDICT_FALSE (flush))
1465     {
1466       //Remove some input buffers
1467       drops += flush;
1468       n_left -= flush;
1469       vlib_error_count (vm, vhost_user_input_node.index,
1470                         VHOST_USER_INPUT_FUNC_ERROR_NO_BUFFER, flush);
1471       while (flush)
1472         {
1473           u16 desc_chain_head =
1474             txvq->avail->ring[txvq->last_avail_idx & qsz_mask];
1475           txvq->last_avail_idx++;
1476           txvq->used->ring[txvq->last_used_idx & qsz_mask].id =
1477             desc_chain_head;
1478           txvq->used->ring[txvq->last_used_idx & qsz_mask].len = 0;
1479           vhost_user_log_dirty_ring (vui, txvq,
1480                                      ring[txvq->last_used_idx & qsz_mask]);
1481           txvq->last_used_idx++;
1482           flush--;
1483         }
1484     }
1485
1486   rx_len = vec_len (vum->rx_buffers[cpu_index]);        //vector might be null
1487   while (n_left > 0)
1488     {
1489       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
1490
1491       while (n_left > 0 && n_left_to_next > 0)
1492         {
1493           vlib_buffer_t *b_head, *b_current;
1494           u32 bi_head, bi_current;
1495           u16 desc_chain_head, desc_current;
1496           u8 error = VHOST_USER_INPUT_FUNC_ERROR_NO_ERROR;
1497
1498           if (PREDICT_TRUE (n_left > 1))
1499             {
1500               u32 next_desc =
1501                 txvq->avail->ring[(txvq->last_avail_idx + 1) & qsz_mask];
1502               void *buffer_addr =
1503                 map_guest_mem (vui, txvq->desc[next_desc].addr,
1504                                &map_guest_hint_desc);
1505               if (PREDICT_TRUE (buffer_addr != 0))
1506                 CLIB_PREFETCH (buffer_addr, 64, STORE);
1507
1508               u32 bi = vum->rx_buffers[cpu_index][rx_len - 2];
1509               vlib_prefetch_buffer_with_index (vm, bi, STORE);
1510               CLIB_PREFETCH (vlib_get_buffer (vm, bi)->data, 128, STORE);
1511             }
1512
1513           desc_chain_head = desc_current =
1514             txvq->avail->ring[txvq->last_avail_idx & qsz_mask];
1515           bi_head = bi_current = vum->rx_buffers[cpu_index][--rx_len];
1516           b_head = b_current = vlib_get_buffer (vm, bi_head);
1517           vlib_buffer_chain_init (b_head);
1518           if (PREDICT_FALSE (n_trace))
1519             {
1520               vlib_trace_buffer (vm, node, next_index, b_head,
1521                                  /* follow_chain */ 0);
1522               vhost_trace_t *t0 =
1523                 vlib_add_trace (vm, node, b_head, sizeof (t0[0]));
1524               vhost_user_rx_trace (t0, vui, qid, b_head, txvq);
1525               n_trace--;
1526               vlib_set_trace_count (vm, node, n_trace);
1527             }
1528
1529           uword offset;
1530           if (PREDICT_TRUE (vui->is_any_layout) ||
1531               (!(txvq->desc[desc_current].flags & VIRTQ_DESC_F_NEXT) &&
1532                !(txvq->desc[desc_current].flags & VIRTQ_DESC_F_INDIRECT)))
1533             {
1534               /* ANYLAYOUT or single buffer */
1535               offset = vui->virtio_net_hdr_sz;
1536             }
1537           else
1538             {
1539               /* CSR case without ANYLAYOUT, skip 1st buffer */
1540               offset = txvq->desc[desc_current].len;
1541             }
1542
1543           vring_desc_t *desc_table = txvq->desc;
1544           u32 desc_index = desc_current;
1545           map_guest_hint_p = &map_guest_hint_desc;
1546
1547           if (txvq->desc[desc_current].flags & VIRTQ_DESC_F_INDIRECT)
1548             {
1549               desc_table = map_guest_mem (vui, txvq->desc[desc_current].addr,
1550                                           &map_guest_hint_desc);
1551               desc_index = 0;
1552               map_guest_hint_p = &map_guest_hint_indirect;
1553               if (PREDICT_FALSE (desc_table == 0))
1554                 {
1555                   error = VHOST_USER_INPUT_FUNC_ERROR_MMAP_FAIL;
1556                   goto out;
1557                 }
1558             }
1559
1560           while (1)
1561             {
1562               void *buffer_addr =
1563                 map_guest_mem (vui, desc_table[desc_index].addr,
1564                                map_guest_hint_p);
1565               if (PREDICT_FALSE (buffer_addr == 0))
1566                 {
1567                   error = VHOST_USER_INPUT_FUNC_ERROR_MMAP_FAIL;
1568                   goto out;
1569                 }
1570
1571               if (PREDICT_TRUE
1572                   (desc_table[desc_index].flags & VIRTQ_DESC_F_NEXT))
1573                 {
1574                   CLIB_PREFETCH (&desc_table[desc_table[desc_index].next],
1575                                  sizeof (vring_desc_t), STORE);
1576                 }
1577
1578               if (desc_table[desc_index].len > offset)
1579                 {
1580                   u16 len = desc_table[desc_index].len - offset;
1581                   u16 copied = vlib_buffer_chain_append_data_with_alloc (vm,
1582                                                                          VLIB_BUFFER_DEFAULT_FREE_LIST_INDEX,
1583                                                                          b_head,
1584                                                                          &b_current,
1585                                                                          buffer_addr
1586                                                                          +
1587                                                                          offset,
1588                                                                          len);
1589                   if (copied != len)
1590                     {
1591                       error = VHOST_USER_INPUT_FUNC_ERROR_NO_BUFFER;
1592                       break;
1593                     }
1594                 }
1595               offset = 0;
1596
1597               /* if next flag is set, take next desc in the chain */
1598               if ((desc_table[desc_index].flags & VIRTQ_DESC_F_NEXT))
1599                 desc_index = desc_table[desc_index].next;
1600               else
1601                 goto out;
1602             }
1603         out:
1604
1605           /* consume the descriptor and return it as used */
1606           txvq->last_avail_idx++;
1607           txvq->used->ring[txvq->last_used_idx & qsz_mask].id =
1608             desc_chain_head;
1609           txvq->used->ring[txvq->last_used_idx & qsz_mask].len = 0;
1610           vhost_user_log_dirty_ring (vui, txvq,
1611                                      ring[txvq->last_used_idx & qsz_mask]);
1612           txvq->last_used_idx++;
1613
1614           //It is important to free RX as fast as possible such that the TX
1615           //process does not drop packets
1616           if ((txvq->last_used_idx & 0x3f) == 0)        // Every 64 packets
1617             txvq->used->idx = txvq->last_used_idx;
1618
1619           if (PREDICT_FALSE (b_head->current_length < 14 &&
1620                              error == VHOST_USER_INPUT_FUNC_ERROR_NO_ERROR))
1621             error = VHOST_USER_INPUT_FUNC_ERROR_UNDERSIZED_FRAME;
1622
1623           VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b_head);
1624
1625           vnet_buffer (b_head)->sw_if_index[VLIB_RX] = vui->sw_if_index;
1626           vnet_buffer (b_head)->sw_if_index[VLIB_TX] = (u32) ~ 0;
1627           b_head->error = node->errors[error];
1628
1629           if (PREDICT_FALSE (error))
1630             {
1631               drops++;
1632               next0 = VNET_DEVICE_INPUT_NEXT_DROP;
1633             }
1634           else
1635             {
1636               n_rx_bytes +=
1637                 b_head->current_length +
1638                 b_head->total_length_not_including_first_buffer;
1639               n_rx_packets++;
1640               next0 = VNET_DEVICE_INPUT_NEXT_ETHERNET_INPUT;
1641             }
1642
1643           to_next[0] = bi_head;
1644           to_next++;
1645           n_left_to_next--;
1646
1647           /* redirect if feature path enabled */
1648           vnet_feature_start_device_input_x1 (vui->sw_if_index, &next0,
1649                                               b_head, 0);
1650
1651           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
1652                                            to_next, n_left_to_next,
1653                                            bi_head, next0);
1654           n_left--;
1655           if (PREDICT_FALSE (!n_left))
1656             {
1657               // I NEED SOME MORE !
1658               u32 remain = (u16) (txvq->avail->idx - txvq->last_avail_idx);
1659               remain = (remain > VLIB_FRAME_SIZE - n_rx_packets) ?
1660                 VLIB_FRAME_SIZE - n_rx_packets : remain;
1661               remain = (remain > rx_len) ? rx_len : remain;
1662               n_left = remain;
1663             }
1664         }
1665
1666       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
1667     }
1668
1669   if (PREDICT_TRUE (vum->rx_buffers[cpu_index] != 0))
1670     _vec_len (vum->rx_buffers[cpu_index]) = rx_len;
1671
1672   /* give buffers back to driver */
1673   CLIB_MEMORY_BARRIER ();
1674   txvq->used->idx = txvq->last_used_idx;
1675   vhost_user_log_dirty_ring (vui, txvq, idx);
1676
1677   /* interrupt (call) handling */
1678   if ((txvq->callfd > -1) && !(txvq->avail->flags & 1))
1679     {
1680       txvq->n_since_last_int += n_rx_packets;
1681
1682       if (txvq->n_since_last_int > vum->coalesce_frames)
1683         vhost_user_send_call (vm, txvq);
1684     }
1685
1686   if (PREDICT_FALSE (drops))
1687     {
1688       vlib_increment_simple_counter
1689         (vnet_main.interface_main.sw_if_counters
1690          + VNET_INTERFACE_COUNTER_DROP, os_get_cpu_number (),
1691          vui->sw_if_index, drops);
1692     }
1693
1694   /* increase rx counters */
1695   vlib_increment_combined_counter
1696     (vnet_main.interface_main.combined_sw_if_counters
1697      + VNET_INTERFACE_COUNTER_RX,
1698      os_get_cpu_number (), vui->sw_if_index, n_rx_packets, n_rx_bytes);
1699
1700   return n_rx_packets;
1701 }
1702
1703 static uword
1704 vhost_user_input (vlib_main_t * vm,
1705                   vlib_node_runtime_t * node, vlib_frame_t * f)
1706 {
1707   vhost_user_main_t *vum = &vhost_user_main;
1708   uword n_rx_packets = 0;
1709   u32 cpu_index = os_get_cpu_number ();
1710
1711
1712   vhost_iface_and_queue_t *vhiq;
1713   vec_foreach (vhiq, vum->cpus[cpu_index].rx_queues)
1714   {
1715     vhost_user_intf_t *vui =
1716       &vum->vhost_user_interfaces[vhiq->vhost_iface_index];
1717     n_rx_packets += vhost_user_if_input (vm, vum, vui, vhiq->qid, node);
1718   }
1719
1720   //TODO: One call might return more than 256 packets here.
1721   //But this is supposed to be the vector size.
1722   return n_rx_packets;
1723 }
1724
1725 /* *INDENT-OFF* */
1726 VLIB_REGISTER_NODE (vhost_user_input_node) = {
1727   .function = vhost_user_input,
1728   .type = VLIB_NODE_TYPE_INPUT,
1729   .name = "vhost-user-input",
1730   .sibling_of = "device-input",
1731
1732   /* Will be enabled if/when hardware is detected. */
1733   .state = VLIB_NODE_STATE_DISABLED,
1734
1735   .format_buffer = format_ethernet_header_with_length,
1736   .format_trace = format_vhost_trace,
1737
1738   .n_errors = VHOST_USER_INPUT_FUNC_N_ERROR,
1739   .error_strings = vhost_user_input_func_error_strings,
1740 };
1741
1742 VLIB_NODE_FUNCTION_MULTIARCH (vhost_user_input_node, vhost_user_input)
1743 /* *INDENT-ON* */
1744
1745
1746 void
1747 vhost_user_tx_trace (vhost_trace_t * t,
1748                      vhost_user_intf_t * vui, u16 qid,
1749                      vlib_buffer_t * b, vhost_user_vring_t * rxvq)
1750 {
1751   vhost_user_main_t *vum = &vhost_user_main;
1752   u32 qsz_mask = rxvq->qsz - 1;
1753   u32 last_avail_idx = rxvq->last_avail_idx;
1754   u32 desc_current = rxvq->avail->ring[last_avail_idx & qsz_mask];
1755   vring_desc_t *hdr_desc = 0;
1756   u32 hint = 0;
1757
1758   memset (t, 0, sizeof (*t));
1759   t->device_index = vui - vum->vhost_user_interfaces;
1760   t->qid = qid;
1761
1762   hdr_desc = &rxvq->desc[desc_current];
1763   if (rxvq->desc[desc_current].flags & VIRTQ_DESC_F_INDIRECT)
1764     {
1765       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_INDIRECT;
1766       //Header is the first here
1767       hdr_desc = map_guest_mem (vui, rxvq->desc[desc_current].addr, &hint);
1768     }
1769   if (rxvq->desc[desc_current].flags & VIRTQ_DESC_F_NEXT)
1770     {
1771       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_SIMPLE_CHAINED;
1772     }
1773   if (!(rxvq->desc[desc_current].flags & VIRTQ_DESC_F_NEXT) &&
1774       !(rxvq->desc[desc_current].flags & VIRTQ_DESC_F_INDIRECT))
1775     {
1776       t->virtio_ring_flags |= 1 << VIRTIO_TRACE_F_SINGLE_DESC;
1777     }
1778
1779   t->first_desc_len = hdr_desc ? hdr_desc->len : 0;
1780 }
1781
1782 static uword
1783 vhost_user_intfc_tx (vlib_main_t * vm,
1784                      vlib_node_runtime_t * node, vlib_frame_t * frame)
1785 {
1786   u32 *buffers = vlib_frame_args (frame);
1787   u32 n_left = 0;
1788   vhost_user_main_t *vum = &vhost_user_main;
1789   uword n_packets = 0;
1790   vnet_interface_output_runtime_t *rd = (void *) node->runtime_data;
1791   vhost_user_intf_t *vui =
1792     vec_elt_at_index (vum->vhost_user_interfaces, rd->dev_instance);
1793   u32 qid = ~0;
1794   vhost_user_vring_t *rxvq;
1795   u16 qsz_mask;
1796   u8 error = VHOST_USER_TX_FUNC_ERROR_NONE;
1797   u32 cpu_index = os_get_cpu_number ();
1798   n_left = n_packets = frame->n_vectors;
1799   u32 map_guest_hint_desc = 0;
1800   u32 map_guest_hint_indirect = 0;
1801   u32 *map_guest_hint_p = &map_guest_hint_desc;
1802   vhost_trace_t *current_trace = 0;
1803   int n_retry;
1804
1805   if (PREDICT_FALSE (!vui->is_up || !vui->admin_up))
1806     {
1807       error = VHOST_USER_TX_FUNC_ERROR_NOT_READY;
1808       goto done3;
1809     }
1810
1811   qid =
1812     VHOST_VRING_IDX_RX (*vec_elt_at_index (vui->per_cpu_tx_qid, cpu_index));
1813   rxvq = &vui->vrings[qid];
1814   if (PREDICT_FALSE (vui->use_tx_spinlock))
1815     vhost_user_vring_lock (vui, qid);
1816
1817   if (PREDICT_FALSE ((rxvq->avail->idx == rxvq->last_avail_idx)))
1818     {
1819       error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOBUF;
1820       goto done2;
1821     }
1822
1823   qsz_mask = rxvq->qsz - 1;     /* qsz is always power of 2 */
1824   n_retry = 8;
1825
1826   while (n_left > 0 && n_retry--)
1827     {
1828
1829       while (n_left > 0)
1830         {
1831           vlib_buffer_t *b0, *current_b0;
1832           u16 desc_head, desc_index, desc_len;
1833           vring_desc_t *desc_table;
1834           void *buffer_addr;
1835           u32 buffer_len;
1836
1837           b0 = vlib_get_buffer (vm, buffers[0]);
1838
1839           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1840             {
1841               current_trace = vlib_add_trace (vm, node, b0,
1842                                               sizeof (*current_trace));
1843               vhost_user_tx_trace (current_trace, vui, qid / 2, b0, rxvq);
1844             }
1845
1846           if (PREDICT_FALSE (rxvq->last_avail_idx == rxvq->avail->idx))
1847             {
1848               error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOBUF;
1849               goto done;
1850             }
1851
1852           desc_table = rxvq->desc;
1853           map_guest_hint_p = &map_guest_hint_desc;
1854           desc_head = desc_index =
1855             rxvq->avail->ring[rxvq->last_avail_idx & qsz_mask];
1856           if (rxvq->desc[desc_head].flags & VIRTQ_DESC_F_INDIRECT)
1857             {
1858               if (PREDICT_FALSE
1859                   (rxvq->desc[desc_head].len < sizeof (vring_desc_t)))
1860                 {
1861                   error = VHOST_USER_TX_FUNC_ERROR_INDIRECT_OVERFLOW;
1862                   goto done;
1863                 }
1864               if (PREDICT_FALSE
1865                   (!(desc_table =
1866                      map_guest_mem (vui, rxvq->desc[desc_index].addr,
1867                                     &map_guest_hint_desc))))
1868                 {
1869                   error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1870                   goto done;
1871                 }
1872               desc_index = 0;
1873               map_guest_hint_p = &map_guest_hint_indirect;
1874             }
1875
1876           desc_len = vui->virtio_net_hdr_sz;
1877
1878           if (PREDICT_FALSE
1879               (!(buffer_addr =
1880                  map_guest_mem (vui, desc_table[desc_index].addr,
1881                                 map_guest_hint_p))))
1882             {
1883               error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1884               goto done;
1885             }
1886           buffer_len = desc_table[desc_index].len;
1887
1888           CLIB_PREFETCH (buffer_addr, CLIB_CACHE_LINE_BYTES, STORE);
1889
1890           virtio_net_hdr_mrg_rxbuf_t *hdr =
1891             (virtio_net_hdr_mrg_rxbuf_t *) buffer_addr;
1892           hdr->hdr.flags = 0;
1893           hdr->hdr.gso_type = 0;
1894           if (vui->virtio_net_hdr_sz == 12)
1895             hdr->num_buffers = 1;
1896
1897           vhost_user_log_dirty_pages (vui, desc_table[desc_index].addr,
1898                                       vui->virtio_net_hdr_sz);
1899
1900           u16 bytes_left = b0->current_length;
1901           buffer_addr += vui->virtio_net_hdr_sz;
1902           buffer_len -= vui->virtio_net_hdr_sz;
1903           current_b0 = b0;
1904           while (1)
1905             {
1906               if (!bytes_left)
1907                 {               //Get new input
1908                   if (current_b0->flags & VLIB_BUFFER_NEXT_PRESENT)
1909                     {
1910                       current_b0 =
1911                         vlib_get_buffer (vm, current_b0->next_buffer);
1912                       bytes_left = current_b0->current_length;
1913                     }
1914                   else
1915                     {
1916                       //End of packet
1917                       break;
1918                     }
1919                 }
1920
1921               if (buffer_len == 0)
1922                 {               //Get new output
1923                   if (desc_table[desc_index].flags & VIRTQ_DESC_F_NEXT)
1924                     {
1925                       //Next one is chained
1926                       desc_index = desc_table[desc_index].next;
1927                       if (PREDICT_FALSE
1928                           (!(buffer_addr =
1929                              map_guest_mem (vui, desc_table[desc_index].addr,
1930                                             map_guest_hint_p))))
1931                         {
1932                           rxvq->last_used_idx -= hdr->num_buffers - 1;
1933                           rxvq->last_avail_idx -= hdr->num_buffers - 1;
1934                           error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1935                           goto done;
1936                         }
1937                       buffer_len = desc_table[desc_index].len;
1938                     }
1939                   else if (vui->virtio_net_hdr_sz == 12)        //MRG is available
1940                     {
1941                       //Move from available to used buffer
1942                       rxvq->used->ring[rxvq->last_used_idx & qsz_mask].id =
1943                         desc_head;
1944                       rxvq->used->ring[rxvq->last_used_idx & qsz_mask].len =
1945                         desc_len;
1946                       vhost_user_log_dirty_ring (vui, rxvq,
1947                                                  ring[rxvq->last_used_idx &
1948                                                       qsz_mask]);
1949                       rxvq->last_avail_idx++;
1950                       rxvq->last_used_idx++;
1951                       hdr->num_buffers++;
1952
1953                       if (PREDICT_FALSE
1954                           (rxvq->last_avail_idx == rxvq->avail->idx))
1955                         {
1956                           //Dequeue queued descriptors for this packet
1957                           rxvq->last_used_idx -= hdr->num_buffers - 1;
1958                           rxvq->last_avail_idx -= hdr->num_buffers - 1;
1959                           error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOBUF;
1960                           goto done;
1961                         }
1962
1963                       desc_table = rxvq->desc;
1964                       map_guest_hint_p = &map_guest_hint_desc;
1965                       desc_head = desc_index =
1966                         rxvq->avail->ring[rxvq->last_avail_idx & qsz_mask];
1967                       if (PREDICT_FALSE
1968                           (rxvq->
1969                            desc[desc_head].flags & VIRTQ_DESC_F_INDIRECT))
1970                         {
1971                           //It is seriously unlikely that a driver will put indirect descriptor
1972                           //after non-indirect descriptor.
1973                           if (PREDICT_FALSE
1974                               (rxvq->desc[desc_head].len <
1975                                sizeof (vring_desc_t)))
1976                             {
1977                               error =
1978                                 VHOST_USER_TX_FUNC_ERROR_INDIRECT_OVERFLOW;
1979                               goto done;
1980                             }
1981                           if (PREDICT_FALSE
1982                               (!(desc_table =
1983                                  map_guest_mem (vui,
1984                                                 rxvq->desc[desc_index].addr,
1985                                                 &map_guest_hint_desc))))
1986                             {
1987                               error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1988                               goto done;
1989                             }
1990                           desc_index = 0;
1991                           map_guest_hint_p = &map_guest_hint_indirect;
1992                         }
1993
1994                       if (PREDICT_FALSE
1995                           (!(buffer_addr =
1996                              map_guest_mem (vui, desc_table[desc_index].addr,
1997                                             map_guest_hint_p))))
1998                         {
1999                           error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
2000                           goto done;
2001                         }
2002                       buffer_len = desc_table[desc_index].len;
2003                       CLIB_PREFETCH (buffer_addr, CLIB_CACHE_LINE_BYTES,
2004                                      STORE);
2005                     }
2006                   else
2007                     {
2008                       error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOMRG;
2009                       goto done;
2010                     }
2011                 }
2012
2013               u16 bytes_to_copy = bytes_left;
2014               bytes_to_copy =
2015                 (bytes_to_copy > buffer_len) ? buffer_len : bytes_to_copy;
2016               clib_memcpy (buffer_addr,
2017                            vlib_buffer_get_current (current_b0) +
2018                            current_b0->current_length - bytes_left,
2019                            bytes_to_copy);
2020
2021               vhost_user_log_dirty_pages (vui,
2022                                           desc_table[desc_index].addr +
2023                                           desc_table[desc_index].len -
2024                                           bytes_left - bytes_to_copy,
2025                                           bytes_to_copy);
2026
2027               CLIB_PREFETCH (rxvq, sizeof (*rxvq), STORE);
2028               bytes_left -= bytes_to_copy;
2029               buffer_len -= bytes_to_copy;
2030               buffer_addr += bytes_to_copy;
2031               desc_len += bytes_to_copy;
2032             }
2033
2034           //Move from available to used ring
2035           rxvq->used->ring[rxvq->last_used_idx & qsz_mask].id = desc_head;
2036           rxvq->used->ring[rxvq->last_used_idx & qsz_mask].len = desc_len;
2037           vhost_user_log_dirty_ring (vui, rxvq,
2038                                      ring[rxvq->last_used_idx & qsz_mask]);
2039
2040           rxvq->last_avail_idx++;
2041           rxvq->last_used_idx++;
2042
2043           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2044             current_trace->hdr = *hdr;
2045
2046           buffers++;
2047           n_left--;             //At the end for error counting when 'goto done' is invoked
2048         }
2049
2050     done:
2051       CLIB_MEMORY_BARRIER ();
2052       rxvq->used->idx = rxvq->last_used_idx;
2053       vhost_user_log_dirty_ring (vui, rxvq, idx);
2054     }
2055
2056   /* interrupt (call) handling */
2057   if ((rxvq->callfd > -1) && !(rxvq->avail->flags & 1))
2058     {
2059       rxvq->n_since_last_int += n_packets - n_left;
2060
2061       if (rxvq->n_since_last_int > vum->coalesce_frames)
2062         vhost_user_send_call (vm, rxvq);
2063     }
2064
2065 done2:
2066   vhost_user_vring_unlock (vui, qid);
2067
2068 done3:
2069   if (PREDICT_FALSE (n_left && error != VHOST_USER_TX_FUNC_ERROR_NONE))
2070     {
2071       vlib_error_count (vm, node->node_index, error, n_left);
2072       vlib_increment_simple_counter
2073         (vnet_main.interface_main.sw_if_counters
2074          + VNET_INTERFACE_COUNTER_DROP,
2075          os_get_cpu_number (), vui->sw_if_index, n_left);
2076     }
2077
2078   vlib_buffer_free (vm, vlib_frame_args (frame), frame->n_vectors);
2079   return frame->n_vectors;
2080 }
2081
2082 static clib_error_t *
2083 vhost_user_interface_admin_up_down (vnet_main_t * vnm, u32 hw_if_index,
2084                                     u32 flags)
2085 {
2086   vnet_hw_interface_t *hif = vnet_get_hw_interface (vnm, hw_if_index);
2087   uword is_up = (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) != 0;
2088   vhost_user_main_t *vum = &vhost_user_main;
2089   vhost_user_intf_t *vui =
2090     vec_elt_at_index (vum->vhost_user_interfaces, hif->dev_instance);
2091
2092   vui->admin_up = is_up;
2093
2094   if (is_up)
2095     vnet_hw_interface_set_flags (vnm, vui->hw_if_index,
2096                                  VNET_HW_INTERFACE_FLAG_LINK_UP);
2097
2098   return /* no error */ 0;
2099 }
2100
2101 /* *INDENT-OFF* */
2102 VNET_DEVICE_CLASS (vhost_user_dev_class,static) = {
2103   .name = "vhost-user",
2104   .tx_function = vhost_user_intfc_tx,
2105   .tx_function_n_errors = VHOST_USER_TX_FUNC_N_ERROR,
2106   .tx_function_error_strings = vhost_user_tx_func_error_strings,
2107   .format_device_name = format_vhost_user_interface_name,
2108   .name_renumber = vhost_user_name_renumber,
2109   .admin_up_down_function = vhost_user_interface_admin_up_down,
2110   .format_tx_trace = format_vhost_trace,
2111 };
2112
2113 VLIB_DEVICE_TX_FUNCTION_MULTIARCH (vhost_user_dev_class,
2114                                    vhost_user_intfc_tx)
2115 /* *INDENT-ON* */
2116
2117 static uword
2118 vhost_user_process (vlib_main_t * vm,
2119                     vlib_node_runtime_t * rt, vlib_frame_t * f)
2120 {
2121   vhost_user_main_t *vum = &vhost_user_main;
2122   vhost_user_intf_t *vui;
2123   struct sockaddr_un sun;
2124   int sockfd;
2125   unix_file_t template = { 0 };
2126   f64 timeout = 3153600000.0 /* 100 years */ ;
2127   uword *event_data = 0;
2128
2129   sockfd = socket (AF_UNIX, SOCK_STREAM, 0);
2130   sun.sun_family = AF_UNIX;
2131   template.read_function = vhost_user_socket_read;
2132   template.error_function = vhost_user_socket_error;
2133
2134
2135   if (sockfd < 0)
2136     return 0;
2137
2138   while (1)
2139     {
2140       vlib_process_wait_for_event_or_clock (vm, timeout);
2141       vlib_process_get_events (vm, &event_data);
2142       vec_reset_length (event_data);
2143
2144       timeout = 3.0;
2145
2146       vec_foreach (vui, vum->vhost_user_interfaces)
2147       {
2148
2149         if (vui->sock_is_server || !vui->active)
2150           continue;
2151
2152         if (vui->unix_fd == -1)
2153           {
2154             /* try to connect */
2155
2156             strncpy (sun.sun_path, (char *) vui->sock_filename,
2157                      sizeof (sun.sun_path) - 1);
2158
2159             if (connect
2160                 (sockfd, (struct sockaddr *) &sun,
2161                  sizeof (struct sockaddr_un)) == 0)
2162               {
2163                 vui->sock_errno = 0;
2164                 vui->unix_fd = sockfd;
2165                 template.file_descriptor = sockfd;
2166                 vui->unix_file_index = unix_file_add (&unix_main, &template);
2167                 hash_set (vum->vhost_user_interface_index_by_sock_fd, sockfd,
2168                           vui - vum->vhost_user_interfaces);
2169
2170                 sockfd = socket (AF_UNIX, SOCK_STREAM, 0);
2171                 if (sockfd < 0)
2172                   return 0;
2173               }
2174             else
2175               {
2176                 vui->sock_errno = errno;
2177               }
2178           }
2179         else
2180           {
2181             /* check if socket is alive */
2182             int error = 0;
2183             socklen_t len = sizeof (error);
2184             int retval =
2185               getsockopt (vui->unix_fd, SOL_SOCKET, SO_ERROR, &error, &len);
2186
2187             if (retval)
2188               {
2189                 DBG_SOCK ("getsockopt returned %d", retval);
2190                 vhost_user_if_disconnect (vui);
2191               }
2192           }
2193       }
2194     }
2195   return 0;
2196 }
2197
2198 /* *INDENT-OFF* */
2199 VLIB_REGISTER_NODE (vhost_user_process_node,static) = {
2200     .function = vhost_user_process,
2201     .type = VLIB_NODE_TYPE_PROCESS,
2202     .name = "vhost-user-process",
2203 };
2204 /* *INDENT-ON* */
2205
2206 int
2207 vhost_user_delete_if (vnet_main_t * vnm, vlib_main_t * vm, u32 sw_if_index)
2208 {
2209   vhost_user_main_t *vum = &vhost_user_main;
2210   vhost_user_intf_t *vui;
2211   uword *p = NULL;
2212   int rv = 0;
2213
2214   p = hash_get (vum->vhost_user_interface_index_by_sw_if_index, sw_if_index);
2215   if (p == 0)
2216     {
2217       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
2218     }
2219   else
2220     {
2221       vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
2222     }
2223
2224   // interface is inactive
2225   vui->active = 0;
2226   // Delete configured thread pinning
2227   vec_reset_length (vui->workers);
2228   // disconnect interface sockets
2229   vhost_user_if_disconnect (vui);
2230   vhost_user_update_iface_state (vui);
2231   // add to inactive interface list
2232   vec_add1 (vum->vhost_user_inactive_interfaces_index, p[0]);
2233
2234   // reset renumbered iface
2235   if (p[0] < vec_len (vum->show_dev_instance_by_real_dev_instance))
2236     vum->show_dev_instance_by_real_dev_instance[p[0]] = ~0;
2237
2238   ethernet_delete_interface (vnm, vui->hw_if_index);
2239   DBG_SOCK ("deleted (deactivated) vhost-user interface instance %d", p[0]);
2240
2241   return rv;
2242 }
2243
2244 // init server socket on specified sock_filename
2245 static int
2246 vhost_user_init_server_sock (const char *sock_filename, int *sockfd)
2247 {
2248   int rv = 0;
2249   struct sockaddr_un un = { };
2250   int fd;
2251   /* create listening socket */
2252   fd = socket (AF_UNIX, SOCK_STREAM, 0);
2253
2254   if (fd < 0)
2255     {
2256       return VNET_API_ERROR_SYSCALL_ERROR_1;
2257     }
2258
2259   un.sun_family = AF_UNIX;
2260   strncpy ((char *) un.sun_path, (char *) sock_filename,
2261            sizeof (un.sun_path) - 1);
2262
2263   /* remove if exists */
2264   unlink ((char *) sock_filename);
2265
2266   if (bind (fd, (struct sockaddr *) &un, sizeof (un)) == -1)
2267     {
2268       rv = VNET_API_ERROR_SYSCALL_ERROR_2;
2269       goto error;
2270     }
2271
2272   if (listen (fd, 1) == -1)
2273     {
2274       rv = VNET_API_ERROR_SYSCALL_ERROR_3;
2275       goto error;
2276     }
2277
2278   unix_file_t template = { 0 };
2279   template.read_function = vhost_user_socksvr_accept_ready;
2280   template.file_descriptor = fd;
2281   unix_file_add (&unix_main, &template);
2282   *sockfd = fd;
2283   return rv;
2284
2285 error:
2286   close (fd);
2287   return rv;
2288 }
2289
2290 // get new vhost_user_intf_t from inactive interfaces or create new one
2291 static vhost_user_intf_t *
2292 vhost_user_vui_new ()
2293 {
2294   vhost_user_main_t *vum = &vhost_user_main;
2295   vhost_user_intf_t *vui = NULL;
2296   int inactive_cnt = vec_len (vum->vhost_user_inactive_interfaces_index);
2297   // if there are any inactive ifaces
2298   if (inactive_cnt > 0)
2299     {
2300       // take last
2301       u32 vui_idx =
2302         vum->vhost_user_inactive_interfaces_index[inactive_cnt - 1];
2303       if (vec_len (vum->vhost_user_interfaces) > vui_idx)
2304         {
2305           vui = vec_elt_at_index (vum->vhost_user_interfaces, vui_idx);
2306           DBG_SOCK ("reusing inactive vhost-user interface index %d",
2307                     vui_idx);
2308         }
2309       // "remove" from inactive list
2310       _vec_len (vum->vhost_user_inactive_interfaces_index) -= 1;
2311     }
2312
2313   // vui was not retrieved from inactive ifaces - create new
2314   if (!vui)
2315     vec_add2 (vum->vhost_user_interfaces, vui, 1);
2316
2317   return vui;
2318 }
2319
2320 // create ethernet interface for vhost user intf
2321 static void
2322 vhost_user_create_ethernet (vnet_main_t * vnm, vlib_main_t * vm,
2323                             vhost_user_intf_t * vui, u8 * hwaddress)
2324 {
2325   vhost_user_main_t *vum = &vhost_user_main;
2326   u8 hwaddr[6];
2327   clib_error_t *error;
2328
2329   /* create hw and sw interface */
2330   if (hwaddress)
2331     {
2332       clib_memcpy (hwaddr, hwaddress, 6);
2333     }
2334   else
2335     {
2336       f64 now = vlib_time_now (vm);
2337       u32 rnd;
2338       rnd = (u32) (now * 1e6);
2339       rnd = random_u32 (&rnd);
2340
2341       clib_memcpy (hwaddr + 2, &rnd, sizeof (rnd));
2342       hwaddr[0] = 2;
2343       hwaddr[1] = 0xfe;
2344     }
2345
2346   error = ethernet_register_interface
2347     (vnm,
2348      vhost_user_dev_class.index,
2349      vui - vum->vhost_user_interfaces /* device instance */ ,
2350      hwaddr /* ethernet address */ ,
2351      &vui->hw_if_index, 0 /* flag change */ );
2352   if (error)
2353     clib_error_report (error);
2354
2355   vnet_hw_interface_t *hi = vnet_get_hw_interface (vnm, vui->hw_if_index);
2356   hi->max_l3_packet_bytes[VLIB_RX] = hi->max_l3_packet_bytes[VLIB_TX] = 9000;
2357 }
2358
2359 // initialize vui with specified attributes
2360 static void
2361 vhost_user_vui_init (vnet_main_t * vnm,
2362                      vhost_user_intf_t * vui, int sockfd,
2363                      const char *sock_filename,
2364                      u8 is_server, u64 feature_mask, u32 * sw_if_index)
2365 {
2366   vnet_sw_interface_t *sw;
2367   sw = vnet_get_hw_sw_interface (vnm, vui->hw_if_index);
2368   int q;
2369
2370   vui->unix_fd = sockfd;
2371   vui->sw_if_index = sw->sw_if_index;
2372   vui->sock_is_server = is_server;
2373   strncpy (vui->sock_filename, sock_filename,
2374            ARRAY_LEN (vui->sock_filename) - 1);
2375   vui->sock_errno = 0;
2376   vui->is_up = 0;
2377   vui->feature_mask = feature_mask;
2378   vui->active = 1;
2379   vui->unix_file_index = ~0;
2380   vui->log_base_addr = 0;
2381
2382   for (q = 0; q < VHOST_VRING_MAX_N; q++)
2383     vhost_user_vring_init (vui, q);
2384
2385   vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
2386
2387   if (sw_if_index)
2388     *sw_if_index = vui->sw_if_index;
2389
2390   for (q = 0; q < VHOST_VRING_MAX_N; q++)
2391     {
2392       vui->vring_locks[q] = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
2393                                                     CLIB_CACHE_LINE_BYTES);
2394       memset ((void *) vui->vring_locks[q], 0, CLIB_CACHE_LINE_BYTES);
2395     }
2396
2397   vec_validate (vui->per_cpu_tx_qid,
2398                 vlib_get_thread_main ()->n_vlib_mains - 1);
2399   vhost_user_tx_thread_placement (vui);
2400 }
2401
2402 // register vui and start polling on it
2403 static void
2404 vhost_user_vui_register (vlib_main_t * vm, vhost_user_intf_t * vui)
2405 {
2406   vhost_user_main_t *vum = &vhost_user_main;
2407   int cpu_index;
2408   vlib_thread_main_t *tm = vlib_get_thread_main ();
2409
2410   hash_set (vum->vhost_user_interface_index_by_listener_fd, vui->unix_fd,
2411             vui - vum->vhost_user_interfaces);
2412   hash_set (vum->vhost_user_interface_index_by_sw_if_index, vui->sw_if_index,
2413             vui - vum->vhost_user_interfaces);
2414
2415   /* start polling */
2416   cpu_index = vum->input_cpu_first_index +
2417     (vui - vum->vhost_user_interfaces) % vum->input_cpu_count;
2418
2419   if (tm->n_vlib_mains == 1)
2420     vlib_node_set_state (vm, vhost_user_input_node.index,
2421                          VLIB_NODE_STATE_POLLING);
2422   else
2423     vlib_node_set_state (vlib_mains[cpu_index], vhost_user_input_node.index,
2424                          VLIB_NODE_STATE_POLLING);
2425
2426   /* tell process to start polling for sockets */
2427   vlib_process_signal_event (vm, vhost_user_process_node.index, 0, 0);
2428 }
2429
2430 int
2431 vhost_user_create_if (vnet_main_t * vnm, vlib_main_t * vm,
2432                       const char *sock_filename,
2433                       u8 is_server,
2434                       u32 * sw_if_index,
2435                       u64 feature_mask,
2436                       u8 renumber, u32 custom_dev_instance, u8 * hwaddr)
2437 {
2438   vhost_user_intf_t *vui = NULL;
2439   u32 sw_if_idx = ~0;
2440   int sockfd = -1;
2441   int rv = 0;
2442
2443   if (is_server)
2444     {
2445       if ((rv = vhost_user_init_server_sock (sock_filename, &sockfd)) != 0)
2446         {
2447           return rv;
2448         }
2449     }
2450
2451   vui = vhost_user_vui_new ();
2452   ASSERT (vui != NULL);
2453
2454   vhost_user_create_ethernet (vnm, vm, vui, hwaddr);
2455   vhost_user_vui_init (vnm, vui, sockfd, sock_filename, is_server,
2456                        feature_mask, &sw_if_idx);
2457
2458   if (renumber)
2459     {
2460       vnet_interface_name_renumber (sw_if_idx, custom_dev_instance);
2461     }
2462
2463   vhost_user_vui_register (vm, vui);
2464
2465   if (sw_if_index)
2466     *sw_if_index = sw_if_idx;
2467
2468   return rv;
2469 }
2470
2471 int
2472 vhost_user_modify_if (vnet_main_t * vnm, vlib_main_t * vm,
2473                       const char *sock_filename,
2474                       u8 is_server,
2475                       u32 sw_if_index,
2476                       u64 feature_mask, u8 renumber, u32 custom_dev_instance)
2477 {
2478   vhost_user_main_t *vum = &vhost_user_main;
2479   vhost_user_intf_t *vui = NULL;
2480   u32 sw_if_idx = ~0;
2481   int sockfd = -1;
2482   int rv = 0;
2483   uword *p = NULL;
2484
2485   p = hash_get (vum->vhost_user_interface_index_by_sw_if_index, sw_if_index);
2486   if (p == 0)
2487     {
2488       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
2489     }
2490   else
2491     {
2492       vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
2493     }
2494
2495   // interface is inactive
2496   vui->active = 0;
2497   // disconnect interface sockets
2498   vhost_user_if_disconnect (vui);
2499
2500   if (is_server)
2501     {
2502       if ((rv = vhost_user_init_server_sock (sock_filename, &sockfd)) != 0)
2503         {
2504           return rv;
2505         }
2506     }
2507
2508   vhost_user_vui_init (vnm, vui, sockfd, sock_filename, is_server,
2509                        feature_mask, &sw_if_idx);
2510
2511   if (renumber)
2512     {
2513       vnet_interface_name_renumber (sw_if_idx, custom_dev_instance);
2514     }
2515
2516   vhost_user_vui_register (vm, vui);
2517
2518   return rv;
2519 }
2520
2521 clib_error_t *
2522 vhost_user_connect_command_fn (vlib_main_t * vm,
2523                                unformat_input_t * input,
2524                                vlib_cli_command_t * cmd)
2525 {
2526   unformat_input_t _line_input, *line_input = &_line_input;
2527   u8 *sock_filename = NULL;
2528   u32 sw_if_index;
2529   u8 is_server = 0;
2530   u64 feature_mask = (u64) ~ (0ULL);
2531   u8 renumber = 0;
2532   u32 custom_dev_instance = ~0;
2533   u8 hwaddr[6];
2534   u8 *hw = NULL;
2535
2536   /* Get a line of input. */
2537   if (!unformat_user (input, unformat_line_input, line_input))
2538     return 0;
2539
2540   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2541     {
2542       if (unformat (line_input, "socket %s", &sock_filename))
2543         ;
2544       else if (unformat (line_input, "server"))
2545         is_server = 1;
2546       else if (unformat (line_input, "feature-mask 0x%llx", &feature_mask))
2547         ;
2548       else
2549         if (unformat
2550             (line_input, "hwaddr %U", unformat_ethernet_address, hwaddr))
2551         hw = hwaddr;
2552       else if (unformat (line_input, "renumber %d", &custom_dev_instance))
2553         {
2554           renumber = 1;
2555         }
2556       else
2557         return clib_error_return (0, "unknown input `%U'",
2558                                   format_unformat_error, input);
2559     }
2560   unformat_free (line_input);
2561
2562   vnet_main_t *vnm = vnet_get_main ();
2563
2564   int rv;
2565   if ((rv = vhost_user_create_if (vnm, vm, (char *) sock_filename,
2566                                   is_server, &sw_if_index, feature_mask,
2567                                   renumber, custom_dev_instance, hw)))
2568     {
2569       vec_free (sock_filename);
2570       return clib_error_return (0, "vhost_user_create_if returned %d", rv);
2571     }
2572
2573   vec_free (sock_filename);
2574   vlib_cli_output (vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main (),
2575                    sw_if_index);
2576   return 0;
2577 }
2578
2579 clib_error_t *
2580 vhost_user_delete_command_fn (vlib_main_t * vm,
2581                               unformat_input_t * input,
2582                               vlib_cli_command_t * cmd)
2583 {
2584   unformat_input_t _line_input, *line_input = &_line_input;
2585   u32 sw_if_index = ~0;
2586   vnet_main_t *vnm = vnet_get_main ();
2587
2588   /* Get a line of input. */
2589   if (!unformat_user (input, unformat_line_input, line_input))
2590     return 0;
2591
2592   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2593     {
2594       if (unformat (line_input, "sw_if_index %d", &sw_if_index))
2595         ;
2596       else if (unformat
2597                (line_input, "%U", unformat_vnet_sw_interface, vnm,
2598                 &sw_if_index))
2599         {
2600           vnet_hw_interface_t *hwif =
2601             vnet_get_sup_hw_interface (vnm, sw_if_index);
2602           if (hwif == NULL ||
2603               vhost_user_dev_class.index != hwif->dev_class_index)
2604             return clib_error_return (0, "Not a vhost interface");
2605         }
2606       else
2607         return clib_error_return (0, "unknown input `%U'",
2608                                   format_unformat_error, input);
2609     }
2610   unformat_free (line_input);
2611   vhost_user_delete_if (vnm, vm, sw_if_index);
2612   return 0;
2613 }
2614
2615 int
2616 vhost_user_dump_ifs (vnet_main_t * vnm, vlib_main_t * vm,
2617                      vhost_user_intf_details_t ** out_vuids)
2618 {
2619   int rv = 0;
2620   vhost_user_main_t *vum = &vhost_user_main;
2621   vhost_user_intf_t *vui;
2622   vhost_user_intf_details_t *r_vuids = NULL;
2623   vhost_user_intf_details_t *vuid = NULL;
2624   u32 *hw_if_indices = 0;
2625   vnet_hw_interface_t *hi;
2626   u8 *s = NULL;
2627   int i;
2628
2629   if (!out_vuids)
2630     return -1;
2631
2632   vec_foreach (vui, vum->vhost_user_interfaces)
2633   {
2634     if (vui->active)
2635       vec_add1 (hw_if_indices, vui->hw_if_index);
2636   }
2637
2638   for (i = 0; i < vec_len (hw_if_indices); i++)
2639     {
2640       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
2641       vui = vec_elt_at_index (vum->vhost_user_interfaces, hi->dev_instance);
2642
2643       vec_add2 (r_vuids, vuid, 1);
2644       vuid->sw_if_index = vui->sw_if_index;
2645       vuid->virtio_net_hdr_sz = vui->virtio_net_hdr_sz;
2646       vuid->features = vui->features;
2647       vuid->is_server = vui->sock_is_server;
2648       vuid->num_regions = vui->nregions;
2649       vuid->sock_errno = vui->sock_errno;
2650       strncpy ((char *) vuid->sock_filename, (char *) vui->sock_filename,
2651                ARRAY_LEN (vuid->sock_filename) - 1);
2652
2653       s = format (s, "%v%c", hi->name, 0);
2654
2655       strncpy ((char *) vuid->if_name, (char *) s,
2656                ARRAY_LEN (vuid->if_name) - 1);
2657       _vec_len (s) = 0;
2658     }
2659
2660   vec_free (s);
2661   vec_free (hw_if_indices);
2662
2663   *out_vuids = r_vuids;
2664
2665   return rv;
2666 }
2667
2668 clib_error_t *
2669 show_vhost_user_command_fn (vlib_main_t * vm,
2670                             unformat_input_t * input,
2671                             vlib_cli_command_t * cmd)
2672 {
2673   clib_error_t *error = 0;
2674   vnet_main_t *vnm = vnet_get_main ();
2675   vhost_user_main_t *vum = &vhost_user_main;
2676   vhost_user_intf_t *vui;
2677   u32 hw_if_index, *hw_if_indices = 0;
2678   vnet_hw_interface_t *hi;
2679   vhost_cpu_t *vhc;
2680   vhost_iface_and_queue_t *vhiq;
2681   u32 ci;
2682
2683   int i, j, q;
2684   int show_descr = 0;
2685   struct feat_struct
2686   {
2687     u8 bit;
2688     char *str;
2689   };
2690   struct feat_struct *feat_entry;
2691
2692   static struct feat_struct feat_array[] = {
2693 #define _(s,b) { .str = #s, .bit = b, },
2694     foreach_virtio_net_feature
2695 #undef _
2696     {.str = NULL}
2697   };
2698
2699 #define foreach_protocol_feature \
2700   _(VHOST_USER_PROTOCOL_F_MQ) \
2701   _(VHOST_USER_PROTOCOL_F_LOG_SHMFD)
2702
2703   static struct feat_struct proto_feat_array[] = {
2704 #define _(s) { .str = #s, .bit = s},
2705     foreach_protocol_feature
2706 #undef _
2707     {.str = NULL}
2708   };
2709
2710   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2711     {
2712       if (unformat
2713           (input, "%U", unformat_vnet_hw_interface, vnm, &hw_if_index))
2714         {
2715           vec_add1 (hw_if_indices, hw_if_index);
2716         }
2717       else if (unformat (input, "descriptors") || unformat (input, "desc"))
2718         show_descr = 1;
2719       else
2720         {
2721           error = clib_error_return (0, "unknown input `%U'",
2722                                      format_unformat_error, input);
2723           goto done;
2724         }
2725     }
2726   if (vec_len (hw_if_indices) == 0)
2727     {
2728       vec_foreach (vui, vum->vhost_user_interfaces)
2729       {
2730         if (vui->active)
2731           vec_add1 (hw_if_indices, vui->hw_if_index);
2732       }
2733     }
2734   vlib_cli_output (vm, "Virtio vhost-user interfaces");
2735   vlib_cli_output (vm, "Global:\n  coalesce frames %d time %e",
2736                    vum->coalesce_frames, vum->coalesce_time);
2737
2738   for (i = 0; i < vec_len (hw_if_indices); i++)
2739     {
2740       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
2741       vui = vec_elt_at_index (vum->vhost_user_interfaces, hi->dev_instance);
2742       vlib_cli_output (vm, "Interface: %s (ifindex %d)",
2743                        hi->name, hw_if_indices[i]);
2744
2745       vlib_cli_output (vm, "virtio_net_hdr_sz %d\n"
2746                        " features mask (0x%llx): \n"
2747                        " features (0x%llx): \n",
2748                        vui->virtio_net_hdr_sz, vui->feature_mask,
2749                        vui->features);
2750
2751       feat_entry = (struct feat_struct *) &feat_array;
2752       while (feat_entry->str)
2753         {
2754           if (vui->features & (1ULL << feat_entry->bit))
2755             vlib_cli_output (vm, "   %s (%d)", feat_entry->str,
2756                              feat_entry->bit);
2757           feat_entry++;
2758         }
2759
2760       vlib_cli_output (vm, "  protocol features (0x%llx)",
2761                        vui->protocol_features);
2762       feat_entry = (struct feat_struct *) &proto_feat_array;
2763       while (feat_entry->str)
2764         {
2765           if (vui->protocol_features & (1ULL << feat_entry->bit))
2766             vlib_cli_output (vm, "   %s (%d)", feat_entry->str,
2767                              feat_entry->bit);
2768           feat_entry++;
2769         }
2770
2771       vlib_cli_output (vm, "\n");
2772
2773       vlib_cli_output (vm, " socket filename %s type %s errno \"%s\"\n\n",
2774                        vui->sock_filename,
2775                        vui->sock_is_server ? "server" : "client",
2776                        strerror (vui->sock_errno));
2777
2778       vlib_cli_output (vm, " rx placement: ");
2779       vec_foreach (vhc, vum->cpus)
2780       {
2781         vec_foreach (vhiq, vhc->rx_queues)
2782         {
2783           if (vhiq->vhost_iface_index == vui - vum->vhost_user_interfaces)
2784             vlib_cli_output (vm, "   thread %d on vring %d\n",
2785                              vhc - vum->cpus, VHOST_VRING_IDX_TX (vhiq->qid));
2786         }
2787       }
2788
2789       vlib_cli_output (vm, " tx placement: %s\n",
2790                        vui->use_tx_spinlock ? "spin-lock" : "lock-free");
2791
2792       vec_foreach_index (ci, vui->per_cpu_tx_qid)
2793       {
2794         vlib_cli_output (vm, "   thread %d on vring %d\n", ci,
2795                          VHOST_VRING_IDX_RX (vui->per_cpu_tx_qid[ci]));
2796       }
2797
2798       vlib_cli_output (vm, "\n");
2799
2800       vlib_cli_output (vm, " Memory regions (total %d)\n", vui->nregions);
2801
2802       if (vui->nregions)
2803         {
2804           vlib_cli_output (vm,
2805                            " region fd    guest_phys_addr    memory_size        userspace_addr     mmap_offset        mmap_addr\n");
2806           vlib_cli_output (vm,
2807                            " ====== ===== ================== ================== ================== ================== ==================\n");
2808         }
2809       for (j = 0; j < vui->nregions; j++)
2810         {
2811           vlib_cli_output (vm,
2812                            "  %d     %-5d 0x%016lx 0x%016lx 0x%016lx 0x%016lx 0x%016lx\n",
2813                            j, vui->region_mmap_fd[j],
2814                            vui->regions[j].guest_phys_addr,
2815                            vui->regions[j].memory_size,
2816                            vui->regions[j].userspace_addr,
2817                            vui->regions[j].mmap_offset,
2818                            pointer_to_uword (vui->region_mmap_addr[j]));
2819         }
2820       for (q = 0; q < VHOST_VRING_MAX_N; q++)
2821         {
2822           if (!vui->vrings[q].started)
2823             continue;
2824
2825           vlib_cli_output (vm, "\n Virtqueue %d (%s%s)\n", q,
2826                            (q & 1) ? "RX" : "TX",
2827                            vui->vrings[q].enabled ? "" : " disabled");
2828
2829           vlib_cli_output (vm,
2830                            "  qsz %d last_avail_idx %d last_used_idx %d\n",
2831                            vui->vrings[q].qsz, vui->vrings[q].last_avail_idx,
2832                            vui->vrings[q].last_used_idx);
2833
2834           if (vui->vrings[q].avail && vui->vrings[q].used)
2835             vlib_cli_output (vm,
2836                              "  avail.flags %x avail.idx %d used.flags %x used.idx %d\n",
2837                              vui->vrings[q].avail->flags,
2838                              vui->vrings[q].avail->idx,
2839                              vui->vrings[q].used->flags,
2840                              vui->vrings[q].used->idx);
2841
2842           vlib_cli_output (vm, "  kickfd %d callfd %d errfd %d\n",
2843                            vui->vrings[q].kickfd,
2844                            vui->vrings[q].callfd, vui->vrings[q].errfd);
2845
2846           if (show_descr)
2847             {
2848               vlib_cli_output (vm, "\n  descriptor table:\n");
2849               vlib_cli_output (vm,
2850                                "   id          addr         len  flags  next      user_addr\n");
2851               vlib_cli_output (vm,
2852                                "  ===== ================== ===== ====== ===== ==================\n");
2853               for (j = 0; j < vui->vrings[q].qsz; j++)
2854                 {
2855                   u32 mem_hint = 0;
2856                   vlib_cli_output (vm,
2857                                    "  %-5d 0x%016lx %-5d 0x%04x %-5d 0x%016lx\n",
2858                                    j, vui->vrings[q].desc[j].addr,
2859                                    vui->vrings[q].desc[j].len,
2860                                    vui->vrings[q].desc[j].flags,
2861                                    vui->vrings[q].desc[j].next,
2862                                    pointer_to_uword (map_guest_mem
2863                                                      (vui,
2864                                                       vui->vrings[q].desc[j].
2865                                                       addr, &mem_hint)));
2866                 }
2867             }
2868         }
2869       vlib_cli_output (vm, "\n");
2870     }
2871 done:
2872   vec_free (hw_if_indices);
2873   return error;
2874 }
2875
2876 /*
2877  * CLI functions
2878  */
2879
2880 /*?
2881  * Create a vHost User interface. Once created, a new virtual interface
2882  * will exist with the name '<em>VirtualEthernet0/0/x</em>', where '<em>x</em>'
2883  * is the next free index.
2884  *
2885  * There are several parameters associated with a vHost interface:
2886  *
2887  * - <b>socket <socket-filename></b> - Name of the linux socket used by QEMU/VM and
2888  * VPP to manage the vHost interface. If socket does not already exist, VPP will
2889  * create the socket.
2890  *
2891  * - <b>server</b> - Optional flag to indicate that VPP should be the server for the
2892  * linux socket. If not provided, VPP will be the client.
2893  *
2894  * - <b>feature-mask <hex></b> - Optional virtio/vhost feature set negotiated at
2895  * startup. By default, all supported features will be advertised. Otherwise,
2896  * provide the set of features desired.
2897  *   - 0x000008000 (15) - VIRTIO_NET_F_MRG_RXBUF
2898  *   - 0x000020000 (17) - VIRTIO_NET_F_CTRL_VQ
2899  *   - 0x000200000 (21) - VIRTIO_NET_F_GUEST_ANNOUNCE
2900  *   - 0x000400000 (22) - VIRTIO_NET_F_MQ
2901  *   - 0x004000000 (26) - VHOST_F_LOG_ALL
2902  *   - 0x008000000 (27) - VIRTIO_F_ANY_LAYOUT
2903  *   - 0x010000000 (28) - VIRTIO_F_INDIRECT_DESC
2904  *   - 0x040000000 (30) - VHOST_USER_F_PROTOCOL_FEATURES
2905  *   - 0x100000000 (32) - VIRTIO_F_VERSION_1
2906  *
2907  * - <b>hwaddr <mac-addr></b> - Optional ethernet address, can be in either
2908  * X:X:X:X:X:X unix or X.X.X cisco format.
2909  *
2910  * - <b>renumber <dev_instance></b> - Optional parameter which allows the instance
2911  * in the name to be specified. If instance already exists, name will be used
2912  * anyway and multiple instances will have the same name. Use with caution.
2913  *
2914  * @cliexpar
2915  * Example of how to create a vhost interface with VPP as the client and all features enabled:
2916  * @cliexstart{create vhost-user socket /tmp/vhost1.sock}
2917  * VirtualEthernet0/0/0
2918  * @cliexend
2919  * Example of how to create a vhost interface with VPP as the server and with just
2920  * multiple queues enabled:
2921  * @cliexstart{create vhost-user socket /tmp/vhost2.sock server feature-mask 0x40400000}
2922  * VirtualEthernet0/0/1
2923  * @cliexend
2924  * Once the vHost interface is created, enable the interface using:
2925  * @cliexcmd{set interface state VirtualEthernet0/0/0 up}
2926 ?*/
2927 /* *INDENT-OFF* */
2928 VLIB_CLI_COMMAND (vhost_user_connect_command, static) = {
2929     .path = "create vhost-user",
2930     .short_help = "create vhost-user socket <socket-filename> [server] [feature-mask <hex>] [hwaddr <mac-addr>] [renumber <dev_instance>]",
2931     .function = vhost_user_connect_command_fn,
2932 };
2933 /* *INDENT-ON* */
2934
2935 /*?
2936  * Delete a vHost User interface using the interface name or the
2937  * software interface index. Use the '<em>show interfaces</em>'
2938  * command to determine the software interface index. On deletion,
2939  * the linux socket will not be deleted.
2940  *
2941  * @cliexpar
2942  * Example of how to delete a vhost interface by name:
2943  * @cliexcmd{delete vhost-user VirtualEthernet0/0/1}
2944  * Example of how to delete a vhost interface by software interface index:
2945  * @cliexcmd{delete vhost-user sw_if_index 1}
2946 ?*/
2947 /* *INDENT-OFF* */
2948 VLIB_CLI_COMMAND (vhost_user_delete_command, static) = {
2949     .path = "delete vhost-user",
2950     .short_help = "delete vhost-user {<interface> | sw_if_index <sw_idx>}",
2951     .function = vhost_user_delete_command_fn,
2952 };
2953
2954 /*?
2955  * Display the attributes of a single vHost User interface (provide interface
2956  * name), multiple vHost User interfaces (provide a list of interface names seperated
2957  * by spaces) or all Vhost User interfaces (omit an interface name to display all
2958  * vHost interfaces).
2959  *
2960  * @cliexpar
2961  * @parblock
2962  * Example of how to display a vhost interface:
2963  * @cliexstart{show vhost-user VirtualEthernet0/0/0}
2964  * Virtio vhost-user interfaces
2965  * Global:
2966  *   coalesce frames 32 time 1e-3
2967  * Interface: VirtualEthernet0/0/0 (ifindex 1)
2968  * virtio_net_hdr_sz 12
2969  *  features mask (0xffffffffffffffff):
2970  *  features (0x50408000):
2971  *    VIRTIO_NET_F_MRG_RXBUF (15)
2972  *    VIRTIO_NET_F_MQ (22)
2973  *    VIRTIO_F_INDIRECT_DESC (28)
2974  *    VHOST_USER_F_PROTOCOL_FEATURES (30)
2975  *   protocol features (0x3)
2976  *    VHOST_USER_PROTOCOL_F_MQ (0)
2977  *    VHOST_USER_PROTOCOL_F_LOG_SHMFD (1)
2978  *
2979  *  socket filename /tmp/vhost1.sock type client errno "Success"
2980  *
2981  * rx placement:
2982  *    thread 1 on vring 1
2983  *    thread 1 on vring 5
2984  *    thread 2 on vring 3
2985  *    thread 2 on vring 7
2986  *  tx placement: spin-lock
2987  *    thread 0 on vring 0
2988  *    thread 1 on vring 2
2989  *    thread 2 on vring 0
2990  *
2991  * Memory regions (total 2)
2992  * region fd    guest_phys_addr    memory_size        userspace_addr     mmap_offset        mmap_addr
2993  * ====== ===== ================== ================== ================== ================== ==================
2994  *   0     60    0x0000000000000000 0x00000000000a0000 0x00002aaaaac00000 0x0000000000000000 0x00002aab2b400000
2995  *   1     61    0x00000000000c0000 0x000000003ff40000 0x00002aaaaacc0000 0x00000000000c0000 0x00002aababcc0000
2996  *
2997  *  Virtqueue 0 (TX)
2998  *   qsz 256 last_avail_idx 0 last_used_idx 0
2999  *   avail.flags 1 avail.idx 128 used.flags 1 used.idx 0
3000  *   kickfd 62 callfd 64 errfd -1
3001  *
3002  *  Virtqueue 1 (RX)
3003  *   qsz 256 last_avail_idx 0 last_used_idx 0
3004  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
3005  *   kickfd 65 callfd 66 errfd -1
3006  *
3007  *  Virtqueue 2 (TX)
3008  *   qsz 256 last_avail_idx 0 last_used_idx 0
3009  *   avail.flags 1 avail.idx 128 used.flags 1 used.idx 0
3010  *   kickfd 63 callfd 70 errfd -1
3011  *
3012  *  Virtqueue 3 (RX)
3013  *   qsz 256 last_avail_idx 0 last_used_idx 0
3014  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
3015  *   kickfd 72 callfd 74 errfd -1
3016  *
3017  *  Virtqueue 4 (TX disabled)
3018  *   qsz 256 last_avail_idx 0 last_used_idx 0
3019  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
3020  *   kickfd 76 callfd 78 errfd -1
3021  *
3022  *  Virtqueue 5 (RX disabled)
3023  *   qsz 256 last_avail_idx 0 last_used_idx 0
3024  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
3025  *   kickfd 80 callfd 82 errfd -1
3026  *
3027  *  Virtqueue 6 (TX disabled)
3028  *   qsz 256 last_avail_idx 0 last_used_idx 0
3029  *  avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
3030  *   kickfd 84 callfd 86 errfd -1
3031  *
3032  *  Virtqueue 7 (RX disabled)
3033  *   qsz 256 last_avail_idx 0 last_used_idx 0
3034  *   avail.flags 1 avail.idx 0 used.flags 1 used.idx 0
3035  *   kickfd 88 callfd 90 errfd -1
3036  *
3037  * @cliexend
3038  *
3039  * The optional '<em>descriptors</em>' parameter will display the same output as
3040  * the previous example but will include the descriptor table for each queue.
3041  * The output is truncated below:
3042  * @cliexstart{show vhost-user VirtualEthernet0/0/0 descriptors}
3043  * Virtio vhost-user interfaces
3044  * Global:
3045  *   coalesce frames 32 time 1e-3
3046  * Interface: VirtualEthernet0/0/0 (ifindex 1)
3047  * virtio_net_hdr_sz 12
3048  *  features mask (0xffffffffffffffff):
3049  *  features (0x50408000):
3050  *    VIRTIO_NET_F_MRG_RXBUF (15)
3051  *    VIRTIO_NET_F_MQ (22)
3052  * :
3053  *  Virtqueue 0 (TX)
3054  *   qsz 256 last_avail_idx 0 last_used_idx 0
3055  *   avail.flags 1 avail.idx 128 used.flags 1 used.idx 0
3056  *   kickfd 62 callfd 64 errfd -1
3057  *
3058  *   descriptor table:
3059  *    id          addr         len  flags  next      user_addr
3060  *   ===== ================== ===== ====== ===== ==================
3061  *   0     0x0000000010b6e974 2060  0x0002 1     0x00002aabbc76e974
3062  *   1     0x0000000010b6e034 2060  0x0002 2     0x00002aabbc76e034
3063  *   2     0x0000000010b6d6f4 2060  0x0002 3     0x00002aabbc76d6f4
3064  *   3     0x0000000010b6cdb4 2060  0x0002 4     0x00002aabbc76cdb4
3065  *   4     0x0000000010b6c474 2060  0x0002 5     0x00002aabbc76c474
3066  *   5     0x0000000010b6bb34 2060  0x0002 6     0x00002aabbc76bb34
3067  *   6     0x0000000010b6b1f4 2060  0x0002 7     0x00002aabbc76b1f4
3068  *   7     0x0000000010b6a8b4 2060  0x0002 8     0x00002aabbc76a8b4
3069  *   8     0x0000000010b69f74 2060  0x0002 9     0x00002aabbc769f74
3070  *   9     0x0000000010b69634 2060  0x0002 10    0x00002aabbc769634
3071  *   10    0x0000000010b68cf4 2060  0x0002 11    0x00002aabbc768cf4
3072  * :
3073  *   249   0x0000000000000000 0     0x0000 250   0x00002aab2b400000
3074  *   250   0x0000000000000000 0     0x0000 251   0x00002aab2b400000
3075  *   251   0x0000000000000000 0     0x0000 252   0x00002aab2b400000
3076  *   252   0x0000000000000000 0     0x0000 253   0x00002aab2b400000
3077  *   253   0x0000000000000000 0     0x0000 254   0x00002aab2b400000
3078  *   254   0x0000000000000000 0     0x0000 255   0x00002aab2b400000
3079  *   255   0x0000000000000000 0     0x0000 32768 0x00002aab2b400000
3080  *
3081  *  Virtqueue 1 (RX)
3082  *   qsz 256 last_avail_idx 0 last_used_idx 0
3083  * :
3084  * @cliexend
3085  * @endparblock
3086 ?*/
3087 /* *INDENT-OFF* */
3088 VLIB_CLI_COMMAND (show_vhost_user_command, static) = {
3089     .path = "show vhost-user",
3090     .short_help = "show vhost-user [<interface> [<interface> [..]]] [descriptors]",
3091     .function = show_vhost_user_command_fn,
3092 };
3093 /* *INDENT-ON* */
3094
3095 static clib_error_t *
3096 vhost_user_config (vlib_main_t * vm, unformat_input_t * input)
3097 {
3098   vhost_user_main_t *vum = &vhost_user_main;
3099
3100   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
3101     {
3102       if (unformat (input, "coalesce-frames %d", &vum->coalesce_frames))
3103         ;
3104       else if (unformat (input, "coalesce-time %f", &vum->coalesce_time))
3105         ;
3106       else if (unformat (input, "dont-dump-memory"))
3107         vum->dont_dump_vhost_user_memory = 1;
3108       else
3109         return clib_error_return (0, "unknown input `%U'",
3110                                   format_unformat_error, input);
3111     }
3112
3113   return 0;
3114 }
3115
3116 /* vhost-user { ... } configuration. */
3117 VLIB_CONFIG_FUNCTION (vhost_user_config, "vhost-user");
3118
3119 void
3120 vhost_user_unmap_all (void)
3121 {
3122   vhost_user_main_t *vum = &vhost_user_main;
3123   vhost_user_intf_t *vui;
3124
3125   if (vum->dont_dump_vhost_user_memory)
3126     {
3127       vec_foreach (vui, vum->vhost_user_interfaces)
3128       {
3129         unmap_all_mem_regions (vui);
3130       }
3131     }
3132 }
3133
3134 static clib_error_t *
3135 vhost_thread_command_fn (vlib_main_t * vm,
3136                          unformat_input_t * input, vlib_cli_command_t * cmd)
3137 {
3138   unformat_input_t _line_input, *line_input = &_line_input;
3139   u32 worker_thread_index;
3140   u32 sw_if_index;
3141   u8 del = 0;
3142   int rv;
3143
3144   /* Get a line of input. */
3145   if (!unformat_user (input, unformat_line_input, line_input))
3146     return 0;
3147
3148   if (!unformat
3149       (line_input, "%U %d", unformat_vnet_sw_interface, vnet_get_main (),
3150        &sw_if_index, &worker_thread_index))
3151     {
3152       unformat_free (line_input);
3153       return clib_error_return (0, "unknown input `%U'",
3154                                 format_unformat_error, input);
3155     }
3156
3157   if (unformat (line_input, "del"))
3158     del = 1;
3159
3160   if ((rv =
3161        vhost_user_thread_placement (sw_if_index, worker_thread_index, del)))
3162     return clib_error_return (0, "vhost_user_thread_placement returned %d",
3163                               rv);
3164   return 0;
3165 }
3166
3167
3168 /*?
3169  * This command is used to move the RX processing for the given
3170  * interfaces to the provided thread. If the '<em>del</em>' option is used,
3171  * the forced thread assignment is removed and the thread assigment is
3172  * reassigned automatically. Use '<em>show vhost-user <interface></em>'
3173  * to see the thread assignment.
3174  *
3175  * @cliexpar
3176  * Example of how to move the RX processing for a given interface to a given thread:
3177  * @cliexcmd{vhost thread VirtualEthernet0/0/0 1}
3178  * Example of how to remove the forced thread assignment for a given interface:
3179  * @cliexcmd{vhost thread VirtualEthernet0/0/0 1 del}
3180 ?*/
3181 /* *INDENT-OFF* */
3182 VLIB_CLI_COMMAND (vhost_user_thread_command, static) = {
3183     .path = "vhost thread",
3184     .short_help = "vhost thread <iface> <worker-index> [del]",
3185     .function = vhost_thread_command_fn,
3186 };
3187 /* *INDENT-ON* */
3188
3189 /*
3190  * fd.io coding-style-patch-verification: ON
3191  *
3192  * Local Variables:
3193  * eval: (c-set-style "gnu")
3194  * End:
3195  */