Use a board specific bootloader and application start
[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 /*if bit_is_clear(PINB,PB5) // PB5 is Digital 9 on Arduino Pro Micro
229 {
230 loop_until_bit_is_set(PINB,PB5);
231
232 while ((RunBootloader || WaitForExit) && bit_is_set(PINB,PB5))
233 USB_USBTask();
234
235 loop_until_bit_is_clear(PINB,PB5);
236 }*/
237
238 stayinbootloader = false;
239
240 uint16_t i = 0;
241 while (RunBootloader || WaitForExit)
242 {
243 USB_USBTask();
244
245 if (!stayinbootloader)
246 {
247 _delay_ms(1);
248 if (i++ > 5000)
249 {
250 break;
251 }
252 }
253 else
254 {
255 i = 0;
256 }
257 }
258
259 /* Wait a short time to end all USB transactions and then disconnect */
260 _delay_us(1000);
261
262 /* Reset configured hardware back to their original states for the user application */
263 ResetHardware();
264
265 /* Start the user application */
266 AppStartPtr();
267 }
268
269 /** Configures all hardware required for the bootloader. */
270 static void SetupHardware(void)
271 {
272 /* Disable watchdog if enabled by bootloader/fuses */
273 MCUSR &= ~(1 << WDRF);
274 wdt_disable();
275
276 /* Disable clock division */
277 clock_prescale_set(clock_div_1);
278
279 /* Relocate the interrupt vector table to the bootloader section */
280 MCUCR = (1 << IVCE);
281 MCUCR = (1 << IVSEL);
282
283 /* Initialize the USB and other board hardware drivers */
284 USB_Init();
285 LEDs_Init();
286
287 /* Bootloader active LED toggle timer initialization */
288 TIMSK1 = (1 << TOIE1);
289 TCCR1B = ((1 << CS11) | (1 << CS10));
290 }
291
292 /** Resets all configured hardware required for the bootloader back to their original states. */
293 static void ResetHardware(void)
294 {
295 /* Shut down the USB and other board hardware drivers */
296 USB_Disable();
297 LEDs_Disable();
298
299 /* Disable Bootloader active LED toggle timer */
300 TIMSK1 = 0;
301 TCCR1B = 0;
302
303 /* Relocate the interrupt vector table back to the application section */
304 MCUCR = (1 << IVCE);
305 MCUCR = 0;
306 }
307
308 /** ISR to periodically toggle the LEDs on the board to indicate that the bootloader is active. */
309 ISR(TIMER1_OVF_vect, ISR_BLOCK)
310 {
311 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
312 }
313
314 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
315 * the device from the USB host before passing along unhandled control requests to the library for processing
316 * internally.
317 */
318 void EVENT_USB_Device_ControlRequest(void)
319 {
320 /* Ignore any requests that aren't directed to the DFU interface */
321 if ((USB_ControlRequest.bmRequestType & (CONTROL_REQTYPE_TYPE | CONTROL_REQTYPE_RECIPIENT)) !=
322 (REQTYPE_CLASS | REQREC_INTERFACE))
323 {
324 return;
325 }
326
327 stayinbootloader = true;
328
329 /* Activity - toggle indicator LEDs */
330 LEDs_ToggleLEDs(LEDS_LED1 | LEDS_LED2);
331
332 /* Get the size of the command and data from the wLength value */
333 SentCommand.DataSize = USB_ControlRequest.wLength;
334
335 switch (USB_ControlRequest.bRequest)
336 {
337 case DFU_REQ_DNLOAD:
338 Endpoint_ClearSETUP();
339
340 /* Check if bootloader is waiting to terminate */
341 if (WaitForExit)
342 {
343 /* Bootloader is terminating - process last received command */
344 ProcessBootloaderCommand();
345
346 /* Indicate that the last command has now been processed - free to exit bootloader */
347 WaitForExit = false;
348 }
349
350 /* If the request has a data stage, load it into the command struct */
351 if (SentCommand.DataSize)
352 {
353 while (!(Endpoint_IsOUTReceived()))
354 {
355 if (USB_DeviceState == DEVICE_STATE_Unattached)
356 return;
357 }
358
359 /* First byte of the data stage is the DNLOAD request's command */
360 SentCommand.Command = Endpoint_Read_8();
361
362 /* One byte of the data stage is the command, so subtract it from the total data bytes */
363 SentCommand.DataSize--;
364
365 /* Load in the rest of the data stage as command parameters */
366 for (uint8_t DataByte = 0; (DataByte < sizeof(SentCommand.Data)) &&
367 Endpoint_BytesInEndpoint(); DataByte++)
368 {
369 SentCommand.Data[DataByte] = Endpoint_Read_8();
370 SentCommand.DataSize--;
371 }
372
373 /* Process the command */
374 ProcessBootloaderCommand();
375 }
376
377 /* Check if currently downloading firmware */
378 if (DFU_State == dfuDNLOAD_IDLE)
379 {
380 if (!(SentCommand.DataSize))
381 {
382 DFU_State = dfuIDLE;
383 }
384 else
385 {
386 /* Throw away the filler bytes before the start of the firmware */
387 DiscardFillerBytes(DFU_FILLER_BYTES_SIZE);
388
389 /* Throw away the packet alignment filler bytes before the start of the firmware */
390 DiscardFillerBytes(StartAddr % FIXED_CONTROL_ENDPOINT_SIZE);
391
392 /* Calculate the number of bytes remaining to be written */
393 uint16_t BytesRemaining = ((EndAddr - StartAddr) + 1);
394
395 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Write flash
396 {
397 /* Calculate the number of words to be written from the number of bytes to be written */
398 uint16_t WordsRemaining = (BytesRemaining >> 1);
399
400 union
401 {
402 uint16_t Words[2];
403 uint32_t Long;
404 } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
405
406 uint32_t CurrFlashPageStartAddress = CurrFlashAddress.Long;
407 uint8_t WordsInFlashPage = 0;
408
409 while (WordsRemaining--)
410 {
411 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
412 if (!(Endpoint_BytesInEndpoint()))
413 {
414 Endpoint_ClearOUT();
415
416 while (!(Endpoint_IsOUTReceived()))
417 {
418 if (USB_DeviceState == DEVICE_STATE_Unattached)
419 return;
420 }
421 }
422
423 /* Write the next word into the current flash page */
424 BootloaderAPI_FillWord(CurrFlashAddress.Long, Endpoint_Read_16_LE());
425
426 /* Adjust counters */
427 WordsInFlashPage += 1;
428 CurrFlashAddress.Long += 2;
429
430 /* See if an entire page has been written to the flash page buffer */
431 if ((WordsInFlashPage == (SPM_PAGESIZE >> 1)) || !(WordsRemaining))
432 {
433 /* Commit the flash page to memory */
434 BootloaderAPI_WritePage(CurrFlashPageStartAddress);
435
436 /* Check if programming incomplete */
437 if (WordsRemaining)
438 {
439 CurrFlashPageStartAddress = CurrFlashAddress.Long;
440 WordsInFlashPage = 0;
441
442 /* Erase next page's temp buffer */
443 BootloaderAPI_ErasePage(CurrFlashAddress.Long);
444 }
445 }
446 }
447
448 /* Once programming complete, start address equals the end address */
449 StartAddr = EndAddr;
450 }
451 else // Write EEPROM
452 {
453 while (BytesRemaining--)
454 {
455 /* Check if endpoint is empty - if so clear it and wait until ready for next packet */
456 if (!(Endpoint_BytesInEndpoint()))
457 {
458 Endpoint_ClearOUT();
459
460 while (!(Endpoint_IsOUTReceived()))
461 {
462 if (USB_DeviceState == DEVICE_STATE_Unattached)
463 return;
464 }
465 }
466
467 /* Read the byte from the USB interface and write to to the EEPROM */
468 eeprom_update_byte((uint8_t*)StartAddr, Endpoint_Read_8());
469
470 /* Adjust counters */
471 StartAddr++;
472 }
473 }
474
475 /* Throw away the currently unused DFU file suffix */
476 DiscardFillerBytes(DFU_FILE_SUFFIX_SIZE);
477 }
478 }
479
480 Endpoint_ClearOUT();
481
482 Endpoint_ClearStatusStage();
483
484 break;
485 case DFU_REQ_UPLOAD:
486 Endpoint_ClearSETUP();
487
488 while (!(Endpoint_IsINReady()))
489 {
490 if (USB_DeviceState == DEVICE_STATE_Unattached)
491 return;
492 }
493
494 if (DFU_State != dfuUPLOAD_IDLE)
495 {
496 if ((DFU_State == dfuERROR) && IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Blank Check
497 {
498 /* Blank checking is performed in the DFU_DNLOAD request - if we get here we've told the host
499 that the memory isn't blank, and the host is requesting the first non-blank address */
500 Endpoint_Write_16_LE(StartAddr);
501 }
502 else
503 {
504 /* Idle state upload - send response to last issued command */
505 Endpoint_Write_8(ResponseByte);
506 }
507 }
508 else
509 {
510 /* Determine the number of bytes remaining in the current block */
511 uint16_t BytesRemaining = ((EndAddr - StartAddr) + 1);
512
513 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Read FLASH
514 {
515 /* Calculate the number of words to be written from the number of bytes to be written */
516 uint16_t WordsRemaining = (BytesRemaining >> 1);
517
518 union
519 {
520 uint16_t Words[2];
521 uint32_t Long;
522 } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
523
524 while (WordsRemaining--)
525 {
526 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
527 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE)
528 {
529 Endpoint_ClearIN();
530
531 while (!(Endpoint_IsINReady()))
532 {
533 if (USB_DeviceState == DEVICE_STATE_Unattached)
534 return;
535 }
536 }
537
538 /* Read the flash word and send it via USB to the host */
539 #if (FLASHEND > 0xFFFF)
540 Endpoint_Write_16_LE(pgm_read_word_far(CurrFlashAddress.Long));
541 #else
542 Endpoint_Write_16_LE(pgm_read_word(CurrFlashAddress.Long));
543 #endif
544
545 /* Adjust counters */
546 CurrFlashAddress.Long += 2;
547 }
548
549 /* Once reading is complete, start address equals the end address */
550 StartAddr = EndAddr;
551 }
552 else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x02)) // Read EEPROM
553 {
554 while (BytesRemaining--)
555 {
556 /* Check if endpoint is full - if so clear it and wait until ready for next packet */
557 if (Endpoint_BytesInEndpoint() == FIXED_CONTROL_ENDPOINT_SIZE)
558 {
559 Endpoint_ClearIN();
560
561 while (!(Endpoint_IsINReady()))
562 {
563 if (USB_DeviceState == DEVICE_STATE_Unattached)
564 return;
565 }
566 }
567
568 /* Read the EEPROM byte and send it via USB to the host */
569 Endpoint_Write_8(eeprom_read_byte((uint8_t*)StartAddr));
570
571 /* Adjust counters */
572 StartAddr++;
573 }
574 }
575
576 /* Return to idle state */
577 DFU_State = dfuIDLE;
578 }
579
580 Endpoint_ClearIN();
581
582 Endpoint_ClearStatusStage();
583 break;
584 case DFU_REQ_GETSTATUS:
585 Endpoint_ClearSETUP();
586
587 while (!(Endpoint_IsINReady()))
588 {
589 if (USB_DeviceState == DEVICE_STATE_Unattached)
590 return;
591 }
592
593 /* Write 8-bit status value */
594 Endpoint_Write_8(DFU_Status);
595
596 /* Write 24-bit poll timeout value */
597 Endpoint_Write_8(0);
598 Endpoint_Write_16_LE(0);
599
600 /* Write 8-bit state value */
601 Endpoint_Write_8(DFU_State);
602
603 /* Write 8-bit state string ID number */
604 Endpoint_Write_8(0);
605
606 Endpoint_ClearIN();
607
608 Endpoint_ClearStatusStage();
609 break;
610 case DFU_REQ_CLRSTATUS:
611 Endpoint_ClearSETUP();
612
613 /* Reset the status value variable to the default OK status */
614 DFU_Status = OK;
615
616 Endpoint_ClearStatusStage();
617 break;
618 case DFU_REQ_GETSTATE:
619 Endpoint_ClearSETUP();
620
621 while (!(Endpoint_IsINReady()))
622 {
623 if (USB_DeviceState == DEVICE_STATE_Unattached)
624 return;
625 }
626
627 /* Write the current device state to the endpoint */
628 Endpoint_Write_8(DFU_State);
629
630 Endpoint_ClearIN();
631
632 Endpoint_ClearStatusStage();
633 break;
634 case DFU_REQ_ABORT:
635 Endpoint_ClearSETUP();
636
637 /* Reset the current state variable to the default idle state */
638 DFU_State = dfuIDLE;
639
640 Endpoint_ClearStatusStage();
641 break;
642 }
643 }
644
645 /** Routine to discard the specified number of bytes from the control endpoint stream. This is used to
646 * discard unused bytes in the stream from the host, including the memory program block suffix.
647 *
648 * \param[in] NumberOfBytes Number of bytes to discard from the host from the control endpoint
649 */
650 static void DiscardFillerBytes(uint8_t NumberOfBytes)
651 {
652 while (NumberOfBytes--)
653 {
654 if (!(Endpoint_BytesInEndpoint()))
655 {
656 Endpoint_ClearOUT();
657
658 /* Wait until next data packet received */
659 while (!(Endpoint_IsOUTReceived()))
660 {
661 if (USB_DeviceState == DEVICE_STATE_Unattached)
662 return;
663 }
664 }
665 else
666 {
667 Endpoint_Discard_8();
668 }
669 }
670 }
671
672 /** Routine to process an issued command from the host, via a DFU_DNLOAD request wrapper. This routine ensures
673 * that the command is allowed based on the current secure mode flag value, and passes the command off to the
674 * appropriate handler function.
675 */
676 static void ProcessBootloaderCommand(void)
677 {
678 /* Check if device is in secure mode */
679 if (IsSecure)
680 {
681 /* Don't process command unless it is a READ or chip erase command */
682 if (!(((SentCommand.Command == COMMAND_WRITE) &&
683 IS_TWOBYTE_COMMAND(SentCommand.Data, 0x00, 0xFF)) ||
684 (SentCommand.Command == COMMAND_READ)))
685 {
686 /* Set the state and status variables to indicate the error */
687 DFU_State = dfuERROR;
688 DFU_Status = errWRITE;
689
690 /* Stall command */
691 Endpoint_StallTransaction();
692
693 /* Don't process the command */
694 return;
695 }
696 }
697
698 /* Dispatch the required command processing routine based on the command type */
699 switch (SentCommand.Command)
700 {
701 case COMMAND_PROG_START:
702 ProcessMemProgCommand();
703 break;
704 case COMMAND_DISP_DATA:
705 ProcessMemReadCommand();
706 break;
707 case COMMAND_WRITE:
708 ProcessWriteCommand();
709 break;
710 case COMMAND_READ:
711 ProcessReadCommand();
712 break;
713 case COMMAND_CHANGE_BASE_ADDR:
714 if (IS_TWOBYTE_COMMAND(SentCommand.Data, 0x03, 0x00)) // Set 64KB flash page command
715 Flash64KBPage = SentCommand.Data[2];
716
717 break;
718 }
719 }
720
721 /** Routine to concatenate the given pair of 16-bit memory start and end addresses from the host, and store them
722 * in the StartAddr and EndAddr global variables.
723 */
724 static void LoadStartEndAddresses(void)
725 {
726 union
727 {
728 uint8_t Bytes[2];
729 uint16_t Word;
730 } Address[2] = {{.Bytes = {SentCommand.Data[2], SentCommand.Data[1]}},
731 {.Bytes = {SentCommand.Data[4], SentCommand.Data[3]}}};
732
733 /* Load in the start and ending read addresses from the sent data packet */
734 StartAddr = Address[0].Word;
735 EndAddr = Address[1].Word;
736 }
737
738 /** Handler for a Memory Program command issued by the host. This routine handles the preparations needed
739 * to write subsequent data from the host into the specified memory.
740 */
741 static void ProcessMemProgCommand(void)
742 {
743 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00) || // Write FLASH command
744 IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Write EEPROM command
745 {
746 /* Load in the start and ending read addresses */
747 LoadStartEndAddresses();
748
749 /* If FLASH is being written to, we need to pre-erase the first page to write to */
750 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00))
751 {
752 union
753 {
754 uint16_t Words[2];
755 uint32_t Long;
756 } CurrFlashAddress = {.Words = {StartAddr, Flash64KBPage}};
757
758 /* Erase the current page's temp buffer */
759 BootloaderAPI_ErasePage(CurrFlashAddress.Long);
760 }
761
762 /* Set the state so that the next DNLOAD requests reads in the firmware */
763 DFU_State = dfuDNLOAD_IDLE;
764 }
765 }
766
767 /** Handler for a Memory Read command issued by the host. This routine handles the preparations needed
768 * to read subsequent data from the specified memory out to the host, as well as implementing the memory
769 * blank check command.
770 */
771 static void ProcessMemReadCommand(void)
772 {
773 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00) || // Read FLASH command
774 IS_ONEBYTE_COMMAND(SentCommand.Data, 0x02)) // Read EEPROM command
775 {
776 /* Load in the start and ending read addresses */
777 LoadStartEndAddresses();
778
779 /* Set the state so that the next UPLOAD requests read out the firmware */
780 DFU_State = dfuUPLOAD_IDLE;
781 }
782 else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Blank check FLASH command
783 {
784 uint32_t CurrFlashAddress = 0;
785
786 while (CurrFlashAddress < (uint32_t)BOOT_START_ADDR)
787 {
788 /* Check if the current byte is not blank */
789 #if (FLASHEND > 0xFFFF)
790 if (pgm_read_byte_far(CurrFlashAddress) != 0xFF)
791 #else
792 if (pgm_read_byte(CurrFlashAddress) != 0xFF)
793 #endif
794 {
795 /* Save the location of the first non-blank byte for response back to the host */
796 Flash64KBPage = (CurrFlashAddress >> 16);
797 StartAddr = CurrFlashAddress;
798
799 /* Set state and status variables to the appropriate error values */
800 DFU_State = dfuERROR;
801 DFU_Status = errCHECK_ERASED;
802
803 break;
804 }
805
806 CurrFlashAddress++;
807 }
808 }
809 }
810
811 /** Handler for a Data Write command issued by the host. This routine handles non-programming commands such as
812 * bootloader exit (both via software jumps and hardware watchdog resets) and flash memory erasure.
813 */
814 static void ProcessWriteCommand(void)
815 {
816 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x03)) // Start application
817 {
818 /* Indicate that the bootloader is terminating */
819 WaitForExit = true;
820
821 /* Check if data supplied for the Start Program command - no data executes the program */
822 if (SentCommand.DataSize)
823 {
824 if (SentCommand.Data[1] == 0x01) // Start via jump
825 {
826 union
827 {
828 uint8_t Bytes[2];
829 AppPtr_t FuncPtr;
830 } Address = {.Bytes = {SentCommand.Data[4], SentCommand.Data[3]}};
831
832 /* Load in the jump address into the application start address pointer */
833 AppStartPtr = Address.FuncPtr;
834 }
835 }
836 else
837 {
838 if (SentCommand.Data[1] == 0x00) // Start via watchdog
839 {
840 /* Unlock the forced application start mode of the bootloader if it is restarted */
841 MagicBootKey = MAGIC_BOOT_KEY;
842
843 /* Start the watchdog to reset the AVR once the communications are finalized */
844 wdt_enable(WDTO_250MS);
845 }
846 else // Start via jump
847 {
848 /* Set the flag to terminate the bootloader at next opportunity if a valid application has been loaded */
849 if (pgm_read_word_near(0) == 0xFFFF)
850 RunBootloader = false;
851 }
852 }
853 }
854 else if (IS_TWOBYTE_COMMAND(SentCommand.Data, 0x00, 0xFF)) // Erase flash
855 {
856 /* Clear the application section of flash */
857 for (uint32_t CurrFlashAddress = 0; CurrFlashAddress < (uint32_t)BOOT_START_ADDR; CurrFlashAddress += SPM_PAGESIZE)
858 BootloaderAPI_ErasePage(CurrFlashAddress);
859
860 /* Memory has been erased, reset the security bit so that programming/reading is allowed */
861 IsSecure = false;
862 }
863 }
864
865 /** Handler for a Data Read command issued by the host. This routine handles bootloader information retrieval
866 * commands such as device signature and bootloader version retrieval.
867 */
868 static void ProcessReadCommand(void)
869 {
870 const uint8_t BootloaderInfo[3] = {BOOTLOADER_VERSION, BOOTLOADER_ID_BYTE1, BOOTLOADER_ID_BYTE2};
871 const uint8_t SignatureInfo[4] = {0x58, AVR_SIGNATURE_1, AVR_SIGNATURE_2, AVR_SIGNATURE_3};
872
873 uint8_t DataIndexToRead = SentCommand.Data[1];
874 bool ReadAddressInvalid = false;
875
876 if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x00)) // Read bootloader info
877 {
878 if (DataIndexToRead < 3)
879 ResponseByte = BootloaderInfo[DataIndexToRead];
880 else
881 ReadAddressInvalid = true;
882 }
883 else if (IS_ONEBYTE_COMMAND(SentCommand.Data, 0x01)) // Read signature byte
884 {
885 switch (DataIndexToRead)
886 {
887 case 0x30:
888 ResponseByte = SignatureInfo[0];
889 break;
890 case 0x31:
891 ResponseByte = SignatureInfo[1];
892 break;
893 case 0x60:
894 ResponseByte = SignatureInfo[2];
895 break;
896 case 0x61:
897 ResponseByte = SignatureInfo[3];
898 break;
899 default:
900 ReadAddressInvalid = true;
901 break;
902 }
903 }
904
905 if (ReadAddressInvalid)
906 {
907 /* Set the state and status variables to indicate the error */
908 DFU_State = dfuERROR;
909 DFU_Status = errADDRESS;
910 }
911 }