-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPracticalSRAMSimulator.cpp
More file actions
1603 lines (1445 loc) · 64 KB
/
Copy pathPracticalSRAMSimulator.cpp
File metadata and controls
1603 lines (1445 loc) · 64 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
#include <algorithm>
#include <array>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <memory>
#include <numeric>
#include <optional>
#include <fstream>
#include <random>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <cmath>
#include <vector>
enum class DecodeStatus { Clean, Corrected, DetectedUncorrectable, UndetectedError };
struct DecodeResult {
uint64_t data = 0;
uint64_t corrected_codeword = 0;
DecodeStatus status = DecodeStatus::Clean;
int corrected_bits = 0;
int syndrome = 0;
std::string detail;
};
struct ECCMetadata {
std::string name;
int parity_bits = 0;
std::string correction_capability;
std::string detection_capability;
};
static uint64_t maskBits(int bits) {
if (bits <= 0) {
return 0;
}
if (bits >= 64) {
return ~0ULL;
}
return (1ULL << bits) - 1ULL;
}
static bool getBit1(uint64_t v, int pos1) { return ((v >> (pos1 - 1)) & 1ULL) != 0; }
static void setBit1(uint64_t& v, int pos1, bool b) {
if (b) {
v |= (1ULL << (pos1 - 1));
} else {
v &= ~(1ULL << (pos1 - 1));
}
}
static void flipBit1(uint64_t& v, int pos1) { v ^= (1ULL << (pos1 - 1)); }
class ECCCodec {
public:
virtual ~ECCCodec() = default;
virtual std::string name() const = 0;
virtual int dataBits() const = 0;
virtual int codewordBits() const = 0;
virtual ECCMetadata metadata() const = 0;
virtual uint64_t encode(uint64_t data) const = 0;
virtual DecodeResult decode(uint64_t codeword) const = 0;
virtual uint64_t dataMask() const { return maskBits(dataBits()); }
};
class HammingSecdedCodec final : public ECCCodec {
public:
explicit HammingSecdedCodec(int data_bits)
: data_bits_(data_bits),
parity_bits_(requiredParityBits(data_bits)),
total_bits_(data_bits + parity_bits_ + 1),
parity_positions_(buildParityPositions(parity_bits_)),
data_positions_(buildDataPositions(total_bits_, parity_positions_)) {
if (data_bits_ <= 0 || data_bits_ > 57) {
throw std::invalid_argument("SEC-DED data_bits must be in [1,57]");
}
}
std::string name() const override { return "SEC-DED"; }
int dataBits() const override { return data_bits_; }
int codewordBits() const override { return total_bits_; }
ECCMetadata metadata() const override {
return ECCMetadata{"SEC-DED", parity_bits_ + 1, "Corrects 1 bit", "Detects 2-bit errors"};
}
uint64_t encode(uint64_t data) const override {
const uint64_t masked_data = data & dataMask();
uint64_t codeword = 0;
for (int i = 0; i < data_bits_; ++i) {
if ((masked_data >> i) & 1ULL) {
setBit1(codeword, data_positions_[i], true);
}
}
for (int parity_pos : parity_positions_) {
int parity = 0;
for (int pos = 1; pos <= total_bits_ - 1; ++pos) {
if ((pos & parity_pos) && getBit1(codeword, pos)) {
parity ^= 1;
}
}
setBit1(codeword, parity_pos, parity != 0);
}
int overall_parity = 0;
for (int pos = 1; pos <= total_bits_ - 1; ++pos) {
if (getBit1(codeword, pos)) {
overall_parity ^= 1;
}
}
setBit1(codeword, total_bits_, overall_parity != 0);
return codeword & maskBits(total_bits_);
}
DecodeResult decode(uint64_t received) const override {
DecodeResult result;
uint64_t working = received & maskBits(total_bits_);
for (int i = 0; i < parity_bits_; ++i) {
const int parity_pos = parity_positions_[i];
int parity = 0;
for (int pos = 1; pos <= total_bits_ - 1; ++pos) {
if ((pos & parity_pos) && getBit1(working, pos)) {
parity ^= 1;
}
}
if (parity) {
result.syndrome |= (1 << i);
}
}
int overall = 0;
for (int pos = 1; pos <= total_bits_; ++pos) {
if (getBit1(working, pos)) {
overall ^= 1;
}
}
const bool overall_parity_odd = (overall != 0);
if (result.syndrome == 0 && !overall_parity_odd) {
result.status = DecodeStatus::Clean;
result.detail = "No detected error";
} else if (result.syndrome == 0 && overall_parity_odd) {
result.status = DecodeStatus::Corrected;
flipBit1(working, total_bits_);
result.corrected_bits = 1;
result.detail = "Corrected overall parity bit";
} else if (result.syndrome != 0 && overall_parity_odd) {
if (result.syndrome < 1 || result.syndrome > total_bits_ - 1) {
result.status = DecodeStatus::DetectedUncorrectable;
result.detail = "Syndrome out of valid range — likely 3+ bit error";
} else {
result.status = DecodeStatus::Corrected;
flipBit1(working, result.syndrome);
result.corrected_bits = 1;
result.detail = "Corrected by syndrome";
}
} else {
result.status = DecodeStatus::DetectedUncorrectable;
result.detail = "Detected uncorrectable multi-bit error";
}
result.data = extractData(working);
result.corrected_codeword = working;
return result;
}
private:
int data_bits_;
int parity_bits_;
int total_bits_;
std::vector<int> parity_positions_;
std::vector<int> data_positions_;
static int requiredParityBits(int data_bits) {
int p = 0;
while ((1 << p) < (data_bits + p + 1)) {
++p;
}
return p;
}
static std::vector<int> buildParityPositions(int parity_bits) {
std::vector<int> positions;
for (int i = 0; i < parity_bits; ++i) {
positions.push_back(1 << i);
}
return positions;
}
static std::vector<int> buildDataPositions(int total_bits, const std::vector<int>& parity_positions) {
std::vector<int> data_positions;
for (int pos = 1; pos <= total_bits - 1; ++pos) {
if (std::find(parity_positions.begin(), parity_positions.end(), pos) == parity_positions.end()) {
data_positions.push_back(pos);
}
}
return data_positions;
}
uint64_t extractData(uint64_t codeword) const {
uint64_t data = 0;
for (int i = 0; i < data_bits_; ++i) {
if (getBit1(codeword, data_positions_[i])) {
data |= (1ULL << i);
}
}
return data;
}
};
// Parity is computed via a non-cryptographic XOR-fold hash.
// Minimum Hamming distance is NOT guaranteed algebraically.
// Error correction is done by exhaustive candidate search (O(n^w) per decode
// where w is the maximum correction weight). This is NOT a BCH or standard
// TAEC code. Rename prefix "Hash" reflects the actual construction.
class ChecksumSearchCodecBase : public ECCCodec {
public:
ChecksumSearchCodecBase(std::string codec_name,
int data_bits,
int parity_bits,
int max_search_weight,
int adjacent_limit,
std::string corr_cap,
std::string det_cap)
: codec_name_(std::move(codec_name)),
data_bits_(data_bits),
parity_bits_(parity_bits),
total_bits_(data_bits + parity_bits),
max_search_weight_(max_search_weight),
adjacent_limit_(adjacent_limit),
corr_capability_(std::move(corr_cap)),
det_capability_(std::move(det_cap)) {
if (data_bits_ <= 0 || data_bits_ > 32) {
throw std::invalid_argument("data_bits must be in [1,32]");
}
if (total_bits_ > 63) {
throw std::invalid_argument("codeword too large for uint64 container");
}
}
std::string name() const override { return codec_name_; }
int dataBits() const override { return data_bits_; }
int codewordBits() const override { return total_bits_; }
ECCMetadata metadata() const override {
return ECCMetadata{codec_name_, parity_bits_, corr_capability_, det_capability_};
}
uint64_t encode(uint64_t data) const override {
const uint64_t payload = data & dataMask();
const uint64_t p = computeParity(payload) & maskBits(parity_bits_);
return payload | (p << data_bits_);
}
DecodeResult decode(uint64_t codeword) const override {
const uint64_t clipped = codeword & maskBits(total_bits_);
const uint64_t raw_data = clipped & dataMask();
const uint64_t stored_p = (clipped >> data_bits_) & maskBits(parity_bits_);
DecodeResult result;
result.corrected_codeword = clipped;
result.data = raw_data;
if (stored_p == (computeParity(raw_data) & maskBits(parity_bits_))) {
result.status = DecodeStatus::Clean;
result.detail = "Checksum matched";
return result;
}
std::vector<uint64_t> candidates;
std::vector<int> weights;
searchCandidates(clipped, candidates, weights);
if (candidates.size() == 1) {
result.status = DecodeStatus::Corrected;
result.corrected_codeword = candidates.front();
result.data = candidates.front() & dataMask();
result.corrected_bits = weights.front();
result.detail = "Pattern search corrected";
return result;
}
result.status = DecodeStatus::DetectedUncorrectable;
if (candidates.empty()) {
result.detail = "No valid correction candidate";
} else {
result.detail = "Ambiguous correction candidates";
}
return result;
}
protected:
virtual uint64_t computeParity(uint64_t payload) const {
uint64_t parity = 0;
for (int i = 0; i < parity_bits_; ++i) {
uint64_t x = payload ^ (payload >> ((i % 7) + 1));
x ^= (x >> 13);
x ^= (x >> 7);
x ^= (x >> 3);
const int bit = static_cast<int>(x & 1ULL);
parity |= (static_cast<uint64_t>(bit) << i);
}
return parity;
}
private:
std::string codec_name_;
int data_bits_;
int parity_bits_;
int total_bits_;
int max_search_weight_;
int adjacent_limit_;
std::string corr_capability_;
std::string det_capability_;
bool passesAdjacencyConstraint(const std::vector<int>& positions) const {
if (adjacent_limit_ <= 0 || positions.empty()) {
return true;
}
const int minp = *std::min_element(positions.begin(), positions.end());
const int maxp = *std::max_element(positions.begin(), positions.end());
return (maxp - minp + 1) <= adjacent_limit_;
}
bool isCodewordValid(uint64_t cw) const {
const uint64_t payload = cw & dataMask();
const uint64_t p = (cw >> dataBits()) & maskBits(codewordBits() - dataBits());
return p == (computeParity(payload) & maskBits(codewordBits() - dataBits()));
}
void searchCandidates(uint64_t clipped, std::vector<uint64_t>& candidates, std::vector<int>& weights) const {
const int n = codewordBits();
for (int i = 1; i <= n; ++i) {
uint64_t c1 = clipped;
flipBit1(c1, i);
if (isCodewordValid(c1)) {
candidates.push_back(c1);
weights.push_back(1);
}
}
if (max_search_weight_ < 2) {
return;
}
for (int i = 1; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
std::vector<int> p{i, j};
if (!passesAdjacencyConstraint(p)) {
continue;
}
uint64_t c2 = clipped;
flipBit1(c2, i);
flipBit1(c2, j);
if (isCodewordValid(c2)) {
candidates.push_back(c2);
weights.push_back(2);
}
}
}
if (max_search_weight_ < 3) {
return;
}
for (int i = 1; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
for (int k = j + 1; k <= n; ++k) {
std::vector<int> p{i, j, k};
if (!passesAdjacencyConstraint(p)) {
continue;
}
uint64_t c3 = clipped;
flipBit1(c3, i);
flipBit1(c3, j);
flipBit1(c3, k);
if (isCodewordValid(c3)) {
candidates.push_back(c3);
weights.push_back(3);
}
}
}
}
}
};
class HashAEC3Codec final : public ChecksumSearchCodecBase {
public:
explicit HashAEC3Codec(int data_bits)
: ChecksumSearchCodecBase("HashAEC3", data_bits, 12, 3, 3,
"Probabilistic correction up to 3 adjacent flips (search-based)",
"Probabilistic detection via 12-bit checksum") {}
};
class HashEC2Codec final : public ChecksumSearchCodecBase {
public:
explicit HashEC2Codec(int data_bits)
: ChecksumSearchCodecBase("HashEC2", data_bits, 16, 2, 0,
"Probabilistic correction up to 2 bit flips (search-based)",
"Probabilistic detection via 16-bit checksum") {}
};
// This is a CRC-8-aided Reed-Muller code, NOT a standard polar code.
// Frozen positions are assigned as the first (n - total_info_bits) indices,
// NOT by Bhattacharyya parameter or Gaussian approximation ordering.
// The decoder uses single-flip exhaustive search, not successive cancellation.
// Published polar code BER curves are not directly comparable to this codec.
class PolarCodec final : public ECCCodec {
public:
explicit PolarCodec(int data_bits)
: data_bits_(data_bits),
crc_bits_(8),
total_info_bits_(data_bits + crc_bits_),
n_(nextPow2(total_info_bits_)),
frozen_(n_, true),
info_positions_(buildInfoPositions(n_, total_info_bits_)) {
if (data_bits_ <= 0 || data_bits_ > 32) {
throw std::invalid_argument("Polar data_bits must be in [1,32]");
}
if (n_ > 64) {
throw std::invalid_argument("Polar shortened length exceeded 64 bits");
}
for (int pos : info_positions_) {
frozen_[pos] = false;
}
}
std::string name() const override { return "CRC-RM"; }
int dataBits() const override { return data_bits_; }
int codewordBits() const override { return n_; }
ECCMetadata metadata() const override {
return ECCMetadata{"CRC-RM", n_ - data_bits_,
"CRC-aided single-flip search correction (heuristic)",
"CRC8 + frozen-bit constraints detect many multi-bit errors"};
}
uint64_t encode(uint64_t data) const override {
const uint64_t payload = data & dataMask();
const uint8_t crc = crc8(payload, data_bits_);
std::vector<int> u(n_, 0);
std::vector<int> info_bits;
info_bits.reserve(total_info_bits_);
for (int i = 0; i < data_bits_; ++i) {
info_bits.push_back(static_cast<int>((payload >> i) & 1ULL));
}
for (int i = 0; i < crc_bits_; ++i) {
info_bits.push_back((crc >> i) & 1U);
}
for (std::size_t i = 0; i < info_positions_.size(); ++i) {
u[info_positions_[i]] = info_bits[i];
}
polarTransform(u);
uint64_t x = 0;
for (int i = 0; i < n_; ++i) {
if (u[i]) {
x |= (1ULL << i);
}
}
return x;
}
DecodeResult decode(uint64_t codeword) const override {
DecodeResult result;
const uint64_t clipped = codeword & maskBits(n_);
auto tryDecode = [&](uint64_t candidate) -> std::optional<uint64_t> {
std::vector<int> x(n_, 0);
for (int i = 0; i < n_; ++i) {
x[i] = static_cast<int>((candidate >> i) & 1ULL);
}
polarTransform(x); // inverse for F^n over GF(2)
for (int i = 0; i < n_; ++i) {
if (frozen_[i] && x[i] != 0) {
return std::nullopt;
}
}
uint64_t payload = 0;
uint8_t rx_crc = 0;
for (int i = 0; i < data_bits_; ++i) {
const int b = x[info_positions_[i]];
payload |= (static_cast<uint64_t>(b) << i);
}
for (int i = 0; i < crc_bits_; ++i) {
const int b = x[info_positions_[data_bits_ + i]];
rx_crc |= static_cast<uint8_t>(b << i);
}
if (rx_crc != crc8(payload, data_bits_)) {
return std::nullopt;
}
return payload & dataMask();
};
if (auto d = tryDecode(clipped)) {
result.status = DecodeStatus::Clean;
result.data = *d;
result.corrected_codeword = clipped;
result.detail = "CRC/frozen constraints satisfied";
return result;
}
std::optional<uint64_t> recovered;
int corrected_pos = -1;
for (int i = 0; i < n_; ++i) {
uint64_t candidate = clipped ^ (1ULL << i);
auto d = tryDecode(candidate);
if (!d) {
continue;
}
if (recovered.has_value()) {
result.status = DecodeStatus::DetectedUncorrectable;
result.data = *d;
result.corrected_codeword = candidate;
result.detail = "Ambiguous single-flip correction candidates";
return result;
}
recovered = d;
corrected_pos = i;
}
if (recovered.has_value()) {
result.status = DecodeStatus::Corrected;
result.data = *recovered;
result.corrected_codeword = clipped ^ (1ULL << corrected_pos);
result.corrected_bits = 1;
result.detail = "CRC-aided single-bit correction";
return result;
}
result.status = DecodeStatus::DetectedUncorrectable;
result.data = clipped & dataMask();
result.corrected_codeword = clipped;
result.detail = "Failed CRC-aided decode";
return result;
}
private:
int data_bits_;
int crc_bits_;
int total_info_bits_;
int n_;
std::vector<bool> frozen_;
std::vector<int> info_positions_;
static int nextPow2(int x) {
int n = 1;
while (n < x) {
n <<= 1;
}
return n;
}
static std::vector<int> buildInfoPositions(int n, int info_bits) {
std::vector<int> positions;
positions.reserve(info_bits);
for (int i = n - info_bits; i < n; ++i) {
positions.push_back(i);
}
return positions;
}
static void polarTransform(std::vector<int>& bits) {
const int n = static_cast<int>(bits.size());
for (int len = 1; len < n; len <<= 1) {
for (int i = 0; i < n; i += (len << 1)) {
for (int j = 0; j < len; ++j) {
bits[i + j] ^= bits[i + j + len];
}
}
}
}
// CRC-8/ROHC: poly=0x07, init=0xFF, no final XOR, MSB-first bit processing.
// Internally consistent for ECC purposes; not interoperable with CRC-8/SMBUS.
static uint8_t crc8(uint64_t payload, int data_bits) {
uint8_t crc = 0xFF;
constexpr uint8_t poly = 0x07;
for (int i = data_bits - 1; i >= 0; --i) {
const uint8_t in = static_cast<uint8_t>((payload >> i) & 1ULL);
const uint8_t mix = static_cast<uint8_t>(((crc >> 7) & 1U) ^ in);
crc <<= 1;
if (mix) {
crc ^= poly;
}
}
return crc;
}
};
static std::unique_ptr<ECCCodec> createCodec(const std::string& codec_name, int word_bits) {
if (codec_name == "secded") {
return std::make_unique<HammingSecdedCodec>(word_bits);
}
if (codec_name == "taec" || codec_name == "hashaec3") {
return std::make_unique<HashAEC3Codec>(word_bits);
}
if (codec_name == "bch" || codec_name == "hashec2") {
return std::make_unique<HashEC2Codec>(word_bits);
}
if (codec_name == "polar" || codec_name == "crcrm") {
return std::make_unique<PolarCodec>(word_bits);
}
throw std::invalid_argument("Unknown codec: " + codec_name);
}
static const char* statusToString(DecodeStatus status) {
switch (status) {
case DecodeStatus::Clean:
return "clean read";
case DecodeStatus::Corrected:
return "corrected read";
case DecodeStatus::DetectedUncorrectable:
return "detected uncorrectable error";
case DecodeStatus::UndetectedError:
return "undetected error";
}
return "unknown";
}
struct SRAMConfig {
std::size_t total_bytes = 0;
int word_width_bits = 0;
};
struct StressStats {
std::uint64_t total_reads = 0;
std::uint64_t total_writes = 0;
std::uint64_t injected_single = 0;
std::uint64_t injected_burst = 0;
std::uint64_t injected_random_multi = 0;
std::uint64_t corrected_errors = 0;
std::uint64_t detected_uncorrectable = 0;
std::uint64_t undetected_errors = 0;
std::uint64_t miscorrections = 0;
std::uint64_t encode_ops = 0;
std::uint64_t decode_ops = 0;
std::uint64_t correction_ops = 0;
double correctionRate() const {
const double denom = static_cast<double>(corrected_errors + detected_uncorrectable + undetected_errors);
return denom == 0.0 ? 0.0 : static_cast<double>(corrected_errors) / denom;
}
double detectionRate() const {
const double denom = static_cast<double>(corrected_errors + detected_uncorrectable + undetected_errors);
return denom == 0.0 ? 0.0 : static_cast<double>(corrected_errors + detected_uncorrectable) / denom;
}
double sdcRate() const {
return total_reads == 0 ? 0.0 : static_cast<double>(undetected_errors) / static_cast<double>(total_reads);
}
};
struct ConfidenceInterval {
double mean = 0.0;
double lower = 0.0;
double upper = 0.0;
};
struct ResearchMetrics {
int parity_bits = 0;
double codeword_expansion_pct = 0.0;
double heuristic_energy_score = 0.0;
double heuristic_latency_score = 0.0;
double correction_success_pct = 0.0;
double detection_success_pct = 0.0;
double sdc_pct = 0.0;
double miscorrection_pct = 0.0;
double effective_protection_score = 0.0;
};
struct CampaignResult {
std::string codec;
SRAMConfig config;
std::string fault_model;
std::size_t iterations = 0;
StressStats stats;
ResearchMetrics metrics;
ConfidenceInterval sdc_ci;
ConfidenceInterval undetected_ci;
};
class SRAMSimulator {
public:
struct ReadResult {
uint64_t data = 0;
DecodeStatus status = DecodeStatus::Clean;
int syndrome = 0;
bool mismatch_vs_golden = false;
bool was_miscorrected = false;
};
SRAMSimulator(SRAMConfig cfg, std::unique_ptr<ECCCodec> codec, std::uint32_t seed = 1234567)
: cfg_(cfg),
codec_(std::move(codec)),
depth_words_(computeDepth(cfg.total_bytes, cfg.word_width_bits)),
memory_(depth_words_, codec_->encode(0)),
golden_(depth_words_, 0),
rng_(seed) {
if (!codec_) {
throw std::invalid_argument("codec must not be null");
}
if (codec_->dataBits() != cfg.word_width_bits) {
throw std::invalid_argument("codec data bits must match word width");
}
}
std::size_t depthWords() const { return depth_words_; }
SRAMConfig config() const { return cfg_; }
const ECCCodec& codec() const { return *codec_; }
void write(std::size_t address, uint64_t data) {
checkAddress(address);
const uint64_t masked = data & codec_->dataMask();
golden_[address] = masked;
memory_[address] = codec_->encode(masked);
}
ReadResult read(std::size_t address) {
checkAddress(address);
DecodeResult decoded = codec_->decode(memory_[address]);
ReadResult rr;
rr.data = decoded.data;
rr.status = decoded.status;
rr.syndrome = decoded.syndrome;
rr.mismatch_vs_golden = (rr.data != golden_[address]);
if (decoded.status == DecodeStatus::Corrected) {
memory_[address] = codec_->encode(decoded.data);
}
if ((decoded.status == DecodeStatus::Clean || decoded.status == DecodeStatus::Corrected) && rr.mismatch_vs_golden) {
if (decoded.status == DecodeStatus::Corrected) {
rr.was_miscorrected = true;
}
rr.status = DecodeStatus::UndetectedError;
}
return rr;
}
void injectSingleBitFault(std::size_t address, int bit_position_1_based) {
checkAddress(address);
checkBitPosition(bit_position_1_based);
memory_[address] ^= (1ULL << (bit_position_1_based - 1));
}
void injectBurstFault(std::size_t address, int start_position_1_based, int burst_length) {
checkAddress(address);
if (burst_length <= 0) {
throw std::out_of_range("burst_length must be positive");
}
for (int i = 0; i < burst_length; ++i) {
int pos = start_position_1_based + i;
if (pos >= 1 && pos <= codec_->codewordBits()) {
memory_[address] ^= (1ULL << (pos - 1));
}
}
}
void injectRandomFaults(std::size_t address, int count) {
checkAddress(address);
if (count <= 0) {
return;
}
std::uniform_int_distribution<int> dist(1, codec_->codewordBits());
for (int i = 0; i < count; ++i) {
injectSingleBitFault(address, dist(rng_));
}
}
void injectFaultPositions(std::size_t address, const std::vector<int>& bit_positions_1_based) {
checkAddress(address);
for (int pos : bit_positions_1_based) {
if (pos >= 1 && pos <= codec_->codewordBits()) {
memory_[address] ^= (1ULL << (pos - 1));
}
}
}
void injectRowFault(std::size_t row_start, std::size_t row_length, int bit_position_1_based) {
checkBitPosition(bit_position_1_based);
const std::size_t end = std::min(depth_words_, row_start + row_length);
for (std::size_t a = row_start; a < end; ++a) {
memory_[a] ^= (1ULL << (bit_position_1_based - 1));
}
}
void injectColumnFault(int bit_position_1_based, std::size_t stride) {
checkBitPosition(bit_position_1_based);
if (stride == 0) {
stride = 1;
}
for (std::size_t a = 0; a < depth_words_; a += stride) {
memory_[a] ^= (1ULL << (bit_position_1_based - 1));
}
}
void applyFaultMap(const std::map<std::size_t, std::set<int>>& fault_map) {
for (const auto& kv : fault_map) {
if (kv.first >= depth_words_) {
continue;
}
for (int pos : kv.second) {
if (pos >= 1 && pos <= codec_->codewordBits()) {
memory_[kv.first] ^= (1ULL << (pos - 1));
}
}
}
}
std::size_t randomAddress(std::mt19937& rng) const {
std::uniform_int_distribution<std::size_t> addr_dist(0, depth_words_ - 1);
return addr_dist(rng);
}
int randomBitPosition(std::mt19937& rng) const {
std::uniform_int_distribution<int> bit_dist(1, codec_->codewordBits());
return bit_dist(rng);
}
bool injectUndetectedPattern(std::size_t address, int max_weight = 4) {
checkAddress(address);
if (max_weight < 2 || codec_->codewordBits() > 40) {
if (codec_->codewordBits() > 40) {
std::cerr << "[warn] injectUndetectedPattern: codeword too wide ("
<< codec_->codewordBits() << " bits); skipping O(n^4) search\n";
}
return false;
}
const uint64_t base = memory_[address];
for (int i = 1; i <= codec_->codewordBits(); ++i) {
for (int j = i + 1; j <= codec_->codewordBits(); ++j) {
for (int k = j + 1; k <= codec_->codewordBits(); ++k) {
for (int l = k + 1; l <= codec_->codewordBits(); ++l) {
uint64_t cand = base;
flipBit1(cand, i);
flipBit1(cand, j);
flipBit1(cand, k);
flipBit1(cand, l);
DecodeResult dr = codec_->decode(cand);
if ((dr.status == DecodeStatus::Clean || dr.status == DecodeStatus::Corrected) &&
dr.data != golden_[address]) {
memory_[address] = cand;
return true;
}
}
}
}
}
return false;
}
private:
SRAMConfig cfg_;
std::unique_ptr<ECCCodec> codec_;
std::size_t depth_words_;
std::vector<uint64_t> memory_;
std::vector<uint64_t> golden_;
std::mt19937 rng_;
static std::size_t computeDepth(std::size_t total_bytes, int word_width_bits) {
if (word_width_bits % 8 != 0 || word_width_bits <= 0) {
throw std::invalid_argument("word_width_bits must be positive and byte-aligned");
}
return total_bytes / static_cast<std::size_t>(word_width_bits / 8);
}
void checkAddress(std::size_t address) const {
if (address >= depth_words_) {
throw std::out_of_range("address out of range");
}
}
void checkBitPosition(int bit_position_1_based) const {
if (bit_position_1_based < 1 || bit_position_1_based > codec_->codewordBits()) {
throw std::out_of_range("bit position out of range");
}
}
};
class FaultModel {
public:
virtual ~FaultModel() = default;
virtual std::string name() const = 0;
virtual void inject(SRAMSimulator& sim,
std::size_t address,
std::mt19937& rng,
StressStats& stats,
std::size_t iteration) = 0;
};
class LegacyMixedFaultModel final : public FaultModel {
public:
std::string name() const override { return "legacy_mixed"; }
void inject(SRAMSimulator& sim, std::size_t address, std::mt19937& rng, StressStats& stats,
std::size_t /*iteration*/) override {
std::uniform_int_distribution<int> op_dist(0, 99);
std::uniform_int_distribution<int> burst_len_dist(2, 5);
std::uniform_int_distribution<int> random_fault_count(2, 4);
const int op = op_dist(rng);
if (op < 50) {
sim.injectSingleBitFault(address, sim.randomBitPosition(rng));
++stats.injected_single;
} else if (op < 80) {
std::uniform_int_distribution<int> start_dist(1, std::max(1, sim.codec().codewordBits() - 4));
sim.injectBurstFault(address, start_dist(rng), burst_len_dist(rng));
++stats.injected_burst;
} else {
sim.injectRandomFaults(address, random_fault_count(rng));
++stats.injected_random_multi;
}
}
};
struct FaultModelConfig {
std::string model = "legacy";
int adjacency_radius = 1;
std::string adjacency_shape = "horizontal";
std::size_t row_length = 64;
std::size_t column_stride = 64;
double retention_probability = 0.01;
double soft_error_rate = 0.005;
double burst_geo_p = 0.35;
double fault_map_probability = 0.0001;
};
class AdvancedFaultModel final : public FaultModel {
public:
explicit AdvancedFaultModel(FaultModelConfig cfg) : cfg_(std::move(cfg)) {}
std::string name() const override { return cfg_.model; }
void inject(SRAMSimulator& sim, std::size_t address, std::mt19937& rng, StressStats& stats,
std::size_t iteration) override {
maybeInitFaultMap(sim, rng);
if (cfg_.model == "adjacent") {
applyAdjacent(sim, address, rng, stats);
} else if (cfg_.model == "row") {
applyRow(sim, rng, stats);
} else if (cfg_.model == "column") {
applyColumn(sim, rng, stats);
} else if (cfg_.model == "retention") {
applyRetention(sim, address, rng, stats, iteration);
} else if (cfg_.model == "soft") {
applySoft(sim, address, rng, stats);
} else if (cfg_.model == "geoburst") {
applyGeometricBurst(sim, address, rng, stats);
} else if (cfg_.model == "faultmap") {
sim.applyFaultMap(fault_map_);
++stats.injected_random_multi;
} else {
fallback_.inject(sim, address, rng, stats, iteration);
}
}
private:
FaultModelConfig cfg_;
std::map<std::size_t, std::set<int>> fault_map_;
bool fault_map_initialized_ = false;
std::map<std::size_t, std::vector<int>> delayed_retention_;
LegacyMixedFaultModel fallback_;
void maybeInitFaultMap(SRAMSimulator& sim, std::mt19937& rng) {
if (cfg_.model != "faultmap" || fault_map_initialized_) {
return;
}
std::bernoulli_distribution defect(cfg_.fault_map_probability);
for (std::size_t a = 0; a < sim.depthWords(); ++a) {
for (int b = 1; b <= sim.codec().codewordBits(); ++b) {
if (defect(rng)) {
fault_map_[a].insert(b);
}
}
}
fault_map_initialized_ = true;
}
void applyAdjacent(SRAMSimulator& sim, std::size_t address, std::mt19937& rng, StressStats& stats) {
const int center = sim.randomBitPosition(rng);
std::vector<int> positions{center};
if (cfg_.adjacency_shape == "clustered") {
for (int d = 1; d <= cfg_.adjacency_radius; ++d) {
positions.push_back(center + d);
positions.push_back(center - d);
}
} else {
const int step = (cfg_.adjacency_shape == "vertical") ? 2 : 1;
for (int d = 1; d <= cfg_.adjacency_radius; ++d) {
positions.push_back(center + d * step);
}