Fix pointer aliasing warning in the Mass Storage demos.
[pub/USBasp.git] / Demos / Device / LowLevel / MassStorage / Lib / SCSI.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all 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 * \return Boolean true if the command completed successfully, false otherwise
88 */
89 bool SCSI_DecodeSCSICommand(void)
90 {
91 /* Set initial sense data, before the requested command is processed */
92 SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD,
93 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
94 SCSI_ASENSEQ_NO_QUALIFIER);
95
96 /* Run the appropriate SCSI command hander function based on the passed command */
97 switch (CommandBlock.SCSICommandData[0])
98 {
99 case SCSI_CMD_INQUIRY:
100 SCSI_Command_Inquiry();
101 break;
102 case SCSI_CMD_REQUEST_SENSE:
103 SCSI_Command_Request_Sense();
104 break;
105 case SCSI_CMD_READ_CAPACITY_10:
106 SCSI_Command_Read_Capacity_10();
107 break;
108 case SCSI_CMD_SEND_DIAGNOSTIC:
109 SCSI_Command_Send_Diagnostic();
110 break;
111 case SCSI_CMD_WRITE_10:
112 SCSI_Command_ReadWrite_10(DATA_WRITE);
113 break;
114 case SCSI_CMD_READ_10:
115 SCSI_Command_ReadWrite_10(DATA_READ);
116 break;
117 case SCSI_CMD_TEST_UNIT_READY:
118 case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
119 case SCSI_CMD_VERIFY_10:
120 /* These commands should just succeed, no handling required */
121 CommandBlock.DataTransferLength = 0;
122 break;
123 default:
124 /* Update the SENSE key to reflect the invalid command */
125 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
126 SCSI_ASENSE_INVALID_COMMAND,
127 SCSI_ASENSEQ_NO_QUALIFIER);
128 break;
129 }
130
131 return (SenseData.SenseKey == SCSI_SENSE_KEY_GOOD);
132 }
133
134 /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features
135 * and capabilities to the host.
136 */
137 static void SCSI_Command_Inquiry(void)
138 {
139 uint16_t AllocationLength = SwapEndian_16(*(uint32_t*)&CommandBlock.SCSICommandData[3]);
140 uint16_t BytesTransferred = (AllocationLength < sizeof(InquiryData))? AllocationLength :
141 sizeof(InquiryData);
142
143 /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */
144 if ((CommandBlock.SCSICommandData[1] & ((1 << 0) | (1 << 1))) ||
145 CommandBlock.SCSICommandData[2])
146 {
147 /* Optional but unsupported bits set - update the SENSE key and fail the request */
148 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
149 SCSI_ASENSE_INVALID_FIELD_IN_CDB,
150 SCSI_ASENSEQ_NO_QUALIFIER);
151
152 return;
153 }
154
155 /* Write the INQUIRY data to the endpoint */
156 Endpoint_Write_Stream_LE(&InquiryData, BytesTransferred, StreamCallback_AbortOnMassStoreReset);
157
158 uint8_t PadBytes[AllocationLength - BytesTransferred];
159
160 /* Pad out remaining bytes with 0x00 */
161 Endpoint_Write_Stream_LE(&PadBytes, sizeof(PadBytes), StreamCallback_AbortOnMassStoreReset);
162
163 /* Finalize the stream transfer to send the last packet */
164 Endpoint_ClearIN();
165
166 /* Succeed the command and update the bytes transferred counter */
167 CommandBlock.DataTransferLength -= BytesTransferred;
168 }
169
170 /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command,
171 * including the error code and additional error information so that the host can determine why a command failed to complete.
172 */
173 static void SCSI_Command_Request_Sense(void)
174 {
175 uint8_t AllocationLength = CommandBlock.SCSICommandData[4];
176 uint8_t BytesTransferred = (AllocationLength < sizeof(SenseData))? AllocationLength : sizeof(SenseData);
177
178 /* Send the SENSE data - this indicates to the host the status of the last command */
179 Endpoint_Write_Stream_LE(&SenseData, BytesTransferred, StreamCallback_AbortOnMassStoreReset);
180
181 uint8_t PadBytes[AllocationLength - BytesTransferred];
182
183 /* Pad out remaining bytes with 0x00 */
184 Endpoint_Write_Stream_LE(&PadBytes, sizeof(PadBytes), StreamCallback_AbortOnMassStoreReset);
185
186 /* Finalize the stream transfer to send the last packet */
187 Endpoint_ClearIN();
188
189 /* Succeed the command and update the bytes transferred counter */
190 CommandBlock.DataTransferLength -= BytesTransferred;
191 }
192
193 /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity
194 * on the selected Logical Unit (drive), as a number of OS-sized blocks.
195 */
196 static void SCSI_Command_Read_Capacity_10(void)
197 {
198 /* Send the total number of logical blocks in the current LUN */
199 Endpoint_Write_DWord_BE(LUN_MEDIA_BLOCKS - 1);
200
201 /* Send the logical block size of the device (must be 512 bytes) */
202 Endpoint_Write_DWord_BE(VIRTUAL_MEMORY_BLOCK_SIZE);
203
204 /* Check if the current command is being aborted by the host */
205 if (IsMassStoreReset)
206 return;
207
208 /* Send the endpoint data packet to the host */
209 Endpoint_ClearIN();
210
211 /* Succeed the command and update the bytes transferred counter */
212 CommandBlock.DataTransferLength -= 8;
213 }
214
215 /** Command processing for an issued SCSI SEND DIAGNOSTIC command. This command performs a quick check of the Dataflash ICs on the
216 * board, and indicates if they are present and functioning correctly. Only the Self-Test portion of the diagnostic command is
217 * supported.
218 */
219 static void SCSI_Command_Send_Diagnostic(void)
220 {
221 /* Check to see if the SELF TEST bit is not set */
222 if (!(CommandBlock.SCSICommandData[1] & (1 << 2)))
223 {
224 /* Only self-test supported - update SENSE key and fail the command */
225 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
226 SCSI_ASENSE_INVALID_FIELD_IN_CDB,
227 SCSI_ASENSEQ_NO_QUALIFIER);
228
229 return;
230 }
231
232 /* Check to see if all attached Dataflash ICs are functional */
233 if (!(DataflashManager_CheckDataflashOperation()))
234 {
235 /* Update SENSE key with a hardware error condition and return command fail */
236 SCSI_SET_SENSE(SCSI_SENSE_KEY_HARDWARE_ERROR,
237 SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
238 SCSI_ASENSEQ_NO_QUALIFIER);
239
240 return;
241 }
242
243 /* Succeed the command and update the bytes transferred counter */
244 CommandBlock.DataTransferLength = 0;
245 }
246
247 /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address
248 * and total number of blocks to process, then calls the appropriate low-level dataflash routine to handle the actual
249 * reading and writing of the data.
250 *
251 * \param[in] IsDataRead Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE)
252 */
253 static void SCSI_Command_ReadWrite_10(const bool IsDataRead)
254 {
255 uint32_t BlockAddress;
256 uint16_t TotalBlocks;
257
258 /* Load in the 32-bit block address (SCSI uses big-endian, so have to reverse the byte order) */
259 BlockAddress = SwapEndian_32(*(uint32_t*)&CommandBlock.SCSICommandData[2]);
260
261 /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to reverse the byte order) */
262 TotalBlocks = SwapEndian_16(*(uint32_t*)&CommandBlock.SCSICommandData[7]);
263
264 /* Check if the block address is outside the maximum allowable value for the LUN */
265 if (BlockAddress >= LUN_MEDIA_BLOCKS)
266 {
267 /* Block address is invalid, update SENSE key and return command fail */
268 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
269 SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE,
270 SCSI_ASENSEQ_NO_QUALIFIER);
271
272 return;
273 }
274
275 #if (TOTAL_LUNS > 1)
276 /* Adjust the given block address to the real media address based on the selected LUN */
277 BlockAddress += ((uint32_t)CommandBlock.LUN * LUN_MEDIA_BLOCKS);
278 #endif
279
280 /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */
281 if (IsDataRead == DATA_READ)
282 DataflashManager_ReadBlocks(BlockAddress, TotalBlocks);
283 else
284 DataflashManager_WriteBlocks(BlockAddress, TotalBlocks);
285
286 /* Update the bytes transferred counter and succeed the command */
287 CommandBlock.DataTransferLength -= ((uint32_t)TotalBlocks * VIRTUAL_MEMORY_BLOCK_SIZE);
288 }