source: lib/format_dag25.c @ 2725318

develop
Last change on this file since 2725318 was 2725318, checked in by Jacob Van Walraven <jcv9@…>, 2 years ago

Cleanup some of the assertions

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