source: lib/format_dpdk.c @ 66baa54

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

Print DPDK debug to stderr rather than stdout

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