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 /** Current address counter. This stores the current address of the FLASH or EEPROM as set by the host, 
  40  *  and is used when reading or writing to the AVRs memory (either FLASH or EEPROM depending on the issued 
  45 /** Flag to indicate if the bootloader should be running, or should exit and allow the application code to run 
  46  *  via a watchdog reset. When cleared the bootloader will exit, starting the watchdog and entering an infinite 
  47  *  loop until the AVR restarts and the application runs. 
  49 bool RunBootloader 
= true; 
  52 /** Main program entry point. This routine configures the hardware required by the bootloader, then continuously  
  53  *  runs the bootloader processing routine until instructed to soft-exit, or hard-reset via the watchdog to start 
  54  *  the loaded application code. 
  58         /* Setup hardware required for the bootloader */ 
  61         /* Enable global interrupts so that the USB stack can function */ 
  70         /* Disconnect from the host - USB interface will be reset later along with the AVR */ 
  73         /* Enable the watchdog and force a timeout to reset the AVR */ 
  74         wdt_enable(WDTO_250MS
); 
  79 /** Configures all hardware required for the bootloader. */ 
  80 void SetupHardware(void) 
  82         /* Disable watchdog if enabled by bootloader/fuses */ 
  83         MCUSR 
&= ~(1 << WDRF
); 
  86         /* Disable clock division */ 
  87         clock_prescale_set(clock_div_1
); 
  89         /* Relocate the interrupt vector table to the bootloader section */ 
  93         /* Initialize USB Subsystem */ 
  97 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready 
  98  *  to relay data to and from the attached USB host. 
 100 void EVENT_USB_Device_ConfigurationChanged(void) 
 102         /* Setup CDC Notification, Rx and Tx Endpoints */ 
 103         Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM
, EP_TYPE_INTERRUPT
, 
 104                                        ENDPOINT_DIR_IN
, CDC_NOTIFICATION_EPSIZE
, 
 105                                    ENDPOINT_BANK_SINGLE
); 
 107         Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
, 
 108                                        ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
, 
 109                                    ENDPOINT_BANK_SINGLE
); 
 111         Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
, 
 112                                        ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
, 
 113                                    ENDPOINT_BANK_SINGLE
); 
 116 /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending 
 117  *  on the AVR910 protocol command issued. 
 119  *  \param[in] Command  Single character AVR910 protocol command indicating what memory operation to perform 
 121 static void ReadWriteMemoryBlock(const uint8_t Command
) 
 126         bool     HighByte 
= false; 
 129         BlockSize  
= (FetchNextCommandByte() << 8); 
 130         BlockSize 
|=  FetchNextCommandByte(); 
 132         MemoryType 
=  FetchNextCommandByte(); 
 134         if ((MemoryType 
!= 'E') && (MemoryType 
!= 'F')) 
 136                 /* Send error byte back to the host */ 
 137                 WriteNextResponseByte('?'); 
 142         /* Check if command is to read memory */ 
 145                 /* Re-enable RWW section */ 
 150                         if (MemoryType 
== 'F') 
 152                                 /* Read the next FLASH byte from the current FLASH page */ 
 153                                 #if (FLASHEND > 0xFFFF) 
 154                                 WriteNextResponseByte(pgm_read_byte_far(CurrAddress 
| HighByte
)); 
 156                                 WriteNextResponseByte(pgm_read_byte(CurrAddress 
| HighByte
));                                    
 159                                 /* If both bytes in current word have been read, increment the address counter */ 
 163                                 HighByte 
= !HighByte
; 
 167                                 /* Read the next EEPROM byte into the endpoint */ 
 168                                 WriteNextResponseByte(eeprom_read_byte((uint8_t*)(intptr_t)(CurrAddress 
>> 1))); 
 170                                 /* Increment the address counter after use */ 
 177                 uint32_t PageStartAddress 
= CurrAddress
; 
 179                 if (MemoryType 
== 'F') 
 181                         boot_page_erase(PageStartAddress
); 
 182                         boot_spm_busy_wait(); 
 187                         if (MemoryType 
== 'F') 
 189                                 /* If both bytes in current word have been written, increment the address counter */ 
 192                                         /* Write the next FLASH word to the current FLASH page */ 
 193                                         boot_page_fill(CurrAddress
, ((FetchNextCommandByte() << 8) | LowByte
)); 
 195                                         /* Increment the address counter after use */ 
 202                                         LowByte 
= FetchNextCommandByte(); 
 209                                 /* Write the next EEPROM byte from the endpoint */ 
 210                                 eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress 
>> 1)), FetchNextCommandByte());                                     
 212                                 /* Increment the address counter after use */ 
 217                 /* If in FLASH programming mode, commit the page after writing */ 
 218                 if (MemoryType 
== 'F') 
 220                         /* Commit the flash page to memory */ 
 221                         boot_page_write(PageStartAddress
); 
 223                         /* Wait until write operation has completed */ 
 224                         boot_spm_busy_wait(); 
 227                 /* Send response byte back to the host */ 
 228                 WriteNextResponseByte('\r');             
 232 /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed 
 233  *  to allow reception of the next data packet from the host. 
 235  *  \return Next received byte from the host in the CDC data OUT endpoint 
 237 static uint8_t FetchNextCommandByte(void) 
 239         /* Select the OUT endpoint so that the next data byte can be read */ 
 240         Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 242         /* If OUT endpoint empty, clear it and wait for the next packet from the host */ 
 243         while (!(Endpoint_IsReadWriteAllowed())) 
 247                 while (!(Endpoint_IsOUTReceived())) 
 249                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 254         /* Fetch the next byte from the OUT endpoint */ 
 255         return Endpoint_Read_Byte(); 
 258 /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the 
 259  *  bank when full ready for the next byte in the packet to the host. 
 261  *  \param[in] Response  Next response byte to send to the host 
 263 static void WriteNextResponseByte(const uint8_t Response
) 
 265         /* Select the IN endpoint so that the next data byte can be written */ 
 266         Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 268         /* If IN endpoint full, clear it and wait until ready for the next packet to the host */ 
 269         if (!(Endpoint_IsReadWriteAllowed())) 
 273                 while (!(Endpoint_IsINReady())) 
 275                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 280         /* Write the next byte to the OUT endpoint */ 
 281         Endpoint_Write_Byte(Response
); 
 284 /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions 
 285  *  and send the appropriate response back to the host. 
 289         /* Select the OUT endpoint */ 
 290         Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 292         /* Check if endpoint has a command in it sent from the host */ 
 293         if (Endpoint_IsOUTReceived()) 
 295                 /* Read in the bootloader command (first byte sent from host) */ 
 296                 uint8_t Command 
= FetchNextCommandByte(); 
 298                 if ((Command 
== 'L') || (Command 
== 'P') || (Command 
== 'T') || (Command 
== 'E')) 
 301                           RunBootloader 
= false; 
 302                         else if (Command 
== 'T') 
 303                           FetchNextCommandByte(); 
 305                         /* Send confirmation byte back to the host */ 
 306                         WriteNextResponseByte('\r');                     
 308                 else if (Command 
== 't') 
 310                         /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */ 
 311                         WriteNextResponseByte(0x44); 
 312                         WriteNextResponseByte(0x00); 
 314                 else if (Command 
== 'a') 
 316                         /* Indicate auto-address increment is supported */ 
 317                         WriteNextResponseByte('Y'); 
 319                 else if (Command 
== 'A') 
 321                         /* Set the current address to that given by the host */ 
 322                         CurrAddress   
= (FetchNextCommandByte() << 9); 
 323                         CurrAddress  
|= (FetchNextCommandByte() << 1); 
 325                         /* Send confirmation byte back to the host */ 
 326                         WriteNextResponseByte('\r'); 
 328                 else if (Command 
== 'p') 
 330                         /* Indicate serial programmer back to the host */ 
 331                         WriteNextResponseByte('S');               
 333                 else if (Command 
== 'S') 
 335                         /* Write the 7-byte software identifier to the endpoint */ 
 336                         for (uint8_t CurrByte 
= 0; CurrByte 
< 7; CurrByte
++) 
 337                           WriteNextResponseByte(SOFTWARE_IDENTIFIER
[CurrByte
]);          
 339                 else if (Command 
== 'V') 
 341                         WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR
); 
 342                         WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR
); 
 344                 else if (Command 
== 's') 
 346                         WriteNextResponseByte(AVR_SIGNATURE_3
);          
 347                         WriteNextResponseByte(AVR_SIGNATURE_2
); 
 348                         WriteNextResponseByte(AVR_SIGNATURE_1
); 
 350                 else if (Command 
== 'b') 
 352                         WriteNextResponseByte('Y'); 
 354                         /* Send block size to the host */ 
 355                         WriteNextResponseByte(SPM_PAGESIZE 
>> 8); 
 356                         WriteNextResponseByte(SPM_PAGESIZE 
& 0xFF);              
 358                 else if (Command 
== 'e') 
 360                         /* Clear the application section of flash */ 
 361                         for (uint32_t CurrFlashAddress 
= 0; CurrFlashAddress 
< BOOT_START_ADDR
; CurrFlashAddress
++) 
 363                                 boot_page_erase(CurrFlashAddress
); 
 364                                 boot_spm_busy_wait(); 
 365                                 boot_page_write(CurrFlashAddress
); 
 366                                 boot_spm_busy_wait(); 
 368                                 CurrFlashAddress 
+= SPM_PAGESIZE
; 
 371                         /* Send confirmation byte back to the host */ 
 372                         WriteNextResponseByte('\r');             
 374                 else if (Command 
== 'l') 
 376                         /* Set the lock bits to those given by the host */ 
 377                         boot_lock_bits_set(FetchNextCommandByte()); 
 379                         /* Send confirmation byte back to the host */ 
 380                         WriteNextResponseByte('\r'); 
 382                 else if (Command 
== 'r') 
 384                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS
));           
 386                 else if (Command 
== 'F') 
 388                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS
)); 
 390                 else if (Command 
== 'N') 
 392                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS
));              
 394                 else if (Command 
== 'Q') 
 396                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS
));          
 398                 else if (Command 
== 'C') 
 400                         /* Write the high byte to the current flash page */ 
 401                         boot_page_fill(CurrAddress
, FetchNextCommandByte()); 
 403                         /* Send confirmation byte back to the host */ 
 404                         WriteNextResponseByte('\r');             
 406                 else if (Command 
== 'c') 
 408                         /* Write the low byte to the current flash page */ 
 409                         boot_page_fill(CurrAddress 
| 1, FetchNextCommandByte()); 
 411                         /* Increment the address */ 
 414                         /* Send confirmation byte back to the host */ 
 415                         WriteNextResponseByte('\r');             
 417                 else if (Command 
== 'm') 
 419                         /* Commit the flash page to memory */ 
 420                         boot_page_write(CurrAddress
); 
 422                         /* Wait until write operation has completed */ 
 423                         boot_spm_busy_wait(); 
 425                         /* Send confirmation byte back to the host */ 
 426                         WriteNextResponseByte('\r');             
 428                 else if ((Command 
== 'B') || (Command 
== 'g')) 
 430                         /* Delegate the block write/read to a separate function for clarity */ 
 431                         ReadWriteMemoryBlock(Command
); 
 433                 else if (Command 
== 'R') 
 435                         #if (FLASHEND > 0xFFFF) 
 436                         uint16_t ProgramWord 
= pgm_read_word_far(CurrAddress
); 
 438                         uint16_t ProgramWord 
= pgm_read_word(CurrAddress
);                       
 441                         WriteNextResponseByte(ProgramWord 
>> 8); 
 442                         WriteNextResponseByte(ProgramWord 
& 0xFF); 
 444                 else if (Command 
== 'D') 
 446                         /* Read the byte from the endpoint and write it to the EEPROM */ 
 447                         eeprom_write_byte((uint8_t*)((intptr_t)(CurrAddress 
>> 1)), FetchNextCommandByte()); 
 449                         /* Increment the address after use */                    
 452                         /* Send confirmation byte back to the host */ 
 453                         WriteNextResponseByte('\r');             
 455                 else if (Command 
== 'd') 
 457                         /* Read the EEPROM byte and write it to the endpoint */ 
 458                         WriteNextResponseByte(eeprom_read_byte((uint8_t*)((intptr_t)(CurrAddress 
>> 1)))); 
 460                         /* Increment the address after use */ 
 463                 else if (Command 
== 27) 
 465                         /* Escape is sync, ignore */ 
 469                         /* Unknown command, return fail code */ 
 470                         WriteNextResponseByte('?'); 
 473                 /* Select the IN endpoint */ 
 474                 Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 476                 /* Remember if the endpoint is completely full before clearing it */ 
 477                 bool IsEndpointFull 
= !(Endpoint_IsReadWriteAllowed()); 
 479                 /* Send the endpoint data to the host */ 
 482                 /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */ 
 485                         while (!(Endpoint_IsINReady())) 
 487                                 if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 494                 /* Wait until the data has been sent to the host */ 
 495                 while (!(Endpoint_IsINReady())) 
 497                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 501                 /* Select the OUT endpoint */ 
 502                 Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 504                 /* Acknowledge the command from the host */