aboutsummaryrefslogtreecommitdiff
path: root/embassy-boot-nrf/src
diff options
context:
space:
mode:
Diffstat (limited to 'embassy-boot-nrf/src')
-rw-r--r--embassy-boot-nrf/src/fmt.rs258
-rw-r--r--embassy-boot-nrf/src/lib.rs145
2 files changed, 403 insertions, 0 deletions
diff --git a/embassy-boot-nrf/src/fmt.rs b/embassy-boot-nrf/src/fmt.rs
new file mode 100644
index 000000000..78e583c1c
--- /dev/null
+++ b/embassy-boot-nrf/src/fmt.rs
@@ -0,0 +1,258 @@
1#![macro_use]
2#![allow(unused_macros)]
3
4use core::fmt::{Debug, Display, LowerHex};
5
6#[cfg(all(feature = "defmt", feature = "log"))]
7compile_error!("You may not enable both `defmt` and `log` features.");
8
9macro_rules! assert {
10 ($($x:tt)*) => {
11 {
12 #[cfg(not(feature = "defmt"))]
13 ::core::assert!($($x)*);
14 #[cfg(feature = "defmt")]
15 ::defmt::assert!($($x)*);
16 }
17 };
18}
19
20macro_rules! assert_eq {
21 ($($x:tt)*) => {
22 {
23 #[cfg(not(feature = "defmt"))]
24 ::core::assert_eq!($($x)*);
25 #[cfg(feature = "defmt")]
26 ::defmt::assert_eq!($($x)*);
27 }
28 };
29}
30
31macro_rules! assert_ne {
32 ($($x:tt)*) => {
33 {
34 #[cfg(not(feature = "defmt"))]
35 ::core::assert_ne!($($x)*);
36 #[cfg(feature = "defmt")]
37 ::defmt::assert_ne!($($x)*);
38 }
39 };
40}
41
42macro_rules! debug_assert {
43 ($($x:tt)*) => {
44 {
45 #[cfg(not(feature = "defmt"))]
46 ::core::debug_assert!($($x)*);
47 #[cfg(feature = "defmt")]
48 ::defmt::debug_assert!($($x)*);
49 }
50 };
51}
52
53macro_rules! debug_assert_eq {
54 ($($x:tt)*) => {
55 {
56 #[cfg(not(feature = "defmt"))]
57 ::core::debug_assert_eq!($($x)*);
58 #[cfg(feature = "defmt")]
59 ::defmt::debug_assert_eq!($($x)*);
60 }
61 };
62}
63
64macro_rules! debug_assert_ne {
65 ($($x:tt)*) => {
66 {
67 #[cfg(not(feature = "defmt"))]
68 ::core::debug_assert_ne!($($x)*);
69 #[cfg(feature = "defmt")]
70 ::defmt::debug_assert_ne!($($x)*);
71 }
72 };
73}
74
75macro_rules! todo {
76 ($($x:tt)*) => {
77 {
78 #[cfg(not(feature = "defmt"))]
79 ::core::todo!($($x)*);
80 #[cfg(feature = "defmt")]
81 ::defmt::todo!($($x)*);
82 }
83 };
84}
85
86#[cfg(not(feature = "defmt"))]
87macro_rules! unreachable {
88 ($($x:tt)*) => {
89 ::core::unreachable!($($x)*)
90 };
91}
92
93#[cfg(feature = "defmt")]
94macro_rules! unreachable {
95 ($($x:tt)*) => {
96 ::defmt::unreachable!($($x)*)
97 };
98}
99
100macro_rules! panic {
101 ($($x:tt)*) => {
102 {
103 #[cfg(not(feature = "defmt"))]
104 ::core::panic!($($x)*);
105 #[cfg(feature = "defmt")]
106 ::defmt::panic!($($x)*);
107 }
108 };
109}
110
111macro_rules! trace {
112 ($s:literal $(, $x:expr)* $(,)?) => {
113 {
114 #[cfg(feature = "log")]
115 ::log::trace!($s $(, $x)*);
116 #[cfg(feature = "defmt")]
117 ::defmt::trace!($s $(, $x)*);
118 #[cfg(not(any(feature = "log", feature="defmt")))]
119 let _ = ($( & $x ),*);
120 }
121 };
122}
123
124macro_rules! debug {
125 ($s:literal $(, $x:expr)* $(,)?) => {
126 {
127 #[cfg(feature = "log")]
128 ::log::debug!($s $(, $x)*);
129 #[cfg(feature = "defmt")]
130 ::defmt::debug!($s $(, $x)*);
131 #[cfg(not(any(feature = "log", feature="defmt")))]
132 let _ = ($( & $x ),*);
133 }
134 };
135}
136
137macro_rules! info {
138 ($s:literal $(, $x:expr)* $(,)?) => {
139 {
140 #[cfg(feature = "log")]
141 ::log::info!($s $(, $x)*);
142 #[cfg(feature = "defmt")]
143 ::defmt::info!($s $(, $x)*);
144 #[cfg(not(any(feature = "log", feature="defmt")))]
145 let _ = ($( & $x ),*);
146 }
147 };
148}
149
150macro_rules! warn {
151 ($s:literal $(, $x:expr)* $(,)?) => {
152 {
153 #[cfg(feature = "log")]
154 ::log::warn!($s $(, $x)*);
155 #[cfg(feature = "defmt")]
156 ::defmt::warn!($s $(, $x)*);
157 #[cfg(not(any(feature = "log", feature="defmt")))]
158 let _ = ($( & $x ),*);
159 }
160 };
161}
162
163macro_rules! error {
164 ($s:literal $(, $x:expr)* $(,)?) => {
165 {
166 #[cfg(feature = "log")]
167 ::log::error!($s $(, $x)*);
168 #[cfg(feature = "defmt")]
169 ::defmt::error!($s $(, $x)*);
170 #[cfg(not(any(feature = "log", feature="defmt")))]
171 let _ = ($( & $x ),*);
172 }
173 };
174}
175
176#[cfg(feature = "defmt")]
177macro_rules! unwrap {
178 ($($x:tt)*) => {
179 ::defmt::unwrap!($($x)*)
180 };
181}
182
183#[cfg(not(feature = "defmt"))]
184macro_rules! unwrap {
185 ($arg:expr) => {
186 match $crate::fmt::Try::into_result($arg) {
187 ::core::result::Result::Ok(t) => t,
188 ::core::result::Result::Err(e) => {
189 ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
190 }
191 }
192 };
193 ($arg:expr, $($msg:expr),+ $(,)? ) => {
194 match $crate::fmt::Try::into_result($arg) {
195 ::core::result::Result::Ok(t) => t,
196 ::core::result::Result::Err(e) => {
197 ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
198 }
199 }
200 }
201}
202
203#[derive(Debug, Copy, Clone, Eq, PartialEq)]
204pub struct NoneError;
205
206pub trait Try {
207 type Ok;
208 type Error;
209 fn into_result(self) -> Result<Self::Ok, Self::Error>;
210}
211
212impl<T> Try for Option<T> {
213 type Ok = T;
214 type Error = NoneError;
215
216 #[inline]
217 fn into_result(self) -> Result<T, NoneError> {
218 self.ok_or(NoneError)
219 }
220}
221
222impl<T, E> Try for Result<T, E> {
223 type Ok = T;
224 type Error = E;
225
226 #[inline]
227 fn into_result(self) -> Self {
228 self
229 }
230}
231
232#[allow(unused)]
233pub(crate) struct Bytes<'a>(pub &'a [u8]);
234
235impl<'a> Debug for Bytes<'a> {
236 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
237 write!(f, "{:#02x?}", self.0)
238 }
239}
240
241impl<'a> Display for Bytes<'a> {
242 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
243 write!(f, "{:#02x?}", self.0)
244 }
245}
246
247impl<'a> LowerHex for Bytes<'a> {
248 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
249 write!(f, "{:#02x?}", self.0)
250 }
251}
252
253#[cfg(feature = "defmt")]
254impl<'a> defmt::Format for Bytes<'a> {
255 fn format(&self, fmt: defmt::Formatter) {
256 defmt::write!(fmt, "{:02x}", self.0)
257 }
258}
diff --git a/embassy-boot-nrf/src/lib.rs b/embassy-boot-nrf/src/lib.rs
new file mode 100644
index 000000000..5b20a93c6
--- /dev/null
+++ b/embassy-boot-nrf/src/lib.rs
@@ -0,0 +1,145 @@
1#![no_std]
2#![warn(missing_docs)]
3#![doc = include_str!("../README.md")]
4mod fmt;
5
6pub use embassy_boot::{
7 AlignedBuffer, BlockingFirmwareState, BlockingFirmwareUpdater, BootLoaderConfig, FirmwareState, FirmwareUpdater,
8 FirmwareUpdaterConfig,
9};
10use embassy_nrf::nvmc::PAGE_SIZE;
11use embassy_nrf::peripherals::WDT;
12use embassy_nrf::wdt;
13use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
14
15/// A bootloader for nRF devices.
16pub struct BootLoader<const BUFFER_SIZE: usize = PAGE_SIZE>;
17
18impl<const BUFFER_SIZE: usize> BootLoader<BUFFER_SIZE> {
19 /// Inspect the bootloader state and perform actions required before booting, such as swapping firmware.
20 pub fn prepare<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash>(
21 config: BootLoaderConfig<ACTIVE, DFU, STATE>,
22 ) -> Self {
23 let mut aligned_buf = AlignedBuffer([0; BUFFER_SIZE]);
24 let mut boot = embassy_boot::BootLoader::new(config);
25 boot.prepare_boot(&mut aligned_buf.0).expect("Boot prepare error");
26 Self
27 }
28
29 /// Boots the application without softdevice mechanisms.
30 ///
31 /// # Safety
32 ///
33 /// This modifies the stack pointer and reset vector and will run code placed in the active partition.
34 #[cfg(not(feature = "softdevice"))]
35 pub unsafe fn load(self, start: u32) -> ! {
36 let mut p = cortex_m::Peripherals::steal();
37 p.SCB.invalidate_icache();
38 p.SCB.vtor.write(start);
39 cortex_m::asm::bootload(start as *const u32)
40 }
41
42 /// Boots the application assuming softdevice is present.
43 ///
44 /// # Safety
45 ///
46 /// This modifies the stack pointer and reset vector and will run code placed in the active partition.
47 #[cfg(feature = "softdevice")]
48 pub unsafe fn load(self, _app: u32) -> ! {
49 use nrf_softdevice_mbr as mbr;
50 const NRF_SUCCESS: u32 = 0;
51
52 // Address of softdevice which we'll forward interrupts to
53 let addr = 0x1000;
54 let mut cmd = mbr::sd_mbr_command_t {
55 command: mbr::NRF_MBR_COMMANDS_SD_MBR_COMMAND_IRQ_FORWARD_ADDRESS_SET,
56 params: mbr::sd_mbr_command_t__bindgen_ty_1 {
57 irq_forward_address_set: mbr::sd_mbr_command_irq_forward_address_set_t { address: addr },
58 },
59 };
60 let ret = mbr::sd_mbr_command(&mut cmd);
61 assert_eq!(ret, NRF_SUCCESS);
62
63 let msp = *(addr as *const u32);
64 let rv = *((addr + 4) as *const u32);
65
66 trace!("msp = {=u32:x}, rv = {=u32:x}", msp, rv);
67
68 // These instructions perform the following operations:
69 //
70 // * Modify control register to use MSP as stack pointer (clear spsel bit)
71 // * Synchronize instruction barrier
72 // * Initialize stack pointer (0x1000)
73 // * Set link register to not return (0xFF)
74 // * Jump to softdevice reset vector
75 core::arch::asm!(
76 "mrs {tmp}, CONTROL",
77 "bics {tmp}, {spsel}",
78 "msr CONTROL, {tmp}",
79 "isb",
80 "msr MSP, {msp}",
81 "mov lr, {new_lr}",
82 "bx {rv}",
83 // `out(reg) _` is not permitted in a `noreturn` asm! call,
84 // so instead use `in(reg) 0` and don't restore it afterwards.
85 tmp = in(reg) 0,
86 spsel = in(reg) 2,
87 new_lr = in(reg) 0xFFFFFFFFu32,
88 msp = in(reg) msp,
89 rv = in(reg) rv,
90 options(noreturn),
91 );
92 }
93}
94
95/// A flash implementation that wraps any flash and will pet a watchdog when touching flash.
96pub struct WatchdogFlash<FLASH> {
97 flash: FLASH,
98 wdt: wdt::WatchdogHandle,
99}
100
101impl<FLASH> WatchdogFlash<FLASH> {
102 /// Start a new watchdog with a given flash and WDT peripheral and a timeout
103 pub fn start(flash: FLASH, wdt: WDT, config: wdt::Config) -> Self {
104 let (_wdt, [wdt]) = match wdt::Watchdog::try_new(wdt, config) {
105 Ok(x) => x,
106 Err(_) => {
107 // In case the watchdog is already running, just spin and let it expire, since
108 // we can't configure it anyway. This usually happens when we first program
109 // the device and the watchdog was previously active
110 info!("Watchdog already active with wrong config, waiting for it to timeout...");
111 loop {}
112 }
113 };
114 Self { flash, wdt }
115 }
116}
117
118impl<FLASH: ErrorType> ErrorType for WatchdogFlash<FLASH> {
119 type Error = FLASH::Error;
120}
121
122impl<FLASH: NorFlash> NorFlash for WatchdogFlash<FLASH> {
123 const WRITE_SIZE: usize = FLASH::WRITE_SIZE;
124 const ERASE_SIZE: usize = FLASH::ERASE_SIZE;
125
126 fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
127 self.wdt.pet();
128 self.flash.erase(from, to)
129 }
130 fn write(&mut self, offset: u32, data: &[u8]) -> Result<(), Self::Error> {
131 self.wdt.pet();
132 self.flash.write(offset, data)
133 }
134}
135
136impl<FLASH: ReadNorFlash> ReadNorFlash for WatchdogFlash<FLASH> {
137 const READ_SIZE: usize = FLASH::READ_SIZE;
138 fn read(&mut self, offset: u32, data: &mut [u8]) -> Result<(), Self::Error> {
139 self.wdt.pet();
140 self.flash.read(offset, data)
141 }
142 fn capacity(&self) -> usize {
143 self.flash.capacity()
144 }
145}