3      Copyright (C) Dean Camera, 2012. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2012  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  *  ISP Protocol handler, to process V2 Protocol wrapped ISP commands used in Atmel programmer devices. 
  36 #include "ISPProtocol.h" 
  38 #if defined(ENABLE_ISP_PROTOCOL) || defined(__DOXYGEN__) 
  40 /** Handler for the CMD_ENTER_PROGMODE_ISP command, which attempts to enter programming mode on 
  41  *  the attached device, returning success or failure back to the host. 
  43 void ISPProtocol_EnterISPMode(void) 
  48                 uint8_t PinStabDelayMS
; 
  49                 uint8_t ExecutionDelayMS
; 
  54                 uint8_t EnterProgBytes
[4]; 
  57         Endpoint_Read_Stream_LE(&Enter_ISP_Params
, sizeof(Enter_ISP_Params
), NULL
); 
  60         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
  61         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
  63         uint8_t ResponseStatus 
= STATUS_CMD_FAILED
; 
  67         /* Perform execution delay, initialize SPI bus */ 
  68         ISPProtocol_DelayMS(Enter_ISP_Params
.ExecutionDelayMS
); 
  69         ISPTarget_EnableTargetISP(); 
  71         ISPTarget_ChangeTargetResetLine(true); 
  72         ISPProtocol_DelayMS(Enter_ISP_Params
.PinStabDelayMS
); 
  74         /* Continuously attempt to synchronize with the target until either the number of attempts specified 
  75          * by the host has exceeded, or the the device sends back the expected response values */ 
  76         while (Enter_ISP_Params
.SynchLoops
-- && TimeoutTicksRemaining
) 
  78                 uint8_t ResponseBytes
[4]; 
  80                 for (uint8_t RByte 
= 0; RByte 
< sizeof(ResponseBytes
); RByte
++) 
  82                         ISPProtocol_DelayMS(Enter_ISP_Params
.ByteDelay
); 
  83                         ResponseBytes
[RByte
] = ISPTarget_TransferByte(Enter_ISP_Params
.EnterProgBytes
[RByte
]); 
  86                 /* Check if polling disabled, or if the polled value matches the expected value */ 
  87                 if (!(Enter_ISP_Params
.PollIndex
) || (ResponseBytes
[Enter_ISP_Params
.PollIndex 
- 1] == Enter_ISP_Params
.PollValue
)) 
  89                         ResponseStatus 
= STATUS_CMD_OK
; 
  94                         ISPTarget_ChangeTargetResetLine(false); 
  95                         ISPProtocol_DelayMS(Enter_ISP_Params
.PinStabDelayMS
); 
  96                         ISPTarget_ChangeTargetResetLine(true); 
  97                         ISPProtocol_DelayMS(Enter_ISP_Params
.PinStabDelayMS
); 
 101         Endpoint_Write_8(CMD_ENTER_PROGMODE_ISP
); 
 102         Endpoint_Write_8(ResponseStatus
); 
 106 /** Handler for the CMD_LEAVE_ISP command, which releases the target from programming mode. */ 
 107 void ISPProtocol_LeaveISPMode(void) 
 115         Endpoint_Read_Stream_LE(&Leave_ISP_Params
, sizeof(Leave_ISP_Params
), NULL
); 
 118         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 119         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 121         /* Perform pre-exit delay, release the target /RESET, disable the SPI bus and perform the post-exit delay */ 
 122         ISPProtocol_DelayMS(Leave_ISP_Params
.PreDelayMS
); 
 123         ISPTarget_ChangeTargetResetLine(false); 
 124         ISPTarget_DisableTargetISP(); 
 125         ISPProtocol_DelayMS(Leave_ISP_Params
.PostDelayMS
); 
 127         Endpoint_Write_8(CMD_LEAVE_PROGMODE_ISP
); 
 128         Endpoint_Write_8(STATUS_CMD_OK
); 
 132 /** Handler for the CMD_PROGRAM_FLASH_ISP and CMD_PROGRAM_EEPROM_ISP commands, writing out bytes, 
 133  *  words or pages of data to the attached device. 
 135  *  \param[in] V2Command  Issued V2 Protocol command byte from the host 
 137 void ISPProtocol_ProgramMemory(uint8_t V2Command
) 
 141                 uint16_t BytesToWrite
; 
 142                 uint8_t  ProgrammingMode
; 
 144                 uint8_t  ProgrammingCommands
[3]; 
 147                 uint8_t  ProgData
[256]; // Note, the Jungo driver has a very short ACK timeout period, need to buffer the 
 148         } Write_Memory_Params
;      // whole page and ACK the packet as fast as possible to prevent it from aborting 
 150         Endpoint_Read_Stream_LE(&Write_Memory_Params
, (sizeof(Write_Memory_Params
) - 
 151                                                        sizeof(Write_Memory_Params
.ProgData
)), NULL
); 
 152         Write_Memory_Params
.BytesToWrite 
= SwapEndian_16(Write_Memory_Params
.BytesToWrite
); 
 154         if (Write_Memory_Params
.BytesToWrite 
> sizeof(Write_Memory_Params
.ProgData
)) 
 157                 Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 158                 Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 160                 Endpoint_Write_8(V2Command
); 
 161                 Endpoint_Write_8(STATUS_CMD_FAILED
); 
 166         Endpoint_Read_Stream_LE(&Write_Memory_Params
.ProgData
, Write_Memory_Params
.BytesToWrite
, NULL
); 
 168         // The driver will terminate transfers that are a round multiple of the endpoint bank in size with a ZLP, need 
 169         // to catch this and discard it before continuing on with packet processing to prevent communication issues 
 170         if (((sizeof(uint8_t) + sizeof(Write_Memory_Params
) - sizeof(Write_Memory_Params
.ProgData
)) + 
 171             Write_Memory_Params
.BytesToWrite
) % AVRISP_DATA_EPSIZE 
== 0) 
 174                 Endpoint_WaitUntilReady(); 
 178         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 179         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 181         uint8_t  ProgrammingStatus 
= STATUS_CMD_OK
; 
 182         uint8_t  PollValue         
= (V2Command 
== CMD_PROGRAM_FLASH_ISP
) ? Write_Memory_Params
.PollValue1 
: 
 183                                                                             Write_Memory_Params
.PollValue2
; 
 184         uint16_t PollAddress       
= 0; 
 185         uint8_t* NextWriteByte     
= Write_Memory_Params
.ProgData
; 
 186         uint16_t PageStartAddress  
= (CurrentAddress 
& 0xFFFF); 
 188         for (uint16_t CurrentByte 
= 0; CurrentByte 
< Write_Memory_Params
.BytesToWrite
; CurrentByte
++) 
 190                 uint8_t ByteToWrite     
= *(NextWriteByte
++); 
 191                 uint8_t ProgrammingMode 
= Write_Memory_Params
.ProgrammingMode
; 
 193                 /* Check to see if we need to send a LOAD EXTENDED ADDRESS command to the target */ 
 194                 if (MustLoadExtendedAddress
) 
 196                         ISPTarget_LoadExtendedAddress(); 
 197                         MustLoadExtendedAddress 
= false; 
 200                 ISPTarget_SendByte(Write_Memory_Params
.ProgrammingCommands
[0]); 
 201                 ISPTarget_SendByte(CurrentAddress 
>> 8); 
 202                 ISPTarget_SendByte(CurrentAddress 
& 0xFF); 
 203                 ISPTarget_SendByte(ByteToWrite
); 
 205                 /* AVR FLASH addressing requires us to modify the write command based on if we are writing a high 
 206                  * or low byte at the current word address */ 
 207                 if (V2Command 
== CMD_PROGRAM_FLASH_ISP
) 
 208                   Write_Memory_Params
.ProgrammingCommands
[0] ^= READ_WRITE_HIGH_BYTE_MASK
; 
 210                 /* Check to see if we have a valid polling address */ 
 211                 if (!(PollAddress
) && (ByteToWrite 
!= PollValue
)) 
 213                         if ((CurrentByte 
& 0x01) && (V2Command 
== CMD_PROGRAM_FLASH_ISP
)) 
 214                           Write_Memory_Params
.ProgrammingCommands
[2] |=  READ_WRITE_HIGH_BYTE_MASK
; 
 216                           Write_Memory_Params
.ProgrammingCommands
[2] &= ~READ_WRITE_HIGH_BYTE_MASK
; 
 218                         PollAddress 
= (CurrentAddress 
& 0xFFFF); 
 221                 /* If in word programming mode, commit the byte to the target's memory */ 
 222                 if (!(ProgrammingMode 
& PROG_MODE_PAGED_WRITES_MASK
)) 
 224                         /* If the current polling address is invalid, switch to timed delay write completion mode */ 
 225                         if (!(PollAddress
) && !(ProgrammingMode 
& PROG_MODE_WORD_READYBUSY_MASK
)) 
 226                           ProgrammingMode 
= (ProgrammingMode 
& ~PROG_MODE_WORD_VALUE_MASK
) | PROG_MODE_WORD_TIMEDELAY_MASK
; 
 228                         ProgrammingStatus 
= ISPTarget_WaitForProgComplete(ProgrammingMode
, PollAddress
, PollValue
, 
 229                                                                           Write_Memory_Params
.DelayMS
, 
 230                                                                           Write_Memory_Params
.ProgrammingCommands
[2]); 
 232                         /* Abort the programming loop early if the byte/word programming failed */ 
 233                         if (ProgrammingStatus 
!= STATUS_CMD_OK
) 
 236                         /* Must reset the polling address afterwards, so it is not erroneously used for the next byte */ 
 240                 /* EEPROM just increments the address each byte, flash needs to increment on each word and 
 241                  * also check to ensure that a LOAD EXTENDED ADDRESS command is issued each time the extended 
 242                  * address boundary has been crossed during FLASH memory programming */ 
 243                 if ((CurrentByte 
& 0x01) || (V2Command 
== CMD_PROGRAM_EEPROM_ISP
)) 
 247                         if ((V2Command 
== CMD_PROGRAM_FLASH_ISP
) && !(CurrentAddress 
& 0xFFFF)) 
 248                           MustLoadExtendedAddress 
= true; 
 252         /* If the current page must be committed, send the PROGRAM PAGE command to the target */ 
 253         if (Write_Memory_Params
.ProgrammingMode 
& PROG_MODE_COMMIT_PAGE_MASK
) 
 255                 ISPTarget_SendByte(Write_Memory_Params
.ProgrammingCommands
[1]); 
 256                 ISPTarget_SendByte(PageStartAddress 
>> 8); 
 257                 ISPTarget_SendByte(PageStartAddress 
& 0xFF); 
 258                 ISPTarget_SendByte(0x00); 
 260                 /* Check if polling is enabled and possible, if not switch to timed delay mode */ 
 261                 if ((Write_Memory_Params
.ProgrammingMode 
& PROG_MODE_PAGED_VALUE_MASK
) && !(PollAddress
)) 
 263                         Write_Memory_Params
.ProgrammingMode 
= (Write_Memory_Params
.ProgrammingMode 
& ~PROG_MODE_PAGED_VALUE_MASK
) | 
 264                                                                                                    PROG_MODE_PAGED_TIMEDELAY_MASK
; 
 267                 ProgrammingStatus 
= ISPTarget_WaitForProgComplete(Write_Memory_Params
.ProgrammingMode
, PollAddress
, PollValue
, 
 268                                                                   Write_Memory_Params
.DelayMS
, 
 269                                                                   Write_Memory_Params
.ProgrammingCommands
[2]); 
 271                 /* Check to see if the FLASH address has crossed the extended address boundary */ 
 272                 if ((V2Command 
== CMD_PROGRAM_FLASH_ISP
) && !(CurrentAddress 
& 0xFFFF)) 
 273                   MustLoadExtendedAddress 
= true; 
 276         Endpoint_Write_8(V2Command
); 
 277         Endpoint_Write_8(ProgrammingStatus
); 
 281 /** Handler for the CMD_READ_FLASH_ISP and CMD_READ_EEPROM_ISP commands, reading in bytes, 
 282  *  words or pages of data from the attached device. 
 284  *  \param[in] V2Command  Issued V2 Protocol command byte from the host 
 286 void ISPProtocol_ReadMemory(uint8_t V2Command
) 
 290                 uint16_t BytesToRead
; 
 291                 uint8_t  ReadMemoryCommand
; 
 292         } Read_Memory_Params
; 
 294         Endpoint_Read_Stream_LE(&Read_Memory_Params
, sizeof(Read_Memory_Params
), NULL
); 
 295         Read_Memory_Params
.BytesToRead 
= SwapEndian_16(Read_Memory_Params
.BytesToRead
); 
 298         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 299         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 301         Endpoint_Write_8(V2Command
); 
 302         Endpoint_Write_8(STATUS_CMD_OK
); 
 304         /* Read each byte from the device and write them to the packet for the host */ 
 305         for (uint16_t CurrentByte 
= 0; CurrentByte 
< Read_Memory_Params
.BytesToRead
; CurrentByte
++) 
 307                 /* Check to see if we need to send a LOAD EXTENDED ADDRESS command to the target */ 
 308                 if (MustLoadExtendedAddress
) 
 310                         ISPTarget_LoadExtendedAddress(); 
 311                         MustLoadExtendedAddress 
= false; 
 314                 /* Read the next byte from the desired memory space in the device */ 
 315                 ISPTarget_SendByte(Read_Memory_Params
.ReadMemoryCommand
); 
 316                 ISPTarget_SendByte(CurrentAddress 
>> 8); 
 317                 ISPTarget_SendByte(CurrentAddress 
& 0xFF); 
 318                 Endpoint_Write_8(ISPTarget_ReceiveByte()); 
 320                 /* Check if the endpoint bank is currently full, if so send the packet */ 
 321                 if (!(Endpoint_IsReadWriteAllowed())) 
 324                         Endpoint_WaitUntilReady(); 
 327                 /* AVR FLASH addressing requires us to modify the read command based on if we are reading a high 
 328                  * or low byte at the current word address */ 
 329                 if (V2Command 
== CMD_READ_FLASH_ISP
) 
 330                   Read_Memory_Params
.ReadMemoryCommand 
^= READ_WRITE_HIGH_BYTE_MASK
; 
 332                 /* EEPROM just increments the address each byte, flash needs to increment on each word and 
 333                  * also check to ensure that a LOAD EXTENDED ADDRESS command is issued each time the extended 
 334                  * address boundary has been crossed */ 
 335                 if ((CurrentByte 
& 0x01) || (V2Command 
== CMD_READ_EEPROM_ISP
)) 
 339                         if ((V2Command 
!= CMD_READ_EEPROM_ISP
) && !(CurrentAddress 
& 0xFFFF)) 
 340                           MustLoadExtendedAddress 
= true; 
 344         Endpoint_Write_8(STATUS_CMD_OK
); 
 346         bool IsEndpointFull 
= !(Endpoint_IsReadWriteAllowed()); 
 349         /* Ensure last packet is a short packet to terminate the transfer */ 
 352                 Endpoint_WaitUntilReady(); 
 354                 Endpoint_WaitUntilReady(); 
 358 /** Handler for the CMD_CHI_ERASE_ISP command, clearing the target's FLASH memory. */ 
 359 void ISPProtocol_ChipErase(void) 
 363                 uint8_t EraseDelayMS
; 
 365                 uint8_t EraseCommandBytes
[4]; 
 368         Endpoint_Read_Stream_LE(&Erase_Chip_Params
, sizeof(Erase_Chip_Params
), NULL
); 
 371         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 372         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 374         uint8_t ResponseStatus 
= STATUS_CMD_OK
; 
 376         /* Send the chip erase commands as given by the host to the device */ 
 377         for (uint8_t SByte 
= 0; SByte 
< sizeof(Erase_Chip_Params
.EraseCommandBytes
); SByte
++) 
 378           ISPTarget_SendByte(Erase_Chip_Params
.EraseCommandBytes
[SByte
]); 
 380         /* Use appropriate command completion check as given by the host (delay or busy polling) */ 
 381         if (!(Erase_Chip_Params
.PollMethod
)) 
 382           ISPProtocol_DelayMS(Erase_Chip_Params
.EraseDelayMS
); 
 384           ResponseStatus 
= ISPTarget_WaitWhileTargetBusy(); 
 386         Endpoint_Write_8(CMD_CHIP_ERASE_ISP
); 
 387         Endpoint_Write_8(ResponseStatus
); 
 391 /** Handler for the CMD_READ_FUSE_ISP, CMD_READ_LOCK_ISP, CMD_READ_SIGNATURE_ISP and CMD_READ_OSCCAL commands, 
 392  *  reading the requested configuration byte from the device. 
 394  *  \param[in] V2Command  Issued V2 Protocol command byte from the host 
 396 void ISPProtocol_ReadFuseLockSigOSCCAL(uint8_t V2Command
) 
 401                 uint8_t ReadCommandBytes
[4]; 
 402         } Read_FuseLockSigOSCCAL_Params
; 
 404         Endpoint_Read_Stream_LE(&Read_FuseLockSigOSCCAL_Params
, sizeof(Read_FuseLockSigOSCCAL_Params
), NULL
); 
 407         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 408         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 410         uint8_t ResponseBytes
[4]; 
 412         /* Send the Fuse or Lock byte read commands as given by the host to the device, store response */ 
 413         for (uint8_t RByte 
= 0; RByte 
< sizeof(ResponseBytes
); RByte
++) 
 414           ResponseBytes
[RByte
] = ISPTarget_TransferByte(Read_FuseLockSigOSCCAL_Params
.ReadCommandBytes
[RByte
]); 
 416         Endpoint_Write_8(V2Command
); 
 417         Endpoint_Write_8(STATUS_CMD_OK
); 
 418         Endpoint_Write_8(ResponseBytes
[Read_FuseLockSigOSCCAL_Params
.RetByte 
- 1]); 
 419         Endpoint_Write_8(STATUS_CMD_OK
); 
 423 /** Handler for the CMD_WRITE_FUSE_ISP and CMD_WRITE_LOCK_ISP commands, writing the requested configuration 
 424  *  byte to the device. 
 426  *  \param[in] V2Command  Issued V2 Protocol command byte from the host 
 428 void ISPProtocol_WriteFuseLock(uint8_t V2Command
) 
 432                 uint8_t WriteCommandBytes
[4]; 
 433         } Write_FuseLockSig_Params
; 
 435         Endpoint_Read_Stream_LE(&Write_FuseLockSig_Params
, sizeof(Write_FuseLockSig_Params
), NULL
); 
 438         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 439         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 441         /* Send the Fuse or Lock byte program commands as given by the host to the device */ 
 442         for (uint8_t SByte 
= 0; SByte 
< sizeof(Write_FuseLockSig_Params
.WriteCommandBytes
); SByte
++) 
 443           ISPTarget_SendByte(Write_FuseLockSig_Params
.WriteCommandBytes
[SByte
]); 
 445         Endpoint_Write_8(V2Command
); 
 446         Endpoint_Write_8(STATUS_CMD_OK
); 
 447         Endpoint_Write_8(STATUS_CMD_OK
); 
 451 /** Handler for the CMD_SPI_MULTI command, writing and reading arbitrary SPI data to and from the attached device. */ 
 452 void ISPProtocol_SPIMulti(void) 
 462         Endpoint_Read_Stream_LE(&SPI_Multi_Params
, (sizeof(SPI_Multi_Params
) - sizeof(SPI_Multi_Params
.TxData
)), NULL
); 
 463         Endpoint_Read_Stream_LE(&SPI_Multi_Params
.TxData
, SPI_Multi_Params
.TxBytes
, NULL
); 
 466         Endpoint_SelectEndpoint(AVRISP_DATA_IN_EPADDR
); 
 467         Endpoint_SetEndpointDirection(ENDPOINT_DIR_IN
); 
 469         Endpoint_Write_8(CMD_SPI_MULTI
); 
 470         Endpoint_Write_8(STATUS_CMD_OK
); 
 472         uint8_t CurrTxPos 
= 0; 
 473         uint8_t CurrRxPos 
= 0; 
 475         /* Write out bytes to transmit until the start of the bytes to receive is met */ 
 476         while (CurrTxPos 
< SPI_Multi_Params
.RxStartAddr
) 
 478                 if (CurrTxPos 
< SPI_Multi_Params
.TxBytes
) 
 479                   ISPTarget_SendByte(SPI_Multi_Params
.TxData
[CurrTxPos
]); 
 481                   ISPTarget_SendByte(0); 
 486         /* Transmit remaining bytes with padding as needed, read in response bytes */ 
 487         while (CurrRxPos 
< SPI_Multi_Params
.RxBytes
) 
 489                 if (CurrTxPos 
< SPI_Multi_Params
.TxBytes
) 
 490                   Endpoint_Write_8(ISPTarget_TransferByte(SPI_Multi_Params
.TxData
[CurrTxPos
++])); 
 492                   Endpoint_Write_8(ISPTarget_ReceiveByte()); 
 494                 /* Check to see if we have filled the endpoint bank and need to send the packet */ 
 495                 if (!(Endpoint_IsReadWriteAllowed())) 
 498                         Endpoint_WaitUntilReady(); 
 504         Endpoint_Write_8(STATUS_CMD_OK
); 
 506         bool IsEndpointFull 
= !(Endpoint_IsReadWriteAllowed()); 
 509         /* Ensure last packet is a short packet to terminate the transfer */ 
 512                 Endpoint_WaitUntilReady(); 
 514                 Endpoint_WaitUntilReady(); 
 518 /** Blocking delay for a given number of milliseconds. This provides a simple wrapper around 
 519  *  the avr-libc provided delay function, so that the delay function can be called with a 
 520  *  constant value (to prevent run-time floating point operations being required). 
 522  *  \param[in] DelayMS  Number of milliseconds to delay for 
 524 void ISPProtocol_DelayMS(uint8_t DelayMS
) 
 526         while (DelayMS
-- && TimeoutTicksRemaining
)