From 2b973fa29c497ba50e7273a43ed34a5c7e94128d Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 23 Apr 2021 18:06:25 +0800 Subject: [PATCH 01/24] check in failing svd file --- emulation/renode.svd | 297 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 251 insertions(+), 46 deletions(-) diff --git a/emulation/renode.svd b/emulation/renode.svd index 27260bd11..794d2937d 100644 --- a/emulation/renode.svd +++ b/emulation/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 @@ -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 + 0x468ba085 32 @@ -2897,7 +3101,7 @@ inject too fast.]]> SEED0 0x0004 - 0x2218afde + 0x5f84de45 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,12 @@ register to disable individual events.]]> wdt - 16 + 17 IDENTIFIER_MEM - 0xF0020000 + 0xF0021000 IDENTIFIER_MEM @@ -5081,7 +5285,7 @@ register to disable individual events.]]> TIMER0 - 0xF0021000 + 0xF0022000 TIMER0 @@ -5293,22 +5497,23 @@ register to disable individual events.]]> - + - + - - - + + + + - - + + - + \ No newline at end of file From 4ecd7c06accf487cdb6be58c7dfd13f6e2294f62 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 23 Apr 2021 21:49:13 +0800 Subject: [PATCH 02/24] trying to fix renode stuff, but not quite there --- emulation/betrusted.repl | 8 ++++---- services/gam/src/status.rs | 1 - services/rtc/src/main.rs | 3 +++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/emulation/betrusted.repl b/emulation/betrusted.repl index db09043ff..7814e844e 100644 --- a/emulation/betrusted.repl +++ b/emulation/betrusted.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 // This peripheral doesn't actually exist, but is required // in order to keep the CPU running. 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/rtc/src/main.rs b/services/rtc/src/main.rs index 4c842fe29..779d653a4 100644 --- a/services/rtc/src/main.rs +++ b/services/rtc/src/main.rs @@ -658,12 +658,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"); From 77c44ccb763754efb5c341c0d1425e0840489af1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 25 Apr 2021 18:49:57 +0800 Subject: [PATCH 03/24] depracate use of SIE by storing SIM to RAM-based backing --- kernel/src/arch/riscv/irq.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/kernel/src/arch/riscv/irq.rs b/kernel/src/arch/riscv/irq.rs index 28961081d..7958908e2 100644 --- a/kernel/src/arch/riscv/irq.rs +++ b/kernel/src/arch/riscv/irq.rs @@ -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) { From 308cda1af435dffc2e39ec3f75bbb49892865ee9 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 25 Apr 2021 21:44:21 +0800 Subject: [PATCH 04/24] remove unused sie use --- kernel/src/arch/riscv/irq.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/src/arch/riscv/irq.rs b/kernel/src/arch/riscv/irq.rs index 7958908e2..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" { From f86f295fa51c916aee569de8ed4ac7049b848198 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 26 Apr 2021 01:11:45 +0800 Subject: [PATCH 05/24] add some version commands --- services/llio/src/lib.rs | 30 +++++++++++++++++++ services/shellchat/src/cmds.rs | 3 ++ services/shellchat/src/cmds/ver.rs | 46 ++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 services/shellchat/src/cmds/ver.rs diff --git a/services/llio/src/lib.rs b/services/llio/src/lib.rs index 1cfae641e..fcea3d5b1 100644 --- a/services/llio/src/lib.rs +++ b/services/llio/src/lib.rs @@ -305,6 +305,36 @@ impl Llio { Message::new_scalar(Opcode::PowerAudio.to_usize().unwrap(), arg, 0, 0, 0) ).map(|_| ()) } + pub fn soc_gitrev(&self) -> Result<(u8, u8, u8, u8, u32), xous::Error> { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::InfoGit.to_usize().unwrap(), 0, 0, 0, 0))?; + if let xous::Result::Scalar2(val1, val2) = response { + Ok( + ( + ((val1 >> 24) as u8), // major + ((val1 >> 16) as u8), // minor + ((val1 >> 8) as u8), // rev + (val1 >> 0) as u8, // gitextra + val2 as u32 // gitrev + ) + ) + } else { + log::error!("LLIO: unexpected return value: {:#?}", response); + Err(xous::Error::InternalError) + } + } + pub fn soc_dna(&self) -> Result { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::InfoDna.to_usize().unwrap(), 0, 0, 0, 0))?; + if let xous::Result::Scalar2(val1, val2) = response { + Ok( + (val1 as u64) | ((val2 as u64) << 32) + ) + } else { + log::error!("LLIO: unexpected return value: {:#?}", response); + Err(xous::Error::InternalError) + } + } } diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index 3835cac72..58b40314b 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -66,6 +66,7 @@ mod callback; use callback::*; mod rtc_cmd; use rtc_cmd::*; mod vibe; use vibe::*; mod ssid; use ssid::*; +mod ver; use ver::*; mod fcc; use fcc::*; mod pds; // dependency of the FCC file @@ -113,6 +114,7 @@ impl CmdEnv { let mut ret = String::<1024>::new(); let mut echo_cmd = Echo {}; // this command has no persistent storage, so we can "create" it every time we call dispatch (but it's a zero-cost absraction so this doesn't actually create any instructions) + let mut ver_cmd = Ver{}; let commands: &mut [& mut dyn ShellCmdApi] = &mut [ ///// 4. add your command to this array, so that it can be looked up and dispatched &mut echo_cmd, @@ -123,6 +125,7 @@ impl CmdEnv { &mut self.rtc_cmd, &mut self.vibe_cmd, &mut self.ssid_cmd, + &mut ver_cmd, &mut self.fcc_cmd, ]; diff --git a/services/shellchat/src/cmds/ver.rs b/services/shellchat/src/cmds/ver.rs new file mode 100644 index 000000000..3336ea71d --- /dev/null +++ b/services/shellchat/src/cmds/ver.rs @@ -0,0 +1,46 @@ +use crate::{ShellCmdApi, CommonEnv}; +use xous_ipc::String; + +#[derive(Debug)] +pub struct Ver { +} + +impl<'a> ShellCmdApi<'a> for Ver { + cmd_api!(ver); // inserts boilerplate for command API + + fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + use core::fmt::Write; + let mut ret = String::<1024>::new(); + let helpstring = "ver options: ec, wf200, soc, dna"; + + let mut tokens = args.as_str().unwrap().split(' '); + + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "ec" => { + let (rev, dirty) = env.com.get_ec_git_rev().unwrap(); + let dirtystr = if dirty { "dirty" } else { "clean" }; + write!(ret, "EC git commit: {:x}, {}", rev, dirtystr).unwrap(); + } + "wf200" => { + let (maj, min, rev) = env.com.get_wf200_fw_rev().unwrap(); + write!(ret, "Wf200 fw rev {}.{}.{}", maj, min, rev).unwrap(); + } + "soc" => { + let (maj, min, rev, extra, gitrev) = env.llio.soc_gitrev().unwrap(); + write!(ret, "SoC git rev {}.{}.{}+{}, commit {:x}", maj, min, rev, extra, gitrev).unwrap(); + } + "dna" => { + write!(ret, "SoC silicon DNA: 0x{:x}", env.llio.soc_dna().unwrap()).unwrap(); + } + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} From 836c836aec1cc102eb88c03872eeb080d034225e Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 26 Apr 2021 14:55:45 +0800 Subject: [PATCH 06/24] wip for susres extensions --- svd2utra/src/generate.rs | 112 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 110 insertions(+), 2 deletions(-) diff --git a/svd2utra/src/generate.rs b/svd2utra/src/generate.rs index 0ce7c79c3..b7c8c68ee 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,6 +477,7 @@ fn parse_vendor_extensions( fn print_header(out: &mut U) -> std::io::Result<()> { let s = r####" +#![allow(dead_code)] use core::convert::TryInto; pub struct Register { /// Offset of this register within this CSR @@ -549,6 +550,7 @@ impl Field { } } } +#[derive(Debug, Copy, Clone)] pub struct CSR { pub base: *mut T, } @@ -676,10 +678,116 @@ fn print_peripherals(peripherals: &[Peripheral], out: &mut U) -> std:: } writeln!(out)?; - writeln!(out, "pub mod utra {{")?; + let s = r####" +pub mod utra { + pub enum Error { + OutOfMemory, + } + + #[derive(Debug, Copy, Clone)] + pub struct ManagedReg { + pub offset: T, + pub mask: usize, + pub value: usize, + } + //#[derive(Debug)] + pub struct SusResRegManager { + pub csr: crate::CSR, + pub registers: [Option>; N], + pub sus_prologue: Option, + pub sus_epilogue: Option, + pub res_prologue: Option, + pub res_epilogue: Option, + } + impl SusResRegManager:: where ManagedReg: core::marker::Copy { + pub fn new(reg_base: *mut u32) -> SusResRegManager { + SusResRegManager:: { + csr: crate::CSR::new(reg_base), + registers: [None; N], + sus_prologue: None, + sus_epilogue: None, + res_prologue: None, + res_epilogue: None, + } + } + } + pub trait SusResReg { + fn push(&mut self, mr: ManagedReg) -> Result<(), Error>; + fn suspend(&mut self); + fn resume(&mut self); + } + impl SusResReg for SusResRegManager where T: core::convert::Into + Copy { + // push registers into the manager in the order you want them suspended + fn push(&mut self, mr: ManagedReg) -> Result<(), Error> { + for entry in self.registers.iter_mut() { + if entry.is_none() { + *entry = Some(mr); + return Ok(()) + } + } + Err(Error::OutOfMemory) + } + fn suspend(&mut self) { + if let Some(sp) = self.sus_prologue { + sp(self); + } + for entry in self.registers.iter_mut() { + if let Some(reg) = entry { + // masking is done on the write side + reg.value = self.csr.r(crate::Register{offset: reg.offset.into()}) 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().rev() { // this is in reverse order to the suspend + if let Some(reg) = entry { + self.csr.wo(crate::Register{offset: reg.offset.into()}, (reg.value & reg.mask) as u32); + } + } + if let Some(re) = self.res_epilogue { + re(self); + } + } + } +/* + pub struct ManagedMem { + pub mem: xous::MemoryRange, + pub backing: [u32; N], + } + pub trait SusResMem { + 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])}; + } + } + } +*/ +"####; + out.write_all(s.as_bytes())?; + for peripheral in peripherals { writeln!(out)?; writeln!(out, " pub mod {} {{", peripheral.name.to_lowercase())?; + 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 { From fab8687aebcbb24b5e1b5a081937b81067085e75 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:38:09 +0800 Subject: [PATCH 07/24] move susres stuff to its own server --- svd2utra/src/generate.rs | 114 ++++++--------------------------------- 1 file changed, 15 insertions(+), 99 deletions(-) diff --git a/svd2utra/src/generate.rs b/svd2utra/src/generate.rs index b7c8c68ee..4cd21b3c5 100644 --- a/svd2utra/src/generate.rs +++ b/svd2utra/src/generate.rs @@ -479,15 +479,20 @@ 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. @@ -680,107 +685,13 @@ fn print_peripherals(peripherals: &[Peripheral], out: &mut U) -> std:: let s = r####" pub mod utra { - pub enum Error { - OutOfMemory, - } - - #[derive(Debug, Copy, Clone)] - pub struct ManagedReg { - pub offset: T, - pub mask: usize, - pub value: usize, - } - //#[derive(Debug)] - pub struct SusResRegManager { - pub csr: crate::CSR, - pub registers: [Option>; N], - pub sus_prologue: Option, - pub sus_epilogue: Option, - pub res_prologue: Option, - pub res_epilogue: Option, - } - impl SusResRegManager:: where ManagedReg: core::marker::Copy { - pub fn new(reg_base: *mut u32) -> SusResRegManager { - SusResRegManager:: { - csr: crate::CSR::new(reg_base), - registers: [None; N], - sus_prologue: None, - sus_epilogue: None, - res_prologue: None, - res_epilogue: None, - } - } - } - pub trait SusResReg { - fn push(&mut self, mr: ManagedReg) -> Result<(), Error>; - fn suspend(&mut self); - fn resume(&mut self); - } - impl SusResReg for SusResRegManager where T: core::convert::Into + Copy { - // push registers into the manager in the order you want them suspended - fn push(&mut self, mr: ManagedReg) -> Result<(), Error> { - for entry in self.registers.iter_mut() { - if entry.is_none() { - *entry = Some(mr); - return Ok(()) - } - } - Err(Error::OutOfMemory) - } - fn suspend(&mut self) { - if let Some(sp) = self.sus_prologue { - sp(self); - } - for entry in self.registers.iter_mut() { - if let Some(reg) = entry { - // masking is done on the write side - reg.value = self.csr.r(crate::Register{offset: reg.offset.into()}) 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().rev() { // this is in reverse order to the suspend - if let Some(reg) = entry { - self.csr.wo(crate::Register{offset: reg.offset.into()}, (reg.value & reg.mask) as u32); - } - } - if let Some(re) = self.res_epilogue { - re(self); - } - } - } -/* - pub struct ManagedMem { - pub mem: xous::MemoryRange, - pub backing: [u32; N], - } - pub trait SusResMem { - 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])}; - } - } - } -*/ "####; 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 { @@ -793,11 +704,16 @@ pub mod utra { 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!( From 85211bb57d7900e99de0ac204031f5e37198a1b5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:38:51 +0800 Subject: [PATCH 08/24] add susres server skeleton --- Cargo.lock | 23 +++- Cargo.toml | 2 + kernel/Cargo.lock | 7 ++ loader/Cargo.lock | 7 ++ services/susres/Cargo.toml | 23 ++++ services/susres/src/api.rs | 230 ++++++++++++++++++++++++++++++++++++ services/susres/src/lib.rs | 27 +++++ services/susres/src/main.rs | 36 ++++++ svd2utra/Cargo.toml | 1 + 9 files changed, 355 insertions(+), 1 deletion(-) create mode 100644 services/susres/Cargo.toml create mode 100644 services/susres/src/api.rs create mode 100644 services/susres/src/lib.rs create mode 100644 services/susres/src/main.rs 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/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/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/services/susres/Cargo.toml b/services/susres/Cargo.toml new file mode 100644 index 000000000..b81ba2142 --- /dev/null +++ b/services/susres/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "susres" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "Manager 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..aaf6d705a --- /dev/null +++ b/services/susres/src/api.rs @@ -0,0 +1,230 @@ +use utralib::generated::*; + +pub(crate) const SERVER_NAME_SUSRES: &str = "_Suspend/resume manager_"; + +/* +#[allow(dead_code)] +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + Placeholder, +}*/ + +#[derive(Debug, Copy, Clone)] +pub enum RegOrField { + Field(Field), + Reg(Register), +} +#[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)] +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, +} +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!"); + } +} +pub trait SuspendResume { + fn suspend(&mut self); + fn resume(&mut self); +} +impl SuspendResume for RegManager { + fn suspend(&mut self) { + if let Some(sp) = self.sus_prologue { + sp(self); + } + for entry in self.registers.iter_mut() { + 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().rev() { // 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); + } + } +} +/* +pub struct ManagedMem { + pub mem: xous::MemoryRange, + pub backing: [u32; N], +} +pub trait SusResMem { + 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..d87c6f1ea --- /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() -> Result { + let conn = xous::connect(xous::SID::from_bytes(b"xoussusresserver").unwrap()).expect("Can't connect to SUSRES server"); + 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..b2620f20b --- /dev/null +++ b/services/susres/src/main.rs @@ -0,0 +1,36 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; + +use num_traits::FromPrimitive; + +use log::info; + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Trace); + 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); + + 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/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" From a4678ee95c4802f73bf960f285f2d84e83492dce Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:39:18 +0800 Subject: [PATCH 09/24] remove dependency of xous-names on ticktimer; use d11ctimeout instead this allows susres to manage ticktimer and have secured namespace integration --- services/xous-names/Cargo.toml | 1 - services/xous-names/src/main.rs | 54 +++++++++++++++++++++++++++------ 2 files changed, 44 insertions(+), 11 deletions(-) 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..9dc067749 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,15 +98,8 @@ 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 } From a1bcfb469e8081e75dd2edd706a7701b354f4fe7 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:40:29 +0800 Subject: [PATCH 10/24] add another call to make sure the RTC is initialized correctly --- services/rtc/src/main.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs index 779d653a4..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(); From 655c92a36cdc7fc3fedd8c7e435ce73b18e9b586 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:40:50 +0800 Subject: [PATCH 11/24] clean up ticktimer susres prototype code --- services/ticktimer-server/Cargo.toml | 1 + services/ticktimer-server/src/main.rs | 61 ++++++--------------------- 2 files changed, 15 insertions(+), 47 deletions(-) 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..2075f24ab 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 } From 00e3cd55fdb03c49dd1891a17a229d1bd71091f2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:46:24 +0800 Subject: [PATCH 12/24] fix generic error message --- services/llio/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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, From 94505ae6c501d04b7a581c78998b4481bea2a562 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:52:52 +0800 Subject: [PATCH 13/24] improve some error messages --- services/xous-names/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/xous-names/src/main.rs b/services/xous-names/src/main.rs index 9dc067749..9e04a072d 100644 --- a/services/xous-names/src/main.rs +++ b/services/xous-names/src/main.rs @@ -103,7 +103,7 @@ fn xmain() -> ! { 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(); @@ -152,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(); From 6a703def63540fe1930711e7ad111cf1e1494d72 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 00:53:08 +0800 Subject: [PATCH 14/24] commit the latest SVD files and other minor changes --- emulation/renode.svd | 54 +++++++++++++++++++++++++++++++++----- services/susres/Cargo.toml | 2 +- services/susres/src/lib.rs | 4 +-- svd2utra/examples/soc.svd | 54 +++++++++++++++++++++++++++++++++----- xtask/src/main.rs | 1 + 5 files changed, 100 insertions(+), 15 deletions(-) diff --git a/emulation/renode.svd b/emulation/renode.svd index 794d2937d..ebf534784 100644 --- a/emulation/renode.svd +++ b/emulation/renode.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/services/susres/Cargo.toml b/services/susres/Cargo.toml index b81ba2142..0d92c8cb5 100644 --- a/services/susres/Cargo.toml +++ b/services/susres/Cargo.toml @@ -3,7 +3,7 @@ name = "susres" version = "0.1.0" authors = ["bunnie "] edition = "2018" -description = "Manager suspend/resume operations" +description = "Manager of suspend/resume operations" [dependencies] xous = { path = "../../xous-rs" } diff --git a/services/susres/src/lib.rs b/services/susres/src/lib.rs index d87c6f1ea..40f9107a5 100644 --- a/services/susres/src/lib.rs +++ b/services/susres/src/lib.rs @@ -10,8 +10,8 @@ pub struct Susres { conn: CID, } impl Susres { - pub fn new() -> Result { - let conn = xous::connect(xous::SID::from_bytes(b"xoussusresserver").unwrap()).expect("Can't connect to SUSRES server"); + 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 }) 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/xtask/src/main.rs b/xtask/src/main.rs index 66be2ad60..98d7e9f72 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() { From 3fe52b31c532fb99f6a6b7586de7dce6a9e1ab88 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 01:37:58 +0800 Subject: [PATCH 15/24] add some debug for the trng CI process --- services/trng/src/main.rs | 6 ++++++ 1 file changed, 6 insertions(+) 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"); From 3c66aff2a6b673547fd6db7e1246cd472f425b92 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 01:44:00 +0800 Subject: [PATCH 16/24] only check soc_csr.bin if it exists --- buildpush.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 From d62f936454e63a78d5428c8b900962e6002ff1eb Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 02:53:22 +0800 Subject: [PATCH 17/24] start fleshing out the susres server --- services/susres/src/api.rs | 11 ++--- services/susres/src/main.rs | 60 ++++++++++++++++++++++++++- services/ticktimer-server/src/main.rs | 2 +- xtask/src/main.rs | 1 + 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/services/susres/src/api.rs b/services/susres/src/api.rs index aaf6d705a..a8f483ef4 100644 --- a/services/susres/src/api.rs +++ b/services/susres/src/api.rs @@ -70,7 +70,7 @@ impl SuspendResume for RegManager { if let Some(sp) = self.sus_prologue { sp(self); } - for entry in self.registers.iter_mut() { + for entry in self.registers.iter_mut().rev() { if let Some(reg) = entry { // masking is done on the write side match reg.item { @@ -87,7 +87,7 @@ impl SuspendResume for RegManager { if let Some(rp) = self.res_prologue { rp(self); } - for entry in self.registers.iter().rev() { // this is in reverse order to the suspend + 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 { @@ -105,12 +105,14 @@ impl SuspendResume for RegManager { } } } -/* + +// 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. pub struct ManagedMem { pub mem: xous::MemoryRange, pub backing: [u32; N], } -pub trait SusResMem { +impl SuspendResume for ManagedMem { fn suspend(&mut self) { let src = self.mem.as_ptr() as *const u32; for words in 0..self.mem.len() { @@ -124,7 +126,6 @@ pub trait SusResMem { } } } -*/ diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs index b2620f20b..796a8547a 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -2,21 +2,77 @@ #![cfg_attr(target_os = "none", no_main)] mod api; +use api::*; use num_traits::FromPrimitive; -use log::info; +#[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, + /// 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 mut sr = SusResHw { + csr: CSR::new(csr.as_mut_ptr() as *mut u32), + time_backing: None, + }; + + 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); - info!("my PID is {}", xous::process::id()); + 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(); /* diff --git a/services/ticktimer-server/src/main.rs b/services/ticktimer-server/src/main.rs index 2075f24ab..fe7eb3bb3 100644 --- a/services/ticktimer-server/src/main.rs +++ b/services/ticktimer-server/src/main.rs @@ -137,7 +137,7 @@ mod implementation { ) .expect("couldn't map Watchdog timer CSR range"); - let susres = RegManager::::new(csr.as_mut_ptr() as *mut u32); + 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), diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 98d7e9f72..46da750fe 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -143,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 " ) } From 36429de62fccde5acc3876f121eed29318e33fb6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 03:51:38 +0800 Subject: [PATCH 18/24] relocate top of kernel memory to save two pages for suspend/resume --- loader/src/asm.S | 4 ++++ tools/src/bin/create-image.rs | 3 +++ 2 files changed, 7 insertions(+) diff --git a/loader/src/asm.S b/loader/src/asm.S index e164ceaaf..9223308f1 100644 --- a/loader/src/asm.S +++ b/loader/src/asm.S @@ -10,6 +10,10 @@ _start: lw t0, 16(a0) // SRAM start lw t1, 20(a0) // SRAM length add sp, t0, t1 + // kernel RAM is two pages lower than the absolute end. + // add two pages to the sp so we are at the loader's private stack area + li t0, 0x2000 + add sp, sp, t0 // Install a machine mode trap handler la t0, abort diff --git a/tools/src/bin/create-image.rs b/tools/src/bin/create-image.rs index c4079b44c..ffedb4a29 100644 --- a/tools/src/bin/create-image.rs +++ b/tools/src/bin/create-image.rs @@ -207,6 +207,9 @@ fn main() { csr_to_config(tools::utils::CsrConfig { regions: map }, &mut ram_config); } + // reserve top two pages for bootloader stack, and for the "clean suspend" page + ram_config.size -= 4096 * 2; + let mut args = XousArguments::new(ram_config.offset, ram_config.size, ram_config.name); if !ram_config.regions.is_empty() { From 07d6055b4e10b22ad1f61ec4886adadf6cb07c27 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 03:52:34 +0800 Subject: [PATCH 19/24] new loader artifacts, change +x mode on script --- loader/assemble.sh | 0 loader/bin/riscv32i-unknown-none-elf.a | Bin 3090 -> 3202 bytes loader/bin/riscv32imac-unknown-none-elf.a | Bin 3094 -> 3202 bytes loader/bin/riscv32imc-unknown-none-elf.a | Bin 3094 -> 3202 bytes loader/bin/riscv64gc-unknown-none-elf.a | Bin 4714 -> 4890 bytes loader/bin/riscv64imac-unknown-none-elf.a | Bin 4714 -> 4890 bytes 6 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 loader/assemble.sh 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 7d0f709729850094d9588760df4a7a08445f8958..9595d25ed85f900dcda413efe61807782c23bb66 100644 GIT binary patch delta 651 zcmZ9Jze^lZ5XWcU-IKdriv$d=xO(fZ?umNtk~{nX+QdRgio}#jKu`}Z_+vp)ECfYT zS%~KpB8gy9*;|OD5Rw#vmiZ6jA7CeFlbL&W2o8Mbedhb-%`WflJKJr0jum^2sQRC} zA1lu@Z1Pa4RBJ27#h29|y(*KfUiY=0`2acz?>2;8ia0MoxCZ88@{wY zFBm@-9yqzd#B$rACRx?E*q#3O|BK{W8S!=Nh{D> z8eonRE5HhomB$hl^^u-SQTz>dlmVCUQm1YTN YSt(W{nl=5kL#L7fIBIyj%416W2a#@HCIA2c delta 565 zcmYL`Jxkj`(Pw=Yv$U)C;wQS$$G%zs(CKrqghwI*_#ktCJP6nKE_2&pyw3{zmu^E^{kmpO z%Z)5yuRB6$-~*kQlfqKKO0lsgLg*0gjaj|{Z4Q>yVPAw`3#Vg_IzPtz*3%hHQslf9 z31@mPlg&$rYqViF>RF>b!_%vL;V)eqjy|aa|Pp0R;@Zz3-m%M#|t+9oh*$H-Cw;C0bp7q=aa8lp#$xlam1)5M; Aa{vGU diff --git a/loader/bin/riscv32imac-unknown-none-elf.a b/loader/bin/riscv32imac-unknown-none-elf.a index b7f535bc457f315da9276b5ae504bced1fad7de1..b1c0cd964eb3648a31a81b042e557da96f302ba2 100644 GIT binary patch delta 611 zcmZ9JF-Rjp6o%(bG7@(q8Wb;HRB3Ig`QI5mnEUq}XRUf)!(V4i~e@W!!lpOYknU4$XXRvB$xb3bc14@j|He*p=8yCTlrPz7&a@H3u=1ml9mQReO%kde zS}+(Oi%YiHe9*~ku+@Pnc}Q^(npFHg$ZiJ7P}i)VMV5hn*-N|4a{^7x5yy1!7Z)^J z>rgJ Qf=313=nmhA97TIy0VQW-F#rGn delta 570 zcmYL`yGz4R6vod2&eyor0Lhdm6(z&Y9#ZFDQ5bSxU^Q%JPQ z)Kh5Dus($e+SS8+>PpX#TL94FaA7I#_Xwa}&E5W>xVn!rHzxgkf?Kb16RnA8J9o?x z^&(4gtj$BH;fA))A;l_y)xgG1520Cc*k|<(D7mmy9CmpKQgOs*FSEnvznm6tQbG1# zkm7jfO(-~rI8UpFt^EkvGh+GyKX{-!!`2HrK$hMO8z(7X#&L_1TsLTjYnisqxb|F2 y7iLVqM1T~%m^QxAw;6YU|JN&9UEaeMY{fx#fL+zAph75S{nP@SRd?Ju&C@S0)L6X$ diff --git a/loader/bin/riscv32imc-unknown-none-elf.a b/loader/bin/riscv32imc-unknown-none-elf.a index b7f535bc457f315da9276b5ae504bced1fad7de1..b1c0cd964eb3648a31a81b042e557da96f302ba2 100644 GIT binary patch delta 611 zcmZ9JF-Rjp6o%(bG7@(q8Wb;HRB3Ig`QI5mnEUq}XRUf)!(V4i~e@W!!lpOYknU4$XXRvB$xb3bc14@j|He*p=8yCTlrPz7&a@H3u=1ml9mQReO%kde zS}+(Oi%YiHe9*~ku+@Pnc}Q^(npFHg$ZiJ7P}i)VMV5hn*-N|4a{^7x5yy1!7Z)^J z>rgJ Qf=313=nmhA97TIy0VQW-F#rGn delta 570 zcmYL`yGz4R6vod2&eyor0Lhdm6(z&Y9#ZFDQ5bSxU^Q%JPQ z)Kh5Dus($e+SS8+>PpX#TL94FaA7I#_Xwa}&E5W>xVn!rHzxgkf?Kb16RnA8J9o?x z^&(4gtj$BH;fA))A;l_y)xgG1520Cc*k|<(D7mmy9CmpKQgOs*FSEnvznm6tQbG1# zkm7jfO(-~rI8UpFt^EkvGh+GyKX{-!!`2HrK$hMO8z(7X#&L_1TsLTjYnisqxb|F2 y7iLVqM1T~%m^QxAw;6YU|JN&9UEaeMY{fx#fL+zAph75S{nP@SRd?Ju&C@S0)L6X$ diff --git a/loader/bin/riscv64gc-unknown-none-elf.a b/loader/bin/riscv64gc-unknown-none-elf.a index 6f52e5e08286ad7905b1d08234eb2df8c0942f0c..cf1ed3413f26884912ed3f33ccf5ad4e0a04925c 100644 GIT binary patch delta 814 zcmZuuF=!M)6rI1jcjx8qa=Qk-EGFK1*+eBdch%(<8>fhHVv2--5+PNRlZcvy3lS?L zrVvSCj$a6Z78X{5kSj$LQW%I}5yZkGMY>emr*Z!7Ebf87nD_pBfByWLIkMl3Z4LIh zRuY}sy!|h;teD4Z!}Fpt&%fe!-n$TX_WgmE3#U7;6~^$n!dACt-5{)@2^@CuF5JUo zDB@T6HRLP@k6O;c+RDoPma`ZvwVWrx+G>3vO0@t}?SnI_bu{8H8fJ7SNsOW@(3 ztOE@!s_Ekv3g= zNOFQi9~1mcO5c&3>WBZMQ+>M6_f-AaRK3)*j5ZA8L9qg(I9;rmlqaD}BL0?HxGvmt ziA9R!^aC~gB-|0H5F~Fyu1)>TYRc{HTrTx?rgx^G9#)r^_CS1Hq3lD5lVzUYj!edW z;AYv+Kg-4GF7Annr>N>&xmm;;`gQn-8#;$?xFgmORfFe48b`!6oHBg4h#Lk!HAmMI bv8=^NvyJ0#V_fW1PxAasDc0ZOW`FfBNuG0n delta 672 zcmZ9IF=!KE6vywKm&9noT_T!>+T=4$YHeC_NiMlyu~&)Et(4+W=t&1#5eFlNPK6F# z9NX|86j3NTI0z!#s9bI|YIeG%IK@P7aI-tq2z@8QJP^4`dadb{3i zwd$_Z8kGF<|I87>7OW`NZM)rW3*odJXYjBtrKtzD_o(i5fMqn(!_OH9jXfr949@ z-&7o;tjvgH1(-{**&K!j7jCWTjKfoF;!t4p8V#>WPT`%XB2`T z>Gu@g_M=&%ef%=LfhHVv2--5+PNRlZcvy3lS?L zrVvSCj$a6Z78X{5kSj$LQW%I}5yZkGMY>emr*Z!7Ebf87nD_pBfByWLIkMl3Z4LIh zRuY}sy!|h;teD4Z!}Fpt&%fe!-n$TX_WgmE3#U7;6~^$n!dACt-5{)@2^@CuF5JUo zDB@T6HRLP@k6O;c+RDoPma`ZvwVWrx+G>3vO0@t}?SnI_bu{8H8fJ7SNsOW@(3 ztOE@!s_Ekv3g= zNOFQi9~1mcO5c&3>WBZMQ+>M6_f-AaRK3)*j5ZA8L9qg(I9;rmlqaD}BL0?HxGvmt ziA9R!^aC~gB-|0H5F~Fyu1)>TYRc{HTrTx?rgx^G9#)r^_CS1Hq3lD5lVzUYj!edW z;AYv+Kg-4GF7Annr>N>&xmm;;`gQn-8#;$?xFgmORfFe48b`!6oHBg4h#Lk!HAmMI bv8=^NvyJ0#V_fW1PxAasDc0ZOW`FfBNuG0n delta 672 zcmZ9IF=!KE6vyvfFG-^bcS)&fs7*f8q_#~Zm*kQQ7JHQl-HM1q!IKWQQaUuH!Aa=g z;@Fn|pol`z!9ft=Mg@z5i-Ur=J1eN5n}dGu?h8`?!~6Z;`##?HzV~42OL>3nM7>>a zwpw-9aSlp;`Clf4Em%>k+jhI%7Q$)Cdyj2eJoxCE_jFCe9bN11U$J{XRxv>yy~1_6 ziTCs=d+EI2?X9i*E4^EN|3+_T-N%u>5)_6~MAPUROZkR&Tok5;wty$b5-sDaQKPFE zkL}SWp2g1MvTop8%)y)3DRklun#4tY1iNvEMCjhe*T_aSQKJT~CAEip!PCTKWlmKxl2zpyw({pBXM^H!*QmTyrIO@nk(L$r)N}!F|9nGmbia@LRA>YJHP&~Gk=uDJqp41 z^g9Z7`@t;HA%2=(@_BfyX-Am1+@zg|(hc0UT-rildHVg6_+>57Lo_oUy+B{aMFbfy r`I!fjs^NFWB@@l8H`?J3N_C8gJlzcLW~;P~AnPR$Q&Ig9=FQ??o&{>6 From 68ed5911892d9e9e2b75638200dd0e676907e364 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 03:56:57 +0800 Subject: [PATCH 20/24] start to flesh out API, allocate clean suspend page --- services/susres/src/api.rs | 19 +++++++++++++++---- services/susres/src/main.rs | 9 +++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/services/susres/src/api.rs b/services/susres/src/api.rs index a8f483ef4..0eb2f050f 100644 --- a/services/susres/src/api.rs +++ b/services/susres/src/api.rs @@ -2,12 +2,23 @@ use utralib::generated::*; pub(crate) const SERVER_NAME_SUSRES: &str = "_Suspend/resume manager_"; -/* -#[allow(dead_code)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { - Placeholder, -}*/ + /// 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, +} #[derive(Debug, Copy, Clone)] pub enum RegOrField { diff --git a/services/susres/src/main.rs b/services/susres/src/main.rs index 796a8547a..8597a46d2 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -20,6 +20,8 @@ mod implementation { pub struct SusResHw { /// our CSR csr: utralib::CSR, + /// memory region for the "clean suspend" marker + marker: xous::MemoryRange, /// backing store for the ticktimer value time_backing: Option<[u32; 2]>, } @@ -33,9 +35,16 @@ mod implementation { ) .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 mut sr = SusResHw { csr: CSR::new(csr.as_mut_ptr() as *mut u32), time_backing: None, + marker, }; xous::claim_interrupt( From 7f6abaea6a28d891d5526da71f20d0758c60056e Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 18:16:33 +0800 Subject: [PATCH 21/24] Revert "relocate top of kernel memory to save two pages for suspend/resume" This reverts commit 36429de62fccde5acc3876f121eed29318e33fb6. Turns out there is a better way to do this. --- loader/src/asm.S | 4 ---- tools/src/bin/create-image.rs | 3 --- 2 files changed, 7 deletions(-) diff --git a/loader/src/asm.S b/loader/src/asm.S index 9223308f1..e164ceaaf 100644 --- a/loader/src/asm.S +++ b/loader/src/asm.S @@ -10,10 +10,6 @@ _start: lw t0, 16(a0) // SRAM start lw t1, 20(a0) // SRAM length add sp, t0, t1 - // kernel RAM is two pages lower than the absolute end. - // add two pages to the sp so we are at the loader's private stack area - li t0, 0x2000 - add sp, sp, t0 // Install a machine mode trap handler la t0, abort diff --git a/tools/src/bin/create-image.rs b/tools/src/bin/create-image.rs index ffedb4a29..c4079b44c 100644 --- a/tools/src/bin/create-image.rs +++ b/tools/src/bin/create-image.rs @@ -207,9 +207,6 @@ fn main() { csr_to_config(tools::utils::CsrConfig { regions: map }, &mut ram_config); } - // reserve top two pages for bootloader stack, and for the "clean suspend" page - ram_config.size -= 4096 * 2; - let mut args = XousArguments::new(ram_config.offset, ram_config.size, ram_config.name); if !ram_config.regions.is_empty() { From 8f679ce41ff5acebb2942fa8904aab180bc79d86 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 18:17:07 +0800 Subject: [PATCH 22/24] revert the loader assembly artifacts --- loader/bin/riscv32i-unknown-none-elf.a | Bin 3202 -> 3098 bytes loader/bin/riscv32imac-unknown-none-elf.a | Bin 3202 -> 3106 bytes loader/bin/riscv32imc-unknown-none-elf.a | Bin 3202 -> 3106 bytes loader/bin/riscv64gc-unknown-none-elf.a | Bin 4890 -> 4730 bytes loader/bin/riscv64imac-unknown-none-elf.a | Bin 4890 -> 4730 bytes 5 files changed, 0 insertions(+), 0 deletions(-) diff --git a/loader/bin/riscv32i-unknown-none-elf.a b/loader/bin/riscv32i-unknown-none-elf.a index 9595d25ed85f900dcda413efe61807782c23bb66..2a092a4b01b8cb661f86d19d1d7904bd92b911f7 100644 GIT binary patch delta 482 zcmXw$F-rqM5QS$hdoj6-c!H1Z=*Umf4c{#`u_9jAvI4|f# zoD!A*mc_D!hWWmO70>a(4pZV zP~GtLYo5PT$8hv@9bl1qyt6|w)5kL^ay_AKt_?aheXTo0kEVyu^uf(H(x2%CihrTY dmWyZEiY=UE$JhgXDXOGA8xjDwgBh>b=YO|mLWTeU delta 586 zcmZ9JJxc>Y5Qb+iIZ1L65~3uMsFypv6O9;*Xo?7;g=NsvCZHB60v0JOl~^j0Fomcn zeiim9#41HBQuq@r?X(E^19av-6ntT3pM7_3cK7xo)fj1B2MhVaeCuvX358p))5#|T zpnw~2rT|bwfqHW@zt^vjip%&yYq(A4c-vl7N*K?8uOJ|!PDg=CyyTnUx-0Y*I3AYu z>c5p5)q`_bqx)b5bqc8EY~HJg@wbWJYJeE?7{>zD)umOPDVgKM(m4tOtO<^k?V!WH zFQxHW*OwjQx%Q`OC%FUMdBTVBloGfs*N5amG2LFd${ zyFA1LW?fDR8?f%oq&J%Gf-Wq#U^z|4U6$*k&WR;m{_IDh>h>m<$OvXoF6Hn*-9})CC$Pf?eGK@I?=4b48MJ!L-w7a Wj+R!UD!pk|su}{gV$+wrs^|xgdPklB diff --git a/loader/bin/riscv32imac-unknown-none-elf.a b/loader/bin/riscv32imac-unknown-none-elf.a index b1c0cd964eb3648a31a81b042e557da96f302ba2..a307283d9c3b2c38d52fde5408964f1b5bf18b37 100644 GIT binary patch delta 487 zcmXw$u}i~H5XSG4mzp*K6@*5rZEb2(Q$(?15kXNpYtgNPf{UYrZVp0m5W2M9ASgN% zhk}Dc!8-UK)WK0uD6UR||A2Q%`@whjyUXLtgIAkuIgNX@v|3zgw(?rrY`*!U*BSuT zG&pJOE*}5(DT*b0p-nvOJmDu|nr`(4^r@$B;5u09xy}2XY$T(dcbPMCkR_Z; z1PBps=!R?yO8{$(jmZFELO2z&+yT>ESQ3Xb0YX|h6LOF_9r7S29!wJC4uXWeWXFzH z5%=jR=AudUm}gw^{*}5h*Qgi(%hcyD+oW3_UQmJSDeZB+q%+IYK1S%l%3+&&y!xg; k%kyo1ig&jBcaE*t!cn%)9_mX`+0Hqp32-;uamNAw14;-)00000 delta 559 zcmZ9JJxc>Y5QcXyx0>Wq7!-{rdgn#&LOx6|MS>uLh?atlprQ~g1Pcqx6p>(KmoT7$ zXdsrcOQV&A7J~kRwCQXj`U9NF<`5j1nP=afc@J)zk?LgaPS5A^i}hwg^9Sl5$PKf0;`%ht!?E_dJU9NfLC0G5_TZeZa@dZQ^E^f0AUQvzAU7%9xy}2XY$T(dcbPMCkR_Z; z1PBps=!R?yO8{$(jmZFELO2z&+yT>ESQ3Xb0YX|h6LOF_9r7S29!wJC4uXWeWXFzH z5%=jR=AudUm}gw^{*}5h*Qgi(%hcyD+oW3_UQmJSDeZB+q%+IYK1S%l%3+&&y!xg; k%kyo1ig&jBcaE*t!cn%)9_mX`+0Hqp32-;uamNAw14;-)00000 delta 559 zcmZ9JJxc>Y5QcXyx0>Wq7!-{rdgn#&LOx6|MS>uLh?atlprQ~g1Pcqx6p>(KmoT7$ zXdsrcOQV&A7J~kRwCQXj`U9NF<`5j1nP=afc@J)zk?LgaPS5A^i}hwg^9Sl5$PKf0;`%ht!?E_dJU9NfLC0G5_TZeZa@dZQ^E^f0AUQvzAU7%An^~_B}i(r@V<9%2cF^ie4p=g_q^}>9Q1s5myhMqvC7F16)P`UeP5O& z?8?$+c`m*2xr7Kgbc01&ai3^GralyuX=_;e8|0OWl*g$uO|y7YQZ$b?wM1*UPxK~?{3v7{%DY*#`fn`b~sikNb3z{=wi=ifCLTCvjrS}R delta 708 zcmZuuF-SsD6n*#iRRm4#Q}!{_>}Q3FTB2KjXfRretSB0Sh-e4`8-t35ph@KpLK4v) z4LOH_LxOFN4Gj$q4GC?v^sc@SU+50^oO{lFm-p`b(XPV98!0nWx=lj6)XFHAJ42WJV3h92hJXVU9}Q@{Too%+plo=yFu zrhcJY86EKBm%|Gaxb5(&R2$(Ig#Q!^Vu8D3hDD0twD%C!xH~Qs0%JGiYBXOBnB3mU z0cY=I+A{^s2v(PzP2eBqb7i27IhSsK=$MSXV8xZOpV_))17CT^2`X+~T5#a1dk*dp v-8wvBi{~~f9?ChMrx88+;08U5$G+S}x>E!{JQ03E8PM&^&aQrqmHxmV=+s{X diff --git a/loader/bin/riscv64imac-unknown-none-elf.a b/loader/bin/riscv64imac-unknown-none-elf.a index cf1ed3413f26884912ed3f33ccf5ad4e0a04925c..72c00d1178e4aa427e4394570b3e7826137bbf6c 100644 GIT binary patch delta 579 zcmZ9Izb^w}7{~9q-1RgxcPg9<)l=$6OInIH5k1m@NgA<An^~_B}i(r@V<9%2cF^ie4p=g_q^}>9Q1s5myhMqvC7F16)P`UeP5O& z?8?$+c`m*2xr7Kgbc01&ai3^GralyuX=_;e8|0OWl*g$uO|y7YQZ$b?wM1*UPxK~?{3v7{%DY*#`fn`b~sikNb3z{=wi=ifCLTCvjrS}R delta 708 zcmZuuF-SsD6n*#iRRm4#Q}!{_>}Q3FTB2KjXfRretSB0Sh-e4`8-t35ph@KpLK4v) z4LOH_LxOFN4Gj$q4GC?v^sc@SU+50^oO{lFm-p`b(XPV98!0nWx=lj6)XFHAJ42WJV3h92hJXVU9}Q@{Too%+plo=yFu zrhcJY86EKBm%|Gaxb5(&R2$(Ig#Q!^Vu8D3hDD0twD%C!xH~Qs0%JGiYBXOBnB3mU z0cY=I+A{^s2v(PzP2eBqb7i27IhSsK=$MSXV8xZOpV_))17CT^2`X+~T5#a1dk*dp v-8wvBi{~~f9?ChMrx88+;08U5$G+S}x>E!{JQ03E8PM&^&aQrqmHxmV=+s{X From d2e9d35d37238ae841d5641a8ec8eff584034319 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 18:47:55 +0800 Subject: [PATCH 23/24] modify loader to block out suspend resume pages per Xobs review --- loader/src/main.rs | 11 +++++++++-- services/susres/src/main.rs | 12 ++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) 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/susres/src/main.rs b/services/susres/src/main.rs index 8597a46d2..293a043f5 100644 --- a/services/susres/src/main.rs +++ b/services/susres/src/main.rs @@ -22,6 +22,8 @@ mod implementation { 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]>, } @@ -41,12 +43,22 @@ mod implementation { 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, From 77ad54e193b9dadf94f9bf40e1d002b23489763f Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 27 Apr 2021 18:55:05 +0800 Subject: [PATCH 24/24] fix hosted mode compatibility issues --- services/susres/src/api.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/services/susres/src/api.rs b/services/susres/src/api.rs index 0eb2f050f..26acc7836 100644 --- a/services/susres/src/api.rs +++ b/services/susres/src/api.rs @@ -1,3 +1,4 @@ +#[cfg(target_os = "none")] use utralib::generated::*; pub(crate) const SERVER_NAME_SUSRES: &str = "_Suspend/resume manager_"; @@ -20,11 +21,13 @@ 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 @@ -34,7 +37,9 @@ pub struct ManagedReg { /// 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], @@ -43,6 +48,7 @@ pub struct RegManager { 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:: { @@ -72,10 +78,12 @@ impl RegManager:: where ManagedReg: core::marker::Copy { 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 { @@ -119,10 +127,12 @@ impl SuspendResume for RegManager { // 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;