usbasploader.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* Copyright 2021 QMK
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "bootloader.h"
  17. #include <avr/wdt.h>
  18. #define FLASH_SIZE (FLASHEND + 1L)
  19. #if !defined(MCUCSR)
  20. # if defined(MCUSR)
  21. # define MCUCSR MCUSR
  22. # endif
  23. #endif
  24. __attribute__((weak)) void bootloader_jump(void) {
  25. // Taken with permission of Stephan Baerwolf from https://github.com/tinyusbboard/API/blob/master/apipage.c
  26. wdt_enable(WDTO_15MS);
  27. wdt_reset();
  28. asm volatile("cli \n\t"
  29. "ldi r29 , %[ramendhi] \n\t"
  30. "ldi r28 , %[ramendlo] \n\t"
  31. #if (FLASHEND > 131071)
  32. "ldi r18 , %[bootaddrhi] \n\t"
  33. "st Y+, r18 \n\t"
  34. #endif
  35. "ldi r18 , %[bootaddrme] \n\t"
  36. "st Y+, r18 \n\t"
  37. "ldi r18 , %[bootaddrlo] \n\t"
  38. "st Y+, r18 \n\t"
  39. "out %[mcucsrio], __zero_reg__ \n\t"
  40. "bootloader_startup_loop%=: \n\t"
  41. "rjmp bootloader_startup_loop%= \n\t"
  42. :
  43. : [mcucsrio] "I"(_SFR_IO_ADDR(MCUCSR)),
  44. #if (FLASHEND > 131071)
  45. [ramendhi] "M"(((RAMEND - 2) >> 8) & 0xff), [ramendlo] "M"(((RAMEND - 2) >> 0) & 0xff), [bootaddrhi] "M"((((FLASH_SIZE - BOOTLOADER_SIZE) >> 1) >> 16) & 0xff),
  46. #else
  47. [ramendhi] "M"(((RAMEND - 1) >> 8) & 0xff), [ramendlo] "M"(((RAMEND - 1) >> 0) & 0xff),
  48. #endif
  49. [bootaddrme] "M"((((FLASH_SIZE - BOOTLOADER_SIZE) >> 1) >> 8) & 0xff), [bootaddrlo] "M"((((FLASH_SIZE - BOOTLOADER_SIZE) >> 1) >> 0) & 0xff));
  50. }