Bare Metal Rust Afternoon

RTC driver

(back to exercise)

main.rs:

  1. #![no_main]
  2. #![no_std]
  3. mod exceptions;
  4. mod logger;
  5. mod pl011;
  6. mod pl031;
  7. use crate::pl031::Rtc;
  8. use arm_gic::gicv3::{IntId, Trigger};
  9. use arm_gic::{irq_enable, wfi};
  10. use chrono::{TimeZone, Utc};
  11. use core::hint::spin_loop;
  12. use crate::pl011::Uart;
  13. use arm_gic::gicv3::GicV3;
  14. use core::panic::PanicInfo;
  15. use log::{error, info, trace, LevelFilter};
  16. use smccc::psci::system_off;
  17. use smccc::Hvc;
  18. /// Base addresses of the GICv3.
  19. const GICD_BASE_ADDRESS: *mut u64 = 0x800_0000 as _;
  20. const GICR_BASE_ADDRESS: *mut u64 = 0x80A_0000 as _;
  21. /// Base address of the primary PL011 UART.
  22. const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;
  23. /// Base address of the PL031 RTC.
  24. const PL031_BASE_ADDRESS: *mut u32 = 0x901_0000 as _;
  25. /// The IRQ used by the PL031 RTC.
  26. const PL031_IRQ: IntId = IntId::spi(2);
  27. // SAFETY: There is no other global function of this name.
  28. #[unsafe(no_mangle)]
  29. extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
  30.     // SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
  31.     // nothing else accesses that address range.
  32.     let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };
  33.     logger::init(uart, LevelFilter::Trace).unwrap();
  34.     info!("main({:#x}, {:#x}, {:#x}, {:#x})", x0, x1, x2, x3);
  35.     // SAFETY: `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the base
  36.     // addresses of a GICv3 distributor and redistributor respectively, and
  37.     // nothing else accesses those address ranges.
  38.     let mut gic = unsafe { GicV3::new(GICD_BASE_ADDRESS, GICR_BASE_ADDRESS) };
  39.     gic.setup();
  40.     // SAFETY: `PL031_BASE_ADDRESS` is the base address of a PL031 device, and
  41.     // nothing else accesses that address range.
  42.     let mut rtc = unsafe { Rtc::new(PL031_BASE_ADDRESS) };
  43.     let timestamp = rtc.read();
  44.     let time = Utc.timestamp_opt(timestamp.into(), 0).unwrap();
  45.     info!("RTC: {time}");
  46.     GicV3::set_priority_mask(0xff);
  47.     gic.set_interrupt_priority(PL031_IRQ, 0x80);
  48.     gic.set_trigger(PL031_IRQ, Trigger::Level);
  49.     irq_enable();
  50.     gic.enable_interrupt(PL031_IRQ, true);
  51.     // Wait for 3 seconds, without interrupts.
  52.     let target = timestamp + 3;
  53.     rtc.set_match(target);
  54.     info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap());
  55.     trace!(
  56.         "matched={}, interrupt_pending={}",
  57.         rtc.matched(),
  58.         rtc.interrupt_pending()
  59.     );
  60.     while !rtc.matched() {
  61.         spin_loop();
  62.     }
  63.     trace!(
  64.         "matched={}, interrupt_pending={}",
  65.         rtc.matched(),
  66.         rtc.interrupt_pending()
  67.     );
  68.     info!("Finished waiting");
  69.     // Wait another 3 seconds for an interrupt.
  70.     let target = timestamp + 6;
  71.     info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap());
  72.     rtc.set_match(target);
  73.     rtc.clear_interrupt();
  74.     rtc.enable_interrupt(true);
  75.     trace!(
  76.         "matched={}, interrupt_pending={}",
  77.         rtc.matched(),
  78.         rtc.interrupt_pending()
  79.     );
  80.     while !rtc.interrupt_pending() {
  81.         wfi();
  82.     }
  83.     trace!(
  84.         "matched={}, interrupt_pending={}",
  85.         rtc.matched(),
  86.         rtc.interrupt_pending()
  87.     );
  88.     info!("Finished waiting");
  89.     system_off::<Hvc>().unwrap();
  90. }
  91. #[panic_handler]
  92. fn panic(info: &PanicInfo) -> ! {
  93.     error!("{info}");
  94.     system_off::<Hvc>().unwrap();
  95.     loop {}
  96. }

pl031.rs:

  1. #![allow(unused)]
  2. fn main() {
  3. #[repr(C, align(4))]
  4. struct Registers {
  5.     /// Data register
  6.     dr: u32,
  7.     /// Match register
  8.     mr: u32,
  9.     /// Load register
  10.     lr: u32,
  11.     /// Control register
  12.     cr: u8,
  13.     _reserved0: [u8; 3],
  14.     /// Interrupt Mask Set or Clear register
  15.     imsc: u8,
  16.     _reserved1: [u8; 3],
  17.     /// Raw Interrupt Status
  18.     ris: u8,
  19.     _reserved2: [u8; 3],
  20.     /// Masked Interrupt Status
  21.     mis: u8,
  22.     _reserved3: [u8; 3],
  23.     /// Interrupt Clear Register
  24.     icr: u8,
  25.     _reserved4: [u8; 3],
  26. }
  27. /// Driver for a PL031 real-time clock.
  28. #[derive(Debug)]
  29. pub struct Rtc {
  30.     registers: *mut Registers,
  31. }
  32. impl Rtc {
  33.     /// Constructs a new instance of the RTC driver for a PL031 device at the
  34.     /// given base address.
  35.     ///
  36.     /// # Safety
  37.     ///
  38.     /// The given base address must point to the MMIO control registers of a
  39.     /// PL031 device, which must be mapped into the address space of the process
  40.     /// as device memory and not have any other aliases.
  41.     pub unsafe fn new(base_address: *mut u32) -> Self {
  42.         Self { registers: base_address as *mut Registers }
  43.     }
  44.     /// Reads the current RTC value.
  45.     pub fn read(&self) -> u32 {
  46.         // SAFETY: We know that self.registers points to the control registers
  47.         // of a PL031 device which is appropriately mapped.
  48.         unsafe { (&raw const (*self.registers).dr).read_volatile() }
  49.     }
  50.     /// Writes a match value. When the RTC value matches this then an interrupt
  51.     /// will be generated (if it is enabled).
  52.     pub fn set_match(&mut self, value: u32) {
  53.         // SAFETY: We know that self.registers points to the control registers
  54.         // of a PL031 device which is appropriately mapped.
  55.         unsafe { (&raw mut (*self.registers).mr).write_volatile(value) }
  56.     }
  57.     /// Returns whether the match register matches the RTC value, whether or not
  58.     /// the interrupt is enabled.
  59.     pub fn matched(&self) -> bool {
  60.         // SAFETY: We know that self.registers points to the control registers
  61.         // of a PL031 device which is appropriately mapped.
  62.         let ris = unsafe { (&raw const (*self.registers).ris).read_volatile() };
  63.         (ris & 0x01) != 0
  64.     }
  65.     /// Returns whether there is currently an interrupt pending.
  66.     ///
  67.     /// This should be true if and only if `matched` returns true and the
  68.     /// interrupt is masked.
  69.     pub fn interrupt_pending(&self) -> bool {
  70.         // SAFETY: We know that self.registers points to the control registers
  71.         // of a PL031 device which is appropriately mapped.
  72.         let ris = unsafe { (&raw const (*self.registers).mis).read_volatile() };
  73.         (ris & 0x01) != 0
  74.     }
  75.     /// Sets or clears the interrupt mask.
  76.     ///
  77.     /// When the mask is true the interrupt is enabled; when it is false the
  78.     /// interrupt is disabled.
  79.     pub fn enable_interrupt(&mut self, mask: bool) {
  80.         let imsc = if mask { 0x01 } else { 0x00 };
  81.         // SAFETY: We know that self.registers points to the control registers
  82.         // of a PL031 device which is appropriately mapped.
  83.         unsafe { (&raw mut (*self.registers).imsc).write_volatile(imsc) }
  84.     }
  85.     /// Clears a pending interrupt, if any.
  86.     pub fn clear_interrupt(&mut self) {
  87.         // SAFETY: We know that self.registers points to the control registers
  88.         // of a PL031 device which is appropriately mapped.
  89.         unsafe { (&raw mut (*self.registers).icr).write_volatile(0x01) }
  90.     }
  91. }
  92. // SAFETY: `Rtc` just contains a pointer to device memory, which can be
  93. // accessed from any context.
  94. unsafe impl Send for Rtc {}
  95. }