Added support to the AVRISP-MKII project for ISP speeds slower than 125KHz via a...
[pub/USBasp.git] / Demos / Device / LowLevel / MassStorage / MassStorage.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 * Main source file for the Mass Storage demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #define INCLUDE_FROM_MASSSTORAGE_C
38 #include "MassStorage.h"
39
40 /** Structure to hold the latest Command Block Wrapper issued by the host, containing a SCSI command to execute. */
41 CommandBlockWrapper_t CommandBlock;
42
43 /** Structure to hold the latest Command Status Wrapper to return to the host, containing the status of the last issued command. */
44 CommandStatusWrapper_t CommandStatus = { .Signature = CSW_SIGNATURE };
45
46 /** Flag to asynchronously abort any in-progress data transfers upon the reception of a mass storage reset command. */
47 volatile bool IsMassStoreReset = false;
48
49
50 /** Main program entry point. This routine configures the hardware required by the application, then
51 * enters a loop to run the application tasks in sequence.
52 */
53 int main(void)
54 {
55 SetupHardware();
56
57 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
58 sei();
59
60 for (;;)
61 {
62 MassStorage_Task();
63 USB_USBTask();
64 }
65 }
66
67 /** Configures the board hardware and chip peripherals for the demo's functionality. */
68 void SetupHardware(void)
69 {
70 /* Disable watchdog if enabled by bootloader/fuses */
71 MCUSR &= ~(1 << WDRF);
72 wdt_disable();
73
74 /* Disable clock division */
75 clock_prescale_set(clock_div_1);
76
77 /* Hardware Initialization */
78 LEDs_Init();
79 SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_ORDER_MSB_FIRST | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER);
80 Dataflash_Init();
81 USB_Init();
82
83 /* Clear Dataflash sector protections, if enabled */
84 DataflashManager_ResetDataflashProtections();
85 }
86
87 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
88 void EVENT_USB_Device_Connect(void)
89 {
90 /* Indicate USB enumerating */
91 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
92
93 /* Reset the MSReset flag upon connection */
94 IsMassStoreReset = false;
95 }
96
97 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
98 * the status LEDs and stops the Mass Storage management task.
99 */
100 void EVENT_USB_Device_Disconnect(void)
101 {
102 /* Indicate USB not ready */
103 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
104 }
105
106 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
107 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
108 */
109 void EVENT_USB_Device_ConfigurationChanged(void)
110 {
111 /* Indicate USB connected and ready */
112 LEDs_SetAllLEDs(LEDMASK_USB_READY);
113
114 /* Setup Mass Storage In and Out Endpoints */
115 if (!(Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM, EP_TYPE_BULK,
116 ENDPOINT_DIR_IN, MASS_STORAGE_IO_EPSIZE,
117 ENDPOINT_BANK_SINGLE)))
118 {
119 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
120 }
121
122 if (!(Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM, EP_TYPE_BULK,
123 ENDPOINT_DIR_OUT, MASS_STORAGE_IO_EPSIZE,
124 ENDPOINT_BANK_SINGLE)))
125 {
126 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
127 }
128 }
129
130 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
131 * control requests that are not handled internally by the USB library (including the Mass Storage class-specific
132 * requests) so that they can be handled appropriately for the application.
133 */
134 void EVENT_USB_Device_UnhandledControlRequest(void)
135 {
136 /* Process UFI specific control requests */
137 switch (USB_ControlRequest.bRequest)
138 {
139 case REQ_MassStorageReset:
140 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
141 {
142 Endpoint_ClearSETUP();
143
144 /* Indicate that the current transfer should be aborted */
145 IsMassStoreReset = true;
146
147 Endpoint_ClearStatusStage();
148 }
149
150 break;
151 case REQ_GetMaxLUN:
152 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
153 {
154 Endpoint_ClearSETUP();
155
156 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
157 Endpoint_Write_Byte(TOTAL_LUNS - 1);
158
159 Endpoint_ClearIN();
160
161 Endpoint_ClearStatusStage();
162 }
163
164 break;
165 }
166 }
167
168 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
169 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
170 */
171 void MassStorage_Task(void)
172 {
173 /* Device must be connected and configured for the task to run */
174 if (USB_DeviceState != DEVICE_STATE_Configured)
175 return;
176
177 /* Process sent command block from the host if one has been sent */
178 if (ReadInCommandBlock())
179 {
180 /* Indicate busy */
181 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
182
183 /* Check direction of command, select Data IN endpoint if data is from the device */
184 if (CommandBlock.Flags & COMMAND_DIRECTION_DATA_IN)
185 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
186
187 /* Decode the received SCSI command, set returned status code */
188 CommandStatus.Status = SCSI_DecodeSCSICommand() ? Command_Pass : Command_Fail;
189
190 /* Load in the CBW tag into the CSW to link them together */
191 CommandStatus.Tag = CommandBlock.Tag;
192
193 /* Load in the data residue counter into the CSW */
194 CommandStatus.DataTransferResidue = CommandBlock.DataTransferLength;
195
196 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
197 if ((CommandStatus.Status == Command_Fail) && (CommandStatus.DataTransferResidue))
198 Endpoint_StallTransaction();
199
200 /* Return command status block to the host */
201 ReturnCommandStatus();
202
203 /* Indicate ready */
204 LEDs_SetAllLEDs(LEDMASK_USB_READY);
205 }
206
207 /* Check if a Mass Storage Reset occurred */
208 if (IsMassStoreReset)
209 {
210 /* Reset the data endpoint banks */
211 Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM);
212 Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM);
213
214 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
215 Endpoint_ClearStall();
216 Endpoint_ResetDataToggle();
217 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
218 Endpoint_ClearStall();
219 Endpoint_ResetDataToggle();
220
221 /* Clear the abort transfer flag */
222 IsMassStoreReset = false;
223 }
224 }
225
226 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
227 * if one has been issued, and performs validation to ensure that the block command is valid.
228 *
229 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
230 */
231 static bool ReadInCommandBlock(void)
232 {
233 /* Select the Data Out endpoint */
234 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
235
236 /* Abort if no command has been sent from the host */
237 if (!(Endpoint_IsOUTReceived()))
238 return false;
239
240 /* Read in command block header */
241 Endpoint_Read_Stream_LE(&CommandBlock, (sizeof(CommandBlock) - sizeof(CommandBlock.SCSICommandData)),
242 StreamCallback_AbortOnMassStoreReset);
243
244 /* Check if the current command is being aborted by the host */
245 if (IsMassStoreReset)
246 return false;
247
248 /* Verify the command block - abort if invalid */
249 if ((CommandBlock.Signature != CBW_SIGNATURE) ||
250 (CommandBlock.LUN >= TOTAL_LUNS) ||
251 (CommandBlock.Flags & 0x1F) ||
252 (CommandBlock.SCSICommandLength == 0) ||
253 (CommandBlock.SCSICommandLength > MAX_SCSI_COMMAND_LENGTH))
254 {
255 /* Stall both data pipes until reset by host */
256 Endpoint_StallTransaction();
257 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
258 Endpoint_StallTransaction();
259
260 return false;
261 }
262
263 /* Read in command block command data */
264 Endpoint_Read_Stream_LE(&CommandBlock.SCSICommandData,
265 CommandBlock.SCSICommandLength,
266 StreamCallback_AbortOnMassStoreReset);
267
268 /* Check if the current command is being aborted by the host */
269 if (IsMassStoreReset)
270 return false;
271
272 /* Finalize the stream transfer to send the last packet */
273 Endpoint_ClearOUT();
274
275 return true;
276 }
277
278 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
279 * stalled data endpoints as needed.
280 */
281 static void ReturnCommandStatus(void)
282 {
283 /* Select the Data Out endpoint */
284 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
285
286 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
287 while (Endpoint_IsStalled())
288 {
289 /* Check if the current command is being aborted by the host */
290 if (IsMassStoreReset)
291 return;
292 }
293
294 /* Select the Data In endpoint */
295 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
296
297 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
298 while (Endpoint_IsStalled())
299 {
300 /* Check if the current command is being aborted by the host */
301 if (IsMassStoreReset)
302 return;
303 }
304
305 /* Write the CSW to the endpoint */
306 Endpoint_Write_Stream_LE(&CommandStatus, sizeof(CommandStatus),
307 StreamCallback_AbortOnMassStoreReset);
308
309 /* Check if the current command is being aborted by the host */
310 if (IsMassStoreReset)
311 return;
312
313 /* Finalize the stream transfer to send the last packet */
314 Endpoint_ClearIN();
315 }
316
317 /** Stream callback function for the Endpoint stream read and write functions. This callback will abort the current stream transfer
318 * if a Mass Storage Reset request has been issued to the control endpoint.
319 */
320 uint8_t StreamCallback_AbortOnMassStoreReset(void)
321 {
322 /* Abort if a Mass Storage reset command was received */
323 if (IsMassStoreReset)
324 return STREAMCALLBACK_Abort;
325
326 /* Continue with the current stream operation */
327 return STREAMCALLBACK_Continue;
328 }