You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

BootloaderDFU.c 25KB

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