forked from sysprog21/semu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ram.c
69 lines (66 loc) · 2.24 KB
/
ram.c
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
#include "riscv.h"
#include "riscv_private.h"
/* RAM handlers (address must be relative, assumes it is within bounds) */
#define RAM_FUNC(width, code) \
do { \
if (unlikely((addr & (width - 1)))) { \
vm_set_exception(vm, exc_cause, vm->exc_val); \
break; \
} \
UNUSED uint8_t offset = (addr & 0b11) * 8; \
uint32_t *cell = &mem[addr >> 2]; \
code; \
} while (0)
void ram_read(vm_t *vm,
uint32_t *mem,
const uint32_t addr,
const uint8_t width,
uint32_t *value)
{
const uint32_t exc_cause = RV_EXC_LOAD_MISALIGN;
switch (width) {
case RV_MEM_LW:
RAM_FUNC(4, *value = *cell);
break;
case RV_MEM_LHU:
RAM_FUNC(2, *value = (uint32_t) (uint16_t) ((*cell) >> offset));
break;
case RV_MEM_LH:
RAM_FUNC(2,
*value = (uint32_t) (int32_t) (int16_t) ((*cell) >> offset));
break;
case RV_MEM_LBU:
RAM_FUNC(1, *value = (uint32_t) (uint8_t) ((*cell) >> offset));
break;
case RV_MEM_LB:
RAM_FUNC(1, *value = (uint32_t) (int32_t) (int8_t) ((*cell) >> offset));
break;
default:
vm_set_exception(vm, RV_EXC_ILLEGAL_INSTR, 0);
return;
}
}
void ram_write(vm_t *vm,
uint32_t *mem,
const uint32_t addr,
const uint8_t width,
const uint32_t value)
{
const uint32_t exc_cause = RV_EXC_STORE_MISALIGN;
switch (width) {
case RV_MEM_SW:
RAM_FUNC(4, *cell = value);
break;
case RV_MEM_SH:
RAM_FUNC(2, *cell = ((*cell) & ~(MASK(16) << offset)) |
(value & MASK(16)) << offset);
break;
case RV_MEM_SB:
RAM_FUNC(1, *cell = ((*cell) & ~(MASK(8) << offset)) | (value & MASK(8))
<< offset);
break;
default:
vm_set_exception(vm, RV_EXC_ILLEGAL_INSTR, 0);
return;
}
}