forked from zlfben/gem5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdram_ctrl.cc
2287 lines (1932 loc) · 81.8 KB
/
dram_ctrl.cc
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
* 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) 2013 Amin Farmahini-Farahani
* 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.
*
* Authors: Andreas Hansson
* Ani Udipi
* Neha Agarwal
* Omar Naji
*/
#include "base/bitfield.hh"
#include "base/trace.hh"
#include "debug/DRAM.hh"
#include "debug/DRAMPower.hh"
#include "debug/DRAMState.hh"
#include "debug/Drain.hh"
#include "mem/dram_ctrl.hh"
#include "sim/system.hh"
using namespace std;
using namespace Data;
DRAMCtrl::DRAMCtrl(const DRAMCtrlParams* p) :
AbstractMemory(p),
port(name() + ".port", *this), isTimingMode(false),
retryRdReq(false), retryWrReq(false),
busState(READ),
nextReqEvent(this), respondEvent(this),
drainManager(NULL),
deviceSize(p->device_size),
deviceBusWidth(p->device_bus_width), burstLength(p->burst_length),
deviceRowBufferSize(p->device_rowbuffer_size),
devicesPerRank(p->devices_per_rank),
burstSize((devicesPerRank * burstLength * deviceBusWidth) / 8),
rowBufferSize(devicesPerRank * deviceRowBufferSize),
columnsPerRowBuffer(rowBufferSize / burstSize),
columnsPerStripe(range.interleaved() ? range.granularity() / burstSize : 1),
ranksPerChannel(p->ranks_per_channel),
bankGroupsPerRank(p->bank_groups_per_rank),
bankGroupArch(p->bank_groups_per_rank > 0),
banksPerRank(p->banks_per_rank), channels(p->channels), rowsPerBank(0),
readBufferSize(p->read_buffer_size),
writeBufferSize(p->write_buffer_size),
writeHighThreshold(writeBufferSize * p->write_high_thresh_perc / 100.0),
writeLowThreshold(writeBufferSize * p->write_low_thresh_perc / 100.0),
minWritesPerSwitch(p->min_writes_per_switch),
writesThisTime(0), readsThisTime(0),
tCK(p->tCK), tWTR(p->tWTR), tRTW(p->tRTW), tCS(p->tCS), tBURST(p->tBURST),
tCCD_L(p->tCCD_L), tRCD(p->tRCD), tCL(p->tCL), tRP(p->tRP), tRAS(p->tRAS),
tWR(p->tWR), tRTP(p->tRTP), tRFC(p->tRFC), tREFI(p->tREFI), tRRD(p->tRRD),
tRRD_L(p->tRRD_L), tXAW(p->tXAW), activationLimit(p->activation_limit),
memSchedPolicy(p->mem_sched_policy), addrMapping(p->addr_mapping),
pageMgmt(p->page_policy),
maxAccessesPerRow(p->max_accesses_per_row),
frontendLatency(p->static_frontend_latency),
backendLatency(p->static_backend_latency),
busBusyUntil(0), prevArrival(0),
nextReqTime(0), activeRank(0), timeStampOffset(0)
{
// sanity check the ranks since we rely on bit slicing for the
// address decoding
fatal_if(!isPowerOf2(ranksPerChannel), "DRAM rank count of %d is not "
"allowed, must be a power of two\n", ranksPerChannel);
for (int i = 0; i < ranksPerChannel; i++) {
Rank* rank = new Rank(*this, p);
ranks.push_back(rank);
rank->actTicks.resize(activationLimit, 0);
rank->banks.resize(banksPerRank);
rank->rank = i;
for (int b = 0; b < banksPerRank; b++) {
rank->banks[b].bank = b;
// GDDR addressing of banks to BG is linear.
// Here we assume that all DRAM generations address bank groups as
// follows:
if (bankGroupArch) {
// Simply assign lower bits to bank group in order to
// rotate across bank groups as banks are incremented
// e.g. with 4 banks per bank group and 16 banks total:
// banks 0,4,8,12 are in bank group 0
// banks 1,5,9,13 are in bank group 1
// banks 2,6,10,14 are in bank group 2
// banks 3,7,11,15 are in bank group 3
rank->banks[b].bankgr = b % bankGroupsPerRank;
} else {
// No bank groups; simply assign to bank number
rank->banks[b].bankgr = b;
}
}
}
// perform a basic check of the write thresholds
if (p->write_low_thresh_perc >= p->write_high_thresh_perc)
fatal("Write buffer low threshold %d must be smaller than the "
"high threshold %d\n", p->write_low_thresh_perc,
p->write_high_thresh_perc);
// determine the rows per bank by looking at the total capacity
uint64_t capacity = ULL(1) << ceilLog2(AbstractMemory::size());
// determine the dram actual capacity from the DRAM config in Mbytes
uint64_t deviceCapacity = deviceSize / (1024 * 1024) * devicesPerRank *
ranksPerChannel;
// if actual DRAM size does not match memory capacity in system warn!
if (deviceCapacity != capacity / (1024 * 1024))
warn("DRAM device capacity (%d Mbytes) does not match the "
"address range assigned (%d Mbytes)\n", deviceCapacity,
capacity / (1024 * 1024));
DPRINTF(DRAM, "Memory capacity %lld (%lld) bytes\n", capacity,
AbstractMemory::size());
DPRINTF(DRAM, "Row buffer size %d bytes with %d columns per row buffer\n",
rowBufferSize, columnsPerRowBuffer);
rowsPerBank = capacity / (rowBufferSize * banksPerRank * ranksPerChannel);
// some basic sanity checks
if (tREFI <= tRP || tREFI <= tRFC) {
fatal("tREFI (%d) must be larger than tRP (%d) and tRFC (%d)\n",
tREFI, tRP, tRFC);
}
// basic bank group architecture checks ->
if (bankGroupArch) {
// must have at least one bank per bank group
if (bankGroupsPerRank > banksPerRank) {
fatal("banks per rank (%d) must be equal to or larger than "
"banks groups per rank (%d)\n",
banksPerRank, bankGroupsPerRank);
}
// must have same number of banks in each bank group
if ((banksPerRank % bankGroupsPerRank) != 0) {
fatal("Banks per rank (%d) must be evenly divisible by bank groups "
"per rank (%d) for equal banks per bank group\n",
banksPerRank, bankGroupsPerRank);
}
// tCCD_L should be greater than minimal, back-to-back burst delay
if (tCCD_L <= tBURST) {
fatal("tCCD_L (%d) should be larger than tBURST (%d) when "
"bank groups per rank (%d) is greater than 1\n",
tCCD_L, tBURST, bankGroupsPerRank);
}
// tRRD_L is greater than minimal, same bank group ACT-to-ACT delay
// some datasheets might specify it equal to tRRD
if (tRRD_L < tRRD) {
fatal("tRRD_L (%d) should be larger than tRRD (%d) when "
"bank groups per rank (%d) is greater than 1\n",
tRRD_L, tRRD, bankGroupsPerRank);
}
}
}
void
DRAMCtrl::init()
{
AbstractMemory::init();
if (!port.isConnected()) {
fatal("DRAMCtrl %s is unconnected!\n", name());
} else {
port.sendRangeChange();
}
// a bit of sanity checks on the interleaving, save it for here to
// ensure that the system pointer is initialised
if (range.interleaved()) {
if (channels != range.stripes())
fatal("%s has %d interleaved address stripes but %d channel(s)\n",
name(), range.stripes(), channels);
if (addrMapping == Enums::RoRaBaChCo) {
if (rowBufferSize != range.granularity()) {
fatal("Channel interleaving of %s doesn't match RoRaBaChCo "
"address map\n", name());
}
} else if (addrMapping == Enums::RoRaBaCoCh ||
addrMapping == Enums::RoCoRaBaCh) {
// for the interleavings with channel bits in the bottom,
// if the system uses a channel striping granularity that
// is larger than the DRAM burst size, then map the
// sequential accesses within a stripe to a number of
// columns in the DRAM, effectively placing some of the
// lower-order column bits as the least-significant bits
// of the address (above the ones denoting the burst size)
assert(columnsPerStripe >= 1);
// channel striping has to be done at a granularity that
// is equal or larger to a cache line
if (system()->cacheLineSize() > range.granularity()) {
fatal("Channel interleaving of %s must be at least as large "
"as the cache line size\n", name());
}
// ...and equal or smaller than the row-buffer size
if (rowBufferSize < range.granularity()) {
fatal("Channel interleaving of %s must be at most as large "
"as the row-buffer size\n", name());
}
// this is essentially the check above, so just to be sure
assert(columnsPerStripe <= columnsPerRowBuffer);
}
}
}
void
DRAMCtrl::startup()
{
// remember the memory system mode of operation
isTimingMode = system()->isTimingMode();
if (isTimingMode) {
// timestamp offset should be in clock cycles for DRAMPower
timeStampOffset = divCeil(curTick(), tCK);
// update the start tick for the precharge accounting to the
// current tick
for (auto r : ranks) {
r->startup(curTick() + tREFI - tRP);
}
// shift the bus busy time sufficiently far ahead that we never
// have to worry about negative values when computing the time for
// the next request, this will add an insignificant bubble at the
// start of simulation
busBusyUntil = curTick() + tRP + tRCD + tCL;
}
}
Tick
DRAMCtrl::recvAtomic(PacketPtr pkt)
{
DPRINTF(DRAM, "recvAtomic: %s 0x%x\n", pkt->cmdString(), pkt->getAddr());
// do the actual memory access and turn the packet into a response
access(pkt);
Tick latency = 0;
if (!pkt->memInhibitAsserted() && pkt->hasData()) {
// this value is not supposed to be accurate, just enough to
// keep things going, mimic a closed page
latency = tRP + tRCD + tCL;
}
return latency;
}
bool
DRAMCtrl::readQueueFull(unsigned int neededEntries) const
{
DPRINTF(DRAM, "Read queue limit %d, current size %d, entries needed %d\n",
readBufferSize, readQueue.size() + respQueue.size(),
neededEntries);
return
(readQueue.size() + respQueue.size() + neededEntries) > readBufferSize;
}
bool
DRAMCtrl::writeQueueFull(unsigned int neededEntries) const
{
DPRINTF(DRAM, "Write queue limit %d, current size %d, entries needed %d\n",
writeBufferSize, writeQueue.size(), neededEntries);
return (writeQueue.size() + neededEntries) > writeBufferSize;
}
DRAMCtrl::DRAMPacket*
DRAMCtrl::decodeAddr(PacketPtr pkt, Addr dramPktAddr, unsigned size,
bool isRead)
{
// decode the address based on the address mapping scheme, with
// Ro, Ra, Co, Ba and Ch denoting row, rank, column, bank and
// channel, respectively
uint8_t rank;
uint8_t bank;
// use a 64-bit unsigned during the computations as the row is
// always the top bits, and check before creating the DRAMPacket
uint64_t row;
// truncate the address to a DRAM burst, which makes it unique to
// a specific column, row, bank, rank and channel
Addr addr = dramPktAddr / burstSize;
// we have removed the lowest order address bits that denote the
// position within the column
if (addrMapping == Enums::RoRaBaChCo) {
// the lowest order bits denote the column to ensure that
// sequential cache lines occupy the same row
addr = addr / columnsPerRowBuffer;
// take out the channel part of the address
addr = addr / channels;
// after the channel bits, get the bank bits to interleave
// over the banks
bank = addr % banksPerRank;
addr = addr / banksPerRank;
// after the bank, we get the rank bits which thus interleaves
// over the ranks
rank = addr % ranksPerChannel;
addr = addr / ranksPerChannel;
// lastly, get the row bits
row = addr % rowsPerBank;
addr = addr / rowsPerBank;
} else if (addrMapping == Enums::RoRaBaCoCh) {
// take out the lower-order column bits
addr = addr / columnsPerStripe;
// take out the channel part of the address
addr = addr / channels;
// next, the higher-order column bites
addr = addr / (columnsPerRowBuffer / columnsPerStripe);
// after the column bits, we get the bank bits to interleave
// over the banks
bank = addr % banksPerRank;
addr = addr / banksPerRank;
// after the bank, we get the rank bits which thus interleaves
// over the ranks
rank = addr % ranksPerChannel;
addr = addr / ranksPerChannel;
// lastly, get the row bits
row = addr % rowsPerBank;
addr = addr / rowsPerBank;
} else if (addrMapping == Enums::RoCoRaBaCh) {
// optimise for closed page mode and utilise maximum
// parallelism of the DRAM (at the cost of power)
// take out the lower-order column bits
addr = addr / columnsPerStripe;
// take out the channel part of the address, not that this has
// to match with how accesses are interleaved between the
// controllers in the address mapping
addr = addr / channels;
// start with the bank bits, as this provides the maximum
// opportunity for parallelism between requests
bank = addr % banksPerRank;
addr = addr / banksPerRank;
// next get the rank bits
rank = addr % ranksPerChannel;
addr = addr / ranksPerChannel;
// next, the higher-order column bites
addr = addr / (columnsPerRowBuffer / columnsPerStripe);
// lastly, get the row bits
row = addr % rowsPerBank;
addr = addr / rowsPerBank;
} else
panic("Unknown address mapping policy chosen!");
assert(rank < ranksPerChannel);
assert(bank < banksPerRank);
assert(row < rowsPerBank);
assert(row < Bank::NO_ROW);
DPRINTF(DRAM, "Address: %lld Rank %d Bank %d Row %d\n",
dramPktAddr, rank, bank, row);
// create the corresponding DRAM packet with the entry time and
// ready time set to the current tick, the latter will be updated
// later
uint16_t bank_id = banksPerRank * rank + bank;
return new DRAMPacket(pkt, isRead, rank, bank, row, bank_id, dramPktAddr,
size, ranks[rank]->banks[bank], *ranks[rank]);
}
void
DRAMCtrl::addToReadQueue(PacketPtr pkt, unsigned int pktCount)
{
// only add to the read queue here. whenever the request is
// eventually done, set the readyTime, and call schedule()
assert(!pkt->isWrite());
assert(pktCount != 0);
// if the request size is larger than burst size, the pkt is split into
// multiple DRAM packets
// Note if the pkt starting address is not aligened to burst size, the
// address of first DRAM packet is kept unaliged. Subsequent DRAM packets
// are aligned to burst size boundaries. This is to ensure we accurately
// check read packets against packets in write queue.
Addr addr = pkt->getAddr();
unsigned pktsServicedByWrQ = 0;
BurstHelper* burst_helper = NULL;
for (int cnt = 0; cnt < pktCount; ++cnt) {
unsigned size = std::min((addr | (burstSize - 1)) + 1,
pkt->getAddr() + pkt->getSize()) - addr;
readPktSize[ceilLog2(size)]++;
readBursts++;
// First check write buffer to see if the data is already at
// the controller
bool foundInWrQ = false;
for (auto i = writeQueue.begin(); i != writeQueue.end(); ++i) {
// check if the read is subsumed in the write entry we are
// looking at
if ((*i)->addr <= addr &&
(addr + size) <= ((*i)->addr + (*i)->size)) {
foundInWrQ = true;
servicedByWrQ++;
pktsServicedByWrQ++;
DPRINTF(DRAM, "Read to addr %lld with size %d serviced by "
"write queue\n", addr, size);
bytesReadWrQ += burstSize;
break;
}
}
// If not found in the write q, make a DRAM packet and
// push it onto the read queue
if (!foundInWrQ) {
// Make the burst helper for split packets
if (pktCount > 1 && burst_helper == NULL) {
DPRINTF(DRAM, "Read to addr %lld translates to %d "
"dram requests\n", pkt->getAddr(), pktCount);
burst_helper = new BurstHelper(pktCount);
}
DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, true);
dram_pkt->burstHelper = burst_helper;
assert(!readQueueFull(1));
rdQLenPdf[readQueue.size() + respQueue.size()]++;
DPRINTF(DRAM, "Adding to read queue\n");
readQueue.push_back(dram_pkt);
// Update stats
avgRdQLen = readQueue.size() + respQueue.size();
}
// Starting address of next dram pkt (aligend to burstSize boundary)
addr = (addr | (burstSize - 1)) + 1;
}
// If all packets are serviced by write queue, we send the repsonse back
if (pktsServicedByWrQ == pktCount) {
accessAndRespond(pkt, frontendLatency);
return;
}
// Update how many split packets are serviced by write queue
if (burst_helper != NULL)
burst_helper->burstsServiced = pktsServicedByWrQ;
// If we are not already scheduled to get a request out of the
// queue, do so now
if (!nextReqEvent.scheduled()) {
DPRINTF(DRAM, "Request scheduled immediately\n");
schedule(nextReqEvent, curTick());
}
}
void
DRAMCtrl::addToWriteQueue(PacketPtr pkt, unsigned int pktCount)
{
// only add to the write queue here. whenever the request is
// eventually done, set the readyTime, and call schedule()
assert(pkt->isWrite());
// if the request size is larger than burst size, the pkt is split into
// multiple DRAM packets
Addr addr = pkt->getAddr();
for (int cnt = 0; cnt < pktCount; ++cnt) {
unsigned size = std::min((addr | (burstSize - 1)) + 1,
pkt->getAddr() + pkt->getSize()) - addr;
writePktSize[ceilLog2(size)]++;
writeBursts++;
// see if we can merge with an existing item in the write
// queue and keep track of whether we have merged or not so we
// can stop at that point and also avoid enqueueing a new
// request
bool merged = false;
auto w = writeQueue.begin();
while(!merged && w != writeQueue.end()) {
// either of the two could be first, if they are the same
// it does not matter which way we go
if ((*w)->addr >= addr) {
// the existing one starts after the new one, figure
// out where the new one ends with respect to the
// existing one
if ((addr + size) >= ((*w)->addr + (*w)->size)) {
// check if the existing one is completely
// subsumed in the new one
DPRINTF(DRAM, "Merging write covering existing burst\n");
merged = true;
// update both the address and the size
(*w)->addr = addr;
(*w)->size = size;
} else if ((addr + size) >= (*w)->addr &&
((*w)->addr + (*w)->size - addr) <= burstSize) {
// the new one is just before or partially
// overlapping with the existing one, and together
// they fit within a burst
DPRINTF(DRAM, "Merging write before existing burst\n");
merged = true;
// the existing queue item needs to be adjusted with
// respect to both address and size
(*w)->size = (*w)->addr + (*w)->size - addr;
(*w)->addr = addr;
}
} else {
// the new one starts after the current one, figure
// out where the existing one ends with respect to the
// new one
if (((*w)->addr + (*w)->size) >= (addr + size)) {
// check if the new one is completely subsumed in the
// existing one
DPRINTF(DRAM, "Merging write into existing burst\n");
merged = true;
// no adjustments necessary
} else if (((*w)->addr + (*w)->size) >= addr &&
(addr + size - (*w)->addr) <= burstSize) {
// the existing one is just before or partially
// overlapping with the new one, and together
// they fit within a burst
DPRINTF(DRAM, "Merging write after existing burst\n");
merged = true;
// the address is right, and only the size has
// to be adjusted
(*w)->size = addr + size - (*w)->addr;
}
}
++w;
}
// if the item was not merged we need to create a new write
// and enqueue it
if (!merged) {
DRAMPacket* dram_pkt = decodeAddr(pkt, addr, size, false);
assert(writeQueue.size() < writeBufferSize);
wrQLenPdf[writeQueue.size()]++;
DPRINTF(DRAM, "Adding to write queue\n");
writeQueue.push_back(dram_pkt);
// Update stats
avgWrQLen = writeQueue.size();
} else {
// keep track of the fact that this burst effectively
// disappeared as it was merged with an existing one
mergedWrBursts++;
}
// Starting address of next dram pkt (aligend to burstSize boundary)
addr = (addr | (burstSize - 1)) + 1;
}
// we do not wait for the writes to be send to the actual memory,
// but instead take responsibility for the consistency here and
// snoop the write queue for any upcoming reads
// @todo, if a pkt size is larger than burst size, we might need a
// different front end latency
accessAndRespond(pkt, frontendLatency);
// If we are not already scheduled to get a request out of the
// queue, do so now
if (!nextReqEvent.scheduled()) {
DPRINTF(DRAM, "Request scheduled immediately\n");
schedule(nextReqEvent, curTick());
}
}
void
DRAMCtrl::printQs() const {
DPRINTF(DRAM, "===READ QUEUE===\n\n");
for (auto i = readQueue.begin() ; i != readQueue.end() ; ++i) {
DPRINTF(DRAM, "Read %lu\n", (*i)->addr);
}
DPRINTF(DRAM, "\n===RESP QUEUE===\n\n");
for (auto i = respQueue.begin() ; i != respQueue.end() ; ++i) {
DPRINTF(DRAM, "Response %lu\n", (*i)->addr);
}
DPRINTF(DRAM, "\n===WRITE QUEUE===\n\n");
for (auto i = writeQueue.begin() ; i != writeQueue.end() ; ++i) {
DPRINTF(DRAM, "Write %lu\n", (*i)->addr);
}
}
bool
DRAMCtrl::recvTimingReq(PacketPtr pkt)
{
/// @todo temporary hack to deal with memory corruption issues until
/// 4-phase transactions are complete
for (int x = 0; x < pendingDelete.size(); x++)
delete pendingDelete[x];
pendingDelete.clear();
// This is where we enter from the outside world
DPRINTF(DRAM, "recvTimingReq: request %s addr %lld size %d\n",
pkt->cmdString(), pkt->getAddr(), pkt->getSize());
// simply drop inhibited packets for now
if (pkt->memInhibitAsserted()) {
DPRINTF(DRAM, "Inhibited packet -- Dropping it now\n");
pendingDelete.push_back(pkt);
return true;
}
// Calc avg gap between requests
if (prevArrival != 0) {
totGap += curTick() - prevArrival;
}
prevArrival = curTick();
// Find out how many dram packets a pkt translates to
// If the burst size is equal or larger than the pkt size, then a pkt
// translates to only one dram packet. Otherwise, a pkt translates to
// multiple dram packets
unsigned size = pkt->getSize();
unsigned offset = pkt->getAddr() & (burstSize - 1);
unsigned int dram_pkt_count = divCeil(offset + size, burstSize);
// check local buffers and do not accept if full
if (pkt->isRead()) {
assert(size != 0);
if (readQueueFull(dram_pkt_count)) {
DPRINTF(DRAM, "Read queue full, not accepting\n");
// remember that we have to retry this port
retryRdReq = true;
numRdRetry++;
return false;
} else {
addToReadQueue(pkt, dram_pkt_count);
readReqs++;
bytesReadSys += size;
}
} else if (pkt->isWrite()) {
assert(size != 0);
if (writeQueueFull(dram_pkt_count)) {
DPRINTF(DRAM, "Write queue full, not accepting\n");
// remember that we have to retry this port
retryWrReq = true;
numWrRetry++;
return false;
} else {
addToWriteQueue(pkt, dram_pkt_count);
writeReqs++;
bytesWrittenSys += size;
}
} else {
DPRINTF(DRAM,"Neither read nor write, ignore timing\n");
neitherReadNorWrite++;
accessAndRespond(pkt, 1);
}
return true;
}
void
DRAMCtrl::processRespondEvent()
{
DPRINTF(DRAM,
"processRespondEvent(): Some req has reached its readyTime\n");
DRAMPacket* dram_pkt = respQueue.front();
if (dram_pkt->burstHelper) {
// it is a split packet
dram_pkt->burstHelper->burstsServiced++;
if (dram_pkt->burstHelper->burstsServiced ==
dram_pkt->burstHelper->burstCount) {
// we have now serviced all children packets of a system packet
// so we can now respond to the requester
// @todo we probably want to have a different front end and back
// end latency for split packets
accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
delete dram_pkt->burstHelper;
dram_pkt->burstHelper = NULL;
}
} else {
// it is not a split packet
accessAndRespond(dram_pkt->pkt, frontendLatency + backendLatency);
}
delete respQueue.front();
respQueue.pop_front();
if (!respQueue.empty()) {
assert(respQueue.front()->readyTime >= curTick());
assert(!respondEvent.scheduled());
schedule(respondEvent, respQueue.front()->readyTime);
} else {
// if there is nothing left in any queue, signal a drain
if (writeQueue.empty() && readQueue.empty() &&
drainManager) {
DPRINTF(Drain, "DRAM controller done draining\n");
drainManager->signalDrainDone();
drainManager = NULL;
}
}
// We have made a location in the queue available at this point,
// so if there is a read that was forced to wait, retry now
if (retryRdReq) {
retryRdReq = false;
port.sendRetryReq();
}
}
bool
DRAMCtrl::chooseNext(std::deque<DRAMPacket*>& queue, bool switched_cmd_type)
{
// This method does the arbitration between requests. The chosen
// packet is simply moved to the head of the queue. The other
// methods know that this is the place to look. For example, with
// FCFS, this method does nothing
assert(!queue.empty());
// bool to indicate if a packet to an available rank is found
bool found_packet = false;
if (queue.size() == 1) {
DRAMPacket* dram_pkt = queue.front();
// available rank corresponds to state refresh idle
if (ranks[dram_pkt->rank]->isAvailable()) {
found_packet = true;
DPRINTF(DRAM, "Single request, going to a free rank\n");
} else {
DPRINTF(DRAM, "Single request, going to a busy rank\n");
}
return found_packet;
}
if (memSchedPolicy == Enums::fcfs) {
// check if there is a packet going to a free rank
for(auto i = queue.begin(); i != queue.end() ; ++i) {
DRAMPacket* dram_pkt = *i;
if (ranks[dram_pkt->rank]->isAvailable()) {
queue.erase(i);
queue.push_front(dram_pkt);
found_packet = true;
break;
}
}
} else if (memSchedPolicy == Enums::frfcfs) {
found_packet = reorderQueue(queue, switched_cmd_type);
} else
panic("No scheduling policy chosen\n");
return found_packet;
}
bool
DRAMCtrl::reorderQueue(std::deque<DRAMPacket*>& queue, bool switched_cmd_type)
{
// Only determine this when needed
uint64_t earliest_banks = 0;
// Search for row hits first, if no row hit is found then schedule the
// packet to one of the earliest banks available
bool found_packet = false;
bool found_earliest_pkt = false;
bool found_prepped_diff_rank_pkt = false;
auto selected_pkt_it = queue.end();
for (auto i = queue.begin(); i != queue.end() ; ++i) {
DRAMPacket* dram_pkt = *i;
const Bank& bank = dram_pkt->bankRef;
// check if rank is busy. If this is the case jump to the next packet
// Check if it is a row hit
if (dram_pkt->rankRef.isAvailable()) {
if (bank.openRow == dram_pkt->row) {
if (dram_pkt->rank == activeRank || switched_cmd_type) {
// FCFS within the hits, giving priority to commands
// that access the same rank as the previous burst
// to minimize bus turnaround delays
// Only give rank prioity when command type is
// not changing
DPRINTF(DRAM, "Row buffer hit\n");
selected_pkt_it = i;
break;
} else if (!found_prepped_diff_rank_pkt) {
// found row hit for command on different rank
// than prev burst
selected_pkt_it = i;
found_prepped_diff_rank_pkt = true;
}
} else if (!found_earliest_pkt & !found_prepped_diff_rank_pkt) {
// packet going to a rank which is currently not waiting for a
// refresh, No row hit and
// haven't found an entry with a row hit to a new rank
if (earliest_banks == 0)
// Determine entries with earliest bank prep delay
// Function will give priority to commands that access the
// same rank as previous burst and can prep
// the bank seamlessly
earliest_banks = minBankPrep(queue, switched_cmd_type);
// FCFS - Bank is first available bank
if (bits(earliest_banks, dram_pkt->bankId,
dram_pkt->bankId)) {
// Remember the packet to be scheduled to one of
// the earliest banks available, FCFS amongst the
// earliest banks
selected_pkt_it = i;
//if the packet found is going to a rank that is currently
//not busy then update the found_packet to true
found_earliest_pkt = true;
}
}
}
}
if (selected_pkt_it != queue.end()) {
DRAMPacket* selected_pkt = *selected_pkt_it;
queue.erase(selected_pkt_it);
queue.push_front(selected_pkt);
found_packet = true;
}
return found_packet;
}
void
DRAMCtrl::accessAndRespond(PacketPtr pkt, Tick static_latency)
{
DPRINTF(DRAM, "Responding to Address %lld.. ",pkt->getAddr());
bool needsResponse = pkt->needsResponse();
// do the actual memory access which also turns the packet into a
// response
access(pkt);
// turn packet around to go back to requester if response expected
if (needsResponse) {
// access already turned the packet into a response
assert(pkt->isResponse());
// response_time consumes the static latency and is charged also
// with headerDelay that takes into account the delay provided by
// the xbar and also the payloadDelay that takes into account the
// number of data beats.
Tick response_time = curTick() + static_latency + pkt->headerDelay +
pkt->payloadDelay;
// Here we reset the timing of the packet before sending it out.
pkt->headerDelay = pkt->payloadDelay = 0;
// queue the packet in the response queue to be sent out after
// the static latency has passed
port.schedTimingResp(pkt, response_time);
} else {
// @todo the packet is going to be deleted, and the DRAMPacket
// is still having a pointer to it
pendingDelete.push_back(pkt);
}
DPRINTF(DRAM, "Done\n");
return;
}
void
DRAMCtrl::activateBank(Rank& rank_ref, Bank& bank_ref,
Tick act_tick, uint32_t row)
{
assert(rank_ref.actTicks.size() == activationLimit);
DPRINTF(DRAM, "Activate at tick %d\n", act_tick);
// update the open row
assert(bank_ref.openRow == Bank::NO_ROW);
bank_ref.openRow = row;
// start counting anew, this covers both the case when we
// auto-precharged, and when this access is forced to
// precharge
bank_ref.bytesAccessed = 0;
bank_ref.rowAccesses = 0;
++rank_ref.numBanksActive;
assert(rank_ref.numBanksActive <= banksPerRank);
DPRINTF(DRAM, "Activate bank %d, rank %d at tick %lld, now got %d active\n",
bank_ref.bank, rank_ref.rank, act_tick,
ranks[rank_ref.rank]->numBanksActive);
rank_ref.power.powerlib.doCommand(MemCommand::ACT, bank_ref.bank,
divCeil(act_tick, tCK) -
timeStampOffset);
DPRINTF(DRAMPower, "%llu,ACT,%d,%d\n", divCeil(act_tick, tCK) -
timeStampOffset, bank_ref.bank, rank_ref.rank);
// The next access has to respect tRAS for this bank
bank_ref.preAllowedAt = act_tick + tRAS;
// Respect the row-to-column command delay
bank_ref.colAllowedAt = std::max(act_tick + tRCD, bank_ref.colAllowedAt);
// start by enforcing tRRD
for(int i = 0; i < banksPerRank; i++) {
// next activate to any bank in this rank must not happen
// before tRRD
if (bankGroupArch && (bank_ref.bankgr == rank_ref.banks[i].bankgr)) {
// bank group architecture requires longer delays between
// ACT commands within the same bank group. Use tRRD_L
// in this case
rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD_L,
rank_ref.banks[i].actAllowedAt);
} else {
// use shorter tRRD value when either
// 1) bank group architecture is not supportted
// 2) bank is in a different bank group
rank_ref.banks[i].actAllowedAt = std::max(act_tick + tRRD,
rank_ref.banks[i].actAllowedAt);
}
}
// next, we deal with tXAW, if the activation limit is disabled
// then we directly schedule an activate power event
if (!rank_ref.actTicks.empty()) {
// sanity check
if (rank_ref.actTicks.back() &&
(act_tick - rank_ref.actTicks.back()) < tXAW) {
panic("Got %d activates in window %d (%llu - %llu) which "
"is smaller than %llu\n", activationLimit, act_tick -
rank_ref.actTicks.back(), act_tick,
rank_ref.actTicks.back(), tXAW);
}
// shift the times used for the book keeping, the last element
// (highest index) is the oldest one and hence the lowest value
rank_ref.actTicks.pop_back();
// record an new activation (in the future)
rank_ref.actTicks.push_front(act_tick);
// cannot activate more than X times in time window tXAW, push the
// next one (the X + 1'st activate) to be tXAW away from the
// oldest in our window of X
if (rank_ref.actTicks.back() &&
(act_tick - rank_ref.actTicks.back()) < tXAW) {
DPRINTF(DRAM, "Enforcing tXAW with X = %d, next activate "
"no earlier than %llu\n", activationLimit,
rank_ref.actTicks.back() + tXAW);
for(int j = 0; j < banksPerRank; j++)
// next activate must not happen before end of window
rank_ref.banks[j].actAllowedAt =
std::max(rank_ref.actTicks.back() + tXAW,
rank_ref.banks[j].actAllowedAt);
}
}
// at the point when this activate takes place, make sure we
// transition to the active power state
if (!rank_ref.activateEvent.scheduled())
schedule(rank_ref.activateEvent, act_tick);
else if (rank_ref.activateEvent.when() > act_tick)
// move it sooner in time