partial progress on EC updater

This commit is contained in:
bunnie 2021-05-24 04:34:50 +08:00
parent 548126d1b6
commit 7529628053
9 changed files with 428 additions and 22 deletions

View file

@ -35,6 +35,30 @@ impl Into<[usize; 2]> for BattStats {
]
}
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum FlashOp {
/// erase a region defined by (address, len)
Erase(u32, u32),
/// Send up to 1kiB of data at a time. This reduces messaging overhead and makes
/// programming more efficient, while taking full advantage of the 1280-deep receive FIFO on the EC.
/// Address + up to 4 pages. page 0 is at address, page 1 is at address + 256, etc.
/// Pages stored as None are skipped, yet the address pointer is still incremented.
Program(u32, [Option<[u8; 256]>; 4])
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum FlashResult {
Pass,
Fail,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct FlashRecord {
/// identifier to validate that we're authorized to do this
pub id: [u32; 4],
/// operation
pub op: FlashOp,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum Opcode {
/// Battery stats
@ -73,11 +97,12 @@ pub(crate) enum Opcode {
/// Request charging
RequestCharging,
/// Erase a region of EC FLASH
//FlashErase,
/// Erase or program a region of EC FLASH
FlashOp,
/// Program a page of FLASH
//FlashProgram(&'a [u8]),
/// Take the mutex on EC update operations.
/// Only one process is allowed to acquire this ever, right now, for security reasons.
FlashAcquire,
/// Checks if an updated SSID list is available
SsidCheckUpdate,

View file

@ -42,6 +42,8 @@ pub struct Com {
conn: CID,
battstats_sid: Option<xous::SID>,
ticktimer: ticktimer_server::Ticktimer,
ec_lock_id: Option<[u32; 4]>,
ec_acquired: bool,
}
impl Com {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
@ -51,6 +53,8 @@ impl Com {
conn,
battstats_sid: None,
ticktimer: ticktimer_server::Ticktimer::new().expect("Can't connect to ticktimer"),
ec_lock_id: None,
ec_acquired: false,
})
}
@ -237,7 +241,64 @@ impl Com {
}
}
// note to future self: add other event listener registrations (such as network events) here
pub fn flash_acquire(&mut self) -> Result<bool, xous::Error> {
let (id0, id1, id2, id3) = xous::create_server_id()?.to_u32();
self.ec_lock_id = Some([id0, id1, id2, id3]);
if let xous::Result::Scalar1(acquired) =
send_message(self.conn,
Message::new_blocking_scalar(Opcode::FlashAcquire.to_usize().unwrap(), id0 as usize, id1 as usize, id2 as usize, id3 as usize)).unwrap() {
if acquired != 0 {
self.ec_acquired = true;
Ok(true)
} else {
self.ec_acquired = false;
Ok(false)
}
} else {
self.ec_acquired = false;
Err(xous::Error::InternalError)
}
}
pub fn flash_erase(&mut self, addr: u32, len: u32) -> Result<bool, xous::Error> {
if !self.ec_acquired {
return Err(xous::Error::AccessDenied)
}
let flashop = api::FlashRecord {
id: self.ec_lock_id.unwrap(),
op: api::FlashOp::Erase(addr, len),
};
let mut buf = Buffer::into_buf(flashop).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::FlashOp.to_u32().unwrap()).expect("couldn't send flash erase command");
match buf.to_original().unwrap() {
api::FlashResult::Pass => {
Ok(true)
},
api::FlashResult::Fail => {
Ok(false)
}
}
}
pub fn flash_program(&mut self, addr: u32, page: [Option<[u8; 256]>; 4]) -> Result<bool, xous::Error> {
if !self.ec_acquired {
return Err(xous::Error::AccessDenied)
}
let flashop = api::FlashRecord {
id: self.ec_lock_id.unwrap(),
op: api::FlashOp::Program(addr, page)
};
let mut buf = Buffer::into_buf(flashop).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::FlashOp.to_u32().unwrap()).expect("couldn't send flash program command");
match buf.to_original().unwrap() {
api::FlashResult::Pass => {
Ok(true)
},
api::FlashResult::Fail => {
Ok(false)
}
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -297,6 +297,10 @@ fn xmain() -> ! {
let mut bl_main = 0;
let mut bl_sec = 0;
let mut flash_id: Option<[u32;4]> = None; // only one process can acquire this, and its ID is stored here.
const FLASH_LEN: u32 = 0x10_0000;
const FLASH_TIMEOUT: u32 = 250;
trace!("starting main loop");
loop {
let mut msg = xous::receive_message(com_sid).unwrap();
@ -313,6 +317,75 @@ fn xmain() -> ! {
com.txrx(ComState::BL_START.verb | (bl_main as u16) & 0x1f | (((bl_sec as u16) & 0x1f) << 5));
}
}),
Some(Opcode::FlashAcquire) => msg_blocking_scalar_unpack!(msg, id0, id1, id2, id3, {
let acquired = if flash_id.is_none() {
flash_id = Some([id0 as u32, id1 as u32, id2 as u32, id3 as u32]);
1
} else {
0
};
xous::return_scalar(msg.sender, acquired as usize).expect("couldn't acknowledge acquire message");
}),
Some(Opcode::FlashOp) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let flash_op = buffer.to_original::<api::FlashRecord, _>().unwrap();
let mut pass = false;
if let Some(id) = flash_id {
if id == flash_op.id {
match flash_op.op {
api::FlashOp::Erase(addr, len) => {
if addr < FLASH_LEN && len + addr < FLASH_LEN {
com.txrx(ComState::FLASH_ERASE.verb);
com.txrx((addr >> 16) as u16);
com.txrx(addr as u16);
com.txrx((len >> 16) as u16);
com.txrx(len as u16);
while ComState::FLASH_ACK.verb != com.wait_txrx(ComState::FLASH_WAITACK.verb, Some(FLASH_TIMEOUT)) {
xous::yield_slice();
}
pass = true;
} else {
pass = false;
}
},
api::FlashOp::Program(addr, some_pages) => {
com.txrx(ComState::FLASH_LOCK.verb);
let mut prog_ptr = addr;
// this will fill the 1280-deep FIFO with up to 4 pages of data for programming
pass = true;
for &maybe_page in some_pages.iter() {
if prog_ptr < FLASH_LEN - 256 {
if let Some(page) = maybe_page {
com.txrx(ComState::FLASH_PP.verb);
com.txrx((prog_ptr >> 16) as u16);
com.txrx(prog_ptr as u16);
for i in 0..128 {
com.txrx(page[i*2] as u16 | ((page[i*2+1] as u16) << 8));
}
}
prog_ptr += 256;
} else {
pass = false;
}
}
// wait for completion only after all 4 pages are sent
while ComState::FLASH_ACK.verb != com.wait_txrx(ComState::FLASH_WAITACK.verb, Some(FLASH_TIMEOUT)) {
xous::yield_slice();
}
com.txrx(ComState::FLASH_UNLOCK.verb);
}
}
}
} else {
pass = false;
}
let response = if pass {
api::FlashResult::Pass
} else {
api::FlashResult::Fail
};
buffer.replace(response).expect("couldn't return result on FlashOp");
}
Some(Opcode::RegisterBattStatsListener) => msg_scalar_unpack!(msg, sid0, sid1, sid2, sid3, {
let sid = xous::SID::from_u32(sid0 as _, sid1 as _, sid2 as _, sid3 as _);
let cid = Some(xous::connect(sid).unwrap());

View file

@ -90,6 +90,7 @@ mod audio; use audio::*;
mod backlight; use backlight::*;
mod accel; use accel::*;
mod sha; use sha::*;
mod ecup; use ecup::*;
mod fcc; use fcc::*;
mod pds; // dependency of the FCC file
@ -108,6 +109,7 @@ pub struct CmdEnv {
ssid_cmd: Ssid,
audio_cmd: Audio,
sha_cmd: Sha,
ecup_cmd: EcUpdate,
fcc_cmd: Fcc,
}
@ -125,6 +127,7 @@ impl CmdEnv {
};
let fcc = Fcc::new(&mut common);
let sha = Sha::new(&xns, &mut common);
let ecup = EcUpdate::new(&mut common);
CmdEnv {
common_env: common,
lastverb: String::<256>::new(),
@ -138,6 +141,7 @@ impl CmdEnv {
ssid_cmd: Ssid::new(),
audio_cmd: Audio::new(&xns),
sha_cmd: sha,
ecup_cmd: ecup,
fcc_cmd: fcc,
}
@ -165,6 +169,7 @@ impl CmdEnv {
&mut backlight_cmd,
&mut accel_cmd,
&mut self.sha_cmd,
&mut self.ecup_cmd,
&mut self.fcc_cmd,
];

View file

@ -0,0 +1,209 @@
use crate::{ShellCmdApi, CommonEnv};
use xous_ipc::String;
use core::sync::atomic::{AtomicU32, Ordering};
static CB_ID: AtomicU32 = AtomicU32::new(0);
use num_traits::*;
use engine_sha512::*;
use digest::Digest;
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum UpdateOp {
//UpdateGateware,
UpdateFirmware,
//UpdateWf200,
//ResetEc,
Quit,
}
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum UpdateResult {
PackageValid,
EraseProgress,
ProgramProgress,
EraseDone,
ProgramDone,
Abort,
}
fn validate_package(pkg: &[u8]) -> bool {
let hasher = engine_sha512::Sha512Trunc256::new(Some(FallbackStrategy::HardwareThenSoftware));
let mut temp: [u8; 4] = Default::default();
temp.copy_from_slice(&pkg[0x20..0x24]);
if temp != [0x70, 0x72, 0x65, 0x63] {
log::error!("update package does not have the correct signature");
return false;
}
temp.copy_from_slice(&pkg[0x24..0x28]);
if u32::from_le_bytes(temp) != 1 {
log::error!("update package version mismatch");
return false;
}
temp.copy_from_slice(&pkg[0x28..0x2c]);
let length = u32::from_le_bytes(temp);
hasher.update(&pkg[0x20..(length as usize + 4096)]);
let digest = hasher.finalize();
for(&stored, &computed) in pkg[..0x20].iter().zip(digest.iter()) {
if stored != computed {
log::error!("update package hash mismatch");
return false;
}
}
true
}
fn ecupdate_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
let xns = xous_names::XousNames::new().unwrap();
let com = com::Com::new(&xns).unwrap();
let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap();
let susres = susres::Susres::new_without_hook(&xns).unwrap();
let ec_package = xous::syscall::map_memory(
xous::MemoryAddress::new(xous::EC_FW_PKG_LOC as usize),
None,
xous::EC_FW_PKG_LEN as usize,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map EC firmware package memory range");
let wf_package = xous::syscall::map_memory(
xous::MemoryAddress::new(xous::EC_WF200_PKG_LOC as usize),
None,
xous::EC_WF200_PKG_LEN as usize,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).expect("couldn't map EC wf200 package memory range");
loop {
let msg = xous::receive_message(sid).unwrap();
log::debug!("EC updater got msg {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(UpdateOp::UpdateFirmware) => {
let package = unsafe{ ec_package.as_ptr() as &[u8]};
if !validate_package(package) {
log::error!("firmware package did not pass validation");
xous::send_message(callback_conn,
xous::Message::new_scalar(CB_ID.load(Ordering::Relaxed) as usize,
UpdateResult::Abort.to_usize().unwrap(),
0, 0, 0)).unwrap();
} else {
// do the update
let mut temp: [u8; 4] = Default::default();
temp.copy_from_slice(&package[0x28..0x2c]);
let length = u32::from_le_bytes(temp);
// erase
// program
// completed successfully, report the result
xous::send_message(callback_conn,
xous::Message::new_scalar(CB_ID.load(Ordering::Relaxed) as usize,
UpdateResult::ProgramDone.to_usize().unwrap(),
length as usize, 0, 0)).unwrap();
}
},
Some(UpdateOp::Quit) => {
log::info!("quitting updater thread");
break;
},
None => {
log::error!("received unknown opcode");
}
}
}
xous::destroy_server(sid).unwrap();
}
#[derive(Debug)]
pub struct EcUpdate {
start_time: Option<u64>,
update_cid: xous::CID,
in_progress: bool,
}
impl EcUpdate {
pub fn new(env: &mut CommonEnv) -> Self {
let sid = xous::create_server().unwrap();
let sid_tuple = sid.to_u32();
let cb_id = env.register_handler(String::<256>::from_str("ecup"));
CB_ID.store(cb_id, Ordering::Relaxed);
xous::create_thread_4(ecupdate_thread, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
EcUpdate {
start_time: None,
update_cid: xous::connect(sid).unwrap(),
in_progress: false,
}
}
}
impl<'a> ShellCmdApi<'a> for EcUpdate {
cmd_api!(ecup); // inserts boilerplate for command API
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
use core::fmt::Write;
let mut ret = String::<1024>::new();
let helpstring = "ecup [all] [gw] [fw] [wf200]";
let mut tokens = args.as_str().unwrap().split(' ');
if self.in_progress {
write!(ret, "Programming already in progress, can't double-initiate!").unwrap();
} else {
if let Some(sub_cmd) = tokens.next() {
match sub_cmd {
"fw" => {
self.in_progress = true;
let start = env.ticktimer.elapsed_ms();
self.start_time = Some(start);
xous::send_message(self.update_cid,
xous::Message::new_scalar(UpdateOp::UpdateFirmware.to_usize().unwrap(), 0, 0, 0, 0)
).unwrap();
write!(ret, "Starting EC firmware update").unwrap();
}
_ => {
write!(ret, "{}", helpstring).unwrap();
}
}
} else {
write!(ret, "{}", helpstring).unwrap();
}
}
Ok(Some(ret))
}
fn callback(&mut self, msg: &xous::MessageEnvelope, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
use core::fmt::Write;
log::debug!("update callback");
let mut ret = String::<1024>::new();
xous::msg_scalar_unpack!(msg, result_code, progress, total, _, {
let end = env.ticktimer.elapsed_ms();
let elapsed: f64 = (end - self.start_time.unwrap()) as f64;
match FromPrimitive::from_usize(result_code) {
UpdateResult::PackageValid => {
write!(ret, "Firmware package validated in {}ms", elapsed).unwrap();
},
UpdateResult::EraseDone => {
write!(ret, "Erase of {} bytes done", progress).unwrap();
},
UpdateResult::EraseProgress => {
write!(ret, "Erasing {:.1}% complete", (progress as f64 / total as f64) * 100.0).unwrap();
},
UpdateResult::ProgramDone => {
write!(ret, "Programming of {} bytes done in {:.1}s", progress, elapsed / 1000.0).unwrap();
self.in_progress = false;
},
UpdateResult::ProgramProgress => {
write!(ret, "Programming {:.1}% complete", (progress as f64 / total as f64) * 100.0).unwrap();
},
UpdateResult::Abort => {
write!(ret, "Programming aborted in {:.1}s due to an internal error!", elapsed / 1000.0).unwrap();
self.in_progress = false;
}
_ => write!(ret, "Got unknown update callback: {:?}", result_code).unwrap()
}
});
Ok(Some(ret))
}
}

View file

@ -8,6 +8,10 @@ pub(crate) const SERVER_NAME_EXEC_GATE: &str = "_Suspend/resume execution gate_
pub(crate) enum Opcode {
/// requests a suspend
SuspendRequest,
/// locks out suspend capability -- meant to be used only to prevent suspend during firmware updates
SuspendDeny,
/// unlocks suspend capability
SuspendAllow,
/// register a subscriber to the suspend event
/// (if you don't register, you just get suspend without any warning!)

View file

@ -67,6 +67,7 @@ impl Susres {
Message::new_scalar(Opcode::SuspendRequest.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_|())
}
pub fn suspend_until_resume(&mut self, token: usize) -> Result<bool, xous::Error> {
if self.suspend_cb_sid.is_none() { // this happens if you created without a hook
return Err(xous::Error::UseBeforeInit)
@ -95,6 +96,19 @@ impl Susres {
Err(xous::Error::InternalError)
}
}
pub fn set_suspendable(&mut self, allow_suspend: bool) -> Result<(), xous::Error> {
if allow_suspend {
send_message(self.conn,
Message::new_scalar(Opcode::SuspendAllow.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_|())
} else {
send_message(self.conn,
Message::new_scalar(Opcode::SuspendDeny.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_|())
}
}
}
fn drop_conn(sid: xous::SID) {
let cid = xous::connect(sid).unwrap();

View file

@ -525,6 +525,7 @@ fn xmain() -> ! {
let mut suspend_requested = false;
let mut timeout_pending = false;
let mut reboot_requested: bool = false;
let mut allow_suspend = true;
let mut suspend_subscribers: [Option<ScalarCallback>; 32] = [None; 32];
loop {
@ -604,24 +605,27 @@ fn xmain() -> ! {
}
}),
Some(Opcode::SuspendRequest) => {
suspend_requested = true;
// clear the resume gate
SHOULD_RESUME.store(false, Ordering::Relaxed);
RESUME_EXEC.store(false, Ordering::Relaxed);
// clear the ready to suspend flag and failed to suspend flag
for maybe_sub in suspend_subscribers.iter_mut() {
if let Some(sub) = maybe_sub {
sub.ready_to_suspend = false;
sub.failed_to_suspend = false;
};
}
// do we want to start the timeout before or after sending the notifications? hmm. 🤔
timeout_pending = true;
send_message(timeout_outgoing_conn,
Message::new_scalar(TimeoutOpcode::Run.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate timeout before suspend!");
if allow_suspend {
suspend_requested = true;
// clear the resume gate
SHOULD_RESUME.store(false, Ordering::Relaxed);
RESUME_EXEC.store(false, Ordering::Relaxed);
// clear the ready to suspend flag and failed to suspend flag
for maybe_sub in suspend_subscribers.iter_mut() {
if let Some(sub) = maybe_sub {
sub.ready_to_suspend = false;
sub.failed_to_suspend = false;
};
}
// do we want to start the timeout before or after sending the notifications? hmm. 🤔
timeout_pending = true;
send_message(timeout_outgoing_conn,
Message::new_scalar(TimeoutOpcode::Run.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate timeout before suspend!");
send_event(&suspend_subscribers);
send_event(&suspend_subscribers);
}
// denied requests just silently fail.
},
Some(Opcode::SuspendTimeout) => {
if timeout_pending {
@ -665,6 +669,12 @@ fn xmain() -> ! {
xous::return_scalar(msg.sender, 0).expect("couldn't return WasSuspendClean result");
}
}),
Some(Opcode::SuspendAllow) => {
allow_suspend = true;
},
Some(Opcode::SuspendDeny) => {
allow_suspend = false;
},
Some(Opcode::Quit) => {
break
}

View file

@ -11,6 +11,11 @@ pub type Connection = usize;
pub const MAX_CID: usize = 34;
pub const EC_WF200_PKG_LOC: u32 = 0x27F8_0000;
pub const EC_WF200_PKG_LEN: u32 = 0x4_E000;
pub const EC_FW_PKG_LOC: u32 = 0x27FC_E000;
pub const EC_FW_PKG_LEN: u32 = 0x3_2000;
#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Copy, Clone)]
pub struct MessageSender {
data: usize,