source: lib/format_dag25.c @ 6b98325

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

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

  • Removes trace_pconfig completely - only trace_set_hasher is left now in trace_config
  • Rework user configuration so this is no longer modified directly. Now we just apply it directly to a trace.
  • Many minor documentation fixes and additions
  • Property mode set to 100644
File size: 44.6 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 * Authors: Daniel Lawson
8 *          Perry Lorier
9 *          Shane Alcock
10 *         
11 * All rights reserved.
12 *
13 * This code has been developed by the University of Waikato WAND
14 * research group. For further information please see http://www.wand.net.nz/
15 *
16 * libtrace is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * libtrace is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with libtrace; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29 *
30 * $Id$
31 *
32 */
33
34#define _GNU_SOURCE
35
36#include "config.h"
37#include "common.h"
38#include "libtrace.h"
39#include "libtrace_int.h"
40#include "format_helper.h"
41#include "format_erf.h"
42
43#include <assert.h>
44#include <errno.h>
45#include <fcntl.h>
46#include <stdio.h>
47#include <string.h>
48#include <stdlib.h>
49#include <sys/stat.h>
50
51#include <sys/mman.h>
52/* XXX: Windows doesn't have pthreads, but this code doesn't compile under
53 * Windows anyway so we'll worry about this more later :] */
54#include <pthread.h>
55
56
57#ifdef WIN32
58#  include <io.h>
59#  include <share.h>
60#  define PATH_MAX _MAX_PATH
61#  define snprintf sprintf_s
62#else
63#  include <netdb.h>
64#  ifndef PATH_MAX
65#       define PATH_MAX 4096
66#  endif
67#  include <sys/ioctl.h>
68#endif
69
70/* This format deals with DAG cards that are using drivers from the 2.5 version
71 * onwards, including 3.X.
72 *
73 * DAG is a LIVE capture format.
74 *
75 * This format does support writing, provided the DAG card that you are using
76 * has transmit (Tx) support. Additionally, packets read using this format
77 * are in the ERF format, so can easily be written as ERF traces without
78 * losing any data.
79 */
80
81#define DATA(x) ((struct dag_format_data_t *)x->format_data)
82#define DATA_OUT(x) ((struct dag_format_data_out_t *)x->format_data)
83#define STREAM_DATA(x) ((struct dag_per_stream_t *)x->data)
84
85#define FORMAT_DATA DATA(libtrace)
86#define FORMAT_DATA_OUT DATA_OUT(libtrace)
87
88#define DUCK FORMAT_DATA->duck
89
90#define FORMAT_DATA_HEAD FORMAT_DATA->per_stream->head
91#define FORMAT_DATA_FIRST ((struct dag_per_stream_t *)FORMAT_DATA_HEAD->data)
92
93static struct libtrace_format_t dag;
94
95/* A DAG device - a DAG device can support multiple streams (and therefore
96 * multiple input traces) so each trace needs to refer to a device */
97struct dag_dev_t {
98        char * dev_name;                /* Device name */
99        int fd;                         /* File descriptor */
100        uint16_t ref_count;             /* Number of input / output traces
101                                           that are using this device */
102        struct dag_dev_t *prev;         /* Pointer to the previous device in
103                                           the device list */
104        struct dag_dev_t *next;         /* Pointer to the next device in the
105                                           device list */
106};
107
108/* "Global" data that is stored for each DAG output trace */
109struct dag_format_data_out_t {
110        /* The DAG device being used for writing */
111        struct dag_dev_t *device;
112        /* The DAG stream that is being written on */
113        unsigned int dagstream;
114        /* Boolean flag indicating whether the stream is currently attached */
115        int stream_attached;
116        /* The amount of data waiting to be transmitted, in bytes */
117        uint64_t waiting;
118        /* A buffer to hold the data to be transmittted */
119        uint8_t *txbuffer;
120};
121
122/* Data that is stored against each input stream */
123struct dag_per_stream_t {
124        /* DAG stream number */
125        uint16_t dagstream;
126        /* Pointer to the last unread byte in the DAG memory */
127        uint8_t *top;
128        /* Pointer to the first unread byte in the DAG memory */
129        uint8_t *bottom;
130        /* Amount of data processed from the bottom pointer */
131        uint32_t processed;
132        /* Number of packets seen by the stream */
133        uint64_t pkt_count;
134        /* Drop count for this particular stream */
135        uint64_t drops;
136        /* Boolean values to indicate if a particular interface has been seen
137         * or not. This is limited to four interfaces, which is enough to
138         * support all current DAG cards */
139        uint8_t seeninterface[4];
140};
141
142/* "Global" data that is stored for each DAG input trace */
143struct dag_format_data_t {
144        /* DAG device */
145        struct dag_dev_t *device;
146        /* Boolean flag indicating whether the trace is currently attached */
147        int stream_attached;
148        /* Data stored against each DAG input stream */
149        libtrace_list_t *per_stream;
150
151        /* Data required for regular DUCK reporting.
152         * We put this on a new cache line otherwise we have a lot of false
153         * sharing caused by updating the last_pkt.
154         * This should only ever be accessed by the first thread stream,
155         * that includes both read and write operations.
156         */
157        struct {
158                /* Timestamp of the last DUCK report */
159                uint32_t last_duck;
160                /* The number of seconds between each DUCK report */
161                uint32_t duck_freq;
162                /* Timestamp of the last packet read from the DAG card */
163                uint32_t last_pkt;
164                /* Dummy trace to ensure DUCK packets are dealt with using the
165                 * DUCK format functions */
166                libtrace_t *dummy_duck;
167        } duck ALIGN_STRUCT(CACHE_LINE_SIZE);
168};
169
170/* To be thread-safe, we're going to need a mutex for operating on the list
171 * of DAG devices */
172pthread_mutex_t open_dag_mutex;
173
174/* The list of DAG devices that have been opened by libtrace.
175 *
176 * We can only open each DAG device once, but we might want to read from
177 * multiple streams. Therefore, we need to maintain a list of devices that we
178 * have opened (with ref counts!) so that we don't try to open a device too
179 * many times or close a device that we're still using */
180struct dag_dev_t *open_dags = NULL;
181
182/* Returns the amount of padding between the ERF header and the start of the
183 * captured packet data */
184static int dag_get_padding(const libtrace_packet_t *packet)
185{
186        /* ERF Ethernet records have a 2 byte padding before the packet itself
187         * so that the IP header is aligned on a 32 bit boundary.
188         */
189        if (packet->trace->format->type==TRACE_FORMAT_ERF) {
190                dag_record_t *erfptr = (dag_record_t *)packet->header;
191                switch(erfptr->type) {
192                        case TYPE_ETH:
193                        case TYPE_DSM_COLOR_ETH:
194                                return 2;
195                        default:                return 0;
196                }
197        }
198        else {
199                switch(trace_get_link_type(packet)) {
200                        case TRACE_TYPE_ETH:    return 2;
201                        default:                return 0;
202                }
203        }
204}
205
206/* Attempts to determine if the given filename refers to a DAG device */
207static int dag_probe_filename(const char *filename)
208{
209        struct stat statbuf;
210        /* Can we stat the file? */
211        if (stat(filename, &statbuf) != 0) {
212                return 0;
213        }
214        /* Is it a character device? */
215        if (!S_ISCHR(statbuf.st_mode)) {
216                return 0;
217        }
218        /* Yeah, it's probably us. */
219        return 1;
220}
221
222/* Initialises the DAG output data structure */
223static void dag_init_format_out_data(libtrace_out_t *libtrace)
224{
225        libtrace->format_data = (struct dag_format_data_out_t *)
226                malloc(sizeof(struct dag_format_data_out_t));
227        // no DUCK on output
228        FORMAT_DATA_OUT->stream_attached = 0;
229        FORMAT_DATA_OUT->device = NULL;
230        FORMAT_DATA_OUT->dagstream = 0;
231        FORMAT_DATA_OUT->waiting = 0;
232
233}
234
235/* Initialises the DAG input data structure */
236static void dag_init_format_data(libtrace_t *libtrace)
237{
238        struct dag_per_stream_t stream_data;
239
240        libtrace->format_data = (struct dag_format_data_t *)
241                malloc(sizeof(struct dag_format_data_t));
242        DUCK.last_duck = 0;
243        DUCK.duck_freq = 0;
244        DUCK.last_pkt = 0;
245        DUCK.dummy_duck = NULL;
246
247        FORMAT_DATA->per_stream =
248                libtrace_list_init(sizeof(stream_data));
249        assert(FORMAT_DATA->per_stream != NULL);
250
251        /* We'll start with just one instance of stream_data, and we'll
252         * add more later if we need them */
253        memset(&stream_data, 0, sizeof(stream_data));
254        libtrace_list_push_back(FORMAT_DATA->per_stream, &stream_data);
255}
256
257/* Determines if there is already an entry for the given DAG device in the
258 * device list and increments the reference count for that device, if found.
259 *
260 * NOTE: This function assumes the open_dag_mutex is held by the caller */
261static struct dag_dev_t *dag_find_open_device(char *dev_name)
262{
263        struct dag_dev_t *dag_dev;
264
265        dag_dev = open_dags;
266
267        /* XXX: Not exactly zippy, but how often are we going to be dealing
268         * with multiple dag cards? */
269        while (dag_dev != NULL) {
270                if (strcmp(dag_dev->dev_name, dev_name) == 0) {
271                        dag_dev->ref_count ++;
272                        return dag_dev;
273                }
274                dag_dev = dag_dev->next;
275        }
276        return NULL;
277}
278
279/* Closes a DAG device and removes it from the device list.
280 *
281 * Attempting to close a DAG device that has a non-zero reference count will
282 * cause an assertion failure!
283 *
284 * NOTE: This function assumes the open_dag_mutex is held by the caller */
285static void dag_close_device(struct dag_dev_t *dev)
286{
287        /* Need to remove from the device list */
288        assert(dev->ref_count == 0);
289
290        if (dev->prev == NULL) {
291                open_dags = dev->next;
292                if (dev->next)
293                        dev->next->prev = NULL;
294        } else {
295                dev->prev->next = dev->next;
296                if (dev->next)
297                        dev->next->prev = dev->prev;
298        }
299
300        dag_close(dev->fd);
301        if (dev->dev_name)
302                free(dev->dev_name);
303        free(dev);
304}
305
306
307/* Opens a new DAG device for writing and adds it to the DAG device list
308 *
309 * NOTE: this function should only be called when opening a DAG device for
310 * writing - there is little practical difference between this and the
311 * function below that covers the reading case, but we need the output trace
312 * object to report errors properly so the two functions take slightly
313 * different arguments. This is really lame and there should be a much better
314 * way of doing this.
315 *
316 * NOTE: This function assumes the open_dag_mutex is held by the caller
317 */
318static struct dag_dev_t *dag_open_output_device(libtrace_out_t *libtrace,
319                                                char *dev_name)
320{
321        struct stat buf;
322        int fd;
323        struct dag_dev_t *new_dev;
324
325        /* Make sure the device exists */
326        if (stat(dev_name, &buf) == -1) {
327                trace_set_err_out(libtrace,errno,"stat(%s)",dev_name);
328                return NULL;
329        }
330
331        /* Make sure it is the appropriate type of device */
332        if (S_ISCHR(buf.st_mode)) {
333                /* Try opening the DAG device */
334                if((fd = dag_open(dev_name)) < 0) {
335                        trace_set_err_out(libtrace,errno,"Cannot open DAG %s",
336                                        dev_name);
337                        return NULL;
338                }
339        } else {
340                trace_set_err_out(libtrace,errno,"Not a valid dag device: %s",
341                                dev_name);
342                return NULL;
343        }
344
345        /* Add the device to our device list - it is just a doubly linked
346         * list with no inherent ordering; just tack the new one on the front
347         */
348        new_dev = (struct dag_dev_t *)malloc(sizeof(struct dag_dev_t));
349        new_dev->fd = fd;
350        new_dev->dev_name = dev_name;
351        new_dev->ref_count = 1;
352
353        new_dev->prev = NULL;
354        new_dev->next = open_dags;
355        if (open_dags)
356                open_dags->prev = new_dev;
357
358        open_dags = new_dev;
359
360        return new_dev;
361}
362
363/* Opens a new DAG device for reading and adds it to the DAG device list
364 *
365 * NOTE: this function should only be called when opening a DAG device for
366 * reading - there is little practical difference between this and the
367 * function above that covers the writing case, but we need the input trace
368 * object to report errors properly so the two functions take slightly
369 * different arguments. This is really lame and there should be a much better
370 * way of doing this.
371 *
372 * NOTE: This function assumes the open_dag_mutex is held by the caller */
373static struct dag_dev_t *dag_open_device(libtrace_t *libtrace, char *dev_name) {
374        struct stat buf;
375        int fd;
376        struct dag_dev_t *new_dev;
377
378        /* Make sure the device exists */
379        if (stat(dev_name, &buf) == -1) {
380                trace_set_err(libtrace,errno,"stat(%s)",dev_name);
381                return NULL;
382        }
383
384        /* Make sure it is the appropriate type of device */
385        if (S_ISCHR(buf.st_mode)) {
386                /* Try opening the DAG device */
387                if((fd = dag_open(dev_name)) < 0) {
388                        trace_set_err(libtrace,errno,"Cannot open DAG %s",
389                                      dev_name);
390                        return NULL;
391                }
392        } else {
393                trace_set_err(libtrace,errno,"Not a valid dag device: %s",
394                              dev_name);
395                return NULL;
396        }
397
398        /* Add the device to our device list - it is just a doubly linked
399         * list with no inherent ordering; just tack the new one on the front
400         */
401        new_dev = (struct dag_dev_t *)malloc(sizeof(struct dag_dev_t));
402        new_dev->fd = fd;
403        new_dev->dev_name = dev_name;
404        new_dev->ref_count = 1;
405
406        new_dev->prev = NULL;
407        new_dev->next = open_dags;
408        if (open_dags)
409                open_dags->prev = new_dev;
410
411        open_dags = new_dev;
412
413        return new_dev;
414}
415
416/* Creates and initialises a DAG output trace */
417static int dag_init_output(libtrace_out_t *libtrace)
418{
419        /* Upon successful creation, the device name is stored against the
420         * device and free when it is free()d */
421        char *dag_dev_name = NULL;
422        char *scan = NULL;
423        struct dag_dev_t *dag_device = NULL;
424        int stream = 1;
425
426        /* XXX I don't know if this is important or not, but this function
427         * isn't present in all of the driver releases that this code is
428         * supposed to support! */
429        /*
430        unsigned long wake_time;
431        dagutil_sleep_get_wake_time(&wake_time,0);
432        */
433
434        dag_init_format_out_data(libtrace);
435        /* Grab the mutex while we're likely to be messing with the device
436         * list */
437        pthread_mutex_lock(&open_dag_mutex);
438
439        /* Specific streams are signified using a comma in the libtrace URI,
440         * e.g. dag:/dev/dag0,1 refers to stream 1 on the dag0 device.
441         *
442         * If no stream is specified, we will write using stream 1 */
443        if ((scan = strchr(libtrace->uridata,',')) == NULL) {
444                dag_dev_name = strdup(libtrace->uridata);
445        } else {
446                dag_dev_name = (char *)strndup(libtrace->uridata,
447                                (size_t)(scan - libtrace->uridata));
448                stream = atoi(++scan);
449        }
450        FORMAT_DATA_OUT->dagstream = stream;
451
452        /* See if our DAG device is already open */
453        dag_device = dag_find_open_device(dag_dev_name);
454
455        if (dag_device == NULL) {
456                /* Device not yet opened - open it ourselves */
457                dag_device = dag_open_output_device(libtrace, dag_dev_name);
458        } else {
459                /* Otherwise, just use the existing one */
460                free(dag_dev_name);
461                dag_dev_name = NULL;
462        }
463
464        /* Make sure we have successfully opened a DAG device */
465        if (dag_device == NULL) {
466                if (dag_dev_name) {
467                        free(dag_dev_name);
468                }
469                pthread_mutex_unlock(&open_dag_mutex);
470                return -1;
471        }
472
473        FORMAT_DATA_OUT->device = dag_device;
474        pthread_mutex_unlock(&open_dag_mutex);
475        return 0;
476}
477
478/* Creates and initialises a DAG input trace */
479static int dag_init_input(libtrace_t *libtrace) {
480        /* Upon successful creation, the device name is stored against the
481         * device and free when it is free()d */
482        char *dag_dev_name = NULL;
483        char *scan = NULL;
484        int stream = 0;
485        struct dag_dev_t *dag_device = NULL;
486
487        dag_init_format_data(libtrace);
488        /* Grab the mutex while we're likely to be messing with the device
489         * list */
490        pthread_mutex_lock(&open_dag_mutex);
491
492
493        /* DAG cards support multiple streams. In a single threaded capture,
494         * these are specified using a comma in the libtrace URI,
495         * e.g. dag:/dev/dag0,2 refers to stream 2 on the dag0 device.
496         *
497         * If no stream is specified, we will read from stream 0 with
498         * one thread
499         */
500        if ((scan = strchr(libtrace->uridata,',')) == NULL) {
501                dag_dev_name = strdup(libtrace->uridata);
502        } else {
503                dag_dev_name = (char *)strndup(libtrace->uridata,
504                                (size_t)(scan - libtrace->uridata));
505                stream = atoi(++scan);
506        }
507
508        FORMAT_DATA_FIRST->dagstream = stream;
509
510        /* See if our DAG device is already open */
511        dag_device = dag_find_open_device(dag_dev_name);
512
513        if (dag_device == NULL) {
514                /* Device not yet opened - open it ourselves */
515                dag_device = dag_open_device(libtrace, dag_dev_name);
516        } else {
517                /* Otherwise, just use the existing one */
518                free(dag_dev_name);
519                dag_dev_name = NULL;
520        }
521
522        /* Make sure we have successfully opened a DAG device */
523        if (dag_device == NULL) {
524                if (dag_dev_name)
525                        free(dag_dev_name);
526                dag_dev_name = NULL;
527                pthread_mutex_unlock(&open_dag_mutex);
528                return -1;
529        }
530
531        FORMAT_DATA->device = dag_device;
532
533        /* See Config_Status_API_Programming_Guide.pdf from the Endace
534           Dag Documentation */
535        /* Check kBooleanAttributeActive is true -- no point capturing
536         * on an interface that's disabled
537         *
538         * The symptom of the port being disabled is that libtrace
539         * will appear to hang. */
540        /* Check kBooleanAttributeFault is false */
541        /* Check kBooleanAttributeLocalFault is false */
542        /* Check kBooleanAttributeLock is true ? */
543        /* Check kBooleanAttributePeerLink ? */
544
545        /* Set kBooleanAttributePromisc/kBooleanPromiscuousMode based
546           on libtrace promisc attribute?*/
547        /* Set kUint32AttributeSnapLength to the snaplength */
548
549        pthread_mutex_unlock(&open_dag_mutex);
550        return 0;
551}
552
553/* Configures a DAG input trace */
554static int dag_config_input(libtrace_t *libtrace, trace_option_t option,
555                            void *data)
556{
557        char conf_str[4096];
558        switch(option) {
559        case TRACE_OPTION_META_FREQ:
560                /* This option is used to specify the frequency of DUCK
561                 * updates */
562                DUCK.duck_freq = *(int *)data;
563                return 0;
564        case TRACE_OPTION_SNAPLEN:
565                /* Tell the card our new snap length */
566                snprintf(conf_str, 4096, "varlen slen=%i", *(int *)data);
567                if (dag_configure(FORMAT_DATA->device->fd,
568                                  conf_str) != 0) {
569                        trace_set_err(libtrace, errno, "Failed to configure "
570                                      "snaplen on DAG card: %s",
571                                      libtrace->uridata);
572                        return -1;
573                }
574                return 0;
575        case TRACE_OPTION_PROMISC:
576                /* DAG already operates in a promisc fashion */
577                return -1;
578        case TRACE_OPTION_FILTER:
579                /* We don't yet support pushing filters into DAG
580                 * cards */
581                return -1;
582        case TRACE_OPTION_EVENT_REALTIME:
583                /* Live capture is always going to be realtime */
584                return -1;
585        case TRACE_OPTION_HASHER:
586                /* Lets just say we did this, it's currently still up to
587                 * the user to configure this correctly. */
588                return 0;
589        }
590        return -1;
591}
592
593/* Starts a DAG output trace */
594static int dag_start_output(libtrace_out_t *libtrace)
595{
596        struct timeval zero, nopoll;
597
598        zero.tv_sec = 0;
599        zero.tv_usec = 0;
600        nopoll = zero;
601
602        /* Attach and start the DAG stream */
603        if (dag_attach_stream(FORMAT_DATA_OUT->device->fd,
604                        FORMAT_DATA_OUT->dagstream, 0, 4 * 1024 * 1024) < 0) {
605                trace_set_err_out(libtrace, errno, "Cannot attach DAG stream");
606                return -1;
607        }
608
609        if (dag_start_stream(FORMAT_DATA_OUT->device->fd,
610                        FORMAT_DATA_OUT->dagstream) < 0) {
611                trace_set_err_out(libtrace, errno, "Cannot start DAG stream");
612                return -1;
613        }
614        FORMAT_DATA_OUT->stream_attached = 1;
615
616        /* We don't want the dag card to do any sleeping */
617        dag_set_stream_poll(FORMAT_DATA_OUT->device->fd,
618                        FORMAT_DATA_OUT->dagstream, 0, &zero,
619                        &nopoll);
620
621        return 0;
622}
623
624static int dag_start_input_stream(libtrace_t *libtrace,
625                                  struct dag_per_stream_t * stream) {
626        struct timeval zero, nopoll;
627        uint8_t *top, *bottom, *starttop;
628        top = bottom = NULL;
629
630        zero.tv_sec = 0;
631        zero.tv_usec = 10000;
632        nopoll = zero;
633
634        /* Attach and start the DAG stream */
635        if (dag_attach_stream(FORMAT_DATA->device->fd,
636                              stream->dagstream, 0, 0) < 0) {
637                trace_set_err(libtrace, errno, "Cannot attach DAG stream #%u",
638                              stream->dagstream);
639                return -1;
640        }
641
642        if (dag_start_stream(FORMAT_DATA->device->fd,
643                             stream->dagstream) < 0) {
644                trace_set_err(libtrace, errno, "Cannot start DAG stream #%u",
645                              stream->dagstream);
646                return -1;
647        }
648        FORMAT_DATA->stream_attached = 1;
649
650        /* We don't want the dag card to do any sleeping */
651        if (dag_set_stream_poll(FORMAT_DATA->device->fd,
652                            stream->dagstream, 0, &zero,
653                            &nopoll) < 0) {
654                trace_set_err(libtrace, errno,
655                              "dag_set_stream_poll failed!");
656                return -1;
657        }
658
659        starttop = dag_advance_stream(FORMAT_DATA->device->fd,
660                                      stream->dagstream,
661                                      &bottom);
662
663        /* Should probably flush the memory hole now */
664        top = starttop;
665        while (starttop - bottom > 0) {
666                bottom += (starttop - bottom);
667                top = dag_advance_stream(FORMAT_DATA->device->fd,
668                                         stream->dagstream,
669                                         &bottom);
670        }
671        stream->top = top;
672        stream->bottom = bottom;
673        stream->processed = 0;
674        stream->drops = 0;
675
676        return 0;
677
678}
679
680/* Starts a DAG input trace */
681static int dag_start_input(libtrace_t *libtrace)
682{
683        return dag_start_input_stream(libtrace, FORMAT_DATA_FIRST);
684}
685
686static int dag_pstart_input(libtrace_t *libtrace)
687{
688        char *scan, *tok;
689        uint16_t stream_count = 0, max_streams;
690        int iserror = 0;
691        struct dag_per_stream_t stream_data;
692
693        /* Check we aren't trying to create more threads than the DAG card can
694         * handle */
695        max_streams = dag_rx_get_stream_count(FORMAT_DATA->device->fd);
696        if (libtrace->perpkt_thread_count > max_streams) {
697                trace_set_err(libtrace, TRACE_ERR_BAD_FORMAT,
698                              "trying to create too many threads (max is %u)",
699                              max_streams);
700                iserror = 1;
701                goto cleanup;
702        }
703
704        /* Get the stream names from the uri */
705        if ((scan = strchr(libtrace->uridata, ',')) == NULL) {
706                trace_set_err(libtrace, TRACE_ERR_BAD_FORMAT,
707                              "format uri doesn't specify the DAG streams");
708                iserror = 1;
709                goto cleanup;
710        }
711
712        scan++;
713
714        tok = strtok(scan, ",");
715        while (tok != NULL) {
716                /* Ensure we haven't specified too many streams */
717                if (stream_count >= libtrace->perpkt_thread_count) {
718                        trace_set_err(libtrace, TRACE_ERR_BAD_FORMAT,
719                                      "format uri specifies too many streams. "
720                                      "Max is %u", max_streams);
721                        iserror = 1;
722                        goto cleanup;
723                }
724
725                /* Save the stream details */
726                if (stream_count == 0) {
727                        /* Special case where we update the existing stream
728                         * data structure */
729                        FORMAT_DATA_FIRST->dagstream = (uint16_t)atoi(tok);
730                } else {
731                        memset(&stream_data, 0, sizeof(stream_data));
732                        stream_data.dagstream = (uint16_t)atoi(tok);
733                        libtrace_list_push_back(FORMAT_DATA->per_stream,
734                                                &stream_data);
735                }
736
737                stream_count++;
738                tok = strtok(NULL, ",");
739        }
740
741        FORMAT_DATA->stream_attached = 1;
742
743 cleanup:
744        if (iserror) {
745                return -1;
746        } else {
747                return 0;
748        }
749}
750
751/* Pauses a DAG output trace */
752static int dag_pause_output(libtrace_out_t *libtrace)
753{
754        /* Stop and detach the stream */
755        if (dag_stop_stream(FORMAT_DATA_OUT->device->fd,
756                            FORMAT_DATA_OUT->dagstream) < 0) {
757                trace_set_err_out(libtrace, errno, "Could not stop DAG stream");
758                return -1;
759        }
760        if (dag_detach_stream(FORMAT_DATA_OUT->device->fd,
761                              FORMAT_DATA_OUT->dagstream) < 0) {
762                trace_set_err_out(libtrace, errno,
763                                  "Could not detach DAG stream");
764                return -1;
765        }
766        FORMAT_DATA_OUT->stream_attached = 0;
767        return 0;
768}
769
770/* Pauses a DAG input trace */
771static int dag_pause_input(libtrace_t *libtrace)
772{
773        libtrace_list_node_t *tmp = FORMAT_DATA_HEAD;
774
775        /* Stop and detach each stream */
776        while (tmp != NULL) {
777                if (dag_stop_stream(FORMAT_DATA->device->fd,
778                                    STREAM_DATA(tmp)->dagstream) < 0) {
779                        trace_set_err(libtrace, errno,
780                                      "Could not stop DAG stream");
781                        printf("Count not stop DAG stream\n");
782                        return -1;
783                }
784                if (dag_detach_stream(FORMAT_DATA->device->fd,
785                                      STREAM_DATA(tmp)->dagstream) < 0) {
786                        trace_set_err(libtrace, errno,
787                                      "Could not detach DAG stream");
788                        printf("Count not detach DAG stream\n");
789                        return -1;
790                }
791
792                tmp = tmp->next;
793        }
794
795        FORMAT_DATA->stream_attached = 0;
796        return 0;
797}
798
799
800
801/* Closes a DAG input trace */
802static int dag_fin_input(libtrace_t *libtrace)
803{
804        /* Need the lock, since we're going to be handling the device list */
805        pthread_mutex_lock(&open_dag_mutex);
806
807        /* Detach the stream if we are not paused */
808        if (FORMAT_DATA->stream_attached)
809                dag_pause_input(libtrace);
810        FORMAT_DATA->device->ref_count--;
811
812        /* Close the DAG device if there are no more references to it */
813        if (FORMAT_DATA->device->ref_count == 0)
814                dag_close_device(FORMAT_DATA->device);
815
816        if (DUCK.dummy_duck)
817                trace_destroy_dead(DUCK.dummy_duck);
818
819        /* Clear the list */
820        libtrace_list_deinit(FORMAT_DATA->per_stream);
821        free(libtrace->format_data);
822        pthread_mutex_unlock(&open_dag_mutex);
823        return 0; /* success */
824}
825
826/* Closes a DAG output trace */
827static int dag_fin_output(libtrace_out_t *libtrace)
828{
829
830        /* Commit any outstanding traffic in the txbuffer */
831        if (FORMAT_DATA_OUT->waiting) {
832                dag_tx_stream_commit_bytes(FORMAT_DATA_OUT->device->fd,
833                                           FORMAT_DATA_OUT->dagstream,
834                                           FORMAT_DATA_OUT->waiting );
835        }
836
837        /* Wait until the buffer is nearly clear before exiting the program,
838         * as we will lose packets otherwise */
839        dag_tx_get_stream_space
840                (FORMAT_DATA_OUT->device->fd,
841                 FORMAT_DATA_OUT->dagstream,
842                 dag_get_stream_buffer_size(FORMAT_DATA_OUT->device->fd,
843                                            FORMAT_DATA_OUT->dagstream) - 8);
844
845        /* Need the lock, since we're going to be handling the device list */
846        pthread_mutex_lock(&open_dag_mutex);
847
848        /* Detach the stream if we are not paused */
849        if (FORMAT_DATA_OUT->stream_attached)
850                dag_pause_output(libtrace);
851        FORMAT_DATA_OUT->device->ref_count --;
852
853        /* Close the DAG device if there are no more references to it */
854        if (FORMAT_DATA_OUT->device->ref_count == 0)
855                dag_close_device(FORMAT_DATA_OUT->device);
856        free(libtrace->format_data);
857        pthread_mutex_unlock(&open_dag_mutex);
858        return 0; /* success */
859}
860
861#ifdef DAGIOC_CARD_DUCK
862#define LIBTRACE_DUCK_IOCTL DAGIOC_CARD_DUCK
863#define LIBTRACE_DUCK_VERSION TRACE_RT_DUCK_5_0
864#else
865#ifdef DAGIOCDUCK
866#define LIBTRACE_DUCK_IOCTL DAGIOCDUCK
867#define LIBTRACE_DUCK_VERSION TRACE_RT_DUCK_2_5
868#else
869#warning "DAG appears to be missing DUCK support"
870#endif
871#endif
872
873/* Extracts DUCK information from the DAG card and produces a DUCK packet */
874static int dag_get_duckinfo(libtrace_t *libtrace,
875                                libtrace_packet_t *packet) {
876
877        if (DUCK.duck_freq == 0)
878                return 0;
879
880#ifndef LIBTRACE_DUCK_IOCTL
881        trace_set_err(libtrace, errno, 
882                "Requested DUCK information but unable to determine the correct ioctl for DUCK");
883        DUCK.duck_freq = 0;
884        return -1;
885#endif
886
887        if (DUCK.last_pkt - DUCK.last_duck < DUCK.duck_freq)
888                return 0;
889
890        /* Allocate memory for the DUCK data */
891        if (packet->buf_control == TRACE_CTRL_EXTERNAL ||
892            !packet->buffer) {
893                packet->buffer = malloc(LIBTRACE_PACKET_BUFSIZE);
894                packet->buf_control = TRACE_CTRL_PACKET;
895                if (!packet->buffer) {
896                        trace_set_err(libtrace, errno,
897                                      "Cannot allocate packet buffer");
898                        return -1;
899                }
900        }
901
902        /* DUCK doesn't have a format header */
903        packet->header = 0;
904        packet->payload = packet->buffer;
905
906        /* No need to check if we can get DUCK or not - we're modern
907         * enough so just grab the DUCK info */
908        if ((ioctl(FORMAT_DATA->device->fd, LIBTRACE_DUCK_IOCTL,
909                   (duckinf_t *)packet->payload) < 0)) {
910                trace_set_err(libtrace, errno, "Error using DUCK ioctl");
911                DUCK.duck_freq = 0;
912                return -1;
913        }
914
915        packet->type = LIBTRACE_DUCK_VERSION;
916
917        /* Set the packet's trace to point at a DUCK trace, so that the
918         * DUCK format functions will be called on the packet rather than the
919         * DAG ones */
920        if (!DUCK.dummy_duck)
921                DUCK.dummy_duck = trace_create_dead("duck:dummy");
922        packet->trace = DUCK.dummy_duck;
923        DUCK.last_duck = DUCK.last_pkt;
924        packet->error = sizeof(duckinf_t);
925        return sizeof(duckinf_t);
926}
927
928/* Determines the amount of data available to read from the DAG card */
929static int dag_available(libtrace_t *libtrace,
930                         struct dag_per_stream_t *stream_data)
931{
932        uint32_t diff = stream_data->top - stream_data->bottom;
933
934        /* If we've processed more than 4MB of data since we last called
935         * dag_advance_stream, then we should call it again to allow the
936         * space occupied by that 4MB to be released */
937        if (diff >= dag_record_size && stream_data->processed < 4 * 1024 * 1024)
938                return diff;
939
940        /* Update the top and bottom pointers */
941        stream_data->top = dag_advance_stream(FORMAT_DATA->device->fd,
942                                              stream_data->dagstream,
943                                              &(stream_data->bottom));
944
945        if (stream_data->top == NULL) {
946                trace_set_err(libtrace, errno, "dag_advance_stream failed!");
947                return -1;
948        }
949        stream_data->processed = 0;
950        diff = stream_data->top - stream_data->bottom;
951        return diff;
952}
953
954/* Returns a pointer to the start of the next complete ERF record */
955static dag_record_t *dag_get_record(struct dag_per_stream_t *stream_data)
956{
957        dag_record_t *erfptr = NULL;
958        uint16_t size;
959
960        erfptr = (dag_record_t *)stream_data->bottom;
961        if (!erfptr)
962                return NULL;
963
964        size = ntohs(erfptr->rlen);
965        assert( size >= dag_record_size );
966
967        /* Make certain we have the full packet available */
968        if (size > (stream_data->top - stream_data->bottom))
969                return NULL;
970
971        stream_data->bottom += size;
972        stream_data->processed += size;
973        return erfptr;
974}
975
976/* Converts a buffer containing a recently read DAG packet record into a
977 * libtrace packet */
978static int dag_prepare_packet_stream(libtrace_t *libtrace,
979                                     struct dag_per_stream_t *stream_data,
980                                     libtrace_packet_t *packet,
981                                     void *buffer, libtrace_rt_types_t rt_type,
982                                     uint32_t flags)
983{
984        dag_record_t *erfptr;
985
986        /* If the packet previously owned a buffer that is not the buffer
987         * that contains the new packet data, we're going to need to free the
988         * old one to avoid memory leaks */
989        if (packet->buffer != buffer &&
990            packet->buf_control == TRACE_CTRL_PACKET) {
991                free(packet->buffer);
992        }
993
994        /* Set the buffer owner appropriately */
995        if ((flags & TRACE_PREP_OWN_BUFFER) == TRACE_PREP_OWN_BUFFER) {
996                packet->buf_control = TRACE_CTRL_PACKET;
997        } else
998                packet->buf_control = TRACE_CTRL_EXTERNAL;
999
1000        /* Update the packet pointers and type appropriately */
1001        erfptr = (dag_record_t *)buffer;
1002        packet->buffer = erfptr;
1003        packet->header = erfptr;
1004        packet->type = rt_type;
1005
1006        if (erfptr->flags.rxerror == 1) {
1007                /* rxerror means the payload is corrupt - drop the payload
1008                 * by tweaking rlen */
1009                packet->payload = NULL;
1010                erfptr->rlen = htons(erf_get_framing_length(packet));
1011        } else {
1012                packet->payload = (char*)packet->buffer
1013                        + erf_get_framing_length(packet);
1014        }
1015
1016        if (libtrace->format_data == NULL) {
1017                dag_init_format_data(libtrace);
1018        }
1019
1020        /* Update the dropped packets counter */
1021        /* No loss counter for DSM coloured records - have to use some
1022         * other API */
1023        if (erfptr->type == TYPE_DSM_COLOR_ETH) {
1024                /* TODO */
1025        } else {
1026                /* Use the ERF loss counter */
1027                if (stream_data->seeninterface[erfptr->flags.iface]
1028                    == 0) {
1029                        stream_data->seeninterface[erfptr->flags.iface]
1030                                = 1;
1031                } else {
1032                        stream_data->drops += ntohs(erfptr->lctr);
1033                }
1034        }
1035
1036        return 0;
1037}
1038
1039static int dag_prepare_packet(libtrace_t *libtrace, libtrace_packet_t *packet,
1040                              void *buffer, libtrace_rt_types_t rt_type,
1041                              uint32_t flags)
1042{
1043        return dag_prepare_packet_stream(libtrace, FORMAT_DATA_FIRST, packet,
1044                                       buffer, rt_type, flags);
1045}
1046
1047/*
1048 * dag_write_packet() at this stage attempts to improve tx performance
1049 * by delaying sending a dag_tx_stream_commit_bytes() until a threshold
1050 * has been met. I observed approximately 270% performance increase
1051 * through this relatively naive tweak. No optimisation of buffer sizes
1052 * was attempted.
1053 */
1054
1055/* Pushes an ERF record onto the transmit stream */
1056static int dag_dump_packet(libtrace_out_t *libtrace,
1057                           dag_record_t *erfptr, unsigned int pad,
1058                           void *buffer)
1059{
1060        int size;
1061
1062        /*
1063         * If we've got 0 bytes waiting in the txqueue, assume that we
1064         * haven't requested any space yet, and request some, storing
1065         * the pointer at FORMAT_DATA_OUT->txbuffer.
1066         *
1067         * The amount to request is slightly magical at the moment - it's
1068         * 16Mebibytes + 128 kibibytes to ensure that we can copy a packet into
1069         * the buffer and handle overruns.
1070         */
1071        if (FORMAT_DATA_OUT->waiting == 0) {
1072                FORMAT_DATA_OUT->txbuffer =
1073                        dag_tx_get_stream_space(FORMAT_DATA_OUT->device->fd,
1074                                                FORMAT_DATA_OUT->dagstream,
1075                                                16908288);
1076        }
1077
1078        /*
1079         * Copy the header separately to the body, as we can't guarantee they
1080         * are in contiguous memory
1081         */
1082        memcpy(FORMAT_DATA_OUT->txbuffer + FORMAT_DATA_OUT->waiting, erfptr,
1083               (dag_record_size + pad));
1084        FORMAT_DATA_OUT->waiting += (dag_record_size + pad);
1085
1086        /*
1087         * Copy our incoming packet into the outgoing buffer, and increment
1088         * our waiting count
1089         */
1090        size = ntohs(erfptr->rlen)-(dag_record_size + pad);
1091        memcpy(FORMAT_DATA_OUT->txbuffer + FORMAT_DATA_OUT->waiting, buffer,
1092               size);
1093        FORMAT_DATA_OUT->waiting += size;
1094
1095        /*
1096         * If our output buffer has more than 16 Mebibytes in it, commit those
1097         * bytes and reset the waiting count to 0.
1098         * Note: dag_fin_output will also call dag_tx_stream_commit_bytes() in
1099         * case there is still data in the buffer at program exit.
1100         */
1101        if (FORMAT_DATA_OUT->waiting >= 16*1024*1024) {
1102                FORMAT_DATA_OUT->txbuffer =
1103                        dag_tx_stream_commit_bytes(FORMAT_DATA_OUT->device->fd,
1104                                                   FORMAT_DATA_OUT->dagstream,
1105                                                   FORMAT_DATA_OUT->waiting);
1106                FORMAT_DATA_OUT->waiting = 0;
1107        }
1108
1109        return size + pad + dag_record_size;
1110}
1111
1112/* Attempts to determine a suitable ERF type for a given packet. Returns true
1113 * if one is found, false otherwise */
1114static bool find_compatible_linktype(libtrace_out_t *libtrace,
1115                                     libtrace_packet_t *packet, char *type)
1116{
1117        /* Keep trying to simplify the packet until we can find
1118         * something we can do with it */
1119
1120        do {
1121                *type = libtrace_to_erf_type(trace_get_link_type(packet));
1122
1123                /* Success */
1124                if (*type != (char)-1)
1125                        return true;
1126
1127                if (!demote_packet(packet)) {
1128                        trace_set_err_out(libtrace,
1129                                          TRACE_ERR_NO_CONVERSION,
1130                                          "No erf type for packet (%i)",
1131                                          trace_get_link_type(packet));
1132                        return false;
1133                }
1134
1135        } while(1);
1136
1137        return true;
1138}
1139
1140/* Writes a packet to the provided DAG output trace */
1141static int dag_write_packet(libtrace_out_t *libtrace, libtrace_packet_t *packet)
1142{
1143        /* This is heavily borrowed from erf_write_packet(). Yes, CnP
1144         * coding sucks, sorry about that.
1145         */
1146        unsigned int pad = 0;
1147        int numbytes;
1148        void *payload = packet->payload;
1149        dag_record_t *header = (dag_record_t *)packet->header;
1150        char erf_type = 0;
1151
1152        if(!packet->header) {
1153                /* No header, probably an RT packet. Lifted from
1154                 * erf_write_packet(). */
1155                return -1;
1156        }
1157
1158        if (trace_get_link_type(packet) == TRACE_TYPE_NONDATA)
1159                return 0;
1160
1161        pad = dag_get_padding(packet);
1162
1163        /*
1164         * If the payload is null, adjust the rlen. Discussion of this is
1165         * attached to erf_write_packet()
1166         */
1167        if (payload == NULL) {
1168                header->rlen = htons(dag_record_size + pad);
1169        }
1170
1171        if (packet->type == TRACE_RT_DATA_ERF) {
1172                numbytes = dag_dump_packet(libtrace, header, pad, payload);
1173        } else {
1174                /* Build up a new packet header from the existing header */
1175
1176                /* Simplify the packet first - if we can't do this, break
1177                 * early */
1178                if (!find_compatible_linktype(libtrace,packet,&erf_type))
1179                        return -1;
1180
1181                dag_record_t erfhdr;
1182
1183                erfhdr.ts = bswap_host_to_le64(trace_get_erf_timestamp(packet));
1184                payload=packet->payload;
1185                pad = dag_get_padding(packet);
1186
1187                /* Flags. Can't do this */
1188                memset(&erfhdr.flags,1,sizeof(erfhdr.flags));
1189                if (trace_get_direction(packet)!=(int)~0U)
1190                        erfhdr.flags.iface = trace_get_direction(packet);
1191
1192                erfhdr.type = erf_type;
1193
1194                /* Packet length (rlen includes format overhead) */
1195                assert(trace_get_capture_length(packet) > 0
1196                       && trace_get_capture_length(packet) <= 65536);
1197                assert(erf_get_framing_length(packet) > 0
1198                       && trace_get_framing_length(packet) <= 65536);
1199                assert(trace_get_capture_length(packet) +
1200                       erf_get_framing_length(packet) > 0
1201                       && trace_get_capture_length(packet) +
1202                       erf_get_framing_length(packet) <= 65536);
1203
1204                erfhdr.rlen = htons(trace_get_capture_length(packet)
1205                                    + erf_get_framing_length(packet));
1206
1207
1208                /* Loss counter. Can't do this */
1209                erfhdr.lctr = 0;
1210                /* Wire length, does not include padding! */
1211                erfhdr.wlen = htons(trace_get_wire_length(packet));
1212
1213                /* Write it out */
1214                numbytes = dag_dump_packet(libtrace, &erfhdr, pad, payload);
1215        }
1216
1217        return numbytes;
1218}
1219
1220/* Reads the next available packet from a DAG card, in a BLOCKING fashion
1221 *
1222 * If DUCK reporting is enabled, the packet returned may be a DUCK update
1223 */
1224static int dag_read_packet_stream(libtrace_t *libtrace,
1225                                struct dag_per_stream_t *stream_data,
1226                                libtrace_thread_t *t, /* Optional */
1227                                libtrace_packet_t *packet)
1228{
1229        int size = 0;
1230        dag_record_t *erfptr = NULL;
1231        struct timeval tv;
1232        int numbytes = 0;
1233        uint32_t flags = 0;
1234        struct timeval maxwait, pollwait;
1235
1236        pollwait.tv_sec = 0;
1237        pollwait.tv_usec = 10000;
1238        maxwait.tv_sec = 0;
1239        maxwait.tv_usec = 250000;
1240
1241        /* Check if we're due for a DUCK report - only report on the first thread */
1242        if (stream_data == FORMAT_DATA_FIRST) {
1243                size = dag_get_duckinfo(libtrace, packet);
1244                if (size != 0)
1245                        return size;
1246        }
1247
1248
1249        /* Don't let anyone try to free our DAG memory hole! */
1250        flags |= TRACE_PREP_DO_NOT_OWN_BUFFER;
1251
1252        /* If the packet buffer is currently owned by libtrace, free it so
1253         * that we can set the packet to point into the DAG memory hole */
1254        if (packet->buf_control == TRACE_CTRL_PACKET) {
1255                free(packet->buffer);
1256                packet->buffer = 0;
1257        }
1258
1259        if (dag_set_stream_poll(FORMAT_DATA->device->fd, stream_data->dagstream,
1260                                sizeof(dag_record_t), &maxwait,
1261                                &pollwait) == -1) {
1262                trace_set_err(libtrace, errno, "dag_set_stream_poll");
1263                return -1;
1264        }
1265
1266        /* Grab a full ERF record */
1267        do {
1268                numbytes = dag_available(libtrace, stream_data);
1269                if (numbytes < 0)
1270                        return numbytes;
1271                if (numbytes < dag_record_size) {
1272                        /* Check the message queue if we have one to check */
1273                        if (t != NULL &&
1274                            libtrace_message_queue_count(&t->messages) > 0)
1275                                return -2;
1276
1277                        if (libtrace_halt)
1278                                return 0;
1279                        /* Block until we see a packet */
1280                        continue;
1281                }
1282                erfptr = dag_get_record(stream_data);
1283        } while (erfptr == NULL);
1284
1285        packet->trace = libtrace;
1286        /* Prepare the libtrace packet */
1287        if (dag_prepare_packet_stream(libtrace, stream_data, packet, erfptr,
1288                                    TRACE_RT_DATA_ERF, flags))
1289                return -1;
1290
1291        /* Update the DUCK timer - don't re-order this check (false-sharing) */
1292        if (stream_data == FORMAT_DATA_FIRST && DUCK.duck_freq != 0) {
1293                tv = trace_get_timeval(packet);
1294                DUCK.last_pkt = tv.tv_sec;
1295        }
1296
1297        packet->error = packet->payload ? htons(erfptr->rlen) :
1298                                          erf_get_framing_length(packet);
1299
1300        return packet->error;
1301}
1302
1303static int dag_read_packet(libtrace_t *libtrace, libtrace_packet_t *packet)
1304{
1305        return dag_read_packet_stream(libtrace, FORMAT_DATA_FIRST, NULL, packet);
1306}
1307
1308static int dag_pread_packets(libtrace_t *libtrace, libtrace_thread_t *t,
1309                             libtrace_packet_t **packets, size_t nb_packets)
1310{
1311        int ret;
1312        size_t read_packets = 0;
1313        int numbytes = 0;
1314
1315        struct dag_per_stream_t *stream_data =
1316                (struct dag_per_stream_t *)t->format_data;
1317
1318        /* Read as many packets as we can, but read atleast one packet */
1319        do {
1320                ret = dag_read_packet_stream(libtrace, stream_data, t,
1321                                           packets[read_packets]);
1322                if (ret < 0)
1323                        return ret;
1324
1325                read_packets++;
1326
1327                /* Make sure we don't read too many packets..! */
1328                if (read_packets >= nb_packets)
1329                        break;
1330
1331                numbytes = dag_available(libtrace, stream_data);
1332        } while (numbytes >= dag_record_size);
1333
1334        return read_packets;
1335}
1336
1337/* Attempts to read a packet from a DAG card in a NON-BLOCKING fashion. If a
1338 * packet is available, we will return a packet event. Otherwise we will
1339 * return a SLEEP event (as we cannot select on the DAG file descriptor).
1340 */
1341static libtrace_eventobj_t trace_event_dag(libtrace_t *libtrace,
1342                                           libtrace_packet_t *packet)
1343{
1344        libtrace_eventobj_t event = {0,0,0.0,0};
1345        dag_record_t *erfptr = NULL;
1346        int numbytes;
1347        uint32_t flags = 0;
1348        struct timeval minwait, tv;
1349       
1350        minwait.tv_sec = 0;
1351        minwait.tv_usec = 10000;
1352
1353        /* Check if we're meant to provide a DUCK update */
1354        numbytes = dag_get_duckinfo(libtrace, packet);
1355        if (numbytes < 0) {
1356                event.type = TRACE_EVENT_TERMINATE;
1357                return event;
1358        } else if (numbytes > 0) {
1359                event.type = TRACE_EVENT_PACKET;
1360                return event;
1361        }
1362       
1363        if (dag_set_stream_poll(FORMAT_DATA->device->fd,
1364                                FORMAT_DATA_FIRST->dagstream, 0, &minwait,
1365                                &minwait) == -1) {
1366                trace_set_err(libtrace, errno, "dag_set_stream_poll");
1367                event.type = TRACE_EVENT_TERMINATE;
1368                return event;
1369        }
1370
1371        do {
1372                erfptr = NULL;
1373                numbytes = 0;
1374
1375                /* Need to call dag_available so that the top pointer will get
1376                 * updated, otherwise we'll never see any data! */
1377                numbytes = dag_available(libtrace, FORMAT_DATA_FIRST);
1378
1379                /* May as well not bother calling dag_get_record if
1380                 * dag_available suggests that there's no data */
1381                if (numbytes != 0)
1382                        erfptr = dag_get_record(FORMAT_DATA_FIRST);
1383                if (erfptr == NULL) {
1384                        /* No packet available - sleep for a very short time */
1385                        if (libtrace_halt) {
1386                                event.type = TRACE_EVENT_TERMINATE;
1387                        } else {
1388                                event.type = TRACE_EVENT_SLEEP;
1389                                event.seconds = 0.0001;
1390                        }
1391                        break;
1392                }
1393                if (dag_prepare_packet_stream(libtrace, FORMAT_DATA_FIRST, packet,
1394                                            erfptr, TRACE_RT_DATA_ERF, flags)) {
1395                        event.type = TRACE_EVENT_TERMINATE;
1396                        break;
1397                }
1398
1399
1400                event.size = trace_get_capture_length(packet) +
1401                        trace_get_framing_length(packet);
1402
1403                /* XXX trace_read_packet() normally applies the following
1404                 * config options for us, but this function is called via
1405                 * trace_event() so we have to do it ourselves */
1406
1407                if (libtrace->filter) {
1408                        int filtret = trace_apply_filter(libtrace->filter,
1409                                                         packet);
1410                        if (filtret == -1) {
1411                                trace_set_err(libtrace, TRACE_ERR_BAD_FILTER,
1412                                              "Bad BPF Filter");
1413                                event.type = TRACE_EVENT_TERMINATE;
1414                                break;
1415                        }
1416
1417                        if (filtret == 0) {
1418                                /* This packet isn't useful so we want to
1419                                 * immediately see if there is another suitable
1420                                 * one - we definitely DO NOT want to return
1421                                 * a sleep event in this case, like we used to
1422                                 * do! */
1423                                libtrace->filtered_packets ++;
1424                                trace_clear_cache(packet);
1425                                continue;
1426                        }
1427
1428                        event.type = TRACE_EVENT_PACKET;
1429                } else {
1430                        event.type = TRACE_EVENT_PACKET;
1431                }
1432
1433                /* Update the DUCK timer */
1434                tv = trace_get_timeval(packet);
1435                DUCK.last_pkt = tv.tv_sec;
1436               
1437                if (libtrace->snaplen > 0) {
1438                        trace_set_capture_length(packet, libtrace->snaplen);
1439                }
1440                libtrace->accepted_packets ++;
1441                break;
1442        } while(1);
1443
1444        return event;
1445}
1446
1447static void dag_get_statistics(libtrace_t *libtrace, libtrace_stat_t *stat)
1448{
1449        libtrace_list_node_t *tmp;
1450        assert(stat && libtrace);
1451        tmp = FORMAT_DATA_HEAD;
1452
1453        /* Dropped packets */
1454        stat->dropped_valid = 1;
1455        stat->dropped = 0;
1456        while (tmp != NULL) {
1457                stat->dropped += STREAM_DATA(tmp)->drops;
1458                tmp = tmp->next;
1459        }
1460
1461}
1462
1463static void dag_get_thread_statisitics(libtrace_t *libtrace, libtrace_thread_t *t,
1464                                       libtrace_stat_t *stat) {
1465        struct dag_per_stream_t *stream_data = t->format_data;
1466        assert(stat && libtrace);
1467
1468        stat->dropped_valid = 1;
1469        stat->dropped = stream_data->drops;
1470
1471        stat->filtered_valid = 1;
1472        stat->filtered = 0;
1473}
1474
1475/* Prints some semi-useful help text about the DAG format module */
1476static void dag_help(void) {
1477        printf("dag format module: $Revision: 1755 $\n");
1478        printf("Supported input URIs:\n");
1479        printf("\tdag:/dev/dagn\n");
1480        printf("\n");
1481        printf("\te.g.: dag:/dev/dag0\n");
1482        printf("\n");
1483        printf("Supported output URIs:\n");
1484        printf("\tnone\n");
1485        printf("\n");
1486}
1487
1488static int dag_pregister_thread(libtrace_t *libtrace, libtrace_thread_t *t,
1489                                bool reader)
1490{
1491        struct dag_per_stream_t *stream_data;
1492        libtrace_list_node_t *node;
1493
1494        if (reader && t->type == THREAD_PERPKT) {
1495                fprintf(stderr, "t%u: registered reader thread", t->perpkt_num);
1496                node = libtrace_list_get_index(FORMAT_DATA->per_stream,
1497                                                t->perpkt_num);
1498                if (node == NULL) {
1499                        trace_set_err(libtrace, TRACE_ERR_INIT_FAILED,
1500                                      "Too few streams supplied for the"
1501                                      " number of threads lanuched");
1502                        return -1;
1503                }
1504                stream_data = node->data;
1505
1506                /* Pass the per thread data to the thread */
1507                t->format_data = stream_data;
1508
1509                /* Attach and start the DAG stream */
1510                printf("t%u: starting and attaching stream #%u\n",
1511                       t->perpkt_num, stream_data->dagstream);
1512                if (dag_start_input_stream(libtrace, stream_data) < 0)
1513                        return -1;
1514        }
1515
1516        fprintf(stderr, "t%u: registered thread\n", t->perpkt_num);
1517
1518        return 0;
1519}
1520
1521static struct libtrace_format_t dag = {
1522        "dag",
1523        "$Id$",
1524        TRACE_FORMAT_ERF,
1525        dag_probe_filename,             /* probe filename */
1526        NULL,                           /* probe magic */
1527        dag_init_input,                 /* init_input */
1528        dag_config_input,               /* config_input */
1529        dag_start_input,                /* start_input */
1530        dag_pause_input,                /* pause_input */
1531        dag_init_output,                /* init_output */
1532        NULL,                           /* config_output */
1533        dag_start_output,               /* start_output */
1534        dag_fin_input,                  /* fin_input */
1535        dag_fin_output,                 /* fin_output */
1536        dag_read_packet,                /* read_packet */
1537        dag_prepare_packet,             /* prepare_packet */
1538        NULL,                           /* fin_packet */
1539        dag_write_packet,               /* write_packet */
1540        erf_get_link_type,              /* get_link_type */
1541        erf_get_direction,              /* get_direction */
1542        erf_set_direction,              /* set_direction */
1543        erf_get_erf_timestamp,          /* get_erf_timestamp */
1544        NULL,                           /* get_timeval */
1545        NULL,                           /* get_seconds */
1546        NULL,                           /* get_timespec */
1547        NULL,                           /* seek_erf */
1548        NULL,                           /* seek_timeval */
1549        NULL,                           /* seek_seconds */
1550        erf_get_capture_length,         /* get_capture_length */
1551        erf_get_wire_length,            /* get_wire_length */
1552        erf_get_framing_length,         /* get_framing_length */
1553        erf_set_capture_length,         /* set_capture_length */
1554        NULL,                           /* get_received_packets */
1555        NULL,                           /* get_filtered_packets */
1556        NULL,                           /* get_dropped_packets */
1557        dag_get_statistics,             /* get_statistics */
1558        NULL,                           /* get_fd */
1559        trace_event_dag,                /* trace_event */
1560        dag_help,                       /* help */
1561        NULL,                            /* next pointer */
1562        {true, 0}, /* live packet capture, thread limit TBD */
1563        dag_pstart_input,
1564        dag_pread_packets,
1565        dag_pause_input,
1566        NULL,
1567        dag_pregister_thread,
1568        NULL,
1569        dag_get_thread_statisitics      /* get thread stats */
1570};
1571
1572void dag_constructor(void)
1573{
1574        register_format(&dag);
1575}
Note: See TracBrowser for help on using the repository browser.