forked from niranjan-m-gowda/LLMLNCL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultilink.cpp
More file actions
1520 lines (1419 loc) · 51.7 KB
/
multilink.cpp
File metadata and controls
1520 lines (1419 loc) · 51.7 KB
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 2020-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written by: Andrey Belogolovy
* e-mail: andrey.belogolovy@intel.com
*/
#include "multilink.h"
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <synchapi.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sysinfoapi.h>
#include "crc.h"
#include "erasure_code.h"
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "Mincore.lib")
#include <windows.h>
#include <stdio.h>
#include <aclapi.h>
#include <tchar.h>
#include <Realtimeapiset.h>
#else
#include <isa-l.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#endif
#undef DEBUG_PRINT
//#define LLMLNCL_DEBUG_PRINT
#ifdef LLMLNCL_DEBUG_PRINT
#define DEBUG_PRINT 1
#endif
#define ALLOC_CHECK(Ptr, Name) \
if (!(Ptr)) { \
printf("Error allocating memory for "); \
printf((Name)); \
printf("\n"); \
exit(-1); \
}
#ifdef _WIN32
#pragma comment(lib, "Ws2_32.lib")
#define READ_CHECK(FD, Buf, Cnt) { \
DWORD CntR; \
if (!ReadFile((FD), (Buf), (Cnt), ((&CntR)), NULL)) { \
printf("Error reading %d bytes\n", (int32_t)Cnt); \
exit(-1); \
} \
}
#define WRITE_CHECK(FD, Buf, Cnt) { \
DWORD CntR; \
if (!WriteFile((FD), (Buf), (Cnt), (&(CntR)), NULL)) { \
printf("Error writing %d bytes\n", (int32_t)Cnt); \
exit(-1); \
} \
}
#define PIPE_CHECK(Pr, Pw) { \
SECURITY_ATTRIBUTES sa = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE}; \
if (!CreatePipe(&Pr, &Pw, &sa, 1024 * 256)) { \
printf("Error opening pipe\n"); \
exit(-1); \
} \
}
#else
#define READ_CHECK(FD, Buf, Cnt) \
if (read((FD), (Buf), (Cnt)) != (Cnt)) { \
printf("Error reading %d bytes\n", (int32_t)Cnt); \
exit(-1); \
}
#define WRITE_CHECK(FD, Buf, Cnt) \
if (write((FD), (Buf), (Cnt)) != (Cnt)) { \
printf("Error writing %d bytes\n", (int32_t)Cnt); \
exit(-1); \
}
#define PIPE_CHECK(Pp) \
if (pipe(Pp) != 0) { \
printf("Error opening pipe\n"); \
exit(-1); \
}
#endif
MultiLink::MultiLink() {
TotalLinkNumber = 0;
LocalCommDeviceNumber = 0;
RemoteCommDeviceNumber = 0;
TopLocalLink = 0; // Number of the latest link set up
TopRemoteLink = 0; // Number of the latest link set up
}
MultiLink::MultiLink(MultiLink &Ml) {
printf("Copy is not allowed for MultiLink class, exiting\n");
exit(1);
}
MultiLink &MultiLink::operator=(const MultiLink &Ml) {
printf("operator= is not allowed for MultiLink class, exiting\n");
exit(1);
}
void MultiLink::setCommDeviceNumber(uint16_t NumLocal, uint16_t NumRemote) {
if (NumLocal > 32 || NumRemote > 32) {
printf("The library do not support local/remote links greater than 32\n");
exit(-1);
}
LocalCommDeviceNumber = NumLocal;
RemoteCommDeviceNumber = NumRemote;
TotalLinkNumber = LocalCommDeviceNumber * RemoteCommDeviceNumber;
Link = (struct LinkT *)malloc(sizeof(struct LinkT) * TotalLinkNumber);
ALLOC_CHECK(Link, "links");
for (int32_t i = 0; i < TotalLinkNumber; i++) {
Link[i].Status = 0; // set to inactive
Link[i].Remote.sin_addr.s_addr = 0;
Link[i].RxTotalBytes = 0;
Link[i].RxPrevMeasuredTotalBytes = 0;
Link[i].TxTotalBytes = 0;
Link[i].TxPrevMeasuredTotalBytes = 0;
Link[i].TxDesiredRate = (uint64_t)1048576; // default = 1MBps
Link[i].ProbationModeCounter = 0;
Link[i].RemoteLinkIdx = 0xFFFF; // forbidden index;
for (int32_t k = 0; k < 10; k++) { // reset all rates
Link[i].RxRateStatistics[k] = 0;
Link[i].TxRateStatistics[k] = 0;
}
Link[i].EstimatedFreeTime = getLocalTime();
}
// to address Links: Link [ local_index * RemoteCommDeviceNumber +
// remote_index]
#ifdef _WIN32
DWORD dwThreadIdArray;
ThreadRxSocket =
(HANDLE*)malloc(sizeof(HANDLE) * LocalCommDeviceNumber);
#else
ThreadRxSocket =
(pthread_t *)malloc(sizeof(pthread_t) * LocalCommDeviceNumber);
#endif
ALLOC_CHECK(ThreadRxSocket, "socket threads");
for (int32_t i = 0; i < LocalCommDeviceNumber; i++) {
ThreadRxSocket[i] = 0;
}
UdpBuffer = (char **)malloc(sizeof(char *) * LocalCommDeviceNumber);
ALLOC_CHECK(UdpBuffer, "udp buffer");
for (int32_t i = 0; i < LocalCommDeviceNumber; i++) {
UdpBuffer[i] = (char *)malloc(sizeof(char) * MaxUdpBufferSize);
ALLOC_CHECK(UdpBuffer[i], "udp buffer");
}
// redundant packet generation parameters
CrsRateNumerator = 4; // default
CrsRateDenominator = 9; // default
MaxSendSequenceId = 8192;
SendSequenceId = 0;
EncodeMatrix = (uint8_t *)malloc(65536);
ALLOC_CHECK(EncodeMatrix, "RS Encode Matrix");
EncodeMatrix2 = (uint8_t *)malloc(65536);
ALLOC_CHECK(EncodeMatrix2, "RS Encode Matrix");
DecodeMatrix = (uint8_t *)malloc(65536);
ALLOC_CHECK(DecodeMatrix, "RS Decode Matrix");
InvertMatrix = (uint8_t *)malloc(65536);
ALLOC_CHECK(InvertMatrix, "RS Invert Matrix");
TempMatrix =(uint8_t *) malloc(65536);
ALLOC_CHECK(TempMatrix, "RS Temp Matrix");
GTbls = (uint8_t *)malloc(65536 * 32);
ALLOC_CHECK(GTbls, "RS Galua Tables");
GTblsd = (uint8_t *)malloc(65536 * 32);
ALLOC_CHECK(GTblsd, "RS Galua Tables");
for (int32_t i = 0; i < 256; i++) {
RecoverOutp[i] = (uint8_t *)malloc(65536);
}
// open inter-thread pipes, allocate memory buffers and start threads:
#ifdef _WIN32
SendMtx = CreateMutex(NULL, false, NULL);
ReceiveMtx = CreateMutex(NULL, false, NULL);
#else
pthread_mutex_init(&SendMtx, NULL);
pthread_mutex_init(&ReceiveMtx, NULL);
#endif
#ifdef _WIN32
PIPE_CHECK(SendSequencePipe[0], SendSequencePipe[1]);
SendSequencePipeSize = 1024 * 256;
#else
PIPE_CHECK(SendSequencePipe);
fcntl(SendSequencePipe[0], F_SETPIPE_SZ, 1024 * 256);
SendSequencePipeSize = fcntl(SendSequencePipe[0], F_GETPIPE_SZ);
#endif
SendSequenceDataBuffer = (uint8_t *)malloc(256 * PacketSizeMax + 6);
ALLOC_CHECK(SendSequenceDataBuffer, "send sequence buffer");
SendPacketDataBuffer = (uint8_t *)malloc(PacketSizeMax);
ALLOC_CHECK(SendPacketDataBuffer, "send packet buffer");
// redundant packet generaton thread
#ifdef _WIN32
ThreadRedundant = CreateThread(NULL, 0, helperRedundant, this,
0, &dwThreadIdArray);
#else
pthread_create(&ThreadRedundant, NULL, helperRedundant, this);
#endif
#ifdef _WIN32
PIPE_CHECK(SendPacketPipe[0], SendPacketPipe[1]);
SendPacketPipeSize = 1024 * 256;
#else
PIPE_CHECK(SendPacketPipe);
fcntl(SendPacketPipe[0], F_SETPIPE_SZ, 1024 * 256);
SendPacketPipeSize = fcntl(SendPacketPipe[0], F_GETPIPE_SZ);
#endif
SendRedundantSequenceDataBuffer =
(uint8_t *)malloc(256 * PacketSizeMax + 6);
ALLOC_CHECK(SendRedundantSequenceDataBuffer, "redundant sequence buffer");
SendRedundantPacketDataBuffer = (uint8_t *)malloc(PacketSizeMax);
ALLOC_CHECK(SendRedundantPacketDataBuffer, "redundant packet buffer");
SendPacketSchedulerBuffer = (uint8_t *)malloc(PacketSizeMax);
ALLOC_CHECK(SendPacketSchedulerBuffer, "scheduler packet buffer");
// UDP packet sender thread
#ifdef _WIN32
ThreadScheduler = CreateThread(NULL, 0, helperScheduler, this,
0, &dwThreadIdArray);
SendPacketWriterMtx = CreateMutex(NULL, false, NULL);
#else
pthread_mutex_init(&SendPacketWriterMtx, NULL);
pthread_create(&ThreadScheduler, NULL, helperScheduler, this);
#endif
#ifdef _WIN32
// to send data from socket receiver to sequence decoder
PIPE_CHECK(ReceivePacketPipe[0], ReceivePacketPipe[1]);
// to send data from sequence decoder to the final recepient
PIPE_CHECK(ReceiveSequencePipe[0], ReceiveSequencePipe[1]);
ReceiveSequencePipeSize = 1024 * 256;
ReceiveSequencePipeCurSize = 0;
#else
PIPE_CHECK(ReceivePacketPipe);
// to send data from socket receiver to sequence decoder
fcntl(ReceivePacketPipe[0], F_SETPIPE_SZ, 1024 * 256);
PIPE_CHECK(ReceiveSequencePipe);
// to send data from sequence decoder to the final recepient
fcntl(ReceiveSequencePipe[0], F_SETPIPE_SZ, 1024 * 256);
ReceiveSequencePipeSize = fcntl(ReceiveSequencePipe[0], F_GETPIPE_SZ);
#endif
ReceivePacketDataBuffer = (uint8_t *)malloc(PacketSizeMax);
ALLOC_CHECK(ReceivePacketDataBuffer, "receive packet buffer");
DecoderSequences = (struct DecoderSequenceT *)malloc(
MaxSendSequenceId * sizeof(struct DecoderSequenceT));
ALLOC_CHECK(DecoderSequences, "decoder sequences");
DecodedSequenceBuffer = (uint8_t *)malloc(256 * PacketSizeMax + 6);
ALLOC_CHECK(DecodedSequenceBuffer, "decoder buffer");
#ifdef _WIN32
ThreadDecoder = CreateThread(NULL, 0, helperDecoder, this,
0, &dwThreadIdArray);
ReceivePacketWriterMtx = CreateMutex(NULL, false, NULL);
WSAStartup(MAKEWORD(2, 2), &wsaData);
#else
// sequence decoder thread
pthread_mutex_init(&ReceivePacketWriterMtx, NULL);
pthread_create(&ThreadDecoder, NULL, helperDecoder, this);
#endif
}
MultiLink::~MultiLink() {
// only if there was initialization before
if (TotalLinkNumber > 0) {
// stop handshake thread if there was an active link
for (int32_t i = 0; i < TotalLinkNumber; i++) {
if (Link[i].Status > 0) {
#ifdef _WIN32
TerminateThread(ThreadHandshake, 0);
#else
pthread_cancel(ThreadHandshake);
#endif
break;
}
}
// stop redundant packet generation thread and free memories
#ifdef _WIN32
TerminateThread(ThreadRedundant, 0);
CloseHandle(SendSequencePipe[0]);
CloseHandle(SendSequencePipe[1]);
#else
pthread_cancel(ThreadRedundant);
close(SendSequencePipe[1]);
close(SendSequencePipe[0]);
#endif
free(SendPacketDataBuffer);
free(SendSequenceDataBuffer);
// stop packet sender thread and free memories
#ifdef _WIN32
TerminateThread(ThreadScheduler, 0);
CloseHandle(SendPacketPipe[1]);
CloseHandle(SendPacketPipe[0]);
#else
pthread_cancel(ThreadScheduler);
close(SendPacketPipe[1]);
close(SendPacketPipe[0]);
#endif
free(SendPacketSchedulerBuffer);
free(SendRedundantPacketDataBuffer);
free(SendRedundantSequenceDataBuffer);
// stop measurements/rate control
for (int32_t i = 0; i < TotalLinkNumber; i++)
if (Link[i].Status == 3) {
#ifdef _WIN32
TerminateThread(Link[i].ThreadMeasurements, 0);
#else
pthread_cancel(Link[i].ThreadMeasurements);
#endif
}
// stop receivers amd free receive buffers
for (int32_t i = 0; i < LocalCommDeviceNumber; i++) {
if (ThreadRxSocket[i]) {
#ifdef _WIN32
TerminateThread(ThreadRxSocket[i], 0);
#else
pthread_cancel(ThreadRxSocket[i]);
#endif
}
free(UdpBuffer[i]);
}
// stop decoder and free memories
#ifdef _WIN32
TerminateThread(ThreadDecoder, 0);
CloseHandle(ReceivePacketPipe[1]);
CloseHandle(ReceivePacketPipe[0]);
CloseHandle(ReceiveSequencePipe[1]);
CloseHandle(ReceiveSequencePipe[0]);
#else
pthread_cancel(ThreadDecoder);
close(ReceivePacketPipe[1]);
close(ReceivePacketPipe[0]);
close(ReceiveSequencePipe[1]);
close(ReceiveSequencePipe[0]);
#endif
free(ReceivePacketDataBuffer);
for (int32_t i = 0; i < MaxSendSequenceId; i++)
if (DecoderSequences[i].AvailableBlockNumber > 0)
free(DecoderSequences[i].Packets);
free(DecoderSequences);
#ifdef _WIN32
WSACleanup();
#endif
}
}
void MultiLink::setRemoteAddrAndPort(uint16_t Num, char *SzIPaddr,
uint16_t Port) {
if (inet_pton(
AF_INET, SzIPaddr,
&Link[0 * RemoteCommDeviceNumber + Num].Remote.sin_addr) <= 0) {
// error
printf("error parsing remote hostname %s\n", SzIPaddr);
exit(-1);
}
for (int32_t ILocal = 0; ILocal < LocalCommDeviceNumber; ILocal++) {
// replicate to all
Link[ILocal * RemoteCommDeviceNumber + Num].Remote.sin_addr.s_addr =
Link[0 * RemoteCommDeviceNumber + Num].Remote.sin_addr.s_addr;
Link[ILocal * RemoteCommDeviceNumber + Num].Remote.sin_family =
AF_INET;
Link[ILocal * RemoteCommDeviceNumber + Num].Remote.sin_port =
htons(Port);
}
}
void MultiLink::addRemoteAddrAndPort(char *SzIPaddr, uint16_t Port) {
setRemoteAddrAndPort(TopRemoteLink, SzIPaddr, Port);
TopRemoteLink++;
if (TopRemoteLink > RemoteCommDeviceNumber) {
printf("Operation exceed number of allowed remote Links (%u)\n",
RemoteCommDeviceNumber);
exit(-1);
}
}
void MultiLink::setLocalIfaceAndPort(uint16_t ILocal, char *Name,
uint16_t Port) {
uint16_t IRemote;
int32_t SocketFd, ErrorCode;
struct sockaddr_in Local;
struct HelperT *Ht1;
#ifdef _WIN32
SocketFd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (SocketFd == INVALID_SOCKET)
wprintf(L"socket function failed with error = %d\n", WSAGetLastError());
#else
SocketFd = socket(AF_INET, SOCK_DGRAM, 0);
#endif
if (SocketFd < 0) {
printf("error creating local socket at iface #%u\n", ILocal);
exit(-1);
}
if (RemoteCommDeviceNumber <= 0) {
printf("error, numbur of remote device can't be 0 or less\n");
exit(-1);
}
for (IRemote = 0; IRemote < RemoteCommDeviceNumber; IRemote++) {
// replicate to all
Link[ILocal * RemoteCommDeviceNumber + IRemote].SocketFd =
SocketFd;
}
Local.sin_family = AF_INET;
Local.sin_port = htons(Port);
Local.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(SocketFd, (const struct sockaddr *)&Local, sizeof(Local)) < 0) {
printf("error binding local socket to port at iface #%u\n", ILocal);
exit(-1);
}
#ifdef _WIN32
if ((ErrorCode = setsockopt(SocketFd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
Name, strlen(Name))) < 0) {
#else
if ((ErrorCode = setsockopt(SocketFd, SOL_SOCKET, SO_BINDTODEVICE, Name,
strlen(Name))) < 0) {
#endif
printf("error binding local socket at iface #%u to device %s\n", ILocal,
Name);
exit(-1);
}
Ht1 = (struct HelperT *)malloc(sizeof(struct HelperT));
ALLOC_CHECK(Ht1, "Helper thread 1");
Ht1->Ml = this;
Ht1->Num = ILocal;
#ifdef _WIN32
DWORD dwThreadIdArray;
ThreadRxSocket[ILocal] = CreateThread(NULL, 0, helperSockets, Ht1,
0, &dwThreadIdArray);
#else
pthread_create(&(ThreadRxSocket[ILocal]), NULL, helperSockets, Ht1);
#endif
}
void MultiLink::addLocalIfaceAndPort(char *Name, uint16_t Port) {
setLocalIfaceAndPort(TopLocalLink, Name, Port);
TopLocalLink++;
if (TopLocalLink > LocalCommDeviceNumber) {
printf("Operation exceed number of allowed remote Links (%u)\n",
LocalCommDeviceNumber);
exit(-1);
}
}
void MultiLink::runSockets(uint16_t LocalSocketIdx) {
uint16_t i, ui16value, RemoteIdx;
struct sockaddr_in SenderAddr;
socklen_t AddrLen;
int32_t MsgLen;
while (1) {
// receive a packet
AddrLen = sizeof(struct sockaddr_in);
#ifdef _WIN32
MsgLen = recvfrom(
Link[LocalSocketIdx * RemoteCommDeviceNumber].SocketFd,
UdpBuffer[LocalSocketIdx], MaxUdpBufferSize, 0,
(struct sockaddr *)&SenderAddr, &AddrLen);
#else
MsgLen = recvfrom(
Link[LocalSocketIdx * RemoteCommDeviceNumber].SocketFd,
UdpBuffer[LocalSocketIdx], MaxUdpBufferSize, MSG_WAITALL,
(struct sockaddr*)&SenderAddr, &AddrLen);
#endif
RemoteIdx = findRemoteIndexByAddr(LocalSocketIdx, SenderAddr);
if (LocalSocketIdx * RemoteCommDeviceNumber + RemoteIdx < TotalLinkNumber)
Link[LocalSocketIdx * RemoteCommDeviceNumber + RemoteIdx]
.RxTotalBytes += MsgLen;
#ifdef DEBUG_PRINT
printf("new packet at local comm#%d: len=%d, from %s:%d\n",
LocalSocketIdx, MsgLen, inet_ntoa(SenderAddr.sin_addr),
ntohs(SenderAddr.sin_port));
if (MsgLen > 1)
printf("fst byte = %0x\n",
*((uint16_t *)&UdpBuffer[LocalSocketIdx][0]));
#endif
// process a packet
switch (MsgLen) {
case 2: // handshake
ui16value = *((uint16_t *)&UdpBuffer[LocalSocketIdx][0]);
if (ui16value != 0xFFFF) { // hanshake request
// check if we already have this sender address in the Links
if (RemoteIdx == RemoteCommDeviceNumber) {
// new request: find an available link ID
for (i = 0; i < RemoteCommDeviceNumber; i++) {
if (Link[LocalSocketIdx * RemoteCommDeviceNumber + i]
.Status == 0)
break;
}
if (i < RemoteCommDeviceNumber) {
int32_t Idx = LocalSocketIdx * RemoteCommDeviceNumber + i;
// we found an empty link slot, so save source IP:port, save remote
// ID and send our link ID to continue
Link[Idx].Remote.sin_addr.s_addr = SenderAddr.sin_addr.s_addr;
Link[Idx].Remote.sin_port = SenderAddr.sin_port;
Link[Idx].Remote.sin_family = AF_INET;
Link[Idx].Status = 2;
// handshake in progress 2
Link[Idx].RemoteLinkIdx = ui16value;
// the value that the other party
// sent is the link idx
} else {
// no free slots, error?
break;
}
} else {
int32_t Idx = LocalSocketIdx * RemoteCommDeviceNumber + RemoteIdx;
// we already have this address, check for Status
if (Link[Idx].Status == 2) {
// handshake started, but the other party SendS the handshate again:
// they did not get our reply. Resend:
i = RemoteIdx;
} else {
if (Link[Idx].Status == 1) {
// we were the source of this initialization, now we have a reply,
// so switch to the next stage
Link[Idx].Status = 2;
// the value that the other party sent is the link idx
Link[Idx].RemoteLinkIdx = ui16value;
} else {
// protocol error? hope it will never happen
}
// we dont have to send the reply back as we have another
// thread that will send 0xFFFF
break;
}
}
// send our link Idx to the remote
ui16value = LocalSocketIdx * RemoteCommDeviceNumber + i;
#ifdef _WIN32
sendto(Link[ui16value].SocketFd, (char *)(&ui16value), 2, 0,
(const struct sockaddr *)&SenderAddr, sizeof(SenderAddr));
#else
sendto(Link[ui16value].SocketFd, (char*)(&ui16value), 2, MSG_DONTWAIT,
(const struct sockaddr*)&SenderAddr, sizeof(SenderAddr));
#endif
// increment tx byte couter
Link[ui16value].TxTotalBytes += 2;
} else { // handshake confirmation
// check if we have this sender address in the links
if (RemoteIdx < RemoteCommDeviceNumber) {
int32_t Idx = LocalSocketIdx * RemoteCommDeviceNumber + RemoteIdx;
if (Link[Idx].Status == 2) {
struct HelperT *Ht2;
// handshake started and processed correctly. Complete it now
ui16value = 0xFFFF;
#ifdef _WIN32
sendto(Link[Idx].SocketFd, (char*)(&ui16value), 2, 0,
(const struct sockaddr*)&SenderAddr, sizeof(SenderAddr));
#else
sendto(Link[Idx].SocketFd, (char*)(&ui16value), 2, MSG_DONTWAIT,
(const struct sockaddr*)&SenderAddr, sizeof(SenderAddr));
#endif
// increment tx byte couter
Link[Idx].TxTotalBytes += 2;
// handshake completed
Link[Idx].Status = 3;
// start measurement thread
Ht2 = (struct HelperT *)malloc(sizeof(struct HelperT));
ALLOC_CHECK(Ht2, "Helper thread 2");
Ht2->Ml = this;
Ht2->Num = Idx;
#ifdef _WIN32
DWORD dwThreadIdArray;
Link[Idx].ThreadMeasurements = CreateThread(NULL, 0,
helperMeasurements, Ht2, 0, &dwThreadIdArray);
#else
pthread_create(&(Link[Idx].ThreadMeasurements),
NULL, helperMeasurements, Ht2);
#endif
#ifdef DEBUG_PRINT
printf("handshake over link %u completed\n",
LocalSocketIdx * RemoteCommDeviceNumber + RemoteIdx);
#endif
}
}
}
break;
case 4: // rate control message
RemoteIdx = *((uint16_t *)&UdpBuffer[LocalSocketIdx][0]);
// this is the link id as remote sees it
ui16value = *((uint16_t *)&UdpBuffer[LocalSocketIdx][2]);
// this is the rate in Kb/s
if (RemoteIdx < TotalLinkNumber) {
for (i = 0; i < TotalLinkNumber; i++) {
// we need to find a link with remote index ID == i
if (Link[i].RemoteLinkIdx == RemoteIdx) { // found it!
Link[i].RxReportedRate = ui16value;
Link[i].LastMeasurementsReceivedTime = getLocalTime();
}
}
}
break;
default: // forward packet to the decoder to be processed
if (MsgLen > 5) {
#ifdef _WIN32
WaitForSingleObject(ReceivePacketWriterMtx, INFINITE);
#else
pthread_mutex_lock(&ReceivePacketWriterMtx);
#endif
WRITE_CHECK(ReceivePacketPipe[1], &MsgLen, 2);
WRITE_CHECK(ReceivePacketPipe[1], UdpBuffer[LocalSocketIdx], MsgLen);
#ifdef _WIN32
ReleaseMutex(ReceivePacketWriterMtx);
#else
pthread_mutex_unlock(&ReceivePacketWriterMtx);
#endif
}
}
}
}
void MultiLink::initiateLinks() {
uint16_t LinkIdx;
if (TopLocalLink != LocalCommDeviceNumber ||
TopRemoteLink != RemoteCommDeviceNumber) {
printf("Local or remote links set up does not equal to requested:\n");
printf("Local set %u, requested %u\n", TopLocalLink, LocalCommDeviceNumber);
printf("Remote set %u, requested %u\n", TopRemoteLink,
RemoteCommDeviceNumber);
exit(-1);
}
// set to handshake init
for (LinkIdx = 0; LinkIdx < TotalLinkNumber; LinkIdx++)
Link[LinkIdx].Status = 1;
#ifdef _WIN32
DWORD dwThreadIdArray;
ThreadHandshake = CreateThread(NULL, 0, helperHandshake,
this, 0, &dwThreadIdArray);
#else
pthread_create(&ThreadHandshake, NULL, helperHandshake, this);
#endif
int32_t HandshakeNotComplete = 1;
printf("Trying to connect %d links (timeout 10 minutes):\n", TotalLinkNumber);
for (LinkIdx = 0; LinkIdx < TotalLinkNumber; LinkIdx++)
printf("localhost %d -> %s:%d\n",
LinkIdx / RemoteCommDeviceNumber,
inet_ntoa(Link[LinkIdx].Remote.sin_addr),
ntohs(Link[LinkIdx].Remote.sin_port));
int32_t Cnt = 0;
while (HandshakeNotComplete && Cnt < 600) {
HandshakeNotComplete = TotalLinkNumber;
for (LinkIdx = 0; LinkIdx < TotalLinkNumber; LinkIdx++) {
// handshake done
if (Link[LinkIdx].Status == 3)
HandshakeNotComplete--;
}
Cnt++;
#ifdef _WIN32
Sleep(1000);
#else
sleep(1);
#endif
printf(".");
}
printf("\n");
if (Cnt >= 600) {
printf("Connection time out! Exiting...\n");
exit(-1);
}
printf("Connection succesfull!\n");
}
void MultiLink::runHandshake() {
/*
Handshake algorithm:
1. initializer SendS its ID to the remote (id should be < then 0xFFFF)
2. Remote replies with its ID
3. initlializer replies with 0xFFFF to confirm/complete ()
4. If remote receives 0xFFFF, it replies with 0xFFFF to confirm completion
*/
uint16_t LinkIdx, Id;
while (1) {
// go over all links
for (LinkIdx = 0; LinkIdx < TotalLinkNumber; LinkIdx++) {
switch (Link[LinkIdx].Status) {
case 1: // send Link ID to init handshake
Id = LinkIdx;
#ifdef _WIN32
sendto(Link[LinkIdx].SocketFd, (char *)&Id, 2, 0,
(const struct sockaddr *)&Link[LinkIdx].Remote,
sizeof(sockaddr_in));
#else
sendto(Link[LinkIdx].SocketFd, (char*)&Id, 2, MSG_DONTWAIT,
(const struct sockaddr*)&Link[LinkIdx].Remote,
sizeof(sockaddr_in));
#endif
// increment tx byte couter
Link[LinkIdx].TxTotalBytes += 2;
break;
case 2:
// send 0xFFFF to complete the handshake
Id = 0xFFFF;
#ifdef _WIN32
sendto(Link[LinkIdx].SocketFd, (char *)&Id, 2, 0,
(const struct sockaddr *)&Link[LinkIdx].Remote,
sizeof(sockaddr_in));
#else
sendto(Link[LinkIdx].SocketFd, (char*)&Id, 2, MSG_DONTWAIT,
(const struct sockaddr*)&Link[LinkIdx].Remote,
sizeof(sockaddr_in));
#endif
// increment tx byte couter
Link[LinkIdx].TxTotalBytes += 2;
break;
}
}
#ifdef _WIN32
Sleep(1000);
#else
sleep(1);
#endif
}
}
void MultiLink::runMeasurements(uint16_t LinkIdx) {
uint64_t CurrentTime, CurTotalBytes, SomeRateObserved;
uint16_t i;
bool RateIncreaseObserved, RateDecreaseObserved;
float AverageOver4Last, MaxAverageOver4Last;
RateDecreaseObserved = false;
RateIncreaseObserved = false;
SomeRateObserved = 1;
#ifdef DEBUG_PRINT
printf("measurements over link %u started\n", LinkIdx);
#endif
Link[LinkIdx].LastRateControlActionTime = getLocalTime();
MaxAverageOver4Last = 0;
while (1) {
#ifdef _WIN32
Sleep(MeasureInterval / 1000);
#else
usleep(MeasureInterval);
#endif
CurrentTime = getLocalTime();
// RX measurements: compute current rate
CurTotalBytes = Link[LinkIdx].RxTotalBytes;
// bytes per second
Link[LinkIdx].RxMeasuredRate = 1.0e6 / MeasureInterval *
(CurTotalBytes - Link[LinkIdx].RxPrevMeasuredTotalBytes);
Link[LinkIdx].RxPrevMeasuredTotalBytes = CurTotalBytes;
// send measurerements to tx in KBps
sendRate(LinkIdx, (uint16_t)(Link[LinkIdx].RxMeasuredRate / 1024));
// TX measurements: compute current rate
CurTotalBytes = Link[LinkIdx].TxTotalBytes;
// bytes per second
Link[LinkIdx].TxMeasuredRate = 1.0e6 / MeasureInterval *
(CurTotalBytes - Link[LinkIdx].TxPrevMeasuredTotalBytes);
Link[LinkIdx].TxPrevMeasuredTotalBytes = CurTotalBytes;
// statistics update
if ((Link[LinkIdx].LastMeasurementsReceivedTime + 2 * MeasureInterval) <
CurrentTime) {
// we did not receive measurements during 2 last intervals
Link[LinkIdx].RxReportedRate = 0;
}
// shift all previous statistics by one
for (i = 9; i > 0; i--) {
Link[LinkIdx].RxRateStatistics[i] =
Link[LinkIdx].RxRateStatistics[i - 1];
Link[LinkIdx].TxRateStatistics[i] =
Link[LinkIdx].TxRateStatistics[i - 1];
}
Link[LinkIdx].RxRateStatistics[0] = (float)Link[LinkIdx].RxReportedRate;
// convert to KBps
Link[LinkIdx].TxRateStatistics[0] =
(float)(Link[LinkIdx].TxMeasuredRate / 1024);
// compute average reported rate
AverageOver4Last = 0;
for (i = 0; i < 4; i++)
AverageOver4Last += Link[LinkIdx].RxRateStatistics[i];
AverageOver4Last *= 0.25;
if (AverageOver4Last > MaxAverageOver4Last)
MaxAverageOver4Last = AverageOver4Last;
#ifdef DEBUG_PRINT
// print measured stats
printf("Link %2u, meas_rx=%5.0fK, rep_rx=%5.0lfK, meas_tx=%5.0fK, "
"desi_tx=%5lu\n", LinkIdx, Link[LinkIdx].RxMeasuredRate / 1024.0,
Link[LinkIdx].RxRateStatistics[0],
Link[LinkIdx].TxRateStatistics[0],
Link[LinkIdx].TxDesiredRate >> 10);
#endif
// Rate Control section
if (Link[LinkIdx].ProbationModeCounter > 0) {
// In Probation mode
if (Link[LinkIdx].RxRateStatistics[0] < MinLinkTXRate / 1024) {
Link[LinkIdx].ProbationModeCounter = 0;
Link[LinkIdx].TxDesiredRate = Link[LinkIdx].TxRateBeforeProbation;
#ifdef DEBUG_PRINT
printf("Probation is skipped as statistic is small %g\n",
Link[LinkIdx].RxRateStatistics[0]);
#endif
continue;
}
// first time run only. Reset counters
if (Link[LinkIdx].ProbationModeCounter == 8) {
RateDecreaseObserved = false;
RateIncreaseObserved = false;
}
// one half of probation time reached. Change TX rate.
if (Link[LinkIdx].ProbationModeCounter == 5) {
Link[LinkIdx].TxDesiredRate -=
2 * (Link[LinkIdx].TxDesiredRate -
Link[LinkIdx].TxRateBeforeProbation);
if (Link[LinkIdx].TxDesiredRate < MinLinkTXRate) {
Link[LinkIdx].TxDesiredRate = MinLinkTXRate;
} else if (Link[LinkIdx].TxDesiredRate > MaxLinkTXRate) {
Link[LinkIdx].TxDesiredRate = MaxLinkTXRate;
}
}
// update probation flags
if ((Link[LinkIdx].RxRateStatistics[0] +
Link[LinkIdx].RxRateStatistics[1] +
Link[LinkIdx].RxRateStatistics[2] +
Link[LinkIdx].RxRateStatistics[3]) *
0.95 >
(Link[LinkIdx].RxRateStatistics[4] +
Link[LinkIdx].RxRateStatistics[5] +
Link[LinkIdx].RxRateStatistics[6] +
Link[LinkIdx].RxRateStatistics[7])) {
// 4 last numbers are REALLY greater than 4 numbers before
RateIncreaseObserved = true;
SomeRateObserved = (uint64_t)(AverageOver4Last * 1024.0);
if (SomeRateObserved < MinLinkTXRate) {
SomeRateObserved = MinLinkTXRate;
}
else if (SomeRateObserved > MaxLinkTXRate) {
SomeRateObserved = MaxLinkTXRate;
}
}
if ((Link[LinkIdx].RxRateStatistics[1] +
Link[LinkIdx].RxRateStatistics[2]) /
2 <
(Link[LinkIdx].RxRateStatistics[3] +
Link[LinkIdx].RxRateStatistics[4] +
Link[LinkIdx].RxRateStatistics[5]) /
3 * 0.95) {
// an average of two prevoius numbers is REALLY less than an average of
// three numbers before
RateDecreaseObserved = true;
}
if (Link[LinkIdx].ProbationModeCounter == 1) {
// this is the last time. Need to decide
#ifdef DEBUG_PRINT
printf("inc=%u, dec=%u ", RateIncreaseObserved, RateDecreaseObserved);
#endif
if (RateIncreaseObserved && RateDecreaseObserved) {
// probation successful
Link[LinkIdx].TxDesiredRate = SomeRateObserved;
#ifdef DEBUG_PRINT
printf("link %u: probation successful. Chahge to %lu\n", LinkIdx,
Link[LinkIdx].TxDesiredRate);
#endif
} else {
// probation failed. Return original rate
Link[LinkIdx].TxDesiredRate = Link[LinkIdx].TxRateBeforeProbation;
#ifdef DEBUG_PRINT
printf("link %u: probation failed. Back to %lu \n", LinkIdx,
Link[LinkIdx].TxDesiredRate);
#endif
}
Link[LinkIdx].LastRateControlActionTime = CurrentTime;
}
Link[LinkIdx].ProbationModeCounter--;
} else {
// Not in Probation mode
// we sent nothing
if ((Link[LinkIdx].TxRateStatistics[0] < (MinLinkTXRate / 1024)) ||
(Link[LinkIdx].TxRateStatistics[1] < (MinLinkTXRate / 1024)) ||
(Link[LinkIdx].TxRateStatistics[2] < (MinLinkTXRate / 1024)))
continue;
// data is sending, but no replies from the rx in 3 intervals
if (Link[LinkIdx].RxRateStatistics[0] +
Link[LinkIdx].RxRateStatistics[1] +
Link[LinkIdx].RxRateStatistics[2] == 0) {
// set to 100 KBps;
Link[LinkIdx].TxDesiredRate = MinLinkTXRate;
Link[LinkIdx].LastRateControlActionTime = CurrentTime;
#ifdef DEBUG_PRINT
printf("link %u, rate decrease to 100 as zero feedback %lu\n",
LinkIdx, Link[LinkIdx].TxDesiredRate);
#endif
continue;
}
// not enough time since last action
if ((Link[LinkIdx].LastRateControlActionTime + MeasureInterval * 5) >
CurrentTime)
continue;
// rate is lower than expected, need to drop the rate
if (Link[LinkIdx].RxRateStatistics[0] <
0.95 * Link[LinkIdx].TxRateStatistics[0]) {
// rate is just lower for a long time
if (1.05 * AverageOver4Last <
0.25 * (Link[LinkIdx].TxRateStatistics[1] +
Link[LinkIdx].TxRateStatistics[2] +
Link[LinkIdx].TxRateStatistics[3] +
Link[LinkIdx].TxRateStatistics[4])) {
// 0.9 is to flush possible packets that are in the link
Link[LinkIdx].TxDesiredRate =
(uint64_t)(0.9 * 1024 * AverageOver4Last);
if (Link[LinkIdx].TxDesiredRate < MinLinkTXRate)
// min threshold
Link[LinkIdx].TxDesiredRate = MinLinkTXRate;
Link[LinkIdx].LastRateControlActionTime = CurrentTime;
#ifdef DEBUG_PRINT
printf("Link %u, rate decrease to %lu\n", LinkIdx,
Link[LinkIdx].TxDesiredRate);
#endif
}
continue;
}
// no changes during last 15 measurements
if ((Link[LinkIdx].LastRateControlActionTime + MeasureInterval * 15) <
CurrentTime) {
// check if other links are in probation
for (i = 0; i < TotalLinkNumber; i++)
if (Link[i].ProbationModeCounter > 0)
break;
if (i == TotalLinkNumber) {
// probe a higher rate
Link[LinkIdx].ProbationModeCounter = 8;
Link[LinkIdx].TxRateBeforeProbation =
Link[LinkIdx].TxDesiredRate;
Link[LinkIdx].TxDesiredRate =
(uint64_t)(1.2 * Link[LinkIdx].TxDesiredRate);
if (Link[LinkIdx].TxDesiredRate < MinLinkTXRate) {
Link[LinkIdx].TxDesiredRate = MinLinkTXRate;
} else if (Link[LinkIdx].TxDesiredRate > MaxLinkTXRate) {
Link[LinkIdx].TxDesiredRate = MaxLinkTXRate;
}
#ifdef DEBUG_PRINT
printf("link %u, probation starts to %lu\n", LinkIdx,
Link[LinkIdx].TxDesiredRate);
#endif
}
}
}
}
}
void MultiLink::sendRate(uint16_t LinkIdx, uint16_t Rate) {
char Buffer4Char[4];
*((uint16_t *)&Buffer4Char[0]) = LinkIdx;
*((uint16_t *)&Buffer4Char[2]) = Rate;
for (int32_t i = 0; i < TotalLinkNumber; i++) {