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