forked from moizumi99/m99_riscv_emulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRISCV_cpu.cc
1862 lines (1769 loc) · 57.4 KB
/
RISCV_cpu.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
#include "RISCV_cpu.h"
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <iostream>
#include "Disassembler.h"
#include "Mmu.h"
#include "bit_tools.h"
#include "instruction_encdec.h"
#include "memory_wrapper.h"
#include "system_call_emulator.h"
namespace RISCV_EMULATOR {
RiscvCpu::RiscvCpu(bool en64bit) {
mxl_ = en64bit ? 2 : 1;
xlen_ = en64bit ? 64 : 32;
privilege_ = PrivilegeMode::MACHINE_MODE;
mstatus_ = 0;
for (int i = 0; i < kRegNum; i++) {
reg_[i] = 0;
}
InitializeCsrs();
ClearTimerInterruptFlag();
peripheral_ = std::make_unique<PeripheralEmulator>(mxl_);
}
RiscvCpu::RiscvCpu() : RiscvCpu(false) {}
void RiscvCpu::ClearTimerInterruptFlag() { timer_interrupt_ = false; }
void RiscvCpu::InitializeCsrs() {
csrs_.resize(kCsrSize, 0);
// U: User mode, S: Supervisor mode, N: User-level Interrupts, I: RV32I/RV64I
// base ISA.
const uint32_t extensions = 0b00000101000010000100000000;
csrs_[MISA] = (mxl_ << (xlen_ - 2)) | extensions;
if (mxl_ == 2) {
// For 64 bit mode, sxl and uxl are the same as mxl.
mstatus_ = (static_cast<uint64_t>(mxl_) << 34) | (static_cast<uint64_t>(mxl_) << 32);
ApplyMstatusToCsr();
}
}
void RiscvCpu::DeviceInitialization() {
if (!peripheral_emulation_) {
return;
}
peripheral_->Initialize();
}
void RiscvCpu::SetDiskImage(std::shared_ptr<std::vector<uint8_t> > disk_image) {
assert(peripheral_ != nullptr);
peripheral_->SetDiskImage(disk_image);
}
uint64_t RiscvCpu::VirtualToPhysical(uint64_t virtual_address, bool write_access) {
mmu_.SetMxl(mxl_);
PrivilegeMode privilege = privilege_;
if (privilege == PrivilegeMode::MACHINE_MODE) {
uint32_t mprv = bitcrop(csrs_[MSTATUS], 1, 17);
if (mprv == 1) {
uint32_t mpp = bitcrop(csrs_[MSTATUS], 2, 11);
privilege = IntToPrivilegeMode(mpp);
}
}
mmu_.SetPrivilege(privilege);
uint64_t physical_address = mmu_.VirtualToPhysical(virtual_address, csrs_[SATP], write_access);
if (mmu_.GetPageFault()) {
page_fault_ = true;
faulting_address_ = mmu_.GetFaultingAddress();
}
return physical_address;
}
// A helper function to record shift sign error.
bool RiscvCpu::CheckShiftSign(uint8_t shamt, uint8_t instruction, const std::string &message_str) {
if (xlen_ == 32 || instruction == INST_SLLIW || instruction == INST_SRAIW || instruction == INST_SRLIW) {
if (shamt >> 5) {
std::cerr << message_str << " Shift value (shamt) error. shamt = " << static_cast<int>(shamt) << std::endl;
return true;
}
}
return false;
}
void RiscvCpu::SetMemory(std::shared_ptr<MemoryWrapper> memory) {
this->memory_ = memory;
peripheral_->SetMemory(memory);
mmu_.SetMemory(memory);
}
uint32_t RiscvCpu::LoadCmd(uint64_t pc) {
auto &mem = *memory_;
uint64_t physical_address = VirtualToPhysical(pc);
uint64_t dram_address = (physical_address >> 2) << 2;
uint32_t cmd = mem.Read32(dram_address);
if ((pc & 0b10) == 0b10) {
cmd = (cmd >> 16) & 0xFFFF;
}
if (!page_fault_ && (pc & 0b10) == 0b10 && (cmd & 0b11) == 0b11) {
uint64_t physical_address_upper = VirtualToPhysical(pc + 2);
uint32_t cmd_upper = mem.Read32((physical_address_upper >> 2) << 2);
cmd = (cmd & 0xFFFF) | (cmd_upper & 0xFFFF) << 16;
}
cmd = (cmd & 0b11) == 0b11 ? cmd : cmd & 0xFFFF;
return cmd;
}
void RiscvCpu::SetRegister(uint32_t num, uint64_t value) { reg_[num] = value; }
uint64_t RiscvCpu::ReadRegister(uint32_t num) { return reg_[num]; }
void RiscvCpu::SetCsr(uint32_t index, uint64_t value) { csrs_[index] = value; }
uint64_t RiscvCpu::ReadCsr(uint32_t index) { return csrs_[index]; }
void RiscvCpu::SetWorkMemory(uint64_t top, uint64_t bottom) {
this->top_ = top;
this->bottom_ = bottom;
}
/* The definition of the Linux system call can be found in
* riscv-gnu-toolchain/linux-headers/include/asm-generic/unistd.h
*/
std::pair<bool, bool> RiscvCpu::SystemCall() { return SystemCallEmulation(memory_, reg_, top_, &brk_); }
uint64_t RiscvCpu::LoadWd(uint64_t physical_address, int width) {
assert(1 <= width && width <= 8);
auto &mem = *memory_;
uint64_t result = 0;
// Mock the 32bit wide access behavior of HW.
if (width == 4 && (physical_address & 0b11) == 0) {
result = mem.Read32(physical_address);
} else if (width == 8 && (physical_address & 0b111) == 0) {
result = mem.Read64(physical_address);
} else {
for (int offset = 0; offset < width; ++offset) {
uint64_t loaded_byte = mem.ReadByte(physical_address + offset);
result |= loaded_byte << offset * 8;
}
}
return result;
}
void RiscvCpu::StoreWd(uint64_t physical_address, uint64_t data, int width) {
auto &mem = *memory_;
assert(1 <= width && width <= 8);
// Mock the 32bit wide access behavior of HW.
if (width == 4 && (physical_address & 0b11) == 0) {
mem.Write32(physical_address, data);
} else if (width == 8 && ((physical_address & 0b111) == 0)) {
mem.Write64(physical_address, data);
} else {
for (int offset = 0; offset < width; ++offset) {
mem.WriteByte(physical_address + offset, (data >> offset * 8) & 0xFF);
}
}
}
void RiscvCpu::Trap(int cause, bool interrupt) {
// Currently supported exceptions: page fault (12, 13, 15) and ecall (8, 9, 11).
// Currently supported interrupts: Supervisor Software Interrupt (1), Machine Timer Intetrupt (7)
assert((interrupt && (cause == MACHINE_TIMER_INTERRUPT || cause == SUPERVISOR_SOFTWARRE_INTERRUPT ||
cause == SUPERVISOR_EXTERNAL_INTERRUPT)) ||
((!interrupt) &
(cause == INSTRUCTION_PAGE_FAULT || cause == LOAD_PAGE_FAULT || cause == STORE_PAGE_FAULT ||
cause == ECALL_UMODE || cause == ECALL_SMODE || cause == ECALL_MMODE)));
// Check the Machine Level Enable.
// Machine interrupt is enabled if the privilege mode is lower than Machine Mode.
const uint64_t global_mie = (privilege_ == PrivilegeMode::MACHINE_MODE && bitcrop(mstatus_, 1, 3) == 1) ||
(privilege_ != PrivilegeMode::MACHINE_MODE);
// Supervisor interrupt is enabled if the privilege mode is lower than supervisor mode.
const uint64_t global_sie = (privilege_ == PrivilegeMode::SUPERVISOR_MODE && bitcrop(mstatus_, 1, 1) == 1) ||
(privilege_ == PrivilegeMode::USER_MODE);
// Interrupt enable condition should be checked before hand in CheckPendingInterrupt().
// Page fault specific processing.
if (!interrupt && (cause == INSTRUCTION_PAGE_FAULT || cause == LOAD_PAGE_FAULT || cause == STORE_PAGE_FAULT)) {
if (prev_page_fault_ && prev_faulting_address_ == faulting_address_) {
std::cerr << "This is a page fault right after another fault at the same "
"address. Exit."
<< std::endl;
error_flag_ = true;
}
prev_page_fault_ = page_fault_;
prev_faulting_address_ = faulting_address_;
page_fault_ = false;
}
// Check supervisor mode delegation status.
// The original machine privilege mode must be user or supervisor mode.
bool sv_delegation = privilege_ == PrivilegeMode::USER_MODE || privilege_ == PrivilegeMode::SUPERVISOR_MODE;
// Check for supervisor delegation bit.
if (interrupt) {
// Supperess machine interrupt delegation for compatibility with QEMU.
const uint64_t mideleg_mask = disable_machine_interrupt_delegation_ ? 0x666 : 0xfff;
const uint64_t mideleg = csrs_[MIDELEG] & mideleg_mask;
sv_delegation &= bitcrop(mideleg, 1, cause) == 1;
} else {
const uint64_t medeleg = csrs_[MEDELEG];
sv_delegation &= bitcrop(medeleg, 1, cause) == 1;
}
// Common process for machine mode and supervisor mode.
// MTVAL, and STVAL.
uint64_t tval = 0;
if (!interrupt) {
if (cause == INSTRUCTION_PAGE_FAULT || cause == LOAD_PAGE_FAULT || cause == STORE_PAGE_FAULT) {
tval = faulting_address_;
} else if (cause == ILLEGAL_INSTRUCTION) {
tval = ir_;
}
}
const uint64_t interrupt_cause_mask = interrupt ? static_cast<uint64_t>(1) << (xlen_ - 1) : 0;
// Processing.
// TODO: Add user delegation.
if (sv_delegation) {
// if (interrupt && cause == SUPERVISOR_EXTERNAL_INTERRUPT) {
// std::cerr << "Supervisor External Interrupt" << std::endl;
// }
csrs_[SCAUSE] = cause | interrupt_cause_mask;
csrs_[SEPC] = pc_;
const uint64_t tvec = csrs_[STVEC];
const uint8_t mode = tvec & 0b11;
if (mode == 0 || interrupt) {
next_pc_ = tvec & ~0b11;
} else {
next_pc_ = (tvec & ~0b11) + 4 * (csrs_[SCAUSE] & GenMask<uint64_t>(xlen_ - 1, 0));
}
csrs_[STVAL] = tval;
// Copy old SIE (#1) to SPIE (#5). Then, disable SIE (#1).
mstatus_ = bitset(mstatus_, 1, 5, global_sie);
constexpr uint64_t kNewSie = 0;
mstatus_ = bitset(mstatus_, 1, 1, kNewSie);
// Save the current privilege mode to SPP (#12-11), and set the privilege to
// Supervisor.
const uint64_t new_mpp = PriviledgeToInt(privilege_);
mstatus_ = bitset(mstatus_, 1, 8, new_mpp);
ApplyMstatusToCsr();
privilege_ = PrivilegeMode::SUPERVISOR_MODE;
} else {
csrs_[MCAUSE] = cause | interrupt_cause_mask;
csrs_[MEPC] = pc_;
const uint64_t tvec = csrs_[MTVEC];
const uint8_t mode = tvec & 0b11;
if (mode == 0 || interrupt) {
next_pc_ = tvec & ~0b11;
} else {
next_pc_ = (tvec & ~0b11) + 4 * (csrs_[MCAUSE] & GenMask<uint64_t>(xlen_ - 1, 0));
}
// Store the faulting address to MTVAL.
csrs_[MTVAL] = tval;
// Copy old MIE (#3) to MPIE (#7). Then, disable MIE.
mstatus_ = bitset(mstatus_, 1, 7, global_mie);
constexpr uint64_t kNewMie = 0;
mstatus_ = bitset(mstatus_, 1, 3, kNewMie);
// Save the current privilege mode to MPP (#12-11), and set the privilege to
// Machine.
const uint64_t new_mpp = PriviledgeToInt(privilege_);
mstatus_ = bitset(mstatus_, 2, 11, new_mpp);
ApplyMstatusToCsr();
// Clear interrupt pending bit.
privilege_ = PrivilegeMode::MACHINE_MODE;
}
// Clear interrupt pending bit.
if (interrupt && cause != SUPERVISOR_SOFTWARRE_INTERRUPT && cause != MACHINE_SOFTWARE_INTERRUPT) {
ClearInterruptPending(cause);
}
ApplyMstatusToCsr();
}
uint64_t kUpper32bitMask = 0xFFFFFFFF00000000;
uint64_t RiscvCpu::Sext32bit(uint64_t data32bit) {
if ((data32bit >> 31) & 1) {
return data32bit | kUpper32bitMask;
} else {
return data32bit & (~kUpper32bitMask);
}
}
void RiscvCpu::CsrsInstruction(uint32_t instruction, uint32_t csr, uint32_t rd, uint32_t rs1) {
uint64_t t = csrs_[csr];
uint64_t new_t = t;
switch (instruction) {
case INST_CSRRC:
new_t &= ~reg_[rs1];
break;
case INST_CSRRCI:
new_t &= ~rs1;
break;
case INST_CSRRS:
new_t |= reg_[rs1];
break;
case INST_CSRRSI:
new_t |= rs1;
break;
case INST_CSRRW:
new_t = reg_[rs1];
break;
case INST_CSRRWI:
new_t = rs1;
break;
default:;
}
// TODO: Check for privilege before writing back to CSR.
csrs_[csr] = new_t;
reg_[rd] = t;
UpdateStatus(csr);
}
uint64_t RiscvCpu::BranchInstruction(uint32_t instruction, uint32_t rs1, uint32_t rs2, int32_t imm13) {
bool condition = false;
switch (instruction) {
case INST_BEQ:
condition = reg_[rs1] == reg_[rs2];
break;
case INST_BGE:
condition = static_cast<int64_t>(reg_[rs1]) >= static_cast<int64_t>(reg_[rs2]);
break;
case INST_BGEU:
condition = reg_[rs1] >= reg_[rs2];
break;
case INST_BLT:
condition = static_cast<int64_t>(reg_[rs1]) < static_cast<int64_t>(reg_[rs2]);
break;
case INST_BLTU:
condition = reg_[rs1] < reg_[rs2];
break;
case INST_BNE:
condition = reg_[rs1] != reg_[rs2];
break;
default:;
}
return condition ? pc_ + imm13 : next_pc_;
}
void RiscvCpu::OperationInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, uint32_t rs2) {
bool w_instruction = instruction == INST_ADDW || instruction == INST_SUBW || instruction == INST_SLLW ||
instruction == INST_SRLW || instruction == INST_SRAW;
uint32_t shift_mask = (xlen_ == 32 || w_instruction) ? 0b0011111 : 0b0111111;
uint64_t temp64;
switch (instruction) {
case INST_ADD:
case INST_ADDW:
temp64 = reg_[rs1] + reg_[rs2];
break;
case INST_SUB:
case INST_SUBW:
temp64 = reg_[rs1] - reg_[rs2];
break;
case INST_AND:
temp64 = reg_[rs1] & reg_[rs2];
break;
case INST_OR:
temp64 = reg_[rs1] | reg_[rs2];
break;
case INST_XOR:
temp64 = reg_[rs1] ^ reg_[rs2];
break;
case INST_SLL:
case INST_SLLW:
temp64 = reg_[rs1] << (reg_[rs2] & shift_mask);
break;
case INST_SRL:
case INST_SRLW:
temp64 = reg_[rs1];
if (xlen_ == 32 || instruction == INST_SRLW) {
temp64 &= 0xFFFFFFFF;
}
temp64 = temp64 >> (reg_[rs2] & shift_mask);
break;
case INST_SRA:
temp64 = static_cast<int64_t>(reg_[rs1]) >> (reg_[rs2] & shift_mask);
break;
case INST_SRAW:
temp64 = Sext32bit(reg_[rs1]) >> (reg_[rs2] & shift_mask);
break;
default:
temp64 = 0;
std::cerr << "Undefined Arithmetic or Logical instruction detected." << std::endl;
assert(false);
}
if (xlen_ == 32 || w_instruction) {
temp64 = Sext32bit(temp64);
}
reg_[rd] = temp64;
}
void RiscvCpu::ImmediateInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, int32_t imm12) {
uint64_t temp64;
switch (instruction) {
case INST_ADDI:
case INST_ADDIW:
temp64 = reg_[rs1] + imm12;
break;
case INST_ANDI:
temp64 = reg_[rs1] & imm12;
break;
case INST_ORI:
temp64 = reg_[rs1] | imm12;
break;
case INST_XORI:
temp64 = reg_[rs1] ^ imm12;
break;
default:
temp64 = 0;
std::cerr << "Unsupported Immediate instruction detected." << std::endl;
assert(false);
}
if (xlen_ == 32 || instruction == INST_ADDIW) {
temp64 = Sext32bit(temp64);
}
reg_[rd] = temp64;
}
void RiscvCpu::ImmediateShiftInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, uint32_t shamt) {
uint64_t temp64;
switch (instruction) {
case INST_SLLI:
temp64 = reg_[rs1] << shamt;
if (xlen_ == 32) {
temp64 = Sext32bit(temp64);
}
reg_[rd] = temp64;
CheckShiftSign(shamt, instruction, "SLLI");
break;
case INST_SLLIW:
temp64 = (reg_[rs1] << shamt) & 0xFFFFFFFF;
temp64 = Sext32bit(temp64);
reg_[rd] = temp64;
CheckShiftSign(shamt, instruction, "SLLIW");
break;
case INST_SRLI:
temp64 = reg_[rs1];
if (xlen_ == 32) {
temp64 &= ~kUpper32bitMask;
}
temp64 = temp64 >> shamt;
if (xlen_ == 32) {
temp64 = Sext32bit(temp64);
}
reg_[rd] = temp64;
CheckShiftSign(shamt, instruction, "SRLI");
break;
case INST_SRLIW:
temp64 = (reg_[rs1] & 0xFFFFFFFF) >> shamt;
temp64 = Sext32bit(temp64);
reg_[rd] = temp64;
CheckShiftSign(shamt, instruction, "SRLIW");
break;
case INST_SRAI:
reg_[rd] = static_cast<int64_t>(reg_[rs1]) >> shamt;
CheckShiftSign(shamt, instruction, "SRAI");
break;
case INST_SRAIW:
reg_[rd] = static_cast<int32_t>(reg_[rs1]) >> shamt;
CheckShiftSign(shamt, instruction, "SRAI");
break;
}
}
int RiscvCpu::GetLoadWidth(uint32_t instruction) {
int width = 8;
switch (instruction) {
case INST_LB:
case INST_LBU:
width = 1;
break;
case INST_LH:
case INST_LHU:
width = 2;
break;
case INST_LW:
case INST_LWU:
width = 4;
break;
case INST_LD:
width = 8;
break;
default:
assert(false);
}
return width;
}
void RiscvCpu::LoadInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, int32_t imm12) {
peripheral_->MemoryMappedValueUpdate();
uint64_t source_address = reg_[rs1] + imm12;
uint64_t address = VirtualToPhysical(source_address);
if (page_fault_) {
Trap(ExceptionCode::LOAD_PAGE_FAULT, kException);
return;
}
int width = GetLoadWidth(instruction);
int access_width = GetAccessWidth(width, address);
int next_width = width - access_width;
uint64_t load_data = LoadWd(address, access_width);
if (next_width > 0) {
uint64_t next_address = VirtualToPhysical(address + access_width, false);
if (page_fault_) {
Trap(ExceptionCode::LOAD_PAGE_FAULT, kException);
return;
}
uint64_t load_data_high = LoadWd(next_address, next_width);
load_data |= (load_data_high << access_width * 8);
}
if (instruction == INST_LB || instruction == INST_LH || instruction == INST_LW) {
load_data = SignExtend(load_data, width * 8);
} else if (instruction == INST_LWU) {
load_data &= 0xFFFFFFFF;
}
peripheral_->CheckDeviceRead(address, width);
reg_[rd] = load_data;
}
int RiscvCpu::GetStoreWidth(uint32_t instruction) {
int width = 8;
switch (instruction) {
case INST_SB:
width = 1;
break;
case INST_SH:
width = 2;
break;
case INST_SW:
width = 4;
break;
case INST_SD:
width = 8;
break;
default:
assert(false);
}
return width;
}
int RiscvCpu::GetAccessWidth(uint32_t width, uint64_t address) {
bool burst_overflow = ((address & 0b111) + width - 1) >> 3;
int access_width = width;
if (burst_overflow) {
const int mask = width == 2 ? 0b1 : (width == 4 ? 0b11 : (width == 8 ? 0b111 : 0));
access_width = width - (address & mask);
}
return access_width;
}
void RiscvCpu::StoreInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, uint32_t rs2, int32_t imm12_stype) {
uint64_t dst_address = reg_[rs1] + imm12_stype;
// Check if the access crosses memory access unit (64 bit).
uint64_t address = VirtualToPhysical(dst_address, true);
if (page_fault_) {
Trap(ExceptionCode::STORE_PAGE_FAULT, kException);
return;
}
int width = GetStoreWidth(instruction);
int access_width = GetAccessWidth(width, dst_address);
int next_width = width - access_width;
int64_t data = reg_[rs2] & GenerateBitMask(access_width * 8);
StoreWd(address, data, access_width);
if (next_width > 0) {
uint64_t next_address = VirtualToPhysical(dst_address + access_width, true);
if (page_fault_) {
Trap(ExceptionCode::STORE_PAGE_FAULT, kException);
return;
}
uint64_t next_data = reg_[rs2] >> (access_width * 8);
StoreWd(next_address, next_data, next_width);
}
peripheral_->CheckDeviceWrite(address, width, reg_[rs2]);
}
void RiscvCpu::SystemInstruction(uint32_t instruction, uint32_t rd, int32_t imm) {
if (imm == 0b000000000000) {
// ECALL
if (ecall_emulation_) {
std::tie(error_flag_, end_flag_) = SystemCall();
} else {
Ecall();
}
} else if (imm == 0b000000000001) {
// EBREAK
// Debug function is not implemented yet.
} else if (imm == 0b001100000010) {
Mret();
} else if (imm == 0b000100000010) {
Sret();
} else if (((imm >> 5) == 0b0001001) && (rd == 0b00000)) {
// sfence.vma.
// TODO: Implement this function.
;
} else {
// not defined.
std::cerr << "Undefined System instruction." << std::endl;
error_flag_ = true;
}
}
uint64_t GetMulh64(int64_t op1, int64_t op2) {
int64_t a = op1 >> 32;
uint64_t b = op1 & 0xFFFFFFFF;
int64_t c = op2 >> 32;
uint64_t d = op2 & 0xFFFFFFFF;
int64_t ac = a * c;
int64_t ad = a * d;
int64_t bc = b * c;
uint64_t bd = b * d;
// Break down into 32 bit segments;
uint64_t d32 = (ad & 0xFFFFFFFF) + (bc & 0xFFFFFFFF) + (bd >> 32);
int64_t upper = ac + (ad >> 32) + (bc >> 32) + (d32 >> 32);
return static_cast<uint64_t>(upper);
}
uint64_t GetMulhsu64(int64_t op1, uint64_t op2) {
int64_t a = op1 >> 32;
uint64_t b = op1 & 0xFFFFFFFF;
uint64_t c = op2 >> 32;
uint64_t d = op2 & 0xFFFFFFFF;
int64_t ac = a * c;
int64_t ad = a * d;
uint64_t bc = b * c;
uint64_t bd = b * d;
// Break down into 32 bit segments;
uint64_t d32 = (ad & 0xFFFFFFFF) + (bc & 0xFFFFFFFF) + (bd >> 32);
int64_t upper = ac + (ad >> 32) + (bc >> 32) + (d32 >> 32);
return static_cast<uint64_t>(upper);
}
uint64_t GetMulhu64(uint64_t op1, uint64_t op2) {
uint64_t a = op1 >> 32;
uint64_t b = op1 & 0xFFFFFFFF;
uint64_t c = op2 >> 32;
uint64_t d = op2 & 0xFFFFFFFF;
uint64_t ac = a * c;
uint64_t ad = a * d;
uint64_t bc = b * c;
uint64_t bd = b * d;
// Break down into 32 bit segments;
uint64_t d32 = (ad & 0xFFFFFFFF) + (bc & 0xFFFFFFFF) + (bd >> 32);
uint64_t upper = ac + (ad >> 32) + (bc >> 32) + (d32 >> 32);
return upper;
}
void RiscvCpu::MultInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, uint32_t rs2) {
bool sign_extend_en = xlen_ == 32;
uint64_t temp64;
uint64_t largest_negative = static_cast<uint64_t>(1) << (xlen_ - 1);
switch (instruction) {
case INST_MUL:
temp64 = reg_[rs1] * reg_[rs2];
break;
case INST_MULW:
temp64 = reg_[rs1] * reg_[rs2];
sign_extend_en = true;
break;
case INST_MULH:
if (xlen_ == 32) {
temp64 = (static_cast<int64_t>(reg_[rs1]) * static_cast<int64_t>(reg_[rs2])) >> 32;
} else {
temp64 = GetMulh64(reg_[rs1], reg_[rs2]);
}
break;
case INST_MULHSU:
if (xlen_ == 32) {
temp64 = (static_cast<int64_t>(reg_[rs1]) * (reg_[rs2] & 0xFFFFFFFF)) >> 32;
} else {
temp64 = GetMulhsu64(static_cast<int64_t>(reg_[rs1]), reg_[rs2]);
}
break;
case INST_MULHU:
if (xlen_ == 32) {
temp64 = ((reg_[rs1] & 0xFFFFFFFF) * (reg_[rs2] & 0xFFFFFFFF)) >> 32;
} else {
temp64 = GetMulhu64(reg_[rs1], reg_[rs2]);
}
break;
case INST_DIV:
if (reg_[rs2] == 0) {
temp64 = -1;
} else if (static_cast<int64_t>(reg_[rs2]) == -1 && reg_[rs1] == largest_negative) {
// Overflow check.
temp64 = largest_negative;
} else {
temp64 = static_cast<int64_t>(reg_[rs1]) / static_cast<int64_t>(reg_[rs2]);
}
break;
case INST_DIVU:
if (reg_[rs2] == 0) {
temp64 = ~0;
} else if (xlen_ == 32) {
temp64 = static_cast<uint64_t>(reg_[rs1] & 0xFFFFFFFF) / static_cast<uint64_t>(reg_[rs2] & 0xFFFFFFFF);
} else {
temp64 = static_cast<uint64_t>(reg_[rs1]) / static_cast<uint64_t>(reg_[rs2]);
}
break;
case INST_DIVUW:
if (reg_[rs2] == 0) {
temp64 = ~0;
} else {
temp64 = (reg_[rs1] & 0xFFFFFFFF) / (reg_[rs2] & 0xFFFFFFFF);
}
sign_extend_en = true;
break;
case INST_DIVW:
if (reg_[rs2] == 0) {
temp64 = -1;
} else if (static_cast<int64_t>(reg_[rs2]) == -1 && reg_[rs1] == (1lu << 31)) {
// Overflow check.
temp64 = (uint64_t)1 << 31;
} else {
temp64 = static_cast<int64_t>(SignExtend(reg_[rs1], 32)) / static_cast<int64_t>(SignExtend(reg_[rs2], 32));
}
sign_extend_en = true;
break;
case INST_REM:
if (reg_[rs2] == 0) {
temp64 = reg_[rs1];
} else if (static_cast<int64_t>(reg_[rs2]) == -1 && reg_[rs1] == largest_negative) {
// Overflow check.
temp64 = 0;
} else {
temp64 = static_cast<int64_t>(reg_[rs1]) % static_cast<int64_t>(reg_[rs2]);
}
break;
case INST_REMU:
if (reg_[rs2] == 0) {
temp64 = reg_[rs1];
} else if (xlen_ == 32) {
temp64 = (reg_[rs1] & 0xFFFFFFFF) % (reg_[rs2] & 0xFFFFFFFF);
} else {
temp64 = reg_[rs1] % reg_[rs2];
}
break;
case INST_REMUW:
if (reg_[rs2] == 0) {
temp64 = reg_[rs1];
} else {
temp64 = (reg_[rs1] & 0xFFFFFFFF) % (reg_[rs2] & 0xFFFFFFFF);
}
sign_extend_en = true;
break;
case INST_REMW:
if (reg_[rs2] == 0) {
temp64 = reg_[rs1];
} else if (static_cast<int64_t>(reg_[rs2]) == -1 && reg_[rs1] == (1lu << 31)) {
// Overflow check.
temp64 = 0;
} else {
temp64 = static_cast<int64_t>(SignExtend(reg_[rs1], 32)) % static_cast<int64_t>(SignExtend(reg_[rs2], 32));
}
sign_extend_en = true;
break;
default:
temp64 = 0;
std::cerr << "Undefined Mul instruction detected." << std::endl;
assert(false);
}
if (sign_extend_en) {
temp64 = Sext32bit(temp64);
}
reg_[rd] = temp64;
}
template <class T>
T max(T a, T b) {
return a > b ? a : b;
}
template <class T>
T min(T a, T b) {
return a < b ? a : b;
}
void RiscvCpu::AmoInstruction(uint32_t instruction, uint32_t rd, uint32_t rs1, uint32_t rs2) {
uint64_t virtual_address = reg_[rs1];
uint64_t physical_address = VirtualToPhysical(virtual_address);
uint64_t new_value;
uint32_t word_width = (instruction == INST_AMOADDD || instruction == INST_AMOANDD || instruction == INST_AMOMAXD ||
instruction == INST_AMOMAXUD || instruction == INST_AMOMIND || instruction == INST_AMOMINUD ||
instruction == INST_AMOORD || instruction == INST_AMOXORD || instruction == INST_AMOSWAPD)
? 8
: 4;
uint64_t t = LoadWd(physical_address, word_width);
if (word_width == 4) {
t = SignExtend(t, 32);
}
switch (instruction) {
case INST_AMOADDD:
new_value = t + reg_[rs2];
break;
case INST_AMOADDW:
new_value = SignExtend(t + reg_[rs2], 32);
break;
case INST_AMOANDD:
new_value = t & reg_[rs2];
break;
case INST_AMOANDW:
new_value = SignExtend(t & reg_[rs2], 32);
break;
case INST_AMOMAXD:
new_value = max<int64_t>(t, reg_[rs2]);
break;
case INST_AMOMAXW:
new_value = max<int32_t>(SignExtend(t, 32), SignExtend(reg_[rs2], 32));
new_value = SignExtend(new_value, 32);
break;
case INST_AMOMAXUD:
new_value = max<uint64_t>(t, reg_[rs2]);
break;
case INST_AMOMAXUW:
new_value = max<uint32_t>(static_cast<uint32_t>(t), static_cast<uint32_t>(reg_[rs2]));
new_value = SignExtend(new_value, 32);
break;
case INST_AMOMIND:
new_value = min<int64_t>(t, reg_[rs2]);
break;
case INST_AMOMINW:
new_value = min<int32_t>(SignExtend(t, 32), SignExtend(reg_[rs2], 32));
new_value = SignExtend(new_value, 32);
break;
case INST_AMOMINUD:
new_value = min<uint64_t>(t, reg_[rs2]);
break;
case INST_AMOMINUW:
new_value = min<uint32_t>(static_cast<uint32_t>(t), static_cast<uint32_t>(reg_[rs2]));
new_value = SignExtend(new_value, 32);
break;
case INST_AMOORD:
new_value = t | reg_[rs2];
break;
case INST_AMOORW:
new_value = SignExtend(t | reg_[rs2], 32);
break;
case INST_AMOXORD:
new_value = t ^ reg_[rs2];
break;
case INST_AMOXORW:
new_value = SignExtend(t ^ reg_[rs2], 32);
break;
case INST_AMOSWAPD:
case INST_AMOSWAPW:
new_value = reg_[rs2];
break;
default:
new_value = 0;
std::cerr << "Undefined AMOxxx instruction." << std::endl;
assert(false);
}
constexpr bool kWriteAccess = true;
physical_address = VirtualToPhysical(virtual_address, kWriteAccess);
StoreWd(physical_address, new_value, word_width);
reg_[rd] = t;
}
bool RiscvCpu::TimerTick() {
peripheral_->TimerTick();
if (!peripheral_->GetTimerInterrupt()) {
return false;
}
peripheral_->ClearTimerInterrupt();
constexpr int kMachineTimerInterrupt = 7;
SetInterruptPending(kMachineTimerInterrupt);
return true;
}
void RiscvCpu::InterruptCheck() {
DiskInterruptCheck();
UartInterruptCheck();
}
void RiscvCpu::DiskInterruptCheck() {
if (virtio_interrupt_) {
virtio_interrupt_ = false;
constexpr int kSupervisorExternalInterrupt = 9;
SetInterruptPending(kSupervisorExternalInterrupt);
}
}
void RiscvCpu::UartInterruptCheck() {
if (uart_interrupt_) {
uart_interrupt_ = false;
constexpr int kSupervisorExternalInterrupt = 9;
SetInterruptPending(kSupervisorExternalInterrupt);
}
}
void RiscvCpu::SetInterruptPending(int cause) {
constexpr uint64_t kSet = 1;
mip_ = bitset(mip_, 1, cause, kSet);
ApplyInterruptEnable();
}
void RiscvCpu::ClearInterruptPending(int cause) {
constexpr uint64_t kClear = 0;
mip_ = bitset(mip_, 1, cause, kClear);
ApplyInterruptPending();
}
void RiscvCpu::DumpDisassembly(bool verbose) {
if (!verbose) {
return;
}
char machine_status = privilege_ == PrivilegeMode::USER_MODE ? 'U'
: privilege_ == PrivilegeMode::SUPERVISOR_MODE ? 'S'
: 'M';
printf("%c %016lx (%04x): ", machine_status, pc_, ir_);
std::cout << Disassemble(ir_, mxl_) << std::endl;
}
int RiscvCpu::RunCpu(uint64_t start_pc, bool verbose) {
error_flag_ = false;
end_flag_ = false;
next_pc_ = start_pc;
do {
pc_ = next_pc_;
TimerTick();
InterruptCheck();
if (CheckPendingInterrupt()) {
continue;
}
ir_ = LoadCmd(pc_);
DumpDisassembly(verbose);
if (page_fault_) {
Trap(ExceptionCode::INSTRUCTION_PAGE_FAULT, kException);
continue;
}
// Decode. Mimick the HW behavior. (In HW, decode is in parallel.)
ctype_ = (ir_ & 0b11) != 0b11;
uint32_t instruction, rd, rs1, rs2;
int32_t imm;
int16_t csr = GetCsr(ir_);
if (!ctype_) {
next_pc_ = pc_ + 4;
instruction = GetCode32(ir_);
rd = GetRd(ir_);
rs1 = GetRs1(ir_);
rs2 = GetRs2(ir_);
imm = GetImm(ir_);
} else {
next_pc_ = pc_ + 2;
GetCode16(ir_, mxl_, &instruction, &rd, &rs1, &rs2, &imm);
}
uint64_t t; // 't' is used in RISCV Reader to show a temporary address.
switch (instruction) {
uint64_t temp64;
case INST_ADD:
case INST_ADDW:
case INST_AND:
case INST_SUB:
case INST_SUBW:
case INST_OR:
case INST_XOR:
case INST_SLL:
case INST_SLLW:
case INST_SRL:
case INST_SRLW:
case INST_SRA:
case INST_SRAW:
OperationInstruction(instruction, rd, rs1, rs2);
break;
case INST_ADDI:
case INST_ADDIW:
case INST_ANDI:
case INST_ORI:
case INST_XORI:
ImmediateInstruction(instruction, rd, rs1, imm);
break;
case INST_SLLI:
case INST_SLLIW:
case INST_SRLI:
case INST_SRLIW:
case INST_SRAI:
case INST_SRAIW:
ImmediateShiftInstruction(instruction, rd, rs1, imm);
break;
case INST_SLT:
reg_[rd] = (static_cast<int64_t>(reg_[rs1]) < static_cast<int64_t>(reg_[rs2])) ? 1 : 0;
break;
case INST_SLTU:
reg_[rd] = (reg_[rs1] < reg_[rs2]) ? 1 : 0;
break;
case INST_SLTI: