bootloader.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "bootloader.h"
  2. #include "ch.h"
  3. #include "hal.h"
  4. #ifdef STM32_BOOTLOADER_ADDRESS
  5. /* STM32 */
  6. /* This code should be checked whether it runs correctly on platforms */
  7. # define SYMVAL(sym) (uint32_t)(((uint8_t *)&(sym)) - ((uint8_t *)0))
  8. extern uint32_t __ram0_end__;
  9. # define BOOTLOADER_MAGIC 0xDEADBEEF
  10. # define MAGIC_ADDR (unsigned long *)(SYMVAL(__ram0_end__) - 4)
  11. /** \brief Jump to the bootloader
  12. *
  13. * FIXME: needs doc
  14. */
  15. void bootloader_jump(void) {
  16. *MAGIC_ADDR = BOOTLOADER_MAGIC; // set magic flag => reset handler will jump into boot loader
  17. NVIC_SystemReset();
  18. }
  19. /** \brief Enter bootloader mode if requested
  20. *
  21. * FIXME: needs doc
  22. */
  23. void enter_bootloader_mode_if_requested(void) {
  24. unsigned long *check = MAGIC_ADDR;
  25. if (*check == BOOTLOADER_MAGIC) {
  26. *check = 0;
  27. __set_CONTROL(0);
  28. __set_MSP(*(__IO uint32_t *)STM32_BOOTLOADER_ADDRESS);
  29. __enable_irq();
  30. typedef void (*BootJump_t)(void);
  31. BootJump_t boot_jump = *(BootJump_t *)(STM32_BOOTLOADER_ADDRESS + 4);
  32. boot_jump();
  33. while (1)
  34. ;
  35. }
  36. }
  37. #elif defined(KL2x) || defined(K20x) /* STM32_BOOTLOADER_ADDRESS */
  38. /* Kinetis */
  39. # if defined(KIIBOHD_BOOTLOADER)
  40. /* Kiibohd Bootloader (MCHCK and Infinity KB) */
  41. # define SCB_AIRCR_VECTKEY_WRITEMAGIC 0x05FA0000
  42. const uint8_t sys_reset_to_loader_magic[] = "\xff\x00\x7fRESET TO LOADER\x7f\x00\xff";
  43. void bootloader_jump(void) {
  44. __builtin_memcpy((void *)VBAT, (const void *)sys_reset_to_loader_magic, sizeof(sys_reset_to_loader_magic));
  45. // request reset
  46. SCB->AIRCR = SCB_AIRCR_VECTKEY_WRITEMAGIC | SCB_AIRCR_SYSRESETREQ_Msk;
  47. }
  48. # else /* defined(KIIBOHD_BOOTLOADER) */
  49. /* Default for Kinetis - expecting an ARM Teensy */
  50. # include "wait.h"
  51. void bootloader_jump(void) {
  52. wait_ms(100);
  53. __BKPT(0);
  54. }
  55. # endif /* defined(KIIBOHD_BOOTLOADER) */
  56. #else /* neither STM32 nor KINETIS */
  57. __attribute__((weak)) void bootloader_jump(void) {}
  58. #endif