source: lib/format_dpdk.c @ 6b98325

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

Removes pconfig_input() and replaces trace_config() with trace_set_<option>

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