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