ベアメタルRust PM
RTC ドライバ
(演習に戻る)
main.rs:
#![no_main]
#![no_std]
mod exceptions;
mod logger;
mod pl011;
mod pl031;
use crate::pl031::Rtc;
use arm_gic::gicv3::{IntId, Trigger};
use arm_gic::{irq_enable, wfi};
use chrono::{TimeZone, Utc};
use core::hint::spin_loop;
use crate::pl011::Uart;
use arm_gic::gicv3::GicV3;
use core::panic::PanicInfo;
use log::{error, info, trace, LevelFilter};
use smccc::psci::system_off;
use smccc::Hvc;
/// GICv3 のベースアドレス。
const GICD_BASE_ADDRESS: *mut u64 = 0x800_0000 as _;
const GICR_BASE_ADDRESS: *mut u64 = 0x80A_0000 as _;
/// プライマリ PL011 UART のベースアドレス。
const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;
/// PL031 RTC のベースアドレス。
const PL031_BASE_ADDRESS: *mut u32 = 0x901_0000 as _;
/// PL031 RTC が使用する IRQ。
const PL031_IRQ: IntId = IntId::spi(2);
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
extern "C" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {
// SAFETY: `PL011_BASE_ADDRESS` is the base address of a PL011 device, and
// nothing else accesses that address range.
let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };
logger::init(uart, LevelFilter::Trace).unwrap();
info!("main({:#x}, {:#x}, {:#x}, {:#x})", x0, x1, x2, x3);
// SAFETY: `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the base
// addresses of a GICv3 distributor and redistributor respectively, and
// nothing else accesses those address ranges.
let mut gic = unsafe { GicV3::new(GICD_BASE_ADDRESS, GICR_BASE_ADDRESS) };
gic.setup();
// SAFETY: `PL031_BASE_ADDRESS` is the base address of a PL031 device, and
// nothing else accesses that address range.
let mut rtc = unsafe { Rtc::new(PL031_BASE_ADDRESS) };
let timestamp = rtc.read();
let time = Utc.timestamp_opt(timestamp.into(), 0).unwrap();
info!("RTC: {time}");
GicV3::set_priority_mask(0xff);
gic.set_interrupt_priority(PL031_IRQ, 0x80);
gic.set_trigger(PL031_IRQ, Trigger::Level);
irq_enable();
gic.enable_interrupt(PL031_IRQ, true);
// 割り込みなしで 3 秒間待機します。
let target = timestamp + 3;
rtc.set_match(target);
info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap());
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
while !rtc.matched() {
spin_loop();
}
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
info!("Finished waiting");
// 割り込みまでさらに 3 秒待ちます。
let target = timestamp + 6;
info!("Waiting for {}", Utc.timestamp_opt(target.into(), 0).unwrap());
rtc.set_match(target);
rtc.clear_interrupt();
rtc.enable_interrupt(true);
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
while !rtc.interrupt_pending() {
wfi();
}
trace!(
"matched={}, interrupt_pending={}",
rtc.matched(),
rtc.interrupt_pending()
);
info!("Finished waiting");
system_off::<Hvc>().unwrap();
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
error!("{info}");
system_off::<Hvc>().unwrap();
loop {}
}
pl031.rs:
#![allow(unused)]
fn main() {
#[repr(C, align(4))]
struct Registers {
/// データレジスタ
dr: u32,
/// 一致レジスタ
mr: u32,
/// 読み込みレジスタ
lr: u32,
/// 制御レジスタ
cr: u8,
_reserved0: [u8; 3],
/// 割り込みマスクセットまたはクリアレジスタ
imsc: u8,
_reserved1: [u8; 3],
/// 未加工の割り込みステータス
ris: u8,
_reserved2: [u8; 3],
/// マスクされた割り込みステータス
mis: u8,
_reserved3: [u8; 3],
/// 割り込みクリアレジスタ
icr: u8,
_reserved4: [u8; 3],
}
/// PL031 リアルタイム クロック用のドライバ。
#[derive(Debug)]
pub struct Rtc {
registers: *mut Registers,
}
impl Rtc {
/// 指定されたベースアドレスに
/// PL031 デバイス用の RTC ドライバの新しいインスタンスを作成します。
///
/// # 安全性
///
/// 指定されたベースアドレスは PL031 デバイスの MMIO 制御レジスタを指している必要があります。
/// これらはデバイスメモリとしてプロセスのアドレス空間に
/// マッピングされ、他のエイリアスはありません。
pub unsafe fn new(base_address: *mut u32) -> Self {
Self { registers: base_address as *mut Registers }
}
/// 現在の RTC 値を読み取ります。
pub fn read(&self) -> u32 {
// SAFETY: We know that self.registers points to the control registers
// of a PL031 device which is appropriately mapped.
unsafe { (&raw const (*self.registers).dr).read_volatile() }
}
/// 一致値を書き込みます。RTC 値がこれに一致すると、割り込みが生成されます
/// (割り込みが有効になっている場合)。
pub fn set_match(&mut self, value: u32) {
// SAFETY: We know that self.registers points to the control registers
// of a PL031 device which is appropriately mapped.
unsafe { (&raw mut (*self.registers).mr).write_volatile(value) }
}
/// 割り込みが有効になっているかどうかに関係なく、一致レジスタが RTC 値と
/// 一致するかどうかを返します。
pub fn matched(&self) -> bool {
// SAFETY: We know that self.registers points to the control registers
// of a PL031 device which is appropriately mapped.
let ris = unsafe { (&raw const (*self.registers).ris).read_volatile() };
(ris & 0x01) != 0
}
/// 現在保留中の割り込みがあるかどうかを返します。
///
/// これは `matched` が true を返し、割り込みがマスクされている場合にのみ
/// true になります。
pub fn interrupt_pending(&self) -> bool {
// SAFETY: We know that self.registers points to the control registers
// of a PL031 device which is appropriately mapped.
let ris = unsafe { (&raw const (*self.registers).mis).read_volatile() };
(ris & 0x01) != 0
}
/// 割り込みマスクを設定またはクリアします。
///
/// マスクが true の場合、割り込みは有効になります。false の場合、
/// 割り込みは無効になります。
pub fn enable_interrupt(&mut self, mask: bool) {
let imsc = if mask { 0x01 } else { 0x00 };
// SAFETY: We know that self.registers points to the control registers
// of a PL031 device which is appropriately mapped.
unsafe { (&raw mut (*self.registers).imsc).write_volatile(imsc) }
}
/// 保留中の割り込みがあればクリアします。
pub fn clear_interrupt(&mut self) {
// SAFETY: We know that self.registers points to the control registers
// of a PL031 device which is appropriately mapped.
unsafe { (&raw mut (*self.registers).icr).write_volatile(0x01) }
}
}
// SAFETY: `Rtc` just contains a pointer to device memory, which can be
// accessed from any context.
unsafe impl Send for Rtc {}
}