source: lib/format_dpdk.c @ 6a1d288

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

Remove some debug references to DPDK version and magic which have been removed in 1.7

This would only be a probably if the DEBUG flag was set when compiling

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