Merge branch 'main' of github.com:betrusted-io/xous-core into main

This commit is contained in:
bunnie 2023-05-03 22:54:09 +08:00
commit aa3c363548
12 changed files with 350 additions and 36 deletions

25
Cargo.lock generated
View file

@ -1146,6 +1146,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.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.41 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ecdsa"
version = "0.13.4"
@ -2124,6 +2143,7 @@ dependencies = [
name = "keyboard"
version = "0.1.0"
dependencies = [
"early_settings",
"llio",
"log",
"num-derive",
@ -2577,9 +2597,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"
@ -3922,6 +3942,7 @@ dependencies = [
"crossbeam",
"digest 0.9.0",
"dns",
"early_settings",
"gam",
"graphics-server",
"keyboard",

View file

@ -28,6 +28,7 @@ default-members = [
"services/dns",
"services/modals",
"services/usb-device-xous",
"services/early_settings",
"libs/userprefs"
]
members = [
@ -70,6 +71,7 @@ members = [
"services/net",
"services/dns",
"services/modals",
"services/early_settings",
"apps/ball",
"apps/hello",
"apps/mtxcli",

View file

@ -0,0 +1,24 @@
[package]
name = "early_settings"
version = "0.1.0"
authors = ["gsora <gsora@disroot.org>"]
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"

View file

@ -0,0 +1,17 @@
# `early_settings`
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
- 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`.

View file

@ -0,0 +1,107 @@
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 {
/// 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,
}
#[doc = include_str!("../README.md")]
#[derive(Debug)]
pub struct EarlySettings {
conn: xous::CID,
}
impl EarlySettings {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns
.request_connection_blocking(SERVER_NAME_ES)
.expect("Can't connect to EarlySettings");
Ok(EarlySettings { conn })
}
/// 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,
Message::new_blocking_scalar(
Opcode::SetKeymap.to_usize().unwrap(),
map.into(),
0,
0,
0,
),
)
.map(|_| ())
}
/// 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<usize, xous::Error> {
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),
}
}
/// Sets value in the early settings FLASH section.
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(|_| ())
}
/// Retrieves the early sleep flag from the early settings FLASH section.
pub fn early_sleep(&self) -> Result<bool, xous::Error> {
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();
}
}
}
}

View file

@ -0,0 +1,126 @@
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<usize> {
(self.offset as usize)..((self.offset + self.size) as usize)
}
}
struct State {
settings_page: Option<MemoryRange>,
spinor: Spinor,
}
impl State {
fn set(&self, data: &[u8], slot: &Slot) {
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());
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 = 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())
}
}
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: page_provider(),
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();
log::trace!("Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::GetKeymap) => {
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();
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();
state.set(&code, &EARLY_SLEEP);
xous::return_scalar(msg.sender, 0).unwrap();
}),
Some(Opcode::EarlySleep) => {
xous::return_scalar(msg.sender, state.get(&EARLY_SLEEP) as usize).unwrap();
}
_ => log::warn!("unrecognized opcode"),
}
}
}
fn page_provider() -> Option<xous::MemoryRange> {
#[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(),
);
}

View file

@ -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"]

View file

@ -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) {

View file

@ -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]);
}
}
}

View file

@ -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}

View file

@ -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();
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");
}
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");
}
@ -1577,4 +1605,4 @@ fn bars(g: &gam::Gam,
g.draw_list(dl).unwrap();
}
}

View file

@ -70,9 +70,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
&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