forked from chipsalliance/VeeR-ISS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hart.cpp
10029 lines (8173 loc) · 206 KB
/
Hart.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Western Digital Corporation or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iomanip>
#include <iostream>
#include <sstream>
#include <climits>
#include <map>
#include <mutex>
#include <array>
#include <atomic>
#include <cstring>
#include <ctime>
#include <boost/format.hpp>
#include <sys/time.h>
#include <poll.h>
#include <boost/multiprecision/cpp_int.hpp>
// On pure 32-bit machines, use boost for 128-bit integer type.
#if __x86_64__
typedef __int128_t Int128;
typedef __uint128_t Uint128;
#else
typedef boost::multiprecision::int128_t Int128;
typedef boost::multiprecision::uint128_t Uint128;
#endif
#include <fcntl.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <cassert>
#include <csignal>
#define __STDC_FORMAT_MACROS
#include <cinttypes>
#include <sys/socket.h>
#include <netinet/in.h>
#include "instforms.hpp"
#include "DecodedInst.hpp"
#include "Hart.hpp"
#include "System.hpp"
#ifndef SO_REUSEPORT
#define SO_REUSEPORT SO_REUSEADDR
#endif
using namespace WdRiscv;
template <typename TYPE>
static
bool
parseNumber(const std::string& numberStr, TYPE& number)
{
bool good = not numberStr.empty();
if (good)
{
char* end = nullptr;
if (sizeof(TYPE) == 4)
number = strtoul(numberStr.c_str(), &end, 0);
else if (sizeof(TYPE) == 8)
number = strtoull(numberStr.c_str(), &end, 0);
else
{
std::cerr << "parseNumber: Only 32/64-bit RISCV harts supported\n";
return false;
}
if (end and *end)
good = false; // Part of the string are non parseable.
}
return good;
}
template <typename URV>
Hart<URV>::Hart(unsigned hartIx, URV hartId, Memory& memory)
: hartIx_(hartIx), memory_(memory), intRegs_(32),
fpRegs_(32), vecRegs_(), syscall_(*this),
pmpManager_(memory.size(), 1024*1024),
virtMem_(hartIx, memory, memory.pageSize(), pmpManager_, 16 /* FIX: TLB size*/)
{
regionHasLocalMem_.resize(16);
regionHasLocalDataMem_.resize(16);
regionHasDccm_.resize(16);
regionHasMemMappedRegs_.resize(16);
regionHasLocalInstMem_.resize(16);
regionIsIdempotent_.resize(16);
decodeCacheSize_ = 128*1024; // Must be a power of 2.
decodeCacheMask_ = decodeCacheSize_ - 1;
decodeCache_.resize(decodeCacheSize_);
interruptStat_.resize(size_t(InterruptCause::MAX_CAUSE) + 1);
exceptionStat_.resize(size_t(ExceptionCause::MAX_CAUSE) + 1);
for (auto& vec : exceptionStat_)
vec.resize(size_t(SecondaryCause::MAX_CAUSE) + 1);
// Tie the retired instruction and cycle counter CSRs to variables
// held in the hart.
if constexpr (sizeof(URV) == 4)
{
URV* low = reinterpret_cast<URV*> (&retiredInsts_);
URV* high = low + 1;
auto& mirLow = csRegs_.regs_.at(size_t(CsrNumber::MINSTRET));
auto& irLow = csRegs_.regs_.at(size_t(CsrNumber::INSTRET));
mirLow.tie(low);
irLow.tie(low);
auto& mirHigh = csRegs_.regs_.at(size_t(CsrNumber::MINSTRETH));
auto& irHigh = csRegs_.regs_.at(size_t(CsrNumber::INSTRETH));
mirHigh.tie(high);
irHigh.tie(high);
low = reinterpret_cast<URV*> (&cycleCount_);
high = low + 1;
auto& mcycleLow = csRegs_.regs_.at(size_t(CsrNumber::MCYCLE));
auto& cycleLow = csRegs_.regs_.at(size_t(CsrNumber::CYCLE));
mcycleLow.tie(low);
cycleLow.tie(low);
auto& mcycleHigh = csRegs_.regs_.at(size_t(CsrNumber::MCYCLEH));
auto& cycleHigh = csRegs_.regs_.at(size_t(CsrNumber::CYCLEH));
mcycleHigh.tie(high);
cycleHigh.tie(high);
// TIME is a read-only shadow of MCYCLE.
csRegs_.regs_.at(size_t(CsrNumber::TIME)).tie(low);
csRegs_.regs_.at(size_t(CsrNumber::TIMEH)).tie(high);
}
else
{
csRegs_.regs_.at(size_t(CsrNumber::MINSTRET)).tie(&retiredInsts_);
csRegs_.regs_.at(size_t(CsrNumber::MCYCLE)).tie(&cycleCount_);
// INSTRET and CYCLE are read-only shadows of MINSTRET and MCYCLE.
csRegs_.regs_.at(size_t(CsrNumber::INSTRET)).tie(&retiredInsts_);
csRegs_.regs_.at(size_t(CsrNumber::CYCLE)).tie(&cycleCount_);
// TIME is a read-only shadow of MCYCLE.
csRegs_.regs_.at(size_t(CsrNumber::TIME)).tie(&cycleCount_);
}
// Tie the FCSR register to variable held in the hart.
csRegs_.regs_.at(size_t(CsrNumber::FCSR)).tie(&fcsrValue_);
// Configure MHARTID CSR.
bool implemented = true, debug = false, shared = false;
URV mask = 0, pokeMask = 0;
csRegs_.configCsr(CsrNumber::MHARTID, implemented, hartId, mask, pokeMask,
debug, shared);
}
template <typename URV>
Hart<URV>::~Hart()
{
}
template <typename URV>
void
Hart<URV>::getImplementedCsrs(std::vector<CsrNumber>& vec) const
{
vec.clear();
for (unsigned i = 0; i <= unsigned(CsrNumber::MAX_CSR_); ++i)
{
CsrNumber csrn = CsrNumber(i);
if (csRegs_.isImplemented(csrn))
vec.push_back(csrn);
}
}
template <typename URV>
bool
Hart<URV>::configureCache(uint64_t size, unsigned lineSize,
unsigned setSize)
{
return memory_.configureCache(size, lineSize, setSize);
}
template <typename URV>
void
Hart<URV>::deleteCache()
{
memory_.deleteCache();
}
template <typename URV>
void
Hart<URV>::getCacheLineAddresses(std::vector<uint64_t>& addresses)
{
memory_.getCacheLineAddresses(addresses);
}
template <typename URV>
unsigned
Hart<URV>::countImplementedPmpRegisters() const
{
unsigned count = 0;
unsigned num = unsigned(CsrNumber::PMPADDR0);
for (unsigned ix = 0; ix < 16; ++ix, ++num)
if (csRegs_.isImplemented(CsrNumber(num)))
count++;
if (count and count < 16)
std::cerr << "Warning: Some but not all PMPADDR CSRs are implemented\n";
unsigned cfgCount = 0;
if (mxlen_ == 32)
{
num = unsigned(CsrNumber::PMPCFG0);
for (unsigned ix = 0; ix < 4; ++ix, ++num)
if (csRegs_.isImplemented(CsrNumber(num)))
cfgCount++;
if (count and cfgCount != 4)
std::cerr << "Warning: Physical memory protection enabled but not all "
<< "of the config register (PMPCFG) are implemented\n";
}
else
{
num = unsigned(CsrNumber::PMPCFG0);
for (unsigned ix = 0; ix < 2; ++ix, num += 2)
if (csRegs_.isImplemented(CsrNumber(num)))
cfgCount++;
if (count and cfgCount != 2)
std::cerr << "Warning: Physical memory protection enabled but not all "
<< "of the config register (PMPCFG) are implemented\n";
}
return count;
}
template <typename URV>
void
Hart<URV>::processExtensions()
{
// D requires F and is enabled only if F is enabled.
rva_ = false;
rvc_ = false;
rvd_ = false;
rve_ = false;
rvf_ = false;
rvm_ = false;
rvs_ = false;
rvu_ = false;
rvv_ = false;
URV value = 0;
if (peekCsr(CsrNumber::MISA, value))
{
if (value & 1) // Atomic ('a') option.
rva_ = true;
if (value & (URV(1) << ('c' - 'a'))) // Compress option.
rvc_ = true;
if (value & (URV(1) << ('f' - 'a'))) // Single precision FP
{
rvf_ = true;
bool isDebug = false, shared = true;
// Make sure FCSR/FRM/FFLAGS are enabled if F extension is on.
if (not csRegs_.isImplemented(CsrNumber::FCSR))
csRegs_.configCsr("fcsr", true, 0, 0xff, 0xff, isDebug, shared);
if (not csRegs_.isImplemented(CsrNumber::FRM))
csRegs_.configCsr("frm", true, 0, 0x7, 0x7, isDebug, shared);
if (not csRegs_.isImplemented(CsrNumber::FFLAGS))
csRegs_.configCsr("fflags", true, 0, 0x1f, 0x1f, isDebug, shared);
}
if (value & (URV(1) << ('d' - 'a'))) // Double precision FP.
{
if (rvf_)
rvd_ = true;
else
std::cerr << "Bit 3 (d) is set in the MISA register but f "
<< "extension (bit 5) is not enabled -- ignored\n";
}
if (value & (URV(1) << ('e' - 'a')))
{
rve_ = true;
intRegs_.regs_.resize(16);
}
if (not (value & (URV(1) << ('i' - 'a'))))
std::cerr << "Bit 8 (i extension) is cleared in the MISA register "
<< " but extension is mandatory -- assuming bit 8 set\n";
if (value & (URV(1) << ('m' - 'a'))) // Multiply/divide option.
rvm_ = true;
if (value & (URV(1) << ('s' - 'a'))) // Supervisor-mode option.
enableSupervisorMode(true);
if (value & (URV(1) << ('u' - 'a'))) // User-mode option.
enableUserMode(true);
if (value & (URV(1) << ('v' - 'a'))) // User-mode option.
rvv_ = true;
for (auto ec : { 'b', 'g', 'h', 'j', 'k', 'l', 'n', 'o', 'p',
'q', 'r', 't', 'v', 'w', 'x', 'y', 'z' } )
{
unsigned bit = ec - 'a';
if (value & (URV(1) << bit))
std::cerr << "Bit " << bit << " (" << ec << ") set in the MISA "
<< "register but extension is not supported "
<< "-- ignored\n";
}
}
}
static
Pmp::Mode
getModeFromPmpconfigByte(uint8_t byte)
{
unsigned m = 0;
if (byte & 1) m = Pmp::Read | m;
if (byte & 2) m = Pmp::Write | m;
if (byte & 4) m = Pmp::Exec | m;
return Pmp::Mode(m);
}
template <typename URV>
void
Hart<URV>::updateMemoryProtection()
{
pmpManager_.reset();
const unsigned count = 16;
unsigned impCount = 0; // Count of implemented PMP registers
// Process the pmp entries in reverse order (since they are supposed to
// be checked in first to last priority). Apply memory protection to
// the range defined by each entry allowing lower numbered entries to
// over-ride higher numberd ones.
for (unsigned ix = 0; ix < count; ++ix)
{
unsigned pmpIx = count - ix - 1;
uint64_t low = 0, high = 0;
Pmp::Type type = Pmp::Type::Off;
Pmp::Mode mode = Pmp::Mode::None;
bool locked = false;
if (unpackMemoryProtection(pmpIx, type, mode, locked, low, high))
{
impCount++;
if (type != Pmp::Type::Off)
pmpManager_.setMode(low, high, type, mode, pmpIx, locked);
}
}
pmpEnabled_ = impCount > 0;
}
template <typename URV>
bool
Hart<URV>::unpackMemoryProtection(unsigned entryIx, Pmp::Type& type,
Pmp::Mode& mode, bool& locked,
uint64_t& low, uint64_t& high) const
{
low = high = 0;
type = Pmp::Type::Off;
mode = Pmp::Mode::None;
locked = false;
if (entryIx >= 16)
return false;
CsrNumber csrn = CsrNumber(unsigned(CsrNumber::PMPADDR0) + entryIx);
unsigned config = csRegs_.getPmpConfigByteFromPmpAddr(csrn);
type = Pmp::Type((config >> 3) & 3);
locked = config & 0x80;
mode = getModeFromPmpconfigByte(config);
if (type == Pmp::Type::Off)
return true; // Entry is off.
URV pmpVal = 0;
if (not peekCsr(csrn, pmpVal))
return false; // Unimplemented PMPADDR reg. Should not happen.
unsigned pmpG = csRegs_.getPmpG();
if (type == Pmp::Type::Tor) // Top of range
{
if (entryIx > 0)
{
URV prevVal = 0;
CsrNumber lowerCsrn = CsrNumber(unsigned(csrn) - 1);
peekCsr(lowerCsrn, prevVal);
low = prevVal;
low = (low >> pmpG) << pmpG; // Clear least sig G bits.
low = low << 2;
}
high = pmpVal;
high = (high >> pmpG) << pmpG;
high = high << 2;
if (high == 0)
{
type = Pmp::Type::Off; // Empty range.
return true;
}
high = high - 1;
return true;
}
uint64_t sizeM1 = 3; // Size minus 1
uint64_t napot = pmpVal; // Naturally aligned power of 2.
if (type == Pmp::Type::Napot) // Naturally algined power of 2.
{
unsigned rzi = 0; // Righmost-zero-bit index in pmpval.
if (pmpVal == URV(-1))
{
// Handle special case where pmpVal is set to maximum value
napot = 0;
rzi = mxlen_;
}
else
{
rzi = __builtin_ctzl(~pmpVal); // rightmost-zero-bit ix.
napot = (napot >> rzi) << rzi; // Clear bits below rightmost zero bit.
}
// Avoid overflow when computing 2 to the power 64 or
// higher. This is incorrect but should work in practice where
// the physical address space is 64-bit wide or less.
if (rzi + 3 >= 64)
sizeM1 = -1L;
else
sizeM1 = (uint64_t(1) << (rzi + 3)) - 1;
}
else
assert(type == Pmp::Type::Na4);
low = napot;
low = (low >> pmpG) << pmpG;
low = low << 2;
high = low + sizeM1;
return true;
}
template <typename URV>
void
Hart<URV>::updateAddressTranslation()
{
if (not isRvs())
return;
URV value = 0;
if (not peekCsr(CsrNumber::SATP, value))
return;
uint32_t prevAsid = virtMem_.addressSpace();
URV mode = 0, asid = 0, ppn = 0;
if constexpr (sizeof(URV) == 4)
{
mode = value >> 31;
asid = (value >> 22) & 0x1ff;
ppn = value & 0x3fffff; // Least sig 22 bits
}
else
{
mode = value >> 60;
if ((mode >= 1 and mode <= 7) or mode >= 12)
mode = 0; // 1-7 and 12-15 are reserved in version 1.12 of sepc.
asid = (value >> 44) & 0xffff;
ppn = value & 0xfffffffffffll; // Least sig 44 bits
}
virtMem_.setMode(VirtMem::Mode(mode));
virtMem_.setAddressSpace(asid);
virtMem_.setPageTableRootPage(ppn);
if (asid != prevAsid)
invalidateDecodeCache();
}
template <typename URV>
void
Hart<URV>::reset(bool resetMemoryMappedRegs)
{
privMode_ = PrivilegeMode::Machine;
hasDefaultIdempotent_ = false;
intRegs_.reset();
csRegs_.reset();
// Suppress resetting memory mapped register on initial resets sent
// by the test bench. Otherwise, initial resets obliterate memory
// mapped register data loaded from the ELF/HEX file.
if (resetMemoryMappedRegs)
memory_.resetMemoryMappedRegisters();
cancelLr(); // Clear LR reservation (if any).
clearPendingNmi();
clearTraceData();
loadQueue_.clear();
setPc(resetPc_);
currPc_ = pc_;
// Enable extensions if corresponding bits are set in the MISA CSR.
processExtensions();
perfControl_ = ~uint32_t(0);
URV value = 0;
if (peekCsr(CsrNumber::MCOUNTINHIBIT, value))
perfControl_ = ~value;
prevPerfControl_ = perfControl_;
debugMode_ = false;
debugStepMode_ = false;
dcsrStepIe_ = false;
dcsrStep_ = false;
if (peekCsr(CsrNumber::DCSR, value))
{
dcsrStep_ = (value >> 2) & 1;
dcsrStepIe_ = (value >> 11) & 1;
}
updateStackChecker(); // Swerv-specific feature.
wideLdSt_ = false; // Swerv-specific feature.
hartStarted_ = true;
// If mhartstart exists then use its bits to decide which hart has
// started.
if (hartIx_ != 0)
{
auto csr = findCsr("mhartstart");
if (csr)
{
URV value = 0;
csRegs_.read(csr->getNumber(), PrivilegeMode::Machine, value);
hartStarted_ = ((URV(1) << hartIx_) & value) != 0;
}
}
resetFloat();
// Update cached values of mstatus.mpp and mstatus.mprv and mstatus.fs.
updateCachedMstatusFields();
updateAddressTranslation();
updateMemoryProtection();
countImplementedPmpRegisters();
csRegs_.updateCounterPrivilege();
alarmLimit_ = alarmInterval_? alarmInterval_ + instCounter_ : ~uint64_t(0);
consecutiveIllegalCount_ = 0;
// Make all idempotent override entries invalid.
for (auto& entry : pmaOverrideVec_)
entry.reset();
}
template <typename URV>
void
Hart<URV>::updateCachedMstatusFields()
{
URV csrVal = csRegs_.peekMstatus();
MstatusFields<URV> msf(csrVal);
mstatusMpp_ = PrivilegeMode(msf.bits_.MPP);
mstatusMprv_ = msf.bits_.MPRV;
mstatusFs_ = FpFs(msf.bits_.FS);
mstatusVs_ = FpFs(msf.bits_.VS);
virtMem_.setExecReadable(msf.bits_.MXR);
virtMem_.setSupervisorAccessUser(msf.bits_.SUM);
}
template <typename URV>
bool
Hart<URV>::loadHexFile(const std::string& file)
{
return memory_.loadHexFile(file);
}
template <typename URV>
bool
Hart<URV>::loadElfFile(const std::string& file, size_t& entryPoint)
{
unsigned registerWidth = sizeof(URV)*8;
size_t end = 0;
if (not memory_.loadElfFile(file, registerWidth, entryPoint, end))
return false;
this->pokePc(URV(entryPoint));
ElfSymbol sym;
if (not toHostSym_.empty() and this->findElfSymbol(toHostSym_, sym))
this->setToHostAddress(sym.addr_);
if (not consoleIoSym_.empty() and this->findElfSymbol(consoleIoSym_, sym))
this->setConsoleIo(URV(sym.addr_));
if (this->findElfSymbol("__global_pointer$", sym))
this->pokeIntReg(RegGp, URV(sym.addr_));
if (this->findElfSymbol("_end", sym)) // For newlib/linux emulation.
this->setTargetProgramBreak(URV(sym.addr_));
else
this->setTargetProgramBreak(URV(end));
return true;
}
template <typename URV>
bool
Hart<URV>::peekMemory(size_t address, uint8_t& val, bool usePma) const
{
return memory_.peek(address, val, usePma);
}
template <typename URV>
bool
Hart<URV>::peekMemory(size_t address, uint16_t& val, bool usePma) const
{
return memory_.peek(address, val, usePma);
}
template <typename URV>
bool
Hart<URV>::peekMemory(size_t address, uint32_t& val, bool usePma) const
{
return memory_.peek(address, val, usePma);
}
template <typename URV>
bool
Hart<URV>::peekMemory(size_t address, uint64_t& val, bool usePma) const
{
uint32_t high = 0, low = 0;
if (memory_.peek(address, low, usePma) and memory_.peek(address + 4, high, usePma))
{
val = (uint64_t(high) << 32) | low;
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(size_t addr, uint8_t val, bool usePma)
{
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateLrs(addr, sizeof(val));
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(size_t addr, uint16_t val, bool usePma)
{
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateLrs(addr, sizeof(val));
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(size_t addr, uint32_t val, bool usePma)
{
// We allow poke to bypass masking for memory mapped registers
// otherwise, there is no way for external driver to clear bits that
// are read-only to this hart.
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateLrs(addr, sizeof(val));
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(size_t addr, uint64_t val, bool usePma)
{
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateLrs(addr, sizeof(val));
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
void
Hart<URV>::setPendingNmi(NmiCause cause)
{
// First nmi sets the cause. The cause is sticky.
if (not nmiPending_)
nmiCause_ = cause;
nmiPending_ = true;
// Set the nmi pending bit in the DCSR register.
URV val = 0; // DCSR value
if (peekCsr(CsrNumber::DCSR, val))
{
val |= URV(1) << 3; // nmip bit
pokeCsr(CsrNumber::DCSR, val);
recordCsrWrite(CsrNumber::DCSR);
}
}
template <typename URV>
void
Hart<URV>::clearPendingNmi()
{
nmiPending_ = false;
nmiCause_ = NmiCause::UNKNOWN;
URV val = 0; // DCSR value
if (peekCsr(CsrNumber::DCSR, val))
{
val &= ~(URV(1) << 3); // nmip bit
pokeCsr(CsrNumber::DCSR, val);
recordCsrWrite(CsrNumber::DCSR);
}
}
template <typename URV>
void
Hart<URV>::setToHostAddress(size_t address)
{
toHost_ = URV(address);
toHostValid_ = true;
}
template <typename URV>
void
Hart<URV>::clearToHostAddress()
{
toHost_ = 0;
toHostValid_ = false;
}
template <typename URV>
void
Hart<URV>::putInLoadQueue(unsigned size, size_t addr, unsigned regIx,
uint64_t data, bool isWide, bool fp)
{
if (not loadQueueEnabled_)
return;
if (isAddrInDccm(addr) or isAddrMemMapped(addr))
{
// Blocking load. Invalidate target register in load queue so
// that it will not be reverted.
invalidateInLoadQueue(regIx, false, fp);
return;
}
size_t newIx = 0; // Index of new entry.
if (loadQueue_.size() >= maxLoadQueueSize_)
{
std::cerr << "At #" << instCounter_ << ": Load queue full.\n";
for (size_t i = 1; i < maxLoadQueueSize_; ++i)
loadQueue_[i-1] = loadQueue_[i];
loadQueue_[maxLoadQueueSize_-1] = LoadInfo(size, addr, regIx, data,
isWide, instCounter_, fp);
newIx = maxLoadQueueSize_ - 1;
}
else
{
loadQueue_.push_back(LoadInfo(size, addr, regIx, data, isWide,
instCounter_, fp));
newIx = loadQueue_.size() - 1;
}
uint64_t prev = loadQueue_.at(newIx).prevData_;
for (size_t i = 0; i < newIx; ++i)
{
auto& entry = loadQueue_.at(i);
if (entry.isValid() and entry.regIx_ == regIx and entry.fp_ == fp)
{
if (entry.wide_ and not loadQueue_.at(newIx).wide_)
pokeCsr(CsrNumber::MDBHD, entry.prevData_ >> 32); // Revert MDBHD.
prev = entry.prevData_;
entry.makeInvalid();
}
}
loadQueue_.at(newIx).prevData_ = prev;
}
template <typename URV>
void
Hart<URV>::invalidateInLoadQueue(unsigned regIx, bool isDiv, bool fp)
{
if (regIx == lastDivRd_ and not isDiv)
hasLastDiv_ = false;
// Invalidate entry containing target register so that a later load
// exception matching entry will not revert target register.
for (unsigned i = 0; i < loadQueue_.size(); ++i)
{
auto& entry = loadQueue_[i];
if (entry.valid_ and entry.regIx_ == regIx and entry.fp_ == fp)
{
if (entry.wide_)
pokeCsr(CsrNumber::MDBHD, entry.prevData_ >> 32); // Revert MDBHD.
entry.makeInvalid();
}
}
}
template <typename URV>
void
Hart<URV>::removeFromLoadQueue(unsigned regIx, bool isDiv, bool fp)
{
if (regIx == 0)
return;
if (regIx == lastDivRd_ and not isDiv)
hasLastDiv_ = false;
// Last (most recent) matching entry is removed. Subsequent entries
// are invalidated.
bool last = true;
size_t removeIx = loadQueue_.size();
for (size_t i = loadQueue_.size(); i > 0; --i)
{
auto& entry = loadQueue_.at(i-1);
if (not entry.isValid())
continue;
if (entry.regIx_ == regIx and entry.fp_ == fp)
{
if (last)
{
removeIx = i-1;
last = false;
}
else
entry.makeInvalid();
}
}
if (removeIx < loadQueue_.size())
loadQueue_.erase(loadQueue_.begin() + removeIx);
}
template <typename URV>
inline
void
Hart<URV>::execBeq(const DecodedInst* di)
{
URV v1 = intRegs_.read(di->op0()), v2 = intRegs_.read(di->op1());
if (v1 != v2)
return;
setPc(currPc_ + di->op2As<SRV>());
lastBranchTaken_ = true;
}
template <typename URV>
inline
void
Hart<URV>::execBne(const DecodedInst* di)
{
URV v1 = intRegs_.read(di->op0()), v2 = intRegs_.read(di->op1());
if (v1 == v2)
return;
setPc(currPc_ + di->op2As<SRV>());
lastBranchTaken_ = true;
}
template <typename URV>
inline
void
Hart<URV>::execAddi(const DecodedInst* di)
{
SRV imm = di->op2As<SRV>();
SRV v = intRegs_.read(di->op1()) + imm;
intRegs_.write(di->op0(), v);
}
template <typename URV>
inline
void
Hart<URV>::execAdd(const DecodedInst* di)
{
URV v = intRegs_.read(di->op1()) + intRegs_.read(di->op2());
intRegs_.write(di->op0(), v);
}
template <typename URV>
inline
void
Hart<URV>::execAndi(const DecodedInst* di)
{
SRV imm = di->op2As<SRV>();
URV v = intRegs_.read(di->op1()) & imm;
intRegs_.write(di->op0(), v);
}