MMIO 的易失性内存访问

  • Use pointer::read_volatile and pointer::write_volatile.
  • Never hold a reference to a location being accessed with these methods. Rust may read from (or write to, for &mut) a reference at any time.
  • Use &raw to get fields of structs without creating an intermediate reference.
const SOME_DEVICE_REGISTER: *mut u64 = 0x800_0000 as _;
// SAFETY: Some device is mapped at this address.
unsafe {
    SOME_DEVICE_REGISTER.write_volatile(0xff);
    SOME_DEVICE_REGISTER.write_volatile(0x80);
    assert_eq!(SOME_DEVICE_REGISTER.read_volatile(), 0xaa);
}
  • 易失性访问:执行读取或写入操作可能会产生副作用,因此应阻止编译器或硬件对这些操作进行重新排序、复制或省略。
    • 通常情况下,如果您先写入操作,紧接着进行读取操作(例如通过可变引用),则编译器可能会认为读取的值是最新写入的值,就不再执行实际的内存读取过程。
  • 虽然在对硬件进行易失性访问时,一些 crate 确实会提及引用,但这很不安全。只要存在引用,编译器就会选择对其进行解引用操作。
  • Use &raw to get struct field pointers from a pointer to the struct.
  • For compatibility with old versions of Rust you can use the addr_of! macro instead.