sifive_test_device/
lib.rs

1//! 为 qemu-system-riscv32/64 提供 SiFive 测试设备定义。
2
3#![no_std]
4#![deny(warnings, missing_docs)]
5
6use core::cell::UnsafeCell;
7
8/// SiFive 测试设备。
9#[repr(transparent)]
10pub struct SifiveTestDevice(UnsafeCell<u32>); // 实测发现源码写的 u64 但只能写进 32 位
11
12const FAIL: u16 = 0x3333;
13const PASS: u16 = 0x5555;
14const RESET: u16 = 0x7777;
15
16impl SifiveTestDevice {
17    /// 以 code 为错误码,退出进程。
18    #[inline]
19    pub fn fail(&self, code: u16) -> ! {
20        self.write(FAIL as u32 | (code as u32) << 16)
21    }
22
23    /// 以 0 为错误码,退出进程。
24    #[inline]
25    pub fn pass(&self) -> ! {
26        self.write(PASS as _)
27    }
28
29    /// 系统重启。
30    #[inline]
31    pub fn reset(&self) -> ! {
32        self.write(RESET as _)
33    }
34
35    #[inline]
36    fn write(&self, bits: u32) -> ! {
37        unsafe { self.0.get().write_volatile(bits) };
38        unreachable!()
39    }
40}