uart.rs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //! Minimal driver for an 8250 UART.
  2. use core::fmt::{self, Write};
  3. use core::ptr::write_volatile;
  4. /// Minimal driver for an 8250 UART.
  5. pub struct Uart {
  6. base_address: *mut u8,
  7. }
  8. impl Uart {
  9. /// Constructs a new instance of the UART driver for a device at the given base address.
  10. ///
  11. /// # Safety
  12. ///
  13. /// The given base address must point to the 8 MMIO control registers of an appropriate UART
  14. /// device, which must be mapped into the address space of the process as device memory and not
  15. /// have any other aliases.
  16. pub unsafe fn new(base_address: usize) -> Self {
  17. Self {
  18. base_address: base_address as *mut u8,
  19. }
  20. }
  21. /// Writes a single byte to the UART.
  22. pub fn write_byte(&self, byte: u8) {
  23. // Safe because we know that the base address points to the control registers of an UART
  24. // device which is appropriately mapped.
  25. unsafe {
  26. write_volatile(self.base_address, byte);
  27. }
  28. }
  29. }
  30. impl Write for Uart {
  31. fn write_str(&mut self, s: &str) -> fmt::Result {
  32. for c in s.as_bytes() {
  33. self.write_byte(*c);
  34. }
  35. Ok(())
  36. }
  37. }
  38. // Safe because it just contains a pointer to device memory, which can be accessed from any context.
  39. unsafe impl Send for Uart {}