ce76abe2999152b5b2167f730bb72ed5f0df7b78
[pub/lufa.git] / Bootloaders / DFU / BootloaderDFU.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2021.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2021 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaims all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 *
33 * Main source file for the DFU class bootloader. This file contains the complete bootloader logic.
34 */
35
36 #define INCLUDE_FROM_BOOTLOADER_C
37 #include "BootloaderDFU.h"
38
39 /** Flag to indicate if the bootloader is currently running in secure mode, disallowing memory operations
40 * other than erase. This is initially set to the value set by SECURE_MODE, and cleared by the bootloader
41 * once a memory erase has completed in a bootloader session.
42 */
43 static bool IsSecure = SECURE_MODE;
44
45 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run
46 * via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application
47 * jumped to via an indirect jump to location 0x0000 (or other location specified by the host).
48 */
49 static bool RunBootloader = true;
50
51 /** Flag to indicate if the bootloader is waiting to exit. When the host requests the bootloader to exit and
52 * jump to the application address it specifies, it sends two sequential commands which must be properly
53 * acknowledged. Upon reception of the first the RunBootloader flag is cleared and the WaitForExit flag is set,
54 * causing the bootloader to wait for the final exit command before shutting down.
55 */
56 static bool WaitForExit = false;
57
58 /** Current DFU state machine state, one of the values in the DFU_State_t enum. */
59 static uint8_t DFU_State = dfuIDLE;
60
61 /** Status code of the last executed DFU command. This is set to one of the values in the DFU_Status_t enum after
62 * each operation, and returned to the host when a Get Status DFU request is issued.
63 */
64 static uint8_t DFU_Status = OK;
65
66 /** Data containing the DFU command sent from the host. */
67 static DFU_Command_t SentCommand;
68
69 /** Response to the last issued Read Data DFU command. Unlike other DFU commands, the read command
70 * requires a single byte response from the bootloader containing the read data when the next DFU_UPLOAD command
71 * is issued by the host.
72 */
73 static uint8_t ResponseByte;
74
75 /** Pointer to the start of the user application. By default this is 0x0000 (the reset vector), however the host
76 * may specify an alternate address when issuing the application soft-start command.
77 */
78 static AppPtr_t AppStartPtr = (AppPtr_t)0x0000;
79
80 /** 64-bit flash page number. This is concatenated with the current 16-bit address on USB AVRs containing more than
81 * 64KB of flash memory.
82 */
83 static uint8_t Flash64KBPage = 0;
84
85 /** Memory start address, indicating the current address in the memory being addressed (either FLASH or EEPROM
86 * depending on the issued command from the host).
87 */
88 static uint16_t StartAddr = 0x0000;
89
90 /** Memory end address, indicating the end address to read from/write to in the memory being addressed (either FLASH
91 * of EEPROM depending on the issued command from the host).
92 */
93 static uint16_t EndAddr = 0x0000;
94
95 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
96 * 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
97 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
98 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
99 */
100 uint16_t MagicBootKey ATTR_NO_INIT;
101
102
103 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
104 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
105 * this will force the user application to start via a software jump.
106 */
107 void Application_Jump_Check(void)
108 {
109 bool JumpToApplication = false;
110
111 #if (BOARD == BOARD_LEONARDO)
112 /* Enable pull-up on the IO13 pin so we can use it to select the mode */
113 PORTC |= (1 << 7);
114 Delay_MS(10);
115
116 /* If IO13 is not jumpered to ground, start the user application instead */
117 JumpToApplication = ((PINC & (1 << 7)) != 0);
118
119 /* Disable pull-up after the check has completed */
120 PORTC &= ~(1 << 7);
121 #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
122 /* Disable JTAG debugging */
123 JTAG_DISABLE();
124
125 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
126 PORTF |= (1 << 4);
127 Delay_MS(10);
128
129 /* If the TCK pin is not jumpered to ground, start the user application instead */
130 JumpToApplication = ((PINF & (1 << 4)) != 0);
131
132 /* Re-enable JTAG debugging */
133 JTAG_ENABLE();
134 #elif ((BOARD == BOARD_PROMICRO) || (BOARD == BOARD_MICRO))
135 /* Pro-Micro and Arduino Micro board use power-on reset, but no external reset. Both boards have
136 * the hardware bootloader pin HWBE enabled. Unfortunately only the external reset allows together
137 * with an enabled HWBE that the CPU start at the bootloader address independent of the FUSE_BOOTRST.
138 * That means the power-on reset will start just controlled by the FUSE_BOOTRST the bootloader or
139 * direct in the application and cannot be overridden by HWBE signal. Therfore FUSE_BOOTRST shall
140 * be enabled, otherwise the bootloader will not be reached for these boards.
141 * The bootloader checks FUSE_HWBE as *unprogammed* instead of FUSE_BOOTRST as programmed on other
142 * board variants to decide fast application start, without waiting the dedicted bootloader timeout
143 * in case of a USB, watchdog, brown-out or JTAG reset. If the watchdog reset was initiated from
144 * the bootloader marked with the MAGIC_BOOT_KEY this reset flag is reset. All other reset flags
145 * are left untouched to allow the application code checking the reset signals, especially in case
146 * of application fast start.
147 * The bootloader is entered always for external reset and power-on reset. But the bootloader is
148 * anyway exited after that dedicted timeout, if a reset-vector to the application is programmed.
149 * Once a DFU program interacts this the bootloader during this dedicted timeout, the timer stops
150 * and the application needs to be started by DFU bootloader command manually or using a reset.
151 */
152
153 /* Check if the device's forced Bootloader via Hardware Bootenable is unprogrammed */
154 if (BootloaderAPI_ReadFuse(GET_EXTENDED_FUSE_BITS) & ~FUSE_HWBE)
155 {
156 /* If the reset source was not an external or power-on reset jump to the application */
157 if (!(MCUSR & ((1 << EXTRF) || (1 << PORF))))
158 JumpToApplication = true;
159 }
160 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
161 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
162 if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
163 {
164 JumpToApplication = true;
165
166 /* Clear reset source */
167 MCUSR &= ~(1 << WDRF);
168 }
169 #else
170 /* Check if the device's BOOTRST fuse is set */
171 if (!(BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & ~FUSE_BOOTRST))
172 {
173 /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
174 if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
175 JumpToApplication = true;
176
177 /* Clear reset source */
178 MCUSR &= ~(1 << EXTRF);
179 }
180 else
181 {
182 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
183 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
184 if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
185 JumpToApplication = true;
186
187 /* Clear reset source */
188 MCUSR &= ~(1 << WDRF);
189 }
190 #endif
191
192 /* Clear the boot key in any case */
193 MagicBootKey = 0;
194
195 /* Don't run the user application if the reset vector is blank (no app loaded) */
196 bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
197
198 /* If a request has been made to jump to the user application, honor it */
199 if (JumpToApplication && ApplicationValid)
200 {
201 /* Turn off the watchdog */
202 wdt_disable();
203
204 // cppcheck-suppress constStatement
205 ((void (*)(void))0x0000)();
206 }
207 }
208
209
210 static volatile bool stayinbootloader;
211
212 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
213 * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
214 * the loaded application code.
215 */
216 int main(void)
217 {
218 /* Configure hardware required by the bootloader */
219 SetupHardware();
220
221 /* Turn on first LED on the board to indicate that the bootloader has started */
222 LEDs_SetAllLEDs(LEDS_LED1);
223
224 /* Enable global interrupts so that the USB stack can function */
225 GlobalInterruptEnable();
226
227 /* Run the USB management task while the bootloader is supposed to be running */
228 stayinbootloader = false;
229
230 uint16_t i = 0;
231 while (RunBootloader || WaitForExit)
232 {
233 USB_USBTask();
234
235 if (!stayinbootloader)
236 {
237 Delay_MS(1);
238 if (i++ > 5000)
239 {
240 if (pgm_read_word_near(0) != 0xFFFF)
241 break;
242 else
243 i = 0;
244 }
245 }
246 else
247 {
248 i = 0;
249 }
250 }
251
252 /* Wait a short time to end all USB transactions and then disconnect */
253 _delay_us(1000);
254
255 /* Reset configured hardware back to their original states for the user application */
256 ResetHardware();
257
258 /* Start the user application */
259 AppStartPtr();
260 }
261
262 /** Configures all hardware required for the bootloader. */
263 static void SetupHardware(void)
264 {
265 /* Disable watchdog if enabled by bootloader/fuses */
266 MCUSR &= ~(1 << WDRF);
267 wdt_disable();
268
269 /* Disable clock division */
270 clock_prescale_set(clock_div_1);
271
272 /* Relocate the interrupt vector table to the bootloader section */
273 MCUCR = (1 << IVCE);
274 MCUCR = (1 << IVSEL);
275
276 /* Initialize the USB and other board hardware drivers */
277 USB_Init();
278 LEDs_Init();
279
280 /* Bootloader active LED toggle timer initialization */
281 TIMSK1 = (1 << TOIE1);
282 TCCR1B = ((1 << CS11) | (1 << CS10));
283 }
284
285 /** Resets all configured hardware required for the bootloader back to their original states. */
286 static void ResetHardware(void)
287 {
288 /* Shut down the USB and other board hardware drivers */
289 USB_Disable();
290 LEDs_Disable();
291
292 /* Disable Bootloader active LED toggle timer */
293 TIMSK1 = 0;
294 TCCR1B = 0;
295
296 /* Relocate the interrupt vector table back to the application section */
297 MCUCR = (1 << IVCE);
298 MCUCR = 0;
299 }
300
301 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
302 ISR(TIMER1_OVF_vect, ISR_BLOCK)
303 {
304 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
305 }
306
307 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
308 * the device from the USB host before passing along unhandled control requests to the library for processing
309 * internally.
310 */
311 void EVENT_USB_Device_ControlRequest(void)
312 {
313 /* Ignore any requests that aren't directed to the DFU interface */
314 if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
315 (REQTYPE_CLASS | REQREC_INTERFACE))
316 {
317 return;
318 }
319
320 stayinbootloader = true;
321
322 /* Activity - toggle indicator LEDs */
323 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
324
325 /* Get the size of the command and data from the wLength value */
326 SentCommand.DataSize = USB_ControlRequest.wLength;
327
328 switch (USB_ControlRequest.bRequest)
329 {
330 case DFU_REQ_DNLOAD:
331 Endpoint_ClearSETUP();
332
333 /* Check if bootloader is waiting to terminate */
334 if (WaitForExit)
335 {
336 /* Bootloader is terminating - process last received command */
337 ProcessBootloaderCommand();
338
339 /* Indicate that the last command has now been processed - free to exit bootloader */
340 WaitForExit = false;
341 }
342
343 /* If the request has a data stage, load it into the command struct */
344 if (SentCommand.DataSize)
345 {
346 while (!(Endpoint_IsOUTReceived()))
347 {
348 if (USB_DeviceState == DEVICE_STATE_Unattached)
349 return;
350 }
351
352 /* First byte of the data stage is the DNLOAD request's command */
353 SentCommand.Command = Endpoint_Read_8();
354
355 /* One byte of the data stage is the command, so subtract it from the total data bytes */
356 SentCommand.DataSize--;
357
358 /* Load in the rest of the data stage as command parameters */
359 for (uint8_t DataByte = 0; (DataByte < sizeof(SentCommand.Data)) &&
360 Endpoint_BytesInEndpoint(); DataByte++)
361 {
362 SentCommand.Data[DataByte] = Endpoint_Read_8();
363 SentCommand.DataSize--;
364 }
365
366 /* Process the command */
367 ProcessBootloaderCommand();
368 }
369
370 /* Check if currently downloading firmware */
371 if (DFU_State == dfuDNLOAD_IDLE)
372 {
373 if (!(SentCommand.DataSize))
374 {
375 DFU_State = dfuIDLE;
376 }
377 else
378 {
379 /* Throw away the filler bytes before the start of the firmware */
380 DiscardFillerBytes(DFU_FILLER_BYTES_SIZE);
381
382 /* Throw away the packet alignment filler bytes before the start of the firmware */
383 DiscardFillerBytes(StartAddr % FIXED_CONTROL_ENDPOINT_SIZE);
384
385 /* Calculate the number of bytes remaining to be written */
386 uint16_t BytesRemaining = ((EndAddr - StartAddr) + 1);
387
388 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Write flash
389 {
390 /* Calculate the number of words to be written from the number of bytes to be written */
391 uint16_t WordsRemaining = (BytesRemaining >> 1);
392
393 union
394 {
395 uint16_t Words[2];
396 uint32_t Long;
397 } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
398
399 uint32_t CurrFlashPageStartAddress = CurrFlashAddress.Long;
400 uint8_t WordsInFlashPage = 0;
401
402 while (WordsRemaining--)
403 {
404 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
405 if (!(Endpoint_BytesInEndpoint()))
406 {
407 Endpoint_ClearOUT();
408
409 while (!(Endpoint_IsOUTReceived()))
410 {
411 if (USB_DeviceState == DEVICE_STATE_Unattached)
412 return;
413 }
414 }
415
416 /* Write the next word into the current flash page */
417 BootloaderAPI_FillWord(CurrFlashAddress.Long, Endpoint_Read_16_LE());
418
419 /* Adjust counters */
420 WordsInFlashPage += 1;
421 CurrFlashAddress.Long += 2;
422
423 /* See if an entire page has been written to the flash page buffer */
424 if ((WordsInFlashPage == (SPM_PAGESIZE >> 1)) || !(WordsRemaining))
425 {
426 /* Commit the flash page to memory */
427 BootloaderAPI_WritePage(CurrFlashPageStartAddress);
428
429 /* Check if programming incomplete */
430 if (WordsRemaining)
431 {
432 CurrFlashPageStartAddress = CurrFlashAddress.Long;
433 WordsInFlashPage = 0;
434
435 /* Erase next page's temp buffer */
436 BootloaderAPI_ErasePage(CurrFlashAddress.Long);
437 }
438 }
439 }
440
441 /* Once programming complete, start address equals the end address */
442 StartAddr = EndAddr;
443 }
444 else // Write EEPROM
445 {
446 while (BytesRemaining--)
447 {
448 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
449 if (!(Endpoint_BytesInEndpoint()))
450 {
451 Endpoint_ClearOUT();
452
453 while (!(Endpoint_IsOUTReceived()))
454 {
455 if (USB_DeviceState == DEVICE_STATE_Unattached)
456 return;
457 }
458 }
459
460 /* Read the byte from the USB interface and write to to the EEPROM */
461 eeprom_update_byte((uint8_t*)StartAddr, Endpoint_Read_8());
462
463 /* Adjust counters */
464 StartAddr++;
465 }
466 }
467
468 /* Throw away the currently unused DFU file suffix */
469 DiscardFillerBytes(DFU_FILE_SUFFIX_SIZE);
470 }
471 }
472
473 Endpoint_ClearOUT();
474
475 Endpoint_ClearStatusStage();
476
477 break;
478 case DFU_REQ_UPLOAD:
479 Endpoint_ClearSETUP();
480
481 while (!(Endpoint_IsINReady()))
482 {
483 if (USB_DeviceState == DEVICE_STATE_Unattached)
484 return;
485 }
486
487 if (DFU_State != dfuUPLOAD_IDLE)
488 {
489 if ((DFU_State == dfuERROR) && IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Blank Check
490 {
491 /* Blank checking is performed in the DFU_DNLOAD request - if we get here we've told the host
492 that the memory isn't blank, and the host is requesting the first non-blank address */
493 Endpoint_Write_16_LE(StartAddr);
494 }
495 else
496 {
497 /* Idle state upload - send response to last issued command */
498 Endpoint_Write_8(ResponseByte);
499 }
500 }
501 else
502 {
503 /* Determine the number of bytes remaining in the current block */
504 uint16_t BytesRemaining = ((EndAddr - StartAddr) + 1);
505
506 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Read FLASH
507 {
508 /* Calculate the number of words to be written from the number of bytes to be written */
509 uint16_t WordsRemaining = (BytesRemaining >> 1);
510
511 union
512 {
513 uint16_t Words[2];
514 uint32_t Long;
515 } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
516
517 while (WordsRemaining--)
518 {
519 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
520 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE)
521 {
522 Endpoint_ClearIN();
523
524 while (!(Endpoint_IsINReady()))
525 {
526 if (USB_DeviceState == DEVICE_STATE_Unattached)
527 return;
528 }
529 }
530
531 /* Read the flash word and send it via USB to the host */
532 #if (FLASHEND > 0xFFFF)
533 Endpoint_Write_16_LE(pgm_read_word_far(CurrFlashAddress.Long));
534 #else
535 Endpoint_Write_16_LE(pgm_read_word(CurrFlashAddress.Long));
536 #endif
537
538 /* Adjust counters */
539 CurrFlashAddress.Long += 2;
540 }
541
542 /* Once reading is complete, start address equals the end address */
543 StartAddr = EndAddr;
544 }
545 else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x02)) // Read EEPROM
546 {
547 while (BytesRemaining--)
548 {
549 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
550 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE)
551 {
552 Endpoint_ClearIN();
553
554 while (!(Endpoint_IsINReady()))
555 {
556 if (USB_DeviceState == DEVICE_STATE_Unattached)
557 return;
558 }
559 }
560
561 /* Read the EEPROM byte and send it via USB to the host */
562 Endpoint_Write_8(eeprom_read_byte((uint8_t*)StartAddr));
563
564 /* Adjust counters */
565 StartAddr++;
566 }
567 }
568
569 /* Return to idle state */
570 DFU_State = dfuIDLE;
571 }
572
573 Endpoint_ClearIN();
574
575 Endpoint_ClearStatusStage();
576 break;
577 case DFU_REQ_GETSTATUS:
578 Endpoint_ClearSETUP();
579
580 while (!(Endpoint_IsINReady()))
581 {
582 if (USB_DeviceState == DEVICE_STATE_Unattached)
583 return;
584 }
585
586 /* Write 8-bit status value */
587 Endpoint_Write_8(DFU_Status);
588
589 /* Write 24-bit poll timeout value */
590 Endpoint_Write_8(0);
591 Endpoint_Write_16_LE(0);
592
593 /* Write 8-bit state value */
594 Endpoint_Write_8(DFU_State);
595
596 /* Write 8-bit state string ID number */
597 Endpoint_Write_8(0);
598
599 Endpoint_ClearIN();
600
601 Endpoint_ClearStatusStage();
602 break;
603 case DFU_REQ_CLRSTATUS:
604 Endpoint_ClearSETUP();
605
606 /* Reset the status value variable to the default OK status */
607 DFU_Status = OK;
608
609 Endpoint_ClearStatusStage();
610 break;
611 case DFU_REQ_GETSTATE:
612 Endpoint_ClearSETUP();
613
614 while (!(Endpoint_IsINReady()))
615 {
616 if (USB_DeviceState == DEVICE_STATE_Unattached)
617 return;
618 }
619
620 /* Write the current device state to the endpoint */
621 Endpoint_Write_8(DFU_State);
622
623 Endpoint_ClearIN();
624
625 Endpoint_ClearStatusStage();
626 break;
627 case DFU_REQ_ABORT:
628 Endpoint_ClearSETUP();
629
630 /* Reset the current state variable to the default idle state */
631 DFU_State = dfuIDLE;
632
633 Endpoint_ClearStatusStage();
634 break;
635 }
636 }
637
638 /** Routine to discard the specified number of bytes from the control endpoint stream. This is used to
639 * discard unused bytes in the stream from the host, including the memory program block suffix.
640 *
641 * \param[in] NumberOfBytes Number of bytes to discard from the host from the control endpoint
642 */
643 static void DiscardFillerBytes(uint8_t NumberOfBytes)
644 {
645 while (NumberOfBytes--)
646 {
647 if (!(Endpoint_BytesInEndpoint()))
648 {
649 Endpoint_ClearOUT();
650
651 /* Wait until next data packet received */
652 while (!(Endpoint_IsOUTReceived()))
653 {
654 if (USB_DeviceState == DEVICE_STATE_Unattached)
655 return;
656 }
657 }
658 else
659 {
660 Endpoint_Discard_8();
661 }
662 }
663 }
664
665 /** Routine to process an issued command from the host, via a DFU_DNLOAD request wrapper. This routine ensures
666 * that the command is allowed based on the current secure mode flag value, and passes the command off to the
667 * appropriate handler function.
668 */
669 static void ProcessBootloaderCommand(void)
670 {
671 /* Check if device is in secure mode */
672 if (IsSecure)
673 {
674 /* Don't process command unless it is a READ or chip erase command */
675 if (!(((SentCommand.Command == COMMAND_WRITE) &&
676 IS_TWOBYTE_COMMAND(SentCommand.Data, 0x00, 0xFF)) ||
677 (SentCommand.Command == COMMAND_READ)))
678 {
679 /* Set the state and status variables to indicate the error */
680 DFU_State = dfuERROR;
681 DFU_Status = errWRITE;
682
683 /* Stall command */
684 Endpoint_StallTransaction();
685
686 /* Don't process the command */
687 return;
688 }
689 }
690
691 /* Dispatch the required command processing routine based on the command type */
692 switch (SentCommand.Command)
693 {
694 case COMMAND_PROG_START:
695 ProcessMemProgCommand();
696 break;
697 case COMMAND_DISP_DATA:
698 ProcessMemReadCommand();
699 break;
700 case COMMAND_WRITE:
701 ProcessWriteCommand();
702 break;
703 case COMMAND_READ:
704 ProcessReadCommand();
705 break;
706 case COMMAND_CHANGE_BASE_ADDR:
707 if (IS_TWOBYTE_COMMAND(SentCommand.Data, 0x03, 0x00)) // Set 64KB flash page command
708 Flash64KBPage = SentCommand.Data[2];
709
710 break;
711 }
712 }
713
714 /** Routine to concatenate the given pair of 16-bit memory start and end addresses from the host, and store them
715 * in the StartAddr and EndAddr global variables.
716 */
717 static void LoadStartEndAddresses(void)
718 {
719 union
720 {
721 uint8_t Bytes[2];
722 uint16_t Word;
723 } Address[2] = {{.Bytes = {SentCommand.Data[2], SentCommand.Data[1]}},
724 {.Bytes = {SentCommand.Data[4], SentCommand.Data[3]}}};
725
726 /* Load in the start and ending read addresses from the sent data packet */
727 StartAddr = Address[0].Word;
728 EndAddr = Address[1].Word;
729 }
730
731 /** Handler for a Memory Program command issued by the host. This routine handles the preparations needed
732 * to write subsequent data from the host into the specified memory.
733 */
734 static void ProcessMemProgCommand(void)
735 {
736 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00) || // Write FLASH command
737 IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Write EEPROM command
738 {
739 /* Load in the start and ending read addresses */
740 LoadStartEndAddresses();
741
742 /* If FLASH is being written to, we need to pre-erase the first page to write to */
743 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00))
744 {
745 union
746 {
747 uint16_t Words[2];
748 uint32_t Long;
749 } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
750
751 /* Erase the current page's temp buffer */
752 BootloaderAPI_ErasePage(CurrFlashAddress.Long);
753 }
754
755 /* Set the state so that the next DNLOAD requests reads in the firmware */
756 DFU_State = dfuDNLOAD_IDLE;
757 }
758 }
759
760 /** Handler for a Memory Read command issued by the host. This routine handles the preparations needed
761 * to read subsequent data from the specified memory out to the host, as well as implementing the memory
762 * blank check command.
763 */
764 static void ProcessMemReadCommand(void)
765 {
766 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00) || // Read FLASH command
767 IS_ONEBYTE_COMMAND(SentCommand.Data, 0x02)) // Read EEPROM command
768 {
769 /* Load in the start and ending read addresses */
770 LoadStartEndAddresses();
771
772 /* Set the state so that the next UPLOAD requests read out the firmware */
773 DFU_State = dfuUPLOAD_IDLE;
774 }
775 else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Blank check FLASH command
776 {
777 uint32_t CurrFlashAddress = 0;
778
779 while (CurrFlashAddress < (uint32_t)BOOT_START_ADDR)
780 {
781 /* Check if the current byte is not blank */
782 #if (FLASHEND > 0xFFFF)
783 if (pgm_read_byte_far(CurrFlashAddress) != 0xFF)
784 #else
785 if (pgm_read_byte(CurrFlashAddress) != 0xFF)
786 #endif
787 {
788 /* Save the location of the first non-blank byte for response back to the host */
789 Flash64KBPage = (CurrFlashAddress >> 16);
790 StartAddr = CurrFlashAddress;
791
792 /* Set state and status variables to the appropriate error values */
793 DFU_State = dfuERROR;
794 DFU_Status = errCHECK_ERASED;
795
796 break;
797 }
798
799 CurrFlashAddress++;
800 }
801 }
802 }
803
804 /** Handler for a Data Write command issued by the host. This routine handles non-programming commands such as
805 * bootloader exit (both via software jumps and hardware watchdog resets) and flash memory erasure.
806 */
807 static void ProcessWriteCommand(void)
808 {
809 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x03)) // Start application
810 {
811 /* Indicate that the bootloader is terminating */
812 WaitForExit = true;
813
814 /* Check if data supplied for the Start Program command - no data executes the program */
815 if (SentCommand.DataSize)
816 {
817 if (SentCommand.Data[1] == 0x01) // Start via jump
818 {
819 union
820 {
821 uint8_t Bytes[2];
822 AppPtr_t FuncPtr;
823 } Address = {.Bytes = {SentCommand.Data[4], SentCommand.Data[3]}};
824
825 /* Load in the jump address into the application start address pointer */
826 AppStartPtr = Address.FuncPtr;
827 }
828 }
829 else
830 {
831 if (SentCommand.Data[1] == 0x00) // Start via watchdog
832 {
833 /* Unlock the forced application start mode of the bootloader if it is restarted */
834 MagicBootKey = MAGIC_BOOT_KEY;
835
836 /* Start the watchdog to reset the AVR once the communications are finalized */
837 wdt_enable(WDTO_250MS);
838 }
839 else // Start via jump
840 {
841 /* Set the flag to terminate the bootloader at next opportunity if a valid application has been loaded */
842 if (pgm_read_word_near(0) != 0xFFFF)
843 RunBootloader = false;
844 }
845 }
846 }
847 else if (IS_TWOBYTE_COMMAND(SentCommand.Data, 0x00, 0xFF)) // Erase flash
848 {
849 /* Clear the application section of flash */
850 for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < (uint32_t)BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE)
851 BootloaderAPI_ErasePage(CurrFlashAddress);
852
853 /* Memory has been erased, reset the security bit so that programming/reading is allowed */
854 IsSecure = false;
855 }
856 }
857
858 /** Handler for a Data Read command issued by the host. This routine handles bootloader information retrieval
859 * commands such as device signature and bootloader version retrieval.
860 */
861 static void ProcessReadCommand(void)
862 {
863 const uint8_t BootloaderInfo[3] = {BOOTLOADER_VERSION, BOOTLOADER_ID_BYTE1, BOOTLOADER_ID_BYTE2};
864 const uint8_t SignatureInfo[4] = {0x58, AVR_SIGNATURE_1, AVR_SIGNATURE_2, AVR_SIGNATURE_3};
865
866 uint8_t DataIndexToRead = SentCommand.Data[1];
867 bool ReadAddressInvalid = false;
868
869 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Read bootloader info
870 {
871 if (DataIndexToRead < 3)
872 ResponseByte = BootloaderInfo[DataIndexToRead];
873 else
874 ReadAddressInvalid = true;
875 }
876 else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Read signature byte
877 {
878 switch (DataIndexToRead)
879 {
880 case 0x30:
881 ResponseByte = SignatureInfo[0];
882 break;
883 case 0x31:
884 ResponseByte = SignatureInfo[1];
885 break;
886 case 0x60:
887 ResponseByte = SignatureInfo[2];
888 break;
889 case 0x61:
890 ResponseByte = SignatureInfo[3];
891 break;
892 default:
893 ReadAddressInvalid = true;
894 break;
895 }
896 }
897
898 if (ReadAddressInvalid)
899 {
900 /* Set the state and status variables to indicate the error */
901 DFU_State = dfuERROR;
902 DFU_Status = errADDRESS;
903 }
904 }