mtvec.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //! mtvec register
  2. /// mtvec register
  3. #[derive(Clone, Copy, Debug)]
  4. pub struct Mtvec {
  5. bits: usize,
  6. }
  7. /// Trap mode
  8. pub enum TrapMode {
  9. Direct = 0,
  10. Vectored = 1,
  11. }
  12. impl Mtvec {
  13. /// Returns the contents of the register as raw bits
  14. pub fn bits(&self) -> usize {
  15. self.bits
  16. }
  17. /// Returns the trap-vector base-address
  18. pub fn address(&self) -> usize {
  19. self.bits - (self.bits & 0b11)
  20. }
  21. /// Returns the trap-vector mode
  22. pub fn trap_mode(&self) -> TrapMode {
  23. let mode = self.bits & 0b11;
  24. match mode {
  25. 0 => TrapMode::Direct,
  26. 1 => TrapMode::Vectored,
  27. _ => unimplemented!()
  28. }
  29. }
  30. }
  31. /// Reads the CSR
  32. #[inline]
  33. pub fn read() -> Mtvec {
  34. match () {
  35. #[cfg(target_arch = "riscv")]
  36. () => {
  37. let r: usize;
  38. unsafe {
  39. asm!("csrrs $0, 0x305, x0" : "=r"(r) ::: "volatile");
  40. }
  41. Mtvec { bits: r }
  42. }
  43. #[cfg(not(target_arch = "riscv"))]
  44. () => unimplemented!(),
  45. }
  46. }
  47. /// Writes the CSR
  48. #[cfg_attr(not(target_arch = "riscv"), allow(unused_variables))]
  49. #[inline]
  50. pub unsafe fn write(addr: usize, mode: TrapMode) {
  51. let bits = addr + mode as usize;
  52. match () {
  53. #[cfg(target_arch = "riscv")]
  54. () => asm!("csrrw x0, 0x305, $0" :: "r"(bits) :: "volatile"),
  55. #[cfg(not(target_arch = "riscv"))]
  56. () => unimplemented!(),
  57. }
  58. }