What is the functionality of mscratch register?
chyyuu opened this issue · comments
Why is mscratch
modified multiple times in mentry.S?
What is the functionality of mscratch
register?
The mscratch register is an XLEN-bit read/write register dedicated for use by machine mode. Typically, it is used to hold a pointer to a machine-mode hart-local context space and swapped with a user register upon entry to an M-mode trap handler.
-- The RISC-V Instruction Set Manual Volume II: Privileged Architecture
The explanation given in the privileged spec is ambiguous. It will be easier to understand mscratch
register by checking the code of bbl
. In machine/mentry.S
, the mscratch
is cleared upon booting (mentry.S#L256) and set to sp
when leaving M-mode (mentry.S#L66). By doing so, we intent to keep two properties during execution:
mscratch
contains 0 when in M-mode;mscratch
contains "machine stack" when in S-mode or U-mode.
To keep above properties, we need to swap sp
and mscratch
when trapped into M-mode from S-mode or U-mode (mentry.S#L40). You can persuade yourself by thinking the status of sp
and mscratch
after line 40 and validating the following statements:
if trap from M-mode:
sp == 0
mscratch == "machine stack"
elif trap from S-mode:
sp == "machine stack"
mscratch == "kernel stack"
elif trap from U-mode:
sp == "machine stack"
mscratch == "user stack"
Therefore, by checking whether sp
equals zero we can infer in which mode the CPU was running, which is helpful if you want nested traps. There is also a sscratch
register in S-mode, this register effectively replaces the role of k0
and k1
registers in MIPS or TSS
in x86 architecture.
The MIPS ISA allocated two user registers (k0/k1) for use by the operating system. Although the MIPS scheme provides a fast and simple implementation, it also reduces available user registers, and does not scale to further privilege levels, or nested traps. It can also require both registers are cleared before returning to user level to avoid a potential security hole and to provide deterministic debugging behavior.
The RISC-V user ISA was designed to support many possible privileged system environments and so we did not want to infect the user-level ISA with any OS-dependent features. The RISC- V CSR swap instructions can quickly save/restore values to the mscratch register. Unlike the MIPS design, the OS can rely on holding a value in the mscratch register while the user context is running.
-- The RISC-V Instruction Set Manual Volume II: Privileged Architecture
Apart from helping us infer the privileged mode before the trap, the sscratch
or mscratch
also provide a spare register for saving general registers, because you have to modify at least one register first to save general registers on stack in trap handling.
@chyyuu I believe this issue can now be closed.