source: lib/format_dpdk.c @ 6a6e6a8

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

More documentation, including some renaming and modifications to behaviour

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