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