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 /* Wait until command has been sent */
94 while(!(Pipe_IsOUTReady()));
96 /* Freeze pipe after use */
99 return PIPE_RWSTREAM_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 /* Select the IN data pipe for data reception */
112 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
115 /* Wait until data received in the IN pipe */
116 while (!(Pipe_IsINReceived()))
118 /* Check to see if a new frame has been issued (1ms elapsed) */
119 if (USB_INT_HasOccurred(USB_INT_HSOFI
))
121 /* Clear the flag and decrement the timeout period counter */
122 USB_INT_Clear(USB_INT_HSOFI
);
125 /* Check to see if the timeout period for the command has elapsed */
127 return PIPE_RWSTREAM_Timeout
;
131 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
134 /* Check if pipe stalled (command failed by device) */
135 if (Pipe_IsStalled())
137 /* Clear the stall condition on the OUT pipe */
138 USB_Host_ClearPipeStall(MASS_STORE_DATA_OUT_PIPE
);
140 return PIPE_RWSTREAM_PipeStalled
;
144 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 USB_Host_ClearPipeStall(MASS_STORE_DATA_IN_PIPE
);
153 return PIPE_RWSTREAM_PipeStalled
;
156 /* Check to see if the device was disconnected, if so exit function */
157 if (!(USB_IsConnected
))
158 return PIPE_RWSTREAM_DeviceDisconnected
;
161 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
164 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
167 return PIPE_RWSTREAM_NoError
;
170 /** Sends or receives the transaction's data stage to or from the attached device, reading or
171 * writing to the nominated buffer.
173 * \param BufferPtr Pointer to the data buffer to read from or write to
175 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
177 static uint8_t MassStore_SendReceiveData(void* BufferPtr
)
179 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
180 uint16_t BytesRem
= SCSICommandBlock
.Header
.DataTransferLength
;
182 /* Check the direction of the SCSI command data stage */
183 if (SCSICommandBlock
.Header
.Flags
& COMMAND_DIRECTION_DATA_IN
)
185 /* Select the IN data pipe for data reception */
186 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
189 /* Read in the block data from the pipe */
190 if ((ErrorCode
= Pipe_Read_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_NoError
)
193 /* Acknowledge the packet */
198 /* Select the OUT data pipe for data transmission */
199 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
202 /* Write the block data to the pipe */
203 if ((ErrorCode
= Pipe_Write_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_NoError
)
206 /* Acknowledge the packet */
209 while (!(Pipe_IsOUTReady()));
212 /* Freeze used pipe after use */
215 return PIPE_RWSTREAM_NoError
;
218 /** Routine to receive the current CSW from the device.
220 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
222 static uint8_t MassStore_GetReturnedStatus(void)
224 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
226 /* If an error in the command ocurred, abort */
227 if ((ErrorCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
230 /* Select the IN data pipe for data reception */
231 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
234 /* Load in the CSW from the attached device */
235 if ((ErrorCode
= Pipe_Read_Stream_LE(&SCSICommandStatus
, sizeof(CommandStatusWrapper_t
))) != PIPE_RWSTREAM_NoError
)
238 /* Clear the data ready for next reception */
241 /* Freeze the IN pipe after use */
244 return PIPE_RWSTREAM_NoError
;
247 /** Issues a Mass Storage class specific request to reset the attached device's Mass Storage interface,
248 * readying the device for the next CBW.
250 * \return A value from the USB_Host_SendControlErrorCodes_t enum
252 uint8_t MassStore_MassStorageReset(void)
254 USB_ControlRequest
= (USB_Request_Header_t
)
256 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
),
257 .bRequest
= REQ_MassStorageReset
,
263 /* Select the control pipe for the request transfer */
264 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
266 return USB_Host_SendControlRequest(NULL
);
269 /** Issues a Mass Storage class specific request to determine the index of the highest numbered Logical
270 * Unit in the attached device.
272 * \param MaxLUNIndex Pointer to the location that the maximum LUN index value should be stored
274 * \return A value from the USB_Host_SendControlErrorCodes_t enum
276 uint8_t MassStore_GetMaxLUN(uint8_t* const MaxLUNIndex
)
280 USB_ControlRequest
= (USB_Request_Header_t
)
282 .bmRequestType
= (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
),
283 .bRequest
= REQ_GetMaxLUN
,
289 /* Select the control pipe for the request transfer */
290 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
292 if ((ErrorCode
= USB_Host_SendControlRequest(MaxLUNIndex
)) == HOST_SENDCONTROL_SetupStalled
)
294 /* Clear the pipe stall */
297 /* Some faulty Mass Storage devices don't implement the GET_MAX_LUN request, so assume a single LUN */
304 /** Issues a SCSI Request Sense command to the attached device, to determine the current SCSI sense information. This
305 * gives error codes for the last issued SCSI command to the device.
307 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
308 * \param SensePtr Pointer to the sense data structure where the sense data from the device is to be stored
310 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
312 uint8_t MassStore_RequestSense(const uint8_t LUNIndex
, const SCSI_Request_Sense_Response_t
* const SensePtr
)
314 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
316 /* Create a CBW with a SCSI command to issue REQUEST SENSE command */
317 SCSICommandBlock
= (CommandBlockWrapper_t
)
321 .Signature
= CBW_SIGNATURE
,
322 .Tag
= MassStore_Tag
,
323 .DataTransferLength
= sizeof(SCSI_Request_Sense_Response_t
),
324 .Flags
= COMMAND_DIRECTION_DATA_IN
,
326 .SCSICommandLength
= 6
331 SCSI_CMD_REQUEST_SENSE
,
335 sizeof(SCSI_Request_Sense_Response_t
), // Allocation Length
336 0x00 // Unused (control)
340 /* Send SCSI command to the attached device */
341 MassStore_SendCommand();
343 /* Wait until data received from the device */
344 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
350 /* Read the returned sense data into the buffer */
351 if ((ReturnCode
= MassStore_SendReceiveData((uint8_t*)SensePtr
)) != PIPE_RWSTREAM_NoError
)
357 /* Read in the returned CSW from the device */
358 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
364 return PIPE_RWSTREAM_NoError
;
367 /** Issues a SCSI Device Block Read command to the attached device, to read in one or more data blocks from the
368 * storage medium into a buffer.
370 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
371 * \param BlockAddress Start block address to read from
372 * \param Blocks Number of blocks to read from the device
373 * \param BlockSize Size in bytes of each block to read
374 * \param BufferPtr Pointer to the buffer where the read data is to be written to
376 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
378 uint8_t MassStore_ReadDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
,
379 const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
)
381 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
383 /* Create a CBW with a SCSI command to read in the given blocks from the device */
384 SCSICommandBlock
= (CommandBlockWrapper_t
)
388 .Signature
= CBW_SIGNATURE
,
389 .Tag
= MassStore_Tag
,
390 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
391 .Flags
= COMMAND_DIRECTION_DATA_IN
,
393 .SCSICommandLength
= 10
399 0x00, // Unused (control bits, all off)
400 (BlockAddress
>> 24), // MSB of Block Address
401 (BlockAddress
>> 16),
403 (BlockAddress
& 0xFF), // LSB of Block Address
404 0x00, // Unused (reserved)
405 0x00, // MSB of Total Blocks to Read
406 Blocks
, // LSB of Total Blocks to Read
407 0x00 // Unused (control)
411 /* Send SCSI command to the attached device */
412 MassStore_SendCommand();
414 /* Wait until data received from the device */
415 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
421 /* Read the returned block data into the buffer */
422 if ((ReturnCode
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_NoError
)
428 /* Read in the returned CSW from the device */
429 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
435 return PIPE_RWSTREAM_NoError
;
438 /** Issues a SCSI Device Block Write command to the attached device, to write one or more data blocks to the
439 * storage medium from a buffer.
441 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
442 * \param BlockAddress Start block address to write to
443 * \param Blocks Number of blocks to write to in the device
444 * \param BlockSize Size in bytes of each block to write
445 * \param BufferPtr Pointer to the buffer where the write data is to be sourced from
447 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
449 uint8_t MassStore_WriteDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
,
450 const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
)
452 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
454 /* Create a CBW with a SCSI command to write the given blocks to the device */
455 SCSICommandBlock
= (CommandBlockWrapper_t
)
459 .Signature
= CBW_SIGNATURE
,
460 .Tag
= MassStore_Tag
,
461 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
462 .Flags
= COMMAND_DIRECTION_DATA_OUT
,
464 .SCSICommandLength
= 10
470 0x00, // Unused (control bits, all off)
471 (BlockAddress
>> 24), // MSB of Block Address
472 (BlockAddress
>> 16),
474 (BlockAddress
& 0xFF), // LSB of Block Address
475 0x00, // Unused (reserved)
476 0x00, // MSB of Total Blocks to Write
477 Blocks
, // LSB of Total Blocks to Write
478 0x00 // Unused (control)
482 /* Send SCSI command to the attached device */
483 MassStore_SendCommand();
485 /* Write the data to the device from the buffer */
486 if ((ReturnCode
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_NoError
)
492 /* Read in the returned CSW from the device */
493 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
499 return PIPE_RWSTREAM_NoError
;
502 /** Issues a SCSI Device Test Unit Ready command to the attached device, to determine if the device is ready to accept
505 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
507 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
509 uint8_t MassStore_TestUnitReady(const uint8_t LUNIndex
)
511 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
513 /* Create a CBW with a SCSI command to issue TEST UNIT READY command */
514 SCSICommandBlock
= (CommandBlockWrapper_t
)
518 .Signature
= CBW_SIGNATURE
,
519 .Tag
= MassStore_Tag
,
520 .DataTransferLength
= 0,
521 .Flags
= COMMAND_DIRECTION_DATA_IN
,
523 .SCSICommandLength
= 6
528 SCSI_CMD_TEST_UNIT_READY
,
533 0x00 // Unused (control)
537 /* Send SCSI command to the attached device */
538 MassStore_SendCommand();
540 /* Read in the returned CSW from the device */
541 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
547 return PIPE_RWSTREAM_NoError
;
550 /** Issues a SCSI Device Read Capacity command to the attached device, to determine the capacity of the
551 * given Logical Unit within the device.
553 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
554 * \param CapacityPtr Device capacity structure where the capacity data is to be stored
556 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
558 uint8_t MassStore_ReadCapacity(const uint8_t LUNIndex
, SCSI_Capacity_t
* const CapacityPtr
)
560 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
562 /* Create a CBW with a SCSI command to issue READ CAPACITY command */
563 SCSICommandBlock
= (CommandBlockWrapper_t
)
567 .Signature
= CBW_SIGNATURE
,
568 .Tag
= MassStore_Tag
,
569 .DataTransferLength
= sizeof(SCSI_Capacity_t
),
570 .Flags
= COMMAND_DIRECTION_DATA_IN
,
572 .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 SCSI command to the attached device */
591 MassStore_SendCommand();
593 /* Wait until data received from the device */
594 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
600 /* Read the returned capacity data into the buffer */
601 if ((ReturnCode
= MassStore_SendReceiveData(CapacityPtr
)) != PIPE_RWSTREAM_NoError
)
607 /* Endian-correct the read data */
608 CapacityPtr
->Blocks
= SwapEndian_32(CapacityPtr
->Blocks
);
609 CapacityPtr
->BlockSize
= SwapEndian_32(CapacityPtr
->BlockSize
);
611 /* Read in the returned CSW from the device */
612 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
618 return PIPE_RWSTREAM_NoError
;
621 /** Issues a SCSI Device Prevent/Allow Medium Removal command to the attached device, to lock the physical media from
622 * being removed. This is a legacy command for SCSI disks with removable storage (such as ZIP disks), but should still
623 * be issued before the first read or write command is sent.
625 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
626 * \param PreventRemoval Whether or not the LUN media should be locked to prevent removal or not
628 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
630 uint8_t MassStore_PreventAllowMediumRemoval(const uint8_t LUNIndex
, const bool PreventRemoval
)
632 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
634 /* Create a CBW with a SCSI command to issue PREVENT ALLOW MEDIUM REMOVAL command */
635 SCSICommandBlock
= (CommandBlockWrapper_t
)
639 .Signature
= CBW_SIGNATURE
,
640 .Tag
= MassStore_Tag
,
641 .DataTransferLength
= 0,
642 .Flags
= COMMAND_DIRECTION_DATA_OUT
,
644 .SCSICommandLength
= 6
649 SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
,
652 PreventRemoval
, // Prevent flag
654 0x00 // Unused (control)
658 /* Send SCSI command to the attached device */
659 MassStore_SendCommand();
661 /* Read in the returned CSW from the device */
662 if ((ReturnCode
= MassStore_GetReturnedStatus()))
668 return PIPE_RWSTREAM_NoError
;