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