a4b0f01475fda86df2b1f5ae1d8e5c2236f2145b
[vpp.git] / vnet / vnet / devices / dpdk / init.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <vnet/vnet.h>
16 #include <vppinfra/vec.h>
17 #include <vppinfra/error.h>
18 #include <vppinfra/format.h>
19
20 #include <vnet/ethernet/ethernet.h>
21 #include <vnet/devices/dpdk/dpdk.h>
22 #include <vlib/unix/physmem.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <sys/stat.h>
28 #include <sys/mount.h>
29 #include <string.h>
30 #include <fcntl.h>
31
32 #include "dpdk_priv.h"
33
34 dpdk_main_t dpdk_main;
35
36 /* force linker to link functions used by vlib and declared weak */
37 void *vlib_weakly_linked_functions[] = {
38   &rte_pktmbuf_init,
39   &rte_pktmbuf_pool_init,
40 };
41
42 #define LINK_STATE_ELOGS        0
43
44 #define DEFAULT_HUGE_DIR "/run/vpp/hugepages"
45 #define VPP_RUN_DIR "/run/vpp"
46
47 /* Port configuration, mildly modified Intel app values */
48
49 static struct rte_eth_conf port_conf_template = {
50   .rxmode = {
51     .split_hdr_size = 0,
52     .header_split   = 0, /**< Header Split disabled */
53     .hw_ip_checksum = 0, /**< IP checksum offload disabled */
54     .hw_vlan_filter = 0, /**< VLAN filtering disabled */
55     .hw_strip_crc   = 1, /**< CRC stripped by hardware */
56   },
57   .txmode = {
58     .mq_mode = ETH_MQ_TX_NONE,
59   },
60 };
61
62 clib_error_t *
63 dpdk_port_setup (dpdk_main_t * dm, dpdk_device_t * xd)
64 {
65   vlib_main_t * vm = vlib_get_main();
66   vlib_buffer_main_t * bm = vm->buffer_main;
67   int rv;
68   int j;
69
70   ASSERT(os_get_cpu_number() == 0);
71
72   if (xd->admin_up) {
73     vnet_hw_interface_set_flags (dm->vnet_main, xd->vlib_hw_if_index, 0);
74     rte_eth_dev_stop (xd->device_index);
75   }
76
77   rv = rte_eth_dev_configure (xd->device_index, xd->rx_q_used,
78                               xd->tx_q_used, &xd->port_conf);
79
80   if (rv < 0)
81     return clib_error_return (0, "rte_eth_dev_configure[%d]: err %d",
82                               xd->device_index, rv);
83
84   /* Set up one TX-queue per worker thread */
85   for (j = 0; j < xd->tx_q_used; j++)
86     {
87       rv = rte_eth_tx_queue_setup(xd->device_index, j, xd->nb_tx_desc,
88                                  xd->cpu_socket, &xd->tx_conf);
89       if (rv < 0)
90         break;
91     }
92
93     if (rv < 0)
94       return clib_error_return (0, "rte_eth_tx_queue_setup[%d]: err %d",
95                                 xd->device_index, rv);
96
97   for (j = 0; j < xd->rx_q_used; j++)
98     {
99
100       rv = rte_eth_rx_queue_setup(xd->device_index, j, xd->nb_rx_desc,
101                                   xd->cpu_socket, 0,
102                                   bm->pktmbuf_pools[xd->cpu_socket_id_by_queue[j]]);
103       if (rv < 0)
104         return clib_error_return (0, "rte_eth_rx_queue_setup[%d]: err %d",
105                                   xd->device_index, rv);
106     }
107
108   if (xd->admin_up) {
109     rte_eth_dev_start (xd->device_index);
110   }
111   return 0;
112 }
113
114 static u32 dpdk_flag_change (vnet_main_t * vnm, 
115                              vnet_hw_interface_t * hi,
116                              u32 flags)
117 {
118   dpdk_main_t * dm = &dpdk_main;
119   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
120   u32 old = 0;
121
122   if (ETHERNET_INTERFACE_FLAG_CONFIG_PROMISC(flags))
123     {
124       old = xd->promisc;
125       xd->promisc = flags & ETHERNET_INTERFACE_FLAG_ACCEPT_ALL;
126       
127       if (xd->admin_up)
128         {
129           if (xd->promisc)
130             rte_eth_promiscuous_enable(xd->device_index);
131           else
132             rte_eth_promiscuous_disable(xd->device_index);
133         }
134     }
135   else if (ETHERNET_INTERFACE_FLAG_CONFIG_MTU(flags))
136     {
137       /*
138        * DAW-FIXME: The Cisco VIC firmware does not provide an api for a
139        *            driver to dynamically change the mtu.  If/when the 
140        *            VIC firmware gets fixed, then this should be removed.
141        */
142       if (xd->pmd == VNET_DPDK_PMD_VICE ||
143           xd->pmd == VNET_DPDK_PMD_ENIC)
144         {
145           struct rte_eth_dev_info dev_info;
146
147           /*
148            * Restore mtu to what has been set by CIMC in the firmware cfg.
149            */
150           rte_eth_dev_info_get(xd->device_index, &dev_info);
151           hi->max_packet_bytes = dev_info.max_rx_pktlen;
152
153           vlib_cli_output (vlib_get_main(), 
154                            "Cisco VIC mtu can only be changed "
155                            "using CIMC then rebooting the server!");
156         }
157       else
158         {
159           int rv;
160       
161           /*
162            * DAW-FIXME: The DPDK VMXNET3 driver does not currently support
163            *            multi-buffer packets.  Max out at 1518 bytes for now.
164            *
165            *            If/when the driver gets fixed, then this should be
166            *            removed.
167            */
168           if ((xd->pmd == VNET_DPDK_PMD_VMXNET3) &&
169               (hi->max_packet_bytes > 1518))
170             {
171               hi->max_packet_bytes = 1518;
172
173               vlib_cli_output (vlib_get_main(), 
174                                "VMXNET3 driver does not  support jumbo frames "
175                                "yet -- setting mtu to 1518!");
176             }
177
178           xd->port_conf.rxmode.max_rx_pkt_len = hi->max_packet_bytes;
179
180           if (xd->admin_up)
181             rte_eth_dev_stop (xd->device_index);
182
183     rv = rte_eth_dev_configure
184       (xd->device_index,
185        xd->rx_q_used,
186        xd->tx_q_used,
187        &xd->port_conf);
188
189           if (rv < 0)
190             vlib_cli_output (vlib_get_main(), 
191                              "rte_eth_dev_configure[%d]: err %d",
192                              xd->device_index, rv);
193
194           rte_eth_dev_set_mtu(xd->device_index, hi->max_packet_bytes);
195
196           if (xd->admin_up)
197             rte_eth_dev_start (xd->device_index);
198         }
199     }
200   return old;
201 }
202
203 #ifdef NETMAP
204 extern int rte_netmap_probe(void);
205 #endif
206
207 static clib_error_t *
208 dpdk_lib_init (dpdk_main_t * dm)
209 {
210   u32 nports;
211   u32 nb_desc = 0;
212   int i;
213   clib_error_t * error;
214   vlib_main_t * vm = vlib_get_main();
215   vlib_thread_main_t * tm = vlib_get_thread_main();
216   vnet_sw_interface_t * sw;
217   vnet_hw_interface_t * hi;
218   dpdk_device_t * xd;
219   vlib_thread_registration_t * tr;
220   uword * p;
221
222   u32 next_cpu = 0;
223   u8 af_packet_port_id = 0;
224
225   dm->input_cpu_first_index = 0;
226   dm->input_cpu_count = 1;
227
228   /* find out which cpus will be used for input */
229   p = hash_get_mem (tm->thread_registrations_by_name, "io");
230   tr = p ? (vlib_thread_registration_t *) p[0] : 0;
231
232   if (!tr || tr->count == 0)
233     {
234       /* no io threads, workers doing input */
235       p = hash_get_mem (tm->thread_registrations_by_name, "workers");
236       tr = p ? (vlib_thread_registration_t *) p[0] : 0;
237     }
238   else
239     {
240       dm->have_io_threads = 1;
241     }
242
243   if (tr && tr->count > 0)
244     {
245       dm->input_cpu_first_index = tr->first_index;
246       dm->input_cpu_count = tr->count;
247     }
248
249   vec_validate_aligned (dm->devices_by_cpu, tm->n_vlib_mains - 1,
250                         CLIB_CACHE_LINE_BYTES);
251
252   vec_validate_aligned (dm->workers, tm->n_vlib_mains - 1,
253                         CLIB_CACHE_LINE_BYTES);
254
255 #ifdef NETMAP
256   if(rte_netmap_probe() < 0)
257     return clib_error_return (0, "rte netmap probe failed");
258 #endif
259
260   nports = rte_eth_dev_count();
261   if (nports < 1) 
262     {
263       clib_warning ("DPDK drivers found no ports...");
264     }
265
266   if (CLIB_DEBUG > 0)
267     clib_warning ("DPDK drivers found %d ports...", nports);
268
269   /* 
270    * All buffers are all allocated from the same rte_mempool.
271    * Thus they all have the same number of data bytes.
272    */
273   dm->vlib_buffer_free_list_index = 
274       vlib_buffer_get_or_create_free_list (
275           vm, VLIB_BUFFER_DEFAULT_FREE_LIST_BYTES, "dpdk rx");
276
277   for (i = 0; i < nports; i++)
278     {
279       u8 addr[6];
280       int j;
281       struct rte_eth_dev_info dev_info;
282       clib_error_t * rv;
283       struct rte_eth_link l;
284
285       /* Create vnet interface */
286       vec_add2_aligned (dm->devices, xd, 1, CLIB_CACHE_LINE_BYTES);
287       xd->nb_rx_desc = DPDK_NB_RX_DESC_DEFAULT;
288       xd->nb_tx_desc = DPDK_NB_TX_DESC_DEFAULT;
289       xd->cpu_socket = (i8) rte_eth_dev_socket_id(i);
290       rte_eth_dev_info_get(i, &dev_info);
291
292       memcpy(&xd->tx_conf, &dev_info.default_txconf,
293              sizeof(struct rte_eth_txconf));
294       if (dm->no_multi_seg)
295         {
296           xd->tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOMULTSEGS;
297           port_conf_template.rxmode.jumbo_frame = 0;
298         }
299       else
300         {
301           xd->tx_conf.txq_flags &= ~ETH_TXQ_FLAGS_NOMULTSEGS;
302           port_conf_template.rxmode.jumbo_frame = 1;
303         }
304
305       memcpy(&xd->port_conf, &port_conf_template, sizeof(struct rte_eth_conf));
306
307       xd->tx_q_used = dev_info.max_tx_queues < tm->n_vlib_mains ?
308                       1 : tm->n_vlib_mains;
309
310       if (dm->use_rss > 1 && dev_info.max_rx_queues >= dm->use_rss)
311         {
312           xd->rx_q_used = dm->use_rss;
313           xd->port_conf.rxmode.mq_mode = ETH_MQ_RX_RSS;
314           xd->port_conf.rx_adv_conf.rss_conf.rss_hf = ETH_RSS_IP | ETH_RSS_UDP | ETH_RSS_TCP;
315         }
316       else
317         xd->rx_q_used = 1;
318
319       xd->dev_type = VNET_DPDK_DEV_ETH;
320       if (!xd->pmd) {
321
322
323 #define _(s,f) else if (!strcmp(dev_info.driver_name, s)) \
324                  xd->pmd = VNET_DPDK_PMD_##f;
325         if (0)
326           ;
327         foreach_dpdk_pmd
328 #undef _
329         else
330           xd->pmd = VNET_DPDK_PMD_UNKNOWN;
331
332
333         switch (xd->pmd) {
334           /* 1G adapters */
335           case VNET_DPDK_PMD_E1000EM:
336           case VNET_DPDK_PMD_IGB:
337           case VNET_DPDK_PMD_IGBVF:
338             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_1G;
339             break;
340
341           /* 10G adapters */
342           case VNET_DPDK_PMD_IXGBE:
343           case VNET_DPDK_PMD_IXGBEVF:
344             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_10G;
345             xd->nb_rx_desc = DPDK_NB_RX_DESC_10GE;
346             xd->nb_tx_desc = DPDK_NB_TX_DESC_10GE;
347             break;
348
349           /* Cisco VIC */
350           case VNET_DPDK_PMD_VICE:
351           case VNET_DPDK_PMD_ENIC:
352             rte_eth_link_get_nowait(xd->device_index, &l);
353             if (l.link_speed == 40000)
354               {
355                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
356                 xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
357                 xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
358               }
359             else
360               {
361                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_10G;
362                 xd->nb_rx_desc = DPDK_NB_RX_DESC_10GE;
363                 xd->nb_tx_desc = DPDK_NB_TX_DESC_10GE;
364               }
365             break;
366
367           /* Intel Fortville */
368           case VNET_DPDK_PMD_I40E:
369           case VNET_DPDK_PMD_I40EVF:
370             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
371             xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
372             xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
373
374             switch (dev_info.pci_dev->id.device_id) {
375               case I40E_DEV_ID_10G_BASE_T:
376               case I40E_DEV_ID_SFP_XL710:
377                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_10G;
378                 break;
379               case I40E_DEV_ID_QSFP_A:
380               case I40E_DEV_ID_QSFP_B:
381               case I40E_DEV_ID_QSFP_C:
382                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
383                 break;
384               case I40E_DEV_ID_VF:
385                 rte_eth_link_get_nowait(xd->device_index, &l);
386                 xd->port_type = l.link_speed == 10000 ?
387                   VNET_DPDK_PORT_TYPE_ETH_10G : VNET_DPDK_PORT_TYPE_ETH_40G;
388                 break;
389               default:
390                 xd->port_type = VNET_DPDK_PORT_TYPE_UNKNOWN;
391             }
392             break;
393
394           /* Intel Red Rock Canyon */
395           case VNET_DPDK_PMD_FM10K:
396             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_SWITCH;
397             xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
398             xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
399             break;
400
401           /* virtio */
402           case VNET_DPDK_PMD_VIRTIO:
403             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_1G;
404             xd->nb_rx_desc = DPDK_NB_RX_DESC_VIRTIO;
405             xd->nb_tx_desc = DPDK_NB_TX_DESC_VIRTIO;
406             break;
407
408           /* vmxnet3 */
409           case VNET_DPDK_PMD_VMXNET3:
410             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_1G;
411             xd->tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOMULTSEGS;
412             break;
413
414           case VNET_DPDK_PMD_AF_PACKET:
415             xd->port_type = VNET_DPDK_PORT_TYPE_AF_PACKET;
416             xd->af_packet_port_id = af_packet_port_id++;
417             break;
418
419           default:
420             xd->port_type = VNET_DPDK_PORT_TYPE_UNKNOWN;
421         }
422
423   #ifdef NETMAP
424         if(strncmp(dev_info.driver_name, "vale", 4) == 0
425              || strncmp(dev_info.driver_name, "netmap", 6) == 0)
426           {
427             xd->pmd = VNET_DPDK_PMD_NETMAP;
428             xd->port_type = VNET_DPDK_PORT_TYPE_NETMAP;
429           }
430   #endif
431
432       }
433
434       /*
435        * Ensure default mtu is not > the mtu read from the hardware.
436        * Otherwise rte_eth_dev_configure() will fail and the port will
437        * not be available.
438        */
439       xd->port_conf.rxmode.max_rx_pkt_len = 
440               (ETHERNET_MAX_PACKET_BYTES > dev_info.max_rx_pktlen) ? 
441               dev_info.max_rx_pktlen : ETHERNET_MAX_PACKET_BYTES;
442
443       /*
444        * DAW-FIXME: VMXNET3 driver doesn't support jumbo / multi-buffer pkts
445        */
446       if (xd->pmd == VNET_DPDK_PMD_VMXNET3)
447         {
448           xd->port_conf.rxmode.max_rx_pkt_len = 1518;
449           xd->port_conf.rxmode.jumbo_frame = 0;
450         }
451
452       if (xd->pmd == VNET_DPDK_PMD_AF_PACKET)
453         {
454           f64 now = vlib_time_now(vm);
455           u32 rnd;
456           rnd = (u32) (now * 1e6);
457           rnd = random_u32 (&rnd);
458           memcpy (addr+2, &rnd, sizeof(rnd));
459           addr[0] = 2;
460           addr[1] = 0xfe;
461         }
462       else
463         rte_eth_macaddr_get(i,(struct ether_addr *)addr);
464
465       if (xd->tx_q_used < tm->n_vlib_mains)
466         {
467           xd->lockp = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
468                                               CLIB_CACHE_LINE_BYTES);
469           memset ((void *) xd->lockp, 0, CLIB_CACHE_LINE_BYTES);
470         }
471
472       xd->device_index = xd - dm->devices;
473       ASSERT(i == xd->device_index);
474       xd->per_interface_next_index = ~0;
475
476       /* assign interface to input thread */
477       dpdk_device_and_queue_t * dq;
478       int q;
479
480       for (q = 0; q < xd->rx_q_used; q++)
481         {
482           int cpu = dm->input_cpu_first_index + next_cpu;
483           unsigned lcore = vlib_worker_threads[cpu].dpdk_lcore_id;
484
485           /*
486            * numa node for worker thread handling this queue
487            * needed for taking buffers from the right mempool
488            */
489           vec_validate(xd->cpu_socket_id_by_queue, q);
490           xd->cpu_socket_id_by_queue[q] = rte_lcore_to_socket_id(lcore);
491
492           /*
493            * construct vector of (device,queue) pairs for each worker thread
494            */
495           vec_add2(dm->devices_by_cpu[cpu], dq, 1);
496           dq->device = xd->device_index;
497           dq->queue_id = q;
498
499           next_cpu++;
500           if (next_cpu == dm->input_cpu_count)
501             next_cpu = 0;
502         }
503
504       vec_validate_aligned (xd->tx_vectors, tm->n_vlib_mains,
505                             CLIB_CACHE_LINE_BYTES);
506       for (j = 0; j < tm->n_vlib_mains; j++)
507         {
508           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE, 
509                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
510           vec_reset_length (xd->tx_vectors[j]);
511         }
512
513       vec_validate_aligned (xd->rx_vectors, xd->rx_q_used,
514                             CLIB_CACHE_LINE_BYTES);
515       for (j = 0; j< xd->rx_q_used; j++)
516         {
517           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
518                                 CLIB_CACHE_LINE_BYTES);
519           vec_reset_length (xd->rx_vectors[j]);
520         }
521
522       vec_validate_aligned (xd->frames, tm->n_vlib_mains,
523                             CLIB_CACHE_LINE_BYTES);
524
525       rv = dpdk_port_setup(dm, xd);
526
527       if (rv < 0)
528         return rv;
529
530       /* count the number of descriptors used for this device */
531       nb_desc += xd->nb_rx_desc + xd->nb_tx_desc * xd->tx_q_used;
532
533       error = ethernet_register_interface
534         (dm->vnet_main,
535          dpdk_device_class.index,
536          xd->device_index,
537          /* ethernet address */ addr,
538          &xd->vlib_hw_if_index, 
539          dpdk_flag_change);
540       if (error)
541         return error;
542       
543       sw = vnet_get_hw_sw_interface (dm->vnet_main, xd->vlib_hw_if_index);
544       xd->vlib_sw_if_index = sw->sw_if_index;
545       hi = vnet_get_hw_interface (dm->vnet_main, xd->vlib_hw_if_index);
546
547       /*
548        * DAW-FIXME: The Cisco VIC firmware does not provide an api for a
549        *            driver to dynamically change the mtu.  If/when the 
550        *            VIC firmware gets fixed, then this should be removed.
551        */
552       if (xd->pmd == VNET_DPDK_PMD_VICE ||
553           xd->pmd == VNET_DPDK_PMD_ENIC)
554         {
555           /*
556            * Initialize mtu to what has been set by CIMC in the firmware cfg.
557            */
558           hi->max_packet_bytes = dev_info.max_rx_pktlen;
559           /*
560            * remove vlan tag from VIC port to fix VLAN0 issue.
561            * TODO Handle VLAN tagged traffic
562            */
563           int vlan_off;
564           vlan_off = rte_eth_dev_get_vlan_offload(xd->device_index);
565           vlan_off |= ETH_VLAN_STRIP_OFFLOAD;
566           rte_eth_dev_set_vlan_offload(xd->device_index, vlan_off);
567         }
568       /*
569        * DAW-FIXME: VMXNET3 driver doesn't support jumbo / multi-buffer pkts
570        */
571       else if (xd->pmd == VNET_DPDK_PMD_VMXNET3)
572           hi->max_packet_bytes = 1518;
573
574       hi->max_l3_packet_bytes[VLIB_RX] = hi->max_l3_packet_bytes[VLIB_TX] = 
575               xd->port_conf.rxmode.max_rx_pkt_len - sizeof(ethernet_header_t);
576
577      rte_eth_dev_set_mtu(xd->device_index, hi->max_packet_bytes);
578     }
579
580   if (dm->num_kni) {
581     clib_warning("Initializing KNI interfaces...");
582     rte_kni_init(dm->num_kni);
583     for (i = 0; i < dm->num_kni; i++)
584     {
585       u8 addr[6];
586       int j;
587
588       /* Create vnet interface */
589       vec_add2_aligned (dm->devices, xd, 1, CLIB_CACHE_LINE_BYTES);
590       xd->dev_type = VNET_DPDK_DEV_KNI;
591
592       xd->device_index = xd - dm->devices;
593       ASSERT(nports + i == xd->device_index);
594       xd->per_interface_next_index = ~0;
595       xd->kni_port_id = i;
596       xd->cpu_socket = -1;
597       hash_set (dm->dpdk_device_by_kni_port_id, i, xd - dm->devices);
598       xd->rx_q_used = 1;
599
600       /* assign interface to input thread */
601       dpdk_device_and_queue_t * dq;
602       vec_add2(dm->devices_by_cpu[dm->input_cpu_first_index], dq, 1);
603       dq->device = xd->device_index;
604       dq->queue_id = 0;
605
606       vec_validate_aligned (xd->tx_vectors, tm->n_vlib_mains,
607                             CLIB_CACHE_LINE_BYTES);
608       for (j = 0; j < tm->n_vlib_mains; j++)
609         {
610           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE, 
611                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
612           vec_reset_length (xd->tx_vectors[j]);
613         }
614
615       vec_validate_aligned (xd->rx_vectors, xd->rx_q_used,
616                             CLIB_CACHE_LINE_BYTES);
617       for (j = 0; j< xd->rx_q_used; j++)
618         {
619           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
620                                 CLIB_CACHE_LINE_BYTES);
621           vec_reset_length (xd->rx_vectors[j]);
622         }
623
624       vec_validate_aligned (xd->frames, tm->n_vlib_mains,
625                             CLIB_CACHE_LINE_BYTES);
626
627       /* FIXME Set up one TX-queue per worker thread */
628
629       {
630         f64 now = vlib_time_now(vm);
631         u32 rnd;
632         rnd = (u32) (now * 1e6);
633         rnd = random_u32 (&rnd);
634
635         memcpy (addr+2, &rnd, sizeof(rnd));
636         addr[0] = 2;
637         addr[1] = 0xfe;
638       }
639
640       error = ethernet_register_interface
641         (dm->vnet_main,
642          dpdk_device_class.index,
643          xd->device_index,
644          /* ethernet address */ addr,
645          &xd->vlib_hw_if_index, 
646          dpdk_flag_change);
647
648       if (error)
649         return error;
650
651       sw = vnet_get_hw_sw_interface (dm->vnet_main, xd->vlib_hw_if_index);
652       xd->vlib_sw_if_index = sw->sw_if_index;
653       hi = vnet_get_hw_interface (dm->vnet_main, xd->vlib_hw_if_index);
654     }
655   }
656
657   if (nb_desc > dm->num_mbufs) 
658     clib_warning ("%d mbufs allocated but total rx/tx ring size is %d\n",
659                   dm->num_mbufs, nb_desc);
660
661   /* init next vhost-user if index */
662   dm->next_vu_if_id = 0;
663
664   return 0;
665 }
666
667 /*
668  * Tell the vlib physical memory allocator that we've handled
669  * the initialization. We don't actually do so until
670  * vlib_main(...) callls the dpdk config function.
671  */
672 int vlib_app_physmem_init (vlib_main_t * vm, physmem_main_t * pm,
673                            int physmem_required)
674 {
675   return 1;
676 }
677
678 static clib_error_t *
679 write_sys_fs (char * file_name, char * fmt, ...)
680 {
681   u8 * s;
682   int fd;
683
684   fd = open (file_name, O_WRONLY);
685   if (fd < 0)
686     return clib_error_return_unix (0, "open `%s'", file_name);
687
688   va_list va;
689   va_start (va, fmt);
690   s = va_format (0, fmt, &va);
691   va_end (va);
692   vec_add1 (s, 0); // terminate c string
693
694   if (write (fd, s, vec_len (s)) < 0)
695       return clib_error_return_unix (0, "write '%s' to '%s'", s, file_name);
696
697   vec_free (s);
698   close (fd);
699   return 0;
700 }
701
702 #define VIRTIO_PCI_NAME  "virtio-pci"
703
704 static clib_error_t * dpdk_bind_eth_kernel_drivers (vlib_main_t * vm,
705                                                     char * pci_dev_id,
706                                                     char * kernel_driver)
707 {
708   dpdk_main_t * dm = &dpdk_main;
709   unformat_input_t _in;
710   unformat_input_t * in = &_in;
711   clib_error_t * error = 0;
712   u8 * line = 0, * modcmd = 0, * path = 0;
713   u8 * pci_vid = 0, *pci_did = 0, * devname = 0;
714   char *driver_name = kernel_driver;
715   FILE * fp;
716
717   /* 
718    * Bail out now if we're not running as root.
719    * This allows non-privileged use of the packet generator, etc.
720    */
721   if (geteuid() != 0)
722     return 0;
723
724   /*
725    * Get all ethernet pci device numbers for the device type specified.
726    */
727   modcmd = format (0, "lspci -nDd %s | grep 0200 | "
728                    "awk '{ print $1, $3 }'%c", pci_dev_id, 0);
729   if ((fp = popen ((const char *)modcmd, "r")) == NULL)
730     {
731       error = clib_error_return_unix (0, 
732                                       "Unable to get %s ethernet pci devices.",
733                                       pci_dev_id);
734       goto done;
735     }
736
737   vec_validate (line, BUFSIZ);
738   vec_validate (path, BUFSIZ);
739   while (fgets ((char *)line, BUFSIZ, fp) != NULL)
740     {
741       struct stat st;
742       u8 bind_uio = 1;
743       line[strlen ((char *)line) - 1] = 0; // chomp trailing newline.
744
745       unformat_init_string (in, (char *)line, strlen((char *)line) + 1);
746       unformat(in, "%s %s:%s", &devname, &pci_vid, &pci_did);
747       unformat_free (in);
748
749       /*
750        * Blacklist all ethernet interfaces in the 
751        * linux IP routing tables (route --inet --inet6)
752        */
753       if (strstr ((char *)dm->eth_if_blacklist, (char *)devname))
754         continue;
755
756       /*
757        * If there are any devices whitelisted, then blacklist all devices
758        * which are not explicitly whitelisted.
759        */
760       if (dm->eth_if_whitelist && 
761           !strstr ((char *)dm->eth_if_whitelist, (char *)devname))
762         continue;
763
764 #ifdef NETMAP
765       /*
766        * Optimistically open the device as a netmap device.
767        */
768       if (eth_nm_open((char *)devname))
769         continue;
770 #endif
771
772       _vec_len (path) = 0;
773       path = format (path, "/sys/bus/pci/devices/%s/driver/unbind%c",
774                      devname, 0);
775
776       /*
777        * If the device is bound to a driver...
778        */
779       if (stat ((const char *)path, &st) == 0)
780         {
781           u8 * device_path;
782
783           /*
784            * If the interface is not a virtio...
785            */
786          if (!driver_name || strcmp(driver_name, VIRTIO_PCI_NAME))
787            {
788               /*
789                * If it is already bound to driver, don't unbind/bind it.
790                */
791               device_path = format (0, "/sys/bus/pci/drivers/%s/%s/device%c",
792                                     driver_name, devname, 0);
793               if (stat ((const char *)device_path, &st) == 0)
794                 bind_uio = 0;
795
796               vec_free (device_path);
797            }
798           
799           /*
800            * unbind it from the current driver
801            */
802           if (bind_uio)
803             {
804               _vec_len (path) -= 1;
805               path = format (path, "%c", 0);
806               error = write_sys_fs ((char *)path, "%s", devname);
807               if (error)
808                 goto done;
809             }
810         }
811
812       /*
813        * DAW-FIXME: The following bind/unbind dance is necessary for the dpdk
814        *            virtio poll-mode driver to work.  
815        */
816  
817       if (driver_name && !strcmp(driver_name, VIRTIO_PCI_NAME))
818         {
819           /*
820            * bind interface to the native kernel module
821            */
822           _vec_len (path) = 0;
823           path = format (path, "/sys/bus/pci/drivers/%s/bind%c",
824                          driver_name, 0);
825           error = write_sys_fs ((char *)path, "%s", devname);
826           if (error)
827             goto done;
828
829           /*
830            * unbind interface from the native kernel module
831            */
832           _vec_len (path) -= 5;
833           path = format (path, "unbind%c", 0);
834           error = write_sys_fs ((char *)path, "%s", devname);
835           if (error)
836             goto done;
837         }
838
839       /*
840        * bind the interface to igb_uio
841        */
842       if (bind_uio)
843         {
844           int pci_vendor_id = strtol((char *) pci_vid, NULL, 16);
845           int pci_device_id = strtol((char *) pci_did, NULL, 16);
846
847           /*
848            * Set PCI ID to ".../virtio-pci/new_id" for Intel fortvile adapaters
849            */
850           if (pci_vendor_id == 0x8086 &&
851               (pci_device_id == I40E_DEV_ID_10G_BASE_T ||
852                pci_device_id == I40E_DEV_ID_SFP_XL710 ||
853                pci_device_id == I40E_DEV_ID_QSFP_A ||
854                pci_device_id == I40E_DEV_ID_QSFP_B ||
855                pci_device_id == I40E_DEV_ID_QSFP_C))
856             {
857               _vec_len (path) = 0;
858               path = format (path, "/sys/bus/pci/drivers/%s/new_id%c", driver_name, 0);
859               error = write_sys_fs ((char *) path, "%s %s", pci_vid, pci_did);
860               if (error)
861                 continue;
862             }
863
864           _vec_len (path) = 0;
865           path = format (path, "/sys/bus/pci/drivers/%s/bind%c", driver_name, 0);
866           error = write_sys_fs ((char *) path, "%s", devname);
867           if (error)
868             {
869               error = 0;
870               continue;
871             }
872         }
873     }
874   
875  done:
876   vec_free (line);
877   vec_free (path);
878   vec_free (devname);
879   vec_free (pci_vid);
880   vec_free (pci_did);
881   vec_free (modcmd);
882   pclose (fp);
883   return error;
884 }
885
886 static uword
887 unformat_socket_mem (unformat_input_t * input, va_list * va)
888 {
889   uword ** r = va_arg (* va, uword **);
890   int i = 0;
891   u32 mem;
892
893   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
894     {
895       if (unformat (input, ","))
896         hash_set (*r, i, 1024);
897       else if (unformat (input, "%u,", &mem))
898         hash_set (*r, i, mem);
899       else if (unformat (input, "%u", &mem))
900         hash_set (*r, i, mem);
901       else
902         {
903           unformat_put_input (input);
904           goto done;
905         }
906       i++;
907     }
908
909 done:
910   return 1;
911 }
912
913 static u32
914 get_node_free_hugepages_num (u32 node, u32 page_size)
915 {
916   FILE * fp;
917   u8 * tmp;
918
919   tmp = format (0, "/sys/devices/system/node/node%u/hugepages/hugepages-%ukB/"
920                 "free_hugepages%c", node, page_size, 0);
921   fp = fopen ((char *) tmp, "r");
922   vec_free(tmp);
923
924   if (fp != NULL)
925     {
926       u8 * buffer = 0;
927       u32 pages_avail = 0;
928
929       vec_validate (buffer, 256-1);
930       if (fgets ((char *)buffer, 256, fp))
931         {
932           unformat_input_t in;
933           unformat_init_string (&in, (char *) buffer, strlen ((char *) buffer));
934           unformat(&in, "%u", &pages_avail);
935           unformat_free (&in);
936         }
937       vec_free(buffer);
938       fclose(fp);
939       return pages_avail;
940     }
941
942   return 0;
943 }
944
945 static clib_error_t *
946 dpdk_config (vlib_main_t * vm, unformat_input_t * input)
947 {
948   clib_error_t * error = 0;
949   dpdk_main_t * dm = &dpdk_main;
950   vlib_thread_main_t * tm = vlib_get_thread_main();
951   u8 * s, * tmp = 0;
952   u8 * pci_dev_id = 0;
953   u8 * rte_cmd = 0, * ethname = 0;
954   FILE * rte_fp;
955   u32 log_level;
956   int ret, i;
957   char * fmt;
958 #ifdef NETMAP
959   int rxrings, txrings, rxslots, txslots, txburst;
960   char * nmnam;
961 #endif
962   unformat_input_t _in;
963   unformat_input_t * in = &_in;
964   u8 no_pci = 0;
965   u8 no_huge = 0;
966   u8 huge_dir = 0;
967   u8 file_prefix = 0;
968   u8 * socket_mem = 0;
969
970   // MATT-FIXME: inverted virtio-vhost logic to use virtio by default
971   dm->use_virtio_vhost = 1;
972
973   while (unformat_check_input(input) != UNFORMAT_END_OF_INPUT)
974     {
975       /* Prime the pump */
976       if (unformat (input, "no-hugetlb"))
977         {
978           vec_add1 (dm->eal_init_args, (u8 *) "no-huge");
979           no_huge = 1;
980         }
981
982       else if (unformat (input, "decimal-interface-names"))
983         dm->interface_name_format_decimal = 1;
984
985       else if (unformat (input, "no-multi-seg"))
986         dm->no_multi_seg = 1;
987
988       else if (unformat (input, "dev %s", &pci_dev_id))
989         {
990           if (dm->eth_if_whitelist)
991             {
992               /*
993                * Don't add duplicate device id's.
994                */
995               if (strstr ((char *)dm->eth_if_whitelist, (char *)pci_dev_id))
996                 continue;
997
998               _vec_len (dm->eth_if_whitelist) -= 1; // chomp trailing NULL.
999               dm->eth_if_whitelist = format (dm->eth_if_whitelist, " %s%c",
1000                                              pci_dev_id, 0);
1001             }
1002           else
1003             dm->eth_if_whitelist = format (0, "%s%c", pci_dev_id, 0);
1004         }
1005
1006 #ifdef NETMAP
1007      else if (unformat(input, "netmap %s/%d:%d/%d:%d/%d",
1008                   &nmname, &rxrings, &rxslots, &txrings, &txslots, &txburst)) {
1009         char * rv;
1010         rv = (char *)
1011           eth_nm_args(nmname, rxrings, rxslots, txrings, txslots, txburst);
1012         if (rv) {
1013           error = clib_error_return (0, "%s", rv);
1014           goto done;
1015         }
1016       }else if (unformat(input, "netmap %s", &nmname)) {
1017         char * rv;
1018         rv = (char *)
1019           eth_nm_args(nmname, 0, 0, 0, 0, 0);
1020         if (rv) {
1021           error = clib_error_return (0, "%s", rv);
1022           goto done;
1023         }
1024       }
1025 #endif
1026
1027       else if (unformat (input, "num-mbufs %d", &dm->num_mbufs))
1028         ;
1029       else if (unformat (input, "kni %d", &dm->num_kni))
1030         ;
1031       else if (unformat (input, "uio-driver %s", &dm->uio_driver_name))
1032         ;
1033       else if (unformat (input, "vhost-user-coalesce-frames %d", &dm->vhost_coalesce_frames))
1034         ;
1035       else if (unformat (input, "vhost-user-coalesce-time %f", &dm->vhost_coalesce_time))
1036         ;
1037       else if (unformat (input, "enable-vhost-user"))
1038         dm->use_virtio_vhost = 0;
1039       else if (unformat (input, "rss %d", &dm->use_rss))
1040         ;
1041
1042 #define _(a)                                    \
1043       else if (unformat(input, #a))             \
1044         {                                       \
1045           if (!strncmp(#a, "no-pci", 6))        \
1046             no_pci = 1;                         \
1047           tmp = format (0, "--%s%c", #a, 0);    \
1048           vec_add1 (dm->eal_init_args, tmp);    \
1049         }
1050       foreach_eal_double_hyphen_predicate_arg
1051 #undef _
1052
1053 #define _(a)                                          \
1054         else if (unformat(input, #a " %s", &s))       \
1055           {                                           \
1056             if (!strncmp(#a, "huge-dir", 8))          \
1057               huge_dir = 1;                           \
1058             else if (!strncmp(#a, "file-prefix", 11)) \
1059               file_prefix = 1;                        \
1060             else if (!strncmp(#a, "socket-mem", 10))  \
1061               socket_mem = vec_dup (s);               \
1062             tmp = format (0, "--%s%c", #a, 0);        \
1063             vec_add1 (dm->eal_init_args, tmp);        \
1064             vec_add1 (s, 0);                          \
1065             vec_add1 (dm->eal_init_args, s);          \
1066           }
1067         foreach_eal_double_hyphen_arg
1068 #undef _
1069
1070 #define _(a,b)                                          \
1071           else if (unformat(input, #a " %s", &s))       \
1072             {                                           \
1073               tmp = format (0, "-%s%c", #b, 0);         \
1074               vec_add1 (dm->eal_init_args, tmp);        \
1075               vec_add1 (s, 0);                          \
1076               vec_add1 (dm->eal_init_args, s);          \
1077             }
1078           foreach_eal_single_hyphen_arg
1079 #undef _
1080
1081 #define _(a,b)                                          \
1082             else if (unformat(input, #a " %s", &s))     \
1083               {                                         \
1084                 tmp = format (0, "-%s%c", #b, 0);       \
1085                 vec_add1 (dm->eal_init_args, tmp);      \
1086                 vec_add1 (s, 0);                        \
1087                 vec_add1 (dm->eal_init_args, s);        \
1088                 dm->a##_set_manually = 1;               \
1089               }
1090             foreach_eal_single_hyphen_mandatory_arg
1091 #undef _
1092
1093           else if (unformat(input, "default"))
1094             ;
1095
1096           else
1097             {
1098               error = clib_error_return (0, "unknown input `%U'",
1099                                          format_unformat_error, input);
1100               goto done;
1101             }
1102     }
1103
1104   if (!dm->uio_driver_name)
1105     dm->uio_driver_name = format (0, "igb_uio");
1106
1107   /*
1108    * Use 1G huge pages if available.
1109    */
1110   if (!no_huge && !huge_dir)
1111     {
1112       uword * mem_by_socket = hash_create (0, sizeof (uword));
1113       uword c;
1114       u8 use_1g = 1;
1115       u8 use_2m = 1;
1116       int rv;
1117
1118       umount(DEFAULT_HUGE_DIR);
1119
1120       /* Process "socket-mem" parameter value */
1121       if (vec_len (socket_mem))
1122         {
1123           unformat_input_t in;
1124           unformat_init_vector(&in, socket_mem);
1125           unformat(&in, "%U", unformat_socket_mem, &mem_by_socket);
1126           unformat_free(&in);
1127         }
1128       else
1129         use_1g = 0;
1130
1131       /* check if available enough 1GB pages for each socket */
1132       clib_bitmap_foreach (c, tm->cpu_socket_bitmap, ({
1133          uword * p = hash_get (mem_by_socket, c);
1134          if (p)
1135            {
1136              u32 mem = p[0];
1137              if (mem)
1138                {
1139                  u32 pages_num_1g = mem / 1024;
1140                  u32 pages_num_2m = mem / 2;
1141                  u32 pages_avail;
1142
1143                  pages_avail = get_node_free_hugepages_num(c, 1048576);
1144                  if (!(pages_avail >= pages_num_1g))
1145                    use_1g = 0;
1146
1147                  pages_avail = get_node_free_hugepages_num(c, 2048);
1148                  if (!(pages_avail >= pages_num_2m))
1149                    use_2m = 0;
1150               }
1151            }
1152       }));
1153
1154       hash_free (mem_by_socket);
1155
1156       rv = mkdir(VPP_RUN_DIR, 0755);
1157       if (rv && errno != EEXIST)
1158         {
1159           error = clib_error_return (0, "mkdir '%s' failed errno %d",
1160                                      VPP_RUN_DIR, errno);
1161           goto done;
1162         }
1163
1164       rv = mkdir(DEFAULT_HUGE_DIR, 0755);
1165       if (rv && errno != EEXIST)
1166         {
1167           error = clib_error_return (0, "mkdir '%s' failed errno %d",
1168                                      DEFAULT_HUGE_DIR, errno);
1169           goto done;
1170         }
1171
1172       if (use_1g)
1173         {
1174           rv = mount("none", DEFAULT_HUGE_DIR, "hugetlbfs", 0, "pagesize=1G");
1175         }
1176       else if (use_2m)
1177         {
1178           rv = mount("none", DEFAULT_HUGE_DIR, "hugetlbfs", 0, NULL);
1179         }
1180       else
1181         {
1182           return clib_error_return (0, "not enough free huge pages");
1183         }
1184
1185       if (rv)
1186         {
1187           error = clib_error_return (0, "mount failed %d", errno);
1188           goto done;
1189         }
1190
1191       tmp = format (0, "--huge-dir%c", 0);
1192       vec_add1 (dm->eal_init_args, tmp);
1193       tmp = format (0, "%s%c", DEFAULT_HUGE_DIR, 0);
1194       vec_add1 (dm->eal_init_args, tmp);
1195       if (!file_prefix)
1196         {
1197           tmp = format (0, "--file-prefix%c", 0);
1198           vec_add1 (dm->eal_init_args, tmp);
1199           tmp = format (0, "vpp%c", 0);
1200           vec_add1 (dm->eal_init_args, tmp);
1201         }
1202     }
1203
1204   /*
1205    * Blacklist all ethernet interfaces in the linux IP routing tables.
1206    */
1207   dm->eth_if_blacklist = format (0, "%c", 0);
1208   rte_cmd = format (0, "route --inet --inet6 -n|awk '{print $7}'|sort -u|"
1209                     "egrep $(echo $(ls -1d /sys/class/net/*/device|"
1210                     "cut -d/ -f5)|sed -s 's/ /|/g')%c", 0);
1211   if ((rte_fp = popen ((const char *)rte_cmd, "r")) == NULL)
1212     {
1213       error = clib_error_return_unix (0, "Unable to find blacklist ethernet"
1214                                       " interface(s) in linux routing tables.");
1215       goto rte_cmd_err;
1216
1217     }
1218
1219   vec_validate (ethname, BUFSIZ);
1220   while (fgets ((char *)ethname, BUFSIZ, rte_fp) != NULL)
1221     {
1222       FILE *rlnk_fp;
1223       u8 * rlnk_cmd = 0, * devname = 0;
1224
1225       ethname[strlen ((char *)ethname) - 1] = 0; // chomp trailing newline.
1226
1227       rlnk_cmd = format (0, "readlink /sys/class/net/%s%c",
1228                          ethname, 0);
1229
1230       if ((rlnk_fp = popen ((const char *)rlnk_cmd, "r")) == NULL)
1231         {
1232           error = clib_error_return_unix (0, "Unable to read %s link.",
1233                                           ethname);
1234           goto rlnk_cmd_err;
1235         }
1236
1237       vec_validate (devname, BUFSIZ);
1238       while (fgets ((char *)devname, BUFSIZ, rlnk_fp) != NULL)
1239         {
1240           char * pci_id = 0;
1241           
1242           /*
1243            * Extract the device PCI ID name from the link. It is the first
1244            * PCI ID searching backwards from the end of the link pathname.
1245            * For example:
1246            *     readlink /sys/class/net/eth0
1247            *     ../../devices/pci0000:00/0000:00:0a.0/virtio4/net/eth0
1248            */
1249           for (pci_id = (char *)((devname + strlen((char *)devname)));
1250                ((u8 *)pci_id > devname) && *pci_id != '.'; pci_id--)
1251             ;
1252
1253           /*
1254            * Verify that the field found is a valid PCI ID.
1255            */
1256           if ((*(pci_id - 1) == '.') || ((u8 *)(pci_id - 11) < devname) || 
1257               (*(pci_id - 11) != '/') || (*(pci_id - 3) != ':') ||
1258               (*(pci_id - 6) != ':'))
1259             {
1260               devname[strlen ((char *)devname) - 1] = 0; // chomp trailing newline.
1261               clib_warning ("Unable to extract %s PCI ID (0x%llx \"%s\") "
1262                             "from 0x%llx \"%s\"", ethname, pci_id, pci_id,
1263                             devname, devname);
1264               continue;
1265             }
1266
1267           pci_id[2] = 0;
1268           pci_id -= 10;
1269
1270           /* Don't blacklist any interfaces which have been whitelisted.
1271            */
1272           if (dm->eth_if_whitelist &&
1273               strstr ((char *)dm->eth_if_whitelist, (char *)pci_id))
1274               continue;
1275
1276           _vec_len (dm->eth_if_blacklist) -= 1; // chomp trailing NULL.
1277           dm->eth_if_blacklist = format (dm->eth_if_blacklist, " %s%c",
1278                                          pci_id, 0);
1279         }
1280   
1281     rlnk_cmd_err:
1282       pclose (rlnk_fp);
1283       vec_free (rlnk_cmd);
1284       vec_free (devname);
1285     }
1286
1287  rte_cmd_err:
1288   pclose (rte_fp);
1289   vec_free (rte_cmd);
1290   vec_free (ethname);
1291
1292   if (error)
1293     return error;
1294
1295   /* I'll bet that -c and -n must be the first and second args... */
1296   if (!dm->coremask_set_manually)
1297     {
1298       vlib_thread_registration_t * tr;
1299       uword coremask;
1300       int i;
1301
1302       /* main thread core */
1303       coremask = 1 << tm->main_lcore;
1304
1305       for (i = 0; i < vec_len (tm->registrations); i++)
1306         {
1307           tr = tm->registrations[i];
1308           if (clib_bitmap_is_zero(tr->coremask))
1309             continue;
1310           coremask |= tr->coremask[0];
1311         }
1312
1313       vec_insert (dm->eal_init_args, 2, 1);
1314       dm->eal_init_args[1] = (u8 *) "-c";
1315       tmp = format (0, "%x%c", coremask, 0);
1316       dm->eal_init_args[2] = tmp;
1317     }
1318
1319   if (!dm->nchannels_set_manually)
1320     {
1321       vec_insert (dm->eal_init_args, 2, 3);
1322       dm->eal_init_args[3] = (u8 *) "-n";
1323       tmp = format (0, "%d", dm->nchannels);
1324       dm->eal_init_args[4] = tmp;
1325     }
1326
1327   /*
1328    * If there are whitelisted devices,
1329    * add the whitelist option & device list to the dpdk arg list...
1330    */
1331   if (dm->eth_if_whitelist)
1332     {
1333       unformat_init_string (in, (char *)dm->eth_if_whitelist,
1334                             vec_len(dm->eth_if_whitelist) - 1);
1335       fmt = "-w%c";
1336     }
1337
1338   /*
1339    * Otherwise add the blacklisted devices to the dpdk arg list.
1340    */
1341   else
1342     {
1343       unformat_init_string (in, (char *)dm->eth_if_blacklist,
1344                             vec_len(dm->eth_if_blacklist) - 1);
1345       fmt = "-b%c";
1346     }
1347
1348   while (unformat_check_input (in) != UNFORMAT_END_OF_INPUT)
1349     {
1350       tmp = format (0, fmt, 0);
1351       vec_add1 (dm->eal_init_args, tmp);
1352       unformat (in, "%s", &pci_dev_id);
1353       vec_add1 (dm->eal_init_args, pci_dev_id);
1354     }
1355
1356   if (no_pci == 0)
1357     {
1358       /*
1359        * Bind Virtio pci devices to the igb_uio kernel driver.
1360        */
1361       error = dpdk_bind_eth_kernel_drivers (vm, "1af4:1000", VIRTIO_PCI_NAME);
1362       if (error)
1363         return error;
1364
1365       /*
1366        * Bind vmxnet3 pci devices to the igb_uio kernel driver.
1367        */
1368       error = dpdk_bind_eth_kernel_drivers (vm, "15ad:07b0",
1369                                             (char *) dm->uio_driver_name);
1370       if (error)
1371         return error;
1372
1373       /*
1374        * Bind Intel ethernet pci devices to igb_uio kernel driver.
1375        */
1376       error = dpdk_bind_eth_kernel_drivers (vm, "8086:",
1377                                             (char *) dm->uio_driver_name);
1378       /*
1379        * Bind Cisco VIC ethernet pci devices to igb_uio kernel driver.
1380        */
1381       error = dpdk_bind_eth_kernel_drivers (vm, "1137:0043",
1382                                             (char *) dm->uio_driver_name);
1383     }
1384
1385   /* set master-lcore */
1386   tmp = format (0, "--master-lcore%c", 0);
1387   vec_add1 (dm->eal_init_args, tmp);
1388   tmp = format (0, "%u%c", tm->main_lcore, 0);
1389   vec_add1 (dm->eal_init_args, tmp);
1390
1391   /* NULL terminate the "argv" vector, in case of stupidity */
1392   vec_add1 (dm->eal_init_args, 0);
1393   _vec_len(dm->eal_init_args) -= 1;
1394
1395   /* Set up DPDK eal and packet mbuf pool early. */
1396
1397   log_level = (CLIB_DEBUG > 0) ? RTE_LOG_DEBUG : RTE_LOG_NOTICE;
1398
1399   rte_set_log_level (log_level);
1400
1401   vm = dm->vlib_main;
1402
1403   ret = rte_eal_init(vec_len(dm->eal_init_args), (char **) dm->eal_init_args);
1404
1405   /* lazy umount hugepages */
1406   umount2(DEFAULT_HUGE_DIR, MNT_DETACH);
1407
1408   if (ret < 0)
1409     return clib_error_return (0, "rte_eal_init returned %d", ret);
1410
1411   /* main thread 1st */
1412   error = vlib_buffer_pool_create(vm, dm->num_mbufs, MBUF_SIZE, rte_socket_id());
1413   if (error)
1414     return error;
1415
1416   for (i = 0; i < RTE_MAX_LCORE; i++)
1417     {
1418       error = vlib_buffer_pool_create(vm, dm->num_mbufs, MBUF_SIZE,
1419                                       rte_lcore_to_socket_id(i));
1420       if (error)
1421         return error;
1422     }
1423
1424   if (dm->use_rss)
1425     {
1426       vlib_node_runtime_t * rt = vlib_node_get_runtime (vm, dpdk_input_node.index);
1427       rt->function = dpdk_input_rss;
1428     }
1429  done:
1430   return error;
1431 }
1432
1433 VLIB_CONFIG_FUNCTION (dpdk_config, "dpdk");
1434
1435 void dpdk_update_link_state (dpdk_device_t * xd, f64 now)
1436 {
1437     vnet_main_t * vnm = vnet_get_main();
1438     struct rte_eth_link prev_link = xd->link;
1439     u32 hw_flags =  0;
1440     u8 hw_flags_chg = 0;
1441
1442     /* only update link state for PMD interfaces */
1443     if (xd->dev_type != VNET_DPDK_DEV_ETH)
1444       return;
1445
1446     xd->time_last_link_update = now ? now : xd->time_last_link_update;
1447     memset(&xd->link, 0, sizeof(xd->link));
1448     rte_eth_link_get_nowait (xd->device_index, &xd->link);
1449
1450     if (LINK_STATE_ELOGS)
1451       {
1452         vlib_main_t * vm = vlib_get_main();
1453         ELOG_TYPE_DECLARE(e) = {
1454           .format = 
1455           "update-link-state: sw_if_index %d, admin_up %d,"
1456           "old link_state %d new link_state %d",
1457           .format_args = "i4i1i1i1",
1458         };
1459
1460         struct { u32 sw_if_index; u8 admin_up; 
1461           u8 old_link_state; u8 new_link_state;} *ed;
1462         ed = ELOG_DATA (&vm->elog_main, e);
1463         ed->sw_if_index = xd->vlib_sw_if_index;
1464         ed->admin_up = xd->admin_up;
1465         ed->old_link_state = (u8)
1466           vnet_hw_interface_is_link_up (vnm, xd->vlib_hw_if_index);
1467         ed->new_link_state = (u8) xd->link.link_status;
1468       }
1469
1470     if ((xd->admin_up == 1) && 
1471         ((xd->link.link_status != 0) ^ 
1472          vnet_hw_interface_is_link_up (vnm, xd->vlib_hw_if_index)))
1473       {
1474         hw_flags_chg = 1;
1475         hw_flags |= (xd->link.link_status ? 
1476                      VNET_HW_INTERFACE_FLAG_LINK_UP: 0);
1477       }
1478
1479     if (hw_flags_chg || (xd->link.link_duplex != prev_link.link_duplex))
1480       {
1481         hw_flags_chg = 1;
1482         switch (xd->link.link_duplex)
1483           {
1484           case ETH_LINK_HALF_DUPLEX:
1485             hw_flags |= VNET_HW_INTERFACE_FLAG_HALF_DUPLEX;
1486             break;
1487           case ETH_LINK_FULL_DUPLEX:
1488             hw_flags |= VNET_HW_INTERFACE_FLAG_FULL_DUPLEX;
1489             break;
1490           default:
1491             break;
1492           }
1493       }
1494     if (hw_flags_chg || (xd->link.link_speed != prev_link.link_speed))
1495       {
1496         hw_flags_chg = 1;
1497         switch (xd->link.link_speed)
1498           {
1499           case ETH_LINK_SPEED_10:
1500             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_10M;
1501             break;
1502           case ETH_LINK_SPEED_100:
1503             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_100M;
1504             break;
1505           case ETH_LINK_SPEED_1000:
1506             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_1G;
1507             break;
1508           case ETH_LINK_SPEED_10000:
1509             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_10G;
1510             break;
1511           case ETH_LINK_SPEED_40G:
1512             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_40G;
1513             break;
1514     case 0:
1515       break;
1516     default:
1517       clib_warning("unknown link speed %d", xd->link.link_speed);
1518             break;
1519           }
1520       }
1521     if (hw_flags_chg)
1522       {
1523         if (LINK_STATE_ELOGS)
1524           {
1525             vlib_main_t * vm = vlib_get_main();
1526
1527             ELOG_TYPE_DECLARE(e) = {
1528               .format = "update-link-state: sw_if_index %d, new flags %d",
1529               .format_args = "i4i4",
1530             };
1531
1532             struct { u32 sw_if_index; u32 flags; } *ed;
1533             ed = ELOG_DATA (&vm->elog_main, e);
1534             ed->sw_if_index = xd->vlib_sw_if_index;
1535             ed->flags = hw_flags;
1536           }
1537         vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index, hw_flags);
1538       }
1539 }
1540
1541 static uword
1542 dpdk_process (vlib_main_t * vm,
1543               vlib_node_runtime_t * rt,
1544               vlib_frame_t * f)
1545 {
1546   clib_error_t * error;
1547   dpdk_main_t * dm = &dpdk_main;
1548   dpdk_device_t * xd;
1549   vlib_thread_main_t * tm = vlib_get_thread_main();
1550   void *vu_state;
1551   int i;
1552
1553   error = dpdk_lib_init (dm);
1554
1555   /* 
1556    * Turn on the input node if we found some devices to drive
1557    * and we're not running worker threads or i/o threads
1558    */
1559
1560   if (error == 0 && vec_len(dm->devices) > 0)
1561     {
1562         if (tm->n_vlib_mains == 1)
1563           vlib_node_set_state (vm, dpdk_input_node.index,
1564                                VLIB_NODE_STATE_POLLING);
1565         else if (tm->main_thread_is_io_node)
1566           vlib_node_set_state (vm, dpdk_io_input_node.index,
1567                                VLIB_NODE_STATE_POLLING);
1568         else if (!dm->have_io_threads)
1569           for (i=0; i < tm->n_vlib_mains; i++)
1570             if (vec_len(dm->devices_by_cpu[i]) > 0)
1571               vlib_node_set_state (vlib_mains[i], dpdk_input_node.index,
1572                                    VLIB_NODE_STATE_POLLING);
1573     }
1574
1575   if (error)
1576     clib_error_report (error);
1577
1578   dpdk_vhost_user_process_init(&vu_state);
1579
1580   dm->io_thread_release = 1;
1581
1582   f64 now = vlib_time_now (vm);
1583   vec_foreach (xd, dm->devices)
1584     {
1585       dpdk_update_link_state (xd, now);
1586     }
1587
1588   while (1)
1589     {
1590       vlib_process_wait_for_event_or_clock (vm, 5.0);
1591
1592       if (dpdk_get_admin_up_down_in_progress())
1593           /* skip the poll if an admin up down is in progress (on any interface) */
1594           continue;
1595
1596       vec_foreach (xd, dm->devices)
1597         {
1598           f64 now = vlib_time_now (vm);
1599           if ((now - xd->time_last_stats_update) >= DPDK_STATS_POLL_INTERVAL)
1600             dpdk_update_counters (xd, now);
1601           if ((now - xd->time_last_link_update) >= DPDK_LINK_POLL_INTERVAL)
1602             dpdk_update_link_state (xd, now);
1603
1604       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER)
1605           if (dpdk_vhost_user_process_if(vm, xd, vu_state) != 0)
1606               continue;
1607         }
1608     }
1609
1610   dpdk_vhost_user_process_cleanup(vu_state);
1611
1612   return 0; 
1613 }
1614
1615 VLIB_REGISTER_NODE (dpdk_process_node,static) = {
1616     .function = dpdk_process,
1617     .type = VLIB_NODE_TYPE_PROCESS,
1618     .name = "dpdk-process",
1619     .process_log2_n_stack_bytes = 17,
1620 };
1621
1622 clib_error_t *
1623 dpdk_init (vlib_main_t * vm)
1624 {
1625   dpdk_main_t * dm = &dpdk_main;
1626   vlib_node_t * ei;
1627   clib_error_t * error = 0;
1628   vlib_thread_main_t * tm = vlib_get_thread_main();
1629
1630   /* verify that structs are cacheline aligned */
1631   ASSERT(offsetof(dpdk_device_t, cacheline0) == 0);
1632   ASSERT(offsetof(dpdk_device_t, cacheline1) == CLIB_CACHE_LINE_BYTES);
1633   ASSERT(offsetof(dpdk_worker_t, cacheline0) == 0);
1634   ASSERT(offsetof(frame_queue_trace_t, cacheline0) == 0);
1635
1636   /* Add references to DPDK Driver Constructor functions to get the dynamic
1637    * loader to pull in the driver library & run the constructors.
1638    */
1639 #define _(d)                                          \
1640 do {                                                  \
1641   void devinitfn_ ##d(void);                          \
1642   __attribute__((unused)) void (* volatile pf)(void); \
1643   pf = devinitfn_ ##d;                                \
1644 } while(0);
1645
1646 #ifdef RTE_LIBRTE_EM_PMD
1647   _(em_pmd_drv)
1648 #endif
1649
1650 #ifdef RTE_LIBRTE_IGB_PMD
1651   _(pmd_igb_drv)
1652 #endif
1653
1654 #ifdef RTE_LIBRTE_IXGBE_PMD
1655   _(rte_ixgbe_driver)
1656 #endif
1657
1658 #ifdef RTE_LIBRTE_I40E_PMD
1659   _(rte_i40e_driver)
1660   _(rte_i40evf_driver)
1661 #endif
1662
1663 #ifdef RTE_LIBRTE_FM10K_PMD
1664   _(rte_fm10k_driver)
1665 #endif
1666
1667 #ifdef RTE_LIBRTE_VIRTIO_PMD
1668   _(rte_virtio_driver)
1669 #endif
1670
1671 #ifdef RTE_LIBRTE_VMXNET3_PMD
1672   _(rte_vmxnet3_driver)
1673 #endif
1674
1675 #ifdef RTE_LIBRTE_VICE_PMD
1676   _(rte_vice_driver)
1677 #endif
1678
1679 #ifdef RTE_LIBRTE_ENIC_PMD
1680   _(rte_enic_driver)
1681 #endif
1682
1683 #ifdef RTE_LIBRTE_PMD_AF_PACKET
1684   _(pmd_af_packet_drv)
1685 #endif
1686
1687 #undef _
1688
1689   dm->vlib_main = vm;
1690   dm->vnet_main = vnet_get_main();
1691
1692   ei = vlib_get_node_by_name (vm, (u8 *) "ethernet-input");
1693   if (ei == 0)
1694       return clib_error_return (0, "ethernet-input node AWOL");
1695
1696   dm->ethernet_input_node_index = ei->index;
1697
1698   dm->nchannels = 4;
1699   dm->num_mbufs = dm->num_mbufs ? dm->num_mbufs : NB_MBUF;
1700   vec_add1 (dm->eal_init_args, (u8 *) "vnet");
1701
1702   dm->dpdk_device_by_kni_port_id = hash_create (0, sizeof (uword));
1703   dm->vu_sw_if_index_by_listener_fd = hash_create (0, sizeof (uword));
1704   dm->vu_sw_if_index_by_sock_fd = hash_create (0, sizeof (uword));
1705
1706   /* $$$ use n_thread_stacks since it's known-good at this point */
1707   vec_validate (dm->recycle, tm->n_thread_stacks - 1);
1708
1709   /* initialize EFD (early fast discard) default settings */
1710   dm->efd.enabled = DPDK_EFD_DISABLED;
1711   dm->efd.queue_hi_thresh = ((DPDK_EFD_DEFAULT_DEVICE_QUEUE_HI_THRESH_PCT *
1712                               DPDK_NB_RX_DESC_10GE)/100);
1713   dm->efd.consec_full_frames_hi_thresh =
1714       DPDK_EFD_DEFAULT_CONSEC_FULL_FRAMES_HI_THRESH;
1715
1716   /* vhost-user coalescence frames defaults */
1717   dm->vhost_coalesce_frames = 32;
1718   dm->vhost_coalesce_time = 1e-3;
1719
1720   /* init CLI */
1721   if ((error = vlib_call_init_function (vm, dpdk_cli_init)))
1722     return error;
1723
1724   return error;
1725 }
1726
1727 VLIB_INIT_FUNCTION (dpdk_init);
1728