main.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2017-2018 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include "py/mphal.h"
  29. #include "extmod/crypto-algorithms/sha256.c"
  30. #include "usbd_core.h"
  31. #include "storage.h"
  32. #include "i2cslave.h"
  33. // Using polling is about 10% faster than not using it (and using IRQ instead)
  34. // This DFU code with polling runs in about 70% of the time of the ST bootloader
  35. #define USE_USB_POLLING (1)
  36. // Using cache probably won't make it faster because we run at 48MHz, and best
  37. // to keep the MCU config as minimal as possible.
  38. #define USE_CACHE (0)
  39. // IRQ priorities (encoded values suitable for NVIC_SetPriority)
  40. #define IRQ_PRI_SYSTICK (NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 0, 0))
  41. #define IRQ_PRI_I2C (NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 1, 0))
  42. // Configure PLL to give a 48MHz CPU freq
  43. #define CORE_PLL_FREQ (48000000)
  44. #undef MICROPY_HW_CLK_PLLM
  45. #undef MICROPY_HW_CLK_PLLN
  46. #undef MICROPY_HW_CLK_PLLP
  47. #undef MICROPY_HW_CLK_PLLQ
  48. #undef MICROPY_HW_FLASH_LATENCY
  49. #define MICROPY_HW_CLK_PLLM (HSE_VALUE / 1000000)
  50. #define MICROPY_HW_CLK_PLLN (192)
  51. #define MICROPY_HW_CLK_PLLP (RCC_PLLP_DIV4)
  52. #define MICROPY_HW_CLK_PLLQ (4)
  53. #define MICROPY_HW_FLASH_LATENCY FLASH_LATENCY_1
  54. // Work out which USB device to use for the USB DFU interface
  55. #if !defined(MICROPY_HW_USB_MAIN_DEV)
  56. #if MICROPY_HW_USB_FS
  57. #define MICROPY_HW_USB_MAIN_DEV (USB_PHY_FS_ID)
  58. #elif MICROPY_HW_USB_HS && MICROPY_HW_USB_HS_IN_FS
  59. #define MICROPY_HW_USB_MAIN_DEV (USB_PHY_HS_ID)
  60. #else
  61. #error Unable to determine proper MICROPY_HW_USB_MAIN_DEV to use
  62. #endif
  63. #endif
  64. // These bits are used to detect valid application firmware at APPLICATION_ADDR
  65. #define APP_VALIDITY_BITS (0x00000003)
  66. #define MP_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  67. static void do_reset(void);
  68. static uint32_t get_le32(const uint8_t *b) {
  69. return b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24;
  70. }
  71. void mp_hal_delay_us(mp_uint_t usec) {
  72. // use a busy loop for the delay
  73. // sys freq is always a multiple of 2MHz, so division here won't lose precision
  74. const uint32_t ucount = CORE_PLL_FREQ / 2000000 * usec / 2;
  75. for (uint32_t count = 0; ++count <= ucount;) {
  76. }
  77. }
  78. static volatile uint32_t systick_ms;
  79. void mp_hal_delay_ms(mp_uint_t ms) {
  80. if (__get_PRIMASK() == 0) {
  81. // IRQs enabled, use systick
  82. if (ms != 0 && ms != (mp_uint_t)-1) {
  83. ++ms; // account for the fact that systick_ms may roll over immediately
  84. }
  85. uint32_t start = systick_ms;
  86. while (systick_ms - start < ms) {
  87. __WFI();
  88. }
  89. } else {
  90. // IRQs disabled, so need to use a busy loop for the delay.
  91. // To prevent possible overflow of the counter we use a double loop.
  92. const uint32_t count_1ms = 16000000 / 8000;
  93. for (uint32_t i = 0; i < ms; i++) {
  94. for (volatile uint32_t count = 0; ++count <= count_1ms;) {
  95. }
  96. }
  97. }
  98. }
  99. // Needed by parts of the HAL
  100. uint32_t HAL_GetTick(void) {
  101. return systick_ms;
  102. }
  103. // Needed by parts of the HAL
  104. void HAL_Delay(uint32_t ms) {
  105. mp_hal_delay_ms(ms);
  106. }
  107. static void __fatal_error(const char *msg) {
  108. NVIC_SystemReset();
  109. for (;;) {
  110. }
  111. }
  112. /******************************************************************************/
  113. // CLOCK
  114. #if defined(STM32F4) || defined(STM32F7)
  115. #define CONFIG_RCC_CR_1ST (RCC_CR_HSION)
  116. #define CONFIG_RCC_CR_2ND (RCC_CR_HSEON || RCC_CR_CSSON || RCC_CR_PLLON)
  117. #define CONFIG_RCC_PLLCFGR (0x24003010)
  118. #else
  119. #error Unknown processor
  120. #endif
  121. void SystemInit(void) {
  122. // Set HSION bit
  123. RCC->CR |= CONFIG_RCC_CR_1ST;
  124. // Reset CFGR register
  125. RCC->CFGR = 0x00000000;
  126. // Reset HSEON, CSSON and PLLON bits
  127. RCC->CR &= ~CONFIG_RCC_CR_2ND;
  128. // Reset PLLCFGR register
  129. RCC->PLLCFGR = CONFIG_RCC_PLLCFGR;
  130. // Reset HSEBYP bit
  131. RCC->CR &= (uint32_t)0xFFFBFFFF;
  132. // Disable all interrupts
  133. RCC->CIR = 0x00000000;
  134. // Set location of vector table
  135. SCB->VTOR = FLASH_BASE;
  136. // Enable 8-byte stack alignment for IRQ handlers, in accord with EABI
  137. SCB->CCR |= SCB_CCR_STKALIGN_Msk;
  138. }
  139. void systick_init(void) {
  140. // Configure SysTick as 1ms ticker
  141. SysTick_Config(SystemCoreClock / 1000);
  142. NVIC_SetPriority(SysTick_IRQn, IRQ_PRI_SYSTICK);
  143. }
  144. void SystemClock_Config(void) {
  145. // This function assumes that HSI is used as the system clock (see RCC->CFGR, SWS bits)
  146. // Enable Power Control clock
  147. __HAL_RCC_PWR_CLK_ENABLE();
  148. // Reduce power consumption
  149. __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  150. // Turn HSE on
  151. __HAL_RCC_HSE_CONFIG(RCC_HSE_ON);
  152. while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) {
  153. }
  154. // Disable PLL
  155. __HAL_RCC_PLL_DISABLE();
  156. while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) {
  157. }
  158. // Configure PLL factors and source
  159. RCC->PLLCFGR =
  160. 1 << RCC_PLLCFGR_PLLSRC_Pos // HSE selected as PLL source
  161. | MICROPY_HW_CLK_PLLM << RCC_PLLCFGR_PLLM_Pos
  162. | MICROPY_HW_CLK_PLLN << RCC_PLLCFGR_PLLN_Pos
  163. | ((MICROPY_HW_CLK_PLLP >> 1) - 1) << RCC_PLLCFGR_PLLP_Pos
  164. | MICROPY_HW_CLK_PLLQ << RCC_PLLCFGR_PLLQ_Pos
  165. #ifdef RCC_PLLCFGR_PLLR
  166. | 2 << RCC_PLLCFGR_PLLR_Pos // default PLLR value of 2
  167. #endif
  168. ;
  169. // Enable PLL
  170. __HAL_RCC_PLL_ENABLE();
  171. while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) {
  172. }
  173. // Increase latency before changing clock
  174. if (MICROPY_HW_FLASH_LATENCY > (FLASH->ACR & FLASH_ACR_LATENCY)) {
  175. __HAL_FLASH_SET_LATENCY(MICROPY_HW_FLASH_LATENCY);
  176. }
  177. // Configure AHB divider
  178. MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_SYSCLK_DIV1);
  179. // Configure SYSCLK source from PLL
  180. __HAL_RCC_SYSCLK_CONFIG(RCC_SYSCLKSOURCE_PLLCLK);
  181. while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) {
  182. }
  183. // Decrease latency after changing clock
  184. if (MICROPY_HW_FLASH_LATENCY < (FLASH->ACR & FLASH_ACR_LATENCY)) {
  185. __HAL_FLASH_SET_LATENCY(MICROPY_HW_FLASH_LATENCY);
  186. }
  187. // Set APB clock dividers
  188. MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_HCLK_DIV4);
  189. MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, RCC_HCLK_DIV2 << 3);
  190. // Update clock value and reconfigure systick now that the frequency changed
  191. SystemCoreClock = CORE_PLL_FREQ;
  192. systick_init();
  193. #if defined(STM32F7)
  194. // The DFU bootloader changes the clocksource register from its default power
  195. // on reset value, so we set it back here, so the clocksources are the same
  196. // whether we were started from DFU or from a power on reset.
  197. RCC->DCKCFGR2 = 0;
  198. #endif
  199. }
  200. // Needed by HAL_PCD_IRQHandler
  201. uint32_t HAL_RCC_GetHCLKFreq(void) {
  202. return SystemCoreClock;
  203. }
  204. /******************************************************************************/
  205. // GPIO
  206. void mp_hal_pin_config(mp_hal_pin_obj_t port_pin, uint32_t mode, uint32_t pull, uint32_t alt) {
  207. GPIO_TypeDef *gpio = (GPIO_TypeDef*)(port_pin & ~0xf);
  208. // Enable the GPIO peripheral clock
  209. uint32_t en_bit = RCC_AHB1ENR_GPIOAEN_Pos + ((uintptr_t)gpio - GPIOA_BASE) / (GPIOB_BASE - GPIOA_BASE);
  210. RCC->AHB1ENR |= 1 << en_bit;
  211. volatile uint32_t tmp = RCC->AHB1ENR; // Delay after enabling clock
  212. (void)tmp;
  213. // Configure the pin
  214. uint32_t pin = port_pin & 0xf;
  215. gpio->MODER = (gpio->MODER & ~(3 << (2 * pin))) | ((mode & 3) << (2 * pin));
  216. gpio->OTYPER = (gpio->OTYPER & ~(1 << pin)) | ((mode >> 2) << pin);
  217. gpio->OSPEEDR = (gpio->OSPEEDR & ~(3 << (2 * pin))) | (2 << (2 * pin)); // full speed
  218. gpio->PUPDR = (gpio->PUPDR & ~(3 << (2 * pin))) | (pull << (2 * pin));
  219. gpio->AFR[pin >> 3] = (gpio->AFR[pin >> 3] & ~(15 << (4 * (pin & 7)))) | (alt << (4 * (pin & 7)));
  220. }
  221. void mp_hal_pin_config_speed(uint32_t port_pin, uint32_t speed) {
  222. GPIO_TypeDef *gpio = (GPIO_TypeDef*)(port_pin & ~0xf);
  223. uint32_t pin = port_pin & 0xf;
  224. gpio->OSPEEDR = (gpio->OSPEEDR & ~(3 << (2 * pin))) | (speed << (2 * pin));
  225. }
  226. /******************************************************************************/
  227. // LED
  228. #define LED0 MICROPY_HW_LED1
  229. #define LED1 MICROPY_HW_LED2
  230. #define LED2 MICROPY_HW_LED3
  231. void led_init(void) {
  232. mp_hal_pin_output(LED0);
  233. mp_hal_pin_output(LED1);
  234. mp_hal_pin_output(LED2);
  235. }
  236. void led_state(int led, int val) {
  237. if (led == 1) {
  238. led = LED0;
  239. }
  240. if (val) {
  241. MICROPY_HW_LED_ON(led);
  242. } else {
  243. MICROPY_HW_LED_OFF(led);
  244. }
  245. }
  246. /******************************************************************************/
  247. // USR BUTTON
  248. static void usrbtn_init(void) {
  249. mp_hal_pin_config(MICROPY_HW_USRSW_PIN, MP_HAL_PIN_MODE_INPUT, MICROPY_HW_USRSW_PULL, 0);
  250. }
  251. static int usrbtn_state(void) {
  252. return mp_hal_pin_read(MICROPY_HW_USRSW_PIN) == MICROPY_HW_USRSW_PRESSED;
  253. }
  254. /******************************************************************************/
  255. // FLASH
  256. #ifndef MBOOT_SPIFLASH_LAYOUT
  257. #define MBOOT_SPIFLASH_LAYOUT ""
  258. #endif
  259. #ifndef MBOOT_SPIFLASH2_LAYOUT
  260. #define MBOOT_SPIFLASH2_LAYOUT ""
  261. #endif
  262. typedef struct {
  263. uint32_t base_address;
  264. uint32_t sector_size;
  265. uint32_t sector_count;
  266. } flash_layout_t;
  267. #if defined(STM32F7)
  268. // FLASH_FLAG_PGSERR (Programming Sequence Error) was renamed to
  269. // FLASH_FLAG_ERSERR (Erasing Sequence Error) in STM32F7
  270. #define FLASH_FLAG_PGSERR FLASH_FLAG_ERSERR
  271. #endif
  272. #if defined(STM32F4) \
  273. || defined(STM32F722xx) \
  274. || defined(STM32F723xx) \
  275. || defined(STM32F732xx) \
  276. || defined(STM32F733xx)
  277. #define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/04*016Kg,01*064Kg,07*128Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
  278. static const flash_layout_t flash_layout[] = {
  279. { 0x08000000, 0x04000, 4 },
  280. { 0x08010000, 0x10000, 1 },
  281. { 0x08020000, 0x20000, 3 },
  282. #if defined(FLASH_SECTOR_8)
  283. { 0x08080000, 0x20000, 4 },
  284. #endif
  285. #if defined(FLASH_SECTOR_12)
  286. { 0x08100000, 0x04000, 4 },
  287. { 0x08110000, 0x10000, 1 },
  288. { 0x08120000, 0x20000, 7 },
  289. #endif
  290. };
  291. #elif defined(STM32F767xx)
  292. #define FLASH_LAYOUT_STR "@Internal Flash /0x08000000/04*032Kg,01*128Kg,07*256Kg" MBOOT_SPIFLASH_LAYOUT MBOOT_SPIFLASH2_LAYOUT
  293. // This is for dual-bank mode disabled
  294. static const flash_layout_t flash_layout[] = {
  295. { 0x08000000, 0x08000, 4 },
  296. { 0x08020000, 0x20000, 1 },
  297. { 0x08040000, 0x40000, 7 },
  298. };
  299. #endif
  300. static uint32_t flash_get_sector_index(uint32_t addr) {
  301. if (addr >= flash_layout[0].base_address) {
  302. uint32_t sector_index = 0;
  303. for (int i = 0; i < MP_ARRAY_SIZE(flash_layout); ++i) {
  304. for (int j = 0; j < flash_layout[i].sector_count; ++j) {
  305. uint32_t sector_start_next = flash_layout[i].base_address
  306. + (j + 1) * flash_layout[i].sector_size;
  307. if (addr < sector_start_next) {
  308. return sector_index;
  309. }
  310. ++sector_index;
  311. }
  312. }
  313. }
  314. return 0;
  315. }
  316. static int flash_mass_erase(void) {
  317. // TODO
  318. return -1;
  319. }
  320. static int flash_page_erase(uint32_t addr) {
  321. uint32_t sector = flash_get_sector_index(addr);
  322. if (sector == 0) {
  323. // Don't allow to erase the sector with this bootloader in it
  324. return -1;
  325. }
  326. HAL_FLASH_Unlock();
  327. // Clear pending flags (if any)
  328. __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
  329. FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
  330. // erase the sector(s)
  331. FLASH_EraseInitTypeDef EraseInitStruct;
  332. EraseInitStruct.TypeErase = TYPEERASE_SECTORS;
  333. EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V
  334. EraseInitStruct.Sector = sector;
  335. EraseInitStruct.NbSectors = 1;
  336. uint32_t SectorError = 0;
  337. if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) {
  338. // error occurred during sector erase
  339. return -1;
  340. }
  341. // Check the erase set bits to 1, at least for the first 256 bytes
  342. for (int i = 0; i < 64; ++i) {
  343. if (((volatile uint32_t*)addr)[i] != 0xffffffff) {
  344. return -2;
  345. }
  346. }
  347. return 0;
  348. }
  349. static int flash_write(uint32_t addr, const uint8_t *src8, size_t len) {
  350. if (addr >= flash_layout[0].base_address && addr < flash_layout[0].base_address + flash_layout[0].sector_size) {
  351. // Don't allow to write the sector with this bootloader in it
  352. return -1;
  353. }
  354. const uint32_t *src = (const uint32_t*)src8;
  355. size_t num_word32 = (len + 3) / 4;
  356. HAL_FLASH_Unlock();
  357. // program the flash word by word
  358. for (size_t i = 0; i < num_word32; i++) {
  359. if (HAL_FLASH_Program(TYPEPROGRAM_WORD, addr, *src) != HAL_OK) {
  360. return -1;
  361. }
  362. addr += 4;
  363. src += 1;
  364. }
  365. // TODO verify data
  366. return 0;
  367. }
  368. /******************************************************************************/
  369. // Writable address space interface
  370. static int do_mass_erase(void) {
  371. // TODO
  372. return flash_mass_erase();
  373. }
  374. #if defined(MBOOT_SPIFLASH_ADDR) || defined(MBOOT_SPIFLASH2_ADDR)
  375. static int spiflash_page_erase(mp_spiflash_t *spif, uint32_t addr, uint32_t n_blocks) {
  376. for (int i = 0; i < n_blocks; ++i) {
  377. int ret = mp_spiflash_erase_block(spif, addr);
  378. if (ret != 0) {
  379. return ret;
  380. }
  381. addr += MP_SPIFLASH_ERASE_BLOCK_SIZE;
  382. }
  383. return 0;
  384. }
  385. #endif
  386. static int do_page_erase(uint32_t addr) {
  387. led_state(LED0, 1);
  388. #if defined(MBOOT_SPIFLASH_ADDR)
  389. if (MBOOT_SPIFLASH_ADDR <= addr && addr < MBOOT_SPIFLASH_ADDR + MBOOT_SPIFLASH_BYTE_SIZE) {
  390. return spiflash_page_erase(MBOOT_SPIFLASH_SPIFLASH,
  391. addr - MBOOT_SPIFLASH_ADDR, MBOOT_SPIFLASH_ERASE_BLOCKS_PER_PAGE);
  392. }
  393. #endif
  394. #if defined(MBOOT_SPIFLASH2_ADDR)
  395. if (MBOOT_SPIFLASH2_ADDR <= addr && addr < MBOOT_SPIFLASH2_ADDR + MBOOT_SPIFLASH2_BYTE_SIZE) {
  396. return spiflash_page_erase(MBOOT_SPIFLASH2_SPIFLASH,
  397. addr - MBOOT_SPIFLASH2_ADDR, MBOOT_SPIFLASH2_ERASE_BLOCKS_PER_PAGE);
  398. }
  399. #endif
  400. return flash_page_erase(addr);
  401. }
  402. static void do_read(uint32_t addr, int len, uint8_t *buf) {
  403. #if defined(MBOOT_SPIFLASH_ADDR)
  404. if (MBOOT_SPIFLASH_ADDR <= addr && addr < MBOOT_SPIFLASH_ADDR + MBOOT_SPIFLASH_BYTE_SIZE) {
  405. mp_spiflash_read(MBOOT_SPIFLASH_SPIFLASH, addr - MBOOT_SPIFLASH_ADDR, len, buf);
  406. return;
  407. }
  408. #endif
  409. #if defined(MBOOT_SPIFLASH2_ADDR)
  410. if (MBOOT_SPIFLASH2_ADDR <= addr && addr < MBOOT_SPIFLASH2_ADDR + MBOOT_SPIFLASH2_BYTE_SIZE) {
  411. mp_spiflash_read(MBOOT_SPIFLASH2_SPIFLASH, addr - MBOOT_SPIFLASH2_ADDR, len, buf);
  412. return;
  413. }
  414. #endif
  415. // Other addresses, just read directly from memory
  416. memcpy(buf, (void*)addr, len);
  417. }
  418. static int do_write(uint32_t addr, const uint8_t *src8, size_t len) {
  419. static uint32_t led_tog = 0;
  420. led_state(LED0, (led_tog++) & 4);
  421. #if defined(MBOOT_SPIFLASH_ADDR)
  422. if (MBOOT_SPIFLASH_ADDR <= addr && addr < MBOOT_SPIFLASH_ADDR + MBOOT_SPIFLASH_BYTE_SIZE) {
  423. return mp_spiflash_write(MBOOT_SPIFLASH_SPIFLASH, addr - MBOOT_SPIFLASH_ADDR, len, src8);
  424. }
  425. #endif
  426. #if defined(MBOOT_SPIFLASH2_ADDR)
  427. if (MBOOT_SPIFLASH2_ADDR <= addr && addr < MBOOT_SPIFLASH2_ADDR + MBOOT_SPIFLASH2_BYTE_SIZE) {
  428. return mp_spiflash_write(MBOOT_SPIFLASH2_SPIFLASH, addr - MBOOT_SPIFLASH2_ADDR, len, src8);
  429. }
  430. #endif
  431. return flash_write(addr, src8, len);
  432. }
  433. /******************************************************************************/
  434. // I2C slave interface
  435. #if defined(MBOOT_I2C_SCL)
  436. #define PASTE2(a, b) a ## b
  437. #define PASTE3(a, b, c) a ## b ## c
  438. #define EVAL_PASTE2(a, b) PASTE2(a, b)
  439. #define EVAL_PASTE3(a, b, c) PASTE3(a, b, c)
  440. #define MBOOT_I2Cx EVAL_PASTE2(I2C, MBOOT_I2C_PERIPH_ID)
  441. #define I2Cx_EV_IRQn EVAL_PASTE3(I2C, MBOOT_I2C_PERIPH_ID, _EV_IRQn)
  442. #define I2Cx_EV_IRQHandler EVAL_PASTE3(I2C, MBOOT_I2C_PERIPH_ID, _EV_IRQHandler)
  443. #define I2C_CMD_BUF_LEN (129)
  444. enum {
  445. I2C_CMD_ECHO = 1,
  446. I2C_CMD_GETID, // () -> u8*12 unique id, ASCIIZ mcu name, ASCIIZ board name
  447. I2C_CMD_GETCAPS, // not implemented
  448. I2C_CMD_RESET, // () -> ()
  449. I2C_CMD_CONFIG, // not implemented
  450. I2C_CMD_GETLAYOUT, // () -> ASCII string
  451. I2C_CMD_MASSERASE, // () -> ()
  452. I2C_CMD_PAGEERASE, // le32 -> ()
  453. I2C_CMD_SETRDADDR, // le32 -> ()
  454. I2C_CMD_SETWRADDR, // le32 -> ()
  455. I2C_CMD_READ, // u8 -> bytes
  456. I2C_CMD_WRITE, // bytes -> ()
  457. I2C_CMD_COPY, // not implemented
  458. I2C_CMD_CALCHASH, // le32 -> u8*32
  459. I2C_CMD_MARKVALID, // () -> ()
  460. };
  461. typedef struct _i2c_obj_t {
  462. volatile bool cmd_send_arg;
  463. volatile bool cmd_arg_sent;
  464. volatile int cmd_arg;
  465. volatile uint32_t cmd_rdaddr;
  466. volatile uint32_t cmd_wraddr;
  467. volatile uint16_t cmd_buf_pos;
  468. uint8_t cmd_buf[I2C_CMD_BUF_LEN];
  469. } i2c_obj_t;
  470. static i2c_obj_t i2c_obj;
  471. void i2c_init(int addr) {
  472. i2c_obj.cmd_send_arg = false;
  473. mp_hal_pin_config(MBOOT_I2C_SCL, MP_HAL_PIN_MODE_ALT_OPEN_DRAIN, MP_HAL_PIN_PULL_NONE, MBOOT_I2C_ALTFUNC);
  474. mp_hal_pin_config(MBOOT_I2C_SDA, MP_HAL_PIN_MODE_ALT_OPEN_DRAIN, MP_HAL_PIN_PULL_NONE, MBOOT_I2C_ALTFUNC);
  475. i2c_slave_init(MBOOT_I2Cx, I2Cx_EV_IRQn, IRQ_PRI_I2C, addr);
  476. }
  477. int i2c_slave_process_addr_match(int rw) {
  478. if (i2c_obj.cmd_arg_sent) {
  479. i2c_obj.cmd_send_arg = false;
  480. }
  481. i2c_obj.cmd_buf_pos = 0;
  482. return 0; // ACK
  483. }
  484. int i2c_slave_process_rx_byte(uint8_t val) {
  485. if (i2c_obj.cmd_buf_pos < sizeof(i2c_obj.cmd_buf)) {
  486. i2c_obj.cmd_buf[i2c_obj.cmd_buf_pos++] = val;
  487. }
  488. return 0; // ACK
  489. }
  490. void i2c_slave_process_rx_end(void) {
  491. if (i2c_obj.cmd_buf_pos == 0) {
  492. return;
  493. }
  494. int len = i2c_obj.cmd_buf_pos - 1;
  495. uint8_t *buf = i2c_obj.cmd_buf;
  496. if (buf[0] == I2C_CMD_ECHO) {
  497. ++len;
  498. } else if (buf[0] == I2C_CMD_GETID && len == 0) {
  499. memcpy(buf, (uint8_t*)MP_HAL_UNIQUE_ID_ADDRESS, 12);
  500. memcpy(buf + 12, MICROPY_HW_MCU_NAME, sizeof(MICROPY_HW_MCU_NAME));
  501. memcpy(buf + 12 + sizeof(MICROPY_HW_MCU_NAME), MICROPY_HW_BOARD_NAME, sizeof(MICROPY_HW_BOARD_NAME) - 1);
  502. len = 12 + sizeof(MICROPY_HW_MCU_NAME) + sizeof(MICROPY_HW_BOARD_NAME) - 1;
  503. } else if (buf[0] == I2C_CMD_RESET && len == 0) {
  504. do_reset();
  505. } else if (buf[0] == I2C_CMD_GETLAYOUT && len == 0) {
  506. len = strlen(FLASH_LAYOUT_STR);
  507. memcpy(buf, FLASH_LAYOUT_STR, len);
  508. } else if (buf[0] == I2C_CMD_MASSERASE && len == 0) {
  509. len = do_mass_erase();
  510. } else if (buf[0] == I2C_CMD_PAGEERASE && len == 4) {
  511. len = do_page_erase(get_le32(buf + 1));
  512. } else if (buf[0] == I2C_CMD_SETRDADDR && len == 4) {
  513. i2c_obj.cmd_rdaddr = get_le32(buf + 1);
  514. len = 0;
  515. } else if (buf[0] == I2C_CMD_SETWRADDR && len == 4) {
  516. i2c_obj.cmd_wraddr = get_le32(buf + 1);
  517. len = 0;
  518. } else if (buf[0] == I2C_CMD_READ && len == 1) {
  519. len = buf[1];
  520. if (len > I2C_CMD_BUF_LEN) {
  521. len = I2C_CMD_BUF_LEN;
  522. }
  523. do_read(i2c_obj.cmd_rdaddr, len, buf);
  524. i2c_obj.cmd_rdaddr += len;
  525. } else if (buf[0] == I2C_CMD_WRITE) {
  526. if (i2c_obj.cmd_wraddr == APPLICATION_ADDR) {
  527. // Mark the 2 lower bits to indicate invalid app firmware
  528. buf[1] |= APP_VALIDITY_BITS;
  529. }
  530. int ret = do_write(i2c_obj.cmd_wraddr, buf + 1, len);
  531. if (ret < 0) {
  532. len = ret;
  533. } else {
  534. i2c_obj.cmd_wraddr += len;
  535. len = 0;
  536. }
  537. } else if (buf[0] == I2C_CMD_CALCHASH && len == 4) {
  538. uint32_t hashlen = get_le32(buf + 1);
  539. static CRYAL_SHA256_CTX ctx;
  540. sha256_init(&ctx);
  541. sha256_update(&ctx, (const void*)i2c_obj.cmd_rdaddr, hashlen);
  542. i2c_obj.cmd_rdaddr += hashlen;
  543. sha256_final(&ctx, buf);
  544. len = 32;
  545. } else if (buf[0] == I2C_CMD_MARKVALID && len == 0) {
  546. uint32_t buf;
  547. buf = *(volatile uint32_t*)APPLICATION_ADDR;
  548. if ((buf & APP_VALIDITY_BITS) != APP_VALIDITY_BITS) {
  549. len = -1;
  550. } else {
  551. buf &= ~APP_VALIDITY_BITS;
  552. int ret = do_write(APPLICATION_ADDR, (void*)&buf, 4);
  553. if (ret < 0) {
  554. len = ret;
  555. } else {
  556. buf = *(volatile uint32_t*)APPLICATION_ADDR;
  557. if ((buf & APP_VALIDITY_BITS) != 0) {
  558. len = -2;
  559. } else {
  560. len = 0;
  561. }
  562. }
  563. }
  564. } else {
  565. len = -127;
  566. }
  567. i2c_obj.cmd_arg = len;
  568. i2c_obj.cmd_send_arg = true;
  569. i2c_obj.cmd_arg_sent = false;
  570. }
  571. uint8_t i2c_slave_process_tx_byte(void) {
  572. if (i2c_obj.cmd_send_arg) {
  573. i2c_obj.cmd_arg_sent = true;
  574. return i2c_obj.cmd_arg;
  575. } else if (i2c_obj.cmd_buf_pos < sizeof(i2c_obj.cmd_buf)) {
  576. return i2c_obj.cmd_buf[i2c_obj.cmd_buf_pos++];
  577. } else {
  578. return 0;
  579. }
  580. }
  581. #endif // defined(MBOOT_I2C_SCL)
  582. /******************************************************************************/
  583. // DFU
  584. #define DFU_XFER_SIZE (2048)
  585. enum {
  586. DFU_DNLOAD = 1,
  587. DFU_UPLOAD = 2,
  588. DFU_GETSTATUS = 3,
  589. DFU_CLRSTATUS = 4,
  590. DFU_ABORT = 6,
  591. };
  592. enum {
  593. DFU_STATUS_IDLE = 2,
  594. DFU_STATUS_BUSY = 4,
  595. DFU_STATUS_DNLOAD_IDLE = 5,
  596. DFU_STATUS_MANIFEST = 7,
  597. DFU_STATUS_UPLOAD_IDLE = 9,
  598. DFU_STATUS_ERROR = 0xa,
  599. };
  600. enum {
  601. DFU_CMD_NONE = 0,
  602. DFU_CMD_EXIT = 1,
  603. DFU_CMD_UPLOAD = 7,
  604. DFU_CMD_DNLOAD = 8,
  605. };
  606. typedef struct _dfu_state_t {
  607. int status;
  608. int cmd;
  609. uint16_t wBlockNum;
  610. uint16_t wLength;
  611. uint32_t addr;
  612. uint8_t buf[DFU_XFER_SIZE] __attribute__((aligned(4)));
  613. } dfu_state_t;
  614. static dfu_state_t dfu_state;
  615. static void dfu_init(void) {
  616. dfu_state.status = DFU_STATUS_IDLE;
  617. dfu_state.cmd = DFU_CMD_NONE;
  618. dfu_state.addr = 0x08000000;
  619. }
  620. static int dfu_process_dnload(void) {
  621. int ret = -1;
  622. if (dfu_state.wBlockNum == 0) {
  623. // download control commands
  624. if (dfu_state.wLength >= 1 && dfu_state.buf[0] == 0x41) {
  625. if (dfu_state.wLength == 1) {
  626. // mass erase
  627. ret = do_mass_erase();
  628. } else if (dfu_state.wLength == 5) {
  629. // erase page
  630. ret = do_page_erase(get_le32(&dfu_state.buf[1]));
  631. }
  632. } else if (dfu_state.wLength >= 1 && dfu_state.buf[0] == 0x21) {
  633. if (dfu_state.wLength == 5) {
  634. // set address
  635. dfu_state.addr = get_le32(&dfu_state.buf[1]);
  636. ret = 0;
  637. }
  638. }
  639. } else if (dfu_state.wBlockNum > 1) {
  640. // write data to memory
  641. ret = do_write(dfu_state.addr, dfu_state.buf, dfu_state.wLength);
  642. }
  643. if (ret == 0) {
  644. return DFU_STATUS_DNLOAD_IDLE;
  645. } else {
  646. return DFU_STATUS_ERROR;
  647. }
  648. }
  649. static void dfu_handle_rx(int cmd, int arg, int len, const void *buf) {
  650. if (cmd == DFU_CLRSTATUS) {
  651. // clear status
  652. dfu_state.status = DFU_STATUS_IDLE;
  653. dfu_state.cmd = DFU_CMD_NONE;
  654. } else if (cmd == DFU_ABORT) {
  655. // clear status
  656. dfu_state.status = DFU_STATUS_IDLE;
  657. dfu_state.cmd = DFU_CMD_NONE;
  658. } else if (cmd == DFU_DNLOAD) {
  659. if (len == 0) {
  660. // exit DFU
  661. dfu_state.cmd = DFU_CMD_EXIT;
  662. } else {
  663. // download
  664. dfu_state.cmd = DFU_CMD_DNLOAD;
  665. dfu_state.wBlockNum = arg;
  666. dfu_state.wLength = len;
  667. memcpy(dfu_state.buf, buf, len);
  668. }
  669. }
  670. }
  671. static void dfu_process(void) {
  672. if (dfu_state.status == DFU_STATUS_MANIFEST) {
  673. do_reset();
  674. }
  675. if (dfu_state.status == DFU_STATUS_BUSY) {
  676. if (dfu_state.cmd == DFU_CMD_DNLOAD) {
  677. dfu_state.cmd = DFU_CMD_NONE;
  678. dfu_state.status = dfu_process_dnload();
  679. }
  680. }
  681. }
  682. static int dfu_handle_tx(int cmd, int arg, int len, uint8_t *buf, int max_len) {
  683. if (cmd == DFU_UPLOAD) {
  684. if (arg >= 2) {
  685. dfu_state.cmd = DFU_CMD_UPLOAD;
  686. uint32_t addr = (arg - 2) * max_len + dfu_state.addr;
  687. do_read(addr, len, buf);
  688. return len;
  689. }
  690. } else if (cmd == DFU_GETSTATUS && len == 6) {
  691. // execute command and get status
  692. switch (dfu_state.cmd) {
  693. case DFU_CMD_NONE:
  694. break;
  695. case DFU_CMD_EXIT:
  696. dfu_state.status = DFU_STATUS_MANIFEST;
  697. break;
  698. case DFU_CMD_UPLOAD:
  699. dfu_state.status = DFU_STATUS_UPLOAD_IDLE;
  700. break;
  701. case DFU_CMD_DNLOAD:
  702. dfu_state.status = DFU_STATUS_BUSY;
  703. break;
  704. }
  705. buf[0] = 0;
  706. buf[1] = dfu_state.cmd; // TODO is this correct?
  707. buf[2] = 0;
  708. buf[3] = 0;
  709. buf[4] = dfu_state.status;
  710. buf[5] = 0;
  711. return 6;
  712. }
  713. return -1;
  714. }
  715. /******************************************************************************/
  716. // USB
  717. #define USB_XFER_SIZE (DFU_XFER_SIZE)
  718. #define USB_PHY_FS_ID (0)
  719. #define USB_PHY_HS_ID (1)
  720. typedef struct _pyb_usbdd_obj_t {
  721. bool started;
  722. bool tx_pending;
  723. USBD_HandleTypeDef hUSBDDevice;
  724. uint8_t bRequest;
  725. uint16_t wValue;
  726. uint16_t wLength;
  727. __ALIGN_BEGIN uint8_t rx_buf[USB_XFER_SIZE] __ALIGN_END;
  728. __ALIGN_BEGIN uint8_t tx_buf[USB_XFER_SIZE] __ALIGN_END;
  729. // RAM to hold the current descriptors, which we configure on the fly
  730. __ALIGN_BEGIN uint8_t usbd_device_desc[USB_LEN_DEV_DESC] __ALIGN_END;
  731. __ALIGN_BEGIN uint8_t usbd_str_desc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END;
  732. } pyb_usbdd_obj_t;
  733. #define USBD_LANGID_STRING (0x409)
  734. __ALIGN_BEGIN static const uint8_t USBD_LangIDDesc[USB_LEN_LANGID_STR_DESC] __ALIGN_END = {
  735. USB_LEN_LANGID_STR_DESC,
  736. USB_DESC_TYPE_STRING,
  737. LOBYTE(USBD_LANGID_STRING),
  738. HIBYTE(USBD_LANGID_STRING),
  739. };
  740. static const uint8_t dev_descr[0x12] = "\x12\x01\x00\x01\x00\x00\x00\x40\x83\x04\x11\xdf\x00\x22\x01\x02\x03\x01";
  741. // This may be modified by USBD_GetDescriptor
  742. static uint8_t cfg_descr[9 + 9 + 9] =
  743. "\x09\x02\x1b\x00\x01\x01\x00\xc0\x32"
  744. "\x09\x04\x00\x00\x00\xfe\x01\x02\x04"
  745. "\x09\x21\x0b\xff\x00\x00\x08\x1a\x01" // \x00\x08 goes with USB_XFER_SIZE
  746. ;
  747. static uint8_t *pyb_usbdd_DeviceDescriptor(USBD_HandleTypeDef *pdev, uint16_t *length) {
  748. *length = USB_LEN_DEV_DESC;
  749. return (uint8_t*)dev_descr;
  750. }
  751. static char get_hex_char(int val) {
  752. val &= 0xf;
  753. if (val <= 9) {
  754. return '0' + val;
  755. } else {
  756. return 'A' + val - 10;
  757. }
  758. }
  759. static void format_hex(char *buf, int val) {
  760. buf[0] = get_hex_char(val >> 4);
  761. buf[1] = get_hex_char(val);
  762. }
  763. static uint8_t *pyb_usbdd_StrDescriptor(USBD_HandleTypeDef *pdev, uint8_t idx, uint16_t *length) {
  764. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  765. uint8_t *str_desc = self->usbd_str_desc;
  766. switch (idx) {
  767. case USBD_IDX_LANGID_STR:
  768. *length = sizeof(USBD_LangIDDesc);
  769. return (uint8_t*)USBD_LangIDDesc; // the data should only be read from this buf
  770. case USBD_IDX_MFC_STR:
  771. USBD_GetString((uint8_t*)"USBDevice Manuf", str_desc, length);
  772. return str_desc;
  773. case USBD_IDX_PRODUCT_STR:
  774. USBD_GetString((uint8_t*)"USBDevice Product", str_desc, length);
  775. return str_desc;
  776. case USBD_IDX_SERIAL_STR: {
  777. // This document: http://www.usb.org/developers/docs/devclass_docs/usbmassbulk_10.pdf
  778. // says that the serial number has to be at least 12 digits long and that
  779. // the last 12 digits need to be unique. It also stipulates that the valid
  780. // character set is that of upper-case hexadecimal digits.
  781. //
  782. // The onboard DFU bootloader produces a 12-digit serial number based on
  783. // the 96-bit unique ID, so for consistency we go with this algorithm.
  784. // You can see the serial number if you do:
  785. //
  786. // dfu-util -l
  787. //
  788. // See: https://my.st.com/52d187b7 for the algorithim used.
  789. uint8_t *id = (uint8_t*)MP_HAL_UNIQUE_ID_ADDRESS;
  790. char serial_buf[16];
  791. format_hex(&serial_buf[0], id[11]);
  792. format_hex(&serial_buf[2], id[10] + id[2]);
  793. format_hex(&serial_buf[4], id[9]);
  794. format_hex(&serial_buf[6], id[8] + id[0]);
  795. format_hex(&serial_buf[8], id[7]);
  796. format_hex(&serial_buf[10], id[6]);
  797. serial_buf[12] = '\0';
  798. USBD_GetString((uint8_t*)serial_buf, str_desc, length);
  799. return str_desc;
  800. }
  801. case USBD_IDX_CONFIG_STR:
  802. USBD_GetString((uint8_t*)FLASH_LAYOUT_STR, str_desc, length);
  803. return str_desc;
  804. default:
  805. return NULL;
  806. }
  807. }
  808. static const USBD_DescriptorsTypeDef pyb_usbdd_descriptors = {
  809. pyb_usbdd_DeviceDescriptor,
  810. pyb_usbdd_StrDescriptor,
  811. };
  812. static uint8_t pyb_usbdd_Init(USBD_HandleTypeDef *pdev, uint8_t cfgidx) {
  813. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  814. (void)self;
  815. return USBD_OK;
  816. }
  817. static uint8_t pyb_usbdd_DeInit(USBD_HandleTypeDef *pdev, uint8_t cfgidx) {
  818. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  819. (void)self;
  820. return USBD_OK;
  821. }
  822. static uint8_t pyb_usbdd_Setup(USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req) {
  823. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  824. (void)self;
  825. self->bRequest = req->bRequest;
  826. self->wValue = req->wValue;
  827. self->wLength = req->wLength;
  828. if (req->bmRequest == 0x21) {
  829. // host-to-device request
  830. if (req->wLength == 0) {
  831. // no data, process command straightaway
  832. dfu_handle_rx(self->bRequest, self->wValue, 0, NULL);
  833. } else {
  834. // have data, prepare to receive it
  835. USBD_CtlPrepareRx(pdev, self->rx_buf, req->wLength);
  836. }
  837. } else if (req->bmRequest == 0xa1) {
  838. // device-to-host request
  839. int len = dfu_handle_tx(self->bRequest, self->wValue, self->wLength, self->tx_buf, USB_XFER_SIZE);
  840. if (len >= 0) {
  841. self->tx_pending = true;
  842. USBD_CtlSendData(&self->hUSBDDevice, self->tx_buf, len);
  843. }
  844. }
  845. return USBD_OK;
  846. }
  847. static uint8_t pyb_usbdd_EP0_TxSent(USBD_HandleTypeDef *pdev) {
  848. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  849. self->tx_pending = false;
  850. #if !USE_USB_POLLING
  851. // Process now that we have sent a response
  852. dfu_process();
  853. #endif
  854. return USBD_OK;
  855. }
  856. static uint8_t pyb_usbdd_EP0_RxReady(USBD_HandleTypeDef *pdev) {
  857. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  858. dfu_handle_rx(self->bRequest, self->wValue, self->wLength, self->rx_buf);
  859. return USBD_OK;
  860. }
  861. static uint8_t *pyb_usbdd_GetCfgDesc(USBD_HandleTypeDef *pdev, uint16_t *length) {
  862. *length = sizeof(cfg_descr);
  863. return (uint8_t*)cfg_descr;
  864. }
  865. // this is used only in high-speed mode, which we don't support
  866. static uint8_t *pyb_usbdd_GetDeviceQualifierDescriptor(USBD_HandleTypeDef *pdev, uint16_t *length) {
  867. pyb_usbdd_obj_t *self = (pyb_usbdd_obj_t*)pdev->pClassData;
  868. (void)self;
  869. /*
  870. *length = sizeof(USBD_CDC_MSC_HID_DeviceQualifierDesc);
  871. return USBD_CDC_MSC_HID_DeviceQualifierDesc;
  872. */
  873. *length = 0;
  874. return NULL;
  875. }
  876. static const USBD_ClassTypeDef pyb_usbdd_class = {
  877. pyb_usbdd_Init,
  878. pyb_usbdd_DeInit,
  879. pyb_usbdd_Setup,
  880. pyb_usbdd_EP0_TxSent,
  881. pyb_usbdd_EP0_RxReady,
  882. NULL, // pyb_usbdd_DataIn,
  883. NULL, // pyb_usbdd_DataOut,
  884. NULL, // SOF
  885. NULL, // IsoINIncomplete
  886. NULL, // IsoOUTIncomplete
  887. pyb_usbdd_GetCfgDesc,
  888. pyb_usbdd_GetCfgDesc,
  889. pyb_usbdd_GetCfgDesc,
  890. pyb_usbdd_GetDeviceQualifierDescriptor,
  891. };
  892. static pyb_usbdd_obj_t pyb_usbdd;
  893. static void pyb_usbdd_init(pyb_usbdd_obj_t *self, int phy_id) {
  894. self->started = false;
  895. USBD_HandleTypeDef *usbd = &self->hUSBDDevice;
  896. usbd->id = phy_id;
  897. usbd->dev_state = USBD_STATE_DEFAULT;
  898. usbd->pDesc = (USBD_DescriptorsTypeDef*)&pyb_usbdd_descriptors;
  899. usbd->pClass = &pyb_usbdd_class;
  900. usbd->pClassData = self;
  901. }
  902. static void pyb_usbdd_start(pyb_usbdd_obj_t *self) {
  903. if (!self->started) {
  904. USBD_LL_Init(&self->hUSBDDevice, 0);
  905. USBD_LL_Start(&self->hUSBDDevice);
  906. self->started = true;
  907. }
  908. }
  909. static void pyb_usbdd_stop(pyb_usbdd_obj_t *self) {
  910. if (self->started) {
  911. USBD_Stop(&self->hUSBDDevice);
  912. self->started = false;
  913. }
  914. }
  915. static int pyb_usbdd_shutdown(void) {
  916. pyb_usbdd_stop(&pyb_usbdd);
  917. return 0;
  918. }
  919. /******************************************************************************/
  920. // main
  921. #define RESET_MODE_NUM_STATES (4)
  922. #define RESET_MODE_TIMEOUT_CYCLES (8)
  923. #define RESET_MODE_LED_STATES 0x7421
  924. static int get_reset_mode(void) {
  925. usrbtn_init();
  926. int reset_mode = 1;
  927. if (usrbtn_state()) {
  928. // Cycle through reset modes while USR is held
  929. // Timeout is roughly 20s, where reset_mode=1
  930. systick_init();
  931. led_init();
  932. reset_mode = 0;
  933. for (int i = 0; i < (RESET_MODE_NUM_STATES * RESET_MODE_TIMEOUT_CYCLES + 1) * 32; i++) {
  934. if (i % 32 == 0) {
  935. if (++reset_mode > RESET_MODE_NUM_STATES) {
  936. reset_mode = 1;
  937. }
  938. uint8_t l = RESET_MODE_LED_STATES >> ((reset_mode - 1) * 4);
  939. led_state(LED0, l & 1);
  940. led_state(LED1, l & 2);
  941. led_state(LED2, l & 4);
  942. }
  943. if (!usrbtn_state()) {
  944. break;
  945. }
  946. mp_hal_delay_ms(19);
  947. }
  948. // Flash the selected reset mode
  949. for (int i = 0; i < 6; i++) {
  950. led_state(LED0, 0);
  951. led_state(LED1, 0);
  952. led_state(LED2, 0);
  953. mp_hal_delay_ms(50);
  954. uint8_t l = RESET_MODE_LED_STATES >> ((reset_mode - 1) * 4);
  955. led_state(LED0, l & 1);
  956. led_state(LED1, l & 2);
  957. led_state(LED2, l & 4);
  958. mp_hal_delay_ms(50);
  959. }
  960. mp_hal_delay_ms(300);
  961. }
  962. return reset_mode;
  963. }
  964. static void do_reset(void) {
  965. led_state(LED0, 0);
  966. led_state(LED1, 0);
  967. led_state(LED2, 0);
  968. mp_hal_delay_ms(50);
  969. pyb_usbdd_shutdown();
  970. #if defined(MBOOT_I2C_SCL)
  971. i2c_slave_shutdown(MBOOT_I2Cx, I2Cx_EV_IRQn);
  972. #endif
  973. mp_hal_delay_ms(50);
  974. NVIC_SystemReset();
  975. }
  976. uint32_t SystemCoreClock;
  977. extern PCD_HandleTypeDef pcd_fs_handle;
  978. extern PCD_HandleTypeDef pcd_hs_handle;
  979. void stm32_main(int initial_r0) {
  980. #if defined(STM32F4)
  981. #if INSTRUCTION_CACHE_ENABLE
  982. __HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
  983. #endif
  984. #if DATA_CACHE_ENABLE
  985. __HAL_FLASH_DATA_CACHE_ENABLE();
  986. #endif
  987. #if PREFETCH_ENABLE
  988. __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
  989. #endif
  990. #elif defined(STM32F7)
  991. #if ART_ACCLERATOR_ENABLE
  992. __HAL_FLASH_ART_ENABLE();
  993. #endif
  994. #endif
  995. NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
  996. #if USE_CACHE && defined(STM32F7)
  997. SCB_EnableICache();
  998. SCB_EnableDCache();
  999. #endif
  1000. #ifdef MBOOT_BOOTPIN_PIN
  1001. mp_hal_pin_config(MBOOT_BOOTPIN_PIN, MP_HAL_PIN_MODE_INPUT, MBOOT_BOOTPIN_PULL, 0);
  1002. if (mp_hal_pin_read(MBOOT_BOOTPIN_PIN) == MBOOT_BOOTPIN_ACTIVE) {
  1003. goto enter_bootloader;
  1004. }
  1005. #endif
  1006. if ((initial_r0 & 0xffffff00) == 0x70ad0000) {
  1007. goto enter_bootloader;
  1008. }
  1009. // MCU starts up with 16MHz HSI
  1010. SystemCoreClock = 16000000;
  1011. int reset_mode = get_reset_mode();
  1012. uint32_t msp = *(volatile uint32_t*)APPLICATION_ADDR;
  1013. if (reset_mode != 4 && (msp & APP_VALIDITY_BITS) == 0) {
  1014. // not DFU mode so jump to application, passing through reset_mode
  1015. // undo our DFU settings
  1016. // TODO probably should disable all IRQ sources first
  1017. #if USE_CACHE && defined(STM32F7)
  1018. SCB_DisableICache();
  1019. SCB_DisableDCache();
  1020. #endif
  1021. __set_MSP(msp);
  1022. ((void (*)(uint32_t)) *((volatile uint32_t*)(APPLICATION_ADDR + 4)))(reset_mode);
  1023. }
  1024. enter_bootloader:
  1025. // Init subsystems (get_reset_mode() may call these, calling them again is ok)
  1026. led_init();
  1027. // set the system clock to be HSE
  1028. SystemClock_Config();
  1029. #if USE_USB_POLLING
  1030. // irqs with a priority value greater or equal to "pri" will be disabled
  1031. // "pri" should be between 1 and 15 inclusive
  1032. uint32_t pri = 2;
  1033. pri <<= (8 - __NVIC_PRIO_BITS);
  1034. __ASM volatile ("msr basepri_max, %0" : : "r" (pri) : "memory");
  1035. #endif
  1036. #if defined(MBOOT_SPIFLASH_ADDR)
  1037. MBOOT_SPIFLASH_SPIFLASH->config = MBOOT_SPIFLASH_CONFIG;
  1038. mp_spiflash_init(MBOOT_SPIFLASH_SPIFLASH);
  1039. #endif
  1040. #if defined(MBOOT_SPIFLASH2_ADDR)
  1041. MBOOT_SPIFLASH2_SPIFLASH->config = MBOOT_SPIFLASH2_CONFIG;
  1042. mp_spiflash_init(MBOOT_SPIFLASH2_SPIFLASH);
  1043. #endif
  1044. dfu_init();
  1045. pyb_usbdd_init(&pyb_usbdd, MICROPY_HW_USB_MAIN_DEV);
  1046. pyb_usbdd_start(&pyb_usbdd);
  1047. #if defined(MBOOT_I2C_SCL)
  1048. initial_r0 &= 0x7f;
  1049. if (initial_r0 == 0) {
  1050. initial_r0 = 0x23; // Default I2C address
  1051. }
  1052. i2c_init(initial_r0);
  1053. #endif
  1054. led_state(LED0, 0);
  1055. led_state(LED1, 0);
  1056. led_state(LED2, 0);
  1057. #if USE_USB_POLLING
  1058. uint32_t ss = systick_ms;
  1059. int ss2 = -1;
  1060. #endif
  1061. for (;;) {
  1062. #if USE_USB_POLLING
  1063. #if MICROPY_HW_USB_MAIN_DEV == USB_PHY_FS_ID
  1064. if (USB_OTG_FS->GINTSTS & USB_OTG_FS->GINTMSK) {
  1065. HAL_PCD_IRQHandler(&pcd_fs_handle);
  1066. }
  1067. #else
  1068. if (USB_OTG_HS->GINTSTS & USB_OTG_HS->GINTMSK) {
  1069. HAL_PCD_IRQHandler(&pcd_hs_handle);
  1070. }
  1071. #endif
  1072. if (!pyb_usbdd.tx_pending) {
  1073. dfu_process();
  1074. }
  1075. #endif
  1076. #if USE_USB_POLLING
  1077. //__WFI(); // slows it down way too much; might work with 10x faster systick
  1078. if (systick_ms - ss > 50) {
  1079. ss += 50;
  1080. ss2 = (ss2 + 1) % 20;
  1081. switch (ss2) {
  1082. case 0: led_state(LED0, 1); break;
  1083. case 1: led_state(LED0, 0); break;
  1084. }
  1085. }
  1086. #else
  1087. led_state(LED0, 1);
  1088. mp_hal_delay_ms(50);
  1089. led_state(LED0, 0);
  1090. mp_hal_delay_ms(950);
  1091. #endif
  1092. }
  1093. }
  1094. void NMI_Handler(void) {
  1095. }
  1096. void MemManage_Handler(void) {
  1097. while (1) {
  1098. __fatal_error("MemManage");
  1099. }
  1100. }
  1101. void BusFault_Handler(void) {
  1102. while (1) {
  1103. __fatal_error("BusFault");
  1104. }
  1105. }
  1106. void UsageFault_Handler(void) {
  1107. while (1) {
  1108. __fatal_error("UsageFault");
  1109. }
  1110. }
  1111. void SVC_Handler(void) {
  1112. }
  1113. void DebugMon_Handler(void) {
  1114. }
  1115. void PendSV_Handler(void) {
  1116. }
  1117. void SysTick_Handler(void) {
  1118. systick_ms += 1;
  1119. // Read the systick control regster. This has the side effect of clearing
  1120. // the COUNTFLAG bit, which makes the logic in mp_hal_ticks_us
  1121. // work properly.
  1122. SysTick->CTRL;
  1123. }
  1124. #if defined(MBOOT_I2C_SCL)
  1125. void I2Cx_EV_IRQHandler(void) {
  1126. i2c_slave_ev_irq_handler(MBOOT_I2Cx);
  1127. }
  1128. #endif
  1129. #if !USE_USB_POLLING
  1130. #if MICROPY_HW_USB_MAIN_DEV == USB_PHY_FS_ID
  1131. void OTG_FS_IRQHandler(void) {
  1132. HAL_PCD_IRQHandler(&pcd_fs_handle);
  1133. }
  1134. #else
  1135. void OTG_HS_IRQHandler(void) {
  1136. HAL_PCD_IRQHandler(&pcd_hs_handle);
  1137. }
  1138. #endif
  1139. #endif