forked from tenstorrent/whisper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHart.cpp
12297 lines (9898 loc) · 273 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 <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 "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 << "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, Syscall<URV>& syscall, uint64_t& time)
: hartIx_(hartIx), memory_(memory), intRegs_(32),
fpRegs_(32),
syscall_(syscall),
time_(time),
pmpManager_(memory.size(), UINT64_C(1024)*1024),
virtMem_(hartIx, memory, memory.pageSize(), pmpManager_, 16)
{
// Enable default extensions
for (RvExtension ext : { RvExtension::C,
RvExtension::M })
{
enableExtension(ext, true);
}
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);
// 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});
URV* low = reinterpret_cast<URV*> (&retiredInsts_);
csRegs_.findCsr(CsrNumber::MINSTRET)->tie(low);
csRegs_.findCsr(CsrNumber::INSTRET)->tie(low);
URV* high = low + 1;
csRegs_.findCsr(CsrNumber::MINSTRETH)->tie(high);
csRegs_.findCsr(CsrNumber::INSTRETH)->tie(high);
low = reinterpret_cast<URV*> (&cycleCount_);
csRegs_.findCsr(CsrNumber::MCYCLE)->tie(low);
csRegs_.findCsr(CsrNumber::CYCLE)->tie(low);
high = low + 1;
csRegs_.findCsr(CsrNumber::MCYCLEH)->tie(high);
csRegs_.findCsr(CsrNumber::CYCLEH)->tie(high);
low = reinterpret_cast<URV*>(&time_);
high = low + 1;
csRegs_.findCsr(CsrNumber::TIME)->tie(low);
csRegs_.findCsr(CsrNumber::TIMEH)->tie(high);
low = reinterpret_cast<URV*>(&stimecmp_);
high = low + 1;
csRegs_.findCsr(CsrNumber::STIMECMP)->tie(low);
csRegs_.findCsr(CsrNumber::STIMECMPH)->tie(high);
low = reinterpret_cast<URV*>(&vstimecmp_);
high = low + 1;
csRegs_.findCsr(CsrNumber::VSTIMECMP)->tie(low);
csRegs_.findCsr(CsrNumber::VSTIMECMPH)->tie(high);
low = reinterpret_cast<URV*>(&htimedelta_);
high = low + 1;
csRegs_.findCsr(CsrNumber::HTIMEDELTA)->tie(low);
csRegs_.findCsr(CsrNumber::HTIMEDELTAH)->tie(high);
}
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_);
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_);
// 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);
}
template <typename URV>
Hart<URV>::~Hart()
{
if (branchBuffer_.max_size() and not branchTraceFile_.empty())
saveBranchTrace(branchTraceFile_);
}
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>
unsigned
Hart<URV>::countImplementedPmpRegisters() const
{
using std::cerr;
unsigned count = 0;
unsigned 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)))
cfgCount++;
if (count and cfgCount != 2 and cfgCount != 8 and hartIx_ == 0) // Only even numbered implemented.
cerr << "Warning: Physical memory protection enabled but only "
<< cfgCount << "/8" << " PMPCFG CSRs implemented.\n";
}
return count;
}
template <typename URV>
void
Hart<URV>::processExtensions(bool verbose)
{
URV value = 0;
if (not peekCsr(CsrNumber::MISA, value))
std::cerr << "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);
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 << "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 << "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 << "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 << "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::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::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::Zicond, isa_.isEnabled(RvExtension::Zicond));
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::Zicsr, true /*isa_.isEnabled(RvExtension::Zicsr)*/);
enableExtension(RvExtension::Zifencei, true /*isa_.isEnabled(RvExtension::Zifencei)*/);
if (isa_.isEnabled(RvExtension::Sstc))
enableRvsstc(true);
if (isa_.isEnabled(RvExtension::Svinval))
enableSvinval(true);
if (isa_.isEnabled(RvExtension::Svpbmt))
enableTranslationPbmt(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::Zvknha) and
isa_.isEnabled(RvExtension::Zvknhb))
{
std::cerr << "Warning: Both Zvknha/b enabled. Using Zvknhb.\n";
enableExtension(RvExtension::Zvknha, false);
}
enableSsnpm(isa_.isEnabled(RvExtension::Ssnpm));
enableSmnpm(isa_.isEnabled(RvExtension::Smnpm));
enableAiaExtension(isa_.isEnabled(RvExtension::Smaia));
stimecmpActive_ = csRegs_.menvcfgStce();
vstimecmpActive_ = csRegs_.henvcfgStce();
}
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 = 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;
CsrNumber csrn = CsrNumber(unsigned(CsrNumber::PMPADDR0) + entryIx);
unsigned config = csRegs_.getPmpConfigByteFromPmpAddr(csrn);
type = Pmp::Type((config >> 3) & 3);
locked = config & 0x80;
mode = getModeFromPmpconfigByte(config);
URV pmpVal = 0;
if (not peekCsr(csrn, pmpVal))
return false; // PMPADDRn not implemented.
if (type == Pmp::Type::Off)
return true; // Entry is off.
unsigned pmpG = csRegs_.getPmpG();
if (type == Pmp::Type::Tor) // Top of range
{
if (entryIx > 0)
{
CsrNumber lowerCsrn = CsrNumber(unsigned(csrn) - 1);
URV lowerVal = 0;
if (not peekCsr(lowerCsrn, lowerVal))
return false; // Should not happen
low = lowerVal;
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 = std::countr_zero(~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()
{
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_.setVsMode(VirtMem::Mode(satp.bits_.MODE));
virtMem_.setVsAsid(satp.bits_.ASID);
virtMem_.setVsRootPage(satp.bits_.PPN);
}
else
{
virtMem_.setMode(VirtMem::Mode(satp.bits_.MODE));
virtMem_.setAsid(satp.bits_.ASID);
virtMem_.setRootPage(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_.setVsMode(VirtMem::Mode(satp.bits_.MODE));
virtMem_.setVsAsid(satp.bits_.ASID);
virtMem_.setVsRootPage(satp.bits_.PPN);
}
if (peekCsr(CsrNumber::HGATP, value))
{
HgatpFields<URV> hgatp(value);
virtMem_.setStage2Mode(VirtMem::Mode(hgatp.bits_.MODE));
virtMem_.setVmid(hgatp.bits_.VMID);
virtMem_.setStage2RootPage(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();
effectiveIe_ = csRegs_.effectiveInterruptEnable();
perfControl_ = ~uint32_t(0);
URV value = 0;
if (peekCsr(CsrNumber::MCOUNTINHIBIT, value))
perfControl_ = ~value;
prevPerfControl_ = perfControl_;
debugMode_ = false;
dcsrStepIe_ = false;
dcsrStep_ = false;
if (peekCsr(CsrNumber::DCSR, value))
{
DcsrFields<URV> dcsr(value);
dcsrStep_ = dcsr.bits_.STEP;
dcsrStepIe_ = dcsr.bits_.STEPIE;
}
resetVector();
resetFloat();
// Update cached values of MSTATUS.
updateCachedMstatus();
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();
csRegs_.updateSstc();
// If any PMACFG CSR is defined, change the default PMA to no access.
bool hasPmacfg = false;
using CN = CsrNumber;
for (unsigned ix = unsigned(CN::PMACFG0); ix <= unsigned(CN::PMACFG15); ++ix)
if (csRegs_.getImplementedCsr(CN(ix)))
{
hasPmacfg = true;
processPmaChange(CN(ix));
}
if (hasPmacfg)
memory_.pmaMgr_.clearDefaultPma();
}
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*/);
uint32_t 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;
GroupMultiplier gm = GroupMultiplier(vtype.bits_.LMUL);
ElementWidth 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_);
}
}
namespace WdRiscv
{
template <>
void
Hart<uint32_t>::updateCachedMstatus()
{
uint32_t csrVal = csRegs_.peekMstatus();
mstatus_.value_.low_ = csrVal;
csrVal = peekCsr(CsrNumber::MSTATUSH);
mstatus_.value_.high_ = csrVal;
virtMem_.setExecReadable(mstatus_.bits_.MXR);
virtMem_.setStage1ExecReadable(mstatus_.bits_.MXR);
virtMem_.setSum(mstatus_.bits_.SUM);
if (virtMode_)
updateCachedVsstatus();
updateBigEndian();
}
template <>
void
Hart<uint64_t>::updateCachedMstatus()
{
uint64_t csrVal = csRegs_.peekMstatus();
mstatus_.value_ = csrVal;
virtMem_.setExecReadable(mstatus_.bits_.MXR);
virtMem_.setStage1ExecReadable(mstatus_.bits_.MXR);
virtMem_.setSum(mstatus_.bits_.SUM);
if (virtMode_)
updateCachedVsstatus();
updateBigEndian();
}
template <>
void
Hart<uint32_t>::writeMstatus()
{
csRegs_.poke(CsrNumber::MSTATUS, mstatus_.value_.low_);
csRegs_.poke(CsrNumber::MSTATUSH, mstatus_.value_.high_);
csRegs_.recordWrite(CsrNumber::MSTATUS);
csRegs_.recordWrite(CsrNumber::MSTATUSH);
updateCachedMstatus();
}
template <>
void
Hart<uint64_t>::writeMstatus()
{
csRegs_.poke(CsrNumber::MSTATUS, mstatus_.value_);
csRegs_.recordWrite(CsrNumber::MSTATUS);
updateCachedMstatus();
}
}
template <typename URV>
void
Hart<URV>::updateCachedVsstatus()
{
vsstatus_.value_ = peekCsr(CsrNumber::VSSTATUS);
virtMem_.setStage1ExecReadable(vsstatus_.bits_.MXR);
virtMem_.setVsSum(vsstatus_.bits_.SUM);
updateBigEndian();
}
template <typename URV>
void
Hart<URV>::updateCachedHstatus()
{
hstatus_.value_ = peekCsr(CsrNumber::HSTATUS);
updateBigEndian();
}
template <typename URV>
void
Hart<URV>::updateBigEndian()
{
PrivilegeMode pm = privMode_;
bool virt = virtMode_;
if (mstatusMprv() and not nmieOverridesMprv())
{
pm = mstatusMpp();
virt = mstatus_.bits_.MPV;
}
if (pm == PrivilegeMode::Machine)
bigEnd_ = mstatus_.bits_.MBE;
else if (pm == PrivilegeMode::Supervisor)
bigEnd_ = virt? hstatus_.bits_.VSBE : mstatus_.bits_.SBE;
else if (pm == PrivilegeMode::User)
bigEnd_ = virt? vsstatus_.bits_.UBE : mstatus_.bits_.UBE;
if (pm != PrivilegeMode::Machine)
{
bool tbe = virt? hstatus_.bits_.VSBE : mstatus_.bits_.SBE; // translatiom big end
virtMem_.setBigEndian(tbe);
}
}
template <typename URV>
bool
Hart<URV>::peekMemory(uint64_t address, uint8_t& val, bool usePma) const
{
return memory_.peek(address, val, usePma);
}
template <typename URV>
bool
Hart<URV>::peekMemory(uint64_t address, uint16_t& val, bool usePma) const
{
return memory_.peek(address, val, usePma);
}
template <typename URV>
bool
Hart<URV>::peekMemory(uint64_t address, uint32_t& val, bool usePma) const
{
return memory_.peek(address, val, usePma);
}
template <typename URV>
bool
Hart<URV>::peekMemory(uint64_t address, uint64_t& val, bool usePma) const
{
if (memory_.peek(address, val, usePma))
return true;
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(uint64_t addr, uint8_t val, bool usePma)
{
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateOtherHartLr(hartIx_, addr, sizeof(val));
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(uint64_t addr, uint16_t val, bool usePma)
{
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateOtherHartLr(hartIx_, addr, sizeof(val));
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(uint64_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_.invalidateOtherHartLr(hartIx_, addr, sizeof(val));
URV adjusted = val;
if (hasAclint() and ((addr >= aclintSwStart_ and addr < aclintSwEnd_) or
(addr >= aclintMtimerStart_ and addr < aclintMtimerEnd_)))
{
processClintWrite(addr, sizeof(val), adjusted);
val = adjusted;
}
else if ((addr >= imsicMbase_ and addr < imsicMend_) or
(addr >= imsicSbase_ and addr < imsicSend_))
{
if (imsicWrite_)
imsicWrite_(addr, sizeof(val), val);
}
else if (pci_ and ((addr >= pciConfigBase_ and addr < pciConfigEnd_) or
(addr >= pciMmioBase_ and addr < pciMmioEnd_)))
{
if (addr >= pciConfigBase_ and addr < pciConfigEnd_)
pci_->config_mmio<uint32_t>(addr, val, true);
else
pci_->mmio<uint32_t>(addr, val, true);
}
if (memory_.poke(addr, val, usePma))
{
invalidateDecodeCache(addr, sizeof(val));
return true;
}
return false;
}
template <typename URV>
bool
Hart<URV>::pokeMemory(uint64_t addr, uint64_t val, bool usePma)
{
std::lock_guard<std::mutex> lock(memory_.lrMutex_);
memory_.invalidateOtherHartLr(hartIx_, addr, sizeof(val));
URV adjusted = val;
if (hasAclint() and ((addr >= aclintSwStart_ and addr < aclintSwEnd_) or
(addr >= aclintMtimerStart_ and addr < aclintMtimerEnd_)))
{
processClintWrite(addr, sizeof(val), adjusted);
val = adjusted;
}
else if ((addr >= imsicMbase_ and addr < imsicMend_) or