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_NoError
;
78 /* Each transmission should have a unique tag value, excluding values 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_NoError
)
90 /* Send the data in the OUT pipe to the attached device */
93 while(!(Pipe_IsOUTReady()));
95 /* Freeze pipe after use */
98 return PIPE_RWSTREAM_NoError
;
101 /** Waits until the attached device is ready to accept data following a CBW, checking
102 * to ensure that the device has not stalled the transaction.
104 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
106 static uint8_t MassStore_WaitForDataReceived(void)
108 uint16_t TimeoutMSRem
= COMMAND_DATA_TIMEOUT_MS
;
110 /* Unfreeze the OUT pipe so that it can be checked */
111 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
114 /* Select the IN data pipe for data reception */
115 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
118 /* Wait until data received in the IN pipe */
119 while (!(Pipe_IsINReceived()))
121 /* Check to see if a new frame has been issued (1ms elapsed) */
124 /* Clear the flag and decrement the timeout period counter */
125 FrameElapsed
= false;
128 /* Check to see if the timeout period for the command has elapsed */
130 return PIPE_RWSTREAM_Timeout
;
133 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
135 /* Check if pipe stalled (command failed by device) */
136 if (Pipe_IsStalled())
138 /* Clear the stall condition on the OUT pipe */
139 MassStore_ClearPipeStall(MASS_STORE_DATA_OUT_PIPE
);
141 return PIPE_RWSTREAM_PipeStalled
;
144 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
146 /* Check if pipe stalled (command failed by device) */
147 if (Pipe_IsStalled())
149 /* Clear the stall condition on the IN pipe */
150 MassStore_ClearPipeStall(MASS_STORE_DATA_IN_PIPE
);
152 return PIPE_RWSTREAM_PipeStalled
;
155 /* Check to see if the device was disconnected, if so exit function */
156 if (!(USB_IsConnected
))
157 return PIPE_RWSTREAM_DeviceDisconnected
;
160 return PIPE_RWSTREAM_NoError
;
163 /** Sends or receives the transaction's data stage to or from the attached device, reading or
164 * writing to the nominated buffer.
166 * \param BufferPtr Pointer to the data buffer to read from or write to
168 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
170 static uint8_t MassStore_SendReceiveData(void* BufferPtr
)
172 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
173 uint16_t BytesRem
= SCSICommandBlock
.Header
.DataTransferLength
;
175 /* Check the direction of the SCSI command data stage */
176 if (SCSICommandBlock
.Header
.Flags
& COMMAND_DIRECTION_DATA_IN
)
178 /* Select the IN data pipe for data reception */
179 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
182 /* Read in the block data from the pipe */
183 if ((ErrorCode
= Pipe_Read_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_NoError
)
186 /* Acknowledge the packet */
191 /* Select the OUT data pipe for data transmission */
192 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
195 /* Write the block data to the pipe */
196 if ((ErrorCode
= Pipe_Write_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_NoError
)
199 /* Acknowledge the packet */
202 while (!(Pipe_IsOUTReady()));
205 /* Freeze used pipe after use */
208 return PIPE_RWSTREAM_NoError
;
211 /** Routine to receive the current CSW from the device.
213 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
215 static uint8_t MassStore_GetReturnedStatus(void)
217 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
219 /* If an error in the command ocurred, abort */
220 if ((ErrorCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
223 /* Select the IN data pipe for data reception */
224 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
227 /* Load in the CSW from the attached device */
228 if ((ErrorCode
= Pipe_Read_Stream_LE(&SCSICommandStatus
, sizeof(CommandStatusWrapper_t
))) != PIPE_RWSTREAM_NoError
)
231 /* Clear the data ready for next reception */
234 /* Freeze the IN pipe after use */
237 return PIPE_RWSTREAM_NoError
;
240 /** Clears the stall condition in the attached device on the nominated endpoint number.
242 * \param EndpointNum Endpoint number in the attached device whose stall condition is to be cleared
244 * \return A value from the USB_Host_SendControlErrorCodes_t enum
246 uint8_t MassStore_ClearPipeStall(const uint8_t EndpointNum
)
248 USB_ControlRequest
= (USB_Request_Header_t
)
250 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_STANDARD
| REQREC_ENDPOINT
),
251 .bRequest
= REQ_ClearFeature
,
252 .wValue
= FEATURE_ENDPOINT_HALT
,
253 .wIndex
= EndpointNum
,
257 /* Select the control pipe for the request transfer */
258 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
260 return USB_Host_SendControlRequest(NULL
);
263 /** Issues a Mass Storage class specific request to reset the attached device's Mass Storage interface,
264 * readying the device for the next CBW.
266 * \return A value from the USB_Host_SendControlErrorCodes_t enum
268 uint8_t MassStore_MassStorageReset(void)
270 USB_ControlRequest
= (USB_Request_Header_t
)
272 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
),
273 .bRequest
= REQ_MassStorageReset
,
279 /* Select the control pipe for the request transfer */
280 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
282 return USB_Host_SendControlRequest(NULL
);
285 /** Issues a Mass Storage class specific request to determine the index of the highest numbered Logical
286 * Unit in the attached device.
288 * \param MaxLUNIndex Pointer to the location that the maximum LUN index value should be stored
290 * \return A value from the USB_Host_SendControlErrorCodes_t enum
292 uint8_t MassStore_GetMaxLUN(uint8_t* const MaxLUNIndex
)
296 USB_ControlRequest
= (USB_Request_Header_t
)
298 .bmRequestType
= (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
),
299 .bRequest
= REQ_GetMaxLUN
,
305 /* Select the control pipe for the request transfer */
306 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
308 if ((ErrorCode
= USB_Host_SendControlRequest(MaxLUNIndex
)) == HOST_SENDCONTROL_SetupStalled
)
310 /* Clear the pipe stall */
313 /* Some faulty Mass Storage devices don't implement the GET_MAX_LUN request, so assume a single LUN */
320 /** Issues a SCSI Request Sense command to the attached device, to determine the current SCSI sense information. This
321 * gives error codes for the last issued SCSI command to the device.
323 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
324 * \param SensePtr Pointer to the sense data structure where the sense data from the device is to be stored
326 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
328 uint8_t MassStore_RequestSense(const uint8_t LUNIndex
, const SCSI_Request_Sense_Response_t
* const SensePtr
)
330 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
332 /* Create a CBW with a SCSI command to issue REQUEST SENSE command */
333 SCSICommandBlock
= (CommandBlockWrapper_t
)
337 .Signature
= CBW_SIGNATURE
,
338 .Tag
= MassStore_Tag
,
339 .DataTransferLength
= sizeof(SCSI_Request_Sense_Response_t
),
340 .Flags
= COMMAND_DIRECTION_DATA_IN
,
342 .SCSICommandLength
= 6
347 SCSI_CMD_REQUEST_SENSE
,
351 sizeof(SCSI_Request_Sense_Response_t
), // Allocation Length
352 0x00 // Unused (control)
356 /* Send SCSI command to the attached device */
357 MassStore_SendCommand();
359 /* Wait until data received from the device */
360 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
366 /* Read the returned sense data into the buffer */
367 if ((ReturnCode
= MassStore_SendReceiveData((uint8_t*)SensePtr
)) != PIPE_RWSTREAM_NoError
)
373 /* Read in the returned CSW from the device */
374 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
380 return PIPE_RWSTREAM_NoError
;
383 /** Issues a SCSI Device Block Read command to the attached device, to read in one or more data blocks from the
384 * storage medium into a buffer.
386 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
387 * \param BlockAddress Start block address to read from
388 * \param Blocks Number of blocks to read from the device
389 * \param BlockSize Size in bytes of each block to read
390 * \param BufferPtr Pointer to the buffer where the read data is to be written to
392 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
394 uint8_t MassStore_ReadDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
,
395 const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
)
397 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
399 /* Create a CBW with a SCSI command to read in the given blocks from the device */
400 SCSICommandBlock
= (CommandBlockWrapper_t
)
404 .Signature
= CBW_SIGNATURE
,
405 .Tag
= MassStore_Tag
,
406 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
407 .Flags
= COMMAND_DIRECTION_DATA_IN
,
409 .SCSICommandLength
= 10
415 0x00, // Unused (control bits, all off)
416 (BlockAddress
>> 24), // MSB of Block Address
417 (BlockAddress
>> 16),
419 (BlockAddress
& 0xFF), // LSB of Block Address
420 0x00, // Unused (reserved)
421 0x00, // MSB of Total Blocks to Read
422 Blocks
, // LSB of Total Blocks to Read
423 0x00 // Unused (control)
427 /* Send SCSI command to the attached device */
428 MassStore_SendCommand();
430 /* Wait until data received from the device */
431 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
437 /* Read the returned block data into the buffer */
438 if ((ReturnCode
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_NoError
)
444 /* Read in the returned CSW from the device */
445 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
451 return PIPE_RWSTREAM_NoError
;
454 /** Issues a SCSI Device Block Write command to the attached device, to write one or more data blocks to the
455 * storage medium from a buffer.
457 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
458 * \param BlockAddress Start block address to write to
459 * \param Blocks Number of blocks to write to in the device
460 * \param BlockSize Size in bytes of each block to write
461 * \param BufferPtr Pointer to the buffer where the write data is to be sourced from
463 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
465 uint8_t MassStore_WriteDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
,
466 const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
)
468 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
470 /* Create a CBW with a SCSI command to write the given blocks to the device */
471 SCSICommandBlock
= (CommandBlockWrapper_t
)
475 .Signature
= CBW_SIGNATURE
,
476 .Tag
= MassStore_Tag
,
477 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
478 .Flags
= COMMAND_DIRECTION_DATA_OUT
,
480 .SCSICommandLength
= 10
486 0x00, // Unused (control bits, all off)
487 (BlockAddress
>> 24), // MSB of Block Address
488 (BlockAddress
>> 16),
490 (BlockAddress
& 0xFF), // LSB of Block Address
491 0x00, // Unused (reserved)
492 0x00, // MSB of Total Blocks to Write
493 Blocks
, // LSB of Total Blocks to Write
494 0x00 // Unused (control)
498 /* Send SCSI command to the attached device */
499 MassStore_SendCommand();
501 /* Write the data to the device from the buffer */
502 if ((ReturnCode
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_NoError
)
508 /* Read in the returned CSW from the device */
509 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
515 return PIPE_RWSTREAM_NoError
;
518 /** Issues a SCSI Device Test Unit Ready command to the attached device, to determine if the device is ready to accept
521 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
523 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
525 uint8_t MassStore_TestUnitReady(const uint8_t LUNIndex
)
527 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
529 /* Create a CBW with a SCSI command to issue TEST UNIT READY command */
530 SCSICommandBlock
= (CommandBlockWrapper_t
)
534 .Signature
= CBW_SIGNATURE
,
535 .Tag
= MassStore_Tag
,
536 .DataTransferLength
= 0,
537 .Flags
= COMMAND_DIRECTION_DATA_IN
,
539 .SCSICommandLength
= 6
544 SCSI_CMD_TEST_UNIT_READY
,
549 0x00 // Unused (control)
553 /* Send SCSI command to the attached device */
554 MassStore_SendCommand();
556 /* Read in the returned CSW from the device */
557 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
563 return PIPE_RWSTREAM_NoError
;
566 /** Issues a SCSI Device Read Capacity command to the attached device, to determine the capacity of the
567 * given Logical Unit within the device.
569 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
570 * \param CapacityPtr Device capacity structure where the capacity data is to be stored
572 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
574 uint8_t MassStore_ReadCapacity(const uint8_t LUNIndex
, SCSI_Capacity_t
* const CapacityPtr
)
576 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
578 /* Create a CBW with a SCSI command to issue READ CAPACITY command */
579 SCSICommandBlock
= (CommandBlockWrapper_t
)
583 .Signature
= CBW_SIGNATURE
,
584 .Tag
= MassStore_Tag
,
585 .DataTransferLength
= sizeof(SCSI_Capacity_t
),
586 .Flags
= COMMAND_DIRECTION_DATA_IN
,
588 .SCSICommandLength
= 10
593 SCSI_CMD_READ_CAPACITY_10
,
595 0x00, // MSB of Logical block address
598 0x00, // LSB of Logical block address
601 0x00, // Partial Medium Indicator
602 0x00 // Unused (control)
606 /* Send SCSI command to the attached device */
607 MassStore_SendCommand();
609 /* Wait until data received from the device */
610 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
616 /* Read the returned capacity data into the buffer */
617 if ((ReturnCode
= MassStore_SendReceiveData(CapacityPtr
)) != PIPE_RWSTREAM_NoError
)
623 /* Endian-correct the read data */
624 CapacityPtr
->Blocks
= SwapEndian_32(CapacityPtr
->Blocks
);
625 CapacityPtr
->BlockSize
= SwapEndian_32(CapacityPtr
->BlockSize
);
627 /* Read in the returned CSW from the device */
628 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
634 return PIPE_RWSTREAM_NoError
;
637 /** Issues a SCSI Device Prevent/Allow Medium Removal command to the attached device, to lock the physical media from
638 * being removed. This is a legacy command for SCSI disks with removable storage (such as ZIP disks), but should still
639 * be issued before the first read or write command is sent.
641 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
642 * \param PreventRemoval Whether or not the LUN media should be locked to prevent removal or not
644 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
646 uint8_t MassStore_PreventAllowMediumRemoval(const uint8_t LUNIndex
, const bool PreventRemoval
)
648 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
650 /* Create a CBW with a SCSI command to issue PREVENT ALLOW MEDIUM REMOVAL command */
651 SCSICommandBlock
= (CommandBlockWrapper_t
)
655 .Signature
= CBW_SIGNATURE
,
656 .Tag
= MassStore_Tag
,
657 .DataTransferLength
= 0,
658 .Flags
= COMMAND_DIRECTION_DATA_OUT
,
660 .SCSICommandLength
= 6
665 SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
,
668 PreventRemoval
, // Prevent flag
670 0x00 // Unused (control)
674 /* Send SCSI command to the attached device */
675 MassStore_SendCommand();
677 /* Read in the returned CSW from the device */
678 if ((ReturnCode
= MassStore_GetReturnedStatus()))
684 return PIPE_RWSTREAM_NoError
;