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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
|
#![feature(type_alias_impl_trait)]
#![feature(generic_associated_types)]
#![no_std]
#![warn(missing_docs)]
#![doc = include_str!("../../README.md")]
mod fmt;
use embedded_storage::nor_flash::{ErrorType, NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash};
use embedded_storage_async::nor_flash::AsyncNorFlash;
const BOOT_MAGIC: u8 = 0xD0;
const SWAP_MAGIC: u8 = 0xF0;
/// A region in flash used by the bootloader.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Partition {
/// Start of the flash region.
pub from: usize,
/// End of the flash region.
pub to: usize,
}
impl Partition {
/// Create a new partition with the provided range
pub const fn new(from: usize, to: usize) -> Self {
Self { from, to }
}
/// Return the length of the partition
pub const fn len(&self) -> usize {
self.to - self.from
}
}
/// The state of the bootloader after running prepare.
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum State {
/// Bootloader is ready to boot the active partition.
Boot,
/// Bootloader has swapped the active partition with the dfu partition and will attempt boot.
Swap,
}
/// Errors returned by bootloader
#[derive(PartialEq, Eq, Debug)]
pub enum BootError {
/// Error from flash.
Flash(NorFlashErrorKind),
/// Invalid bootloader magic
BadMagic,
}
impl<E> From<E> for BootError
where
E: NorFlashError,
{
fn from(error: E) -> Self {
BootError::Flash(error.kind())
}
}
/// Buffer aligned to 32 byte boundary, largest known alignment requirement for embassy-boot.
#[repr(align(32))]
pub struct AlignedBuffer<const N: usize>(pub [u8; N]);
impl<const N: usize> AsRef<[u8]> for AlignedBuffer<N> {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl<const N: usize> AsMut<[u8]> for AlignedBuffer<N> {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
/// Extension of the embedded-storage flash type information with block size and erase value.
pub trait Flash: NorFlash + ReadNorFlash {
/// The block size that should be used when writing to flash. For most builtin flashes, this is the same as the erase
/// size of the flash, but for external QSPI flash modules, this can be lower.
const BLOCK_SIZE: usize;
/// The erase value of the flash. Typically the default of 0xFF is used, but some flashes use a different value.
const ERASE_VALUE: u8 = 0xFF;
}
/// Trait defining the flash handles used for active and DFU partition
pub trait FlashConfig {
/// Flash type used for the state partition.
type STATE: Flash;
/// Flash type used for the active partition.
type ACTIVE: Flash;
/// Flash type used for the dfu partition.
type DFU: Flash;
/// Return flash instance used to write/read to/from active partition.
fn active(&mut self) -> &mut Self::ACTIVE;
/// Return flash instance used to write/read to/from dfu partition.
fn dfu(&mut self) -> &mut Self::DFU;
/// Return flash instance used to write/read to/from bootloader state.
fn state(&mut self) -> &mut Self::STATE;
}
/// BootLoader works with any flash implementing embedded_storage and can also work with
/// different page sizes and flash write sizes.
pub struct BootLoader {
// Page with current state of bootloader. The state partition has the following format:
// | Range | Description |
// | 0 - WRITE_SIZE | Magic indicating bootloader state. BOOT_MAGIC means boot, SWAP_MAGIC means swap. |
// | WRITE_SIZE - N | Progress index used while swapping or reverting |
state: Partition,
// Location of the partition which will be booted from
active: Partition,
// Location of the partition which will be swapped in when requested
dfu: Partition,
}
impl BootLoader {
/// Create a new instance of a bootloader with the given partitions.
///
/// - All partitions must be aligned with the PAGE_SIZE const generic parameter.
/// - The dfu partition must be at least PAGE_SIZE bigger than the active partition.
pub fn new(active: Partition, dfu: Partition, state: Partition) -> Self {
Self { active, dfu, state }
}
/// Return the boot address for the active partition.
pub fn boot_address(&self) -> usize {
self.active.from
}
/// Perform necessary boot preparations like swapping images.
///
/// The DFU partition is assumed to be 1 page bigger than the active partition for the swap
/// algorithm to work correctly.
///
/// SWAPPING
///
/// Assume a flash size of 3 pages for the active partition, and 4 pages for the DFU partition.
/// The swap index contains the copy progress, as to allow continuation of the copy process on
/// power failure. The index counter is represented within 1 or more pages (depending on total
/// flash size), where a page X is considered swapped if index at location (X + WRITE_SIZE)
/// contains a zero value. This ensures that index updates can be performed atomically and
/// avoid a situation where the wrong index value is set (page write size is "atomic").
///
/// +-----------+------------+--------+--------+--------+--------+
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
/// +-----------+------------+--------+--------+--------+--------+
/// | Active | 0 | 1 | 2 | 3 | - |
/// | DFU | 0 | 3 | 2 | 1 | X |
/// +-----------+-------+--------+--------+--------+--------+
///
/// The algorithm starts by copying 'backwards', and after the first step, the layout is
/// as follows:
///
/// +-----------+------------+--------+--------+--------+--------+
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
/// +-----------+------------+--------+--------+--------+--------+
/// | Active | 1 | 1 | 2 | 1 | - |
/// | DFU | 1 | 3 | 2 | 1 | 3 |
/// +-----------+------------+--------+--------+--------+--------+
///
/// The next iteration performs the same steps
///
/// +-----------+------------+--------+--------+--------+--------+
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
/// +-----------+------------+--------+--------+--------+--------+
/// | Active | 2 | 1 | 2 | 1 | - |
/// | DFU | 2 | 3 | 2 | 2 | 3 |
/// +-----------+------------+--------+--------+--------+--------+
///
/// And again until we're done
///
/// +-----------+------------+--------+--------+--------+--------+
/// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
/// +-----------+------------+--------+--------+--------+--------+
/// | Active | 3 | 3 | 2 | 1 | - |
/// | DFU | 3 | 3 | 1 | 2 | 3 |
/// +-----------+------------+--------+--------+--------+--------+
///
/// REVERTING
///
/// The reverting algorithm uses the swap index to discover that images were swapped, but that
/// the application failed to mark the boot successful. In this case, the revert algorithm will
/// run.
///
/// The revert index is located separately from the swap index, to ensure that revert can continue
/// on power failure.
///
/// The revert algorithm works forwards, by starting copying into the 'unused' DFU page at the start.
///
/// +-----------+--------------+--------+--------+--------+--------+
/// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
//*/
/// +-----------+--------------+--------+--------+--------+--------+
/// | Active | 3 | 1 | 2 | 1 | - |
/// | DFU | 3 | 3 | 1 | 2 | 3 |
/// +-----------+--------------+--------+--------+--------+--------+
///
///
/// +-----------+--------------+--------+--------+--------+--------+
/// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
/// +-----------+--------------+--------+--------+--------+--------+
/// | Active | 3 | 1 | 2 | 1 | - |
/// | DFU | 3 | 3 | 2 | 2 | 3 |
/// +-----------+--------------+--------+--------+--------+--------+
///
/// +-----------+--------------+--------+--------+--------+--------+
/// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
/// +-----------+--------------+--------+--------+--------+--------+
/// | Active | 3 | 1 | 2 | 3 | - |
/// | DFU | 3 | 3 | 2 | 1 | 3 |
/// +-----------+--------------+--------+--------+--------+--------+
///
pub fn prepare_boot<P: FlashConfig>(
&mut self,
p: &mut P,
magic: &mut [u8],
page: &mut [u8],
) -> Result<State, BootError> {
// Ensure we have enough progress pages to store copy progress
assert_eq!(self.active.len() % page.len(), 0);
assert_eq!(self.dfu.len() % page.len(), 0);
assert!(self.dfu.len() - self.active.len() >= page.len());
assert!(self.active.len() / page.len() <= (self.state.len() - P::STATE::WRITE_SIZE) / P::STATE::WRITE_SIZE);
assert_eq!(magic.len(), P::STATE::WRITE_SIZE);
// Copy contents from partition N to active
let state = self.read_state(p, magic)?;
match state {
State::Swap => {
//
// Check if we already swapped. If we're in the swap state, this means we should revert
// since the app has failed to mark boot as successful
//
if !self.is_swapped(p, magic, page)? {
trace!("Swapping");
self.swap(p, magic, page)?;
trace!("Swapping done");
} else {
trace!("Reverting");
self.revert(p, magic, page)?;
// Overwrite magic and reset progress
let fstate = p.state();
magic.fill(!P::STATE::ERASE_VALUE);
fstate.write(self.state.from as u32, magic)?;
fstate.erase(self.state.from as u32, self.state.to as u32)?;
magic.fill(BOOT_MAGIC);
fstate.write(self.state.from as u32, magic)?;
}
}
_ => {}
}
Ok(state)
}
fn is_swapped<P: FlashConfig>(&mut self, p: &mut P, magic: &mut [u8], page: &mut [u8]) -> Result<bool, BootError> {
let page_size = page.len();
let page_count = self.active.len() / page_size;
let progress = self.current_progress(p, magic)?;
Ok(progress >= page_count * 2)
}
fn current_progress<P: FlashConfig>(&mut self, config: &mut P, aligned: &mut [u8]) -> Result<usize, BootError> {
let write_size = aligned.len();
let max_index = ((self.state.len() - write_size) / write_size) - 1;
aligned.fill(!P::STATE::ERASE_VALUE);
let flash = config.state();
for i in 0..max_index {
flash.read((self.state.from + write_size + i * write_size) as u32, aligned)?;
if aligned.iter().any(|&b| b == P::STATE::ERASE_VALUE) {
return Ok(i);
}
}
Ok(max_index)
}
fn update_progress<P: FlashConfig>(&mut self, idx: usize, p: &mut P, magic: &mut [u8]) -> Result<(), BootError> {
let flash = p.state();
let write_size = magic.len();
let w = self.state.from + write_size + idx * write_size;
let aligned = magic;
aligned.fill(!P::STATE::ERASE_VALUE);
flash.write(w as u32, aligned)?;
Ok(())
}
fn active_addr(&self, n: usize, page_size: usize) -> usize {
self.active.from + n * page_size
}
fn dfu_addr(&self, n: usize, page_size: usize) -> usize {
self.dfu.from + n * page_size
}
fn copy_page_once_to_active<P: FlashConfig>(
&mut self,
idx: usize,
from_page: usize,
to_page: usize,
p: &mut P,
magic: &mut [u8],
page: &mut [u8],
) -> Result<(), BootError> {
let buf = page;
if self.current_progress(p, magic)? <= idx {
let mut offset = from_page;
for chunk in buf.chunks_mut(P::DFU::BLOCK_SIZE) {
p.dfu().read(offset as u32, chunk)?;
offset += chunk.len();
}
p.active().erase(to_page as u32, (to_page + buf.len()) as u32)?;
let mut offset = to_page;
for chunk in buf.chunks(P::ACTIVE::BLOCK_SIZE) {
p.active().write(offset as u32, chunk)?;
offset += chunk.len();
}
self.update_progress(idx, p, magic)?;
}
Ok(())
}
fn copy_page_once_to_dfu<P: FlashConfig>(
&mut self,
idx: usize,
from_page: usize,
to_page: usize,
p: &mut P,
magic: &mut [u8],
page: &mut [u8],
) -> Result<(), BootError> {
let buf = page;
if self.current_progress(p, magic)? <= idx {
let mut offset = from_page;
for chunk in buf.chunks_mut(P::ACTIVE::BLOCK_SIZE) {
p.active().read(offset as u32, chunk)?;
offset += chunk.len();
}
p.dfu().erase(to_page as u32, (to_page + buf.len()) as u32)?;
let mut offset = to_page;
for chunk in buf.chunks(P::DFU::BLOCK_SIZE) {
p.dfu().write(offset as u32, chunk)?;
offset += chunk.len();
}
self.update_progress(idx, p, magic)?;
}
Ok(())
}
fn swap<P: FlashConfig>(&mut self, p: &mut P, magic: &mut [u8], page: &mut [u8]) -> Result<(), BootError> {
let page_size = page.len();
let page_count = self.active.len() / page_size;
trace!("Page count: {}", page_count);
for page_num in 0..page_count {
trace!("COPY PAGE {}", page_num);
// Copy active page to the 'next' DFU page.
let active_page = self.active_addr(page_count - 1 - page_num, page_size);
let dfu_page = self.dfu_addr(page_count - page_num, page_size);
//trace!("Copy active {} to dfu {}", active_page, dfu_page);
self.copy_page_once_to_dfu(page_num * 2, active_page, dfu_page, p, magic, page)?;
// Copy DFU page to the active page
let active_page = self.active_addr(page_count - 1 - page_num, page_size);
let dfu_page = self.dfu_addr(page_count - 1 - page_num, page_size);
//trace!("Copy dfy {} to active {}", dfu_page, active_page);
self.copy_page_once_to_active(page_num * 2 + 1, dfu_page, active_page, p, magic, page)?;
}
Ok(())
}
fn revert<P: FlashConfig>(&mut self, p: &mut P, magic: &mut [u8], page: &mut [u8]) -> Result<(), BootError> {
let page_size = page.len();
let page_count = self.active.len() / page_size;
for page_num in 0..page_count {
// Copy the bad active page to the DFU page
let active_page = self.active_addr(page_num, page_size);
let dfu_page = self.dfu_addr(page_num, page_size);
self.copy_page_once_to_dfu(page_count * 2 + page_num * 2, active_page, dfu_page, p, magic, page)?;
// Copy the DFU page back to the active page
let active_page = self.active_addr(page_num, page_size);
let dfu_page = self.dfu_addr(page_num + 1, page_size);
self.copy_page_once_to_active(page_count * 2 + page_num * 2 + 1, dfu_page, active_page, p, magic, page)?;
}
Ok(())
}
fn read_state<P: FlashConfig>(&mut self, config: &mut P, magic: &mut [u8]) -> Result<State, BootError> {
let flash = config.state();
flash.read(self.state.from as u32, magic)?;
if !magic.iter().any(|&b| b != SWAP_MAGIC) {
Ok(State::Swap)
} else {
Ok(State::Boot)
}
}
}
/// Convenience provider that uses a single flash for all partitions.
pub struct SingleFlashConfig<'a, F>
where
F: Flash,
{
flash: &'a mut F,
}
impl<'a, F> SingleFlashConfig<'a, F>
where
F: Flash,
{
/// Create a provider for a single flash.
pub fn new(flash: &'a mut F) -> Self {
Self { flash }
}
}
impl<'a, F> FlashConfig for SingleFlashConfig<'a, F>
where
F: Flash,
{
type STATE = F;
type ACTIVE = F;
type DFU = F;
fn active(&mut self) -> &mut Self::STATE {
self.flash
}
fn dfu(&mut self) -> &mut Self::ACTIVE {
self.flash
}
fn state(&mut self) -> &mut Self::DFU {
self.flash
}
}
/// A flash wrapper implementing the Flash and embedded_storage traits.
pub struct BootFlash<'a, F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8 = 0xFF>
where
F: NorFlash + ReadNorFlash,
{
flash: &'a mut F,
}
impl<'a, F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> BootFlash<'a, F, BLOCK_SIZE, ERASE_VALUE>
where
F: NorFlash + ReadNorFlash,
{
/// Create a new instance of a bootable flash
pub fn new(flash: &'a mut F) -> Self {
Self { flash }
}
}
impl<'a, F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> Flash for BootFlash<'a, F, BLOCK_SIZE, ERASE_VALUE>
where
F: NorFlash + ReadNorFlash,
{
const BLOCK_SIZE: usize = BLOCK_SIZE;
const ERASE_VALUE: u8 = ERASE_VALUE;
}
impl<'a, F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> ErrorType for BootFlash<'a, F, BLOCK_SIZE, ERASE_VALUE>
where
F: ReadNorFlash + NorFlash,
{
type Error = F::Error;
}
impl<'a, F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> NorFlash for BootFlash<'a, F, BLOCK_SIZE, ERASE_VALUE>
where
F: ReadNorFlash + NorFlash,
{
const WRITE_SIZE: usize = F::WRITE_SIZE;
const ERASE_SIZE: usize = F::ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
F::erase(self.flash, from, to)
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
F::write(self.flash, offset, bytes)
}
}
impl<'a, F, const BLOCK_SIZE: usize, const ERASE_VALUE: u8> ReadNorFlash for BootFlash<'a, F, BLOCK_SIZE, ERASE_VALUE>
where
F: ReadNorFlash + NorFlash,
{
const READ_SIZE: usize = F::READ_SIZE;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
F::read(self.flash, offset, bytes)
}
fn capacity(&self) -> usize {
F::capacity(self.flash)
}
}
/// Convenience flash provider that uses separate flash instances for each partition.
pub struct MultiFlashConfig<'a, ACTIVE, STATE, DFU>
where
ACTIVE: Flash,
STATE: Flash,
DFU: Flash,
{
active: &'a mut ACTIVE,
state: &'a mut STATE,
dfu: &'a mut DFU,
}
impl<'a, ACTIVE, STATE, DFU> MultiFlashConfig<'a, ACTIVE, STATE, DFU>
where
ACTIVE: Flash,
STATE: Flash,
DFU: Flash,
{
/// Create a new flash provider with separate configuration for all three partitions.
pub fn new(active: &'a mut ACTIVE, state: &'a mut STATE, dfu: &'a mut DFU) -> Self {
Self { active, state, dfu }
}
}
impl<'a, ACTIVE, STATE, DFU> FlashConfig for MultiFlashConfig<'a, ACTIVE, STATE, DFU>
where
ACTIVE: Flash,
STATE: Flash,
DFU: Flash,
{
type STATE = STATE;
type ACTIVE = ACTIVE;
type DFU = DFU;
fn active(&mut self) -> &mut Self::ACTIVE {
self.active
}
fn dfu(&mut self) -> &mut Self::DFU {
self.dfu
}
fn state(&mut self) -> &mut Self::STATE {
self.state
}
}
/// FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
/// 'mess up' the internal bootloader state
pub struct FirmwareUpdater {
state: Partition,
dfu: Partition,
}
impl Default for FirmwareUpdater {
fn default() -> Self {
extern "C" {
static __bootloader_state_start: u32;
static __bootloader_state_end: u32;
static __bootloader_dfu_start: u32;
static __bootloader_dfu_end: u32;
}
let dfu = unsafe {
Partition::new(
&__bootloader_dfu_start as *const u32 as usize,
&__bootloader_dfu_end as *const u32 as usize,
)
};
let state = unsafe {
Partition::new(
&__bootloader_state_start as *const u32 as usize,
&__bootloader_state_end as *const u32 as usize,
)
};
trace!("DFU: 0x{:x} - 0x{:x}", dfu.from, dfu.to);
trace!("STATE: 0x{:x} - 0x{:x}", state.from, state.to);
FirmwareUpdater::new(dfu, state)
}
}
impl FirmwareUpdater {
/// Create a firmware updater instance with partition ranges for the update and state partitions.
pub const fn new(dfu: Partition, state: Partition) -> Self {
Self { dfu, state }
}
/// Return the length of the DFU area
pub fn firmware_len(&self) -> usize {
self.dfu.len()
}
/// Mark to trigger firmware swap on next boot.
///
/// # Safety
///
/// The `aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being written to.
pub async fn mark_updated<F: AsyncNorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic(aligned, SWAP_MAGIC, flash).await
}
/// Mark firmware boot successful and stop rollback on reset.
///
/// # Safety
///
/// The `aligned` buffer must have a size of F::WRITE_SIZE, and follow the alignment rules for the flash being written to.
pub async fn mark_booted<F: AsyncNorFlash>(&mut self, flash: &mut F, aligned: &mut [u8]) -> Result<(), F::Error> {
assert_eq!(aligned.len(), F::WRITE_SIZE);
self.set_magic(aligned, BOOT_MAGIC, flash).await
}
async fn set_magic<F: AsyncNorFlash>(
&mut self,
aligned: &mut [u8],
magic: u8,
flash: &mut F,
) -> Result<(), F::Error> {
flash.read(self.state.from as u32, aligned).await?;
if aligned.iter().any(|&b| b != magic) {
aligned.fill(0);
flash.write(self.state.from as u32, aligned).await?;
flash.erase(self.state.from as u32, self.state.to as u32).await?;
aligned.fill(magic);
flash.write(self.state.from as u32, aligned).await?;
}
Ok(())
}
/// Write data to a flash page.
///
/// The buffer must follow alignment requirements of the target flash and a multiple of page size big.
///
/// # Safety
///
/// Failing to meet alignment and size requirements may result in a panic.
pub async fn write_firmware<F: AsyncNorFlash>(
&mut self,
offset: usize,
data: &[u8],
flash: &mut F,
block_size: usize,
) -> Result<(), F::Error> {
assert!(data.len() >= F::ERASE_SIZE);
trace!(
"Writing firmware at offset 0x{:x} len {}",
self.dfu.from + offset,
data.len()
);
flash
.erase(
(self.dfu.from + offset) as u32,
(self.dfu.from + offset + data.len()) as u32,
)
.await?;
trace!(
"Erased from {} to {}",
self.dfu.from + offset,
self.dfu.from + offset + data.len()
);
let mut write_offset = self.dfu.from + offset;
for chunk in data.chunks(block_size) {
trace!("Wrote chunk at {}: {:?}", write_offset, chunk);
flash.write(write_offset as u32, chunk).await?;
write_offset += chunk.len();
}
/*
trace!("Wrote data, reading back for verification");
let mut buf: [u8; 4096] = [0; 4096];
let mut data_offset = 0;
let mut read_offset = self.dfu.from + offset;
for chunk in buf.chunks_mut(block_size) {
flash.read(read_offset as u32, chunk).await?;
trace!("Read chunk at {}: {:?}", read_offset, chunk);
assert_eq!(&data[data_offset..data_offset + block_size], chunk);
read_offset += chunk.len();
data_offset += chunk.len();
}
*/
Ok(())
}
}
#[cfg(test)]
mod tests {
use core::convert::Infallible;
use core::future::Future;
use embedded_storage::nor_flash::ErrorType;
use embedded_storage_async::nor_flash::AsyncReadNorFlash;
use futures::executor::block_on;
use super::*;
/*
#[test]
fn test_bad_magic() {
let mut flash = MemFlash([0xff; 131072]);
let mut flash = SingleFlashConfig::new(&mut flash);
let mut bootloader = BootLoader::<4096>::new(ACTIVE, DFU, STATE);
assert_eq!(
bootloader.prepare_boot(&mut flash),
Err(BootError::BadMagic)
);
}
*/
#[test]
fn test_boot_state() {
const STATE: Partition = Partition::new(0, 4096);
const ACTIVE: Partition = Partition::new(4096, 61440);
const DFU: Partition = Partition::new(61440, 122880);
let mut flash = MemFlash::<131072, 4096, 4>([0xff; 131072]);
flash.0[0..4].copy_from_slice(&[BOOT_MAGIC; 4]);
let mut flash = SingleFlashConfig::new(&mut flash);
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Boot,
bootloader.prepare_boot(&mut flash, &mut magic, &mut page).unwrap()
);
}
#[test]
fn test_swap_state() {
const STATE: Partition = Partition::new(0, 4096);
const ACTIVE: Partition = Partition::new(4096, 61440);
const DFU: Partition = Partition::new(61440, 122880);
let mut flash = MemFlash::<131072, 4096, 4>([0xff; 131072]);
let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
let mut aligned = [0; 4];
for i in ACTIVE.from..ACTIVE.to {
flash.0[i] = original[i - ACTIVE.from];
}
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut updater = FirmwareUpdater::new(DFU, STATE);
let mut offset = 0;
for chunk in update.chunks(4096) {
block_on(updater.write_firmware(offset, chunk, &mut flash, 4096)).unwrap();
offset += chunk.len();
}
block_on(updater.mark_updated(&mut flash, &mut aligned)).unwrap();
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Swap,
bootloader
.prepare_boot(&mut SingleFlashConfig::new(&mut flash), &mut magic, &mut page)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(flash.0[i], update[i - ACTIVE.from], "Index {}", i);
}
// First DFU page is untouched
for i in DFU.from + 4096..DFU.to {
assert_eq!(flash.0[i], original[i - DFU.from - 4096], "Index {}", i);
}
// Running again should cause a revert
assert_eq!(
State::Swap,
bootloader
.prepare_boot(&mut SingleFlashConfig::new(&mut flash), &mut magic, &mut page)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(flash.0[i], original[i - ACTIVE.from], "Index {}", i);
}
// Last page is untouched
for i in DFU.from..DFU.to - 4096 {
assert_eq!(flash.0[i], update[i - DFU.from], "Index {}", i);
}
// Mark as booted
block_on(updater.mark_booted(&mut flash, &mut aligned)).unwrap();
assert_eq!(
State::Boot,
bootloader
.prepare_boot(&mut SingleFlashConfig::new(&mut flash), &mut magic, &mut page)
.unwrap()
);
}
#[test]
fn test_separate_flash_active_page_biggest() {
const STATE: Partition = Partition::new(2048, 4096);
const ACTIVE: Partition = Partition::new(4096, 16384);
const DFU: Partition = Partition::new(0, 16384);
let mut active = MemFlash::<16384, 4096, 8>([0xff; 16384]);
let mut dfu = MemFlash::<16384, 2048, 8>([0xff; 16384]);
let mut state = MemFlash::<4096, 128, 4>([0xff; 4096]);
let mut aligned = [0; 4];
let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
for i in ACTIVE.from..ACTIVE.to {
active.0[i] = original[i - ACTIVE.from];
}
let mut updater = FirmwareUpdater::new(DFU, STATE);
let mut offset = 0;
for chunk in update.chunks(2048) {
block_on(updater.write_firmware(offset, chunk, &mut dfu, chunk.len())).unwrap();
offset += chunk.len();
}
block_on(updater.mark_updated(&mut state, &mut aligned)).unwrap();
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Swap,
bootloader
.prepare_boot(
&mut MultiFlashConfig::new(&mut active, &mut state, &mut dfu),
&mut magic,
&mut page
)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(active.0[i], update[i - ACTIVE.from], "Index {}", i);
}
// First DFU page is untouched
for i in DFU.from + 4096..DFU.to {
assert_eq!(dfu.0[i], original[i - DFU.from - 4096], "Index {}", i);
}
}
#[test]
fn test_separate_flash_dfu_page_biggest() {
const STATE: Partition = Partition::new(2048, 4096);
const ACTIVE: Partition = Partition::new(4096, 16384);
const DFU: Partition = Partition::new(0, 16384);
let mut aligned = [0; 4];
let mut active = MemFlash::<16384, 2048, 4>([0xff; 16384]);
let mut dfu = MemFlash::<16384, 4096, 8>([0xff; 16384]);
let mut state = MemFlash::<4096, 128, 4>([0xff; 4096]);
let original: [u8; ACTIVE.len()] = [rand::random::<u8>(); ACTIVE.len()];
let update: [u8; DFU.len()] = [rand::random::<u8>(); DFU.len()];
for i in ACTIVE.from..ACTIVE.to {
active.0[i] = original[i - ACTIVE.from];
}
let mut updater = FirmwareUpdater::new(DFU, STATE);
let mut offset = 0;
for chunk in update.chunks(4096) {
block_on(updater.write_firmware(offset, chunk, &mut dfu, chunk.len())).unwrap();
offset += chunk.len();
}
block_on(updater.mark_updated(&mut state, &mut aligned)).unwrap();
let mut bootloader: BootLoader = BootLoader::new(ACTIVE, DFU, STATE);
let mut magic = [0; 4];
let mut page = [0; 4096];
assert_eq!(
State::Swap,
bootloader
.prepare_boot(
&mut MultiFlashConfig::new(&mut active, &mut state, &mut dfu,),
&mut magic,
&mut page
)
.unwrap()
);
for i in ACTIVE.from..ACTIVE.to {
assert_eq!(active.0[i], update[i - ACTIVE.from], "Index {}", i);
}
// First DFU page is untouched
for i in DFU.from + 4096..DFU.to {
assert_eq!(dfu.0[i], original[i - DFU.from - 4096], "Index {}", i);
}
}
struct MemFlash<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize>([u8; SIZE]);
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> NorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const WRITE_SIZE: usize = WRITE_SIZE;
const ERASE_SIZE: usize = ERASE_SIZE;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
let from = from as usize;
let to = to as usize;
assert!(from % ERASE_SIZE == 0);
assert!(to % ERASE_SIZE == 0, "To: {}, erase size: {}", to, ERASE_SIZE);
for i in from..to {
self.0[i] = 0xFF;
}
Ok(())
}
fn write(&mut self, offset: u32, data: &[u8]) -> Result<(), Self::Error> {
assert!(data.len() % WRITE_SIZE == 0);
assert!(offset as usize % WRITE_SIZE == 0);
assert!(offset as usize + data.len() <= SIZE);
self.0[offset as usize..offset as usize + data.len()].copy_from_slice(data);
Ok(())
}
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ErrorType
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
type Error = Infallible;
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> ReadNorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const READ_SIZE: usize = 4;
fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
let len = buf.len();
buf[..].copy_from_slice(&self.0[offset as usize..offset as usize + len]);
Ok(())
}
fn capacity(&self) -> usize {
SIZE
}
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> super::Flash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const BLOCK_SIZE: usize = ERASE_SIZE;
const ERASE_VALUE: u8 = 0xFF;
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncReadNorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const READ_SIZE: usize = 4;
type ReadFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn read<'a>(&'a mut self, offset: u32, buf: &'a mut [u8]) -> Self::ReadFuture<'a> {
async move {
let len = buf.len();
buf[..].copy_from_slice(&self.0[offset as usize..offset as usize + len]);
Ok(())
}
}
fn capacity(&self) -> usize {
SIZE
}
}
impl<const SIZE: usize, const ERASE_SIZE: usize, const WRITE_SIZE: usize> AsyncNorFlash
for MemFlash<SIZE, ERASE_SIZE, WRITE_SIZE>
{
const WRITE_SIZE: usize = WRITE_SIZE;
const ERASE_SIZE: usize = ERASE_SIZE;
type EraseFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn erase<'a>(&'a mut self, from: u32, to: u32) -> Self::EraseFuture<'a> {
async move {
let from = from as usize;
let to = to as usize;
assert!(from % ERASE_SIZE == 0);
assert!(to % ERASE_SIZE == 0);
for i in from..to {
self.0[i] = 0xFF;
}
Ok(())
}
}
type WriteFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn write<'a>(&'a mut self, offset: u32, data: &'a [u8]) -> Self::WriteFuture<'a> {
info!("Writing {} bytes to 0x{:x}", data.len(), offset);
async move {
assert!(data.len() % WRITE_SIZE == 0);
assert!(offset as usize % WRITE_SIZE == 0);
assert!(
offset as usize + data.len() <= SIZE,
"OFFSET: {}, LEN: {}, FLASH SIZE: {}",
offset,
data.len(),
SIZE
);
self.0[offset as usize..offset as usize + data.len()].copy_from_slice(data);
Ok(())
}
}
}
}
|