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 watchdog reset. When cleared the bootloader will exit, starting the watchdog and entering an infinite 
  58  *  loop until the AVR restarts and the application runs. 
  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 */ 
  72         /* Enable global interrupts so that the USB stack can function */ 
  81         /* Disconnect from the host - USB interface will be reset later along with the AVR */ 
  84         /* Enable the watchdog and force a timeout to reset the AVR */ 
  85         wdt_enable(WDTO_250MS
); 
  90 /** Configures all hardware required for the bootloader. */ 
  91 void SetupHardware(void) 
  93         /* Disable watchdog if enabled by bootloader/fuses */ 
  94         MCUSR 
&= ~(1 << WDRF
); 
  97         /* Disable clock division */ 
  98         clock_prescale_set(clock_div_1
); 
 100         /* Relocate the interrupt vector table to the bootloader section */ 
 102         MCUCR 
= (1 << IVSEL
); 
 104         /* Initialize USB Subsystem */ 
 108 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready 
 109  *  to relay data to and from the attached USB host. 
 111 void EVENT_USB_Device_ConfigurationChanged(void) 
 113         /* Setup CDC Notification, Rx and Tx Endpoints */ 
 114         Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM
, EP_TYPE_INTERRUPT
, 
 115                                        ENDPOINT_DIR_IN
, CDC_NOTIFICATION_EPSIZE
, 
 116                                    ENDPOINT_BANK_SINGLE
); 
 118         Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
, 
 119                                        ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
, 
 120                                    ENDPOINT_BANK_SINGLE
); 
 122         Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
, 
 123                                        ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
, 
 124                                    ENDPOINT_BANK_SINGLE
); 
 127 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific 
 128  *  control requests that are not handled internally by the USB library, so that they can be handled appropriately 
 129  *  for the application. 
 131 void EVENT_USB_Device_UnhandledControlRequest(void) 
 133         uint8_t* LineCodingData 
= (uint8_t*)&LineCoding
; 
 135         /* Process CDC specific control requests */ 
 136         switch (USB_ControlRequest
.bRequest
) 
 138                 case REQ_GetLineEncoding
: 
 139                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 141                                 Endpoint_ClearSETUP(); 
 143                                 for (uint8_t i 
= 0; i 
< sizeof(LineCoding
); i
++) 
 144                                   Endpoint_Write_Byte(*(LineCodingData
++));      
 148                                 Endpoint_ClearStatusStage(); 
 152                 case REQ_SetLineEncoding
: 
 153                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 155                                 Endpoint_ClearSETUP(); 
 157                                 while (!(Endpoint_IsOUTReceived())) 
 159                                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 163                                 for (uint8_t i 
= 0; i 
< sizeof(LineCoding
); i
++) 
 164                                   *(LineCodingData
++) = Endpoint_Read_Byte(); 
 168                                 Endpoint_ClearStatusStage(); 
 172                 case REQ_SetControlLineState
: 
 173                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 175                                 Endpoint_ClearSETUP(); 
 177                                 Endpoint_ClearStatusStage(); 
 184 /** Reads or writes a block of EEPROM or FLASH memory to or from the appropriate CDC data endpoint, depending 
 185  *  on the AVR910 protocol command issued. 
 187  *  \param[in] Command  Single character AVR910 protocol command indicating what memory operation to perform 
 189 static void ReadWriteMemoryBlock(const uint8_t Command
) 
 194         bool     HighByte 
= false; 
 197         BlockSize  
= (FetchNextCommandByte() << 8); 
 198         BlockSize 
|=  FetchNextCommandByte(); 
 200         MemoryType 
=  FetchNextCommandByte(); 
 202         if ((MemoryType 
!= 'E') && (MemoryType 
!= 'F')) 
 204                 /* Send error byte back to the host */ 
 205                 WriteNextResponseByte('?'); 
 210         /* Check if command is to read memory */ 
 213                 /* Re-enable RWW section */ 
 218                         if (MemoryType 
== 'F') 
 220                                 /* Read the next FLASH byte from the current FLASH page */ 
 221                                 #if (FLASHEND > 0xFFFF) 
 222                                 WriteNextResponseByte(pgm_read_byte_far(CurrAddress 
| HighByte
)); 
 224                                 WriteNextResponseByte(pgm_read_byte(CurrAddress 
| HighByte
));                                    
 227                                 /* If both bytes in current word have been read, increment the address counter */ 
 231                                 HighByte 
= !HighByte
; 
 235                                 /* Read the next EEPROM byte into the endpoint */ 
 236                                 WriteNextResponseByte(eeprom_read_byte((uint8_t*)(uint16_t)(CurrAddress 
>> 1))); 
 238                                 /* Increment the address counter after use */ 
 245                 uint32_t PageStartAddress 
= CurrAddress
; 
 247                 if (MemoryType 
== 'F') 
 249                         boot_page_erase(PageStartAddress
); 
 250                         boot_spm_busy_wait(); 
 255                         if (MemoryType 
== 'F') 
 257                                 /* If both bytes in current word have been written, increment the address counter */ 
 260                                         /* Write the next FLASH word to the current FLASH page */ 
 261                                         boot_page_fill(CurrAddress
, ((FetchNextCommandByte() << 8) | LowByte
)); 
 263                                         /* Increment the address counter after use */ 
 270                                         LowByte 
= FetchNextCommandByte(); 
 277                                 /* Write the next EEPROM byte from the endpoint */ 
 278                                 eeprom_write_byte((uint8_t*)(uint16_t)(CurrAddress 
>> 1), FetchNextCommandByte());                                       
 280                                 /* Increment the address counter after use */ 
 285                 /* If in FLASH programming mode, commit the page after writing */ 
 286                 if (MemoryType 
== 'F') 
 288                         /* Commit the flash page to memory */ 
 289                         boot_page_write(PageStartAddress
); 
 291                         /* Wait until write operation has completed */ 
 292                         boot_spm_busy_wait(); 
 295                 /* Send response byte back to the host */ 
 296                 WriteNextResponseByte('\r');             
 300 /** Retrieves the next byte from the host in the CDC data OUT endpoint, and clears the endpoint bank if needed 
 301  *  to allow reception of the next data packet from the host. 
 303  *  \return Next received byte from the host in the CDC data OUT endpoint 
 305 static uint8_t FetchNextCommandByte(void) 
 307         /* Select the OUT endpoint so that the next data byte can be read */ 
 308         Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 310         /* If OUT endpoint empty, clear it and wait for the next packet from the host */ 
 311         while (!(Endpoint_IsReadWriteAllowed())) 
 315                 while (!(Endpoint_IsOUTReceived())) 
 317                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 322         /* Fetch the next byte from the OUT endpoint */ 
 323         return Endpoint_Read_Byte(); 
 326 /** Writes the next response byte to the CDC data IN endpoint, and sends the endpoint back if needed to free up the 
 327  *  bank when full ready for the next byte in the packet to the host. 
 329  *  \param[in] Response  Next response byte to send to the host 
 331 static void WriteNextResponseByte(const uint8_t Response
) 
 333         /* Select the IN endpoint so that the next data byte can be written */ 
 334         Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 336         /* If IN endpoint full, clear it and wait until ready for the next packet to the host */ 
 337         if (!(Endpoint_IsReadWriteAllowed())) 
 341                 while (!(Endpoint_IsINReady())) 
 343                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 348         /* Write the next byte to the OUT endpoint */ 
 349         Endpoint_Write_Byte(Response
); 
 352 /** Task to read in AVR910 commands from the CDC data OUT endpoint, process them, perform the required actions 
 353  *  and send the appropriate response back to the host. 
 357         /* Select the OUT endpoint */ 
 358         Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 360         /* Check if endpoint has a command in it sent from the host */ 
 361         if (Endpoint_IsOUTReceived()) 
 363                 /* Read in the bootloader command (first byte sent from host) */ 
 364                 uint8_t Command 
= FetchNextCommandByte(); 
 366                 if ((Command 
== 'L') || (Command 
== 'P') || (Command 
== 'T') || (Command 
== 'E')) 
 369                           RunBootloader 
= false; 
 371                           FetchNextCommandByte(); 
 373                         /* Send confirmation byte back to the host */ 
 374                         WriteNextResponseByte('\r');                     
 376                 else if (Command 
== 't') 
 378                         /* Return ATMEGA128 part code - this is only to allow AVRProg to use the bootloader */ 
 379                         WriteNextResponseByte(0x44); 
 381                         WriteNextResponseByte(0x00); 
 383                 else if (Command 
== 'a') 
 385                         /* Indicate auto-address increment is supported */ 
 386                         WriteNextResponseByte('Y'); 
 388                 else if (Command 
== 'A') 
 390                         /* Set the current address to that given by the host */ 
 391                         CurrAddress   
= (FetchNextCommandByte() << 9); 
 392                         CurrAddress  
|= (FetchNextCommandByte() << 1); 
 394                         /* Send confirmation byte back to the host */ 
 395                         WriteNextResponseByte('\r'); 
 397                 else if (Command 
== 'p') 
 399                         /* Indicate serial programmer back to the host */ 
 400                         WriteNextResponseByte('S');               
 402                 else if (Command 
== 'S') 
 404                         /* Write the 7-byte software identifier to the endpoint */ 
 405                         for (uint8_t CurrByte 
= 0; CurrByte 
< 7; CurrByte
++) 
 406                           WriteNextResponseByte(SOFTWARE_IDENTIFIER
[CurrByte
]);          
 408                 else if (Command 
== 'V') 
 410                         WriteNextResponseByte('0' + BOOTLOADER_VERSION_MAJOR
); 
 411                         WriteNextResponseByte('0' + BOOTLOADER_VERSION_MINOR
); 
 413                 else if (Command 
== 's') 
 415                         WriteNextResponseByte(AVR_SIGNATURE_3
);          
 416                         WriteNextResponseByte(AVR_SIGNATURE_2
); 
 417                         WriteNextResponseByte(AVR_SIGNATURE_1
); 
 419                 else if (Command 
== 'b') 
 421                         WriteNextResponseByte('Y'); 
 423                         /* Send block size to the host */ 
 424                         WriteNextResponseByte(SPM_PAGESIZE 
>> 8); 
 425                         WriteNextResponseByte(SPM_PAGESIZE 
& 0xFF);              
 427                 else if (Command 
== 'e') 
 429                         /* Clear the application section of flash */ 
 430                         for (uint32_t CurrFlashAddress 
= 0; CurrFlashAddress 
< BOOT_START_ADDR
; CurrFlashAddress
++) 
 432                                 boot_page_erase(CurrFlashAddress
); 
 433                                 boot_spm_busy_wait(); 
 434                                 boot_page_write(CurrFlashAddress
); 
 435                                 boot_spm_busy_wait(); 
 437                                 CurrFlashAddress 
+= SPM_PAGESIZE
; 
 440                         /* Send confirmation byte back to the host */ 
 441                         WriteNextResponseByte('\r');             
 443                 else if (Command 
== 'l') 
 445                         /* Set the lock bits to those given by the host */ 
 446                         boot_lock_bits_set(FetchNextCommandByte()); 
 448                         /* Send confirmation byte back to the host */ 
 449                         WriteNextResponseByte('\r'); 
 451                 else if (Command 
== 'r') 
 453                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOCK_BITS
));           
 455                 else if (Command 
== 'F') 
 457                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS
)); 
 459                 else if (Command 
== 'N') 
 461                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS
));              
 463                 else if (Command 
== 'Q') 
 465                         WriteNextResponseByte(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS
));          
 467                 else if (Command 
== 'C') 
 469                         /* Write the high byte to the current flash page */ 
 470                         boot_page_fill(CurrAddress
, FetchNextCommandByte()); 
 472                         /* Send confirmation byte back to the host */ 
 473                         WriteNextResponseByte('\r');             
 475                 else if (Command 
== 'c') 
 477                         /* Write the low byte to the current flash page */ 
 478                         boot_page_fill(CurrAddress 
| 1, FetchNextCommandByte()); 
 480                         /* Increment the address */ 
 483                         /* Send confirmation byte back to the host */ 
 484                         WriteNextResponseByte('\r');             
 486                 else if (Command 
== 'm') 
 488                         /* Commit the flash page to memory */ 
 489                         boot_page_write(CurrAddress
); 
 491                         /* Wait until write operation has completed */ 
 492                         boot_spm_busy_wait(); 
 494                         /* Send confirmation byte back to the host */ 
 495                         WriteNextResponseByte('\r');             
 497                 else if ((Command 
== 'B') || (Command 
== 'g')) 
 499                         /* Delegate the block write/read to a separate function for clarity */ 
 500                         ReadWriteMemoryBlock(Command
); 
 502                 else if (Command 
== 'R') 
 504                         #if (FLASHEND > 0xFFFF) 
 505                         uint16_t ProgramWord 
= pgm_read_word_far(CurrAddress
); 
 507                         uint16_t ProgramWord 
= pgm_read_word(CurrAddress
);                       
 510                         WriteNextResponseByte(ProgramWord 
>> 8); 
 511                         WriteNextResponseByte(ProgramWord 
& 0xFF); 
 513                 else if (Command 
== 'D') 
 515                         /* Read the byte from the endpoint and write it to the EEPROM */ 
 516                         eeprom_write_byte((uint8_t*)((uint16_t)(CurrAddress 
>> 1)), FetchNextCommandByte()); 
 518                         /* Increment the address after use */                    
 521                         /* Send confirmation byte back to the host */ 
 522                         WriteNextResponseByte('\r');             
 524                 else if (Command 
== 'd') 
 526                         /* Read the EEPROM byte and write it to the endpoint */ 
 527                         WriteNextResponseByte(eeprom_read_byte((uint8_t*)((uint16_t)(CurrAddress 
>> 1)))); 
 529                         /* Increment the address after use */ 
 532                 else if (Command 
== 27) 
 534                         /* Escape is sync, ignore */ 
 538                         /* Unknown command, return fail code */ 
 539                         WriteNextResponseByte('?'); 
 542                 /* Select the IN endpoint */ 
 543                 Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 545                 /* Remember if the endpoint is completely full before clearing it */ 
 546                 bool IsEndpointFull 
= !(Endpoint_IsReadWriteAllowed()); 
 548                 /* Send the endpoint data to the host */ 
 551                 /* If a full endpoint's worth of data was sent, we need to send an empty packet afterwards to signal end of transfer */ 
 554                         while (!(Endpoint_IsINReady())) 
 556                                 if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 563                 /* Wait until the data has been sent to the host */ 
 564                 while (!(Endpoint_IsINReady())) 
 566                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 570                 /* Select the OUT endpoint */ 
 571                 Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 573                 /* Acknowledge the command from the host */