3      Copyright (C) Dean Camera, 2009. 
   5   dean [at] fourwalledcubicle [dot] com 
   6       www.fourwalledcubicle.com 
  10   Copyright 2009  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  12   Permission to use, copy, modify, and distribute this software 
  13   and its documentation for any purpose and without fee is hereby 
  14   granted, provided that the above copyright notice appear in all 
  15   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  *  SCSI command processing routines, for SCSI commands issued by the host. Mass Storage 
  34  *  devices use a thin "Bulk-Only Transport" protocol for issuing commands and status information, 
  35  *  which wrap around standard SCSI device commands for controlling the actual storage medium. 
  38 #define  INCLUDE_FROM_SCSI_C 
  41 /** Structure to hold the SCSI response data to a SCSI INQUIRY command. This gives information about the device's 
  42  *  features and capabilities. 
  44 SCSI_Inquiry_Response_t InquiryData 
=  
  46                 .DeviceType          
= DEVICE_TYPE_BLOCK
, 
  47                 .PeripheralQualifier 
= 0, 
  53                 .ResponseDataFormat  
= 2, 
  58                 .AdditionalLength    
= 0x1F, 
  64                 .WideBus16Bit        
= false, 
  65                 .WideBus32Bit        
= false, 
  69                 .ProductID           
= "Dataflash Disk", 
  70                 .RevisionID          
= {'0','.','0','0'}, 
  73 /** Structure to hold the sense data for the last issued SCSI command, which is returned to the host after a SCSI REQUEST SENSE 
  74  *  command is issued. This gives information on exactly why the last command failed to complete. 
  76 SCSI_Request_Sense_Response_t SenseData 
= 
  79                 .AdditionalLength    
= 0x0A, 
  83 /** Main routine to process the SCSI command located in the Command Block Wrapper read from the host. This dispatches 
  84  *  to the appropriate SCSI command handling routine if the issued command is supported by the device, else it returns 
  85  *  a command failure due to a ILLEGAL REQUEST. 
  87 void SCSI_DecodeSCSICommand(void) 
  89         bool CommandSuccess 
= false; 
  91         /* Run the appropriate SCSI command hander function based on the passed command */ 
  92         switch (CommandBlock
.SCSICommandData
[0]) 
  94                 case SCSI_CMD_INQUIRY
: 
  95                         CommandSuccess 
= SCSI_Command_Inquiry();                         
  97                 case SCSI_CMD_REQUEST_SENSE
: 
  98                         CommandSuccess 
= SCSI_Command_Request_Sense(); 
 100                 case SCSI_CMD_READ_CAPACITY_10
: 
 101                         CommandSuccess 
= SCSI_Command_Read_Capacity_10();                        
 103                 case SCSI_CMD_SEND_DIAGNOSTIC
: 
 104                         CommandSuccess 
= SCSI_Command_Send_Diagnostic(); 
 106                 case SCSI_CMD_WRITE_10
: 
 107                         CommandSuccess 
= SCSI_Command_ReadWrite_10(DATA_WRITE
); 
 109                 case SCSI_CMD_READ_10
: 
 110                         CommandSuccess 
= SCSI_Command_ReadWrite_10(DATA_READ
); 
 112                 case SCSI_CMD_TEST_UNIT_READY
: 
 113                 case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
: 
 114                 case SCSI_CMD_VERIFY_10
: 
 115                         /* These commands should just succeed, no handling required */ 
 116                         CommandSuccess 
= true; 
 117                         CommandBlock
.DataTransferLength 
= 0; 
 120                         /* Update the SENSE key to reflect the invalid command */ 
 121                         SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 122                                    SCSI_ASENSE_INVALID_COMMAND
, 
 123                                    SCSI_ASENSEQ_NO_QUALIFIER
); 
 127         /* Check if command was successfully processed */ 
 130                 /* Command succeeded - set the CSW status and update the SENSE key */ 
 131                 CommandStatus
.Status 
= Command_Pass
; 
 133                 SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD
, 
 134                                SCSI_ASENSE_NO_ADDITIONAL_INFORMATION
, 
 135                                SCSI_ASENSEQ_NO_QUALIFIER
);                                          
 139                 /* Command failed - set the CSW status - failed command function updates the SENSE key */ 
 140                 CommandStatus
.Status 
= Command_Fail
; 
 144 /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features 
 145  *  and capabilities to the host. 
 147  *  \return Boolean true if the command completed successfully, false otherwise. 
 149 static bool SCSI_Command_Inquiry(void) 
 151         uint16_t AllocationLength  
= (((uint16_t)CommandBlock
.SCSICommandData
[3] << 8) | 
 152                                                  CommandBlock
.SCSICommandData
[4]); 
 153         uint16_t BytesTransferred  
= (AllocationLength 
< sizeof(InquiryData
))? AllocationLength 
: 
 156         /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */ 
 157         if ((CommandBlock
.SCSICommandData
[1] & ((1 << 0) | (1 << 1))) || 
 158              CommandBlock
.SCSICommandData
[2]) 
 160                 /* Optional but unsupported bits set - update the SENSE key and fail the request */ 
 161                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 162                                SCSI_ASENSE_INVALID_FIELD_IN_CDB
, 
 163                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 168         /* Write the INQUIRY data to the endpoint */ 
 169         Endpoint_Write_Stream_LE(&InquiryData
, BytesTransferred
, AbortOnMassStoreReset
); 
 171         uint8_t PadBytes
[AllocationLength 
- BytesTransferred
]; 
 173         /* Pad out remaining bytes with 0x00 */ 
 174         Endpoint_Write_Stream_LE(&PadBytes
, (AllocationLength 
- BytesTransferred
), AbortOnMassStoreReset
); 
 176         /* Finalize the stream transfer to send the last packet */ 
 179         /* Succeed the command and update the bytes transferred counter */ 
 180         CommandBlock
.DataTransferLength 
-= BytesTransferred
; 
 185 /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command, 
 186  *  including the error code and additional error information so that the host can determine why a command failed to complete. 
 188  *  \return Boolean true if the command completed successfully, false otherwise. 
 190 static bool SCSI_Command_Request_Sense(void) 
 192         uint8_t  AllocationLength 
= CommandBlock
.SCSICommandData
[4]; 
 193         uint8_t  BytesTransferred 
= (AllocationLength 
< sizeof(SenseData
))? AllocationLength 
: sizeof(SenseData
); 
 195         /* Send the SENSE data - this indicates to the host the status of the last command */ 
 196         Endpoint_Write_Stream_LE(&SenseData
, BytesTransferred
, AbortOnMassStoreReset
); 
 198         uint8_t PadBytes
[AllocationLength 
- BytesTransferred
]; 
 200         /* Pad out remaining bytes with 0x00 */ 
 201         Endpoint_Write_Stream_LE(&PadBytes
, (AllocationLength 
- BytesTransferred
), AbortOnMassStoreReset
); 
 203         /* Finalize the stream transfer to send the last packet */ 
 206         /* Succeed the command and update the bytes transferred counter */ 
 207         CommandBlock
.DataTransferLength 
-= BytesTransferred
; 
 212 /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity 
 213  *  on the selected Logical Unit (drive), as a number of OS-sized blocks. 
 215  *  \return Boolean true if the command completed successfully, false otherwise. 
 217 static bool SCSI_Command_Read_Capacity_10(void) 
 219         /* Send the total number of logical blocks in the current LUN */ 
 220         Endpoint_Write_DWord_BE(LUN_MEDIA_BLOCKS 
- 1); 
 222         /* Send the logical block size of the device (must be 512 bytes) */ 
 223         Endpoint_Write_DWord_BE(VIRTUAL_MEMORY_BLOCK_SIZE
); 
 225         /* Check if the current command is being aborted by the host */ 
 226         if (IsMassStoreReset
) 
 229         /* Send the endpoint data packet to the host */ 
 232         /* Succeed the command and update the bytes transferred counter */ 
 233         CommandBlock
.DataTransferLength 
-= 8; 
 238 /** Command processing for an issued SCSI SEND DIAGNOSTIC command. This command performs a quick check of the Dataflash ICs on the 
 239  *  board, and indicates if they are present and functioning correctly. Only the Self-Test portion of the diagnostic command is 
 242  *  \return Boolean true if the command completed successfully, false otherwise. 
 244 static bool SCSI_Command_Send_Diagnostic(void) 
 248         /* Check to see if the SELF TEST bit is not set */ 
 249         if (!(CommandBlock
.SCSICommandData
[1] & (1 << 2))) 
 251                 /* Only self-test supported - update SENSE key and fail the command */ 
 252                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 253                                SCSI_ASENSE_INVALID_FIELD_IN_CDB
, 
 254                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 259         /* Test first Dataflash IC is present and responding to commands */ 
 260         Dataflash_SelectChip(DATAFLASH_CHIP1
); 
 261         Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO
); 
 262         ReturnByte 
= Dataflash_ReceiveByte(); 
 263         Dataflash_DeselectChip(); 
 265         /* If returned data is invalid, fail the command */ 
 266         if (ReturnByte 
!= DF_MANUFACTURER_ATMEL
) 
 268                 /* Update SENSE key with a hardware error condition and return command fail */ 
 269                 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR
, 
 270                                SCSI_ASENSE_NO_ADDITIONAL_INFORMATION
, 
 271                                SCSI_ASENSEQ_NO_QUALIFIER
);       
 276         #if (DATAFLASH_TOTALCHIPS == 2) 
 277         /* Test second Dataflash IC is present and responding to commands */ 
 278         Dataflash_SelectChip(DATAFLASH_CHIP2
); 
 279         Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO
); 
 280         ReturnByte 
= Dataflash_ReceiveByte(); 
 281         Dataflash_DeselectChip(); 
 283         /* If returned data is invalid, fail the command */ 
 284         if (ReturnByte 
!= DF_MANUFACTURER_ATMEL
) 
 286                 /* Update SENSE key with a hardware error condition and return command fail */ 
 287                 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR
, 
 288                                SCSI_ASENSE_NO_ADDITIONAL_INFORMATION
, 
 289                                SCSI_ASENSEQ_NO_QUALIFIER
);       
 295         /* Succeed the command and update the bytes transferred counter */ 
 296         CommandBlock
.DataTransferLength 
= 0; 
 301 /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address 
 302  *  and total number of blocks to process, then calls the appropriate low-level dataflash routine to handle the actual 
 303  *  reading and writing of the data. 
 305  *  \param IsDataRead  Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE) 
 307  *  \return Boolean true if the command completed successfully, false otherwise. 
 309 static bool SCSI_Command_ReadWrite_10(const bool IsDataRead
) 
 311         uint32_t BlockAddress
; 
 312         uint16_t TotalBlocks
; 
 314         /* Load in the 32-bit block address (SCSI uses big-endian, so have to do it byte-by-byte) */ 
 315         ((uint8_t*)&BlockAddress
)[3] = CommandBlock
.SCSICommandData
[2]; 
 316         ((uint8_t*)&BlockAddress
)[2] = CommandBlock
.SCSICommandData
[3]; 
 317         ((uint8_t*)&BlockAddress
)[1] = CommandBlock
.SCSICommandData
[4]; 
 318         ((uint8_t*)&BlockAddress
)[0] = CommandBlock
.SCSICommandData
[5]; 
 320         /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to do it byte-by-byte) */ 
 321         ((uint8_t*)&TotalBlocks
)[1]  = CommandBlock
.SCSICommandData
[7]; 
 322         ((uint8_t*)&TotalBlocks
)[0]  = CommandBlock
.SCSICommandData
[8]; 
 324         /* Check if the block address is outside the maximum allowable value for the LUN */ 
 325         if (BlockAddress 
>= LUN_MEDIA_BLOCKS
) 
 327                 /* Block address is invalid, update SENSE key and return command fail */ 
 328                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 329                                SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
, 
 330                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 336         /* Adjust the given block address to the real media address based on the selected LUN */ 
 337         BlockAddress 
+= ((uint32_t)CommandBlock
.LUN 
* LUN_MEDIA_BLOCKS
); 
 340         /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */ 
 341         if (IsDataRead 
== DATA_READ
) 
 342           DataflashManager_ReadBlocks(BlockAddress
, TotalBlocks
); 
 344           DataflashManager_WriteBlocks(BlockAddress
, TotalBlocks
); 
 346         /* Update the bytes transferred counter and succeed the command */ 
 347         CommandBlock
.DataTransferLength 
-= ((uint32_t)TotalBlocks 
* VIRTUAL_MEMORY_BLOCK_SIZE
);