source: lib/format_dpdk.c @ 59e8400

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

Fix bug with DPDK PCI address parsing this should be hex not base 10
Fix typo in previous commit removed 's' from whitelist_device(s)

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