Minor documentation page updates.
[pub/USBasp.git] / Demos / Device / MassStorage / Lib / SCSI.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
33 * SCSI command processing routines, for SCSI commands issued by the host. Mass Storage
34 * devices use a thin "Bulk-Only Transport" protocol for issuing commands and status information,
35 * which wrap around standard SCSI device commands for controlling the actual storage medium.
36 */
37
38 #define INCLUDE_FROM_SCSI_C
39 #include "SCSI.h"
40
41 /** Structure to hold the SCSI response data to a SCSI INQUIRY command. This gives information about the device's
42 * features and capabilities.
43 */
44 SCSI_Inquiry_Response_t InquiryData =
45 {
46 .DeviceType = DEVICE_TYPE_BLOCK,
47 .PeripheralQualifier = 0,
48
49 .Removable = true,
50
51 .Version = 0,
52
53 .ResponseDataFormat = 2,
54 .NormACA = false,
55 .TrmTsk = false,
56 .AERC = false,
57
58 .AdditionalLength = 0x1F,
59
60 .SoftReset = false,
61 .CmdQue = false,
62 .Linked = false,
63 .Sync = false,
64 .WideBus16Bit = false,
65 .WideBus32Bit = false,
66 .RelAddr = false,
67
68 .VendorID = "LUFA",
69 .ProductID = "Dataflash Disk",
70 .RevisionID = {'0','.','0','0'},
71 };
72
73 /** Structure to hold the sense data for the last issued SCSI command, which is returned to the host after a SCSI REQUEST SENSE
74 * command is issued. This gives information on exactly why the last command failed to complete.
75 */
76 SCSI_Request_Sense_Response_t SenseData =
77 {
78 .ResponseCode = 0x70,
79 .AdditionalLength = 0x0A,
80 };
81
82
83 /** Main routine to process the SCSI command located in the Command Block Wrapper read from the host. This dispatches
84 * to the appropriate SCSI command handling routine if the issued command is supported by the device, else it returns
85 * a command failure due to a ILLEGAL REQUEST.
86 */
87 bool SCSI_DecodeSCSICommand(USB_ClassInfo_MS_t* MSInterfaceInfo)
88 {
89 bool CommandSuccess = false;
90
91 /* Run the appropriate SCSI command hander function based on the passed command */
92 switch (MSInterfaceInfo->CommandBlock.SCSICommandData[0])
93 {
94 case SCSI_CMD_INQUIRY:
95 CommandSuccess = SCSI_Command_Inquiry(MSInterfaceInfo);
96 break;
97 case SCSI_CMD_REQUEST_SENSE:
98 CommandSuccess = SCSI_Command_Request_Sense(MSInterfaceInfo);
99 break;
100 case SCSI_CMD_READ_CAPACITY_10:
101 CommandSuccess = SCSI_Command_Read_Capacity_10(MSInterfaceInfo);
102 break;
103 case SCSI_CMD_SEND_DIAGNOSTIC:
104 CommandSuccess = SCSI_Command_Send_Diagnostic(MSInterfaceInfo);
105 break;
106 case SCSI_CMD_WRITE_10:
107 CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_WRITE);
108 break;
109 case SCSI_CMD_READ_10:
110 CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_READ);
111 break;
112 case SCSI_CMD_TEST_UNIT_READY:
113 case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
114 case SCSI_CMD_VERIFY_10:
115 /* These commands should just succeed, no handling required */
116 CommandSuccess = true;
117 MSInterfaceInfo->CommandBlock.DataTransferLength = 0;
118 break;
119 default:
120 /* Update the SENSE key to reflect the invalid command */
121 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
122 SCSI_ASENSE_INVALID_COMMAND,
123 SCSI_ASENSEQ_NO_QUALIFIER);
124 break;
125 }
126
127 /* Check if command was successfully processed */
128 if (CommandSuccess)
129 {
130 SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD,
131 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
132 SCSI_ASENSEQ_NO_QUALIFIER);
133
134 return true;
135 }
136
137 return false;
138 }
139
140 /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features
141 * and capabilities to the host.
142 *
143 * \return Boolean true if the command completed successfully, false otherwise.
144 */
145 static bool SCSI_Command_Inquiry(USB_ClassInfo_MS_t* MSInterfaceInfo)
146 {
147 uint16_t AllocationLength = (((uint16_t)MSInterfaceInfo->CommandBlock.SCSICommandData[3] << 8) |
148 MSInterfaceInfo->CommandBlock.SCSICommandData[4]);
149 uint16_t BytesTransferred = (AllocationLength < sizeof(InquiryData))? AllocationLength :
150 sizeof(InquiryData);
151
152 /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */
153 if ((MSInterfaceInfo->CommandBlock.SCSICommandData[1] & ((1 << 0) | (1 << 1))) ||
154 MSInterfaceInfo->CommandBlock.SCSICommandData[2])
155 {
156 /* Optional but unsupported bits set - update the SENSE key and fail the request */
157 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
158 SCSI_ASENSE_INVALID_FIELD_IN_CDB,
159 SCSI_ASENSEQ_NO_QUALIFIER);
160
161 return false;
162 }
163
164 Endpoint_Write_Stream_LE(&InquiryData, BytesTransferred, NO_STREAM_CALLBACK);
165
166 uint8_t PadBytes[AllocationLength - BytesTransferred];
167
168 /* Pad out remaining bytes with 0x00 */
169 Endpoint_Write_Stream_LE(&PadBytes, (AllocationLength - BytesTransferred), NO_STREAM_CALLBACK);
170
171 /* Finalize the stream transfer to send the last packet */
172 Endpoint_ClearIN();
173
174 /* Succeed the command and update the bytes transferred counter */
175 MSInterfaceInfo->CommandBlock.DataTransferLength -= BytesTransferred;
176
177 return true;
178 }
179
180 /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command,
181 * including the error code and additional error information so that the host can determine why a command failed to complete.
182 *
183 * \return Boolean true if the command completed successfully, false otherwise.
184 */
185 static bool SCSI_Command_Request_Sense(USB_ClassInfo_MS_t* MSInterfaceInfo)
186 {
187 uint8_t AllocationLength = MSInterfaceInfo->CommandBlock.SCSICommandData[4];
188 uint8_t BytesTransferred = (AllocationLength < sizeof(SenseData))? AllocationLength : sizeof(SenseData);
189
190 uint8_t PadBytes[AllocationLength - BytesTransferred];
191
192 Endpoint_Write_Stream_LE(&SenseData, BytesTransferred, NO_STREAM_CALLBACK);
193 Endpoint_Write_Stream_LE(&PadBytes, (AllocationLength - BytesTransferred), NO_STREAM_CALLBACK);
194 Endpoint_ClearIN();
195
196 /* Succeed the command and update the bytes transferred counter */
197 MSInterfaceInfo->CommandBlock.DataTransferLength -= BytesTransferred;
198
199 return true;
200 }
201
202 /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity
203 * on the selected Logical Unit (drive), as a number of OS-sized blocks.
204 *
205 * \return Boolean true if the command completed successfully, false otherwise.
206 */
207 static bool SCSI_Command_Read_Capacity_10(USB_ClassInfo_MS_t* MSInterfaceInfo)
208 {
209 uint32_t TotalLUNs = (LUN_MEDIA_BLOCKS - 1);
210 uint32_t MediaBlockSize = VIRTUAL_MEMORY_BLOCK_SIZE;
211
212 Endpoint_Write_Stream_BE(&TotalLUNs, sizeof(TotalLUNs), NO_STREAM_CALLBACK);
213 Endpoint_Write_Stream_BE(&MediaBlockSize, sizeof(MediaBlockSize), NO_STREAM_CALLBACK);
214 Endpoint_ClearIN();
215
216 /* Succeed the command and update the bytes transferred counter */
217 MSInterfaceInfo->CommandBlock.DataTransferLength -= 8;
218
219 return true;
220 }
221
222 /** Command processing for an issued SCSI SEND DIAGNOSTIC command. This command performs a quick check of the Dataflash ICs on the
223 * board, and indicates if they are present and functioning correctly. Only the Self-Test portion of the diagnostic command is
224 * supported.
225 *
226 * \return Boolean true if the command completed successfully, false otherwise.
227 */
228 static bool SCSI_Command_Send_Diagnostic(USB_ClassInfo_MS_t* MSInterfaceInfo)
229 {
230 uint8_t ReturnByte;
231
232 /* Check to see if the SELF TEST bit is not set */
233 if (!(MSInterfaceInfo->CommandBlock.SCSICommandData[1] & (1 << 2)))
234 {
235 /* Only self-test supported - update SENSE key and fail the command */
236 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
237 SCSI_ASENSE_INVALID_FIELD_IN_CDB,
238 SCSI_ASENSEQ_NO_QUALIFIER);
239
240 return false;
241 }
242
243 /* Test first Dataflash IC is present and responding to commands */
244 Dataflash_SelectChip(DATAFLASH_CHIP1);
245 Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
246 ReturnByte = Dataflash_ReceiveByte();
247 Dataflash_DeselectChip();
248
249 /* If returned data is invalid, fail the command */
250 if (ReturnByte != DF_MANUFACTURER_ATMEL)
251 {
252 /* Update SENSE key with a hardware error condition and return command fail */
253 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR,
254 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
255 SCSI_ASENSEQ_NO_QUALIFIER);
256
257 return false;
258 }
259
260 #if (DATAFLASH_TOTALCHIPS == 2)
261 /* Test second Dataflash IC is present and responding to commands */
262 Dataflash_SelectChip(DATAFLASH_CHIP2);
263 Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
264 ReturnByte = Dataflash_ReceiveByte();
265 Dataflash_DeselectChip();
266
267 /* If returned data is invalid, fail the command */
268 if (ReturnByte != DF_MANUFACTURER_ATMEL)
269 {
270 /* Update SENSE key with a hardware error condition and return command fail */
271 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR,
272 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
273 SCSI_ASENSEQ_NO_QUALIFIER);
274
275 return false;
276 }
277 #endif
278
279 /* Succeed the command and update the bytes transferred counter */
280 MSInterfaceInfo->CommandBlock.DataTransferLength = 0;
281
282 return true;
283 }
284
285 /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address
286 * and total number of blocks to process, then calls the appropriate low-level dataflash routine to handle the actual
287 * reading and writing of the data.
288 *
289 * \param IsDataRead Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE)
290 *
291 * \return Boolean true if the command completed successfully, false otherwise.
292 */
293 static bool SCSI_Command_ReadWrite_10(USB_ClassInfo_MS_t* MSInterfaceInfo, const bool IsDataRead)
294 {
295 uint32_t BlockAddress;
296 uint16_t TotalBlocks;
297
298 /* Load in the 32-bit block address (SCSI uses big-endian, so have to do it byte-by-byte) */
299 ((uint8_t*)&BlockAddress)[3] = MSInterfaceInfo->CommandBlock.SCSICommandData[2];
300 ((uint8_t*)&BlockAddress)[2] = MSInterfaceInfo->CommandBlock.SCSICommandData[3];
301 ((uint8_t*)&BlockAddress)[1] = MSInterfaceInfo->CommandBlock.SCSICommandData[4];
302 ((uint8_t*)&BlockAddress)[0] = MSInterfaceInfo->CommandBlock.SCSICommandData[5];
303
304 /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to do it byte-by-byte) */
305 ((uint8_t*)&TotalBlocks)[1] = MSInterfaceInfo->CommandBlock.SCSICommandData[7];
306 ((uint8_t*)&TotalBlocks)[0] = MSInterfaceInfo->CommandBlock.SCSICommandData[8];
307
308 /* Check if the block address is outside the maximum allowable value for the LUN */
309 if (BlockAddress >= LUN_MEDIA_BLOCKS)
310 {
311 /* Block address is invalid, update SENSE key and return command fail */
312 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
313 SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE,
314 SCSI_ASENSEQ_NO_QUALIFIER);
315
316 return false;
317 }
318
319 #if (TOTAL_LUNS > 1)
320 /* Adjust the given block address to the real media address based on the selected LUN */
321 BlockAddress += ((uint32_t)MSInterfaceInfo->CommandBlock.LUN * LUN_MEDIA_BLOCKS);
322 #endif
323
324 /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */
325 if (IsDataRead == DATA_READ)
326 DataflashManager_ReadBlocks(MSInterfaceInfo, BlockAddress, TotalBlocks);
327 else
328 DataflashManager_WriteBlocks(MSInterfaceInfo, BlockAddress, TotalBlocks);
329
330 /* Update the bytes transferred counter and succeed the command */
331 MSInterfaceInfo->CommandBlock.DataTransferLength -= ((uint32_t)TotalBlocks * VIRTUAL_MEMORY_BLOCK_SIZE);
332
333 return true;
334 }