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 * 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"
53 /** Current Tag value used in issued CBWs to the device. This is automatically incremented
54 * each time a command is sent, and is not externally accessible.
56 static uint32_t MassStore_Tag
= 1;
59 /** Routine to send the current CBW to the device, and increment the Tag value as needed.
61 * \param[in] SCSICommandBlock Pointer to a SCSI command block structure to send to the attached device
62 * \param[in,out] BufferPtr Pointer to a buffer for the data to send or receive to/from the device, or NULL if no data
64 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
66 static uint8_t MassStore_SendCommand(MS_CommandBlockWrapper_t
* const SCSICommandBlock
,
69 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
71 /* Wrap Tag value when invalid - MS class defines tag values of 0 and 0xFFFFFFFF to be invalid */
72 if (++MassStore_Tag
== 0xFFFFFFFF)
75 /* Each transmission should have a unique tag value, increment before use */
76 SCSICommandBlock
->Tag
= MassStore_Tag
;
78 /* Select the OUT data pipe for CBW transmission */
79 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
82 /* Write the CBW command to the OUT pipe */
83 if ((ErrorCode
= Pipe_Write_Stream_LE(SCSICommandBlock
, sizeof(MS_CommandBlockWrapper_t
), NULL
)) !=
84 PIPE_RWSTREAM_NoError
)
90 /* Send the data in the OUT pipe to the attached device */
93 /* Wait until command has been sent */
94 Pipe_WaitUntilReady();
96 /* Freeze pipe after use */
99 if (BufferPtr
!= NULL
)
101 /* Transfer the requested data (if any) to or from the device */
102 ErrorCode
= MassStore_SendReceiveData(SCSICommandBlock
, (void*)BufferPtr
);
104 /* Only fail completely if the transfer fails without a STALL, as a logical STALL can be recovered from */
105 if ((ErrorCode
!= PIPE_RWSTREAM_NoError
) && (ErrorCode
!= PIPE_RWSTREAM_PipeStalled
))
112 /* Retrieve the returned SCSI status from the device */
113 MS_CommandStatusWrapper_t SCSIStatusBlock
;
114 return MassStore_GetReturnedStatus(&SCSIStatusBlock
);
117 /** Waits until the attached device is ready to accept data following a CBW, checking
118 * to ensure that the device has not stalled the transaction.
120 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
122 static uint8_t MassStore_WaitForDataReceived(void)
124 uint16_t TimeoutMSRem
= COMMAND_DATA_TIMEOUT_MS
;
125 uint16_t PreviousFrameNumber
= USB_Host_GetFrameNumber();
127 /* Select the IN data pipe for data reception */
128 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
131 /* Wait until data received in the IN pipe */
132 while (!(Pipe_IsINReceived()))
134 uint16_t CurrentFrameNumber
= USB_Host_GetFrameNumber();
136 /* Check to see if a new frame has been issued (1ms elapsed) */
137 if (CurrentFrameNumber
!= PreviousFrameNumber
)
139 /* Save the new frame number and decrement the timeout period */
140 PreviousFrameNumber
= CurrentFrameNumber
;
143 /* Check to see if the timeout period for the command has elapsed */
145 return PIPE_RWSTREAM_Timeout
;
149 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
152 /* Check if pipe stalled (command failed by device) */
153 if (Pipe_IsStalled())
155 /* Clear the stall condition on the OUT pipe */
156 USB_Host_ClearEndpointStall(Pipe_GetBoundEndpointAddress());
158 return PIPE_RWSTREAM_PipeStalled
;
162 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
165 /* Check if pipe stalled (command failed by device) */
166 if (Pipe_IsStalled())
168 /* Clear the stall condition on the IN pipe */
169 USB_Host_ClearEndpointStall(Pipe_GetBoundEndpointAddress());
171 return PIPE_RWSTREAM_PipeStalled
;
174 /* Check to see if the device was disconnected, if so exit function */
175 if (USB_HostState
== HOST_STATE_Unattached
)
176 return PIPE_RWSTREAM_DeviceDisconnected
;
179 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
182 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
185 return PIPE_RWSTREAM_NoError
;
188 /** Sends or receives the transaction's data stage to or from the attached device, reading or
189 * writing to the nominated buffer.
191 * \param[in] SCSICommandBlock Pointer to a SCSI command block structure being sent to the attached device
192 * \param[in,out] BufferPtr Pointer to the data buffer to read from or write to
194 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
196 static uint8_t MassStore_SendReceiveData(MS_CommandBlockWrapper_t
* const SCSICommandBlock
,
199 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
200 uint16_t BytesRem
= SCSICommandBlock
->DataTransferLength
;
202 /* Check the direction of the SCSI command data stage */
203 if (SCSICommandBlock
->Flags
& MS_COMMAND_DIR_DATA_IN
)
205 /* Wait until the device has replied with some data */
206 if ((ErrorCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
209 /* Select the IN data pipe for data reception */
210 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
213 /* Read in the block data from the pipe */
214 if ((ErrorCode
= Pipe_Read_Stream_LE(BufferPtr
, BytesRem
, NULL
)) != PIPE_RWSTREAM_NoError
)
217 /* Acknowledge the packet */
222 /* Select the OUT data pipe for data transmission */
223 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
226 /* Write the block data to the pipe */
227 if ((ErrorCode
= Pipe_Write_Stream_LE(BufferPtr
, BytesRem
, NULL
)) != PIPE_RWSTREAM_NoError
)
230 /* Acknowledge the packet */
233 while (!(Pipe_IsOUTReady()))
235 if (USB_HostState
== HOST_STATE_Unattached
)
236 return PIPE_RWSTREAM_DeviceDisconnected
;
240 /* Freeze used pipe after use */
243 return PIPE_RWSTREAM_NoError
;
246 /** Routine to receive the current CSW from the device.
248 * \param[out] SCSICommandStatus Pointer to a destination where the returned status data should be stored
250 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
252 static uint8_t MassStore_GetReturnedStatus(MS_CommandStatusWrapper_t
* const SCSICommandStatus
)
254 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
256 /* If an error in the command occurred, abort */
257 if ((ErrorCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
260 /* Select the IN data pipe for data reception */
261 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
264 /* Load in the CSW from the attached device */
265 if ((ErrorCode
= Pipe_Read_Stream_LE(SCSICommandStatus
, sizeof(MS_CommandStatusWrapper_t
), NULL
)) !=
266 PIPE_RWSTREAM_NoError
)
271 /* Clear the data ready for next reception */
274 /* Freeze the IN pipe after use */
277 /* Check to see if command failed */
278 if (SCSICommandStatus
->Status
!= MS_SCSI_COMMAND_Pass
)
279 ErrorCode
= MASS_STORE_SCSI_COMMAND_FAILED
;
284 /** Issues a Mass Storage class specific request to reset the attached device's Mass Storage interface,
285 * readying the device for the next CBW. The Data endpoints are cleared of any STALL condition once this
286 * command completes sucessfuly.
288 * \return A value from the USB_Host_SendControlErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
290 uint8_t MassStore_MassStorageReset(void)
294 USB_ControlRequest
= (USB_Request_Header_t
)
296 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
),
297 .bRequest
= MS_REQ_MassStorageReset
,
303 /* Select the control pipe for the request transfer */
304 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
306 if ((ErrorCode
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
)
309 /* Select first data pipe to clear STALL condition if one exists */
310 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
312 if ((ErrorCode
= USB_Host_ClearEndpointStall(Pipe_GetBoundEndpointAddress())) != HOST_SENDCONTROL_Successful
)
315 /* Select second data pipe to clear STALL condition if one exists */
316 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
318 if ((ErrorCode
= USB_Host_ClearEndpointStall(Pipe_GetBoundEndpointAddress())) != HOST_SENDCONTROL_Successful
)
321 return HOST_SENDCONTROL_Successful
;
324 /** Issues a Mass Storage class specific request to determine the index of the highest numbered Logical
325 * Unit in the attached device.
327 * \note Some devices do not support this request, and will STALL it when issued. To get around this,
328 * on unsupported devices the max LUN index will be reported as zero and no error will be returned
329 * if the device STALLs the request.
331 * \param[out] MaxLUNIndex Pointer to the location that the maximum LUN index value should be stored
333 * \return A value from the USB_Host_SendControlErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
335 uint8_t MassStore_GetMaxLUN(uint8_t* const MaxLUNIndex
)
339 USB_ControlRequest
= (USB_Request_Header_t
)
341 .bmRequestType
= (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
),
342 .bRequest
= MS_REQ_GetMaxLUN
,
348 /* Select the control pipe for the request transfer */
349 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
351 if ((ErrorCode
= USB_Host_SendControlRequest(MaxLUNIndex
)) == HOST_SENDCONTROL_SetupStalled
)
353 /* Clear the pipe stall */
356 /* Some faulty Mass Storage devices don't implement the GET_MAX_LUN request, so assume a single LUN */
359 /* Clear the error, and pretend the request executed correctly if the device STALLed it */
360 ErrorCode
= HOST_SENDCONTROL_Successful
;
366 /** Issues a SCSI Inquiry command to the attached device, to determine the device's information. This
367 * gives information on the device's capabilities.
369 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
370 * \param[out] InquiryPtr Pointer to the inquiry data structure where the inquiry data from the device is to be stored
372 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
374 uint8_t MassStore_Inquiry(const uint8_t LUNIndex
,
375 SCSI_Inquiry_Response_t
* const InquiryPtr
)
377 /* Create a CBW with a SCSI command to issue INQUIRY command */
378 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
380 .Signature
= MS_CBW_SIGNATURE
,
381 .DataTransferLength
= sizeof(SCSI_Inquiry_Response_t
),
382 .Flags
= MS_COMMAND_DIR_DATA_IN
,
384 .SCSICommandLength
= 6,
391 sizeof(SCSI_Inquiry_Response_t
), // Allocation Length
392 0x00 // Unused (control)
396 /* Send the command and any data to the attached device */
397 return MassStore_SendCommand(&SCSICommandBlock
, InquiryPtr
);
400 /** Issues a SCSI Request Sense command to the attached device, to determine the current SCSI sense information. This
401 * gives error codes for the last issued SCSI command to the device.
403 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
404 * \param[out] SensePtr Pointer to the sense data structure where the sense data from the device is to be stored
406 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
408 uint8_t MassStore_RequestSense(const uint8_t LUNIndex
,
409 SCSI_Request_Sense_Response_t
* const SensePtr
)
411 /* Create a CBW with a SCSI command to issue REQUEST SENSE command */
412 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
414 .Signature
= MS_CBW_SIGNATURE
,
415 .DataTransferLength
= sizeof(SCSI_Request_Sense_Response_t
),
416 .Flags
= MS_COMMAND_DIR_DATA_IN
,
418 .SCSICommandLength
= 6,
421 SCSI_CMD_REQUEST_SENSE
,
425 sizeof(SCSI_Request_Sense_Response_t
), // Allocation Length
426 0x00 // Unused (control)
430 /* Send the command and any data to the attached device */
431 return MassStore_SendCommand(&SCSICommandBlock
, SensePtr
);
434 /** Issues a SCSI Device Block Read command to the attached device, to read in one or more data blocks from the
435 * storage medium into a buffer.
437 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
438 * \param[in] BlockAddress Start block address to read from
439 * \param[in] Blocks Number of blocks to read from the device
440 * \param[in] BlockSize Size in bytes of each block to read
441 * \param[out] BufferPtr Pointer to the buffer where the read data is to be written to
443 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
445 uint8_t MassStore_ReadDeviceBlock(const uint8_t LUNIndex
,
446 const uint32_t BlockAddress
,
447 const uint8_t Blocks
,
448 const uint16_t BlockSize
,
451 /* Create a CBW with a SCSI command to read in the given blocks from the device */
452 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
454 .Signature
= MS_CBW_SIGNATURE
,
455 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
456 .Flags
= MS_COMMAND_DIR_DATA_IN
,
458 .SCSICommandLength
= 10,
462 0x00, // Unused (control bits, all off)
463 (BlockAddress
>> 24), // MSB of Block Address
464 (BlockAddress
>> 16),
466 (BlockAddress
& 0xFF), // LSB of Block Address
468 0x00, // MSB of Total Blocks to Read
469 Blocks
, // LSB of Total Blocks to Read
470 0x00 // Unused (control)
474 /* Send the command and any data to the attached device */
475 return MassStore_SendCommand(&SCSICommandBlock
, BufferPtr
);
478 /** Issues a SCSI Device Block Write command to the attached device, to write one or more data blocks to the
479 * storage medium from a buffer.
481 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
482 * \param[in] BlockAddress Start block address to write to
483 * \param[in] Blocks Number of blocks to write to in the device
484 * \param[in] BlockSize Size in bytes of each block to write
485 * \param[in] BufferPtr Pointer to the buffer where the write data is to be sourced from
487 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
489 uint8_t MassStore_WriteDeviceBlock(const uint8_t LUNIndex
,
490 const uint32_t BlockAddress
,
491 const uint8_t Blocks
,
492 const uint16_t BlockSize
,
495 /* Create a CBW with a SCSI command to write the given blocks to the device */
496 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
498 .Signature
= MS_CBW_SIGNATURE
,
499 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
500 .Flags
= MS_COMMAND_DIR_DATA_OUT
,
502 .SCSICommandLength
= 10,
506 0x00, // Unused (control bits, all off)
507 (BlockAddress
>> 24), // MSB of Block Address
508 (BlockAddress
>> 16),
510 (BlockAddress
& 0xFF), // LSB of Block Address
511 0x00, // Unused (reserved)
512 0x00, // MSB of Total Blocks to Write
513 Blocks
, // LSB of Total Blocks to Write
514 0x00 // Unused (control)
518 /* Send the command and any data to the attached device */
519 return MassStore_SendCommand(&SCSICommandBlock
, BufferPtr
);
522 /** Issues a SCSI Device Test Unit Ready command to the attached device, to determine if the device is ready to accept
525 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
527 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
529 uint8_t MassStore_TestUnitReady(const uint8_t LUNIndex
)
531 /* Create a CBW with a SCSI command to issue TEST UNIT READY command */
532 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
534 .Signature
= MS_CBW_SIGNATURE
,
535 .DataTransferLength
= 0,
536 .Flags
= MS_COMMAND_DIR_DATA_IN
,
538 .SCSICommandLength
= 6,
541 SCSI_CMD_TEST_UNIT_READY
,
546 0x00 // Unused (control)
550 /* Send the command and any data to the attached device */
551 return MassStore_SendCommand(&SCSICommandBlock
, NULL
);
554 /** Issues a SCSI Device Read Capacity command to the attached device, to determine the capacity of the
555 * given Logical Unit within the device.
557 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
558 * \param[out] CapacityPtr Device capacity structure where the capacity data is to be stored
560 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
562 uint8_t MassStore_ReadCapacity(const uint8_t LUNIndex
,
563 SCSI_Capacity_t
* const CapacityPtr
)
565 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
567 /* Create a CBW with a SCSI command to issue READ CAPACITY command */
568 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
570 .Signature
= MS_CBW_SIGNATURE
,
571 .DataTransferLength
= sizeof(SCSI_Capacity_t
),
572 .Flags
= MS_COMMAND_DIR_DATA_IN
,
574 .SCSICommandLength
= 10,
577 SCSI_CMD_READ_CAPACITY_10
,
579 0x00, // MSB of Logical block address
582 0x00, // LSB of Logical block address
585 0x00, // Partial Medium Indicator
586 0x00 // Unused (control)
590 /* Send the command and any data to the attached device */
591 if ((ErrorCode
= MassStore_SendCommand(&SCSICommandBlock
, CapacityPtr
)) != PIPE_RWSTREAM_NoError
)
594 /* Endian-correct the read data */
595 CapacityPtr
->Blocks
= SwapEndian_32(CapacityPtr
->Blocks
);
596 CapacityPtr
->BlockSize
= SwapEndian_32(CapacityPtr
->BlockSize
);
601 /** Issues a SCSI Device Prevent/Allow Medium Removal command to the attached device, to lock the physical media from
602 * being removed. This is a legacy command for SCSI disks with removable storage (such as ZIP disks), but should still
603 * be issued before the first read or write command is sent.
605 * \param[in] LUNIndex Index of the LUN inside the device the command is being addressed to
606 * \param[in] PreventRemoval Whether or not the LUN media should be locked to prevent removal or not
608 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum, or MASS_STORE_SCSI_COMMAND_FAILED if the SCSI command fails
610 uint8_t MassStore_PreventAllowMediumRemoval(const uint8_t LUNIndex
,
611 const bool PreventRemoval
)
613 /* Create a CBW with a SCSI command to issue PREVENT ALLOW MEDIUM REMOVAL command */
614 MS_CommandBlockWrapper_t SCSICommandBlock
= (MS_CommandBlockWrapper_t
)
616 .Signature
= MS_CBW_SIGNATURE
,
617 .DataTransferLength
= 0,
618 .Flags
= MS_COMMAND_DIR_DATA_OUT
,
620 .SCSICommandLength
= 6,
623 SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
,
626 PreventRemoval
, // Prevent flag
628 0x00 // Unused (control)
632 /* Send the command and any data to the attached device */
633 return MassStore_SendCommand(&SCSICommandBlock
, NULL
);