BootloaderMassStorage.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 Mass Storage class bootloader. This file contains the complete bootloader logic.
  29. */
  30. #define INCLUDE_FROM_BOOTLOADER_MASSSTORAGE_C
  31. #include "BootloaderMassStorage.h"
  32. /** LUFA Mass Storage Class driver interface configuration and state information. This structure is
  33. * passed to all Mass Storage Class driver functions, so that multiple instances of the same class
  34. * within a device can be differentiated from one another.
  35. */
  36. USB_ClassInfo_MS_Device_t Disk_MS_Interface =
  37. {
  38. .Config =
  39. {
  40. .InterfaceNumber = INTERFACE_ID_MassStorage,
  41. .DataINEndpoint =
  42. {
  43. .Address = MASS_STORAGE_IN_EPADDR,
  44. .Size = MASS_STORAGE_IO_EPSIZE,
  45. .Banks = 1,
  46. },
  47. .DataOUTEndpoint =
  48. {
  49. .Address = MASS_STORAGE_OUT_EPADDR,
  50. .Size = MASS_STORAGE_IO_EPSIZE,
  51. .Banks = 1,
  52. },
  53. .TotalLUNs = 1,
  54. },
  55. };
  56. /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
  57. * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
  58. * started via a forced watchdog reset.
  59. */
  60. bool RunBootloader = true;
  61. /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
  62. * 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
  63. * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
  64. * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
  65. */
  66. uint16_t MagicBootKey ATTR_NO_INIT;
  67. /** Indicates if the bootloader is allowed to exit immediately if \ref RunBootloader is \c false. During shutdown all
  68. * pending commands must be processed before jumping to the user-application, thus this tracks the main program loop
  69. * iterations since a SCSI command from the host was received.
  70. */
  71. static uint8_t TicksSinceLastCommand = 0;
  72. /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
  73. * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
  74. * this will force the user application to start via a software jump.
  75. */
  76. void Application_Jump_Check(void)
  77. {
  78. bool JumpToApplication = false;
  79. #if (BOARD == BOARD_LEONARDO)
  80. /* Enable pull-up on the IO13 pin so we can use it to select the mode */
  81. PORTC |= (1 << 7);
  82. Delay_MS(10);
  83. /* If IO13 is not jumpered to ground, start the user application instead */
  84. JumpToApplication = ((PINC & (1 << 7)) != 0);
  85. /* Disable pull-up after the check has completed */
  86. PORTC &= ~(1 << 7);
  87. #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
  88. /* Disable JTAG debugging */
  89. JTAG_DISABLE();
  90. /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
  91. PORTF |= (1 << 4);
  92. Delay_MS(10);
  93. /* If the TCK pin is not jumpered to ground, start the user application instead */
  94. JumpToApplication = ((PINF & (1 << 4)) != 0);
  95. /* Re-enable JTAG debugging */
  96. JTAG_ENABLE();
  97. #else
  98. /* Check if the device's BOOTRST fuse is set */
  99. if (BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & FUSE_BOOTRST)
  100. {
  101. /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
  102. if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
  103. JumpToApplication = true;
  104. /* Clear reset source */
  105. MCUSR &= ~(1 << EXTRF);
  106. }
  107. else
  108. {
  109. /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
  110. * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
  111. if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
  112. JumpToApplication = true;
  113. /* Clear reset source */
  114. MCUSR &= ~(1 << WDRF);
  115. }
  116. #endif
  117. /* Don't run the user application if the reset vector is blank (no app loaded) */
  118. bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
  119. /* If a request has been made to jump to the user application, honor it */
  120. if (JumpToApplication && ApplicationValid)
  121. {
  122. /* Turn off the watchdog */
  123. MCUSR &= ~(1 << WDRF);
  124. wdt_disable();
  125. /* Clear the boot key and jump to the user application */
  126. MagicBootKey = 0;
  127. // cppcheck-suppress constStatement
  128. ((void (*)(void))0x0000)();
  129. }
  130. }
  131. /** Main program entry point. This routine configures the hardware required by the application, then
  132. * enters a loop to run the application tasks in sequence.
  133. */
  134. int main(void)
  135. {
  136. SetupHardware();
  137. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  138. GlobalInterruptEnable();
  139. while (RunBootloader || TicksSinceLastCommand++ < 0xFF)
  140. {
  141. MS_Device_USBTask(&Disk_MS_Interface);
  142. USB_USBTask();
  143. }
  144. /* Wait a short time to end all USB transactions and then disconnect */
  145. _delay_us(1000);
  146. /* Disconnect from the host - USB interface will be reset later along with the AVR */
  147. USB_Detach();
  148. /* Unlock the forced application start mode of the bootloader if it is restarted */
  149. MagicBootKey = MAGIC_BOOT_KEY;
  150. /* Enable the watchdog and force a timeout to reset the AVR */
  151. wdt_enable(WDTO_250MS);
  152. for (;;);
  153. }
  154. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  155. static void SetupHardware(void)
  156. {
  157. /* Disable watchdog if enabled by bootloader/fuses */
  158. MCUSR &= ~(1 << WDRF);
  159. wdt_disable();
  160. /* Disable clock division */
  161. clock_prescale_set(clock_div_1);
  162. /* Relocate the interrupt vector table to the bootloader section */
  163. MCUCR = (1 << IVCE);
  164. MCUCR = (1 << IVSEL);
  165. /* Hardware Initialization */
  166. LEDs_Init();
  167. USB_Init();
  168. /* Bootloader active LED toggle timer initialization */
  169. TIMSK1 = (1 << TOIE1);
  170. TCCR1B = ((1 << CS11) | (1 << CS10));
  171. }
  172. /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
  173. ISR(TIMER1_OVF_vect, ISR_BLOCK)
  174. {
  175. LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
  176. }
  177. /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
  178. void EVENT_USB_Device_Connect(void)
  179. {
  180. /* Indicate USB enumerating */
  181. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  182. }
  183. /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
  184. * the status LEDs and stops the Mass Storage management task.
  185. */
  186. void EVENT_USB_Device_Disconnect(void)
  187. {
  188. /* Indicate USB not ready */
  189. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  190. }
  191. /** Event handler for the library USB Configuration Changed event. */
  192. void EVENT_USB_Device_ConfigurationChanged(void)
  193. {
  194. bool ConfigSuccess = true;
  195. /* Setup Mass Storage Data Endpoints */
  196. ConfigSuccess &= MS_Device_ConfigureEndpoints(&Disk_MS_Interface);
  197. /* Indicate endpoint configuration success or failure */
  198. LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
  199. }
  200. /** Event handler for the library USB Control Request reception event. */
  201. void EVENT_USB_Device_ControlRequest(void)
  202. {
  203. MS_Device_ProcessControlRequest(&Disk_MS_Interface);
  204. }
  205. /** Mass Storage class driver callback function the reception of SCSI commands from the host, which must be processed.
  206. *
  207. * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface configuration structure being referenced
  208. */
  209. bool CALLBACK_MS_Device_SCSICommandReceived(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
  210. {
  211. bool CommandSuccess;
  212. LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
  213. CommandSuccess = SCSI_DecodeSCSICommand(MSInterfaceInfo);
  214. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  215. /* Signal that a command was processed, must not exit bootloader yet */
  216. TicksSinceLastCommand = 0;
  217. return CommandSuccess;
  218. }