From cc0f37a80e91dad20ad65c47c0f5fd185b949957 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 17 Jul 2021 02:04:22 +0800 Subject: [PATCH] rewrite the spinor services - you can only "patch" regions of memory. caller provides a slice to the region of data they are patching, so that patches can be computed by the lib-side code of the server. - erasing is done with a "patch" with all 0xff's as the write data. a sequence of pure 0xff for a page does not actually cause a write, the condition is detected and the write is skipped after an erase. - patches attempt to be somewhat intelligent and not re-write unchnaged data, or erase blocks that don't need udpating. However, if a user submits a "sparse patch" with just a couple bytes modified in a megabyte region they can expect bad performance. Ideally, in that scenario, each of the smaller modifications are submitted as individual calls to the patch function, instead of regurgitating all the data and hoping that hthe patch function does some intelligent diffing to be as light-fingered as possible about updating the flash. In other words, the onus is on the calling server to format patches intelligently. The patch server does only the simplest, safest optimizations. You don't want to be shuttling megabytes of redundant data anyways between servers for many other reasons....! --- services/spinor/src/api.rs | 18 ++- services/spinor/src/lib.rs | 220 ++++++++++++++++++++--------- services/spinor/src/main.rs | 275 ++++++++++++++++++++++++------------ xous-rs/src/definitions.rs | 26 ++-- 4 files changed, 354 insertions(+), 185 deletions(-) diff --git a/services/spinor/src/api.rs b/services/spinor/src/api.rs index 3cc469665..597941ca9 100644 --- a/services/spinor/src/api.rs +++ b/services/spinor/src/api.rs @@ -1,23 +1,27 @@ pub(crate) const SERVER_NAME_SPINOR: &str = "_SPINOR Hardware Interface Server_"; pub const SPINOR_SIZE_BYTES: u32 = 128 * 1024 * 1024; // physical size of the device, used for hardware sanity checks on requests +pub const SPINOR_ERASE_SIZE: u32 = 0x1000; // this is the smallest sector size. 64k sectors also exist, but this implementation does not use them. // note: logical lengths of regions are in xous::definitions #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] pub(crate) enum Opcode { - /// erase a region. The whole op is atomic, so no exclusivity is required. - EraseRegion, - /// writes are split into multiple transactions. Must acquire exclusive rights before initiation AcquireExclusive, ReleaseExclusive, - /// program a region + /// a special token is reserved for writing to the SoC region, only one service is allowed to do that + RegisterSocToken, + /// program a region. Erase is accomplished by calling WriteRegion with all 0xFF's as data. WriteRegion, /// allow the susres manager to prevent new ops from happening during a suspend AcquireSuspendLock, ReleaseSuspendLock, + /// intra-thread messages for suspend and resume + SuspendInner, + ResumeInner, + /// internal interrupt handler ops EccError, } @@ -45,8 +49,8 @@ pub struct WriteRegion { pub id: [u32; 4], /// start address for the write; address 0 is start of FLASH. pub start: u32, - /// if true, erase the region to write if not already erased; otherwise, if not erased, the routine will error out - pub autoerase: bool, + /// set if the sector was checked to be erased already + pub clean_patch: bool, /// data to write - up to one page pub data: [u8; 4096], /// length of data to write @@ -65,8 +69,10 @@ pub enum SpinorError { VerifyFailed, InvalidRequest, ImplementationError, + AlignmentError, IpcError, BusyTryAgain, IdMismatch, NoId, + AccessDenied, } diff --git a/services/spinor/src/lib.rs b/services/spinor/src/lib.rs index 035c12091..88b2bd1a7 100644 --- a/services/spinor/src/lib.rs +++ b/services/spinor/src/lib.rs @@ -31,27 +31,25 @@ impl Spinor { /// this returns the minimum alignment for an erase block. `write` and `erase` operations /// benefit in performance if the requests are aligned to this number. pub fn erase_alignment(&self) -> u32 { - 0x1000 + SPINOR_ERASE_SIZE } - // convenience function to wrap the IPC mess into a single function, but it makes some key assumptions: - // - caller guarantees that the length of data is less than 4096 bytes - // - caller also guarantees we have the exclusive lock to do this op - fn write_page(&mut self, data: &[u8], start_addr: u32) -> Result<(), SpinorError> { - assert!(data.len() <= 4096, "Assumption of write_page() helper was violated by library code."); + /// this function needs to be called by the "one true" authorized updater for the SOC gateware region + /// it must be called very early in the boot process, while we are still in the fully trusted code zone + /// This registers that server as the only server which is authorized to request a patch to the SOC gateware region. + /// later on, anyone is welcome to try to call it; it will have no effect. + pub fn register_soc_token(&self) -> Result<(), xous::Error> { + send_message(self.conn, + Message::new_scalar(Opcode::RegisterSocToken.to_usize().unwrap(), + self.token[0] as usize, + self.token[1] as usize, + self.token[2] as usize, + self.token[3] as usize, + )).map(|_| ()) + } - let mut wr = WriteRegion { - id: self.token, - start: start_addr, - autoerase: true, - data: [0; 4096], - len: data.len() as u32, - result: None, - }; - for (&src, dst) in data.iter().zip(wr.data.iter_mut()) { - *dst = src; - } - let mut buf = Buffer::into_buf(wr).or(Err(SpinorError::IpcError))?; + fn send_write_region(&mut self, wr: &WriteRegion) -> Result<(), SpinorError> { + let mut buf = Buffer::into_buf(*wr).or(Err(SpinorError::IpcError))?; buf.lend_mut(self.conn, Opcode::WriteRegion.to_u32().unwrap()).or(Err(SpinorError::IpcError))?; match buf.to_original::() { @@ -69,14 +67,42 @@ impl Spinor { } } - /// REWORK THIS to take the source data, the patch data, and the offset. + /* + cases to check: + - mis-aligned start address + - mis-aligned end address + - mis-aligned start and end address + - aligned start and end address - /// note: this implementation will write precisely the slice of u8 contained - /// in data starting from start_addr. If the request is not aligned, the - /// operation is "expensive" in that it will make a copy of the misaligned edges, - /// erase the entire sectors underneath, and then re-write the data that was adjacent - /// to the write data - pub fn write(&mut self, data: &[u8], start_addr: u32) -> Result<(), SpinorError> { + - patch of data into a mostly pre-erased sector with existing data, but into the already-erased section + - the above, but where the patch length goes beyond the length of a single sector + */ + + /// `patch` is an extremely low-level function that can patch data on FLASH. Access control must be enforced by higher level + /// abstractions. However, there is a single sanity check on the server side that prevents rogue writes to the SoC gateware area. + /// Aside from that, it's the wild west! Think of this as `dd` into a raw disk device node, and not a filesystem-abstracted `write` + /// `region` is a slice that points to the ostensible region that we have access to, and wish to patch + /// `region_base` is the base address of `region`, given as an offset from base of FLASH (that is, physical address minus 0x2000_0000) + /// this *must* be aligned to an erase sector. + /// `patch_data` is a slice that contains exactly the data we want to have patched into FLASH. If you're lazy and you just send a large + /// amount of unchanged data with a couple small changes scattered about, this will not be "smart" about it and do a diff and + /// optimally patch sub-regions. It will erase and re-write the entire region included in the patch. It must also be a multiple + /// of two u8s in length, because the DDR interface can only tranfer even multiples of bytes. + /// `patch_index` is the offset relative to the base address of `region` to patch. It is *not* relative to the base of FLASH, + /// it is relative to the base of `region`. You can think of it as the index into the `region` slice where the patch data should go. + /// patch_index /can/ have an odd byte offset, but it will still need to write at a minimum two bytes of data starting at the odd + /// byte offset. + /// Notes: + /// - the server will entirely skip writing over 256-byte pages that are blank. So, if the goal is to erase a region, + /// call patch with data of all 0xFF - this will effectively only do an erase, but no subsequent writes. + pub fn patch(&mut self, region: &[u8], region_base: u32, patch_data: &[u8], patch_index: u32) -> Result<(), SpinorError> { + let align_mask = self.erase_alignment() - 1; + if (region_base & align_mask) != 0 { + return Err(SpinorError::AlignmentError); + } + if patch_data.len() % 2 != 0 { + return Err(SpinorError::AlignmentError); + } // acquire a write lock on the unit let response = send_message(self.conn, Message::new_blocking_scalar(Opcode::AcquireExclusive.to_usize().unwrap(), @@ -92,30 +118,108 @@ impl Spinor { } } - let align_mask = self.erase_alignment() - 1; + // pre-allocate a buffer that we'll use repeatedly to communicate with the server + let mut wr = WriteRegion { + id: self.token, + start: 0, + data: [0xFF; 4096], + len: 0, + result: None, + clean_patch: false, + }; + // snap the patch index to the next nearest lower erase block boundary + let patch_index_aligned = patch_index & !align_mask; + let patch_pre_pad = patch_index - patch_index_aligned; + // add the alignment difference to the total length + let mut patch_len_aligned = patch_data.len() as u32 + patch_pre_pad; + // if the total length is not aligned to an erase block, add the padding up until the next erase block + if patch_len_aligned & align_mask != 0 { + patch_len_aligned += self.erase_alignment() - patch_len_aligned & align_mask; + } + + let mut cur_index = patch_index_aligned; + let mut cur_patch_index = 0; let mut ret: Result<(), SpinorError> = Ok(()); - let mut req_addr = start_addr; - if req_addr & align_mask != 0 { - let u8_to_alignment = self.erase_alignment() - (req_addr & align_mask); - if u8_to_alignment < self.erase_alignment() { - // can't align anything, data is smaller than a page - ret = self.write_page(data, req_addr); - } else { - // issue one mis-aligned request first; this will trigger a partial erase and re-write - self.write_page(&data[0..u8_to_alignment as usize], req_addr)?; - req_addr += u8_to_alignment; - // now send the rest as aligned; this is much more efficient than streaming a bunch of mis-aligned pages - for page in data[u8_to_alignment as usize..].chunks(self.erase_alignment() as usize).into_iter() { - self.write_page(page, req_addr)?; - req_addr += self.erase_alignment(); + for sector in region[patch_index_aligned as usize ..(patch_index_aligned + patch_len_aligned) as usize].chunks_exact(self.erase_alignment() as usize).into_iter() { + // we get chunks instead of chunks_exact() as we /want/ to catch errors in computing alignments + assert!(sector.len() as u32 == self.erase_alignment(), "alignment masks not computed correctly"); + + // check to see if the region we're writing is already erased; if so, just send the data that needs patching + let mut check_index = cur_index; + let mut check_patch_index = cur_patch_index; + let mut data_index = 0; + let mut erased = true; + let mut patch_start: Option = None; + let mut patch_dirty = false; + for &rom_byte in sector.iter() { + if !((check_index < check_patch_index) || (check_index >= (check_patch_index + patch_data.len() as u32))) { + if rom_byte != patch_data[check_patch_index as usize] { + patch_dirty = true; + } + if rom_byte != 0xFF { + erased = false; + break; // skip this loop and go to the full-sector replace version + } + if patch_start.is_none() { + patch_start = Some(check_index + region_base); + } + // we're actually in a data region to be patched + wr.data[data_index] = patch_data[check_patch_index as usize]; + data_index += 1; + check_patch_index += 1; } + check_index += 1; } - } else { - // the request is aligned, just issue it; the last page, if mis-aligned, might be a little ugly, but nothing we can do about it. - for page in data.chunks(self.erase_alignment() as usize) { - self.write_page(page, req_addr)?; - req_addr += self.erase_alignment(); + + if erased && patch_dirty { + wr.clean_patch = true; + wr.start = patch_start.expect("check region did not intersect patch region; this shouldn't be possible."); + wr.len = data_index as u32; + ret = self.send_write_region(&wr); + if ret.is_err() { + break; + } + cur_index = check_index; + cur_patch_index = check_patch_index; + } else { + // the sector needs erasing first, assemble the primitives accordingly + + wr.start = cur_index + region_base; + // load WriteRegion with one sector of data: + // - copy from original region for pre-pad data + // - if we're in the patch region, copy the patch_data + // - after the patch region, copy the pre-pad data + let mut dirty = false; + let mut first_patch_addr: Option = None; + for (&src, dst) in sector.iter().zip(wr.data.iter_mut()) { + if (cur_index < patch_index) || (cur_index >= (patch_index + patch_data.len() as u32)) { + *dst = src; + } else { + if src != patch_data[cur_patch_index as usize] { + dirty = true; + if first_patch_addr.is_none() { + first_patch_addr = Some(cur_index + region_base); + } + } + *dst = patch_data[cur_patch_index as usize]; + cur_patch_index += 1; + } + cur_index += 1; + } + wr.len = sector.len() as u32; + wr.result = None; + wr.clean_patch = false; + assert!(wr.start & align_mask == 0, "write became misaligned"); + + // if the requested patch data happens to be identical to the existing data already, don't even send + // the request. + if dirty { + ret = self.send_write_region(&wr); + if ret.is_err() { + break; // abort fast if we encounter an error + } + } } } @@ -123,34 +227,10 @@ impl Spinor { let _ = send_message(self.conn, Message::new_blocking_scalar(Opcode::ReleaseExclusive.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't send ReleaseExclusive message"); + ret } - /// note: this implementation will erase precisely the number of u8 starting - /// at start_addr; if this is not naturally aligned to an erase block, the operation - /// is "expensive" in that it will make a copy of the misaligned sector, erase the - /// sector, and then re-write the data that was not meant to be erased! - pub fn erase(&mut self, start_addr: u32, num_u8: u32) -> SpinorError { - if start_addr & (self.erase_alignment() - 1) != 0 { - - } - let response = send_message(self.conn, - Message::new_blocking_scalar(Opcode::EraseRegion.to_usize().unwrap(), start_addr as usize, num_u8 as usize, 0, 0) - ).expect("Couldn't send erase command"); - if let xous::Result::Scalar1(result) = response { - match FromPrimitive::from_usize(result) { - Some(r) => r, - None => { - log::error!("Couldn't transform return enum: {:?}", result); - SpinorError::ImplementationError - }, - } - } else { - log::error!("unexpected return structure: {:#?}", response); - SpinorError::ImplementationError - } - } - /// these functions are intended for use by the suspend/resume manager. most functions wouldn't have a need to call this. pub fn acquire_suspend_lock(&self) -> Result { let response = send_message(self.conn, diff --git a/services/spinor/src/main.rs b/services/spinor/src/main.rs index d1380028d..35850618c 100644 --- a/services/spinor/src/main.rs +++ b/services/spinor/src/main.rs @@ -9,24 +9,6 @@ use xous_ipc::Buffer; use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack}; use core::sync::atomic::{AtomicBool, Ordering}; - -/* -OK, we have two approaches to doing this block. - -1. we own all the read pages, and third party blocks send -requests to us to patch areas - -2. we own nothing, and we can only patch areas that are pre-aligned -to word boundaries - -We should do (2). Owning everything sucks for everything else. -However, the lib.rs side would be able to take a &[u8] that -represents the readable area, and then another &[u8] that represents -the data we want patched. And then it can format the requests to the -spinor block such that everything is aligned. - -*/ - #[cfg(target_os = "none")] mod implementation { use utralib::generated::*; @@ -37,7 +19,7 @@ mod implementation { enum FlashOp { EraseSector(u32), // 4k sector - WritePage(u32, [u8; 256], u8), // page, data, len + WritePages(u32, [u8; 4096], usize), // page address, data, len ReadId, } @@ -48,11 +30,89 @@ mod implementation { let mut result = 0; match spinor.cur_op { - Some(FlashOp::EraseSector(sector)) => { - + Some(FlashOp::EraseSector(sector_address)) => { + // enable writes: set wren mode + loop { + flash_wren(&mut spinor.csr); + let status = flash_rdsr(&mut spinor.csr, 1); + if status & 0x02 != 0 { + break; + } + } + // issue erase command + flash_se4b(&mut spinor.csr, sector_address); + // wait for WIP bit to drop + loop { + let status = flash_rdsr(&mut spinor.csr, 1); + if status & 0x01 == 0 { + break; + } + } + // get the success code for return + result = flash_rdscur(&mut spinor.csr); + // disable writes: send wrdi + if flash_rdsr(&mut spinor.csr, 1) & 0x02 != 0 { + loop { + flash_wrdi(&mut spinor.csr); + let status = flash_rdsr(&mut spinor.csr, 1); + if status & 0x02 == 0 { + break; + } + } + } + flash_rdsr(&mut spinor.csr, 0); // dummy read to clear the "read lock" bit }, - Some(FlashOp::WritePage(page, data, len)) => { + Some(FlashOp::WritePages(start_addr, data, len)) => { + // assumption: data being written to is already erased (set to 0xFF) + assert!(len <= 4096, "data len is too large"); + assert!((len % 2) == 0, "data is not a multiple of 2 in length: the SPI DDR interface always requires two bytes per transfer"); + let mut cur_addr = start_addr; + for page in data[..len].chunks(256) { + // pre-fill the page fifo + let mut blank = true; + for word in page.chunks(2) { + let wdata = word[0] as u32 | ((word[1] as u32) << 8); + if wdata != 0xFFFF { + blank = false; + } + spinor.csr.wfo(utra::spinor::WDATA_WDATA, wdata); + } + if blank { + // skip over pages that are entirely blank + continue; + } + // enable writes: set wren mode + loop { + flash_wren(&mut spinor.csr); + let status = flash_rdsr(&mut spinor.csr, 1); + if status & 0x02 != 0 { + break; + } + } + // send the data to be programmed + flash_pp4b(&mut spinor.csr, cur_addr, page.len() as u32); + cur_addr += page.len() as u32; + while (flash_rdsr(&mut spinor.csr, 1) & 0x01) != 0 { + // wait while WIP is set + } + // get the success code for return + result = flash_rdscur(&mut spinor.csr); + if result & 0x20 != 0 { + break; // abort if error + } + } + // disable writes: send wrdi + if flash_rdsr(&mut spinor.csr, 1) & 0x02 != 0 { + loop { + flash_wrdi(&mut spinor.csr); + let status = flash_rdsr(&mut spinor.csr, 1); + if status & 0x02 == 0 { + break; + } + } + } + flash_rdsr(&mut spinor.csr, 0); // dummy read to clear the "read lock" bit }, Some(FlashOp::ReadId) => { let upper = flash_rdid(&mut spinor.csr, 2); @@ -155,6 +215,7 @@ mod implementation { while csr.rf(utra::spinor::STATUS_WIP) != 0 {} } + #[allow(dead_code)] fn flash_be4b(csr: &mut utralib::CSR, block_address: u32) { csr.wfo(utra::spinor::CMD_ARG_CMD_ARG, block_address); csr.wo(utra::spinor::COMMAND, @@ -248,10 +309,11 @@ mod implementation { /// changes into the spinor interrupt handler context, which is "safe" for ROM operations because we guarantee /// we don't touch the SPINOR block inside that interrupt context - fn change_context(&mut self) -> u32 { + /// we name it with _blocking suffix to remind ourselves that this op should full-block Xous, no exceptions, until the flash op is done. + fn call_spinor_context_blocking(&mut self) -> u32 { if self.cur_op.is_none() { - log::error!("change_context called with no spinor op set. This is an internal error...panicing!"); - panic!("change_context called with no spinor op set."); + log::error!("called with no spinor op set. This is an internal error...panicing!"); + panic!("called with no spinor op set."); } self.ticktimer.ping_wdt(); SPINOR_RUNNING.store(true, Ordering::Relaxed); @@ -265,65 +327,49 @@ mod implementation { SPINOR_RESULT.load(Ordering::Relaxed) } - pub fn write_region(&mut self, wr: &mut WriteRegion) { - if wr.start + wr.len > SPINOR_SIZE_BYTES { - wr.result = Some(SpinorError::InvalidRequest); - return; + pub fn write_region(&mut self, wr: &mut WriteRegion) -> SpinorError { + if wr.start + wr.len > SPINOR_SIZE_BYTES { // basic security check. this is necessary so we don't have wrap-around attacks on the SoC gateware region + return SpinorError::InvalidRequest; } - } - pub fn erase_region(&mut self, start_adr: u32, num_u8: u32) -> SpinorError { - let mut erased = 0; + if !wr.clean_patch { + // the `lib.rs` side has ostensibly already done the following checks for us: + // - made sure there is some "dirty" data in this page + // - provided us with a copy of any existing data we want to replace after the patch within the given page + // - ensured that the request is aligned with an erase sector + let alignment_mask = SPINOR_ERASE_SIZE - 1; + if (wr.start & alignment_mask) != 0 { + return SpinorError::AlignmentError; + } + self.cur_op = Some(FlashOp::EraseSector(wr.start)); + let erase_result = self.call_spinor_context_blocking(); + if erase_result & 0x40 != 0 { + log::error!("E_FAIL set, erase failed: result 0x{:02x}, sector addr 0x{:08x}", erase_result, wr.start); + return SpinorError::EraseFailed; + } - let blocksize; - if num_u8 - erased > 4096 { - blocksize = 4096; + // now write the data sector + self.cur_op = Some(FlashOp::WritePages(wr.start, wr.data, wr.len as usize)); + let write_result = self.call_spinor_context_blocking(); + if write_result & 0x20 != 0 { + log::error!("P_FAIL set, program failed/partial abort: result 0x{:02x}, sector addr 0x{:08x}", write_result, wr.start); + return SpinorError::WriteFailed; + } + SpinorError::NoError } else { - blocksize = 65536; - } - - loop { - flash_wren()?; - let status = flash_rdsr(1)?; - // println!("WREN: FLASH status register: 0x{:08x}", status); - if status & 0x02 != 0 { - break; + // clean patch path: + // we're just patching sectors -- the caller PROMISES the data has been erased already + // this function has no way of knowing, because we don't have read priveledges... + // here, almost any data alignment and length is acceptable -- we can patch even just two bytes using + // this call. + self.cur_op = Some(FlashOp::WritePages(wr.start, wr.data, wr.len as usize)); + let write_result = self.call_spinor_context_blocking(); + if write_result & 0x20 != 0 { + log::error!("P_FAIL set, program failed/partial abort: result 0x{:02x}, sector addr 0x{:08x}", write_result, wr.start); + return SpinorError::WriteFailed; } + SpinorError::NoError } - - if blocksize <= 4096 { - flash_se4b(addr + erased as u32)?; - } else { - flash_be4b(addr + erased as u32)?; - } - erased += blocksize; - - loop { - let status = flash_rdsr(1)?; - // println!("BE4B: FLASH status register: 0x{:08x}", status); - if status & 0x01 == 0 { - break; - } - } - - let result = flash_rdscur()?; - // println!("erase result: 0x{:08x}", result); - if result & 0x60 != 0 { - error!("E_FAIL/P_FAIL set, programming may have failed.") - } - - if flash_rdsr(1)? & 0x02 != 0 { - flash_wrdi()?; - loop { - let status = flash_rdsr(1)?; - // println!("WRDI: FLASH status register: 0x{:08x}", status); - if status & 0x02 == 0 { - break; - } - } - } - - SpinorError::NoError } pub fn suspend(&mut self) { @@ -370,6 +416,8 @@ fn susres_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { let sr_cid = xous::connect(susres_sid).expect("couldn't create suspend callback connection"); let mut susres = susres::Susres::new(&xns, api::SusResOps::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + let main_cid = xns.request_connection_blocking(api::SERVER_NAME_SPINOR).expect("couldn't connect to our main thread for susres coordination"); + log::trace!("starting SPINOR suspend/resume manager loop"); loop { let msg = xous::receive_message(susres_sid).unwrap(); @@ -380,11 +428,15 @@ fn susres_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { while OP_IN_PROGRESS.load(Ordering::Relaxed) { xous::yield_slice(); } + xous::send_message(main_cid, + xous::Message::new_blocking_scalar(Opcode::SuspendInner.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't send suspend message"); if susres.suspend_until_resume(token).expect("couldn't execute suspend/resume") == false { SUSPEND_FAILURE.store(true, Ordering::Relaxed); } else { SUSPEND_FAILURE.store(false, Ordering::Relaxed); } + xous::send_message(main_cid, + xous::Message::new_blocking_scalar(Opcode::ResumeInner.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't send suspend message"); SUSPEND_PENDING.store(false, Ordering::Relaxed); }), Some(SusResOps::Quit) => { @@ -433,13 +485,36 @@ fn xmain() -> ! { xous::create_thread_4(susres_thread, sid0 as usize, sid1 as usize, sid2 as usize, sid3 as usize).expect("couldn't start susres handler thread"); let mut client_id: Option<[u32; 4]> = None; + let mut soc_token: Option<[u32; 4]> = None; let mut ecc_errors: [Option; 4] = [None, None, None, None]; // just record the first few errors, until we can get `std` and a convenient Vec/Queue loop { let mut msg = xous::receive_message(spinor_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::SuspendInner) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + spinor.suspend(); + xous::return_scalar(msg.sender, 1).unwrap(); + }), + Some(Opcode::ResumeInner) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + spinor.resume(); + xous::return_scalar(msg.sender, 1).unwrap(); + }), + Some(Opcode::RegisterSocToken) => msg_scalar_unpack!(msg, id0, id1, id2, id3, { + // only the first process to claim it can have it! + // make sure to do it correctly at boot: this must be done extremely early in the + // boot process; any attempt to access this unit for functional ops before this is registered shall panic + // this is to mitigate a DoS attack on the legitimate registrar that gives way for the incorrect + // process to grab this token + if soc_token.is_none() { + soc_token = Some([id0 as u32, id1 as u32, id2 as u32, id3 as u32]); + } + }), Some(Opcode::AcquireExclusive) => msg_blocking_scalar_unpack!(msg, id0, id1, id2, id3, { + if soc_token.is_none() { // reject any ops until a soc token is registered + xous::return_scalar(msg.sender, 0).unwrap(); + } if client_id.is_none() && !SUSPEND_PENDING.load(Ordering::Relaxed) { + OP_IN_PROGRESS.store(true, Ordering::Relaxed); // lock out suspends when the exclusive lock is acquired client_id = Some([id0 as u32, id1 as u32, id2 as u32, id3 as u32]); log::trace!("giving {:x?} an exclusive lock", client_id); SUSPEND_FAILURE.store(false, Ordering::Relaxed); @@ -450,10 +525,11 @@ fn xmain() -> ! { }), Some(Opcode::ReleaseExclusive) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { client_id = None; + OP_IN_PROGRESS.store(false, Ordering::Relaxed); xous::return_scalar(msg.sender, 1).unwrap(); }), Some(Opcode::AcquireSuspendLock) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { - if client_id.is_none() { + if client_id.is_none() && !OP_IN_PROGRESS.load(Ordering::Relaxed) { SUSPEND_PENDING.store(true, Ordering::Relaxed); xous::return_scalar(msg.sender, 1).expect("couldn't ack AcquireSuspendLock"); } else { @@ -464,23 +540,38 @@ fn xmain() -> ! { SUSPEND_PENDING.store(false, Ordering::Relaxed); xous::return_scalar(msg.sender, 1).expect("couldn't ack ReleaseSuspendLock"); }), - Some(Opcode::EraseRegion) => msg_blocking_scalar_unpack!(msg, start_adr, num_u8, _, _, { - let ret = spinor.erase_region(start_adr as u32, num_u8 as u32); - xous::return_scalar(msg.sender, ret.to_usize().unwrap()).expect("couldn't return EraseRegion response"); - }), Some(Opcode::WriteRegion) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut wr = buffer.to_original::().unwrap(); - match client_id { - Some(id) => { - if wr.id == id { - spinor.write_region(&mut wr); - } else { - wr.result = Some(SpinorError::IdMismatch); + let mut authorized = true; + if let Some(st) = soc_token { + if (wr.start >= xous::SOC_REGION_LOC) && (wr.start < xous::LOADER_LOC) { + // if only the holder of the ID that matches the SoC token can write to the SOC flash area + // other areas are not as strictly controlled because signature checks ostensibly should catch + // attempts to modify them. However, access to the gateware definition would allow one to rewrite + // the boot ROM, which would then change the trust root. Therefore, we check this region specifically. + if st != wr.id { + wr.result = Some(SpinorError::AccessDenied); + authorized = false; + } + } + } else { + // the soc token MUST be initialized early on, if not, something bad has happened. + wr.result = Some(SpinorError::AccessDenied); + authorized = false; + } + if authorized { + match client_id { + Some(id) => { + if wr.id == id { + wr.result = Some(spinor.write_region(&mut wr)); // note: this must reject out-of-bound length requests for security reasons + } else { + wr.result = Some(SpinorError::IdMismatch); + } + }, + _ => { + wr.result = Some(SpinorError::NoId); } - }, - _ => { - wr.result = Some(SpinorError::NoId); } } buffer.replace(wr).expect("couldn't return response code to WriteRegion"); diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index f1a2a7399..31db4ce58 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -11,25 +11,25 @@ pub type Connection = usize; pub const MAX_CID: usize = 34; -pub const SOC_REGION_LOC: u32 = 0x2000_0000; -pub const SOC_MAIN_GW_LOC: u32 = 0x2000_0000; +pub const SOC_REGION_LOC: u32 = 0x0000_0000; +pub const SOC_MAIN_GW_LOC: u32 = 0x0000_0000; pub const SOC_MAIN_GW_LEN: u32 = 0x0028_0000; -pub const SOC_SEC_GW_LOC: u32 = 0x2028_0000; +pub const SOC_SEC_GW_LOC: u32 = 0x0028_0000; pub const SOC_SEC_GW_LEN: u32 = 0x0028_0000; -pub const LOADER_LOC: u32 = 0x2050_0000; +pub const LOADER_LOC: u32 = 0x0050_0000; pub const LOADER_LEN: u32 = 0x0048_0000; -pub const KERNEL_LOC: u32 = 0x2098_0000; +pub const KERNEL_LOC: u32 = 0x0098_0000; pub const KERNEL_LEN: u32 = 0x0038_0000; pub const SOC_REGION_LEN: u32 = 0x00D0_0000; -pub const PDDB_LOC: u32 = 0x20D0_0000; +pub const PDDB_LOC: u32 = 0x00D0_0000; pub const PDDB_LEN: u32 = 0x0530_0000; // this reserves space for testing structures // pub const PDDB_LEN: u32 = 0x0728_0000; // length without testing structure -pub const EC_REGION_LOC: u32 = 0x27F8_0000; -pub const EC_WF200_PKG_LOC: u32 = 0x27F8_0000; +pub const EC_REGION_LOC: u32 = 0x07F8_0000; +pub const EC_WF200_PKG_LOC: u32 = 0x07F8_0000; pub const EC_WF200_PKG_LEN: u32 = 0x0004_E000; -pub const EC_FW_PKG_LOC: u32 = 0x27FC_E000; +pub const EC_FW_PKG_LOC: u32 = 0x07FC_E000; pub const EC_FW_PKG_LEN: u32 = 0x0003_2000; pub const EC_REGION_LEN: u32 = 0x0008_0000; @@ -639,14 +639,6 @@ impl MemoryRange { MemoryRange { addr, size } } - pub fn addr_in_range(&self, addr: usize) -> bool { - if (addr >= self.addr) && (add < (self.addr + self.size)) { - true - } else { - false - } - } - pub fn len(&self) -> usize { self.size.get() }