source: lib/format_dag25.c @ 32a3ec5

4.0.1-hotfixescachetimestampsdevelopdpdk-ndagetsilivelibtrace4ndag_formatpfringrc-4.0.1rc-4.0.2rc-4.0.3rc-4.0.4ringdecrementfixringperformanceringtimestampfixes
Last change on this file since 32a3ec5 was 32a3ec5, checked in by Shane Alcock <salcock@…>, 6 years ago

Various DAG fixes

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