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