3      Copyright (C) Dean Camera, 2010. 
   5   dean [at] fourwalledcubicle [dot] com 
   6       www.fourwalledcubicle.com 
  10   Copyright 2010  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  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. 
  21   The author disclaim 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 
  33  *  Main source file for the CDC class bootloader. This file contains the complete bootloader logic. 
  36 #define  INCLUDE_FROM_BOOTLOADERCDC_C 
  37 #include "BootloaderCDC.h" 
  39 /** Line coding options for the virtual serial port. Although the virtual serial port data is never 
  40  *  sent through a physical serial port, the line encoding data must still be read and preserved from 
  41  *  the host, or the host will detect a problem and fail to open the port. This structure contains the 
  42  *  current encoding options, including baud rate, character format, parity mode and total number of  
  43  *  bits in each data chunk. 
  45 CDC_Line_Coding_t LineCoding 
= { .BaudRateBPS 
= 9600, 
  46                                  .CharFormat  
= OneStopBit
, 
  47                                  .ParityType  
= Parity_None
, 
  50 /** Current address counter. This stores the current address of the FLASH or EEPROM as set by the host, 
  51  *  and is used when reading or writing to the AVRs memory (either FLASH or EEPROM depending on the issued 
  56 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run 
  57  *  via a soft reset. When cleared, the bootloader will abort, the USB interface will shut down and the application 
  58  *  jumped to via an indirect jump to location 0x0000. 
  60 bool RunBootloader 
= true; 
  63 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously  
  64  *  runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start 
  65  *  the loaded application code. 
  69         /* Setup hardware required for the bootloader */ 
  78         /* Reset all configured hardware to their default states for the user app */ 
  81         /* Start the user application */ 
  82         AppPtr_t AppStartPtr 
= (AppPtr_t
)0x0000; 
  86 /** Configures all hardware required for the bootloader. */ 
  87 void SetupHardware(void) 
  89         /* Disable watchdog if enabled by bootloader/fuses */ 
  90         MCUSR 
&= ~(1 << WDRF
); 
  93         /* Disable clock division */ 
  94         clock_prescale_set(clock_div_1
); 
  96         /* Relocate the interrupt vector table to the bootloader section */ 
 100         /* Initialize USB Subsystem */ 
 104 /** Resets all configured hardware required for the bootloader back to their original states. */ 
 105 void ResetHardware(void) 
 107         /* Shut down the USB subsystem */ 
 110         /* Relocate the interrupt vector table back to the application section */ 
 114         /* Re-enable RWW section */ 
 118 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready 
 119  *  to relay data to and from the attached USB host. 
 121 void EVENT_USB_Device_ConfigurationChanged(void) 
 123         /* Setup CDC Notification, Rx and Tx Endpoints */ 
 124         Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM
, EP_TYPE_INTERRUPT
, 
 125                                        ENDPOINT_DIR_IN
, CDC_NOTIFICATION_EPSIZE
, 
 126                                    ENDPOINT_BANK_SINGLE
); 
 128         Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
, 
 129                                        ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
, 
 130                                    ENDPOINT_BANK_SINGLE
); 
 132         Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
, 
 133                                        ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
, 
 134                                    ENDPOINT_BANK_SINGLE
); 
 137 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific 
 138  *  control requests that are not handled internally by the USB library, so that they can be handled appropriately 
 139  *  for the application. 
 141 void EVENT_USB_Device_UnhandledControlRequest(void) 
 143         uint8_t* LineCodingData 
= (uint8_t*)&LineCoding
; 
 145         /* Process CDC specific control requests */ 
 146         switch (USB_ControlRequest
.bRequest
) 
 148                 case REQ_GetLineEncoding
: 
 149                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 151                                 Endpoint_ClearSETUP(); 
 153                                 for (uint8_t i 
= 0; i 
< sizeof(LineCoding
); i
++) 
 154                                   Endpoint_Write_Byte(*(LineCodingData
++));      
 158                                 Endpoint_ClearStatusStage(); 
 162                 case REQ_SetLineEncoding
: 
 163                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 165                                 Endpoint_ClearSETUP(); 
 167                                 while (!(Endpoint_IsOUTReceived())) 
 169                                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 173                                 for (uint8_t i 
= 0; i 
< sizeof(LineCoding
); i
++) 
 174                                   *(LineCodingData
++) = Endpoint_Read_Byte(); 
 178                                 Endpoint_ClearStatusStage(); 
 182                 case REQ_SetControlLineState
: 
 183                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 185                                 Endpoint_ClearSETUP(); 
 187                                 Endpoint_ClearStatusStage(); 
 194 /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending 
 195  *  on the AVR910 protocol command issued. 
 197  *  \param[in] Command  Single character AVR910 protocol command indicating what memory operation to perform 
 199 static void ReadWriteMemoryBlock(const uint8_t Command
) 
 204         bool     HighByte 
= false; 
 207         BlockSize  
= (FetchNextCommandByte() << 8); 
 208         BlockSize 
|=  FetchNextCommandByte(); 
 210         MemoryType 
=  FetchNextCommandByte(); 
 212         if ((MemoryType 
!= 'E') && (MemoryType 
!= 'F')) 
 214                 /* Send error byte back to the host */ 
 215                 WriteNextResponseByte('?'); 
 220         /* Check if command is to read memory */ 
 223                 /* Re-enable RWW section */ 
 228                         if (MemoryType 
== 'F') 
 230                                 /* Read the next FLASH byte from the current FLASH page */ 
 231                                 #if (FLASHEND > 0xFFFF) 
 232                                 WriteNextResponseByte(pgm_read_byte_far(CurrAddress 
| HighByte
)); 
 234                                 WriteNextResponseByte(pgm_read_byte(CurrAddress 
| HighByte
));                                    
 237                                 /* If both bytes in current word have been read, increment the address counter */ 
 241                                 HighByte 
= !HighByte
; 
 245                                 /* Read the next EEPROM byte into the endpoint */ 
 246                                 WriteNextResponseByte(eeprom_read_byte((uint8_t*)(uint16_t)(CurrAddress 
>> 1))); 
 248                                 /* Increment the address counter after use */ 
 255                 uint32_t PageStartAddress 
= CurrAddress
; 
 257                 if (MemoryType 
== 'F') 
 259                         boot_page_erase(PageStartAddress
); 
 260                         boot_spm_busy_wait(); 
 265                         if (MemoryType 
== 'F') 
 267                                 /* If both bytes in current word have been written, increment the address counter */ 
 270                                         /* Write the next FLASH word to the current FLASH page */ 
 271                                         boot_page_fill(CurrAddress
, ((FetchNextCommandByte() << 8) | LowByte
)); 
 273                                         /* Increment the address counter after use */ 
 280                                         LowByte 
= FetchNextCommandByte(); 
 287                                 /* Write the next EEPROM byte from the endpoint */ 
 288                                 eeprom_write_byte((uint8_t*)(uint16_t)(CurrAddress 
>> 1), FetchNextCommandByte());                                       
 290                                 /* Increment the address counter after use */ 
 295                 /* If in FLASH programming mode, commit the page after writing */ 
 296                 if (MemoryType 
== 'F') 
 298                         /* Commit the flash page to memory */ 
 299                         boot_page_write(PageStartAddress
); 
 301                         /* Wait until write operation has completed */ 
 302                         boot_spm_busy_wait(); 
 305                 /* Send response byte back to the host */ 
 306                 WriteNextResponseByte('\r');             
 310 /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed 
 311  *  to allow reception of the next data packet from the host. 
 313  *  \return Next received byte from the host in the CDC data OUT endpoint 
 315 static uint8_t FetchNextCommandByte(void) 
 317         /* Select the OUT endpoint so that the next data byte can be read */ 
 318         Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 320         /* If OUT endpoint empty, clear it and wait for the next packet from the host */ 
 321         while (!(Endpoint_IsReadWriteAllowed())) 
 325                 while (!(Endpoint_IsOUTReceived())) 
 327                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 332         /* Fetch the next byte from the OUT endpoint */ 
 333         return Endpoint_Read_Byte(); 
 336 /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the 
 337  *  bank when full ready for the next byte in the packet to the host. 
 339  *  \param[in] Response  Next response byte to send to the host 
 341 static void WriteNextResponseByte(const uint8_t Response
) 
 343         /* Select the IN endpoint so that the next data byte can be written */ 
 344         Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 346         /* If IN endpoint full, clear it and wait until ready for the next packet to the host */ 
 347         if (!(Endpoint_IsReadWriteAllowed())) 
 351                 while (!(Endpoint_IsINReady())) 
 353                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 358         /* Write the next byte to the OUT endpoint */ 
 359         Endpoint_Write_Byte(Response
); 
 362 /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions 
 363  *  and send the appropriate response back to the host. 
 367         /* Select the OUT endpoint */ 
 368         Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 370         /* Check if endpoint has a command in it sent from the host */ 
 371         if (Endpoint_IsOUTReceived()) 
 373                 /* Read in the bootloader command (first byte sent from host) */ 
 374                 uint8_t Command 
= FetchNextCommandByte(); 
 376                 if ((Command 
== 'L') || (Command 
== 'P') || (Command 
== 'T') || (Command 
== 'E')) 
 379                           RunBootloader 
= false; 
 381                           FetchNextCommandByte(); 
 383                         /* Send confirmation byte back to the host */ 
 384                         WriteNextResponseByte('\r');                     
 386                 else if (Command 
== 't') 
 388                         /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */ 
 389                         WriteNextResponseByte(0x44); 
 391                         WriteNextResponseByte(0x00); 
 393                 else if (Command 
== 'a') 
 395                         /* Indicate auto-address increment is supported */ 
 396                         WriteNextResponseByte('Y'); 
 398                 else if (Command 
== 'A') 
 400                         /* Set the current address to that given by the host */ 
 401                         CurrAddress   
= (FetchNextCommandByte() << 9); 
 402                         CurrAddress  
|= (FetchNextCommandByte() << 1); 
 404                         /* Send confirmation byte back to the host */ 
 405                         WriteNextResponseByte('\r'); 
 407                 else if (Command 
== 'p') 
 409                         /* Indicate serial programmer back to the host */ 
 410                         WriteNextResponseByte('S');               
 412                 else if (Command 
== 'S') 
 414                         /* Write the 7-byte software identifier to the endpoint */ 
 415                         for (uint8_t CurrByte 
= 0; CurrByte 
< 7; CurrByte
++) 
 416                           WriteNextResponseByte(SOFTWARE_IDENTIFIER
[CurrByte
]);          
 418                 else if (Command 
== 'V') 
 420                         WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR
); 
 421                         WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR
); 
 423                 else if (Command 
== 's') 
 425                         WriteNextResponseByte(AVR_SIGNATURE_3
);          
 426                         WriteNextResponseByte(AVR_SIGNATURE_2
); 
 427                         WriteNextResponseByte(AVR_SIGNATURE_1
); 
 429                 else if (Command 
== 'b') 
 431                         WriteNextResponseByte('Y'); 
 433                         /* Send block size to the host */ 
 434                         WriteNextResponseByte(SPM_PAGESIZE 
>> 8); 
 435                         WriteNextResponseByte(SPM_PAGESIZE 
& 0xFF);              
 437                 else if (Command 
== 'e') 
 439                         /* Clear the application section of flash */ 
 440                         for (uint32_t CurrFlashAddress 
= 0; CurrFlashAddress 
< BOOT_START_ADDR
; CurrFlashAddress
++) 
 442                                 boot_page_erase(CurrFlashAddress
); 
 443                                 boot_spm_busy_wait(); 
 444                                 boot_page_write(CurrFlashAddress
); 
 445                                 boot_spm_busy_wait(); 
 447                                 CurrFlashAddress 
+= SPM_PAGESIZE
; 
 450                         /* Send confirmation byte back to the host */ 
 451                         WriteNextResponseByte('\r');             
 453                 else if (Command 
== 'l') 
 455                         /* Set the lock bits to those given by the host */ 
 456                         boot_lock_bits_set(FetchNextCommandByte()); 
 458                         /* Send confirmation byte back to the host */ 
 459                         WriteNextResponseByte('\r'); 
 461                 else if (Command 
== 'r') 
 463                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS
));           
 465                 else if (Command 
== 'F') 
 467                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS
)); 
 469                 else if (Command 
== 'N') 
 471                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS
));              
 473                 else if (Command 
== 'Q') 
 475                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS
));          
 477                 else if (Command 
== 'C') 
 479                         /* Write the high byte to the current flash page */ 
 480                         boot_page_fill(CurrAddress
, FetchNextCommandByte()); 
 482                         /* Send confirmation byte back to the host */ 
 483                         WriteNextResponseByte('\r');             
 485                 else if (Command 
== 'c') 
 487                         /* Write the low byte to the current flash page */ 
 488                         boot_page_fill(CurrAddress 
| 1, FetchNextCommandByte()); 
 490                         /* Increment the address */ 
 493                         /* Send confirmation byte back to the host */ 
 494                         WriteNextResponseByte('\r');             
 496                 else if (Command 
== 'm') 
 498                         /* Commit the flash page to memory */ 
 499                         boot_page_write(CurrAddress
); 
 501                         /* Wait until write operation has completed */ 
 502                         boot_spm_busy_wait(); 
 504                         /* Send confirmation byte back to the host */ 
 505                         WriteNextResponseByte('\r');             
 507                 else if ((Command 
== 'B') || (Command 
== 'g')) 
 509                         /* Delegate the block write/read to a separate function for clarity */ 
 510                         ReadWriteMemoryBlock(Command
); 
 512                 else if (Command 
== 'R') 
 514                         #if (FLASHEND > 0xFFFF) 
 515                         uint16_t ProgramWord 
= pgm_read_word_far(CurrAddress
); 
 517                         uint16_t ProgramWord 
= pgm_read_word(CurrAddress
);                       
 520                         WriteNextResponseByte(ProgramWord 
>> 8); 
 521                         WriteNextResponseByte(ProgramWord 
& 0xFF); 
 523                 else if (Command 
== 'D') 
 525                         /* Read the byte from the endpoint and write it to the EEPROM */ 
 526                         eeprom_write_byte((uint8_t*)((uint16_t)(CurrAddress 
>> 1)), FetchNextCommandByte()); 
 528                         /* Increment the address after use */                    
 531                         /* Send confirmation byte back to the host */ 
 532                         WriteNextResponseByte('\r');             
 534                 else if (Command 
== 'd') 
 536                         /* Read the EEPROM byte and write it to the endpoint */ 
 537                         WriteNextResponseByte(eeprom_read_byte((uint8_t*)((uint16_t)(CurrAddress 
>> 1)))); 
 539                         /* Increment the address after use */ 
 542                 else if (Command 
== 27) 
 544                         /* Escape is sync, ignore */ 
 548                         /* Unknown command, return fail code */ 
 549                         WriteNextResponseByte('?'); 
 552                 /* Select the IN endpoint */ 
 553                 Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 555                 /* Remember if the endpoint is completely full before clearing it */ 
 556                 bool IsEndpointFull 
= !(Endpoint_IsReadWriteAllowed()); 
 558                 /* Send the endpoint data to the host */ 
 561                 /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */ 
 564                         while (!(Endpoint_IsINReady())) 
 566                                 if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 573                 /* Wait until the data has been sent to the host */ 
 574                 while (!(Endpoint_IsINReady())) 
 576                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 580                 /* Select the OUT endpoint */ 
 581                 Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 583                 /* Acknowledge the command from the host */