flash-algorithm 0.7.0

A crate to write CMSIS-DAP flash algorithms for flashing embedded targets.
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Implement a [CMSIS-Pack] flash algorithm in Rust
//!
//! [CMSIS-Pack]: https://open-cmsis-pack.github.io/Open-CMSIS-Pack-Spec/main/html/flashAlgorithm.html
//!
//! # Feature flags
//!
//! - `panic-handler` this is enabled by default and includes a simple abort-on-panic
//!   panic handler. Disable this feature flag if you would prefer to use a different
//!   handler.

#![no_std]
#![no_main]
#![macro_use]

#[cfg(all(not(test), feature = "panic-handler"))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    #[cfg(not(any(target_arch = "arm", target_arch = "riscv32")))]
    compile_error!("Panic handler can only be compiled for arm and riscv32");

    unsafe {
        #[cfg(target_arch = "arm")]
        core::arch::asm!("udf #0");
        #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
        core::arch::asm!("UNIMP");
        core::hint::unreachable_unchecked();
    }
}

pub const FUNCTION_ERASE: u32 = 1;
pub const FUNCTION_PROGRAM: u32 = 2;
pub const FUNCTION_VERIFY: u32 = 3;
pub const FUNCTION_BLANKCHECK: u32 = 4;

pub type ErrorCode = core::num::NonZeroU32;

pub trait FlashAlgorithm: Sized + 'static {
    /// Initialize the flash algorithm.
    ///
    /// It can happen that the flash algorithm does not need any specific initialization
    /// for the function to be executed or no initialization at all. It is up to the implementor
    /// to decide this.
    ///
    /// # Arguments
    ///
    /// * `address` - The start address of the flash region to program.
    /// * `clock` - The clock speed in Hertz for programming the device.
    /// * `function` - The function for which this initialization is for.
    fn new(address: u32, clock: u32, function: Function) -> Result<Self, ErrorCode>;

    /// Erase entire chip. Will only be called after [`FlashAlgorithm::new()`] with [`Function::Erase`].
    #[cfg(feature = "erase-chip")]
    fn erase_all(&mut self) -> Result<(), ErrorCode>;

    /// Erase sector. Will only be called after [`FlashAlgorithm::new()`] with [`Function::Erase`].
    ///
    /// # Arguments
    ///
    /// * `address` - The start address of the flash sector to erase.
    fn erase_sector(&mut self, address: u32) -> Result<(), ErrorCode>;

    /// Program bytes. Will only be called after [`FlashAlgorithm::new()`] with [`Function::Program`].
    ///
    /// # Arguments
    ///
    /// * `address` - The start address of the flash page to program.
    /// * `data` - The data to be written to the page.
    fn program_page(&mut self, address: u32, data: &[u8]) -> Result<(), ErrorCode>;

    /// Verify the firmware that has been programmed.  Will only be called after [`FlashAlgorithm::new()`] with [`Function::Verify`].
    ///
    /// # Arguments
    ///
    /// * `address` - The start address of the flash to verify.
    /// * `size` - The length of the data to verify.
    /// * `data` - The data to compare with.
    ///
    /// # Return
    ///
    /// Return `Ok(())` on success, otherwise the first failing address as an error,
    /// which must be less than `address + size`.
    #[cfg(feature = "verify")]
    fn verify(&mut self, address: u32, size: u32, data: Option<&[u8]>) -> Result<(), u32>;

    /// Read flash.
    ///
    /// # Arguments
    ///
    /// * `address` - The start address of the flash to read.
    /// * `data` - The data.
    #[cfg(feature = "read-flash")]
    fn read_flash(&mut self, address: u32, data: &mut [u8]) -> Result<(), ErrorCode>;

    /// Verify that flash is blank.
    ///
    /// # Arguments
    ///
    /// * `address` - The start address of the flash to check.
    /// * `size` - The length of the area to check.
    /// * `pattern` - A pattern to be checked. The algorithm may choose ignore this value.
    #[cfg(feature = "blank-check")]
    fn blank_check(&mut self, address: u32, size: u32, pattern: u8) -> Result<(), ErrorCode>;
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Function {
    Erase = 1,
    Program = 2,
    Verify = 3,
    BlankCheck = 4,
}

/// A macro to define a new flash algoritm.
///
/// It takes care of placing the functions in the correct linker sections
/// and checking the flash algorithm initialization status.
#[macro_export]
macro_rules! algorithm {
    ($type:ty, {
        device_name: $device_name:expr,
        device_type: $device_type:expr,
        flash_address: $flash_address:expr,
        flash_size: $flash_size:expr,
        page_size: $page_size:expr,
        empty_value: $empty_value:expr,
        program_time_out: $program_time_out:expr,
        erase_time_out: $erase_time_out:expr,
        sectors: [$({
            size: $size:expr,
            address: $address:expr,
        }),+]
    }) => {
        static mut _IS_INIT: bool = false;
        static mut _ALGO_INSTANCE: core::mem::MaybeUninit<$type> = core::mem::MaybeUninit::uninit();

        core::arch::global_asm!(".section .PrgData, \"aw\"");

        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn Init(addr: u32, clock: u32, function: u32) -> u32 {
            unsafe {
                if _IS_INIT {
                    UnInit();
                }
                _IS_INIT = true;
            }
            let function = match function {
                1 => $crate::Function::Erase,
                2 => $crate::Function::Program,
                3 => $crate::Function::Verify,
                4 => $crate::Function::BlankCheck,
                _ => core::panic!("This branch can only be reached if the host library sent an unknown function code.")
            };
            match <$type as $crate::FlashAlgorithm>::new(addr, clock, function) {
                Ok(inst) => {
                    unsafe { _ALGO_INSTANCE.as_mut_ptr().write(inst) };
                    unsafe { _IS_INIT = true };
                    0
                }
                Err(e) => e.get(),
            }
        }
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn UnInit() -> u32 {
            unsafe {
                if !_IS_INIT {
                    return 1;
                }
                _ALGO_INSTANCE.as_mut_ptr().drop_in_place();
                _IS_INIT = false;
            }
            0
        }
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn EraseSector(addr: u32) -> u32 {
            let this = unsafe {
                if !unsafe { _IS_INIT } {
                    return 1;
                }
                &mut *_ALGO_INSTANCE.as_mut_ptr()
            };
            match <$type as $crate::FlashAlgorithm>::erase_sector(this, addr) {
                Ok(()) => 0,
                Err(e) => e.get(),
            }
        }
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn ProgramPage(addr: u32, size: u32, data: *const u8) -> u32 {
            let (this, data_slice) = unsafe {
                if !_IS_INIT {
                    return 1;
                }
                let this = &mut *_ALGO_INSTANCE.as_mut_ptr();
                let data_slice: &[u8] = core::slice::from_raw_parts(data, size as usize);
                (this, data_slice)
            };
            match <$type as $crate::FlashAlgorithm>::program_page(this, addr, data_slice) {
                Ok(()) => 0,
                Err(e) => e.get(),
            }
        }
        $crate::erase_chip!($type);
        $crate::read_flash!($type);
        $crate::verify!($type);
        $crate::blank_check!($type);

        #[allow(non_upper_case_globals)]
        #[no_mangle]
        #[used]
        #[link_section = "DeviceData"]
        pub static FlashDevice: FlashDeviceDescription = FlashDeviceDescription {
            // The version is never read by probe-rs and can be fixed.
            vers: 0x1u16.to_le(),
            // The device name here can be customized but it really has no real use
            // appart from identifying the device the ELF is intended for which we have
            // in our YAML.
            dev_name: $crate::arrayify_string($device_name),
            // The specification does not specify the values that can go here,
            // but this value means internal flash device.
            dev_type: ($device_type as u16).to_le(),
            dev_addr: ($flash_address as u32).to_le(),
            device_size: ($flash_size as u32).to_le(),
            page_size: ($page_size as u32).to_le(),
            _reserved: 0,
            // The empty state of a byte in flash.
            empty: ($empty_value as u8).to_le(),
            // This value can be used to estimate the amount of time the flashing procedure takes worst case.
            program_time_out: ($program_time_out as u32).to_le(),
            // This value can be used to estimate the amount of time the erasing procedure takes worst case.
            erase_time_out: ($erase_time_out as u32).to_le(),
            flash_sectors: [
                $(
                    FlashSector {
                        size: ($size as u32).to_le(),
                        address: ($address as u32).to_le(),
                    }
                ),+,
                // This marks the end of the flash sector list.
                FlashSector {
                    size: 0xffff_ffffu32.to_le(),
                    address: 0xffff_ffffu32.to_le(),
                }
            ],
        };

        #[repr(C)]
        pub struct FlashDeviceDescription {
            vers: u16,
            dev_name: [u8; 128],
            dev_type: u16,
            dev_addr: u32,
            device_size: u32,
            page_size: u32,
            _reserved: u32,
            empty: u8,
            program_time_out: u32,
            erase_time_out: u32,

            flash_sectors: [FlashSector; $crate::count!($($size)*) + 1],
        }

        #[repr(C)]
        #[derive(Copy, Clone)]
        pub struct FlashSector {
            size: u32,
            address: u32,
        }

        #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
        #[repr(u16)]
        pub enum DeviceType {
            Unknown = 0,
            Onchip = 1,
            Ext8Bit = 2,
            Ext16Bit = 3,
            Ext32Bit = 4,
            ExtSpi = 5,
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "erase-chip"))]
macro_rules! erase_chip {
    ($type:ty) => {};
}
#[doc(hidden)]
#[macro_export]
#[cfg(feature = "erase-chip")]
macro_rules! erase_chip {
    ($type:ty) => {
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn EraseChip() -> u32 {
            let this = unsafe {
                if !_IS_INIT {
                    return 1;
                }
                &mut *_ALGO_INSTANCE.as_mut_ptr()
            };
            match <$type as $crate::FlashAlgorithm>::erase_all(this) {
                Ok(()) => 0,
                Err(e) => e.get(),
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "read-flash"))]
macro_rules! read_flash {
    ($type:ty) => {};
}
#[doc(hidden)]
#[macro_export]
#[cfg(feature = "read-flash")]
macro_rules! read_flash {
    ($type:ty) => {
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn ReadFlash(addr: u32, size: u32, data: *mut u8) -> u32 {
            let (this, data_slice) = unsafe {
                if !_IS_INIT {
                    return 1;
                }
                let this = &mut *_ALGO_INSTANCE.as_mut_ptr();
                let data_slice: &mut [u8] = core::slice::from_raw_parts_mut(data, size as usize);
                (this, data_slice)
            };
            match <$type as $crate::FlashAlgorithm>::read_flash(this, addr, data_slice) {
                Ok(()) => 0,
                Err(e) => e.get(),
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "verify"))]
macro_rules! verify {
    ($type:ty) => {};
}
#[doc(hidden)]
#[macro_export]
#[cfg(feature = "verify")]
macro_rules! verify {
    ($type:ty) => {
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn Verify(addr: u32, size: u32, data: *const u8) -> u32 {
            let this = unsafe {
                if !_IS_INIT {
                    return 1;
                }
                &mut *_ALGO_INSTANCE.as_mut_ptr()
            };

            if data.is_null() {
                match <$type as $crate::FlashAlgorithm>::verify(this, addr, size, None) {
                    Ok(()) => addr.wrapping_add(size),
                    Err(e) => e,
                }
            } else {
                let data_slice: &[u8] = unsafe { core::slice::from_raw_parts(data, size as usize) };
                match <$type as $crate::FlashAlgorithm>::verify(this, addr, size, Some(data_slice)) {
                    Ok(()) => addr.wrapping_add(size),
                    Err(e) => e,
                }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
#[cfg(not(feature = "blank-check"))]
macro_rules! blank_check {
    ($type:ty) => {};
}
#[doc(hidden)]
#[macro_export]
#[cfg(feature = "blank-check")]
macro_rules! blank_check {
    ($type:ty) => {
        #[no_mangle]
        #[link_section = ".entry"]
        pub unsafe extern "C" fn BlankCheck(addr: u32, size: u32, pattern: u8) -> u32 {
            let this = unsafe {
                if !_IS_INIT {
                    return 1;
                }
                &mut *_ALGO_INSTANCE.as_mut_ptr()
            };
            match <$type as $crate::FlashAlgorithm>::blank_check(this, addr, size, pattern) {
                Ok(()) => 0,
                Err(e) => e.get(),
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! count {
    () => (0usize);
    ( $x:tt $($xs:tt)* ) => (1usize + $crate::count!($($xs)*));
}

pub const fn arrayify_string<const N: usize>(msg: &'static str) -> [u8; N] {
    let mut arr = [0u8; N];
    let mut idx = 0;
    let msg_bytes = msg.as_bytes();

    while (idx < msg_bytes.len()) && (idx < N) {
        arr[idx] = msg_bytes[idx];
        idx += 1;
    }

    arr
}