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