From c267cb9ab764176bc8514535f4db8ac2331e30ce Mon Sep 17 00:00:00 2001
From: Badr Bouslikhin <bouslikhin.badr@gmail.com>
Date: Tue, 6 Feb 2024 16:25:45 +0100
Subject: [PATCH] feat: enhance bootloader for multiple flash support

---
 embassy-boot/src/boot_loader.rs               | 20 ++++---
 embassy-boot/src/firmware_updater/asynch.rs   | 13 +++--
 embassy-boot/src/firmware_updater/blocking.rs | 14 +++--
 .../bootloader/stm32-dual-bank/Cargo.toml     | 57 +++++++++++++++++++
 .../boot/bootloader/stm32-dual-bank/README.md | 44 ++++++++++++++
 .../boot/bootloader/stm32-dual-bank/build.rs  | 27 +++++++++
 .../boot/bootloader/stm32-dual-bank/memory.x  | 18 ++++++
 .../bootloader/stm32-dual-bank/src/main.rs    | 53 +++++++++++++++++
 examples/boot/bootloader/stm32/src/main.rs    |  2 +-
 .../boot/bootloader/stm32wb-dfu/src/main.rs   |  4 +-
 10 files changed, 231 insertions(+), 21 deletions(-)
 create mode 100644 examples/boot/bootloader/stm32-dual-bank/Cargo.toml
 create mode 100644 examples/boot/bootloader/stm32-dual-bank/README.md
 create mode 100644 examples/boot/bootloader/stm32-dual-bank/build.rs
 create mode 100644 examples/boot/bootloader/stm32-dual-bank/memory.x
 create mode 100644 examples/boot/bootloader/stm32-dual-bank/src/main.rs

diff --git a/embassy-boot/src/boot_loader.rs b/embassy-boot/src/boot_loader.rs
index e568001bc..54ae8a34b 100644
--- a/embassy-boot/src/boot_loader.rs
+++ b/embassy-boot/src/boot_loader.rs
@@ -49,16 +49,20 @@ pub struct BootLoaderConfig<ACTIVE, DFU, STATE> {
     pub state: STATE,
 }
 
-impl<'a, FLASH: NorFlash>
+impl<'a, ActiveFlash: NorFlash, DFUFlash: NorFlash, StateFlash: NorFlash>
     BootLoaderConfig<
-        BlockingPartition<'a, NoopRawMutex, FLASH>,
-        BlockingPartition<'a, NoopRawMutex, FLASH>,
-        BlockingPartition<'a, NoopRawMutex, FLASH>,
+        BlockingPartition<'a, NoopRawMutex, ActiveFlash>,
+        BlockingPartition<'a, NoopRawMutex, DFUFlash>,
+        BlockingPartition<'a, NoopRawMutex, StateFlash>,
     >
 {
     /// Create a bootloader config from the flash and address symbols defined in the linkerfile
     // #[cfg(target_os = "none")]
-    pub fn from_linkerfile_blocking(flash: &'a Mutex<NoopRawMutex, RefCell<FLASH>>) -> Self {
+    pub fn from_linkerfile_blocking(
+        active_flash: &'a Mutex<NoopRawMutex, RefCell<ActiveFlash>>,
+        dfu_flash: &'a Mutex<NoopRawMutex, RefCell<DFUFlash>>,
+        state_flash: &'a Mutex<NoopRawMutex, RefCell<StateFlash>>,
+    ) -> Self {
         extern "C" {
             static __bootloader_state_start: u32;
             static __bootloader_state_end: u32;
@@ -73,21 +77,21 @@ impl<'a, FLASH: NorFlash>
             let end = &__bootloader_active_end as *const u32 as u32;
             trace!("ACTIVE: 0x{:x} - 0x{:x}", start, end);
 
-            BlockingPartition::new(flash, start, end - start)
+            BlockingPartition::new(active_flash, start, end - start)
         };
         let dfu = unsafe {
             let start = &__bootloader_dfu_start as *const u32 as u32;
             let end = &__bootloader_dfu_end as *const u32 as u32;
             trace!("DFU: 0x{:x} - 0x{:x}", start, end);
 
-            BlockingPartition::new(flash, start, end - start)
+            BlockingPartition::new(dfu_flash, start, end - start)
         };
         let state = unsafe {
             let start = &__bootloader_state_start as *const u32 as u32;
             let end = &__bootloader_state_end as *const u32 as u32;
             trace!("STATE: 0x{:x} - 0x{:x}", start, end);
 
-            BlockingPartition::new(flash, start, end - start)
+            BlockingPartition::new(state_flash, start, end - start)
         };
 
         Self { active, dfu, state }
diff --git a/embassy-boot/src/firmware_updater/asynch.rs b/embassy-boot/src/firmware_updater/asynch.rs
index 2e43e1cc1..5634b48d4 100644
--- a/embassy-boot/src/firmware_updater/asynch.rs
+++ b/embassy-boot/src/firmware_updater/asynch.rs
@@ -16,11 +16,14 @@ pub struct FirmwareUpdater<'d, DFU: NorFlash, STATE: NorFlash> {
 }
 
 #[cfg(target_os = "none")]
-impl<'a, FLASH: NorFlash>
-    FirmwareUpdaterConfig<Partition<'a, NoopRawMutex, FLASH>, Partition<'a, NoopRawMutex, FLASH>>
+impl<'a, DFUFlash: NorFlash, StateFlash: NorFlash>
+    FirmwareUpdaterConfig<Partition<'a, NoopRawMutex, DFUFlash>, Partition<'a, NoopRawMutex, StateFlash>>
 {
     /// Create a firmware updater config from the flash and address symbols defined in the linkerfile
-    pub fn from_linkerfile(flash: &'a embassy_sync::mutex::Mutex<NoopRawMutex, FLASH>) -> Self {
+    pub fn from_linkerfile(
+        dfu_flash: &'a embassy_sync::mutex::Mutex<NoopRawMutex, DFUFlash>,
+        state_flash: &'a embassy_sync::mutex::Mutex<NoopRawMutex, StateFlash>,
+    ) -> Self {
         extern "C" {
             static __bootloader_state_start: u32;
             static __bootloader_state_end: u32;
@@ -33,14 +36,14 @@ impl<'a, FLASH: NorFlash>
             let end = &__bootloader_dfu_end as *const u32 as u32;
             trace!("DFU: 0x{:x} - 0x{:x}", start, end);
 
-            Partition::new(flash, start, end - start)
+            Partition::new(dfu_flash, start, end - start)
         };
         let state = unsafe {
             let start = &__bootloader_state_start as *const u32 as u32;
             let end = &__bootloader_state_end as *const u32 as u32;
             trace!("STATE: 0x{:x} - 0x{:x}", start, end);
 
-            Partition::new(flash, start, end - start)
+            Partition::new(state_flash, start, end - start)
         };
 
         Self { dfu, state }
diff --git a/embassy-boot/src/firmware_updater/blocking.rs b/embassy-boot/src/firmware_updater/blocking.rs
index f1368540d..3814b6c31 100644
--- a/embassy-boot/src/firmware_updater/blocking.rs
+++ b/embassy-boot/src/firmware_updater/blocking.rs
@@ -16,12 +16,16 @@ pub struct BlockingFirmwareUpdater<'d, DFU: NorFlash, STATE: NorFlash> {
 }
 
 #[cfg(target_os = "none")]
-impl<'a, FLASH: NorFlash>
-    FirmwareUpdaterConfig<BlockingPartition<'a, NoopRawMutex, FLASH>, BlockingPartition<'a, NoopRawMutex, FLASH>>
+impl<'a, DFUFlash: NorFlash, StateFlash: NorFlash>
+    FirmwareUpdaterConfig<
+        BlockingPartition<'a, NoopRawMutex, DFUFlash>,
+        BlockingPartition<'a, NoopRawMutex, StateFlash>,
+    >
 {
     /// Create a firmware updater config from the flash and address symbols defined in the linkerfile
     pub fn from_linkerfile_blocking(
-        flash: &'a embassy_sync::blocking_mutex::Mutex<NoopRawMutex, core::cell::RefCell<FLASH>>,
+        dfu_flash: &'a embassy_sync::blocking_mutex::Mutex<NoopRawMutex, core::cell::RefCell<DFUFlash>>,
+        state_flash: &'a embassy_sync::blocking_mutex::Mutex<NoopRawMutex, core::cell::RefCell<StateFlash>>,
     ) -> Self {
         extern "C" {
             static __bootloader_state_start: u32;
@@ -35,14 +39,14 @@ impl<'a, FLASH: NorFlash>
             let end = &__bootloader_dfu_end as *const u32 as u32;
             trace!("DFU: 0x{:x} - 0x{:x}", start, end);
 
-            BlockingPartition::new(flash, start, end - start)
+            BlockingPartition::new(dfu_flash, start, end - start)
         };
         let state = unsafe {
             let start = &__bootloader_state_start as *const u32 as u32;
             let end = &__bootloader_state_end as *const u32 as u32;
             trace!("STATE: 0x{:x} - 0x{:x}", start, end);
 
-            BlockingPartition::new(flash, start, end - start)
+            BlockingPartition::new(state_flash, start, end - start)
         };
 
         Self { dfu, state }
diff --git a/examples/boot/bootloader/stm32-dual-bank/Cargo.toml b/examples/boot/bootloader/stm32-dual-bank/Cargo.toml
new file mode 100644
index 000000000..313187adc
--- /dev/null
+++ b/examples/boot/bootloader/stm32-dual-bank/Cargo.toml
@@ -0,0 +1,57 @@
+[package]
+edition = "2021"
+name = "stm32-bootloader-dual-bank-flash-example"
+version = "0.1.0"
+description = "Example bootloader for dual-bank flash STM32 chips"
+license = "MIT OR Apache-2.0"
+
+[dependencies]
+defmt = { version = "0.3", optional = true }
+defmt-rtt = { version = "0.4", optional = true }
+
+embassy-stm32 = { path = "../../../../embassy-stm32", features = [] }
+embassy-boot-stm32 = { path = "../../../../embassy-boot-stm32" }
+cortex-m = { version = "0.7.6", features = [
+  "inline-asm",
+  "critical-section-single-core",
+] }
+embassy-sync = { version = "0.5.0", path = "../../../../embassy-sync" }
+cortex-m-rt = { version = "0.7" }
+embedded-storage = "0.3.1"
+embedded-storage-async = "0.4.0"
+cfg-if = "1.0.0"
+
+[features]
+defmt = ["dep:defmt", "embassy-boot-stm32/defmt", "embassy-stm32/defmt"]
+debug = ["defmt-rtt", "defmt"]
+
+[profile.dev]
+debug = 2
+debug-assertions = true
+incremental = false
+opt-level = 'z'
+overflow-checks = true
+
+[profile.release]
+codegen-units = 1
+debug = 2
+debug-assertions = false
+incremental = false
+lto = 'fat'
+opt-level = 'z'
+overflow-checks = false
+
+# do not optimize proc-macro crates = faster builds from scratch
+[profile.dev.build-override]
+codegen-units = 8
+debug = false
+debug-assertions = false
+opt-level = 0
+overflow-checks = false
+
+[profile.release.build-override]
+codegen-units = 8
+debug = false
+debug-assertions = false
+opt-level = 0
+overflow-checks = false
diff --git a/examples/boot/bootloader/stm32-dual-bank/README.md b/examples/boot/bootloader/stm32-dual-bank/README.md
new file mode 100644
index 000000000..3de3171cd
--- /dev/null
+++ b/examples/boot/bootloader/stm32-dual-bank/README.md
@@ -0,0 +1,44 @@
+# STM32 dual-bank flash Bootloader
+
+## Overview
+
+This bootloader leverages `embassy-boot` to interact with the flash. 
+This example targets STM32 devices with dual-bank flash memory, with a primary focus on the STM32H747XI series. 
+Users must modify the `memory.x` configuration file to match with the memory layout of their specific STM32 device.
+
+Additionally, this example can be extended to utilize external flash memory, such as QSPI, for storing partitions.
+
+## Memory Configuration
+
+In this example's `memory.x` file, various symbols are defined to assist in effective memory management within the bootloader environment.  
+For dual-bank STM32 devices, it's crucial to assign these symbols correctly to their respective memory banks. 
+
+### Symbol Definitions
+
+The bootloader's state and active symbols are anchored to the flash origin of **bank 1**:
+
+- `__bootloader_state_start` and `__bootloader_state_end`
+- `__bootloader_active_start` and `__bootloader_active_end`
+
+In contrast, the Device Firmware Upgrade (DFU) symbols are aligned with the DFU flash origin in **bank 2**:
+
+- `__bootloader_dfu_start` and `__bootloader_dfu_end`
+
+```rust
+__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(**DFU**);
+__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(**DFU**);
+```
+
+## Flashing the Bootloader
+
+To flash the bootloader onto your STM32H747XI device, use the following command:
+
+```bash
+cargo flash --features embassy-stm32/stm32h747xi-cm7 --release --chip STM32H747XIHx
+```
diff --git a/examples/boot/bootloader/stm32-dual-bank/build.rs b/examples/boot/bootloader/stm32-dual-bank/build.rs
new file mode 100644
index 000000000..fd605991f
--- /dev/null
+++ b/examples/boot/bootloader/stm32-dual-bank/build.rs
@@ -0,0 +1,27 @@
+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/bootloader/stm32-dual-bank/memory.x b/examples/boot/bootloader/stm32-dual-bank/memory.x
new file mode 100644
index 000000000..665da7139
--- /dev/null
+++ b/examples/boot/bootloader/stm32-dual-bank/memory.x
@@ -0,0 +1,18 @@
+MEMORY
+{
+  /* NOTE 1 K = 1 KiBi = 1024 bytes */
+  FLASH                             : ORIGIN = 0x08000000, LENGTH = 128K
+  BOOTLOADER_STATE                  : ORIGIN = 0x08020000, LENGTH = 128K
+  ACTIVE                            : ORIGIN = 0x08040000, LENGTH = 512K
+  DFU                               : ORIGIN = 0x08100000, LENGTH = 640K
+  RAM                         (rwx) : ORIGIN = 0x24000000, LENGTH = 512K
+}
+
+__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(DFU);
+__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(DFU);
diff --git a/examples/boot/bootloader/stm32-dual-bank/src/main.rs b/examples/boot/bootloader/stm32-dual-bank/src/main.rs
new file mode 100644
index 000000000..4d2e82d26
--- /dev/null
+++ b/examples/boot/bootloader/stm32-dual-bank/src/main.rs
@@ -0,0 +1,53 @@
+#![no_std]
+#![no_main]
+
+use core::cell::RefCell;
+
+use cortex_m_rt::{entry, exception};
+#[cfg(feature = "defmt")]
+use defmt_rtt as _;
+use embassy_boot_stm32::*;
+use embassy_stm32::flash::{Flash, BANK1_REGION};
+use embassy_sync::blocking_mutex::Mutex;
+
+#[entry]
+fn main() -> ! {
+    let p = embassy_stm32::init(Default::default());
+
+    // Uncomment this if you are debugging the bootloader with debugger/RTT attached,
+    // as it prevents a hard fault when accessing flash 'too early' after boot.
+    /*
+        for i in 0..10000000 {
+            cortex_m::asm::nop();
+        }
+    */
+
+    let layout = Flash::new_blocking(p.FLASH).into_blocking_regions();
+    let flash_bank1 = Mutex::new(RefCell::new(layout.bank1_region));
+    let flash_bank2 = Mutex::new(RefCell::new(layout.bank2_region));
+
+    let config = BootLoaderConfig::from_linkerfile_blocking(&flash_bank1, &flash_bank2, &flash_bank1);
+    let active_offset = config.active.offset();
+    let bl = BootLoader::prepare::<_, _, _, 2048>(config);
+
+    unsafe { bl.load(BANK1_REGION.base + active_offset) }
+}
+
+#[no_mangle]
+#[cfg_attr(target_os = "none", link_section = ".HardFault.user")]
+unsafe extern "C" fn HardFault() {
+    cortex_m::peripheral::SCB::sys_reset();
+}
+
+#[exception]
+unsafe fn DefaultHandler(_: i16) -> ! {
+    const SCB_ICSR: *const u32 = 0xE000_ED04 as *const u32;
+    let irqn = core::ptr::read_volatile(SCB_ICSR) as u8 as i16 - 16;
+
+    panic!("DefaultHandler #{:?}", irqn);
+}
+
+#[panic_handler]
+fn panic(_info: &core::panic::PanicInfo) -> ! {
+    cortex_m::asm::udf();
+}
diff --git a/examples/boot/bootloader/stm32/src/main.rs b/examples/boot/bootloader/stm32/src/main.rs
index 5fd9ea588..99a7a6a6b 100644
--- a/examples/boot/bootloader/stm32/src/main.rs
+++ b/examples/boot/bootloader/stm32/src/main.rs
@@ -25,7 +25,7 @@ fn main() -> ! {
     let layout = Flash::new_blocking(p.FLASH).into_blocking_regions();
     let flash = Mutex::new(RefCell::new(layout.bank1_region));
 
-    let config = BootLoaderConfig::from_linkerfile_blocking(&flash);
+    let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash);
     let active_offset = config.active.offset();
     let bl = BootLoader::prepare::<_, _, _, 2048>(config);
 
diff --git a/examples/boot/bootloader/stm32wb-dfu/src/main.rs b/examples/boot/bootloader/stm32wb-dfu/src/main.rs
index a7ab813b6..d989fbfdf 100644
--- a/examples/boot/bootloader/stm32wb-dfu/src/main.rs
+++ b/examples/boot/bootloader/stm32wb-dfu/src/main.rs
@@ -35,7 +35,7 @@ fn main() -> ! {
     let layout = Flash::new_blocking(p.FLASH).into_blocking_regions();
     let flash = Mutex::new(RefCell::new(layout.bank1_region));
 
-    let config = BootLoaderConfig::from_linkerfile_blocking(&flash);
+    let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash);
     let active_offset = config.active.offset();
     let bl = BootLoader::prepare::<_, _, _, 2048>(config);
     if bl.state == State::DfuDetach {
@@ -45,7 +45,7 @@ fn main() -> ! {
         config.product = Some("USB-DFU Bootloader example");
         config.serial_number = Some("1235678");
 
-        let fw_config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash);
+        let fw_config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash);
         let mut buffer = AlignedBuffer([0; WRITE_SIZE]);
         let updater = BlockingFirmwareUpdater::new(fw_config, &mut buffer.0[..]);