Added CDC_Device_Flush() command to the CDC Device mode class driver.
[pub/USBasp.git] / Demos / Device / ClassDriver / 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 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with
88 */
89 bool SCSI_DecodeSCSICommand(USB_ClassInfo_MS_Device_t* MSInterfaceInfo)
90 {
91 bool CommandSuccess = false;
92
93 /* Run the appropriate SCSI command hander function based on the passed command */
94 switch (MSInterfaceInfo->State.CommandBlock.SCSICommandData[0])
95 {
96 case SCSI_CMD_INQUIRY:
97 CommandSuccess = SCSI_Command_Inquiry(MSInterfaceInfo);
98 break;
99 case SCSI_CMD_REQUEST_SENSE:
100 CommandSuccess = SCSI_Command_Request_Sense(MSInterfaceInfo);
101 break;
102 case SCSI_CMD_READ_CAPACITY_10:
103 CommandSuccess = SCSI_Command_Read_Capacity_10(MSInterfaceInfo);
104 break;
105 case SCSI_CMD_SEND_DIAGNOSTIC:
106 CommandSuccess = SCSI_Command_Send_Diagnostic(MSInterfaceInfo);
107 break;
108 case SCSI_CMD_WRITE_10:
109 CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_WRITE);
110 break;
111 case SCSI_CMD_READ_10:
112 CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_READ);
113 break;
114 case SCSI_CMD_TEST_UNIT_READY:
115 case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
116 case SCSI_CMD_VERIFY_10:
117 /* These commands should just succeed, no handling required */
118 CommandSuccess = true;
119 MSInterfaceInfo->State.CommandBlock.DataTransferLength = 0;
120 break;
121 default:
122 /* Update the SENSE key to reflect the invalid command */
123 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
124 SCSI_ASENSE_INVALID_COMMAND,
125 SCSI_ASENSEQ_NO_QUALIFIER);
126 break;
127 }
128
129 /* Check if command was successfully processed */
130 if (CommandSuccess)
131 {
132 SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD,
133 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
134 SCSI_ASENSEQ_NO_QUALIFIER);
135
136 return true;
137 }
138
139 return false;
140 }
141
142 /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features
143 * and capabilities to the host.
144 *
145 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with
146 *
147 * \return Boolean true if the command completed successfully, false otherwise.
148 */
149 static bool SCSI_Command_Inquiry(USB_ClassInfo_MS_Device_t* MSInterfaceInfo)
150 {
151 uint16_t AllocationLength = (((uint16_t)MSInterfaceInfo->State.CommandBlock.SCSICommandData[3] << 8) |
152 MSInterfaceInfo->State.CommandBlock.SCSICommandData[4]);
153 uint16_t BytesTransferred = (AllocationLength < sizeof(InquiryData))? AllocationLength :
154 sizeof(InquiryData);
155
156 /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */
157 if ((MSInterfaceInfo->State.CommandBlock.SCSICommandData[1] & ((1 << 0) | (1 << 1))) ||
158 MSInterfaceInfo->State.CommandBlock.SCSICommandData[2])
159 {
160 /* Optional but unsupported bits set - update the SENSE key and fail the request */
161 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
162 SCSI_ASENSE_INVALID_FIELD_IN_CDB,
163 SCSI_ASENSEQ_NO_QUALIFIER);
164
165 return false;
166 }
167
168 Endpoint_Write_Stream_LE(&InquiryData, BytesTransferred, NO_STREAM_CALLBACK);
169
170 uint8_t PadBytes[AllocationLength - BytesTransferred];
171
172 /* Pad out remaining bytes with 0x00 */
173 Endpoint_Write_Stream_LE(&PadBytes, (AllocationLength - BytesTransferred), NO_STREAM_CALLBACK);
174
175 /* Finalize the stream transfer to send the last packet */
176 Endpoint_ClearIN();
177
178 /* Succeed the command and update the bytes transferred counter */
179 MSInterfaceInfo->State.CommandBlock.DataTransferLength -= BytesTransferred;
180
181 return true;
182 }
183
184 /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command,
185 * including the error code and additional error information so that the host can determine why a command failed to complete.
186 *
187 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with
188 *
189 * \return Boolean true if the command completed successfully, false otherwise.
190 */
191 static bool SCSI_Command_Request_Sense(USB_ClassInfo_MS_Device_t* MSInterfaceInfo)
192 {
193 uint8_t AllocationLength = MSInterfaceInfo->State.CommandBlock.SCSICommandData[4];
194 uint8_t BytesTransferred = (AllocationLength < sizeof(SenseData))? AllocationLength : sizeof(SenseData);
195
196 uint8_t PadBytes[AllocationLength - BytesTransferred];
197
198 Endpoint_Write_Stream_LE(&SenseData, BytesTransferred, NO_STREAM_CALLBACK);
199 Endpoint_Write_Stream_LE(&PadBytes, (AllocationLength - BytesTransferred), NO_STREAM_CALLBACK);
200 Endpoint_ClearIN();
201
202 /* Succeed the command and update the bytes transferred counter */
203 MSInterfaceInfo->State.CommandBlock.DataTransferLength -= BytesTransferred;
204
205 return true;
206 }
207
208 /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity
209 * on the selected Logical Unit (drive), as a number of OS-sized blocks.
210 *
211 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with
212 *
213 * \return Boolean true if the command completed successfully, false otherwise.
214 */
215 static bool SCSI_Command_Read_Capacity_10(USB_ClassInfo_MS_Device_t* MSInterfaceInfo)
216 {
217 uint32_t LastBlockAddressInLUN = (LUN_MEDIA_BLOCKS - 1);
218 uint32_t MediaBlockSize = VIRTUAL_MEMORY_BLOCK_SIZE;
219
220 Endpoint_Write_Stream_BE(&LastBlockAddressInLUN, sizeof(LastBlockAddressInLUN), NO_STREAM_CALLBACK);
221 Endpoint_Write_Stream_BE(&MediaBlockSize, sizeof(MediaBlockSize), NO_STREAM_CALLBACK);
222 Endpoint_ClearIN();
223
224 /* Succeed the command and update the bytes transferred counter */
225 MSInterfaceInfo->State.CommandBlock.DataTransferLength -= 8;
226
227 return true;
228 }
229
230 /** Command processing for an issued SCSI SEND DIAGNOSTIC command. This command performs a quick check of the Dataflash ICs on the
231 * board, and indicates if they are present and functioning correctly. Only the Self-Test portion of the diagnostic command is
232 * supported.
233 *
234 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with
235 *
236 * \return Boolean true if the command completed successfully, false otherwise.
237 */
238 static bool SCSI_Command_Send_Diagnostic(USB_ClassInfo_MS_Device_t* MSInterfaceInfo)
239 {
240 uint8_t ReturnByte;
241
242 /* Check to see if the SELF TEST bit is not set */
243 if (!(MSInterfaceInfo->State.CommandBlock.SCSICommandData[1] & (1 << 2)))
244 {
245 /* Only self-test supported - update SENSE key and fail the command */
246 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
247 SCSI_ASENSE_INVALID_FIELD_IN_CDB,
248 SCSI_ASENSEQ_NO_QUALIFIER);
249
250 return false;
251 }
252
253 /* Test first Dataflash IC is present and responding to commands */
254 Dataflash_SelectChip(DATAFLASH_CHIP1);
255 Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
256 ReturnByte = Dataflash_ReceiveByte();
257 Dataflash_DeselectChip();
258
259 /* If returned data is invalid, fail the command */
260 if (ReturnByte != DF_MANUFACTURER_ATMEL)
261 {
262 /* Update SENSE key with a hardware error condition and return command fail */
263 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR,
264 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
265 SCSI_ASENSEQ_NO_QUALIFIER);
266
267 return false;
268 }
269
270 #if (DATAFLASH_TOTALCHIPS == 2)
271 /* Test second Dataflash IC is present and responding to commands */
272 Dataflash_SelectChip(DATAFLASH_CHIP2);
273 Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
274 ReturnByte = Dataflash_ReceiveByte();
275 Dataflash_DeselectChip();
276
277 /* If returned data is invalid, fail the command */
278 if (ReturnByte != DF_MANUFACTURER_ATMEL)
279 {
280 /* Update SENSE key with a hardware error condition and return command fail */
281 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR,
282 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
283 SCSI_ASENSEQ_NO_QUALIFIER);
284
285 return false;
286 }
287 #endif
288
289 /* Succeed the command and update the bytes transferred counter */
290 MSInterfaceInfo->State.CommandBlock.DataTransferLength = 0;
291
292 return true;
293 }
294
295 /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address
296 * and total number of blocks to process, then calls the appropriate low-level dataflash routine to handle the actual
297 * reading and writing of the data.
298 *
299 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface structure that the command is associated with
300 * \param[in] IsDataRead Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE)
301 *
302 * \return Boolean true if the command completed successfully, false otherwise.
303 */
304 static bool SCSI_Command_ReadWrite_10(USB_ClassInfo_MS_Device_t* MSInterfaceInfo, const bool IsDataRead)
305 {
306 uint32_t BlockAddress;
307 uint16_t TotalBlocks;
308
309 /* Load in the 32-bit block address (SCSI uses big-endian, so have to do it byte-by-byte) */
310 ((uint8_t*)&BlockAddress)[3] = MSInterfaceInfo->State.CommandBlock.SCSICommandData[2];
311 ((uint8_t*)&BlockAddress)[2] = MSInterfaceInfo->State.CommandBlock.SCSICommandData[3];
312 ((uint8_t*)&BlockAddress)[1] = MSInterfaceInfo->State.CommandBlock.SCSICommandData[4];
313 ((uint8_t*)&BlockAddress)[0] = MSInterfaceInfo->State.CommandBlock.SCSICommandData[5];
314
315 /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to do it byte-by-byte) */
316 ((uint8_t*)&TotalBlocks)[1] = MSInterfaceInfo->State.CommandBlock.SCSICommandData[7];
317 ((uint8_t*)&TotalBlocks)[0] = MSInterfaceInfo->State.CommandBlock.SCSICommandData[8];
318
319 /* Check if the block address is outside the maximum allowable value for the LUN */
320 if (BlockAddress >= LUN_MEDIA_BLOCKS)
321 {
322 /* Block address is invalid, update SENSE key and return command fail */
323 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
324 SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE,
325 SCSI_ASENSEQ_NO_QUALIFIER);
326
327 return false;
328 }
329
330 #if (TOTAL_LUNS > 1)
331 /* Adjust the given block address to the real media address based on the selected LUN */
332 BlockAddress += ((uint32_t)MSInterfaceInfo->State.CommandBlock.LUN * LUN_MEDIA_BLOCKS);
333 #endif
334
335 /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */
336 if (IsDataRead == DATA_READ)
337 DataflashManager_ReadBlocks(MSInterfaceInfo, BlockAddress, TotalBlocks);
338 else
339 DataflashManager_WriteBlocks(MSInterfaceInfo, BlockAddress, TotalBlocks);
340
341 /* Update the bytes transferred counter and succeed the command */
342 MSInterfaceInfo->State.CommandBlock.DataTransferLength -= ((uint32_t)TotalBlocks * VIRTUAL_MEMORY_BLOCK_SIZE);
343
344 return true;
345 }