Fix duplicate free
[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 #include <vppinfra/bitmap.h>
20
21 #include <vnet/ethernet/ethernet.h>
22 #include <vnet/devices/dpdk/dpdk.h>
23 #include <vlib/unix/physmem.h>
24 #include <vlib/pci/pci.h>
25 #include <vlib/unix/pci.h>
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31 #include <sys/mount.h>
32 #include <string.h>
33 #include <fcntl.h>
34
35 #include "dpdk_priv.h"
36
37 dpdk_main_t dpdk_main;
38
39 /* force linker to link functions used by vlib and declared weak */
40 void *vlib_weakly_linked_functions[] = {
41   &rte_pktmbuf_init,
42   &rte_pktmbuf_pool_init,
43 };
44
45 #define LINK_STATE_ELOGS        0
46
47 #define DEFAULT_HUGE_DIR "/run/vpp/hugepages"
48 #define VPP_RUN_DIR "/run/vpp"
49
50 /* Port configuration, mildly modified Intel app values */
51
52 static struct rte_eth_conf port_conf_template = {
53   .rxmode = {
54     .split_hdr_size = 0,
55     .header_split   = 0, /**< Header Split disabled */
56     .hw_ip_checksum = 0, /**< IP checksum offload disabled */
57     .hw_vlan_filter = 0, /**< VLAN filtering disabled */
58     .hw_strip_crc   = 1, /**< CRC stripped by hardware */
59   },
60   .txmode = {
61     .mq_mode = ETH_MQ_TX_NONE,
62   },
63 };
64
65 clib_error_t *
66 dpdk_port_setup (dpdk_main_t * dm, dpdk_device_t * xd)
67 {
68   vlib_main_t * vm = vlib_get_main();
69   vlib_buffer_main_t * bm = vm->buffer_main;
70   int rv;
71   int j;
72
73   ASSERT(os_get_cpu_number() == 0);
74
75   if (xd->admin_up) {
76     vnet_hw_interface_set_flags (dm->vnet_main, xd->vlib_hw_if_index, 0);
77     rte_eth_dev_stop (xd->device_index);
78   }
79
80   rv = rte_eth_dev_configure (xd->device_index, xd->rx_q_used,
81                               xd->tx_q_used, &xd->port_conf);
82
83   if (rv < 0)
84     return clib_error_return (0, "rte_eth_dev_configure[%d]: err %d",
85                               xd->device_index, rv);
86
87   /* Set up one TX-queue per worker thread */
88   for (j = 0; j < xd->tx_q_used; j++)
89     {
90       rv = rte_eth_tx_queue_setup(xd->device_index, j, xd->nb_tx_desc,
91                                  xd->cpu_socket, &xd->tx_conf);
92
93       /* retry with any other CPU socket */
94       if (rv < 0)
95         rv = rte_eth_tx_queue_setup(xd->device_index, j, xd->nb_tx_desc,
96                                    SOCKET_ID_ANY, &xd->tx_conf);
97       if (rv < 0)
98         break;
99     }
100
101     if (rv < 0)
102       return clib_error_return (0, "rte_eth_tx_queue_setup[%d]: err %d",
103                                 xd->device_index, rv);
104
105   for (j = 0; j < xd->rx_q_used; j++)
106     {
107
108       rv = rte_eth_rx_queue_setup(xd->device_index, j, xd->nb_rx_desc,
109                                   xd->cpu_socket, 0,
110                                   bm->pktmbuf_pools[xd->cpu_socket_id_by_queue[j]]);
111
112       /* retry with any other CPU socket */
113       if (rv < 0)
114         rv = rte_eth_rx_queue_setup(xd->device_index, j, xd->nb_rx_desc,
115                                     SOCKET_ID_ANY, 0,
116                                     bm->pktmbuf_pools[xd->cpu_socket_id_by_queue[j]]);
117       if (rv < 0)
118         return clib_error_return (0, "rte_eth_rx_queue_setup[%d]: err %d",
119                                   xd->device_index, rv);
120     }
121
122   if (xd->admin_up) {
123     rte_eth_dev_start (xd->device_index);
124   }
125   return 0;
126 }
127
128 static u32 dpdk_flag_change (vnet_main_t * vnm, 
129                              vnet_hw_interface_t * hi,
130                              u32 flags)
131 {
132   dpdk_main_t * dm = &dpdk_main;
133   dpdk_device_t * xd = vec_elt_at_index (dm->devices, hi->dev_instance);
134   u32 old = 0;
135
136   if (ETHERNET_INTERFACE_FLAG_CONFIG_PROMISC(flags))
137     {
138       old = xd->promisc;
139       xd->promisc = flags & ETHERNET_INTERFACE_FLAG_ACCEPT_ALL;
140       
141       if (xd->admin_up)
142         {
143           if (xd->promisc)
144             rte_eth_promiscuous_enable(xd->device_index);
145           else
146             rte_eth_promiscuous_disable(xd->device_index);
147         }
148     }
149   else if (ETHERNET_INTERFACE_FLAG_CONFIG_MTU(flags))
150     {
151       /*
152        * DAW-FIXME: The Cisco VIC firmware does not provide an api for a
153        *            driver to dynamically change the mtu.  If/when the 
154        *            VIC firmware gets fixed, then this should be removed.
155        */
156       if (xd->pmd == VNET_DPDK_PMD_VICE ||
157           xd->pmd == VNET_DPDK_PMD_ENIC)
158         {
159           struct rte_eth_dev_info dev_info;
160
161           /*
162            * Restore mtu to what has been set by CIMC in the firmware cfg.
163            */
164           rte_eth_dev_info_get(xd->device_index, &dev_info);
165           hi->max_packet_bytes = dev_info.max_rx_pktlen;
166
167           vlib_cli_output (vlib_get_main(), 
168                            "Cisco VIC mtu can only be changed "
169                            "using CIMC then rebooting the server!");
170         }
171       else
172         {
173           int rv;
174       
175           xd->port_conf.rxmode.max_rx_pkt_len = hi->max_packet_bytes;
176
177           if (xd->admin_up)
178             rte_eth_dev_stop (xd->device_index);
179
180     rv = rte_eth_dev_configure
181       (xd->device_index,
182        xd->rx_q_used,
183        xd->tx_q_used,
184        &xd->port_conf);
185
186           if (rv < 0)
187             vlib_cli_output (vlib_get_main(), 
188                              "rte_eth_dev_configure[%d]: err %d",
189                              xd->device_index, rv);
190
191           rte_eth_dev_set_mtu(xd->device_index, hi->max_packet_bytes);
192
193           if (xd->admin_up)
194             rte_eth_dev_start (xd->device_index);
195         }
196     }
197   return old;
198 }
199
200 #ifdef NETMAP
201 extern int rte_netmap_probe(void);
202 #endif
203
204 void
205 dpdk_device_lock_init(dpdk_device_t * xd)
206 {
207   int q;
208   vec_validate(xd->lockp, xd->tx_q_used - 1);
209   for (q = 0; q < xd->tx_q_used; q++)
210     {
211       xd->lockp[q] = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
212                                              CLIB_CACHE_LINE_BYTES);
213       memset ((void *) xd->lockp[q], 0, CLIB_CACHE_LINE_BYTES);
214   }
215   xd->need_txlock = 1;
216 }
217
218 void
219 dpdk_device_lock_free(dpdk_device_t * xd)
220 {
221   int q;
222
223   for (q = 0; q < vec_len(xd->lockp); q++)
224     clib_mem_free((void *) xd->lockp[q]);
225   vec_free(xd->lockp);
226   xd->lockp = 0;
227   xd->need_txlock = 0;
228 }
229
230 static clib_error_t *
231 dpdk_lib_init (dpdk_main_t * dm)
232 {
233   u32 nports;
234   u32 nb_desc = 0;
235   int i;
236   clib_error_t * error;
237   vlib_main_t * vm = vlib_get_main();
238   vlib_thread_main_t * tm = vlib_get_thread_main();
239   vnet_sw_interface_t * sw;
240   vnet_hw_interface_t * hi;
241   dpdk_device_t * xd;
242   vlib_thread_registration_t * tr;
243   uword * p;
244
245   u32 next_cpu = 0;
246   u8 af_packet_port_id = 0;
247
248   dm->input_cpu_first_index = 0;
249   dm->input_cpu_count = 1;
250
251   /* find out which cpus will be used for input */
252   p = hash_get_mem (tm->thread_registrations_by_name, "io");
253   tr = p ? (vlib_thread_registration_t *) p[0] : 0;
254
255   if (!tr || tr->count == 0)
256     {
257       /* no io threads, workers doing input */
258       p = hash_get_mem (tm->thread_registrations_by_name, "workers");
259       tr = p ? (vlib_thread_registration_t *) p[0] : 0;
260     }
261   else
262     {
263       dm->have_io_threads = 1;
264     }
265
266   if (tr && tr->count > 0)
267     {
268       dm->input_cpu_first_index = tr->first_index;
269       dm->input_cpu_count = tr->count;
270     }
271
272   vec_validate_aligned (dm->devices_by_cpu, tm->n_vlib_mains - 1,
273                         CLIB_CACHE_LINE_BYTES);
274
275   vec_validate_aligned (dm->workers, tm->n_vlib_mains - 1,
276                         CLIB_CACHE_LINE_BYTES);
277
278 #ifdef NETMAP
279   if(rte_netmap_probe() < 0)
280     return clib_error_return (0, "rte netmap probe failed");
281 #endif
282
283   nports = rte_eth_dev_count();
284   if (nports < 1) 
285     {
286       clib_warning ("DPDK drivers found no ports...");
287     }
288
289   if (CLIB_DEBUG > 0)
290     clib_warning ("DPDK drivers found %d ports...", nports);
291
292   /* 
293    * All buffers are all allocated from the same rte_mempool.
294    * Thus they all have the same number of data bytes.
295    */
296   dm->vlib_buffer_free_list_index = 
297       vlib_buffer_get_or_create_free_list (
298           vm, VLIB_BUFFER_DEFAULT_FREE_LIST_BYTES, "dpdk rx");
299
300   for (i = 0; i < nports; i++)
301     {
302       u8 addr[6];
303       int j;
304       struct rte_eth_dev_info dev_info;
305       clib_error_t * rv;
306       struct rte_eth_link l;
307
308       /* Create vnet interface */
309       vec_add2_aligned (dm->devices, xd, 1, CLIB_CACHE_LINE_BYTES);
310       xd->nb_rx_desc = DPDK_NB_RX_DESC_DEFAULT;
311       xd->nb_tx_desc = DPDK_NB_TX_DESC_DEFAULT;
312       xd->cpu_socket = (i8) rte_eth_dev_socket_id(i);
313       rte_eth_dev_info_get(i, &dev_info);
314
315       memcpy(&xd->tx_conf, &dev_info.default_txconf,
316              sizeof(struct rte_eth_txconf));
317       if (dm->no_multi_seg)
318         {
319           xd->tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOMULTSEGS;
320           port_conf_template.rxmode.jumbo_frame = 0;
321         }
322       else
323         {
324           xd->tx_conf.txq_flags &= ~ETH_TXQ_FLAGS_NOMULTSEGS;
325           port_conf_template.rxmode.jumbo_frame = 1;
326         }
327
328       memcpy(&xd->port_conf, &port_conf_template, sizeof(struct rte_eth_conf));
329
330       xd->tx_q_used = clib_min(dev_info.max_tx_queues, tm->n_vlib_mains);
331
332       if (dm->max_tx_queues)
333         xd->tx_q_used = clib_min(xd->tx_q_used, dm->max_tx_queues);
334
335       if (dm->use_rss > 1 && dev_info.max_rx_queues >= dm->use_rss)
336         {
337           xd->rx_q_used = dm->use_rss;
338           xd->port_conf.rxmode.mq_mode = ETH_MQ_RX_RSS;
339           xd->port_conf.rx_adv_conf.rss_conf.rss_hf = ETH_RSS_IP | ETH_RSS_UDP | ETH_RSS_TCP;
340         }
341       else
342         xd->rx_q_used = 1;
343
344       xd->dev_type = VNET_DPDK_DEV_ETH;
345
346       /* workaround for drivers not setting driver_name */
347       if (!dev_info.driver_name)
348         dev_info.driver_name = dev_info.pci_dev->driver->name;
349       ASSERT(dev_info.driver_name);
350
351       if (!xd->pmd) {
352
353
354 #define _(s,f) else if (!strcmp(dev_info.driver_name, s)) \
355                  xd->pmd = VNET_DPDK_PMD_##f;
356         if (0)
357           ;
358         foreach_dpdk_pmd
359 #undef _
360         else
361           xd->pmd = VNET_DPDK_PMD_UNKNOWN;
362
363
364         switch (xd->pmd) {
365           /* 1G adapters */
366           case VNET_DPDK_PMD_E1000EM:
367           case VNET_DPDK_PMD_IGB:
368           case VNET_DPDK_PMD_IGBVF:
369             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_1G;
370             break;
371
372           /* 10G adapters */
373           case VNET_DPDK_PMD_IXGBE:
374           case VNET_DPDK_PMD_IXGBEVF:
375           case VNET_DPDK_PMD_THUNDERX:
376             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_10G;
377             xd->nb_rx_desc = DPDK_NB_RX_DESC_10GE;
378             xd->nb_tx_desc = DPDK_NB_TX_DESC_10GE;
379             break;
380
381           /* Cisco VIC */
382           case VNET_DPDK_PMD_VICE:
383           case VNET_DPDK_PMD_ENIC:
384             rte_eth_link_get_nowait(i, &l);
385             if (l.link_speed == 40000)
386               {
387                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
388                 xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
389                 xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
390               }
391             else
392               {
393                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_10G;
394                 xd->nb_rx_desc = DPDK_NB_RX_DESC_10GE;
395                 xd->nb_tx_desc = DPDK_NB_TX_DESC_10GE;
396               }
397             break;
398
399           /* Intel Fortville */
400           case VNET_DPDK_PMD_I40E:
401           case VNET_DPDK_PMD_I40EVF:
402             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
403             xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
404             xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
405
406             switch (dev_info.pci_dev->id.device_id) {
407               case I40E_DEV_ID_10G_BASE_T:
408               case I40E_DEV_ID_SFP_XL710:
409                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_10G;
410                 break;
411               case I40E_DEV_ID_QSFP_A:
412               case I40E_DEV_ID_QSFP_B:
413               case I40E_DEV_ID_QSFP_C:
414                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
415                 break;
416               case I40E_DEV_ID_VF:
417                 rte_eth_link_get_nowait(i, &l);
418                 xd->port_type = l.link_speed == 10000 ?
419                   VNET_DPDK_PORT_TYPE_ETH_10G : VNET_DPDK_PORT_TYPE_ETH_40G;
420                 break;
421               default:
422                 xd->port_type = VNET_DPDK_PORT_TYPE_UNKNOWN;
423             }
424             break;
425
426           case VNET_DPDK_PMD_CXGBE:
427             switch (dev_info.pci_dev->id.device_id) {
428               case 0x5410: /* T580-LP-cr */
429                 xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
430                 xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
431                 xd->port_type = VNET_DPDK_PORT_TYPE_ETH_40G;
432                 break;
433               default:
434                 xd->nb_rx_desc = DPDK_NB_RX_DESC_10GE;
435                 xd->nb_tx_desc = DPDK_NB_TX_DESC_10GE;
436                 xd->port_type = VNET_DPDK_PORT_TYPE_UNKNOWN;
437             }
438             break;
439
440           /* Intel Red Rock Canyon */
441           case VNET_DPDK_PMD_FM10K:
442             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_SWITCH;
443             xd->nb_rx_desc = DPDK_NB_RX_DESC_40GE;
444             xd->nb_tx_desc = DPDK_NB_TX_DESC_40GE;
445             break;
446
447           /* virtio */
448           case VNET_DPDK_PMD_VIRTIO:
449             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_1G;
450             xd->nb_rx_desc = DPDK_NB_RX_DESC_VIRTIO;
451             xd->nb_tx_desc = DPDK_NB_TX_DESC_VIRTIO;
452             break;
453
454           /* vmxnet3 */
455           case VNET_DPDK_PMD_VMXNET3:
456             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_1G;
457             xd->tx_conf.txq_flags |= ETH_TXQ_FLAGS_NOMULTSEGS;
458             break;
459
460           case VNET_DPDK_PMD_AF_PACKET:
461             xd->port_type = VNET_DPDK_PORT_TYPE_AF_PACKET;
462             xd->af_packet_port_id = af_packet_port_id++;
463             break;
464
465           case VNET_DPDK_PMD_BOND:
466             xd->port_type = VNET_DPDK_PORT_TYPE_ETH_BOND;
467             break;
468
469           default:
470             xd->port_type = VNET_DPDK_PORT_TYPE_UNKNOWN;
471         }
472
473   #ifdef NETMAP
474         if(strncmp(dev_info.driver_name, "vale", 4) == 0
475              || strncmp(dev_info.driver_name, "netmap", 6) == 0)
476           {
477             xd->pmd = VNET_DPDK_PMD_NETMAP;
478             xd->port_type = VNET_DPDK_PORT_TYPE_NETMAP;
479           }
480   #endif
481
482       }
483
484       /*
485        * Ensure default mtu is not > the mtu read from the hardware.
486        * Otherwise rte_eth_dev_configure() will fail and the port will
487        * not be available.
488        */
489       if (ETHERNET_MAX_PACKET_BYTES > dev_info.max_rx_pktlen)
490         {
491           /*
492            * This device does not support the platforms's max frame
493            * size. Use it's advertised mru instead.
494            */
495           xd->port_conf.rxmode.max_rx_pkt_len = dev_info.max_rx_pktlen;
496         }
497       else
498         {
499           xd->port_conf.rxmode.max_rx_pkt_len = ETHERNET_MAX_PACKET_BYTES;
500
501           /*
502            * Some platforms do not account for Ethernet FCS (4 bytes) in
503            * MTU calculations. To interop with them increase mru but only
504            * if the device's settings can support it.
505            */
506           if ((dev_info.max_rx_pktlen >= (ETHERNET_MAX_PACKET_BYTES + 4)) &&
507               xd->port_conf.rxmode.hw_strip_crc)
508             {
509               /*
510                * Allow additional 4 bytes (for Ethernet FCS). These bytes are
511                * stripped by h/w and so will not consume any buffer memory.
512                */
513               xd->port_conf.rxmode.max_rx_pkt_len += 4;
514             }
515         }
516
517       if (xd->pmd == VNET_DPDK_PMD_AF_PACKET)
518         {
519           f64 now = vlib_time_now(vm);
520           u32 rnd;
521           rnd = (u32) (now * 1e6);
522           rnd = random_u32 (&rnd);
523           memcpy (addr+2, &rnd, sizeof(rnd));
524           addr[0] = 2;
525           addr[1] = 0xfe;
526         }
527       else
528         rte_eth_macaddr_get(i,(struct ether_addr *)addr);
529
530       if (xd->tx_q_used < tm->n_vlib_mains)
531         dpdk_device_lock_init(xd);
532
533       xd->device_index = xd - dm->devices;
534       ASSERT(i == xd->device_index);
535       xd->per_interface_next_index = ~0;
536
537       /* assign interface to input thread */
538       dpdk_device_and_queue_t * dq;
539       int q;
540
541       for (q = 0; q < xd->rx_q_used; q++)
542         {
543           int cpu = dm->input_cpu_first_index + next_cpu;
544           unsigned lcore = vlib_worker_threads[cpu].dpdk_lcore_id;
545
546           /*
547            * numa node for worker thread handling this queue
548            * needed for taking buffers from the right mempool
549            */
550           vec_validate(xd->cpu_socket_id_by_queue, q);
551           xd->cpu_socket_id_by_queue[q] = rte_lcore_to_socket_id(lcore);
552
553           /*
554            * construct vector of (device,queue) pairs for each worker thread
555            */
556           vec_add2(dm->devices_by_cpu[cpu], dq, 1);
557           dq->device = xd->device_index;
558           dq->queue_id = q;
559
560           next_cpu++;
561           if (next_cpu == dm->input_cpu_count)
562             next_cpu = 0;
563         }
564
565       vec_validate_aligned (xd->tx_vectors, tm->n_vlib_mains,
566                             CLIB_CACHE_LINE_BYTES);
567       for (j = 0; j < tm->n_vlib_mains; j++)
568         {
569           vec_validate_ha (xd->tx_vectors[j], DPDK_TX_RING_SIZE, 
570                            sizeof(tx_ring_hdr_t), CLIB_CACHE_LINE_BYTES);
571           vec_reset_length (xd->tx_vectors[j]);
572         }
573
574       vec_validate_aligned (xd->rx_vectors, xd->rx_q_used,
575                             CLIB_CACHE_LINE_BYTES);
576       for (j = 0; j< xd->rx_q_used; j++)
577         {
578           vec_validate_aligned (xd->rx_vectors[j], VLIB_FRAME_SIZE-1,
579                                 CLIB_CACHE_LINE_BYTES);
580           vec_reset_length (xd->rx_vectors[j]);
581         }
582
583       vec_validate_aligned (xd->frames, tm->n_vlib_mains,
584                             CLIB_CACHE_LINE_BYTES);
585
586       rv = dpdk_port_setup(dm, xd);
587
588       if (rv < 0)
589         return rv;
590
591       /* count the number of descriptors used for this device */
592       nb_desc += xd->nb_rx_desc + xd->nb_tx_desc * xd->tx_q_used;
593
594       error = ethernet_register_interface
595         (dm->vnet_main,
596          dpdk_device_class.index,
597          xd->device_index,
598          /* ethernet address */ addr,
599          &xd->vlib_hw_if_index, 
600          dpdk_flag_change);
601       if (error)
602         return error;
603       
604       sw = vnet_get_hw_sw_interface (dm->vnet_main, xd->vlib_hw_if_index);
605       xd->vlib_sw_if_index = sw->sw_if_index;
606       hi = vnet_get_hw_interface (dm->vnet_main, xd->vlib_hw_if_index);
607
608       /*
609        * DAW-FIXME: The Cisco VIC firmware does not provide an api for a
610        *            driver to dynamically change the mtu.  If/when the 
611        *            VIC firmware gets fixed, then this should be removed.
612        */
613       if (xd->pmd == VNET_DPDK_PMD_VICE ||
614           xd->pmd == VNET_DPDK_PMD_ENIC)
615         {
616           /*
617            * Initialize mtu to what has been set by CIMC in the firmware cfg.
618            */
619           hi->max_packet_bytes = dev_info.max_rx_pktlen;
620           /*
621            * remove vlan tag from VIC port to fix VLAN0 issue.
622            * TODO Handle VLAN tagged traffic
623            */
624           int vlan_off;
625           vlan_off = rte_eth_dev_get_vlan_offload(xd->device_index);
626           vlan_off |= ETH_VLAN_STRIP_OFFLOAD;
627           rte_eth_dev_set_vlan_offload(xd->device_index, vlan_off);
628         }
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 void
726 dpdk_bind_devices_to_uio (dpdk_main_t * dm)
727 {
728   linux_pci_main_t * pm = &linux_pci_main;
729   clib_error_t * error;
730   vlib_pci_device_t * d;
731   pci_config_header_t * c;
732   u8 * pci_addr = 0;
733
734   pool_foreach (d, pm->pci_devs, ({
735     c = &d->config0.header;
736     vec_reset_length (pci_addr);
737     pci_addr = format (pci_addr, "%U%c", format_vlib_pci_addr, &d->bus_address, 0);
738
739     if (c->device_class != PCI_CLASS_NETWORK_ETHERNET)
740       continue;
741
742     /* if whitelist exists process only whitelisted devices */
743     if (dm->eth_if_whitelist &&
744         !strstr ((char *) dm->eth_if_whitelist, (char *) pci_addr))
745     continue;
746
747     /* virtio */
748     if (c->vendor_id == 0x1af4 && c->device_id == 0x1000)
749       ;
750     /* vmxnet3 */
751     else if (c->vendor_id == 0x15ad && c->device_id == 0x07b0)
752       ;
753     /* all Intel devices */
754     else if (c->vendor_id == 0x8086)
755       ;
756     /* Cisco VIC */
757     else if (c->vendor_id == 0x1137 && c->device_id == 0x0043)
758       ;
759     /* Chelsio T4/T5 */
760     else if (c->vendor_id == 0x1425 && (c->device_id & 0xe000) == 0x4000)
761       ;
762     else
763       {
764         clib_warning ("Unsupported Ethernet PCI device 0x%04x:0x%04x found "
765                       "at PCI address %s\n", (u16) c->vendor_id, (u16) c->device_id,
766                       pci_addr);
767         continue;
768       }
769
770     error = vlib_pci_bind_to_uio (d, (char *) dm->uio_driver_name);
771
772     if (error)
773       {
774         if (!dm->eth_if_whitelist)
775           dm->eth_if_blacklist = format (dm->eth_if_blacklist, "%U ",
776                                          format_vlib_pci_addr, &d->bus_address);
777         clib_error_report (error);
778       }
779   }));
780   vec_free (pci_addr);
781 }
782
783 static clib_error_t *
784 dpdk_config (vlib_main_t * vm, unformat_input_t * input)
785 {
786   clib_error_t * error = 0;
787   dpdk_main_t * dm = &dpdk_main;
788   vlib_thread_main_t * tm = vlib_get_thread_main();
789   u8 * s, * tmp = 0;
790   u8 * pci_dev_id = 0;
791   u8 * rte_cmd = 0, * ethname = 0;
792   u32 log_level;
793   int ret, i;
794   char * fmt;
795 #ifdef NETMAP
796   int rxrings, txrings, rxslots, txslots, txburst;
797   char * nmnam;
798 #endif
799   unformat_input_t _in;
800   unformat_input_t * in = &_in;
801   u8 no_pci = 0;
802   u8 no_huge = 0;
803   u8 huge_dir = 0;
804   u8 file_prefix = 0;
805   u8 * socket_mem = 0;
806
807   // MATT-FIXME: inverted virtio-vhost logic to use virtio by default
808   dm->use_virtio_vhost = 1;
809
810   while (unformat_check_input(input) != UNFORMAT_END_OF_INPUT)
811     {
812       /* Prime the pump */
813       if (unformat (input, "no-hugetlb"))
814         {
815           vec_add1 (dm->eal_init_args, (u8 *) "no-huge");
816           no_huge = 1;
817         }
818
819       else if (unformat (input, "enable-tcp-udp-checksum"))
820         {
821           dm->buffer_flags_template &= 
822             ~(IP_BUFFER_L4_CHECKSUM_CORRECT | IP_BUFFER_L4_CHECKSUM_COMPUTED);
823         }
824
825       else if (unformat (input, "decimal-interface-names"))
826         dm->interface_name_format_decimal = 1;
827
828       else if (unformat (input, "no-multi-seg"))
829         dm->no_multi_seg = 1;
830
831       else if (unformat (input, "dev %s", &pci_dev_id))
832         {
833           if (dm->eth_if_whitelist)
834             {
835               /*
836                * Don't add duplicate device id's.
837                */
838               if (strstr ((char *)dm->eth_if_whitelist, (char *)pci_dev_id))
839                 continue;
840
841               _vec_len (dm->eth_if_whitelist) -= 1; // chomp trailing NULL.
842               dm->eth_if_whitelist = format (dm->eth_if_whitelist, " %s%c",
843                                              pci_dev_id, 0);
844             }
845           else
846             dm->eth_if_whitelist = format (0, "%s%c", pci_dev_id, 0);
847         }
848
849 #ifdef NETMAP
850      else if (unformat(input, "netmap %s/%d:%d/%d:%d/%d",
851                   &nmname, &rxrings, &rxslots, &txrings, &txslots, &txburst)) {
852         char * rv;
853         rv = (char *)
854           eth_nm_args(nmname, rxrings, rxslots, txrings, txslots, txburst);
855         if (rv) {
856           error = clib_error_return (0, "%s", rv);
857           goto done;
858         }
859       }else if (unformat(input, "netmap %s", &nmname)) {
860         char * rv;
861         rv = (char *)
862           eth_nm_args(nmname, 0, 0, 0, 0, 0);
863         if (rv) {
864           error = clib_error_return (0, "%s", rv);
865           goto done;
866         }
867       }
868 #endif
869
870       else if (unformat (input, "num-mbufs %d", &dm->num_mbufs))
871         ;
872       else if (unformat (input, "max-tx-queues %d", &dm->max_tx_queues))
873         ;
874       else if (unformat (input, "kni %d", &dm->num_kni))
875         ;
876       else if (unformat (input, "uio-driver %s", &dm->uio_driver_name))
877         ;
878       else if (unformat (input, "socket-mem %s", &socket_mem))
879         ;
880       else if (unformat (input, "vhost-user-coalesce-frames %d", &dm->vhost_coalesce_frames))
881         ;
882       else if (unformat (input, "vhost-user-coalesce-time %f", &dm->vhost_coalesce_time))
883         ;
884       else if (unformat (input, "enable-vhost-user"))
885         dm->use_virtio_vhost = 0;
886       else if (unformat (input, "rss %d", &dm->use_rss))
887         ;
888
889 #define _(a)                                    \
890       else if (unformat(input, #a))             \
891         {                                       \
892           if (!strncmp(#a, "no-pci", 6))        \
893             no_pci = 1;                         \
894           tmp = format (0, "--%s%c", #a, 0);    \
895           vec_add1 (dm->eal_init_args, tmp);    \
896         }
897       foreach_eal_double_hyphen_predicate_arg
898 #undef _
899
900 #define _(a)                                          \
901         else if (unformat(input, #a " %s", &s))       \
902           {                                           \
903             if (!strncmp(#a, "huge-dir", 8))          \
904               huge_dir = 1;                           \
905             else if (!strncmp(#a, "file-prefix", 11)) \
906               file_prefix = 1;                        \
907             tmp = format (0, "--%s%c", #a, 0);        \
908             vec_add1 (dm->eal_init_args, tmp);        \
909             vec_add1 (s, 0);                          \
910             vec_add1 (dm->eal_init_args, s);          \
911           }
912         foreach_eal_double_hyphen_arg
913 #undef _
914
915 #define _(a,b)                                          \
916           else if (unformat(input, #a " %s", &s))       \
917             {                                           \
918               tmp = format (0, "-%s%c", #b, 0);         \
919               vec_add1 (dm->eal_init_args, tmp);        \
920               vec_add1 (s, 0);                          \
921               vec_add1 (dm->eal_init_args, s);          \
922             }
923           foreach_eal_single_hyphen_arg
924 #undef _
925
926 #define _(a,b)                                          \
927             else if (unformat(input, #a " %s", &s))     \
928               {                                         \
929                 tmp = format (0, "-%s%c", #b, 0);       \
930                 vec_add1 (dm->eal_init_args, tmp);      \
931                 vec_add1 (s, 0);                        \
932                 vec_add1 (dm->eal_init_args, s);        \
933                 dm->a##_set_manually = 1;               \
934               }
935             foreach_eal_single_hyphen_mandatory_arg
936 #undef _
937
938           else if (unformat(input, "default"))
939             ;
940
941           else
942             {
943               error = clib_error_return (0, "unknown input `%U'",
944                                          format_unformat_error, input);
945               goto done;
946             }
947     }
948
949   if (!dm->uio_driver_name)
950     dm->uio_driver_name = format (0, "igb_uio%c", 0);
951
952   /*
953    * Use 1G huge pages if available.
954    */
955   if (!no_huge && !huge_dir)
956     {
957       u32 x, * mem_by_socket = 0;
958       uword c = 0;
959       u8 use_1g = 1;
960       u8 use_2m = 1;
961       u8 less_than_1g = 1;
962       int rv;
963
964       umount(DEFAULT_HUGE_DIR);
965
966       /* Process "socket-mem" parameter value */
967       if (vec_len (socket_mem))
968         {
969           unformat_input_t in;
970           unformat_init_vector(&in, socket_mem);
971           while (unformat_check_input (&in) != UNFORMAT_END_OF_INPUT)
972             {
973               if (unformat (&in, "%u,", &x))
974                 ;
975               else if (unformat (&in, "%u", &x))
976                 ;
977               else if (unformat (&in, ","))
978                 x = 0;
979               else
980                 break;
981
982               vec_add1(mem_by_socket, x);
983
984               if (x > 1023)
985                 less_than_1g = 0;
986             }
987           /* Note: unformat_free vec_frees(in.buffer), aka socket_mem... */
988           unformat_free(&in);
989           socket_mem = 0;
990         }
991       else
992         {
993           clib_bitmap_foreach (c, tm->cpu_socket_bitmap, (
994             {
995               vec_validate(mem_by_socket, c);
996               mem_by_socket[c] = 512; /* default per-socket mem */
997             }
998           ));
999         }
1000
1001       /* check if available enough 1GB pages for each socket */
1002       clib_bitmap_foreach (c, tm->cpu_socket_bitmap, (
1003         {
1004           u32 pages_avail, page_size, mem;
1005           u8 *s = 0;
1006           char * path = "/sys/devices/system/node/node%u/hugepages/"
1007                         "hugepages-%ukB/free_hugepages%c";
1008
1009           vec_validate(mem_by_socket, c);
1010           mem = mem_by_socket[c];
1011
1012           page_size = 1024;
1013           pages_avail = 0;
1014           s = format (s, path, c, page_size * 1024, 0);
1015           read_sys_fs ((char *) s, "%u", &pages_avail);
1016           vec_reset_length (s);
1017
1018           if (page_size * pages_avail < mem)
1019             use_1g = 0;
1020
1021           page_size = 2;
1022           pages_avail = 0;
1023           s = format (s, path, c, page_size * 1024, 0);
1024           read_sys_fs ((char *) s, "%u", &pages_avail);
1025           vec_reset_length (s);
1026
1027           if (page_size * pages_avail < mem)
1028             use_2m = 0;
1029
1030           vec_free(s);
1031       }));
1032       _vec_len (mem_by_socket) = c + 1;
1033
1034       /* regenerate socket_mem string */
1035       vec_foreach_index (x, mem_by_socket)
1036         socket_mem = format (socket_mem, "%s%u",
1037                              socket_mem ? "," : "",
1038                              mem_by_socket[x]);
1039       socket_mem = format (socket_mem, "%c", 0);
1040
1041       vec_free (mem_by_socket);
1042
1043       rv = mkdir(VPP_RUN_DIR, 0755);
1044       if (rv && errno != EEXIST)
1045         {
1046           error = clib_error_return (0, "mkdir '%s' failed errno %d",
1047                                      VPP_RUN_DIR, errno);
1048           goto done;
1049         }
1050
1051       rv = mkdir(DEFAULT_HUGE_DIR, 0755);
1052       if (rv && errno != EEXIST)
1053         {
1054           error = clib_error_return (0, "mkdir '%s' failed errno %d",
1055                                      DEFAULT_HUGE_DIR, errno);
1056           goto done;
1057         }
1058
1059       if (use_1g && !(less_than_1g && use_2m))
1060         {
1061           rv = mount("none", DEFAULT_HUGE_DIR, "hugetlbfs", 0, "pagesize=1G");
1062         }
1063       else if (use_2m)
1064         {
1065           rv = mount("none", DEFAULT_HUGE_DIR, "hugetlbfs", 0, NULL);
1066         }
1067       else
1068         {
1069           return clib_error_return (0, "not enough free huge pages");
1070         }
1071
1072       if (rv)
1073         {
1074           error = clib_error_return (0, "mount failed %d", errno);
1075           goto done;
1076         }
1077
1078       tmp = format (0, "--huge-dir%c", 0);
1079       vec_add1 (dm->eal_init_args, tmp);
1080       tmp = format (0, "%s%c", DEFAULT_HUGE_DIR, 0);
1081       vec_add1 (dm->eal_init_args, tmp);
1082       if (!file_prefix)
1083         {
1084           tmp = format (0, "--file-prefix%c", 0);
1085           vec_add1 (dm->eal_init_args, tmp);
1086           tmp = format (0, "vpp%c", 0);
1087           vec_add1 (dm->eal_init_args, tmp);
1088         }
1089     }
1090
1091   vec_free (rte_cmd);
1092   vec_free (ethname);
1093
1094   if (error)
1095     return error;
1096
1097   /* I'll bet that -c and -n must be the first and second args... */
1098   if (!dm->coremask_set_manually)
1099     {
1100       vlib_thread_registration_t * tr;
1101       uword * coremask = 0;
1102       int i;
1103
1104       /* main thread core */
1105       coremask = clib_bitmap_set(coremask, tm->main_lcore, 1);
1106
1107       for (i = 0; i < vec_len (tm->registrations); i++)
1108         {
1109           tr = tm->registrations[i];
1110           coremask = clib_bitmap_or(coremask, tr->coremask);
1111         }
1112
1113       vec_insert (dm->eal_init_args, 2, 1);
1114       dm->eal_init_args[1] = (u8 *) "-c";
1115       tmp = format (0, "%U%c", format_bitmap_hex, coremask, 0);
1116       dm->eal_init_args[2] = tmp;
1117       clib_bitmap_free(coremask);
1118     }
1119
1120   if (!dm->nchannels_set_manually)
1121     {
1122       vec_insert (dm->eal_init_args, 2, 3);
1123       dm->eal_init_args[3] = (u8 *) "-n";
1124       tmp = format (0, "%d", dm->nchannels);
1125       dm->eal_init_args[4] = tmp;
1126     }
1127
1128   if (no_pci == 0 && geteuid() == 0)
1129     dpdk_bind_devices_to_uio(dm);
1130
1131   /*
1132    * If there are whitelisted devices,
1133    * add the whitelist option & device list to the dpdk arg list...
1134    */
1135   if (dm->eth_if_whitelist)
1136     {
1137       unformat_init_string (in, (char *)dm->eth_if_whitelist,
1138                             vec_len(dm->eth_if_whitelist) - 1);
1139       fmt = "-w%c";
1140     }
1141
1142   /*
1143    * Otherwise add the blacklisted devices to the dpdk arg list.
1144    */
1145   else
1146     {
1147       unformat_init_string (in, (char *)dm->eth_if_blacklist,
1148                             vec_len(dm->eth_if_blacklist) - 1);
1149       fmt = "-b%c";
1150     }
1151
1152   while (unformat_check_input (in) != UNFORMAT_END_OF_INPUT)
1153     {
1154       tmp = format (0, fmt, 0);
1155       vec_add1 (dm->eal_init_args, tmp);
1156       unformat (in, "%s", &pci_dev_id);
1157       vec_add1 (dm->eal_init_args, pci_dev_id);
1158     }
1159
1160   /* set master-lcore */
1161   tmp = format (0, "--master-lcore%c", 0);
1162   vec_add1 (dm->eal_init_args, tmp);
1163   tmp = format (0, "%u%c", tm->main_lcore, 0);
1164   vec_add1 (dm->eal_init_args, tmp);
1165
1166   /* set socket-mem */
1167   tmp = format (0, "--socket-mem%c", 0);
1168   vec_add1 (dm->eal_init_args, tmp);
1169   tmp = format (0, "%s%c", socket_mem, 0);
1170   vec_add1 (dm->eal_init_args, tmp);
1171
1172   /* NULL terminate the "argv" vector, in case of stupidity */
1173   vec_add1 (dm->eal_init_args, 0);
1174   _vec_len(dm->eal_init_args) -= 1;
1175
1176   /* Set up DPDK eal and packet mbuf pool early. */
1177
1178   log_level = (CLIB_DEBUG > 0) ? RTE_LOG_DEBUG : RTE_LOG_NOTICE;
1179
1180   rte_set_log_level (log_level);
1181
1182   vm = dm->vlib_main;
1183
1184   /* make copy of args as rte_eal_init tends to mess up with arg array */
1185   for (i = 1; i < vec_len(dm->eal_init_args); i++)
1186     dm->eal_init_args_str = format(dm->eal_init_args_str, "%s ",
1187                                    dm->eal_init_args[i]);
1188
1189   ret = rte_eal_init(vec_len(dm->eal_init_args), (char **) dm->eal_init_args);
1190
1191   /* lazy umount hugepages */
1192   umount2(DEFAULT_HUGE_DIR, MNT_DETACH);
1193
1194   if (ret < 0)
1195     return clib_error_return (0, "rte_eal_init returned %d", ret);
1196
1197   /* Dump the physical memory layout prior to creating the mbuf_pool */
1198   fprintf(stdout, "DPDK physical memory layout:\n");
1199   rte_dump_physmem_layout(stdout);
1200
1201   /* main thread 1st */
1202   error = vlib_buffer_pool_create(vm, dm->num_mbufs, rte_socket_id());
1203   if (error)
1204     return error;
1205
1206   for (i = 0; i < RTE_MAX_LCORE; i++)
1207     {
1208       error = vlib_buffer_pool_create(vm, dm->num_mbufs,
1209                                       rte_lcore_to_socket_id(i));
1210       if (error)
1211         return error;
1212     }
1213
1214   if (dm->use_rss)
1215     {
1216       vlib_node_runtime_t * rt = vlib_node_get_runtime (vm, dpdk_input_node.index);
1217       rt->function = dpdk_input_rss;
1218     }
1219  done:
1220   return error;
1221 }
1222
1223 VLIB_CONFIG_FUNCTION (dpdk_config, "dpdk");
1224
1225 void dpdk_update_link_state (dpdk_device_t * xd, f64 now)
1226 {
1227     vnet_main_t * vnm = vnet_get_main();
1228     struct rte_eth_link prev_link = xd->link;
1229     u32 hw_flags =  0;
1230     u8 hw_flags_chg = 0;
1231
1232     /* only update link state for PMD interfaces */
1233     if (xd->dev_type != VNET_DPDK_DEV_ETH)
1234       return;
1235
1236     xd->time_last_link_update = now ? now : xd->time_last_link_update;
1237     memset(&xd->link, 0, sizeof(xd->link));
1238     rte_eth_link_get_nowait (xd->device_index, &xd->link);
1239
1240     if (LINK_STATE_ELOGS)
1241       {
1242         vlib_main_t * vm = vlib_get_main();
1243         ELOG_TYPE_DECLARE(e) = {
1244           .format = 
1245           "update-link-state: sw_if_index %d, admin_up %d,"
1246           "old link_state %d new link_state %d",
1247           .format_args = "i4i1i1i1",
1248         };
1249
1250         struct { u32 sw_if_index; u8 admin_up; 
1251           u8 old_link_state; u8 new_link_state;} *ed;
1252         ed = ELOG_DATA (&vm->elog_main, e);
1253         ed->sw_if_index = xd->vlib_sw_if_index;
1254         ed->admin_up = xd->admin_up;
1255         ed->old_link_state = (u8)
1256           vnet_hw_interface_is_link_up (vnm, xd->vlib_hw_if_index);
1257         ed->new_link_state = (u8) xd->link.link_status;
1258       }
1259
1260     if ((xd->admin_up == 1) && 
1261         ((xd->link.link_status != 0) ^ 
1262          vnet_hw_interface_is_link_up (vnm, xd->vlib_hw_if_index)))
1263       {
1264         hw_flags_chg = 1;
1265         hw_flags |= (xd->link.link_status ? 
1266                      VNET_HW_INTERFACE_FLAG_LINK_UP: 0);
1267       }
1268
1269     if (hw_flags_chg || (xd->link.link_duplex != prev_link.link_duplex))
1270       {
1271         hw_flags_chg = 1;
1272         switch (xd->link.link_duplex)
1273           {
1274           case ETH_LINK_HALF_DUPLEX:
1275             hw_flags |= VNET_HW_INTERFACE_FLAG_HALF_DUPLEX;
1276             break;
1277           case ETH_LINK_FULL_DUPLEX:
1278             hw_flags |= VNET_HW_INTERFACE_FLAG_FULL_DUPLEX;
1279             break;
1280           default:
1281             break;
1282           }
1283       }
1284 #if RTE_VERSION >= RTE_VERSION_NUM(16, 4, 0, 0)
1285     if (hw_flags_chg || (xd->link.link_speed != prev_link.link_speed))
1286       {
1287         hw_flags_chg = 1;
1288         switch (xd->link.link_speed)
1289           {
1290           case ETH_SPEED_NUM_10M:
1291             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_10M;
1292             break;
1293           case ETH_SPEED_NUM_100M:
1294             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_100M;
1295             break;
1296           case ETH_SPEED_NUM_1G:
1297             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_1G;
1298             break;
1299           case ETH_SPEED_NUM_10G:
1300             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_10G;
1301             break;
1302           case ETH_SPEED_NUM_40G:
1303             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_40G;
1304             break;
1305     case 0:
1306       break;
1307     default:
1308       clib_warning("unknown link speed %d", xd->link.link_speed);
1309             break;
1310           }
1311       }
1312 #else
1313     if (hw_flags_chg || (xd->link.link_speed != prev_link.link_speed))
1314       {
1315         hw_flags_chg = 1;
1316         switch (xd->link.link_speed)
1317           {
1318           case ETH_LINK_SPEED_10:
1319             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_10M;
1320             break;
1321           case ETH_LINK_SPEED_100:
1322             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_100M;
1323             break;
1324           case ETH_LINK_SPEED_1000:
1325             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_1G;
1326             break;
1327           case ETH_LINK_SPEED_10000:
1328             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_10G;
1329             break;
1330           case ETH_LINK_SPEED_40G:
1331             hw_flags |= VNET_HW_INTERFACE_FLAG_SPEED_40G;
1332             break;
1333     case 0:
1334       break;
1335     default:
1336       clib_warning("unknown link speed %d", xd->link.link_speed);
1337             break;
1338           }
1339       }
1340 #endif
1341     if (hw_flags_chg)
1342       {
1343         if (LINK_STATE_ELOGS)
1344           {
1345             vlib_main_t * vm = vlib_get_main();
1346
1347             ELOG_TYPE_DECLARE(e) = {
1348               .format = "update-link-state: sw_if_index %d, new flags %d",
1349               .format_args = "i4i4",
1350             };
1351
1352             struct { u32 sw_if_index; u32 flags; } *ed;
1353             ed = ELOG_DATA (&vm->elog_main, e);
1354             ed->sw_if_index = xd->vlib_sw_if_index;
1355             ed->flags = hw_flags;
1356           }
1357         vnet_hw_interface_set_flags (vnm, xd->vlib_hw_if_index, hw_flags);
1358       }
1359 }
1360
1361 static uword
1362 dpdk_process (vlib_main_t * vm,
1363               vlib_node_runtime_t * rt,
1364               vlib_frame_t * f)
1365 {
1366   clib_error_t * error;
1367   vnet_main_t * vnm = vnet_get_main();
1368   dpdk_main_t * dm = &dpdk_main;
1369   ethernet_main_t * em = &ethernet_main;
1370   dpdk_device_t * xd;
1371   vlib_thread_main_t * tm = vlib_get_thread_main();
1372   void *vu_state;
1373   int i;
1374
1375   error = dpdk_lib_init (dm);
1376
1377   /* 
1378    * Turn on the input node if we found some devices to drive
1379    * and we're not running worker threads or i/o threads
1380    */
1381
1382   if (error == 0 && vec_len(dm->devices) > 0)
1383     {
1384         if (tm->n_vlib_mains == 1)
1385           vlib_node_set_state (vm, dpdk_input_node.index,
1386                                VLIB_NODE_STATE_POLLING);
1387         else if (tm->main_thread_is_io_node)
1388           vlib_node_set_state (vm, dpdk_io_input_node.index,
1389                                VLIB_NODE_STATE_POLLING);
1390         else if (!dm->have_io_threads)
1391           for (i=0; i < tm->n_vlib_mains; i++)
1392             if (vec_len(dm->devices_by_cpu[i]) > 0)
1393               vlib_node_set_state (vlib_mains[i], dpdk_input_node.index,
1394                                    VLIB_NODE_STATE_POLLING);
1395     }
1396
1397   if (error)
1398     clib_error_report (error);
1399
1400   dpdk_vhost_user_process_init(&vu_state);
1401
1402   dm->io_thread_release = 1;
1403
1404   f64 now = vlib_time_now (vm);
1405   vec_foreach (xd, dm->devices)
1406     {
1407       dpdk_update_link_state (xd, now);
1408     }
1409
1410 { // Extra set up for bond interfaces:
1411   // 1. Setup MACs for bond interfaces and their slave links which was set
1412   //    in dpdk_port_setup() but needs to be done again here to take effect.
1413   // 2. Set max L3 packet size of each bond interface to the lowerst value of 
1414   //    its slave links 
1415   // 3. Set up info for bond interface related CLI support.
1416   int nports = rte_eth_dev_count();
1417   if (nports > 0) {
1418       for (i = 0; i < nports; i++) {
1419           struct rte_eth_dev_info dev_info;
1420           rte_eth_dev_info_get(i, &dev_info);
1421           if (!dev_info.driver_name)
1422               dev_info.driver_name = dev_info.pci_dev->driver->name;
1423           ASSERT(dev_info.driver_name);
1424           if (strncmp(dev_info.driver_name, "rte_bond_pmd", 12) == 0) {
1425               u8  addr[6]; 
1426               u8  slink[16];
1427               int nlink = rte_eth_bond_slaves_get(i, slink, 16);
1428               if (nlink > 0) {
1429                   vnet_hw_interface_t * bhi;
1430                   ethernet_interface_t * bei;
1431                   /* Get MAC of 1st slave link */
1432                   rte_eth_macaddr_get(slink[0], (struct ether_addr *)addr);
1433                   /* Set MAC of bounded interface to that of 1st slave link */
1434                   rte_eth_bond_mac_address_set(i, (struct ether_addr *)addr);
1435                   /* Populate MAC of bonded interface in VPP hw tables */
1436                   bhi = vnet_get_hw_interface(
1437                       vnm, dm->devices[i].vlib_hw_if_index);
1438                   bei = pool_elt_at_index(em->interfaces, bhi->hw_instance);
1439                   memcpy(bhi->hw_address, addr, 6);
1440                   memcpy(bei->address, addr, 6);
1441                   /* Init l3 packet size allowed on bonded interface */
1442                   bhi->max_l3_packet_bytes[VLIB_RX] = 
1443                   bhi->max_l3_packet_bytes[VLIB_TX] = 
1444                       ETHERNET_MAX_PACKET_BYTES - sizeof(ethernet_header_t);
1445                   while (nlink >= 1) { /* for all slave links */
1446                       int slave = slink[--nlink];
1447                       dpdk_device_t * sdev = &dm->devices[slave];
1448                       vnet_hw_interface_t * shi;
1449                       vnet_sw_interface_t * ssi;
1450                       /* Add MAC to all slave links except the first one */
1451                       if (nlink) rte_eth_dev_mac_addr_add(
1452                           slave, (struct ether_addr *)addr, 0);
1453                       /* Set slaves bitmap for bonded interface */
1454                       bhi->bond_info = clib_bitmap_set(
1455                           bhi->bond_info, sdev->vlib_hw_if_index, 1);
1456                       /* Set slave link flags on slave interface */
1457                       shi = vnet_get_hw_interface(vnm, sdev->vlib_hw_if_index);
1458                       ssi = vnet_get_sw_interface(vnm, sdev->vlib_sw_if_index);
1459                       shi->bond_info = VNET_HW_INTERFACE_BOND_INFO_SLAVE;
1460                       ssi->flags |= VNET_SW_INTERFACE_FLAG_BOND_SLAVE;
1461                       /* Set l3 packet size allowed as the lowest of slave */
1462                       if (bhi->max_l3_packet_bytes[VLIB_RX] >
1463                           shi->max_l3_packet_bytes[VLIB_RX]) 
1464                           bhi->max_l3_packet_bytes[VLIB_RX] =
1465                           bhi->max_l3_packet_bytes[VLIB_TX] =
1466                               shi->max_l3_packet_bytes[VLIB_RX];
1467                   }
1468               }
1469           }
1470       }
1471   }
1472 }
1473
1474   while (1)
1475     {
1476       /*
1477        * check each time through the loop in case intervals are changed
1478        */
1479       f64 min_wait = dm->link_state_poll_interval < dm->stat_poll_interval ?
1480                      dm->link_state_poll_interval : dm->stat_poll_interval;
1481
1482       vlib_process_wait_for_event_or_clock (vm, min_wait);
1483
1484       if (dpdk_get_admin_up_down_in_progress())
1485           /* skip the poll if an admin up down is in progress (on any interface) */
1486           continue;
1487
1488       vec_foreach (xd, dm->devices)
1489         {
1490           f64 now = vlib_time_now (vm);
1491           if ((now - xd->time_last_stats_update) >= dm->stat_poll_interval)
1492             dpdk_update_counters (xd, now);
1493           if ((now - xd->time_last_link_update) >= dm->link_state_poll_interval)
1494             dpdk_update_link_state (xd, now);
1495
1496       if (xd->dev_type == VNET_DPDK_DEV_VHOST_USER)
1497           if (dpdk_vhost_user_process_if(vm, xd, vu_state) != 0)
1498               continue;
1499         }
1500     }
1501
1502   dpdk_vhost_user_process_cleanup(vu_state);
1503
1504   return 0; 
1505 }
1506
1507 VLIB_REGISTER_NODE (dpdk_process_node,static) = {
1508     .function = dpdk_process,
1509     .type = VLIB_NODE_TYPE_PROCESS,
1510     .name = "dpdk-process",
1511     .process_log2_n_stack_bytes = 17,
1512 };
1513
1514 int dpdk_set_stat_poll_interval (f64 interval)
1515 {
1516   if (interval < DPDK_MIN_STATS_POLL_INTERVAL)
1517       return (VNET_API_ERROR_INVALID_VALUE);
1518
1519   dpdk_main.stat_poll_interval = interval;
1520
1521   return 0;
1522 }
1523
1524 int dpdk_set_link_state_poll_interval (f64 interval)
1525 {
1526   if (interval < DPDK_MIN_LINK_POLL_INTERVAL)
1527       return (VNET_API_ERROR_INVALID_VALUE);
1528
1529   dpdk_main.link_state_poll_interval = interval;
1530
1531   return 0;
1532 }
1533
1534 clib_error_t *
1535 dpdk_init (vlib_main_t * vm)
1536 {
1537   dpdk_main_t * dm = &dpdk_main;
1538   vlib_node_t * ei;
1539   clib_error_t * error = 0;
1540   vlib_thread_main_t * tm = vlib_get_thread_main();
1541
1542   /* verify that structs are cacheline aligned */
1543   ASSERT(offsetof(dpdk_device_t, cacheline0) == 0);
1544   ASSERT(offsetof(dpdk_device_t, cacheline1) == CLIB_CACHE_LINE_BYTES);
1545   ASSERT(offsetof(dpdk_worker_t, cacheline0) == 0);
1546   ASSERT(offsetof(frame_queue_trace_t, cacheline0) == 0);
1547
1548   dm->vlib_main = vm;
1549   dm->vnet_main = vnet_get_main();
1550
1551   ei = vlib_get_node_by_name (vm, (u8 *) "ethernet-input");
1552   if (ei == 0)
1553       return clib_error_return (0, "ethernet-input node AWOL");
1554
1555   dm->ethernet_input_node_index = ei->index;
1556
1557   dm->nchannels = 4;
1558   dm->num_mbufs = dm->num_mbufs ? dm->num_mbufs : NB_MBUF;
1559   vec_add1 (dm->eal_init_args, (u8 *) "vnet");
1560
1561   dm->dpdk_device_by_kni_port_id = hash_create (0, sizeof (uword));
1562   dm->vu_sw_if_index_by_listener_fd = hash_create (0, sizeof (uword));
1563   dm->vu_sw_if_index_by_sock_fd = hash_create (0, sizeof (uword));
1564
1565   /* $$$ use n_thread_stacks since it's known-good at this point */
1566   vec_validate (dm->recycle, tm->n_thread_stacks - 1);
1567
1568   /* initialize EFD (early fast discard) default settings */
1569   dm->efd.enabled = DPDK_EFD_DISABLED;
1570   dm->efd.queue_hi_thresh = ((DPDK_EFD_DEFAULT_DEVICE_QUEUE_HI_THRESH_PCT *
1571                               DPDK_NB_RX_DESC_10GE)/100);
1572   dm->efd.consec_full_frames_hi_thresh =
1573       DPDK_EFD_DEFAULT_CONSEC_FULL_FRAMES_HI_THRESH;
1574
1575   /* vhost-user coalescence frames defaults */
1576   dm->vhost_coalesce_frames = 32;
1577   dm->vhost_coalesce_time = 1e-3;
1578
1579   /* Default vlib_buffer_t flags, DISABLES tcp/udp checksumming... */
1580   dm->buffer_flags_template = 
1581     (VLIB_BUFFER_TOTAL_LENGTH_VALID 
1582      | IP_BUFFER_L4_CHECKSUM_COMPUTED
1583      | IP_BUFFER_L4_CHECKSUM_CORRECT);
1584
1585   dm->stat_poll_interval = DPDK_STATS_POLL_INTERVAL;
1586   dm->link_state_poll_interval = DPDK_LINK_POLL_INTERVAL;
1587
1588   /* init CLI */
1589   if ((error = vlib_call_init_function (vm, dpdk_cli_init)))
1590     return error;
1591
1592   return error;
1593 }
1594
1595 VLIB_INIT_FUNCTION (dpdk_init);
1596