From 6d56f772e11eaae7495e08ba55d9c98d11e0ac09 Mon Sep 17 00:00:00 2001 From: Matous Hybl Date: Tue, 3 May 2022 16:16:37 +0200 Subject: [PATCH] Add F7 flash and bootloader support --- embassy-boot/stm32/src/lib.rs | 2 +- embassy-stm32/src/flash/f7.rs | 138 +++++++++++++++++++++++ embassy-stm32/src/flash/mod.rs | 4 +- embassy-stm32/src/lib.rs | 2 +- examples/boot/stm32f7/.cargo/config.toml | 6 + examples/boot/stm32f7/Cargo.toml | 26 +++++ examples/boot/stm32f7/README.md | 29 +++++ examples/boot/stm32f7/build.rs | 37 ++++++ examples/boot/stm32f7/flash-boot.sh | 8 ++ examples/boot/stm32f7/memory-bl.x | 18 +++ examples/boot/stm32f7/memory.x | 15 +++ examples/boot/stm32f7/src/bin/a.rs | 44 ++++++++ examples/boot/stm32f7/src/bin/b.rs | 27 +++++ examples/stm32f7/Cargo.toml | 1 + examples/stm32f7/src/bin/flash.rs | 59 ++++++++++ 15 files changed, 413 insertions(+), 3 deletions(-) create mode 100644 embassy-stm32/src/flash/f7.rs create mode 100644 examples/boot/stm32f7/.cargo/config.toml create mode 100644 examples/boot/stm32f7/Cargo.toml create mode 100644 examples/boot/stm32f7/README.md create mode 100644 examples/boot/stm32f7/build.rs create mode 100755 examples/boot/stm32f7/flash-boot.sh create mode 100644 examples/boot/stm32f7/memory-bl.x create mode 100644 examples/boot/stm32f7/memory.x create mode 100644 examples/boot/stm32f7/src/bin/a.rs create mode 100644 examples/boot/stm32f7/src/bin/b.rs create mode 100644 examples/stm32f7/src/bin/flash.rs diff --git a/embassy-boot/stm32/src/lib.rs b/embassy-boot/stm32/src/lib.rs index 82e32a97..48512534 100644 --- a/embassy-boot/stm32/src/lib.rs +++ b/embassy-boot/stm32/src/lib.rs @@ -67,7 +67,7 @@ impl BootLoader { [(); <::ACTIVE as FlashConfig>::FLASH::ERASE_SIZE]:, { match self.boot.prepare_boot(flash) { - Ok(_) => self.boot.boot_address(), + Ok(_) => embassy_stm32::flash::FLASH_BASE + self.boot.boot_address(), Err(_) => panic!("boot prepare error!"), } } diff --git a/embassy-stm32/src/flash/f7.rs b/embassy-stm32/src/flash/f7.rs new file mode 100644 index 00000000..16316fd9 --- /dev/null +++ b/embassy-stm32/src/flash/f7.rs @@ -0,0 +1,138 @@ +use core::convert::TryInto; +use core::ptr::write_volatile; + +use atomic_polyfill::{fence, Ordering}; + +use crate::flash::Error; +use crate::pac; + +pub(crate) unsafe fn lock() { + pac::FLASH.cr().modify(|w| w.set_lock(true)); +} + +pub(crate) unsafe fn unlock() { + pac::FLASH.keyr().write(|w| w.set_key(0x4567_0123)); + pac::FLASH.keyr().write(|w| w.set_key(0xCDEF_89AB)); +} + +pub(crate) unsafe fn blocking_write(offset: u32, buf: &[u8]) -> Result<(), Error> { + pac::FLASH.cr().write(|w| { + w.set_pg(true); + w.set_psize(pac::flash::vals::Psize::PSIZE32); + }); + + let ret = { + let mut ret: Result<(), Error> = Ok(()); + let mut offset = offset; + for chunk in buf.chunks(super::WRITE_SIZE) { + for val in chunk.chunks(4) { + write_volatile( + offset as *mut u32, + u32::from_le_bytes(val[0..4].try_into().unwrap()), + ); + offset += val.len() as u32; + + // prevents parallelism errors + fence(Ordering::SeqCst); + } + + ret = blocking_wait_ready(); + if ret.is_err() { + break; + } + } + ret + }; + + pac::FLASH.cr().write(|w| w.set_pg(false)); + + ret +} + +pub(crate) unsafe fn blocking_erase(from: u32, to: u32) -> Result<(), Error> { + let start_sector = if from >= (super::FLASH_BASE + super::ERASE_SIZE / 2) as u32 { + 4 + (from - super::FLASH_BASE as u32) / super::ERASE_SIZE as u32 + } else { + (from - super::FLASH_BASE as u32) / (super::ERASE_SIZE as u32 / 8) + }; + + let end_sector = if to >= (super::FLASH_BASE + super::ERASE_SIZE / 2) as u32 { + 4 + (to - super::FLASH_BASE as u32) / super::ERASE_SIZE as u32 + } else { + (to - super::FLASH_BASE as u32) / (super::ERASE_SIZE as u32 / 8) + }; + + for sector in start_sector..end_sector { + let ret = erase_sector(sector as u8); + if ret.is_err() { + return ret; + } + } + + Ok(()) +} + +unsafe fn erase_sector(sector: u8) -> Result<(), Error> { + pac::FLASH.cr().modify(|w| { + w.set_ser(true); + w.set_snb(sector) + }); + + pac::FLASH.cr().modify(|w| { + w.set_strt(true); + }); + + let ret: Result<(), Error> = blocking_wait_ready(); + + pac::FLASH.cr().modify(|w| w.set_ser(false)); + + clear_all_err(); + + ret +} + +pub(crate) unsafe fn clear_all_err() { + pac::FLASH.sr().modify(|w| { + if w.erserr() { + w.set_erserr(true); + } + if w.pgperr() { + w.set_pgperr(true); + } + if w.pgaerr() { + w.set_pgaerr(true); + } + if w.wrperr() { + w.set_wrperr(true); + } + if w.eop() { + w.set_eop(true); + } + }); +} + +pub(crate) unsafe fn blocking_wait_ready() -> Result<(), Error> { + loop { + let sr = pac::FLASH.sr().read(); + + if !sr.bsy() { + if sr.erserr() { + return Err(Error::Seq); + } + + if sr.pgperr() { + return Err(Error::Parallelism); + } + + if sr.pgaerr() { + return Err(Error::Unaligned); + } + + if sr.wrperr() { + return Err(Error::Protected); + } + + return Ok(()); + } + } +} diff --git a/embassy-stm32/src/flash/mod.rs b/embassy-stm32/src/flash/mod.rs index 8b2a7711..8efbe476 100644 --- a/embassy-stm32/src/flash/mod.rs +++ b/embassy-stm32/src/flash/mod.rs @@ -16,6 +16,7 @@ const FLASH_END: usize = FLASH_BASE + FLASH_SIZE; #[cfg_attr(any(flash_wl, flash_wb, flash_l0, flash_l1, flash_l4), path = "l.rs")] #[cfg_attr(flash_f3, path = "f3.rs")] +#[cfg_attr(flash_f7, path = "f7.rs")] mod family; pub struct Flash<'d> { @@ -75,7 +76,7 @@ impl<'d> Flash<'d> { if to < from || to as usize > FLASH_END { return Err(Error::Size); } - if from as usize % ERASE_SIZE != 0 || to as usize % ERASE_SIZE != 0 { + if ((to - from) as usize % ERASE_SIZE) != 0 { return Err(Error::Unaligned); } @@ -104,6 +105,7 @@ pub enum Error { Seq, Protected, Unaligned, + Parallelism, } impl<'d> ErrorType for Flash<'d> { diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index 8f9b4a58..74d8ed86 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -50,7 +50,7 @@ pub mod i2c; #[cfg(crc)] pub mod crc; -#[cfg(any(flash_l0, flash_l1, flash_wl, flash_wb, flash_l4, flash_f3))] +#[cfg(any(flash_l0, flash_l1, flash_wl, flash_wb, flash_l4, flash_f3, flash_f7))] pub mod flash; pub mod pwm; #[cfg(rng)] diff --git a/examples/boot/stm32f7/.cargo/config.toml b/examples/boot/stm32f7/.cargo/config.toml new file mode 100644 index 00000000..df511452 --- /dev/null +++ b/examples/boot/stm32f7/.cargo/config.toml @@ -0,0 +1,6 @@ +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +# replace STM32F429ZITx with your chip as listed in `probe-run --list-chips` +runner = "probe-run --chip STM32F767ZITx -v" + +[build] +target = "thumbv7em-none-eabihf" diff --git a/examples/boot/stm32f7/Cargo.toml b/examples/boot/stm32f7/Cargo.toml new file mode 100644 index 00000000..857b287d --- /dev/null +++ b/examples/boot/stm32f7/Cargo.toml @@ -0,0 +1,26 @@ +[package] +authors = ["Ulf Lilleengen "] +edition = "2021" +name = "embassy-boot-stm32f7-examples" +version = "0.1.0" + +[dependencies] +embassy = { version = "0.1.0", path = "../../../embassy", features = ["nightly"] } +embassy-stm32 = { version = "0.1.0", path = "../../../embassy-stm32", features = ["unstable-traits", "nightly", "stm32f767zi", "time-driver-any", "exti"] } +embassy-boot-stm32 = { version = "0.1.0", path = "../../../embassy-boot/stm32" } +embassy-traits = { version = "0.1.0", path = "../../../embassy-traits" } + +defmt = { version = "0.3", optional = true } +defmt-rtt = { version = "0.3", optional = true } +panic-reset = { version = "0.1.1" } +embedded-hal = { version = "0.2.6" } + +cortex-m = "0.7.3" +cortex-m-rt = "0.7.0" + +[features] +defmt = [ + "dep:defmt", + "embassy-stm32/defmt", + "embassy-boot-stm32/defmt", +] diff --git a/examples/boot/stm32f7/README.md b/examples/boot/stm32f7/README.md new file mode 100644 index 00000000..bf9142a1 --- /dev/null +++ b/examples/boot/stm32f7/README.md @@ -0,0 +1,29 @@ +# Examples using bootloader + +Example for STM32F7 demonstrating the bootloader. The example consists of application binaries, 'a' +which allows you to press a button to start the DFU process, and 'b' which is the updated +application. + + +## Prerequisites + +* `cargo-binutils` +* `cargo-flash` +* `embassy-boot-stm32` + +## Usage + +``` +# Flash bootloader +./flash-boot.sh +# Build 'b' +cargo build --release --bin b +# Generate binary for 'b' +cargo objcopy --release --bin b -- -O binary b.bin +``` + +# Flash `a` (which includes b.bin) + +``` +cargo flash --release --bin a --chip STM32F767ZITx +``` diff --git a/examples/boot/stm32f7/build.rs b/examples/boot/stm32f7/build.rs new file mode 100644 index 00000000..e1da6932 --- /dev/null +++ b/examples/boot/stm32f7/build.rs @@ -0,0 +1,37 @@ +//! This build script copies the `memory.x` file from the crate root into +//! a directory where the linker can always find it at build time. +//! For many projects this is optional, as the linker always searches the +//! project root directory -- wherever `Cargo.toml` is. However, if you +//! are using a workspace or have a more complicated build setup, this +//! build script becomes required. Additionally, by requesting that +//! Cargo re-run the build script whenever `memory.x` is changed, +//! updating `memory.x` ensures a rebuild of the application with the +//! new memory settings. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Put `memory.x` in our output directory and ensure it's + // on the linker search path. + let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); + File::create(out.join("memory.x")) + .unwrap() + .write_all(include_bytes!("memory.x")) + .unwrap(); + println!("cargo:rustc-link-search={}", out.display()); + + // By default, Cargo will re-run a build script whenever + // any file in the project changes. By specifying `memory.x` + // here, we ensure the build script is only re-run when + // `memory.x` is changed. + println!("cargo:rerun-if-changed=memory.x"); + + println!("cargo:rustc-link-arg-bins=--nmagic"); + println!("cargo:rustc-link-arg-bins=-Tlink.x"); + if env::var("CARGO_FEATURE_DEFMT").is_ok() { + println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); + } +} diff --git a/examples/boot/stm32f7/flash-boot.sh b/examples/boot/stm32f7/flash-boot.sh new file mode 100755 index 00000000..86074ffa --- /dev/null +++ b/examples/boot/stm32f7/flash-boot.sh @@ -0,0 +1,8 @@ +#!/bin/bash +mv ../../../embassy-boot/stm32/memory.x ../../../embassy-boot/stm32/memory-old.x +cp memory-bl.x ../../../embassy-boot/stm32/memory.x + +cargo flash --manifest-path ../../../embassy-boot/stm32/Cargo.toml --release --features embassy-stm32/stm32f767zi --chip STM32F767ZITx --target thumbv7em-none-eabihf + +rm ../../../embassy-boot/stm32/memory.x +mv ../../../embassy-boot/stm32/memory-old.x ../../../embassy-boot/stm32/memory.x diff --git a/examples/boot/stm32f7/memory-bl.x b/examples/boot/stm32f7/memory-bl.x new file mode 100644 index 00000000..47f3f4d9 --- /dev/null +++ b/examples/boot/stm32f7/memory-bl.x @@ -0,0 +1,18 @@ +MEMORY +{ + /* NOTE 1 K = 1 KiBi = 1024 bytes */ + FLASH : ORIGIN = 0x08000000, LENGTH = 256K + BOOTLOADER_STATE : ORIGIN = 0x08040000, LENGTH = 256K + ACTIVE : ORIGIN = 0x08080000, LENGTH = 256K + DFU : ORIGIN = 0x080c0000, LENGTH = 512K + RAM (rwx) : ORIGIN = 0x20000008, LENGTH = 368K + 16K +} + +__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(FLASH); +__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(FLASH); + +__bootloader_active_start = ORIGIN(ACTIVE) - ORIGIN(FLASH); +__bootloader_active_end = ORIGIN(ACTIVE) + LENGTH(ACTIVE) - ORIGIN(FLASH); + +__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(FLASH); +__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(FLASH); diff --git a/examples/boot/stm32f7/memory.x b/examples/boot/stm32f7/memory.x new file mode 100644 index 00000000..1c5537d1 --- /dev/null +++ b/examples/boot/stm32f7/memory.x @@ -0,0 +1,15 @@ +MEMORY +{ + /* NOTE 1 K = 1 KiBi = 1024 bytes */ + BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 256K + BOOTLOADER_STATE : ORIGIN = 0x08040000, LENGTH = 256K + FLASH : ORIGIN = 0x08080000, LENGTH = 256K + DFU : ORIGIN = 0x080c0000, LENGTH = 512K + RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 368K + 16K +} + +__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER); +__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(BOOTLOADER); + +__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(BOOTLOADER); +__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(BOOTLOADER); diff --git a/examples/boot/stm32f7/src/bin/a.rs b/examples/boot/stm32f7/src/bin/a.rs new file mode 100644 index 00000000..ca154f0a --- /dev/null +++ b/examples/boot/stm32f7/src/bin/a.rs @@ -0,0 +1,44 @@ +#![no_std] +#![no_main] +#![feature(type_alias_impl_trait)] + +use embassy_boot_stm32::FirmwareUpdater; +use embassy_stm32::exti::ExtiInput; +use embassy_stm32::flash::Flash; +use embassy_stm32::gpio::{Input, Level, Output, Pull, Speed}; +use embassy_stm32::Peripherals; +use embassy_traits::adapter::BlockingAsync; +use panic_reset as _; + +#[cfg(feature = "defmt-rtt")] +use defmt_rtt::*; + +static APP_B: &[u8] = include_bytes!("../../b.bin"); + +#[embassy::main] +async fn main(_s: embassy::executor::Spawner, p: Peripherals) { + let flash = Flash::unlock(p.FLASH); + let mut flash = BlockingAsync::new(flash); + + let button = Input::new(p.PC13, Pull::Down); + let mut button = ExtiInput::new(button, p.EXTI13); + + let mut led = Output::new(p.PB7, Level::Low, Speed::Low); + led.set_high(); + + let mut updater = FirmwareUpdater::default(); + button.wait_for_rising_edge().await; + let mut offset = 0; + let mut buf: [u8; 256 * 1024] = [0; 256 * 1024]; + for chunk in APP_B.chunks(256 * 1024) { + buf[..chunk.len()].copy_from_slice(chunk); + updater + .write_firmware(offset, &buf, &mut flash, 2048) + .await + .unwrap(); + offset += chunk.len(); + } + updater.update(&mut flash).await.unwrap(); + led.set_low(); + cortex_m::peripheral::SCB::sys_reset(); +} diff --git a/examples/boot/stm32f7/src/bin/b.rs b/examples/boot/stm32f7/src/bin/b.rs new file mode 100644 index 00000000..ed37137f --- /dev/null +++ b/examples/boot/stm32f7/src/bin/b.rs @@ -0,0 +1,27 @@ +#![no_std] +#![no_main] +#![feature(type_alias_impl_trait)] + +use embassy::executor::Spawner; +use embassy::time::{Duration, Timer}; +use embassy_stm32::gpio::{Level, Output, Speed}; +use embassy_stm32::Peripherals; +use panic_reset as _; + +#[cfg(feature = "defmt-rtt")] +use defmt_rtt::*; + +#[embassy::main] +async fn main(_spawner: Spawner, p: Peripherals) { + Timer::after(Duration::from_millis(300)).await; + let mut led = Output::new(p.PB7, Level::High, Speed::Low); + led.set_high(); + + loop { + led.set_high(); + Timer::after(Duration::from_millis(500)).await; + + led.set_low(); + Timer::after(Duration::from_millis(500)).await; + } +} diff --git a/examples/stm32f7/Cargo.toml b/examples/stm32f7/Cargo.toml index 09a06aa7..ce0a6d48 100644 --- a/examples/stm32f7/Cargo.toml +++ b/examples/stm32f7/Cargo.toml @@ -22,6 +22,7 @@ heapless = { version = "0.7.5", default-features = false } nb = "1.0.0" rand_core = "0.6.3" critical-section = "0.2.3" +embedded-storage = "0.3.0" [dependencies.smoltcp] version = "0.8.0" diff --git a/examples/stm32f7/src/bin/flash.rs b/examples/stm32f7/src/bin/flash.rs new file mode 100644 index 00000000..9eb8e4b9 --- /dev/null +++ b/examples/stm32f7/src/bin/flash.rs @@ -0,0 +1,59 @@ +#![no_std] +#![no_main] +#![feature(type_alias_impl_trait)] + +use defmt::{info, unwrap}; +use embassy::executor::Spawner; +use embassy::time::{Duration, Timer}; +use embassy_stm32::flash::Flash; +use embassy_stm32::Peripherals; +use embedded_storage::nor_flash::{NorFlash, ReadNorFlash}; + +use defmt_rtt as _; // global logger +use panic_probe as _; + +#[embassy::main] +async fn main(_spawner: Spawner, p: Peripherals) { + info!("Hello Flash!"); + + const ADDR: u32 = 0x8_0000; + + // wait a bit before accessing the flash + Timer::after(Duration::from_millis(300)).await; + + let mut f = Flash::unlock(p.FLASH); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.read(ADDR, &mut buf)); + info!("Read: {=[u8]:x}", buf); + + info!("Erasing..."); + unwrap!(f.erase(ADDR, ADDR + 256 * 1024)); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.read(ADDR, &mut buf)); + info!("Read after erase: {=[u8]:x}", buf); + + info!("Writing..."); + unwrap!(f.write( + ADDR, + &[ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32 + ] + )); + + info!("Reading..."); + let mut buf = [0u8; 32]; + unwrap!(f.read(ADDR, &mut buf)); + info!("Read: {=[u8]:x}", buf); + assert_eq!( + &buf[..], + &[ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32 + ] + ); +}