source: lib/format_dpdk.c @ 9f43919

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

A terrible fix to allow nesting of getopts, because DPDK uses this internally.
This is probably going to break for someone, but it is the best solution I can think of for now.
In the future hopefully DPDK will have a programming interface for all these settings.

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