source: lib/format_dag25.c @ 44028d4

4.0.1-hotfixescachetimestampsdevelopdpdk-ndagetsilivegetfragoffhelplibtrace4ndag_formatpfringrc-4.0.1rc-4.0.2rc-4.0.3rc-4.0.4ringdecrementfixringperformanceringtimestampfixes
Last change on this file since 44028d4 was 44028d4, checked in by Shane Alcock <salcock@…>, 10 years ago
  • Fixed problem that Nevil was having with building on Fedora Core 15
  • Property mode set to 100644
File size: 36.8 KB
Line 
1/*
2 * This file is part of libtrace
3 *
4 * Copyright (c) 2007,2008,2009,2010 The University of Waikato, Hamilton,
5 * New Zealand.
6 *
7 * Authors: Daniel Lawson
8 *          Perry Lorier
9 *          Shane Alcock
10 *         
11 * All rights reserved.
12 *
13 * This code has been developed by the University of Waikato WAND
14 * research group. For further information please see http://www.wand.net.nz/
15 *
16 * libtrace is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
20 *
21 * libtrace is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with libtrace; if not, write to the Free Software
28 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29 *
30 * $Id$
31 *
32 */
33
34#define _GNU_SOURCE
35
36#include "config.h"
37#include "common.h"
38#include "libtrace.h"
39#include "libtrace_int.h"
40#include "format_helper.h"
41#include "format_erf.h"
42
43#include <assert.h>
44#include <errno.h>
45#include <fcntl.h>
46#include <stdio.h>
47#include <string.h>
48#include <stdlib.h>
49#include <sys/stat.h>
50
51#include <sys/mman.h>
52/* XXX: Windows doesn't have pthreads, but this code doesn't compile under
53 * Windows anyway so we'll worry about this more later :] */
54#include <pthread.h>
55
56
57#ifdef WIN32
58#  include <io.h>
59#  include <share.h>
60#  define PATH_MAX _MAX_PATH
61#  define snprintf sprintf_s
62#else
63#  include <netdb.h>
64#  ifndef PATH_MAX
65#       define PATH_MAX 4096
66#  endif
67#  include <sys/ioctl.h>
68#endif
69
70/* This format deals with DAG cards that are using drivers from the 2.5 version
71 * onwards, including 3.X.
72 *
73 * DAG is a LIVE capture format.
74 *
75 * This format does support writing, provided the DAG card that you are using
76 * has transmit (Tx) support. Additionally, packets read using this format
77 * are in the ERF format, so can easily be written as ERF traces without
78 * losing any data.
79 */
80
81
82#define DATA(x) ((struct dag_format_data_t *)x->format_data)
83#define DATA_OUT(x) ((struct dag_format_data_out_t *)x->format_data)
84
85#define FORMAT_DATA DATA(libtrace)
86#define FORMAT_DATA_OUT DATA_OUT(libtrace)
87
88#define DUCK FORMAT_DATA->duck
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/* "Global" data that is stored for each DAG input trace */
119struct dag_format_data_t {
120
121        /* Data required for regular DUCK reporting */
122        struct {
123                /* Timestamp of the last DUCK report */
124                uint32_t last_duck;
125                /* The number of seconds between each DUCK report */
126                uint32_t duck_freq;
127                /* Timestamp of the last packet read from the DAG card */
128                uint32_t last_pkt;
129                /* Dummy trace to ensure DUCK packets are dealt with using the
130                 * DUCK format functions */
131                libtrace_t *dummy_duck;
132        } duck;
133
134        /* The DAG device that we are reading from */
135        struct dag_dev_t *device;
136        /* The DAG stream that we are reading from */
137        unsigned int dagstream;
138        /* Boolean flag indicating whether the stream is currently attached */
139        int stream_attached;
140        /* Pointer to the first unread byte in the DAG memory hole */
141        uint8_t *bottom;
142        /* Pointer to the last unread byte in the DAG memory hole */
143        uint8_t *top;
144        /* The amount of data processed thus far from the bottom pointer */
145        uint32_t processed;
146        /* The number of packets that have been dropped */
147        uint64_t drops;
148};
149
150/* To be thread-safe, we're going to need a mutex for operating on the list
151 * of DAG devices */
152pthread_mutex_t open_dag_mutex;
153
154/* The list of DAG devices that have been opened by libtrace.
155 *
156 * We can only open each DAG device once, but we might want to read from
157 * multiple streams. Therefore, we need to maintain a list of devices that we
158 * have opened (with ref counts!) so that we don't try to open a device too
159 * many times or close a device that we're still using */
160struct dag_dev_t *open_dags = NULL;
161
162/* Returns the amount of padding between the ERF header and the start of the
163 * captured packet data */
164static int dag_get_padding(const libtrace_packet_t *packet)
165{
166        /* ERF Ethernet records have a 2 byte padding before the packet itself
167         * so that the IP header is aligned on a 32 bit boundary.
168         */
169        if (packet->trace->format->type==TRACE_FORMAT_ERF) {
170                dag_record_t *erfptr = (dag_record_t *)packet->header;
171                switch(erfptr->type) {
172                        case TYPE_ETH:
173                        case TYPE_DSM_COLOR_ETH:
174                                return 2;
175                        default:                return 0;
176                }
177        }
178        else {
179                switch(trace_get_link_type(packet)) {
180                        case TRACE_TYPE_ETH:    return 2;
181                        default:                return 0;
182                }
183        }
184}
185
186/* Attempts to determine if the given filename refers to a DAG device */
187static int dag_probe_filename(const char *filename)
188{
189        struct stat statbuf;
190        /* Can we stat the file? */
191        if (stat(filename, &statbuf) != 0) {
192                return 0;
193        }
194        /* Is it a character device? */
195        if (!S_ISCHR(statbuf.st_mode)) {
196                return 0;
197        }
198        /* Yeah, it's probably us. */
199        return 1;
200}
201
202/* Initialises the DAG output data structure */
203static void dag_init_format_out_data(libtrace_out_t *libtrace) {
204        libtrace->format_data = (struct dag_format_data_out_t *) malloc(sizeof(struct dag_format_data_out_t));
205        // no DUCK on output
206        FORMAT_DATA_OUT->stream_attached = 0;
207        FORMAT_DATA_OUT->device = NULL;
208        FORMAT_DATA_OUT->dagstream = 0;
209        FORMAT_DATA_OUT->waiting = 0;
210
211}
212
213/* Initialises the DAG input data structure */
214static void dag_init_format_data(libtrace_t *libtrace) {
215        libtrace->format_data = (struct dag_format_data_t *)
216                malloc(sizeof(struct dag_format_data_t));
217        DUCK.last_duck = 0;
218        DUCK.duck_freq = 0;
219        DUCK.last_pkt = 0;
220        DUCK.dummy_duck = NULL;
221        FORMAT_DATA->stream_attached = 0;
222        FORMAT_DATA->drops = 0;
223        FORMAT_DATA->device = NULL;
224        FORMAT_DATA->dagstream = 0;
225        FORMAT_DATA->processed = 0;
226        FORMAT_DATA->bottom = NULL;
227        FORMAT_DATA->top = NULL;
228}
229
230/* Determines if there is already an entry for the given DAG device in the
231 * device list and increments the reference count for that device, if found.
232 *
233 * NOTE: This function assumes the open_dag_mutex is held by the caller */
234static struct dag_dev_t *dag_find_open_device(char *dev_name) {
235        struct dag_dev_t *dag_dev;
236
237        dag_dev = open_dags;
238
239        /* XXX: Not exactly zippy, but how often are we going to be dealing
240         * with multiple dag cards? */
241        while (dag_dev != NULL) {
242                if (strcmp(dag_dev->dev_name, dev_name) == 0) {
243                        dag_dev->ref_count ++;
244                        return dag_dev;
245
246                }
247                dag_dev = dag_dev->next;
248        }
249        return NULL;
250
251
252}
253
254/* Closes a DAG device and removes it from the device list.
255 *
256 * Attempting to close a DAG device that has a non-zero reference count will
257 * cause an assertion failure!
258 *
259 * NOTE: This function assumes the open_dag_mutex is held by the caller */
260static void dag_close_device(struct dag_dev_t *dev) {
261        /* Need to remove from the device list */
262
263        assert(dev->ref_count == 0);
264
265        if (dev->prev == NULL) {
266                open_dags = dev->next;
267                if (dev->next)
268                        dev->next->prev = NULL;
269        } else {
270                dev->prev->next = dev->next;
271                if (dev->next)
272                        dev->next->prev = dev->prev;
273        }
274
275        dag_close(dev->fd);
276        if (dev->dev_name)
277        free(dev->dev_name);
278        free(dev);
279}
280
281
282/* Opens a new DAG device for writing and adds it to the DAG device list
283 *
284 * NOTE: this function should only be called when opening a DAG device for
285 * writing - there is little practical difference between this and the
286 * function below that covers the reading case, but we need the output trace
287 * object to report errors properly so the two functions take slightly
288 * different arguments. This is really lame and there should be a much better
289 * way of doing this.
290 *
291 * NOTE: This function assumes the open_dag_mutex is held by the caller
292 */
293static struct dag_dev_t *dag_open_output_device(libtrace_out_t *libtrace, char *dev_name) {
294        struct stat buf;
295        int fd;
296        struct dag_dev_t *new_dev;
297
298        /* Make sure the device exists */
299        if (stat(dev_name, &buf) == -1) {
300                trace_set_err_out(libtrace,errno,"stat(%s)",dev_name);
301                return NULL;
302}
303
304        /* Make sure it is the appropriate type of device */
305        if (S_ISCHR(buf.st_mode)) {
306                /* Try opening the DAG device */
307                if((fd = dag_open(dev_name)) < 0) {
308                        trace_set_err_out(libtrace,errno,"Cannot open DAG %s",
309                                        dev_name);
310                        return NULL;
311                }
312        } else {
313                trace_set_err_out(libtrace,errno,"Not a valid dag device: %s",
314                                dev_name);
315                return NULL;
316        }
317
318        /* Add the device to our device list - it is just a doubly linked
319         * list with no inherent ordering; just tack the new one on the front
320         */
321        new_dev = (struct dag_dev_t *)malloc(sizeof(struct dag_dev_t));
322        new_dev->fd = fd;
323        new_dev->dev_name = dev_name;
324        new_dev->ref_count = 1;
325
326        new_dev->prev = NULL;
327        new_dev->next = open_dags;
328        if (open_dags)
329                open_dags->prev = new_dev;
330
331        open_dags = new_dev;
332
333        return new_dev;
334}
335
336/* Opens a new DAG device for reading and adds it to the DAG device list
337 *
338 * NOTE: this function should only be called when opening a DAG device for
339 * reading - there is little practical difference between this and the
340 * function above that covers the writing case, but we need the input trace
341 * object to report errors properly so the two functions take slightly
342 * different arguments. This is really lame and there should be a much better
343 * way of doing this.
344 *
345 * NOTE: This function assumes the open_dag_mutex is held by the caller */
346static struct dag_dev_t *dag_open_device(libtrace_t *libtrace, char *dev_name) {
347        struct stat buf;
348        int fd;
349        struct dag_dev_t *new_dev;
350
351        /* Make sure the device exists */
352        if (stat(dev_name, &buf) == -1) {
353                trace_set_err(libtrace,errno,"stat(%s)",dev_name);
354                return NULL;
355        }
356
357        /* Make sure it is the appropriate type of device */
358        if (S_ISCHR(buf.st_mode)) {
359                /* Try opening the DAG device */
360                if((fd = dag_open(dev_name)) < 0) {
361                        trace_set_err(libtrace,errno,"Cannot open DAG %s",
362                                        dev_name);
363                        return NULL;
364                }
365        } else {
366                trace_set_err(libtrace,errno,"Not a valid dag device: %s",
367                                dev_name);
368                return NULL;
369        }
370
371        /* Add the device to our device list - it is just a doubly linked
372         * list with no inherent ordering; just tack the new one on the front
373         */
374        new_dev = (struct dag_dev_t *)malloc(sizeof(struct dag_dev_t));
375        new_dev->fd = fd;
376        new_dev->dev_name = dev_name;
377        new_dev->ref_count = 1;
378
379        new_dev->prev = NULL;
380        new_dev->next = open_dags;
381        if (open_dags)
382                open_dags->prev = new_dev;
383
384        open_dags = new_dev;
385
386        return new_dev;
387}
388
389/* Creates and initialises a DAG output trace */
390static int dag_init_output(libtrace_out_t *libtrace) {
391        char *dag_dev_name = NULL;
392        char *scan = NULL;
393        struct dag_dev_t *dag_device = NULL;
394        int stream = 1;
395       
396        /* XXX I don't know if this is important or not, but this function
397         * isn't present in all of the driver releases that this code is
398         * supposed to support! */
399        /*
400        unsigned long wake_time;
401        dagutil_sleep_get_wake_time(&wake_time,0);
402        */
403
404        dag_init_format_out_data(libtrace);
405        /* Grab the mutex while we're likely to be messing with the device
406         * list */
407        pthread_mutex_lock(&open_dag_mutex);
408       
409        /* Specific streams are signified using a comma in the libtrace URI,
410         * e.g. dag:/dev/dag0,1 refers to stream 1 on the dag0 device.
411         *
412         * If no stream is specified, we will write using stream 1 */
413        if ((scan = strchr(libtrace->uridata,',')) == NULL) {
414                dag_dev_name = strdup(libtrace->uridata);
415        } else {
416                dag_dev_name = (char *)strndup(libtrace->uridata,
417                                (size_t)(scan - libtrace->uridata));
418                stream = atoi(++scan);
419        }
420        FORMAT_DATA_OUT->dagstream = stream;
421
422        /* See if our DAG device is already open */
423        dag_device = dag_find_open_device(dag_dev_name);
424
425        if (dag_device == NULL) {
426                /* Device not yet opened - open it ourselves */
427                dag_device = dag_open_output_device(libtrace, dag_dev_name);
428        } else {
429                /* Otherwise, just use the existing one */
430                free(dag_dev_name);
431                dag_dev_name = NULL;
432        }
433
434        /* Make sure we have successfully opened a DAG device */
435        if (dag_device == NULL) {
436                if (dag_dev_name) {
437                        free(dag_dev_name);
438                }
439                pthread_mutex_unlock(&open_dag_mutex);
440                return -1;
441        }
442
443        FORMAT_DATA_OUT->device = dag_device;
444        pthread_mutex_unlock(&open_dag_mutex);
445        return 0;
446}
447
448/* Creates and initialises a DAG input trace */
449static int dag_init_input(libtrace_t *libtrace) {
450        char *dag_dev_name = NULL;
451        char *scan = NULL;
452        int stream = 0;
453        struct dag_dev_t *dag_device = NULL;
454
455        dag_init_format_data(libtrace);
456        /* Grab the mutex while we're likely to be messing with the device
457         * list */
458        pthread_mutex_lock(&open_dag_mutex);
459       
460       
461        /* Specific streams are signified using a comma in the libtrace URI,
462         * e.g. dag:/dev/dag0,2 refers to stream 2 on the dag0 device.
463         *
464         * If no stream is specified, we will read from stream 0 */
465        if ((scan = strchr(libtrace->uridata,',')) == NULL) {
466                dag_dev_name = strdup(libtrace->uridata);
467        } else {
468                dag_dev_name = (char *)strndup(libtrace->uridata,
469                                (size_t)(scan - libtrace->uridata));
470                stream = atoi(++scan);
471        }
472
473        FORMAT_DATA->dagstream = stream;
474
475        /* See if our DAG device is already open */
476        dag_device = dag_find_open_device(dag_dev_name);
477
478        if (dag_device == NULL) {
479                /* Device not yet opened - open it ourselves */
480                dag_device = dag_open_device(libtrace, dag_dev_name);
481        } else {
482                /* Otherwise, just use the existing one */
483                free(dag_dev_name);
484                dag_dev_name = NULL;
485        }
486
487        /* Make sure we have successfully opened a DAG device */
488        if (dag_device == NULL) {
489                if (dag_dev_name)
490                        free(dag_dev_name);
491                dag_dev_name = NULL;
492                pthread_mutex_unlock(&open_dag_mutex);
493                return -1;
494        }
495
496        FORMAT_DATA->device = dag_device;
497
498        /* See Config_Status_API_Programming_Guide.pdf from the Endace Dag Documentation */
499        /* Check kBooleanAttributeActive is true -- no point capturing on an interface that's disabled
500 
501        *  The symptom of the port being disabled is that libtrace will appear to hang.
502        */
503        /* Check kBooleanAttributeFault is false */
504        /* Check kBooleanAttributeLocalFault is false */
505        /* Check kBooleanAttributeLock is true ? */
506        /* Check kBooleanAttributePeerLink ? */
507
508        /* Set kBooleanAttributePromisc/kBooleanPromiscuousMode based on libtrace promisc attribute?*/
509        /* Set kUint32AttributeSnapLength to the snaplength */
510
511        pthread_mutex_unlock(&open_dag_mutex);
512        return 0;
513}
514
515/* Configures a DAG input trace */
516static int dag_config_input(libtrace_t *libtrace, trace_option_t option,
517                                void *data) {
518        char conf_str[4096];
519        switch(option) {
520                case TRACE_OPTION_META_FREQ:
521                        /* This option is used to specify the frequency of DUCK
522                         * updates */
523                        DUCK.duck_freq = *(int *)data;
524                        return 0;
525                case TRACE_OPTION_SNAPLEN:
526                        /* Tell the card our new snap length */
527                        snprintf(conf_str, 4096, "varlen slen=%i", *(int *)data);
528                        if (dag_configure(FORMAT_DATA->device->fd,
529                                                conf_str) != 0) {
530                                trace_set_err(libtrace, errno, "Failed to configure snaplen on DAG card: %s", libtrace->uridata);
531                                return -1;
532                        }
533                        return 0;
534                case TRACE_OPTION_PROMISC:
535                        /* DAG already operates in a promisc fashion */
536                        return -1;
537                case TRACE_OPTION_FILTER:
538                        /* We don't yet support pushing filters into DAG
539                         * cards */
540                        return -1;
541                case TRACE_OPTION_EVENT_REALTIME:
542                        /* Live capture is always going to be realtime */
543                        return -1;
544        }
545        return -1;
546}
547
548/* Starts a DAG output trace */
549static int dag_start_output(libtrace_out_t *libtrace) {
550        struct timeval zero, nopoll;
551        uint8_t *top, *bottom;
552        top = bottom = NULL;
553
554        zero.tv_sec = 0;
555        zero.tv_usec = 0;
556        nopoll = zero;
557
558        /* Attach and start the DAG stream */
559
560        if (dag_attach_stream(FORMAT_DATA_OUT->device->fd,
561                        FORMAT_DATA_OUT->dagstream, 0, 1048576) < 0) {
562                trace_set_err_out(libtrace, errno, "Cannot attach DAG stream");
563                return -1;
564        }
565
566        if (dag_start_stream(FORMAT_DATA_OUT->device->fd,
567                        FORMAT_DATA_OUT->dagstream) < 0) {
568                trace_set_err_out(libtrace, errno, "Cannot start DAG stream");
569                return -1;
570        }
571        FORMAT_DATA_OUT->stream_attached = 1;
572
573        /* We don't want the dag card to do any sleeping */
574
575        dag_set_stream_poll(FORMAT_DATA_OUT->device->fd,
576                        FORMAT_DATA_OUT->dagstream, 0, &zero,
577                        &nopoll);
578
579        return 0;
580}
581
582/* Starts a DAG input trace */
583static int dag_start_input(libtrace_t *libtrace) {
584        struct timeval zero, nopoll;
585        uint8_t *top, *bottom;
586        uint8_t diff = 0;
587        top = bottom = NULL;
588
589        zero.tv_sec = 0;
590        zero.tv_usec = 0;
591        nopoll = zero;
592
593        /* Attach and start the DAG stream */
594        if (dag_attach_stream(FORMAT_DATA->device->fd,
595                                FORMAT_DATA->dagstream, 0, 0) < 0) {
596                trace_set_err(libtrace, errno, "Cannot attach DAG stream");
597                return -1;
598        }
599
600        if (dag_start_stream(FORMAT_DATA->device->fd,
601                                FORMAT_DATA->dagstream) < 0) {
602                trace_set_err(libtrace, errno, "Cannot start DAG stream");
603                return -1;
604        }
605        FORMAT_DATA->stream_attached = 1;
606       
607        /* We don't want the dag card to do any sleeping */
608        dag_set_stream_poll(FORMAT_DATA->device->fd,
609                                FORMAT_DATA->dagstream, 0, &zero,
610                                &nopoll);
611
612        /* Should probably flush the memory hole now */
613        do {
614                top = dag_advance_stream(FORMAT_DATA->device->fd,
615                                        FORMAT_DATA->dagstream,
616                                        &bottom);
617                assert(top && bottom);
618                diff = top - bottom;
619                bottom -= diff;
620        } while (diff != 0);
621        FORMAT_DATA->top = NULL;
622        FORMAT_DATA->bottom = NULL;
623        FORMAT_DATA->processed = 0;
624        FORMAT_DATA->drops = 0;
625
626        return 0;
627}
628
629/* Pauses a DAG output trace */
630static int dag_pause_output(libtrace_out_t *libtrace) {
631
632        /* Stop and detach the stream */
633        if (dag_stop_stream(FORMAT_DATA_OUT->device->fd,
634                        FORMAT_DATA_OUT->dagstream) < 0) {
635                trace_set_err_out(libtrace, errno, "Could not stop DAG stream");
636                return -1;
637        }
638        if (dag_detach_stream(FORMAT_DATA_OUT->device->fd,
639                        FORMAT_DATA_OUT->dagstream) < 0) {
640                trace_set_err_out(libtrace, errno, "Could not detach DAG stream");
641                return -1;
642        }
643        FORMAT_DATA_OUT->stream_attached = 0;
644        return 0;
645}
646
647/* Pauses a DAG input trace */
648static int dag_pause_input(libtrace_t *libtrace) {
649
650        /* Stop and detach the stream */
651        if (dag_stop_stream(FORMAT_DATA->device->fd,
652                                FORMAT_DATA->dagstream) < 0) {
653                trace_set_err(libtrace, errno, "Could not stop DAG stream");
654                return -1;
655        }
656        if (dag_detach_stream(FORMAT_DATA->device->fd,
657                                FORMAT_DATA->dagstream) < 0) {
658                trace_set_err(libtrace, errno, "Could not detach DAG stream");
659                return -1;
660        }
661        FORMAT_DATA->stream_attached = 0;
662        return 0;
663}
664
665/* Closes a DAG input trace */
666static int dag_fin_input(libtrace_t *libtrace) {
667        /* Need the lock, since we're going to be handling the device list */
668        pthread_mutex_lock(&open_dag_mutex);
669       
670        /* Detach the stream if we are not paused */
671        if (FORMAT_DATA->stream_attached)
672                dag_pause_input(libtrace);
673        FORMAT_DATA->device->ref_count --;
674
675        /* Close the DAG device if there are no more references to it */
676        if (FORMAT_DATA->device->ref_count == 0)
677                dag_close_device(FORMAT_DATA->device);
678        if (DUCK.dummy_duck)
679                trace_destroy_dead(DUCK.dummy_duck);
680        free(libtrace->format_data);
681        pthread_mutex_unlock(&open_dag_mutex);
682        return 0; /* success */
683}
684
685/* Closes a DAG output trace */
686static int dag_fin_output(libtrace_out_t *libtrace) {
687       
688        /* Commit any outstanding traffic in the txbuffer */
689        if (FORMAT_DATA_OUT->waiting) {
690                dag_tx_stream_commit_bytes(FORMAT_DATA_OUT->device->fd, FORMAT_DATA_OUT->dagstream,
691                                FORMAT_DATA_OUT->waiting );
692        }
693
694        /* Wait until the buffer is nearly clear before exiting the program,
695         * as we will lose packets otherwise */
696        dag_tx_get_stream_space(FORMAT_DATA_OUT->device->fd,
697                        FORMAT_DATA_OUT->dagstream,
698                        dag_get_stream_buffer_size(FORMAT_DATA_OUT->device->fd,
699                                        FORMAT_DATA_OUT->dagstream) - 8
700                        );
701
702        /* Need the lock, since we're going to be handling the device list */
703        pthread_mutex_lock(&open_dag_mutex);
704
705        /* Detach the stream if we are not paused */
706        if (FORMAT_DATA_OUT->stream_attached)
707                dag_pause_output(libtrace);
708        FORMAT_DATA_OUT->device->ref_count --;
709
710        /* Close the DAG device if there are no more references to it */
711        if (FORMAT_DATA_OUT->device->ref_count == 0)
712                dag_close_device(FORMAT_DATA_OUT->device);
713        free(libtrace->format_data);
714        pthread_mutex_unlock(&open_dag_mutex);
715        return 0; /* success */
716}
717
718/* Extracts DUCK information from the DAG card and produces a DUCK packet */
719static int dag_get_duckinfo(libtrace_t *libtrace,
720                                libtrace_packet_t *packet) {
721
722        /* Allocate memory for the DUCK data */
723        if (packet->buf_control == TRACE_CTRL_EXTERNAL ||
724                        !packet->buffer) {
725                packet->buffer = malloc(LIBTRACE_PACKET_BUFSIZE);
726                packet->buf_control = TRACE_CTRL_PACKET;
727                if (!packet->buffer) {
728                        trace_set_err(libtrace, errno,
729                                        "Cannot allocate packet buffer");
730                        return -1;
731                }
732        }
733
734        /* DUCK doesn't have a format header */
735        packet->header = 0;
736        packet->payload = packet->buffer;
737
738        /* No need to check if we can get DUCK or not - we're modern
739         * enough so just grab the DUCK info */
740        if ((ioctl(FORMAT_DATA->device->fd, DAGIOCDUCK,
741                                        (duckinf_t *)packet->payload) < 0)) {
742                trace_set_err(libtrace, errno, "Error using DAGIOCDUCK");
743                return -1;
744        }
745
746        packet->type = TRACE_RT_DUCK_2_5;
747
748        /* Set the packet's tracce to point at a DUCK trace, so that the
749         * DUCK format functions will be called on the packet rather than the
750         * DAG ones */
751        if (!DUCK.dummy_duck)
752                DUCK.dummy_duck = trace_create_dead("rt:localhost:3434");
753        packet->trace = DUCK.dummy_duck;
754        return sizeof(duckinf_t);
755}
756
757/* Determines the amount of data available to read from the DAG card */
758static int dag_available(libtrace_t *libtrace) {
759        uint32_t diff = FORMAT_DATA->top - FORMAT_DATA->bottom;
760
761        /* If we've processed more than 4MB of data since we last called
762         * dag_advance_stream, then we should call it again to allow the
763         * space occupied by that 4MB to be released */
764        if (diff >= dag_record_size && FORMAT_DATA->processed < 4 * 1024 * 1024)
765                return diff;
766       
767        /* Update the top and bottom pointers */
768        FORMAT_DATA->top = dag_advance_stream(FORMAT_DATA->device->fd,
769                        FORMAT_DATA->dagstream,
770                        &(FORMAT_DATA->bottom));
771       
772        if (FORMAT_DATA->top == NULL) {
773                trace_set_err(libtrace, errno, "dag_advance_stream failed!");
774                return -1;
775        }
776        FORMAT_DATA->processed = 0;
777        diff = FORMAT_DATA->top - FORMAT_DATA->bottom;
778        return diff;
779}
780
781/* Returns a pointer to the start of the next complete ERF record */
782static dag_record_t *dag_get_record(libtrace_t *libtrace) {
783        dag_record_t *erfptr = NULL;
784        uint16_t size;
785        erfptr = (dag_record_t *)FORMAT_DATA->bottom;
786        if (!erfptr)
787                return NULL;
788        size = ntohs(erfptr->rlen);
789        assert( size >= dag_record_size );
790        /* Make certain we have the full packet available */
791        if (size > (FORMAT_DATA->top - FORMAT_DATA->bottom))
792                return NULL;
793        FORMAT_DATA->bottom += size;
794        FORMAT_DATA->processed += size;
795        return erfptr;
796}
797
798/* Converts a buffer containing a recently read DAG packet record into a
799 * libtrace packet */
800static int dag_prepare_packet(libtrace_t *libtrace, libtrace_packet_t *packet,
801                void *buffer, libtrace_rt_types_t rt_type, uint32_t flags) {
802
803        dag_record_t *erfptr;
804       
805        /* If the packet previously owned a buffer that is not the buffer
806         * that contains the new packet data, we're going to need to free the
807         * old one to avoid memory leaks */
808        if (packet->buffer != buffer &&
809                        packet->buf_control == TRACE_CTRL_PACKET) {
810                free(packet->buffer);
811        }
812
813        /* Set the buffer owner appropriately */
814        if ((flags & TRACE_PREP_OWN_BUFFER) == TRACE_PREP_OWN_BUFFER) {
815                packet->buf_control = TRACE_CTRL_PACKET;
816        } else
817                packet->buf_control = TRACE_CTRL_EXTERNAL;
818
819        /* Update the packet pointers and type appropriately */
820        erfptr = (dag_record_t *)buffer;
821        packet->buffer = erfptr;
822        packet->header = erfptr;
823        packet->type = rt_type;
824
825        if (erfptr->flags.rxerror == 1) {
826                /* rxerror means the payload is corrupt - drop the payload
827                 * by tweaking rlen */
828                packet->payload = NULL;
829                erfptr->rlen = htons(erf_get_framing_length(packet));
830        } else {
831                packet->payload = (char*)packet->buffer
832                        + erf_get_framing_length(packet);
833        }
834
835        if (libtrace->format_data == NULL) {
836                dag_init_format_data(libtrace);
837        }
838
839        /* Update the dropped packets counter */
840
841        /* No loss counter for DSM coloured records - have to use
842         * some other API */
843        if (erfptr->type == TYPE_DSM_COLOR_ETH) {
844                /* TODO */
845        } else {
846                /* Use the ERF loss counter */
847                DATA(libtrace)->drops += ntohs(erfptr->lctr);
848        }
849
850        return 0;
851}
852
853/*
854 * dag_write_packet() at this stage attempts to improve tx performance
855 * by delaying sending a dag_tx_stream_commit_bytes() until a threshold
856 * has been met. I observed approximately 270% performance increase
857 * through this relatively naive tweak. No optimisation of buffer sizes
858 * was attempted.
859 */
860
861/* Pushes an ERF record onto the transmit stream */
862static int dag_dump_packet(libtrace_out_t *libtrace,
863                dag_record_t *erfptr, unsigned int pad, void *buffer) {
864        int size;
865
866        /*
867         * If we've got 0 bytes waiting in the txqueue, assume that we haven't
868         * requested any space yet, and request some, storing the pointer at
869         * FORMAT_DATA_OUT->txbuffer.
870         *
871         * The amount to request is slightly magical at the moment - it's
872         * 16Mebibytes + 128 kibibytes to ensure that we can copy a packet into
873         * the buffer and handle overruns.
874         */
875        if (FORMAT_DATA_OUT->waiting == 0) {
876                FORMAT_DATA_OUT->txbuffer = dag_tx_get_stream_space(FORMAT_DATA_OUT->device->fd,
877                                FORMAT_DATA_OUT->dagstream, 16908288);
878        }
879
880        /*
881         * Copy the header separately to the body, as we can't guarantee they
882         * are in contiguous memory
883         */
884        memcpy(FORMAT_DATA_OUT->txbuffer + FORMAT_DATA_OUT->waiting,erfptr,(dag_record_size + pad));
885        FORMAT_DATA_OUT->waiting += (dag_record_size + pad);
886
887
888
889        /*
890         * Copy our incoming packet into the outgoing buffer, and increment
891         * our waiting count
892         */
893        size = ntohs(erfptr->rlen)-(dag_record_size + pad);
894        memcpy(FORMAT_DATA_OUT->txbuffer + FORMAT_DATA_OUT->waiting,buffer,size);
895        FORMAT_DATA_OUT->waiting += size;
896
897        /*
898         * If our output buffer has more than 16 Mebibytes in it, commit those
899         * bytes and reset the waiting count to 0.
900         * Note: dag_fin_output will also call dag_tx_stream_commit_bytes() in
901         * case there is still data in the buffer at program exit.
902         */
903
904        if (FORMAT_DATA_OUT->waiting >= 16*1024*1024) {
905                FORMAT_DATA_OUT->txbuffer = dag_tx_stream_commit_bytes(FORMAT_DATA_OUT->device->fd, FORMAT_DATA_OUT->dagstream,
906                        FORMAT_DATA_OUT->waiting );
907                FORMAT_DATA_OUT->waiting = 0;
908        }
909
910        return size + pad + dag_record_size;
911
912}
913
914/* Attempts to determine a suitable ERF type for a given packet. Returns true
915 * if one is found, false otherwise */
916static bool find_compatible_linktype(libtrace_out_t *libtrace,
917                                libtrace_packet_t *packet, char *type)
918{
919         // Keep trying to simplify the packet until we can find
920         //something we can do with it
921
922        do {
923                *type=libtrace_to_erf_type(trace_get_link_type(packet));
924
925                // Success
926                if (*type != (char)-1)
927                        return true;
928
929                if (!demote_packet(packet)) {
930                        trace_set_err_out(libtrace,
931                                        TRACE_ERR_NO_CONVERSION,
932                                        "No erf type for packet (%i)",
933                                        trace_get_link_type(packet));
934                        return false;
935                }
936
937        } while(1);
938
939        return true;
940}
941
942/* Writes a packet to the provided DAG output trace */
943static int dag_write_packet(libtrace_out_t *libtrace, libtrace_packet_t *packet) {
944        /*
945         * This is heavily borrowed from erf_write_packet(). Yes, CnP coding
946         * sucks, sorry about that.
947         */
948        unsigned int pad = 0;
949        int numbytes;
950        void *payload = packet->payload;
951        dag_record_t *header = (dag_record_t *)packet->header;
952        char erf_type = 0;
953
954        if(!packet->header) {
955                /* No header, probably an RT packet. Lifted from
956                 * erf_write_packet(). */
957                return -1;
958        }
959
960        if (trace_get_link_type(packet) == TRACE_TYPE_NONDATA)
961                return 0;
962
963        pad = dag_get_padding(packet);
964
965        /*
966         * If the payload is null, adjust the rlen. Discussion of this is
967         * attached to erf_write_packet()
968         */
969        if (payload == NULL) {
970                header->rlen = htons(dag_record_size + pad);
971        }
972
973        if (packet->type == TRACE_RT_DATA_ERF) {
974                numbytes = dag_dump_packet(libtrace,
975                                header,
976                                pad,
977                                payload
978                                );
979
980        } else {
981                /* Build up a new packet header from the existing header */
982
983                /* Simplify the packet first - if we can't do this, break
984                 * early */
985                if (!find_compatible_linktype(libtrace,packet,&erf_type))
986                        return -1;
987
988                dag_record_t erfhdr;
989
990                erfhdr.ts = bswap_host_to_le64(trace_get_erf_timestamp(packet));
991                payload=packet->payload;
992                pad = dag_get_padding(packet);
993
994                /* Flags. Can't do this */
995                memset(&erfhdr.flags,1,sizeof(erfhdr.flags));
996                if (trace_get_direction(packet)!=~0U)
997                        erfhdr.flags.iface = trace_get_direction(packet);
998
999                erfhdr.type = erf_type;
1000
1001                /* Packet length (rlen includes format overhead) */
1002                assert(trace_get_capture_length(packet)>0
1003                                && trace_get_capture_length(packet)<=65536);
1004                assert(erf_get_framing_length(packet)>0
1005                                && trace_get_framing_length(packet)<=65536);
1006                assert(trace_get_capture_length(packet)+erf_get_framing_length(packet)>0
1007                      &&trace_get_capture_length(packet)+erf_get_framing_length(packet)<=65536);
1008
1009                erfhdr.rlen = htons(trace_get_capture_length(packet)
1010                        + erf_get_framing_length(packet));
1011
1012
1013                /* Loss counter. Can't do this */
1014                erfhdr.lctr = 0;
1015                /* Wire length, does not include padding! */
1016                erfhdr.wlen = htons(trace_get_wire_length(packet));
1017
1018                /* Write it out */
1019                numbytes = dag_dump_packet(libtrace,
1020                                &erfhdr,
1021                                pad,
1022                                payload);
1023
1024        }
1025
1026        return numbytes;
1027}
1028
1029/* Reads the next available packet from a DAG card, in a BLOCKING fashion
1030 *
1031 * If DUCK reporting is enabled, the packet returned may be a DUCK update
1032 */
1033static int dag_read_packet(libtrace_t *libtrace, libtrace_packet_t *packet) {
1034        int size = 0;
1035        struct timeval tv;
1036        dag_record_t *erfptr = NULL;
1037        int numbytes = 0;
1038        uint32_t flags = 0;
1039
1040        /* Check if we're due for a DUCK report */
1041        if (DUCK.last_pkt - DUCK.last_duck > DUCK.duck_freq &&
1042                        DUCK.duck_freq != 0) {
1043                size = dag_get_duckinfo(libtrace, packet);
1044                DUCK.last_duck = DUCK.last_pkt;
1045                if (size != 0) {
1046                        return size;
1047                }
1048                /* No DUCK support, so don't waste our time anymore */
1049                DUCK.duck_freq = 0;
1050        }
1051
1052        /* Don't let anyone try to free our DAG memory hole! */
1053        flags |= TRACE_PREP_DO_NOT_OWN_BUFFER;
1054
1055        /* If the packet buffer is currently owned by libtrace, free it so
1056         * that we can set the packet to point into the DAG memory hole */
1057        if (packet->buf_control == TRACE_CTRL_PACKET) {
1058                free(packet->buffer);
1059                packet->buffer = 0;
1060        }
1061
1062        /* Grab a full ERF record */
1063        do {
1064                numbytes = dag_available(libtrace);
1065                if (numbytes < 0)
1066                        return numbytes;
1067                if (numbytes < dag_record_size)
1068                        /* Block until we see a packet */
1069                        continue;
1070                erfptr = dag_get_record(libtrace);
1071        } while (erfptr == NULL);
1072
1073        /* Prepare the libtrace packet */
1074        if (dag_prepare_packet(libtrace, packet, erfptr, TRACE_RT_DATA_ERF,
1075                                flags))
1076                return -1;
1077
1078        /* Update the DUCK timer */
1079        tv = trace_get_timeval(packet);
1080        DUCK.last_pkt = tv.tv_sec;
1081
1082        return packet->payload ? htons(erfptr->rlen) :
1083                                erf_get_framing_length(packet);
1084}
1085
1086/* Attempts to read a packet from a DAG card in a NON-BLOCKING fashion. If a
1087 * packet is available, we will return a packet event. Otherwise we will
1088 * return a SLEEP event (as we cannot select on the DAG file descriptor).
1089 */
1090static libtrace_eventobj_t trace_event_dag(libtrace_t *trace,
1091                                        libtrace_packet_t *packet) {
1092        libtrace_eventobj_t event = {0,0,0.0,0};
1093        dag_record_t *erfptr = NULL;
1094        int numbytes;
1095        uint32_t flags = 0;
1096
1097        do {
1098                erfptr = NULL;
1099                numbytes = 0;
1100       
1101                /* Need to call dag_available so that the top pointer will get
1102                 * updated, otherwise we'll never see any data! */
1103                numbytes = dag_available(trace);
1104
1105                /* May as well not bother calling dag_get_record if
1106                 * dag_available suggests that there's no data */
1107                if (numbytes != 0)
1108                        erfptr = dag_get_record(trace);
1109                if (erfptr == NULL) {
1110                        /* No packet available - sleep for a very short time */
1111                        event.type = TRACE_EVENT_SLEEP;
1112                        event.seconds = 0.0001;
1113                        break;
1114                }
1115                if (dag_prepare_packet(trace, packet, erfptr, 
1116                                        TRACE_RT_DATA_ERF, flags)) {
1117                        event.type = TRACE_EVENT_TERMINATE;
1118                        break;
1119                }
1120
1121
1122                event.size = trace_get_capture_length(packet) + 
1123                                trace_get_framing_length(packet);
1124               
1125                /* XXX trace_read_packet() normally applies the following
1126                 * config options for us, but this function is called via
1127                 * trace_event() so we have to do it ourselves */
1128
1129                if (trace->filter) {
1130                        if (trace_apply_filter(trace->filter, packet)) {
1131                                event.type = TRACE_EVENT_PACKET;
1132                        } else {
1133                                /* This packet isn't useful so we want to
1134                                 * immediately see if there is another suitable
1135                                 * one - we definitely DO NOT want to return
1136                                 * a sleep event in this case, like we used to
1137                                 * do! */
1138                                trace_clear_cache(packet);
1139                                continue;
1140                        }
1141                } else {
1142                        event.type = TRACE_EVENT_PACKET;
1143                }
1144
1145                if (trace->snaplen > 0) {
1146                        trace_set_capture_length(packet, trace->snaplen);
1147                }
1148                break;
1149        } while (1);
1150
1151        return event;
1152}
1153
1154/* Gets the number of dropped packets */
1155static uint64_t dag_get_dropped_packets(libtrace_t *trace) {
1156        if (trace->format_data == NULL)
1157                return (uint64_t)-1;
1158        return DATA(trace)->drops;
1159}
1160
1161/* Prints some semi-useful help text about the DAG format module */
1162static void dag_help(void) {
1163        printf("dag format module: $Revision$\n");
1164        printf("Supported input URIs:\n");
1165        printf("\tdag:/dev/dagn\n");
1166        printf("\n");
1167        printf("\te.g.: dag:/dev/dag0\n");
1168        printf("\n");
1169        printf("Supported output URIs:\n");
1170        printf("\tnone\n");
1171        printf("\n");
1172}
1173
1174static struct libtrace_format_t dag = {
1175        "dag",
1176        "$Id$",
1177        TRACE_FORMAT_ERF,
1178        dag_probe_filename,             /* probe filename */
1179        NULL,                           /* probe magic */
1180        dag_init_input,                 /* init_input */
1181        dag_config_input,               /* config_input */
1182        dag_start_input,                /* start_input */
1183        dag_pause_input,                /* pause_input */
1184        dag_init_output,                /* init_output */
1185        NULL,                           /* config_output */
1186        dag_start_output,               /* start_output */
1187        dag_fin_input,                  /* fin_input */
1188        dag_fin_output,                 /* fin_output */
1189        dag_read_packet,                /* read_packet */
1190        dag_prepare_packet,             /* prepare_packet */
1191        NULL,                           /* fin_packet */
1192        dag_write_packet,               /* write_packet */
1193        erf_get_link_type,              /* get_link_type */
1194        erf_get_direction,              /* get_direction */
1195        erf_set_direction,              /* set_direction */
1196        erf_get_erf_timestamp,          /* get_erf_timestamp */
1197        NULL,                           /* get_timeval */
1198        NULL,                           /* get_seconds */
1199        NULL,                           /* get_timespec */
1200        NULL,                           /* seek_erf */
1201        NULL,                           /* seek_timeval */
1202        NULL,                           /* seek_seconds */
1203        erf_get_capture_length,         /* get_capture_length */
1204        erf_get_wire_length,            /* get_wire_length */
1205        erf_get_framing_length,         /* get_framing_length */
1206        erf_set_capture_length,         /* set_capture_length */
1207        NULL,                           /* get_received_packets */
1208        NULL,                           /* get_filtered_packets */
1209        dag_get_dropped_packets,        /* get_dropped_packets */
1210        NULL,                           /* get_captured_packets */
1211        NULL,                           /* get_fd */
1212        trace_event_dag,                /* trace_event */
1213        dag_help,                       /* help */
1214        NULL                            /* next pointer */
1215};
1216
1217void dag_constructor(void) {
1218        register_format(&dag);
1219}
Note: See TracBrowser for help on using the repository browser.