3      Copyright (C) Dean Camera, 2017. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2017  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 disclaims 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 static const 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 static 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  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
  89  *  \return Boolean \c true if the command completed successfully, \c false otherwise 
  91 bool SCSI_DecodeSCSICommand(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
  93         bool CommandSuccess 
= false; 
  95         /* Run the appropriate SCSI command hander function based on the passed command */ 
  96         switch (MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[0]) 
  98                 case SCSI_CMD_INQUIRY
: 
  99                         CommandSuccess 
= SCSI_Command_Inquiry(MSInterfaceInfo
); 
 101                 case SCSI_CMD_REQUEST_SENSE
: 
 102                         CommandSuccess 
= SCSI_Command_Request_Sense(MSInterfaceInfo
); 
 104                 case SCSI_CMD_READ_CAPACITY_10
: 
 105                         CommandSuccess 
= SCSI_Command_Read_Capacity_10(MSInterfaceInfo
); 
 107                 case SCSI_CMD_SEND_DIAGNOSTIC
: 
 108                         CommandSuccess 
= SCSI_Command_Send_Diagnostic(MSInterfaceInfo
); 
 110                 case SCSI_CMD_WRITE_10
: 
 111                         CommandSuccess 
= SCSI_Command_ReadWrite_10(MSInterfaceInfo
, DATA_WRITE
); 
 113                 case SCSI_CMD_READ_10
: 
 114                         CommandSuccess 
= SCSI_Command_ReadWrite_10(MSInterfaceInfo
, DATA_READ
); 
 116                 case SCSI_CMD_MODE_SENSE_6
: 
 117                         CommandSuccess 
= SCSI_Command_ModeSense_6(MSInterfaceInfo
); 
 119                 case SCSI_CMD_START_STOP_UNIT
: 
 120                 case SCSI_CMD_TEST_UNIT_READY
: 
 121                 case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
: 
 122                 case SCSI_CMD_VERIFY_10
: 
 123                         /* These commands should just succeed, no handling required */ 
 124                         CommandSuccess 
= true; 
 125                         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
= 0; 
 128                         /* Update the SENSE key to reflect the invalid command */ 
 129                         SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 130                                    SCSI_ASENSE_INVALID_COMMAND
, 
 131                                    SCSI_ASENSEQ_NO_QUALIFIER
); 
 135         /* Check if command was successfully processed */ 
 138                 SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD
, 
 139                                SCSI_ASENSE_NO_ADDITIONAL_INFORMATION
, 
 140                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 148 /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features 
 149  *  and capabilities to the host. 
 151  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
 153  *  \return Boolean \c true if the command completed successfully, \c false otherwise. 
 155 static bool SCSI_Command_Inquiry(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
 157         uint16_t AllocationLength  
= SwapEndian_16(*(uint16_t*)&MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[3]); 
 158         uint16_t BytesTransferred  
= MIN(AllocationLength
, sizeof(InquiryData
)); 
 160         /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */ 
 161         if ((MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[1] & ((1 << 0) | (1 << 1))) || 
 162              MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[2]) 
 164                 /* Optional but unsupported bits set - update the SENSE key and fail the request */ 
 165                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 166                                SCSI_ASENSE_INVALID_FIELD_IN_CDB
, 
 167                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 172         Endpoint_Write_Stream_LE(&InquiryData
, BytesTransferred
, NULL
); 
 174         /* Pad out remaining bytes with 0x00 */ 
 175         Endpoint_Null_Stream((AllocationLength 
- BytesTransferred
), NULL
); 
 177         /* Finalize the stream transfer to send the last packet */ 
 180         /* Succeed the command and update the bytes transferred counter */ 
 181         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
-= BytesTransferred
; 
 186 /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command, 
 187  *  including the error code and additional error information so that the host can determine why a command failed to complete. 
 189  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
 191  *  \return Boolean \c true if the command completed successfully, \c false otherwise. 
 193 static bool SCSI_Command_Request_Sense(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
 195         uint8_t  AllocationLength 
= MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[4]; 
 196         uint8_t  BytesTransferred 
= MIN(AllocationLength
, sizeof(SenseData
)); 
 198         Endpoint_Write_Stream_LE(&SenseData
, BytesTransferred
, NULL
); 
 199         Endpoint_Null_Stream((AllocationLength 
- BytesTransferred
), NULL
); 
 202         /* Succeed the command and update the bytes transferred counter */ 
 203         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
-= BytesTransferred
; 
 208 /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity 
 209  *  on the selected Logical Unit (drive), as a number of OS-sized blocks. 
 211  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
 213  *  \return Boolean \c true if the command completed successfully, \c false otherwise. 
 215 static bool SCSI_Command_Read_Capacity_10(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
 217         uint32_t LastBlockAddressInLUN 
= (LUN_MEDIA_BLOCKS 
- 1); 
 218         uint32_t MediaBlockSize        
= VIRTUAL_MEMORY_BLOCK_SIZE
; 
 220         Endpoint_Write_Stream_BE(&LastBlockAddressInLUN
, sizeof(LastBlockAddressInLUN
), NULL
); 
 221         Endpoint_Write_Stream_BE(&MediaBlockSize
, sizeof(MediaBlockSize
), NULL
); 
 224         /* Succeed the command and update the bytes transferred counter */ 
 225         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
-= 8; 
 230 /** Command processing for an issued SCSI SEND DIAGNOSTIC command. This command performs a quick check of the Dataflash ICs on the 
 231  *  board, and indicates if they are present and functioning correctly. Only the Self-Test portion of the diagnostic command is 
 234  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
 236  *  \return Boolean \c true if the command completed successfully, \c false otherwise. 
 238 static bool SCSI_Command_Send_Diagnostic(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
 240         /* Check to see if the SELF TEST bit is not set */ 
 241         if (!(MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[1] & (1 << 2))) 
 243                 /* Only self-test supported - update SENSE key and fail the command */ 
 244                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 245                                SCSI_ASENSE_INVALID_FIELD_IN_CDB
, 
 246                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 251         /* Check to see if all attached Dataflash ICs are functional */ 
 252         if (!(DataflashManager_CheckDataflashOperation())) 
 254                 /* Update SENSE key with a hardware error condition and return command fail */ 
 255                 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR
, 
 256                                SCSI_ASENSE_NO_ADDITIONAL_INFORMATION
, 
 257                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 262         /* Succeed the command and update the bytes transferred counter */ 
 263         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
= 0; 
 268 /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address 
 269  *  and total number of blocks to process, then calls the appropriate low-level Dataflash routine to handle the actual 
 270  *  reading and writing of the data. 
 272  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
 273  *  \param[in] IsDataRead  Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE) 
 275  *  \return Boolean \c true if the command completed successfully, \c false otherwise. 
 277 static bool SCSI_Command_ReadWrite_10(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
, 
 278                                       const bool IsDataRead
) 
 280         uint32_t BlockAddress
; 
 281         uint16_t TotalBlocks
; 
 283         /* Check if the disk is write protected or not */ 
 284         if ((IsDataRead 
== DATA_WRITE
) && DISK_READ_ONLY
) 
 286                 /* Block address is invalid, update SENSE key and return command fail */ 
 287                 SCSI_SET_SENSE(SCSI_SENSE_KEY_DATA_PROTECT
, 
 288                                SCSI_ASENSE_WRITE_PROTECTED
, 
 289                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 294         /* Load in the 32-bit block address (SCSI uses big-endian, so have to reverse the byte order) */ 
 295         BlockAddress 
= SwapEndian_32(*(uint32_t*)&MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[2]); 
 297         /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to reverse the byte order) */ 
 298         TotalBlocks  
= SwapEndian_16(*(uint16_t*)&MSInterfaceInfo
->State
.CommandBlock
.SCSICommandData
[7]); 
 300         /* Check if the block address is outside the maximum allowable value for the LUN */ 
 301         if (BlockAddress 
>= LUN_MEDIA_BLOCKS
) 
 303                 /* Block address is invalid, update SENSE key and return command fail */ 
 304                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST
, 
 305                                SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE
, 
 306                                SCSI_ASENSEQ_NO_QUALIFIER
); 
 312         /* Adjust the given block address to the real media address based on the selected LUN */ 
 313         BlockAddress 
+= ((uint32_t)MSInterfaceInfo
->State
.CommandBlock
.LUN 
* LUN_MEDIA_BLOCKS
); 
 316         /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */ 
 317         if (IsDataRead 
== DATA_READ
) 
 318           DataflashManager_ReadBlocks(MSInterfaceInfo
, BlockAddress
, TotalBlocks
); 
 320           DataflashManager_WriteBlocks(MSInterfaceInfo
, BlockAddress
, TotalBlocks
); 
 322         /* Update the bytes transferred counter and succeed the command */ 
 323         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
-= ((uint32_t)TotalBlocks 
* VIRTUAL_MEMORY_BLOCK_SIZE
); 
 328 /** Command processing for an issued SCSI MODE SENSE (6) command. This command returns various informational pages about 
 329  *  the SCSI device, as well as the device's Write Protect status. 
 331  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with 
 333  *  \return Boolean \c true if the command completed successfully, \c false otherwise. 
 335 static bool SCSI_Command_ModeSense_6(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
 337         /* Send an empty header response with the Write Protect flag status */ 
 338         Endpoint_Write_8(0x00); 
 339         Endpoint_Write_8(0x00); 
 340         Endpoint_Write_8(DISK_READ_ONLY ? 
0x80 : 0x00); 
 341         Endpoint_Write_8(0x00); 
 344         /* Update the bytes transferred counter and succeed the command */ 
 345         MSInterfaceInfo
->State
.CommandBlock
.DataTransferLength 
-= 4;