/
main.c
1662 lines (1435 loc) · 51.7 KB
/
main.c
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
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include "py/mphal.h"
#include "lib/crypto-algorithms/sha256.c"
#include "boardctrl.h"
#include "usbd_core.h"
#include "storage.h"
#include "flash.h"
#include "i2cslave.h"
#include "irq.h"
#include "mboot.h"
#include "powerctrl.h"
#include "dfu.h"
#include "pack.h"
// Whether the bootloader will leave via reset, or direct jump to the application.
#ifndef MBOOT_LEAVE_BOOTLOADER_VIA_RESET
#define MBOOT_LEAVE_BOOTLOADER_VIA_RESET (1)
#endif
// This option selects whether to use explicit polling or IRQs for USB events.
// In some test cases polling mode can run slightly faster, but it uses more power.
// Polling mode will also cause failures with the mass-erase command because USB
// events will not be serviced for the duration of the mass erase.
// With STM32WB MCUs only non-polling/IRQ mode is supported.
#define USE_USB_POLLING (0)
// Using cache probably won't make it faster because we run at a low frequency, and best
// to keep the MCU config as minimal as possible.
#define USE_CACHE (0)
// IRQ priorities (encoded values suitable for NVIC_SetPriority)
// Most values are defined in irq.h.
#define IRQ_PRI_I2C (NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 1, 0))
// Configure PLL to give the desired CPU freq
#undef MICROPY_HW_FLASH_LATENCY
#if defined(STM32F4) || defined(STM32F7)
#if MBOOT_ENABLE_PACKING
// With encryption/signing/compression, a faster CPU makes processing much faster.
#define CORE_PLL_FREQ (96000000)
#define MICROPY_HW_FLASH_LATENCY FLASH_LATENCY_3
#else
#define CORE_PLL_FREQ (48000000)
#define MICROPY_HW_FLASH_LATENCY FLASH_LATENCY_1
#endif
#elif defined(STM32H7)
#define CORE_PLL_FREQ (96000000)
#define MICROPY_HW_FLASH_LATENCY FLASH_LATENCY_2
#endif
#undef MICROPY_HW_CLK_PLLM
#undef MICROPY_HW_CLK_PLLN
#undef MICROPY_HW_CLK_PLLP
#undef MICROPY_HW_CLK_PLLQ
#undef MICROPY_HW_CLK_PLLR
#define MICROPY_HW_CLK_PLLM (HSE_VALUE / 1000000)
#define MICROPY_HW_CLK_PLLN (192)
#define MICROPY_HW_CLK_PLLP (MICROPY_HW_CLK_PLLN / (CORE_PLL_FREQ / 1000000))
#define MICROPY_HW_CLK_PLLQ (4)
#define MICROPY_HW_CLK_PLLR (2)
// Work out which USB device to use for the USB DFU interface
#if !defined(MICROPY_HW_USB_MAIN_DEV)
#if MICROPY_HW_USB_FS
#define MICROPY_HW_USB_MAIN_DEV (USB_PHY_FS_ID)
#elif MICROPY_HW_USB_HS
#define MICROPY_HW_USB_MAIN_DEV (USB_PHY_HS_ID)
#else
#error Unable to determine proper MICROPY_HW_USB_MAIN_DEV to use
#endif
#endif
// These bits are used to detect valid application firmware at APPLICATION_ADDR
#define APP_VALIDITY_BITS (0x00000003)
// For 1ms system ticker.
static volatile uint32_t systick_ms;
// Global dfu state
dfu_context_t dfu_context SECTION_NOZERO_BSS;
uint32_t get_le32(const uint8_t *b) {
return b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24;
}
mp_uint_t mp_hal_ticks_ms(void) {
return systick_ms;
}
void mp_hal_delay_us(mp_uint_t usec) {
// use a busy loop for the delay
// sys freq is always a multiple of 2MHz, so division here won't lose precision
#if defined(CORE_PLL_FREQ)
const uint32_t ucount = CORE_PLL_FREQ / 2000000 * usec / 2;
#else
const uint32_t ucount = SystemCoreClock / 2000000 * usec / 2;
#endif
for (uint32_t count = 0; ++count <= ucount;) {
__NOP();
}
}
void mp_hal_delay_ms(mp_uint_t ms) {
if (__get_PRIMASK() == 0) {
// IRQs enabled, use systick
if (ms != 0 && ms != (mp_uint_t)-1) {
++ms; // account for the fact that systick_ms may roll over immediately
}
uint32_t start = systick_ms;
while (systick_ms - start < ms) {
__WFI();
}
} else {
// IRQs disabled, so need to use a busy loop for the delay.
// To prevent possible overflow of the counter we use a double loop.
const uint32_t count_1ms = 16000000 / 8000;
for (uint32_t i = 0; i < ms; i++) {
for (volatile uint32_t count = 0; ++count <= count_1ms;) {
}
}
}
}
// Needed by parts of the HAL
uint32_t HAL_GetTick(void) {
return systick_ms;
}
// Needed by parts of the HAL
void HAL_Delay(uint32_t ms) {
mp_hal_delay_ms(ms);
}
NORETURN static void __fatal_error(const char *msg) {
NVIC_SystemReset();
for (;;) {
}
}
/******************************************************************************/
// CLOCK
void systick_init(void) {
// Configure SysTick as 1ms ticker
SysTick_Config(SystemCoreClock / 1000);
NVIC_SetPriority(SysTick_IRQn, IRQ_PRI_SYSTICK);
}
#if defined(STM32F4) || defined(STM32F7)
void SystemClock_Config(void) {
// This function assumes that HSI is used as the system clock (see RCC->CFGR, SWS bits)
// Enable Power Control clock
__HAL_RCC_PWR_CLK_ENABLE();
// Reduce power consumption
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
// Turn HSE on
__HAL_RCC_HSE_CONFIG(RCC_HSE_ON);
while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) {
}
// Disable PLL
__HAL_RCC_PLL_DISABLE();
while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) {
}
// Configure PLL factors and source
RCC->PLLCFGR =
1 << RCC_PLLCFGR_PLLSRC_Pos // HSE selected as PLL source
| MICROPY_HW_CLK_PLLM << RCC_PLLCFGR_PLLM_Pos
| MICROPY_HW_CLK_PLLN << RCC_PLLCFGR_PLLN_Pos
| ((MICROPY_HW_CLK_PLLP >> 1) - 1) << RCC_PLLCFGR_PLLP_Pos
| MICROPY_HW_CLK_PLLQ << RCC_PLLCFGR_PLLQ_Pos
#ifdef RCC_PLLCFGR_PLLR
| 2 << RCC_PLLCFGR_PLLR_Pos // default PLLR value of 2
#endif
;
// Enable PLL
__HAL_RCC_PLL_ENABLE();
while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) {
}
// Increase latency before changing clock
if (MICROPY_HW_FLASH_LATENCY > (FLASH->ACR & FLASH_ACR_LATENCY)) {
__HAL_FLASH_SET_LATENCY(MICROPY_HW_FLASH_LATENCY);
}
// Configure AHB divider
MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_SYSCLK_DIV1);
// Configure SYSCLK source from PLL
__HAL_RCC_SYSCLK_CONFIG(RCC_SYSCLKSOURCE_PLLCLK);
while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) {
}
// Decrease latency after changing clock
if (MICROPY_HW_FLASH_LATENCY < (FLASH->ACR & FLASH_ACR_LATENCY)) {
__HAL_FLASH_SET_LATENCY(MICROPY_HW_FLASH_LATENCY);
}
// Set APB clock dividers
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_HCLK_DIV4);
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, RCC_HCLK_DIV2 << 3);
// Update clock value and reconfigure systick now that the frequency changed
SystemCoreClock = CORE_PLL_FREQ;
systick_init();
#if defined(STM32F7)
// The DFU bootloader changes the clocksource register from its default power
// on reset value, so we set it back here, so the clocksources are the same
// whether we were started from DFU or from a power on reset.
RCC->DCKCFGR2 = 0;
#endif
}
#elif defined(STM32H7)
void SystemClock_Config(void) {
// This function assumes that HSI is used as the system clock (see RCC->CFGR, SWS bits)
// Select VOS level as high voltage to give reliable operation
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
while (__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY) == RESET) {
}
// Turn HSE on
__HAL_RCC_HSE_CONFIG(RCC_HSE_ON);
while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) {
}
// Disable PLL1
__HAL_RCC_PLL_DISABLE();
while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) {
}
// Configure PLL1 factors and source
RCC->PLLCKSELR =
MICROPY_HW_CLK_PLLM << RCC_PLLCKSELR_DIVM1_Pos
| 2 << RCC_PLLCKSELR_PLLSRC_Pos; // HSE selected as PLL source
RCC->PLL1DIVR =
(MICROPY_HW_CLK_PLLN - 1) << RCC_PLL1DIVR_N1_Pos
| (MICROPY_HW_CLK_PLLP - 1) << RCC_PLL1DIVR_P1_Pos // only even P allowed
| (MICROPY_HW_CLK_PLLQ - 1) << RCC_PLL1DIVR_Q1_Pos
| (MICROPY_HW_CLK_PLLR - 1) << RCC_PLL1DIVR_R1_Pos;
// Enable PLL1 outputs for SYSCLK and USB
RCC->PLLCFGR = RCC_PLLCFGR_DIVP1EN | RCC_PLLCFGR_DIVQ1EN;
// Select PLL1-Q for USB clock source
RCC->D2CCIP2R |= 1 << RCC_D2CCIP2R_USBSEL_Pos;
// Enable PLL1
__HAL_RCC_PLL_ENABLE();
while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) {
}
// Increase latency before changing SYSCLK
if (MICROPY_HW_FLASH_LATENCY > (FLASH->ACR & FLASH_ACR_LATENCY)) {
__HAL_FLASH_SET_LATENCY(MICROPY_HW_FLASH_LATENCY);
}
// Configure AHB divider
RCC->D1CFGR =
0 << RCC_D1CFGR_D1CPRE_Pos // SYSCLK prescaler of 1
| 8 << RCC_D1CFGR_HPRE_Pos // AHB prescaler of 2
;
// Configure SYSCLK source from PLL
__HAL_RCC_SYSCLK_CONFIG(RCC_SYSCLKSOURCE_PLLCLK);
while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL1) {
}
// Decrease latency after changing clock
if (MICROPY_HW_FLASH_LATENCY < (FLASH->ACR & FLASH_ACR_LATENCY)) {
__HAL_FLASH_SET_LATENCY(MICROPY_HW_FLASH_LATENCY);
}
// Set APB clock dividers
RCC->D1CFGR |=
4 << RCC_D1CFGR_D1PPRE_Pos // APB3 prescaler of 2
;
RCC->D2CFGR =
4 << RCC_D2CFGR_D2PPRE2_Pos // APB2 prescaler of 2
| 4 << RCC_D2CFGR_D2PPRE1_Pos // APB1 prescaler of 2
;
RCC->D3CFGR =
4 << RCC_D3CFGR_D3PPRE_Pos // APB4 prescaler of 2
;
// Update clock value and reconfigure systick now that the frequency changed
SystemCoreClock = CORE_PLL_FREQ;
systick_init();
}
#endif
/******************************************************************************/
// GPIO
#if defined(STM32F4) || defined(STM32F7)
#define AHBxENR AHB1ENR
#define AHBxENR_GPIOAEN_Pos RCC_AHB1ENR_GPIOAEN_Pos
#elif defined(STM32H7)
#define AHBxENR AHB4ENR
#define AHBxENR_GPIOAEN_Pos RCC_AHB4ENR_GPIOAEN_Pos
#elif defined(STM32WB)
#define AHBxENR AHB2ENR
#define AHBxENR_GPIOAEN_Pos RCC_AHB2ENR_GPIOAEN_Pos
#endif
void mp_hal_pin_config(mp_hal_pin_obj_t port_pin, uint32_t mode, uint32_t pull, uint32_t alt) {
GPIO_TypeDef *gpio = (GPIO_TypeDef*)(port_pin & ~0xf);
// Enable the GPIO peripheral clock
uint32_t gpio_idx = ((uintptr_t)gpio - GPIOA_BASE) / (GPIOB_BASE - GPIOA_BASE);
RCC->AHBxENR |= 1 << (AHBxENR_GPIOAEN_Pos + gpio_idx);
volatile uint32_t tmp = RCC->AHBxENR; // Delay after enabling clock
(void)tmp;
// Configure the pin
uint32_t pin = port_pin & 0xf;
gpio->MODER = (gpio->MODER & ~(3 << (2 * pin))) | ((mode & 3) << (2 * pin));
gpio->OTYPER = (gpio->OTYPER & ~(1 << pin)) | ((mode >> 2) << pin);
gpio->OSPEEDR = (gpio->OSPEEDR & ~(3 << (2 * pin))) | (2 << (2 * pin)); // full speed
gpio->PUPDR = (gpio->PUPDR & ~(3 << (2 * pin))) | (pull << (2 * pin));
gpio->AFR[pin >> 3] = (gpio->AFR[pin >> 3] & ~(15 << (4 * (pin & 7)))) | (alt << (4 * (pin & 7)));
}
void mp_hal_pin_config_speed(uint32_t port_pin, uint32_t speed) {
GPIO_TypeDef *gpio = (GPIO_TypeDef*)(port_pin & ~0xf);
uint32_t pin = port_pin & 0xf;
gpio->OSPEEDR = (gpio->OSPEEDR & ~(3 << (2 * pin))) | (speed << (2 * pin));
}
/******************************************************************************/
// LED
#if defined(MBOOT_LED1)
#define LED0 MBOOT_LED1
#elif defined(MICROPY_HW_LED1)
#define LED0 MICROPY_HW_LED1
#endif
#if defined(MBOOT_LED2)
#define LED1 MBOOT_LED2
#elif defined(MICROPY_HW_LED2)
#define LED1 MICROPY_HW_LED2
#endif
#if defined(MBOOT_LED3)
#define LED2 MBOOT_LED3
#elif defined(MICROPY_HW_LED3)
#define LED2 MICROPY_HW_LED3
#endif
#if defined(MBOOT_LED4)
#define LED3 MBOOT_LED4
#elif defined(MICROPY_HW_LED4)
#define LED3 MICROPY_HW_LED4
#endif
// For flashing states: bit 0 is "active", bit 1 is "inactive", bits 2-6 are flash rate.
typedef enum {
LED0_STATE_OFF = 0,
LED0_STATE_ON = 1,
LED0_STATE_SLOW_FLASH = (20 << 2) | 1,
LED0_STATE_FAST_FLASH = (2 << 2) | 1,
LED0_STATE_SLOW_INVERTED_FLASH = (20 << 2) | 2,
} led0_state_t;
static led0_state_t led0_cur_state = LED0_STATE_OFF;
static uint32_t led0_ms_interval = 0;
static int led0_toggle_count = 0;
MP_WEAK void led_init(void) {
#if defined(MBOOT_BOARD_LED_INIT)
// Custom LED init function provided by the board.
MBOOT_BOARD_LED_INIT();
#else
// Init LEDs using GPIO calls.
mp_hal_pin_output(LED0);
#ifdef LED1
mp_hal_pin_output(LED1);
#endif
#ifdef LED2
mp_hal_pin_output(LED2);
#endif
#ifdef LED3
mp_hal_pin_output(LED3);
#endif
#endif
led0_cur_state = LED0_STATE_OFF;
}
MP_WEAK void led_state(uint32_t led, int val) {
#if defined(MBOOT_BOARD_LED_STATE)
// Custom LED state function provided by the board.
return MBOOT_BOARD_LED_STATE(led, val);
#else
// Set LEDs using GPIO calls.
if (val) {
MICROPY_HW_LED_ON(led);
} else {
MICROPY_HW_LED_OFF(led);
}
#endif
}
void led_state_all(unsigned int mask) {
led_state(LED0, mask & 1);
#ifdef LED1
led_state(LED1, mask & 2);
#endif
#ifdef LED2
led_state(LED2, mask & 4);
#endif
#ifdef LED3
led_state(LED3, mask & 8);
#endif
}
void led0_state(led0_state_t state) {
led0_cur_state = state;
if (state == LED0_STATE_OFF || state == LED0_STATE_ON) {
led_state(LED0, state);
}
}
void led0_update() {
if (led0_cur_state != LED0_STATE_OFF && systick_ms - led0_ms_interval > 50) {
uint8_t rate = (led0_cur_state >> 2) & 0x1f;
led0_ms_interval += 50;
if (++led0_toggle_count >= rate) {
led0_toggle_count = 0;
}
led_state(LED0, (led0_cur_state & (led0_toggle_count == 0 ? 1 : 2)));
}
}
/******************************************************************************/
// FLASH
#if defined(STM32WB)
#define FLASH_END FLASH_END_ADDR
#endif
#define APPLICATION_FLASH_LENGTH (FLASH_END + 1 - APPLICATION_ADDR)
#ifndef MBOOT_SPIFLASH_LAYOUT
#define MBOOT_SPIFLASH_LAYOUT ""
#endif
#ifndef MBOOT_SPIFLASH2_LAYOUT
#define MBOOT_SPIFLASH2_LAYOUT ""
#endif
#if defined(STM32F4) \
|| defined(STM32F722xx) \
|| defined(STM32F723xx) \
|| defined(STM32F732xx) \
|| defined(STM32F733xx)
#define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/04*016Kg,01*064Kg,07*128Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
#elif defined(STM32F765xx) || defined(STM32F767xx) || defined(STM32F769xx)
#define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/04*032Kg,01*128Kg,07*256Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
#elif defined(STM32H743xx)
#define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/16*128Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
#elif defined(STM32H750xx)
#define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/01*128Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
#elif defined(STM32WB)
#define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/256*04Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
#endif
static int mboot_flash_mass_erase(void) {
// Erase all flash pages after mboot.
int ret = flash_erase(APPLICATION_ADDR, APPLICATION_FLASH_LENGTH / sizeof(uint32_t));
return ret;
}
static int mboot_flash_page_erase(uint32_t addr, uint32_t *next_addr) {
uint32_t sector_size = 0;
uint32_t sector_start = 0;
int32_t sector = flash_get_sector_info(addr, §or_start, §or_size);
if (sector <= 0) {
// Don't allow to erase the sector with this bootloader in it, or invalid sectors
dfu_context.status = DFU_STATUS_ERROR_ADDRESS;
dfu_context.error = (sector == 0) ? MBOOT_ERROR_STR_OVERWRITE_BOOTLOADER_IDX
: MBOOT_ERROR_STR_INVALID_ADDRESS_IDX;
return -MBOOT_ERRNO_FLASH_ERASE_DISALLOWED;
}
*next_addr = sector_start + sector_size;
// Erase the flash page.
int ret = flash_erase(sector_start, sector_size / sizeof(uint32_t));
if (ret != 0) {
return ret;
}
// Check the erase set bits to 1, at least for the first 256 bytes
for (int i = 0; i < 64; ++i) {
if (((volatile uint32_t*)sector_start)[i] != 0xffffffff) {
return -MBOOT_ERRNO_FLASH_ERASE_FAILED;
}
}
return 0;
}
static int mboot_flash_write(uint32_t addr, const uint8_t *src8, size_t len) {
int32_t sector = flash_get_sector_info(addr, NULL, NULL);
if (sector <= 0) {
// Don't allow to write the sector with this bootloader in it
dfu_context.status = DFU_STATUS_ERROR_ADDRESS;
dfu_context.error = (sector == 0) ? MBOOT_ERROR_STR_OVERWRITE_BOOTLOADER_IDX
: MBOOT_ERROR_STR_INVALID_ADDRESS_IDX;
return -MBOOT_ERRNO_FLASH_WRITE_DISALLOWED;
}
const uint32_t *src = (const uint32_t*)src8;
size_t num_word32 = (len + 3) / 4;
// Write the data to flash.
int ret = flash_write(addr, src, num_word32);
if (ret != 0) {
return ret;
}
// TODO verify data
return 0;
}
/******************************************************************************/
// Writable address space interface
static int do_mass_erase(void) {
// TODO spiflash erase ?
return mboot_flash_mass_erase();
}
#if defined(MBOOT_SPIFLASH_ADDR) || defined(MBOOT_SPIFLASH2_ADDR)
static int spiflash_page_erase(mp_spiflash_t *spif, uint32_t addr, uint32_t n_blocks) {
for (int i = 0; i < n_blocks; ++i) {
int ret = mp_spiflash_erase_block(spif, addr);
if (ret != 0) {
return ret;
}
addr += MP_SPIFLASH_ERASE_BLOCK_SIZE;
}
return 0;
}
#endif
int hw_page_erase(uint32_t addr, uint32_t *next_addr) {
int ret = -1;
led0_state(LED0_STATE_ON);
#if defined(MBOOT_SPIFLASH_ADDR)
if (MBOOT_SPIFLASH_ADDR <= addr && addr < MBOOT_SPIFLASH_ADDR + MBOOT_SPIFLASH_BYTE_SIZE) {
*next_addr = addr + MBOOT_SPIFLASH_ERASE_BLOCKS_PER_PAGE * MP_SPIFLASH_ERASE_BLOCK_SIZE;
ret = spiflash_page_erase(MBOOT_SPIFLASH_SPIFLASH,
addr - MBOOT_SPIFLASH_ADDR, MBOOT_SPIFLASH_ERASE_BLOCKS_PER_PAGE);
} else
#endif
#if defined(MBOOT_SPIFLASH2_ADDR)
if (MBOOT_SPIFLASH2_ADDR <= addr && addr < MBOOT_SPIFLASH2_ADDR + MBOOT_SPIFLASH2_BYTE_SIZE) {
*next_addr = addr + MBOOT_SPIFLASH2_ERASE_BLOCKS_PER_PAGE * MP_SPIFLASH_ERASE_BLOCK_SIZE;
ret = spiflash_page_erase(MBOOT_SPIFLASH2_SPIFLASH,
addr - MBOOT_SPIFLASH2_ADDR, MBOOT_SPIFLASH2_ERASE_BLOCKS_PER_PAGE);
} else
#endif
{
ret = mboot_flash_page_erase(addr, next_addr);
}
led0_state((ret == 0) ? LED0_STATE_SLOW_FLASH : LED0_STATE_SLOW_INVERTED_FLASH);
return ret;
}
void hw_read(uint32_t addr, int len, uint8_t *buf) {
led0_state(LED0_STATE_FAST_FLASH);
#if defined(MBOOT_SPIFLASH_ADDR)
if (MBOOT_SPIFLASH_ADDR <= addr && addr < MBOOT_SPIFLASH_ADDR + MBOOT_SPIFLASH_BYTE_SIZE) {
mp_spiflash_read(MBOOT_SPIFLASH_SPIFLASH, addr - MBOOT_SPIFLASH_ADDR, len, buf);
} else
#endif
#if defined(MBOOT_SPIFLASH2_ADDR)
if (MBOOT_SPIFLASH2_ADDR <= addr && addr < MBOOT_SPIFLASH2_ADDR + MBOOT_SPIFLASH2_BYTE_SIZE) {
mp_spiflash_read(MBOOT_SPIFLASH2_SPIFLASH, addr - MBOOT_SPIFLASH2_ADDR, len, buf);
} else
#endif
{
// Other addresses, just read directly from memory
memcpy(buf, (void*)addr, len);
}
led0_state(LED0_STATE_SLOW_FLASH);
}
int hw_write(uint32_t addr, const uint8_t *src8, size_t len) {
int ret = -1;
led0_state(LED0_STATE_FAST_FLASH);
#if defined(MBOOT_SPIFLASH_ADDR)
if (MBOOT_SPIFLASH_ADDR <= addr && addr < MBOOT_SPIFLASH_ADDR + MBOOT_SPIFLASH_BYTE_SIZE) {
ret = mp_spiflash_write(MBOOT_SPIFLASH_SPIFLASH, addr - MBOOT_SPIFLASH_ADDR, len, src8);
} else
#endif
#if defined(MBOOT_SPIFLASH2_ADDR)
if (MBOOT_SPIFLASH2_ADDR <= addr && addr < MBOOT_SPIFLASH2_ADDR + MBOOT_SPIFLASH2_BYTE_SIZE) {
ret = mp_spiflash_write(MBOOT_SPIFLASH2_SPIFLASH, addr - MBOOT_SPIFLASH2_ADDR, len, src8);
} else
#endif
if (flash_is_valid_addr(addr)) {
ret = mboot_flash_write(addr, src8, len);
} else {
dfu_context.status = DFU_STATUS_ERROR_ADDRESS;
dfu_context.error = MBOOT_ERROR_STR_INVALID_ADDRESS_IDX;
}
led0_state((ret == 0) ? LED0_STATE_SLOW_FLASH : LED0_STATE_SLOW_INVERTED_FLASH);
return ret;
}
int do_page_erase(uint32_t addr, uint32_t *next_addr) {
#if MBOOT_ENABLE_PACKING
// Erase handled automatically for packed mode.
return 0;
#else
return hw_page_erase(addr, next_addr);
#endif
}
void do_read(uint32_t addr, int len, uint8_t *buf) {
#if MBOOT_ENABLE_PACKING
// Read disabled on packed (encrypted) mode.
dfu_context.status = DFU_STATUS_ERROR_FILE;
dfu_context.error = MBOOT_ERROR_STR_INVALID_READ_IDX;
led0_state(LED0_STATE_SLOW_INVERTED_FLASH);
#else
hw_read(addr, len, buf);
#endif
}
int do_write(uint32_t addr, const uint8_t *src8, size_t len) {
#if MBOOT_ENABLE_PACKING
return mboot_pack_write(addr, src8, len);
#else
return hw_write(addr, src8, len);
#endif
}
/******************************************************************************/
// I2C slave interface
#if defined(MBOOT_I2C_SCL)
#define PASTE2(a, b) a ## b
#define PASTE3(a, b, c) a ## b ## c
#define EVAL_PASTE2(a, b) PASTE2(a, b)
#define EVAL_PASTE3(a, b, c) PASTE3(a, b, c)
#define MBOOT_I2Cx EVAL_PASTE2(I2C, MBOOT_I2C_PERIPH_ID)
#define I2Cx_EV_IRQn EVAL_PASTE3(I2C, MBOOT_I2C_PERIPH_ID, _EV_IRQn)
#define I2Cx_EV_IRQHandler EVAL_PASTE3(I2C, MBOOT_I2C_PERIPH_ID, _EV_IRQHandler)
#define I2C_CMD_BUF_LEN (129)
enum {
I2C_CMD_ECHO = 1,
I2C_CMD_GETID, // () -> u8*12 unique id, ASCIIZ mcu name, ASCIIZ board name
I2C_CMD_GETCAPS, // not implemented
I2C_CMD_RESET, // () -> ()
I2C_CMD_CONFIG, // not implemented
I2C_CMD_GETLAYOUT, // () -> ASCII string
I2C_CMD_MASSERASE, // () -> ()
I2C_CMD_PAGEERASE, // le32 -> ()
I2C_CMD_SETRDADDR, // le32 -> ()
I2C_CMD_SETWRADDR, // le32 -> ()
I2C_CMD_READ, // u8 -> bytes
I2C_CMD_WRITE, // bytes -> ()
I2C_CMD_COPY, // not implemented
I2C_CMD_CALCHASH, // le32 -> u8*32
I2C_CMD_MARKVALID, // () -> ()
};
typedef struct _i2c_obj_t {
volatile bool cmd_send_arg;
volatile bool cmd_arg_sent;
volatile int cmd_arg;
volatile uint32_t cmd_rdaddr;
volatile uint32_t cmd_wraddr;
volatile uint16_t cmd_buf_pos;
uint8_t cmd_buf[I2C_CMD_BUF_LEN];
} i2c_obj_t;
static i2c_obj_t i2c_obj;
void i2c_init(int addr) {
i2c_obj.cmd_send_arg = false;
mp_hal_pin_config(MBOOT_I2C_SCL, MP_HAL_PIN_MODE_ALT_OPEN_DRAIN, MP_HAL_PIN_PULL_NONE, MBOOT_I2C_ALTFUNC);
mp_hal_pin_config(MBOOT_I2C_SDA, MP_HAL_PIN_MODE_ALT_OPEN_DRAIN, MP_HAL_PIN_PULL_NONE, MBOOT_I2C_ALTFUNC);
i2c_slave_init(MBOOT_I2Cx, I2Cx_EV_IRQn, IRQ_PRI_I2C, addr);
}
int i2c_slave_process_addr_match(i2c_slave_t *i2c, int rw) {
if (i2c_obj.cmd_arg_sent) {
i2c_obj.cmd_send_arg = false;
}
i2c_obj.cmd_buf_pos = 0;
return 0; // ACK
}
int i2c_slave_process_rx_byte(i2c_slave_t *i2c, uint8_t val) {
if (i2c_obj.cmd_buf_pos < sizeof(i2c_obj.cmd_buf)) {
i2c_obj.cmd_buf[i2c_obj.cmd_buf_pos++] = val;
}
return 0; // ACK
}
void i2c_slave_process_rx_end(i2c_slave_t *i2c) {
if (i2c_obj.cmd_buf_pos == 0) {
return;
}
int len = i2c_obj.cmd_buf_pos - 1;
uint8_t *buf = i2c_obj.cmd_buf;
if (buf[0] == I2C_CMD_ECHO) {
++len;
} else if (buf[0] == I2C_CMD_GETID && len == 0) {
memcpy(buf, (uint8_t*)MP_HAL_UNIQUE_ID_ADDRESS, 12);
memcpy(buf + 12, MICROPY_HW_MCU_NAME, sizeof(MICROPY_HW_MCU_NAME));
memcpy(buf + 12 + sizeof(MICROPY_HW_MCU_NAME), MICROPY_HW_BOARD_NAME, sizeof(MICROPY_HW_BOARD_NAME) - 1);
len = 12 + sizeof(MICROPY_HW_MCU_NAME) + sizeof(MICROPY_HW_BOARD_NAME) - 1;
} else if (buf[0] == I2C_CMD_RESET && len == 0) {
dfu_context.leave_dfu = true;
} else if (buf[0] == I2C_CMD_GETLAYOUT && len == 0) {
len = strlen(FLASH_LAYOUT_STR);
memcpy(buf, FLASH_LAYOUT_STR, len);
} else if (buf[0] == I2C_CMD_MASSERASE && len == 0) {
len = do_mass_erase();
} else if (buf[0] == I2C_CMD_PAGEERASE && len == 4) {
uint32_t next_addr;
len = do_page_erase(get_le32(buf + 1), &next_addr);
} else if (buf[0] == I2C_CMD_SETRDADDR && len == 4) {
i2c_obj.cmd_rdaddr = get_le32(buf + 1);
len = 0;
} else if (buf[0] == I2C_CMD_SETWRADDR && len == 4) {
i2c_obj.cmd_wraddr = get_le32(buf + 1);
len = 0;
} else if (buf[0] == I2C_CMD_READ && len == 1) {
len = buf[1];
if (len > I2C_CMD_BUF_LEN) {
len = I2C_CMD_BUF_LEN;
}
do_read(i2c_obj.cmd_rdaddr, len, buf);
i2c_obj.cmd_rdaddr += len;
} else if (buf[0] == I2C_CMD_WRITE) {
if (i2c_obj.cmd_wraddr == APPLICATION_ADDR) {
// Mark the 2 lower bits to indicate invalid app firmware
buf[1] |= APP_VALIDITY_BITS;
}
int ret = do_write(i2c_obj.cmd_wraddr, buf + 1, len);
if (ret < 0) {
len = ret;
} else {
i2c_obj.cmd_wraddr += len;
len = 0;
}
} else if (buf[0] == I2C_CMD_CALCHASH && len == 4) {
uint32_t hashlen = get_le32(buf + 1);
static CRYAL_SHA256_CTX ctx;
sha256_init(&ctx);
sha256_update(&ctx, (const void*)i2c_obj.cmd_rdaddr, hashlen);
i2c_obj.cmd_rdaddr += hashlen;
sha256_final(&ctx, buf);
len = 32;
} else if (buf[0] == I2C_CMD_MARKVALID && len == 0) {
uint32_t buf;
buf = *(volatile uint32_t*)APPLICATION_ADDR;
if ((buf & APP_VALIDITY_BITS) != APP_VALIDITY_BITS) {
len = -1;
} else {
buf &= ~APP_VALIDITY_BITS;
int ret = do_write(APPLICATION_ADDR, (void*)&buf, 4);
if (ret < 0) {
len = ret;
} else {
buf = *(volatile uint32_t*)APPLICATION_ADDR;
if ((buf & APP_VALIDITY_BITS) != 0) {
len = -2;
} else {
len = 0;
}
}
}
} else {
len = -127;
}
i2c_obj.cmd_arg = len;
i2c_obj.cmd_send_arg = true;
i2c_obj.cmd_arg_sent = false;
}
uint8_t i2c_slave_process_tx_byte(i2c_slave_t *i2c) {
if (i2c_obj.cmd_send_arg) {
i2c_obj.cmd_arg_sent = true;
return i2c_obj.cmd_arg;
} else if (i2c_obj.cmd_buf_pos < sizeof(i2c_obj.cmd_buf)) {
return i2c_obj.cmd_buf[i2c_obj.cmd_buf_pos++];
} else {
return 0;
}
}
void i2c_slave_process_tx_end(i2c_slave_t *i2c) {
}
#endif // defined(MBOOT_I2C_SCL)
/******************************************************************************/
// DFU
static void dfu_init(void) {
dfu_context.state = DFU_STATE_IDLE;
dfu_context.cmd = DFU_CMD_NONE;
dfu_context.status = DFU_STATUS_OK;
dfu_context.error = 0;
dfu_context.leave_dfu = false;
dfu_context.addr = 0x08000000;
}
static int dfu_process_dnload(void) {
int ret = -1;
if (dfu_context.wBlockNum == 0) {
// download control commands
if (dfu_context.wLength >= 1 && dfu_context.buf[0] == DFU_CMD_DNLOAD_ERASE) {
if (dfu_context.wLength == 1) {
// mass erase
ret = do_mass_erase();
if (ret != 0) {
dfu_context.cmd = DFU_CMD_NONE;
}
} else if (dfu_context.wLength == 5) {
// erase page
uint32_t next_addr;
ret = do_page_erase(get_le32(&dfu_context.buf[1]), &next_addr);
}
} else if (dfu_context.wLength >= 1 && dfu_context.buf[0] == DFU_CMD_DNLOAD_SET_ADDRESS) {
if (dfu_context.wLength == 5) {
// set address
dfu_context.addr = get_le32(&dfu_context.buf[1]);
ret = 0;
}
}
} else if (dfu_context.wBlockNum > 1) {
// write data to memory
uint32_t addr = (dfu_context.wBlockNum - 2) * DFU_XFER_SIZE + dfu_context.addr;
ret = do_write(addr, dfu_context.buf, dfu_context.wLength);
}
if (ret == 0) {
return DFU_STATE_DNLOAD_IDLE;
} else {
return DFU_STATE_ERROR;
}
}
static void dfu_handle_rx(int cmd, int arg, int len, const void *buf) {
if (cmd == DFU_CLRSTATUS) {
// clear status
dfu_context.state = DFU_STATE_IDLE;
dfu_context.cmd = DFU_CMD_NONE;
dfu_context.status = DFU_STATUS_OK;
dfu_context.error = 0;
} else if (cmd == DFU_ABORT) {
// clear status
dfu_context.state = DFU_STATE_IDLE;
dfu_context.cmd = DFU_CMD_NONE;
dfu_context.status = DFU_STATUS_OK;
dfu_context.error = 0;
} else if (cmd == DFU_DNLOAD) {
if (len == 0) {
// exit DFU
dfu_context.cmd = DFU_CMD_EXIT;
} else {
// download
dfu_context.cmd = DFU_CMD_DNLOAD;
dfu_context.wBlockNum = arg;
dfu_context.wLength = len;
memcpy(dfu_context.buf, buf, len);
}
}
}
static void dfu_process(void) {
if (dfu_context.state == DFU_STATE_MANIFEST) {
// Set a flag to leave DFU mode from the main thread (here we are in an IRQ handler).
dfu_context.leave_dfu = true;
}
if (dfu_context.state == DFU_STATE_BUSY) {
if (dfu_context.cmd == DFU_CMD_DNLOAD) {
dfu_context.cmd = DFU_CMD_NONE;
dfu_context.state = dfu_process_dnload();
}
}
}
static int dfu_handle_tx(int cmd, int arg, int len, uint8_t *buf, int max_len) {
if (cmd == DFU_UPLOAD) {
if (arg >= 2) {
dfu_context.cmd = DFU_CMD_UPLOAD;
uint32_t addr = (arg - 2) * max_len + dfu_context.addr;
do_read(addr, len, buf);
return len;
}
} else if (cmd == DFU_GETSTATUS && len == 6) {
// execute command and get status
switch (dfu_context.cmd) {
case DFU_CMD_NONE:
break;
case DFU_CMD_EXIT:
dfu_context.state = DFU_STATE_MANIFEST;
break;
case DFU_CMD_UPLOAD:
dfu_context.state = DFU_STATE_UPLOAD_IDLE;
break;
case DFU_CMD_DNLOAD:
dfu_context.state = DFU_STATE_BUSY;
break;
default:
dfu_context.state = DFU_STATE_BUSY;
}
buf[0] = dfu_context.status; // bStatus
buf[1] = 0; // bwPollTimeout_lsb (ms)
buf[2] = 0; // bwPollTimeout (ms)
buf[3] = 0; // bwPollTimeout_msb (ms)
buf[4] = dfu_context.state; // bState
buf[5] = dfu_context.error; // iString
// Clear errors now they've been sent
dfu_context.status = DFU_STATUS_OK;
dfu_context.error = 0;
return 6;
} else if (cmd == DFU_GETSTATE && len == 1) {
buf[0] = dfu_context.state; // bState
return 1;
}
return -1;
}
/******************************************************************************/
// USB
#define USB_XFER_SIZE (DFU_XFER_SIZE)
#define USB_PHY_FS_ID (0)
#define USB_PHY_HS_ID (1)
typedef struct _pyb_usbdd_obj_t {
bool started;
bool tx_pending;
USBD_HandleTypeDef hUSBDDevice;
uint8_t bRequest;
uint16_t wValue;
uint16_t wLength;
__ALIGN_BEGIN uint8_t rx_buf[USB_XFER_SIZE] __ALIGN_END;