diff --git a/Cargo.lock b/Cargo.lock index 0001f9523..7f2b25860 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -343,6 +343,12 @@ dependencies = [ "xous-names", ] +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + [[package]] name = "crc" version = "1.8.1" @@ -1322,12 +1328,27 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" +[[package]] +name = "susres" +version = "0.1.0" +dependencies = [ + "log", + "log-server", + "num-derive", + "num-traits", + "rkyv 0.4.3", + "utralib", + "xous", + "xous-names", +] + [[package]] name = "svd2utra" version = "0.1.0" dependencies = [ "anyhow", "clap", + "convert_case", "quick-xml", ] @@ -1414,6 +1435,7 @@ dependencies = [ "log-server", "num-derive", "num-traits", + "susres", "utralib", "xous", ] @@ -1754,7 +1776,6 @@ dependencies = [ "num-derive", "num-traits", "rkyv 0.4.3", - "ticktimer-server", "utralib", "xous", "xous-ipc", diff --git a/Cargo.toml b/Cargo.toml index 52f78c759..dda0ca6d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ default-members = [ "services/cb-test-srv", "services/cb-test-c1", "services/cb-test-c2", + "services/susres", ] members = [ "xous-ipc", @@ -57,6 +58,7 @@ members = [ "services/cb-test-srv", "services/cb-test-c1", "services/cb-test-c2", + "services/susres", ] resolver = "2" diff --git a/buildpush.sh b/buildpush.sh index 35645fc67..e8324ac86 100755 --- a/buildpush.sh +++ b/buildpush.sh @@ -135,7 +135,10 @@ then fi else - md5sum $FPGA_IMAGE + if [ -e "$FPGA_IMAGE" ] + then + md5sum $FPGA_IMAGE + fi md5sum $KERNEL_IMAGE md5sum $LOADER_IMAGE diff --git a/emulation/soc/betrusted-soc.repl b/emulation/soc/betrusted-soc.repl index 7e9e51534..5577cef23 100644 --- a/emulation/soc/betrusted-soc.repl +++ b/emulation/soc/betrusted-soc.repl @@ -19,7 +19,7 @@ app_uart: UART.LiteX_UART @ { -> cpu@1004 timer0: Timers.LiteX_Timer_32 @ { - sysbus 0xF0021000 + sysbus 0xF0022000 } frequency: 100000000 -> cpu@1001 @@ -41,12 +41,12 @@ fbmem: Memory.MappedMemory @ sysbus 0xB0000000 memlcd: Video.BetrustedLCD @ sysbus 0xF000B000 -keyboard: Input.BetrustedKbd @ sysbus 0xF0014000 +keyboard: Input.BetrustedKbd @ sysbus 0xF0015000 -> cpu @ 1010 -trng_kernel: Miscellaneous.BetrustedRNGKernel @ sysbus 0xF0019000 +trng_kernel: Miscellaneous.BetrustedRNGKernel @ sysbus 0xF001A000 -trng_server: Miscellaneous.BetrustedRNGServer @ sysbus 0xF001A000 +trng_server: Miscellaneous.BetrustedRNGServer @ sysbus 0xF001B000 ticktimer: Timers.TickTimer @ sysbus 0xF0011000 periodInMs: 1 diff --git a/emulation/soc/renode.svd b/emulation/soc/renode.svd index 27260bd11..ebf534784 100644 --- a/emulation/soc/renode.svd +++ b/emulation/soc/renode.svd @@ -3,7 +3,7 @@ litex SOC - + 8 32 @@ -1070,10 +1070,10 @@ register to disable individual events.]]> GIT_GITREV 0x0014 - 0x7edc9bd9 + 0x4878d3c3 32 @@ -1090,7 +1090,7 @@ the exact git version used to build this firmware.]]> is ``1``, then the repository this was built from has one additional commit beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> 0x0018 - 0x1b + 0x1f 32 @@ -1104,7 +1104,7 @@ beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> GIT_DIRTY 0x001c - 0x00 + 0x01 32 @@ -2015,14 +2015,8 @@ register advances the read pointer automatically.]]> 0 [0:0] 0 - - - - pause - 1 - [1:1] - 1 - + @@ -2150,8 +2144,218 @@ register to disable individual events.]]> - POWER + SUSRES 0xF0012000 + SUSRES + + + CONTROL + 0x0000 + 0x00 + 32 + + + reset + 0 + [0:0] + 0 + + + + pause + 1 + [1:1] + 1 + + + + load + 2 + [2:2] + 2 + + + + + + RESUME_TIME1 + + 0x0004 + 0x00 + 32 + + + resume_time + 31 + [31:0] + 0 + + + + + RESUME_TIME0 + + 0x0008 + 0x00 + 32 + + + resume_time + 31 + [31:0] + 0 + + + + + TIME1 + + 0x000c + 0x00 + 32 + + + time + 31 + [31:0] + 0 + + + + + TIME0 + + 0x0010 + 0x00 + 32 + + + time + 31 + [31:0] + 0 + + + + + STATUS + 0x0014 + 0x00 + 32 + + + paused + 0 + [0:0] + 0 + + + + + + STATE + 0x0018 + 0x00 + 32 + + + resume + 0 + [0:0] + 0 + + + + + + INTERRUPT + 0x001c + 0x00 + 32 + + + interrupt + 0 + [0:0] + 0 + + + + + + EV_STATUS + + 0x0020 + 0x00 + 32 + + + soft_int + 0 + [0:0] + 0 + + + + + + EV_PENDING + + 0x0024 + 0x00 + 32 + + + soft_int + 0 + [0:0] + 0 + + + + + + EV_ENABLE + + 0x0028 + 0x00 + 32 + + + soft_int + 0 + [0:0] + 0 + + + + + + + 0 + 0x2c + registers + + + susres + 9 + + + + POWER + 0xF0013000 POWER @@ -2295,12 +2499,12 @@ reset fashion]]> power - 9 + 10 SPINOR - 0xF0013000 + 0xF0014000 SPINOR @@ -2581,7 +2785,7 @@ checked]]> KEYBOARD - 0xF0014000 + 0xF0015000 KEYBOARD @@ -2834,12 +3038,12 @@ again until the interrupt is serviced.]]> keyboard - 10 + 11 KEYINJECT - 0xF0015000 + 0xF0016000 KEYINJECT @@ -2875,14 +3079,14 @@ inject too fast.]]> SEED - 0xF0016000 + 0xF0017000 SEED SEED1 0x0000 - 0x470716fd + 0x77083f9a 32 @@ -2897,7 +3101,7 @@ inject too fast.]]> SEED0 0x0004 - 0x2218afde + 0x9411178 32 @@ -2917,7 +3121,7 @@ inject too fast.]]> KEYROM - 0xF0017000 + 0xF0018000 KEYROM @@ -2959,7 +3163,7 @@ inject too fast.]]> AUDIO - 0xF0018000 + 0xF0019000 AUDIO @@ -3326,12 +3530,12 @@ I2S_FORMAT.I2S_STANDARD is I2S standard]]> audio - 11 + 12 TRNG_KERNEL - 0xF0019000 + 0xF001A000 TRNG_KERNEL @@ -3462,12 +3666,12 @@ I2S_FORMAT.I2S_STANDARD is I2S standard]]> trng_kernel - 12 + 13 TRNG_SERVER - 0xF001A000 + 0xF001B000 TRNG_SERVER @@ -3794,12 +3998,12 @@ to max field size]]> trng_server - 13 + 14 TRNG - 0xF001B000 + 0xF001C000 TRNG @@ -4112,7 +4316,7 @@ VCCBRAM (V) = ``Value`` x 3 / 4096.]]> SHA512 - 0xF001C000 + 0xF001D000 SHA512 @@ -4602,12 +4806,12 @@ in bits]]> sha512 - 14 + 15 ENGINE - 0xF001D000 + 0xF001E000 ENGINE @@ -4831,12 +5035,12 @@ exactly reflects the binary layout of an Engine instruction.]]> engine - 15 + 16 JTAG - 0xF001E000 + 0xF001F000 JTAG @@ -4894,7 +5098,7 @@ exactly reflects the binary layout of an Engine instruction.]]> WDT - 0xF001F000 + 0xF0020000 WDT @@ -5049,12 +5253,54 @@ register to disable individual events.]]> wdt - 16 + 17 + + D11CTIME + 0xF0021000 + D11CTIME + + + CONTROL + 0x0000 + 0x666 + 32 + + + count + 14 + [14:0] + 0 + + + + + + HEARTBEAT + 0x0004 + 0x00 + 32 + + + beat + 0 + [0:0] + 0 + + + + + + + 0 + 0x8 + registers + + IDENTIFIER_MEM - 0xF0020000 + 0xF0022000 IDENTIFIER_MEM @@ -5081,7 +5327,7 @@ register to disable individual events.]]> TIMER0 - 0xF0021000 + 0xF0023000 TIMER0 @@ -5293,22 +5539,23 @@ register to disable individual events.]]> - + - + - - - + + + + - - + + - + \ No newline at end of file diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock index 4a7dc2e14..9748665a6 100644 --- a/kernel/Cargo.lock +++ b/kernel/Cargo.lock @@ -142,6 +142,12 @@ dependencies = [ "vec_map", ] +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + [[package]] name = "crossbeam-channel" version = "0.5.0" @@ -450,6 +456,7 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", + "convert_case", "quick-xml", ] diff --git a/kernel/src/arch/riscv/irq.rs b/kernel/src/arch/riscv/irq.rs index 28961081d..0dd7970da 100644 --- a/kernel/src/arch/riscv/irq.rs +++ b/kernel/src/arch/riscv/irq.rs @@ -7,7 +7,7 @@ use crate::arch::process::Process as ArchProcess; use crate::arch::process::{Thread, RETURN_FROM_ISR}; use crate::mem::{MemoryManager, PAGE_SIZE}; use crate::services::SystemServices; -use riscv::register::{scause, sepc, sie, sstatus, stval, vexriscv::sim, vexriscv::sip}; +use riscv::register::{scause, sepc, sstatus, stval, vexriscv::sim, vexriscv::sip}; use xous_kernel::{SysCall, PID, TID}; extern "Rust" { @@ -18,14 +18,17 @@ extern "C" { fn flush_mmu(); } +// use RAM-based backing so this variable is automatically saved on suspend +static mut SIM_BACKING: usize = 0; /// Disable external interrupts pub fn disable_all_irqs() { - unsafe { sie::clear_sext() }; + unsafe{SIM_BACKING = sim::read()}; + sim::write(0x0); } /// Enable external interrupts pub fn enable_all_irqs() { - unsafe { sie::set_sext() }; + sim::write(unsafe{SIM_BACKING}); } pub fn enable_irq(irq_no: usize) { diff --git a/loader/Cargo.lock b/loader/Cargo.lock index 99f05a234..223d5ba7a 100644 --- a/loader/Cargo.lock +++ b/loader/Cargo.lock @@ -53,6 +53,12 @@ dependencies = [ "vec_map", ] +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + [[package]] name = "getrandom" version = "0.1.14" @@ -168,6 +174,7 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", + "convert_case", "quick-xml", ] diff --git a/loader/assemble.sh b/loader/assemble.sh old mode 100644 new mode 100755 diff --git a/loader/bin/riscv32i-unknown-none-elf.a b/loader/bin/riscv32i-unknown-none-elf.a index 7d0f70972..2a092a4b0 100644 Binary files a/loader/bin/riscv32i-unknown-none-elf.a and b/loader/bin/riscv32i-unknown-none-elf.a differ diff --git a/loader/bin/riscv32imac-unknown-none-elf.a b/loader/bin/riscv32imac-unknown-none-elf.a index b7f535bc4..a307283d9 100644 Binary files a/loader/bin/riscv32imac-unknown-none-elf.a and b/loader/bin/riscv32imac-unknown-none-elf.a differ diff --git a/loader/bin/riscv32imc-unknown-none-elf.a b/loader/bin/riscv32imc-unknown-none-elf.a index b7f535bc4..a307283d9 100644 Binary files a/loader/bin/riscv32imc-unknown-none-elf.a and b/loader/bin/riscv32imc-unknown-none-elf.a differ diff --git a/loader/bin/riscv64gc-unknown-none-elf.a b/loader/bin/riscv64gc-unknown-none-elf.a index 6f52e5e08..72c00d117 100644 Binary files a/loader/bin/riscv64gc-unknown-none-elf.a and b/loader/bin/riscv64gc-unknown-none-elf.a differ diff --git a/loader/bin/riscv64imac-unknown-none-elf.a b/loader/bin/riscv64imac-unknown-none-elf.a index 889352195..72c00d117 100644 Binary files a/loader/bin/riscv64imac-unknown-none-elf.a and b/loader/bin/riscv64imac-unknown-none-elf.a differ diff --git a/loader/src/main.rs b/loader/src/main.rs index 26ee628cf..84b407262 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -1116,6 +1116,8 @@ fn phase_1(cfg: &mut BootConfig) { // prior to jumping to our program, so allocate one page of data for // stack. // All other allocations will be placed below the stack pointer. + // + // As of Xous 0.8, the top page is bootloader stack, and the page below that is the 'clean suspend' page. cfg.init_size += PAGE_SIZE * 2; // The first region is defined as being "main RAM", which will be used @@ -1152,8 +1154,11 @@ fn phase_1(cfg: &mut BootConfig) { // will require us to transfer ownership in `stage3`. // Note also that we skip the first index, causing the stack to be // returned to the process pool. + // We also skip the second index as that is the clean suspend page. This + // needs to be claimed by the susres server before the kernel allocates it. + // Lower numbered indices corresponding to higher address pages. println!("Marking pages as in-use"); - for i in 1..(cfg.init_size / PAGE_SIZE) { + for i in 3..(cfg.init_size / PAGE_SIZE) { cfg.runtime_page_tracker[cfg.sram_size / PAGE_SIZE - i] = 1; } } @@ -1229,5 +1234,7 @@ pub fn phase_2(cfg: &mut BootConfig) { "Runtime Page Tracker: {} bytes", cfg.runtime_page_tracker.len() ); - cfg.runtime_page_tracker[cfg.sram_size / PAGE_SIZE - 1] = 0; + // mark pages used by suspend/resume as unused for later allocation by the susres server + cfg.runtime_page_tracker[cfg.sram_size / PAGE_SIZE - 1] = 0; // loader stack + cfg.runtime_page_tracker[cfg.sram_size / PAGE_SIZE - 2] = 0; // clean suspend page } diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs index 753862708..6f136640d 100644 --- a/services/gam/src/status.rs +++ b/services/gam/src/status.rs @@ -116,7 +116,6 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi let mut rtc = rtc::Rtc::new(&xns).unwrap(); - #[cfg(target_os = "none")] rtc.clear_wakeup_alarm().unwrap(); // clear any wakeup alarm state, if it was set rtc.hook_rtc_callback(dt_callback).unwrap(); diff --git a/services/llio/src/lib.rs b/services/llio/src/lib.rs index fcea3d5b1..b85280b2b 100644 --- a/services/llio/src/lib.rs +++ b/services/llio/src/lib.rs @@ -23,7 +23,7 @@ pub struct Llio { } impl Llio { pub fn new(xns: &xous_names::XousNames) -> Result { - let conn = xns.request_connection_blocking(api::SERVER_NAME_LLIO).expect("Can't connect to MyServer"); + let conn = xns.request_connection_blocking(api::SERVER_NAME_LLIO).expect("Can't connect to LLIO"); Ok(Llio { conn, com_sid: None, diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs index 4c842fe29..16bf770dd 100644 --- a/services/rtc/src/main.rs +++ b/services/rtc/src/main.rs @@ -402,6 +402,9 @@ mod implementation { pub fn clear_wakeup_alarm(&mut self) { self.wakeup_alarm_enabled = false; + // make sure battery switchover is enabled, otherwise we won't keep time when power goes off + self.blocking_i2c_write2([ABRTCMC_CONTROL3, (Control3::BATT_STD_BL_EN).bits()]); + let mut config = Config::CLKOUT_DISABLE.bits(); if self.rtc_alarm_enabled { config |= (Config::TIMER_A_COUNTDWN | Config::TIMERA_SECONDS_INT_PULSED).bits(); @@ -658,12 +661,15 @@ fn xmain() -> ! { }), Some(Opcode::ClearWakeupAlarm) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { rtc.clear_wakeup_alarm(); // blocks until transaction is finished + xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); }), Some(Opcode::SetRtcAlarm) => msg_blocking_scalar_unpack!(msg, delay, _, _, _, { rtc.rtc_alarm(delay as u8); // this will block until finished, no callbacks used + xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); }), Some(Opcode::ClearRtcAlarm) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { rtc.clear_rtc_alarm(); // blocks until transaction is finished + xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); }), None => { log::error!("unknown opcode received, exiting"); diff --git a/services/susres/Cargo.toml b/services/susres/Cargo.toml new file mode 100644 index 000000000..0d92c8cb5 --- /dev/null +++ b/services/susres/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "susres" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "Manager of suspend/resume operations" + +[dependencies] +xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +xous-names = { path = "../xous-names" } +log = "0.4" + +num-derive = {version = "0.3", default-features = false} +num-traits = {version = "0.2", default-features = false} +rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} + + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +default = [] diff --git a/services/susres/src/api.rs b/services/susres/src/api.rs new file mode 100644 index 000000000..26acc7836 --- /dev/null +++ b/services/susres/src/api.rs @@ -0,0 +1,252 @@ +#[cfg(target_os = "none")] +use utralib::generated::*; + +pub(crate) const SERVER_NAME_SUSRES: &str = "_Suspend/resume manager_"; + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + /// requests a suspend + SuspendRequest, + + /// register a subscriber to the suspend event + /// (if you don't register, you just get suspend without any warning!) + SuspendEventSubscribe, + + /// indicate we're ready to suspend + SuspendReady, +} + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum ExecGateOpcode { + SuspendNow, +} + +#[cfg(target_os = "none")] +#[derive(Debug, Copy, Clone)] +pub enum RegOrField { + Field(Field), + Reg(Register), +} +#[cfg(target_os = "none")] +#[derive(Debug, Copy, Clone)] +pub struct ManagedReg { + /// register, or a field of a register + pub item: RegOrField, + /// override the default mask value if Some() - mask is aligned to the register or field (do not shift the mask to the left to correspond to the actual bit position) + pub mask: Option, + /// the saved value of the field or register + pub value: Option, +} + +//#[derive(Debug)] +#[cfg(target_os = "none")] +pub struct RegManager { + pub csr: CSR, + pub registers: [Option; N], + pub sus_prologue: Option, + pub sus_epilogue: Option, + pub res_prologue: Option, + pub res_epilogue: Option, +} +#[cfg(target_os = "none")] +impl RegManager:: where ManagedReg: core::marker::Copy { + pub fn new(reg_base: *mut u32) -> RegManager:: { + RegManager:: { + csr: CSR::new(reg_base), + registers: [None; N], + sus_prologue: None, + sus_epilogue: None, + res_prologue: None, + res_epilogue: None, + } + } + // push registers into the manager in the order you want them suspended + pub fn push(&mut self, mr: RegOrField, mask_override: Option) { + let mrt = ManagedReg { + item: mr, + mask: mask_override, + value: None, + }; + for entry in self.registers.iter_mut() { + if entry.is_none() { + *entry = Some(mrt); + return; + } + } + // A panic! is most appropriate here, because there is really no graceful + // remedy to this. It is a straight-up programmer error that needs to be fixed. + panic!("Ran out of space pushing to suspend/resume manager structure. Please increase the allocated size!"); + } +} +#[cfg(target_os = "none")] +pub trait SuspendResume { + fn suspend(&mut self); + fn resume(&mut self); +} +#[cfg(target_os = "none")] +impl SuspendResume for RegManager { + fn suspend(&mut self) { + if let Some(sp) = self.sus_prologue { + sp(self); + } + for entry in self.registers.iter_mut().rev() { + if let Some(reg) = entry { + // masking is done on the write side + match reg.item { + RegOrField::Field(field) => reg.value = Some(self.csr.rf(field) as usize), + RegOrField::Reg(r) => reg.value = Some(self.csr.r(r) as usize), + } + } + } + if let Some(se) = self.sus_epilogue { + se(self); + } + } + fn resume(&mut self) { + if let Some(rp) = self.res_prologue { + rp(self); + } + for entry in self.registers.iter() { // this is in reverse order to the suspend + if let Some(reg) = entry { + if let Some(mut value) = reg.value { + if let Some(mask) = reg.mask { + value &= mask; + } + match reg.item { + RegOrField::Field(field) => self.csr.rmwf(field, value as u32), + RegOrField::Reg(r) => self.csr.wo(r, value as u32), + } + } + } + } + if let Some(re) = self.res_epilogue { + re(self); + } + } +} + +// because the volatile memory regions can be potentially large (128kiB), but fewer (maybe 5-6 total in the system), +// we allocate these as stand-alone structures and manage them explicitly. +#[cfg(target_os = "none")] +pub struct ManagedMem { + pub mem: xous::MemoryRange, + pub backing: [u32; N], +} +#[cfg(target_os = "none")] +impl SuspendResume for ManagedMem { + fn suspend(&mut self) { + let src = self.mem.as_ptr() as *const u32; + for words in 0..self.mem.len() { + self.backing[words] = unsafe{src.add(words).read_volatile()}; + } + } + fn resume(&mut self) { + let dst = self.mem.as_ptr() as *mut u32; + for words in 0..self.mem.len() { + unsafe{dst.add(words).write_volatile(self.backing[words])}; + } + } +} + + + + +/* +// "suspend/resume u32" +struct SrU32 { + /// offset of the register + offset: crate::Register, + /// the saved value of the register + value: u32, + /// the order in which this register should be written. If none, it's written at any convenient time. + resume_order: Option, + /// if this register should be in the suspend/resume set + do_sr: bool, +} + +/* sketching some structs for suspend/resume */ +struct TicktimerSusres { + csr: utralib::CSR, // new(csr_base) will allocate this register, from the virtual CSR base given to us by the owning server + pub control: Option, + pub time1: Option, + pub time0: Option, + pub resume_time1: Option, + pub resume_time0: Option, + pub status: Option, + pub msleep_target1: Option, + pub msleep_target0: Option, + pub ev_status: Option, + pub ev_pending: Option, + pub ev_enable: Option, + pub ticktimer_irq: Option, // whether to enable or not after resume + pub wait_suspend: Option bool>, // function to call to check if a block can suspend +} +pub trait SuspendResume { + pub fn suspend(&mut self) { + /* + go through each item of the structure, and if the item is Some(item), access the corresponding + register and save it into the register + */ + } + pub fn resume(&mut self) { + /* + go through each item of the stucture, and if the item is Some(item), unwrap the value and + poke it into the register + */ + } +} + +enum TickttimerReg { + Control = 0, + Time1 = 1, + Time0 = 2, + MSleepTarget1 = 3, + //... +} +//enum TickttimerInterrupt { +// Alarm = 0, +//} + +struct ManagedReg { + offset: TickttimerReg, + mask: usize, // mask of data to store + value: u32, +} +//struct ManagedInterrupt { +// irq: usize, +//} +struct ManagedMem { + offset: usize, // the starting offset of the volatile memory block + mem: [u32; MEMLEN], // backup copy of the memory +} +// this can operate on the above three structure +pub trait SusResOps { + fn save(); + fn restore(); +} + +/* +Interrupts need no suspend/resume setup: +- the hooks and callback locations are all stored in non-volatile SRAM +- the SIM register, which contains the mask of interrupts that are enabled, will be restored + by the loader on boot + +Between these two facts, all of the interrupt mechanism are transparently handled by the kernel + */ + + +struct SusResManager { + csr: utralib::CSR, + pub registers: [Option; 12], // max number is set by the utra2svd generator + //pub interrupts: [Option; 1], // if in this list, this interrupt should be enabled + + // i think maybe these go in the library, not in the auto-generated manager structure + pub suspend_cb: fn(), + pub resume_cb: fn(), +} +pub trait SusResBlockOps { + fn append(reg: ManagedReg); // adds a register to the managed suspend list + fn suspend(); // iterates through the list of registers and performs the suspend operation + fn resume(); // iterates through the list of registers and performs the resume operation +} +*/ \ No newline at end of file diff --git a/services/susres/src/lib.rs b/services/susres/src/lib.rs new file mode 100644 index 000000000..40f9107a5 --- /dev/null +++ b/services/susres/src/lib.rs @@ -0,0 +1,27 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +pub use api::*; + +use xous::{CID, send_message}; +use num_traits::ToPrimitive; + +pub struct Susres { + conn: CID, +} +impl Susres { + pub fn new(xns: &xous_names::XousNames) -> Result { + let conn = xns.request_connection_blocking(api::SERVER_NAME_SUSRES).expect("Can't connect to SUSRES"); + Ok(Susres { + conn + }) + } +} + +impl Drop for Susres { + fn drop(&mut self) { + // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. + unsafe{xous::disconnect(self.conn).unwrap();} + + } +} \ No newline at end of file diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs new file mode 100644 index 000000000..293a043f5 --- /dev/null +++ b/services/susres/src/main.rs @@ -0,0 +1,113 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; +use api::*; + +use num_traits::FromPrimitive; + +#[cfg(target_os = "none")] +mod implementation { + use utralib::generated::*; + use crate::api::*; + + fn handle_irq(_irq_no: usize, arg: *mut usize) { + let sr = unsafe{ &mut *(arg as *mut SusResHw) }; + // dummy routine for now + sr.csr.wfo(utra::susres::EV_PENDING_SOFT_INT, 1); + } + + pub struct SusResHw { + /// our CSR + csr: utralib::CSR, + /// memory region for the "clean suspend" marker + marker: xous::MemoryRange, + /// loader stack region -- this data is dirtied on every resume; claim it in this process so no others accidentally use it + loader_stack: xous::MemoryRange, + /// backing store for the ticktimer value + time_backing: Option<[u32; 2]>, + } + impl SusResHw { + pub fn new() -> Self { + let csr = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::susres::HW_SUSRES_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map SusRes CSR range"); + + let marker = xous::syscall::map_memory( + xous::MemoryAddress::new(0x40FFE000), // this is a special, hard-coded location + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map clean suspend page"); + let loader_stack = xous::syscall::map_memory( + xous::MemoryAddress::new(0x40FFF000), // this is a special, hard-coded location + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ).expect("couldn't map clean suspend page"); + let mut sr = SusResHw { + csr: CSR::new(csr.as_mut_ptr() as *mut u32), + time_backing: None, + marker, + loader_stack, + }; + + // check that the marker has been zerod by map_memory + // TODO + + xous::claim_interrupt( + utra::susres::SUSRES_IRQ, + handle_irq, + (&mut sr) as *mut SusResHw as *mut usize, + ).expect("couldn't claim IRQ"); + + sr + } + } + +} + +#[cfg(not(target_os = "none"))] +mod implementation { + pub struct SusResHw { + } + impl SusResHw { + pub fn new() -> Self { + SusResHw {} + } + } +} + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Trace); + log::info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + let susres_sid = xns.register_name(api::SERVER_NAME_SUSRES).expect("can't register server"); + log::trace!("registered with NS -- {:?}", susres_sid); + + let susres_hw = implementation::SusResHw::new(); + + loop { + let msg = xous::receive_message(susres_sid).unwrap(); + /* + match FromPrimitive::from_usize(msg.body.id()) { + None => { + log::error!("couldn't convert opcode"); + break + } + }*/ + } + // clean up our program + log::trace!("main loop exit, destroying servers"); + xns.unregister_server(susres_sid).unwrap(); + xous::destroy_server(susres_sid).unwrap(); + log::trace!("quitting"); + xous::terminate_process(); loop {} +} diff --git a/services/ticktimer-server/Cargo.toml b/services/ticktimer-server/Cargo.toml index c85bc9d1e..c0fa7fcd1 100644 --- a/services/ticktimer-server/Cargo.toml +++ b/services/ticktimer-server/Cargo.toml @@ -12,6 +12,7 @@ log-server = {path = "../log-server"} xous = {path = "../../xous-rs"} num-derive = {version = "0.3", default-features = false} num-traits = {version = "0.2", default-features = false} +susres = {path = "../susres"} [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index f60952fb3..fe7eb3bb3 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -52,56 +52,13 @@ impl core::cmp::PartialEq for SleepRequest { } } -/* -// "suspend/resume u32" -struct SrU32 { - /// offset of the register - offset: crate::Register, - /// the saved value of the register - value: u32, - /// the order in which this register should be written. If none, it's written at any convenient time. - resume_order: Option, - /// if this register should be in the suspend/resume set - do_sr: bool, -} - -/* sketching some structs for suspend/resume */ -struct TicktimerSusres { - csr: utralib::CSR, // new(csr_base) will allocate this register, from the virtual CSR base given to us by the owning server - pub control: Option, - pub time1: Option, - pub time0: Option, - pub resume_time1: Option, - pub resume_time0: Option, - pub status: Option, - pub msleep_target1: Option, - pub msleep_target0: Option, - pub ev_status: Option, - pub ev_pending: Option, - pub ev_enable: Option, - pub ticktimer_irq: Option, // whether to enable or not after resume - pub wait_suspend: Option bool>, // function to call to check if a block can suspend -} -pub trait SuspendResume { - pub fn suspend(&mut self) { - /* - go through each item of the structure, and if the item is Some(item), access the corresponding - register and save it into the register - */ - } - pub fn resume(&mut self) { - /* - go through each item of the stucture, and if the item is Some(item), unwrap the value and - poke it into the register - */ - } -} -*/ #[cfg(target_os = "none")] mod implementation { const TICKS_PER_MS: u64 = 1; use super::SleepRequest; use utralib::generated::*; + use utra::ticktimer::*; + use susres::*; pub struct XousTickTimer { csr: utralib::CSR, @@ -109,6 +66,7 @@ mod implementation { wdt: utralib::CSR, current_response: Option, connection: xous::CID, + susres: RegManager, } fn handle_wdt(_irq_no: usize, arg: *mut usize) { @@ -179,16 +137,22 @@ mod implementation { ) .expect("couldn't map Watchdog timer CSR range"); + let susres = RegManager::new(csr.as_mut_ptr() as *mut u32); + let mut xtt = XousTickTimer { csr: CSR::new(csr.as_mut_ptr() as *mut u32), #[cfg(feature = "watchdog")] wdt: CSR::new(wdt.as_mut_ptr() as *mut u32), current_response: None, connection, + susres, }; #[cfg(feature = "watchdog")] - xtt.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1); + { + xtt.wdt.wfo(utra::wdt::WATCHDOG_ENABLE, 1); + xtt.susres.push(RegOrField::Field(utra::wdt::WATCHDOG_ENABLE), None); + } xous::claim_interrupt( utra::ticktimer::TICKTIMER_IRQ, @@ -205,7 +169,10 @@ mod implementation { .expect("couldn't claim irq"); #[cfg(feature = "watchdog")] - xtt.wdt.wfo(utra::wdt::EV_ENABLE_SOFT_INT, 1); + { + xtt.wdt.wfo(utra::wdt::EV_ENABLE_SOFT_INT, 1); + xtt.susres.push(RegOrField::Reg(utra::wdt::EV_ENABLE), None); + } xtt } diff --git a/services/trng/src/main.rs b/services/trng/src/main.rs index 934538401..3f6a89808 100644 --- a/services/trng/src/main.rs +++ b/services/trng/src/main.rs @@ -354,6 +354,12 @@ fn xmain() -> ! { #[cfg(not(target_os = "none"))] let mut trng = Trng::new(); + #[cfg(feature = "avalanchetest")] + log::info!("TRNG built with avalanche test enabled"); + + #[cfg(feature = "ringosctest")] + log::info!("TRNG built with ring oscillator test enabled"); + #[cfg(any(feature = "avalanchetest", feature="ringosctest"))] xous::create_thread_1(tester_thread, trng.get_trng_csr() as usize).expect("couldn't create test thread"); diff --git a/services/xous-names/Cargo.toml b/services/xous-names/Cargo.toml index bf9850147..3fd193d41 100644 --- a/services/xous-names/Cargo.toml +++ b/services/xous-names/Cargo.toml @@ -13,7 +13,6 @@ num-derive = {version = "0.3", default-features = false} num-traits = {version = "0.2", default-features = false} log = "0.4" log-server = {path = "../log-server"} -ticktimer-server = {path = "../ticktimer-server"} xous = {path = "../../xous-rs"} xous-ipc = {path = "../../xous-ipc"} rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} diff --git a/services/xous-names/src/main.rs b/services/xous-names/src/main.rs index 1d3e2a4ca..9e04a072d 100644 --- a/services/xous-names/src/main.rs +++ b/services/xous-names/src/main.rs @@ -15,11 +15,52 @@ use xous_ipc::{String, Buffer}; use log::{error, info}; -const FAIL_TIMEOUT_MS: u64 = 100; +#[cfg(target_os = "none")] +mod implementation { + use utralib::generated::*; + pub struct D11cTimeout { + d11t_csr: utralib::CSR, + } + impl D11cTimeout { + pub fn new() -> Self { + let csr = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::d11ctime::HW_D11CTIME_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map D11cTimeout CSR range"); + + D11cTimeout { + d11t_csr: CSR::new(csr.as_mut_ptr() as *mut u32), + } + } + pub fn deterministic_busy_wait(&self) { + let phase = self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT); + while phase == self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT) { + xous::yield_slice(); + } + } + } +} + +#[cfg(not(target_os = "none"))] +mod implementation { + pub struct D11cTimeout {} + impl D11cTimeout { + pub fn new() -> Self { + D11cTimeout {} + } + pub fn deterministic_busy_wait(&self) { + // don't do anything for hosted mode + } + } +} #[xous::xous_main] fn xmain() -> ! { + use implementation::*; let debug1 = false; log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); @@ -28,7 +69,7 @@ fn xmain() -> ! { let name_server = xous::create_server_with_address(b"xous-name-server") .expect("Couldn't create xousnames-server"); - let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); + let d11ctimeout = D11cTimeout::new(); // this limits the number of available servers to be requested to 128...! let mut name_table = FnvIndexMap::<_, _, U128>::new(); @@ -57,19 +98,12 @@ fn xmain() -> ! { response = api::Return::SID(new_sid.into()); } else { - // compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels - let target_time: u64 = ((ticktimer.elapsed_ms() - / FAIL_TIMEOUT_MS) - + 1) - * FAIL_TIMEOUT_MS; info!("request failed, waiting for deterministic timeout"); - while ticktimer.elapsed_ms() < target_time { - xous::yield_slice(); - } + d11ctimeout.deterministic_busy_wait(); info!("deterministic timeout done"); response = api::Return::Failure } - buffer.replace(response).unwrap(); + buffer.replace(response).expect("Register can't serialize return value"); } Some(api::Opcode::Lookup) => { let mem = msg.body.memory_message_mut().unwrap(); @@ -118,7 +152,7 @@ fn xmain() -> ! { }; response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path } - buffer.replace(response).unwrap(); + buffer.replace(response).expect("Lookup can't serialize return value"); } Some(api::Opcode::AuthenticatedLookup) => { let mem = msg.body.memory_message_mut().unwrap(); diff --git a/svd2utra/Cargo.toml b/svd2utra/Cargo.toml index 262bf80ec..45f615b9b 100644 --- a/svd2utra/Cargo.toml +++ b/svd2utra/Cargo.toml @@ -10,3 +10,4 @@ edition = "2018" quick-xml = "0.19" clap = "2" anyhow = "1.0" +convert_case = "0.4" diff --git a/svd2utra/examples/soc.svd b/svd2utra/examples/soc.svd index 794d2937d..ebf534784 100644 --- a/svd2utra/examples/soc.svd +++ b/svd2utra/examples/soc.svd @@ -3,7 +3,7 @@ litex SOC - + 8 32 @@ -1104,7 +1104,7 @@ beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> GIT_DIRTY 0x001c - 0x00 + 0x01 32 @@ -3086,7 +3086,7 @@ inject too fast.]]> SEED1 0x0000 - 0x468ba085 + 0x77083f9a 32 @@ -3101,7 +3101,7 @@ inject too fast.]]> SEED0 0x0004 - 0x5f84de45 + 0x9411178 32 @@ -5257,8 +5257,50 @@ register to disable individual events.]]> - IDENTIFIER_MEM + D11CTIME 0xF0021000 + D11CTIME + + + CONTROL + 0x0000 + 0x666 + 32 + + + count + 14 + [14:0] + 0 + + + + + + HEARTBEAT + 0x0004 + 0x00 + 32 + + + beat + 0 + [0:0] + 0 + + + + + + + 0 + 0x8 + registers + + + + IDENTIFIER_MEM + 0xF0022000 IDENTIFIER_MEM @@ -5285,7 +5327,7 @@ register to disable individual events.]]> TIMER0 - 0xF0022000 + 0xF0023000 TIMER0 diff --git a/svd2utra/src/generate.rs b/svd2utra/src/generate.rs index 0ce7c79c3..4cd21b3c5 100644 --- a/svd2utra/src/generate.rs +++ b/svd2utra/src/generate.rs @@ -1,7 +1,7 @@ use quick_xml::events::Event; use quick_xml::Reader; use std::io::{BufRead, BufReader, Read, Write}; - +use convert_case::{Case, Casing}; #[derive(Debug)] pub enum ParseError { UnexpectedTag, @@ -477,16 +477,22 @@ fn parse_vendor_extensions( fn print_header(out: &mut U) -> std::io::Result<()> { let s = r####" +#![allow(dead_code)] use core::convert::TryInto; + +#[derive(Debug, Copy, Clone)] pub struct Register { /// Offset of this register within this CSR offset: usize, + /// Mask of SVD-specified bits for the register + mask: usize, } impl Register { - pub const fn new(offset: usize) -> Register { - Register { offset } + pub const fn new(offset: usize, mask: usize) -> Register { + Register { offset, mask } } } +#[derive(Debug, Copy, Clone)] pub struct Field { /// A bitmask we use to AND to the value, unshifted. /// E.g. for a width of `3` bits, this mask would be 0b111. @@ -549,6 +555,7 @@ impl Field { } } } +#[derive(Debug, Copy, Clone)] pub struct CSR { pub base: *mut T, } @@ -676,20 +683,37 @@ fn print_peripherals(peripherals: &[Peripheral], out: &mut U) -> std:: } writeln!(out)?; - writeln!(out, "pub mod utra {{")?; + let s = r####" +pub mod utra { +"####; + out.write_all(s.as_bytes())?; + for peripheral in peripherals { writeln!(out)?; writeln!(out, " pub mod {} {{", peripheral.name.to_lowercase())?; + writeln!(out, " // this enum is vestigal, and currently not used by anything")?; + writeln!(out, " #[derive(Debug, Copy, Clone)]")?; + writeln!(out, " pub enum {}Offset {{", peripheral.name.to_case(Case::UpperCamel))?; + for register in &peripheral.registers { + writeln!(out, " {} = {},", register.name.to_case(Case::UpperCamel), register.offset / 4)?; + } + writeln!(out, " }}")?; + writeln!(out, " pub const {}_NUMREGS: usize = {};", peripheral.name.to_uppercase(), peripheral.registers.len())?; for register in &peripheral.registers { writeln!(out)?; if let Some(description) = ®ister.description { writeln!(out, " /// {}", description)?; } + let mut mask: usize = 0; + for field in ®ister.fields { + mask |= ((1 << (field.msb + 1 - field.lsb)) - 1) << field.lsb; + } writeln!( out, - " pub const {}: crate::Register = crate::Register::new({});", + " pub const {}: crate::Register = crate::Register::new({}, 0x{:x});", register.name.to_uppercase(), - register.offset / 4 + register.offset / 4, + mask, )?; for field in ®ister.fields { writeln!( diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 380b8dfd0..f98e77f4e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -98,6 +98,7 @@ fn try_main() -> Result<(), DynError> { "llio", "rkyv-test-client", "rkyv-test-server", + "susres", ]; let task = env::args().nth(1); match task.as_deref() { @@ -142,6 +143,7 @@ cbtest builds an image for callback testing trng-test [soc.svd] builds an image for TRNG testing (both avalanche and ring oscillator on) ro-test [soc.svd] builds an image for ring oscillator only TRNG testing av-test [soc.svd] builds an image for avalanche generater only TRNG testing +sr-test [soc.svd] builds the suspend/resume testing image " ) }