编写 UART 驱动程序

QEMU “虚拟机”具有 PL011 UART,现在为其编写驱动程序。

const FLAG_REGISTER_OFFSET: usize = 0x18;
const FR_BUSY: u8 = 1 << 3;
const FR_TXFF: u8 = 1 << 5;

/// Minimal driver for a PL011 UART.
#[derive(Debug)]
pub struct Uart {
    base_address: *mut u8,
}

impl Uart {
    /// Constructs a new instance of the UART driver for a PL011 device at the
    /// given base address.
    ///
    /// # Safety
    ///
    /// The given base address must point to the 8 MMIO control registers of a
    /// PL011 device, which must be mapped into the address space of the process
    /// as device memory and not have any other aliases.
    pub unsafe fn new(base_address: *mut u8) -> Self {
        Self { base_address }
    }

    /// Writes a single byte to the UART.
    pub fn write_byte(&self, byte: u8) {
        // Wait until there is room in the TX buffer.
        while self.read_flag_register() & FR_TXFF != 0 {}

        // SAFETY: We know that the base address points to the control
        // registers of a PL011 device which is appropriately mapped.
        unsafe {
            // Write to the TX buffer.
            self.base_address.write_volatile(byte);
        }

        // Wait until the UART is no longer busy.
        while self.read_flag_register() & FR_BUSY != 0 {}
    }

    fn read_flag_register(&self) -> u8 {
        // SAFETY: We know that the base address points to the control
        // registers of a PL011 device which is appropriately mapped.
        unsafe { self.base_address.add(FLAG_REGISTER_OFFSET).read_volatile() }
    }
}
  • 请注意,使用 Uart::new 方法不安全,而其他方法则安全。原因在于,只要 Uart::new 的调用方保证满足其安全要求(即所指定的 UART 只有一个驱动程序实例,且没有其他内容与其地址空间存在重叠),那么后续调用 write_byte 始终是安全的,因为我们假定需要满足的前提条件。
  • 我们也可以采用相反的方式(即确保 new 安全,但 write_byte 不安全),不过这样会很不方便,因为每当调用 write_byte 时都需要推断是否安全。
  • 这是安全地封装不安全代码时常见的策略:即在少数调用代码的地方进行安全验证,而不是在很多地方进行。