source: lib/format_dpdk.c @ 17a3dff

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

Rename from google map/reduce framework names to something more meaningful.
Rename mapper to perpkt since this is what it actually is in libtrace.

  • Property mode set to 100644
File size: 57.8 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}
829
830/* Attach memory to the port and start the port or restart the ports.
831 */
832static int dpdk_start_port_queues (libtrace_t *libtrace, struct dpdk_format_data_t * format_data, char *err, int errlen, uint16_t rx_queues){
833    int ret, i; /* Check return values for errors */
834    struct rte_eth_link link_info; /* Wait for link */
835   
836    /* Already started */
837    if (format_data->paused == DPDK_RUNNING)
838        return 0;
839
840    /* First time started we need to alloc our memory, doing this here
841     * rather than in enviroment setup because we don't have snaplen then */
842    if (format_data->paused == DPDK_NEVER_STARTED) {
843        if (format_data->snaplen == 0) {
844            format_data->snaplen = RX_MBUF_SIZE;
845            port_conf.rxmode.jumbo_frame = 0;
846            port_conf.rxmode.max_rx_pkt_len = 0;
847        } else {
848            /* Use jumbo frames */
849            port_conf.rxmode.jumbo_frame = 1;
850            port_conf.rxmode.max_rx_pkt_len = format_data->snaplen;
851        }
852
853        /* This is additional overhead so make sure we allow space for this */
854#if GET_MAC_CRC_CHECKSUM
855        format_data->snaplen += ETHER_CRC_LEN;
856#endif
857#if HAS_HW_TIMESTAMPS_82580
858        format_data->snaplen += sizeof(struct hw_timestamp_82580);
859#endif
860
861        /* Create the mbuf pool, which is the place our packets are allocated
862         * from - TODO figure out if there is is a free function (I cannot see one)
863         * NOTE: RX queue requires nb_packets + 1 otherwise it fails to
864         * allocate however that extra 1 packet is not used.
865         * (I assume <= vs < error some where in DPDK code)
866         * TX requires nb_tx_buffers + 1 in the case the queue is full
867         * so that will fill the new buffer and wait until slots in the
868         * ring become available.
869         */
870#if DEBUG
871    printf("Creating mempool named %s\n", format_data->mempool_name);
872#endif
873        format_data->pktmbuf_pool =
874            rte_mempool_create(format_data->mempool_name,
875                       format_data->nb_rx_buf*rx_queues + format_data->nb_tx_buf + 1,
876                       format_data->snaplen + sizeof(struct rte_mbuf) 
877                                        + RTE_PKTMBUF_HEADROOM,
878                       8, sizeof(struct rte_pktmbuf_pool_private),
879                       rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
880                       0, MEMPOOL_F_SP_PUT | MEMPOOL_F_SC_GET);
881
882        if (format_data->pktmbuf_pool == NULL) {
883            snprintf(err, errlen, "Intel DPDK - Initialisation of mbuf "
884                        "pool failed: %s", strerror(rte_errno));
885            return -1;
886        }
887    }
888   
889    /* ----------- Now do the setup for the port mapping ------------ */
890    /* Order of calls must be
891     * rte_eth_dev_configure()
892     * rte_eth_tx_queue_setup()
893     * rte_eth_rx_queue_setup()
894     * rte_eth_dev_start()
895     * other rte_eth calls
896     */
897   
898    /* This must be called first before another *eth* function
899     * 1 rx, 1 tx queue, port_conf sets checksum stripping etc */
900    ret = rte_eth_dev_configure(format_data->port, rx_queues, 1, &port_conf);
901    if (ret < 0) {
902        snprintf(err, errlen, "Intel DPDK - Cannot configure device port"
903                            " %"PRIu8" : %s", format_data->port,
904                            strerror(-ret));
905        return -1;
906    }
907#if DEBUG
908    printf("Doing dev configure\n");
909#endif
910    /* Initilise the TX queue a minimum value if using this port for
911     * receiving. Otherwise a larger size if writing packets.
912     */
913    ret = rte_eth_tx_queue_setup(format_data->port, format_data->queue_id,
914                        format_data->nb_tx_buf, SOCKET_ID_ANY, &tx_conf);
915    if (ret < 0) {
916        snprintf(err, errlen, "Intel DPDK - Cannot configure TX queue on port"
917                            " %"PRIu8" : %s", format_data->port,
918                            strerror(-ret));
919        return -1;
920    }
921   
922    for (i=0; i < rx_queues; i++) {
923#if DEBUG
924    printf("Doing queue configure\n");
925#endif 
926                /* Initilise the RX queue with some packets from memory */
927                ret = rte_eth_rx_queue_setup(format_data->port, i,
928                                                                format_data->nb_rx_buf, SOCKET_ID_ANY,
929                                                                &rx_conf, format_data->pktmbuf_pool);
930                if (ret < 0) {
931                        snprintf(err, errlen, "Intel DPDK - Cannot configure RX queue on port"
932                                                " %"PRIu8" : %s", format_data->port,
933                                                strerror(-ret));
934                        return -1;
935                }
936        }
937   
938#if DEBUG
939    printf("Doing start device\n");
940#endif 
941    /* Start device */
942    ret = rte_eth_dev_start(format_data->port);
943#if DEBUG
944    printf("Done start device\n");
945#endif 
946    if (ret < 0) {
947        snprintf(err, errlen, "Intel DPDK - rte_eth_dev_start failed : %s",
948                    strerror(-ret));
949        return -1;
950    }
951
952
953    /* Default promiscuous to on */
954    if (format_data->promisc == -1)
955        format_data->promisc = 1;
956   
957    if (format_data->promisc == 1)
958        rte_eth_promiscuous_enable(format_data->port);
959    else
960        rte_eth_promiscuous_disable(format_data->port);
961   
962   
963    /* We have now successfully started/unpased */
964    format_data->paused = DPDK_RUNNING;
965   
966    // Can use remote launch for all
967    /*RTE_LCORE_FOREACH_SLAVE(i) {
968                rte_eal_remote_launch(perpkt_threads_entry, (void *)libtrace, i);
969        }*/
970   
971    /* Wait for the link to come up */
972    rte_eth_link_get(format_data->port, &link_info);
973#if DEBUG
974    printf("Link status is %d %d %d\n", (int) link_info.link_status,
975            (int) link_info.link_duplex, (int) link_info.link_speed);
976#endif
977
978    return 0;
979}
980
981static int dpdk_start_input (libtrace_t *libtrace) {
982    char err[500];
983    err[0] = 0;
984
985    if (dpdk_start_port(FORMAT(libtrace), err, sizeof(err)) != 0) {
986        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
987        free(libtrace->format_data);
988        libtrace->format_data = NULL;
989        return -1;
990    }
991    return 0;
992}
993
994static int dpdk_pstart_input (libtrace_t *libtrace) {
995    char err[500];
996    int enabled_lcore_count = 0, i=0;
997    int tot = libtrace->perpkt_thread_count;
998    err[0] = 0;
999       
1000        libtrace->perpkt_thread_count;
1001       
1002        for (i = 0; i < RTE_MAX_LCORE; i++)
1003        {
1004                if (rte_lcore_is_enabled(i))
1005                        enabled_lcore_count++;
1006        }
1007       
1008        tot = MIN(libtrace->perpkt_thread_count, enabled_lcore_count);
1009        tot = MIN(tot, 8);
1010        printf("Running pstart DPDK %d %d %d %d\n", tot, libtrace->perpkt_thread_count, enabled_lcore_count, rte_lcore_count());
1011       
1012    if (dpdk_start_port_queues(libtrace, FORMAT(libtrace), err, sizeof(err), tot) != 0) {
1013        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
1014        free(libtrace->format_data);
1015        libtrace->format_data = NULL;
1016        return -1;
1017    }
1018   
1019    return 0;
1020    return tot;
1021}
1022
1023static int dpdk_start_output(libtrace_out_t *libtrace)
1024{
1025    char err[500];
1026    err[0] = 0;
1027   
1028    if (dpdk_start_port(FORMAT(libtrace), err, sizeof(err)) != 0) {
1029        trace_set_err_out(libtrace, TRACE_ERR_INIT_FAILED, "%s", err);
1030        free(libtrace->format_data);
1031        libtrace->format_data = NULL;
1032        return -1;
1033    }
1034    return 0;
1035}
1036
1037static int dpdk_pause_input(libtrace_t * libtrace){
1038    /* This stops the device, but can be restarted using rte_eth_dev_start() */
1039    if (FORMAT(libtrace)->paused == DPDK_RUNNING) {
1040#if DEBUG     
1041        printf("Pausing port\n");
1042#endif
1043        rte_eth_dev_stop(FORMAT(libtrace)->port);
1044        FORMAT(libtrace)->paused = DPDK_PAUSED;
1045        /* If we pause it the driver will be reset and likely our counter */
1046#if HAS_HW_TIMESTAMPS_82580
1047        FORMAT(libtrace)->ts_first_sys = 0;
1048        FORMAT(libtrace)->ts_last_sys = 0;
1049#endif
1050    }
1051    return 0;
1052}
1053
1054static int dpdk_write_packet(libtrace_out_t *trace, 
1055                libtrace_packet_t *packet){
1056    struct rte_mbuf* m_buff[1];
1057   
1058    int wirelen = trace_get_wire_length(packet);
1059    int caplen = trace_get_capture_length(packet);
1060   
1061    /* Check for a checksum and remove it */
1062    if (trace_get_link_type(packet) == TRACE_TYPE_ETH &&
1063                                            wirelen == caplen)
1064        caplen -= ETHER_CRC_LEN;
1065
1066    m_buff[0] = rte_pktmbuf_alloc(FORMAT(trace)->pktmbuf_pool);
1067    if (m_buff[0] == NULL) {
1068        trace_set_err_out(trace, errno, "Cannot get an empty packet buffer");
1069        return -1;
1070    } else {
1071        int ret;
1072        memcpy(rte_pktmbuf_append(m_buff[0], caplen), packet->payload, caplen);
1073        do {
1074            ret = rte_eth_tx_burst(FORMAT(trace)->queue_id, FORMAT(trace)->port, m_buff, 1);
1075        } while (ret != 1);
1076    }
1077
1078    return 0;
1079}
1080
1081static int dpdk_fin_input(libtrace_t * libtrace) {
1082    /* Free our memory structures */
1083    if (libtrace->format_data != NULL) {
1084        /* Close the device completely, device cannot be restarted */
1085        if (FORMAT(libtrace)->port != 0xFF)
1086            rte_eth_dev_close(FORMAT(libtrace)->port);
1087        /* filter here if we used it */
1088                free(libtrace->format_data);
1089        }
1090
1091    /* Revert to the original PCI drivers */
1092    /* No longer in DPDK
1093    rte_eal_pci_exit(); */
1094    return 0;
1095}
1096
1097
1098static int dpdk_fin_output(libtrace_out_t * libtrace) {
1099    /* Free our memory structures */
1100    if (libtrace->format_data != NULL) {
1101        /* Close the device completely, device cannot be restarted */
1102        if (FORMAT(libtrace)->port != 0xFF)
1103            rte_eth_dev_close(FORMAT(libtrace)->port);
1104        /* filter here if we used it */
1105                free(libtrace->format_data);
1106        }
1107
1108    /* Revert to the original PCI drivers */
1109    /* No longer in DPDK
1110    rte_eal_pci_exit(); */
1111    return 0;
1112}
1113
1114/**
1115 * Get the start of additional header that we added to a packet.
1116 */
1117static inline struct dpdk_addt_hdr * get_addt_hdr (const libtrace_packet_t *packet) {
1118    uint8_t *hdrsize;
1119    assert(packet);
1120    assert(packet->buffer);
1121    hdrsize = (uint8_t *) MBUF_PKTDATA(packet->buffer);
1122    /* The byte before the original packet data denotes the size in bytes
1123     * of our additional header that we added sits before the 'size byte' */
1124    hdrsize--;
1125    return (struct dpdk_addt_hdr *) (hdrsize - *hdrsize);
1126}
1127
1128static int dpdk_get_capture_length (const libtrace_packet_t *packet) {
1129    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1130    return hdr->cap_len;
1131}
1132
1133static size_t dpdk_set_capture_length(libtrace_packet_t *packet, size_t size) {
1134    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1135    if (size > hdr->cap_len) {
1136        /* Cannot make a packet bigger */
1137                return trace_get_capture_length(packet);
1138        }
1139
1140    /* Reset the cached capture length first*/
1141    packet->capture_length = -1;
1142    hdr->cap_len = (uint32_t) size;
1143        return trace_get_capture_length(packet);
1144}
1145
1146static int dpdk_get_wire_length (const libtrace_packet_t *packet) {
1147    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1148    int org_cap_size; /* The original capture size */
1149    if (hdr->flags & INCLUDES_HW_TIMESTAMP) {
1150        org_cap_size = (int) rte_pktmbuf_pkt_len(MBUF(packet->buffer)) -
1151                            (MBUF_PKTDATA(packet->buffer) - (char *) hdr) -
1152                            sizeof(struct hw_timestamp_82580);
1153    } else {
1154        org_cap_size = (int) rte_pktmbuf_pkt_len(MBUF(packet->buffer)) -
1155                            (MBUF_PKTDATA(packet->buffer) - (char *) hdr);
1156    }
1157    if (hdr->flags & INCLUDES_CHECKSUM) {
1158        return org_cap_size;
1159    } else {
1160        /* DPDK packets are always TRACE_TYPE_ETH packets */
1161        return org_cap_size + ETHER_CRC_LEN;
1162    }
1163}
1164static int dpdk_get_framing_length (const libtrace_packet_t *packet) {
1165    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1166    if (hdr->flags & INCLUDES_HW_TIMESTAMP)
1167        return sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM +
1168                sizeof(struct hw_timestamp_82580);
1169    else
1170        return sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM;
1171}
1172
1173static int dpdk_prepare_packet(libtrace_t *libtrace UNUSED,
1174                libtrace_packet_t *packet, void *buffer,
1175                libtrace_rt_types_t rt_type, uint32_t flags) {
1176    assert(packet);
1177    if (packet->buffer != buffer &&
1178        packet->buf_control == TRACE_CTRL_PACKET) {
1179        free(packet->buffer);
1180    }
1181
1182    if ((flags & TRACE_PREP_OWN_BUFFER) == TRACE_PREP_OWN_BUFFER) {
1183        packet->buf_control = TRACE_CTRL_PACKET;
1184    } else
1185        packet->buf_control = TRACE_CTRL_EXTERNAL;
1186
1187    packet->buffer = buffer;
1188    packet->header = buffer;
1189
1190    /* Don't use pktmbuf_mtod will fail if the packet is a copy */
1191    packet->payload = (char *)buffer + dpdk_get_framing_length(packet);
1192    packet->type = rt_type;
1193    return 0;
1194}
1195
1196/*
1197 * Does any extra preperation to a captured packet.
1198 * This includes adding our extra header to it with the timestamp
1199 */
1200static inline int dpdk_ready_pkt(libtrace_t *libtrace, libtrace_packet_t *packet,
1201                                                        struct rte_mbuf* pkt){
1202    uint8_t * hdr_size;
1203    struct dpdk_addt_hdr *hdr;
1204#if HAS_HW_TIMESTAMPS_82580
1205    struct hw_timestamp_82580 *hw_ts;
1206    struct timeval cur_sys_time;
1207    uint64_t cur_sys_time_ns;
1208    uint64_t estimated_wraps;
1209   
1210    /* Using gettimeofday because it's most likely to be a vsyscall
1211     * We don't want to slow down anything with systemcalls we dont need
1212     * accauracy */
1213    gettimeofday(&cur_sys_time, NULL);
1214#else
1215# if USE_CLOCK_GETTIME
1216    struct timespec cur_sys_time;
1217   
1218    /* This looks terrible and I feel bad doing it. But it's OK
1219     * on new kernels, because this is a vsyscall */
1220    clock_gettime(CLOCK_REALTIME, &cur_sys_time);
1221# else
1222    struct timeval cur_sys_time;
1223    /* Should be a vsyscall */
1224    gettimeofday(&cur_sys_time, NULL);
1225# endif
1226#endif
1227
1228    /* Record the size of our header */
1229    hdr_size = (uint8_t *) rte_pktmbuf_prepend(pkt, sizeof(uint8_t));
1230    *hdr_size = sizeof(struct dpdk_addt_hdr);
1231    /* Now put our header in front of that size */
1232    hdr = (struct dpdk_addt_hdr *) rte_pktmbuf_prepend(pkt, sizeof(struct dpdk_addt_hdr));
1233    memset(hdr, 0, sizeof(struct dpdk_addt_hdr));
1234   
1235#if GET_MAC_CRC_CHECKSUM
1236    /* Add back in the CRC sum */
1237    pkt->pkt.pkt_len += ETHER_CRC_LEN;
1238    pkt->pkt.data_len += ETHER_CRC_LEN;
1239    hdr->flags |= INCLUDES_CHECKSUM;
1240#endif
1241
1242#if HAS_HW_TIMESTAMPS_82580
1243    /* Taken from igb_ptp.c part of Intel Linux drivers (Good example code)
1244     *
1245     *        +----------+---+   +--------------+
1246     *  82580 |    24    | 8 |   |      32      |
1247     *        +----------+---+   +--------------+
1248     *          reserved  \______ 40 bits _____/
1249     *
1250     * The 40 bit 82580 SYSTIM overflows every
1251     *   2^40 * 10^-9 /  60  = 18.3 minutes.
1252     *
1253     * NOTE picture is in Big Endian order, in memory it's acutally in Little
1254     * Endian (for the full 64 bits) i.e. picture is mirrored
1255     */
1256   
1257    /* The timestamp is sitting before our packet and is included in pkt_len */
1258    hdr->flags |= INCLUDES_HW_TIMESTAMP;
1259    hw_ts = (struct hw_timestamp_82580 *) MBUF_PKTDATA(pkt);
1260   
1261    /* Despite what the documentation says this is in Little
1262     * Endian byteorder. Mask the reserved section out.
1263     */
1264    hdr->timestamp = le64toh(hw_ts->timestamp) & 
1265                ~(((~0ull)>>TS_NBITS_82580)<<TS_NBITS_82580);
1266               
1267    cur_sys_time_ns = TV_TO_NS(cur_sys_time);
1268    if (unlikely(FORMAT(libtrace)->ts_first_sys == 0)) {
1269        FORMAT(libtrace)->ts_first_sys = cur_sys_time_ns - hdr->timestamp;
1270        FORMAT(libtrace)->ts_last_sys = FORMAT(libtrace)->ts_first_sys;
1271    }
1272   
1273    /* This will have serious problems if packets aren't read quickly
1274     * that is within a couple of seconds because our clock cycles every
1275     * 18 seconds */
1276    estimated_wraps = (cur_sys_time_ns - FORMAT(libtrace)->ts_last_sys)
1277                            / (1ull<<TS_NBITS_82580);
1278   
1279    /* Estimated_wraps gives the number of times the counter should have
1280     * wrapped (however depending on value last time it could have wrapped
1281     * twice more (if hw clock is close to its max value) or once less (allowing
1282     * for a bit of variance between hw and sys clock). But if the clock
1283     * shouldn't have wrapped once then don't allow it to go backwards in time */
1284    if (unlikely(estimated_wraps >= 2)) {
1285        /* 2 or more wrap arounds add all but the very last wrap */
1286        FORMAT(libtrace)->wrap_count += estimated_wraps - 1;
1287    }
1288   
1289    /* Set the timestamp to the lowest possible value we're considering */
1290    hdr->timestamp += FORMAT(libtrace)->ts_first_sys +
1291                        FORMAT(libtrace)->wrap_count * (1ull<<TS_NBITS_82580);
1292   
1293    /* In most runs only the first if() will need evaluating - i.e our
1294     * estimate is correct. */
1295    if (unlikely(!WITHIN_VARIANCE(cur_sys_time_ns,
1296                                hdr->timestamp, MAXSKEW_82580))) {
1297        /* Failed to match estimated_wraps-1 (or estimated_wraps in ==0 case) */
1298        FORMAT(libtrace)->wrap_count++;
1299        hdr->timestamp += (1ull<<TS_NBITS_82580);
1300        if (!WITHIN_VARIANCE(cur_sys_time_ns,
1301                                hdr->timestamp, MAXSKEW_82580)) {
1302            /* Failed to match estimated_wraps */
1303            FORMAT(libtrace)->wrap_count++;
1304            hdr->timestamp += (1ull<<TS_NBITS_82580);
1305            if (!WITHIN_VARIANCE(cur_sys_time_ns,
1306                                hdr->timestamp, MAXSKEW_82580)) {
1307                if (estimated_wraps == 0) {
1308                    /* 0 case Failed to match estimated_wraps+2 */
1309                    printf("WARNING - Hardware Timestamp failed to"
1310                                            " match using systemtime!\n");
1311                    hdr->timestamp = cur_sys_time_ns;
1312                } else {
1313                    /* Failed to match estimated_wraps+1 */
1314                    FORMAT(libtrace)->wrap_count++;
1315                    hdr->timestamp += (1ull<<TS_NBITS_82580);
1316                    if (!WITHIN_VARIANCE(cur_sys_time_ns,
1317                                hdr->timestamp, MAXSKEW_82580)) {
1318                        /* Failed to match estimated_wraps+2 */
1319                        printf("WARNING - Hardware Timestamp failed to"
1320                                            " match using systemtime!!\n");
1321                    }
1322                }
1323            }
1324        }
1325    }
1326
1327    /* Log our previous for the next loop */
1328    FORMAT(libtrace)->ts_last_sys = TV_TO_NS(cur_sys_time);
1329
1330#else
1331# if USE_CLOCK_GETTIME
1332    hdr->timestamp = TS_TO_NS(cur_sys_time);
1333# else
1334    hdr->timestamp = TV_TO_NS(cur_sys_time);
1335# endif
1336#endif
1337
1338    /* Intels samples prefetch into level 0 cache lets assume it is a good
1339     * idea and do the same */
1340    rte_prefetch0(rte_pktmbuf_mtod(pkt, void *));
1341    packet->buffer = pkt;
1342    dpdk_prepare_packet(libtrace, packet, packet->buffer, packet->type, 0);
1343
1344    /* Set our capture length for the first time */
1345    hdr->cap_len = dpdk_get_wire_length(packet);
1346    if (!(hdr->flags & INCLUDES_CHECKSUM)) {
1347        hdr->cap_len -= ETHER_CRC_LEN;
1348    }
1349   
1350
1351    return dpdk_get_framing_length(packet) +
1352                        dpdk_get_capture_length(packet);
1353}
1354
1355
1356static void dpdk_fin_packet(libtrace_packet_t *packet)
1357{
1358        if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1359                rte_pktmbuf_free(packet->buffer);
1360                packet->buffer = NULL;
1361        }
1362}
1363
1364static int dpdk_read_packet (libtrace_t *libtrace, libtrace_packet_t *packet) {
1365    int nb_rx; /* Number of rx packets we've recevied */
1366    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) */
1367
1368    /* Free the last packet buffer */
1369    if (packet->buffer != NULL) {
1370        /* Buffer is owned by DPDK */
1371        if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1372            rte_pktmbuf_free(packet->buffer);
1373            packet->buffer = NULL;
1374        } else
1375        /* Buffer is owned by packet i.e. has been malloc'd */
1376        if (packet->buf_control == TRACE_CTRL_PACKET) {
1377            free(packet->buffer);
1378            packet->buffer = NULL;
1379        }
1380    }
1381   
1382    packet->buf_control = TRACE_CTRL_EXTERNAL;
1383    packet->type = TRACE_RT_DATA_DPDK;
1384   
1385    /* Wait for a packet */
1386    while (1) {
1387        /* Poll for a single packet */
1388        nb_rx = rte_eth_rx_burst(FORMAT(libtrace)->port,
1389                            FORMAT(libtrace)->queue_id, pkts_burst, 1);       
1390        if (nb_rx > 0) { /* Got a packet - otherwise we keep spining */
1391            return dpdk_ready_pkt(libtrace, packet, pkts_burst[0]);
1392        }
1393    }
1394   
1395    /* We'll never get here - but if we did it would be bad */
1396    return -1;
1397}
1398libtrace_thread_t * get_thread_table(libtrace_t *libtrace);
1399static int dpdk_pread_packet (libtrace_t *libtrace, libtrace_packet_t *packet) {
1400    int nb_rx; /* Number of rx packets we've recevied */
1401    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) */
1402
1403    /* Free the last packet buffer */
1404    if (packet->buffer != NULL) {
1405        /* Buffer is owned by DPDK */
1406        if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1407            rte_pktmbuf_free(packet->buffer);
1408            packet->buffer = NULL;
1409        } else
1410        /* Buffer is owned by packet i.e. has been malloc'd */
1411        if (packet->buf_control == TRACE_CTRL_PACKET) {
1412            free(packet->buffer);
1413            packet->buffer = NULL;
1414        }
1415    }
1416   
1417    packet->buf_control = TRACE_CTRL_EXTERNAL;
1418    packet->type = TRACE_RT_DATA_DPDK;
1419   
1420    /* Wait for a packet */
1421    while (1) {
1422        /* Poll for a single packet */
1423        nb_rx = rte_eth_rx_burst(FORMAT(libtrace)->port,
1424                            get_thread_table_num(libtrace), pkts_burst, 1);
1425        if (nb_rx > 0) { /* Got a packet - otherwise we keep spining */
1426                        printf("Doing P READ PACKET port=%d q=%d\n", (int) FORMAT(libtrace)->port, (int) get_thread_table_num(libtrace));
1427            return dpdk_ready_pkt(libtrace, packet, pkts_burst[0]);
1428        }
1429        // Check the message queue this could be (Well it shouldn't but anyway) be less than 0
1430        if (libtrace_message_queue_count(&(get_thread_table(libtrace)->messages)) > 0) {
1431                        printf("Extra message yay");
1432                        return -2;
1433                }
1434    }
1435   
1436    /* We'll never get here - but if we did it would be bad */
1437    return -1;
1438}
1439
1440static struct timeval dpdk_get_timeval (const libtrace_packet_t *packet) {
1441    struct timeval tv;
1442    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1443   
1444    tv.tv_sec = hdr->timestamp / (uint64_t) 1000000000;
1445    tv.tv_usec = (hdr->timestamp % (uint64_t) 1000000000) / 1000;
1446    return tv;
1447}
1448
1449static struct timespec dpdk_get_timespec (const libtrace_packet_t *packet) {
1450    struct timespec ts;
1451    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1452   
1453    ts.tv_sec = hdr->timestamp / (uint64_t) 1000000000;
1454    ts.tv_nsec = hdr->timestamp % (uint64_t) 1000000000;
1455    return ts;
1456}
1457
1458static libtrace_linktype_t dpdk_get_link_type (const libtrace_packet_t *packet UNUSED) {
1459    return TRACE_TYPE_ETH; /* Always ethernet until proven otherwise */
1460}
1461
1462static libtrace_direction_t dpdk_get_direction (const libtrace_packet_t *packet) {
1463    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1464    return (libtrace_direction_t) hdr->direction;
1465}
1466
1467static libtrace_direction_t dpdk_set_direction(libtrace_packet_t *packet, libtrace_direction_t direction) {
1468    struct dpdk_addt_hdr * hdr = get_addt_hdr(packet);
1469    hdr->direction = (uint8_t) direction;
1470    return (libtrace_direction_t) hdr->direction;
1471}
1472
1473/*
1474 * NOTE: Drops could occur for other reasons than running out of buffer
1475 * space. Such as failed MAC checksums and oversized packets.
1476 */
1477static uint64_t dpdk_get_dropped_packets (libtrace_t *trace) {
1478    struct rte_eth_stats stats = {0};
1479   
1480    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1481        return UINT64_MAX;
1482    /* Grab the current stats */
1483    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1484   
1485    /* Get the drop counter */
1486    return (uint64_t) stats.ierrors;
1487}
1488
1489static uint64_t dpdk_get_captured_packets (libtrace_t *trace) {
1490    struct rte_eth_stats stats = {0};
1491   
1492    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1493        return UINT64_MAX;
1494    /* Grab the current stats */
1495    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1496   
1497    /* Get the drop counter */
1498    return (uint64_t) stats.ipackets;
1499}
1500
1501/*
1502 * This is the number of packets filtered by the NIC
1503 * and maybe ahead of number read using libtrace.
1504 *
1505 * XXX we are yet to implement any filtering, but if it was this should
1506 * get the result. So this will just return 0 for now.
1507 */
1508static uint64_t dpdk_get_filtered_packets (libtrace_t *trace) {
1509    struct rte_eth_stats stats = {0};
1510   
1511    if (trace->format_data == NULL || FORMAT(trace)->port == 0xFF)
1512        return UINT64_MAX;
1513    /* Grab the current stats */
1514    rte_eth_stats_get(FORMAT(trace)->port, &stats);
1515   
1516    /* Get the drop counter */
1517    return (uint64_t) stats.fdirmiss;
1518}
1519
1520/* Attempts to read a packet in a non-blocking fashion. If one is not
1521 * available a SLEEP event is returned. We do not have the ability to
1522 * create a select()able file descriptor in DPDK.
1523 */
1524static libtrace_eventobj_t dpdk_trace_event(libtrace_t *trace,
1525                                        libtrace_packet_t *packet) {
1526    libtrace_eventobj_t event = {0,0,0.0,0};
1527    int nb_rx; /* Number of receive packets we've read */
1528    struct rte_mbuf* pkts_burst[1]; /* Array of 1 pointer(s) to rx buffers */
1529   
1530    do {
1531   
1532        /* See if we already have a packet waiting */
1533        nb_rx = rte_eth_rx_burst(FORMAT(trace)->port,
1534                        FORMAT(trace)->queue_id, pkts_burst, 1);
1535       
1536        if (nb_rx > 0) {
1537            /* Free the last packet buffer */
1538            if (packet->buffer != NULL) {
1539                /* Buffer is owned by DPDK */
1540                if ( packet->buf_control == TRACE_CTRL_EXTERNAL ) {
1541                    rte_pktmbuf_free(packet->buffer);
1542                    packet->buffer = NULL;
1543                } else
1544                /* Buffer is owned by packet i.e. has been malloc'd */
1545                if (packet->buf_control == TRACE_CTRL_PACKET) {
1546                    free(packet->buffer);
1547                    packet->buffer = NULL;
1548                }
1549            }
1550           
1551            packet->buf_control = TRACE_CTRL_EXTERNAL;
1552            packet->type = TRACE_RT_DATA_DPDK;
1553            event.type = TRACE_EVENT_PACKET;
1554            event.size = dpdk_ready_pkt(trace, packet, pkts_burst[0]);
1555           
1556            /* XXX - Check this passes the filter trace_read_packet normally
1557             * does this for us but this wont */
1558            if (trace->filter) {
1559                if (!trace_apply_filter(trace->filter, packet)) {
1560                    /* Failed the filter so we loop for another packet */
1561                    continue;
1562                }
1563            }
1564        } else {
1565            /* We only want to sleep for a very short time - we are non-blocking */
1566            event.type = TRACE_EVENT_SLEEP;
1567            event.seconds = 0.0001;
1568            event.size = 0;
1569        }
1570       
1571        /* If we get here we have our event */
1572        break;
1573    } while (1);
1574
1575    return event;
1576}
1577
1578
1579static void dpdk_help(void) {
1580    printf("dpdk format module: $Revision: 1752 $\n");
1581    printf("Supported input URIs:\n");
1582    printf("\tdpdk:<domain:bus:devid.func>-<coreid>\n");
1583    printf("\tThe -<coreid> is optional \n");
1584    printf("\t e.g. dpdk:0000:01:00.1\n");
1585    printf("\t e.g. dpdk:0000:01:00.1-2 (Use the second CPU core)\n\n");
1586    printf("\t By default the last CPU core is used if not otherwise specified.\n");
1587    printf("\t Only a single libtrace instance of dpdk can use the same CPU core.\n");
1588    printf("\t Support for multiple simultaneous instances of dpdk format is currently limited.\n");
1589    printf("\n");
1590    printf("Supported output URIs:\n");
1591    printf("\tSame format as the input URI.\n");
1592    printf("\t e.g. dpdk:0000:01:00.1\n");
1593    printf("\t e.g. dpdk:0000:01:00.1-2 (Use the second CPU core)\n");
1594    printf("\n");
1595}
1596
1597 static struct libtrace_format_t dpdk = {
1598        "dpdk",
1599        "$Id: format_dpdk.c 1805 2013-03-08 02:01:35Z salcock $",
1600        TRACE_FORMAT_DPDK,
1601        NULL,                   /* probe filename */
1602        NULL,                               /* probe magic */
1603        dpdk_init_input,            /* init_input */
1604        dpdk_config_input,          /* config_input */
1605        dpdk_start_input,           /* start_input */
1606        dpdk_pause_input,           /* pause_input */
1607        dpdk_init_output,           /* init_output */
1608        NULL,                               /* config_output */
1609        dpdk_start_output,          /* start_ouput */
1610        dpdk_fin_input,             /* fin_input */
1611        dpdk_fin_output,        /* fin_output */
1612        dpdk_read_packet,           /* read_packet */
1613        dpdk_prepare_packet,    /* prepare_packet */
1614        dpdk_fin_packet,                                    /* fin_packet */
1615        dpdk_write_packet,          /* write_packet */
1616        dpdk_get_link_type,         /* get_link_type */
1617        dpdk_get_direction,         /* get_direction */
1618        dpdk_set_direction,         /* set_direction */
1619        NULL,                               /* get_erf_timestamp */
1620        dpdk_get_timeval,           /* get_timeval */
1621        dpdk_get_timespec,          /* get_timespec */
1622        NULL,                               /* get_seconds */
1623        NULL,                               /* seek_erf */
1624        NULL,                               /* seek_timeval */
1625        NULL,                               /* seek_seconds */
1626        dpdk_get_capture_length,/* get_capture_length */
1627        dpdk_get_wire_length,   /* get_wire_length */
1628        dpdk_get_framing_length,/* get_framing_length */
1629        dpdk_set_capture_length,/* set_capture_length */
1630        NULL,                               /* get_received_packets */
1631        dpdk_get_filtered_packets,/* get_filtered_packets */
1632        dpdk_get_dropped_packets,/* get_dropped_packets */
1633    dpdk_get_captured_packets,/* get_captured_packets */
1634        NULL,                       /* get_fd */
1635        dpdk_trace_event,               /* trace_event */
1636    dpdk_help,              /* help */
1637    dpdk_pstart_input, /* pstart_input */
1638        dpdk_pread_packet, /* pread_packet */
1639        dpdk_pause_input, /* ppause */
1640        dpdk_fin_input, /* p_fin */
1641        dpdk_pconfig_input, /* pconfig_input */
1642        NULL
1643};
1644
1645void dpdk_constructor(void) {
1646        register_format(&dpdk);
1647}
Note: See TracBrowser for help on using the repository browser.