source: lib/format_dpdk.c @ d7fd648

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

Improves speed of the DPDK format(and parallel libtrace) and fixes some DPDK bugs

Fixes bug with PCI address being parsed as a decimal instead of hex.
Fixes bug so DPDK Breaks out of loop when libtrace_halt is called

For performance

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