source: lib/format_dpdk.c @ 34dafcc

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

Fixes whitelisting DPDK ports cards with DPDK 1.7, allowing more than one port to have the igb_uio driver loaded.

  • Property mode set to 100644
File size: 52.9 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#include "config.h"
44#include "libtrace.h"
45#include "libtrace_int.h"
46#include "format_helper.h"
47#include "libtrace_arphrd.h"
48
49#ifdef HAVE_INTTYPES_H
50#  include <inttypes.h>
51#else
52# error "Can't find inttypes.h"
53#endif
54
55#include <stdlib.h>
56#include <assert.h>
57#include <unistd.h>
58#include <endian.h>
59#include <string.h>
60
61/* We can deal with any minor differences by checking the RTE VERSION
62 * Typically DPDK backports some fixes (typically for building against
63 * newer kernels) to the older version of DPDK.
64 *
65 * These get released with the rX suffix. The following macros where added
66 * in these new releases.
67 *
68 * Below this is a log of version that required changes to the libtrace
69 * code (that we still attempt to support).
70 *
71 * Currently 1.5 to 1.7 is supported.
72 */
73#include <rte_eal.h>
74#include <rte_version.h>
75#ifndef RTE_VERSION_NUM
76#       define RTE_VERSION_NUM(a,b,c,d) ((a) << 24 | (b) << 16 | (c) << 8 | (d))
77#endif
78#ifndef RTE_VER_PATCH_RELEASE
79#       define RTE_VER_PATCH_RELEASE 0
80#endif
81#ifndef RTE_VERSION
82#       define RTE_VERSION RTE_VERSION_NUM(RTE_VER_MAJOR,RTE_VER_MINOR, \
83        RTE_VER_PATCH_LEVEL, RTE_VER_PATCH_RELEASE)
84#endif
85
86/* 1.6.0r2 :
87 *      rte_eal_pci_set_blacklist() is removed
88 *      device_list is renamed to pci_device_list
89 *      In the 1.7.0 release rte_eal_pci_probe is called by rte_eal_init
90 *      as such we do apply the whitelist before rte_eal_init.
91 *      This also works correctly with DPDK 1.6.0r2.
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
130/* The default size of memory buffers to use - This is the max size of standard
131 * ethernet packet less the size of the MAC CHECKSUM */
132#define RX_MBUF_SIZE 1514
133
134/* The minimum number of memory buffers per queue tx or rx. Search for
135 * _MIN_RING_DESC in DPDK. The largest minimum is 64 for 10GBit cards.
136 */
137#define MIN_NB_BUF 64
138
139/* Number of receive memory buffers to use
140 * By default this is limited by driver to 4k and must be a multiple of 128.
141 * A modification can be made to the driver to remove this limit.
142 * This can be increased in the driver and here.
143 * Should be at least MIN_NB_BUF.
144 */
145#define NB_RX_MBUF 4096
146
147/* Number of send memory buffers to use.
148 * Same limits apply as those to NB_TX_MBUF.
149 */
150#define NB_TX_MBUF 1024
151
152/* The size of the PCI blacklist needs to be big enough to contain
153 * every PCI device address (listed by lspci every bus:device.function tuple).
154 */
155#define BLACK_LIST_SIZE 50
156
157/* The maximum number of characters the mempool name can be */
158#define MEMPOOL_NAME_LEN 20
159
160#define MBUF(x) ((struct rte_mbuf *) x)
161/* Get the original placement of the packet data */
162#define MBUF_PKTDATA(x) ((char *) x + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
163#define FORMAT(x) ((struct dpdk_format_data_t*)(x->format_data))
164#define TV_TO_NS(tv) ((uint64_t) tv.tv_sec*1000000000ull + \
165                        (uint64_t) tv.tv_usec*1000ull)
166#define TS_TO_NS(ts) ((uint64_t) ts.tv_sec*1000000000ull + \
167                        (uint64_t) ts.tv_nsec)
168
169#if RTE_PKTMBUF_HEADROOM != 128
170#warning "RTE_PKT_MBUF_HEADROOM is not set to the default value of 128 - " \
171         "any libtrace instance processing these packet must be have the" \
172         "same RTE_PKTMBUF_HEADROOM set"
173#endif
174
175/* ~~~~~~~~~~~~~~~~~~~~~~ Advance settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176 * THESE MAY REQUIRE MODIFICATIONS TO INTEL DPDK
177 *
178 * Make sure you understand what these are doing before enabling them.
179 * They might make traces incompatable with other builds etc.
180 *
181 * These are also included to show how to do somethings which aren't
182 * obvious in the DPDK documentation.
183 */
184
185/* Print verbose messages to stdout */
186#define DEBUG 0
187
188/* Use clock_gettime() for nanosecond resolution rather than gettimeofday()
189 * only turn on if you know clock_gettime is a vsyscall on your system
190 * overwise could be a large overhead. Again gettimeofday() should be
191 * vsyscall also if it's not you should seriously consider updating your
192 * kernel.
193 */
194#ifdef HAVE_LIBRT
195/* You can turn this on (set to 1) to prefer clock_gettime */
196#define USE_CLOCK_GETTIME 0
197#else
198/* DONT CHANGE THIS !!! */
199#define USE_CLOCK_GETTIME 0
200#endif
201
202/* This is fairly safe to turn on - currently there appears to be a 'bug'
203 * in DPDK that will remove the checksum by making the packet appear 4bytes
204 * smaller than what it really is. Most formats don't include the checksum
205 * hence writing out a port such as int: ring: and dpdk: assumes there
206 * is no checksum and will attempt to write the checksum as part of the
207 * packet
208 */
209#define GET_MAC_CRC_CHECKSUM 0
210
211/* This requires a modification of the pmd drivers (inside Intel DPDK)
212 */
213#define HAS_HW_TIMESTAMPS_82580 0
214
215#if HAS_HW_TIMESTAMPS_82580
216# define TS_NBITS_82580     40
217/* The maximum on the +ve or -ve side that we can be, make it half way */
218# define MAXSKEW_82580 ((uint64_t) (.5 * (double)(1ull<<TS_NBITS_82580)))
219#define WITHIN_VARIANCE(v1,v2,var) (((v1) - (var) < (v2)) && ((v1) + (var) > (v2)))
220#endif
221
222/* As per Intel 82580 specification - mismatch in 82580 datasheet
223 * it states ts is stored in Big Endian, however its actually Little */
224struct hw_timestamp_82580 {
225    uint64_t reserved;
226    uint64_t timestamp; /* Little Endian only lower 40 bits are valid */
227};
228
229enum paused_state {
230    DPDK_NEVER_STARTED,
231    DPDK_RUNNING,
232    DPDK_PAUSED,
233};
234
235/* Used by both input and output however some fields are not used
236 * for output */
237struct dpdk_format_data_t {
238    int8_t promisc; /* promiscuous mode - RX only */
239    uint8_t port; /* Always 0 we only whitelist a single port - Shared TX & RX */
240    uint8_t nb_ports; /* Total number of usable ports on system should be 1 */
241    uint8_t paused; /* See paused_state */ 
242    uint16_t queue_id; /* Always 0 we use a single queue - Shared TX & RX */
243    int snaplen; /* The snap length for the capture - RX only */
244    /* We always have to setup both rx and tx queues even if we don't want them */
245    int nb_rx_buf; /* The number of packet buffers in the rx ring */
246    int nb_tx_buf; /* The number of packet buffers in the tx ring */
247    struct rte_mempool * pktmbuf_pool; /* Our packet memory pool */
248#if DPDK_USE_BLACKLIST
249    struct rte_pci_addr blacklist[BLACK_LIST_SIZE]; /* Holds our device blacklist */
250        unsigned int nb_blacklist; /* Number of blacklist items in are valid */
251#endif
252    char mempool_name[MEMPOOL_NAME_LEN]; /* The name of the mempool that we are using */
253#if HAS_HW_TIMESTAMPS_82580
254    /* Timestamping only relevent to RX */
255    uint64_t ts_first_sys; /* Sytem timestamp of the first packet in nanoseconds */
256    uint64_t ts_last_sys; /* System timestamp of our most recent packet in nanoseconds */
257    uint32_t wrap_count; /* Number of times the NIC clock has wrapped around completely */
258#endif
259};
260
261enum dpdk_addt_hdr_flags {
262    INCLUDES_CHECKSUM = 0x1,
263    INCLUDES_HW_TIMESTAMP = 0x2, /* Used with 82580 driver */
264};
265
266/**
267 * A structure placed in front of the packet where we can store
268 * additional information about the given packet.
269 * +--------------------------+
270 * |       rte_mbuf (pkt)     | sizeof(rte_mbuf)
271 * +--------------------------+
272 * |           padding        | RTE_PKTMBUF_HEADROOM-1-sizeof(dpdk_addt_hdr)
273 * +--------------------------+
274 * |       dpdk_addt_hdr      | sizeof(dpdk_addt_hdr)
275 * +--------------------------+
276 * |   sizeof(dpdk_addt_hdr)  | 1 byte
277 * +--------------------------+
278 * *   hw_timestamp_82580     * 16 bytes Optional
279 * +--------------------------+
280 * |       Packet data        | Variable Size
281 * |                          |
282 */
283struct dpdk_addt_hdr {
284    uint64_t timestamp;
285    uint8_t flags;
286    uint8_t direction;
287    uint8_t reserved1;
288    uint8_t reserved2;
289    uint32_t cap_len; /* The size to say the capture is */
290};
291
292/**
293 * We want to blacklist all devices except those on the whitelist
294 * (I say list, but yes it is only the one).
295 *
296 * The default behaviour of rte_pci_probe() will map every possible device
297 * to its DPDK driver. The DPDK driver will take the ethernet device
298 * out of the kernel (i.e. no longer /dev/ethx) and cannot be used.
299 *
300 * So blacklist all devices except the one that we wish to use so that
301 * the others can still be used as standard ethernet ports.
302 *
303 * @return 0 if successful, otherwise -1 on error.
304 */
305#if DPDK_USE_BLACKLIST
306static int blacklist_devices(struct dpdk_format_data_t *format_data, struct rte_pci_addr *whitelist)
307{
308        struct rte_pci_device *dev = NULL;
309        format_data->nb_blacklist = 0;
310
311        memset(format_data->blacklist, 0, sizeof (format_data->blacklist));
312
313        TAILQ_FOREACH(dev, &device_list, next) {
314        if (whitelist != NULL && whitelist->domain == dev->addr.domain
315            && whitelist->bus == dev->addr.bus
316            && whitelist->devid == dev->addr.devid
317            && whitelist->function == dev->addr.function)
318            continue;
319                if (format_data->nb_blacklist >= sizeof (format_data->blacklist)
320                                / sizeof (format_data->blacklist[0])) {
321                        printf("Warning: too many devices to blacklist consider"
322                                        " increasing BLACK_LIST_SIZE");
323                        break;
324                }
325                format_data->blacklist[format_data->nb_blacklist] = dev->addr;
326                ++format_data->nb_blacklist;
327        }
328
329        rte_eal_pci_set_blacklist(format_data->blacklist, format_data->nb_blacklist);
330        return 0;
331}
332#else /* DPDK_USE_BLACKLIST */
333#include <rte_devargs.h>
334static int whitelist_device(struct dpdk_format_data_t *format_data UNUSED, struct rte_pci_addr *whitelist)
335{
336        char pci_str[20] = {0};
337        snprintf(pci_str, sizeof(pci_str), PCI_PRI_FMT,
338                 whitelist->domain,
339                 whitelist->bus,
340                 whitelist->devid,
341                 whitelist->function);
342        if (rte_eal_devargs_add(RTE_DEVTYPE_WHITELISTED_PCI, pci_str) < 0) {
343                return -1;
344        }
345        return 0;
346}
347#endif
348
349/**
350 * Parse the URI format as a pci address
351 * Fills in addr, note core is optional and is unchanged if
352 * a value for it is not provided.
353 *
354 * i.e. ./libtrace dpdk:0:1:0.0 -> 0:1:0.0
355 * or ./libtrace dpdk:0:1:0.1-2 -> 0:1:0.1 (Using CPU core #2)
356 */
357static int parse_pciaddr(char * str, struct rte_pci_addr * addr, long * core) {
358    char * wrkstr;
359    char * pch;
360    assert(str);
361    wrkstr = strdup(str);
362   
363    pch = strtok(wrkstr,":");
364    if (pch == NULL || pch[0] == 0) {
365        free(wrkstr); return -1;
366    }
367    addr->domain = (uint16_t) atoi(pch);
368
369    pch = strtok(NULL,":");
370    if (pch == NULL || pch[0] == 0) {
371        free(wrkstr); return -1;
372    }
373    addr->bus = (uint8_t) atoi(pch);
374
375    pch = strtok(NULL,".");
376    if (pch == NULL || pch[0] == 0) {
377        free(wrkstr); return -1;
378    }
379    addr->devid = (uint8_t) atoi(pch);
380
381    pch = strtok(NULL,"-"); /* Might not find the '-' it's optional */
382    if (pch == NULL || pch[0] == 0) {
383        free(wrkstr); return -1;
384    }
385    addr->function = (uint8_t) atoi(pch);
386
387    pch = strtok(NULL, ""); /* Find end of string */
388   
389    if (pch != NULL && pch[0] != 0) {
390        *core = (long) atoi(pch);
391    }
392
393    free(wrkstr);
394    return 0;
395}
396
397#if DEBUG
398/* For debugging */
399static inline void dump_configuration()
400{
401    struct rte_config * global_config;
402    long nb_cpu = sysconf(_SC_NPROCESSORS_ONLN);
403
404    if (nb_cpu <= 0) {
405        perror("sysconf(_SC_NPROCESSORS_ONLN) failed. Falling back to the first core.");
406        nb_cpu = 1; /* fallback to just 1 core */
407    }
408    if (nb_cpu > RTE_MAX_LCORE)
409        nb_cpu = RTE_MAX_LCORE;
410
411    global_config = rte_eal_get_configuration();
412
413    if (global_config != NULL) {
414        int i;
415        fprintf(stderr, "Intel DPDK setup\n"
416               "---Version      : %s\n"
417               "---Master LCore : %"PRIu32"\n"
418               "---LCore Count  : %"PRIu32"\n",
419               rte_version(),
420               global_config->master_lcore, global_config->lcore_count);
421
422        for (i = 0 ; i < nb_cpu; i++) {
423            fprintf(stderr, "   ---Core %d : %s\n", i,
424                   global_config->lcore_role[i] == ROLE_RTE ? "on" : "off");
425        }
426
427        const char * proc_type;
428        switch (global_config->process_type) {
429            case RTE_PROC_AUTO:
430                proc_type = "auto";
431                break;
432            case RTE_PROC_PRIMARY:
433                proc_type = "primary";
434                break;
435            case RTE_PROC_SECONDARY:
436                proc_type = "secondary";
437                break;
438            case RTE_PROC_INVALID:
439                proc_type = "invalid";
440                break;
441            default:
442                proc_type = "something worse than invalid!!";
443        }
444        fprintf(stderr, "---Process Type : %s\n", proc_type);
445    }
446
447}
448#endif
449
450/**
451 * XXX This is very bad XXX
452 * But we have to do something to allow getopts nesting
453 * Luckly normally the format is last so it doesn't matter
454 * DPDK only supports modern systems so hopefully this
455 * will continue to work
456 */
457struct saved_getopts {
458        char *optarg;
459        int optind;
460        int opterr;
461        int optopt;
462};
463
464static void save_getopts(struct saved_getopts *opts) {
465        opts->optarg = optarg;
466        opts->optind = optind;
467        opts->opterr = opterr;
468        opts->optopt = optopt;
469}
470
471static void restore_getopts(struct saved_getopts *opts) {
472        optarg = opts->optarg;
473        optind = opts->optind;
474        opterr = opts->opterr;
475        optopt = opts->optopt;
476}
477
478static inline int dpdk_init_environment(char * uridata, struct dpdk_format_data_t * format_data,
479                                        char * err, int errlen) {
480    int ret; /* Returned error codes */
481    struct rte_pci_addr use_addr; /* The only address that we don't blacklist */
482    char cpu_number[10] = {0}; /* The CPU mask we want to bind to */
483    char mem_map[20] = {0}; /* The memory name */
484    long nb_cpu; /* The number of CPUs in the system */
485    long my_cpu; /* The CPU number we want to bind to */
486        struct saved_getopts save_opts;
487   
488#if DEBUG
489    rte_set_log_level(RTE_LOG_DEBUG);
490#else
491    rte_set_log_level(RTE_LOG_WARNING);
492#endif
493    /*
494     * Using unique file prefixes mean separate memory is used, unlinking
495     * the two processes. However be careful we still cannot access a
496     * port that already in use.
497     */
498    char* argv[] = {"libtrace", "-c", cpu_number, "-n", "1", "--proc-type", "auto",
499                "--file-prefix", mem_map, "-m", "256", NULL};
500    int argc = sizeof(argv) / sizeof(argv[0]) - 1;
501
502    /* This initialises the Environment Abstraction Layer (EAL)
503     * If we had slave workers these are put into WAITING state
504     *
505     * Basically binds this thread to a fixed core, which we choose as
506     * the last core on the machine (assuming fewer interrupts mapped here).
507     * "-c" controls the cpu mask 0x1=1st core 0x2=2nd 0x4=3rd and so on
508     * "-n" the number of memory channels into the CPU (hardware specific)
509     *      - Most likely to be half the number of ram slots in your machine.
510     *        We could count ram slots by "dmidecode -t 17 | grep -c 'Size:'"
511     * Controls where in memory packets are stored and should spread across
512     * the channels. We just use 1 to be safe.
513     */
514
515    /* Get the number of cpu cores in the system and use the last core */
516    nb_cpu = sysconf(_SC_NPROCESSORS_ONLN);
517    if (nb_cpu <= 0) {
518        perror("sysconf(_SC_NPROCESSORS_ONLN) failed. Falling back to the first core.");
519        nb_cpu = 1; /* fallback to the first core */
520    }
521    if (nb_cpu > RTE_MAX_LCORE)
522        nb_cpu = RTE_MAX_LCORE;
523
524    my_cpu = nb_cpu;
525    /* This allows the user to specify the core - we would try to do this
526     * automatically but it's hard to tell that this is secondary
527     * before running rte_eal_init(...). Currently we are limited to 1
528     * instance per core due to the way memory is allocated. */
529    if (parse_pciaddr(uridata, &use_addr, &my_cpu) != 0) {
530        snprintf(err, errlen, "Failed to parse URI");
531        return -1;
532    }
533
534    snprintf(format_data->mempool_name, MEMPOOL_NAME_LEN,
535                "libtrace_pool_%"PRIu32, (uint32_t) nb_cpu);
536
537    if (!(my_cpu > 0 && my_cpu <= nb_cpu)) {
538        snprintf(err, errlen, 
539          "Intel DPDK - User defined a bad CPU number %"PRIu32" must be"
540          " between 1 and %"PRIu32, (uint32_t) my_cpu, (uint32_t) nb_cpu);
541        return -1;
542    }
543
544    /* Make our mask */
545    snprintf(cpu_number, sizeof(cpu_number), "%x", 0x1 << (my_cpu - 1));
546
547#if !DPDK_USE_BLACKLIST
548    /* Black list all ports besides the one that we want to use */
549    if ((ret = whitelist_device(format_data, &use_addr)) < 0) {
550        snprintf(err, errlen, "Intel DPDK - Whitelisting PCI device failed,"
551                 " are you sure the address is correct?: %s", strerror(-ret));
552        return -1;
553    }
554#endif
555
556        /* Give the memory map a unique name */
557        snprintf(mem_map, sizeof(mem_map), "libtrace-%d", (int) getpid());
558    /* rte_eal_init it makes a call to getopt so we need to reset the
559     * global optind variable of getopt otherwise this fails */
560        save_getopts(&save_opts);
561    optind = 1;
562    if ((ret = rte_eal_init(argc, argv)) < 0) {
563        snprintf(err, errlen, 
564          "Intel DPDK - Initialisation of EAL failed: %s", strerror(-ret));
565        return -1;
566    }
567        restore_getopts(&save_opts);
568
569#if DEBUG
570    dump_configuration();
571#endif
572
573#if DPDK_USE_PMD_INIT
574    /* This registers all available NICs with Intel DPDK
575     * These are not loaded until rte_eal_pci_probe() is called.
576     */
577    if ((ret = rte_pmd_init_all()) < 0) {
578        snprintf(err, errlen, 
579          "Intel DPDK - rte_pmd_init_all failed: %s", strerror(-ret));
580        return -1;
581    }
582#endif
583
584#if DPDK_USE_BLACKLIST
585    /* Blacklist all ports besides the one that we want to use */
586        if ((ret = blacklist_devices(format_data, &use_addr)) < 0) {
587                snprintf(err, errlen, "Intel DPDK - Whitelisting PCI device failed,"
588                         " are you sure the address is correct?: %s", strerror(-ret));
589                return -1;
590        }
591#endif
592
593    /* This loads DPDK drivers against all ports that are not blacklisted */
594        if ((ret = rte_eal_pci_probe()) < 0) {
595        snprintf(err, errlen, 
596            "Intel DPDK - rte_eal_pci_probe failed: %s", strerror(-ret));
597        return -1;
598    }
599
600    format_data->nb_ports = rte_eth_dev_count();
601
602    if (format_data->nb_ports != 1) {
603        snprintf(err, errlen, 
604            "Intel DPDK - rte_eth_dev_count returned %d but it should be 1",
605            format_data->nb_ports);
606        return -1;
607    }
608
609    return 0;
610}
611
612static int dpdk_init_input (libtrace_t *libtrace) {
613    char err[500];
614    err[0] = 0;
615   
616    libtrace->format_data = (struct dpdk_format_data_t *)
617                            malloc(sizeof(struct dpdk_format_data_t));
618    FORMAT(libtrace)->port = 0; /* Always assume 1 port loaded */
619    FORMAT(libtrace)->queue_id = 0; /* Single queue per port */
620    FORMAT(libtrace)->nb_ports = 0;
621    FORMAT(libtrace)->snaplen = 0; /* Use default */
622    FORMAT(libtrace)->nb_rx_buf = NB_RX_MBUF;
623    FORMAT(libtrace)->nb_tx_buf = MIN_NB_BUF;
624    FORMAT(libtrace)->promisc = -1;
625    FORMAT(libtrace)->pktmbuf_pool = NULL;
626#if DPDK_USE_BLACKLIST
627    FORMAT(libtrace)->nb_blacklist = 0;
628#endif
629    FORMAT(libtrace)->paused = DPDK_NEVER_STARTED;
630    FORMAT(libtrace)->mempool_name[0] = 0;
631#if HAS_HW_TIMESTAMPS_82580
632    FORMAT(libtrace)->ts_first_sys = 0;
633    FORMAT(libtrace)->ts_last_sys = 0;
634    FORMAT(libtrace)->wrap_count = 0;
635#endif
636
637    if (dpdk_init_environment(libtrace->uridata, FORMAT(libtrace), err, sizeof(err)) != 0) {
638        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
639        free(libtrace->format_data);
640        libtrace->format_data = NULL;
641        return -1;
642    }
643    return 0;
644};
645
646static int dpdk_init_output(libtrace_out_t *libtrace)
647{
648    char err[500];
649    err[0] = 0;
650   
651    libtrace->format_data = (struct dpdk_format_data_t *)
652                            malloc(sizeof(struct dpdk_format_data_t));
653    FORMAT(libtrace)->port = 0; /* Always assume 1 port loaded */
654    FORMAT(libtrace)->queue_id = 0; /* Single queue per port */
655    FORMAT(libtrace)->nb_ports = 0;
656    FORMAT(libtrace)->snaplen = 0; /* Use default */
657    FORMAT(libtrace)->nb_rx_buf = MIN_NB_BUF;
658    FORMAT(libtrace)->nb_tx_buf = NB_TX_MBUF;
659    FORMAT(libtrace)->promisc = -1;
660    FORMAT(libtrace)->pktmbuf_pool = NULL;
661#if DPDK_USE_BLACKLIST
662    FORMAT(libtrace)->nb_blacklist = 0;
663#endif
664    FORMAT(libtrace)->paused = DPDK_NEVER_STARTED;
665    FORMAT(libtrace)->mempool_name[0] = 0;
666#if HAS_HW_TIMESTAMPS_82580
667    FORMAT(libtrace)->ts_first_sys = 0;
668    FORMAT(libtrace)->ts_last_sys = 0;
669    FORMAT(libtrace)->wrap_count = 0;
670#endif
671
672    if (dpdk_init_environment(libtrace->uridata, FORMAT(libtrace), err, sizeof(err)) != 0) {
673        trace_set_err_out(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
674        free(libtrace->format_data);
675        libtrace->format_data = NULL;
676        return -1;
677    }
678    return 0;
679};
680
681/**
682 * Note here snaplen excludes the MAC checksum. Packets over
683 * the requested snaplen will be dropped. (Excluding MAC checksum)
684 *
685 * I.e the maximum size of a standard ethernet packet is 1518 (Including MAC checksum)
686 * So to allow packets upto 1518 this would be set to 1514 and if GET_MAC_CRC_CHECKSUM
687 * is set the maximum size of the returned packet would be 1518 otherwise
688 * 1514 would be the largest size possibly returned.
689 *
690 */
691static int dpdk_config_input (libtrace_t *libtrace,
692                                        trace_option_t option,
693                                        void *data) {
694    switch (option) {
695        case TRACE_OPTION_SNAPLEN:
696            /* Only support changing snaplen before a call to start is
697             * made */
698            if (FORMAT(libtrace)->paused == DPDK_NEVER_STARTED)
699                FORMAT(libtrace)->snaplen=*(int*)data;
700            else
701                return -1;
702            return 0;
703                case TRACE_OPTION_PROMISC:
704                        FORMAT(libtrace)->promisc=*(int*)data;
705            return 0;
706        case TRACE_OPTION_FILTER:
707            /* TODO filtering */
708            break;
709        case TRACE_OPTION_META_FREQ:
710            break;
711        case TRACE_OPTION_EVENT_REALTIME:
712            break;
713        /* Avoid default: so that future options will cause a warning
714         * here to remind us to implement it, or flag it as
715         * unimplementable
716         */
717    }
718
719        /* Don't set an error - trace_config will try to deal with the
720         * option and will set an error if it fails */
721    return -1;
722}
723
724/* Can set jumbo frames/ or limit the size of a frame by setting both
725 * max_rx_pkt_len and jumbo_frame. This can be limited to less than
726 *
727 */
728static struct rte_eth_conf port_conf = {
729        .rxmode = {
730                .split_hdr_size = 0,
731                .header_split   = 0, /**< Header Split disabled */
732                .hw_ip_checksum = 0, /**< IP checksum offload disabled */
733                .hw_vlan_filter = 0, /**< VLAN filtering disabled */
734                .jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
735        .max_rx_pkt_len = 0, /**< Max frame Size if Jumbo enabled */
736#if GET_MAC_CRC_CHECKSUM
737/* So it appears that if hw_strip_crc is turned off the driver will still
738 * take this off. See line 955ish in lib/librte_pmd_e1000/igb_rxtx.c.
739 * So if .hw_strip_crc=0 a valid CRC exists 4 bytes after the end of the
740 * So lets just add it back on when we receive the packet.
741 */
742                .hw_strip_crc   = 0, /**< CRC stripped by hardware */
743#else
744/* By default strip the MAC checksum because it's a bit of a hack to
745 * actually read these. And don't want to rely on disabling this to actualy
746 * always cut off the checksum in the future
747 */
748        .hw_strip_crc   = 1, /**< CRC stripped by hardware */
749#endif
750        },
751        .txmode = {
752                .mq_mode = ETH_DCB_NONE,
753        },
754};
755
756static const struct rte_eth_rxconf rx_conf = {
757        .rx_thresh = {
758                .pthresh = 8,/* RX_PTHRESH prefetch */
759                .hthresh = 8,/* RX_HTHRESH host */
760                .wthresh = 4,/* RX_WTHRESH writeback */
761        },
762    .rx_free_thresh = 0,
763    .rx_drop_en = 0, /* Drop packets oldest packets if out of space */
764};
765
766static const struct rte_eth_txconf tx_conf = {
767        .tx_thresh = {
768        /**
769         * TX_PTHRESH prefetch
770         * Set on the NIC, if the number of unprocessed descriptors to queued on
771         * the card fall below this try grab at least hthresh more unprocessed
772         * descriptors.
773         */
774                .pthresh = 36,
775
776        /* TX_HTHRESH host
777         * Set on the NIC, the batch size to prefetch unprocessed tx descriptors.
778         */
779                .hthresh = 0,
780       
781        /* TX_WTHRESH writeback
782         * Set on the NIC, the number of sent descriptors before writing back
783         * status to confirm the transmission. This is done more efficiently as
784         * a bulk DMA-transfer rather than writing one at a time.
785         * Similar to tx_free_thresh however this is applied to the NIC, where
786         * as tx_free_thresh is when DPDK will check these. This is extended
787         * upon by tx_rs_thresh (10Gbit cards) which doesn't write all
788         * descriptors rather only every n'th item, reducing DMA memory bandwidth.
789         */
790                .wthresh = 4,
791        },
792
793    /* Used internally by DPDK rather than passed to the NIC. The number of
794     * packet descriptors to send before checking for any responses written
795     * back (to confirm the transmission). Default = 32 if set to 0)
796     */
797        .tx_free_thresh = 0,
798
799    /* This is the Report Status threshold, used by 10Gbit cards,
800     * This signals the card to only write back status (such as
801     * transmission successful) after this minimum number of transmit
802     * descriptors are seen. The default is 32 (if set to 0) however if set
803     * to greater than 1 TX wthresh must be set to zero, because this is kindof
804     * a replacement. See the dpdk programmers guide for more restrictions.
805     */
806        .tx_rs_thresh = 1,
807};
808
809/* Attach memory to the port and start the port or restart the port.
810 */
811static int dpdk_start_port (struct dpdk_format_data_t * format_data, char *err, int errlen){
812    int ret; /* Check return values for errors */
813    struct rte_eth_link link_info; /* Wait for link */
814   
815    /* Already started */
816    if (format_data->paused == DPDK_RUNNING)
817        return 0;
818
819    /* First time started we need to alloc our memory, doing this here
820     * rather than in environment setup because we don't have snaplen then */
821    if (format_data->paused == DPDK_NEVER_STARTED) {
822        if (format_data->snaplen == 0) {
823            format_data->snaplen = RX_MBUF_SIZE;
824            port_conf.rxmode.jumbo_frame = 0;
825            port_conf.rxmode.max_rx_pkt_len = 0;
826        } else {
827            /* Use jumbo frames */
828            port_conf.rxmode.jumbo_frame = 1;
829            port_conf.rxmode.max_rx_pkt_len = format_data->snaplen;
830        }
831
832        /* This is additional overhead so make sure we allow space for this */
833#if GET_MAC_CRC_CHECKSUM
834        format_data->snaplen += ETHER_CRC_LEN;
835#endif
836#if HAS_HW_TIMESTAMPS_82580
837        format_data->snaplen += sizeof(struct hw_timestamp_82580);
838#endif
839
840        /* Create the mbuf pool, which is the place our packets are allocated
841         * from - TODO figure out if there is is a free function (I cannot see one)
842         * NOTE: RX queue requires nb_packets + 1 otherwise it fails to
843         * allocate however that extra 1 packet is not used.
844         * (I assume <= vs < error some where in DPDK code)
845         * TX requires nb_tx_buffers + 1 in the case the queue is full
846         * so that will fill the new buffer and wait until slots in the
847         * ring become available.
848         */
849#if DEBUG
850    fprintf(stderr, "Creating mempool named %s\n", format_data->mempool_name);
851#endif
852        format_data->pktmbuf_pool =
853            rte_mempool_create(format_data->mempool_name,
854                       format_data->nb_rx_buf + format_data->nb_tx_buf + 1,
855                       format_data->snaplen + sizeof(struct rte_mbuf) 
856                                        + RTE_PKTMBUF_HEADROOM,
857                       8, sizeof(struct rte_pktmbuf_pool_private),
858                       rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
859                       0, MEMPOOL_F_SP_PUT | MEMPOOL_F_SC_GET);
860
861        if (format_data->pktmbuf_pool == NULL) {
862            snprintf(err, errlen, "Intel DPDK - Initialisation of mbuf "
863                        "pool failed: %s", strerror(rte_errno));
864            return -1;
865        }
866    }
867   
868    /* ----------- Now do the setup for the port mapping ------------ */
869    /* Order of calls must be
870     * rte_eth_dev_configure()
871     * rte_eth_tx_queue_setup()
872     * rte_eth_rx_queue_setup()
873     * rte_eth_dev_start()
874     * other rte_eth calls
875     */
876   
877    /* This must be called first before another *eth* function
878     * 1 rx, 1 tx queue, port_conf sets checksum stripping etc */
879    ret = rte_eth_dev_configure(format_data->port, 1, 1, &port_conf);
880    if (ret < 0) {
881        snprintf(err, errlen, "Intel DPDK - Cannot configure device port"
882                            " %"PRIu8" : %s", format_data->port,
883                            strerror(-ret));
884        return -1;
885    }
886    /* Initialise the TX queue a minimum value if using this port for
887     * receiving. Otherwise a larger size if writing packets.
888     */
889    ret = rte_eth_tx_queue_setup(format_data->port, format_data->queue_id,
890                        format_data->nb_tx_buf, SOCKET_ID_ANY, &tx_conf);
891    if (ret < 0) {
892        snprintf(err, errlen, "Intel DPDK - Cannot configure TX queue on port"
893                            " %"PRIu8" : %s", format_data->port,
894                            strerror(-ret));
895        return -1;
896    }
897    /* Initialise the RX queue with some packets from memory */
898    ret = rte_eth_rx_queue_setup(format_data->port, format_data->queue_id,
899                            format_data->nb_rx_buf, SOCKET_ID_ANY, 
900                            &rx_conf, format_data->pktmbuf_pool);
901    if (ret < 0) {
902        snprintf(err, errlen, "Intel DPDK - Cannot configure RX queue on port"
903                    " %"PRIu8" : %s", format_data->port,
904                    strerror(-ret));
905        return -1;
906    }
907   
908    /* Start device */
909    ret = rte_eth_dev_start(format_data->port);
910    if (ret < 0) {
911        snprintf(err, errlen, "Intel DPDK - rte_eth_dev_start failed : %s",
912                    strerror(-ret));
913        return -1;
914    }
915
916    /* Default promiscuous to on */
917    if (format_data->promisc == -1)
918        format_data->promisc = 1;
919   
920    if (format_data->promisc == 1)
921        rte_eth_promiscuous_enable(format_data->port);
922    else
923        rte_eth_promiscuous_disable(format_data->port);
924   
925    /* Wait for the link to come up */
926    rte_eth_link_get(format_data->port, &link_info);
927#if DEBUG
928    fprintf(stderr, "Link status is %d %d %d\n", (int) link_info.link_status,
929            (int) link_info.link_duplex, (int) link_info.link_speed);
930#endif
931
932    /* We have now successfully started/unpaused */
933    format_data->paused = DPDK_RUNNING;
934   
935    return 0;
936}
937
938static int dpdk_start_input (libtrace_t *libtrace) {
939    char err[500];
940    err[0] = 0;
941
942    if (dpdk_start_port(FORMAT(libtrace), err, sizeof(err)) != 0) {
943        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
944        free(libtrace->format_data);
945        libtrace->format_data = NULL;
946        return -1;
947    }
948    return 0;
949}
950
951static int dpdk_start_output(libtrace_out_t *libtrace)
952{
953    char err[500];
954    err[0] = 0;
955   
956    if (dpdk_start_port(FORMAT(libtrace), err, sizeof(err)) != 0) {
957        trace_set_err_out(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
958        free(libtrace->format_data);
959        libtrace->format_data = NULL;
960        return -1;
961    }
962    return 0;
963}
964
965static int dpdk_pause_input(libtrace_t * libtrace){
966    /* This stops the device, but can be restarted using rte_eth_dev_start() */
967    if (FORMAT(libtrace)->paused == DPDK_RUNNING) {
968#if DEBUG     
969        fprintf(stderr, "Pausing port\n");
970#endif
971        rte_eth_dev_stop(FORMAT(libtrace)->port);
972        FORMAT(libtrace)->paused = DPDK_PAUSED;
973        /* If we pause it the driver will be reset and likely our counter */
974#if HAS_HW_TIMESTAMPS_82580
975        FORMAT(libtrace)->ts_first_sys = 0;
976        FORMAT(libtrace)->ts_last_sys = 0;
977#endif
978    }
979    return 0;
980}
981
982static int dpdk_write_packet(libtrace_out_t *trace, 
983                libtrace_packet_t *packet){
984    struct rte_mbuf* m_buff[1];
985   
986    int wirelen = trace_get_wire_length(packet);
987    int caplen = trace_get_capture_length(packet);
988   
989    /* Check for a checksum and remove it */
990    if (trace_get_link_type(packet) == TRACE_TYPE_ETH &&
991                                            wirelen == caplen)
992        caplen -= ETHER_CRC_LEN;
993
994    m_buff[0] = rte_pktmbuf_alloc(FORMAT(trace)->pktmbuf_pool);
995    if (m_buff[0] == NULL) {
996        trace_set_err_out(trace, errno, "Cannot get an empty packet buffer");
997        return -1;
998    } else {
999        int ret;
1000        memcpy(rte_pktmbuf_append(m_buff[0], caplen), packet->payload, caplen);
1001        do {
1002            ret = rte_eth_tx_burst(FORMAT(trace)->queue_id, FORMAT(trace)->port, m_buff, 1);
1003        } while (ret != 1);
1004    }
1005
1006    return 0;
1007}
1008
1009static int dpdk_fin_input(libtrace_t * libtrace) {
1010    /* Free our memory structures */
1011    if (libtrace->format_data != NULL) {
1012        /* Close the device completely, device cannot be restarted */
1013        if (FORMAT(libtrace)->port != 0xFF)
1014            rte_eth_dev_close(FORMAT(libtrace)->port);
1015        /* filter here if we used it */
1016                free(libtrace->format_data);
1017        }
1018
1019    /* Revert to the original PCI drivers */
1020    /* No longer in DPDK
1021    rte_eal_pci_exit(); */
1022    return 0;
1023}
1024
1025
1026static int dpdk_fin_output(libtrace_out_t * libtrace) {
1027    /* Free our memory structures */
1028    if (libtrace->format_data != NULL) {
1029        /* Close the device completely, device cannot be restarted */
1030        if (FORMAT(libtrace)->port != 0xFF)
1031            rte_eth_dev_close(FORMAT(libtrace)->port);
1032        /* filter here if we used it */
1033                free(libtrace->format_data);
1034        }
1035
1036    /* Revert to the original PCI drivers */
1037    /* No longer in DPDK
1038    rte_eal_pci_exit(); */
1039    return 0;
1040}
1041
1042/**
1043 * Get the start of additional header that we added to a packet.
1044 */
1045static inline struct dpdk_addt_hdr * get_addt_hdr (const libtrace_packet_t *packet) {
1046    uint8_t *hdrsize;
1047    assert(packet);
1048    assert(packet->buffer);
1049    hdrsize = (uint8_t *) MBUF_PKTDATA(packet->buffer);
1050    /* The byte before the original packet data denotes the size in bytes
1051     * of our additional header that we added sits before the 'size byte' */
1052    hdrsize--;
1053    return (struct dpdk_addt_hdr *) (hdrsize - *hdrsize);
1054}
1055
1056static int dpdk_get_capture_length (const libtrace_packet_t *packet) {
1057    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1058    return hdr->cap_len;
1059}
1060
1061static size_t dpdk_set_capture_length(libtrace_packet_t *packet, size_t size) {
1062    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1063    if (size > hdr->cap_len) {
1064        /* Cannot make a packet bigger */
1065                return trace_get_capture_length(packet);
1066        }
1067
1068    /* Reset the cached capture length first*/
1069    packet->capture_length = -1;
1070    hdr->cap_len = (uint32_t) size;
1071        return trace_get_capture_length(packet);
1072}
1073
1074static int dpdk_get_wire_length (const libtrace_packet_t *packet) {
1075    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1076    int org_cap_size; /* The original capture size */
1077    if (hdr->flags & INCLUDES_HW_TIMESTAMP) {
1078        org_cap_size = (int) rte_pktmbuf_pkt_len(MBUF(packet->buffer)) -
1079                            (MBUF_PKTDATA(packet->buffer) - (char *) hdr) -
1080                            sizeof(struct hw_timestamp_82580);
1081    } else {
1082        org_cap_size = (int) rte_pktmbuf_pkt_len(MBUF(packet->buffer)) -
1083                            (MBUF_PKTDATA(packet->buffer) - (char *) hdr);
1084    }
1085    if (hdr->flags & INCLUDES_CHECKSUM) {
1086        return org_cap_size;
1087    } else {
1088        /* DPDK packets are always TRACE_TYPE_ETH packets */
1089        return org_cap_size + ETHER_CRC_LEN;
1090    }
1091}
1092static int dpdk_get_framing_length (const libtrace_packet_t *packet) {
1093    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1094    if (hdr->flags & INCLUDES_HW_TIMESTAMP)
1095        return sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM +
1096                sizeof(struct hw_timestamp_82580);
1097    else
1098        return sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM;
1099}
1100
1101static int dpdk_prepare_packet(libtrace_t *libtrace UNUSED,
1102                libtrace_packet_t *packet, void *buffer,
1103                libtrace_rt_types_t rt_type, uint32_t flags) {
1104    assert(packet);
1105    if (packet->buffer != buffer &&
1106        packet->buf_control == TRACE_CTRL_PACKET) {
1107        free(packet->buffer);
1108    }
1109
1110    if ((flags & TRACE_PREP_OWN_BUFFER) == TRACE_PREP_OWN_BUFFER) {
1111        packet->buf_control = TRACE_CTRL_PACKET;
1112    } else
1113        packet->buf_control = TRACE_CTRL_EXTERNAL;
1114
1115    packet->buffer = buffer;
1116    packet->header = buffer;
1117
1118    /* Don't use pktmbuf_mtod will fail if the packet is a copy */
1119    packet->payload = (char *)buffer + dpdk_get_framing_length(packet);
1120    packet->type = rt_type;
1121    return 0;
1122}
1123
1124/*
1125 * Does any extra preperation to a captured packet.
1126 * This includes adding our extra header to it with the timestamp
1127 */
1128static inline int dpdk_ready_pkt(libtrace_t *libtrace, libtrace_packet_t *packet,
1129                                                        struct rte_mbuf* pkt){
1130    uint8_t * hdr_size;
1131    struct dpdk_addt_hdr *hdr;
1132#if HAS_HW_TIMESTAMPS_82580
1133    struct hw_timestamp_82580 *hw_ts;
1134    struct timeval cur_sys_time;
1135    uint64_t cur_sys_time_ns;
1136    uint64_t estimated_wraps;
1137   
1138    /* Using gettimeofday because it's most likely to be a vsyscall
1139     * We don't want to slow down anything with systemcalls we dont need
1140     * accauracy */
1141    gettimeofday(&cur_sys_time, NULL);
1142#else
1143# if USE_CLOCK_GETTIME
1144    struct timespec cur_sys_time;
1145   
1146    /* This looks terrible and I feel bad doing it. But it's OK
1147     * on new kernels, because this is a vsyscall */
1148    clock_gettime(CLOCK_REALTIME, &cur_sys_time);
1149# else
1150    struct timeval cur_sys_time;
1151    /* Should be a vsyscall */
1152    gettimeofday(&cur_sys_time, NULL);
1153# endif
1154#endif
1155
1156    /* Record the size of our header */
1157    hdr_size = (uint8_t *) rte_pktmbuf_prepend(pkt, sizeof(uint8_t));
1158    *hdr_size = sizeof(struct dpdk_addt_hdr);
1159    /* Now put our header in front of that size */
1160    hdr = (struct dpdk_addt_hdr *) rte_pktmbuf_prepend(pkt, sizeof(struct dpdk_addt_hdr));
1161    memset(hdr, 0, sizeof(struct dpdk_addt_hdr));
1162   
1163#if GET_MAC_CRC_CHECKSUM
1164    /* Add back in the CRC sum */
1165    pkt->pkt.pkt_len += ETHER_CRC_LEN;
1166    pkt->pkt.data_len += ETHER_CRC_LEN;
1167    hdr->flags |= INCLUDES_CHECKSUM;
1168#endif
1169
1170#if HAS_HW_TIMESTAMPS_82580
1171    /* Taken from igb_ptp.c part of Intel Linux drivers (Good example code)
1172     *
1173     *        +----------+---+   +--------------+
1174     *  82580 |    24    | 8 |   |      32      |
1175     *        +----------+---+   +--------------+
1176     *          reserved  \______ 40 bits _____/
1177     *
1178     * The 40 bit 82580 SYSTIM overflows every
1179     *   2^40 * 10^-9 /  60  = 18.3 minutes.
1180     *
1181     * NOTE picture is in Big Endian order, in memory it's acutally in Little
1182     * Endian (for the full 64 bits) i.e. picture is mirrored
1183     */
1184   
1185    /* The timestamp is sitting before our packet and is included in pkt_len */
1186    hdr->flags |= INCLUDES_HW_TIMESTAMP;
1187    hw_ts = (struct hw_timestamp_82580 *) MBUF_PKTDATA(pkt);
1188   
1189    /* Despite what the documentation says this is in Little
1190     * Endian byteorder. Mask the reserved section out.
1191     */
1192    hdr->timestamp = le64toh(hw_ts->timestamp) & 
1193                ~(((~0ull)>>TS_NBITS_82580)<<TS_NBITS_82580);
1194               
1195    cur_sys_time_ns = TV_TO_NS(cur_sys_time);
1196    if (unlikely(FORMAT(libtrace)->ts_first_sys == 0)) {
1197        FORMAT(libtrace)->ts_first_sys = cur_sys_time_ns - hdr->timestamp;
1198        FORMAT(libtrace)->ts_last_sys = FORMAT(libtrace)->ts_first_sys;
1199    }
1200   
1201    /* This will have serious problems if packets aren't read quickly
1202     * that is within a couple of seconds because our clock cycles every
1203     * 18 seconds */
1204    estimated_wraps = (cur_sys_time_ns - FORMAT(libtrace)->ts_last_sys)
1205                            / (1ull<<TS_NBITS_82580);
1206   
1207    /* Estimated_wraps gives the number of times the counter should have
1208     * wrapped (however depending on value last time it could have wrapped
1209     * twice more (if hw clock is close to its max value) or once less (allowing
1210     * for a bit of variance between hw and sys clock). But if the clock
1211     * shouldn't have wrapped once then don't allow it to go backwards in time */
1212    if (unlikely(estimated_wraps >= 2)) {
1213        /* 2 or more wrap arounds add all but the very last wrap */
1214        FORMAT(libtrace)->wrap_count += estimated_wraps - 1;
1215    }
1216   
1217    /* Set the timestamp to the lowest possible value we're considering */
1218    hdr->timestamp += FORMAT(libtrace)->ts_first_sys +
1219                        FORMAT(libtrace)->wrap_count * (1ull<<TS_NBITS_82580);
1220   
1221    /* In most runs only the first if() will need evaluating - i.e our
1222     * estimate is correct. */
1223    if (unlikely(!WITHIN_VARIANCE(cur_sys_time_ns,
1224                                hdr->timestamp, MAXSKEW_82580))) {
1225        /* Failed to match estimated_wraps-1 (or estimated_wraps in ==0 case) */
1226        FORMAT(libtrace)->wrap_count++;
1227        hdr->timestamp += (1ull<<TS_NBITS_82580);
1228        if (!WITHIN_VARIANCE(cur_sys_time_ns,
1229                                hdr->timestamp, MAXSKEW_82580)) {
1230            /* Failed to match estimated_wraps */
1231            FORMAT(libtrace)->wrap_count++;
1232            hdr->timestamp += (1ull<<TS_NBITS_82580);
1233            if (!WITHIN_VARIANCE(cur_sys_time_ns,
1234                                hdr->timestamp, MAXSKEW_82580)) {
1235                if (estimated_wraps == 0) {
1236                    /* 0 case Failed to match estimated_wraps+2 */
1237                    printf("WARNING - Hardware Timestamp failed to"
1238                                            " match using systemtime!\n");
1239                    hdr->timestamp = cur_sys_time_ns;
1240                } else {
1241                    /* Failed to match estimated_wraps+1 */
1242                    FORMAT(libtrace)->wrap_count++;
1243                    hdr->timestamp += (1ull<<TS_NBITS_82580);
1244                    if (!WITHIN_VARIANCE(cur_sys_time_ns,
1245                                hdr->timestamp, MAXSKEW_82580)) {
1246                        /* Failed to match estimated_wraps+2 */
1247                        printf("WARNING - Hardware Timestamp failed to"
1248                                            " match using systemtime!!\n");
1249                    }
1250                }
1251            }
1252        }
1253    }
1254
1255    /* Log our previous for the next loop */
1256    FORMAT(libtrace)->ts_last_sys = TV_TO_NS(cur_sys_time);
1257
1258#else
1259# if USE_CLOCK_GETTIME
1260    hdr->timestamp = TS_TO_NS(cur_sys_time);
1261# else
1262    hdr->timestamp = TV_TO_NS(cur_sys_time);
1263# endif
1264#endif
1265
1266    /* Intels samples prefetch into level 0 cache lets assume it is a good
1267     * idea and do the same */
1268    rte_prefetch0(rte_pktmbuf_mtod(pkt, void *));
1269    packet->buffer = pkt;
1270    dpdk_prepare_packet(libtrace, packet, packet->buffer, packet->type, 0);
1271
1272    /* Set our capture length for the first time */
1273    hdr->cap_len = dpdk_get_wire_length(packet);
1274    if (!(hdr->flags & INCLUDES_CHECKSUM)) {
1275        hdr->cap_len -= ETHER_CRC_LEN;
1276    }
1277   
1278
1279    return dpdk_get_framing_length(packet) +
1280                        dpdk_get_capture_length(packet);
1281}
1282
1283static int dpdk_read_packet (libtrace_t *libtrace, libtrace_packet_t *packet) {
1284    int nb_rx; /* Number of rx packets we've recevied */
1285    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) */
1286
1287    /* Free the last packet buffer */
1288    if (packet->buffer != NULL) {
1289        /* Buffer is owned by DPDK */
1290        if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1291            rte_pktmbuf_free(packet->buffer);
1292            packet->buffer = NULL;
1293        } else
1294        /* Buffer is owned by packet i.e. has been malloc'd */
1295        if (packet->buf_control == TRACE_CTRL_PACKET) {
1296            free(packet->buffer);
1297            packet->buffer = NULL;
1298        }
1299    }
1300   
1301    packet->buf_control = TRACE_CTRL_EXTERNAL;
1302    packet->type = TRACE_RT_DATA_DPDK;
1303   
1304    /* Wait for a packet */
1305    while (1) {
1306        /* Poll for a single packet */
1307        nb_rx = rte_eth_rx_burst(FORMAT(libtrace)->port,
1308                            FORMAT(libtrace)->queue_id, pkts_burst, 1);       
1309        if (nb_rx > 0) { /* Got a packet - otherwise we keep spining */
1310            return dpdk_ready_pkt(libtrace, packet, pkts_burst[0]);
1311        }
1312    }
1313   
1314    /* We'll never get here - but if we did it would be bad */
1315    return -1;
1316}
1317
1318static struct timeval dpdk_get_timeval (const libtrace_packet_t *packet) {
1319    struct timeval tv;
1320    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1321   
1322    tv.tv_sec = hdr->timestamp / (uint64_t) 1000000000;
1323    tv.tv_usec = (hdr->timestamp % (uint64_t) 1000000000) / 1000;
1324    return tv;
1325}
1326
1327static struct timespec dpdk_get_timespec (const libtrace_packet_t *packet) {
1328    struct timespec ts;
1329    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1330   
1331    ts.tv_sec = hdr->timestamp / (uint64_t) 1000000000;
1332    ts.tv_nsec = hdr->timestamp % (uint64_t) 1000000000;
1333    return ts;
1334}
1335
1336static libtrace_linktype_t dpdk_get_link_type (const libtrace_packet_t *packet UNUSED) {
1337    return TRACE_TYPE_ETH; /* Always ethernet until proven otherwise */
1338}
1339
1340static libtrace_direction_t dpdk_get_direction (const libtrace_packet_t *packet) {
1341    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1342    return (libtrace_direction_t) hdr->direction;
1343}
1344
1345static libtrace_direction_t dpdk_set_direction(libtrace_packet_t *packet, libtrace_direction_t direction) {
1346    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1347    hdr->direction = (uint8_t) direction;
1348    return (libtrace_direction_t) hdr->direction;
1349}
1350
1351/*
1352 * NOTE: Drops could occur for other reasons than running out of buffer
1353 * space. Such as failed MAC checksums and oversized packets.
1354 */
1355static uint64_t dpdk_get_dropped_packets (libtrace_t *trace) {
1356    struct rte_eth_stats stats = {0};
1357   
1358    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1359        return UINT64_MAX;
1360    /* Grab the current stats */
1361    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1362   
1363    /* Get the drop counter */
1364    return (uint64_t) stats.ierrors;
1365}
1366
1367static uint64_t dpdk_get_captured_packets (libtrace_t *trace) {
1368    struct rte_eth_stats stats = {0};
1369   
1370    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1371        return UINT64_MAX;
1372    /* Grab the current stats */
1373    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1374   
1375    /* Get the drop counter */
1376    return (uint64_t) stats.ipackets;
1377}
1378
1379/*
1380 * This is the number of packets filtered by the NIC
1381 * and maybe ahead of number read using libtrace.
1382 *
1383 * XXX we are yet to implement any filtering, but if it was this should
1384 * get the result. So this will just return 0 for now.
1385 */
1386static uint64_t dpdk_get_filtered_packets (libtrace_t *trace) {
1387    struct rte_eth_stats stats = {0};
1388   
1389    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1390        return UINT64_MAX;
1391    /* Grab the current stats */
1392    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1393   
1394    /* Get the drop counter */
1395    return (uint64_t) stats.fdirmiss;
1396}
1397
1398/* Attempts to read a packet in a non-blocking fashion. If one is not
1399 * available a SLEEP event is returned. We do not have the ability to
1400 * create a select()able file descriptor in DPDK.
1401 */
1402static libtrace_eventobj_t dpdk_trace_event(libtrace_t *trace,
1403                                        libtrace_packet_t *packet) {
1404    libtrace_eventobj_t event = {0,0,0.0,0};
1405    int nb_rx; /* Number of receive packets we've read */
1406    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) to rx buffers */
1407   
1408    do {
1409   
1410        /* See if we already have a packet waiting */
1411        nb_rx = rte_eth_rx_burst(FORMAT(trace)->port,
1412                        FORMAT(trace)->queue_id, pkts_burst, 1);
1413       
1414        if (nb_rx > 0) {
1415            /* Free the last packet buffer */
1416            if (packet->buffer != NULL) {
1417                /* Buffer is owned by DPDK */
1418                if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1419                    rte_pktmbuf_free(packet->buffer);
1420                    packet->buffer = NULL;
1421                } else
1422                /* Buffer is owned by packet i.e. has been malloc'd */
1423                if (packet->buf_control == TRACE_CTRL_PACKET) {
1424                    free(packet->buffer);
1425                    packet->buffer = NULL;
1426                }
1427            }
1428           
1429            packet->buf_control = TRACE_CTRL_EXTERNAL;
1430            packet->type = TRACE_RT_DATA_DPDK;
1431            event.type = TRACE_EVENT_PACKET;
1432            event.size = dpdk_ready_pkt(trace, packet, pkts_burst[0]);
1433           
1434            /* XXX - Check this passes the filter trace_read_packet normally
1435             * does this for us but this wont */
1436            if (trace->filter) {
1437                if (!trace_apply_filter(trace->filter, packet)) {
1438                    /* Failed the filter so we loop for another packet */
1439                    trace->filtered_packets ++;
1440                    continue;
1441                }
1442            }
1443            trace->accepted_packets ++;
1444        } else {
1445            /* We only want to sleep for a very short time - we are non-blocking */
1446            event.type = TRACE_EVENT_SLEEP;
1447            event.seconds = 0.0001;
1448            event.size = 0;
1449        }
1450       
1451        /* If we get here we have our event */
1452        break;
1453    } while (1);
1454
1455    return event;
1456}
1457
1458
1459static void dpdk_help(void) {
1460    printf("dpdk format module: $Revision: 1752 $\n");
1461    printf("Supported input URIs:\n");
1462    printf("\tdpdk:<domain:bus:devid.func>-<coreid>\n");
1463    printf("\tThe -<coreid> is optional \n");
1464    printf("\t e.g. dpdk:0000:01:00.1\n");
1465    printf("\t e.g. dpdk:0000:01:00.1-2 (Use the second CPU core)\n\n");
1466    printf("\t By default the last CPU core is used if not otherwise specified.\n");
1467    printf("\t Only a single libtrace instance of dpdk can use the same CPU core.\n");
1468    printf("\t Support for multiple simultaneous instances of dpdk format is currently limited.\n");
1469    printf("\n");
1470    printf("Supported output URIs:\n");
1471    printf("\tSame format as the input URI.\n");
1472    printf("\t e.g. dpdk:0000:01:00.1\n");
1473    printf("\t e.g. dpdk:0000:01:00.1-2 (Use the second CPU core)\n");
1474    printf("\n");
1475}
1476
1477 static struct libtrace_format_t dpdk = {
1478        "dpdk",
1479        "$Id: format_dpdk.c 1805 2013-03-08 02:01:35Z salcock $",
1480        TRACE_FORMAT_DPDK,
1481        NULL,                   /* probe filename */
1482        NULL,                               /* probe magic */
1483        dpdk_init_input,            /* init_input */
1484        dpdk_config_input,          /* config_input */
1485        dpdk_start_input,           /* start_input */
1486        dpdk_pause_input,           /* pause_input */
1487        dpdk_init_output,           /* init_output */
1488        NULL,                               /* config_output */
1489        dpdk_start_output,          /* start_ouput */
1490        dpdk_fin_input,             /* fin_input */
1491        dpdk_fin_output,        /* fin_output */
1492        dpdk_read_packet,           /* read_packet */
1493        dpdk_prepare_packet,    /* prepare_packet */
1494        NULL,                               /* fin_packet */
1495        dpdk_write_packet,          /* write_packet */
1496        dpdk_get_link_type,         /* get_link_type */
1497        dpdk_get_direction,         /* get_direction */
1498        dpdk_set_direction,         /* set_direction */
1499        NULL,                               /* get_erf_timestamp */
1500        dpdk_get_timeval,           /* get_timeval */
1501        dpdk_get_timespec,          /* get_timespec */
1502        NULL,                               /* get_seconds */
1503        NULL,                               /* seek_erf */
1504        NULL,                               /* seek_timeval */
1505        NULL,                               /* seek_seconds */
1506        dpdk_get_capture_length,/* get_capture_length */
1507        dpdk_get_wire_length,   /* get_wire_length */
1508        dpdk_get_framing_length,/* get_framing_length */
1509        dpdk_set_capture_length,/* set_capture_length */
1510        NULL,                               /* get_received_packets */
1511        dpdk_get_filtered_packets,/* get_filtered_packets */
1512        dpdk_get_dropped_packets,/* get_dropped_packets */
1513    dpdk_get_captured_packets,/* get_captured_packets */
1514        NULL,                       /* get_fd */
1515        dpdk_trace_event,               /* trace_event */
1516    dpdk_help,              /* help */
1517        NULL
1518};
1519
1520void dpdk_constructor(void) {
1521        register_format(&dpdk);
1522}
Note: See TracBrowser for help on using the repository browser.