forked from tenstorrent/whisper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHart.cpp
More file actions
14129 lines (11427 loc) · 330 KB
/
Copy pathHart.cpp
File metadata and controls
14129 lines (11427 loc) · 330 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 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 <numeric>
#include <cstring>
#include <ctime>
#include <poll.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <cassert>
#include <csignal>
#include <cinttypes>
#include <sys/socket.h>
#include <netinet/in.h>
#include <thread>
#include <chrono>
#include <boost/algorithm/string.hpp>
#include "instforms.hpp"
#include "DecodedInst.hpp"
#include "Hart.hpp"
#include "Mcm.hpp"
#include "PerfApi.hpp"
#include "wideint.hpp"
#ifndef SO_REUSEPORT
#define SO_REUSEPORT SO_REUSEADDR
#endif
using namespace WdRiscv;
template <typename TYPE>
static
bool
parseNumber(std::string_view numberStr, TYPE& number)
{
bool good = not numberStr.empty();
if (good)
{
char* end = nullptr;
if constexpr (sizeof(TYPE) == 4)
number = strtoul(numberStr.data(), &end, 0);
else if constexpr (sizeof(TYPE) == 8)
number = strtoull(numberStr.data(), &end, 0);
else
{
std::cerr << "Error: 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, unsigned numHarts, Memory& memory,
Syscall<URV>& syscall, uint64_t& time)
: hartIx_(hartIx), numHarts_(numHarts), memory_(memory),
intRegs_(32),
csRegs_(pmpManager_),
fpRegs_(32),
syscall_(syscall),
time_(time),
decodeCacheSize_(128*1024),
decodeCacheMask_(decodeCacheSize_ - 1),
virtMem_(hartIx, memory.pageSize(), 2048)
{
setupVirtMemCallbacks();
// Enable default extensions
for (RvExtension ext : { RvExtension::C, RvExtension::M })
enableExtension(ext, true);
decodeCache_.resize(decodeCacheSize_);
interruptStat_.resize(size_t(InterruptCause::MAX_CAUSE) + 1);
exceptionStat_.resize(size_t(ExceptionCause::MAX_CAUSE) + 1);
// Tie frequently updated CSR to variables held in the hart so that their values can be
// obtained directly by the hart and without having to use the read/write/peek/poke
// interfaces. This is done for speed.
tieCsrs();
// Configure MHARTID CSR.
bool implemented = true, shared = false;
URV mask = 0, pokeMask = 0;
csRegs_.configCsr(CsrNumber::MHARTID, implemented, hartId, mask, pokeMask, shared);
// Give disassembler a way to get abi-names of CSRs.
auto callback = [this](unsigned ix) {
auto csr = this->findCsr(CsrNumber(ix));
return csr? csr->getName() : std::string_view{};
};
disas_.setCsrNameCallback(callback);
using IC = InterruptCause;
// Define the default machine interrupts in high to low priority. VS interrupts
// VSTIP/VSEIP/VSSIP are always delegated to supervisor privilege (section 19.4.2 of
// privileged spec).
mInterrupts_ = { IC::M_EXTERNAL, IC::M_SOFTWARE, IC::M_TIMER,
IC::S_EXTERNAL, IC::S_SOFTWARE, IC::S_TIMER,
IC::G_EXTERNAL, IC::LCOF };
// Define the default supervisor (S/HS) interrupts in high to low priority.
sInterrupts_ = { IC::M_EXTERNAL, IC::M_SOFTWARE, IC::M_TIMER,
IC::S_EXTERNAL, IC::S_SOFTWARE, IC::S_TIMER,
IC::G_EXTERNAL, IC::VS_EXTERNAL, IC::VS_SOFTWARE,
IC::VS_TIMER, IC::LCOF };
// Define the virtual supervisor (VS) interrupts in high to low priority.
vsInterrupts_ = { IC::VS_EXTERNAL, IC::VS_SOFTWARE, IC::VS_TIMER, IC::LCOF };
// Define possible NMIs.
nmInterrupts_ = { 0xf0001000, 0xf0000001, 0xf0000000, 3, 2, 1, 0 };
}
template <typename URV>
Hart<URV>::~Hart()
{
if (branchBuffer_.max_size() and not branchTraceFile_.empty())
saveBranchTrace(branchTraceFile_);
if (cacheBuffer_.max_size() and not cacheTraceFile_.empty())
saveCacheTrace(cacheTraceFile_);
}
template <typename URV>
void Hart<URV>::filterMachineInterrupts(bool verbose) {
// Get the poke masks for the MIP and MIE CSRs.
const Csr<URV>* mipCsr = csRegs_.findCsr(CsrNumber::MIP);
const Csr<URV>* mieCsr = csRegs_.findCsr(CsrNumber::MIE);
URV maskMIP = mipCsr->getPokeMask();
URV maskMIE = mieCsr->getPokeMask();
// Combine the masks (only bits allowed in both are effective).
URV combinedMask = maskMIP & maskMIE;
// For each bit allowed by the hardware, warn if the user did not provide it.
if (verbose) {
// Build a set of the interrupt causes provided by the user.
std::unordered_set<unsigned> userCauses;
for (const auto &ic : mInterrupts_)
userCauses.insert(static_cast<unsigned>(ic));
for (unsigned bitPos = 0; bitPos < sizeof(URV) * 8; ++bitPos) {
if (combinedMask & (URV(1) << bitPos)) {
if (userCauses.find(bitPos) == userCauses.end()) {
std::cerr << "Warning: Interrupt cause " << bitPos
<< " is allowed by hardware mask but not provided in configuration.\n";
}
}
}
}
// Remove any interrupt cause for which the corresponding bit in the combined mask is 0.
mInterrupts_.erase(
std::remove_if(
mInterrupts_.begin(), mInterrupts_.end(),
[combinedMask](InterruptCause ic) {
auto bitPos = static_cast<unsigned>(ic);
return ((combinedMask & (URV(1) << bitPos)) == 0);
}
),
mInterrupts_.end()
);
}
template <typename URV>
void Hart<URV>::filterSupervisorInterrupts(bool verbose) {
// Get the poke masks for SIP and SIE.
const Csr<URV>* sipCsr = csRegs_.findCsr(CsrNumber::SIP);
const Csr<URV>* sieCsr = csRegs_.findCsr(CsrNumber::SIE);
URV maskSIP = sipCsr->getPokeMask();
URV maskSIE = sieCsr->getPokeMask();
// Combined mask: only bits allowed by both.
URV combinedMask = maskSIP & maskSIE;
// Always allow S_EXTERNAL regardless of the mask.
const auto s_external = static_cast<unsigned>(InterruptCause::S_EXTERNAL);
combinedMask |= (URV(1) << s_external);
// Warn if a bit is allowed by hardware but not configured.
if (verbose) {
std::unordered_set<unsigned> userCauses;
for (const auto &ic : sInterrupts_)
userCauses.insert(static_cast<unsigned>(ic));
for (unsigned bitPos = 0; bitPos < sizeof(URV) * 8; ++bitPos) {
if (combinedMask & (URV(1) << bitPos)) {
if (userCauses.find(bitPos) == userCauses.end())
std::cerr << "Error: Supervisor interrupt cause " << bitPos
<< " allowed by hardware but missing in configuration.\n";
}
}
}
// Remove any supervisor interrupt cause whose bit is 0 in the mask.
sInterrupts_.erase(
std::remove_if(
sInterrupts_.begin(), sInterrupts_.end(),
[combinedMask](InterruptCause ic) {
auto bitPos = static_cast<unsigned>(ic);
return ((combinedMask & (URV(1) << bitPos)) == 0);
}
),
sInterrupts_.end()
);
}
template <typename URV>
void
Hart<URV>::tieCsrs()
{
// Tie the retired instruction and cycle counter CSRs to variables held in the hart.
if constexpr (sizeof(URV) == 4)
{
virtMem_.setSupportedModes({VirtMem::Mode::Bare, VirtMem::Mode::Sv32});
auto split = util::view_arith_as_arr_of<URV>(retiredInsts_);
csRegs_.findCsr(CsrNumber::MINSTRET)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::INSTRET)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::MINSTRETH)->tie(&split[1]);
csRegs_.findCsr(CsrNumber::INSTRETH)->tie(&split[1]);
split = util::view_arith_as_arr_of<URV>(cycleCount_);
csRegs_.findCsr(CsrNumber::MCYCLE)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::CYCLE)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::MCYCLEH)->tie(&split[1]);
csRegs_.findCsr(CsrNumber::CYCLEH)->tie(&split[1]);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
split = util::view_arith_as_arr_of<URV>(time_);
csRegs_.findCsr(CsrNumber::TIME)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::TIMEH)->tie(&split[1]);
split = util::view_arith_as_arr_of<URV>(stimecmp_);
csRegs_.findCsr(CsrNumber::STIMECMP)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::STIMECMPH)->tie(&split[1]);
split = util::view_arith_as_arr_of<URV>(vstimecmp_);
csRegs_.findCsr(CsrNumber::VSTIMECMP)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::VSTIMECMPH)->tie(&split[1]);
split = util::view_arith_as_arr_of<URV>(htimedelta_);
csRegs_.findCsr(CsrNumber::HTIMEDELTA)->tie(&split[0]);
csRegs_.findCsr(CsrNumber::HTIMEDELTAH)->tie(&split[1]);
}
else
{
virtMem_.setSupportedModes({VirtMem::Mode::Bare, VirtMem::Mode::Sv39,
VirtMem::Mode::Sv48, VirtMem::Mode::Sv57 });
csRegs_.findCsr(CsrNumber::MINSTRET)->tie(&retiredInsts_);
csRegs_.findCsr(CsrNumber::MCYCLE)->tie(&cycleCount_);
// INSTRET and CYCLE are read-only shadows of MINSTRET and MCYCLE.
csRegs_.findCsr(CsrNumber::INSTRET)->tie(&retiredInsts_);
csRegs_.findCsr(CsrNumber::CYCLE)->tie(&cycleCount_);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
csRegs_.findCsr(CsrNumber::TIME)->tie(&time_);
csRegs_.findCsr(CsrNumber::STIMECMP)->tie(&stimecmp_);
csRegs_.findCsr(CsrNumber::VSTIMECMP)->tie(&vstimecmp_);
csRegs_.findCsr(CsrNumber::HTIMEDELTA)->tie(&htimedelta_);
}
// Tie the FCSR register to variable held in the hart.
csRegs_.findCsr(CsrNumber::FCSR)->tie(&fcsrValue_);
// Tie the SSP register to variable held in the hart.
csRegs_.findCsr(CsrNumber::SSP)->tie(&ssp_);
}
template <typename URV>
void
Hart<URV>::setupVirtMemCallbacks()
{
virtMem_.setMemReadCallback([this](uint64_t addr, bool bigEndian, unsigned size, uint64_t& data) -> bool {
if (steeEnabled_)
{
if (!stee_.isValidAddress(addr))
return false;
addr = stee_.clearSecureBits(addr);
}
// Proceed with normal memory read based on size.
bool result = false;
if (size == 4) {
uint32_t data32 = 0;
result = ((mcm_ and dataCache_) ?
peekMemory(addr, data32, false) :
memory_.read(addr, data32));
if (result) {
if (bigEndian)
data32 = util::byteswap(data32);
data = data32;
}
} else if (size == 8) {
uint64_t data64 = 0;
result = ((mcm_ and dataCache_) ?
peekMemory(addr, data64, false) :
memory_.read(addr, data64));
if (result) {
if (bigEndian)
data64 = util::byteswap(data64);
data = data64;
}
}
return result;
});
virtMem_.setMemWriteCallback([this](uint64_t addr, bool bigEndian, unsigned size, uint64_t data) -> bool {
if (steeEnabled_)
{
if (!stee_.isValidAddress(addr))
return false;
addr = stee_.clearSecureBits(addr);
}
if (not memory_.hasReserveAttribute(addr))
return false;
if (size == 4)
{
auto value = static_cast<uint32_t>(data);
if (bigEndian)
value = util::byteswap(value);
if (mcm_ and dataCache_)
{
bool ok = true;
for (unsigned i = 0; i < 4; ++i)
ok = ok and pokeMcmCache<McmMem::Data>(addr + i, (value >> uint8_t(8*i)));
return ok;
}
return memory_.write(hartIx_, addr, value);
}
if (size == 8)
{
auto value = data;
if (bigEndian)
value = util::byteswap(value);
if (mcm_ and dataCache_)
{
bool ok = true;
for (unsigned i = 0; i < 8; ++i)
ok = ok and pokeMcmCache<McmMem::Data>(addr + i, (value >> uint8_t(8*i)));
return ok;
}
return memory_.write(hartIx_, addr, value);
}
return false;
});
virtMem_.setIsReadableCallback([this](uint64_t addr) -> bool {
if (pmpManager_.isEnabled())
{
const Pmp& pmp = pmpManager_.accessPmp(addr);
if (not pmp.isRead(PrivilegeMode::Supervisor))
return false;
}
if (steeEnabled_)
{
if (!stee_.isValidAddress(addr))
return false;
addr = stee_.clearSecureBits(addr);
}
auto pma = memory_.pmaMgr_.accessPma(addr);
return pma.isRead();
});
virtMem_.setIsWritableCallback([this](uint64_t addr) -> bool {
if (pmpManager_.isEnabled())
{
const Pmp& pmp = pmpManager_.accessPmp(addr);
if (not pmp.isWrite(PrivilegeMode::Supervisor))
return false;
}
if (steeEnabled_)
{
if (!stee_.isValidAddress(addr))
return false;
addr = stee_.clearSecureBits(addr);
}
auto pma = memory_.pmaMgr_.accessPma(addr);
// return pma.isWrite() and pma.isRsrv(); // FIX: RTL does not do this. It should.
return pma.isWrite();
});
}
template <typename URV>
void
Hart<URV>::getImplementedCsrs(std::vector<CsrNumber>& vec) const
{
vec.clear();
for (unsigned i = 0; i <= unsigned(CsrNumber::MAX_CSR_); ++i)
{
auto csrn = CsrNumber(i);
if (csRegs_.isImplemented(csrn))
vec.push_back(csrn);
}
}
template <typename URV>
unsigned
Hart<URV>::countImplementedPmpRegisters() const
{
using std::cerr;
unsigned count = 0;
auto num = unsigned(CsrNumber::PMPADDR0);
for (unsigned ix = 0; ix < 64; ++ix, ++num)
if (csRegs_.isImplemented(CsrNumber(num)))
count++;
if (count and count != 16 and count != 64 and hartIx_ == 0)
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 < 16; ++ix, ++num)
if (csRegs_.isImplemented(CsrNumber(num)))
cfgCount++;
if (count and cfgCount != 4 and cfgCount != 16 and hartIx_ == 0)
cerr << "Warning: Physical memory protection enabled but only "
<< cfgCount << "/16" << " PMPCFG CSRs implemented\n";
}
else
{
num = unsigned(CsrNumber::PMPCFG0);
for (unsigned ix = 0; ix < 16; ++ix, ++num)
if (csRegs_.isImplemented(CsrNumber(num)))
{
if ((ix & 1) == 1)
cerr << "Error: Odd numbered PMPCFG" << ix << " CSR should not be implemented.\n";
cfgCount++;
}
// Count should be 0, 16, or 14. cfgCount should be count/8.
if (cfgCount != count / 8)
{
cerr << "Error: The number of implemented PMPADDR CSRs is " << count
<< ", but the number of implemented PMPCFG CSRs is " << cfgCount
<< " (should be " << count << "/8 = " << (count/8) << ")\n";
}
}
return count;
}
template <typename URV>
void
Hart<URV>::processExtensions(bool verbose)
{
URV value = 0;
if (not peekCsr(CsrNumber::MISA, value))
std::cerr << "Error: CSR MISA is not defined\n";
bool flag = value & (URV(1) << ('s' - 'a')); // Supervisor-mode option.
flag = flag and isa_.isEnabled(RvExtension::S);
enableSupervisorMode(flag);
flag = value & (URV(1) << ('u' - 'a')); // User-mode option.
flag = flag and isa_.isEnabled(RvExtension::U);
enableUserMode(flag);
flag = value & (URV(1) << ('h' - 'a')); // Hypervisor.
flag = flag and isa_.isEnabled(RvExtension::H);
enableHypervisorMode(flag);
flag = (value & 1) and isa_.isEnabled(RvExtension::A); // Atomic
enableExtension(RvExtension::A, flag);
flag = (value & 2) and isa_.isEnabled(RvExtension::B); // Bit-manip
enableExtension(RvExtension::B, flag);
flag = (value & (URV(1) << ('c' - 'a'))); // Compress option.
flag = flag and (isa_.isEnabled(RvExtension::C) or isa_.isEnabled(RvExtension::Zca));
enableRvc(flag);
flag = value & (URV(1) << ('f' - 'a')); // Single precision FP
flag = flag and isa_.isEnabled(RvExtension::F);
enableRvf(flag);
// D requires F and is enabled only if F is enabled.
flag = value & (URV(1) << ('d' - 'a')); // Double precision FP
flag = flag and isa_.isEnabled(RvExtension::D);
if (flag and not extensionIsEnabled(RvExtension::F))
{
flag = false;
if (verbose and hartIx_ == 0)
std::cerr << "Warning: Bit 3 (d) is set in the MISA register but f "
<< "extension (bit 5) is not enabled -- ignored\n";
}
enableRvd(flag);
flag = value & (URV(1) << ('e' - 'a'));
flag = flag and isa_.isEnabled(RvExtension::E);
if (flag)
intRegs_.regs_.resize(16);
enableExtension(RvExtension::E, flag);
flag = value & (URV(1) << ('i' - 'a'));
if (not flag and not extensionIsEnabled(RvExtension::E) and verbose and hartIx_ == 0)
std::cerr << "Warning: Bit 8 (i extension) is cleared in the MISA register "
<< " but extension is mandatory -- assuming bit 8 set\n";
flag = value & (URV(1) << ('m' - 'a'));
flag = flag and isa_.isEnabled(RvExtension::M);
enableExtension(RvExtension::M, flag);
flag = value & (URV(1) << ('v' - 'a')); // User-mode option.
if (flag and not (extensionIsEnabled(RvExtension::F) and extensionIsEnabled(RvExtension::D)))
{
flag = false;
if (verbose and hartIx_ == 0)
std::cerr << "Warning: Bit 21 (v) is set in the MISA register but the d/f "
<< "extensions are not enabled -- ignored\n";
}
flag = flag and isa_.isEnabled(RvExtension::V);
enableVectorExtension(flag);
if (verbose and hartIx_ == 0)
for (auto ec : { 'j', 'k', 'l', 'n', 'o', 'p',
'q', 'r', 't', 'w', 'x', 'y', 'z' } )
{
unsigned bit = ec - 'a';
if (value & (URV(1) << bit))
std::cerr << "Warninig: Bit " << bit << " (" << ec << ") set in the MISA "
<< "register but extension is not supported "
<< "-- ignored\n";
}
enableExtension(RvExtension::Zba, isa_.isEnabled(RvExtension::Zba));
enableExtension(RvExtension::Zbb, isa_.isEnabled(RvExtension::Zbb));
enableExtension(RvExtension::Zbc, isa_.isEnabled(RvExtension::Zbc));
enableExtension(RvExtension::Zbs, isa_.isEnabled(RvExtension::Zbs));
enableExtension(RvExtension::Zfbfmin, isa_.isEnabled(RvExtension::Zfbfmin));
enableExtension(RvExtension::Zfh, isa_.isEnabled(RvExtension::Zfh));
enableExtension(RvExtension::Zfhmin, isa_.isEnabled(RvExtension::Zfhmin));
enableExtension(RvExtension::Zknd, isa_.isEnabled(RvExtension::Zknd));
enableExtension(RvExtension::Zkne, isa_.isEnabled(RvExtension::Zkne));
enableExtension(RvExtension::Zknh, isa_.isEnabled(RvExtension::Zknh));
enableExtension(RvExtension::Zbkb, isa_.isEnabled(RvExtension::Zbkb));
enableExtension(RvExtension::Zbkc, isa_.isEnabled(RvExtension::Zbkc));
enableExtension(RvExtension::Zbkx, isa_.isEnabled(RvExtension::Zbkx));
enableExtension(RvExtension::Zksed, isa_.isEnabled(RvExtension::Zksed));
enableExtension(RvExtension::Zksh, isa_.isEnabled(RvExtension::Zksh));
enableExtension(RvExtension::Zicbom, isa_.isEnabled(RvExtension::Zicbom));
enableExtension(RvExtension::Zicboz, isa_.isEnabled(RvExtension::Zicboz));
enableExtension(RvExtension::Zicbop, isa_.isEnabled(RvExtension::Zicbop));
enableExtension(RvExtension::Zawrs, isa_.isEnabled(RvExtension::Zawrs));
enableExtension(RvExtension::Zmmul, isa_.isEnabled(RvExtension::Zmmul));
enableExtension(RvExtension::Zvbb, isa_.isEnabled(RvExtension::Zvbb));
enableExtension(RvExtension::Zvbc, isa_.isEnabled(RvExtension::Zvbc));
enableExtension(RvExtension::Zvfbfmin, isa_.isEnabled(RvExtension::Zvfbfmin));
enableExtension(RvExtension::Zvfbfwma, isa_.isEnabled(RvExtension::Zvfbfwma));
enableExtension(RvExtension::Zvqdot, isa_.isEnabled(RvExtension::Zvqdot));
enableExtension(RvExtension::Zvfh, isa_.isEnabled(RvExtension::Zvfh));
enableExtension(RvExtension::Zvfhmin, isa_.isEnabled(RvExtension::Zvfhmin));
enableExtension(RvExtension::Zvkg, isa_.isEnabled(RvExtension::Zvkg));
enableExtension(RvExtension::Zvkned, isa_.isEnabled(RvExtension::Zvkned));
enableExtension(RvExtension::Zvknha, isa_.isEnabled(RvExtension::Zvknha));
enableExtension(RvExtension::Zvknhb, isa_.isEnabled(RvExtension::Zvknhb));
enableExtension(RvExtension::Zvksed, isa_.isEnabled(RvExtension::Zvksed));
enableExtension(RvExtension::Zvksh, isa_.isEnabled(RvExtension::Zvksh));
enableExtension(RvExtension::Zvkb, isa_.isEnabled(RvExtension::Zvkb));
enableExtension(RvExtension::Zvzip, isa_.isEnabled(RvExtension::Zvzip));
enableExtension(RvExtension::Zvabd, isa_.isEnabled(RvExtension::Zvabd));
enableExtension(RvExtension::Zicond, isa_.isEnabled(RvExtension::Zicond));
enableExtension(RvExtension::Zca, isa_.isEnabled(RvExtension::Zca));
enableExtension(RvExtension::Zcb, isa_.isEnabled(RvExtension::Zcb));
enableExtension(RvExtension::Zfa, isa_.isEnabled(RvExtension::Zfa));
enableExtension(RvExtension::Zacas, isa_.isEnabled(RvExtension::Zacas));
enableExtension(RvExtension::Zimop, isa_.isEnabled(RvExtension::Zimop));
enableExtension(RvExtension::Zcmop, isa_.isEnabled(RvExtension::Zcmop));
enableExtension(RvExtension::Smaia, isa_.isEnabled(RvExtension::Smaia));
enableExtension(RvExtension::Ssaia, isa_.isEnabled(RvExtension::Ssaia));
enableExtension(RvExtension::Smdbltrp, isa_.isEnabled(RvExtension::Smdbltrp));
enableExtension(RvExtension::Zicsr, true /*isa_.isEnabled(RvExtension::Zicsr)*/); // Default true until we fix riscof
enableExtension(RvExtension::Zifencei, true /*isa_.isEnabled(RvExtension::Zifencei)*/); // Default true until RTL catches up
enableExtension(RvExtension::Zaamo, isa_.isEnabled(RvExtension::Zaamo));
enableExtension(RvExtension::Zalrsc, isa_.isEnabled(RvExtension::Zalrsc));
enableExtension(RvExtension::Zabha, isa_.isEnabled(RvExtension::Zabha));
enableExtension(RvExtension::Zalasr, isa_.isEnabled(RvExtension::Zalasr));
if (isa_.isEnabled(RvExtension::Sstc))
enableRvsstc(true);
if (isa_.isEnabled(RvExtension::Svinval))
enableSvinval(true);
if (isa_.isEnabled(RvExtension::Svnapot))
enableTranslationNapot(true);
if (isa_.isEnabled(RvExtension::Svpbmt))
enableTranslationPbmt(true);
if (isa_.isEnabled(RvExtension::Svadu))
enableTranslationAdu(true);
if (isa_.isEnabled(RvExtension::Smrnmi))
enableSmrnmi(true);
if (isa_.isEnabled(RvExtension::Zicntr))
enableZicntr(true);
if (isa_.isEnabled(RvExtension::Zihpm))
enableZihpm(true);
if (isa_.isEnabled(RvExtension::Sscofpmf))
enableSscofpmf(true);
if (isa_.isEnabled(RvExtension::Zkr))
enableZkr(true);
if (isa_.isEnabled(RvExtension::Smstateen))
enableSmstateen(true);
if (isa_.isEnabled(RvExtension::Ssqosid))
enableSsqosid(true);
if (isa_.isEnabled(RvExtension::Sdtrig))
enableSdtrig(true);
if (isa_.isEnabled(RvExtension::Zvknha) and isa_.isEnabled(RvExtension::Zvknhb))
{
std::cerr << "Info: Both Zvknha/b enabled.";
if (rv64_)
{
std::cerr << "Info: Using Zvknhb.\n";
enableExtension(RvExtension::Zvknha, false);
}
else
{
std::cerr << "Info: Using Zvknha.\n";
enableExtension(RvExtension::Zvknhb, false);
}
}
enableSmmpm(isa_.isEnabled(RvExtension::Smmpm));
enableSsnpm(isa_.isEnabled(RvExtension::Ssnpm));
enableSmnpm(isa_.isEnabled(RvExtension::Smnpm));
enableAiaExtension(isa_.isEnabled(RvExtension::Smaia));
enableZicfilp(isa_.isEnabled(RvExtension::Zicfilp));
enableZicfiss(isa_.isEnabled(RvExtension::Zicfiss));
enableZibi(isa_.isEnabled(RvExtension::Zibi));
bool zca = isRvc() or isa_.isEnabled(RvExtension::Zca); // C implies Zca
enableExtension(RvExtension::Zca, zca);
if (isa_.isEnabled(RvExtension::Zcd) and not zca)
std::cerr << "Warning: Zcd extension enabled but pre-requisite Zca extension is not\n";
bool zcd = isRvc() and isRvd(); // C+D implise Zcd
zcd = zcd or (zca and isa_.isEnabled(RvExtension::Zcd)); // Zcd explcitly enabled.
enableExtension(RvExtension::Zcd, zcd);
if (isRv64())
{
if (isa_.isEnabled(RvExtension::Zcf))
std::cerr << "Warning: Zcf extension enabled in Rv64\n";
}
else
{
if (isa_.isEnabled(RvExtension::Zcf) and not zca)
std::cerr << "Warning: Zcf extension enabled but pre-requisite Zca extension is not\n";
bool zcf = isRvc() and isRvf(); // C+F implise Zcf
zcf = zcf or (zca and isa_.isEnabled(RvExtension::Zcf)); // Zcf explcitly enabled.
enableExtension(RvExtension::Zcf, zcf);
}
stimecmpActive_ = csRegs_.menvcfgStce();
vstimecmpActive_ = csRegs_.henvcfgStce();
}
template <typename URV>
void
Hart<URV>::updateMemoryProtection()
{
pmpManager_.reset();
const unsigned count = 64;
unsigned impCount = 0; // Count of implemented PMP registers
for (unsigned ix = 0; ix < count; ++ix)
{
uint64_t low = 0, high = 0;
Pmp::Type type = Pmp::Type::Off;
Pmp::Mode mode = Pmp::Mode::None;
bool locked = false;
if (unpackMemoryProtection(ix, type, mode, locked, low, high))
{
impCount++;
if (type != Pmp::Type::Off)
pmpManager_.defineRegion(low, high, type, mode, ix, locked);
}
}
#ifndef FAST_SLOPPY
pmpEnabled_ = impCount > 0;
#endif
pmpManager_.enable(pmpEnabled_);
}
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 >= 64)
return false;
auto csrn = CsrNumber(unsigned(CsrNumber::PMPADDR0) + entryIx);
URV pmpVal = 0;
if (not peekCsr(csrn, pmpVal))
return false; // PMPADDRn not implemented.
URV lowerVal = 0; // Value of preceding PMPADDR CSR if any.
if (entryIx > 0)
{
auto lowerCsrn = CsrNumber(unsigned(csrn) - 1);
if (not peekCsr(lowerCsrn, lowerVal))
return false; // Should not happen
}
unsigned config = csRegs_.getPmpConfigByteFromPmpAddr(csrn);
return pmpManager_.unpackMemoryProtection(config, pmpVal, lowerVal, not rv64_,
mode, type, locked, low, high);
}
template <typename URV>
void
Hart<URV>::updateAddressTranslation()
{
URV value = 0;
if (peekCsr(CsrNumber::SATP, value))
{
SatpFields<URV> satp(value);
if constexpr (sizeof(URV) != 4)
if ((satp.bits_.MODE >= 1 and satp.bits_.MODE <= 7) or satp.bits_.MODE >= 12)
satp.bits_.MODE = 0;
if (virtMode_)
virtMem_.configStage1(VirtMem::Mode(satp.bits_.MODE), satp.bits_.ASID, satp.bits_.PPN,
vsstatus_.bits_.SUM);
else
virtMem_.configTranslation(VirtMem::Mode(satp.bits_.MODE), satp.bits_.ASID, satp.bits_.PPN);
}
if (peekCsr(CsrNumber::VSATP, value))
{
SatpFields<URV> satp(value);
if constexpr (sizeof(URV) != 4)
if ((satp.bits_.MODE >= 1 and satp.bits_.MODE <= 7) or satp.bits_.MODE >= 12)
satp.bits_.MODE = 0;
virtMem_.configStage1(VirtMem::Mode(satp.bits_.MODE), satp.bits_.ASID, satp.bits_.PPN,
vsstatus_.bits_.SUM);
}
if (peekCsr(CsrNumber::HGATP, value))
{
HgatpFields<URV> hgatp(value);
virtMem_.configStage2(VirtMem::Mode(hgatp.bits_.MODE), hgatp.bits_.VMID, hgatp.bits_.PPN);
}
}
template <typename URV>
void
Hart<URV>::reset(bool resetMemoryMappedRegs)
{
privMode_ = PrivilegeMode::Machine;
virtMode_ = false;
intRegs_.reset();
csRegs_.reset();
vecRegs_.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(CancelLrCause::RESET); // Clear LR reservation (if any).
clearPendingNmi();
setPc(resetPc_);
currPc_ = pc_;
bbPc_ = pc_;
// Enable extensions if corresponding bits are set in the MISA CSR.
processExtensions();
csRegs_.reset();
effectiveMie_ = csRegs_.effectiveMie();
effectiveSie_ = csRegs_.effectiveSie();
effectiveVsie_ = csRegs_.effectiveVsie();
updateCachedHvictl();
perfControl_ = ~uint32_t(0);
URV value = 0;
if (peekCsr(CsrNumber::MCOUNTINHIBIT, value))
perfControl_ = ~value;
prevPerfControl_ = perfControl_;
debugMode_ = false;
updateCachedTriggerState();
dcsrStepIe_ = false;
dcsrStep_ = false;
if (peekCsr(CsrNumber::DCSR, value))
{
DcsrFields<URV> dcsr(value);
dcsrStep_ = dcsr.bits_.STEP;
dcsrStepIe_ = dcsr.bits_.STEPIE;
}
resetVector();
resetFloat();
if (isRvsmdbltrp())
{
mstatus_.bits_.MDT = 1; // MSTATUS.MDT set to 1 on reset.
writeMstatus();
}
// Update cached values of MSTATUS.
updateCachedMstatus();
if (isRvh())
updateCachedHstatus();
// Update cached shadow stack control flags from envcfg CSRs
updateShadowStackEnable();
updateAddressTranslation();
updateMemoryProtection();
countImplementedPmpRegisters();
csRegs_.updateCounterPrivilege();
alarmLimit_ = alarmInterval_? alarmInterval_ + time_ : ~uint64_t(0);
consecutiveIllegalCount_ = 0;
// Trigger software interrupt in hart 0 on reset.
if (aclintSiOnReset_ and hartIx_ == 0)
pokeMemory(aclintSwStart_, uint32_t(1), true);
clearTraceData();
decoder_.enableRv64(isRv64());
disas_.enableRv64(isRv64());
// Reflect initial state of menvcfg CSR on pbmt and sstc.
updateTranslationPbmt();
updateTranslationAdu();
updateTranslationPmm();
csRegs_.updateSstc();
// If any PMACFG CSR is defined, change the default PMA to no access.
bool hasPmacfg = false;
using CN = CsrNumber;
for (auto ix = unsigned(CN::PMACFG0); ix <= unsigned(CN::PMACFG15); ++ix)
if (csRegs_.getImplementedCsr(CN(ix)))
{
hasPmacfg = true;
URV val = csRegs_.peek(CN(ix));
processPmacfgChange(CN(ix), val);
}
if (hasPmacfg)
{
memory_.pmaMgr_.clearDefaultPma(); // No access.
memory_.pmaMgr_.enableInDefaultPma(Pma::Attrib::MisalAccFault); // Access fault on misal.
}
// Update IID priority for benefit of *topi registers.
csRegs_.updateIidPrio(mInterrupts_, sInterrupts_, vsInterrupts_);
}
template <typename URV>
void
Hart<URV>::resetVector()
{
if (isRvv())
{
bool configured = vecRegs_.registerCount() > 0;
if (not configured) {
constexpr uint32_t bytesPerReg = std::is_same<URV, uint32_t>::value ? 32 : 64;
constexpr uint32_t maxBytesPerElem = std::is_same<URV, uint32_t>::value ? 4 : 8;
vecRegs_.config(
bytesPerReg,
1 /*minBytesPerElem*/,
maxBytesPerElem,
nullptr /*minSewPerLmul*/,
nullptr /*maxSewPerLmul*/
);
}
unsigned bytesPerReg = vecRegs_.bytesPerRegister();
csRegs_.configCsr(CsrNumber::VLENB, true, bytesPerReg, 0, 0, false /*shared*/);
auto vstartBits = static_cast<uint32_t>(std::log2(bytesPerReg*8));
URV vstartMask = (URV(1) << vstartBits) - 1;
auto csr = csRegs_.findCsr(CsrNumber::VSTART);
if (not csr or csr->getWriteMask() != vstartMask)
{
if (hartIx_ == 0 and configured)
std::cerr << "Warning: Write mask of CSR VSTART changed to 0x" << std::hex
<< vstartMask << " to be compatible with VLEN=" << std::dec
<< (bytesPerReg*8) << '\n';
csRegs_.configCsr(CsrNumber::VSTART, true, 0, vstartMask, vstartMask, false);
}
}
// Make cached vector engine parameters match reset value of the VTYPE CSR.
URV value = 0;
if (peekCsr(CsrNumber::VTYPE, value))
{
VtypeFields<URV> vtype(value);
bool vill = vtype.bits_.VILL;
bool ma = vtype.bits_.VMA;
bool ta = vtype.bits_.VTA;
auto gm = GroupMultiplier(vtype.bits_.LMUL);
auto ew = ElementWidth(vtype.bits_.SEW);
vecRegs_.updateConfig(ew, gm, ma, ta, vill);
}
// Update cached VL
if (peekCsr(CsrNumber::VL, value))
vecRegs_.elemCount(value);
// Set VS to initial in MSTATUS if linux/newlib emulation. This
// allows linux/newlib program to run without startup code.
if (isRvv() and (newlib_ or linux_))
{
URV val = csRegs_.peekMstatus();
MstatusFields<URV> fields(val);
fields.bits_.VS = unsigned(VecStatus::Initial);
csRegs_.write(CsrNumber::MSTATUS, PrivilegeMode::Machine, fields.value_);
}
}