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