source: lib/format_dpdk.c @ b585975

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

Adds support for DPDK v1.8.0

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