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