This repository has been archived by the owner on Sep 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
systolicArraySim.cpp
1600 lines (1364 loc) · 38 KB
/
systolicArraySim.cpp
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) 2022 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License, as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
#include <stdio.h>
#include <float.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <climits>
#include <memory>
#include <cmath>
#include "verilated.h"
#ifdef NETLIST
#include "netlistFaultInjector.hpp"
#endif // NETLIST
#ifdef NETLIST
#include "VSystolicArray_netlist.h"
#else // !NETLIST
#include "VSystolicArray.h"
#endif // !NETLIST
#include "helpers.h"
#include "systolicArraySim.h"
#ifdef VERILATED_VSYSTOLICARRAY_NETLIST_H_
#define testBench_t VSystolicArray_netlist
#else // !VERILATED_VSYSTOLICARRAY_NETLIST_H_
#define testBench_t VSystolicArray
#endif // !VERILATED_VSYSTOLICARRAY_NETLIST_H_
static const double unitTestRelTolerance = 0.0000000003;
static int unitTestExponentRange = INT_MAX; // TODO: Having this global is ugly
template <typename Enumeration>
auto to_integer(Enumeration const value)
-> typename std::underlying_type<Enumeration>::type
{
return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}
SystolicArraySim::SystolicArraySim()
{
// Call commandArgs first!
#if 0
const char appName[][20] = {"SystolicArraySim"};
Verilated::commandArgs(1, (const char **) &appName); // TODO: Find out what the args look like
#endif
// Instantiate our design
TbVoid_ = (void *) new testBench_t;
#ifdef NETLIST
// Initialize NetlistFaultInjector
auto netlistFaultInjector = new NetlistFaultInjector;
if(netlistFaultInjector->Init()) // TODO: Would be nicer if it used the struct required as input
{
sasError("NetlistFaultInjector Init failed\n");
}
NetlistFaultInjectorVoid_ = (void*) netlistFaultInjector;
#endif // NETLIST
}
SystolicArraySim::~SystolicArraySim() {
delete (testBench_t*) TbVoid_;
#ifdef NETLIST
delete (NetlistFaultInjector *) NetlistFaultInjectorVoid_;
#endif // NETLIST
}
int SystolicArraySim::DispatchMma(const job_t &job)
{
#if DEBUG_VERBOSE
sasDebug("Dispatched Job:\n");
sasDebug("A =\n");
matrixPrint(job.MatA, Config_.Mmma, Config_.Kmma, job.StrideA);
sasDebug("B =\n");
matrixPrint(job.MatB, Config_.Kmma, Config_.Nmma, job.StrideB);
sasDebug("C =\n");
matrixPrint(job.MatC, Config_.Mmma, Config_.Nmma, job.StrideC);
#endif // DEBUG_VERBOSE
JobQueue_.push_back({0, job});
return 0;
}
int SystolicArraySim::DispatchMma(const job_t &job, size_t mCnt, size_t nCnt)
{
#if DEBUG_VERBOSE
sasDebug("Dispatched %lu x %lu MMAs:\n", mCnt, nCnt);
sasDebug("A =\n");
matrixPrint(job.MatA, mCnt * Mmma(), Ktile(), job.StrideA);
sasDebug("B =\n");
matrixPrint(job.MatB, Ktile(), nCnt * Nmma(), job.StrideB);
sasDebug("C =\n");
matrixPrint(job.MatC, mCnt * Mmma(), nCnt * Nmma(), job.StrideC);
#endif // DEBUG_VERBOSE
// Left buffer larger than right buffer: Walk through rows first
for(size_t row = 0; row < mCnt * Mmma(); row += Mmma())
{
const double * Ap = job.MatA + row * job.StrideA;
for(size_t col = 0; col < nCnt * Nmma(); col += Nmma())
{
const double * Bp = job.MatB + col;
double * Cp = job.MatC + row * job.StrideC + col;
const job_t jobMma = {
Ap, job.StrideA,
Bp, job.StrideB,
Cp, job.StrideC};
if(DispatchMma(jobMma))
{
sasError("DispatchMma failed\n");
return -1;
}
}
}
return 0;
}
int SystolicArraySim::DispatchTile(const job_t &job)
{
#if DEBUG_VERBOSE
sasDebug("Dispatched Tile:\n");
sasDebug("A =\n");
matrixPrint(job.MatA, Mtile(), Ktile(), job.StrideA);
sasDebug("B =\n");
matrixPrint(job.MatB, Ktile(), Ntile(), job.StrideB);
sasDebug("C =\n");
matrixPrint(job.MatC, Mtile(), Ntile(), job.StrideC);
#endif // DEBUG_VERBOSE
// Left buffer larger than right buffer: Walk through rows first
for(size_t row = 0; row < Mtile(); row += Mmma())
{
const double * Ap = job.MatA + row * job.StrideA;
for(size_t col = 0; col < Ntile(); col += Nmma())
{
const double * Bp = job.MatB + col;
double * Cp = job.MatC + row * job.StrideC + col;
const job_t jobMma = {
Ap, job.StrideA,
Bp, job.StrideB,
Cp, job.StrideC};
if(DispatchMma(jobMma))
{
sasError("DispatchMma failed\n");
return -1;
}
}
}
return 0;
}
// Non-netlist simulation
[[maybe_unused]] static int setValue(VlWide<3> * out, size_t outIndex, double in)
{
// TODO: Handle nan
// 65'b{11'b: -1023 biased exp, 54'sb: signed mantissa with leading 1}
const doubleUnion uval = {in};
const uint16_t tmpExp = (uval.u64 >> 52) & BIT_MASK(11);
int64_t signedMantissa = uval.u64 & BIT_MASK(52);
if(std::isnormal(in))
{
signedMantissa |= 1ULL << 52;
}
if(uval.u64 & (1ULL << 63))
{
signedMantissa = -signedMantissa;
}
signedMantissa &= BIT_MASK(54);
if(bitsCopy((uint8_t*) out[outIndex].data(), sizeof(out[0]), 0, (uint8_t*) &signedMantissa, 54))
{
sasError("bitsCopy failed\n");
return -1;
}
if(bitsCopy((uint8_t*) out[outIndex].data(), sizeof(out[0]), 54, (uint8_t*) &tmpExp, 11))
{
sasError("bitsCopy failed\n");
return -1;
}
return 0;
}
// Netlist simulation
[[maybe_unused]] static int setValue(WData* pData, size_t nData, size_t nBitsElem, size_t pos, double value)
{
if(65 != nBitsElem)
{
sasError("nBitsData = %lu not implemented (only implemented for 65'b double so far)\n", nBitsElem);
return -1;
}
if(nBitsElem * pos >= 8 * nData)
{
sasError("Pos doesn't fit into destination\n");
return -1;
}
// TODO: Write function to create this 65-bit double representation. Code is replicated.
// TODO: Handle nan
// 65'b{11'b: -1023 biased exp, 54'sb: signed mantissa with leading 1}
const doubleUnion uval = {value};
const uint16_t tmpExp = (uval.u64 >> 52) & BIT_MASK(11);
int64_t signedMantissa = uval.u64 & BIT_MASK(52);
if(std::isnormal(value))
{
signedMantissa |= 1ULL << 52;
}
if(uval.u64 & (1ULL << 63))
{
signedMantissa = -signedMantissa;
}
signedMantissa &= BIT_MASK(54);
if(bitsCopy((uint8_t*) pData, nData, pos * nBitsElem, (uint8_t*) &signedMantissa, 54))
{
sasError("bitsCopy failed\n");
return -1;
}
if(bitsCopy((uint8_t*) pData, nData, pos * nBitsElem + 54, (uint8_t*) &tmpExp, 11))
{
sasError("bitsCopy failed\n");
return -1;
}
return 0;
}
// Non-netlist simulation
[[maybe_unused]] static double getValue(VlWide<3> * in, size_t index)
{
return toDouble(in[index]);
}
// Netlist simulation
[[maybe_unused]] static double getValue(const WData * pData, size_t nData, size_t nBitsElem, size_t pos)
{
if(65 != nBitsElem)
{
sasError("nBitsData = %lu not implemented (only implemented for 65'b double so far)\n", nBitsElem);
return -1;
}
if(nBitsElem * (pos + 1) >= 8 * nData)
{
sasError("Pos doesn't fit into destination\n");
return -1;
}
VlWide<3> tmp;
for(size_t index = 0; index < sizeof(tmp.m_storage) / sizeof(tmp.m_storage[0]); index++)
{
tmp[index] = 0;
}
const size_t bitStart = pos * nBitsElem;
uint8_t* tmpU8 = (uint8_t*) tmp.data();
for(size_t bit = 0; bit < 65; bit++)
{
size_t tmpByte = bit / 8;
uint8_t tmpBit = bit % 8;
size_t dataByte = (bitStart + bit) / 8;
uint8_t dataBit = (bitStart + bit) % 8;
if(((const uint8_t*)pData)[dataByte] & (1 << dataBit))
{
tmpU8[tmpByte] |= 1 << tmpBit;
}
}
return toDouble(tmp);
}
size_t SystolicArraySim::CyclesRequired(size_t jobCnt) const
{
if(0 == jobCnt)
{
return 0;
}
return JobCycleDone_ + (jobCnt - 1) *(JobCyclePassedFirstStage_ + 1) + 1;
}
size_t SystolicArraySim::JobsDoneInCycles(size_t cycleCnt) const
{
if(JobCycleDone_ > cycleCnt)
{
return 0;
}
return (cycleCnt - JobCycleDone_ - 1) / (JobCyclePassedFirstStage_ + 1) + 1;
}
int SystolicArraySim::IoSet(void * TbVoid, std::deque<queueEntry_t> * jobs, bool clkHigh)
{
if(jobs->empty())
{
sasError("deque is empty\n");
return -1;
}
std::vector<queueEntry_t *> concurrentJobs = {&jobs->front()};
for(size_t job = 1; job < jobs->size(); job++)
{
if(jobs->at(job - 1).JobCycle > JobCyclePassedFirstStage_) // check that previous job has freed first stage
{
concurrentJobs.push_back(&jobs->at(job));
}
else
{
break;
}
}
testBench_t * Tb = (testBench_t*) TbVoid;
#ifdef NETLIST
const size_t MmmaRTL = (sizeof(Tb->out.m_storage) * 8) / 65;
#else // !NETLIST
const size_t MmmaRTL = (sizeof(Tb->out->m_storage) * 8) / 65;
#endif // !NETLIST
for(size_t job = 0; job < concurrentJobs.size(); job++)
{
job_t * jobp = &concurrentJobs[job]->Job;
for(size_t m = 0; m < MmmaRTL; m++)
{
// Dispatch Order
// Cycle 0 : k = 0, n = 0
// Cycle 1 : k = 1, n = 0
// Cycle 2 : k = 0, n = 1
// Cycle 3 : k = 1, n = 1
// Cycle 4 : k = 0, n = 2
// ...
// Cycle FmaCycles : k = 2, n = 0
// Cycle FmaCycles+1: k = 3, n = 0
// Cycle FmaCycles+2: k = 2, n = 1
// ...
// Left matrix input
// The left matrix does not change with n so needs only to be set for n = 0
// Note that the next k-value (= next FMA input) need only be set once
// the previous k output (= previous FMA Output) has been produced.
// To add some complications, each SA row is separated into two independent phase-shifted FMAs
const bool lInEvenK = (0 == concurrentJobs[job]->JobCycle % FmaCycles_);
const bool lInOddK = (0 == (concurrentJobs[job]->JobCycle - 1) % FmaCycles_) && concurrentJobs[job]->JobCycle;
if(lInEvenK || lInOddK)
{
const size_t k = 2 * (concurrentJobs[job]->JobCycle / FmaCycles_) + (lInEvenK ? 0 : 1);
if(k < Kmma())
{
#ifdef NETLIST
if(setValue(Tb->multLeft.data(), sizeof(Tb->multLeft.m_storage), 65, m * Kmma() + k, jobp->MatA[m * jobp->StrideA + k]))
#else // !NETLIST
if(setValue(Tb->multLeft[0], m * Kmma() + k, jobp->MatA[m * jobp->StrideA + k]))
#endif // !NETLIST
{
sasError("setValue failed\n");
return -1;
};
}
}
// Right matrix input
const size_t nCnt = std::min(concurrentJobs[job]->JobCycle / 2 + 1, Nmma());
for(size_t n = 0; n < nCnt; n++)
{
const size_t nJobCycle = concurrentJobs[job]->JobCycle - 2 * n;
const bool rInEvenK = (0 == nJobCycle % FmaCycles_);
const bool rInOddK = (0 == (nJobCycle - 1) % FmaCycles_) && nJobCycle;
if(rInEvenK || rInOddK)
{
const size_t k = 2 * (nJobCycle / FmaCycles_) + (rInEvenK ? 0: 1);
if(k < Kmma())
{
#ifdef NETLIST
if(setValue(Tb->multRight.data(), sizeof(Tb->multRight.m_storage), 65, k, jobp->MatB[k * jobp->StrideB + n]))
#else // !NETLIST
if(setValue(Tb->multRight, k, jobp->MatB[k * jobp->StrideB + n]))
#endif // !NETLIST
{
sasError("setValue failed\n");
return -1;
}
}
}
}
// Acc: Each time a new "n" is added
if(0 == (concurrentJobs[job]->JobCycle % 2))
{
const size_t n = concurrentJobs[job]->JobCycle / 2;
if(n < Nmma())
{
#ifdef NETLIST
if(setValue(Tb->acc.data(), sizeof(Tb->acc.m_storage), 65, m, jobp->MatC[m * jobp->StrideC + n]))
#else // !NETLIST
if(setValue(Tb->acc, m, jobp->MatC[m * jobp->StrideC + n]))
#endif // !NETLIST
{
sasError("setValue failed\n");
return -1;
}
}
}
// Gather output
if(JobCycleOutputStart_ <= concurrentJobs[job]->JobCycle)
{
const size_t cycleOffset = concurrentJobs[job]->JobCycle - JobCycleOutputStart_;
if(0 == (cycleOffset % 2))
{
const size_t n = cycleOffset / 2;
if(n > Nmma())
{
sasError("Unexpected n: Job should have been removed already\n");
return -1;
}
#ifdef NETLIST
jobp->MatC[m * jobp->StrideC + n] = getValue(Tb->out.data(), sizeof(Tb->out.m_storage), 65, m);
#else // !NETLIST
jobp->MatC[m * jobp->StrideC + n] = getValue(Tb->out, m);
#endif // !NETLIST
}
}
}
}
if(JobCycleDone_ == jobs->front().JobCycle)
{
// Are we only simulating a single column of the SA?
// Then calculate the other entries directly
if(MmmaRTL != Mmma()) // TODO: This also means fault is always injected into the first SA column!
{
job_t * jobp = &jobs->front().Job;
for(size_t row = MmmaRTL; row < Mmma(); row++)
{
for(size_t col = 0; col < Nmma(); col++)
{
for(size_t k = 0; k < Kmma(); k++)
{
jobp->MatC[row * jobp->StrideC + col] += jobp->MatA[row * jobp->StrideA + k] * jobp->MatB[k * jobp->StrideB + col];
}
}
}
}
jobs->pop_front();
}
else if(JobCycleDone_ < jobs->front().JobCycle)
{
sasError("Jobcycle threshold breached (have %lu)!\n", jobs->front().JobCycle);
return -4;
}
for(size_t job = 0; job < concurrentJobs.size(); job++)
{
concurrentJobs[job]->JobCycle++;
}
return 0;
}
SystolicArraySim::faultRTL_t SystolicArraySim::FiSetRTL(fiMode mode)
{
#ifdef NETLIST
if(fiMode::None == mode)
{
sasError("Setting None-fault\n");
return faultRTL_t();
}
NetlistFaultInjector * netlistFaultInjector = (NetlistFaultInjector*) NetlistFaultInjectorVoid_;
size_t fiSignalWidth = 0;
if(netlistFaultInjector->RandomFiGet(
&FaultRTL_.ModuleInstanceChain,
&FaultRTL_.AssignUUID,
&fiSignalWidth))
{
sasError("RandomFiGet failed\n");
return faultRTL_t();
}
FaultRTL_.BitPos = randomBits() % fiSignalWidth;
if(fiMode::Transient == mode)
{
CycleCnt_ = 0;
const size_t cyclesRequired = CyclesRequired(JobQueue_.size());
if(0 == cyclesRequired)
{
sasError("Trying to set transient fault with empty JobQueue\n");
return faultRTL_t();
}
FaultRTLTransCycle_ = randomBits() % cyclesRequired;
}
FaultRTL_.Mode = mode;
sasFaultPrint("Set FaultRTL_:\n\tModule Instance Chain: ");
for(const auto &inst: FaultRTL_.ModuleInstanceChain)
{
sasFaultPrint("%u, ", inst);
}
sasFaultPrint("\n\tAssignUUID = %u\n\tBitPos = %u\n\tMode = %i\n",
FaultRTL_.AssignUUID, FaultRTL_.BitPos, (int) FaultRTL_.Mode);
return FaultRTL_;
#else // !NETLIST
sasError("Only available with NETLIST\n");
return faultRTL_t();
#endif // !NETLIST
}
SystolicArraySim::faultCsim_t SystolicArraySim::FiSetCsim(
fiCsimPlace place,
fiBits bits,
fiCorruption corruption,
fiMode mode)
{
if((fiCsimPlace::None == place) || (fiBits::None == bits) ||
(fiCorruption::None == corruption) || (fiMode::None == mode))
{
sasError("Setting None-fault\n");
return faultCsim_t();
}
if(fiCsimPlace::Everywhere == place)
{
// Assuming equal distribution across
// inputs, Kmma multipliers, Kmma acc adders, 1 final column adder)
// I.e. 2 * Kmma + 1 components (inputs have significant derating)
// TODO: Multiplier much larger than adder
// coverity[DC.WEAK_CRYPTO]
const int randNr = rand();
const int FractionRandMax = RAND_MAX / (2 * Kmma() + 1);
if(randNr < Kmma() * FractionRandMax)
{
FaultCsim_.Place = fiCsimPlace::Multipliers;
}
else if(randNr < 2 * Kmma() * FractionRandMax)
{
FaultCsim_.Place = fiCsimPlace::AccAdders;
}
else if(randNr < (2 * Kmma() + 1) * FractionRandMax)
{
FaultCsim_.Place = fiCsimPlace::ColumnAdders;
}
else
{
FaultCsim_.Place = fiCsimPlace::Inputs;
}
}
else
{
FaultCsim_.Place = place;
}
FaultCsim_.Corruption = corruption;
if(fiMode::Transient == mode)
{
CycleCnt_ = 0;
const size_t totalJobQueueCycles = JobQueue_.size() * Nmma();
// coverity[DC.WEAK_CRYPTO]
FaultCsimTransCycle_ = rand() % totalJobQueueCycles;
}
FaultCsim_.Mode = mode;
switch(bits)
{
default: // no break intended
case fiBits::None:
sasError("Setting None fiBits\n");
return faultCsim_t();
case fiBits::Everywhere:
// coverity[DC.WEAK_CRYPTO]
FaultCsim_.BitPos = rand() % (sizeof(double) * 8);
break;
case fiBits::Mantissa:
// coverity[DC.WEAK_CRYPTO]
FaultCsim_.BitPos = rand() % 52;
break;
}
// coverity[DC.WEAK_CRYPTO]
FaultCsim_.Row = rand() % Mmma();
sasFaultPrint("Set FaultCsim_: Place %i, Corruption %i, fiMode %i, Column %u, BitPos %u\n",
to_integer(FaultCsim_.Place), to_integer(FaultCsim_.Corruption),
to_integer(FaultCsim_.Mode), FaultCsim_.Row, FaultCsim_.BitPos);
return FaultCsim_;
}
int SystolicArraySim::FiResetRTL()
{
if(fiMode::None == FaultRTL_.Mode)
{
sasError("No fault was set!\n");
return -1;
}
FaultRTL_ = faultRTL_t();
FaultRTLTransCycle_ = SIZE_MAX;
return 0;
}
int SystolicArraySim::FiResetCsim()
{
if(fiCsimPlace::None == FaultCsim_.Place)
{
sasError("No fault was set!\n");
return -1;
}
FaultCsim_ = faultCsim_t();
FaultCsimTransCycle_ = SIZE_MAX;
return 0;
}
static double corrupt(double in, SystolicArraySim::fiCorruption corruption, uint8_t bitPos)
{
if(63 < bitPos)
{
sasError("bitPos > 64\n");
return NAN;
}
doubleUnion inU64 = {in};
switch(corruption)
{
default: // no break intended
case SystolicArraySim::fiCorruption::None:
return in;
case SystolicArraySim::fiCorruption::Flip:
inU64.u64 ^= 1UL << bitPos;
break;
case SystolicArraySim::fiCorruption::StuckHigh:
inU64.u64 |= 1UL << bitPos;
break;
case SystolicArraySim::fiCorruption::StuckLow:
inU64.u64 &= ~(1UL << bitPos);
break;
}
sasFaultPrint("Corrupting %f -> %f\n", in, inU64.flt);
return inU64.flt;
}
// out = out + A_1 * B_1 + ... + A_8 * B_8
// fi = nullptr if no fault injection intended
int SystolicArraySim::RowCsim(double * out, double * a, double * b, const faultCsim_t * fi) const
{
// coverity[DC.WEAK_CRYPTO]
int kFi = rand() % Kmma();
for(size_t k = 0; k < Kmma(); k++)
{
if((k == kFi) && (nullptr != fi))
{
// Inputs
double accIn = *out;
double aIn = a[k];
double bIn = b[k];
if(fiCsimPlace::Multipliers == fi->Place)
{
// coverity[DC.WEAK_CRYPTO]
size_t inRand = rand() % 3;
if(0 == inRand) accIn = corrupt(*out, fi->Corruption, fi->BitPos);
else if(1 == inRand) aIn = corrupt(aIn, fi->Corruption, fi->BitPos);
else bIn = corrupt(bIn, fi->Corruption, fi->BitPos);
}
// Mul
double mul = aIn * bIn;
if(fiCsimPlace::Multipliers == fi->Place)
{
mul = corrupt(mul, fi->Corruption, fi->BitPos);
}
// Acc Add
double acc = mul + accIn;
if(fiCsimPlace::AccAdders == fi->Place)
{
acc = corrupt(acc, fi->Corruption, fi->BitPos);
}
}
else
{
*out += a[k] * b[k];
}
}
if((nullptr != fi) && (fiCsimPlace::ColumnAdders == fi->Place))
{
*out = corrupt(*out, fi->Corruption, fi->BitPos);
}
return 0;
}
int SystolicArraySim::ExecCsim(size_t maxJobs)
{
const size_t origJobs = JobQueue_.size();
while(!JobQueue_.empty() && (origJobs - JobQueue_.size() < maxJobs))
{
// JobCycle = col for c sim
job_t * job = &JobQueue_.front().Job;
const size_t col = JobQueue_.front().JobCycle;
// Calculate non-simulated cols
for(size_t row = 0; row < Mmma(); row++)
{
if(FaultCsim_.Row == row)
{
continue;
}
for(size_t sum = 0; sum < Kmma(); sum++)
{
job->MatC[row * job->StrideC + col] += job->MatA[row * job->StrideA + sum] * job->MatB[sum * job->StrideB + col];
}
}
// Calculate simulated row
std::vector<double> leftIn(Kmma());
std::vector<double> rightIn(Kmma());
for(size_t sum = 0; sum < Kmma(); sum++)
{
leftIn[sum] = job->MatA[FaultCsim_.Row * job->StrideA + sum];
rightIn[sum] = job->MatB[sum * job->StrideB + col];
}
const faultCsim_t * colCsimFi = ((CycleCnt_ == FaultCsimTransCycle_) || (fiMode::Permanent == FaultCsim_.Mode)) ? &FaultCsim_ : nullptr;
if(RowCsim(&job->MatC[FaultCsim_.Row * job->StrideC + col], leftIn.data(), rightIn.data(), colCsimFi))
{
sasError("ColCsim failed\n");
return -1;
}
CycleCnt_++;
JobQueue_.front().JobCycle++;
if(JobQueue_.front().JobCycle >= Nmma())
{
JobQueue_.pop_front();
}
}
return 0;
}
int SystolicArraySim::FiRtlApply(void * TbVoid, const std::vector<uint16_t> &modInst, uint32_t assignNr, size_t fiBit)
{
#ifdef NETLIST
testBench_t * Tb = (testBench_t*) TbVoid;
// Set instance chain
for(size_t inst = 0; inst < sizeof(Tb->GlobalFiModInstNr) / sizeof(Tb->GlobalFiModInstNr[0]); inst++)
{
if(modInst.size() > inst)
{
Tb->GlobalFiModInstNr[inst] = modInst[inst];
}
else
{
Tb->GlobalFiModInstNr[inst] = 0;
}
}
Tb->GlobalFiNumber = assignNr;
// Reset whatever was set before in fi signal
memset(Tb->GlobalFiSignal.m_storage, 0, sizeof(Tb->GlobalFiSignal.m_storage));
// Set specific bit
const size_t bitsInArrayElem = sizeof(Tb->GlobalFiSignal.m_storage[0]) * 8;
const size_t arrayIndex = fiBit / bitsInArrayElem;
const size_t arrayBit = fiBit % bitsInArrayElem;
Tb->GlobalFiSignal.m_storage[arrayIndex] = 1UL << arrayBit;
#else // !NETLIST
sasError("Only available with NETLIST\n");
return -1;
#endif // !NETLIST
return 0;
}
int SystolicArraySim::FiRtlReset(void * TbVoid)
{
#ifdef NETLIST
testBench_t * Tb = (testBench_t*) TbVoid;
for(size_t inst = 0; inst < sizeof(Tb->GlobalFiModInstNr) / sizeof(Tb->GlobalFiModInstNr[0]); inst++)
{
Tb->GlobalFiModInstNr[inst] = 0;
}
return 0;
#else // !NETLIST
return 0;
#endif // !NETLIST
}
bool SystolicArraySim::JobQueueReadBeforeWrite(const std::deque<queueEntry_t> &jobQueue) const
{
const size_t jobsInPipe = JobCycleDone_ / JobCyclePassedFirstStage_;
for(size_t job = 0; job < jobQueue.size(); job++)
{
for(size_t nextJob = job + 1; nextJob < std::min(job + jobsInPipe, jobQueue.size()); nextJob++)
{
if((jobQueue[job].Job.MatC == jobQueue[nextJob].Job.MatA) ||
(jobQueue[job].Job.MatC == jobQueue[nextJob].Job.MatB) ||
jobQueue[job].Job.MatC == jobQueue[nextJob].Job.MatC)
{
return true;
}
}
}
return false;
}
int SystolicArraySim::ExecRtl(bool fastTransient, bool fastTransientTest)
{
// Run sanity check on jobqueue
if(JobQueueReadBeforeWrite(JobQueue_))
{
sasError("Read before write in jobqueue\n");
return -1;
}
// Set permanent fault if enabled
if(fiMode::Permanent == FaultRTL_.Mode)
{
if(FiRtlApply(TbVoid_, FaultRTL_.ModuleInstanceChain, FaultRTL_.AssignUUID, FaultRTL_.BitPos))
{
sasError("FiRtlApply failed\n");
return -1;
}
}
else if(FiRtlReset(TbVoid_))
{
sasError("FiRtlReset failed\n");
return -1;
}
// Skip jobs before transient fault happens
if((fiMode::Transient == FaultRTL_.Mode) && fastTransient)
{
const size_t jobsBefore = FaultRTLTransCycle_ > JobCycleDone_ ? JobsDoneInCycles(FaultRTLTransCycle_ - JobCycleDone_) : 0;
if(jobsBefore)
{
if(ExecCsim(jobsBefore))
{
sasError("ExecCsim failed\n");
return -1;
}
// reset cycle cnt
for(auto &job: JobQueue_)
{
job.JobCycle = 0;
}
// Set cycles
CycleCnt_ = CyclesRequired(jobsBefore);
sasDebug("Cycle %lu: fastTransient: Skip first jobs\n", CycleCnt_);
}
}
// Start the actual simulation
testBench_t * Tb = (testBench_t*) TbVoid_;
#ifdef NETLIST
const size_t MmmaRTL = (sizeof(Tb->out.m_storage) * 8) / 65;
#else // !NETLIST
const size_t MmmaRTL = (sizeof(Tb->out->m_storage) * 8) / 65;
#endif // !NETLIST
if(MmmaRTL != Mmma())
{
sasDebug("RTL simulation running for %lu SA-columns out of %lu\n", MmmaRTL, Mmma());
}
// Perform simulation for chosen channel
Tb->clk = 1;
while(!JobQueue_.empty())
{
Tb->clk = Tb->clk ? 0 : 1;
if(IoSet(Tb, &JobQueue_, Tb->clk))
{
sasError("inputSet failed\n");
return -1;
}
// Fault injection
if(fiMode::Transient == FaultRTL_.Mode)
{
if(CycleCnt_ == FaultRTLTransCycle_)
{
sasDebug("Cycle %lu: Setting transient fault\n", CycleCnt_);
if(!fastTransientTest && FiRtlApply(TbVoid_, FaultRTL_.ModuleInstanceChain, FaultRTL_.AssignUUID, FaultRTL_.BitPos))
{
sasError("FiRtlApply failed\n");
return -1;
}
}
else if(FiRtlReset(TbVoid_))
{
sasError("FiRtlReset failed\n");
return -1;
}
}
#if DEBUG_VERBOSE
sasDebug("cycle = %lu:%s:\n", CycleCnt_, Tb->clk ? "H" : "L");
sasDebug("\tout =");
for(size_t m = 0; m < Mmma(); m++)
{
sasDebug("%.10f, ", getValue(Tb->out.data(), sizeof(Tb->out.m_storage), 65, m));
}
sasDebug("\n");
printBinary((uint8_t*) Tb->out.data(), 130);
sasInfo("\n");
sasDebug("cycle = %lu:%s:\n", CycleCnt_, Tb->clk ? "H" : "L");
sasDebug("\tout = %.10e\n", getValue(Tb->out, 0));
sasDebug("\tmulLeft = \n");
for(size_t row = 0; row < Mmma(); row++)
{
sasDebug("\t\t");
for(size_t k = 0; k < Kmma(); k++)
{
sasDebug("%f,", getValue(Tb->multLeft[0], row * Kmma() + k));
}
sasDebug("\n");