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