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