diff --git a/.github/workflows/riscv.yaml b/.github/workflows/riscv.yaml index b3dfc06c..54eeb490 100644 --- a/.github/workflows/riscv.yaml +++ b/.github/workflows/riscv.yaml @@ -47,6 +47,8 @@ jobs: run: cargo build --package riscv --target ${{ matrix.target }} - name: Build (M-mode, critical section) run: cargo build --package riscv --target ${{ matrix.target }} --features=critical-section-single-hart + - name: Build (HS-mode) + run: cargo build --package riscv --target ${{ matrix.target }} --features=hs-mode - name: Build (S-mode) run: cargo build --package riscv --target ${{ matrix.target }} --features=s-mode - name: Build (all features) diff --git a/.gitignore b/.gitignore index cb60d8be..22606cd5 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ target/ .idea/ .vscode/ .DS_Store +makefile diff --git a/riscv/CHANGELOG.md b/riscv/CHANGELOG.md index 4f1b5f23..c4e5d1e2 100644 --- a/riscv/CHANGELOG.md +++ b/riscv/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added +- Add `hstatus` CSR and support for `hs-mode` - Add `seed` CSR - Add new feature `defmt` which will optionally derive `defmt::Format` on certain types. - Add `stimecmp`/`stimecmph` CSRs diff --git a/riscv/Cargo.toml b/riscv/Cargo.toml index f334cd62..02d3647b 100644 --- a/riscv/Cargo.toml +++ b/riscv/Cargo.toml @@ -22,6 +22,7 @@ targets = [ [features] default = ["riscv-macros"] s-mode = [] +hs-mode = [] critical-section-single-hart = ["critical-section/restore-state-bool"] rt = ["riscv-macros/rt"] rt-v-trap = ["rt", "riscv-macros/rt-v-trap"] diff --git a/riscv/src/interrupt.rs b/riscv/src/interrupt.rs index 4a1c98d8..a187cf41 100644 --- a/riscv/src/interrupt.rs +++ b/riscv/src/interrupt.rs @@ -7,10 +7,13 @@ use crate::result::Result; // re-export useful riscv-types traits pub use crate::{CoreInterruptNumber, ExceptionNumber, InterruptNumber}; +pub mod hypervisor; pub mod machine; pub mod supervisor; -#[cfg(not(feature = "s-mode"))] +#[cfg(all(feature = "hs-mode", not(feature = "s-mode")))] +pub use hypervisor::*; +#[cfg(not(any(feature = "s-mode", feature = "hs-mode")))] pub use machine::*; #[cfg(feature = "s-mode")] pub use supervisor::*; diff --git a/riscv/src/interrupt/hypervisor.rs b/riscv/src/interrupt/hypervisor.rs new file mode 100644 index 00000000..6f589f00 --- /dev/null +++ b/riscv/src/interrupt/hypervisor.rs @@ -0,0 +1,337 @@ +//! This is a WIP section +//! Experimental. Not to be used +use crate::{ + interrupt::Trap, + register::hstatus, + register::{scause, sepc, sstatus}, + result::{Error, Result}, + CoreInterruptNumber, ExceptionNumber, InterruptNumber, +}; + +/// Interrupt +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(usize)] +pub enum Interrupt { + SupervisorSoft = 1, + VirtSupervisorSoft = 2, + SupervisorTimer = 5, + VirtSupervisorTimer = 6, + SupervisorExternal = 9, + VirtSupervisorExternal = 10, + SupervisorGuestExternal = 12, +} + +/// SAFETY: `Interrupt` represents the standard RISC-V interrupts +unsafe impl InterruptNumber for Interrupt { + const MAX_INTERRUPT_NUMBER: usize = Self::SupervisorGuestExternal as usize; + + #[inline] + fn number(self) -> usize { + self as usize + } + + #[inline] + fn from_number(value: usize) -> Result { + match value { + 1 => Ok(Self::SupervisorSoft), + 2 => Ok(Self::VirtSupervisorSoft), + 5 => Ok(Self::SupervisorTimer), + 6 => Ok(Self::VirtSupervisorTimer), + 9 => Ok(Self::SupervisorExternal), + 10 => Ok(Self::VirtSupervisorExternal), + 12 => Ok(Self::SupervisorGuestExternal), + _ => Err(Error::InvalidVariant(value)), + } + } +} + +/// SAFETY: `Interrupt` represents the standard RISC-V core interrupts +unsafe impl CoreInterruptNumber for Interrupt {} + +/// Exception +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(usize)] +pub enum Exception { + InstructionMisaligned = 0, + InstructionFault = 1, + IllegalInstruction = 2, + Breakpoint = 3, + LoadMisaligned = 4, + LoadFault = 5, + StoreMisaligned = 6, + StoreFault = 7, + // User or Virtual User Environment Call + UserEnvCall = 8, + SupervisorEnvCall = 9, + // Virtual Supervisor Environment Call + GuestSupervisorEnvCall = 10, + InstructionPageFault = 12, + LoadPageFault = 13, + StorePageFault = 15, + SoftwareCheck = 18, + HardwareError = 19, + // 2 stage translation fault on instruction fetch + InstructionGuestFault = 20, + // 2 stage translation fault on memory load + LoadGuestFault = 21, + VirtualInstructionGuest = 22, + // 2 stage translation fault on memory store or atomic op + StoreGuestPageFault = 23, +} + +/// SAFETY: `Exception` represents the standard RISC-V exceptions +unsafe impl ExceptionNumber for Exception { + const MAX_EXCEPTION_NUMBER: usize = Self::StorePageFault as usize; + + #[inline] + fn number(self) -> usize { + self as usize + } + + #[inline] + fn from_number(value: usize) -> Result { + match value { + 0 => Ok(Self::InstructionMisaligned), + 1 => Ok(Self::InstructionFault), + 2 => Ok(Self::IllegalInstruction), + 3 => Ok(Self::Breakpoint), + 4 => Ok(Self::LoadMisaligned), + 5 => Ok(Self::LoadFault), + 6 => Ok(Self::StoreMisaligned), + 7 => Ok(Self::StoreFault), + 8 => Ok(Self::UserEnvCall), + 9 => Ok(Self::SupervisorEnvCall), + 10 => Ok(Self::GuestSupervisorEnvCall), + 12 => Ok(Self::InstructionPageFault), + 13 => Ok(Self::LoadPageFault), + 15 => Ok(Self::StorePageFault), + 18 => Ok(Self::SoftwareCheck), + 19 => Ok(Self::HardwareError), + 20 => Ok(Self::InstructionGuestFault), + 21 => Ok(Self::LoadGuestFault), + 22 => Ok(Self::VirtualInstructionGuest), + 23 => Ok(Self::StoreGuestPageFault), + _ => Err(Error::InvalidVariant(value)), + } + } +} + +/// Checks if a specific core interrupt source is enabled in the current hart (hypervisor mode). +#[inline] +pub fn is_interrupt_enabled(_interrupt: I) -> bool { + todo!() //hie::read().is_enabled(interrupt) +} + +/// Disables interrupts for a specific core interrupt source in the current hart (hypervisor mode). +#[inline] +pub fn disable_interrupt(_interrupt: I) { + // SAFETY: it is safe to disable an interrupt source + todo!() //hie::disable(interrupt); +} + +/// Enables interrupts for a specific core interrupt source in the current hart (hypervisor mode). +/// +/// # Note +/// +/// Interrupts will only be triggered if globally enabled in the hart. To do this, use [`enable`]. +/// +/// # Safety +/// +/// Enabling interrupts might break critical sections or other synchronization mechanisms. +/// Ensure that this is called in a safe context where interrupts can be enabled. +#[inline] +pub unsafe fn enable_interrupt(_interrupt: I) { + todo!() //hie::enable(interrupt); +} + +/// Checks if a specific core interrupt source is pending in the current hart (hypervisor mode). +#[inline] +pub fn is_interrupt_pending(_interrupt: I) -> bool { + todo!() //hip::read().is_pending(interrupt) +} + +/// Disables interrupts globally in the current hart (hypervisor mode). +#[inline] +pub fn disable() { + // SAFETY: It is safe to disable interrupts + unsafe { sstatus::clear_sie() } +} + +/// Enables interrupts globally in the current hart (hypervisor mode). +/// +/// # Note +/// +/// Only enabled interrupt sources will be triggered. +/// To enable specific interrupt sources, use [`enable_interrupt`]. +/// +/// # Safety +/// +/// Enabling interrupts might break critical sections or other synchronization mechanisms. +/// Ensure that this is called in a safe context where interrupts can be enabled. +#[inline] +pub unsafe fn enable() { + sstatus::set_sie() +} + +/// Retrieves the cause of a trap in the current hart (hypervisor mode). +/// +/// This function expects the target-specific interrupt and exception types. +/// If the raw cause is not a valid interrupt or exception for the target, it returns an error. +#[inline] +pub fn try_cause() -> Result> { + scause::read().cause().try_into() +} + +/// Retrieves the cause of a trap in the current hart (hypervisor mode). +/// +/// This function expects the target-specific interrupt and exception types. +/// If the raw cause is not a valid interrupt or exception for the target, it panics. +#[inline] +pub fn cause() -> Trap { + try_cause().unwrap() +} + +/// Execute closure `f` with interrupts disabled in the current hart (hypervisor mode). +/// +/// This method does not synchronise multiple harts, so it is not suitable for +/// using as a critical section. See the `critical-section` crate for a cross-platform +/// way to enter a critical section which provides a `CriticalSection` token. +/// +/// This crate provides an implementation for `critical-section` suitable for single-hart systems, +/// based on disabling all interrupts. It can be enabled with the `critical-section-single-hart` feature. +#[inline] +pub fn free(f: F) -> R +where + F: FnOnce() -> R, +{ + let sstatus = sstatus::read(); + + // disable interrupts + disable(); + + let r = f(); + + // If the interrupts were active before our `disable` call, then re-enable + // them. Otherwise, keep them disabled + if sstatus.sie() { + unsafe { enable() }; + } + + r +} + +/// Execute closure `f` with interrupts enabled in the current hart (hypervisor mode). +/// +/// This method is assumed to be called within an interrupt handler, and allows +/// nested interrupts to occur. After the closure `f` is executed, the [`hstatus`] +/// and [`hepc`] registers are properly restored to their previous values. +/// +/// # Safety +/// +/// - Do not call this function inside a critical section. +/// - This method is assumed to be called within an interrupt handler. +/// - Make sure to clear the interrupt flag that caused the interrupt before calling +/// this method. Otherwise, the interrupt will be re-triggered before executing `f`. +#[inline] +pub unsafe fn nested(f: F) -> R +where + F: FnOnce() -> R, +{ + let sstatus = sstatus::read(); + let hstatus = hstatus::read(); + let sepc = sepc::read(); + + // enable interrupts to allow nested interrupts + enable(); + + let r = f(); + + // If the interrupts were inactive before our `enable` call, then re-disable + // them. Otherwise, keep them enabled + if !sstatus.sie() { + disable(); + } + + // Restore SSTATUS.SPIE, SSTATUS.SPP, and SEPC + if sstatus.spie() { + sstatus::set_spie(); + } + if hstatus.spv() { + todo!(); // hstatus::set_spv(hstatus::SPV::Virtualization); + } + //hstatus::set_spv(hstatus.spv()); + sepc::write(sepc); + + r +} + +#[cfg(test)] +mod test { + use super::*; + use Exception::*; + use Interrupt::*; + + #[test] + fn test_interrupt() { + assert_eq!(Interrupt::from_number(1), Ok(SupervisorSoft)); + assert_eq!(Interrupt::from_number(2), Ok(VirtSupervisorSoft)); + assert_eq!(Interrupt::from_number(3), Err(Error::InvalidVariant(3))); + assert_eq!(Interrupt::from_number(4), Err(Error::InvalidVariant(4))); + assert_eq!(Interrupt::from_number(5), Ok(SupervisorTimer)); + assert_eq!(Interrupt::from_number(6), Ok(VirtSupervisorTimer)); + assert_eq!(Interrupt::from_number(7), Err(Error::InvalidVariant(7))); + assert_eq!(Interrupt::from_number(8), Err(Error::InvalidVariant(8))); + assert_eq!(Interrupt::from_number(9), Ok(SupervisorExternal)); + assert_eq!(Interrupt::from_number(10), Ok(VirtSupervisorExternal)); + assert_eq!(Interrupt::from_number(11), Err(Error::InvalidVariant(11))); + assert_eq!(Interrupt::from_number(12), Ok(SupervisorGuestExternal)); + + assert_eq!(SupervisorSoft.number(), 1); + assert_eq!(SupervisorTimer.number(), 5); + assert_eq!(SupervisorExternal.number(), 9); + + assert_eq!( + SupervisorGuestExternal.number(), + Interrupt::MAX_INTERRUPT_NUMBER + ) + } + + #[test] + fn test_exception() { + assert_eq!(Exception::from_number(0), Ok(InstructionMisaligned)); + assert_eq!(Exception::from_number(1), Ok(InstructionFault)); + assert_eq!(Exception::from_number(2), Ok(IllegalInstruction)); + assert_eq!(Exception::from_number(3), Ok(Breakpoint)); + assert_eq!(Exception::from_number(4), Ok(LoadMisaligned)); + assert_eq!(Exception::from_number(5), Ok(LoadFault)); + assert_eq!(Exception::from_number(6), Ok(StoreMisaligned)); + assert_eq!(Exception::from_number(7), Ok(StoreFault)); + assert_eq!(Exception::from_number(8), Ok(UserEnvCall)); + assert_eq!(Exception::from_number(9), Ok(SupervisorEnvCall)); + assert_eq!(Exception::from_number(10), Ok(GuestSupervisorEnvCall)); + assert_eq!(Exception::from_number(11), Err(Error::InvalidVariant(11))); + assert_eq!(Exception::from_number(12), Ok(InstructionPageFault)); + assert_eq!(Exception::from_number(13), Ok(LoadPageFault)); + assert_eq!(Exception::from_number(14), Err(Error::InvalidVariant(14))); + assert_eq!(Exception::from_number(15), Ok(StorePageFault)); + assert_eq!(Exception::from_number(16), Err(Error::InvalidVariant(16))); + + assert_eq!(InstructionMisaligned.number(), 0); + assert_eq!(InstructionFault.number(), 1); + assert_eq!(IllegalInstruction.number(), 2); + assert_eq!(Breakpoint.number(), 3); + assert_eq!(LoadMisaligned.number(), 4); + assert_eq!(LoadFault.number(), 5); + assert_eq!(StoreMisaligned.number(), 6); + assert_eq!(StoreFault.number(), 7); + assert_eq!(UserEnvCall.number(), 8); + assert_eq!(SupervisorEnvCall.number(), 9); + assert_eq!(InstructionPageFault.number(), 12); + assert_eq!(LoadPageFault.number(), 13); + assert_eq!(StorePageFault.number(), 15); + + assert_eq!(StorePageFault.number(), Exception::MAX_EXCEPTION_NUMBER) + } +} diff --git a/riscv/src/interrupt/machine.rs b/riscv/src/interrupt/machine.rs index 22f2eee1..fd169a9d 100644 --- a/riscv/src/interrupt/machine.rs +++ b/riscv/src/interrupt/machine.rs @@ -11,11 +11,15 @@ use crate::{ #[repr(usize)] pub enum Interrupt { SupervisorSoft = 1, + VirtSupervisorSoft = 2, MachineSoft = 3, SupervisorTimer = 5, + VirtSupervisorTimer = 6, MachineTimer = 7, SupervisorExternal = 9, + VirtSupervisorExternal = 10, MachineExternal = 11, + SupervisorGuestExternal = 12, } /// SAFETY: `Interrupt` represents the standard RISC-V interrupts @@ -31,11 +35,15 @@ unsafe impl InterruptNumber for Interrupt { fn from_number(value: usize) -> Result { match value { 1 => Ok(Self::SupervisorSoft), + 2 => Ok(Self::VirtSupervisorSoft), 3 => Ok(Self::MachineSoft), 5 => Ok(Self::SupervisorTimer), + 6 => Ok(Self::VirtSupervisorTimer), 7 => Ok(Self::MachineTimer), 9 => Ok(Self::SupervisorExternal), + 10 => Ok(Self::VirtSupervisorExternal), 11 => Ok(Self::MachineExternal), + 12 => Ok(Self::SupervisorGuestExternal), _ => Err(Error::InvalidVariant(value)), } } @@ -57,17 +65,29 @@ pub enum Exception { LoadFault = 5, StoreMisaligned = 6, StoreFault = 7, + // User or Virtual User Environment Call UserEnvCall = 8, SupervisorEnvCall = 9, + // Virtual Supervisor Environment Call + GuestSupervisorEnvCall = 10, MachineEnvCall = 11, InstructionPageFault = 12, LoadPageFault = 13, StorePageFault = 15, + SoftwareCheck = 18, + HardwareError = 19, + // 2 stage translation fault on instruction fetch + InstructionGuestFault = 20, + // 2 stage translation fault on memory load + LoadGuestFault = 21, + VirtualInstructionGuest = 22, + // 2 stage translation fault on memory store or atomic op + StoreGuestPageFault = 23, } /// SAFETY: `Exception` represents the standard RISC-V exceptions unsafe impl ExceptionNumber for Exception { - const MAX_EXCEPTION_NUMBER: usize = Self::StorePageFault as usize; + const MAX_EXCEPTION_NUMBER: usize = Self::StoreGuestPageFault as usize; #[inline] fn number(self) -> usize { @@ -87,10 +107,17 @@ unsafe impl ExceptionNumber for Exception { 7 => Ok(Self::StoreFault), 8 => Ok(Self::UserEnvCall), 9 => Ok(Self::SupervisorEnvCall), + 10 => Ok(Self::GuestSupervisorEnvCall), 11 => Ok(Self::MachineEnvCall), 12 => Ok(Self::InstructionPageFault), 13 => Ok(Self::LoadPageFault), 15 => Ok(Self::StorePageFault), + 18 => Ok(Self::SoftwareCheck), + 19 => Ok(Self::HardwareError), + 20 => Ok(Self::InstructionGuestFault), + 21 => Ok(Self::LoadGuestFault), + 22 => Ok(Self::VirtualInstructionGuest), + 23 => Ok(Self::StoreGuestPageFault), _ => Err(Error::InvalidVariant(value)), } } @@ -249,17 +276,17 @@ mod test { #[test] fn test_interrupt() { assert_eq!(Interrupt::from_number(1), Ok(SupervisorSoft)); - assert_eq!(Interrupt::from_number(2), Err(Error::InvalidVariant(2))); + assert_eq!(Interrupt::from_number(2), Ok(VirtSupervisorSoft)); assert_eq!(Interrupt::from_number(3), Ok(MachineSoft)); assert_eq!(Interrupt::from_number(4), Err(Error::InvalidVariant(4))); assert_eq!(Interrupt::from_number(5), Ok(SupervisorTimer)); - assert_eq!(Interrupt::from_number(6), Err(Error::InvalidVariant(6))); + assert_eq!(Interrupt::from_number(6), Ok(VirtSupervisorTimer)); assert_eq!(Interrupt::from_number(7), Ok(MachineTimer)); assert_eq!(Interrupt::from_number(8), Err(Error::InvalidVariant(8))); assert_eq!(Interrupt::from_number(9), Ok(SupervisorExternal)); - assert_eq!(Interrupt::from_number(10), Err(Error::InvalidVariant(10))); + assert_eq!(Interrupt::from_number(10), Ok(VirtSupervisorExternal)); assert_eq!(Interrupt::from_number(11), Ok(MachineExternal)); - assert_eq!(Interrupt::from_number(12), Err(Error::InvalidVariant(12))); + assert_eq!(Interrupt::from_number(12), Ok(SupervisorGuestExternal)); assert_eq!(SupervisorSoft.number(), 1); assert_eq!(MachineSoft.number(), 3); @@ -283,13 +310,20 @@ mod test { assert_eq!(Exception::from_number(7), Ok(StoreFault)); assert_eq!(Exception::from_number(8), Ok(UserEnvCall)); assert_eq!(Exception::from_number(9), Ok(SupervisorEnvCall)); - assert_eq!(Exception::from_number(10), Err(Error::InvalidVariant(10))); + assert_eq!(Exception::from_number(10), Ok(GuestSupervisorEnvCall)); assert_eq!(Exception::from_number(11), Ok(MachineEnvCall)); assert_eq!(Exception::from_number(12), Ok(InstructionPageFault)); assert_eq!(Exception::from_number(13), Ok(LoadPageFault)); assert_eq!(Exception::from_number(14), Err(Error::InvalidVariant(14))); assert_eq!(Exception::from_number(15), Ok(StorePageFault)); assert_eq!(Exception::from_number(16), Err(Error::InvalidVariant(16))); + assert_eq!(Exception::from_number(17), Err(Error::InvalidVariant(17))); + assert_eq!(Exception::from_number(18), Ok(SoftwareCheck)); + assert_eq!(Exception::from_number(19), Ok(HardwareError)); + assert_eq!(Exception::from_number(20), Ok(InstructionGuestFault)); + assert_eq!(Exception::from_number(21), Ok(LoadGuestFault)); + assert_eq!(Exception::from_number(22), Ok(VirtualInstructionGuest)); + assert_eq!(Exception::from_number(23), Ok(StoreGuestPageFault)); assert_eq!(InstructionMisaligned.number(), 0); assert_eq!(InstructionFault.number(), 1); @@ -306,6 +340,9 @@ mod test { assert_eq!(LoadPageFault.number(), 13); assert_eq!(StorePageFault.number(), 15); - assert_eq!(StorePageFault.number(), Exception::MAX_EXCEPTION_NUMBER) + assert_eq!( + StoreGuestPageFault.number(), + Exception::MAX_EXCEPTION_NUMBER + ) } } diff --git a/riscv/src/register.rs b/riscv/src/register.rs index 0e948db4..cc588308 100644 --- a/riscv/src/register.rs +++ b/riscv/src/register.rs @@ -142,6 +142,9 @@ pub mod stimecmph; // Virtual supervisor indirect access pub mod vsiselect; +// Hypervisor Trap Setup +pub mod hstatus; + // Entropy source pub mod seed; diff --git a/riscv/src/register/hstatus.rs b/riscv/src/register/hstatus.rs new file mode 100644 index 00000000..4918e3b8 --- /dev/null +++ b/riscv/src/register/hstatus.rs @@ -0,0 +1,275 @@ +//! hstatus register + +pub use super::misa::XLEN; +pub use super::mstatus::{Endianness, GVA}; + +use crate::bits::{bf_extract, bf_insert}; + +#[cfg(not(target_arch = "riscv32"))] +read_write_csr! { + /// hstatus register + Hstatus: 0x600, + mask: 0x0003_0003_0073_F3E0, +} + +#[cfg(target_arch = "riscv32")] +read_write_csr! { + /// hstatus register + Hstatus: 0x600, + mask: 0x0073_F3E0, +} + +csr_field_enum! { + /// Supervisor Previous Virtualization Mode + SPV { + default: NoVirtualization, + NoVirtualization = 0, + Virtualization = 1, + } +} + +csr_field_enum! { + /// Supervisor Previous Virtual Privilege + SPVP { + default: VirtualUser, + VirtualUser = 0, + VirtualSupervisor = 1, + } +} + +csr_field_enum! { + /// Hypervisor User Mode Handling + HU { + default: HandlingOff, + HandlingOff = 0, + HandlingOn = 1, + } +} + +csr_field_enum! { + /// Virtual Trap Virtual Memory + VTVM { + default: TrapMemoryDisabled, + TrapMemoryDisabled = 0, + TrapMemoryEnabled = 1, + } +} + +csr_field_enum! { + /// Virtual Timeout Wait + VTW { + default: IndefiniteWFI, + IndefiniteWFI = 0, + TrapOnWFI = 1, + } +} + +csr_field_enum! { + /// Virtual Trap SRET + VTSR { + default: TrapResumeInU, + TrapResumeInU = 0, + TrapCapturedInHS = 1, + } +} + +read_only_csr_field! { + Hstatus, + /// Guest Virtual Address + gva, + GVA: [6:6], +} + +read_write_csr_field! { + Hstatus, + /// Supervisor Previous Virtualization + spv: 7, +} + +read_write_csr_field! { + Hstatus, + /// Supervisor Previous Virtual Privilege + spvp: 8, +} + +read_write_csr_field! { + Hstatus, + /// Hypervisor User HLV HLVX HSV Enable + hu: 9, +} + +read_write_csr_field! { + Hstatus, + /// Virtual Guest External Interrupt Number + vgein: [12:17], +} + +read_write_csr_field! { + Hstatus, + /// Virtual Trap Virtual Memory + vtvm: 20, +} + +read_write_csr_field! { + Hstatus, + /// Virtual Timeout Wait + vtw: 21, +} + +read_write_csr_field! { + Hstatus, + /// Virtual Trap SRET + vtsr: 22, +} + +#[cfg(not(target_arch = "riscv32"))] +read_write_csr_field! { + Hstatus, + /// Hypervisor User Pointer Masking Mode + hupmm: [48:49], +} + +impl Hstatus { + /// Effective xlen in VS-mode (i.e., `VSXLEN`). + /// + /// In RISCV-32, VSXL does not exist, and `VSXLEN` is always [`XLEN::XLEN32`]. + #[inline] + pub fn vsxl(&self) -> XLEN { + match () { + #[cfg(not(target_arch = "riscv32"))] + () => XLEN::try_from(bf_extract(self.bits, 32, 2)).unwrap_or_default(), + #[cfg(target_arch = "riscv32")] + () => XLEN::XLEN32, + } + } + + /// Update Effective xlen in VS-mode (i.e., `VSXLEN`). + /// + /// Note this updates a previously read [`Hstatus`] value, but does not + /// affect the hstatus CSR itself. + /// + /// # Note + /// + /// In RISCV-32, `VSXL` does not exist, and `VSXLEN` is always [`XLEN::XLEN32`]. + #[inline] + #[cfg(not(target_arch = "riscv32"))] + pub fn set_vsxl(&mut self, uxl: XLEN) { + self.bits = bf_insert(self.bits, 32, 2, uxl as usize); + } + + /// VS-mode non-instruction-fetch memory endianness. + #[inline] + pub fn vsbe(&self) -> Endianness { + Endianness::from(bf_extract(self.bits, 5, 1) != 0) + } + + /// Update VS-mode non-instruction-fetch memory endianness + /// + /// Note this updates a previously read [`Hstatus`] value, but does not + /// affect the hstatus CSR itself. See [`set_vsbe`] to directly update the + /// CSR. + #[inline] + pub fn set_vsbe(&mut self, endianness: Endianness) { + self.bits = bf_insert(self.bits, 5, 1, endianness as usize); + } +} + +/// Bitfield constants for the `hstatus` fields that are implemented manually +/// (rather than via the field macros) because they only exist on 64-bit targets. +/// +/// These complement the macro-generated `_SHIFT`/`_WIDTH`/`_MASK` +/// constants for the remaining `hstatus` fields. +/// HUPMM left unimplemented +#[cfg(not(target_arch = "riscv32"))] +impl Hstatus { + /// Bit shift of the `vsxl` (VS-mode XLEN) field. + pub const VSXL_SHIFT: usize = 32; + /// Bit width of the `vsxl` field. + pub const VSXL_WIDTH: usize = 2; + /// Field-shifted bitmask of the `vsxl` field. + pub const VSXL_MASK: usize = ((1 << Self::VSXL_WIDTH) - 1) << Self::VSXL_SHIFT; +} + +set!(0x600); +clear!(0x600); + +set_clear_csr!( + /// Virtual Trap Virtual Memory + , set_vtvm, clear_vtvm, 1 << 20); +set_clear_csr!( + /// Virtual Timeout Wait + , set_vtw, clear_vtw, 1 << 21); +set_clear_csr!( + /// Virtual Trap SRET + , set_vtsr, clear_vtsr, 1 << 22); + +/// Set VS-mode non-instruction-fetch memory endianness +#[inline] +pub unsafe fn set_vsbe(endianness: Endianness) { + match endianness { + Endianness::BigEndian => _set(1 << 5), + Endianness::LittleEndian => _clear(1 << 5), + } +} + +/// Supervisor Previous Virtualization Mode +#[inline] +pub unsafe fn set_spv(spv: SPV) { + match spv { + SPV::NoVirtualization => _set(1 << 7), + SPV::Virtualization => _clear(1 << 7), + } +} + +/// Supervisor Previous Virtual Privilege +#[inline] +pub unsafe fn set_spvp(spvp: SPVP) { + match spvp { + SPVP::VirtualSupervisor => _set(1 << 8), + SPVP::VirtualUser => _clear(1 << 8), + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_hstatus() { + let mut hstatus = Hstatus { bits: 0 }; + + test_csr_field!(hstatus, spv); + test_csr_field!(hstatus, spvp); + test_csr_field!(hstatus, hu); + test_csr_field!(hstatus, vtvm); + test_csr_field!(hstatus, vtw); + test_csr_field!(hstatus, vtsr); + + #[cfg(not(target_arch = "riscv32"))] + { + [XLEN::XLEN32, XLEN::XLEN64, XLEN::XLEN128] + .into_iter() + .for_each(|xlen| { + let mut h = Hstatus::from_bits(0); + h.set_vsxl(xlen); + assert_eq!(h.vsxl(), xlen); + }); + + [Endianness::LittleEndian, Endianness::BigEndian] + .into_iter() + .for_each(|endianness| { + let mut h = Hstatus::from_bits(0); + h.set_vsbe(endianness); + assert_eq!(h.vsbe(), endianness); + }); + + [GVA::NoTranslation, GVA::GuestAddress] + .into_iter() + .for_each(|gva| { + let m = Hstatus::from_bits(gva.into_usize() << 6); + assert_eq!(m.gva(), gva); + assert_eq!(m.try_gva(), Ok(gva)); + }); + } + } +} diff --git a/riscv/src/register/mstatus.rs b/riscv/src/register/mstatus.rs index d40bc590..8f75468b 100644 --- a/riscv/src/register/mstatus.rs +++ b/riscv/src/register/mstatus.rs @@ -8,7 +8,7 @@ use crate::bits::{bf_extract, bf_insert}; read_write_csr! { /// mstatus register Mstatus: 0x300, - mask: 0x8000_003f_007f_ffea, + mask: 0x8000_00ff_007f_ffea, } #[cfg(target_arch = "riscv32")] @@ -65,6 +65,15 @@ csr_field_enum! { } } +csr_field_enum! { + /// Machine Previous Virtualization Mode + MPV { + default: VirtualizationDisabled, + VirtualizationDisabled = 0, + VirtualizationEnabled = 1, + } +} + csr_field_enum! { /// Supervisor Previous Privilege Mode SPP { @@ -74,6 +83,15 @@ csr_field_enum! { } } +csr_field_enum! { + /// Guest Virtual Address + GVA { + default: NoTranslation, + NoTranslation = 0, + GuestAddress = 1, + } +} + csr_field_enum! { /// Non-instruction-fetch memory endianness Endianness { @@ -168,7 +186,7 @@ read_only_csr_field! { read_write_csr_field! { Mstatus, - /// Modify Memory PRiVilege + /// Modify Memory Privilege mprv: 17, } @@ -180,7 +198,7 @@ read_write_csr_field! { read_write_csr_field! { Mstatus, - /// Make eXecutable Readable + /// Make Executable Readable mxr: 19, } @@ -229,6 +247,22 @@ read_only_csr_field! { sd: 31, } +#[cfg(not(target_arch = "riscv32"))] +read_only_csr_field! { + Mstatus, + /// Guest Virtual Address + gva, + GVA: [38:38], +} + +#[cfg(not(target_arch = "riscv32"))] +read_only_csr_field! { + Mstatus, + /// Machine Previous Virtualization + mpv, + MPV: [39:39] +} + #[cfg(not(target_arch = "riscv32"))] read_only_csr_field! { Mstatus, @@ -581,7 +615,6 @@ mod test { assert_eq!(m.xs(), xs); assert_eq!(m.try_xs(), Ok(xs)); }); - test_csr_field!(mstatus, sie); test_csr_field!(mstatus, mie); test_csr_field!(mstatus, spie); @@ -627,6 +660,22 @@ mod test { m.set_mbe(endianness); assert_eq!(m.mbe(), endianness); }); + // MPV is read-only: it contains previous mode virtualization state + [MPV::VirtualizationDisabled, MPV::VirtualizationEnabled] + .into_iter() + .for_each(|mpv| { + let m = Mstatus::from_bits(mpv.into_usize() << 39); + assert_eq!(m.mpv(), mpv); + assert_eq!(m.try_mpv(), Ok(mpv)); + }); + // GVA is read-only: it indicates the trap address in mtval is from a guest + [GVA::NoTranslation, GVA::GuestAddress] + .into_iter() + .for_each(|gva| { + let m = Mstatus::from_bits(gva.into_usize() << 38); + assert_eq!(m.gva(), gva); + assert_eq!(m.try_gva(), Ok(gva)); + }); } } } diff --git a/riscv/src/register/mstatush.rs b/riscv/src/register/mstatush.rs index cc64598e..30a949b2 100644 --- a/riscv/src/register/mstatush.rs +++ b/riscv/src/register/mstatush.rs @@ -1,9 +1,9 @@ //! mstatush register (RISCV-32 only) -pub use super::mstatus::Endianness; +pub use super::mstatus::{Endianness, GVA, MPV}; read_write_csr! { - /// mstatus register + /// mstatush register Mstatush: 0x310, mask: 0x30, } @@ -22,6 +22,22 @@ read_write_csr_field! { Endianness: [5:5], } +#[cfg(target_arch = "riscv32")] +read_only_csr_field! { + Mstatush, + /// Guest Virtual Address + gva, + GVA: [6:6] +} + +#[cfg(target_arch = "riscv32")] +read_only_csr_field! { + Mstatush, + /// Machine Previous Virtualization + mpv, + MPV: [7:7] +} + set_rv32!(0x310); clear_rv32!(0x310); diff --git a/tests-trybuild/tests/riscv-rt/core_interrupt/fail_impl.stderr b/tests-trybuild/tests/riscv-rt/core_interrupt/fail_impl.stderr index ce2a266f..76d25815 100644 --- a/tests-trybuild/tests/riscv-rt/core_interrupt/fail_impl.stderr +++ b/tests-trybuild/tests/riscv-rt/core_interrupt/fail_impl.stderr @@ -13,6 +13,11 @@ help: the following other types implement trait `CoreInterruptNumber` | unsafe impl CoreInterruptNumber for Interrupt {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `riscv::interrupt::Interrupt` | + ::: $WORKSPACE/riscv/src/interrupt/hypervisor.rs + | + | unsafe impl CoreInterruptNumber for Interrupt {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `riscv::interrupt::hypervisor::Interrupt` + | ::: $WORKSPACE/riscv/src/interrupt/supervisor.rs | | unsafe impl CoreInterruptNumber for Interrupt {} diff --git a/tests-trybuild/tests/riscv-rt/exception/fail_impl.stderr b/tests-trybuild/tests/riscv-rt/exception/fail_impl.stderr index 519f8258..c99d10ac 100644 --- a/tests-trybuild/tests/riscv-rt/exception/fail_impl.stderr +++ b/tests-trybuild/tests/riscv-rt/exception/fail_impl.stderr @@ -13,6 +13,11 @@ help: the following other types implement trait `ExceptionNumber` | unsafe impl ExceptionNumber for Exception { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `riscv::interrupt::Exception` | + ::: $WORKSPACE/riscv/src/interrupt/hypervisor.rs + | + | unsafe impl ExceptionNumber for Exception { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `riscv::interrupt::hypervisor::Exception` + | ::: $WORKSPACE/riscv/src/interrupt/supervisor.rs | | unsafe impl ExceptionNumber for Exception {