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