4c228633cd77a248a44866391d007d2ea5e15923
[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   int n_retry;
1796
1797   if (PREDICT_FALSE (!vui->is_up || !vui->admin_up))
1798     {
1799       error = VHOST_USER_TX_FUNC_ERROR_NOT_READY;
1800       goto done3;
1801     }
1802
1803   qid =
1804     VHOST_VRING_IDX_RX (*vec_elt_at_index (vui->per_cpu_tx_qid, cpu_index));
1805   rxvq = &vui->vrings[qid];
1806   if (PREDICT_FALSE (vui->use_tx_spinlock))
1807     vhost_user_vring_lock (vui, qid);
1808
1809   if (PREDICT_FALSE ((rxvq->avail->idx == rxvq->last_avail_idx)))
1810     {
1811       error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOBUF;
1812       goto done2;
1813     }
1814
1815   qsz_mask = rxvq->qsz - 1;     /* qsz is always power of 2 */
1816   n_retry = 8;
1817
1818   while (n_left > 0 && n_retry--)
1819     {
1820
1821       while (n_left > 0)
1822         {
1823           vlib_buffer_t *b0, *current_b0;
1824           u16 desc_head, desc_index, desc_len;
1825           vring_desc_t *desc_table;
1826           void *buffer_addr;
1827           u32 buffer_len;
1828
1829           b0 = vlib_get_buffer (vm, buffers[0]);
1830
1831           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
1832             {
1833               current_trace = vlib_add_trace (vm, node, b0,
1834                                               sizeof (*current_trace));
1835               vhost_user_tx_trace (current_trace, vui, qid / 2, b0, rxvq);
1836             }
1837
1838           if (PREDICT_FALSE (rxvq->last_avail_idx == rxvq->avail->idx))
1839             {
1840               error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOBUF;
1841               goto done;
1842             }
1843
1844           desc_table = rxvq->desc;
1845           map_guest_hint_p = &map_guest_hint_desc;
1846           desc_head = desc_index =
1847             rxvq->avail->ring[rxvq->last_avail_idx & qsz_mask];
1848           if (rxvq->desc[desc_head].flags & VIRTQ_DESC_F_INDIRECT)
1849             {
1850               if (PREDICT_FALSE
1851                   (rxvq->desc[desc_head].len < sizeof (vring_desc_t)))
1852                 {
1853                   error = VHOST_USER_TX_FUNC_ERROR_INDIRECT_OVERFLOW;
1854                   goto done;
1855                 }
1856               if (PREDICT_FALSE
1857                   (!(desc_table =
1858                      map_guest_mem (vui, rxvq->desc[desc_index].addr,
1859                                     &map_guest_hint_desc))))
1860                 {
1861                   error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1862                   goto done;
1863                 }
1864               desc_index = 0;
1865               map_guest_hint_p = &map_guest_hint_indirect;
1866             }
1867
1868           desc_len = vui->virtio_net_hdr_sz;
1869
1870           if (PREDICT_FALSE
1871               (!(buffer_addr =
1872                  map_guest_mem (vui, desc_table[desc_index].addr,
1873                                 map_guest_hint_p))))
1874             {
1875               error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1876               goto done;
1877             }
1878           buffer_len = desc_table[desc_index].len;
1879
1880           CLIB_PREFETCH (buffer_addr, CLIB_CACHE_LINE_BYTES, STORE);
1881
1882           virtio_net_hdr_mrg_rxbuf_t *hdr =
1883             (virtio_net_hdr_mrg_rxbuf_t *) buffer_addr;
1884           hdr->hdr.flags = 0;
1885           hdr->hdr.gso_type = 0;
1886           if (vui->virtio_net_hdr_sz == 12)
1887             hdr->num_buffers = 1;
1888
1889           vhost_user_log_dirty_pages (vui, desc_table[desc_index].addr,
1890                                       vui->virtio_net_hdr_sz);
1891
1892           u16 bytes_left = b0->current_length;
1893           buffer_addr += vui->virtio_net_hdr_sz;
1894           buffer_len -= vui->virtio_net_hdr_sz;
1895           current_b0 = b0;
1896           while (1)
1897             {
1898               if (!bytes_left)
1899                 {               //Get new input
1900                   if (current_b0->flags & VLIB_BUFFER_NEXT_PRESENT)
1901                     {
1902                       current_b0 =
1903                         vlib_get_buffer (vm, current_b0->next_buffer);
1904                       bytes_left = current_b0->current_length;
1905                     }
1906                   else
1907                     {
1908                       //End of packet
1909                       break;
1910                     }
1911                 }
1912
1913               if (buffer_len == 0)
1914                 {               //Get new output
1915                   if (desc_table[desc_index].flags & VIRTQ_DESC_F_NEXT)
1916                     {
1917                       //Next one is chained
1918                       desc_index = desc_table[desc_index].next;
1919                       if (PREDICT_FALSE
1920                           (!(buffer_addr =
1921                              map_guest_mem (vui, desc_table[desc_index].addr,
1922                                             map_guest_hint_p))))
1923                         {
1924                           rxvq->last_used_idx -= hdr->num_buffers - 1;
1925                           rxvq->last_avail_idx -= hdr->num_buffers - 1;
1926                           error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1927                           goto done;
1928                         }
1929                       buffer_len = desc_table[desc_index].len;
1930                     }
1931                   else if (vui->virtio_net_hdr_sz == 12)        //MRG is available
1932                     {
1933                       //Move from available to used buffer
1934                       rxvq->used->ring[rxvq->last_used_idx & qsz_mask].id =
1935                         desc_head;
1936                       rxvq->used->ring[rxvq->last_used_idx & qsz_mask].len =
1937                         desc_len;
1938                       vhost_user_log_dirty_ring (vui, rxvq,
1939                                                  ring[rxvq->last_used_idx &
1940                                                       qsz_mask]);
1941                       rxvq->last_avail_idx++;
1942                       rxvq->last_used_idx++;
1943                       hdr->num_buffers++;
1944
1945                       if (PREDICT_FALSE
1946                           (rxvq->last_avail_idx == rxvq->avail->idx))
1947                         {
1948                           //Dequeue queued descriptors for this packet
1949                           rxvq->last_used_idx -= hdr->num_buffers - 1;
1950                           rxvq->last_avail_idx -= hdr->num_buffers - 1;
1951                           error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOBUF;
1952                           goto done;
1953                         }
1954
1955                       desc_table = rxvq->desc;
1956                       map_guest_hint_p = &map_guest_hint_desc;
1957                       desc_head = desc_index =
1958                         rxvq->avail->ring[rxvq->last_avail_idx & qsz_mask];
1959                       if (PREDICT_FALSE
1960                           (rxvq->
1961                            desc[desc_head].flags & VIRTQ_DESC_F_INDIRECT))
1962                         {
1963                           //It is seriously unlikely that a driver will put indirect descriptor
1964                           //after non-indirect descriptor.
1965                           if (PREDICT_FALSE
1966                               (rxvq->desc[desc_head].len <
1967                                sizeof (vring_desc_t)))
1968                             {
1969                               error =
1970                                 VHOST_USER_TX_FUNC_ERROR_INDIRECT_OVERFLOW;
1971                               goto done;
1972                             }
1973                           if (PREDICT_FALSE
1974                               (!(desc_table =
1975                                  map_guest_mem (vui,
1976                                                 rxvq->desc[desc_index].addr,
1977                                                 &map_guest_hint_desc))))
1978                             {
1979                               error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1980                               goto done;
1981                             }
1982                           desc_index = 0;
1983                           map_guest_hint_p = &map_guest_hint_indirect;
1984                         }
1985
1986                       if (PREDICT_FALSE
1987                           (!(buffer_addr =
1988                              map_guest_mem (vui, desc_table[desc_index].addr,
1989                                             map_guest_hint_p))))
1990                         {
1991                           error = VHOST_USER_TX_FUNC_ERROR_MMAP_FAIL;
1992                           goto done;
1993                         }
1994                       buffer_len = desc_table[desc_index].len;
1995                       CLIB_PREFETCH (buffer_addr, CLIB_CACHE_LINE_BYTES,
1996                                      STORE);
1997                     }
1998                   else
1999                     {
2000                       error = VHOST_USER_TX_FUNC_ERROR_PKT_DROP_NOMRG;
2001                       goto done;
2002                     }
2003                 }
2004
2005               u16 bytes_to_copy = bytes_left;
2006               bytes_to_copy =
2007                 (bytes_to_copy > buffer_len) ? buffer_len : bytes_to_copy;
2008               clib_memcpy (buffer_addr,
2009                            vlib_buffer_get_current (current_b0) +
2010                            current_b0->current_length - bytes_left,
2011                            bytes_to_copy);
2012
2013               vhost_user_log_dirty_pages (vui,
2014                                           desc_table[desc_index].addr +
2015                                           desc_table[desc_index].len -
2016                                           bytes_left - bytes_to_copy,
2017                                           bytes_to_copy);
2018
2019               CLIB_PREFETCH (rxvq, sizeof (*rxvq), STORE);
2020               bytes_left -= bytes_to_copy;
2021               buffer_len -= bytes_to_copy;
2022               buffer_addr += bytes_to_copy;
2023               desc_len += bytes_to_copy;
2024             }
2025
2026           //Move from available to used ring
2027           rxvq->used->ring[rxvq->last_used_idx & qsz_mask].id = desc_head;
2028           rxvq->used->ring[rxvq->last_used_idx & qsz_mask].len = desc_len;
2029           vhost_user_log_dirty_ring (vui, rxvq,
2030                                      ring[rxvq->last_used_idx & qsz_mask]);
2031
2032           rxvq->last_avail_idx++;
2033           rxvq->last_used_idx++;
2034
2035           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2036             current_trace->hdr = *hdr;
2037
2038           buffers++;
2039           n_left--;             //At the end for error counting when 'goto done' is invoked
2040         }
2041
2042     done:
2043       CLIB_MEMORY_BARRIER ();
2044       rxvq->used->idx = rxvq->last_used_idx;
2045       vhost_user_log_dirty_ring (vui, rxvq, idx);
2046     }
2047
2048   /* interrupt (call) handling */
2049   if ((rxvq->callfd > -1) && !(rxvq->avail->flags & 1))
2050     {
2051       rxvq->n_since_last_int += n_packets - n_left;
2052
2053       if (rxvq->n_since_last_int > vum->coalesce_frames)
2054         vhost_user_send_call (vm, rxvq);
2055     }
2056
2057 done2:
2058   vhost_user_vring_unlock (vui, qid);
2059
2060 done3:
2061   if (PREDICT_FALSE (n_left && error != VHOST_USER_TX_FUNC_ERROR_NONE))
2062     {
2063       vlib_error_count (vm, node->node_index, error, n_left);
2064       vlib_increment_simple_counter
2065         (vnet_main.interface_main.sw_if_counters
2066          + VNET_INTERFACE_COUNTER_DROP,
2067          os_get_cpu_number (), vui->sw_if_index, n_left);
2068     }
2069
2070   vlib_buffer_free (vm, vlib_frame_args (frame), frame->n_vectors);
2071   return frame->n_vectors;
2072 }
2073
2074 static clib_error_t *
2075 vhost_user_interface_admin_up_down (vnet_main_t * vnm, u32 hw_if_index,
2076                                     u32 flags)
2077 {
2078   vnet_hw_interface_t *hif = vnet_get_hw_interface (vnm, hw_if_index);
2079   uword is_up = (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) != 0;
2080   vhost_user_main_t *vum = &vhost_user_main;
2081   vhost_user_intf_t *vui =
2082     vec_elt_at_index (vum->vhost_user_interfaces, hif->dev_instance);
2083
2084   vui->admin_up = is_up;
2085
2086   if (is_up)
2087     vnet_hw_interface_set_flags (vnm, vui->hw_if_index,
2088                                  VNET_HW_INTERFACE_FLAG_LINK_UP);
2089
2090   return /* no error */ 0;
2091 }
2092
2093 /* *INDENT-OFF* */
2094 VNET_DEVICE_CLASS (vhost_user_dev_class,static) = {
2095   .name = "vhost-user",
2096   .tx_function = vhost_user_intfc_tx,
2097   .tx_function_n_errors = VHOST_USER_TX_FUNC_N_ERROR,
2098   .tx_function_error_strings = vhost_user_tx_func_error_strings,
2099   .format_device_name = format_vhost_user_interface_name,
2100   .name_renumber = vhost_user_name_renumber,
2101   .admin_up_down_function = vhost_user_interface_admin_up_down,
2102   .no_flatten_output_chains = 1,
2103   .format_tx_trace = format_vhost_trace,
2104 };
2105
2106 VLIB_DEVICE_TX_FUNCTION_MULTIARCH (vhost_user_dev_class,
2107                                    vhost_user_intfc_tx)
2108 /* *INDENT-ON* */
2109
2110 static uword
2111 vhost_user_process (vlib_main_t * vm,
2112                     vlib_node_runtime_t * rt, vlib_frame_t * f)
2113 {
2114   vhost_user_main_t *vum = &vhost_user_main;
2115   vhost_user_intf_t *vui;
2116   struct sockaddr_un sun;
2117   int sockfd;
2118   unix_file_t template = { 0 };
2119   f64 timeout = 3153600000.0 /* 100 years */ ;
2120   uword *event_data = 0;
2121
2122   sockfd = socket (AF_UNIX, SOCK_STREAM, 0);
2123   sun.sun_family = AF_UNIX;
2124   template.read_function = vhost_user_socket_read;
2125   template.error_function = vhost_user_socket_error;
2126
2127
2128   if (sockfd < 0)
2129     return 0;
2130
2131   while (1)
2132     {
2133       vlib_process_wait_for_event_or_clock (vm, timeout);
2134       vlib_process_get_events (vm, &event_data);
2135       vec_reset_length (event_data);
2136
2137       timeout = 3.0;
2138
2139       vec_foreach (vui, vum->vhost_user_interfaces)
2140       {
2141
2142         if (vui->sock_is_server || !vui->active)
2143           continue;
2144
2145         if (vui->unix_fd == -1)
2146           {
2147             /* try to connect */
2148
2149             strncpy (sun.sun_path, (char *) vui->sock_filename,
2150                      sizeof (sun.sun_path) - 1);
2151
2152             if (connect
2153                 (sockfd, (struct sockaddr *) &sun,
2154                  sizeof (struct sockaddr_un)) == 0)
2155               {
2156                 vui->sock_errno = 0;
2157                 vui->unix_fd = sockfd;
2158                 template.file_descriptor = sockfd;
2159                 vui->unix_file_index = unix_file_add (&unix_main, &template);
2160                 hash_set (vum->vhost_user_interface_index_by_sock_fd, sockfd,
2161                           vui - vum->vhost_user_interfaces);
2162
2163                 sockfd = socket (AF_UNIX, SOCK_STREAM, 0);
2164                 if (sockfd < 0)
2165                   return 0;
2166               }
2167             else
2168               {
2169                 vui->sock_errno = errno;
2170               }
2171           }
2172         else
2173           {
2174             /* check if socket is alive */
2175             int error = 0;
2176             socklen_t len = sizeof (error);
2177             int retval =
2178               getsockopt (vui->unix_fd, SOL_SOCKET, SO_ERROR, &error, &len);
2179
2180             if (retval)
2181               {
2182                 DBG_SOCK ("getsockopt returned %d", retval);
2183                 vhost_user_if_disconnect (vui);
2184               }
2185           }
2186       }
2187     }
2188   return 0;
2189 }
2190
2191 /* *INDENT-OFF* */
2192 VLIB_REGISTER_NODE (vhost_user_process_node,static) = {
2193     .function = vhost_user_process,
2194     .type = VLIB_NODE_TYPE_PROCESS,
2195     .name = "vhost-user-process",
2196 };
2197 /* *INDENT-ON* */
2198
2199 int
2200 vhost_user_delete_if (vnet_main_t * vnm, vlib_main_t * vm, u32 sw_if_index)
2201 {
2202   vhost_user_main_t *vum = &vhost_user_main;
2203   vhost_user_intf_t *vui;
2204   uword *p = NULL;
2205   int rv = 0;
2206
2207   p = hash_get (vum->vhost_user_interface_index_by_sw_if_index, sw_if_index);
2208   if (p == 0)
2209     {
2210       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
2211     }
2212   else
2213     {
2214       vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
2215     }
2216
2217   // interface is inactive
2218   vui->active = 0;
2219   // Delete configured thread pinning
2220   vec_reset_length (vui->workers);
2221   // disconnect interface sockets
2222   vhost_user_if_disconnect (vui);
2223   vhost_user_update_iface_state (vui);
2224   // add to inactive interface list
2225   vec_add1 (vum->vhost_user_inactive_interfaces_index, p[0]);
2226
2227   // reset renumbered iface
2228   if (p[0] < vec_len (vum->show_dev_instance_by_real_dev_instance))
2229     vum->show_dev_instance_by_real_dev_instance[p[0]] = ~0;
2230
2231   ethernet_delete_interface (vnm, vui->hw_if_index);
2232   DBG_SOCK ("deleted (deactivated) vhost-user interface instance %d", p[0]);
2233
2234   return rv;
2235 }
2236
2237 // init server socket on specified sock_filename
2238 static int
2239 vhost_user_init_server_sock (const char *sock_filename, int *sockfd)
2240 {
2241   int rv = 0;
2242   struct sockaddr_un un = { };
2243   int fd;
2244   /* create listening socket */
2245   fd = socket (AF_UNIX, SOCK_STREAM, 0);
2246
2247   if (fd < 0)
2248     {
2249       return VNET_API_ERROR_SYSCALL_ERROR_1;
2250     }
2251
2252   un.sun_family = AF_UNIX;
2253   strncpy ((char *) un.sun_path, (char *) sock_filename,
2254            sizeof (un.sun_path) - 1);
2255
2256   /* remove if exists */
2257   unlink ((char *) sock_filename);
2258
2259   if (bind (fd, (struct sockaddr *) &un, sizeof (un)) == -1)
2260     {
2261       rv = VNET_API_ERROR_SYSCALL_ERROR_2;
2262       goto error;
2263     }
2264
2265   if (listen (fd, 1) == -1)
2266     {
2267       rv = VNET_API_ERROR_SYSCALL_ERROR_3;
2268       goto error;
2269     }
2270
2271   unix_file_t template = { 0 };
2272   template.read_function = vhost_user_socksvr_accept_ready;
2273   template.file_descriptor = fd;
2274   unix_file_add (&unix_main, &template);
2275   *sockfd = fd;
2276   return rv;
2277
2278 error:
2279   close (fd);
2280   return rv;
2281 }
2282
2283 // get new vhost_user_intf_t from inactive interfaces or create new one
2284 static vhost_user_intf_t *
2285 vhost_user_vui_new ()
2286 {
2287   vhost_user_main_t *vum = &vhost_user_main;
2288   vhost_user_intf_t *vui = NULL;
2289   int inactive_cnt = vec_len (vum->vhost_user_inactive_interfaces_index);
2290   // if there are any inactive ifaces
2291   if (inactive_cnt > 0)
2292     {
2293       // take last
2294       u32 vui_idx =
2295         vum->vhost_user_inactive_interfaces_index[inactive_cnt - 1];
2296       if (vec_len (vum->vhost_user_interfaces) > vui_idx)
2297         {
2298           vui = vec_elt_at_index (vum->vhost_user_interfaces, vui_idx);
2299           DBG_SOCK ("reusing inactive vhost-user interface index %d",
2300                     vui_idx);
2301         }
2302       // "remove" from inactive list
2303       _vec_len (vum->vhost_user_inactive_interfaces_index) -= 1;
2304     }
2305
2306   // vui was not retrieved from inactive ifaces - create new
2307   if (!vui)
2308     vec_add2 (vum->vhost_user_interfaces, vui, 1);
2309
2310   return vui;
2311 }
2312
2313 // create ethernet interface for vhost user intf
2314 static void
2315 vhost_user_create_ethernet (vnet_main_t * vnm, vlib_main_t * vm,
2316                             vhost_user_intf_t * vui, u8 * hwaddress)
2317 {
2318   vhost_user_main_t *vum = &vhost_user_main;
2319   u8 hwaddr[6];
2320   clib_error_t *error;
2321
2322   /* create hw and sw interface */
2323   if (hwaddress)
2324     {
2325       clib_memcpy (hwaddr, hwaddress, 6);
2326     }
2327   else
2328     {
2329       f64 now = vlib_time_now (vm);
2330       u32 rnd;
2331       rnd = (u32) (now * 1e6);
2332       rnd = random_u32 (&rnd);
2333
2334       clib_memcpy (hwaddr + 2, &rnd, sizeof (rnd));
2335       hwaddr[0] = 2;
2336       hwaddr[1] = 0xfe;
2337     }
2338
2339   error = ethernet_register_interface
2340     (vnm,
2341      vhost_user_dev_class.index,
2342      vui - vum->vhost_user_interfaces /* device instance */ ,
2343      hwaddr /* ethernet address */ ,
2344      &vui->hw_if_index, 0 /* flag change */ );
2345   if (error)
2346     clib_error_report (error);
2347
2348   vnet_hw_interface_t *hi = vnet_get_hw_interface (vnm, vui->hw_if_index);
2349   hi->max_l3_packet_bytes[VLIB_RX] = hi->max_l3_packet_bytes[VLIB_TX] = 9000;
2350 }
2351
2352 // initialize vui with specified attributes
2353 static void
2354 vhost_user_vui_init (vnet_main_t * vnm,
2355                      vhost_user_intf_t * vui, int sockfd,
2356                      const char *sock_filename,
2357                      u8 is_server, u64 feature_mask, u32 * sw_if_index)
2358 {
2359   vnet_sw_interface_t *sw;
2360   sw = vnet_get_hw_sw_interface (vnm, vui->hw_if_index);
2361   int q;
2362
2363   vui->unix_fd = sockfd;
2364   vui->sw_if_index = sw->sw_if_index;
2365   vui->sock_is_server = is_server;
2366   strncpy (vui->sock_filename, sock_filename,
2367            ARRAY_LEN (vui->sock_filename) - 1);
2368   vui->sock_errno = 0;
2369   vui->is_up = 0;
2370   vui->feature_mask = feature_mask;
2371   vui->active = 1;
2372   vui->unix_file_index = ~0;
2373   vui->log_base_addr = 0;
2374
2375   for (q = 0; q < VHOST_VRING_MAX_N; q++)
2376     vhost_user_vring_init (vui, q);
2377
2378   vnet_hw_interface_set_flags (vnm, vui->hw_if_index, 0);
2379
2380   if (sw_if_index)
2381     *sw_if_index = vui->sw_if_index;
2382
2383   for (q = 0; q < VHOST_VRING_MAX_N; q++)
2384     {
2385       vui->vring_locks[q] = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
2386                                                     CLIB_CACHE_LINE_BYTES);
2387       memset ((void *) vui->vring_locks[q], 0, CLIB_CACHE_LINE_BYTES);
2388     }
2389
2390   vec_validate (vui->per_cpu_tx_qid,
2391                 vlib_get_thread_main ()->n_vlib_mains - 1);
2392   vhost_user_tx_thread_placement (vui);
2393 }
2394
2395 // register vui and start polling on it
2396 static void
2397 vhost_user_vui_register (vlib_main_t * vm, vhost_user_intf_t * vui)
2398 {
2399   vhost_user_main_t *vum = &vhost_user_main;
2400   int cpu_index;
2401   vlib_thread_main_t *tm = vlib_get_thread_main ();
2402
2403   hash_set (vum->vhost_user_interface_index_by_listener_fd, vui->unix_fd,
2404             vui - vum->vhost_user_interfaces);
2405   hash_set (vum->vhost_user_interface_index_by_sw_if_index, vui->sw_if_index,
2406             vui - vum->vhost_user_interfaces);
2407
2408   /* start polling */
2409   cpu_index = vum->input_cpu_first_index +
2410     (vui - vum->vhost_user_interfaces) % vum->input_cpu_count;
2411
2412   if (tm->n_vlib_mains == 1)
2413     vlib_node_set_state (vm, vhost_user_input_node.index,
2414                          VLIB_NODE_STATE_POLLING);
2415   else
2416     vlib_node_set_state (vlib_mains[cpu_index], vhost_user_input_node.index,
2417                          VLIB_NODE_STATE_POLLING);
2418
2419   /* tell process to start polling for sockets */
2420   vlib_process_signal_event (vm, vhost_user_process_node.index, 0, 0);
2421 }
2422
2423 int
2424 vhost_user_create_if (vnet_main_t * vnm, vlib_main_t * vm,
2425                       const char *sock_filename,
2426                       u8 is_server,
2427                       u32 * sw_if_index,
2428                       u64 feature_mask,
2429                       u8 renumber, u32 custom_dev_instance, u8 * hwaddr)
2430 {
2431   vhost_user_intf_t *vui = NULL;
2432   u32 sw_if_idx = ~0;
2433   int sockfd = -1;
2434   int rv = 0;
2435
2436   if (is_server)
2437     {
2438       if ((rv = vhost_user_init_server_sock (sock_filename, &sockfd)) != 0)
2439         {
2440           return rv;
2441         }
2442     }
2443
2444   vui = vhost_user_vui_new ();
2445   ASSERT (vui != NULL);
2446
2447   vhost_user_create_ethernet (vnm, vm, vui, hwaddr);
2448   vhost_user_vui_init (vnm, vui, sockfd, sock_filename, is_server,
2449                        feature_mask, &sw_if_idx);
2450
2451   if (renumber)
2452     {
2453       vnet_interface_name_renumber (sw_if_idx, custom_dev_instance);
2454     }
2455
2456   vhost_user_vui_register (vm, vui);
2457
2458   if (sw_if_index)
2459     *sw_if_index = sw_if_idx;
2460
2461   return rv;
2462 }
2463
2464 int
2465 vhost_user_modify_if (vnet_main_t * vnm, vlib_main_t * vm,
2466                       const char *sock_filename,
2467                       u8 is_server,
2468                       u32 sw_if_index,
2469                       u64 feature_mask, u8 renumber, u32 custom_dev_instance)
2470 {
2471   vhost_user_main_t *vum = &vhost_user_main;
2472   vhost_user_intf_t *vui = NULL;
2473   u32 sw_if_idx = ~0;
2474   int sockfd = -1;
2475   int rv = 0;
2476   uword *p = NULL;
2477
2478   p = hash_get (vum->vhost_user_interface_index_by_sw_if_index, sw_if_index);
2479   if (p == 0)
2480     {
2481       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
2482     }
2483   else
2484     {
2485       vui = vec_elt_at_index (vum->vhost_user_interfaces, p[0]);
2486     }
2487
2488   // interface is inactive
2489   vui->active = 0;
2490   // disconnect interface sockets
2491   vhost_user_if_disconnect (vui);
2492
2493   if (is_server)
2494     {
2495       if ((rv = vhost_user_init_server_sock (sock_filename, &sockfd)) != 0)
2496         {
2497           return rv;
2498         }
2499     }
2500
2501   vhost_user_vui_init (vnm, vui, sockfd, sock_filename, is_server,
2502                        feature_mask, &sw_if_idx);
2503
2504   if (renumber)
2505     {
2506       vnet_interface_name_renumber (sw_if_idx, custom_dev_instance);
2507     }
2508
2509   vhost_user_vui_register (vm, vui);
2510
2511   return rv;
2512 }
2513
2514 clib_error_t *
2515 vhost_user_connect_command_fn (vlib_main_t * vm,
2516                                unformat_input_t * input,
2517                                vlib_cli_command_t * cmd)
2518 {
2519   unformat_input_t _line_input, *line_input = &_line_input;
2520   u8 *sock_filename = NULL;
2521   u32 sw_if_index;
2522   u8 is_server = 0;
2523   u64 feature_mask = (u64) ~ (0ULL);
2524   u8 renumber = 0;
2525   u32 custom_dev_instance = ~0;
2526   u8 hwaddr[6];
2527   u8 *hw = NULL;
2528
2529   /* Get a line of input. */
2530   if (!unformat_user (input, unformat_line_input, line_input))
2531     return 0;
2532
2533   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2534     {
2535       if (unformat (line_input, "socket %s", &sock_filename))
2536         ;
2537       else if (unformat (line_input, "server"))
2538         is_server = 1;
2539       else if (unformat (line_input, "feature-mask 0x%llx", &feature_mask))
2540         ;
2541       else
2542         if (unformat
2543             (line_input, "hwaddr %U", unformat_ethernet_address, hwaddr))
2544         hw = hwaddr;
2545       else if (unformat (line_input, "renumber %d", &custom_dev_instance))
2546         {
2547           renumber = 1;
2548         }
2549       else
2550         return clib_error_return (0, "unknown input `%U'",
2551                                   format_unformat_error, input);
2552     }
2553   unformat_free (line_input);
2554
2555   vnet_main_t *vnm = vnet_get_main ();
2556
2557   int rv;
2558   if ((rv = vhost_user_create_if (vnm, vm, (char *) sock_filename,
2559                                   is_server, &sw_if_index, feature_mask,
2560                                   renumber, custom_dev_instance, hw)))
2561     {
2562       vec_free (sock_filename);
2563       return clib_error_return (0, "vhost_user_create_if returned %d", rv);
2564     }
2565
2566   vec_free (sock_filename);
2567   vlib_cli_output (vm, "%U\n", format_vnet_sw_if_index_name, vnet_get_main (),
2568                    sw_if_index);
2569   return 0;
2570 }
2571
2572 clib_error_t *
2573 vhost_user_delete_command_fn (vlib_main_t * vm,
2574                               unformat_input_t * input,
2575                               vlib_cli_command_t * cmd)
2576 {
2577   unformat_input_t _line_input, *line_input = &_line_input;
2578   u32 sw_if_index = ~0;
2579   vnet_main_t *vnm = vnet_get_main ();
2580
2581   /* Get a line of input. */
2582   if (!unformat_user (input, unformat_line_input, line_input))
2583     return 0;
2584
2585   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2586     {
2587       if (unformat (line_input, "sw_if_index %d", &sw_if_index))
2588         ;
2589       else if (unformat
2590                (line_input, "%U", unformat_vnet_sw_interface, vnm,
2591                 &sw_if_index))
2592         {
2593           vnet_hw_interface_t *hwif =
2594             vnet_get_sup_hw_interface (vnm, sw_if_index);
2595           if (hwif == NULL ||
2596               vhost_user_dev_class.index != hwif->dev_class_index)
2597             return clib_error_return (0, "Not a vhost interface");
2598         }
2599       else
2600         return clib_error_return (0, "unknown input `%U'",
2601                                   format_unformat_error, input);
2602     }
2603   unformat_free (line_input);
2604   vhost_user_delete_if (vnm, vm, sw_if_index);
2605   return 0;
2606 }
2607
2608 int
2609 vhost_user_dump_ifs (vnet_main_t * vnm, vlib_main_t * vm,
2610                      vhost_user_intf_details_t ** out_vuids)
2611 {
2612   int rv = 0;
2613   vhost_user_main_t *vum = &vhost_user_main;
2614   vhost_user_intf_t *vui;
2615   vhost_user_intf_details_t *r_vuids = NULL;
2616   vhost_user_intf_details_t *vuid = NULL;
2617   u32 *hw_if_indices = 0;
2618   vnet_hw_interface_t *hi;
2619   u8 *s = NULL;
2620   int i;
2621
2622   if (!out_vuids)
2623     return -1;
2624
2625   vec_foreach (vui, vum->vhost_user_interfaces)
2626   {
2627     if (vui->active)
2628       vec_add1 (hw_if_indices, vui->hw_if_index);
2629   }
2630
2631   for (i = 0; i < vec_len (hw_if_indices); i++)
2632     {
2633       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
2634       vui = vec_elt_at_index (vum->vhost_user_interfaces, hi->dev_instance);
2635
2636       vec_add2 (r_vuids, vuid, 1);
2637       vuid->sw_if_index = vui->sw_if_index;
2638       vuid->virtio_net_hdr_sz = vui->virtio_net_hdr_sz;
2639       vuid->features = vui->features;
2640       vuid->is_server = vui->sock_is_server;
2641       vuid->num_regions = vui->nregions;
2642       vuid->sock_errno = vui->sock_errno;
2643       strncpy ((char *) vuid->sock_filename, (char *) vui->sock_filename,
2644                ARRAY_LEN (vuid->sock_filename) - 1);
2645
2646       s = format (s, "%v%c", hi->name, 0);
2647
2648       strncpy ((char *) vuid->if_name, (char *) s,
2649                ARRAY_LEN (vuid->if_name) - 1);
2650       _vec_len (s) = 0;
2651     }
2652
2653   vec_free (s);
2654   vec_free (hw_if_indices);
2655
2656   *out_vuids = r_vuids;
2657
2658   return rv;
2659 }
2660
2661 clib_error_t *
2662 show_vhost_user_command_fn (vlib_main_t * vm,
2663                             unformat_input_t * input,
2664                             vlib_cli_command_t * cmd)
2665 {
2666   clib_error_t *error = 0;
2667   vnet_main_t *vnm = vnet_get_main ();
2668   vhost_user_main_t *vum = &vhost_user_main;
2669   vhost_user_intf_t *vui;
2670   u32 hw_if_index, *hw_if_indices = 0;
2671   vnet_hw_interface_t *hi;
2672   vhost_cpu_t *vhc;
2673   vhost_iface_and_queue_t *vhiq;
2674   u32 ci;
2675
2676   int i, j, q;
2677   int show_descr = 0;
2678   struct feat_struct
2679   {
2680     u8 bit;
2681     char *str;
2682   };
2683   struct feat_struct *feat_entry;
2684
2685   static struct feat_struct feat_array[] = {
2686 #define _(s,b) { .str = #s, .bit = b, },
2687     foreach_virtio_net_feature
2688 #undef _
2689     {.str = NULL}
2690   };
2691
2692 #define foreach_protocol_feature \
2693   _(VHOST_USER_PROTOCOL_F_MQ) \
2694   _(VHOST_USER_PROTOCOL_F_LOG_SHMFD)
2695
2696   static struct feat_struct proto_feat_array[] = {
2697 #define _(s) { .str = #s, .bit = s},
2698     foreach_protocol_feature
2699 #undef _
2700     {.str = NULL}
2701   };
2702
2703   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2704     {
2705       if (unformat
2706           (input, "%U", unformat_vnet_hw_interface, vnm, &hw_if_index))
2707         {
2708           vec_add1 (hw_if_indices, hw_if_index);
2709         }
2710       else if (unformat (input, "descriptors") || unformat (input, "desc"))
2711         show_descr = 1;
2712       else
2713         {
2714           error = clib_error_return (0, "unknown input `%U'",
2715                                      format_unformat_error, input);
2716           goto done;
2717         }
2718     }
2719   if (vec_len (hw_if_indices) == 0)
2720     {
2721       vec_foreach (vui, vum->vhost_user_interfaces)
2722       {
2723         if (vui->active)
2724           vec_add1 (hw_if_indices, vui->hw_if_index);
2725       }
2726     }
2727   vlib_cli_output (vm, "Virtio vhost-user interfaces");
2728   vlib_cli_output (vm, "Global:\n  coalesce frames %d time %e",
2729                    vum->coalesce_frames, vum->coalesce_time);
2730
2731   for (i = 0; i < vec_len (hw_if_indices); i++)
2732     {
2733       hi = vnet_get_hw_interface (vnm, hw_if_indices[i]);
2734       vui = vec_elt_at_index (vum->vhost_user_interfaces, hi->dev_instance);
2735       vlib_cli_output (vm, "Interface: %s (ifindex %d)",
2736                        hi->name, hw_if_indices[i]);
2737
2738       vlib_cli_output (vm, "virtio_net_hdr_sz %d\n"
2739                        " features mask (0x%llx): \n"
2740                        " features (0x%llx): \n",
2741                        vui->virtio_net_hdr_sz, vui->feature_mask,
2742                        vui->features);
2743
2744       feat_entry = (struct feat_struct *) &feat_array;
2745       while (feat_entry->str)
2746         {
2747           if (vui->features & (1ULL << feat_entry->bit))
2748             vlib_cli_output (vm, "   %s (%d)", feat_entry->str,
2749                              feat_entry->bit);
2750           feat_entry++;
2751         }
2752
2753       vlib_cli_output (vm, "  protocol features (0x%llx)",
2754                        vui->protocol_features);
2755       feat_entry = (struct feat_struct *) &proto_feat_array;
2756       while (feat_entry->str)
2757         {
2758           if (vui->protocol_features & (1ULL << feat_entry->bit))
2759             vlib_cli_output (vm, "   %s (%d)", feat_entry->str,
2760                              feat_entry->bit);
2761           feat_entry++;
2762         }
2763
2764       vlib_cli_output (vm, "\n");
2765
2766       vlib_cli_output (vm, " socket filename %s type %s errno \"%s\"\n\n",
2767                        vui->sock_filename,
2768                        vui->sock_is_server ? "server" : "client",
2769                        strerror (vui->sock_errno));
2770
2771       vlib_cli_output (vm, " rx placement: ");
2772       vec_foreach (vhc, vum->cpus)
2773       {
2774         vec_foreach (vhiq, vhc->rx_queues)
2775         {
2776           if (vhiq->vhost_iface_index == vui - vum->vhost_user_interfaces)
2777             vlib_cli_output (vm, "   thread %d on vring %d\n",
2778                              vhc - vum->cpus, VHOST_VRING_IDX_TX (vhiq->qid));
2779         }
2780       }
2781
2782       vlib_cli_output (vm, " tx placement: %s\n",
2783                        vui->use_tx_spinlock ? "spin-lock" : "lock-free");
2784
2785       vec_foreach_index (ci, vui->per_cpu_tx_qid)
2786       {
2787         vlib_cli_output (vm, "   thread %d on vring %d\n", ci,
2788                          VHOST_VRING_IDX_RX (vui->per_cpu_tx_qid[ci]));
2789       }
2790
2791       vlib_cli_output (vm, "\n");
2792
2793       vlib_cli_output (vm, " Memory regions (total %d)\n", vui->nregions);
2794
2795       if (vui->nregions)
2796         {
2797           vlib_cli_output (vm,
2798                            " region fd    guest_phys_addr    memory_size        userspace_addr     mmap_offset        mmap_addr\n");
2799           vlib_cli_output (vm,
2800                            " ====== ===== ================== ================== ================== ================== ==================\n");
2801         }
2802       for (j = 0; j < vui->nregions; j++)
2803         {
2804           vlib_cli_output (vm,
2805                            "  %d     %-5d 0x%016lx 0x%016lx 0x%016lx 0x%016lx 0x%016lx\n",
2806                            j, vui->region_mmap_fd[j],
2807                            vui->regions[j].guest_phys_addr,
2808                            vui->regions[j].memory_size,
2809                            vui->regions[j].userspace_addr,
2810                            vui->regions[j].mmap_offset,
2811                            pointer_to_uword (vui->region_mmap_addr[j]));
2812         }
2813       for (q = 0; q < VHOST_VRING_MAX_N; q++)
2814         {
2815           if (!vui->vrings[q].started)
2816             continue;
2817
2818           vlib_cli_output (vm, "\n Virtqueue %d (%s%s)\n", q,
2819                            (q & 1) ? "RX" : "TX",
2820                            vui->vrings[q].enabled ? "" : " disabled");
2821
2822           vlib_cli_output (vm,
2823                            "  qsz %d last_avail_idx %d last_used_idx %d\n",
2824                            vui->vrings[q].qsz, vui->vrings[q].last_avail_idx,
2825                            vui->vrings[q].last_used_idx);
2826
2827           if (vui->vrings[q].avail && vui->vrings[q].used)
2828             vlib_cli_output (vm,
2829                              "  avail.flags %x avail.idx %d used.flags %x used.idx %d\n",
2830                              vui->vrings[q].avail->flags,
2831                              vui->vrings[q].avail->idx,
2832                              vui->vrings[q].used->flags,
2833                              vui->vrings[q].used->idx);
2834
2835           vlib_cli_output (vm, "  kickfd %d callfd %d errfd %d\n",
2836                            vui->vrings[q].kickfd,
2837                            vui->vrings[q].callfd, vui->vrings[q].errfd);
2838
2839           if (show_descr)
2840             {
2841               vlib_cli_output (vm, "\n  descriptor table:\n");
2842               vlib_cli_output (vm,
2843                                "   id          addr         len  flags  next      user_addr\n");
2844               vlib_cli_output (vm,
2845                                "  ===== ================== ===== ====== ===== ==================\n");
2846               for (j = 0; j < vui->vrings[q].qsz; j++)
2847                 {
2848                   u32 mem_hint = 0;
2849                   vlib_cli_output (vm,
2850                                    "  %-5d 0x%016lx %-5d 0x%04x %-5d 0x%016lx\n",
2851                                    j, vui->vrings[q].desc[j].addr,
2852                                    vui->vrings[q].desc[j].len,
2853                                    vui->vrings[q].desc[j].flags,
2854                                    vui->vrings[q].desc[j].next,
2855                                    pointer_to_uword (map_guest_mem
2856                                                      (vui,
2857                                                       vui->vrings[q].desc[j].
2858                                                       addr, &mem_hint)));
2859                 }
2860             }
2861         }
2862       vlib_cli_output (vm, "\n");
2863     }
2864 done:
2865   vec_free (hw_if_indices);
2866   return error;
2867 }
2868
2869 /*
2870  * CLI functions
2871  */
2872
2873 /* *INDENT-OFF* */
2874 VLIB_CLI_COMMAND (vhost_user_connect_command, static) = {
2875     .path = "create vhost-user",
2876     .short_help = "create vhost-user socket <socket-filename> [server] [feature-mask <hex>] [renumber <dev_instance>]",
2877     .function = vhost_user_connect_command_fn,
2878 };
2879
2880 VLIB_CLI_COMMAND (vhost_user_delete_command, static) = {
2881     .path = "delete vhost-user",
2882     .short_help = "delete vhost-user sw_if_index <nn>",
2883     .function = vhost_user_delete_command_fn,
2884 };
2885
2886 VLIB_CLI_COMMAND (show_vhost_user_command, static) = {
2887     .path = "show vhost-user",
2888     .short_help = "show vhost-user interface",
2889     .function = show_vhost_user_command_fn,
2890 };
2891 /* *INDENT-ON* */
2892
2893 static clib_error_t *
2894 vhost_user_config (vlib_main_t * vm, unformat_input_t * input)
2895 {
2896   vhost_user_main_t *vum = &vhost_user_main;
2897
2898   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2899     {
2900       if (unformat (input, "coalesce-frames %d", &vum->coalesce_frames))
2901         ;
2902       else if (unformat (input, "coalesce-time %f", &vum->coalesce_time))
2903         ;
2904       else if (unformat (input, "dont-dump-memory"))
2905         vum->dont_dump_vhost_user_memory = 1;
2906       else
2907         return clib_error_return (0, "unknown input `%U'",
2908                                   format_unformat_error, input);
2909     }
2910
2911   return 0;
2912 }
2913
2914 /* vhost-user { ... } configuration. */
2915 VLIB_CONFIG_FUNCTION (vhost_user_config, "vhost-user");
2916
2917 void
2918 vhost_user_unmap_all (void)
2919 {
2920   vhost_user_main_t *vum = &vhost_user_main;
2921   vhost_user_intf_t *vui;
2922
2923   if (vum->dont_dump_vhost_user_memory)
2924     {
2925       vec_foreach (vui, vum->vhost_user_interfaces)
2926       {
2927         unmap_all_mem_regions (vui);
2928       }
2929     }
2930 }
2931
2932 static clib_error_t *
2933 vhost_thread_command_fn (vlib_main_t * vm,
2934                          unformat_input_t * input, vlib_cli_command_t * cmd)
2935 {
2936   unformat_input_t _line_input, *line_input = &_line_input;
2937   u32 worker_thread_index;
2938   u32 sw_if_index;
2939   u8 del = 0;
2940   int rv;
2941
2942   /* Get a line of input. */
2943   if (!unformat_user (input, unformat_line_input, line_input))
2944     return 0;
2945
2946   if (!unformat
2947       (line_input, "%U %d", unformat_vnet_sw_interface, vnet_get_main (),
2948        &sw_if_index, &worker_thread_index))
2949     {
2950       unformat_free (line_input);
2951       return clib_error_return (0, "unknown input `%U'",
2952                                 format_unformat_error, input);
2953     }
2954
2955   if (unformat (line_input, "del"))
2956     del = 1;
2957
2958   if ((rv =
2959        vhost_user_thread_placement (sw_if_index, worker_thread_index, del)))
2960     return clib_error_return (0, "vhost_user_thread_placement returned %d",
2961                               rv);
2962   return 0;
2963 }
2964
2965
2966 /* *INDENT-OFF* */
2967 VLIB_CLI_COMMAND (vhost_user_thread_command, static) = {
2968     .path = "vhost thread",
2969     .short_help = "vhost thread <iface> <worker-index> [del]",
2970     .function = vhost_thread_command_fn,
2971 };
2972 /* *INDENT-ON* */
2973
2974 /*
2975  * fd.io coding-style-patch-verification: ON
2976  *
2977  * Local Variables:
2978  * eval: (c-set-style "gnu")
2979  * End:
2980  */