Add script reading bootloader flags
[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 * Use volatile to prevent compiler to do optimization, because we change this variable from interrupt context.
49 */
50 static volatile bool RunBootloader = true;
51
52 /** Flag to indicate if the bootloader is waiting to exit. When the host requests the bootloader to exit and
53 * jump to the application address it specifies, it sends two sequential commands which must be properly
54 * acknowledged. Upon reception of the first the RunBootloader flag is cleared and the WaitForExit flag is set,
55 * causing the bootloader to wait for the final exit command before shutting down.
56 */
57 static bool WaitForExit = false;
58
59 /** Minimum time in seconds stay forced into bootloader mode before application will be started. This especially
60 * helpful if the application does not support any update or reflashing or jumping back into bootloader. It prevents
61 * to brick the device if now ISP programmer is available.
62 */
63 #ifndef BL_TIME
64 #define BL_TIME 5 /* seconds */
65 #endif
66
67 /** Minimum time ticks stay in bootloader before application is started or negative value to prevent leaving
68 * bootloader. Timer 1 is a 16 bit timer, which overflows after 65536 cycles if it is load with zero. The
69 * timer 1 prescaler is programmed to divide by 64 and the prescaler engine uses a clock_div_1 divisor, means
70 * no divisor of the CPU clock frequency F_CPU.
71 */
72 static int8_t ForceBootloaderTime = ((BL_TIME) > 0) ? (F_CPU / 64 * (BL_TIME) / 65536 + 1) : -1;
73
74 /** Current DFU state machine state, one of the values in the DFU_State_t enum. */
75 static uint8_t DFU_State = dfuIDLE;
76
77 /** Status code of the last executed DFU command. This is set to one of the values in the DFU_Status_t enum after
78 * each operation, and returned to the host when a Get Status DFU request is issued.
79 */
80 static uint8_t DFU_Status = OK;
81
82 /** Data containing the DFU command sent from the host. */
83 static DFU_Command_t SentCommand;
84
85 /** Response to the last issued Read Data DFU command. Unlike other DFU commands, the read command
86 * requires a single byte response from the bootloader containing the read data when the next DFU_UPLOAD command
87 * is issued by the host.
88 */
89 static uint8_t ResponseByte;
90
91 /** Pointer to the start of the user application. By default this is 0x0000 (the reset vector), however the host
92 * may specify an alternate address when issuing the application soft-start command.
93 */
94 static AppPtr_t AppStartPtr = (AppPtr_t)0x0000;
95
96 /** 64-bit flash page number. This is concatenated with the current 16-bit address on USB AVRs containing more than
97 * 64KB of flash memory.
98 */
99 static uint8_t Flash64KBPage = 0;
100
101 /** Memory start address, indicating the current address in the memory being addressed (either FLASH or EEPROM
102 * depending on the issued command from the host).
103 */
104 static uint16_t StartAddr = 0x0000;
105
106 /** Memory end address, indicating the end address to read from/write to in the memory being addressed (either FLASH
107 * of EEPROM depending on the issued command from the host).
108 */
109 static uint16_t EndAddr = 0x0000;
110
111 /** Magic lock for forced application start. If the HWBE fuse is programmed and BOOTRST is unprogrammed, the bootloader
112 * 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
113 * low when the application attempts to start via a watchdog reset, the bootloader will re-start. If set to the value
114 * \ref MAGIC_BOOT_KEY the special init function \ref Application_Jump_Check() will force the application to start.
115 */
116 uint16_t MagicBootKey ATTR_NO_INIT;
117
118
119 /** Special startup routine to check if the bootloader was started via a watchdog reset, and if the magic application
120 * start key has been loaded into \ref MagicBootKey. If the bootloader started via the watchdog and the key is valid,
121 * this will force the user application to start via a software jump.
122 */
123 void Application_Jump_Check(void)
124 {
125 bool JumpToApplication = false;
126
127 #if (BOARD == BOARD_LEONARDO)
128 /* Enable pull-up on the IO13 pin so we can use it to select the mode */
129 PORTC |= (1 << 7);
130 Delay_MS(10);
131
132 /* If IO13 is not jumpered to ground, start the user application instead */
133 JumpToApplication = ((PINC & (1 << 7)) != 0);
134
135 /* Disable pull-up after the check has completed */
136 PORTC &= ~(1 << 7);
137 #elif ((BOARD == BOARD_XPLAIN) || (BOARD == BOARD_XPLAIN_REV1))
138 /* Disable JTAG debugging */
139 JTAG_DISABLE();
140
141 /* Enable pull-up on the JTAG TCK pin so we can use it to select the mode */
142 PORTF |= (1 << 4);
143 Delay_MS(10);
144
145 /* If the TCK pin is not jumpered to ground, start the user application instead */
146 JumpToApplication = ((PINF & (1 << 4)) != 0);
147
148 /* Re-enable JTAG debugging */
149 JTAG_ENABLE();
150 #elif ((BOARD == BOARD_PROMICRO) || (BOARD == BOARD_MICRO))
151 /* Pro-Micro and Arduino Micro board use power-on reset, but no external reset. Both boards have
152 * the hardware bootloader pin HWBE enabled. Unfortunately only the external reset allows together
153 * with an enabled HWBE that the CPU start at the bootloader address independent of the FUSE_BOOTRST.
154 * That means the power-on reset will start just controlled by the FUSE_BOOTRST the bootloader or
155 * direct in the application and cannot be overridden by HWBE signal. Therfore FUSE_BOOTRST shall
156 * be enabled, otherwise the bootloader will not be reached for these boards.
157 * The bootloader checks FUSE_HWBE as *unprogammed* instead of FUSE_BOOTRST as programmed on other
158 * board variants to decide fast application start, without waiting the dedicted bootloader timeout
159 * in case of a USB, watchdog, brown-out or JTAG reset. If the watchdog reset was initiated from
160 * the bootloader marked with the MAGIC_BOOT_KEY this reset flag is reset. All other reset flags
161 * are left untouched to allow the application code checking the reset signals, especially in case
162 * of application fast start.
163 * The bootloader is entered always for external reset and power-on reset. But the bootloader is
164 * anyway exited after that dedicted timeout, if a reset-vector to the application is programmed.
165 * Once a DFU program interacts this the bootloader during this dedicted timeout, the timer stops
166 * and the application needs to be started by DFU bootloader command manually or using a reset.
167 */
168
169 /* Check if the device's forced Bootloader via Hardware Bootenable is unprogrammed */
170 if (BootloaderAPI_ReadFuse(GET_EXTENDED_FUSE_BITS) & ~FUSE_HWBE)
171 {
172 /* If the reset source was not an external or power-on reset jump to the application */
173 if (!(MCUSR & ((1 << EXTRF) || (1 << PORF))))
174 JumpToApplication = true;
175 }
176 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
177 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
178 if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
179 {
180 JumpToApplication = true;
181
182 /* Clear reset source */
183 MCUSR &= ~(1 << WDRF);
184 }
185 #else
186 /* Check if the device's BOOTRST fuse is set */
187 if (!(BootloaderAPI_ReadFuse(GET_HIGH_FUSE_BITS) & ~FUSE_BOOTRST))
188 {
189 /* If the reset source was not an external reset or the key is correct, clear it and jump to the application */
190 if (!(MCUSR & (1 << EXTRF)) || (MagicBootKey == MAGIC_BOOT_KEY))
191 JumpToApplication = true;
192
193 /* Clear reset source */
194 MCUSR &= ~(1 << EXTRF);
195 }
196 else
197 {
198 /* If the reset source was the bootloader and the key is correct, clear it and jump to the application;
199 * this can happen in the HWBE fuse is set, and the HBE pin is low during the watchdog reset */
200 if ((MCUSR & (1 << WDRF)) && (MagicBootKey == MAGIC_BOOT_KEY))
201 JumpToApplication = true;
202
203 /* Clear reset source */
204 MCUSR &= ~(1 << WDRF);
205 }
206 #endif
207
208 /* Clear the boot key in any case */
209 MagicBootKey = 0;
210
211 /* Don't run the user application if the reset vector is blank (no app loaded) */
212 bool ApplicationValid = (pgm_read_word_near(0) != 0xFFFF);
213
214 /* If a request has been made to jump to the user application, honor it */
215 if (JumpToApplication && ApplicationValid)
216 {
217 /* Turn off the watchdog */
218 wdt_disable();
219
220 // cppcheck-suppress constStatement
221 ((void (*)(void))0x0000)();
222 }
223 }
224
225 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously
226 * runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start
227 * the loaded application code.
228 */
229 int main(void)
230 {
231 /* Configure hardware required by the bootloader */
232 SetupHardware();
233
234 /* Turn on first LED on the board to indicate that the bootloader has started */
235 LEDs_SetAllLEDs(LEDS_LED1);
236
237 /* Enable global interrupts so that the USB stack can function */
238 GlobalInterruptEnable();
239
240 /* Run the USB management task while the bootloader is supposed to be running */
241 while (RunBootloader || WaitForExit)
242 USB_USBTask();
243
244 /* Wait a short time to end all USB transactions and then disconnect */
245 _delay_us(1000);
246
247 /* Reset configured hardware back to their original states for the user application */
248 ResetHardware();
249
250 /* Start the user application */
251 AppStartPtr();
252 }
253
254 /** Configures all hardware required for the bootloader. */
255 static void SetupHardware(void)
256 {
257 /* Disable watchdog if enabled by bootloader/fuses */
258 MCUSR &= ~(1 << WDRF);
259 wdt_disable();
260
261 /* Disable clock division */
262 clock_prescale_set(clock_div_1);
263
264 /* Relocate the interrupt vector table to the bootloader section */
265 MCUCR = (1 << IVCE);
266 MCUCR = (1 << IVSEL);
267
268 /* Initialize the USB and other board hardware drivers */
269 USB_Init();
270 LEDs_Init();
271
272 /* Bootloader active LED toggle timer initialization */
273 TIMSK1 = (1 << TOIE1);
274 /* config timer 1 prescaler to F_CPU / clock_div_1 / 64 */
275 TCCR1B = ((1 << CS11) | (1 << CS10));
276 }
277
278 /** Resets all configured hardware required for the bootloader back to their original states. */
279 static void ResetHardware(void)
280 {
281 /* Shut down the USB and other board hardware drivers */
282 USB_Disable();
283 LEDs_Disable();
284
285 /* Disable Bootloader active LED toggle timer */
286 TIMSK1 = 0;
287 TCCR1B = 0;
288
289 /* Relocate the interrupt vector table back to the application section */
290 MCUCR = (1 << IVCE);
291 MCUCR = 0;
292 }
293
294 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
295 ISR(TIMER1_OVF_vect, ISR_BLOCK)
296 {
297 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
298 /* Count number for forced ticks not below zero */
299 if (ForceBootloaderTime > 0)
300 ForceBootloaderTime--;
301 /* check if it is time to leave the bootloader and a valid application exists */
302 if ((ForceBootloaderTime == 0) && (pgm_read_word_near(0) != 0xFFFF))
303 RunBootloader = false;
304 }
305
306 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
307 * the device from the USB host before passing along unhandled control requests to the library for processing
308 * internally.
309 */
310 void EVENT_USB_Device_ControlRequest(void)
311 {
312 /* Ignore any requests that aren't directed to the DFU interface */
313 if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
314 (REQTYPE_CLASS | REQREC_INTERFACE))
315 {
316 return;
317 }
318
319 /* prevent counter to reach zero */
320 ForceBootloaderTime = -1;
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 }