Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/riscv.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ target/
.idea/
.vscode/
.DS_Store
makefile
1 change: 1 addition & 0 deletions riscv/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions riscv/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
5 changes: 4 additions & 1 deletion riscv/src/interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down
337 changes: 337 additions & 0 deletions riscv/src/interrupt/hypervisor.rs
Original file line number Diff line number Diff line change
@@ -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,
}
Comment on lines +15 to +23

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add the new variants to interrupt::machine.rs and interrupt::supervisor.rs?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@romancardenas I'm not sure I'm following here. When I look at interrupt::supervisor.rs it does not contain m-mode interrupts. also interrupt::supervisor.rs would not be active at the export on the crate level, as s-mode would not be enabled while hs-mode is. I believe m-mode could see hs-mode, so i can add them there.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added exceptions and interrupts to machine.rs as well.

@vm-kit vm-kit Nov 28, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I started working on this logic on another branch for interrupt::hypervisor.rs and I see why you want them in interrupt::supervisor.rs now. Do you want me to ensure the new exceptions and interrupts are behind the hs-mode flag, so they do not impact any other crate users? Some might not have a catch _ arm when switching on the invariants. causing them to need to add one before they can use the new crate version.


/// 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<Self> {
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,
Comment on lines +65 to +81

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add these new variants to interrupt::machine.rs and interrupt::supervisor.rs.
Also, preserve the naming for already user-level causes.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as here. Let me know your thoughts on supervisor receiving the new exceptions. I believe it should be fine either way, but I don't think supervisor => s-mode in this repository can ever actually trap on the hs-mode ones.

}

/// 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<Self> {
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<I: CoreInterruptNumber>(_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<I: CoreInterruptNumber>(_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<I: CoreInterruptNumber>(_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<I: CoreInterruptNumber>(_interrupt: I) -> bool {
todo!() //hip::read().is_pending(interrupt)
}

/// Disables interrupts globally in the current hart (hypervisor mode).
#[inline]
pub fn disable() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For same functions as in supervisor level, you can just reexport them from interrupt::supervisor.rs

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if I can yet. I have not worked through the logic, but I think a lot of things depend on whether the trap came from HS, or VS-VU mode. Is it okay if I tackle this later?

// 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<I: CoreInterruptNumber, E: ExceptionNumber>() -> Result<Trap<I, E>> {
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<I: CoreInterruptNumber, E: ExceptionNumber>() -> Trap<I, E> {
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, R>(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, R>(f: F) -> R
where
F: FnOnce() -> R,
{
let sstatus = sstatus::read();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can reuse the interrupt::supervisor::nested function and just add the code required for hypervisor mode.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if I can yet. I have not worked through the logic, but I think a lot of things depend on whether the trap came from HS, or VS-VU mode. Is it okay if I tackle this later?

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)
}
}
Loading