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 /* Select the IN data pipe for data reception */
111 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
114 /* Wait until data received in the IN pipe */
115 while (!(Pipe_IsINReceived()))
117 /* Check to see if a new frame has been issued (1ms elapsed) */
118 if (USB_INT_HasOccurred(USB_INT_HSOFI
))
120 /* Clear the flag and decrement the timeout period counter */
121 USB_INT_Clear(USB_INT_HSOFI
);
124 /* Check to see if the timeout period for the command has elapsed */
126 return PIPE_RWSTREAM_Timeout
;
130 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
133 /* Check if pipe stalled (command failed by device) */
134 if (Pipe_IsStalled())
136 /* Clear the stall condition on the OUT pipe */
137 USB_Host_ClearPipeStall(MASS_STORE_DATA_OUT_PIPE
);
139 return PIPE_RWSTREAM_PipeStalled
;
143 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 USB_Host_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 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
163 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
166 return PIPE_RWSTREAM_NoError
;
169 /** Sends or receives the transaction's data stage to or from the attached device, reading or
170 * writing to the nominated buffer.
172 * \param BufferPtr Pointer to the data buffer to read from or write to
174 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
176 static uint8_t MassStore_SendReceiveData(void* BufferPtr
)
178 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
179 uint16_t BytesRem
= SCSICommandBlock
.Header
.DataTransferLength
;
181 /* Check the direction of the SCSI command data stage */
182 if (SCSICommandBlock
.Header
.Flags
& COMMAND_DIRECTION_DATA_IN
)
184 /* Select the IN data pipe for data reception */
185 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
188 /* Read in the block data from the pipe */
189 if ((ErrorCode
= Pipe_Read_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_NoError
)
192 /* Acknowledge the packet */
197 /* Select the OUT data pipe for data transmission */
198 Pipe_SelectPipe(MASS_STORE_DATA_OUT_PIPE
);
201 /* Write the block data to the pipe */
202 if ((ErrorCode
= Pipe_Write_Stream_LE(BufferPtr
, BytesRem
)) != PIPE_RWSTREAM_NoError
)
205 /* Acknowledge the packet */
208 while (!(Pipe_IsOUTReady()));
211 /* Freeze used pipe after use */
214 return PIPE_RWSTREAM_NoError
;
217 /** Routine to receive the current CSW from the device.
219 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
221 static uint8_t MassStore_GetReturnedStatus(void)
223 uint8_t ErrorCode
= PIPE_RWSTREAM_NoError
;
225 /* If an error in the command ocurred, abort */
226 if ((ErrorCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
229 /* Select the IN data pipe for data reception */
230 Pipe_SelectPipe(MASS_STORE_DATA_IN_PIPE
);
233 /* Load in the CSW from the attached device */
234 if ((ErrorCode
= Pipe_Read_Stream_LE(&SCSICommandStatus
, sizeof(CommandStatusWrapper_t
))) != PIPE_RWSTREAM_NoError
)
237 /* Clear the data ready for next reception */
240 /* Freeze the IN pipe after use */
243 return PIPE_RWSTREAM_NoError
;
246 /** Issues a Mass Storage class specific request to reset the attached device's Mass Storage interface,
247 * readying the device for the next CBW.
249 * \return A value from the USB_Host_SendControlErrorCodes_t enum
251 uint8_t MassStore_MassStorageReset(void)
253 USB_ControlRequest
= (USB_Request_Header_t
)
255 .bmRequestType
= (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
),
256 .bRequest
= REQ_MassStorageReset
,
262 /* Select the control pipe for the request transfer */
263 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
265 return USB_Host_SendControlRequest(NULL
);
268 /** Issues a Mass Storage class specific request to determine the index of the highest numbered Logical
269 * Unit in the attached device.
271 * \param MaxLUNIndex Pointer to the location that the maximum LUN index value should be stored
273 * \return A value from the USB_Host_SendControlErrorCodes_t enum
275 uint8_t MassStore_GetMaxLUN(uint8_t* const MaxLUNIndex
)
279 USB_ControlRequest
= (USB_Request_Header_t
)
281 .bmRequestType
= (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
),
282 .bRequest
= REQ_GetMaxLUN
,
288 /* Select the control pipe for the request transfer */
289 Pipe_SelectPipe(PIPE_CONTROLPIPE
);
291 if ((ErrorCode
= USB_Host_SendControlRequest(MaxLUNIndex
)) == HOST_SENDCONTROL_SetupStalled
)
293 /* Clear the pipe stall */
296 /* Some faulty Mass Storage devices don't implement the GET_MAX_LUN request, so assume a single LUN */
303 /** Issues a SCSI Request Sense command to the attached device, to determine the current SCSI sense information. This
304 * gives error codes for the last issued SCSI command to the device.
306 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
307 * \param SensePtr Pointer to the sense data structure where the sense data from the device is to be stored
309 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
311 uint8_t MassStore_RequestSense(const uint8_t LUNIndex
, const SCSI_Request_Sense_Response_t
* const SensePtr
)
313 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
315 /* Create a CBW with a SCSI command to issue REQUEST SENSE command */
316 SCSICommandBlock
= (CommandBlockWrapper_t
)
320 .Signature
= CBW_SIGNATURE
,
321 .Tag
= MassStore_Tag
,
322 .DataTransferLength
= sizeof(SCSI_Request_Sense_Response_t
),
323 .Flags
= COMMAND_DIRECTION_DATA_IN
,
325 .SCSICommandLength
= 6
330 SCSI_CMD_REQUEST_SENSE
,
334 sizeof(SCSI_Request_Sense_Response_t
), // Allocation Length
335 0x00 // Unused (control)
339 /* Send SCSI command to the attached device */
340 MassStore_SendCommand();
342 /* Wait until data received from the device */
343 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
349 /* Read the returned sense data into the buffer */
350 if ((ReturnCode
= MassStore_SendReceiveData((uint8_t*)SensePtr
)) != PIPE_RWSTREAM_NoError
)
356 /* Read in the returned CSW from the device */
357 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
363 return PIPE_RWSTREAM_NoError
;
366 /** Issues a SCSI Device Block Read command to the attached device, to read in one or more data blocks from the
367 * storage medium into a buffer.
369 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
370 * \param BlockAddress Start block address to read from
371 * \param Blocks Number of blocks to read from the device
372 * \param BlockSize Size in bytes of each block to read
373 * \param BufferPtr Pointer to the buffer where the read data is to be written to
375 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
377 uint8_t MassStore_ReadDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
,
378 const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
)
380 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
382 /* Create a CBW with a SCSI command to read in the given blocks from the device */
383 SCSICommandBlock
= (CommandBlockWrapper_t
)
387 .Signature
= CBW_SIGNATURE
,
388 .Tag
= MassStore_Tag
,
389 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
390 .Flags
= COMMAND_DIRECTION_DATA_IN
,
392 .SCSICommandLength
= 10
398 0x00, // Unused (control bits, all off)
399 (BlockAddress
>> 24), // MSB of Block Address
400 (BlockAddress
>> 16),
402 (BlockAddress
& 0xFF), // LSB of Block Address
403 0x00, // Unused (reserved)
404 0x00, // MSB of Total Blocks to Read
405 Blocks
, // LSB of Total Blocks to Read
406 0x00 // Unused (control)
410 /* Send SCSI command to the attached device */
411 MassStore_SendCommand();
413 /* Wait until data received from the device */
414 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
420 /* Read the returned block data into the buffer */
421 if ((ReturnCode
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_NoError
)
427 /* Read in the returned CSW from the device */
428 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
434 return PIPE_RWSTREAM_NoError
;
437 /** Issues a SCSI Device Block Write command to the attached device, to write one or more data blocks to the
438 * storage medium from a buffer.
440 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
441 * \param BlockAddress Start block address to write to
442 * \param Blocks Number of blocks to write to in the device
443 * \param BlockSize Size in bytes of each block to write
444 * \param BufferPtr Pointer to the buffer where the write data is to be sourced from
446 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
448 uint8_t MassStore_WriteDeviceBlock(const uint8_t LUNIndex
, const uint32_t BlockAddress
,
449 const uint8_t Blocks
, const uint16_t BlockSize
, void* BufferPtr
)
451 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
453 /* Create a CBW with a SCSI command to write the given blocks to the device */
454 SCSICommandBlock
= (CommandBlockWrapper_t
)
458 .Signature
= CBW_SIGNATURE
,
459 .Tag
= MassStore_Tag
,
460 .DataTransferLength
= ((uint32_t)Blocks
* BlockSize
),
461 .Flags
= COMMAND_DIRECTION_DATA_OUT
,
463 .SCSICommandLength
= 10
469 0x00, // Unused (control bits, all off)
470 (BlockAddress
>> 24), // MSB of Block Address
471 (BlockAddress
>> 16),
473 (BlockAddress
& 0xFF), // LSB of Block Address
474 0x00, // Unused (reserved)
475 0x00, // MSB of Total Blocks to Write
476 Blocks
, // LSB of Total Blocks to Write
477 0x00 // Unused (control)
481 /* Send SCSI command to the attached device */
482 MassStore_SendCommand();
484 /* Write the data to the device from the buffer */
485 if ((ReturnCode
= MassStore_SendReceiveData(BufferPtr
)) != PIPE_RWSTREAM_NoError
)
491 /* Read in the returned CSW from the device */
492 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
498 return PIPE_RWSTREAM_NoError
;
501 /** Issues a SCSI Device Test Unit Ready command to the attached device, to determine if the device is ready to accept
504 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
506 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
508 uint8_t MassStore_TestUnitReady(const uint8_t LUNIndex
)
510 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
512 /* Create a CBW with a SCSI command to issue TEST UNIT READY command */
513 SCSICommandBlock
= (CommandBlockWrapper_t
)
517 .Signature
= CBW_SIGNATURE
,
518 .Tag
= MassStore_Tag
,
519 .DataTransferLength
= 0,
520 .Flags
= COMMAND_DIRECTION_DATA_IN
,
522 .SCSICommandLength
= 6
527 SCSI_CMD_TEST_UNIT_READY
,
532 0x00 // Unused (control)
536 /* Send SCSI command to the attached device */
537 MassStore_SendCommand();
539 /* Read in the returned CSW from the device */
540 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
546 return PIPE_RWSTREAM_NoError
;
549 /** Issues a SCSI Device Read Capacity command to the attached device, to determine the capacity of the
550 * given Logical Unit within the device.
552 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
553 * \param CapacityPtr Device capacity structure where the capacity data is to be stored
555 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
557 uint8_t MassStore_ReadCapacity(const uint8_t LUNIndex
, SCSI_Capacity_t
* const CapacityPtr
)
559 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
561 /* Create a CBW with a SCSI command to issue READ CAPACITY command */
562 SCSICommandBlock
= (CommandBlockWrapper_t
)
566 .Signature
= CBW_SIGNATURE
,
567 .Tag
= MassStore_Tag
,
568 .DataTransferLength
= sizeof(SCSI_Capacity_t
),
569 .Flags
= COMMAND_DIRECTION_DATA_IN
,
571 .SCSICommandLength
= 10
576 SCSI_CMD_READ_CAPACITY_10
,
578 0x00, // MSB of Logical block address
581 0x00, // LSB of Logical block address
584 0x00, // Partial Medium Indicator
585 0x00 // Unused (control)
589 /* Send SCSI command to the attached device */
590 MassStore_SendCommand();
592 /* Wait until data received from the device */
593 if ((ReturnCode
= MassStore_WaitForDataReceived()) != PIPE_RWSTREAM_NoError
)
599 /* Read the returned capacity data into the buffer */
600 if ((ReturnCode
= MassStore_SendReceiveData(CapacityPtr
)) != PIPE_RWSTREAM_NoError
)
606 /* Endian-correct the read data */
607 CapacityPtr
->Blocks
= SwapEndian_32(CapacityPtr
->Blocks
);
608 CapacityPtr
->BlockSize
= SwapEndian_32(CapacityPtr
->BlockSize
);
610 /* Read in the returned CSW from the device */
611 if ((ReturnCode
= MassStore_GetReturnedStatus()) != PIPE_RWSTREAM_NoError
)
617 return PIPE_RWSTREAM_NoError
;
620 /** Issues a SCSI Device Prevent/Allow Medium Removal command to the attached device, to lock the physical media from
621 * being removed. This is a legacy command for SCSI disks with removable storage (such as ZIP disks), but should still
622 * be issued before the first read or write command is sent.
624 * \param LUNIndex Index of the LUN inside the device the command is being addressed to
625 * \param PreventRemoval Whether or not the LUN media should be locked to prevent removal or not
627 * \return A value from the Pipe_Stream_RW_ErrorCodes_t enum
629 uint8_t MassStore_PreventAllowMediumRemoval(const uint8_t LUNIndex
, const bool PreventRemoval
)
631 uint8_t ReturnCode
= PIPE_RWSTREAM_NoError
;
633 /* Create a CBW with a SCSI command to issue PREVENT ALLOW MEDIUM REMOVAL command */
634 SCSICommandBlock
= (CommandBlockWrapper_t
)
638 .Signature
= CBW_SIGNATURE
,
639 .Tag
= MassStore_Tag
,
640 .DataTransferLength
= 0,
641 .Flags
= COMMAND_DIRECTION_DATA_OUT
,
643 .SCSICommandLength
= 6
648 SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
,
651 PreventRemoval
, // Prevent flag
653 0x00 // Unused (control)
657 /* Send SCSI command to the attached device */
658 MassStore_SendCommand();
660 /* Read in the returned CSW from the device */
661 if ((ReturnCode
= MassStore_GetReturnedStatus()))
667 return PIPE_RWSTREAM_NoError
;