source: lib/format_dpdk.c @ 60e8e86

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

My work from over summer, with a few things tidied up and updated to include recent commits/patches to bring this up to date. Still very much work in progress.

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