-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathTraceFetch.cc
More file actions
1583 lines (1439 loc) · 64.4 KB
/
Copy pathTraceFetch.cc
File metadata and controls
1583 lines (1439 loc) · 64.4 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 (c) 2025
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/o3/trace/TraceFetch.hh"
#include <algorithm>
#include <array>
#include <limits>
#include "arch/riscv/isa.hh"
#include "arch/riscv/pagetable.hh"
#include "arch/riscv/pcstate.hh"
#include "arch/riscv/regs/misc.hh"
#include "base/intmath.hh"
#include "base/logging.hh"
#include "cpu/o3/cpu.hh"
#include "cpu/o3/dyn_inst.hh"
#include "cpu/o3/fetch.hh"
#include "debug/Fetch.hh"
#include "debug/Override.hh"
#include "sim/system.hh"
namespace gem5
{
namespace o3
{
namespace
{
uint64_t
sv39NonLeafPte(Addr next_level_table_pa)
{
RiscvISA::PTE pte = 0;
pte.v = 1;
pte.ppn = next_level_table_pa >> RiscvISA::PGSHFT;
return static_cast<uint64_t>(pte);
}
uint64_t
sv39LeafPte(Addr pa, bool readable, bool writable, bool executable)
{
RiscvISA::PTE pte = 0;
pte.v = 1;
pte.r = readable ? 1 : 0;
pte.w = writable ? 1 : 0;
pte.x = executable ? 1 : 0;
pte.a = 1;
pte.d = 1;
pte.ppn = pa >> RiscvISA::PGSHFT;
return static_cast<uint64_t>(pte);
}
} // anonymous namespace
TraceFetch::TraceFetch(Fetch &fetch_, const BaseO3CPUParams ¶ms)
: fetch(fetch_)
{
for (int i = 0; i < MaxThreads; i++) {
traceFetchExpectedCorrectIdx[i] = 1;
}
traceMode = params.enableTraceMode;
traceFormat = params.traceFormat;
traceTimingPTW = params.traceTimingPTW;
tracePTReservedBytes = params.tracePTReservedBytes;
tracePTLeafPageSize = params.tracePTLeafPageSize;
traceAddrBase = params.traceAddrBase;
traceAddrSize = params.traceAddrSize;
if (traceMode) {
DPRINTF(Fetch, "Trace mode enabled, file: %s, format: %s\n",
params.traceFile, params.traceFormat);
traceTrainBranches = params.traceTrainBranches;
traceDecoupledFrontend = params.enableDecoupledBPInTrace;
traceCheckpointInterval = params.traceCheckpointInterval;
// Wire CPU params to fetch trace modeling knobs
traceMispredictPenalty = params.traceMispredictPenalty;
traceEnableWrongPath = params.traceEnableWrongPath;
// Wrong-path injection mode (default NOPs)
traceWrongPathUseTraceInst = params.traceWrongPathUseTraceInst;
fatal_if(traceWrongPathUseTraceInst,
"traceWrongPathUseTraceInst is currently unimplemented");
// Enable BP-vs-trace validation independent of training
traceBPValidation = params.traceBPValidation;
// Note: pass CPU as parent stats group; keep reader name simple to avoid
// duplicated prefixes in stats paths.
traceReader = createTraceReader(params.traceFormat, params.traceFile,
"traceReader",
params.traceAddrBase, params.traceAddrSize,
params.traceAddrMapMode, params.traceAddrPageAlign,
fetch.cpu);
if (!traceReader) {
fatal("Failed to create trace reader for format: %s\n",
params.traceFormat);
}
} else {
traceReader = nullptr;
}
}
TraceFetch::~TraceFetch() = default;
bool
TraceFetch::initializeTraceReader()
{
if (!traceReader) {
return false;
}
DPRINTF(Fetch, "Initializing trace reader\n");
bool success = traceReader->init();
if (!success) {
warn("Failed to initialize trace reader\n");
return false;
}
DPRINTF(Fetch, "Trace reader initialized successfully\n");
// 同步清理 reader 内部缓冲/历史窗口,保持状态一致
traceReader->resetHistory();
return true;
}
void
TraceFetch::setupTraceTimingPTW(::gem5::ThreadContext *tc)
{
if (!traceMode || !traceTimingPTW) {
return;
}
if (!tc) {
fatal("Trace timing PTW enabled but ThreadContext is null\n");
}
if (tracePTReservedBytes == 0) {
fatal("Trace timing PTW enabled but tracePTReservedBytes is 0\n");
}
if (tracePTLeafPageSize != 4 * 1024 && tracePTLeafPageSize != 2 * 1024 * 1024) {
fatal("Trace timing PTW: unsupported tracePTLeafPageSize=%llu\n",
(unsigned long long)tracePTLeafPageSize);
}
constexpr Addr kPageSize = 4 * 1024;
constexpr size_t kEntriesPerPt = 512;
constexpr Addr kL0Coverage = static_cast<Addr>(kEntriesPerPt) * kPageSize; // 2MiB
constexpr Addr kL1Coverage = static_cast<Addr>(kEntriesPerPt) * kL0Coverage; // 1GiB
Addr va_start = roundDown(traceAddrBase, kPageSize);
Addr va_end = roundUp(traceAddrBase + traceAddrSize, kPageSize);
if (va_end <= va_start) {
fatal("Trace timing PTW: invalid trace mapping window base=0x%llx size=0x%llx\n",
(unsigned long long)traceAddrBase, (unsigned long long)traceAddrSize);
}
Addr pt_region_base = traceAddrBase + traceAddrSize;
if (pt_region_base % kPageSize) {
fatal("Trace timing PTW: page table region base is not 4KiB-aligned "
"(base=0x%llx)\n",
(unsigned long long)pt_region_base);
}
Addr pt_region_end = pt_region_base + tracePTReservedBytes;
fatal_if(pt_region_end <= pt_region_base,
"Trace timing PTW: invalid page table region "
"(base=0x%llx, end=0x%llx)\n",
(unsigned long long)pt_region_base,
(unsigned long long)pt_region_end);
if (pt_region_base < va_end) {
fatal("Trace timing PTW: page table region overlaps trace mapping window "
"(trace=[0x%llx,0x%llx), pt=[0x%llx,0x%llx))\n",
(unsigned long long)va_start, (unsigned long long)va_end,
(unsigned long long)pt_region_base, (unsigned long long)pt_region_end);
}
auto *system = tc->getSystemPtr();
if (!system) {
fatal("Trace timing PTW enabled but System is null\n");
}
fatal_if(!system->isMemAddr(pt_region_base) ||
!system->isMemAddr(pt_region_end - 1),
"Trace timing PTW: page table region is outside physical memory "
"(pt=[0x%llx,0x%llx))\n",
(unsigned long long)pt_region_base,
(unsigned long long)pt_region_end);
PortProxy &phys = system->physProxy;
phys.memsetBlob(pt_region_base, 0, tracePTReservedBytes);
const uint64_t first_vpn2 = va_start / kL1Coverage;
const uint64_t last_vpn2 = (va_end - 1) / kL1Coverage;
const uint64_t num_l1_pages = last_vpn2 - first_vpn2 + 1;
uint64_t num_leaf_pages = 0;
if (tracePTLeafPageSize == kPageSize) {
const uint64_t first_vpn1 = va_start / kL0Coverage;
const uint64_t last_vpn1 = (va_end - 1) / kL0Coverage;
num_leaf_pages = last_vpn1 - first_vpn1 + 1;
}
const uint64_t total_pt_pages =
1 + num_l1_pages + (tracePTLeafPageSize == kPageSize ? num_leaf_pages : 0);
const uint64_t required_bytes = total_pt_pages * kPageSize;
if (required_bytes > tracePTReservedBytes) {
fatal("Trace timing PTW: reserved region too small "
"(required=0x%llx, reserved=0x%llx)\n",
(unsigned long long)required_bytes,
(unsigned long long)tracePTReservedBytes);
}
Addr root_pa = pt_region_base;
Addr next_free = root_pa + kPageSize;
std::array<uint64_t, kEntriesPerPt> root_entries{};
root_entries.fill(0);
for (uint64_t vpn2 = first_vpn2; vpn2 <= last_vpn2; ++vpn2) {
Addr l1_pa = next_free;
next_free += kPageSize;
const uint64_t vpn2_idx = vpn2 & (kEntriesPerPt - 1);
root_entries[vpn2_idx] = sv39NonLeafPte(l1_pa);
std::array<uint64_t, kEntriesPerPt> l1_entries{};
l1_entries.fill(0);
Addr v2_base = vpn2 * kL1Coverage;
Addr v2_start = std::max(va_start, v2_base);
Addr v2_end = std::min(va_end, v2_base + kL1Coverage);
if (v2_start >= v2_end) {
continue;
}
const uint64_t first_vpn1 = v2_start / kL0Coverage;
const uint64_t last_vpn1 = (v2_end - 1) / kL0Coverage;
for (uint64_t vpn1 = first_vpn1; vpn1 <= last_vpn1; ++vpn1) {
Addr v1_base = vpn1 * kL0Coverage;
Addr v1_start = std::max(v2_start, v1_base);
Addr v1_end = std::min(v2_end, v1_base + kL0Coverage);
const uint64_t vpn1_idx = vpn1 & (kEntriesPerPt - 1);
if (tracePTLeafPageSize == kL0Coverage) {
l1_entries[vpn1_idx] = sv39LeafPte(v1_base, true, true, true);
continue;
}
Addr l0_pa = next_free;
next_free += kPageSize;
l1_entries[vpn1_idx] = sv39NonLeafPte(l0_pa);
std::array<uint64_t, kEntriesPerPt> l0_entries{};
l0_entries.fill(0);
const uint64_t first_vpn0 = v1_start / kPageSize;
const uint64_t last_vpn0 = (v1_end - 1) / kPageSize;
for (uint64_t vpn0 = first_vpn0; vpn0 <= last_vpn0; ++vpn0) {
const uint64_t vpn0_idx = vpn0 & (kEntriesPerPt - 1);
Addr page_base = vpn0 * kPageSize;
l0_entries[vpn0_idx] = sv39LeafPte(page_base, true, true, true);
}
phys.writeBlob(l0_pa, l0_entries.data(), kPageSize);
}
phys.writeBlob(l1_pa, l1_entries.data(), kPageSize);
}
phys.writeBlob(root_pa, root_entries.data(), kPageSize);
tc->setMiscReg(RiscvISA::MiscRegIndex::MISCREG_PRV,
static_cast<RegVal>(RiscvISA::PrivilegeMode::PRV_S));
RiscvISA::SATP satp = 0;
satp.mode = RiscvISA::AddrXlateMode::SV39;
satp.asid = 0;
satp.ppn = root_pa >> RiscvISA::PGSHFT;
tc->setMiscReg(RiscvISA::MiscRegIndex::MISCREG_SATP,
static_cast<RegVal>(satp));
DPRINTF(Fetch,
"Trace timing PTW: installed SATP(root=0x%llx), PRV=S, "
"trace=[0x%llx,0x%llx), pt=[0x%llx,0x%llx), leaf=%llu\n",
(unsigned long long)root_pa,
(unsigned long long)va_start, (unsigned long long)va_end,
(unsigned long long)pt_region_base, (unsigned long long)pt_region_end,
(unsigned long long)tracePTLeafPageSize);
}
bool
TraceFetch::initTraceMode()
{
if (!initializeTraceReader()) {
return false;
}
if (traceReader->isEOF()) {
return true;
}
o3::TraceInstruction firstInstr = traceReader->getNextInstruction();
if (!firstInstr.isValid()) {
return false;
}
traceReader->reset();
if (!initializeTraceReader()) {
return false;
}
std::unique_ptr<PCStateBase> tracePC(fetch.pc[0]->clone());
auto& riscv_pc = tracePC->as<RiscvISA::PCState>();
riscv_pc.set(firstInstr.getPC());
set(fetch.pc[0], *tracePC);
fetch.cpu->pcState(*tracePC, 0);
auto* tc0 = fetch.cpu->getContext(0);
if (tc0) {
tc0->pcState(*tracePC);
RegVal status = tc0->readMiscReg(RiscvISA::MiscRegIndex::MISCREG_STATUS);
status |= RiscvISA::STATUS_FS_MASK;
tc0->setMiscReg(RiscvISA::MiscRegIndex::MISCREG_STATUS, status);
}
if (tc0) {
setupTraceTimingPTW(tc0);
} else if (traceTimingPTW) {
fatal("Trace timing PTW enabled but ThreadContext[0] is null\n");
}
DPRINTF(Fetch,
"Trace mode: Set initial PC to 0x%llx from first trace instruction\n",
firstInstr.getPC());
if (tc0) {
DPRINTF(Fetch,
"Trace mode: fetch PC = 0x%llx, cpu PC = 0x%llx, TC PC = 0x%llx\n",
fetch.pc[0]->instAddr(), fetch.cpu->pcState(0).instAddr(),
tc0->pcState().instAddr());
} else {
DPRINTF(Fetch,
"Trace mode: fetch PC = 0x%llx, cpu PC = 0x%llx (no TC)\n",
fetch.pc[0]->instAddr(), fetch.cpu->pcState(0).instAddr());
}
if (fetch.branchPred) {
DPRINTF(Fetch, "Trace mode: Priming decoupled BPU with start PC 0x%llx\n",
firstInstr.getPC());
assert(fetch.dbpbtb);
fetch.dbpbtb->resetPC(firstInstr.getPC());
}
return true;
}
void
TraceFetch::resetStage()
{
for (ThreadID tid = 0; tid < fetch.numThreads; ++tid) {
// 正确路径的期望 trace 索引从 1 开始
traceFetchExpectedCorrectIdx[tid] = 1;
}
// Reset trace consumption counter for precise seqNum→trace index mapping
// Start consumed trace index from 1 to make indices human-friendly and
// consistent with reader semantics used elsewhere.
traceInstrConsumed = 1;
}
bool
TraceFetch::maybeStallFetch(ThreadID tid)
{
static_cast<void>(tid);
if (!traceMode) {
return false;
}
// If we're modeling a generic mispredict stall (coupled frontend), stall for this cycle
if (traceStallRemaining > Cycles(0)) {
traceStallRemaining = traceStallRemaining - Cycles(1);
auto stall_left = (unsigned long long) traceStallRemaining;
DPRINTF(Fetch, "[tid:%i] Trace mispredict stall active, remaining=%llu cycles\n",
tid, stall_left);
return true;
}
return false;
}
void
TraceFetch::ensureTraceStreamFilled(ThreadID tid, size_t min_count)
{
if (!traceMode || !traceReader) {
return;
}
if (traceEnableWrongPath && traceWrongPathActive) {
return;
}
while (traceExpectedStream[tid].size() < min_count) {
auto ti = traceReader->getNextInstruction();
if (!ti.isValid()) {
break;
}
DPRINTF(Fetch, "[TraceStream] Fetched PC=0x%lx (sn:%llu)\n",
ti.getPC(), (unsigned long long)ti.getSeqNum());
traceExpectedStream[tid].push_back(ti);
}
}
StallReason
TraceFetch::checkMemoryNeeds(ThreadID tid, const PCStateBase &this_pc)
{
// 防御:正常情况下 traceMode 必然伴随有效的 traceReader
panic_if(!traceReader, "traceMode enabled but traceReader is unavailable");
return fetchTraceInstruction(tid, this_pc);
}
StallReason
TraceFetch::fetchTraceInstruction(ThreadID tid, const PCStateBase &this_pc)
{
const bool wrong_path = (traceEnableWrongPath && traceWrongPathActive);
if (wrong_path) {
const unsigned nop_size =
chooseWrongPathNopSize(tid, this_pc.instAddr());
// RISC-V 32b nop: 0x00000013; 16b compressed nop: 0x0001
TheISA::MachInst nop = (nop_size == 2)
? static_cast<TheISA::MachInst>(0x0001u)
: static_cast<TheISA::MachInst>(0x00000013u);
supplyTraceToDecoder(
tid, this_pc, nop, this_pc.instAddr(),
nop_size == 2 ? "supplied 2B NOP without advancing reader"
: "supplied 4B NOP without advancing reader (pred takenPC)");
return StallReason::NoStall;
}
// 正确路径:填充期望指令流并供码(不在此处消费流,仅在构建后比对并消耗)
ensureTraceStreamFilled(tid, TRACE_STREAM_MIN_FILL);
if (traceExpectedStream[tid].empty()) {
DPRINTF(Fetch, "[tid:%i] Trace on-demand: expected stream empty (EOF=%d)\n",
tid, traceReader->isEOF());
return StallReason::IcacheStall;
}
auto head = traceExpectedStream[tid].front();
// 对非分支/异常类 ctrl-flow-change,在 decoupled + wrong-path 校验场景下,
// 若缺乏可靠 nextPC,保守将长度标为 2B,避免后续进入 wrong-path 时跨过块内预测点。
if (traceEnableWrongPath && traceBPValidation &&
head.isCtrlFlowChange() && !head.isAnyBranch()) {
head.setInstSizeBytes(2);
}
pendingTraceInstr = head;
pendingTraceValid = true;
TheISA::MachInst machInst = createMachInstFromTrace(head);
supplyTraceToDecoder(tid, this_pc, machInst, head.getPC(),
"supplied 4B to decoder (from expected stream head)");
return StallReason::NoStall;
}
void
TraceFetch::supplyTraceToDecoder(ThreadID tid, const PCStateBase &this_pc,
TheISA::MachInst machInst, Addr instrPC,
const char *tag)
{
auto *dec_ptr = fetch.decoder[tid];
memcpy(dec_ptr->moreBytesPtr(), &machInst, sizeof(machInst));
fetch.decoder[tid]->moreBytes(this_pc, instrPC);
fetch.fetchBuffer[tid].startPC = instrPC;
fetch.fetchBuffer[tid].valid = true;
DPRINTF(Fetch, "[tid:%i] Trace on-demand: %s at PC=0x%llx\n",
tid, tag, (unsigned long long)instrPC);
}
void
TraceFetch::enterTraceWrongPath(ThreadID tid, InstSeqNum branchSeqNum, Addr predPC,
Addr corrPC, bool forceMinStep,
const char *reason, uint64_t traceSeqNum)
{
traceWrongPathActive = true;
traceWrongPathBranchSeqNum = branchSeqNum;
traceWrongPathForceMinStep = forceMinStep;
traceWrongPathPredPC = predPC;
traceWrongPathCorrectPC = corrPC;
DPRINTF(Fetch,
"[tid:%i] %s (predPC=0x%llx, corrPC=0x%llx, sn:%llu, tracesn:%llu)\n",
tid, reason,
(unsigned long long)predPC,
(unsigned long long)corrPC,
(unsigned long long)traceWrongPathBranchSeqNum,
(unsigned long long)traceSeqNum);
}
void
TraceFetch::exitTraceWrongPath(ThreadID tid, const char *reason)
{
DPRINTF(Fetch, "[tid:%i] Exit wrong-path mode: %s\n", tid, reason);
traceWrongPathActive = false;
traceWrongPathForceMinStep = false;
traceWrongPathPredPC = 0;
traceWrongPathCorrectPC = 0;
traceWrongPathBranchSeqNum = 0;
}
unsigned
TraceFetch::chooseWrongPathNopSize(ThreadID tid, Addr pc)
{
static_cast<void>(tid);
if (traceWrongPathForceMinStep) {
return 2;
}
unsigned sz = 2;
Addr block_end = 0;
Addr taken_pc = 0;
bool taken = false;
if (fetch.isBTBPred()) {
assert(fetch.dbpbtb);
if (fetch.dbpbtb->ftqHasHead()) {
const auto &stream = fetch.dbpbtb->ftqHead();
block_end = stream.predEndPC;
taken_pc = stream.predBranchInfo.pc;
taken = stream.predTaken;
}
}
// If the current PC matches predicted takenPC (assume 4B branches), use a 4B NOP.
if (taken && taken_pc && pc == taken_pc) {
sz = 4;
} else if (block_end && pc + 2 == block_end) {
sz = 2;
}
return sz;
}
void
TraceFetch::bindPendingTraceMetadata(ThreadID tid, const DynInstPtr &instruction,
const PCStateBase &pc,
o3::TraceInstruction &traceForThisInst)
{
traceForThisInst = o3::TraceInstruction();
// 在按需 trace 模式下,将挂起的 trace 元数据绑定到 DynInst
// 保留一份本条指令的 trace 记录用于后续 BP 校验
if (instruction && traceMode && pendingTraceValid) {
bindTraceMetadata(instruction, pendingTraceInstr, tid);
traceForThisInst = pendingTraceInstr;
}
// Fetch-side严格顺序校验(流式):正确路径构建指令后,与期望流head对比并消耗
if (instruction && traceMode && traceEnableWrongPath && !traceWrongPathActive) {
validateAndConsumeTraceStream(tid, pc);
}
}
void
TraceFetch::postBranchPredict(ThreadID tid, const DynInstPtr &instruction,
const o3::TraceInstruction &traceForThisInst,
PCStateBase &pc, PCStateBase &next_pc,
bool predictedBranch)
{
// 非分支或 cond-trap 控制流改变(例如异常/陷入)在 decoupled + wrong-path 模式下视为
// "trace 驱动的 trap wrong-path":从该指令之后沿 BPU 预测路径走的指令
// 对 traceReader 而言都是 wrong-path,后续由 commit 触发 trap squash 统一纠正。
if (traceMode && instruction && traceForThisInst.isValid() &&
traceForThisInst.isCtrlFlowChange() &&
traceEnableWrongPath) {
maybeEnterTraceCtrlFlowWrongPath(tid, instruction, traceForThisInst, pc, next_pc);
}
// 若启用 BP 校验,则将 BPU 预测与 trace 真值对比,决定是否进入 wrong-path。
// 注意:带异常/陷入(ctrlFlowChange)的指令由上方 trap wrong-path 逻辑统一处理,
// 这里仅处理“正常控制流”的分支/非分支指令,避免重复、语义混淆。
if (traceMode && traceBPValidation && instruction &&
traceForThisInst.isValid() &&
!traceForThisInst.isCtrlFlowChange()) {
handleTraceBPValidation(tid, instruction, traceForThisInst, next_pc, predictedBranch);
}
// 清除 pending 标记
if (traceMode && pendingTraceValid) {
pendingTraceValid = false;
}
}
void
TraceFetch::clearPending()
{
pendingTraceValid = false;
}
void
TraceFetch::handleTraceSquash(ThreadID tid, const PCStateBase &new_pc,
const DynInstPtr squashInst, InstSeqNum seqNum)
{
// Clean up trace instruction metadata for squashed instructions
if (!traceMode) {
return;
}
bool allow_rb = true;
bool squash_itself = false;
auto trace_rb_seqnum = seqNum;
if (traceWrongPathActive) {
// 处于 wrong-path:优先处理边界分支产生的 squash。
// 注意:也可能出现非边界的 squash(例如 TLB/page fault、trap、重放),
// 此时 squashInst 可能为空。对这类情况不应 panic,而是温和退出 wrong-path。
DPRINTF(Fetch, "[tid:%i] In wrong-path, processing squash for trace rollback, wrong path seqnum is %llu\n",
tid, (unsigned long long)traceWrongPathBranchSeqNum);
if (squashInst) {
DPRINTF(Fetch, "[tid:%i] In wrong-path, detected squash from inst (sn:%llu->tracesn:%llu)\n",
tid,
(unsigned long long)squashInst->seqNum,
findTraceIndexForSeqNum(squashInst->seqNum));
if (squashInst->seqNum == traceWrongPathBranchSeqNum) {
DPRINTF(Fetch,
"[tid:%i] In wrong-path, detected squash from "
"mispredicted inst (sn:%llu->tracesn:%llu), trigger trace rollback\n",
tid,
(unsigned long long)traceWrongPathBranchSeqNum,
findTraceIndexForSeqNum(traceWrongPathBranchSeqNum));
// check whether new pc is correct
bool is_correct_target = new_pc.instAddr() == traceWrongPathCorrectPC;
if (is_correct_target) {
DPRINTF(Fetch,
"[tid:%i] Squash target PC (0x%#lx) matches correct PC (0x%#lx)\n",
tid, new_pc.instAddr(), traceWrongPathCorrectPC);
exitTraceWrongPath(tid, "mispred boundary squash reaches correct PC");
} else {
DPRINTF(Fetch,
"[tid:%i] Warning: Squash target PC (0x%#lx) does not match "
"correct PC (0x%#lx)\n",
tid, new_pc.instAddr(), traceWrongPathCorrectPC);
// stay in wrong-path, let later squash handle
}
} else if (squashInst->seqNum < traceWrongPathBranchSeqNum) {
DPRINTF(Fetch,
"[tid:%i] In wrong-path, detected squash from inst "
"(sn:%llu->tracesn:%llu) prior to mispredicted inst (sn:%llu)\n",
tid,
(unsigned long long)squashInst->seqNum,
findTraceIndexForSeqNum(squashInst->seqNum),
(unsigned long long)traceWrongPathBranchSeqNum);
exitTraceWrongPath(tid, "squash before mispredicted branch");
} else {
allow_rb = false;
DPRINTF(Fetch,
"[tid:%i] In wrong-path, skip trace rollback for "
"non-boundary squash (sn:%llu)\n",
tid, (unsigned long long)seqNum);
}
if (squashInst->getPC() == new_pc.instAddr()) {
squash_itself = true;
DPRINTF(Fetch, "Squashing inst squashing itself, probably load replay (pc: 0x%#lx)\n",
squashInst->getPC());
}
} else {
DPRINTF(Fetch, "[tid:%i] In wrong-path, detected squash from non-inst event (sn:%llu->tracesn:%llu)\n",
tid,
(unsigned long long)seqNum,
findTraceIndexForSeqNum(seqNum));
if (new_pc.instAddr() == traceWrongPathCorrectPC) {
// non-inst squash (例如 trap squash) 把 PC 直接带回了正确路径
// traceReader 在 wrong-path 期间未前进,因此此处无需回滚,只需退出
// wrong-path 模式即可。
squash_itself = false;
trace_rb_seqnum = traceWrongPathBranchSeqNum;
exitTraceWrongPath(tid, "non-inst squash reached correct PC");
// allow_rb = false; // 不需要触碰 traceReader
DPRINTF(Fetch,
"[tid:%i] In wrong-path, non-inst squash reached "
"correct PC (0x%#llx); exit wrong-path without rollback "
"(sn:%llu)\n",
tid,
(unsigned long long)new_pc.instAddr(),
(unsigned long long)seqNum);
} else if (seqNum <= traceWrongPathBranchSeqNum) {
DPRINTF(Fetch,
"[tid:%i] In wrong-path, detected squash from "
"non-inst event (sn:%llu->tracesn:%llu) prior to mispredicted inst (sn:%llu), "
"trigger trace rollback\n",
tid,
(unsigned long long)seqNum,
findTraceIndexForSeqNum(seqNum),
(unsigned long long)traceWrongPathBranchSeqNum);
trace_rb_seqnum = seqNum + 1; // for non-inst squash before branch, rollback to seqNum + 1
squash_itself = true;
exitTraceWrongPath(tid, "non-inst squash before mispredicted branch");
// this would happen for memory violation
} else {
allow_rb = false;
DPRINTF(Fetch,
"[tid:%i] In wrong-path, skip trace rollback for "
"non-boundary squash (sn:%llu) without squashInst\n",
tid, (unsigned long long)seqNum);
}
}
} else {
// not in wrong-path: normal squash, rollback to squashInst seqNum
if (squashInst) {
trace_rb_seqnum = squashInst->seqNum;
DPRINTF(Fetch, "[tid:%i] Normal squash to seqNum %llu from inst (sn:%llu->tracesn:%llu)\n",
tid,
(unsigned long long)trace_rb_seqnum,
(unsigned long long)squashInst->seqNum,
findTraceIndexForSeqNum(squashInst->seqNum));
if (squashInst->getPC() == new_pc.instAddr()) {
squash_itself = true;
DPRINTF(Fetch, "Squashing inst squashing itself, probably load replay (pc: 0x%#lx)\n",
squashInst->getPC());
}
} else {
// non-inst squash (e.g., TLB/page fault, trap, replay)
trace_rb_seqnum = seqNum + 1;
DPRINTF(Fetch, "[tid:%i] Normal squash to seqNum %llu from non-inst event (sn:%llu->tracesn:%llu)\n",
tid,
(unsigned long long)trace_rb_seqnum,
(unsigned long long)seqNum,
findTraceIndexForSeqNum(seqNum));
squash_itself = true;
}
traceWrongPathForceMinStep = false;
}
if (allow_rb) {
DPRINTF(Fetch, "[tid:%i] Rolling back trace reader to seqNum %llu, squash_itself=%d\n",
tid, (unsigned long long)trace_rb_seqnum, squash_itself);
cleanupTraceMetadata(trace_rb_seqnum);
// Rollback trace reader to handle misprediction
if (!rollbackTraceReader(trace_rb_seqnum, squash_itself)) {
DPRINTF(Fetch, "[tid:%i] Warning: Failed to rollback trace reader to seqNum %llu\n",
tid, (unsigned long long)trace_rb_seqnum);
}
// 回滚后清空期望流,避免与reader位置不一致
traceExpectedStream[tid].clear();
DPRINTF(Fetch, "[tid:%i] Cleared expected trace stream after rollback\n", tid);
}
}
void
TraceFetch::storeTraceInstMetadata(InstSeqNum seqNum, const o3::TraceInstruction &traceInstr)
{
// Create shared_ptr to avoid large object copy that caused segfault
auto traceInstrPtr = std::make_shared<const o3::TraceInstruction>(traceInstr);
traceInstMap[seqNum] = traceInstrPtr;
// Stats: count stored metadata records
fetch.fetchStats.traceMetaStores++;
DPRINTF(Fetch, "[sn:%lli] Stored trace instruction metadata (shared_ptr at %p)\n",
seqNum, traceInstrPtr.get());
}
const o3::TraceInstruction*
TraceFetch::getTraceInstMetadata(InstSeqNum seqNum) const
{
auto it = traceInstMap.find(seqNum);
if (it != traceInstMap.end()) {
return it->second.get();
}
return nullptr;
}
bool
TraceFetch::isTraceInstruction(InstSeqNum seqNum) const
{
return traceInstMap.find(seqNum) != traceInstMap.end();
}
void
TraceFetch::cleanupTraceMetadata(InstSeqNum seqNum)
{
// Remove trace metadata for all instructions with seqNum >= threshold
Counter removed = 0;
auto it = traceInstMap.begin();
while (it != traceInstMap.end()) {
if (it->first > seqNum) {
DPRINTF(Fetch, "[sn:%lli] Removing trace metadata due to squash\n", it->first);
it = traceInstMap.erase(it);
++removed;
} else {
++it;
}
}
// Also clean up sequence number to trace index mapping
auto seqIt = seqNumToTraceIndex.begin();
while (seqIt != seqNumToTraceIndex.end()) {
if (seqIt->first > seqNum) {
DPRINTF(Fetch, "[sn:%lli] Removing seqNum to trace index mapping due to squash\n", seqIt->first);
seqIt = seqNumToTraceIndex.erase(seqIt);
++removed;
} else {
++seqIt;
}
}
// Stats: record cleanup calls and total removed entries
fetch.fetchStats.traceMetaCleanupSquashCalls++;
fetch.fetchStats.traceMetaCleanupSquashEntries += removed;
}
void
TraceFetch::cleanupTraceMetadataOnCommit(InstSeqNum /*seqNum*/)
{
// Sliding-window cleanup: keep a guard window behind the oldest in-flight
// instruction and (if active) behind the wrong-path boundary. This avoids
// removing metadata that may still be needed by a late-arriving squash.
static constexpr uint64_t TRACE_META_GUARD = 256; // conservative default
const InstSeqNum oldest_inflight = fetch.cpu->getOldestInFlightSeqNum();
const InstSeqNum wp_boundary = traceWrongPathActive ? traceWrongPathBranchSeqNum
: std::numeric_limits<InstSeqNum>::max();
const InstSeqNum keep_min = std::min(oldest_inflight, wp_boundary);
const InstSeqNum safe_threshold = (keep_min > TRACE_META_GUARD)
? (keep_min - TRACE_META_GUARD)
: 0;
Counter removed = 0;
// Erase entries with seqNum strictly less than safe_threshold
for (auto it = traceInstMap.begin(); it != traceInstMap.end(); ) {
if (it->first < safe_threshold) {
it = traceInstMap.erase(it);
++removed;
} else {
++it;
}
}
for (auto it = seqNumToTraceIndex.begin(); it != seqNumToTraceIndex.end(); ) {
if (it->first < safe_threshold) {
it = seqNumToTraceIndex.erase(it);
++removed;
} else {
++it;
}
}
DPRINTF(Fetch,
"[TraceMetaCleanup] oldest_inflight=%llu wp_active=%d wp_boundary=%llu "
"guard=%llu threshold=%llu removed=%llu\n",
(unsigned long long)oldest_inflight,
(int)traceWrongPathActive,
(unsigned long long)wp_boundary,
(unsigned long long)TRACE_META_GUARD,
(unsigned long long)safe_threshold,
(unsigned long long)removed);
// Stats: count commit-side cleanups
fetch.fetchStats.traceMetaCleanupCommitCalls++;
}
void
TraceFetch::maybeCreateTraceCheckpoint(InstSeqNum seqNum)
{
if (!traceMode || !traceReader) {
return;
}
// Create checkpoint every traceCheckpointInterval instructions.
if (traceCheckpointInterval != 0 && (seqNum % traceCheckpointInterval) == 0) {
auto checkpoint = traceReader->createCheckpoint();
if (checkpoint.valid) {
traceCheckpoints.push_back(checkpoint);
checkpointSeqNums.push_back(seqNum);
DPRINTF(Fetch, "[sn:%lli] Created trace checkpoint at trace index %lu\n",
seqNum, checkpoint.instructionIndex);
// Limit number of checkpoints to avoid memory growth
const size_t MAX_CHECKPOINTS = 16;
if (traceCheckpoints.size() > MAX_CHECKPOINTS) {
traceCheckpoints.erase(traceCheckpoints.begin());
checkpointSeqNums.erase(checkpointSeqNums.begin());
DPRINTF(Fetch, "Removed oldest trace checkpoint\n");
}
}
}
}
uint64_t
TraceFetch::findTraceIndexForSeqNum(InstSeqNum seqNum) const
{
// First try direct lookup
auto it = seqNumToTraceIndex.find(seqNum);
if (it != seqNumToTraceIndex.end()) {
DPRINTF(Fetch, "findTraceIndexForSeqNum[sn:%lli]: Direct mapping found: traceIndex=%lu\n",
seqNum, it->second);
return it->second;
}
// dump seqNumToTraceIndex
DPRINTF(Fetch, seqNumToTraceIndex.size() == 0 ?
" seqNumToTraceIndex is empty\n" :
" seqNumToTraceIndex contents:\n");
for (const auto& pair : seqNumToTraceIndex) {
DPRINTF(Fetch, " seqNum=%lli => traceIndex=%lu\n", pair.first, pair.second);
}
DPRINTF(Fetch, "findTraceIndexForSeqNum[sn:%lli]: No direct mapping\n", seqNum);
return 0;
}
bool
TraceFetch::lookupTraceIndexForSeqNum(InstSeqNum seqNum, uint64_t &index) const
{
auto it = seqNumToTraceIndex.find(seqNum);
if (it != seqNumToTraceIndex.end()) {
index = it->second;
return true;
}
index = 0;
return false;
}
bool
TraceFetch::rollbackTraceReader(InstSeqNum seqNum, bool squash_itself)
{
if (!traceMode || !traceReader) {
DPRINTF(Fetch, "rollbackTraceReader[sn:%lli]: Not in trace mode\n", seqNum);
return false;
}
bool need_to_decrement_index = squash_itself;
// Find trace index to rollback to (1-based). We want the next getNextInstruction()
// to return the instruction at 'index'.
uint64_t index = findTraceIndexForSeqNum(seqNum);
bool found = index != 0;
if (!found) {
if (squash_itself) {
// If squashing the instruction itself, try one earlier
DPRINTF(Fetch,
"rollbackTraceReader[sn:%lli]: No mapped trace index, "
"trying earlier instruction\n",
seqNum);
index = findTraceIndexForSeqNum(seqNum - 1);
if (index != 0) {
found = true;
need_to_decrement_index = false; // already moved back
} else {
DPRINTF(Fetch, "rollbackTraceReader[sn:%lli]: No mapped trace index (skip)\n", seqNum);
return false;
}
}
}
if (need_to_decrement_index) {
// If squashing the instruction itself, we need to go back one more instruction
if (index > 0) {
DPRINTF(Fetch, "rollbackTraceReader[sn:%lli]: Squashing itself, moving back one instruction\n", seqNum);
--index;
} else {
DPRINTF(Fetch, "rollbackTraceReader[sn:%lli]: Cannot move back before start of trace\n", seqNum);
return false;
}
}
// 交由 TraceReader 软回滚(命中本地历史窗口则不触碰文件指针),超界时内部自行降级
const uint64_t seek_cursor = (index > 0) ? (index - 1) : 0;
const bool success = traceReader->softSeekToInstruction(seek_cursor);
DPRINTF(Fetch, "rollbackTraceReader[sn:%lli]: softSeekToInstruction(index=%lu,cursor=%lu) => %d\n",
seqNum, index, seek_cursor, (int)success);
return success;
}
bool
TraceFetch::validateBPPrediction(const o3::TraceInstruction& traceInstr,
Addr predictedPC, bool predictedTaken)
{
if (!traceInstr.getBranch()) {
// Non-branch instructions always "match" since there's no prediction to validate
return true;
}
bool traceWrong = (!traceInstr.getBranchTaken() && predictedTaken) || (
traceInstr.getBranchTaken() && traceInstr.getBranchTarget() != predictedPC);
DPRINTF(Fetch,
"validateBPPrediction: PC=0x%lx, predictedPC=0x%lx, actualTarget=0x%lx, "
"predictedTaken=%d, actualTaken=%d\n",
traceInstr.getPC(), predictedPC,