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