-
Notifications
You must be signed in to change notification settings - Fork 3
/
hercules.c
3068 lines (2745 loc) · 103 KB
/
hercules.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
// SPDX-License-Identifier: GPL-2.0
// Copyright(c) 2017 - 2018 Intel Corporation.
// Copyright(c) 2019 ETH Zurich.
// Enable extra warnings; cannot be enabled in CFLAGS because cgo generates a
// ton of warnings that can apparantly not be suppressed.
#pragma GCC diagnostic warning "-Wextra"
#include "hercules.h"
#include "packet.h"
#include <stdatomic.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/if_packet.h>
#include <linux/if_xdp.h>
#include <locale.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <float.h>
#include <linux/bpf_util.h>
#include "bpf/src/libbpf.h"
#include "bpf/src/bpf.h"
#include "bpf/src/xsk.h"
#include "linux/filter.h" // actually linux/tools/include/linux/filter.h
#include "frame_queue.h"
#include "bitset.h"
#include "libscion_checksum.h"
#include "congestion_control.h"
#include "utils.h"
#include "send_queue.h"
#include "bpf_prgms.h"
#define MAX_MIDDLEBOX_PROTO_EXTENSION_SIZE 128 // E.g., SCION SPAO header added by LightningFilter
#define L4_SCMP 1
#define NUM_FRAMES (4 * 1024)
#define BATCH_SIZE 64
#define RANDOMIZE_FLOWID
//#define NO_PRELOAD
#define RATE_LIMIT_CHECK 1000 // check rate limit every X packets
// Maximum burst above target pps allowed
#define PATH_HANDSHAKE_TIMEOUT_NS 100e6 // send a path handshake every X=100 ms until the first response arrives
#define ACK_RATE_TIME_MS 100 // send ACKS after at most X milliseconds
static const int rbudp_headerlen = sizeof(u32) + sizeof(u8) + sizeof(sequence_number);
static const u64 tx_handshake_retry_after = 1e9;
static const u64 tx_handshake_timeout = 5e9;
#define PCC_NO_PATH UINT8_MAX // tell the receiver not to count the packet on any path
// exported from hercules.go
extern int HerculesGetReplyPath(const char *packetPtr, int length, struct hercules_path *reply_path);
struct xsk_umem_info {
struct xsk_ring_prod fq;
struct xsk_ring_cons cq;
struct frame_queue available_frames;
pthread_spinlock_t lock;
struct xsk_umem *umem;
void *buffer;
struct hercules_interface *iface;
};
struct xsk_socket_info {
struct xsk_ring_cons rx;
struct xsk_ring_prod tx;
struct xsk_umem_info *umem;
struct xsk_socket *xsk;
};
struct receiver_state_per_path {
struct bitset seq_rcvd;
sequence_number nack_end;
sequence_number prev_nack_end;
u64 rx_npkts;
};
struct hercules_interface {
char ifname[IFNAMSIZ];
int ifid;
int queue;
u32 prog_id;
int ethtool_rule;
u32 num_sockets;
struct xsk_umem_info *umem;
struct xsk_socket_info **xsks;
};
struct hercules_config {
u32 xdp_flags;
struct hercules_app_addr local_addr;
int ether_size;
};
struct hercules_session {
struct hercules_config config;
struct receiver_state *rx_state;
struct sender_state *tx_state;
bool is_running;
bool is_closed;
// State for stat dump
size_t rx_npkts;
size_t tx_npkts;
int control_sockfd;
int num_ifaces;
struct hercules_interface ifaces[];
};
struct receiver_state {
struct hercules_session *session;
atomic_uint_least64_t handshake_rtt;
/** Filesize in bytes */
size_t filesize;
/** Size of file data (in byte) per packet */
u32 chunklen;
/** Number of packets that will make up the entire file. Equal to `ceil(filesize/chunklen)` */
u32 total_chunks;
/** Memory mapped file for receive */
char *mem;
struct bitset received_chunks;
// XXX: reads/writes to this is are a huge data race. Need to sync.
char rx_sample_buf[XSK_UMEM__DEFAULT_FRAME_SIZE];
int rx_sample_len;
int rx_sample_ifid;
// Start/end time of the current transfer
u64 start_time;
u64 end_time;
u64 cts_sent_at;
u64 last_pkt_rcvd; // Timeout detection
u8 num_tracked_paths;
bool is_pcc_benchmark;
struct receiver_state_per_path path_state[256];
};
struct sender_state_per_receiver {
u64 prev_round_start;
u64 prev_round_end;
u64 prev_slope;
u64 ack_wait_duration;
u32 prev_chunk_idx;
bool finished;
/** Next batch should be sent via this path */
u8 path_index;
struct bitset acked_chunks;
atomic_uint_least64_t handshake_rtt; // Handshake RTT in ns
u32 num_paths;
u32 return_path_idx;
struct hercules_app_addr addr;
struct hercules_path *paths;
struct ccontrol_state *cc_states;
bool cts_received;
};
struct sender_state {
struct hercules_session *session;
struct send_queue *send_queue;
// State for transmit rate control
size_t tx_npkts_queued;
u64 prev_rate_check;
size_t prev_tx_npkts_queued;
/** Filesize in bytes */
size_t filesize;
/** Size of file data (in byte) per packet */
u32 chunklen;
/** Number of packets that will make up the entire file. Equal to `ceil(filesize/chunklen)` */
u32 total_chunks;
/** Memory mapped file for receive */
char *mem;
_Atomic u32 rate_limit;
// Start/end time of the current transfer
u64 start_time;
u64 end_time;
u32 num_receivers;
struct sender_state_per_receiver *receiver;
u32 max_paths_per_rcvr;
// shared with Go
struct hercules_path *shd_paths;
const int *shd_num_paths;
atomic_bool has_new_paths;
};
typedef int xskmap;
/**
* @param scionaddrhdr
* @return The receiver index given by the sender address in scionaddrhdr
*/
static u32 rcvr_by_src_address(struct sender_state *tx_state, const struct scionaddrhdr_ipv4 *scionaddrhdr,
const struct udphdr *udphdr)
{
u32 r;
for(r = 0; r < tx_state->num_receivers; r++) {
struct hercules_app_addr *addr = &tx_state->receiver[r].addr;
if(scionaddrhdr->src_ia == addr->ia && scionaddrhdr->src_ip == addr->ip && udphdr->uh_sport == addr->port) {
break;
}
}
return r;
}
static void fill_rbudp_pkt(void *rbudp_pkt, u32 chunk_idx, u8 path_idx, sequence_number seqnr, const char *data,
size_t n, size_t payloadlen);
static bool rbudp_parse_initial(const char *pkt, size_t len, struct rbudp_initial_pkt *parsed_pkt);
static void stitch_checksum(const struct hercules_path *path, u16 precomputed_checksum, char *pkt);
static bool rx_received_all(const struct receiver_state *rx_state)
{
return (rx_state->received_chunks.num_set == rx_state->total_chunks);
}
static bool tx_acked_all(const struct sender_state *tx_state)
{
for(u32 r = 0; r < tx_state->num_receivers; r++) {
if(tx_state->receiver[r].acked_chunks.num_set != tx_state->total_chunks) {
return false;
}
}
return true;
}
static void set_rx_sample(struct receiver_state *rx_state, int ifid, const char *pkt, int len)
{
rx_state->rx_sample_len = len;
rx_state->rx_sample_ifid = ifid;
memcpy(rx_state->rx_sample_buf, pkt, len);
}
static void remove_xdp_program(struct hercules_session *session)
{
for(int i = 0; i < session->num_ifaces; i++) {
u32 curr_prog_id = 0;
if(bpf_get_link_xdp_id(session->ifaces[i].ifid, &curr_prog_id, session->config.xdp_flags)) {
printf("bpf_get_link_xdp_id failed\n");
exit(EXIT_FAILURE);
}
if(session->ifaces[i].prog_id == curr_prog_id)
bpf_set_link_xdp_fd(session->ifaces[i].ifid, -1, session->config.xdp_flags);
else if(!curr_prog_id)
printf("couldn't find a prog id on a given interface\n");
else
printf("program on interface changed, not removing\n");
}
}
static int unconfigure_rx_queues(struct hercules_session *session);
static void __exit_with_error(struct hercules_session *session, int error, const char *file, const char *func, int line)
{
fprintf(stderr, "%s:%s:%i: errno: %d/\"%s\"\n", file, func, line, error, strerror(error));
if(session) {
remove_xdp_program(session);
unconfigure_rx_queues(session);
}
exit(EXIT_FAILURE);
}
#define exit_with_error(session, error) __exit_with_error(session, error, __FILE__, __func__, __LINE__)
static void close_xsk(struct xsk_socket_info *xsk)
{
// Removes socket and frees xsk
xsk_socket__delete(xsk->xsk);
free(xsk);
}
static inline struct hercules_interface *get_interface_by_id(struct hercules_session *session, int ifid)
{
for(int i = 0; i < session->num_ifaces; i++) {
if(session->ifaces[i].ifid == ifid) {
return &session->ifaces[i];
}
}
return NULL;
}
// XXX: from lib/scion/udp.c
/*
* Calculate UDP checksum
* Same as regular IP/UDP checksum but IP addrs replaced with SCION addrs
* buf: Pointer to start of SCION packet
* len: Length of the upper-layer header and data
* return value: Checksum value or 0 iff input is invalid
*/
u16 scion_udp_checksum(const u8 *buf, int len)
{
chk_input chk_input_s;
chk_input *input = init_chk_input(&chk_input_s, 2); // initialize checksum_parse for 2 chunks
if(!input) {
debug_printf("Unable to initialize checksum input: %p", input);
return 0;
}
// XXX construct a pseudo header that is compatible with the checksum computation in
// scionproto/go/lib/slayers/scion.go
u32 pseudo_header_size = sizeof(struct scionaddrhdr_ipv4) + sizeof(struct udphdr) + 2 * sizeof(u32);
u32 pseudo_header[pseudo_header_size / sizeof(u32)];
// SCION address header
const u32 *addr_hdr = (u32 *)(buf + sizeof(struct scionhdr));
size_t i = 0;
for(; i < sizeof(struct scionaddrhdr_ipv4) / sizeof(u32); i++) {
pseudo_header[i] = ntohl(addr_hdr[i]);
}
struct scionhdr *scion_hdr = (struct scionhdr *)buf;
pseudo_header[i++] = len;
__u8 next_header = scion_hdr->next_header;
size_t next_offset = scion_hdr->header_len * SCION_HEADER_LINELEN;
if(next_header == SCION_HEADER_HBH) {
next_header = *(buf + next_offset);
next_offset += (*(buf + next_offset + 1) + 1) * SCION_HEADER_LINELEN;
}
if(next_header == SCION_HEADER_E2E) {
next_header = *(buf + next_offset);
next_offset += (*(buf + next_offset + 1) + 1) * SCION_HEADER_LINELEN;
}
pseudo_header[i++] = next_header;
// UDP header
const u32 *udp_hdr = (const u32 *)(buf + next_offset); // skip over SCION header and extension headers
for(int offset = i; i - offset < sizeof(struct udphdr) / sizeof(u32); i++) {
pseudo_header[i] = ntohl(udp_hdr[i - offset]);
}
pseudo_header[i - 1] &= 0xFFFF0000; // zero-out UDP checksum
chk_add_chunk(input, (u8 *)pseudo_header, pseudo_header_size);
// Length in UDP header includes header size, so subtract it.
struct udphdr *udphdr = (struct udphdr *)udp_hdr;
u16 payload_len = ntohs(udphdr->len) - sizeof(struct udphdr);
if(payload_len != len - sizeof(struct udphdr)) {
debug_printf("Invalid payload_len: Got %u, Expected: %d", payload_len, len - (int)sizeof(struct udphdr));
return 0;
}
const u8 *payload = (u8 *)(udphdr + 1); // skip over UDP header
chk_add_chunk(input, payload, payload_len);
u16 computed_checksum = checksum(input);
return computed_checksum;
}
// Parse ethernet/IP/UDP/SCION/UDP packet,
// this is an extension to the parse_pkt
// function below only doing the checking
// that the BPF program has not already done.
//
// The BPF program writes the offset and the
// addr_idx to the first two words, set
// these arguments to -1 to use them.
static const char *parse_pkt_fast_path(const char *pkt, size_t length, bool check, size_t offset)
{
if(offset == UINT32_MAX) {
offset = *(int *)pkt;
}
if(check) {
struct udphdr *l4udph = (struct udphdr *)(pkt + offset) - 1;
u16 header_checksum = l4udph->check;
if(header_checksum != 0) {
// we compute these pointers here again so that we do not have to pass it from kernel space into user space
// which could negatively affect the performance in the case when the checksum is not verified
struct scionhdr *scionh = (struct scionhdr *)
(pkt + sizeof(struct ether_header) + sizeof(struct iphdr) + sizeof(struct udphdr));
u16 computed_checksum = scion_udp_checksum((u8 *)scionh, length - offset + sizeof(struct udphdr));
if(header_checksum != computed_checksum) {
debug_printf("Checksum in SCION/UDP header %u "
"does not match computed checksum %u",
ntohs(header_checksum), ntohs(computed_checksum));
return NULL;
}
}
}
return pkt + offset;
}
// Parse ethernet/IP/UDP/SCION/UDP packet,
// check that it is addressed to us,
// check SCION-UDP checksum if set.
// sets scionaddrh_o to SCION address header, if provided
// return rbudp-packet (i.e. SCION/UDP packet payload)
static const char *parse_pkt(const struct hercules_session *session, const char *pkt, size_t length, bool check,
const struct scionaddrhdr_ipv4 **scionaddrh_o, const struct udphdr **udphdr_o)
{
// Parse Ethernet frame
if(sizeof(struct ether_header) > length) {
debug_printf("too short for eth header: %zu", length);
return NULL;
}
const struct ether_header *eh = (const struct ether_header *)pkt;
if(eh->ether_type != htons(ETHERTYPE_IP)) { // TODO: support VLAN etc?
debug_printf("not IP");
return NULL;
}
size_t offset = sizeof(struct ether_header);
// Parse IP header
if(offset + sizeof(struct iphdr) > length) {
debug_printf("too short for iphdr: %zu %zu", offset, length);
return NULL;
}
const struct iphdr *iph = (const struct iphdr *)(pkt + offset);
if(iph->protocol != IPPROTO_UDP) {
debug_printf("not UDP: %u, %zu", iph->protocol, offset);
return NULL;
}
if(iph->daddr != session->config.local_addr.ip) {
debug_printf("not addressed to us (IP overlay)");
return NULL;
}
offset += iph->ihl * 4u; // IHL is header length, in number of 32-bit words.
// Parse UDP header
if(offset + sizeof(struct udphdr) > length) {
debug_printf("too short for udphdr: %zu %zu", offset, length);
return NULL;
}
const struct udphdr *udph = (const struct udphdr *)(pkt + offset);
if(udph->dest != htons(SCION_ENDHOST_PORT)) {
debug_printf("not to SCION endhost port: %u", ntohs(udph->dest));
return NULL;
}
offset += sizeof(struct udphdr);
// Parse SCION Common header
if(offset + sizeof(struct scionhdr) > length) {
debug_printf("too short for SCION header: %zu %zu", offset, length);
return NULL;
}
const struct scionhdr *scionh = (const struct scionhdr *)(pkt + offset);
if(scionh->version != 0u) {
debug_printf("unsupported SCION version: %u != 0", scionh->version);
return NULL;
}
if(scionh->dst_type != 0u) {
debug_printf("unsupported destination address type: %u != 0 (IPv4)", scionh->dst_type);
}
if(scionh->src_type != 0u) {
debug_printf("unsupported source address type: %u != 0 (IPv4)", scionh->src_type);
}
__u8 next_header = scionh->next_header;
size_t next_offset = offset + scionh->header_len * SCION_HEADER_LINELEN;
if(next_header == SCION_HEADER_HBH) {
if(next_offset + 2 > length) {
debug_printf("too short for SCION HBH options header: %zu %zu", next_offset, length);
return NULL;
}
next_header = *((__u8 *)pkt + next_offset);
next_offset += (*((__u8 *)pkt + next_offset + 1) + 1) * SCION_HEADER_LINELEN;
}
if(next_header == SCION_HEADER_E2E) {
if(next_offset + 2 > length) {
debug_printf("too short for SCION E2E options header: %zu %zu", next_offset, length);
return NULL;
}
next_header = *((__u8 *)pkt + next_offset);
next_offset += (*((__u8 *)pkt + next_offset + 1) + 1) * SCION_HEADER_LINELEN;
}
if(next_header != IPPROTO_UDP) {
if(next_header == L4_SCMP) {
debug_printf("SCION/SCMP L4: not implemented, ignoring...");
} else {
debug_printf("unknown SCION L4: %u", next_header);
}
return NULL;
}
const struct scionaddrhdr_ipv4 *scionaddrh = (const struct scionaddrhdr_ipv4 *)(pkt + offset +
sizeof(struct scionhdr));
if(scionaddrh->dst_ia != session->config.local_addr.ia) {
debug_printf("not addressed to us (IA)");
return NULL;
}
if(scionaddrh->dst_ip != session->config.local_addr.ip) {
debug_printf("not addressed to us (IP in SCION hdr), expect %x, have %x, remote %x",
session->config.local_addr.ip, scionaddrh->dst_ip, session->tx_state->receiver[0].addr.ip);
return NULL;
}
offset = next_offset;
// Finally parse the L4-UDP header
if(offset + sizeof(struct udphdr) > length) {
debug_printf("too short for SCION/UDP header: %zu %zu", offset, length);
return NULL;
}
const struct udphdr *l4udph = (const struct udphdr *)(pkt + offset);
if(l4udph->dest != session->config.local_addr.port) {
debug_printf("not addressed to us (L4 UDP port): %u", ntohs(l4udph->dest));
return NULL;
}
offset += sizeof(struct udphdr);
if(scionaddrh_o != NULL) {
*scionaddrh_o = scionaddrh;
}
if(udphdr_o != NULL) {
*udphdr_o = l4udph;
}
return parse_pkt_fast_path(pkt, length, check, offset);
}
static bool recv_rbudp_control_pkt(struct hercules_session *session, char *buf, size_t buflen,
const char **payload, int *payloadlen, const struct scionaddrhdr_ipv4 **scionaddrh,
const struct udphdr **udphdr, u8 *path, int *ifid)
{
struct sockaddr_ll addr;
socklen_t addr_size = sizeof(addr);
ssize_t len = recvfrom(session->control_sockfd, buf, buflen, 0, (struct sockaddr *) &addr,
&addr_size); // XXX set timeout
if(len == -1) {
if(errno == EAGAIN || errno == EINTR) {
return false;
}
exit_with_error(session, errno); // XXX: are there situations where we want to try again?
}
if(get_interface_by_id(session, addr.sll_ifindex) == NULL) {
return false; // wrong interface, ignore packet
}
const char *rbudp_pkt = parse_pkt(session, buf, len, true, scionaddrh, udphdr);
if(rbudp_pkt == NULL) {
return false;
}
const size_t rbudp_len = len - (rbudp_pkt - buf);
if(rbudp_len < sizeof(u32)) {
return false;
}
u32 chunk_idx;
memcpy(&chunk_idx, rbudp_pkt, sizeof(u32));
if(chunk_idx != UINT_MAX) {
return false;
}
*payload = rbudp_pkt + rbudp_headerlen;
*payloadlen = rbudp_len - rbudp_headerlen;
u32 path_idx;
memcpy(&path_idx, rbudp_pkt + sizeof(u32), sizeof(*path));
if(path != NULL) {
*path = path_idx;
}
if(ifid != NULL) {
*ifid = addr.sll_ifindex;
}
atomic_fetch_add(&session->rx_npkts, 1);
if(path_idx < PCC_NO_PATH && session->rx_state != NULL) {
atomic_fetch_add(&session->rx_state->path_state[path_idx].rx_npkts, 1);
}
return true;
}
static bool handle_rbudp_data_pkt(struct receiver_state *rx_state, const char *pkt, size_t length)
{
if(length < rbudp_headerlen + rx_state->chunklen) {
return false;
}
u32 chunk_idx;
memcpy(&chunk_idx, pkt, sizeof(u32));
if(chunk_idx >= rx_state->total_chunks) {
if(chunk_idx == UINT_MAX) {
// control packet is handled elsewhere
} else {
fprintf(stderr, "ERROR: chunk_idx larger than expected: %u >= %u\n",
chunk_idx, rx_state->total_chunks);
}
return false;
}
u8 path_idx;
mempcpy(&path_idx, &pkt[4], sizeof(u8));
if(path_idx < PCC_NO_PATH) {
sequence_number seqnr;
memcpy(&seqnr, &pkt[5], sizeof(sequence_number));
if(rx_state->path_state[path_idx].seq_rcvd.bitmap == NULL) {
// TODO compute correct number here
bitset__create(&rx_state->path_state[path_idx].seq_rcvd, 200 * rx_state->total_chunks);
// TODO work out wrap-around
}
if(seqnr >= rx_state->path_state[path_idx].seq_rcvd.num) {
// XXX: currently we cannot track these sequence numbers, as a consequence congestion control breaks at this
// point, abort.
if(!rx_state->session->is_running) {
return true;
} else {
fprintf(stderr, "sequence number overflow %d / %d\n", seqnr,
rx_state->path_state[path_idx].seq_rcvd.num);
exit(EXIT_FAILURE);
}
}
bitset__set_mt_safe(&rx_state->path_state[path_idx].seq_rcvd, seqnr);
u8 old_num = atomic_load(&rx_state->num_tracked_paths);
while(old_num < path_idx + 1) { // update num_tracked_paths
atomic_compare_exchange_strong(&rx_state->num_tracked_paths, &old_num, path_idx + 1);
}
atomic_fetch_add(&rx_state->path_state[path_idx].rx_npkts, 1);
}
bool prev;
if(rx_state->is_pcc_benchmark) {
prev = false; // for benchmarking, we did "not receive this packet before"
// this wilrcl trick the sender into sending the file over and over again,
// regardless of which packets have actually been received. This does not
// break PCC because that takes NACKs send on a per-path basis as feedback
} else {
// mark as received in received_chunks bitmap
prev = bitset__set_mt_safe(&rx_state->received_chunks, chunk_idx);
}
if(!prev) {
const char *payload = pkt + rbudp_headerlen;
const size_t chunk_start = (size_t)chunk_idx * rx_state->chunklen;
const size_t len = umin64(rx_state->chunklen, rx_state->filesize - chunk_start);
memcpy(rx_state->mem + chunk_start, payload, len);
}
return true;
}
static struct xsk_umem_info *xsk_configure_umem(struct hercules_session *session, u32 ifidx, void *buffer, u64 size)
{
struct xsk_umem_info *umem;
int ret;
umem = calloc(1, sizeof(*umem));
if(!umem)
exit_with_error(session, errno);
ret = xsk_umem__create(&umem->umem, buffer, size, &umem->fq, &umem->cq,
NULL);
if(ret)
exit_with_error(session, -ret);
umem->buffer = buffer;
umem->iface = &session->ifaces[ifidx];
// The number of slots in the umem->available_frames queue needs to be larger than the number of frames in the loop,
// pushed in submit_initial_tx_frames() (assumption in pop_completion_ring() and handle_send_queue_unit())
ret = frame_queue__init(&umem->available_frames, XSK_RING_PROD__DEFAULT_NUM_DESCS);
if(ret)
exit_with_error(session, ret);
pthread_spin_init(&umem->lock, 0);
return umem;
}
static void kick_tx(struct hercules_session *session, struct xsk_socket_info *xsk)
{
int ret;
do {
ret = sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
} while(ret < 0 && errno == EAGAIN);
if(ret < 0 && errno != ENOBUFS && errno != EBUSY) {
exit_with_error(session, errno);
}
}
static void kick_all_tx(struct hercules_session *session, struct hercules_interface *iface)
{
for(u32 s = 0; s < iface->num_sockets; s++) {
kick_tx(session, iface->xsks[s]);
}
}
static void submit_initial_rx_frames(struct hercules_session *session, struct xsk_umem_info *umem)
{
int initial_kernel_rx_frame_count = XSK_RING_PROD__DEFAULT_NUM_DESCS - BATCH_SIZE;
u32 idx;
int ret = xsk_ring_prod__reserve(&umem->fq,
initial_kernel_rx_frame_count,
&idx);
if(ret != initial_kernel_rx_frame_count)
exit_with_error(session, -ret);
for(int i = 0; i < initial_kernel_rx_frame_count; i++)
*xsk_ring_prod__fill_addr(&umem->fq, idx++) =
(XSK_RING_PROD__DEFAULT_NUM_DESCS + i) * XSK_UMEM__DEFAULT_FRAME_SIZE;
xsk_ring_prod__submit(&umem->fq, initial_kernel_rx_frame_count);
}
static void submit_initial_tx_frames(struct hercules_session *session, struct xsk_umem_info *umem)
{
// This number needs to be smaller than the number of slots in the umem->available_frames queue (initialized in
// xsk_configure_umem(); assumption in pop_completion_ring() and handle_send_queue_unit())
int initial_tx_frames = XSK_RING_PROD__DEFAULT_NUM_DESCS - BATCH_SIZE;
int avail = frame_queue__prod_reserve(&umem->available_frames, initial_tx_frames);
if(initial_tx_frames > avail) {
debug_printf("trying to push %d initial frames, but only %d slots available", initial_tx_frames, avail);
exit_with_error(session, EINVAL);
}
for(int i = 0; i < avail; i++) {
frame_queue__prod_fill(&umem->available_frames, i, i * XSK_UMEM__DEFAULT_FRAME_SIZE);
}
frame_queue__push(&umem->available_frames, avail);
}
static struct xsk_socket_info *xsk_configure_socket(struct hercules_session *session, int ifidx,
struct xsk_umem_info *umem, int queue, int libbpf_flags,
int bind_flags)
{
struct xsk_socket_config cfg;
struct xsk_socket_info *xsk;
int ret;
if(session->ifaces[ifidx].ifid != umem->iface->ifid) {
debug_printf("cannot configure XSK on interface %d with queue on interface %d", session->ifaces[ifidx].ifid, umem->iface->ifid);
exit_with_error(session, EINVAL);
}
xsk = calloc(1, sizeof(*xsk));
if(!xsk)
exit_with_error(session, errno);
xsk->umem = umem;
cfg.rx_size = XSK_RING_CONS__DEFAULT_NUM_DESCS;
cfg.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
cfg.libbpf_flags = libbpf_flags;
cfg.xdp_flags = session->config.xdp_flags;
cfg.bind_flags = bind_flags;
ret = xsk_socket__create_shared(&xsk->xsk, session->ifaces[ifidx].ifname, queue, umem->umem, &xsk->rx, &xsk->tx,
&umem->fq, &umem->cq, &cfg);
if(ret)
exit_with_error(session, -ret);
ret = bpf_get_link_xdp_id(session->ifaces[ifidx].ifid, &session->ifaces[ifidx].prog_id, session->config.xdp_flags);
if(ret)
exit_with_error(session, -ret);
return xsk;
}
static struct xsk_umem_info *create_umem(struct hercules_session *session, u32 ifidx)
{
void *bufs;
int ret = posix_memalign(&bufs, getpagesize(), /* PAGE_SIZE aligned */
NUM_FRAMES * XSK_UMEM__DEFAULT_FRAME_SIZE);
if(ret)
exit_with_error(session, ret);
struct xsk_umem_info *umem;
umem = xsk_configure_umem(session, ifidx, bufs, NUM_FRAMES * XSK_UMEM__DEFAULT_FRAME_SIZE);
return umem;
}
static void destroy_umem(struct xsk_umem_info *umem)
{
xsk_umem__delete(umem->umem);
free(umem->buffer);
free(umem);
}
// Pop entries from completion ring and store them in umem->available_frames.
static void pop_completion_ring(struct hercules_session *session, struct xsk_umem_info *umem)
{
u32 idx;
size_t entries = xsk_ring_cons__peek(&umem->cq, SIZE_MAX, &idx);
if(entries > 0) {
u16 num = frame_queue__prod_reserve(&umem->available_frames, entries);
if(num < entries) { // there are less frames in the loop than the number of slots in frame_queue
debug_printf("trying to push %ld frames, only got %d slots in frame_queue", entries, num);
exit_with_error(session, EINVAL);
}
for(u16 i = 0; i < num; i++) {
frame_queue__prod_fill(&umem->available_frames, i, *xsk_ring_cons__comp_addr(&umem->cq, idx + i));
}
frame_queue__push(&umem->available_frames, num);
xsk_ring_cons__release(&umem->cq, entries);
atomic_fetch_add(&session->tx_npkts, entries);
}
}
static inline void pop_completion_rings(struct hercules_session *session)
{
for(int i = 0; i < session->num_ifaces; i++) {
pop_completion_ring(session, session->ifaces[i].umem);
}
}
static u32 ack__max_num_entries(u32 len)
{
struct rbudp_ack_pkt ack; // dummy declval
return umin32(UINT8_MAX - 1, (len - sizeof(ack.num_acks) - sizeof(ack.ack_nr) - sizeof(ack.max_seq) - sizeof(ack.timestamp)) / sizeof(ack.acks[0]));
}
static u32 ack__len(const struct rbudp_ack_pkt *ack)
{
return sizeof(ack->num_acks) + sizeof(ack->ack_nr) + sizeof(ack->max_seq) + sizeof(ack->timestamp) + ack->num_acks * sizeof(ack->acks[0]);
}
static u32 fill_ack_pkt(struct receiver_state *rx_state, u32 first, struct rbudp_ack_pkt *ack, size_t max_num_acks)
{
size_t e = 0;
u32 curr = first;
for(; e < max_num_acks;) {
u32 begin = bitset__scan(&rx_state->received_chunks, curr);
if(begin == rx_state->received_chunks.num) {
curr = begin;
break;
}
u32 end = bitset__scan_neg(&rx_state->received_chunks, begin + 1);
curr = end + 1;
ack->acks[e].begin = begin;
ack->acks[e].end = end;
e++;
}
ack->num_acks = e;
return curr;
}
static sequence_number
fill_nack_pkt(sequence_number first, struct rbudp_ack_pkt *ack, size_t max_num_acks, struct bitset *seqs)
{
size_t e = 0;
u32 curr = first;
for(; e < max_num_acks;) {
u32 begin = bitset__scan_neg(seqs, curr);
u32 end = bitset__scan(seqs, begin + 1);
if(end == seqs->num) {
break;
}
curr = end + 1;
ack->acks[e].begin = begin;
ack->acks[e].end = end;
e++;
}
ack->num_acks = e;
return curr;
}
static bool has_more_nacks(sequence_number curr, struct bitset *seqs)
{
u32 begin = bitset__scan_neg(seqs, curr);
u32 end = bitset__scan(seqs, begin + 1);
return end < seqs->num;
}
static void send_eth_frame(struct hercules_session *session, const struct hercules_path *path, void *buf)
{
struct sockaddr_ll addr;
// Index of the network device
addr.sll_ifindex = path->ifid;
// Address length
addr.sll_halen = ETH_ALEN;
// Destination MAC; extracted from ethernet header
memcpy(addr.sll_addr, buf, ETH_ALEN);
ssize_t ret = sendto(session->control_sockfd, buf, path->framelen, 0, (struct sockaddr *) &addr, sizeof(struct sockaddr_ll));
if(ret == -1) {
exit_with_error(session, errno);
}
}
static void tx_register_acks(const struct rbudp_ack_pkt *ack, struct sender_state_per_receiver *rcvr)
{
for(uint16_t e = 0; e < ack->num_acks; ++e) {
const u32 begin = ack->acks[e].begin;
const u32 end = ack->acks[e].end;
if(begin >= end || end > rcvr->acked_chunks.num) {
return; // Abort
}
for(u32 i = begin; i < end; ++i) { // XXX: this can *obviously* be optimized
bitset__set(&rcvr->acked_chunks, i); // don't need thread-safety here, all updates in same thread
}
}
}
#define NACK_TRACE_SIZE (1024*1024)
static u32 nack_trace_count = 0;
static struct {
long long sender_timestamp;
long long receiver_timestamp;
u32 nr;
} nack_trace[NACK_TRACE_SIZE];
static void nack_trace_push(u64 timestamp, u32 nr) {
return;
u32 idx = atomic_fetch_add(&nack_trace_count, 1);
if(idx >= NACK_TRACE_SIZE) {
fprintf(stderr, "oops: nack trace too small, trying to push #%d\n", idx);
exit(133);
}
nack_trace[idx].sender_timestamp = timestamp;
nack_trace[idx].receiver_timestamp = get_nsecs();
nack_trace[idx].nr = nr;
}
#define PCC_TRACE_SIZE (1024*1024)
static u32 pcc_trace_count = 0;
static struct {
u64 time;
sequence_number range_start, range_end, mi_min, mi_max;
u32 excess;
float loss;
u32 delta_left, delta_right, nnacks, nack_pkts;
enum pcc_state state;
u32 target_rate, actual_rate;
double target_duration, actual_duration;
} pcc_trace[PCC_TRACE_SIZE];
static void pcc_trace_push(u64 time, sequence_number range_start, sequence_number range_end, sequence_number mi_min,
sequence_number mi_max, u32 excess, float loss, u32 delta_left, u32 delta_right, u32 nnacks, u32 nack_pkts,
enum pcc_state state, u32 target_rate, u32 actual_rate, double target_duration, double actual_duration) {
u32 idx = atomic_fetch_add(&pcc_trace_count, 1);
if(idx >= PCC_TRACE_SIZE) {
fprintf(stderr, "oops: pcc trace too small, trying to push #%d\n", idx);
exit(133);
}
pcc_trace[idx].time = time;
pcc_trace[idx].range_start = range_start;
pcc_trace[idx].range_end = range_end;
pcc_trace[idx].mi_min = mi_min;
pcc_trace[idx].mi_max = mi_max;
pcc_trace[idx].excess = excess;
pcc_trace[idx].loss = loss;
pcc_trace[idx].delta_left = delta_left;
pcc_trace[idx].delta_right = delta_right;
pcc_trace[idx].nnacks = nnacks;
pcc_trace[idx].nack_pkts = nack_pkts;
pcc_trace[idx].state = state;
pcc_trace[idx].target_rate = target_rate;
pcc_trace[idx].actual_rate = actual_rate;
pcc_trace[idx].target_duration = target_duration;
pcc_trace[idx].actual_duration = actual_duration;
}
static void tx_register_nacks(const struct rbudp_ack_pkt *nack, struct ccontrol_state *cc_state)
{
pthread_spin_lock(&cc_state->lock);
atomic_store(&cc_state->mi_seq_max, umax32(atomic_load(&cc_state->mi_seq_max), nack->max_seq));
cc_state->num_nack_pkts++;
u32 counted = 0;
for(uint16_t e = 0; e < nack->num_acks; ++e) {
u32 begin = nack->acks[e].begin;
u32 end = nack->acks[e].end;
cc_state->mi_seq_min = umin32(cc_state->mi_seq_min, begin);
atomic_store(&cc_state->mi_seq_max_rcvd, umax32(atomic_load(&cc_state->mi_seq_max_rcvd), end));
begin = umax32(begin, cc_state->mi_seq_start);
u32 seq_end = atomic_load(&cc_state->mi_seq_end);
if(seq_end != 0) {
end = umin32(end, seq_end);
}
if(begin >= end) {
continue;
}
counted += end - begin;
cc_state->num_nacks += end - begin;
begin -= cc_state->mi_seq_start;
end -= cc_state->mi_seq_start;
if(end >= cc_state->mi_nacked.num) {
fprintf(stderr, "Cannot track NACK! Out of range: nack end = %d >= bitset size %d\n", end, cc_state->mi_nacked.num);
}
end = umin32(end, cc_state->mi_nacked.num);
for(u32 i = begin; i < end; ++i) { // XXX: this can *obviously* be optimized
bitset__set(&cc_state->mi_nacked, i); // don't need thread-safety here, all updates in same thread
}
}
pthread_spin_unlock(&cc_state->lock);