Repository navigation
Expand file tree
/
Copy pathlibwolfboot.c
More file actions
3897 lines (3545 loc) · 121 KB
/
Copy pathlibwolfboot.c
File metadata and controls
3897 lines (3545 loc) · 121 KB
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
/* libwolfboot.c
*
* Copyright (C) 2026 wolfSSL Inc.
*
* This file is part of wolfBoot.
*
* wolfBoot is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfBoot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
/**
* @file libwolfboot.c
*
* @brief wolfBoot library implementation.
*
* This file contains the implementation of the wolfBoot library.
*/
#include <stdint.h>
#include "hal.h"
#include "wolfboot/wolfboot.h"
#include "image.h"
#include "printf.h"
#ifdef WATCHDOG
/* Weak no-op default; a port HAL overrides this to service the watchdog.
* RAMFUNCTION so the fallback is safe when called from the RAM-resident flash
* paths (update_flash.c) on RAM_CODE targets. */
void RAMFUNCTION WEAKFUNCTION wolfBoot_watchdog_feed(void)
{
}
#endif
#ifdef UNIT_TEST
/**
* @def unit_dbg
* @brief Conditional debug macro for unit tests.
*
* Conditional debug macro for unit tests, redirects to wolfBoot_printf.
*/
# define unit_dbg wolfBoot_printf
#else
/**
* @def unit_dbg
* @brief Empty macro for unit_dbg in non-test builds.
*
* Empty macro for unit_dbg in non-test builds.
*/
# define unit_dbg(...) do{}while(0)
#endif
#ifndef TRAILER_SKIP
/**
* @def TRAILER_SKIP
* @brief Trailer skip value for partition encryption.
*
* Trailer skip value for partition encryption, defaults to 0 if not defined.
*/
# define TRAILER_SKIP 0
#endif
#include <stddef.h> /* for size_t */
#if defined(EXT_ENCRYPTED) && (defined(__WOLFBOOT) || defined(UNIT_TEST) || defined(MMU))
#include "encrypt.h"
static int encrypt_initialized = 0;
static uint8_t encrypt_iv_nonce[ENCRYPT_NONCE_SIZE] XALIGNED(4);
static uint32_t encrypt_iv_offset = 0;
static int fallback_iv_forced = 0;
static int encrypt_key_is_valid(const uint8_t *key, uint32_t len)
{
const volatile uint8_t *vkey = key;
uint8_t has_one = 0;
uint8_t has_zero = 0;
uint32_t i;
for (i = 0; i < len; i++) {
has_one |= vkey[i];
has_zero |= (uint8_t)~vkey[i];
}
return (has_one != 0) && (has_zero != 0);
}
#define FALLBACK_IV_OFFSET 0x00100000U
#if !defined(XMEMSET)
#include <string.h>
#define XMEMSET memset
#define XMEMCPY memcpy
#define XMEMCMP memcmp
#endif
#if defined(ENCRYPT_WITH_AES128) || defined(ENCRYPT_WITH_AES256)
extern void aes_set_iv(uint8_t *nonce, uint32_t address);
#endif
#if defined (__WOLFBOOT) || defined (UNIT_TEST)
int wolfBoot_initialize_encryption(void)
{
if (!encrypt_initialized) {
if (crypto_init() != 0) {
return -1;
}
encrypt_initialized = 1;
}
return 0;
}
#endif
#else
#define wolfBoot_initialize_encryption() (0)
#endif /* EXT_ENCRYPTED */
/* Despite the name, ENCRYPT_TMP_SECRET_OFFSET* set the end-of-partition
* trailer position for all builds (PART_*_ENDFLAGS derive from them); only
* encrypted builds also keep the tmp key/nonce there. */
#if defined(EXT_FLASH) && defined(EXT_ENCRYPTED)
#define ENCRYPT_TMP_SECRET_OFFSET (WOLFBOOT_PARTITION_SIZE - \
(TRAILER_SKIP + ENCRYPT_KEY_SIZE + ENCRYPT_NONCE_SIZE))
/* Same trailer layout at the end of the (possibly larger) UPDATE slot */
#define ENCRYPT_TMP_SECRET_OFFSET_UPDATE (WOLFBOOT_PARTITION_UPDATE_SIZE - \
(TRAILER_SKIP + ENCRYPT_KEY_SIZE + ENCRYPT_NONCE_SIZE))
#define TRAILER_OVERHEAD (4 + 1 + (WOLFBOOT_PARTITION_SIZE / \
(2 * WOLFBOOT_SECTOR_SIZE)))
/* MAGIC (4B) + PART_FLAG (1B) + (N_SECTORS / 2) */
#define START_FLAGS_OFFSET (ENCRYPT_TMP_SECRET_OFFSET - TRAILER_OVERHEAD)
#define SECTOR_FLAGS_SIZE (WOLFBOOT_SECTOR_SIZE - (4 + 1 + \
ENCRYPT_KEY_SIZE + ENCRYPT_NONCE_SIZE))
/* MAGIC (4B) + PART_FLAG (1B) + ENCRYPT_KEY_SIZE + ENCRYPT_NONCE_SIZE */
#else
#define ENCRYPT_TMP_SECRET_OFFSET (WOLFBOOT_PARTITION_SIZE - (TRAILER_SKIP))
#define ENCRYPT_TMP_SECRET_OFFSET_UPDATE \
(WOLFBOOT_PARTITION_UPDATE_SIZE - (TRAILER_SKIP))
#define SECTOR_FLAGS_SIZE (WOLFBOOT_SECTOR_SIZE - (4 + 1))
/* MAGIC (4B) + PART_FLAG (1B) */
#endif /* EXT_FLASH && EXT_ENCRYPTED */
#if !defined(__WOLFBOOT) && !defined(UNIT_TEST)
/* Avoid redefining if already defined by wolfSSL headers */
#if !defined(XMEMSET)
#define XMEMSET memset
#define XMEMCPY memcpy
#define XMEMCMP memcmp
#endif
#endif
#ifndef NULL
# define NULL (void *)0
#endif
#ifndef NVM_CACHE_SIZE
#define NVM_CACHE_SIZE WOLFBOOT_SECTOR_SIZE
#endif
#ifdef BUILD_TOOL
/* Building for a local utility tool */
#undef EXT_FLASH
#undef EXT_ENCRYPTED
#undef WOLFBOOT_FIXED_PARTITIONS
#endif
#if defined(EXT_FLASH) && !defined(WOLFBOOT_NO_PARTITIONS) && \
!defined(CUSTOM_PARTITION_TRAILER) && !defined(NVM_FLASH_JOURNAL)
static uint32_t ext_cache;
#endif
/* EXT_ENCRYPTED is listed because the key-handling code below calls
* ForceZero() unconditionally, including from the test-app build of this file,
* where __WOLFBOOT is not defined. NVM_FLASH_WRITEONCE is deliberately NOT
* listed: the partition-trailer helpers scrub with nvm_cache_scrub(), so the
* NVM path stays free of the wolfSSL headers that tools/check_config and the
* STM32Cube test-app cannot resolve. */
#if defined(__WOLFBOOT) || defined(UNIT_TEST) || defined(EXT_ENCRYPTED)
#define WOLFSSL_MISC_INCLUDED /* allow misc.c code to be inlined */
#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/wolfcrypt/wc_port.h>
#include <wolfcrypt/src/misc.c> /* for ByteReverseWord32 */
#if defined(EXT_ENCRYPTED) || defined(UNIT_TEST)
static uint32_t wb_reverse_word32(uint32_t x)
{
return ByteReverseWord32(x);
}
#endif
#endif
#if (defined(WOLFBOOT_FIXED_PARTITIONS) || defined(EXT_FLASH) || \
defined(NVM_FLASH_WRITEONCE)) && !defined(WOLFBOOT_NO_PARTITIONS)
static const uint32_t wolfboot_magic_trail = WOLFBOOT_MAGIC_TRAIL;
#endif
/* Top addresses for FLAGS field
* - PART_BOOT_ENDFLAGS = top of flags for BOOT partition
* - PART_UPDATE_ENDFLAGS = top of flags for UPDATE_PARTITION
*/
#ifndef PART_BOOT_ENDFLAGS
#define PART_BOOT_ENDFLAGS (WOLFBOOT_PARTITION_BOOT_ADDRESS + ENCRYPT_TMP_SECRET_OFFSET)
#endif
#define FLAGS_BOOT_EXT() PARTN_IS_EXT(PART_BOOT)
#ifdef FLAGS_HOME
/*
* In FLAGS_HOME mode, all FLAGS live at the end of the boot partition:
* / -12 /-8 /-4 / END
* |Sn| ... |S2|S1|S0|PU| MAGIC |X|X|X|PB| MAGIC |
* ^--sectors --^ ^--update ^---boot partition
* flags partition flag
* flag
*
* */
#define PART_UPDATE_ENDFLAGS (PART_BOOT_ENDFLAGS - 8)
#define FLAGS_UPDATE_EXT() PARTN_IS_EXT(PART_BOOT)
#else
/* FLAGS are at the end of each partition */
#define PART_UPDATE_ENDFLAGS (WOLFBOOT_PARTITION_UPDATE_ADDRESS + ENCRYPT_TMP_SECRET_OFFSET_UPDATE)
#define FLAGS_UPDATE_EXT() PARTN_IS_EXT(PART_UPDATE)
#endif
/* Weak no-op default: targets whose flash reads are not cached need not
* implement this. It lives outside NVM_FLASH_WRITEONCE because callers such
* as src/pkcs11_store.c are built independently of that option. */
void WEAKFUNCTION hal_cache_invalidate(void)
{
/* if cache flushing is required implement in hal */
}
/* Weak default; a port with the MMU and D-cache on overrides it. Fails
* rather than succeeding: a silent no-op would leave the caller sharing
* write-back memory with a non-coherent master. */
int WEAKFUNCTION hal_dma_set_noncached(uintptr_t start, uintptr_t end)
{
(void)start;
(void)end;
return -1;
}
/* Weak default erased check that compares a plain read with
* FLASH_BYTE_ERASED. A HAL overrides it where a plain read is not reliable. */
int RAMFUNCTION WEAKFUNCTION hal_flash_is_erased(haladdr_t address, int len)
{
const volatile uint8_t *p = (const volatile uint8_t *)(uintptr_t)address;
int i;
for (i = 0; i < len; i++) {
if (p[i] != FLASH_BYTE_ERASED)
return 0;
}
return 1;
}
#ifdef EXT_FLASH
/* Weak default erased check for external flash, read through the HAL */
int RAMFUNCTION WEAKFUNCTION ext_flash_is_erased(uintptr_t address, int len)
{
uint8_t buf[32];
int n, i;
while (len > 0) {
n = (len > (int)sizeof(buf)) ? (int)sizeof(buf) : len;
if (ext_flash_read(address, buf, n) != n)
return -1;
for (i = 0; i < n; i++) {
if (buf[i] != FLASH_BYTE_ERASED)
return 0;
}
address += n;
len -= n;
}
return 1;
}
#endif
#if defined(WOLFBOOT_PERSIST_FAILURE_STATUS) || defined(NVM_FLASH_JOURNAL)
/* CRC32 (IEEE 802.3), bitwise to keep the code small */
static uint32_t RAMFUNCTION wb_crc32(const void *data, uint32_t len)
{
const uint8_t *p = (const uint8_t *)data;
uint32_t crc = 0xFFFFFFFFUL;
uint32_t i, j;
for (i = 0; i < len; i++) {
crc ^= p[i];
for (j = 0; j < 8; j++)
crc = (crc >> 1) ^ (0xEDB88320UL & (0U - (crc & 1U)));
}
return crc ^ 0xFFFFFFFFUL;
}
#endif
#if (defined(NVM_FLASH_JOURNAL) || defined(NVM_FLASH_ECC)) && \
defined(WOLFBOOT_FIXED_PARTITIONS)
static int RAMFUNCTION part_is_erased(uint8_t part, uintptr_t addr, int len)
{
#ifdef EXT_FLASH
if (PARTN_IS_EXT(part))
return ext_flash_is_erased(addr, len);
#endif
(void)part;
return hal_flash_is_erased(addr, len);
}
#endif
#ifdef NVM_FLASH_WRITEONCE
/* Some internal FLASH memory models don't allow
* multiple writes after erase in the same page/area.
*
* NVM_FLASH_WRITEONCE uses a redundant two-sector model
* to mitigate the effect of power failures.
*
*/
#ifndef WOLFBOOT_FLAGS_INVERT
#define FLAG_CMP(a,b) ((a < b)? 0 : 1)
#else
#define FLAG_CMP(a,b) ((a > b)? 0 : 1)
#endif
#include <stddef.h>
#include <string.h>
uint8_t NVM_CACHE[NVM_CACHE_SIZE] XALIGNED(16);
static int nvm_cached_sector = 0;
/* Scrub the staging buffer without depending on wolfCrypt: ForceZero()
* would pull wolfSSL headers into every NVM_FLASH_WRITEONCE build,
* including tools/check_config and the STM32Cube test-app, which cannot
* supply them. A volatile byte loop also suits the RAMFUNCTION callers,
* since ForceZero() lives in flash. */
static void RAMFUNCTION nvm_cache_scrub(void)
{
volatile uint8_t *p = (volatile uint8_t *)NVM_CACHE;
unsigned int i;
for (i = 0; i < NVM_CACHE_SIZE; i++)
p[i] = 0;
}
static uint8_t get_base_offset(uint8_t *base, uintptr_t off)
{
return *(uint8_t*)((uintptr_t)base - off); /* ignore array bounds error */
}
#ifdef __CCRX__
#pragma section FRAM
#endif
static int RAMFUNCTION nvm_select_fresh_sector(int part)
{
int sel;
uintptr_t off;
uint8_t *base;
uint8_t* addrErase = 0;
uint32_t word_0;
uint32_t word_1;
#if defined(EXT_FLASH) && !defined(FLAGS_HOME)
if ((part == PART_UPDATE) && FLAGS_UPDATE_EXT()) {
return 0;
}
#endif
hal_cache_invalidate();
if (part == PART_BOOT) {
base = (uint8_t *)PART_BOOT_ENDFLAGS;
addrErase = (uint8_t *)WOLFBOOT_PARTITION_BOOT_ADDRESS +
WOLFBOOT_PARTITION_SIZE - WOLFBOOT_SECTOR_SIZE;
}
else {
base = (uint8_t *)PART_UPDATE_ENDFLAGS;
#ifdef FLAGS_HOME
addrErase = (uint8_t *)WOLFBOOT_PARTITION_BOOT_ADDRESS +
WOLFBOOT_PARTITION_SIZE - WOLFBOOT_SECTOR_SIZE;
#else
addrErase = (uint8_t *)WOLFBOOT_PARTITION_UPDATE_ADDRESS +
WOLFBOOT_PARTITION_UPDATE_SIZE - WOLFBOOT_SECTOR_SIZE;
#endif
}
/* check magic in case the sector is corrupt */
word_0 = *((uint32_t*)((uintptr_t)base - sizeof(uint32_t)));
word_1 = *((uint32_t*)((uintptr_t)base - (WOLFBOOT_SECTOR_SIZE + sizeof(uint32_t))));
if (word_0 == WOLFBOOT_MAGIC_TRAIL && word_1 != WOLFBOOT_MAGIC_TRAIL) {
sel = 0;
goto finish;
}
else if (word_0 != WOLFBOOT_MAGIC_TRAIL && word_1 == WOLFBOOT_MAGIC_TRAIL) {
sel = 1;
goto finish;
} else if (word_0 != WOLFBOOT_MAGIC_TRAIL && word_1 != WOLFBOOT_MAGIC_TRAIL) {
/* none of the partition has a valid trailer, default to '0' */
sel = 0;
goto finish;
}
/* Default to last sector if no match is found */
sel = 0;
/* Select the sector with more flags set. Partition flag is at offset '4'.
* Sector flags begin from offset '5'.
*/
for (off = 4; off < WOLFBOOT_SECTOR_SIZE; off++) {
volatile uint8_t byte_0 = get_base_offset(base, off);
volatile uint8_t byte_1 = get_base_offset(base, (WOLFBOOT_SECTOR_SIZE + off));
if (byte_0 == FLASH_BYTE_ERASED && byte_1 != FLASH_BYTE_ERASED) {
sel = 1;
break;
}
else if (byte_0 != FLASH_BYTE_ERASED && byte_1 == FLASH_BYTE_ERASED) {
sel = 0;
break;
}
else if ((byte_0 == FLASH_BYTE_ERASED) &&
(byte_1 == FLASH_BYTE_ERASED)) {
/* Examine previous position one byte ahead */
byte_0 = get_base_offset(base, (off - 1));
byte_1 = get_base_offset(base, ((WOLFBOOT_SECTOR_SIZE + off) - 1));
sel = FLAG_CMP(byte_0, byte_1);
break;
}
}
finish:
/* Erase the non-selected partition, requires unlocked flash */
addrErase -= WOLFBOOT_SECTOR_SIZE * (!sel);
if (*((uint32_t*)(addrErase + WOLFBOOT_SECTOR_SIZE - sizeof(uint32_t)))
!= FLASH_WORD_ERASED) {
hal_flash_erase((uintptr_t)addrErase, WOLFBOOT_SECTOR_SIZE);
}
return sel;
}
/**
* @brief Write the trailer in a non-volatile memory.
*
* This function writes the trailer in a non-volatile memory.
*
* @param[in] part Partition number.
* @param[in] addr Address of the trailer.
* @param[in] val New value to write in the trailer.
* @return 0 on success, -1 on failure.
*/
static int RAMFUNCTION trailer_write(uint8_t part, uintptr_t addr, uint8_t val)
{
uintptr_t addr_align = (size_t)(addr & (~(NVM_CACHE_SIZE - 1)));
uintptr_t addr_read, addr_write;
uintptr_t addr_off = addr & (NVM_CACHE_SIZE - 1);
int ret = 0;
nvm_cached_sector = nvm_select_fresh_sector(part);
addr_read = addr_align - (nvm_cached_sector * NVM_CACHE_SIZE);
XMEMCPY(NVM_CACHE, (void*)addr_read, NVM_CACHE_SIZE);
NVM_CACHE[addr_off] = val;
/* Calculate write address */
addr_write = addr_align - ((!nvm_cached_sector) * NVM_CACHE_SIZE);
/* Ensure that the destination was erased */
hal_flash_erase(addr_write, NVM_CACHE_SIZE);
#if FLASHBUFFER_SIZE != WOLFBOOT_SECTOR_SIZE
addr_off = 0;
while ((addr_off < WOLFBOOT_SECTOR_SIZE) && (ret == 0)) {
ret = hal_flash_write(addr_write + addr_off, NVM_CACHE + addr_off,
FLASHBUFFER_SIZE);
addr_off += FLASHBUFFER_SIZE;
}
#else
ret = hal_flash_write(addr_write, NVM_CACHE, NVM_CACHE_SIZE);
#endif
if (ret != 0) {
/* The staged sector may hold the firmware key/nonce (see
* ENCRYPT_CACHE under NVM_FLASH_WRITEONCE): scrub it before
* returning, success or not. */
nvm_cache_scrub();
return ret;
}
/* Once a copy has been written, erase the older sector */
ret = hal_flash_erase(addr_read, NVM_CACHE_SIZE);
nvm_cached_sector = !nvm_cached_sector;
nvm_cache_scrub();
return ret;
}
/**
* @brief Write the partition magic in a non-volatile memory.
*
* This function writes the partition magic in a non-volatile memory.
*
* @param[in] part Partition number.
* @param[in] addr Address of the magic trailer.
* @return 0 on success, -1 on failure.
*/
static int RAMFUNCTION partition_magic_write(uint8_t part, uintptr_t addr)
{
uintptr_t off = addr % NVM_CACHE_SIZE;
uintptr_t base = (uintptr_t)addr - off;
uintptr_t addr_read, addr_write;
int ret;
nvm_cached_sector = nvm_select_fresh_sector(part);
addr_read = base - (nvm_cached_sector * NVM_CACHE_SIZE);
addr_write = base - (!nvm_cached_sector * NVM_CACHE_SIZE);
XMEMCPY(NVM_CACHE, (void*)addr_read, NVM_CACHE_SIZE);
XMEMCPY(NVM_CACHE + off, &wolfboot_magic_trail, sizeof(uint32_t));
ret = hal_flash_write(addr_write, NVM_CACHE, WOLFBOOT_SECTOR_SIZE);
if (ret != 0) {
/* The staged sector may hold the firmware key/nonce (see
* ENCRYPT_CACHE under NVM_FLASH_WRITEONCE): scrub it before
* returning, success or not. */
nvm_cache_scrub();
return ret;
}
nvm_cached_sector = !nvm_cached_sector;
ret = hal_flash_erase(addr_read, WOLFBOOT_SECTOR_SIZE);
nvm_cache_scrub();
return ret;
}
#ifdef __CCRX__
#pragma section
#endif
#else
# define trailer_write(part,addr, val) hal_flash_write(addr, (void *)&val, 1)
# define partition_magic_write(part,addr) hal_flash_write(addr, \
(void*)&wolfboot_magic_trail, sizeof(uint32_t));
#endif /* NVM_FLASH_WRITEONCE */
#ifndef MOCK_PARTITION_TRAILER /* used for unit-mock-state.c */
#ifdef CUSTOM_PARTITION_TRAILER
/* Custom partition trailer
* Function implementation externally defined
*/
uint8_t* RAMFUNCTION get_trailer_at(uint8_t part, uint32_t at);
void RAMFUNCTION set_trailer_at(uint8_t part, uint32_t at, uint8_t val);
void RAMFUNCTION set_partition_magic(uint8_t part);
#elif !defined(WOLFBOOT_FIXED_PARTITIONS)
#ifdef __CCRX__
#pragma section FRAM
#endif
static uint8_t* RAMFUNCTION get_trailer_at(uint8_t part, uint32_t at)
{
(void)part;
(void)at;
return 0;
}
static void RAMFUNCTION set_trailer_at(uint8_t part, uint32_t at, uint8_t val)
{
(void)part;
(void)at;
(void)val;
return;
}
static void RAMFUNCTION set_partition_magic(uint8_t part)
{
(void)part;
return;
}
#ifdef __CCRX__
#pragma section
#endif
#elif defined(NVM_FLASH_JOURNAL)
#include <string.h>
#ifdef __CCRX__
#pragma section FRAM
#endif
/* Largest partition, in sectors */
#if WOLFBOOT_PARTITION_UPDATE_SIZE > WOLFBOOT_PARTITION_SIZE
#define JOURNAL_PART_SECTORS (WOLFBOOT_PARTITION_UPDATE_SIZE / WOLFBOOT_SECTOR_SIZE)
#else
#define JOURNAL_PART_SECTORS (WOLFBOOT_PARTITION_SIZE / WOLFBOOT_SECTOR_SIZE)
#endif
/* The magic, the state and one flag byte for each two sectors, rounded up to
* whole words, as the RAM copy is a uint32_t array ending with the magic */
#define JOURNAL_TRAILER_SIZE \
(((4 + 1 + (JOURNAL_PART_SECTORS + 1) / 2) + 3) & ~3)
/* One record per write unit, at least 16 bytes. Records fill the sector
* from its start and never reach the in-place trailer area at its end. */
#if WOLFBOOT_FLASH_WRITE_UNIT > 16
#define JOURNAL_SLOT_SIZE WOLFBOOT_FLASH_WRITE_UNIT
#else
#define JOURNAL_SLOT_SIZE 16
#endif
#define JOURNAL_SLOTS ((WOLFBOOT_SECTOR_SIZE - TRAILER_SKIP - \
JOURNAL_TRAILER_SIZE) / JOURNAL_SLOT_SIZE)
#if (WOLFBOOT_FLASH_WRITE_UNIT & (WOLFBOOT_FLASH_WRITE_UNIT - 1)) != 0
#error "WOLFBOOT_FLASH_WRITE_UNIT must be a power of two"
#endif
#ifdef NVM_FLASH_JOURNAL_DUAL
/* Two trailer sectors take turns. Slot 0 of each sector holds a header, so
* the log starts at slot 1. */
#define JOURNAL_DUAL 1
#define JOURNAL_FIRST_SLOT 1
#define JOURNAL_LOG_SLOTS JOURNAL_SLOTS
/* A new log holds a header, a copy of the trailer, and a commit record */
#if JOURNAL_SLOTS < (JOURNAL_TRAILER_SIZE / 4 + 4)
#error "NVM_FLASH_JOURNAL_DUAL: trailer sector can't hold a copy of the trailer"
#endif
#else
#define JOURNAL_DUAL 0
#define JOURNAL_FIRST_SLOT 0
/* Number of slots available for the journal log */
#define JOURNAL_LOG_SLOTS (JOURNAL_SLOTS - 1)
/* The last slot is reserved for the erase marker */
#define JOURNAL_MARK_SLOT (JOURNAL_SLOTS - 1)
/* An update logs magic, UPDATING, three flags per sector and FINAL_FLAGS.
* The bootloader also skips one slot when it loads the log. */
#if JOURNAL_LOG_SLOTS < (3 * (JOURNAL_PART_SECTORS - 1) + 4)
#error "NVM_FLASH_JOURNAL: trailer sector can't log a full-partition update"
#endif
#endif /* NVM_FLASH_JOURNAL_DUAL */
#define JOURNAL_TAG 0x4A01U /* 'J', format version 1 */
/* Header and commit records of the dual mode hold the generation number in
* data. The offset of a header is the number of records in the copy. */
#define JOURNAL_TAG_HEADER 0x4A02U
#define JOURNAL_TAG_COMMIT 0x4A03U
struct journal_rec {
uint16_t tag;
uint16_t seq; /* record number, from 0 after each erase */
uint16_t offset; /* first trailer byte written */
uint16_t len;
uint8_t data[4];
uint32_t crc; /* CRC32 of the fields above */
};
#define JOURNAL_REC_CRC_LEN 12
/* Journal state values */
#define JOURNAL_UNLOADED 0
#define JOURNAL_READY 1
#define JOURNAL_ERASE 2 /* invalid log, start a new one before next write */
#define JOURNAL_COMPACT 3 /* in-place trailer, rewrite it as records */
struct journal {
uint32_t trailer[JOURNAL_TRAILER_SIZE / 4]; /* RAM copy of the trailer */
uintptr_t check_addr; /* stays programmed while the RAM copy is current */
uint32_t gen; /* dual mode, highest generation in a header */
uint16_t check_len;
uint16_t next_slot;
uint16_t next_seq;
uint8_t state;
uint8_t active; /* dual mode, sector in use where 0 is the last one */
};
static struct journal journals[2]; /* PART_BOOT, PART_UPDATE */
static uintptr_t RAMFUNCTION journal_end(uint8_t part)
{
return (part == PART_BOOT) ? (uintptr_t)PART_BOOT_ENDFLAGS :
(uintptr_t)PART_UPDATE_ENDFLAGS;
}
/* Start of the sector in use. The other sector of the dual mode is the one
* before the last sector. */
static uintptr_t RAMFUNCTION journal_base(uint8_t part,
const struct journal *j)
{
return (((journal_end(part) - 1) / WOLFBOOT_SECTOR_SIZE) - j->active) *
WOLFBOOT_SECTOR_SIZE;
}
static int RAMFUNCTION journal_read(uint8_t part, uintptr_t addr, void *buf,
int len)
{
uint8_t *dst = (uint8_t *)buf;
#ifdef EXT_FLASH
if (PARTN_IS_EXT(part))
return (ext_flash_read(addr, dst, len) == len) ? 0 : -1;
#endif
while (len > 0) {
int n = WOLFBOOT_FLASH_WRITE_UNIT -
(int)(addr % WOLFBOOT_FLASH_WRITE_UNIT);
if (n > len)
n = len;
#ifdef NVM_FLASH_ECC
/* A read of an erased ECC unit can fault, so check it first */
if (hal_flash_is_erased(addr, n) == 1)
XMEMSET(dst, FLASH_BYTE_ERASED, n);
else
#endif
XMEMCPY(dst, (void *)addr, n);
addr += n;
dst += n;
len -= n;
}
return 0;
}
static int RAMFUNCTION journal_flash_write(uint8_t part, uintptr_t addr,
const uint8_t *data, int len)
{
#ifdef EXT_FLASH
if (PARTN_IS_EXT(part))
return ext_flash_write(addr, data, len);
#endif
return hal_flash_write(addr, data, len);
}
static int RAMFUNCTION journal_flash_erase(uint8_t part, uintptr_t addr,
int len)
{
#ifdef EXT_FLASH
if (PARTN_IS_EXT(part))
return ext_flash_erase(addr, len);
#endif
return hal_flash_erase(addr, len);
}
static void RAMFUNCTION journal_reset(struct journal *j)
{
XMEMSET(j->trailer, FLASH_BYTE_ERASED, JOURNAL_TRAILER_SIZE);
j->check_len = 0;
j->next_slot = 0;
j->next_seq = 0;
j->state = JOURNAL_READY;
}
/* An unloaded journal has an empty RAM copy, so the trailer reads as missing
* until a load succeeds */
static void RAMFUNCTION journal_unload(struct journal *j)
{
journal_reset(j);
j->state = JOURNAL_UNLOADED;
}
static int RAMFUNCTION journal_rec_ok(const struct journal_rec *rec)
{
return (rec->tag == JOURNAL_TAG) && (rec->len >= 1) &&
(rec->len <= sizeof(rec->data)) &&
(rec->offset + rec->len <= JOURNAL_TRAILER_SIZE) &&
(rec->crc == wb_crc32(rec, JOURNAL_REC_CRC_LEN));
}
struct journal_scan {
int last; /* slot of the last record, or -1 */
int junk; /* bad slots after the last record */
int gap; /* a record is missing */
int commit; /* the commit record of the generation is present */
};
/* Replay the sector in use into the RAM copy and set up the next write.
* Return -1 if a flash check fails. */
static int RAMFUNCTION journal_scan(uint8_t part, struct journal *j,
uint32_t gen, struct journal_scan *s)
{
uintptr_t base = journal_base(part, j);
struct journal_rec rec;
int slot, erased;
s->last = -1;
s->junk = 0;
s->gap = 0;
s->commit = 0;
for (slot = JOURNAL_FIRST_SLOT; slot < JOURNAL_LOG_SLOTS; slot++) {
uintptr_t addr = base + (uintptr_t)slot * JOURNAL_SLOT_SIZE;
erased = part_is_erased(part, addr, JOURNAL_SLOT_SIZE);
if (erased < 0)
return -1;
if (erased) {
/* Stop once the rest of the log is blank */
erased = part_is_erased(part, addr,
(JOURNAL_LOG_SLOTS - slot) * JOURNAL_SLOT_SIZE);
if (erased < 0)
return -1;
if (erased)
break;
continue;
}
if (journal_read(part, addr, &rec, sizeof(rec)) != 0) {
s->junk++;
continue;
}
if (journal_rec_ok(&rec)) {
/* A retried append can potentially repeat the previous seq number.
* Apply the repeat, as it is either the same record, or a later
* write that reused the number after a failed append. */
if ((rec.seq != j->next_seq) && (rec.seq + 1 != j->next_seq)) {
s->gap = 1;
break;
}
XMEMCPY((uint8_t *)j->trailer + rec.offset, rec.data, rec.len);
if (rec.seq == j->next_seq) {
j->next_seq++;
}
}
else if (JOURNAL_DUAL && (rec.tag == JOURNAL_TAG_COMMIT) &&
(rec.crc == wb_crc32(&rec, JOURNAL_REC_CRC_LEN)) &&
(XMEMCMP(rec.data, &gen, sizeof(gen)) == 0)) {
s->commit = 1;
}
else {
s->junk++;
continue;
}
s->last = slot;
s->junk = 0;
}
if (s->last >= 0) {
j->check_addr = base + (uintptr_t)s->last * JOURNAL_SLOT_SIZE;
j->check_len = JOURNAL_SLOT_SIZE;
}
/* A write cut by the last reset can still read as erased, so the next
* write skips the slot after the last record */
j->next_slot = (uint16_t)(s->last + 2);
return 0;
}
/* A journal never writes the in-place trailer area, so a magic there means
* the sector holds a trailer in the in-place format. Return 1 if it was read
* and -1 if a read fails. */
static int RAMFUNCTION journal_import(uint8_t part, struct journal *j)
{
uintptr_t addr = journal_end(part) - JOURNAL_TRAILER_SIZE;
uint32_t magic;
if (journal_read(part, addr + JOURNAL_TRAILER_SIZE - 4, &magic, 4) != 0)
return -1;
if (magic != WOLFBOOT_MAGIC_TRAIL)
return 0;
if (journal_read(part, addr, j->trailer, JOURNAL_TRAILER_SIZE) != 0)
return -1;
j->check_addr = addr + JOURNAL_TRAILER_SIZE - 4;
j->check_len = 4;
j->state = JOURNAL_COMPACT;
return 1;
}
/* Program one record into the next free slot and check it reads back. A
* slot that is not erased, or that fails, is skipped. A failed program can
* still land, so the record can end up in the log twice. */
static int RAMFUNCTION journal_append(uint8_t part, struct journal *j,
uint16_t tag, uint16_t offset, const uint8_t *data, uint16_t len)
{
union {
struct journal_rec rec;
uint8_t raw[JOURNAL_SLOT_SIZE];
} buf, chk;
uintptr_t base = journal_base(part, j);
int tries = 0;
XMEMSET(buf.raw, FLASH_BYTE_ERASED, sizeof(buf.raw));
buf.rec.tag = tag;
buf.rec.seq = j->next_seq;
buf.rec.offset = offset;
buf.rec.len = len;
XMEMCPY(buf.rec.data, data, len);
buf.rec.crc = wb_crc32(&buf.rec, JOURNAL_REC_CRC_LEN);
while ((j->next_slot < JOURNAL_LOG_SLOTS) && (tries < 3)) {
uintptr_t addr = base + (uintptr_t)j->next_slot * JOURNAL_SLOT_SIZE;
j->next_slot++;
if (part_is_erased(part, addr, JOURNAL_SLOT_SIZE) != 1)
continue;
tries++;
if ((journal_flash_write(part, addr, buf.raw, JOURNAL_SLOT_SIZE) != 0)
|| (journal_read(part, addr, chk.raw, JOURNAL_SLOT_SIZE) != 0)
|| (XMEMCMP(buf.raw, chk.raw, JOURNAL_SLOT_SIZE) != 0)) {
continue;
}
/* Header and commit records do not change the trailer */
if (tag == JOURNAL_TAG) {
XMEMCPY((uint8_t *)j->trailer + offset, data, len);
j->next_seq++;
}
j->check_addr = addr;
j->check_len = JOURNAL_SLOT_SIZE;
return 0;
}
return -1;
}
#ifdef NVM_FLASH_JOURNAL_DUAL
/* Read the header of the sector in use. Return 1 if it is valid, 0 if not,
* and -1 if a flash check fails. */
static int RAMFUNCTION journal_header(uint8_t part, struct journal *j,
uint32_t *gen, uint16_t *count)
{
uintptr_t addr = journal_base(part, j);
struct journal_rec rec;
int erased = part_is_erased(part, addr, JOURNAL_SLOT_SIZE);
if (erased != 0)
return (erased < 0) ? -1 : 0;
if ((journal_read(part, addr, &rec, sizeof(rec)) != 0) ||
(rec.tag != JOURNAL_TAG_HEADER) ||
(rec.crc != wb_crc32(&rec, JOURNAL_REC_CRC_LEN)))
return 0;
XMEMCPY(gen, rec.data, sizeof(*gen));
*count = rec.offset;
return 1;
}
/* Replay the newest sector that holds a complete log. A new log is complete
* once its commit record, or a record after its copy, is in flash. */
static void RAMFUNCTION journal_load(uint8_t part, struct journal *j)
{
struct journal_scan s;
uint32_t gen[2];
uint16_t count[2];
int valid[2], i, sec, newer;
journal_unload(j);
j->gen = 0;
for (sec = 0; sec < 2; sec++) {
j->active = (uint8_t)sec;
valid[sec] = journal_header(part, j, &gen[sec], &count[sec]);
if (valid[sec] < 0)
return;
if ((valid[sec] == 1) && (gen[sec] > j->gen))
j->gen = gen[sec];
}
newer = (valid[1] == 1) && ((valid[0] != 1) || (gen[1] > gen[0]));
for (i = 0; i < 2; i++) {
sec = (i == 0) ? newer : !newer;
if (valid[sec] != 1)
continue;
journal_unload(j);
j->active = (uint8_t)sec;
if (journal_scan(part, j, gen[sec], &s) != 0) {
/* Drop the partial replay */
journal_unload(j);
return;
}
if (!s.commit && (j->next_seq <= count[sec]))
continue;
if (s.gap) {
/* A record that was valid before is now unreadable */
journal_reset(j);
j->state = JOURNAL_ERASE;
return;
}
j->state = JOURNAL_READY;
return;
}
/* No complete log. The next write starts one in the sector before the
* last one. */
journal_reset(j);
j->active = 0;
i = journal_import(part, j);
if (i < 0)
journal_unload(j);
else if (i == 0)
j->state = JOURNAL_ERASE;
}
/* Start a new log in the other sector with a header, a copy of the trailer
* and a commit record. The old log stays valid until the commit is in flash. */
static int RAMFUNCTION journal_newgen(uint8_t part, struct journal *j)
{
uint32_t copy[JOURNAL_TRAILER_SIZE / 4];
uint32_t gen = j->gen + 1;
uint16_t count = 0;
int i, ret;
if (j->state == JOURNAL_UNLOADED)
return -1;
XMEMCPY(copy, j->trailer, JOURNAL_TRAILER_SIZE);
for (i = 0; i < JOURNAL_TRAILER_SIZE; i += 4) {
if (copy[i / 4] != FLASH_WORD_ERASED)
count++;
}
j->active = (uint8_t)!j->active;
ret = journal_flash_erase(part, journal_base(part, j),
WOLFBOOT_SECTOR_SIZE);
journal_reset(j);
if (ret == 0) {
ret = journal_append(part, j, JOURNAL_TAG_HEADER, count,
(const uint8_t *)&gen, sizeof(gen));
/* The load looks for the header in slot 0 only */
if ((ret == 0) && (j->next_slot != 1))
ret = -1;
}
for (i = 0; (ret == 0) && (i < JOURNAL_TRAILER_SIZE); i += 4) {
if (copy[i / 4] != FLASH_WORD_ERASED) {
ret = journal_append(part, j, JOURNAL_TAG, (uint16_t)i,
(const uint8_t *)copy + i, 4);
}
}
if (ret == 0) {
ret = journal_append(part, j, JOURNAL_TAG_COMMIT, 0,
(const uint8_t *)&gen, sizeof(gen));
}