From e6d44795a1a7e0fca057a425a667635b4ac92d01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 21 Apr 2023 18:10:36 +0200 Subject: [PATCH 1/9] early_settings: first commit --- Cargo.lock | 25 +++++++- Cargo.toml | 2 + services/early_settings/Cargo.toml | 24 ++++++++ services/early_settings/README.md | 15 +++++ services/early_settings/src/lib.rs | 93 +++++++++++++++++++++++++++++ services/early_settings/src/main.rs | 82 +++++++++++++++++++++++++ xtask/src/main.rs | 7 ++- 7 files changed, 243 insertions(+), 5 deletions(-) create mode 100644 services/early_settings/Cargo.toml create mode 100644 services/early_settings/README.md create mode 100644 services/early_settings/src/lib.rs create mode 100644 services/early_settings/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 8d5308846..4a92d011f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1156,6 +1156,25 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" +[[package]] +name = "early_settings" +version = "0.1.0" +dependencies = [ + "log", + "num-derive", + "num-traits", + "once_cell", + "rkyv", + "spinor", + "utralib", + "xous 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-log", + "xous-api-names", + "xous-api-susres", + "xous-api-ticktimer", + "xous-ipc 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ecdsa" version = "0.13.4" @@ -2134,6 +2153,7 @@ dependencies = [ name = "keyboard" version = "0.1.0" dependencies = [ + "early_settings", "llio", "log", "num-derive", @@ -2587,9 +2607,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.12.0" +version = "1.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" +checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" [[package]] name = "oorandom" @@ -3932,6 +3952,7 @@ dependencies = [ "crossbeam", "digest 0.9.0", "dns", + "early_settings", "gam", "graphics-server", "keyboard", diff --git a/Cargo.toml b/Cargo.toml index d896ce944..028599f63 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ default-members = [ "services/dns", "services/modals", "services/usb-device-xous", + "services/early_settings", "libs/userprefs" ] members = [ @@ -72,6 +73,7 @@ members = [ "services/net", "services/dns", "services/modals", + "services/early_settings", "apps/ball", "apps/hello", "apps/mtxcli", diff --git a/services/early_settings/Cargo.toml b/services/early_settings/Cargo.toml new file mode 100644 index 000000000..0413cc61f --- /dev/null +++ b/services/early_settings/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "early_settings" +version = "0.1.0" +authors = ["gsora "] +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +log = {version = "0.4", features = ["max_level_trace", "release_max_level_trace"]} +log-server = {package = "xous-api-log", version = "0.1.30"} +ticktimer-server = {package = "xous-api-ticktimer", version = "0.9.30"} +xous = "0.9.35" +xous-ipc = "0.9.35" +xous-names = {package = "xous-api-names", version = "0.9.32"} +susres = {package = "xous-api-susres", version = "0.9.30"} +spinor = {path = "../../services/spinor"} + +num-derive = {version = "0.3.3", default-features = false} +num-traits = {version = "0.2.14", default-features = false} +rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} + +utralib = {version = "0.1.15", optional = true, default-features = false } +once_cell = "1.17.1" diff --git a/services/early_settings/README.md b/services/early_settings/README.md new file mode 100644 index 000000000..035ba2f37 --- /dev/null +++ b/services/early_settings/README.md @@ -0,0 +1,15 @@ +# `early_settings` + +This crate provides a service and API to access some settings stored in the first 4096 bytes of FLASH. + +Settings currently stored here: + - keymap + - early sleep flag + +**Do not store any personal informations here, user settings must go into `libs/userprefs`!** + +This scratch area is provided for extreme edge cases: + - keymap must live here because users need to write their password in order to mount PDDB + - early sleep is used in the "lock device" lifecycle, placing it here is the most convenient thing to do to achieve that use-case + +If you're thinking of placing something in here please open an issue or shoot us a Matrix message on `#xous-apps:matrix.org`. \ No newline at end of file diff --git a/services/early_settings/src/lib.rs b/services/early_settings/src/lib.rs new file mode 100644 index 000000000..8fe7a8a70 --- /dev/null +++ b/services/early_settings/src/lib.rs @@ -0,0 +1,93 @@ +use core::sync::atomic::{AtomicU32, Ordering}; +use num_traits::*; +use xous::{send_message, Message}; + +pub const SERVER_NAME_ES: &str = "_EARLY_SETTINGS"; + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub enum Opcode { + SetKeymap, + GetKeymap, + EarlySleep, + SetEarlySleep, +} + +#[derive(Debug)] +pub struct EarlySettings { + conn: xous::CID, +} + +impl EarlySettings { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.fetch_add(1, Ordering::Relaxed); + let conn = xns + .request_connection_blocking(SERVER_NAME_ES) + .expect("Can't connect to EarlySettings"); + Ok(EarlySettings { conn }) + } + + pub fn set_keymap(&self, map: usize) -> Result<(), xous::Error> { + send_message( + self.conn, + Message::new_blocking_scalar( + Opcode::SetKeymap.to_usize().unwrap(), + map.into(), + 0, + 0, + 0, + ), + ) + .map(|_| ()) + } + + pub fn get_keymap(&self) -> Result { + match send_message( + self.conn, + Message::new_blocking_scalar(Opcode::GetKeymap.to_usize().unwrap(), 0, 0, 0, 0), + ) { + Ok(xous::Result::Scalar1(code)) => Ok(code), + _ => Err(xous::Error::InternalError), + } + } + + pub fn set_early_sleep(&self, value: bool) -> Result<(), xous::Error> { + send_message( + self.conn, + Message::new_blocking_scalar( + Opcode::SetEarlySleep.to_usize().unwrap(), + value as usize, + 0, + 0, + 0, + ), + ) + .map(|_| ()) + } + + pub fn early_sleep(&self) -> Result { + match send_message( + self.conn, + Message::new_blocking_scalar(Opcode::EarlySleep.to_usize().unwrap(), 0, 0, 0, 0), + ) { + Ok(xous::Result::Scalar1(value)) => match value { + 0 => Ok(false), + 1 => Ok(true), + _ => Ok(false), // instead of doing `value != 0` we're explicitly matching against specific values, because + // reading off FLASH can yield a true value otherwise, even if it wasn't set before + }, + _ => Err(xous::Error::InternalError), + } + } +} + +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for EarlySettings { + fn drop(&mut self) { + // now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { + unsafe { + xous::disconnect(self.conn).unwrap(); + } + } + } +} diff --git a/services/early_settings/src/main.rs b/services/early_settings/src/main.rs new file mode 100644 index 000000000..2328110d4 --- /dev/null +++ b/services/early_settings/src/main.rs @@ -0,0 +1,82 @@ +use early_settings::{Opcode, SERVER_NAME_ES}; +use num_traits::FromPrimitive; +use spinor::Spinor; +use xous::{msg_blocking_scalar_unpack, MemoryRange}; + +struct State { + settings_page: MemoryRange, + spinor: Spinor, +} + +fn main() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + log::info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + + let state = State { + settings_page: xous::syscall::map_memory( + xous::MemoryAddress::new((xous::EARLY_SETTINGS + xous::FLASH_PHYS_BASE) as usize), + None, + 4096, + xous::MemoryFlags::R, + ) + .unwrap(), + spinor: spinor::Spinor::new(&xns).unwrap(), + }; + + let sid = xns + .register_name(SERVER_NAME_ES, None) + .expect("can't register server"); + + loop { + let msg = xous::receive_message(sid).unwrap(); // this blocks until we get a message + log::trace!("Message: {:?}", msg); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::GetKeymap) => { + let settings: &[u8] = state.settings_page.as_slice(); + + let code = u32::from_le_bytes(settings[..4].try_into().unwrap()); + + xous::return_scalar(msg.sender, code as usize).unwrap(); + } + Some(Opcode::SetKeymap) => msg_blocking_scalar_unpack!(msg, map, _, _, _, { + let code = (map as u32).to_le_bytes(); + let settings: &[u8] = state.settings_page.as_slice(); + + state + .spinor + .patch(settings, xous::EARLY_SETTINGS, &code, 0) + .expect("couldn't patch our keyboard code"); + + log::info!("writing early keymap: {}", map); + + xous::return_scalar(msg.sender, 0).unwrap(); + }), + Some(Opcode::SetEarlySleep) => msg_blocking_scalar_unpack!(msg, value, _, _, _, { + let code = (value as u32).to_le_bytes(); + let settings: &[u8] = state.settings_page.as_slice(); + + state + .spinor + .patch(settings, xous::EARLY_SETTINGS, &code, 4) + .expect("couldn't patch early reboot flag"); + + log::info!("writing must sleep on reboot: {}", value); + + xous::return_scalar(msg.sender, 0).unwrap(); + }), + Some(Opcode::EarlySleep) => { + let settings: &[u8] = state.settings_page.as_slice(); + + let value = u32::from_le_bytes(settings[4..8].try_into().unwrap()); + + log::info!("value read for early sleep: {}", value); + + xous::return_scalar(msg.sender, value as usize).unwrap(); + } + _ => log::warn!("unrecognized opcode"), + } + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2b67a1540..5235a83ea 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -70,9 +70,10 @@ fn main() -> Result<(), Box> { &base_pkgs[..], &[ "graphics-server", // raw (unprotected) frame buffer primitives - "keyboard", // required by graphics-server - "spinor", // required by keyboard - to save key mapping - "llio", // required by spinor + "early_settings", // required by keyboard + "keyboard", // required by graphics-server + "spinor", // required by keyboard - to save key mapping + "llio", // required by spinor ] ].concat(); // packages in the user image - most of the services at this layer have cross-dependencies From 523ec0ac800251c894964c1ffd0cf8003c028b8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 21 Apr 2023 18:11:04 +0200 Subject: [PATCH 2/9] services/keyboard: remove explicit early settings FLASH access Use early_settings service. --- services/keyboard/Cargo.toml | 1 + services/keyboard/src/main.rs | 41 +++++++++++------------------------ 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/services/keyboard/Cargo.toml b/services/keyboard/Cargo.toml index f0d6e879f..d6f377067 100644 --- a/services/keyboard/Cargo.toml +++ b/services/keyboard/Cargo.toml @@ -22,6 +22,7 @@ num-traits = {version = "0.2.14", default-features = false} rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} utralib = {version = "0.1.17", optional = true, default-features = false } +early_settings ={ path = "../early_settings"} [features] precursor = ["utralib/precursor"] diff --git a/services/keyboard/src/main.rs b/services/keyboard/src/main.rs index 3f939a75b..82cc6af3d 100644 --- a/services/keyboard/src/main.rs +++ b/services/keyboard/src/main.rs @@ -25,7 +25,6 @@ mod implementation { use num_traits::ToPrimitive; use susres::{RegManager, RegOrField, SuspendResume}; use std::collections::HashSet; - use std::convert::TryInto; /// note: the code is structured to use at most 16 rows or 16 cols const KBD_ROWS: usize = 9; @@ -69,10 +68,8 @@ mod implementation { susres: RegManager::<{utra::keyboard::KEYBOARD_NUMREGS}>, /// a field used for debugging various keyboard issues, especially with the interrupt handler pub debug: usize, - /// a slice that contains the location of the early-boot keyboard settings - settings: xous::MemoryRange, - /// a handle to the spinor block so we can update our settings - spinor: spinor::Spinor, + /// access to settings stored in the first few sectors of FLASH + early_settings: early_settings::EarlySettings, } fn handle_kbd(_irq_no: usize, arg: *mut usize) { @@ -139,17 +136,13 @@ mod implementation { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("couldn't map Keyboard CSR range"); - let setting_page = xous::syscall::map_memory( - xous::MemoryAddress::new((xous::EARLY_SETTINGS + xous::FLASH_PHYS_BASE) as usize), - None, - 4096, - xous::MemoryFlags::R, - ) - .expect("couldn't map Keyboard pre-boot setting"); let ticktimer = ticktimer_server::Ticktimer::new().expect("couldn't connect to ticktimer"); let timestamp = ticktimer.elapsed_ms(); - let settings: &[u8] = setting_page.as_slice(); + + let xns = xous_names::XousNames::new().unwrap(); + + let ea = early_settings::EarlySettings::new(&xns).unwrap(); let default_map = if cfg!(feature = "braille") { KeyMap::Braille @@ -160,10 +153,10 @@ mod implementation { // unencrypted and plaintext bit of memory that anyone can read or mess with. The only reason the keyboard // layout is kept here is because you want your keyboard to be in the right language before typing in the // password to unlock the PDDB, which is *actually* where all the user settings should be located. - let code = u32::from_le_bytes(settings[..4].try_into().unwrap()); - KeyMap::from(code as usize) + let kb_raw = ea.get_keymap().expect("cannot fetch keymap from early settings"); + let map = KeyMap::from(kb_raw); + map }; - let xns = xous_names::XousNames::new().unwrap(); let mut kbd = Keyboard { conn: xous::connect(sid).unwrap(), @@ -187,8 +180,7 @@ mod implementation { chord_captured: false, susres: RegManager::new(csr.as_mut_ptr() as *mut u32), debug: 0, - settings: setting_page, - spinor: spinor::Spinor::new(&xns).unwrap(), + early_settings: ea, }; xous::claim_interrupt( @@ -239,19 +231,12 @@ mod implementation { } pub(crate) fn set_map(&mut self, map: KeyMap) { - let code_usize: usize = map.into(); - let code = (code_usize as u32).to_le_bytes(); - let settings: &[u8] = self.settings.as_slice(); - self.spinor.patch(settings, xous::EARLY_SETTINGS, - &code, 0 - ).expect("couldn't patch our keyboard code"); + self.early_settings.set_keymap(map.into()).expect("cannot set early keymap"); self.map = map; } pub(crate) fn get_map(&mut self) -> KeyMap { - // refresh the map from the setting in the FLASH - let settings: &[u8] = self.settings.as_slice(); - let code = u32::from_le_bytes(settings[..4].try_into().unwrap()); - self.map = KeyMap::from(code as usize); + let kb_raw = self.early_settings.get_keymap().expect("cannot fetch early keymap"); + self.map = KeyMap::from(kb_raw); self.map } pub(crate) fn set_repeat(&mut self, rate: u32, delay: u32) { From 6abf497ac9aad9fe352b4a09d7c7f56447c1dda2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Fri, 21 Apr 2023 18:12:36 +0200 Subject: [PATCH 3/9] services/status: if early sleep flag is present, sleep immediately This flag is only set if the user selects "Lock (reboot)". This way, the device sleeps immediately after boot, and makes easier turning it on and off in a safe manner. --- services/status/Cargo.toml | 2 ++ services/status/src/main.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index f865b30c8..d0341213d 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -30,6 +30,8 @@ usb-device-xous = {path="../usb-device-xous"} codec = {path="../codec"} userprefs = {path = "../../libs/userprefs"} dns = {path="../dns"} +early_settings ={ path = "../early_settings"} + num-derive = {version = "0.3.3", default-features = false} num-traits = {version = "0.2.14", default-features = false} diff --git a/services/status/src/main.rs b/services/status/src/main.rs index ee6261317..a23571f21 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -153,6 +153,7 @@ fn wrapped_main() -> ! { // ------------------ acquire the status canvas GID let xns = xous_names::XousNames::new().unwrap(); + let early_settings = early_settings::EarlySettings::new(&xns).unwrap(); // 1 connection exactly -- from the GAM to set our canvas GID let status_gam_getter = xns .register_name(SERVER_NAME_STATUS_GID, Some(1)) @@ -626,6 +627,29 @@ fn wrapped_main() -> ! { #[cfg(any(feature="precursor", feature="renode"))] llio.clear_wakeup_alarm().unwrap(); // this is here to clear any wake-up alarms that were set by a prior coldboot command + // get the last status + let must_sleep = early_settings.early_sleep().unwrap(); + + // reset it for good measure + early_settings.set_early_sleep(false).unwrap(); + + if must_sleep { + while ((llio.adc_vbus().unwrap() as u32) * 503) > 150_000 { + modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG), None).expect("couldn't notify that power is plugged in"); + } + + match susres.initiate_suspend() { + Ok(_) => {}, + Err(xous::Error::Timeout) => { + // TODO: maybe this branch needs a different log message/flow? + modals.show_notification(t!("suspend.fail", xous::LANG), None).unwrap(); + } + Err(_e) => { + panic!("Unhandled error on suspend request"); + } + } + } + // spawn a thread to auto-mount the PDDB let _ = thread::spawn({ move || { @@ -1103,6 +1127,10 @@ fn wrapped_main() -> ! { if !pddb.try_unmount() { // sync the pddb prior to lock modals.show_notification(t!("socup.unmount_fail", xous::LANG), None).ok(); } else { + early_settings.set_early_sleep(true).unwrap(); + + log::info!("forcing sleep on reboot"); + pddb.pddb_halt(); susres.reboot(true).expect("couldn't issue reboot command"); } From 7062c460328fa3ebf732b2fafdb092abff090887 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Mon, 24 Apr 2023 20:18:57 +0200 Subject: [PATCH 4/9] document how everything works a little more --- services/early_settings/README.md | 6 +++-- services/early_settings/src/lib.rs | 15 +++++++++++- services/early_settings/src/main.rs | 38 +++++++++++++++++++++++++---- 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/services/early_settings/README.md b/services/early_settings/README.md index 035ba2f37..a823c2d64 100644 --- a/services/early_settings/README.md +++ b/services/early_settings/README.md @@ -1,6 +1,8 @@ # `early_settings` -This crate provides a service and API to access some settings stored in the first 4096 bytes of FLASH. +This crate provides a service and API to access settings stored in the first 4096 bytes of FLASH. + +Settings stored there do not contain any personal identifiable information. Settings currently stored here: - keymap @@ -12,4 +14,4 @@ This scratch area is provided for extreme edge cases: - keymap must live here because users need to write their password in order to mount PDDB - early sleep is used in the "lock device" lifecycle, placing it here is the most convenient thing to do to achieve that use-case -If you're thinking of placing something in here please open an issue or shoot us a Matrix message on `#xous-apps:matrix.org`. \ No newline at end of file +If you're thinking of placing something in here please open an issue or shoot us a Matrix message on `#xous-apps:matrix.org`. diff --git a/services/early_settings/src/lib.rs b/services/early_settings/src/lib.rs index 8fe7a8a70..354844ada 100644 --- a/services/early_settings/src/lib.rs +++ b/services/early_settings/src/lib.rs @@ -6,9 +6,16 @@ pub const SERVER_NAME_ES: &str = "_EARLY_SETTINGS"; #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub enum Opcode { + /// Sets the keymap in early settings. SetKeymap, + + /// Retrieves keymap from early settings. GetKeymap, + + /// Retrieves the status of the early sleep flag. EarlySleep, + + /// Sets early sleep flag in early settings. SetEarlySleep, } @@ -26,6 +33,8 @@ impl EarlySettings { Ok(EarlySettings { conn }) } + /// set_keymap sets map as keymap in the early settings FLASH section. + /// No validation on map is done, use with caution. pub fn set_keymap(&self, map: usize) -> Result<(), xous::Error> { send_message( self.conn, @@ -40,6 +49,8 @@ impl EarlySettings { .map(|_| ()) } + /// get_keymap gets the keymap from the early settings FLASH section. + /// No validation is done on the return value, use with caution. pub fn get_keymap(&self) -> Result { match send_message( self.conn, @@ -50,6 +61,7 @@ impl EarlySettings { } } + /// set_early_sleep sets value in the early settings FLASH section. pub fn set_early_sleep(&self, value: bool) -> Result<(), xous::Error> { send_message( self.conn, @@ -64,6 +76,7 @@ impl EarlySettings { .map(|_| ()) } + /// early_sleep retrieves the early sleep flag from the early settings FLASH section. pub fn early_sleep(&self) -> Result { match send_message( self.conn, @@ -73,7 +86,7 @@ impl EarlySettings { 0 => Ok(false), 1 => Ok(true), _ => Ok(false), // instead of doing `value != 0` we're explicitly matching against specific values, because - // reading off FLASH can yield a true value otherwise, even if it wasn't set before + // reading off FLASH can yield a true value otherwise, even if it wasn't set before }, _ => Err(xous::Error::InternalError), } diff --git a/services/early_settings/src/main.rs b/services/early_settings/src/main.rs index 2328110d4..3f99428c8 100644 --- a/services/early_settings/src/main.rs +++ b/services/early_settings/src/main.rs @@ -1,8 +1,36 @@ +use std::ops::Range; + use early_settings::{Opcode, SERVER_NAME_ES}; use num_traits::FromPrimitive; use spinor::Spinor; use xous::{msg_blocking_scalar_unpack, MemoryRange}; +/* +!!!! EARLY SETTINGS ALLOCATED SLOTS !!!! + +If you'll ever need a data slot in the early settings FLASH section, +please document it here for reference and use the Slot struct! + +Thanks! + +Keymap: offset 0, size 4 +Early sleep: offset 4, size 4 +*/ + +const KEYMAP: Slot = Slot { offset: 0, size: 4 }; +const EARLY_SLEEP: Slot = Slot { offset: 4, size: 4 }; + +struct Slot { + offset: u32, + size: u32, +} + +impl Slot { + fn range(&self) -> Range { + (self.offset as usize)..((self.offset + self.size) as usize) + } +} + struct State { settings_page: MemoryRange, spinor: Spinor, @@ -31,13 +59,13 @@ fn main() -> ! { .expect("can't register server"); loop { - let msg = xous::receive_message(sid).unwrap(); // this blocks until we get a message + let msg = xous::receive_message(sid).unwrap(); log::trace!("Message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(Opcode::GetKeymap) => { let settings: &[u8] = state.settings_page.as_slice(); - let code = u32::from_le_bytes(settings[..4].try_into().unwrap()); + let code = u32::from_le_bytes(settings[KEYMAP.range()].try_into().unwrap()); xous::return_scalar(msg.sender, code as usize).unwrap(); } @@ -47,7 +75,7 @@ fn main() -> ! { state .spinor - .patch(settings, xous::EARLY_SETTINGS, &code, 0) + .patch(settings, xous::EARLY_SETTINGS, &code, KEYMAP.offset) .expect("couldn't patch our keyboard code"); log::info!("writing early keymap: {}", map); @@ -60,7 +88,7 @@ fn main() -> ! { state .spinor - .patch(settings, xous::EARLY_SETTINGS, &code, 4) + .patch(settings, xous::EARLY_SETTINGS, &code, EARLY_SLEEP.offset) .expect("couldn't patch early reboot flag"); log::info!("writing must sleep on reboot: {}", value); @@ -70,7 +98,7 @@ fn main() -> ! { Some(Opcode::EarlySleep) => { let settings: &[u8] = state.settings_page.as_slice(); - let value = u32::from_le_bytes(settings[4..8].try_into().unwrap()); + let value = u32::from_le_bytes(settings[EARLY_SLEEP.range()].try_into().unwrap()); log::info!("value read for early sleep: {}", value); From b10a51a3bdabe7c7f414608d1fe6a546840912d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Mon, 24 Apr 2023 20:19:12 +0200 Subject: [PATCH 5/9] spinor: make hosted and non-hosted `new()` signature the same --- services/spinor/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/spinor/src/lib.rs b/services/spinor/src/lib.rs index 134ab8f0e..875398dfb 100644 --- a/services/spinor/src/lib.rs +++ b/services/spinor/src/lib.rs @@ -26,7 +26,7 @@ pub struct Spinor { } impl Spinor { #[cfg(test)] - pub fn new() -> Self { + pub fn new(_: &xous_names::XousNames) -> Self { Spinor { conn: 0, token: [0, 0, 0, 0] } } @@ -805,4 +805,4 @@ mod tests { print!("wrong {:x?}\n", &EMU_FLASH.lock().unwrap()[0x27e000..0x27e100]); } -} \ No newline at end of file +} From 42bc425ca9a626858da93865f8aec7b04d6cd4cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Mon, 1 May 2023 18:25:12 +0200 Subject: [PATCH 6/9] reformat early_settings interactions so that it only writes if data is actually changed also abstract get/set off the early settings FLASH section, easier to maintain still todo: make hosted mode work again --- services/early_settings/src/main.rs | 57 ++++++++++++++--------------- services/status/src/main.rs | 12 +++--- 2 files changed, 33 insertions(+), 36 deletions(-) diff --git a/services/early_settings/src/main.rs b/services/early_settings/src/main.rs index 3f99428c8..e724993b5 100644 --- a/services/early_settings/src/main.rs +++ b/services/early_settings/src/main.rs @@ -31,11 +31,34 @@ impl Slot { } } +// TODO(gsora): implement this so that it's a no-op on hosted mode struct State { settings_page: MemoryRange, spinor: Spinor, } +impl State { + fn set(&self, data: &[u8], slot: &Slot) { + let settings: &[u8] = self.settings_page.as_slice(); + + let new_data_u32 = u32::from_le_bytes(data.try_into().unwrap()); + + if new_data_u32 == self.get(slot) { + return; + } + + self.spinor + .patch(settings, xous::EARLY_SETTINGS, &data, slot.offset) + .expect("couldn't patch slot data"); + } + + fn get(&self, slot: &Slot) -> u32 { + let settings: &[u8] = self.settings_page.as_slice(); + + u32::from_le_bytes(settings[slot.range()].try_into().unwrap()) + } +} + fn main() -> ! { log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); @@ -63,46 +86,20 @@ fn main() -> ! { log::trace!("Message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(Opcode::GetKeymap) => { - let settings: &[u8] = state.settings_page.as_slice(); - - let code = u32::from_le_bytes(settings[KEYMAP.range()].try_into().unwrap()); - - xous::return_scalar(msg.sender, code as usize).unwrap(); + xous::return_scalar(msg.sender, state.get(&KEYMAP) as usize).unwrap(); } Some(Opcode::SetKeymap) => msg_blocking_scalar_unpack!(msg, map, _, _, _, { let code = (map as u32).to_le_bytes(); - let settings: &[u8] = state.settings_page.as_slice(); - - state - .spinor - .patch(settings, xous::EARLY_SETTINGS, &code, KEYMAP.offset) - .expect("couldn't patch our keyboard code"); - - log::info!("writing early keymap: {}", map); - + state.set(&code, &KEYMAP); xous::return_scalar(msg.sender, 0).unwrap(); }), Some(Opcode::SetEarlySleep) => msg_blocking_scalar_unpack!(msg, value, _, _, _, { let code = (value as u32).to_le_bytes(); - let settings: &[u8] = state.settings_page.as_slice(); - - state - .spinor - .patch(settings, xous::EARLY_SETTINGS, &code, EARLY_SLEEP.offset) - .expect("couldn't patch early reboot flag"); - - log::info!("writing must sleep on reboot: {}", value); - + state.set(&code, &EARLY_SLEEP); xous::return_scalar(msg.sender, 0).unwrap(); }), Some(Opcode::EarlySleep) => { - let settings: &[u8] = state.settings_page.as_slice(); - - let value = u32::from_le_bytes(settings[EARLY_SLEEP.range()].try_into().unwrap()); - - log::info!("value read for early sleep: {}", value); - - xous::return_scalar(msg.sender, value as usize).unwrap(); + xous::return_scalar(msg.sender, state.get(&EARLY_SLEEP) as usize).unwrap(); } _ => log::warn!("unrecognized opcode"), } diff --git a/services/status/src/main.rs b/services/status/src/main.rs index a23571f21..8c1b9f494 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -629,11 +629,11 @@ fn wrapped_main() -> ! { // get the last status let must_sleep = early_settings.early_sleep().unwrap(); - - // reset it for good measure - early_settings.set_early_sleep(false).unwrap(); if must_sleep { + // reset it for good measure + early_settings.set_early_sleep(false).unwrap(); + while ((llio.adc_vbus().unwrap() as u32) * 503) > 150_000 { modals.show_notification(t!("mainmenu.cant_sleep", xous::LANG), None).expect("couldn't notify that power is plugged in"); } @@ -647,7 +647,7 @@ fn wrapped_main() -> ! { Err(_e) => { panic!("Unhandled error on suspend request"); } - } + } } // spawn a thread to auto-mount the PDDB @@ -1130,7 +1130,7 @@ fn wrapped_main() -> ! { early_settings.set_early_sleep(true).unwrap(); log::info!("forcing sleep on reboot"); - + pddb.pddb_halt(); susres.reboot(true).expect("couldn't issue reboot command"); } @@ -1605,4 +1605,4 @@ fn bars(g: &gam::Gam, g.draw_list(dl).unwrap(); -} \ No newline at end of file +} From 5771294f9096a0f929e4b139d438a3bc9c45555c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Tue, 2 May 2023 15:33:17 +0200 Subject: [PATCH 7/9] document EarlySettings by including README.md Also make sure to capitalise its method properly. --- services/early_settings/src/lib.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/early_settings/src/lib.rs b/services/early_settings/src/lib.rs index 354844ada..df62e8858 100644 --- a/services/early_settings/src/lib.rs +++ b/services/early_settings/src/lib.rs @@ -19,6 +19,7 @@ pub enum Opcode { SetEarlySleep, } +#[doc = include_str!("../README.md")] #[derive(Debug)] pub struct EarlySettings { conn: xous::CID, @@ -33,7 +34,7 @@ impl EarlySettings { Ok(EarlySettings { conn }) } - /// set_keymap sets map as keymap in the early settings FLASH section. + /// Sets map as keymap in the early settings FLASH section. /// No validation on map is done, use with caution. pub fn set_keymap(&self, map: usize) -> Result<(), xous::Error> { send_message( @@ -49,7 +50,7 @@ impl EarlySettings { .map(|_| ()) } - /// get_keymap gets the keymap from the early settings FLASH section. + /// Gets the keymap from the early settings FLASH section. /// No validation is done on the return value, use with caution. pub fn get_keymap(&self) -> Result { match send_message( @@ -61,7 +62,7 @@ impl EarlySettings { } } - /// set_early_sleep sets value in the early settings FLASH section. + /// Sets value in the early settings FLASH section. pub fn set_early_sleep(&self, value: bool) -> Result<(), xous::Error> { send_message( self.conn, @@ -76,7 +77,7 @@ impl EarlySettings { .map(|_| ()) } - /// early_sleep retrieves the early sleep flag from the early settings FLASH section. + /// Retrieves the early sleep flag from the early settings FLASH section. pub fn early_sleep(&self) -> Result { match send_message( self.conn, From 28846d69eca7285a181b5b9c8011f31124c578a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Tue, 2 May 2023 16:11:25 +0200 Subject: [PATCH 8/9] do not crash hosted mode --- services/early_settings/src/main.rs | 41 +++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/services/early_settings/src/main.rs b/services/early_settings/src/main.rs index e724993b5..934afc34a 100644 --- a/services/early_settings/src/main.rs +++ b/services/early_settings/src/main.rs @@ -31,15 +31,19 @@ impl Slot { } } -// TODO(gsora): implement this so that it's a no-op on hosted mode struct State { - settings_page: MemoryRange, + settings_page: Option, spinor: Spinor, } impl State { fn set(&self, data: &[u8], slot: &Slot) { - let settings: &[u8] = self.settings_page.as_slice(); + let settings = match self.settings_page { + Some(page) => page, + None => return, + }; + + let settings: &[u8] = settings.as_slice(); let new_data_u32 = u32::from_le_bytes(data.try_into().unwrap()); @@ -53,7 +57,12 @@ impl State { } fn get(&self, slot: &Slot) -> u32 { - let settings: &[u8] = self.settings_page.as_slice(); + let settings = match self.settings_page { + Some(page) => page, + None => return 0, + }; + + let settings: &[u8] = settings.as_slice(); u32::from_le_bytes(settings[slot.range()].try_into().unwrap()) } @@ -67,13 +76,7 @@ fn main() -> ! { let xns = xous_names::XousNames::new().unwrap(); let state = State { - settings_page: xous::syscall::map_memory( - xous::MemoryAddress::new((xous::EARLY_SETTINGS + xous::FLASH_PHYS_BASE) as usize), - None, - 4096, - xous::MemoryFlags::R, - ) - .unwrap(), + settings_page: page_provider(), spinor: spinor::Spinor::new(&xns).unwrap(), }; @@ -105,3 +108,19 @@ fn main() -> ! { } } } + +fn page_provider() -> Option { + #[cfg(not(target_os = "xous"))] + return None; + + #[cfg(target_os = "xous")] + return Some( + xous::syscall::map_memory( + xous::MemoryAddress::new((xous::EARLY_SETTINGS + xous::FLASH_PHYS_BASE) as usize), + None, + 4096, + xous::MemoryFlags::R, + ) + .unwrap(), + ); +} From 183723b38543e433b45731657d2ceb0e05d11293 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Tue, 2 May 2023 16:16:27 +0200 Subject: [PATCH 9/9] update xous-ipc, xous Cargo.lock version --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 388542900..4c29292a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1164,12 +1164,12 @@ dependencies = [ "rkyv", "spinor", "utralib", - "xous 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)", + "xous 0.9.41 (registry+https://github.com/rust-lang/crates.io-index)", "xous-api-log", "xous-api-names", "xous-api-susres", "xous-api-ticktimer", - "xous-ipc 0.9.40 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-ipc 0.9.41 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]]