BootloaderHID.c 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2018.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2018 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Main source file for the HID class bootloader. This file contains the complete bootloader logic.
  29. */
  30. #include "BootloaderHID.h"
  31. /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
  32. * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
  33. * started via a forced watchdog reset.
  34. */
  35. static bool RunBootloader = true;
  36. /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
  37. * will start if the /HWB line of the AVR is held low and the system is reset. However, if the /HWB line is still held
  38. * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
  39. * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
  40. */
  41. uint16_t MagicBootKey ATTR_NO_INIT;
  42. /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
  43. * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
  44. * this will force the user application to start via a software jump.
  45. */
  46. void Application_Jump_Check(void)
  47. {
  48. /* If the reset source was the bootloader and the key is correct, clear it and jump to the application */
  49. if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
  50. {
  51. /* Turn off the watchdog */
  52. MCUSR &= ~(1 << WDRF);
  53. wdt_disable();
  54. /* Clear the boot key and jump to the user application */
  55. MagicBootKey = 0;
  56. // cppcheck-suppress constStatement
  57. ((void (*)(void))0x0000)();
  58. }
  59. }
  60. /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
  61. * runs the bootloader processing routine until instructed to soft-exit.
  62. */
  63. int main(void)
  64. {
  65. /* Setup hardware required for the bootloader */
  66. SetupHardware();
  67. /* Enable global interrupts so that the USB stack can function */
  68. GlobalInterruptEnable();
  69. while (RunBootloader)
  70. USB_USBTask();
  71. /* Wait a short time to end all USB transactions and then disconnect */
  72. _delay_us(1000);
  73. /* Disconnect from the host - USB interface will be reset later along with the AVR */
  74. USB_Detach();
  75. /* Unlock the forced application start mode of the bootloader if it is restarted */
  76. MagicBootKey = MAGIC_BOOT_KEY;
  77. /* Enable the watchdog and force a timeout to reset the AVR */
  78. wdt_enable(WDTO_250MS);
  79. for (;;);
  80. }
  81. /** Configures all hardware required for the bootloader. */
  82. static void SetupHardware(void)
  83. {
  84. /* Disable watchdog if enabled by bootloader/fuses */
  85. MCUSR &= ~(1 << WDRF);
  86. wdt_disable();
  87. /* Disable clock division */
  88. clock_prescale_set(clock_div_1);
  89. /* Relocate the interrupt vector table to the bootloader section */
  90. MCUCR = (1 << IVCE);
  91. MCUCR = (1 << IVSEL);
  92. /* Initialize USB subsystem */
  93. USB_Init();
  94. }
  95. /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
  96. * to relay data to and from the attached USB host.
  97. */
  98. void EVENT_USB_Device_ConfigurationChanged(void)
  99. {
  100. /* Setup HID Report Endpoint */
  101. Endpoint_ConfigureEndpoint(HID_IN_EPADDR, EP_TYPE_INTERRUPT, HID_IN_EPSIZE, 1);
  102. }
  103. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  104. * the device from the USB host before passing along unhandled control requests to the library for processing
  105. * internally.
  106. */
  107. void EVENT_USB_Device_ControlRequest(void)
  108. {
  109. /* Ignore any requests that aren't directed to the HID interface */
  110. if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
  111. (REQTYPE_CLASS | REQREC_INTERFACE))
  112. {
  113. return;
  114. }
  115. /* Process HID specific control requests */
  116. switch (USB_ControlRequest.bRequest)
  117. {
  118. case HID_REQ_SetReport:
  119. Endpoint_ClearSETUP();
  120. /* Wait until the command has been sent by the host */
  121. while (!(Endpoint_IsOUTReceived()));
  122. /* Read in the write destination address */
  123. #if (FLASHEND > 0xFFFF)
  124. uint32_t PageAddress = ((uint32_t)Endpoint_Read_16_LE() << 8);
  125. #else
  126. uint16_t PageAddress = Endpoint_Read_16_LE();
  127. #endif
  128. /* Determine if the given page address is correctly aligned to the
  129. start of a flash page. */
  130. bool PageAddressIsAligned = !(PageAddress & (SPM_PAGESIZE - 1));
  131. /* Check if the command is a program page command, or a start application command */
  132. #if (FLASHEND > 0xFFFF)
  133. if ((uint16_t)(PageAddress >> 8) == COMMAND_STARTAPPLICATION)
  134. #else
  135. if (PageAddress == COMMAND_STARTAPPLICATION)
  136. #endif
  137. {
  138. RunBootloader = false;
  139. }
  140. else if ((PageAddress < BOOT_START_ADDR) && PageAddressIsAligned)
  141. {
  142. /* Erase the given FLASH page, ready to be programmed */
  143. ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
  144. {
  145. boot_page_erase(PageAddress);
  146. boot_spm_busy_wait();
  147. }
  148. /* Write each of the FLASH page's bytes in sequence */
  149. for (uint8_t PageWord = 0; PageWord < (SPM_PAGESIZE / 2); PageWord++)
  150. {
  151. /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
  152. if (!(Endpoint_BytesInEndpoint()))
  153. {
  154. Endpoint_ClearOUT();
  155. while (!(Endpoint_IsOUTReceived()));
  156. }
  157. /* Write the next data word to the FLASH page */
  158. boot_page_fill(PageAddress + ((uint16_t)PageWord << 1), Endpoint_Read_16_LE());
  159. }
  160. /* Write the filled FLASH page to memory */
  161. ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
  162. {
  163. boot_page_write(PageAddress);
  164. boot_spm_busy_wait();
  165. }
  166. /* Re-enable RWW section */
  167. boot_rww_enable();
  168. }
  169. Endpoint_ClearOUT();
  170. Endpoint_ClearStatusStage();
  171. break;
  172. }
  173. }