source: lib/format_dpdk.c @ 773a2a3

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

Remove debug prints from dpdk and int/ring

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