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