]> git.donarmstrong.com Git - qmk_firmware.git/blob - protocol/lufa/LUFA-git/Bootloaders/MassStorage/Lib/SCSI.c
Squashed 'tmk_core/' changes from caca2c0..dc0e46e
[qmk_firmware.git] / protocol / lufa / LUFA-git / Bootloaders / MassStorage / Lib / SCSI.c
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2014.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2014  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 disclaims 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 static const 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           = "Bootloader",
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 static 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  *  \return Boolean \c true if the command completed successfully, \c false otherwise
90  */
91 bool SCSI_DecodeSCSICommand(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
92 {
93         bool CommandSuccess = false;
94
95         /* Run the appropriate SCSI command hander function based on the passed command */
96         switch (MSInterfaceInfo->State.CommandBlock.SCSICommandData[0])
97         {
98                 case SCSI_CMD_INQUIRY:
99                         CommandSuccess = SCSI_Command_Inquiry(MSInterfaceInfo);
100                         break;
101                 case SCSI_CMD_REQUEST_SENSE:
102                         CommandSuccess = SCSI_Command_Request_Sense(MSInterfaceInfo);
103                         break;
104                 case SCSI_CMD_READ_CAPACITY_10:
105                         CommandSuccess = SCSI_Command_Read_Capacity_10(MSInterfaceInfo);
106                         break;
107                 case SCSI_CMD_WRITE_10:
108                         CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_WRITE);
109                         break;
110                 case SCSI_CMD_READ_10:
111                         CommandSuccess = SCSI_Command_ReadWrite_10(MSInterfaceInfo, DATA_READ);
112                         break;
113                 case SCSI_CMD_MODE_SENSE_6:
114                         CommandSuccess = SCSI_Command_ModeSense_6(MSInterfaceInfo);
115                         break;
116                 case SCSI_CMD_START_STOP_UNIT:
117 #if !defined(NO_APP_START_ON_EJECT)
118                         /* If the user ejected the volume, signal bootloader exit at next opportunity. */
119                         RunBootloader = ((MSInterfaceInfo->State.CommandBlock.SCSICommandData[4] & 0x03) != 0x02);
120 #endif
121                 case SCSI_CMD_SEND_DIAGNOSTIC:
122                 case SCSI_CMD_TEST_UNIT_READY:
123                 case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
124                 case SCSI_CMD_VERIFY_10:
125                         /* These commands should just succeed, no handling required */
126                         CommandSuccess = true;
127                         MSInterfaceInfo->State.CommandBlock.DataTransferLength = 0;
128                         break;
129                 default:
130                         /* Update the SENSE key to reflect the invalid command */
131                         SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
132                                    SCSI_ASENSE_INVALID_COMMAND,
133                                    SCSI_ASENSEQ_NO_QUALIFIER);
134                         break;
135         }
136
137         /* Check if command was successfully processed */
138         if (CommandSuccess)
139         {
140                 SCSI_SET_SENSE(SCSI_SENSE_KEY_GOOD,
141                                SCSI_ASENSE_NO_ADDITIONAL_INFORMATION,
142                                SCSI_ASENSEQ_NO_QUALIFIER);
143
144                 return true;
145         }
146
147         return false;
148 }
149
150 /** Command processing for an issued SCSI INQUIRY command. This command returns information about the device's features
151  *  and capabilities to the host.
152  *
153  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with
154  *
155  *  \return Boolean \c true if the command completed successfully, \c false otherwise.
156  */
157 static bool SCSI_Command_Inquiry(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
158 {
159         uint16_t AllocationLength  = SwapEndian_16(*(uint16_t*)&MSInterfaceInfo->State.CommandBlock.SCSICommandData[3]);
160         uint16_t BytesTransferred  = MIN(AllocationLength, sizeof(InquiryData));
161
162         /* Only the standard INQUIRY data is supported, check if any optional INQUIRY bits set */
163         if ((MSInterfaceInfo->State.CommandBlock.SCSICommandData[1] & ((1 << 0) | (1 << 1))) ||
164              MSInterfaceInfo->State.CommandBlock.SCSICommandData[2])
165         {
166                 /* Optional but unsupported bits set - update the SENSE key and fail the request */
167                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
168                                SCSI_ASENSE_INVALID_FIELD_IN_CDB,
169                                SCSI_ASENSEQ_NO_QUALIFIER);
170
171                 return false;
172         }
173
174         Endpoint_Write_Stream_LE(&InquiryData, BytesTransferred, NULL);
175
176         /* Pad out remaining bytes with 0x00 */
177         Endpoint_Null_Stream((AllocationLength - BytesTransferred), NULL);
178
179         /* Finalize the stream transfer to send the last packet */
180         Endpoint_ClearIN();
181
182         /* Succeed the command and update the bytes transferred counter */
183         MSInterfaceInfo->State.CommandBlock.DataTransferLength -= BytesTransferred;
184
185         return true;
186 }
187
188 /** Command processing for an issued SCSI REQUEST SENSE command. This command returns information about the last issued command,
189  *  including the error code and additional error information so that the host can determine why a command failed to complete.
190  *
191  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with
192  *
193  *  \return Boolean \c true if the command completed successfully, \c false otherwise.
194  */
195 static bool SCSI_Command_Request_Sense(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
196 {
197         uint8_t AllocationLength = MSInterfaceInfo->State.CommandBlock.SCSICommandData[4];
198         uint8_t BytesTransferred = MIN(AllocationLength, sizeof(SenseData));
199
200         Endpoint_Write_Stream_LE(&SenseData, BytesTransferred, NULL);
201         Endpoint_Null_Stream((AllocationLength - BytesTransferred), NULL);
202         Endpoint_ClearIN();
203
204         /* Succeed the command and update the bytes transferred counter */
205         MSInterfaceInfo->State.CommandBlock.DataTransferLength -= BytesTransferred;
206
207         return true;
208 }
209
210 /** Command processing for an issued SCSI READ CAPACITY (10) command. This command returns information about the device's capacity
211  *  on the selected Logical Unit (drive), as a number of OS-sized blocks.
212  *
213  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with
214  *
215  *  \return Boolean \c true if the command completed successfully, \c false otherwise.
216  */
217 static bool SCSI_Command_Read_Capacity_10(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
218 {
219         Endpoint_Write_32_BE(LUN_MEDIA_BLOCKS - 1);
220         Endpoint_Write_32_BE(SECTOR_SIZE_BYTES);
221         Endpoint_ClearIN();
222
223         /* Succeed the command and update the bytes transferred counter */
224         MSInterfaceInfo->State.CommandBlock.DataTransferLength -= 8;
225
226         return true;
227 }
228
229 /** Command processing for an issued SCSI READ (10) or WRITE (10) command. This command reads in the block start address
230  *  and total number of blocks to process, then calls the appropriate low-level Dataflash routine to handle the actual
231  *  reading and writing of the data.
232  *
233  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with
234  *  \param[in] IsDataRead  Indicates if the command is a READ (10) command or WRITE (10) command (DATA_READ or DATA_WRITE)
235  *
236  *  \return Boolean \c true if the command completed successfully, \c false otherwise.
237  */
238 static bool SCSI_Command_ReadWrite_10(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo,
239                                       const bool IsDataRead)
240 {
241         uint16_t BlockAddress;
242         uint16_t TotalBlocks;
243
244         /* Load in the 32-bit block address (SCSI uses big-endian, so have to reverse the byte order) */
245         BlockAddress = SwapEndian_32(*(uint32_t*)&MSInterfaceInfo->State.CommandBlock.SCSICommandData[2]);
246
247         /* Load in the 16-bit total blocks (SCSI uses big-endian, so have to reverse the byte order) */
248         TotalBlocks  = SwapEndian_16(*(uint16_t*)&MSInterfaceInfo->State.CommandBlock.SCSICommandData[7]);
249
250         /* Check if the block address is outside the maximum allowable value for the LUN */
251         if (BlockAddress >= LUN_MEDIA_BLOCKS)
252         {
253                 /* Block address is invalid, update SENSE key and return command fail */
254                 SCSI_SET_SENSE(SCSI_SENSE_KEY_ILLEGAL_REQUEST,
255                                SCSI_ASENSE_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE,
256                                SCSI_ASENSEQ_NO_QUALIFIER);
257
258                 return false;
259         }
260
261         /* Determine if the packet is a READ (10) or WRITE (10) command, call appropriate function */
262         for (uint16_t i = 0; i < TotalBlocks; i++)
263         {
264                 if (IsDataRead == DATA_READ)
265                   VirtualFAT_ReadBlock(BlockAddress + i);
266                 else
267                   VirtualFAT_WriteBlock(BlockAddress + i);
268         }
269
270         /* Update the bytes transferred counter and succeed the command */
271         MSInterfaceInfo->State.CommandBlock.DataTransferLength -= ((uint32_t)TotalBlocks * SECTOR_SIZE_BYTES);
272
273         return true;
274 }
275
276 /** Command processing for an issued SCSI MODE SENSE (6) command. This command returns various informational pages about
277  *  the SCSI device, as well as the device's Write Protect status.
278  *
279  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface structure that the command is associated with
280  *
281  *  \return Boolean \c true if the command completed successfully, \c false otherwise.
282  */
283 static bool SCSI_Command_ModeSense_6(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
284 {
285         /* Send an empty header response indicating Write Protect flag is off */
286         Endpoint_Write_32_LE(0);
287         Endpoint_ClearIN();
288
289         /* Update the bytes transferred counter and succeed the command */
290         MSInterfaceInfo->State.CommandBlock.DataTransferLength -= 4;
291
292         return true;
293 }
294