add swap/spim writing to boot1

This commit is contained in:
bunnie 2025-10-04 00:48:23 +08:00
parent 86f0c60d95
commit 1b36c34341
5 changed files with 332 additions and 0 deletions

View file

@ -151,6 +151,11 @@ pub unsafe extern "C" fn rust_entry() -> ! {
marquee(sh1107, "Update mode");
}
// if Baosec, initialize the QPI SPI flash interface (for receiving updates)
if board_type == BoardTypeCoding::Baosec {
crate::glue::setup_spim(perclk);
}
// provide some feedback on the run state of the BIO by peeking at the program counter
// value, and provide feedback on the CPU operation by flashing the RGB LEDs.
let mut repl = crate::repl::Repl::new();
@ -249,6 +254,25 @@ pub unsafe extern "C" fn rust_entry() -> ! {
// without this, USB init will hang later on.
glue::shutdown();
// check that all pages in the SPI memory page cache have been written out
critical_section::with(|cs| {
if let Some(assembler) = &mut *crate::glue::SECTOR_TRACKER.borrow(cs).borrow_mut() {
if assembler.active_pages() > 0 {
loop {
if let Some((addr, data)) = assembler.take_next_incomplete() {
// the "holes" will just have 0 in them, which is fine for these purposes
// the primary case that triggers this is when the last sector written doesn't fill
// up a whole page.
crate::print_d!("Flushing final swap page at {:x}", addr);
crate::glue::write_spim_page(addr, data);
} else {
break;
}
}
}
}
});
// when we get to this point, there's only two options...
crate::secboot::boot_or_die();
}

View file

@ -1,12 +1,25 @@
use alloc::boxed::Box;
use core::cell::RefCell;
use core::convert::TryInto;
use bao1x_api::baosec::SPINOR_ERASE_SIZE;
use bao1x_api::*;
use bao1x_hal::board::SPIM_FLASH_IFRAM_ADDR;
use bao1x_hal::ifram::IframRange;
use bao1x_hal::iox::Iox;
use bao1x_hal::udma::*;
use bao1x_hal::usb::driver::UsbDeviceState;
use critical_section::Mutex;
use utralib::*;
use crate::platform::usb::page_defrag::PageAssembler;
use crate::uf2::Uf2Block;
use crate::usb;
pub(crate) static SECTOR: Mutex<RefCell<Uf2Sector>> = Mutex::new(RefCell::new(Uf2Sector::new(0)));
pub type PageCallback = fn(usize, Box<[u8; SPINOR_ERASE_SIZE as usize]>);
pub static SECTOR_TRACKER: Mutex<RefCell<Option<PageAssembler<PageCallback>>>> =
Mutex::new(RefCell::new(None));
// Empirically measured PORTSC when the port is unplugged. This might be a brittle way
// to detect if the device is unplugged.
@ -15,6 +28,82 @@ const DISCONNECT_STATE_HS: u32 = 0xc6b; // 11_0_0011_0_1_01_1
pub fn is_disconnected(state: u32) -> bool { state == DISCONNECT_STATE_HS || state == DISCONNECT_STATE }
pub fn setup_spim(perclk: u32) {
critical_section::with(|cs| SECTOR_TRACKER.borrow(cs).replace(Some(PageAssembler::new(write_spim_page))));
let udma_global = GlobalConfig::new();
// setup the I/O pins
let iox = Iox::new(utralib::generated::HW_IOX_BASE as *mut u32);
let channel = bao1x_hal::board::setup_memory_pins(&iox);
udma_global.clock_on(PeriphId::from(channel));
// safety: this is safe because clocks have been set up
let mut flash_spim = unsafe {
Spim::new_with_ifram(
channel,
// has to be half the clock frequency reaching the block, but
// run it as fast
// as we can run perclk
perclk / 4,
perclk / 2,
SpimClkPol::LeadingEdgeRise,
SpimClkPha::CaptureOnLeading,
SpimCs::Cs0,
0,
0,
None,
256 + 16, /* just enough space to send commands + programming
* page */
4096,
Some(6),
None,
IframRange::from_raw_parts(SPIM_FLASH_IFRAM_ADDR, SPIM_FLASH_IFRAM_ADDR, 4096 * 2),
)
};
flash_spim.mem_qpi_mode(false);
let flash_id = flash_spim.mem_read_id_flash();
crate::println_d!("flash ID (init): {:x}", flash_id);
flash_spim.mem_qpi_mode(true);
let flash_id = flash_spim.mem_read_id_flash();
crate::println_d!("QPI flash ID: {:x}", flash_id);
}
pub fn write_spim_page(addr: usize, data: Box<[u8; SPINOR_ERASE_SIZE as usize]>) {
// conjure a handle to SPIM. The function has to work through a Mutex and the structure below
// isn't safe to pass through the Mutex, so we re-create the handle here without re-initializing the
// hardware itself. This is only safe because we're sure there are no other concurrent calls trying
// to do this in this environment.
let mut flash_spim = unsafe {
Spim::from_raw_parts(
match bao1x_hal::board::SPI_MEM_CHANNEL {
SpimChannel::Channel0 => utra::udma_spim_0::HW_UDMA_SPIM_0_BASE,
SpimChannel::Channel1 => utra::udma_spim_1::HW_UDMA_SPIM_1_BASE,
SpimChannel::Channel2 => utra::udma_spim_2::HW_UDMA_SPIM_2_BASE,
SpimChannel::Channel3 => utra::udma_spim_3::HW_UDMA_SPIM_3_BASE,
},
SpimCs::Cs0,
0,
0,
None,
SpimMode::Quad,
SpimByteAlign::Disable,
IframRange::from_raw_parts(SPIM_FLASH_IFRAM_ADDR, SPIM_FLASH_IFRAM_ADDR, 4096 * 2),
256 + 16,
4096,
6,
)
};
crate::println_d!("Erasing sector at addr {:x}", addr);
flash_spim.flash_erase_sector(addr as u32);
for (page_offset, buf) in data.chunks_exact(256).enumerate() {
// crate::println_d!("writing page at {:x}: {:x?}", addr + page_offset * FLASH_PAGE_LEN, &buf[..8]);
flash_spim
.mem_flash_write_page((addr + page_offset * FLASH_PAGE_LEN) as u32, buf.try_into().unwrap());
}
}
pub fn setup() -> (UsbDeviceState, u32) {
crate::println!(
"RAM disk starts at {:x} and advertises {}kiB in length, but is actually {}kiB of storage",

View file

@ -1,3 +1,4 @@
use core::convert::TryInto;
use core::sync::atomic::Ordering;
use bao1x_hal::usb::driver::CorigineUsb;
@ -210,6 +211,32 @@ pub fn usb_ep1_bulk_out_complete(
&record.data()[..8]
);
*/
} else if record.address() as usize >= bao1x_api::SWAP_START_UF2
&& (record.address() as usize) < bao1x_api::SWAP_START_UF2 + bao1x_api::SWAP_UF2_LEN
&& record.family() == bao1x_api::BAOCHIP_1X_UF2_FAMILY
{
let spim_addr = record.address() & (bao1x_api::SWAP_UF2_LEN as u32 - 1);
/*
crate::println_d!(
"Received {} to 0x{:x}: {:x?}",
record.data().len(),
spim_addr,
&record.data()[..8]
);
*/
match critical_section::with(|cs| {
if let Some(assembler) = &mut *super::glue::SECTOR_TRACKER.borrow(cs).borrow_mut()
{
assembler.add_page(spim_addr as usize, record.data().try_into().unwrap())
} else {
Err(
"Write to swap received but no swap is available on this board. Ignoring!",
)
}
}) {
Ok(_) => (),
Err(s) => crate::println_d!("Swap update error: {}", s),
}
} else {
crate::println_d!("Invalid write address {:x}, block ignored!", record.address());
}

View file

@ -4,6 +4,7 @@ pub mod glue;
mod handlers;
pub use driver::*;
pub use handlers::*;
mod page_defrag;
use crate::irq::*;

View file

@ -0,0 +1,191 @@
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use core::mem;
const PAGE_SIZE: usize = bao1x_api::baosec::SPINOR_PAGE_LEN as usize;
const SECTOR_SIZE: usize = bao1x_api::baosec::SPINOR_ERASE_SIZE as usize;
const PAGES_PER_SECTOR: usize = PAGE_SIZE / SECTOR_SIZE;
/// Manages assembly of pages from pages
pub struct PageAssembler<F> {
/// Active pages being assembled (key is page address)
pages: BTreeMap<usize, SectorState>,
/// Callback for completed pages
on_complete: F,
}
struct SectorState {
/// The page data buffer
data: Box<[u8; SECTOR_SIZE]>,
/// Bitmap tracking which pages have been received (bit i = page i)
received_mask: u16,
}
impl SectorState {
fn new() -> Self { Self { data: Box::new([0u8; SECTOR_SIZE]), received_mask: 0 } }
/// Add a page at the given offset (0-15)
fn add_page(&mut self, page_offset: usize, data: &[u8; PAGE_SIZE]) {
debug_assert!(page_offset < PAGES_PER_SECTOR);
// Copy page data to the appropriate position
let byte_offset = page_offset * PAGE_SIZE;
self.data[byte_offset..byte_offset + PAGE_SIZE].copy_from_slice(data);
// Mark page as received
self.received_mask |= 1 << page_offset;
}
/// Check if all pages have been received
fn is_complete(&self) -> bool {
// All 16 bits should be set
self.received_mask == 0xFFFF
}
}
impl<F> PageAssembler<F>
where
F: Fn(usize, Box<[u8; SECTOR_SIZE]>),
{
pub fn new(on_complete: F) -> Self { Self { pages: BTreeMap::new(), on_complete } }
/// Process an incoming page
///
/// # Arguments
/// * `address` - The byte address where this page belongs in memory
/// * `data` - The page data (must be PAGE_SIZE bytes)
///
/// # Returns
/// * `Ok(true)` if this page completed a page
/// * `Ok(false)` if the page is still incomplete
/// * `Err(&str)` if the page is invalid
pub fn add_page(&mut self, address: usize, data: &[u8; PAGE_SIZE]) -> Result<bool, &'static str> {
// Calculate page and page offset
let page_addr = address & !(SECTOR_SIZE - 1); // Align to sector boundary
let byte_offset = address & (SECTOR_SIZE - 1); // Offset within page
// Verify page alignment
if byte_offset % PAGE_SIZE != 0 {
return Err("page not aligned to 256-byte boundary");
}
let page_offset = byte_offset / PAGE_SIZE;
// Get or create page state
let page = self.pages.entry(page_addr).or_insert_with(SectorState::new);
// Warn if page double-receive
if page.received_mask & (1 << page_offset) != 0 {
crate::println_d!("WARN: double-receive of page at {:x}", page_addr);
}
// Add the page
// crate::println_d!("Adding to page offset {:x} on page at {:x}", page_offset, page_addr);
page.add_page(page_offset, data);
// Check if page is complete
if page.is_complete() {
// Remove completed page and trigger callback
if let Some(mut completed) = self.pages.remove(&page_addr) {
// Extract the data to pass to callback
let data = mem::replace(&mut completed.data, Box::new([0u8; SECTOR_SIZE]));
// crate::println!("calling on_complete with {:x}, {:x?}", page_addr, &data[..8]);
(self.on_complete)(page_addr, data);
return Ok(true);
}
}
Ok(false)
}
/// Get the number of active (incomplete) pages
pub fn active_pages(&self) -> usize { self.pages.len() }
/// Check progress of a specific page
#[allow(dead_code)]
pub fn page_progress(&self, page_addr: usize) -> Option<(usize, usize)> {
self.pages.get(&page_addr).map(|page| {
let received = page.received_mask.count_ones() as usize;
(received, PAGES_PER_SECTOR)
})
}
/// Clear all incomplete pages (useful for error recovery)
#[allow(dead_code)]
pub fn clear(&mut self) { self.pages.clear(); }
/// Remove and return the next incomplete sector from the assembler
///
/// This method removes sectors in address order (lowest address first)
/// and returns the sector address and its current data (which may be partially filled).
///
/// # Returns
/// * `Some((address, data))` - The address and data of an incomplete sector
/// * `None` - If there are no more incomplete sectors
pub fn take_next_incomplete(&mut self) -> Option<(usize, Box<[u8; SECTOR_SIZE]>)> {
// Use pop_first() to remove the lowest address sector
// This gives predictable ordering
self.pages.pop_first().map(|(addr, mut state)| {
// Replace the data with a zero buffer to avoid double-move
let data = mem::replace(&mut state.data, Box::new([0u8; SECTOR_SIZE]));
(addr, data)
})
}
}
// Example usage
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use super::*;
#[test]
fn test_in_order_assembly() {
let mut completed_pages = Vec::new();
let mut assembler = PageAssembler::new(|addr, data| {
completed_pages.push((addr, data));
});
// Send pages in order for page at address 0x1000
for i in 0..16 {
let page = [i as u8; PAGE_SIZE];
let addr = 0x1000 + (i * PAGE_SIZE);
let completed = assembler.add_page(addr, &page).unwrap();
if i < 15 {
assert!(!completed);
} else {
assert!(completed);
}
}
assert_eq!(completed_pages.len(), 1);
assert_eq!(completed_pages[0].0, 0x1000);
}
#[test]
fn test_out_of_order_assembly() {
let mut completed_pages = Vec::new();
let mut assembler = PageAssembler::new(|addr, _data| {
completed_pages.push(addr);
});
// Send pages out of order
let indices = [15, 0, 7, 3, 11, 1, 9, 2, 14, 4, 8, 5, 13, 6, 10, 12];
for (step, &i) in indices.iter().enumerate() {
let page = [i as u8; PAGE_SIZE];
let addr = 0x2000 + (i * PAGE_SIZE);
let completed = assembler.add_page(addr, &page).unwrap();
if step < 15 {
assert!(!completed);
} else {
assert!(completed);
}
}
assert_eq!(completed_pages.len(), 1);
assert_eq!(completed_pages[0], 0x2000);
}
}