From b8194e7c8360f03ddbf4d42ee7b6d5aee60ce3a1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 7 Apr 2026 15:57:19 +0800 Subject: [PATCH] add RTC wakeup alarm handling a bit convoluted: - RTC wakeup goes through the "always on" subsystem - keyboard routes through "always on" because the system can wake on keyboard press - thus the keyboard mechanism is abused/re-used to pass wakeup events throughout the system. Other notes - a wakeup alarm sent within 2 seconds of the current time will trigger an assert. It's not recommended to use the RTC for very near-term wakeups because if you e.g. hit swap or have something else going on that's very "busy" (like QR code scanning) the system might not get to waking things up in time. Some code can be written to handle this and set up a degenerate wakeup, maybe, but for now, I am leaving it as an assert because I want to remind myself that there is an edge case here. --- services/bao1x-hal-service/Cargo.toml | 1 + services/bao1x-hal-service/src/api.rs | 6 ++ services/bao1x-hal-service/src/lib.rs | 67 ++++++++++++++++++- .../bao1x-hal-service/src/servers/keyboard.rs | 46 ++++++++++++- services/bao1x-hal-service/src/servers/rtc.rs | 50 +++++++++++++- 5 files changed, 165 insertions(+), 5 deletions(-) diff --git a/services/bao1x-hal-service/Cargo.toml b/services/bao1x-hal-service/Cargo.toml index 4814d847c..0b6174bec 100644 --- a/services/bao1x-hal-service/Cargo.toml +++ b/services/bao1x-hal-service/Cargo.toml @@ -31,6 +31,7 @@ bitfield = "0.13.2" bitbybit = "1.4.0" arbitrary-int = "1.2" bytemuck = "1.24.0" +chrono = { version = "0.4.33", default-features = false, features = ["std"] } num-derive = { version = "0.4.2", default-features = false } num-traits = { version = "0.2.14", default-features = false } diff --git a/services/bao1x-hal-service/src/api.rs b/services/bao1x-hal-service/src/api.rs index 8ae1aa918..654075516 100644 --- a/services/bao1x-hal-service/src/api.rs +++ b/services/bao1x-hal-service/src/api.rs @@ -17,8 +17,14 @@ pub enum TimeOp { /// Query to see if timezone and time relative to UTC have been set. WallClockTimeInit = 6, + // Below are ops used by implementations, these can be modified/updated /// Serialize the internal state for storage across reboots GetState = 1024, + /// Sets a wakeup alarm. Returns # of RTC rollover events that must + /// elapse before the alarm is actually valid. + SetWakeup = 1025, + /// Clears any pending alarm + ClearWakeup = 1026, } #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)] diff --git a/services/bao1x-hal-service/src/lib.rs b/services/bao1x-hal-service/src/lib.rs index b2e295531..7d8a745ab 100644 --- a/services/bao1x-hal-service/src/lib.rs +++ b/services/bao1x-hal-service/src/lib.rs @@ -3,11 +3,12 @@ pub mod trng; use bao1x_api::*; use bao1x_hal::udma::{AdcExtChannel, AdcSource}; +use chrono::{DateTime, Offset, TimeZone, Utc}; use num_traits::*; use xous::{Message, send_message}; use xous_api_susres::api::Opcode as SusresOp; -use crate::api::ClockOp; +use crate::api::{ClockOp, TIME_SERVER_PUBLIC, TimeOp}; pub struct UdmaGlobal { conn: xous::CID, @@ -129,6 +130,70 @@ impl UdmaGlobalConfig for UdmaGlobal { } } +pub struct Rtc { + conn: xous::CID, +} +impl Rtc { + pub fn new() -> Self { + let conn = xous::connect(xous::SID::from_bytes(TIME_SERVER_PUBLIC).unwrap()).unwrap(); + Rtc { conn } + } + + pub fn set_time(&self, datetime: DateTime) { + let utc_time = datetime.with_timezone(&Utc); + log::info!("Time (UTC): {}", utc_time); + let since_epoch_ms = utc_time.timestamp_millis(); + xous::send_message( + self.conn, + xous::Message::new_scalar( + TimeOp::SetUtcTimeMs.to_usize().unwrap(), + ((since_epoch_ms >> 32) & 0xFFFF_FFFF) as usize, + (since_epoch_ms & 0xFFFF_FFFF) as usize, + 0, + 0, + ), + ) + .ok(); + let offset_ms = (datetime.offset().fix().local_minus_utc() as i64) * 1000; + xous::send_message( + self.conn, + xous::Message::new_scalar( + TimeOp::SetTzOffsetMs.to_usize().unwrap(), + (((offset_ms as u64) >> 32) & 0xFFFF_FFFF) as usize, + (offset_ms & 0xFFFF_FFFF) as usize, + 0, + 0, + ), + ) + .ok(); + } + + pub fn set_wakeup(&self, alarm: DateTime) -> Result { + let utc_alarm = alarm.with_timezone(&Utc); + let ts_utc_ms = utc_alarm.timestamp_millis(); + match xous::send_message( + self.conn, + xous::Message::new_blocking_scalar( + TimeOp::SetWakeup.to_usize().unwrap(), + ((ts_utc_ms >> 32) & 0xFFFF_FFFF) as usize, + (ts_utc_ms & 0xFFFF_FFFF) as usize, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar5(_op, epochs, _, _, _)) => Ok(epochs), + _ => Err(xous::Error::InternalError), + } + } + + pub fn clear_wakeup(&self) { + xous::send_message( + self.conn, + xous::Message::new_blocking_scalar(TimeOp::ClearWakeup.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); + } +} pub struct Adc { conn: xous::CID, } diff --git a/services/bao1x-hal-service/src/servers/keyboard.rs b/services/bao1x-hal-service/src/servers/keyboard.rs index 03b963c23..652d1a0a9 100644 --- a/services/bao1x-hal-service/src/servers/keyboard.rs +++ b/services/bao1x-hal-service/src/servers/keyboard.rs @@ -7,6 +7,7 @@ use bao1x_api::keyboard::*; use bao1x_hal::board::KeyPress; #[cfg(feature = "board-baosec")] use bao1x_hal::kpc_aoint::{AoIntStatus, KpcAoInt}; +use bao1x_hal_service::Rtc; use num_traits::*; #[cfg(feature = "board-baosec")] use utralib::utra::irqarray2; @@ -263,10 +264,10 @@ fn keyboard_service() { let kbd_sid = xns.register_name(bao1x_api::SERVER_NAME_KBD, None).expect("can't register server"); + #[cfg(feature = "board-baosec")] + let kbd_conn = xous::connect(kbd_sid).unwrap(); #[cfg(feature = "board-baosec")] { - let kbd_conn = xous::connect(kbd_sid).unwrap(); - let kpc_int = u4::new(bao1x_hal::kpc_aoint::IrqMapping::AoInt as u8); kpc_aoint.add_irq_notifier(IrqNotification { bit: kpc_int, @@ -274,12 +275,35 @@ fn keyboard_service() { opcode: KeyboardOpcode::HandlerTrigger.to_usize().unwrap(), args: [0, 0, 0, 0], }); + // clear any leftovers from prior configs - this bank is a little tricky because it has wakeup events + // on it + kpc_aoint.irq.wo(utra::irqarray2::EV_ENABLE, 0); + kpc_aoint.irq.wo(utra::irqarray2::EV_PENDING, 0xFFFF_FFFF); // feels like a bit of an abstraction violation, but I don't know how much the other interrupts // require edge-triggered handling kpc_aoint.irq.wo(utra::irqarray2::EV_EDGE_TRIGGERED, 1 << kpc_int.as_u32()); kpc_aoint.irq.wo(utra::irqarray2::EV_POLARITY, 1 << kpc_int.as_u32()); kpc_aoint.modify_irq_ena(kpc_int, true); } + /* + #[cfg(feature = "board-baosec")] + { + let kpc_int = u4::new(bao1x_hal::kpc_aoint::IrqMapping::AoWakeup as u8); + kpc_aoint.add_irq_notifier(IrqNotification { + bit: kpc_int, + conn: kbd_conn, + opcode: KeyboardOpcode::WakeupHandler.to_usize().unwrap(), + args: [0, 0, 0, 0], + }); + // feels like a bit of an abstraction violation, but I don't know how much the other interrupts + // require edge-triggered handling + let d = kpc_aoint.irq.r(utra::irqarray2::EV_EDGE_TRIGGERED); + kpc_aoint.irq.wo(utra::irqarray2::EV_EDGE_TRIGGERED, 1 << kpc_int.as_u32() | d); + let d = kpc_aoint.irq.r(utra::irqarray2::EV_POLARITY); + kpc_aoint.irq.wo(utra::irqarray2::EV_POLARITY, 1 << kpc_int.as_u32() | d); + kpc_aoint.modify_irq_ena(kpc_int, true); + } + */ #[cfg(feature = "board-baosec")] let tt = ticktimer::Ticktimer::new().unwrap(); @@ -324,6 +348,7 @@ fn keyboard_service() { } }); + let rtc = Rtc::new(); #[cfg(feature = "board-baosec")] let mut key_tracker = KeyTracker::new(); #[cfg(feature = "board-baosec")] @@ -493,7 +518,23 @@ fn keyboard_service() { }), #[cfg(feature = "board-baosec")] Some(KeyboardOpcode::HandlerTrigger) => msg_scalar_unpack!(msg, pending, _, _, _, { + log::debug!("kbd pending: {:x}", pending); if pending & (1 << bao1x_hal::kpc_aoint::IrqMapping::AoInt as usize) != 0 { + let fr = AoIntStatus::new_with_raw_value(kpc_aoint.ao.r(utra::ao_sysctrl::SFR_AOFR)); + log::debug!("fr: {:x}", fr.raw_value()); + // RTC interrupts also fire this interrupt. Handle and clear the RTC interrupt. + if fr.rtc_interrupt() { + rtc.clear_wakeup(); + kpc_aoint.ao.wo(utra::ao_sysctrl::SFR_AOFR, fr.raw_value()); + for &(listener_conn, listener_op) in listeners.iter() { + xous::try_send_message( + listener_conn, + xous::Message::new_scalar(listener_op, '⏰' as u32 as usize, 0, 0, 0), + ) + .ok(); + } + continue; + } let mut kc: Vec = Vec::new(); let now = tt.elapsed_ms(); if now - last_key_event > KEYUP_DELAY_MS { @@ -523,7 +564,6 @@ fn keyboard_service() { } // clear the FR bits - let fr = AoIntStatus::new_with_raw_value(kpc_aoint.ao.r(utra::ao_sysctrl::SFR_AOFR)); kpc_aoint.ao.wo(utra::ao_sysctrl::SFR_AOFR, fr.raw_value()); // add any repeat keys to the key response array diff --git a/services/bao1x-hal-service/src/servers/rtc.rs b/services/bao1x-hal-service/src/servers/rtc.rs index f430cdcd4..fd6797812 100644 --- a/services/bao1x-hal-service/src/servers/rtc.rs +++ b/services/bao1x-hal-service/src/servers/rtc.rs @@ -21,6 +21,14 @@ fn rtc_code_to_ms(rtc_code: u32, rollovers: u32) -> i64 { ((rtc_code as i64 + ((rollovers as i64) << 32)) * 1000) / 1024 } +fn ms_to_rtc_code(ms: i64) -> (u32, u32) { + assert!(ms > 0, "can't set alarm to negative times"); + let codes = (ms * 1024) / 1000; + let rtc_code = (codes & 0xFFFF_FFFF) as u32; + let rollovers = (codes >> 32) as u32; + (rtc_code, rollovers) +} + fn rtc_service() -> ! { // the public SID is well known and accessible by anyone who uses `libstd` let pub_sid = @@ -33,7 +41,7 @@ fn rtc_service() -> ! { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("couldn't map RTC range"); - let rtc = CSR::new(rtc_range.as_mut_ptr() as *mut u32); + let mut rtc = CSR::new(rtc_range.as_mut_ptr() as *mut u32); let mut rtc_rollovers: u32 = 0; // gives us up to 168 years let mut last_rtc_val = rtc.r(DR); // use this to detect rollovers @@ -149,6 +157,46 @@ fn rtc_service() -> ! { scalar.arg4 = ((tz_offset_ms >> 32) & 0xFFFF_FFFF) as usize; } } + Some(TimeOp::SetWakeup) => { + if let Some(scalar) = msg.body.scalar_message_mut() { + // just in case of race condition... + rtc.wo(IMSC, 0); // disable the interrupt + rtc.wo(ICR, 1); // clear the interrupt + + let utc_hi_ms = scalar.arg1; + let utc_lo_ms = scalar.arg2; + let utc_time_ms = (utc_hi_ms as i64) << 32 | (utc_lo_ms as i64); + + let (rtc_code, rollovers) = ms_to_rtc_code(utc_time_ms); + + // don't allow alarms that are too close to the current time, the system is not + // precise enough to handle. currently set to 2 seconds (2048 ticks). Also, + // this doesn't handle the rollover case correctly! + assert!( + rtc_code - rtc_val_atomic > 2048, + "Edge case: need handling for alarm time too close to RTC time" + ); + log::debug!( + "wakeup setting: code {}, rovers {}; current code {}", + rtc_code, + rollovers, + rtc_val_atomic + ); + + rtc.wo(MR, rtc_code); // set the target + rtc.wo(IMSC, 1); // enable the interrupt + // return rollovers to wakeup + scalar.arg1 = rollovers as usize; + } + } + Some(TimeOp::ClearWakeup) => { + if let Some(_scalar) = msg.body.scalar_message_mut() { + log::debug!("bef clr: ris({:x}) mis({:x})", rtc.r(RIS), rtc.r(MIS)); + rtc.wo(IMSC, 0); // disable the interrupt + rtc.wo(ICR, 1); // clear the interrupt + log::debug!("clear RTC int: ris({:x}) mis({:x})", rtc.r(RIS), rtc.r(MIS)); + } + } None => log::error!("Time server public thread received unknown opcode: {:?}", msg), } }