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