-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnmreplay.c
1861 lines (1620 loc) · 49.7 KB
/
nmreplay.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2016 Universita` di Pisa. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* This program implements NMREPLAY, a program to replay a pcap file
* enforcing the output rate and possibly random losses and delay
* distributions.
* It is meant to be run from the command line and implemented with a main
* control thread for monitoring, plus a thread to push packets out.
*
* The control thread parses command line arguments, prepares a
* schedule for transmission in a memory buffer and then sits
* in a loop where it periodically reads traffic statistics from
* the other threads and prints them out on the console.
*
* The transmit buffer contains headers and packets. Each header
* includes a timestamp that determines when the packet should be sent out.
* A "consumer" thread cons() reads from the queue and transmits packets
* on the output netmap port when their time has come.
*
* The program does CPU pinning and sets the scheduler and priority
* for the "cons" threads. Externally one should do the
* assignment of other threads (e.g. interrupt handlers) and
* make sure that network interfaces are configured properly.
*
* --- Main functions of the program ---
* within each function, q is used as a pointer to the queue holding
* packets and parameters.
*
* pcap_prod()
*
* reads from the pcap file and prepares packets to transmit.
* After reading a packet from the pcap file, the following information
* are extracted which can be used to determine the schedule:
*
* q->cur_pkt points to the buffer containing the packet
* q->cur_len packet length, excluding CRC
* q->cur_caplen available packet length (may be shorter than cur_len)
* q->cur_tt transmission time for the packet, computed from the trace.
*
* The following functions are then called in sequence:
*
* q->c_loss (set with the -L command line option) decides
* whether the packet should be dropped before even queuing.
* This is generally useful to emulate random loss.
* The function is supposed to set q->c_drop = 1 if the
* packet should be dropped, or leave it to 0 otherwise.
*
* q->c_bw (set with the -B command line option) is used to
* enforce the transmit bandwidth. The function must store
* in q->cur_tt the transmission time (in nanoseconds) of
* the packet, which is typically proportional to the length
* of the packet, i.e. q->cur_tt = q->cur_len / <bandwidth>
* Variants are possible, eg. to account for constant framing
* bits as on the ethernet, or variable channel acquisition times,
* etc.
* This mechanism can also be used to simulate variable queueing
* delay e.g. due to the presence of cross traffic.
*
* q->c_delay (set with the -ED option) implements delay emulation.
* The function should set q->cur_delay to the additional
* delay the packet is subject to. The framework will take care of
* computing the actual exit time of a packet so that there is no
* reordering.
*/
// debugging macros
#define NED(_fmt, ...) do {} while (0)
#define ED(_fmt, ...) \
do { \
struct timeval _t0; \
gettimeofday(&_t0, NULL); \
fprintf(stderr, "%03d.%03d %-10.10s [%5d] \t" _fmt "\n", \
(int)(_t0.tv_sec % 1000), (int)_t0.tv_usec/1000, \
__FUNCTION__, __LINE__, ##__VA_ARGS__); \
} while (0)
/* WWW is for warnings, EEE is for errors */
#define WWW(_fmt, ...) ED("--WWW-- " _fmt, ##__VA_ARGS__)
#define EEE(_fmt, ...) ED("--EEE-- " _fmt, ##__VA_ARGS__)
#define DDD(_fmt, ...) ED("--DDD-- " _fmt, ##__VA_ARGS__)
#define _GNU_SOURCE // for CPU_SET() etc
#include <errno.h>
#include <fcntl.h>
//#include <libnetmap.h>
#include <math.h> /* log, exp etc. */
#include <pthread.h>
#ifdef __FreeBSD__
#include <pthread_np.h> /* pthread w/ affinity */
#include <sys/cpuset.h> /* cpu_set */
#endif /* __FreeBSD__ */
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* memcpy */
#include <stdint.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/resource.h> // setpriority
#include <sys/time.h>
#include <unistd.h>
#include <nethuns/nethuns.h>
static inline void
my_pkt_copy(const void *_src, void *_dst, int l)
{
const uint64_t *src = (const uint64_t *)_src;
uint64_t *dst = (uint64_t *)_dst;
if (unlikely(l >= 1024 || l % 64)) {
memcpy(dst, src, l);
return;
}
for (; likely(l > 0); l-=64) {
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
*dst++ = *src++;
}
}
/*
*
* A packet in the queue is q_pkt plus the payload.
*
* For the packet descriptor we need the following:
*
* - position of next packet in the queue (can go backwards).
* We can reduce to 32 bits if we consider alignments,
* or we just store the length to be added to the current
* value and assume 0 as a special index.
* - actual packet length (16 bits may be ok)
* - queue output time, in nanoseconds (64 bits)
* - delay line output time, in nanoseconds
* One of the two can be packed to a 32bit value
*
* A convenient coding uses 32 bytes per packet.
*/
struct q_pkt {
uint64_t next; /* buffer index for next packet */
uint64_t pktlen; /* actual packet len */
uint64_t pt_qout; /* time of output from queue */
uint64_t pt_tx; /* transmit time */
};
/*
* The header for a pcap file
*/
struct pcap_file_header {
uint32_t magic;
/*used to detect the file format itself and the byte
ordering. The writing application writes 0xa1b2c3d4 with it's native byte
ordering format into this field. The reading application will read either
0xa1b2c3d4 (identical) or 0xd4c3b2a1 (swapped). If the reading application
reads the swapped 0xd4c3b2a1 value, it knows that all the following fields
will have to be swapped too. For nanosecond-resolution files, the writing
application writes 0xa1b23c4d, with the two nibbles of the two lower-order
bytes swapped, and the reading application will read either 0xa1b23c4d
(identical) or 0x4d3cb2a1 (swapped)*/
uint16_t version_major;
uint16_t version_minor; /*the version number of this file format */
int32_t thiszone;
/*the correction time in seconds between GMT (UTC) and the
local timezone of the following packet header timestamps. Examples: If the
timestamps are in GMT (UTC), thiszone is simply 0. If the timestamps are in
Central European time (Amsterdam, Berlin, ...) which is GMT + 1:00, thiszone
must be -3600*/
uint32_t stampacc; /*the accuracy of time stamps in the capture*/
uint32_t snaplen;
/*the "snapshot length" for the capture (typically 65535
or even more, but might be limited by the user)*/
uint32_t network;
/*link-layer header type, specifying the type of headers
at the beginning of the packet (e.g. 1 for Ethernet); this can be various
types such as 802.11, 802.11 with various radio information, PPP, Token
Ring, FDDI, etc.*/
};
#if 0 /* from pcap.h */
struct pcap_file_header {
bpf_u_int32 magic;
u_short version_major;
u_short version_minor;
bpf_int32 thiszone; /* gmt to local correction */
bpf_u_int32 sigfigs; /* accuracy of timestamps */
bpf_u_int32 snaplen; /* max length saved portion of each pkt */
bpf_u_int32 linktype; /* data link type (LINKTYPE_*) */
};
struct pcap_pkthdr {
struct timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
};
#endif /* from pcap.h */
struct pcap_pkthdr {
uint32_t ts_sec; /* seconds from epoch */
uint32_t ts_frac; /* microseconds or nanoseconds depending on sigfigs */
uint32_t caplen;
/*the number of bytes of packet data actually captured
and saved in the file. This value should never become larger than orig_len
or the snaplen value of the global header*/
uint32_t len; /* wire length */
};
#define PKT_PAD (32) /* padding on packets */
static inline int pad(int x)
{
return ((x) + PKT_PAD - 1) & ~(PKT_PAD - 1) ;
}
/*
* wrapper around the pcap file.
* We mmap the file so it is easy to do multiple passes through it.
*/
struct nm_pcap_file {
int fd;
uint64_t filesize;
const char *data; /* mmapped file */
uint64_t tot_pkt;
uint64_t tot_bytes;
uint64_t tot_bytes_rounded; /* need hdr + pad(len) */
uint32_t resolution; /* 1000 for us, 1 for ns */
int swap; /* need to swap fields ? */
uint64_t first_ts;
uint64_t total_tx_time;
/*
* total_tx_time is computed as last_ts - first_ts, plus the
* transmission time for the first packet which in turn is
* computed according to the average bandwidth
*/
uint64_t file_len;
const char *cur; /* running pointer */
const char *lim; /* data + file_len */
int err;
};
static struct nm_pcap_file *readpcap(const char *fn);
static void destroy_pcap(struct nm_pcap_file *file);
#define NS_SCALE 1000000000UL /* nanoseconds in 1s */
static void destroy_pcap(struct nm_pcap_file *pf)
{
if (!pf)
return;
munmap((void *)(uintptr_t)pf->data, pf->filesize);
close(pf->fd);
bzero(pf, sizeof(*pf));
free(pf);
return;
}
// convert a field of given size if swap is needed.
static uint32_t
cvt(const void *src, int size, char swap)
{
uint32_t ret = 0;
if (size != 2 && size != 4) {
EEE("Invalid size %d\n", size);
exit(1);
}
memcpy(&ret, src, size);
if (swap) {
unsigned char tmp, *data = (unsigned char *)&ret;
int i;
for (i = 0; i < size / 2; i++) {
tmp = data[i];
data[i] = data[size - (1 + i)];
data[size - (1 + i)] = tmp;
}
}
return ret;
}
static uint32_t
read_next_info(struct nm_pcap_file *pf, int size)
{
const char *end = pf->cur + size;
uint32_t ret;
if (end > pf->lim) {
pf->err = 1;
ret = 0;
} else {
ret = cvt(pf->cur, size, pf->swap);
pf->cur = end;
}
return ret;
}
/*
* mmap the file, make sure timestamps are sorted, and count
* packets and sizes
* Timestamps represent the receive time of the packets.
* We need to compute also the 'first_ts' which refers to a hypotetical
* packet right before the first one, see the code for details.
*/
static struct nm_pcap_file *
readpcap(const char *fn)
{
struct nm_pcap_file _f, *pf = &_f;
uint64_t prev_ts, first_pkt_time;
uint32_t magic, first_len = 0;
bzero(pf, sizeof(*pf));
pf->fd = open(fn, O_RDONLY);
if (pf->fd < 0) {
EEE("cannot open file %s", fn);
return NULL;
}
/* compute length */
pf->filesize = lseek(pf->fd, 0, SEEK_END);
lseek(pf->fd, 0, SEEK_SET);
ED("filesize is %lu", (u_long)(pf->filesize));
if (pf->filesize < sizeof(struct pcap_file_header)) {
EEE("file too short %s", fn);
close(pf->fd);
return NULL;
}
pf->data = mmap(NULL, pf->filesize, PROT_READ, MAP_SHARED, pf->fd, 0);
if (pf->data == MAP_FAILED) {
EEE("cannot mmap file %s", fn);
close(pf->fd);
return NULL;
}
pf->cur = pf->data;
pf->lim = pf->data + pf->filesize;
pf->err = 0;
pf->swap = 0; /* default, same endianness when read magic */
magic = read_next_info(pf, 4);
ED("magic is 0x%x", magic);
switch (magic) {
case 0xa1b2c3d4: /* native, us resolution */
pf->swap = 0;
pf->resolution = 1000;
break;
case 0xd4c3b2a1: /* swapped, us resolution */
pf->swap = 1;
pf->resolution = 1000;
break;
case 0xa1b23c4d: /* native, ns resolution */
pf->swap = 0;
pf->resolution = 1; /* nanoseconds */
break;
case 0x4d3cb2a1: /* swapped, ns resolution */
pf->swap = 1;
pf->resolution = 1; /* nanoseconds */
break;
default:
EEE("unknown magic 0x%x", magic);
return NULL;
}
ED("swap %d res %d\n", pf->swap, pf->resolution);
pf->cur = pf->data + sizeof(struct pcap_file_header);
pf->lim = pf->data + pf->filesize;
pf->err = 0;
prev_ts = 0;
while (pf->cur < pf->lim && pf->err == 0) {
uint32_t base = pf->cur - pf->data;
uint64_t cur_ts = read_next_info(pf, 4) * NS_SCALE +
read_next_info(pf, 4) * pf->resolution;
uint32_t caplen = read_next_info(pf, 4);
uint32_t len = read_next_info(pf, 4);
if (pf->err) {
WWW("end of pcap file after %d packets\n",
(int)pf->tot_pkt);
break;
}
if (cur_ts < prev_ts) {
WWW("reordered packet %d\n",
(int)pf->tot_pkt);
}
prev_ts = cur_ts;
(void)base;
if (pf->tot_pkt == 0) {
pf->first_ts = cur_ts;
first_len = len;
}
pf->tot_pkt++;
pf->tot_bytes += len;
pf->tot_bytes_rounded += pad(len) + sizeof(struct q_pkt);
pf->cur += caplen;
}
pf->total_tx_time = prev_ts - pf->first_ts; /* excluding first packet */
ED("tot_pkt %lu tot_bytes %lu tx_time %.6f s first_len %lu",
(u_long)pf->tot_pkt, (u_long)pf->tot_bytes,
1e-9*pf->total_tx_time, (u_long)first_len);
/*
* We determine that based on the
* average bandwidth of the trace, as follows
* first_pkt_ts = p[0].len / avg_bw
* In turn avg_bw = (total_len - p[0].len)/(p[n-1].ts - p[0].ts)
* so
* first_ts = p[0].ts - p[0].len * (p[n-1].ts - p[0].ts) / (total_len - p[0].len)
*/
if (pf->tot_bytes == first_len) {
/* cannot estimate bandwidth, so force 1 Gbit */
first_pkt_time = first_len * 8; /* * 10^9 / bw */
} else {
first_pkt_time = pf->total_tx_time * first_len / (pf->tot_bytes - first_len);
}
ED("first_pkt_time %.6f s", 1e-9*first_pkt_time);
pf->total_tx_time += first_pkt_time;
pf->first_ts -= first_pkt_time;
/* all correct, allocate a record and copy */
pf = calloc(1, sizeof(*pf));
*pf = _f;
/* reset pointer to start */
pf->cur = pf->data + sizeof(struct pcap_file_header);
pf->err = 0;
return pf;
}
enum my_pcap_mode { PM_NONE, PM_FAST, PM_FIXED, PM_REAL };
static int verbose = 0;
static int do_abort = 0;
#ifdef linux
#define cpuset_t cpu_set_t
#endif
#ifdef __APPLE__
#define cpuset_t uint64_t // XXX
static inline void CPU_ZERO(cpuset_t *p)
{
*p = 0;
}
static inline void CPU_SET(uint32_t i, cpuset_t *p)
{
*p |= 1<< (i & 0x3f);
}
#define pthread_setaffinity_np(a, b, c) ((void)a, 0)
#define sched_setscheduler(a, b, c) (1) /* error */
#define clock_gettime(a,b) \
do {struct timespec t0 = {0,0}; *(b) = t0; } while (0)
#define _P64 unsigned long
#endif
#ifndef _P64
/* we use uint64_t widely, but printf gives trouble on different
* platforms so we use _P64 as a cast
*/
#define _P64 uint64_t
#endif /* print stuff */
struct _qs; /* forward */
/*
* descriptor of a configuration entry.
* Each handler has a parse function which takes ac/av[] and returns
* true if successful. Any allocated space is stored into struct _cfg *
* that is passed as argument.
* arg and arg_len are included for convenience.
*/
struct _cfg {
int (*parse)(struct _qs *, struct _cfg *, int ac, char *av[]); /* 0 ok, 1 on error */
int (*run)(struct _qs *, struct _cfg *arg); /* 0 Ok, 1 on error */
// int close(struct _qs *, void *arg); /* 0 Ok, 1 on error */
const char *optarg; /* command line argument. Initial value is the error message */
/* placeholders for common values */
void *arg; /* allocated memory if any */
int arg_len; /* size of *arg in case a realloc is needed */
uint64_t d[16]; /* static storage for simple cases */
double f[4]; /* static storage for simple cases */
};
/*
* communication occurs through this data structure, with fields
* cache-aligned according to who are the readers/writers.
*
The queue is an array of memory (buf) of size buflen (does not change).
The producer uses 'tail' as an index in the queue to indicate
the first empty location (ie. after the last byte of data),
the consumer uses head to indicate the next byte to consume.
For best performance we should align buffers and packets
to multiples of cacheline, but this would explode memory too much.
Worst case memory explosion is with 65 byte packets.
Memory usage as shown below:
qpkt-pad
size 32-16 32-32 32-64 64-64
64 96 96 96 128
65 112 128 160 192
An empty queue has head == tail, a full queue will have free space
below a threshold. In our case the queue is large enough and we
are non blocking so we can simply drop traffic when the queue
approaches a full state.
To simulate bandwidth limitations efficiently, the producer has a second
pointer, prod_tail_1, used to check for expired packets. This is done lazily.
*/
/*
* When sizing the buffer, we must assume some value for the bandwidth.
* INFINITE_BW is supposed to be faster than what we support
*/
#define INFINITE_BW (200ULL*1000000*1000)
#define MY_CACHELINE (128ULL)
#define MAX_PKT (9200) /* max packet size */
#define ALIGN_CACHE __attribute__ ((aligned (MY_CACHELINE)))
struct _qs { /* shared queue */
uint64_t t0; /* start of times */
uint64_t buflen; /* queue length */
char *buf;
/* handlers for various options */
struct _cfg c_delay;
struct _cfg c_bw;
struct _cfg c_loss;
/* producer's fields */
uint64_t tx ALIGN_CACHE; /* tx counter */
uint64_t prod_tail_1; /* head of queue */
uint64_t prod_head; /* cached copy */
uint64_t prod_tail; /* cached copy */
uint64_t prod_drop; /* drop packet count */
uint64_t prod_max_gap; /* rx round duration */
struct nm_pcap_file *pcap; /* the pcap struct */
/* parameters for reading from the netmap port */
nethuns_socket_t *src_port; /* nethuns socket */
const char * prod_ifname; /* interface name or pcap file */
struct netmap_ring *rxring; /* current ring being handled */
uint32_t si; /* ring index */
int burst;
uint32_t rx_qmax; /* stats on max queued */
uint64_t qt_qout; /* queue exit time for last packet */
/*
* when doing shaping, the software computes and stores here
* the time when the most recently queued packet will exit from
* the queue.
*/
uint64_t qt_tx; /* delay line exit time for last packet */
/*
* The software computes the time at which the most recently
* queued packet exits from the queue.
* To avoid reordering, the next packet should exit at least
* at qt_tx + cur_tt
*/
/* producer's fields controlling the queueing */
const char * cur_pkt; /* current packet being analysed */
uint32_t cur_len; /* length of current packet */
uint32_t cur_caplen; /* captured length of current packet */
int cur_drop; /* 1 if current packet should be dropped. */
/*
* cur_drop can be set as a result of the loss emulation,
* and may need to use the packet size, current time, etc.
*/
uint64_t cur_tt; /* transmission time (ns) for current packet */
/*
* The transmission time is how much link time the packet will consume.
* should be set by the function that does the bandwidth emulation,
* but could also be the result of a function that emulates the
* presence of competing traffic, MAC protocols etc.
* cur_tt is 0 for links with infinite bandwidth.
*/
uint64_t cur_delay; /* delay (ns) for current packet from c_delay.run() */
/*
* this should be set by the function that computes the extra delay
* applied to the packet.
* The code makes sure that there is no reordering and possibly
* bumps the output time as needed.
*/
/* consumer's fields */
const char * cons_ifname;
uint64_t rx ALIGN_CACHE; /* rx counter */
uint64_t cons_head; /* cached copy */
uint64_t cons_tail; /* cached copy */
uint64_t cons_now; /* most recent producer timestamp */
uint64_t rx_wait; /* stats */
/* shared fields */
volatile uint64_t _tail ALIGN_CACHE ; /* producer writes here */
volatile uint64_t _head ALIGN_CACHE ; /* consumer reads from here */
};
struct pipe_args {
int wait_link;
pthread_t cons_tid; /* main thread */
pthread_t prod_tid; /* producer thread */
/* Affinity: */
int cons_core; /* core for cons() */
int prod_core; /* core for prod() */
nethuns_socket_t *pa; /* netmap descriptor */
nethuns_socket_t *pb;
struct _qs q;
};
#define NS_IN_S (1000000000ULL) // nanoseconds
#define TIME_UNITS NS_IN_S
/* set the thread affinity. */
static int
setaffinity(int i)
{
cpuset_t cpumask;
struct sched_param p;
if (i == -1)
return 0;
/* Set thread affinity affinity.*/
CPU_ZERO(&cpumask);
CPU_SET(i, &cpumask);
if (pthread_setaffinity_np(pthread_self(), sizeof(cpuset_t), &cpumask) != 0) {
WWW("Unable to set affinity: %s", strerror(errno));
}
if (setpriority(PRIO_PROCESS, 0, -10)) {; // XXX not meaningful
WWW("Unable to set priority: %s", strerror(errno));
}
bzero(&p, sizeof(p));
p.sched_priority = 10; // 99 on linux ?
// use SCHED_RR or SCHED_FIFO
if (sched_setscheduler(0, SCHED_RR, &p)) {
WWW("Unable to set scheduler: %s", strerror(errno));
}
return 0;
}
/*
* set the timestamp from the clock, subtract t0
*/
static inline void
set_tns_now(uint64_t *now, uint64_t t0)
{
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t); // XXX precise on FreeBSD ?
*now = (uint64_t)(t.tv_nsec + NS_IN_S * t.tv_sec);
*now -= t0;
}
/* compare two timestamps */
static inline int64_t
ts_cmp(uint64_t a, uint64_t b)
{
return (int64_t)(a - b);
}
/* create a packet descriptor */
static inline struct q_pkt *
pkt_at(struct _qs *q, uint64_t ofs)
{
return (struct q_pkt *)(q->buf + ofs);
}
/*
* we have already checked for room and prepared p->next
*/
static inline int
enq(struct _qs *q)
{
struct q_pkt *p = pkt_at(q, q->prod_tail);
/* hopefully prefetch has been done ahead */
my_pkt_copy(q->cur_pkt, (char *)(p+1), q->cur_caplen);
p->pktlen = q->cur_len;
p->pt_qout = q->qt_qout;
p->pt_tx = q->qt_tx;
p->next = q->prod_tail + pad(q->cur_len) + sizeof(struct q_pkt);
//NED("enqueue len %d at %d new tail %ld qout %.6f tx %.6f",
// q->cur_len, (int)q->prod_tail, p->next,
// 1e-9*p->pt_qout, 1e-9*p->pt_tx);
q->prod_tail = p->next;
q->tx++;
return 0;
}
/*
* simple handler for parameters not supplied
*/
static int
null_run_fn(struct _qs *q, struct _cfg *cfg)
{
(void)q;
(void)cfg;
return 0;
}
/*
* put packet data into the buffer.
* We read from the mmapped pcap file, construct header, copy
* the captured length of the packet and pad with zeroes.
*/
static void *
pcap_prod(void *_pa)
{
struct pipe_args *pa = _pa;
struct _qs *q = &pa->q;
struct nm_pcap_file *pf = q->pcap; /* already opened by readpcap */
uint32_t loops, i, tot_pkts;
/* data plus the loop record */
uint64_t need;
uint64_t t_tx, tt, last_ts; /* last timestamp from trace */
/*
* For speed we make sure the trace is at least some 1000 packets,
* so we may need to loop the trace more than once (for short traces)
*/
loops = (1 + 10000 / pf->tot_pkt);
tot_pkts = loops * pf->tot_pkt;
need = loops * pf->tot_bytes_rounded + sizeof(struct q_pkt);
q->buf = calloc(1, need);
if (q->buf == NULL) {
ED("alloc %lld bytes for queue failed, exiting",(long long)need);
goto fail;
}
q->prod_head = q->prod_tail = 0;
q->buflen = need;
pf->cur = pf->data + sizeof(struct pcap_file_header);
pf->err = 0;
ED("--- start create %lu packets at tail %d",
(u_long)tot_pkts, (int)q->prod_tail);
last_ts = pf->first_ts; /* beginning of the trace */
q->qt_qout = 0; /* first packet out of the queue */
for (loops = 0, i = 0; i < tot_pkts && !do_abort; i++) {
const char *next_pkt; /* in the pcap buffer */
uint64_t cur_ts;
/* read values from the pcap buffer */
cur_ts = read_next_info(pf, 4) * NS_SCALE +
read_next_info(pf, 4) * pf->resolution;
q->cur_caplen = read_next_info(pf, 4);
q->cur_len = read_next_info(pf, 4);
next_pkt = pf->cur + q->cur_caplen;
/* prepare fields in q for the generator */
q->cur_pkt = pf->cur;
/* initial estimate of tx time */
q->cur_tt = cur_ts - last_ts;
// -pf->first_ts + loops * pf->total_tx_time - last_ts;
if ((i % pf->tot_pkt) == 0)
ED("insert %5d len %lu cur_tt %.6f",
i, (u_long)q->cur_len, 1e-9*q->cur_tt);
/* prepare for next iteration */
pf->cur = next_pkt;
last_ts = cur_ts;
if (next_pkt == pf->lim) { //last pkt
pf->cur = pf->data + sizeof(struct pcap_file_header);
last_ts = pf->first_ts; /* beginning of the trace */
loops++;
}
q->c_loss.run(q, &q->c_loss);
if (q->cur_drop)
continue;
q->c_bw.run(q, &q->c_bw);
tt = q->cur_tt;
q->qt_qout += tt;
#if 0
if (drop_after(q))
continue;
#endif
q->c_delay.run(q, &q->c_delay); /* compute delay */
t_tx = q->qt_qout + q->cur_delay;
NED(5, "tt %ld qout %ld tx %ld qt_tx %ld", tt, q->qt_qout, t_tx, q->qt_tx);
/* insure no reordering and spacing by transmission time */
q->qt_tx = (t_tx >= q->qt_tx + tt) ? t_tx : q->qt_tx + tt;
enq(q);
q->tx++;
NED("ins %d q->prod_tail = %lu", (int)insert, (unsigned long)q->prod_tail);
}
/* loop marker ? */
ED("done q->prod_tail:%d",(int)q->prod_tail);
q->_tail = q->prod_tail; /* publish */
return NULL;
fail:
if (q->buf != NULL) {
free(q->buf);
}
nethuns_close(pa->pb);
return (NULL);
}
/*
* the consumer reads from the queue using head,
* advances it every now and then.
*/
static void *
cons(void *_pa)
{
struct pipe_args *pa = _pa;
struct _qs *q = &pa->q;
int pending = 0;
uint64_t last_ts = 0;
/* read the start of times in q->t0 */
set_tns_now(&q->t0, 0);
/* set the time (cons_now) to clock - q->t0 */
set_tns_now(&q->cons_now, q->t0);
q->cons_head = q->_head;
q->cons_tail = q->_tail;
while (!do_abort) { /* consumer, infinite */
struct q_pkt *p = pkt_at(q, q->cons_head);
__builtin_prefetch (q->buf + p->next);
if (q->cons_head == q->cons_tail) { //reset record
NED("Transmission restarted");
/*
* add to q->t0 the time for the last packet
*/
q->t0 += last_ts;
set_tns_now(&q->cons_now, q->t0);
q->cons_head = 0; //restart from beginning of the queue
continue;
}
last_ts = p->pt_tx;
if (ts_cmp(p->pt_tx, q->cons_now) > 0) {
// packet not ready
q->rx_wait++;
/* the ioctl should be conditional */
nethuns_flush(pa->pb); // XXX just in case
pending = 0;
usleep(20);
set_tns_now(&q->cons_now, q->t0);
continue;
}
/* XXX copy is inefficient but simple */
if (nethuns_send(pa->pb, (uint8_t *)(p + 1), p->pktlen) <= 0) {
// ED("inject failed len %d now %ld tx %ld h %ld t %ld next %ld",
// (int)p->pktlen, (u_long)q->cons_now, (u_long)p->pt_tx,
// (u_long)q->_head, (u_long)q->_tail, (u_long)p->next);
nethuns_flush(pa->pb);
pending = 0;
continue;
}
pending++;
if (pending > q->burst) {
nethuns_flush(pa->pb);
pending = 0;
}
q->cons_head = p->next;
/* drain packets from the queue */
q->rx++;
}
ED("exiting on abort");
return NULL;
}
/*
* In case of pcap file as input, the program acts in 2 different
* phases. It first fill the queue and then starts the cons()
*/
static void *
nmreplay_main(void *_a)
{
struct pipe_args *a = _a;
struct _qs *q = &a->q;
const char *cap_fname = q->prod_ifname;
char errbuf[NETHUNS_ERRBUF_SIZE];
struct nethuns_socket_options netopt = {
.numblocks = 1
, .numpackets = 2048
, .packetsize = 2048
, .timeout_ms = 0
, .dir = nethuns_out
, .capture = nethuns_cap_zero_copy
, .mode = nethuns_socket_rx_tx
, .promisc = false
, .rxhash = false
, .tx_qdisc_bypass = true
, .xdp_prog = NULL
, .xdp_prog_sec = NULL
, .xsk_map_name = NULL
, .reuse_maps = false
, .pin_dir = NULL
};
setaffinity(a->cons_core);
set_tns_now(&q->t0, 0); /* starting reference */
if (cap_fname == NULL) {
goto fail;
}
q->pcap = readpcap(cap_fname);
if (q->pcap == NULL) {
EEE("unable to read file %s", cap_fname);
goto fail;
}
pcap_prod((void*)a);
destroy_pcap(q->pcap);
q->pcap = NULL;
a->pb = nethuns_open(&netopt, errbuf);
if (a->pb == NULL) {
EEE("cannot open nethuns socket: %s", errbuf);
do_abort = 1; // XXX any better way ?
return NULL;
}
if (nethuns_bind(a->pb, q->cons_ifname, 0) < 0) {
EEE("cannot bind %s: %s", q->cons_ifname, strerror(errno));
do_abort = 1; // XXX any better way ?
return NULL;
}
/* continue as cons() */
WWW("prepare to send packets");
usleep(1000);
cons((void*)a);
EEE("exiting on abort");
fail:
if (q->pcap != NULL) {
destroy_pcap(q->pcap);
}
do_abort = 1;
return NULL;
}