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