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