-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathfetch.cc
More file actions
2434 lines (2044 loc) · 79.8 KB
/
Copy pathfetch.cc
File metadata and controls
2434 lines (2044 loc) · 79.8 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) 2010-2014 ARM Limited
* Copyright (c) 2012-2013 AMD
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* 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/fetch.hh"
#include <algorithm>
#include <cstring>
#include <list>
#include <map>
#include <queue>
#include "arch/generic/tlb.hh"
#include "arch/riscv/decoder.hh"
#include "arch/riscv/pcstate.hh"
#include "base/debug_helper.hh"
#include "base/random.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/nop_static_inst.hh"
#include "cpu/o3/cpu.hh"
#include "cpu/o3/dyn_inst.hh"
#include "cpu/o3/limits.hh"
#include "cpu/o3/trace/TraceFetch.hh"
#include "cpu/pred/btb/decoupled_bpred.hh"
#include "debug/Activity.hh"
#include "debug/Counters.hh"
#include "debug/DecoupleBPProbe.hh"
#include "debug/Drain.hh"
#include "debug/Fetch.hh"
#include "debug/FetchFault.hh"
#include "debug/FetchVerbose.hh"
#include "debug/O3CPU.hh"
#include "debug/O3PipeView.hh"
#include "debug/TraceReader.hh"
#include "mem/packet.hh"
#include "params/BaseO3CPU.hh"
#include "sim/byteswap.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "sim/full_system.hh"
#include "sim/system.hh"
namespace gem5
{
namespace o3
{
Fetch::IcachePort::IcachePort(Fetch *_fetch, CPU *_cpu) :
RequestPort(_cpu->name() + ".icache_port", _cpu), fetch(_fetch)
{}
Fetch::Fetch(CPU *_cpu, const BaseO3CPUParams ¶ms)
: fetchPolicy(params.smtFetchPolicy),
cpu(_cpu),
branchPred(nullptr),
resolveQueueSize(params.resolveQueueSize),
decodeToFetchDelay(params.decodeToFetchDelay),
renameToFetchDelay(params.renameToFetchDelay),
iewToFetchDelay(params.iewToFetchDelay),
commitToFetchDelay(params.commitToFetchDelay),
fetchWidth(params.fetchWidth),
decodeWidth(params.decodeWidth),
retryPkt(),
retryTid(InvalidThreadID),
cacheBlkSize(cpu->cacheLineSize()),
fetchBufferSize(params.fetchBufferSize),
fetchQueueSize(params.fetchQueueSize),
numThreads(params.numThreads),
numFetchingThreads(params.smtNumFetchingThreads),
icachePort(this, _cpu),
finishTranslationEvent(this), fetchStats(_cpu, this)
{
if (numThreads > MaxThreads)
fatal("numThreads (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxThreads in src/cpu/o3/limits.hh\n",
numThreads, static_cast<int>(MaxThreads));
if (fetchWidth > MaxWidth)
fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxWidth in src/cpu/o3/limits.hh\n",
fetchWidth, static_cast<int>(MaxWidth));
for (int i = 0; i < MaxThreads; i++) {
setThreadStatus(i, Idle);
decoder[i] = nullptr;
pc[i].reset(params.isa[0]->newPCState());
macroop[i] = nullptr;
delayedCommit[i] = false;
stalls[i] = {false, false};
lastIcacheStall[i] = 0;
}
branchPred = params.branchPred;
// This fetch implementation only supports the decoupled frontend with the
// decoupled BTB predictor. Fail fast to avoid silently using legacy paths.
assert(branchPred);
assert(branchPred->isDecoupled());
assert(branchPred->isBTB());
dbpbtb =
dynamic_cast<branch_prediction::btb_pred::DecoupledBPUWithBTB*>(
branchPred);
assert(dbpbtb);
dbpbtb->setCpu(_cpu);
assert(params.decoder.size());
for (ThreadID tid = 0; tid < numThreads; tid++) {
decoder[tid] = params.decoder[tid];
// Set the size and allocate data for each fetch buffer instance
fetchBuffer[tid].size = fetchBufferSize;
fetchBuffer[tid].data = new uint8_t[fetchBufferSize];
}
// Get the size of an instruction.
// stallReason size should be the same as decodeWidth,renameWidth,dispWidth
stallReason.resize(decodeWidth, StallReason::NoStall);
traceFetch = std::make_unique<TraceFetch>(*this, params);
if (isTraceMode() && traceFetch && !traceFetch->allowDecoupledFrontend()) {
fatal("Trace mode requires allowDecoupledFrontend=true for decoupled+BTB-only fetch\n");
}
}
Fetch::~Fetch() = default;
bool
Fetch::isTraceMode() const
{
return traceFetch && traceFetch->enabled();
}
bool
Fetch::isTraceEOF() const
{
return traceFetch && traceFetch->isEOF();
}
std::string Fetch::name() const { return cpu->name() + ".fetch"; }
void
Fetch::regProbePoints()
{
ppFetch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Fetch");
ppFetchRequestSent = new ProbePointArg<RequestPtr>(cpu->getProbeManager(),
"FetchRequest");
}
Fetch::FetchStatGroup::FetchStatGroup(CPU *cpu, Fetch *fetch)
: statistics::Group(cpu, "fetch"),
ADD_STAT(icacheStallCycles, statistics::units::Cycle::get(),
"Number of cycles fetch is stalled on an Icache miss"),
ADD_STAT(insts, statistics::units::Count::get(),
"Number of instructions fetch has processed"),
ADD_STAT(branches, statistics::units::Count::get(),
"Number of branches that fetch encountered"),
ADD_STAT(predictedBranches, statistics::units::Count::get(),
"Number of branches that fetch has predicted taken"),
ADD_STAT(cycles, statistics::units::Cycle::get(),
"Number of cycles fetch has run and was not squashing or "
"blocked"),
ADD_STAT(squashCycles, statistics::units::Cycle::get(),
"Number of cycles fetch has spent squashing"),
ADD_STAT(tlbCycles, statistics::units::Cycle::get(),
"Number of cycles fetch has spent waiting for tlb"),
ADD_STAT(idleCycles, statistics::units::Cycle::get(),
"Number of cycles fetch was idle"),
ADD_STAT(blockedCycles, statistics::units::Cycle::get(),
"Number of cycles fetch has spent blocked"),
ADD_STAT(miscStallCycles, statistics::units::Cycle::get(),
"Number of cycles fetch has spent waiting on interrupts, or bad "
"addresses, or out of MSHRs"),
ADD_STAT(pendingDrainCycles, statistics::units::Cycle::get(),
"Number of cycles fetch has spent waiting on pipes to drain"),
ADD_STAT(noActiveThreadStallCycles, statistics::units::Cycle::get(),
"Number of stall cycles due to no active thread to fetch from"),
ADD_STAT(pendingTrapStallCycles, statistics::units::Cycle::get(),
"Number of stall cycles due to pending traps"),
ADD_STAT(pendingQuiesceStallCycles, statistics::units::Cycle::get(),
"Number of stall cycles due to pending quiesce instructions"),
ADD_STAT(icacheWaitRetryStallCycles, statistics::units::Cycle::get(),
"Number of stall cycles due to full MSHR"),
ADD_STAT(cacheLines, statistics::units::Count::get(),
"Number of cache lines fetched"),
ADD_STAT(icacheSquashes, statistics::units::Count::get(),
"Number of outstanding Icache misses that were squashed"),
ADD_STAT(tlbSquashes, statistics::units::Count::get(),
"Number of outstanding ITLB misses that were squashed"),
ADD_STAT(nisnDist, statistics::units::Count::get(),
"Number of instructions fetched each cycle (Total)"),
ADD_STAT(idleRate, statistics::units::Ratio::get(),
"Ratio of cycles fetch was idle",
idleCycles / cpu->baseStats.numCycles),
ADD_STAT(branchRate, statistics::units::Ratio::get(),
"Number of branch fetches per cycle",
branches / cpu->baseStats.numCycles),
ADD_STAT(rate, statistics::units::Rate<
statistics::units::Count, statistics::units::Cycle>::get(),
"Number of inst fetches per cycle",
insts / cpu->baseStats.numCycles),
ADD_STAT(fetchStatusDist, statistics::units::Count::get(),
"Distribution of fetch status"),
ADD_STAT(decodeStalls, statistics::units::Count::get(),
"Number of decode stalls"),
ADD_STAT(decodeStallRate, statistics::units::Rate<
statistics::units::Count, statistics::units::Cycle>::get(),
"Number of decode stalls per cycle",
decodeStalls / cpu->baseStats.numCycles),
ADD_STAT(fetchBubbles, statistics::units::Count::get(),
"Unutilized issue-pipeline slots while there is no backend-stall"),
ADD_STAT(fetchBubbles_max, statistics::units::Count::get(),
"Cycles that fetch 0 instruction while there is no backend-stall"),
ADD_STAT(frontendBound, statistics::units::Rate<
statistics::units::Count, statistics::units::Cycle>::get(),
"Frontend Bound",
fetchBubbles / (cpu->baseStats.numCycles * fetch->decodeWidth)),
ADD_STAT(frontendLatencyBound, statistics::units::Rate<
statistics::units::Count, statistics::units::Cycle>::get(),
"Frontend Latency Bound",
fetchBubbles_max / cpu->baseStats.numCycles),
ADD_STAT(frontendBandwidthBound, statistics::units::Rate<
statistics::units::Count, statistics::units::Cycle>::get(),
"Frontend Bandwidth Bound",
frontendBound - frontendLatencyBound),
ADD_STAT(resolveQueueFullEvents, statistics::units::Count::get(),
"Number of events the resolve queue becomes full"),
ADD_STAT(resolveEnqueueFailEvent, statistics::units::Count::get(),
"Number of times an entry could not be enqueued to the resolve queue"),
ADD_STAT(resolveDequeueCount, statistics::units::Count::get(),
"Number of times an entry is dequeued from the resolve queue"),
ADD_STAT(resolveEnqueueCount, statistics::units::Count::get(),
"Number of times an entry is enqueued to the resolve queue"),
ADD_STAT(resolveQueueOccupancy, statistics::units::Count::get(),
"Number of entries in the resolve queue"),
ADD_STAT(traceMetaStores, statistics::units::Count::get(),
"Number of stored trace metadata records (seqNum -> traceInst)"),
ADD_STAT(traceMetaCleanupSquashCalls, statistics::units::Count::get(),
"Number of times cleanup was called due to squash/rollback"),
ADD_STAT(traceMetaCleanupSquashEntries, statistics::units::Count::get(),
"Total entries erased by squash/rollback cleanups"),
ADD_STAT(traceMetaCleanupCommitCalls, statistics::units::Count::get(),
"Number of times cleanup was called on successful commit")
{
icacheStallCycles
.prereq(icacheStallCycles);
insts
.prereq(insts);
branches
.prereq(branches);
predictedBranches
.prereq(predictedBranches);
cycles
.prereq(cycles);
squashCycles
.prereq(squashCycles);
tlbCycles
.prereq(tlbCycles);
idleCycles
.prereq(idleCycles);
blockedCycles
.prereq(blockedCycles);
cacheLines
.prereq(cacheLines);
miscStallCycles
.prereq(miscStallCycles);
pendingDrainCycles
.prereq(pendingDrainCycles);
noActiveThreadStallCycles
.prereq(noActiveThreadStallCycles);
pendingTrapStallCycles
.prereq(pendingTrapStallCycles);
pendingQuiesceStallCycles
.prereq(pendingQuiesceStallCycles);
icacheWaitRetryStallCycles
.prereq(icacheWaitRetryStallCycles);
icacheSquashes
.prereq(icacheSquashes);
tlbSquashes
.prereq(tlbSquashes);
nisnDist
.init(/* base value */ 0,
/* last value */ fetch->fetchWidth,
/* bucket size */ 1)
.flags(statistics::pdf);
idleRate
.prereq(idleRate);
branchRate
.flags(statistics::total);
rate
.flags(statistics::total);
fetchStatusDist
.init(NumFetchStatus)
.flags(statistics::pdf | statistics::total);
for (int i = 0; i < NumFetchStatus; i++) {
fetchStatusDist.subname(i, fetch->fetchStatusStr[static_cast<Fetch::ThreadStatus>(i)]);
}
decodeStalls
.prereq(decodeStalls);
decodeStallRate
.flags(statistics::total);
fetchBubbles
.prereq(fetchBubbles);
fetchBubbles_max
.prereq(fetchBubbles_max);
frontendBound
.flags(statistics::total);
frontendLatencyBound
.flags(statistics::total);
frontendBandwidthBound
.flags(statistics::total);
resolveEnqueueCount
.init(1, 8, 1);
resolveQueueOccupancy
.init(0, 32, 1);
traceMetaStores
.prereq(traceMetaStores);
traceMetaCleanupSquashCalls
.prereq(traceMetaCleanupSquashCalls);
traceMetaCleanupSquashEntries
.prereq(traceMetaCleanupSquashEntries);
traceMetaCleanupCommitCalls
.prereq(traceMetaCleanupCommitCalls);
}
void
Fetch::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
{
timeBuffer = time_buffer;
// Create wires to get information from proper places in time buffer.
fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
fromRename = timeBuffer->getWire(-renameToFetchDelay);
fromIEW = timeBuffer->getWire(-iewToFetchDelay);
fromCommit = timeBuffer->getWire(-commitToFetchDelay);
}
void
Fetch::setActiveThreads(std::list<ThreadID> *at_ptr)
{
activeThreads = at_ptr;
}
void
Fetch::setFetchQueue(TimeBuffer<FetchStruct> *ftb_ptr)
{
// Create wire to write information to proper place in fetch time buf.
toDecode = ftb_ptr->getWire(0);
// initialize to toDecode stall vector
toDecode->fetchStallReason = stallReason;
}
void
Fetch::startupStage()
{
assert(priorityList.empty());
resetStage();
// Fetch needs to start fetching instructions at the very beginning,
// so it must start up in active state.
switchToActive();
if (isTraceMode() && !traceFetch->initTraceMode()) {
fatal("Failed to initialize trace mode\n");
}
}
void
Fetch::clearStates(ThreadID tid)
{
setThreadStatus(tid, Running);
set(pc[tid], cpu->pcState(tid));
macroop[tid] = NULL;
delayedCommit[tid] = false;
cacheReq[tid].reset();
stalls[tid].decode = false;
stalls[tid].drain = false;
fetchBuffer[tid].reset();
fetchQueue[tid].clear();
// TODO not sure what to do with priorityList for now
// priorityList.push_back(tid);
}
void
Fetch::resetStage()
{
numInst = 0;
interruptPending = false;
cacheBlocked = false;
priorityList.clear();
// Setup PC and nextPC with initial state.
for (ThreadID tid = 0; tid < numThreads; ++tid) {
setThreadStatus(tid, Running);
set(pc[tid], cpu->pcState(tid));
macroop[tid] = NULL;
delayedCommit[tid] = false;
cacheReq[tid].reset();
stalls[tid].decode = false;
stalls[tid].drain = false;
fetchBuffer[tid].reset();
ftqEntryFetchedInsts[tid] = 0;
fetchQueue[tid].clear();
priorityList.push_back(tid);
}
wroteToTimeBuffer = false;
_status = Inactive;
if (traceFetch) {
traceFetch->resetStage();
}
assert(dbpbtb);
dbpbtb->resetPC(pc[0]->instAddr());
}
bool
Fetch::handleMultiCacheLineFetch(Addr vaddr, ThreadID tid, Addr pc)
{
DPRINTF(Fetch, "[tid:%i] Handling multi-cacheline fetch for addr %#x, pc=%#lx\n", tid, vaddr, pc);
// Transition to WaitingCache state when initiating cache access
setThreadStatus(tid, WaitingCache);
// Reset cache request state for this thread
cacheReq[tid].reset();
cacheReq[tid].baseAddr = vaddr;
cacheReq[tid].totalSize = fetchBufferSize;
Addr fetchPC = vaddr;
unsigned fetchSize = cacheBlkSize - fetchPC % cacheBlkSize; // Size for first cache line
DPRINTF(Fetch, "[tid:%i] Creating first cache line request: addr=%#x, size=%d\n",
tid, fetchPC, fetchSize);
// Create and send first request (tail of first cache line)
RequestPtr first_mem_req = std::make_shared<Request>(
fetchPC, fetchSize,
Request::INST_FETCH, cpu->instRequestorId(), pc,
cpu->thread[tid]->contextId());
first_mem_req->taskId(cpu->taskId());
first_mem_req->setMisalignedFetch();
first_mem_req->setReqNum(1);
cacheReq[tid].addRequest(first_mem_req); // packet will be created later
// Initiate translation for first request
updateCacheRequestStatusByRequest(tid, first_mem_req, TlbWait);
setAllFetchStalls(StallReason::ITlbStall);
FetchTranslation *trans = new FetchTranslation(this);
cpu->mmu->translateTiming(first_mem_req, cpu->thread[tid]->getTC(),
trans, BaseMMU::Execute);
// Prepare second request (head of second cache line)
fetchPC += fetchSize; // Move to start of next cache line
assert(fetchPC % cacheBlkSize == 0);
fetchSize = fetchBufferSize - fetchSize; // Remaining size
DPRINTF(Fetch, "[tid:%i] Creating second cache line request: addr=%#x, size=%d\n",
tid, fetchPC, fetchSize);
// Create and send second request
RequestPtr second_mem_req = std::make_shared<Request>(
fetchPC, fetchSize,
Request::INST_FETCH, cpu->instRequestorId(), pc,
cpu->thread[tid]->contextId());
second_mem_req->taskId(cpu->taskId());
second_mem_req->setMisalignedFetch();
second_mem_req->setReqNum(2);
cacheReq[tid].addRequest(second_mem_req); // Add second request to cache request
DPRINTF(Fetch, "[tid:%i] Initiating translation for second cache line\n", tid);
// Always initiate translation for second request, regardless of first request status
updateCacheRequestStatusByRequest(tid, second_mem_req, TlbWait);
setAllFetchStalls(StallReason::ITlbStall);
FetchTranslation *trans2 = new FetchTranslation(this);
cpu->mmu->translateTiming(second_mem_req, cpu->thread[tid]->getTC(),
trans2, BaseMMU::Execute);
return true;
}
bool
Fetch::processMultiCacheLineCompletion(ThreadID tid, PacketPtr pkt)
{
DPRINTF(Fetch, "[tid:%i] Processing dual cacheline fetch completion for addr %#lx.\n",
tid, pkt->getAddr());
// Mark this packet as completed in the cache request (this also stores the packet)
bool found_packet = cacheReq[tid].markCompletedAndStorePacket(pkt);
if (!found_packet) {
DPRINTF(Fetch, "[tid:%i] Packet doesn't match current requests, deleting pkt %#lx\n",
tid, pkt->getAddr());
DPRINTF(Fetch, "[tid:%i] Expected requests: ", tid);
for (size_t i = 0; i < cacheReq[tid].requests.size(); i++) {
DPRINTF(Fetch, "req[%d]=0x%lx ", i, cacheReq[tid].requests[i]->getVaddr());
}
DPRINTF(Fetch, "\n");
return false;
}
DPRINTF(Fetch, "[tid:%i] Packet successfully matched and stored. Current status: %s\n",
tid, cacheReq[tid].getStatusSummary().c_str());
// Check if we're still waiting for other packets
if (!cacheReq[tid].allCompleted()) {
DPRINTF(Fetch, "[tid:%i] Waiting for remaining packets. Completed: %d, Total: %d\n",
tid, cacheReq[tid].completedPackets, cacheReq[tid].packets.size());
// Note: retry is handled completely by the standard gem5 recvReqRetry mechanism
// No need to handle retry here to avoid duplicate packet sending
return false; // Return false to indicate we're still waiting
}
// All packets have arrived - merge them directly into fetchBuffer
DPRINTF(Fetch, "[tid:%i] All packets arrived, merging data into fetchBuffer.\n", tid);
// Find the packets by request number
PacketPtr firstPkt = nullptr;
PacketPtr secondPkt = nullptr;
for (size_t i = 0; i < cacheReq[tid].packets.size(); i++) {
if (cacheReq[tid].requests[i]->getReqNum() == 1) {
firstPkt = cacheReq[tid].packets[i];
} else if (cacheReq[tid].requests[i]->getReqNum() == 2) {
secondPkt = cacheReq[tid].packets[i];
}
}
assert(firstPkt && secondPkt);
// Copy merged data directly into fetchBuffer
memcpy(fetchBuffer[tid].data, firstPkt->getConstPtr<uint8_t>(), firstPkt->getSize());
memcpy(fetchBuffer[tid].data + firstPkt->getSize(), secondPkt->getConstPtr<uint8_t>(), secondPkt->getSize());
fetchBuffer[tid].valid = true;
// Clean up the packets
delete firstPkt;
delete secondPkt;
DPRINTF(Fetch, "[tid:%i] Dual cacheline fetch completion processed successfully.\n", tid);
return true;
}
void
Fetch::processCacheCompletion(PacketPtr pkt)
{
ThreadID tid = cpu->contextToThread(pkt->req->contextId());
assert(pkt->req->isMisalignedFetch() && "Only multi-cacheline fetch is supported");
bool allCompleted = processMultiCacheLineCompletion(tid, pkt);
// If we're still waiting for another packet, return early
if (!allCompleted) {
return;
}
// Check if this completion should be processed
// Either thread is waiting for cache, or cache just completed
CacheRequestStatus cacheStatus = cacheReq[tid].getOverallStatus();
if (!hasPendingCacheRequests(tid) && cacheStatus != AccessComplete) {
DPRINTF(Fetch, "[tid:%i] Thread not waiting for cache and no completion, ignoring\n", tid);
++fetchStats.icacheSquashes;
return;
}
// Data has been merged into fetchBuffer, we can proceed
DPRINTF(Fetch, "[tid:%i] All misaligned packets received and merged.\n", tid);
assert(!cpu->switchedOut());
// Trace 按需消费:不在 icache 完成时写入 trace 指令码,避免批量消费。
if (isTraceMode()) {
DPRINTF(TraceReader,
"[TRACE] Icache completion: keep timing only; no trace bytes injection\n");
}
// Verify fetchBufferPC alignment with the supplying FSQ entry.
if (fetchBuffer[tid].valid && dbpbtb->ftqHasHead()) {
const auto &stream = dbpbtb->ftqHead();
if (fetchBuffer[tid].startPC != stream.startPC) {
panic("fetchBufferPC %#x should be aligned with FSQ startPC %#x",
fetchBuffer[tid].startPC, stream.startPC);
}
}
// Wake up the CPU (if it went to sleep and was waiting on
// this completion event).
cpu->wakeCPU();
DPRINTF(Activity, "[tid:%i] Activating fetch due to cache completion\n",
tid);
switchToActive();
// Complete cache request and transition to appropriate state
if (checkStall(tid)) {
setThreadStatus(tid, Blocked);
} else {
// Transition from WaitingCache back to Running when cache access completes
setThreadStatus(tid, Running);
}
}
void
Fetch::drainResume()
{
for (ThreadID i = 0; i < numThreads; ++i) {
stalls[i].decode = false;
stalls[i].drain = false;
}
}
void
Fetch::drainSanityCheck() const
{
assert(isDrained());
assert(retryPkt.size() == 0);
assert(retryTid == InvalidThreadID);
assert(!cacheBlocked);
assert(!interruptPending);
for (ThreadID i = 0; i < numThreads; ++i) {
assert(cacheReq[i].packets.empty());
assert(fetchStatus[i] == Idle || stalls[i].drain);
}
branchPred->drainSanityCheck();
}
bool
Fetch::isDrained() const
{
/* Make sure that threads are either idle of that the commit stage
* has signaled that draining has completed by setting the drain
* stall flag. This effectively forces the pipeline to be disabled
* until the whole system is drained (simulation may continue to
* drain other components).
*/
for (ThreadID i = 0; i < numThreads; ++i) {
// Verify fetch queues are drained
if (!fetchQueue[i].empty())
return false;
// Return false if not idle or drain stalled
if (fetchStatus[i] != Idle) {
if (fetchStatus[i] == Blocked && stalls[i].drain)
continue;
else
return false;
}
}
/* The pipeline might start up again in the middle of the drain
* cycle if the finish translation event is scheduled, so make
* sure that's not the case.
*/
return !finishTranslationEvent.scheduled();
}
void
Fetch::takeOverFrom()
{
assert(cpu->getInstPort().isConnected());
resetStage();
}
void
Fetch::drainStall(ThreadID tid)
{
assert(cpu->isDraining());
assert(!stalls[tid].drain);
DPRINTF(Drain, "%i: Thread drained.\n", tid);
stalls[tid].drain = true;
}
void
Fetch::wakeFromQuiesce()
{
DPRINTF(Fetch, "Waking up from quiesce\n");
// Hopefully this is safe
// @todo: Allow other threads to wake from quiesce.
setThreadStatus(0, Running);
}
void
Fetch::switchToActive()
{
if (_status == Inactive) {
DPRINTF(Activity, "Activating stage.\n");
cpu->activateStage(CPU::FetchIdx);
_status = Active;
}
}
void
Fetch::switchToInactive()
{
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(CPU::FetchIdx);
_status = Inactive;
}
}
void
Fetch::deactivateThread(ThreadID tid)
{
// Update priority list
auto thread_it = std::find(priorityList.begin(), priorityList.end(), tid);
if (thread_it != priorityList.end()) {
priorityList.erase(thread_it);
}
}
bool
Fetch::lookupAndUpdateNextPC(const DynInstPtr &inst, PCStateBase &next_pc)
{
// Do branch prediction check here.
// A bit of a misnomer...next_PC is actually the current PC until
// this function updates it.
bool predict_taken = false;
// Decoupled+BTB-only: compute next PC directly from the supplying FSQ entry.
ThreadID tid = inst->threadNumber;
assert(dbpbtb);
assert(dbpbtb->ftqHasHead());
const auto &stream = dbpbtb->ftqHead();
const Addr curr_pc = next_pc.instAddr();
assert(stream.startPC <= curr_pc && curr_pc < stream.predEndPC);
bool run_out = false;
// Taken when the current PC matches the predicted control PC.
predict_taken = stream.predTaken && (curr_pc == stream.predBranchInfo.pc);
if (predict_taken) {
auto &rpc = next_pc.as<GenericISA::PCStateWithNext>();
rpc.pc(stream.predBranchInfo.target);
rpc.npc(stream.predBranchInfo.target + 4);
rpc.uReset();
run_out = true;
} else if (inst->staticInst->isMicroop()) {
// Microops must advance uPC explicitly; they do not rely on decoder NPC.
inst->staticInst->advancePC(next_pc);
run_out = next_pc.instAddr() >= stream.predEndPC;
} else {
// Sequential fetch: decoder already computed npc with correct inst size.
auto &rpc = next_pc.as<RiscvISA::PCState>();
const Addr fall_thru = rpc.npc();
rpc.pc(fall_thru);
// Placeholder; decoder will overwrite npc on the next decode.
rpc.npc(fall_thru + 4);
rpc.uReset();
run_out = fall_thru >= stream.predEndPC;
}
// Track how many dynamic instructions were fetched for this (legacy) FTQ/FSQ entry.
ftqEntryFetchedInsts[tid]++;
if (run_out) {
dbpbtb->consumeFetchTarget(ftqEntryFetchedInsts[tid]);
ftqEntryFetchedInsts[tid] = 0;
fetchBuffer[tid].valid = false;
DPRINTF(DecoupleBP, "Used up fetch targets.\n");
}
inst->setLoopIteration(currentLoopIter);
// For decoupled frontend, the instruction type is predicted with BTB
if (!predict_taken) {
inst->setPredTarg(next_pc);
inst->setPredTaken(false);
return false;
}
DPRINTF(Fetch, "[tid:%i] [sn:%llu] Branch at PC %#x predicted to be taken to %s\n",
tid, inst->seqNum, inst->pcState().instAddr(), next_pc);
DPRINTF(Fetch, "[tid:%i] [sn:%llu] Branch at PC %#x "
"predicted to go to %s\n",
tid, inst->seqNum, inst->pcState().instAddr(), next_pc);
inst->setPredTarg(next_pc);
inst->setPredTaken(predict_taken);
++fetchStats.branches;
if (predict_taken) {
++fetchStats.predictedBranches;
}
return predict_taken;
}
bool
Fetch::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
{
assert(!cpu->switchedOut());
// Check for blocking conditions
if (cacheBlocked) {
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n", tid);
setAllFetchStalls(StallReason::IcacheStall);
return false;
} else if (checkInterrupt(pc) && !delayedCommit[tid]) {
// Hold off fetch from getting new instructions when:
// Cache is blocked, or
// while an interrupt is pending and we're not in PAL mode, or
// fetch is switched out.
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n", tid);
setAllFetchStalls(StallReason::IntStall);
return false;
}
DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x, pc=%#lx\n",
tid, vaddr, vaddr, pc);
// With 66-byte fetchBufferSize, we always need to access 2 cache lines
return handleMultiCacheLineFetch(vaddr, tid, pc);
}
bool
Fetch::validateTranslationRequest(ThreadID tid, const RequestPtr &mem_req)
{
// Check if this request belongs to current cache request
bool isExpectedReq = false;
for (size_t i = 0; i < cacheReq[tid].requests.size(); i++) {
if (mem_req == cacheReq[tid].requests[i]) {
isExpectedReq = true;
break;
}
}
// Check if request should be processed using new state system
if (!isExpectedReq || !hasPendingCacheRequests(tid)) {
DPRINTF(Fetch, "[tid:%i] Ignoring translation completed after squash or unexpected request\n", tid);
DPRINTF(Fetch, "[tid:%i] Ignoring req addr=%#lx\n", tid, mem_req->getVaddr());
++fetchStats.tlbSquashes;
return false;
}
return true;
}
void
Fetch::handleSuccessfulTranslation(ThreadID tid, const RequestPtr &mem_req, Addr fetchPC)
{
// Check that we're not going off into random memory
if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
DPRINTF(Fetch, "Address %#x is outside of physical memory, stopping fetch, %lu\n",
mem_req->getPaddr(), curTick());
// Update cache request status using new interface
updateCacheRequestStatusByRequest(tid, mem_req, AccessFailed);
setAllFetchStalls(StallReason::OtherFetchStall);
// Note: Don't reset here, let the caller handle cleanup based on overall status
return;
}
// Build packet here.
PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
data_pkt->dataDynamic(new uint8_t[fetchBufferSize]);
// All requests are multi-cacheline, always set send right away
data_pkt->setSendRightAway();
DPRINTF(Fetch, "[tid:%i] Fetching data for addr %#x, pc=%#lx\n",
tid, mem_req->getVaddr(), fetchPC);
fetchBuffer[tid].startPC = fetchPC;
fetchBuffer[tid].valid = false;
DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
fetchStats.cacheLines++;
// Access the cache.
if (!icachePort.sendTimingReq(data_pkt)) {
DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
// Update cache request status using new interface
updateCacheRequestStatusByRequest(tid, mem_req, CacheWaitRetry);
data_pkt->setRetriedPkt();
DPRINTF(Fetch, "[tid:%i] mem_req.addr=%#lx needs retry.\n", tid,
mem_req->getVaddr());
setAllFetchStalls(StallReason::IcacheStall);
retryPkt.push_back(data_pkt);
retryTid = tid;
cacheBlocked = true;
} else {
DPRINTF(Fetch, "[tid:%i] Doing Icache access.\n", tid);
DPRINTF(Activity, "[tid:%i] Activity: Waiting on I-cache response.\n", tid);
lastIcacheStall[tid] = curTick();
// Update cache request status using new interface
updateCacheRequestStatusByRequest(tid, mem_req, CacheWaitResponse);
setAllFetchStalls(StallReason::IcacheStall);
// Notify Fetch Request probe when a packet containing a fetch request is successfully sent
ppFetchRequestSent->notify(mem_req);
}
}
void
Fetch::handleTranslationFault(ThreadID tid, const RequestPtr &mem_req, const Fault &fault)
{
DPRINTF(FetchFault, "fault, mem_req.addr=%#lx\n", mem_req->getVaddr());
// Don't send an instruction to decode if we can't handle it.
if (!(numInst < fetchWidth) || !(fetchQueue[tid].size() < fetchQueueSize)) {
if (finishTranslationEvent.scheduled() && finishTranslationEvent.getReq() != mem_req) {
DPRINTF(FetchFault, "fault, finishTranslationEvent.getReq().addr=%#lx, mem_req.addr=%#lx\n",
finishTranslationEvent.getReq()->getVaddr(), mem_req->getVaddr());
return;
}
assert(!finishTranslationEvent.scheduled());
finishTranslationEvent.setFault(fault);
finishTranslationEvent.setReq(mem_req);
cpu->schedule(finishTranslationEvent, cpu->clockEdge(Cycles(1)));
return;
}
DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected base addr %#x\n",
tid, mem_req->getVaddr(), cacheReq[tid].baseAddr);
// Update new cache request status system
updateCacheRequestStatusByRequest(tid, mem_req, AccessFailed);
// Translation faulted, icache request won't be sent.
cacheReq[tid].reset();
// Send the fault to commit. This thread will not do anything
// until commit handles the fault. The only other way it can
// wake up is if a squash comes along and changes the PC.
const PCStateBase &fetch_pc = *pc[tid];
DPRINTF(Fetch, "[tid:%i] Translation faulted, building noop.\n", tid);
// We will use a nop in order to carry the fault.
DynInstPtr instruction = buildInst(tid, nopStaticInstPtr, nullptr,
fetch_pc, fetch_pc, false);
instruction->setVersion(localSquashVer);
instruction->setNotAnInst();
instruction->setPredTarg(fetch_pc);
instruction->fault = fault;
std::unique_ptr<PCStateBase> next_pc(fetch_pc.clone());
instruction->staticInst->advancePC(*next_pc);