BootloaderDFU.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 DFU class bootloader. This file contains the complete bootloader logic.
  29. */
  30. #define INCLUDE_FROM_BOOTLOADER_C
  31. #include "BootloaderDFU.h"
  32. /** Flag to indicate if the bootloader is currently running in secure mode, disallowing memory operations
  33. * other than erase. This is initially set to the value set by SECURE_MODE, and cleared by the bootloader
  34. * once a memory erase has completed in a bootloader session.
  35. */
  36. static bool IsSecure = SECURE_MODE;
  37. /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
  38. * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
  39. * jumped to via an indirect jump to location 0x0000 (or other location specified by the host).
  40. */
  41. static bool RunBootloader = true;
  42. /** Flag to indicate if the bootloader is waiting to exit. When the host requests the bootloader to exit and
  43. * jump to the application address it specifies, it sends two sequential commands which must be properly
  44. * acknowledged. Upon reception of the first the RunBootloader flag is cleared and the WaitForExit flag is set,
  45. * causing the bootloader to wait for the final exit command before shutting down.
  46. */
  47. static bool WaitForExit = false;
  48. /** Current DFU state machine state, one of the values in the DFU_State_t enum. */
  49. static uint8_t DFU_State = dfuIDLE;
  50. /** Status code of the last executed DFU command. This is set to one of the values in the DFU_Status_t enum after
  51. * each operation, and returned to the host when a Get Status DFU request is issued.
  52. */
  53. static uint8_t DFU_Status = OK;
  54. /** Data containing the DFU command sent from the host. */
  55. static DFU_Command_t SentCommand;
  56. /** Response to the last issued Read Data DFU command. Unlike other DFU commands, the read command
  57. * requires a single byte response from the bootloader containing the read data when the next DFU_UPLOAD command
  58. * is issued by the host.
  59. */
  60. static uint8_t ResponseByte;
  61. /** Pointer to the start of the user application. By default this is 0x0000 (the reset vector), however the host
  62. * may specify an alternate address when issuing the application soft-start command.
  63. */
  64. static AppPtr_t AppStartPtr = (AppPtr_t)0x0000;
  65. /** 64-bit flash page number. This is concatenated with the current 16-bit address on USB AVRs containing more than
  66. * 64KB of flash memory.
  67. */
  68. static uint8_t Flash64KBPage = 0;
  69. /** Memory start address, indicating the current address in the memory being addressed (either FLASH or EEPROM
  70. * depending on the issued command from the host).
  71. */
  72. static uint16_t StartAddr = 0x0000;
  73. /** Memory end address, indicating the end address to read from/write to in the memory being addressed (either FLASH
  74. * of EEPROM depending on the issued command from the host).
  75. */
  76. static uint16_t EndAddr = 0x0000;
  77. /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
  78. * 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
  79. * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
  80. * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
  81. */
  82. uint16_t MagicBootKey ATTR_NO_INIT;
  83. /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
  84. * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
  85. * this will force the user application to start via a software jump.
  86. */
  87. void Application_Jump_Check(void)
  88. {
  89. bool JumpToApplication = false;
  90. #if (BOARD == BOARD_LEONARDO)
  91. /* Enable pull-up on the IO13 pin so we can use it to select the mode */
  92. PORTC |= (1 << 7);
  93. Delay_MS(10);
  94. /* If IO13 is not jumpered to ground, start the user application instead */
  95. JumpToApplication = ((PINC & (1 << 7)) != 0);
  96. /* Disable pull-up after the check has completed */
  97. PORTC &= ~(1 << 7);
  98. #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
  99. /* Disable JTAG debugging */
  100. JTAG_DISABLE();
  101. /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
  102. PORTF |= (1 << 4);
  103. Delay_MS(10);
  104. /* If the TCK pin is not jumpered to ground, start the user application instead */
  105. JumpToApplication = ((PINF & (1 << 4)) != 0);
  106. /* Re-enable JTAG debugging */
  107. JTAG_ENABLE();
  108. #else
  109. /* Check if the device's BOOTRST fuse is set */
  110. if (BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & FUSE_BOOTRST)
  111. {
  112. /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
  113. if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
  114. JumpToApplication = true;
  115. /* Clear reset source */
  116. MCUSR &= ~(1 << EXTRF);
  117. }
  118. else
  119. {
  120. /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
  121. * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
  122. if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
  123. JumpToApplication = true;
  124. /* Clear reset source */
  125. MCUSR &= ~(1 << WDRF);
  126. }
  127. #endif
  128. /* Don't run the user application if the reset vector is blank (no app loaded) */
  129. bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
  130. /* If a request has been made to jump to the user application, honor it */
  131. if (JumpToApplication && ApplicationValid)
  132. {
  133. /* Turn off the watchdog */
  134. MCUSR &= ~(1 << WDRF);
  135. wdt_disable();
  136. /* Clear the boot key and jump to the user application */
  137. MagicBootKey = 0;
  138. // cppcheck-suppress constStatement
  139. ((void (*)(void))0x0000)();
  140. }
  141. }
  142. /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
  143. * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
  144. * the loaded application code.
  145. */
  146. int main(void)
  147. {
  148. /* Configure hardware required by the bootloader */
  149. SetupHardware();
  150. /* Turn on first LED on the board to indicate that the bootloader has started */
  151. LEDs_SetAllLEDs(LEDS_LED1);
  152. /* Enable global interrupts so that the USB stack can function */
  153. GlobalInterruptEnable();
  154. /* Run the USB management task while the bootloader is supposed to be running */
  155. while (RunBootloader || WaitForExit)
  156. USB_USBTask();
  157. /* Wait a short time to end all USB transactions and then disconnect */
  158. _delay_us(1000);
  159. /* Reset configured hardware back to their original states for the user application */
  160. ResetHardware();
  161. /* Start the user application */
  162. AppStartPtr();
  163. }
  164. /** Configures all hardware required for the bootloader. */
  165. static void SetupHardware(void)
  166. {
  167. /* Disable watchdog if enabled by bootloader/fuses */
  168. MCUSR &= ~(1 << WDRF);
  169. wdt_disable();
  170. /* Disable clock division */
  171. clock_prescale_set(clock_div_1);
  172. /* Relocate the interrupt vector table to the bootloader section */
  173. MCUCR = (1 << IVCE);
  174. MCUCR = (1 << IVSEL);
  175. /* Initialize the USB and other board hardware drivers */
  176. USB_Init();
  177. LEDs_Init();
  178. /* Bootloader active LED toggle timer initialization */
  179. TIMSK1 = (1 << TOIE1);
  180. TCCR1B = ((1 << CS11) | (1 << CS10));
  181. }
  182. /** Resets all configured hardware required for the bootloader back to their original states. */
  183. static void ResetHardware(void)
  184. {
  185. /* Shut down the USB and other board hardware drivers */
  186. USB_Disable();
  187. LEDs_Disable();
  188. /* Disable Bootloader active LED toggle timer */
  189. TIMSK1 = 0;
  190. TCCR1B = 0;
  191. /* Relocate the interrupt vector table back to the application section */
  192. MCUCR = (1 << IVCE);
  193. MCUCR = 0;
  194. }
  195. /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
  196. ISR(TIMER1_OVF_vect, ISR_BLOCK)
  197. {
  198. LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
  199. }
  200. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  201. * the device from the USB host before passing along unhandled control requests to the library for processing
  202. * internally.
  203. */
  204. void EVENT_USB_Device_ControlRequest(void)
  205. {
  206. /* Ignore any requests that aren't directed to the DFU interface */
  207. if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
  208. (REQTYPE_CLASS | REQREC_INTERFACE))
  209. {
  210. return;
  211. }
  212. /* Activity - toggle indicator LEDs */
  213. LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
  214. /* Get the size of the command and data from the wLength value */
  215. SentCommand.DataSize = USB_ControlRequest.wLength;
  216. switch (USB_ControlRequest.bRequest)
  217. {
  218. case DFU_REQ_DNLOAD:
  219. Endpoint_ClearSETUP();
  220. /* Check if bootloader is waiting to terminate */
  221. if (WaitForExit)
  222. {
  223. /* Bootloader is terminating - process last received command */
  224. ProcessBootloaderCommand();
  225. /* Indicate that the last command has now been processed - free to exit bootloader */
  226. WaitForExit = false;
  227. }
  228. /* If the request has a data stage, load it into the command struct */
  229. if (SentCommand.DataSize)
  230. {
  231. while (!(Endpoint_IsOUTReceived()))
  232. {
  233. if (USB_DeviceState == DEVICE_STATE_Unattached)
  234. return;
  235. }
  236. /* First byte of the data stage is the DNLOAD request's command */
  237. SentCommand.Command = Endpoint_Read_8();
  238. /* One byte of the data stage is the command, so subtract it from the total data bytes */
  239. SentCommand.DataSize--;
  240. /* Load in the rest of the data stage as command parameters */
  241. for (uint8_t DataByte = 0; (DataByte < sizeof(SentCommand.Data)) &&
  242. Endpoint_BytesInEndpoint(); DataByte++)
  243. {
  244. SentCommand.Data[DataByte] = Endpoint_Read_8();
  245. SentCommand.DataSize--;
  246. }
  247. /* Process the command */
  248. ProcessBootloaderCommand();
  249. }
  250. /* Check if currently downloading firmware */
  251. if (DFU_State == dfuDNLOAD_IDLE)
  252. {
  253. if (!(SentCommand.DataSize))
  254. {
  255. DFU_State = dfuIDLE;
  256. }
  257. else
  258. {
  259. /* Throw away the filler bytes before the start of the firmware */
  260. DiscardFillerBytes(DFU_FILLER_BYTES_SIZE);
  261. /* Throw away the packet alignment filler bytes before the start of the firmware */
  262. DiscardFillerBytes(StartAddr % FIXED_CONTROL_ENDPOINT_SIZE);
  263. /* Calculate the number of bytes remaining to be written */
  264. uint16_t BytesRemaining = ((EndAddr - StartAddr) + 1);
  265. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Write flash
  266. {
  267. /* Calculate the number of words to be written from the number of bytes to be written */
  268. uint16_t WordsRemaining = (BytesRemaining >> 1);
  269. union
  270. {
  271. uint16_t Words[2];
  272. uint32_t Long;
  273. } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
  274. uint32_t CurrFlashPageStartAddress = CurrFlashAddress.Long;
  275. uint8_t WordsInFlashPage = 0;
  276. while (WordsRemaining--)
  277. {
  278. /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
  279. if (!(Endpoint_BytesInEndpoint()))
  280. {
  281. Endpoint_ClearOUT();
  282. while (!(Endpoint_IsOUTReceived()))
  283. {
  284. if (USB_DeviceState == DEVICE_STATE_Unattached)
  285. return;
  286. }
  287. }
  288. /* Write the next word into the current flash page */
  289. BootloaderAPI_FillWord(CurrFlashAddress.Long, Endpoint_Read_16_LE());
  290. /* Adjust counters */
  291. WordsInFlashPage += 1;
  292. CurrFlashAddress.Long += 2;
  293. /* See if an entire page has been written to the flash page buffer */
  294. if ((WordsInFlashPage == (SPM_PAGESIZE >> 1)) || !(WordsRemaining))
  295. {
  296. /* Commit the flash page to memory */
  297. BootloaderAPI_WritePage(CurrFlashPageStartAddress);
  298. /* Check if programming incomplete */
  299. if (WordsRemaining)
  300. {
  301. CurrFlashPageStartAddress = CurrFlashAddress.Long;
  302. WordsInFlashPage = 0;
  303. /* Erase next page's temp buffer */
  304. BootloaderAPI_ErasePage(CurrFlashAddress.Long);
  305. }
  306. }
  307. }
  308. /* Once programming complete, start address equals the end address */
  309. StartAddr = EndAddr;
  310. }
  311. else // Write EEPROM
  312. {
  313. while (BytesRemaining--)
  314. {
  315. /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
  316. if (!(Endpoint_BytesInEndpoint()))
  317. {
  318. Endpoint_ClearOUT();
  319. while (!(Endpoint_IsOUTReceived()))
  320. {
  321. if (USB_DeviceState == DEVICE_STATE_Unattached)
  322. return;
  323. }
  324. }
  325. /* Read the byte from the USB interface and write to to the EEPROM */
  326. eeprom_update_byte((uint8_t*)StartAddr, Endpoint_Read_8());
  327. /* Adjust counters */
  328. StartAddr++;
  329. }
  330. }
  331. /* Throw away the currently unused DFU file suffix */
  332. DiscardFillerBytes(DFU_FILE_SUFFIX_SIZE);
  333. }
  334. }
  335. Endpoint_ClearOUT();
  336. Endpoint_ClearStatusStage();
  337. break;
  338. case DFU_REQ_UPLOAD:
  339. Endpoint_ClearSETUP();
  340. while (!(Endpoint_IsINReady()))
  341. {
  342. if (USB_DeviceState == DEVICE_STATE_Unattached)
  343. return;
  344. }
  345. if (DFU_State != dfuUPLOAD_IDLE)
  346. {
  347. if ((DFU_State == dfuERROR) && IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Blank Check
  348. {
  349. /* Blank checking is performed in the DFU_DNLOAD request - if we get here we've told the host
  350. that the memory isn't blank, and the host is requesting the first non-blank address */
  351. Endpoint_Write_16_LE(StartAddr);
  352. }
  353. else
  354. {
  355. /* Idle state upload - send response to last issued command */
  356. Endpoint_Write_8(ResponseByte);
  357. }
  358. }
  359. else
  360. {
  361. /* Determine the number of bytes remaining in the current block */
  362. uint16_t BytesRemaining = ((EndAddr - StartAddr) + 1);
  363. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Read FLASH
  364. {
  365. /* Calculate the number of words to be written from the number of bytes to be written */
  366. uint16_t WordsRemaining = (BytesRemaining >> 1);
  367. union
  368. {
  369. uint16_t Words[2];
  370. uint32_t Long;
  371. } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
  372. while (WordsRemaining--)
  373. {
  374. /* Check if endpoint is full - if so clear it and wait until ready for next packet */
  375. if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE)
  376. {
  377. Endpoint_ClearIN();
  378. while (!(Endpoint_IsINReady()))
  379. {
  380. if (USB_DeviceState == DEVICE_STATE_Unattached)
  381. return;
  382. }
  383. }
  384. /* Read the flash word and send it via USB to the host */
  385. #if (FLASHEND > 0xFFFF)
  386. Endpoint_Write_16_LE(pgm_read_word_far(CurrFlashAddress.Long));
  387. #else
  388. Endpoint_Write_16_LE(pgm_read_word(CurrFlashAddress.Long));
  389. #endif
  390. /* Adjust counters */
  391. CurrFlashAddress.Long += 2;
  392. }
  393. /* Once reading is complete, start address equals the end address */
  394. StartAddr = EndAddr;
  395. }
  396. else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x02)) // Read EEPROM
  397. {
  398. while (BytesRemaining--)
  399. {
  400. /* Check if endpoint is full - if so clear it and wait until ready for next packet */
  401. if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE)
  402. {
  403. Endpoint_ClearIN();
  404. while (!(Endpoint_IsINReady()))
  405. {
  406. if (USB_DeviceState == DEVICE_STATE_Unattached)
  407. return;
  408. }
  409. }
  410. /* Read the EEPROM byte and send it via USB to the host */
  411. Endpoint_Write_8(eeprom_read_byte((uint8_t*)StartAddr));
  412. /* Adjust counters */
  413. StartAddr++;
  414. }
  415. }
  416. /* Return to idle state */
  417. DFU_State = dfuIDLE;
  418. }
  419. Endpoint_ClearIN();
  420. Endpoint_ClearStatusStage();
  421. break;
  422. case DFU_REQ_GETSTATUS:
  423. Endpoint_ClearSETUP();
  424. while (!(Endpoint_IsINReady()))
  425. {
  426. if (USB_DeviceState == DEVICE_STATE_Unattached)
  427. return;
  428. }
  429. /* Write 8-bit status value */
  430. Endpoint_Write_8(DFU_Status);
  431. /* Write 24-bit poll timeout value */
  432. Endpoint_Write_8(0);
  433. Endpoint_Write_16_LE(0);
  434. /* Write 8-bit state value */
  435. Endpoint_Write_8(DFU_State);
  436. /* Write 8-bit state string ID number */
  437. Endpoint_Write_8(0);
  438. Endpoint_ClearIN();
  439. Endpoint_ClearStatusStage();
  440. break;
  441. case DFU_REQ_CLRSTATUS:
  442. Endpoint_ClearSETUP();
  443. /* Reset the status value variable to the default OK status */
  444. DFU_Status = OK;
  445. Endpoint_ClearStatusStage();
  446. break;
  447. case DFU_REQ_GETSTATE:
  448. Endpoint_ClearSETUP();
  449. while (!(Endpoint_IsINReady()))
  450. {
  451. if (USB_DeviceState == DEVICE_STATE_Unattached)
  452. return;
  453. }
  454. /* Write the current device state to the endpoint */
  455. Endpoint_Write_8(DFU_State);
  456. Endpoint_ClearIN();
  457. Endpoint_ClearStatusStage();
  458. break;
  459. case DFU_REQ_ABORT:
  460. Endpoint_ClearSETUP();
  461. /* Reset the current state variable to the default idle state */
  462. DFU_State = dfuIDLE;
  463. Endpoint_ClearStatusStage();
  464. break;
  465. }
  466. }
  467. /** Routine to discard the specified number of bytes from the control endpoint stream. This is used to
  468. * discard unused bytes in the stream from the host, including the memory program block suffix.
  469. *
  470. * \param[in] NumberOfBytes Number of bytes to discard from the host from the control endpoint
  471. */
  472. static void DiscardFillerBytes(uint8_t NumberOfBytes)
  473. {
  474. while (NumberOfBytes--)
  475. {
  476. if (!(Endpoint_BytesInEndpoint()))
  477. {
  478. Endpoint_ClearOUT();
  479. /* Wait until next data packet received */
  480. while (!(Endpoint_IsOUTReceived()))
  481. {
  482. if (USB_DeviceState == DEVICE_STATE_Unattached)
  483. return;
  484. }
  485. }
  486. else
  487. {
  488. Endpoint_Discard_8();
  489. }
  490. }
  491. }
  492. /** Routine to process an issued command from the host, via a DFU_DNLOAD request wrapper. This routine ensures
  493. * that the command is allowed based on the current secure mode flag value, and passes the command off to the
  494. * appropriate handler function.
  495. */
  496. static void ProcessBootloaderCommand(void)
  497. {
  498. /* Check if device is in secure mode */
  499. if (IsSecure)
  500. {
  501. /* Don't process command unless it is a READ or chip erase command */
  502. if (!(((SentCommand.Command == COMMAND_WRITE) &&
  503. IS_TWOBYTE_COMMAND(SentCommand.Data, 0x00, 0xFF)) ||
  504. (SentCommand.Command == COMMAND_READ)))
  505. {
  506. /* Set the state and status variables to indicate the error */
  507. DFU_State = dfuERROR;
  508. DFU_Status = errWRITE;
  509. /* Stall command */
  510. Endpoint_StallTransaction();
  511. /* Don't process the command */
  512. return;
  513. }
  514. }
  515. /* Dispatch the required command processing routine based on the command type */
  516. switch (SentCommand.Command)
  517. {
  518. case COMMAND_PROG_START:
  519. ProcessMemProgCommand();
  520. break;
  521. case COMMAND_DISP_DATA:
  522. ProcessMemReadCommand();
  523. break;
  524. case COMMAND_WRITE:
  525. ProcessWriteCommand();
  526. break;
  527. case COMMAND_READ:
  528. ProcessReadCommand();
  529. break;
  530. case COMMAND_CHANGE_BASE_ADDR:
  531. if (IS_TWOBYTE_COMMAND(SentCommand.Data, 0x03, 0x00)) // Set 64KB flash page command
  532. Flash64KBPage = SentCommand.Data[2];
  533. break;
  534. }
  535. }
  536. /** Routine to concatenate the given pair of 16-bit memory start and end addresses from the host, and store them
  537. * in the StartAddr and EndAddr global variables.
  538. */
  539. static void LoadStartEndAddresses(void)
  540. {
  541. union
  542. {
  543. uint8_t Bytes[2];
  544. uint16_t Word;
  545. } Address[2] = {{.Bytes = {SentCommand.Data[2], SentCommand.Data[1]}},
  546. {.Bytes = {SentCommand.Data[4], SentCommand.Data[3]}}};
  547. /* Load in the start and ending read addresses from the sent data packet */
  548. StartAddr = Address[0].Word;
  549. EndAddr = Address[1].Word;
  550. }
  551. /** Handler for a Memory Program command issued by the host. This routine handles the preparations needed
  552. * to write subsequent data from the host into the specified memory.
  553. */
  554. static void ProcessMemProgCommand(void)
  555. {
  556. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00) || // Write FLASH command
  557. IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Write EEPROM command
  558. {
  559. /* Load in the start and ending read addresses */
  560. LoadStartEndAddresses();
  561. /* If FLASH is being written to, we need to pre-erase the first page to write to */
  562. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00))
  563. {
  564. union
  565. {
  566. uint16_t Words[2];
  567. uint32_t Long;
  568. } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
  569. /* Erase the current page's temp buffer */
  570. BootloaderAPI_ErasePage(CurrFlashAddress.Long);
  571. }
  572. /* Set the state so that the next DNLOAD requests reads in the firmware */
  573. DFU_State = dfuDNLOAD_IDLE;
  574. }
  575. }
  576. /** Handler for a Memory Read command issued by the host. This routine handles the preparations needed
  577. * to read subsequent data from the specified memory out to the host, as well as implementing the memory
  578. * blank check command.
  579. */
  580. static void ProcessMemReadCommand(void)
  581. {
  582. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00) || // Read FLASH command
  583. IS_ONEBYTE_COMMAND(SentCommand.Data, 0x02)) // Read EEPROM command
  584. {
  585. /* Load in the start and ending read addresses */
  586. LoadStartEndAddresses();
  587. /* Set the state so that the next UPLOAD requests read out the firmware */
  588. DFU_State = dfuUPLOAD_IDLE;
  589. }
  590. else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Blank check FLASH command
  591. {
  592. uint32_t CurrFlashAddress = 0;
  593. while (CurrFlashAddress < (uint32_t)BOOT_START_ADDR)
  594. {
  595. /* Check if the current byte is not blank */
  596. #if (FLASHEND > 0xFFFF)
  597. if (pgm_read_byte_far(CurrFlashAddress) != 0xFF)
  598. #else
  599. if (pgm_read_byte(CurrFlashAddress) != 0xFF)
  600. #endif
  601. {
  602. /* Save the location of the first non-blank byte for response back to the host */
  603. Flash64KBPage = (CurrFlashAddress >> 16);
  604. StartAddr = CurrFlashAddress;
  605. /* Set state and status variables to the appropriate error values */
  606. DFU_State = dfuERROR;
  607. DFU_Status = errCHECK_ERASED;
  608. break;
  609. }
  610. CurrFlashAddress++;
  611. }
  612. }
  613. }
  614. /** Handler for a Data Write command issued by the host. This routine handles non-programming commands such as
  615. * bootloader exit (both via software jumps and hardware watchdog resets) and flash memory erasure.
  616. */
  617. static void ProcessWriteCommand(void)
  618. {
  619. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x03)) // Start application
  620. {
  621. /* Indicate that the bootloader is terminating */
  622. WaitForExit = true;
  623. /* Check if data supplied for the Start Program command - no data executes the program */
  624. if (SentCommand.DataSize)
  625. {
  626. if (SentCommand.Data[1] == 0x01) // Start via jump
  627. {
  628. union
  629. {
  630. uint8_t Bytes[2];
  631. AppPtr_t FuncPtr;
  632. } Address = {.Bytes = {SentCommand.Data[4], SentCommand.Data[3]}};
  633. /* Load in the jump address into the application start address pointer */
  634. AppStartPtr = Address.FuncPtr;
  635. }
  636. }
  637. else
  638. {
  639. if (SentCommand.Data[1] == 0x00) // Start via watchdog
  640. {
  641. /* Unlock the forced application start mode of the bootloader if it is restarted */
  642. MagicBootKey = MAGIC_BOOT_KEY;
  643. /* Start the watchdog to reset the AVR once the communications are finalized */
  644. wdt_enable(WDTO_250MS);
  645. }
  646. else // Start via jump
  647. {
  648. /* Set the flag to terminate the bootloader at next opportunity if a valid application has been loaded */
  649. if (pgm_read_word_near(0) == 0xFFFF)
  650. RunBootloader = false;
  651. }
  652. }
  653. }
  654. else if (IS_TWOBYTE_COMMAND(SentCommand.Data, 0x00, 0xFF)) // Erase flash
  655. {
  656. /* Clear the application section of flash */
  657. for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < (uint32_t)BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE)
  658. BootloaderAPI_ErasePage(CurrFlashAddress);
  659. /* Memory has been erased, reset the security bit so that programming/reading is allowed */
  660. IsSecure = false;
  661. }
  662. }
  663. /** Handler for a Data Read command issued by the host. This routine handles bootloader information retrieval
  664. * commands such as device signature and bootloader version retrieval.
  665. */
  666. static void ProcessReadCommand(void)
  667. {
  668. const uint8_t BootloaderInfo[3] = {BOOTLOADER_VERSION, BOOTLOADER_ID_BYTE1, BOOTLOADER_ID_BYTE2};
  669. const uint8_t SignatureInfo[4] = {0x58, AVR_SIGNATURE_1, AVR_SIGNATURE_2, AVR_SIGNATURE_3};
  670. uint8_t DataIndexToRead = SentCommand.Data[1];
  671. bool ReadAddressInvalid = false;
  672. if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Read bootloader info
  673. {
  674. if (DataIndexToRead < 3)
  675. ResponseByte = BootloaderInfo[DataIndexToRead];
  676. else
  677. ReadAddressInvalid = true;
  678. }
  679. else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Read signature byte
  680. {
  681. switch (DataIndexToRead)
  682. {
  683. case 0x30:
  684. ResponseByte = SignatureInfo[0];
  685. break;
  686. case 0x31:
  687. ResponseByte = SignatureInfo[1];
  688. break;
  689. case 0x60:
  690. ResponseByte = SignatureInfo[2];
  691. break;
  692. case 0x61:
  693. ResponseByte = SignatureInfo[3];
  694. break;
  695. default:
  696. ReadAddressInvalid = true;
  697. break;
  698. }
  699. }
  700. if (ReadAddressInvalid)
  701. {
  702. /* Set the state and status variables to indicate the error */
  703. DFU_State = dfuERROR;
  704. DFU_Status = errADDRESS;
  705. }
  706. }