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  *  Mass Storage Device commands, to issue MSD commands to the device for 
  34  *  reading device status, capacity, and other characteristics. This file 
  35  *  also contains block read and write functions, so that device blocks 
  36  *  can be read and written. In general, these functions would be chained 
  37  *  to a FAT library to give file-level access to an attached device's contents. 
  39  *  \note Many Mass Storage devices on the market are non-compliant to the 
  40  *        specifications and thus can prove difficult to interface with. It 
  41  *        may be necessary to retry the functions in the module several times 
  42  *        after they have returned and error to successfully send the command 
  43  *        to the device. Some devices may also need to have the stream function 
  44  *        timeout period extended beyond 100ms (some badly designed devices exceeding 
  45  *        1.5 seconds occasionally) by defining USB_STREAM_TIMEOUT_MS to a 
  46  *        larger value in the project makefile and passing it to the compiler 
  50 #define  INCLUDE_FROM_MASSSTORE_COMMANDS_C 
  51 #include "MassStoreCommands.h" 
  54 /** Current CBW to send to the device. This is automatically filled by the routines 
  55  *  in this file and is not externally accessible. 
  57 static CommandBlockWrapper_t  SCSICommandBlock
; 
  59 /** Current CSW received from the device. This is automatically filled by the routines 
  60  *  in this file and is externally accessible so that the return codes may be checked. 
  62 CommandStatusWrapper_t        SCSICommandStatus
; 
  64 /** Current Tag value used in issued CBWs to the device. This is automatically incremented 
  65  *  by the routines in this file, and is not externally accessible. 
  67 static uint32_t               MassStore_Tag 
= 1; 
  70 /** Routine to send the current CBW to the device, and increment the Tag value as needed. 
  72  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
  74 static uint8_t MassStore_SendCommand(void) 
  76         uint8_t ErrorCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
  78         /* Each transmission should have a unique tag value, excluding valued 0 and 0xFFFFFFFF */ 
  79         if (++MassStore_Tag 
== 0xFFFFFFFF) 
  82         /* Select the OUT data pipe for CBW transmission */ 
  83         Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
); 
  86         /* Write the CBW command to the OUT pipe */ 
  87         if ((ErrorCode 
= Pipe_Write_Stream_LE(&SCSICommandBlock
, sizeof(CommandBlockWrapper_t
))) != PIPE_RWSTREAM_ERROR_NoError
) 
  90         /* Send the data in the OUT pipe to the attached device */ 
  91         Pipe_ClearCurrentBank(); 
  93         /* Some buggy devices require a delay here before the pipe freezing or they will lock up */ 
  96         /* Freeze pipe after use */ 
  99         return PIPE_RWSTREAM_ERROR_NoError
; 
 102 /** Waits until the attached device is ready to accept data following a CBW, checking 
 103  *  to ensure that the device has not stalled the transaction. 
 105  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 107 static uint8_t MassStore_WaitForDataReceived(void) 
 109         uint16_t TimeoutMSRem 
= COMMAND_DATA_TIMEOUT_MS
; 
 111         /* Unfreeze the OUT pipe so that it can be checked */ 
 112         Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
); 
 115         /* Select the IN data pipe for data reception */ 
 116         Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
); 
 119         /* Wait until data received in the IN pipe */ 
 120         while (!(Pipe_ReadWriteAllowed())) 
 122                 /* Check to see if a new frame has been issued (1ms elapsed) */ 
 123                 if (USB_INT_HasOccurred(USB_INT_HSOFI
)) 
 125                         /* Clear the flag and decrement the timeout period counter */ 
 126                         USB_INT_Clear(USB_INT_HSOFI
); 
 129                         /* Check to see if the timeout period for the command has elapsed */ 
 131                           return PIPE_RWSTREAM_ERROR_Timeout
; 
 134                 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
); 
 136                 /* Check if pipe stalled (command failed by device) */ 
 137                 if (Pipe_IsStalled()) 
 139                         /* Clear the stall condition on the OUT pipe */ 
 140                         MassStore_ClearPipeStall(MASS_STORE_DATA_OUT_PIPE
); 
 142                         return PIPE_RWSTREAM_ERROR_PipeStalled
; 
 145                 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
); 
 147                 /* Check if pipe stalled (command failed by device) */ 
 148                 if (Pipe_IsStalled()) 
 150                         /* Clear the stall condition on the IN pipe */ 
 151                         MassStore_ClearPipeStall(MASS_STORE_DATA_IN_PIPE
); 
 153                         return PIPE_RWSTREAM_ERROR_PipeStalled
; 
 156                 /* Check to see if the device was disconnected, if so exit function */ 
 157                 if (!(USB_IsConnected
)) 
 158                   return PIPE_RWSTREAM_ERROR_DeviceDisconnected
; 
 161         return PIPE_RWSTREAM_ERROR_NoError
; 
 164 /** Sends or receives the transaction's data stage to or from the attached device, reading or 
 165  *  writing to the nominated buffer. 
 167  *  \param  BufferPtr  Pointer to the data buffer to read from or write to 
 169  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 171 static uint8_t MassStore_SendReceiveData(void* BufferPtr
) 
 173         uint8_t  ErrorCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 174         uint16_t BytesRem  
= SCSICommandBlock
.Header
.DataTransferLength
; 
 176         /* Check the direction of the SCSI command data stage */ 
 177         if (SCSICommandBlock
.Header
.Flags 
& COMMAND_DIRECTION_DATA_IN
) 
 179                 /* Select the IN data pipe for data reception */ 
 180                 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
); 
 183                 /* Read in the block data from the pipe */ 
 184                 if ((ErrorCode 
= Pipe_Read_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_ERROR_NoError
) 
 189                 /* Select the OUT data pipe for data transmission */ 
 190                 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
); 
 193                 /* Write the block data to the pipe */ 
 194                 if ((ErrorCode 
= Pipe_Write_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_ERROR_NoError
) 
 198         /* Acknowledge the packet */ 
 199         Pipe_ClearCurrentBank(); 
 201         /* Some buggy devices require a delay here before the pipe freezing or they will lock up */ 
 204         /* Freeze used pipe after use */ 
 207         return PIPE_RWSTREAM_ERROR_NoError
; 
 210 /** Routine to receive the current CSW from the device. 
 212  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 214 static uint8_t MassStore_GetReturnedStatus(void) 
 216         uint8_t ErrorCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 218         /* If an error in the command ocurred, abort */ 
 219         if (MassStore_WaitForDataReceived() != NoError
) 
 222         /* Select the IN data pipe for data reception */ 
 223         Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
); 
 226         /* Load in the CSW from the attached device */ 
 227         if ((ErrorCode 
= Pipe_Read_Stream_LE(&SCSICommandStatus
, sizeof(CommandStatusWrapper_t
))) != PIPE_RWSTREAM_ERROR_NoError
) 
 230         /* Clear the data ready for next reception */ 
 231         Pipe_ClearCurrentBank(); 
 233         /* Some buggy devices require a delay here before the pipe freezing or they will lock up */ 
 236         /* Freeze the IN pipe after use */ 
 239         return PIPE_RWSTREAM_ERROR_NoError
; 
 242 /** Clears the stall condition in the attached device on the nominated endpoint number. 
 244  *  \param EndpointNum  Endpoint number in the attached device whose stall condition is to be cleared 
 246  *  \return A value from the USB_Host_SendControlErrorCodes_t enum 
 248 uint8_t MassStore_ClearPipeStall(const uint8_t EndpointNum
) 
 250         USB_HostRequest 
= (USB_Host_Request_Header_t
) 
 252                         bmRequestType
: (REQDIR_HOSTTODEVICE 
| REQTYPE_STANDARD 
| REQREC_ENDPOINT
), 
 253                         bRequest
:      REQ_ClearFeature
, 
 254                         wValue
:        FEATURE_ENDPOINT_HALT
, 
 259         return USB_Host_SendControlRequest(NULL
); 
 262 /** Issues a Mass Storage class specific request to reset the attached device's Mass Storage interface, 
 263  *  readying the device for the next CBW. 
 265  *  \return A value from the USB_Host_SendControlErrorCodes_t enum 
 267 uint8_t MassStore_MassStorageReset(void) 
 269         USB_HostRequest 
= (USB_Host_Request_Header_t
) 
 271                         bmRequestType
: (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
), 
 272                         bRequest
:      REQ_MassStorageReset
, 
 278         return USB_Host_SendControlRequest(NULL
); 
 281 /** Issues a Mass Storage class specific request to determine the index of the highest numbered Logical 
 282  *  Unit in the attached device. 
 284  *  \param MaxLUNIndex  Pointer to the location that the maximum LUN index value should be stored 
 286  *  \return A value from the USB_Host_SendControlErrorCodes_t enum 
 288 uint8_t MassStore_GetMaxLUN(uint8_t* const MaxLUNIndex
) 
 292         USB_HostRequest 
= (USB_Host_Request_Header_t
) 
 294                         bmRequestType
: (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
), 
 295                         bRequest
:      REQ_GetMaxLUN
, 
 301         if ((ErrorCode 
= USB_Host_SendControlRequest(MaxLUNIndex
)) == HOST_SENDCONTROL_SetupStalled
) 
 303                 /* Clear the pipe stall */ 
 306                 /* Some faulty Mass Storage devices don't implement the GET_MAX_LUN request, so assume a single LUN */ 
 313 /** Issues a SCSI Request Sense command to the attached device, to determine the current SCSI sense information. This 
 314  *  gives error codes for the last issued SCSI command to the device. 
 316  *  \param LUNIndex  Index of the LUN inside the device the command is being addressed to 
 317  *  \param SensePtr  Pointer to the sense data structure where the sense data from the device is to be stored 
 319  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 321 uint8_t MassStore_RequestSense(const uint8_t LUNIndex
, const SCSI_Request_Sense_Response_t
* const SensePtr
) 
 323         uint8_t ReturnCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 325         /* Create a CBW with a SCSI command to issue REQUEST SENSE command */ 
 326         SCSICommandBlock 
= (CommandBlockWrapper_t
) 
 330                                         Signature
:          CBW_SIGNATURE
, 
 332                                         DataTransferLength
: sizeof(SCSI_Request_Sense_Response_t
), 
 333                                         Flags
:              COMMAND_DIRECTION_DATA_IN
, 
 340                                         SCSI_CMD_REQUEST_SENSE
, 
 344                                         sizeof(SCSI_Request_Sense_Response_t
), // Allocation Length 
 345                                         0x00                    // Unused (control) 
 349         /* Send SCSI command to the attached device */ 
 350         MassStore_SendCommand(); 
 352         /* Wait until data received from the device */ 
 353         if ((ReturnCode 
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_ERROR_NoError
) 
 359         /* Read the returned sense data into the buffer */ 
 360         if ((ReturnCode 
= MassStore_SendReceiveData((uint8_t*)SensePtr
)) != PIPE_RWSTREAM_ERROR_NoError
) 
 366         /* Read in the returned CSW from the device */ 
 367         if ((ReturnCode 
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_ERROR_NoError
) 
 373         return PIPE_RWSTREAM_ERROR_NoError
; 
 376 /** Issues a SCSI Device Block Read command to the attached device, to read in one or more data blocks from the 
 377  *  storage medium into a buffer. 
 379  *  \param LUNIndex      Index of the LUN inside the device the command is being addressed to 
 380  *  \param BlockAddress  Start block address to read from 
 381  *  \param Blocks        Number of blocks to read from the device 
 382  *  \param BlockSize     Size in bytes of each block to read 
 383  *  \param BufferPtr     Pointer to the buffer where the read data is to be written to 
 385  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 387 uint8_t MassStore_ReadDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
, 
 388                                   const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
) 
 390         uint8_t ReturnCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 392         /* Create a CBW with a SCSI command to read in the given blocks from the device */ 
 393         SCSICommandBlock 
= (CommandBlockWrapper_t
) 
 397                                         Signature
:          CBW_SIGNATURE
, 
 399                                         DataTransferLength
: ((uint32_t)Blocks 
* BlockSize
), 
 400                                         Flags
:              COMMAND_DIRECTION_DATA_IN
, 
 402                                         SCSICommandLength
:  10 
 408                                         0x00,                   // Unused (control bits, all off) 
 409                                         (BlockAddress 
>> 24),   // MSB of Block Address 
 410                                         (BlockAddress 
>> 16), 
 412                                         (BlockAddress 
& 0xFF),  // LSB of Block Address 
 413                                         0x00,                   // Unused (reserved) 
 414                                         0x00,                   // MSB of Total Blocks to Read 
 415                                         Blocks
,                 // LSB of Total Blocks to Read 
 416                                         0x00                    // Unused (control) 
 420         /* Send SCSI command to the attached device */ 
 421         MassStore_SendCommand(); 
 423         /* Wait until data received from the device */ 
 424         if ((ReturnCode 
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_ERROR_NoError
) 
 430         /* Read the returned block data into the buffer */ 
 431         if ((ReturnCode 
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_ERROR_NoError
) 
 437         /* Read in the returned CSW from the device */ 
 438         if ((ReturnCode 
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_ERROR_NoError
) 
 444         return PIPE_RWSTREAM_ERROR_NoError
; 
 447 /** Issues a SCSI Device Block Write command to the attached device, to write one or more data blocks to the 
 448  *  storage medium from a buffer. 
 450  *  \param LUNIndex      Index of the LUN inside the device the command is being addressed to 
 451  *  \param BlockAddress  Start block address to write to 
 452  *  \param Blocks        Number of blocks to write to in the device 
 453  *  \param BlockSize     Size in bytes of each block to write 
 454  *  \param BufferPtr     Pointer to the buffer where the write data is to be sourced from 
 456  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 458 uint8_t MassStore_WriteDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
, 
 459                                    const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
) 
 461         uint8_t ReturnCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 463         /* Create a CBW with a SCSI command to write the given blocks to the device */ 
 464         SCSICommandBlock 
= (CommandBlockWrapper_t
) 
 468                                         Signature
:          CBW_SIGNATURE
, 
 470                                         DataTransferLength
: ((uint32_t)Blocks 
* BlockSize
), 
 471                                         Flags
:              COMMAND_DIRECTION_DATA_OUT
, 
 473                                         SCSICommandLength
:  10 
 479                                         0x00,                   // Unused (control bits, all off) 
 480                                         (BlockAddress 
>> 24),   // MSB of Block Address 
 481                                         (BlockAddress 
>> 16), 
 483                                         (BlockAddress 
& 0xFF),  // LSB of Block Address 
 484                                         0x00,                   // Unused (reserved) 
 485                                         0x00,                   // MSB of Total Blocks to Write 
 486                                         Blocks
,                 // LSB of Total Blocks to Write 
 487                                         0x00                    // Unused (control) 
 491         /* Send SCSI command to the attached device */ 
 492         MassStore_SendCommand(); 
 494         /* Write the data to the device from the buffer */ 
 495         if ((ReturnCode 
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_ERROR_NoError
) 
 501         /* Read in the returned CSW from the device */ 
 502         if ((ReturnCode 
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_ERROR_NoError
) 
 508         return PIPE_RWSTREAM_ERROR_NoError
; 
 511 /** Issues a SCSI Device Test Unit Ready command to the attached device, to determine if the device is ready to accept 
 514  *  \param LUNIndex      Index of the LUN inside the device the command is being addressed to 
 516  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 518 uint8_t MassStore_TestUnitReady(const uint8_t LUNIndex
) 
 520         uint8_t ReturnCode 
= PIPE_RWSTREAM_ERROR_NoError
;        
 522         /* Create a CBW with a SCSI command to issue TEST UNIT READY command */ 
 523         SCSICommandBlock 
= (CommandBlockWrapper_t
) 
 527                                         Signature
:          CBW_SIGNATURE
, 
 529                                         DataTransferLength
: 0, 
 530                                         Flags
:              COMMAND_DIRECTION_DATA_IN
, 
 537                                         SCSI_CMD_TEST_UNIT_READY
, 
 542                                         0x00                    // Unused (control) 
 546         /* Send SCSI command to the attached device */ 
 547         MassStore_SendCommand(); 
 549         /* Read in the returned CSW from the device */ 
 550         if ((ReturnCode 
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_ERROR_NoError
) 
 556         return PIPE_RWSTREAM_ERROR_NoError
; 
 559 /** Issues a SCSI Device Read Capacity command to the attached device, to determine the capacity of the 
 560  *  given Logical Unit within the device. 
 562  *  \param LUNIndex     Index of the LUN inside the device the command is being addressed to 
 563  *  \param CapacityPtr  Device capacity structure where the capacity data is to be stored 
 565  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 567 uint8_t MassStore_ReadCapacity(const uint8_t LUNIndex
, SCSI_Capacity_t
* const CapacityPtr
) 
 569         uint8_t ReturnCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 571         /* Create a CBW with a SCSI command to issue READ CAPACITY command */ 
 572         SCSICommandBlock 
= (CommandBlockWrapper_t
) 
 576                                         Signature
:          CBW_SIGNATURE
, 
 578                                         DataTransferLength
: 8, 
 579                                         Flags
:              COMMAND_DIRECTION_DATA_IN
, 
 581                                         SCSICommandLength
:  10 
 586                                         SCSI_CMD_READ_CAPACITY_10
, 
 588                                         0x00,                   // MSB of Logical block address 
 591                                         0x00,                   // LSB of Logical block address 
 594                                         0x00,                   // Partial Medium Indicator 
 595                                         0x00                    // Unused (control) 
 599         /* Send SCSI command to the attached device */ 
 600         MassStore_SendCommand(); 
 602         /* Wait until data received from the device */ 
 603         if ((ReturnCode 
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_ERROR_NoError
) 
 609         /* Read the returned capacity data into the buffer */ 
 610         if ((ReturnCode 
= MassStore_SendReceiveData(CapacityPtr
)) != PIPE_RWSTREAM_ERROR_NoError
) 
 616         /* Endian-correct the read data */ 
 617         CapacityPtr
->Blocks    
= SwapEndian_32(CapacityPtr
->Blocks
); 
 618         CapacityPtr
->BlockSize 
= SwapEndian_32(CapacityPtr
->BlockSize
); 
 620         /* Read in the returned CSW from the device */ 
 621         if ((ReturnCode 
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_ERROR_NoError
) 
 627         return PIPE_RWSTREAM_ERROR_NoError
; 
 630 /** Issues a SCSI Device Prevent/Allow Medium Removal command to the attached device, to lock the physical media from 
 631  *  being removed. This is a legacy command for SCSI disks with removable storage (such as ZIP disks), but should still 
 632  *  be issued before the first read or write command is sent. 
 634  *  \param LUNIndex        Index of the LUN inside the device the command is being addressed to 
 635  *  \param PreventRemoval  Whether or not the LUN media should be locked to prevent removal or not 
 637  *  \return A value from the Pipe_Stream_RW_ErrorCodes_t enum 
 639 uint8_t MassStore_PreventAllowMediumRemoval(const uint8_t LUNIndex
, const bool PreventRemoval
) 
 641         uint8_t ReturnCode 
= PIPE_RWSTREAM_ERROR_NoError
; 
 643         /* Create a CBW with a SCSI command to issue PREVENT ALLOW MEDIUM REMOVAL command */ 
 644         SCSICommandBlock 
= (CommandBlockWrapper_t
) 
 648                                         Signature
:          CBW_SIGNATURE
, 
 650                                         DataTransferLength
: 0, 
 651                                         Flags
:              COMMAND_DIRECTION_DATA_OUT
, 
 658                                         SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
, 
 661                                         PreventRemoval
,         // Prevent flag 
 663                                         0x00                    // Unused (control) 
 667         /* Send SCSI command to the attached device */ 
 668         MassStore_SendCommand(); 
 670         /* Read in the returned CSW from the device */ 
 671         if ((ReturnCode 
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_ERROR_NoError
) 
 677         return PIPE_RWSTREAM_ERROR_NoError
;