source: lib/format_dpdk.c @ cf05223

4.0.1-hotfixescachetimestampsdevelopdpdk-ndagetsilivelibtrace4ndag_formatpfringrc-4.0.1rc-4.0.2rc-4.0.3rc-4.0.4ringdecrementfixringperformanceringtimestampfixes
Last change on this file since cf05223 was cf05223, checked in by Richard Sanger <rsangerarj@…>, 7 years ago

No longer print out DPDK version or magic from the rte_config structure since 1.7 these have been removed.
See dpdk commit 69020660c382b1feff2a0b6c56f8decf2f79e953
I've replaced the version with rte_version() which returns a nice formated string.

  • Property mode set to 100644
File size: 69.6 KB
Line 
1/*
2 * This file is part of libtrace
3 *
4 * Copyright (c) 2007,2008,2009,2010 The University of Waikato, Hamilton,
5 * New Zealand.
6 *
7 * Author: Richard Sanger
8 *         
9 * All rights reserved.
10 *
11 * This code has been developed by the University of Waikato WAND
12 * research group. For further information please see http://www.wand.net.nz/
13 *
14 * libtrace is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
18 *
19 * libtrace is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with libtrace; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27 *
28 * $Id: format_dpdk.c 1805 2013-03-08 02:01:35Z salcock $
29 *
30 */
31
32/* This format module deals with using the Intel Data Plane Development
33 * Kit capture format.
34 *
35 * Intel Data Plane Development Kit is a LIVE capture format.
36 *
37 * This format also supports writing which will write packets out to the
38 * network as a form of packet replay. This should not be confused with the
39 * RT protocol which is intended to transfer captured packet records between
40 * RT-speaking programs.
41 */
42
43#define _GNU_SOURCE
44
45#include "config.h"
46#include "libtrace.h"
47#include "libtrace_int.h"
48#include "format_helper.h"
49#include "libtrace_arphrd.h"
50#include "hash_toeplitz.h"
51
52#ifdef HAVE_INTTYPES_H
53#  include <inttypes.h>
54#else
55# error "Can't find inttypes.h"
56#endif
57
58#include <stdlib.h>
59#include <assert.h>
60#include <unistd.h>
61#include <endian.h>
62#include <string.h>
63
64/* We can deal with any minor differences by checking the RTE VERSION
65 * Typically DPDK backports some fixes (typically for building against
66 * newer kernels) to the older version of DPDK.
67 *
68 * These get released with the rX suffix. The following macros where added
69 * in these new releases.
70 *
71 * Below this is a log of version that required changes to the libtrace
72 * code (that we still attempt to support).
73 *
74 * Currently 1.5 to 1.7 is supported.
75 */
76#include <rte_eal.h>
77#include <rte_version.h>
78#ifndef RTE_VERSION_NUM
79#       define RTE_VERSION_NUM(a,b,c,d) ((a) << 24 | (b) << 16 | (c) << 8 | (d))
80#endif
81#ifndef RTE_VER_PATCH_RELEASE
82#       define RTE_VER_PATCH_RELEASE 0
83#endif
84#ifndef RTE_VERSION
85#       define RTE_VERSION RTE_VERSION_NUM(RTE_VER_MAJOR,RTE_VER_MINOR, \
86        RTE_VER_PATCH_LEVEL, RTE_VER_PATCH_RELEASE)
87#endif
88
89/* 1.6.0r2 :
90 *      rte_eal_pci_set_blacklist() is removed
91 *      device_list is renamed ot pci_device_list
92 *
93 * Replaced by:
94 *      rte_devargs (we can simply whitelist)
95 */
96#if RTE_VERSION <= RTE_VERSION_NUM(1, 6, 0, 1)
97#       define DPDK_USE_BLACKLIST 1
98#else
99#       define DPDK_USE_BLACKLIST 0
100#endif
101
102/*
103 * 1.7.0 :
104 *      rte_pmd_init_all is removed
105 *
106 * Replaced by:
107 *      Nothing, no longer needed
108 */
109#if RTE_VERSION < RTE_VERSION_NUM(1, 7, 0, 0)
110#       define DPDK_USE_PMD_INIT 1
111#else
112#       define DPDK_USE_PMD_INIT 0
113#endif
114
115#include <rte_per_lcore.h>
116#include <rte_debug.h>
117#include <rte_errno.h>
118#include <rte_common.h>
119#include <rte_log.h>
120#include <rte_memcpy.h>
121#include <rte_prefetch.h>
122#include <rte_branch_prediction.h>
123#include <rte_pci.h>
124#include <rte_ether.h>
125#include <rte_ethdev.h>
126#include <rte_ring.h>
127#include <rte_mempool.h>
128#include <rte_mbuf.h>
129#include <rte_launch.h>
130#include <rte_lcore.h>
131#include <rte_per_lcore.h>
132#include <pthread.h>
133
134/* The default size of memory buffers to use - This is the max size of standard
135 * ethernet packet less the size of the MAC CHECKSUM */
136#define RX_MBUF_SIZE 1514
137
138/* The minimum number of memory buffers per queue tx or rx. Search for
139 * _MIN_RING_DESC in DPDK. The largest minimum is 64 for 10GBit cards.
140 */
141#define MIN_NB_BUF 64
142
143/* Number of receive memory buffers to use
144 * By default this is limited by driver to 4k and must be a multiple of 128.
145 * A modification can be made to the driver to remove this limit.
146 * This can be increased in the driver and here.
147 * Should be at least MIN_NB_BUF.
148 */
149#define NB_RX_MBUF 4096
150
151/* Number of send memory buffers to use.
152 * Same limits apply as those to NB_TX_MBUF.
153 */
154#define NB_TX_MBUF 1024
155
156/* The size of the PCI blacklist needs to be big enough to contain
157 * every PCI device address (listed by lspci every bus:device.function tuple).
158 */
159#define BLACK_LIST_SIZE 50
160
161/* The maximum number of characters the mempool name can be */
162#define MEMPOOL_NAME_LEN 20
163
164#define MBUF(x) ((struct rte_mbuf *) x)
165/* Get the original placement of the packet data */
166#define MBUF_PKTDATA(x) ((char *) x + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
167#define FORMAT(x) ((struct dpdk_format_data_t*)(x->format_data))
168#define PERPKT_FORMAT(x) ((struct dpdk_per_lcore_t*)(x->format_data))
169
170#define TV_TO_NS(tv) ((uint64_t) tv.tv_sec*1000000000ull + \
171                        (uint64_t) tv.tv_usec*1000ull)
172#define TS_TO_NS(ts) ((uint64_t) ts.tv_sec*1000000000ull + \
173                        (uint64_t) ts.tv_nsec)
174
175#if RTE_PKTMBUF_HEADROOM != 128
176#warning "RTE_PKT_MBUF_HEADROOM is not set to the default value of 128 - " \
177         "any libtrace instance processing these packet must be have the" \
178         "same RTE_PKTMBUF_HEADROOM set"
179#endif
180
181/* ~~~~~~~~~~~~~~~~~~~~~~ Advance settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
182 * THESE MAY REQUIRE MODIFICATIONS TO INTEL DPDK
183 *
184 * Make sure you understand what these are doing before enabling them.
185 * They might make traces incompatable with other builds etc.
186 *
187 * These are also included to show how to do somethings which aren't
188 * obvious in the DPDK documentation.
189 */
190
191/* Print verbose messages to stdout */
192#define DEBUG 1
193
194/* Use clock_gettime() for nanosecond resolution rather than gettimeofday()
195 * only turn on if you know clock_gettime is a vsyscall on your system
196 * overwise could be a large overhead. Again gettimeofday() should be
197 * vsyscall also if it's not you should seriously consider updating your
198 * kernel.
199 */
200#ifdef HAVE_LIBRT
201/* You can turn this on (set to 1) to prefer clock_gettime */
202#define USE_CLOCK_GETTIME 0
203#else
204/* DONT CHANGE THIS !!! */
205#define USE_CLOCK_GETTIME 0
206#endif
207
208/* This is fairly safe to turn on - currently there appears to be a 'bug'
209 * in DPDK that will remove the checksum by making the packet appear 4bytes
210 * smaller than what it really is. Most formats don't include the checksum
211 * hence writing out a port such as int: ring: and dpdk: assumes there
212 * is no checksum and will attempt to write the checksum as part of the
213 * packet
214 */
215#define GET_MAC_CRC_CHECKSUM 0
216
217/* This requires a modification of the pmd drivers (inside Intel DPDK)
218 */
219#define HAS_HW_TIMESTAMPS_82580 0
220
221#if HAS_HW_TIMESTAMPS_82580
222# define TS_NBITS_82580     40
223/* The maximum on the +ve or -ve side that we can be, make it half way */
224# define MAXSKEW_82580 ((uint64_t) (.5 * (double)(1ull<<TS_NBITS_82580)))
225#define WITHIN_VARIANCE(v1,v2,var) (((v1) - (var) < (v2)) && ((v1) + (var) > (v2)))
226#endif
227
228/* As per Intel 82580 specification - mismatch in 82580 datasheet
229 * it states ts is stored in Big Endian, however its actually Little */
230struct hw_timestamp_82580 {
231    uint64_t reserved;
232    uint64_t timestamp; /* Little Endian only lower 40 bits are valid */
233};
234
235enum paused_state {
236    DPDK_NEVER_STARTED,
237    DPDK_RUNNING,
238    DPDK_PAUSED,
239};
240
241struct dpdk_per_lcore_t
242{
243        // TODO move time stamp stuff here
244        uint16_t queue_id;
245        uint8_t port;
246};
247
248/* Used by both input and output however some fields are not used
249 * for output */
250struct dpdk_format_data_t {
251    int8_t promisc; /* promiscuous mode - RX only */
252    uint8_t port; /* Always 0 we only whitelist a single port - Shared TX & RX */
253    uint8_t nb_ports; /* Total number of usable ports on system should be 1 */
254    uint8_t paused; /* See paused_state */ 
255    uint16_t queue_id; /* Always 0 we use a single queue - Shared TX & RX */
256    int snaplen; /* The snap length for the capture - RX only */
257    /* We always have to setup both rx and tx queues even if we don't want them */
258    int nb_rx_buf; /* The number of packet buffers in the rx ring */
259    int nb_tx_buf; /* The number of packet buffers in the tx ring */
260    struct rte_mempool * pktmbuf_pool; /* Our packet memory pool */
261#if DPDK_USE_BLACKLIST
262    struct rte_pci_addr blacklist[BLACK_LIST_SIZE]; /* Holds our device blacklist */
263        unsigned int nb_blacklist; /* Number of blacklist items in are valid */
264#endif
265    char mempool_name[MEMPOOL_NAME_LEN]; /* The name of the mempool that we are using */
266    uint8_t rss_key[40]; // This is the RSS KEY
267#if HAS_HW_TIMESTAMPS_82580
268    /* Timestamping only relevent to RX */
269    uint64_t ts_first_sys; /* Sytem timestamp of the first packet in nanoseconds */
270    uint64_t ts_last_sys; /* System timestamp of our most recent packet in nanoseconds */
271    uint32_t wrap_count; /* Number of times the NIC clock has wrapped around completely */
272#endif
273        // DPDK normally seems to have a limit of 8 queues for a given card
274        struct dpdk_per_lcore_t per_lcore[RTE_MAX_LCORE];
275};
276
277enum dpdk_addt_hdr_flags {
278    INCLUDES_CHECKSUM = 0x1,
279    INCLUDES_HW_TIMESTAMP = 0x2, /* Used with 82580 driver */
280};
281
282/**
283 * A structure placed in front of the packet where we can store
284 * additional information about the given packet.
285 * +--------------------------+
286 * |       rte_mbuf (pkt)     | sizeof(rte_mbuf)
287 * +--------------------------+
288 * |           padding        | RTE_PKTMBUF_HEADROOM-1-sizeof(dpdk_addt_hdr)
289 * +--------------------------+
290 * |       dpdk_addt_hdr      | sizeof(dpdk_addt_hdr)
291 * +--------------------------+
292 * |   sizeof(dpdk_addt_hdr)  | 1 byte
293 * +--------------------------+
294 * *   hw_timestamp_82580     * 16 bytes Optional
295 * +--------------------------+
296 * |       Packet data        | Variable Size
297 * |                          |
298 */
299struct dpdk_addt_hdr {
300    uint64_t timestamp;
301    uint8_t flags;
302    uint8_t direction;
303    uint8_t reserved1;
304    uint8_t reserved2;
305    uint32_t cap_len; /* The size to say the capture is */
306};
307
308/**
309 * We want to blacklist all devices except those on the whitelist
310 * (I say list, but yes it is only the one).
311 *
312 * The default behaviour of rte_pci_probe() will map every possible device
313 * to its DPDK driver. The DPDK driver will take the ethernet device
314 * out of the kernel (i.e. no longer /dev/ethx) and cannot be used.
315 *
316 * So blacklist all devices except the one that we wish to use so that
317 * the others can still be used as standard ethernet ports.
318 *
319 * @return 0 if successful, otherwise -1 on error.
320 */
321#if DPDK_USE_BLACKLIST
322static int blacklist_devices(struct dpdk_format_data_t *format_data, struct rte_pci_addr *whitelist)
323{
324        struct rte_pci_device *dev = NULL;
325        format_data->nb_blacklist = 0;
326
327        memset(format_data->blacklist, 0, sizeof (format_data->blacklist));
328
329        TAILQ_FOREACH(dev, &device_list, next) {
330        if (whitelist != NULL && whitelist->domain == dev->addr.domain
331            && whitelist->bus == dev->addr.bus
332            && whitelist->devid == dev->addr.devid
333            && whitelist->function == dev->addr.function)
334            continue;
335                if (format_data->nb_blacklist >= sizeof (format_data->blacklist)
336                                / sizeof (format_data->blacklist[0])) {
337                        printf("Warning: too many devices to blacklist consider"
338                                        " increasing BLACK_LIST_SIZE");
339                        break;
340                }
341                format_data->blacklist[format_data->nb_blacklist] = dev->addr;
342                ++format_data->nb_blacklist;
343        }
344
345        rte_eal_pci_set_blacklist(format_data->blacklist, format_data->nb_blacklist);
346        return 0;
347}
348#else /* DPDK_USE_BLACKLIST */
349#include <rte_devargs.h>
350static int blacklist_devices(struct dpdk_format_data_t *format_data UNUSED, struct rte_pci_addr *whitelist)
351{
352        char pci_str[20] = {0};
353        snprintf(pci_str, sizeof(pci_str), PCI_PRI_FMT,
354                 whitelist->domain,
355                 whitelist->bus,
356                 whitelist->devid,
357                 whitelist->function);
358        if (rte_eal_devargs_add(RTE_DEVTYPE_WHITELISTED_PCI, pci_str) < 0) {
359                return -1;
360        }
361        return 0;
362}
363#endif
364
365/**
366 * Parse the URI format as a pci address
367 * Fills in addr, note core is optional and is unchanged if
368 * a value for it is not provided.
369 *
370 * i.e. ./libtrace dpdk:0:1:0.0 -> 0:1:0.0
371 * or ./libtrace dpdk:0:1:0.1-2 -> 0:1:0.1 (Using CPU core #2)
372 */
373static int parse_pciaddr(char * str, struct rte_pci_addr * addr, long * core) {
374    char * wrkstr;
375    char * pch;
376    assert(str);
377    wrkstr = strdup(str);
378   
379    pch = strtok(wrkstr,":");
380    if (pch == NULL || pch[0] == 0) {
381        free(wrkstr); return -1;
382    }
383    addr->domain = (uint16_t) atoi(pch);
384
385    pch = strtok(NULL,":");
386    if (pch == NULL || pch[0] == 0) {
387        free(wrkstr); return -1;
388    }
389    addr->bus = (uint8_t) atoi(pch);
390
391    pch = strtok(NULL,".");
392    if (pch == NULL || pch[0] == 0) {
393        free(wrkstr); return -1;
394    }
395    addr->devid = (uint8_t) atoi(pch);
396
397    pch = strtok(NULL,"-"); /* Might not find the '-' it's optional */
398    if (pch == NULL || pch[0] == 0) {
399        free(wrkstr); return -1;
400    }
401    addr->function = (uint8_t) atoi(pch);
402
403    pch = strtok(NULL, ""); /* Find end of string */
404   
405    if (pch != NULL && pch[0] != 0) {
406        *core = (long) atoi(pch);
407    }
408
409    free(wrkstr);
410    return 0;
411}
412
413#if DEBUG
414/* For debugging */
415static inline void dump_configuration()
416{
417    struct rte_config * global_config;
418    long nb_cpu = sysconf(_SC_NPROCESSORS_ONLN);
419   
420    if (nb_cpu <= 0) {
421        perror("sysconf(_SC_NPROCESSORS_ONLN) failed. Falling back to the first core.");
422        nb_cpu = 1; /* fallback to just 1 core */
423    }
424    if (nb_cpu > RTE_MAX_LCORE)
425        nb_cpu = RTE_MAX_LCORE;
426   
427    global_config = rte_eal_get_configuration();
428   
429    if (global_config != NULL) {
430        int i;
431        fprintf(stderr, "Intel DPDK setup\n"
432               "---Version      : %s\n"
433               "---Master LCore : %"PRIu32"\n"
434               "---LCore Count  : %"PRIu32"\n",
435               rte_version(),
436               global_config->master_lcore, global_config->lcore_count);
437       
438        for (i = 0 ; i < nb_cpu; i++) {
439            fprintf(stderr, "   ---Core %d : %s\n", i, 
440                   global_config->lcore_role[i] == ROLE_RTE ? "on" : "off");
441        }
442       
443        const char * proc_type;
444        switch (global_config->process_type) {
445            case RTE_PROC_AUTO:
446                proc_type = "auto";
447                break;
448            case RTE_PROC_PRIMARY:
449                proc_type = "primary";
450                break;
451            case RTE_PROC_SECONDARY:
452                proc_type = "secondary";
453                break;
454            case RTE_PROC_INVALID:
455                proc_type = "invalid";
456                break;
457            default:
458                proc_type = "something worse than invalid!!";
459        }
460        fprintf(stderr, "---Process Type : %s\n", proc_type);
461    }
462   
463}
464#endif
465
466/**
467 * Expects to be called from the master lcore and moves it to the given dpdk id
468 * @param core (zero indexed) If core is on the physical system affinity is bound otherwise
469 *               affinity is set to all cores. Must be less than RTE_MAX_LCORE
470 *               and not already in use.
471 * @return 0 is successful otherwise -1 on error.
472 */
473static inline int dpdk_move_master_lcore(size_t core) {
474    struct rte_config *cfg = rte_eal_get_configuration();
475    cpu_set_t cpuset;
476    int i;
477
478    assert (core < RTE_MAX_LCORE);
479    assert (rte_get_master_lcore() == rte_lcore_id());
480
481    if (core == rte_lcore_id())
482        return 0;
483
484    // Make sure we are not overwriting someone else
485    assert(!rte_lcore_is_enabled(core));
486
487    // Move the core
488    cfg->lcore_role[rte_lcore_id()] = ROLE_OFF;
489    cfg->lcore_role[core] = ROLE_RTE;
490    lcore_config[core].thread_id = lcore_config[rte_lcore_id()].thread_id;
491    rte_eal_get_configuration()->master_lcore = core;
492    RTE_PER_LCORE(_lcore_id) = core;
493
494    // Now change the affinity
495    CPU_ZERO(&cpuset);
496
497    if (lcore_config[core].detected) {
498        CPU_SET(core, &cpuset);
499    } else {
500        for (i = 0; i < RTE_MAX_LCORE; ++i) {
501            if (lcore_config[i].detected)
502                CPU_SET(i, &cpuset);
503        }
504    }
505
506    i = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
507    if (i != 0) {
508        // TODO proper libtrace style error here!!
509        fprintf(stderr, "pthread_setaffinity_np failed\n");
510        return -1;
511    }
512    return 0;
513}
514
515
516/**
517 * XXX This is very bad XXX
518 * But we have to do something to allow getopts nesting
519 * Luckly normally the format is last so it doesn't matter
520 * DPDK only supports modern systems so hopefully this
521 * will continue to work
522 */
523struct saved_getopts {
524        char *optarg;
525        int optind;
526        int opterr;
527        int optopt;
528};
529
530static void save_getopts(struct saved_getopts *opts) {
531        opts->optarg = optarg;
532        opts->optind = optind;
533        opts->opterr = opterr;
534        opts->optopt = optopt;
535}
536
537static void restore_getopts(struct saved_getopts *opts) {
538        optarg = opts->optarg;
539        optind = opts->optind;
540        opterr = opts->opterr;
541        optopt = opts->optopt;
542}
543
544static inline int dpdk_init_environment(char * uridata, struct dpdk_format_data_t * format_data,
545                                        char * err, int errlen) {
546    int ret; /* Returned error codes */
547    struct rte_pci_addr use_addr; /* The only address that we don't blacklist */   
548    char cpu_number[10] = {0}; /* The CPU mask we want to bind to */
549    char mem_map[20] = {0}; /* The memory name */
550    long nb_cpu; /* The number of CPUs in the system */
551    long my_cpu; /* The CPU number we want to bind to */
552    int i;
553    struct rte_config *cfg = rte_eal_get_configuration();
554        struct saved_getopts save_opts;
555   
556#if DEBUG
557    rte_set_log_level(RTE_LOG_DEBUG);
558#else
559    rte_set_log_level(RTE_LOG_WARNING);
560#endif
561    /*
562     * Using unique file prefixes mean separate memory is used, unlinking
563     * the two processes. However be careful we still cannot access a
564     * port that already in use.
565     *
566     * Using unique file prefixes mean separate memory is used, unlinking
567     * the two processes. However be careful we still cannot access a
568     * port that already in use.
569     */
570    char* argv[] = {"libtrace", "-c", cpu_number, "-n", "1", "--proc-type", "auto",
571                "--file-prefix", mem_map, "-m", "256", NULL};
572    int argc = sizeof(argv) / sizeof(argv[0]) - 1;
573   
574    /* This initialises the Environment Abstraction Layer (EAL)
575     * If we had slave workers these are put into WAITING state
576     *
577     * Basically binds this thread to a fixed core, which we choose as
578     * the last core on the machine (assuming fewer interrupts mapped here).
579     * "-c" controls the cpu mask 0x1=1st core 0x2=2nd 0x4=3rd and so on
580     * "-n" the number of memory channels into the CPU (hardware specific)
581     *      - Most likely to be half the number of ram slots in your machine.
582     *        We could count ram slots by "dmidecode -t 17 | grep -c 'Size:'"
583     * Controls where in memory packets are stored and should spread across
584     * the channels. We just use 1 to be safe.
585     */
586
587    /* Get the number of cpu cores in the system and use the last core */
588    nb_cpu = sysconf(_SC_NPROCESSORS_ONLN);
589    if (nb_cpu <= 0) {
590        perror("sysconf(_SC_NPROCESSORS_ONLN) failed. Falling back to the first core.");
591        nb_cpu = 1; /* fallback to the first core */
592    }
593    if (nb_cpu > RTE_MAX_LCORE)
594        nb_cpu = RTE_MAX_LCORE;
595
596    my_cpu = nb_cpu;
597    /* This allows the user to specify the core - we would try to do this
598     * automatically but it's hard to tell that this is secondary
599     * before running rte_eal_init(...). Currently we are limited to 1
600     * instance per core due to the way memory is allocated. */
601    if (parse_pciaddr(uridata, &use_addr, &my_cpu) != 0) {
602        snprintf(err, errlen, "Failed to parse URI");
603        return -1;
604    }
605
606    snprintf(format_data->mempool_name, MEMPOOL_NAME_LEN,
607                "libtrace_pool_%"PRIu32, (uint32_t) nb_cpu);
608
609    if (!(my_cpu > 0 && my_cpu <= nb_cpu)) {
610        snprintf(err, errlen, 
611          "Intel DPDK - User defined a bad CPU number %"PRIu32" must be"
612          " between 1 and %"PRIu32, (uint32_t) my_cpu, (uint32_t) nb_cpu);
613        return -1;
614    }
615
616    /* Make our mask with all cores turned on this is so that DPDK to gets CPU
617       info older versions */
618    snprintf(cpu_number, sizeof(cpu_number), "%x", ~(UINT32_MAX<<MIN(31, nb_cpu)));
619    //snprintf(cpu_number, sizeof(cpu_number), "%x", 0x1 << (my_cpu - 1));
620
621
622        /* Give the memory map a unique name */
623        snprintf(mem_map, sizeof(mem_map), "libtrace-%d", (int) getpid());
624    /* rte_eal_init it makes a call to getopt so we need to reset the
625     * global optind variable of getopt otherwise this fails */
626        save_getopts(&save_opts);
627    optind = 1;
628    if ((ret = rte_eal_init(argc, argv)) < 0) {
629        snprintf(err, errlen, 
630          "Intel DPDK - Initialisation of EAL failed: %s", strerror(-ret));
631        return -1;
632    }
633        restore_getopts(&save_opts);
634    // These are still running but will never do anything with DPDK v1.7 we
635    // should remove this XXX in the future
636    for(i = 0; i < RTE_MAX_LCORE; ++i) {
637        if (rte_lcore_is_enabled(i) && i != rte_get_master_lcore()) {
638            cfg->lcore_role[i] = ROLE_OFF;
639            cfg->lcore_count--;
640        }
641    }
642    // Only the master should be running
643    assert(cfg->lcore_count == 1);
644
645    dpdk_move_master_lcore(my_cpu-1);
646
647#if DEBUG
648    dump_configuration();
649#endif
650
651#if DPDK_USE_PMD_INIT
652    /* This registers all available NICs with Intel DPDK
653     * These are not loaded until rte_eal_pci_probe() is called.
654     */
655    if ((ret = rte_pmd_init_all()) < 0) {
656        snprintf(err, errlen, 
657          "Intel DPDK - rte_pmd_init_all failed: %s", strerror(-ret));
658        return -1;
659    }
660#endif
661
662    /* Black list all ports besides the one that we want to use */
663        if ((ret = blacklist_devices(format_data, &use_addr)) < 0) {
664                snprintf(err, errlen, "Intel DPDK - Whitelisting PCI device failed,"
665                         " are you sure the address is correct?: %s", strerror(-ret));
666                return -1;
667        }
668
669    /* This loads DPDK drivers against all ports that are not blacklisted */
670        if ((ret = rte_eal_pci_probe()) < 0) {
671        snprintf(err, errlen, 
672            "Intel DPDK - rte_eal_pci_probe failed: %s", strerror(-ret));
673        return -1;
674    }
675
676    format_data->nb_ports = rte_eth_dev_count();
677
678    if (format_data->nb_ports != 1) {
679        snprintf(err, errlen, 
680            "Intel DPDK - rte_eth_dev_count returned %d but it should be 1",
681            format_data->nb_ports);
682        return -1;
683    }
684   
685    struct rte_eth_dev_info dev_info;
686    rte_eth_dev_info_get(0, &dev_info);
687    printf("Device port=0\n\tmin_rx_bufsize=%d\n\tmax_rx_pktlen=%d\n\tmax rx queues=%d\n\tmax tx queues=%d", 
688                (int) dev_info.min_rx_bufsize, (int) dev_info.max_rx_pktlen, (int) dev_info.max_rx_queues, (int) dev_info.max_tx_queues);
689
690    return 0;
691}
692
693static int dpdk_init_input (libtrace_t *libtrace) {
694    char err[500];
695    err[0] = 0;
696   
697    libtrace->format_data = (struct dpdk_format_data_t *)
698                            malloc(sizeof(struct dpdk_format_data_t));
699    FORMAT(libtrace)->port = 0; /* Always assume 1 port loaded */
700    FORMAT(libtrace)->queue_id = 0; /* Single queue per port */
701    FORMAT(libtrace)->nb_ports = 0;
702    FORMAT(libtrace)->snaplen = 0; /* Use default */
703    FORMAT(libtrace)->nb_rx_buf = NB_RX_MBUF;
704    FORMAT(libtrace)->nb_tx_buf = MIN_NB_BUF;
705    FORMAT(libtrace)->promisc = -1;
706    FORMAT(libtrace)->pktmbuf_pool = NULL;
707#if DPDK_USE_BLACKLIST
708    FORMAT(libtrace)->nb_blacklist = 0;
709#endif
710    FORMAT(libtrace)->paused = DPDK_NEVER_STARTED;
711    FORMAT(libtrace)->mempool_name[0] = 0;
712#if HAS_HW_TIMESTAMPS_82580
713    FORMAT(libtrace)->ts_first_sys = 0;
714    FORMAT(libtrace)->ts_last_sys = 0;
715    FORMAT(libtrace)->wrap_count = 0;
716#endif
717       
718    if (dpdk_init_environment(libtrace->uridata, FORMAT(libtrace), err, sizeof(err)) != 0) {
719        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
720        free(libtrace->format_data);
721        libtrace->format_data = NULL;
722        return -1;
723    }
724    return 0;
725};
726
727static int dpdk_init_output(libtrace_out_t *libtrace)
728{
729    char err[500];
730    err[0] = 0;
731   
732    libtrace->format_data = (struct dpdk_format_data_t *)
733                            malloc(sizeof(struct dpdk_format_data_t));
734    FORMAT(libtrace)->port = 0; /* Always assume 1 port loaded */
735    FORMAT(libtrace)->queue_id = 0; /* Single queue per port */
736    FORMAT(libtrace)->nb_ports = 0;
737    FORMAT(libtrace)->snaplen = 0; /* Use default */
738    FORMAT(libtrace)->nb_rx_buf = MIN_NB_BUF;
739    FORMAT(libtrace)->nb_tx_buf = NB_TX_MBUF;
740    FORMAT(libtrace)->promisc = -1;
741    FORMAT(libtrace)->pktmbuf_pool = NULL;
742#if DPDK_USE_BLACKLIST
743    FORMAT(libtrace)->nb_blacklist = 0;
744#endif
745    FORMAT(libtrace)->paused = DPDK_NEVER_STARTED;
746    FORMAT(libtrace)->mempool_name[0] = 0;
747#if HAS_HW_TIMESTAMPS_82580
748    FORMAT(libtrace)->ts_first_sys = 0;
749    FORMAT(libtrace)->ts_last_sys = 0;
750    FORMAT(libtrace)->wrap_count = 0;
751#endif
752
753    if (dpdk_init_environment(libtrace->uridata, FORMAT(libtrace), err, sizeof(err)) != 0) {
754        trace_set_err_out(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
755        free(libtrace->format_data);
756        libtrace->format_data = NULL;
757        return -1;
758    }
759    return 0;
760};
761
762static int dpdk_pconfig_input (libtrace_t *libtrace,
763                                trace_parallel_option_t option,
764                                void *data) {
765        switch (option) {
766                case TRACE_OPTION_SET_HASHER:
767                        switch (*((enum hasher_types *) data))
768                        {
769                                case HASHER_BALANCE:
770                                case HASHER_UNIDIRECTIONAL:
771                                        toeplitz_create_unikey(FORMAT(libtrace)->rss_key);
772                                        return 0;
773                                case HASHER_BIDIRECTIONAL:
774                                        toeplitz_create_bikey(FORMAT(libtrace)->rss_key);
775                                        return 0;
776                                case HASHER_HARDWARE:
777                                case HASHER_CUSTOM:
778                                        // We don't support these
779                                        return -1;
780                        }
781        break;
782        }
783        return -1;
784}
785/**
786 * Note here snaplen excludes the MAC checksum. Packets over
787 * the requested snaplen will be dropped. (Excluding MAC checksum)
788 *
789 * I.e the maximum size of a standard ethernet packet is 1518 (Including MAC checksum)
790 * So to allow packets upto 1518 this would be set to 1514 and if GET_MAC_CRC_CHECKSUM
791 * is set the maximum size of the returned packet would be 1518 otherwise
792 * 1514 would be the largest size possibly returned.
793 *
794 */
795static int dpdk_config_input (libtrace_t *libtrace,
796                                        trace_option_t option,
797                                        void *data) {
798    switch (option) {
799        case TRACE_OPTION_SNAPLEN:
800            /* Only support changing snaplen before a call to start is
801             * made */
802            if (FORMAT(libtrace)->paused == DPDK_NEVER_STARTED)
803                FORMAT(libtrace)->snaplen=*(int*)data;
804            else
805                return -1;
806            return 0;
807                case TRACE_OPTION_PROMISC:
808                        FORMAT(libtrace)->promisc=*(int*)data;
809            return 0;
810        case TRACE_OPTION_FILTER:
811            /* TODO filtering */
812            break;
813        case TRACE_OPTION_META_FREQ:
814            break;
815        case TRACE_OPTION_EVENT_REALTIME:
816            break;
817        /* Avoid default: so that future options will cause a warning
818         * here to remind us to implement it, or flag it as
819         * unimplementable
820         */
821    }
822
823        /* Don't set an error - trace_config will try to deal with the
824         * option and will set an error if it fails */
825    return -1;
826}
827
828/* Can set jumbo frames/ or limit the size of a frame by setting both
829 * max_rx_pkt_len and jumbo_frame. This can be limited to less than
830 *
831 */
832static struct rte_eth_conf port_conf = {
833        .rxmode = {
834                .mq_mode = ETH_RSS,
835                .split_hdr_size = 0,
836                .header_split   = 0, /**< Header Split disabled */
837                .hw_ip_checksum = 0, /**< IP checksum offload disabled */
838                .hw_vlan_filter = 0, /**< VLAN filtering disabled */
839                .jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
840        .max_rx_pkt_len = 0, /**< Max frame Size if Jumbo enabled */
841#if GET_MAC_CRC_CHECKSUM
842/* So it appears that if hw_strip_crc is turned off the driver will still
843 * take this off. See line 955ish in lib/librte_pmd_e1000/igb_rxtx.c.
844 * So if .hw_strip_crc=0 a valid CRC exists 4 bytes after the end of the
845 * So lets just add it back on when we receive the packet.
846 */
847                .hw_strip_crc   = 0, /**< CRC stripped by hardware */
848#else
849/* By default strip the MAC checksum because it's a bit of a hack to
850 * actually read these. And don't want to rely on disabling this to actualy
851 * always cut off the checksum in the future
852 */
853        .hw_strip_crc   = 1, /**< CRC stripped by hardware */
854#endif
855        },
856        .txmode = {
857                .mq_mode = ETH_DCB_NONE,
858        },
859        .rx_adv_conf = {
860                .rss_conf = {
861                        // .rss_key = &rss_key, // We set this per format
862                        .rss_hf = ETH_RSS_IPV4_UDP | ETH_RSS_IPV6 | ETH_RSS_IPV4 | ETH_RSS_IPV4_TCP | ETH_RSS_IPV6_TCP | ETH_RSS_IPV6_UDP,
863                },
864        },
865};
866
867static const struct rte_eth_rxconf rx_conf = {
868        .rx_thresh = {
869                .pthresh = 8,/* RX_PTHRESH prefetch */
870                .hthresh = 8,/* RX_HTHRESH host */
871                .wthresh = 4,/* RX_WTHRESH writeback */
872        },
873    .rx_free_thresh = 0,
874    .rx_drop_en = 0, /* Drop packets oldest packets if out of space */
875};
876
877static const struct rte_eth_txconf tx_conf = {
878        .tx_thresh = {
879        /**
880         * TX_PTHRESH prefetch
881         * Set on the NIC, if the number of unprocessed descriptors to queued on
882         * the card fall below this try grab at least hthresh more unprocessed
883         * descriptors.
884         */
885                .pthresh = 36,
886
887        /* TX_HTHRESH host
888         * Set on the NIC, the batch size to prefetch unprocessed tx descriptors.
889         */
890                .hthresh = 0,
891       
892        /* TX_WTHRESH writeback
893         * Set on the NIC, the number of sent descriptors before writing back
894         * status to confirm the transmission. This is done more efficiently as
895         * a bulk DMA-transfer rather than writing one at a time.
896         * Similar to tx_free_thresh however this is applied to the NIC, where
897         * as tx_free_thresh is when DPDK will check these. This is extended
898         * upon by tx_rs_thresh (10Gbit cards) which doesn't write all
899         * descriptors rather only every n'th item, reducing DMA memory bandwidth.
900         */
901                .wthresh = 4,
902        },
903
904    /* Used internally by DPDK rather than passed to the NIC. The number of
905     * packet descriptors to send before checking for any responses written
906     * back (to confirm the transmission). Default = 32 if set to 0)
907     */
908        .tx_free_thresh = 0,
909
910    /* This is the Report Status threshold, used by 10Gbit cards,
911     * This signals the card to only write back status (such as
912     * transmission successful) after this minimum number of transmit
913     * descriptors are seen. The default is 32 (if set to 0) however if set
914     * to greater than 1 TX wthresh must be set to zero, because this is kindof
915     * a replacement. See the dpdk programmers guide for more restrictions.
916     */
917        .tx_rs_thresh = 1,
918};
919
920/* Attach memory to the port and start the port or restart the port.
921 */
922static int dpdk_start_port (struct dpdk_format_data_t * format_data, char *err, int errlen){
923    int ret; /* Check return values for errors */
924    struct rte_eth_link link_info; /* Wait for link */
925   
926    /* Already started */
927    if (format_data->paused == DPDK_RUNNING)
928        return 0;
929
930    /* First time started we need to alloc our memory, doing this here
931     * rather than in environment setup because we don't have snaplen then */
932    if (format_data->paused == DPDK_NEVER_STARTED) {
933        if (format_data->snaplen == 0) {
934            format_data->snaplen = RX_MBUF_SIZE;
935            port_conf.rxmode.jumbo_frame = 0;
936            port_conf.rxmode.max_rx_pkt_len = 0;
937        } else {
938            /* Use jumbo frames */
939            port_conf.rxmode.jumbo_frame = 1;
940            port_conf.rxmode.max_rx_pkt_len = format_data->snaplen;
941        }
942
943        /* This is additional overhead so make sure we allow space for this */
944#if GET_MAC_CRC_CHECKSUM
945        format_data->snaplen += ETHER_CRC_LEN;
946#endif
947#if HAS_HW_TIMESTAMPS_82580
948        format_data->snaplen += sizeof(struct hw_timestamp_82580);
949#endif
950
951        /* Create the mbuf pool, which is the place our packets are allocated
952         * from - TODO figure out if there is is a free function (I cannot see one)
953         * NOTE: RX queue requires nb_packets + 1 otherwise it fails to
954         * allocate however that extra 1 packet is not used.
955         * (I assume <= vs < error some where in DPDK code)
956         * TX requires nb_tx_buffers + 1 in the case the queue is full
957         * so that will fill the new buffer and wait until slots in the
958         * ring become available.
959         */
960#if DEBUG
961    fprintf(stderr, "Creating mempool named %s\n", format_data->mempool_name);
962#endif
963        format_data->pktmbuf_pool =
964            rte_mempool_create(format_data->mempool_name,
965                       format_data->nb_rx_buf + format_data->nb_tx_buf + 1,
966                       format_data->snaplen + sizeof(struct rte_mbuf) 
967                                        + RTE_PKTMBUF_HEADROOM,
968                       8, sizeof(struct rte_pktmbuf_pool_private),
969                       rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
970                       0, MEMPOOL_F_SP_PUT | MEMPOOL_F_SC_GET);
971
972        if (format_data->pktmbuf_pool == NULL) {
973            snprintf(err, errlen, "Intel DPDK - Initialisation of mbuf "
974                        "pool failed: %s", strerror(rte_errno));
975            return -1;
976        }
977    }
978   
979    /* ----------- Now do the setup for the port mapping ------------ */
980    /* Order of calls must be
981     * rte_eth_dev_configure()
982     * rte_eth_tx_queue_setup()
983     * rte_eth_rx_queue_setup()
984     * rte_eth_dev_start()
985     * other rte_eth calls
986     */
987   
988   
989    port_conf.rx_adv_conf.rss_conf.rss_key = format_data->rss_key;
990   
991    /* This must be called first before another *eth* function
992     * 1 rx, 1 tx queue, port_conf sets checksum stripping etc */
993    ret = rte_eth_dev_configure(format_data->port, 1, 1, &port_conf);
994    if (ret < 0) {
995        snprintf(err, errlen, "Intel DPDK - Cannot configure device port"
996                            " %"PRIu8" : %s", format_data->port,
997                            strerror(-ret));
998        return -1;
999    }
1000    /* Initialise the TX queue a minimum value if using this port for
1001     * receiving. Otherwise a larger size if writing packets.
1002     */
1003    ret = rte_eth_tx_queue_setup(format_data->port, format_data->queue_id,
1004                        format_data->nb_tx_buf, SOCKET_ID_ANY, &tx_conf);
1005    if (ret < 0) {
1006        snprintf(err, errlen, "Intel DPDK - Cannot configure TX queue on port"
1007                            " %"PRIu8" : %s", format_data->port,
1008                            strerror(-ret));
1009        return -1;
1010    }
1011    /* Initialise the RX queue with some packets from memory */
1012    ret = rte_eth_rx_queue_setup(format_data->port, format_data->queue_id,
1013                            format_data->nb_rx_buf, SOCKET_ID_ANY, 
1014                            &rx_conf, format_data->pktmbuf_pool);
1015    if (ret < 0) {
1016        snprintf(err, errlen, "Intel DPDK - Cannot configure RX queue on port"
1017                    " %"PRIu8" : %s", format_data->port,
1018                    strerror(-ret));
1019        return -1;
1020    }
1021   
1022    /* Start device */
1023    ret = rte_eth_dev_start(format_data->port);
1024    if (ret < 0) {
1025        snprintf(err, errlen, "Intel DPDK - rte_eth_dev_start failed : %s",
1026                    strerror(-ret));
1027        return -1;
1028    }
1029
1030    /* Default promiscuous to on */
1031    if (format_data->promisc == -1)
1032        format_data->promisc = 1;
1033   
1034    if (format_data->promisc == 1)
1035        rte_eth_promiscuous_enable(format_data->port);
1036    else
1037        rte_eth_promiscuous_disable(format_data->port);
1038   
1039    /* Wait for the link to come up */
1040    rte_eth_link_get(format_data->port, &link_info);
1041#if DEBUG
1042    fprintf(stderr, "Link status is %d %d %d\n", (int) link_info.link_status,
1043            (int) link_info.link_duplex, (int) link_info.link_speed);
1044#endif
1045
1046    /* We have now successfully started/unpaused */
1047    format_data->paused = DPDK_RUNNING;
1048   
1049    return 0;
1050}
1051
1052/* Attach memory to the port and start (or restart) the port/s.
1053 */
1054static int dpdk_start_port_queues (libtrace_t *libtrace, struct dpdk_format_data_t *format_data, char *err, int errlen, uint16_t rx_queues){
1055    int ret, i; /* Check return values for errors */
1056    struct rte_eth_link link_info; /* Wait for link */
1057   
1058    /* Already started */
1059    if (format_data->paused == DPDK_RUNNING)
1060        return 0;
1061
1062    /* First time started we need to alloc our memory, doing this here
1063     * rather than in environment setup because we don't have snaplen then */
1064    if (format_data->paused == DPDK_NEVER_STARTED) {
1065        if (format_data->snaplen == 0) {
1066            format_data->snaplen = RX_MBUF_SIZE;
1067            port_conf.rxmode.jumbo_frame = 0;
1068            port_conf.rxmode.max_rx_pkt_len = 0;
1069        } else {
1070            /* Use jumbo frames */
1071            port_conf.rxmode.jumbo_frame = 1;
1072            port_conf.rxmode.max_rx_pkt_len = format_data->snaplen;
1073        }
1074
1075        /* This is additional overhead so make sure we allow space for this */
1076#if GET_MAC_CRC_CHECKSUM
1077        format_data->snaplen += ETHER_CRC_LEN;
1078#endif
1079#if HAS_HW_TIMESTAMPS_82580
1080        format_data->snaplen += sizeof(struct hw_timestamp_82580);
1081#endif
1082
1083        /* Create the mbuf pool, which is the place our packets are allocated
1084         * from - TODO figure out if there is is a free function (I cannot see one)
1085         * NOTE: RX queue requires nb_packets + 1 otherwise it fails to
1086         * allocate however that extra 1 packet is not used.
1087         * (I assume <= vs < error some where in DPDK code)
1088         * TX requires nb_tx_buffers + 1 in the case the queue is full
1089         * so that will fill the new buffer and wait until slots in the
1090         * ring become available.
1091         */
1092#if DEBUG
1093    printf("Creating mempool named %s\n", format_data->mempool_name);
1094#endif
1095        format_data->pktmbuf_pool =
1096            rte_mempool_create(format_data->mempool_name,
1097                       format_data->nb_rx_buf*rx_queues + format_data->nb_tx_buf + 1,
1098                       format_data->snaplen + sizeof(struct rte_mbuf) 
1099                                        + RTE_PKTMBUF_HEADROOM,
1100                       8, sizeof(struct rte_pktmbuf_pool_private),
1101                       rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
1102                       0, MEMPOOL_F_SP_PUT | MEMPOOL_F_SC_GET);
1103
1104        if (format_data->pktmbuf_pool == NULL) {
1105            snprintf(err, errlen, "Intel DPDK - Initialisation of mbuf "
1106                        "pool failed: %s", strerror(rte_errno));
1107            return -1;
1108        }
1109    }
1110   
1111    /* ----------- Now do the setup for the port mapping ------------ */
1112    /* Order of calls must be
1113     * rte_eth_dev_configure()
1114     * rte_eth_tx_queue_setup()
1115     * rte_eth_rx_queue_setup()
1116     * rte_eth_dev_start()
1117     * other rte_eth calls
1118     */
1119   
1120    /* This must be called first before another *eth* function
1121     * 1 rx, 1 tx queue, port_conf sets checksum stripping etc */
1122    ret = rte_eth_dev_configure(format_data->port, rx_queues, 1, &port_conf);
1123    if (ret < 0) {
1124        snprintf(err, errlen, "Intel DPDK - Cannot configure device port"
1125                            " %"PRIu8" : %s", format_data->port,
1126                            strerror(-ret));
1127        return -1;
1128    }
1129#if DEBUG
1130    printf("Doing dev configure\n");
1131#endif
1132    /* Initialise the TX queue a minimum value if using this port for
1133     * receiving. Otherwise a larger size if writing packets.
1134     */
1135    ret = rte_eth_tx_queue_setup(format_data->port, format_data->queue_id,
1136                        format_data->nb_tx_buf, SOCKET_ID_ANY, &tx_conf);
1137    if (ret < 0) {
1138        snprintf(err, errlen, "Intel DPDK - Cannot configure TX queue on port"
1139                            " %"PRIu8" : %s", format_data->port,
1140                            strerror(-ret));
1141        return -1;
1142    }
1143   
1144    for (i=0; i < rx_queues; i++) {
1145#if DEBUG
1146    printf("Doing queue configure\n");
1147#endif 
1148                /* Initialise the RX queue with some packets from memory */
1149                ret = rte_eth_rx_queue_setup(format_data->port, i,
1150                                                                format_data->nb_rx_buf, SOCKET_ID_ANY,
1151                                                                &rx_conf, format_data->pktmbuf_pool);
1152        /* Init per_thread data structures */
1153        format_data->per_lcore[i].port = format_data->port;
1154        format_data->per_lcore[i].queue_id = i;
1155
1156                if (ret < 0) {
1157                        snprintf(err, errlen, "Intel DPDK - Cannot configure RX queue on port"
1158                                                " %"PRIu8" : %s", format_data->port,
1159                                                strerror(-ret));
1160                        return -1;
1161                }
1162        }
1163   
1164#if DEBUG
1165    fprintf(stderr, "Doing start device\n");
1166#endif 
1167    /* Start device */
1168    ret = rte_eth_dev_start(format_data->port);
1169#if DEBUG
1170    fprintf(stderr, "Done start device\n");
1171#endif 
1172    if (ret < 0) {
1173        snprintf(err, errlen, "Intel DPDK - rte_eth_dev_start failed : %s",
1174                    strerror(-ret));
1175        return -1;
1176    }
1177
1178
1179    /* Default promiscuous to on */
1180    if (format_data->promisc == -1)
1181        format_data->promisc = 1;
1182   
1183    if (format_data->promisc == 1)
1184        rte_eth_promiscuous_enable(format_data->port);
1185    else
1186        rte_eth_promiscuous_disable(format_data->port);
1187   
1188   
1189    /* We have now successfully started/unpased */
1190    format_data->paused = DPDK_RUNNING;
1191   
1192    // Can use remote launch for all
1193    /*RTE_LCORE_FOREACH_SLAVE(i) {
1194                rte_eal_remote_launch(perpkt_threads_entry, (void *)libtrace, i);
1195        }*/
1196   
1197    /* Wait for the link to come up */
1198    rte_eth_link_get(format_data->port, &link_info);
1199#if DEBUG
1200    fprintf(stderr, "Link status is %d %d %d\n", (int) link_info.link_status,
1201            (int) link_info.link_duplex, (int) link_info.link_speed);
1202#endif
1203
1204    return 0;
1205}
1206
1207static int dpdk_start_input (libtrace_t *libtrace) {
1208    char err[500];
1209    err[0] = 0;
1210
1211    if (dpdk_start_port(FORMAT(libtrace), err, sizeof(err)) != 0) {
1212        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
1213        free(libtrace->format_data);
1214        libtrace->format_data = NULL;
1215        return -1;
1216    }
1217    return 0;
1218}
1219
1220static inline size_t dpdk_get_max_rx_queues (uint8_t port_id) {
1221    struct rte_eth_dev_info dev_info;
1222    rte_eth_dev_info_get(port_id, &dev_info);
1223    return dev_info.max_rx_queues;
1224}
1225
1226static inline size_t dpdk_processor_count () {
1227    long nb_cpu = sysconf(_SC_NPROCESSORS_ONLN);
1228    if (nb_cpu <= 0)
1229        return 1;
1230    else
1231        return (size_t) nb_cpu;
1232}
1233
1234static int dpdk_pstart_input (libtrace_t *libtrace) {
1235    char err[500];
1236    int i=0, phys_cores=0;
1237    int tot = libtrace->perpkt_thread_count;
1238    err[0] = 0;
1239
1240    if (rte_lcore_id() != rte_get_master_lcore())
1241        fprintf(stderr, "Warning dpdk_pstart_input should be called from the master DPDK thread!\n");
1242
1243    // If the master is not on the last thread we move it there
1244    if (rte_get_master_lcore() != RTE_MAX_LCORE - 1) {
1245        // Consider error handling here
1246        dpdk_move_master_lcore(RTE_MAX_LCORE - 1) == -1;
1247    }
1248
1249    // Don't exceed the number of cores in the system/detected by dpdk
1250    // We don't have to force this but performance wont be good if we don't
1251    for (i = 0; i < RTE_MAX_LCORE; ++i) {
1252        if (lcore_config[i].detected) {
1253            if (rte_lcore_is_enabled(i))
1254                fprintf(stderr, "Found core %d already in use!\n", i);
1255            else
1256                phys_cores++;
1257        }
1258    }
1259
1260        tot = MIN(libtrace->perpkt_thread_count, dpdk_get_max_rx_queues(FORMAT(libtrace)->port));
1261    tot = MIN(tot, phys_cores);
1262
1263        fprintf(stderr, "Running pstart DPDK tot=%d req=%d phys=%d\n", tot, libtrace->perpkt_thread_count, phys_cores);
1264       
1265    if (dpdk_start_port_queues(libtrace, FORMAT(libtrace), err, sizeof(err), tot) != 0) {
1266        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
1267        free(libtrace->format_data);
1268        libtrace->format_data = NULL;
1269        return -1;
1270    }
1271
1272    // Make sure we only start the number that we should
1273    libtrace->perpkt_thread_count = tot;
1274    return 0;
1275}
1276
1277
1278/**
1279 * Register a thread with the DPDK system,
1280 * When we start DPDK in parallel libtrace we move the 'main thread' to the
1281 * MAXIMUM CPU core slot (32) and remove any affinity restrictions DPDK
1282 * gives it.
1283 *
1284 * We then allow a mapper thread to be started on every real core as DPDK would
1285 * we also bind these to the corresponding CPU cores.
1286 *
1287 * @param libtrace A pointer to the trace
1288 * @param reading True if the thread will be used to read packets, i.e. will
1289 *                call pread_packet(), false if thread used to process packet
1290 *                in any other manner including statistics functions.
1291 */
1292static int dpdk_pregister_thread(libtrace_t *libtrace, libtrace_thread_t *t, bool reading)
1293{
1294    struct rte_config *cfg = rte_eal_get_configuration();
1295    int i;
1296    int new_id = -1;
1297
1298    // If 'reading packets' fill in cores from 0 up and bind affinity
1299    // otherwise start from the MAX core (which is also the master) and work backwards
1300    // in this case physical cores on the system will not exist so we don't bind
1301    // these to any particular physical core
1302    if (reading) {
1303        for (i = 0; i < RTE_MAX_LCORE; ++i) {
1304            if (!rte_lcore_is_enabled(i)) {
1305                new_id = i;
1306                if (!lcore_config[i].detected)
1307                    fprintf(stderr, "Warning the number of 'reading' threads exceed cores on machine!!\n");
1308                break;
1309            }
1310        }
1311    } else {
1312        for (i = RTE_MAX_LCORE-1; i >= 0; --i) {
1313            if (!rte_lcore_is_enabled(i)) {
1314                new_id = i;
1315                break;
1316            }
1317        }
1318    }
1319
1320    if (new_id == -1) {
1321        assert(cfg->lcore_count == RTE_MAX_LCORE);
1322        // TODO proper libtrace style error here!!
1323        fprintf(stderr, "Too many threads for DPDK!!\n");
1324        return -1;
1325    }
1326
1327    // Enable the core in global DPDK structs
1328    cfg->lcore_role[new_id] = ROLE_RTE;
1329    cfg->lcore_count++;
1330    // Set TLS to reflect our new number
1331    assert(rte_lcore_id() == 0); // I think new threads are going get a default thread number of 0
1332    fprintf(stderr, "original id%d", rte_lcore_id());
1333    RTE_PER_LCORE(_lcore_id) = new_id;
1334    fprintf(stderr, " new id%d\n", rte_lcore_id());
1335
1336    if (reading) {
1337        // Set affinity bind to corresponding core
1338        cpu_set_t cpuset;
1339        CPU_ZERO(&cpuset);
1340        CPU_SET(rte_lcore_id(), &cpuset);
1341        i = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
1342        if (i != 0) {
1343            fprintf(stderr, "Warning pthread_setaffinity_np failed\n");
1344            return -1;
1345        }
1346    }
1347
1348    // Map our TLS to the thread data
1349    if (reading) {
1350        if(t->type == THREAD_PERPKT) {
1351            t->format_data = &FORMAT(libtrace)->per_lcore[t->perpkt_num];
1352        } else {
1353            t->format_data = &FORMAT(libtrace)->per_lcore[0];
1354        }
1355    }
1356}
1357
1358
1359/**
1360 * Unregister a thread with the DPDK system.
1361 *
1362 * Only previously registered threads should be calling this just before
1363 * they are destroyed.
1364 */
1365static int dpdk_punregister_thread(libtrace_t libtrace, libtrace_thread_t *t UNUSED)
1366{
1367    struct rte_config *cfg = rte_eal_get_configuration();
1368
1369    assert(rte_lcore_id() >= 0 && rte_lcore_id() < RTE_MAX_LCORE);
1370
1371    // Skip if master!!
1372    if (rte_lcore_id() == rte_get_master_lcore()) {
1373        fprintf(stderr, "INFO: we are skipping unregistering the master lcore\n");
1374        return 0;
1375    }
1376
1377    // Disable this core in global DPDK structs
1378    cfg->lcore_role[rte_lcore_id()] = ROLE_OFF;
1379    cfg->lcore_count--;
1380    RTE_PER_LCORE(_lcore_id) = -1; // Might make the world burn if used again
1381    assert(cfg->lcore_count >= 1); // We cannot unregister the master LCORE!!
1382    return 0;
1383}
1384
1385static int dpdk_start_output(libtrace_out_t *libtrace)
1386{
1387    char err[500];
1388    err[0] = 0;
1389   
1390    if (dpdk_start_port(FORMAT(libtrace), err, sizeof(err)) != 0) {
1391        trace_set_err_out(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
1392        free(libtrace->format_data);
1393        libtrace->format_data = NULL;
1394        return -1;
1395    }
1396    return 0;
1397}
1398
1399static int dpdk_pause_input(libtrace_t * libtrace){
1400    /* This stops the device, but can be restarted using rte_eth_dev_start() */
1401    if (FORMAT(libtrace)->paused == DPDK_RUNNING) {
1402#if DEBUG     
1403        fprintf(stderr, "Pausing port\n");
1404#endif
1405        rte_eth_dev_stop(FORMAT(libtrace)->port);
1406        FORMAT(libtrace)->paused = DPDK_PAUSED;
1407        /* If we pause it the driver will be reset and likely our counter */
1408#if HAS_HW_TIMESTAMPS_82580
1409        FORMAT(libtrace)->ts_first_sys = 0;
1410        FORMAT(libtrace)->ts_last_sys = 0;
1411#endif
1412    }
1413    return 0;
1414}
1415
1416static int dpdk_write_packet(libtrace_out_t *trace, 
1417                libtrace_packet_t *packet){
1418    struct rte_mbuf* m_buff[1];
1419   
1420    int wirelen = trace_get_wire_length(packet);
1421    int caplen = trace_get_capture_length(packet);
1422   
1423    /* Check for a checksum and remove it */
1424    if (trace_get_link_type(packet) == TRACE_TYPE_ETH &&
1425                                            wirelen == caplen)
1426        caplen -= ETHER_CRC_LEN;
1427
1428    m_buff[0] = rte_pktmbuf_alloc(FORMAT(trace)->pktmbuf_pool);
1429    if (m_buff[0] == NULL) {
1430        trace_set_err_out(trace, errno, "Cannot get an empty packet buffer");
1431        return -1;
1432    } else {
1433        int ret;
1434        memcpy(rte_pktmbuf_append(m_buff[0], caplen), packet->payload, caplen);
1435        do {
1436            ret = rte_eth_tx_burst(FORMAT(trace)->queue_id, FORMAT(trace)->port, m_buff, 1);
1437        } while (ret != 1);
1438    }
1439
1440    return 0;
1441}
1442
1443static int dpdk_fin_input(libtrace_t * libtrace) {
1444    /* Free our memory structures */
1445    if (libtrace->format_data != NULL) {
1446        /* Close the device completely, device cannot be restarted */
1447        if (FORMAT(libtrace)->port != 0xFF)
1448            rte_eth_dev_close(FORMAT(libtrace)->port);
1449        /* filter here if we used it */
1450                free(libtrace->format_data);
1451        }
1452
1453    /* Revert to the original PCI drivers */
1454    /* No longer in DPDK
1455    rte_eal_pci_exit(); */
1456    return 0;
1457}
1458
1459
1460static int dpdk_fin_output(libtrace_out_t * libtrace) {
1461    /* Free our memory structures */
1462    if (libtrace->format_data != NULL) {
1463        /* Close the device completely, device cannot be restarted */
1464        if (FORMAT(libtrace)->port != 0xFF)
1465            rte_eth_dev_close(FORMAT(libtrace)->port);
1466        /* filter here if we used it */
1467                free(libtrace->format_data);
1468        }
1469
1470    /* Revert to the original PCI drivers */
1471    /* No longer in DPDK
1472    rte_eal_pci_exit(); */
1473    return 0;
1474}
1475
1476/**
1477 * Get the start of additional header that we added to a packet.
1478 */
1479static inline struct dpdk_addt_hdr * get_addt_hdr (const libtrace_packet_t *packet) {
1480    uint8_t *hdrsize;
1481    assert(packet);
1482    assert(packet->buffer);
1483    hdrsize = (uint8_t *) MBUF_PKTDATA(packet->buffer);
1484    /* The byte before the original packet data denotes the size in bytes
1485     * of our additional header that we added sits before the 'size byte' */
1486    hdrsize--;
1487    return (struct dpdk_addt_hdr *) (hdrsize - *hdrsize);
1488}
1489
1490static int dpdk_get_capture_length (const libtrace_packet_t *packet) {
1491    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1492    return hdr->cap_len;
1493}
1494
1495static size_t dpdk_set_capture_length(libtrace_packet_t *packet, size_t size) {
1496    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1497    if (size > hdr->cap_len) {
1498        /* Cannot make a packet bigger */
1499                return trace_get_capture_length(packet);
1500        }
1501
1502    /* Reset the cached capture length first*/
1503    packet->capture_length = -1;
1504    hdr->cap_len = (uint32_t) size;
1505        return trace_get_capture_length(packet);
1506}
1507
1508static int dpdk_get_wire_length (const libtrace_packet_t *packet) {
1509    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1510    int org_cap_size; /* The original capture size */
1511    if (hdr->flags & INCLUDES_HW_TIMESTAMP) {
1512        org_cap_size = (int) rte_pktmbuf_pkt_len(MBUF(packet->buffer)) -
1513                            (MBUF_PKTDATA(packet->buffer) - (char *) hdr) -
1514                            sizeof(struct hw_timestamp_82580);
1515    } else {
1516        org_cap_size = (int) rte_pktmbuf_pkt_len(MBUF(packet->buffer)) -
1517                            (MBUF_PKTDATA(packet->buffer) - (char *) hdr);
1518    }
1519    if (hdr->flags & INCLUDES_CHECKSUM) {
1520        return org_cap_size;
1521    } else {
1522        /* DPDK packets are always TRACE_TYPE_ETH packets */
1523        return org_cap_size + ETHER_CRC_LEN;
1524    }
1525}
1526static int dpdk_get_framing_length (const libtrace_packet_t *packet) {
1527    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1528    if (hdr->flags & INCLUDES_HW_TIMESTAMP)
1529        return sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM +
1530                sizeof(struct hw_timestamp_82580);
1531    else
1532        return sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM;
1533}
1534
1535static int dpdk_prepare_packet(libtrace_t *libtrace UNUSED,
1536                libtrace_packet_t *packet, void *buffer,
1537                libtrace_rt_types_t rt_type, uint32_t flags) {
1538    assert(packet);
1539    if (packet->buffer != buffer &&
1540        packet->buf_control == TRACE_CTRL_PACKET) {
1541        free(packet->buffer);
1542    }
1543
1544    if ((flags & TRACE_PREP_OWN_BUFFER) == TRACE_PREP_OWN_BUFFER) {
1545        packet->buf_control = TRACE_CTRL_PACKET;
1546    } else
1547        packet->buf_control = TRACE_CTRL_EXTERNAL;
1548
1549    packet->buffer = buffer;
1550    packet->header = buffer;
1551
1552    /* Don't use pktmbuf_mtod will fail if the packet is a copy */
1553    packet->payload = (char *)buffer + dpdk_get_framing_length(packet);
1554    packet->type = rt_type;
1555    return 0;
1556}
1557
1558/*
1559 * Does any extra preperation to a captured packet.
1560 * This includes adding our extra header to it with the timestamp
1561 */
1562static inline int dpdk_ready_pkt(libtrace_t *libtrace, libtrace_packet_t *packet,
1563                                                        struct rte_mbuf* pkt){
1564    uint8_t * hdr_size;
1565    struct dpdk_addt_hdr *hdr;
1566#if HAS_HW_TIMESTAMPS_82580
1567    struct hw_timestamp_82580 *hw_ts;
1568    struct timeval cur_sys_time;
1569    uint64_t cur_sys_time_ns;
1570    uint64_t estimated_wraps;
1571   
1572    /* Using gettimeofday because it's most likely to be a vsyscall
1573     * We don't want to slow down anything with systemcalls we dont need
1574     * accauracy */
1575    gettimeofday(&cur_sys_time, NULL);
1576#else
1577# if USE_CLOCK_GETTIME
1578    struct timespec cur_sys_time;
1579   
1580    /* This looks terrible and I feel bad doing it. But it's OK
1581     * on new kernels, because this is a vsyscall */
1582    clock_gettime(CLOCK_REALTIME, &cur_sys_time);
1583# else
1584    struct timeval cur_sys_time;
1585    /* Should be a vsyscall */
1586    gettimeofday(&cur_sys_time, NULL);
1587# endif
1588#endif
1589
1590    /* Record the size of our header */
1591    hdr_size = (uint8_t *) rte_pktmbuf_prepend(pkt, sizeof(uint8_t));
1592    *hdr_size = sizeof(struct dpdk_addt_hdr);
1593    /* Now put our header in front of that size */
1594    hdr = (struct dpdk_addt_hdr *) rte_pktmbuf_prepend(pkt, sizeof(struct dpdk_addt_hdr));
1595    memset(hdr, 0, sizeof(struct dpdk_addt_hdr));
1596   
1597#if GET_MAC_CRC_CHECKSUM
1598    /* Add back in the CRC sum */
1599    pkt->pkt.pkt_len += ETHER_CRC_LEN;
1600    pkt->pkt.data_len += ETHER_CRC_LEN;
1601    hdr->flags |= INCLUDES_CHECKSUM;
1602#endif
1603
1604#if HAS_HW_TIMESTAMPS_82580
1605    /* Taken from igb_ptp.c part of Intel Linux drivers (Good example code)
1606     *
1607     *        +----------+---+   +--------------+
1608     *  82580 |    24    | 8 |   |      32      |
1609     *        +----------+---+   +--------------+
1610     *          reserved  \______ 40 bits _____/
1611     *
1612     * The 40 bit 82580 SYSTIM overflows every
1613     *   2^40 * 10^-9 /  60  = 18.3 minutes.
1614     *
1615     * NOTE picture is in Big Endian order, in memory it's acutally in Little
1616     * Endian (for the full 64 bits) i.e. picture is mirrored
1617     */
1618   
1619    /* The timestamp is sitting before our packet and is included in pkt_len */
1620    hdr->flags |= INCLUDES_HW_TIMESTAMP;
1621    hw_ts = (struct hw_timestamp_82580 *) MBUF_PKTDATA(pkt);
1622   
1623    /* Despite what the documentation says this is in Little
1624     * Endian byteorder. Mask the reserved section out.
1625     */
1626    hdr->timestamp = le64toh(hw_ts->timestamp) & 
1627                ~(((~0ull)>>TS_NBITS_82580)<<TS_NBITS_82580);
1628               
1629    cur_sys_time_ns = TV_TO_NS(cur_sys_time);
1630    if (unlikely(FORMAT(libtrace)->ts_first_sys == 0)) {
1631        FORMAT(libtrace)->ts_first_sys = cur_sys_time_ns - hdr->timestamp;
1632        FORMAT(libtrace)->ts_last_sys = FORMAT(libtrace)->ts_first_sys;
1633    }
1634   
1635    /* This will have serious problems if packets aren't read quickly
1636     * that is within a couple of seconds because our clock cycles every
1637     * 18 seconds */
1638    estimated_wraps = (cur_sys_time_ns - FORMAT(libtrace)->ts_last_sys)
1639                            / (1ull<<TS_NBITS_82580);
1640   
1641    /* Estimated_wraps gives the number of times the counter should have
1642     * wrapped (however depending on value last time it could have wrapped
1643     * twice more (if hw clock is close to its max value) or once less (allowing
1644     * for a bit of variance between hw and sys clock). But if the clock
1645     * shouldn't have wrapped once then don't allow it to go backwards in time */
1646    if (unlikely(estimated_wraps >= 2)) {
1647        /* 2 or more wrap arounds add all but the very last wrap */
1648        FORMAT(libtrace)->wrap_count += estimated_wraps - 1;
1649    }
1650   
1651    /* Set the timestamp to the lowest possible value we're considering */
1652    hdr->timestamp += FORMAT(libtrace)->ts_first_sys +
1653                        FORMAT(libtrace)->wrap_count * (1ull<<TS_NBITS_82580);
1654   
1655    /* In most runs only the first if() will need evaluating - i.e our
1656     * estimate is correct. */
1657    if (unlikely(!WITHIN_VARIANCE(cur_sys_time_ns,
1658                                hdr->timestamp, MAXSKEW_82580))) {
1659        /* Failed to match estimated_wraps-1 (or estimated_wraps in ==0 case) */
1660        FORMAT(libtrace)->wrap_count++;
1661        hdr->timestamp += (1ull<<TS_NBITS_82580);
1662        if (!WITHIN_VARIANCE(cur_sys_time_ns,
1663                                hdr->timestamp, MAXSKEW_82580)) {
1664            /* Failed to match estimated_wraps */
1665            FORMAT(libtrace)->wrap_count++;
1666            hdr->timestamp += (1ull<<TS_NBITS_82580);
1667            if (!WITHIN_VARIANCE(cur_sys_time_ns,
1668                                hdr->timestamp, MAXSKEW_82580)) {
1669                if (estimated_wraps == 0) {
1670                    /* 0 case Failed to match estimated_wraps+2 */
1671                    printf("WARNING - Hardware Timestamp failed to"
1672                                            " match using systemtime!\n");
1673                    hdr->timestamp = cur_sys_time_ns;
1674                } else {
1675                    /* Failed to match estimated_wraps+1 */
1676                    FORMAT(libtrace)->wrap_count++;
1677                    hdr->timestamp += (1ull<<TS_NBITS_82580);
1678                    if (!WITHIN_VARIANCE(cur_sys_time_ns,
1679                                hdr->timestamp, MAXSKEW_82580)) {
1680                        /* Failed to match estimated_wraps+2 */
1681                        printf("WARNING - Hardware Timestamp failed to"
1682                                            " match using systemtime!!\n");
1683                    }
1684                }
1685            }
1686        }
1687    }
1688
1689    /* Log our previous for the next loop */
1690    FORMAT(libtrace)->ts_last_sys = TV_TO_NS(cur_sys_time);
1691
1692#else
1693# if USE_CLOCK_GETTIME
1694    hdr->timestamp = TS_TO_NS(cur_sys_time);
1695# else
1696    hdr->timestamp = TV_TO_NS(cur_sys_time);
1697# endif
1698#endif
1699
1700    /* Intels samples prefetch into level 0 cache lets assume it is a good
1701     * idea and do the same */
1702    rte_prefetch0(rte_pktmbuf_mtod(pkt, void *));
1703    packet->buffer = pkt;
1704    dpdk_prepare_packet(libtrace, packet, packet->buffer, packet->type, 0);
1705
1706    /* Set our capture length for the first time */
1707    hdr->cap_len = dpdk_get_wire_length(packet);
1708    if (!(hdr->flags & INCLUDES_CHECKSUM)) {
1709        hdr->cap_len -= ETHER_CRC_LEN;
1710    }
1711   
1712
1713    return dpdk_get_framing_length(packet) +
1714                        dpdk_get_capture_length(packet);
1715}
1716
1717
1718static void dpdk_fin_packet(libtrace_packet_t *packet)
1719{
1720        if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1721                rte_pktmbuf_free(packet->buffer);
1722                packet->buffer = NULL;
1723        }
1724}
1725
1726static int dpdk_read_packet (libtrace_t *libtrace, libtrace_packet_t *packet) {
1727    int nb_rx; /* Number of rx packets we've recevied */
1728    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) */
1729
1730    /* Free the last packet buffer */
1731    if (packet->buffer != NULL) {
1732        /* Buffer is owned by DPDK */
1733        if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1734            rte_pktmbuf_free(packet->buffer);
1735            packet->buffer = NULL;
1736        } else
1737        /* Buffer is owned by packet i.e. has been malloc'd */
1738        if (packet->buf_control == TRACE_CTRL_PACKET) {
1739            free(packet->buffer);
1740            packet->buffer = NULL;
1741        }
1742    }
1743   
1744    packet->buf_control = TRACE_CTRL_EXTERNAL;
1745    packet->type = TRACE_RT_DATA_DPDK;
1746   
1747    /* Wait for a packet */
1748    while (1) {
1749        /* Poll for a single packet */
1750        nb_rx = rte_eth_rx_burst(FORMAT(libtrace)->port,
1751                            FORMAT(libtrace)->queue_id, pkts_burst, 1);       
1752        if (nb_rx > 0) { /* Got a packet - otherwise we keep spining */
1753            return dpdk_ready_pkt(libtrace, packet, pkts_burst[0]);
1754        }
1755    }
1756   
1757    /* We'll never get here - but if we did it would be bad */
1758    return -1;
1759}
1760
1761static int dpdk_pread_packet (libtrace_t *libtrace, libtrace_thread_t *t, libtrace_packet_t *packet) {
1762    int nb_rx; /* Number of rx packets we've recevied */
1763    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) */
1764
1765    /* Free the last packet buffer */
1766    if (packet->buffer != NULL) {
1767        /* Buffer is owned by DPDK */
1768        if ( packet->buf_control == TRACE_CTRL_EXTERNAL) {
1769            rte_pktmbuf_free(packet->buffer);
1770            packet->buffer = NULL;
1771        } else
1772        /* Buffer is owned by packet i.e. has been malloc'd */
1773        if (packet->buf_control == TRACE_CTRL_PACKET) {
1774            free(packet->buffer);
1775            packet->buffer = NULL;
1776        }
1777    }
1778   
1779    packet->buf_control = TRACE_CTRL_EXTERNAL;
1780    packet->type = TRACE_RT_DATA_DPDK;
1781   
1782    /* Wait for a packet */
1783    while (1) {
1784        /* Poll for a single packet */
1785        nb_rx = rte_eth_rx_burst(PERPKT_FORMAT(t)->port,
1786                            PERPKT_FORMAT(t)->queue_id, pkts_burst, 1);
1787        if (nb_rx > 0) { /* Got a packet - otherwise we keep spining */
1788                        //fprintf(stderr, "Doing P READ PACKET port=%d q=%d\n", (int) FORMAT(libtrace)->port, (int) get_thread_table_num(libtrace));
1789            return dpdk_ready_pkt(libtrace, packet, pkts_burst[0]);
1790        }
1791        // Check the message queue this could be (Well it shouldn't but anyway) be less than 0
1792        if (libtrace_message_queue_count(&t->messages) > 0) {
1793                        printf("Extra message yay");
1794                        return -2;
1795                }
1796    }
1797   
1798    /* We'll never get here - but if we did it would be bad */
1799    return -1;
1800}
1801
1802static struct timeval dpdk_get_timeval (const libtrace_packet_t *packet) {
1803    struct timeval tv;
1804    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1805   
1806    tv.tv_sec = hdr->timestamp / (uint64_t) 1000000000;
1807    tv.tv_usec = (hdr->timestamp % (uint64_t) 1000000000) / 1000;
1808    return tv;
1809}
1810
1811static struct timespec dpdk_get_timespec (const libtrace_packet_t *packet) {
1812    struct timespec ts;
1813    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1814   
1815    ts.tv_sec = hdr->timestamp / (uint64_t) 1000000000;
1816    ts.tv_nsec = hdr->timestamp % (uint64_t) 1000000000;
1817    return ts;
1818}
1819
1820static libtrace_linktype_t dpdk_get_link_type (const libtrace_packet_t *packet UNUSED) {
1821    return TRACE_TYPE_ETH; /* Always ethernet until proven otherwise */
1822}
1823
1824static libtrace_direction_t dpdk_get_direction (const libtrace_packet_t *packet) {
1825    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1826    return (libtrace_direction_t) hdr->direction;
1827}
1828
1829static libtrace_direction_t dpdk_set_direction(libtrace_packet_t *packet, libtrace_direction_t direction) {
1830    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1831    hdr->direction = (uint8_t) direction;
1832    return (libtrace_direction_t) hdr->direction;
1833}
1834
1835/*
1836 * NOTE: Drops could occur for other reasons than running out of buffer
1837 * space. Such as failed MAC checksums and oversized packets.
1838 */
1839static uint64_t dpdk_get_dropped_packets (libtrace_t *trace) {
1840    struct rte_eth_stats stats = {0};
1841   
1842    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1843        return UINT64_MAX;
1844    /* Grab the current stats */
1845    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1846   
1847    /* Get the drop counter */
1848    return (uint64_t) stats.ierrors;
1849}
1850
1851static uint64_t dpdk_get_captured_packets (libtrace_t *trace) {
1852    struct rte_eth_stats stats = {0};
1853   
1854    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1855        return UINT64_MAX;
1856    /* Grab the current stats */
1857    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1858   
1859    /* Get the drop counter */
1860    return (uint64_t) stats.ipackets;
1861}
1862
1863/*
1864 * This is the number of packets filtered by the NIC
1865 * and maybe ahead of number read using libtrace.
1866 *
1867 * XXX we are yet to implement any filtering, but if it was this should
1868 * get the result. So this will just return 0 for now.
1869 */
1870static uint64_t dpdk_get_filtered_packets (libtrace_t *trace) {
1871    struct rte_eth_stats stats = {0};
1872   
1873    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1874        return UINT64_MAX;
1875    /* Grab the current stats */
1876    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1877   
1878    /* Get the drop counter */
1879    return (uint64_t) stats.fdirmiss;
1880}
1881
1882/* Attempts to read a packet in a non-blocking fashion. If one is not
1883 * available a SLEEP event is returned. We do not have the ability to
1884 * create a select()able file descriptor in DPDK.
1885 */
1886static libtrace_eventobj_t dpdk_trace_event(libtrace_t *trace,
1887                                        libtrace_packet_t *packet) {
1888    libtrace_eventobj_t event = {0,0,0.0,0};
1889    int nb_rx; /* Number of receive packets we've read */
1890    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) to rx buffers */
1891   
1892    do {
1893   
1894        /* See if we already have a packet waiting */
1895        nb_rx = rte_eth_rx_burst(FORMAT(trace)->port,
1896                        FORMAT(trace)->queue_id, pkts_burst, 1);
1897       
1898        if (nb_rx > 0) {
1899            /* Free the last packet buffer */
1900            if (packet->buffer != NULL) {
1901                /* Buffer is owned by DPDK */
1902                if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1903                    rte_pktmbuf_free(packet->buffer);
1904                    packet->buffer = NULL;
1905                } else
1906                /* Buffer is owned by packet i.e. has been malloc'd */
1907                if (packet->buf_control == TRACE_CTRL_PACKET) {
1908                    free(packet->buffer);
1909                    packet->buffer = NULL;
1910                }
1911            }
1912           
1913            packet->buf_control = TRACE_CTRL_EXTERNAL;
1914            packet->type = TRACE_RT_DATA_DPDK;
1915            event.type = TRACE_EVENT_PACKET;
1916            event.size = dpdk_ready_pkt(trace, packet, pkts_burst[0]);
1917           
1918            /* XXX - Check this passes the filter trace_read_packet normally
1919             * does this for us but this wont */
1920            if (trace->filter) {
1921                if (!trace_apply_filter(trace->filter, packet)) {
1922                    /* Failed the filter so we loop for another packet */
1923                    trace->filtered_packets ++;
1924                    continue;
1925                }
1926            }
1927            trace->accepted_packets ++;
1928        } else {
1929            /* We only want to sleep for a very short time - we are non-blocking */
1930            event.type = TRACE_EVENT_SLEEP;
1931            event.seconds = 0.0001;
1932            event.size = 0;
1933        }
1934       
1935        /* If we get here we have our event */
1936        break;
1937    } while (1);
1938
1939    return event;
1940}
1941
1942
1943static void dpdk_help(void) {
1944    printf("dpdk format module: $Revision: 1752 $\n");
1945    printf("Supported input URIs:\n");
1946    printf("\tdpdk:<domain:bus:devid.func>-<coreid>\n");
1947    printf("\tThe -<coreid> is optional \n");
1948    printf("\t e.g. dpdk:0000:01:00.1\n");
1949    printf("\t e.g. dpdk:0000:01:00.1-2 (Use the second CPU core)\n\n");
1950    printf("\t By default the last CPU core is used if not otherwise specified.\n");
1951    printf("\t Only a single libtrace instance of dpdk can use the same CPU core.\n");
1952    printf("\t Support for multiple simultaneous instances of dpdk format is currently limited.\n");
1953    printf("\n");
1954    printf("Supported output URIs:\n");
1955    printf("\tSame format as the input URI.\n");
1956    printf("\t e.g. dpdk:0000:01:00.1\n");
1957    printf("\t e.g. dpdk:0000:01:00.1-2 (Use the second CPU core)\n");
1958    printf("\n");
1959}
1960
1961static struct libtrace_format_t dpdk = {
1962        "dpdk",
1963        "$Id: format_dpdk.c 1805 2013-03-08 02:01:35Z salcock $",
1964        TRACE_FORMAT_DPDK,
1965        NULL,                   /* probe filename */
1966        NULL,                               /* probe magic */
1967        dpdk_init_input,            /* init_input */
1968        dpdk_config_input,          /* config_input */
1969        dpdk_start_input,           /* start_input */
1970        dpdk_pause_input,           /* pause_input */
1971        dpdk_init_output,           /* init_output */
1972        NULL,                               /* config_output */
1973        dpdk_start_output,          /* start_ouput */
1974        dpdk_fin_input,             /* fin_input */
1975        dpdk_fin_output,        /* fin_output */
1976        dpdk_read_packet,           /* read_packet */
1977        dpdk_prepare_packet,    /* prepare_packet */
1978        dpdk_fin_packet,                                    /* fin_packet */
1979        dpdk_write_packet,          /* write_packet */
1980        dpdk_get_link_type,         /* get_link_type */
1981        dpdk_get_direction,         /* get_direction */
1982        dpdk_set_direction,         /* set_direction */
1983        NULL,                               /* get_erf_timestamp */
1984        dpdk_get_timeval,           /* get_timeval */
1985        dpdk_get_timespec,          /* get_timespec */
1986        NULL,                               /* get_seconds */
1987        NULL,                               /* seek_erf */
1988        NULL,                               /* seek_timeval */
1989        NULL,                               /* seek_seconds */
1990        dpdk_get_capture_length,/* get_capture_length */
1991        dpdk_get_wire_length,   /* get_wire_length */
1992        dpdk_get_framing_length,/* get_framing_length */
1993        dpdk_set_capture_length,/* set_capture_length */
1994        NULL,                               /* get_received_packets */
1995        dpdk_get_filtered_packets,/* get_filtered_packets */
1996        dpdk_get_dropped_packets,/* get_dropped_packets */
1997    dpdk_get_captured_packets,/* get_captured_packets */
1998        NULL,                       /* get_fd */
1999        dpdk_trace_event,               /* trace_event */
2000    dpdk_help,              /* help */
2001    NULL,                   /* next pointer */
2002    {true, 8},              /* Live, NICs typically have 8 threads */
2003    dpdk_pstart_input, /* pstart_input */
2004        dpdk_pread_packet, /* pread_packet */
2005        dpdk_pause_input, /* ppause */
2006        dpdk_fin_input, /* p_fin */
2007        dpdk_pconfig_input, /* pconfig_input */
2008    dpdk_pregister_thread, /* pregister_thread */
2009    dpdk_punregister_thread /* unpregister_thread */
2010};
2011
2012void dpdk_constructor(void) {
2013        register_format(&dpdk);
2014}
Note: See TracBrowser for help on using the repository browser.