Changed GenericHID device demo to use the LUFA scheduler, added INTERRUPT_DATA_ENDPOI...
[pub/USBasp.git] / Demos / Device / MassStorage / MassStorage.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 * 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 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName, "LUFA MassStore App");
42 BUTTLOADTAG(BuildTime, __TIME__);
43 BUTTLOADTAG(BuildDate, __DATE__);
44 BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);
45
46 /* Scheduler Task List */
47 TASK_LIST
48 {
49 { Task: USB_MassStorage , TaskStatus: TASK_STOP },
50 };
51
52 /* Global Variables */
53 /** Structure to hold the latest Command Block Wrapper issued by the host, containing a SCSI command to execute. */
54 CommandBlockWrapper_t CommandBlock;
55
56 /** Structure to hold the latest Command Status Wrapper to return to the host, containing the status of the last issued command. */
57 CommandStatusWrapper_t CommandStatus = { Signature: CSW_SIGNATURE };
58
59 /** Flag to asyncronously abort any in-progress data transfers upon the reception of a mass storage reset command. */
60 volatile bool IsMassStoreReset = false;
61
62 /** Main program entry point. This routine configures the hardware required by the application, then
63 * starts the scheduler to run the application tasks.
64 */
65 int main(void)
66 {
67 /* Disable watchdog if enabled by bootloader/fuses */
68 MCUSR &= ~(1 << WDRF);
69 wdt_disable();
70
71 /* Disable clock division */
72 clock_prescale_set(clock_div_1);
73
74 /* Hardware Initialization */
75 LEDs_Init();
76 Dataflash_Init(SPI_SPEED_FCPU_DIV_2);
77
78 /* Clear Dataflash sector protections, if enabled */
79 DataflashManager_ResetDataflashProtections();
80
81 /* Indicate USB not ready */
82 UpdateStatus(Status_USBNotReady);
83
84 /* Initialize Scheduler so that it can be used */
85 Scheduler_Init();
86
87 /* Initialize USB Subsystem */
88 USB_Init();
89
90 /* Scheduling - routine never returns, so put this last in the main function */
91 Scheduler_Start();
92 }
93
94 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
95 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
96 * asynchronously when they arrive rather than when the control endpoint is polled manually.
97 */
98 EVENT_HANDLER(USB_Reset)
99 {
100 /* Select the control endpoint */
101 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
102
103 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
104 USB_INT_Enable(ENDPOINT_INT_SETUP);
105 }
106
107 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
108 EVENT_HANDLER(USB_Connect)
109 {
110 /* Indicate USB enumerating */
111 UpdateStatus(Status_USBEnumerating);
112
113 /* Reset the MSReset flag upon connection */
114 IsMassStoreReset = false;
115 }
116
117 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
118 * the status LEDs and stops the Mass Storage management task.
119 */
120 EVENT_HANDLER(USB_Disconnect)
121 {
122 /* Stop running mass storage task */
123 Scheduler_SetTaskMode(USB_MassStorage, TASK_STOP);
124
125 /* Indicate USB not ready */
126 UpdateStatus(Status_USBNotReady);
127 }
128
129 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
130 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
131 */
132 EVENT_HANDLER(USB_ConfigurationChanged)
133 {
134 /* Setup Mass Storage In and Out Endpoints */
135 Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM, EP_TYPE_BULK,
136 ENDPOINT_DIR_IN, MASS_STORAGE_IO_EPSIZE,
137 ENDPOINT_BANK_DOUBLE);
138
139 Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM, EP_TYPE_BULK,
140 ENDPOINT_DIR_OUT, MASS_STORAGE_IO_EPSIZE,
141 ENDPOINT_BANK_DOUBLE);
142
143 /* Indicate USB connected and ready */
144 UpdateStatus(Status_USBReady);
145
146 /* Start mass storage task */
147 Scheduler_SetTaskMode(USB_MassStorage, TASK_RUN);
148 }
149
150 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
151 * control requests that are not handled internally by the USB library (including the Mass Storage class-specific
152 * requests) so that they can be handled appropriately for the application.
153 */
154 EVENT_HANDLER(USB_UnhandledControlPacket)
155 {
156 /* Process UFI specific control requests */
157 switch (bRequest)
158 {
159 case REQ_MassStorageReset:
160 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
161 {
162 Endpoint_ClearSetupReceived();
163
164 /* Indicate that the current transfer should be aborted */
165 IsMassStoreReset = true;
166
167 /* Acknowledge status stage */
168 while (!(Endpoint_IsSetupINReady()));
169 Endpoint_ClearSetupIN();
170 }
171
172 break;
173 case REQ_GetMaxLUN:
174 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
175 {
176 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
177 Endpoint_ClearSetupReceived();
178
179 Endpoint_Write_Byte(TOTAL_LUNS - 1);
180
181 Endpoint_ClearSetupIN();
182
183 /* Acknowledge status stage */
184 while (!(Endpoint_IsSetupOUTReceived()));
185 Endpoint_ClearSetupOUT();
186 }
187
188 break;
189 }
190 }
191
192 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
193 * log to a serial port, or anything else that is suitable for status updates.
194 *
195 * \param CurrentStatus Current status of the system, from the MassStorage_StatusCodes_t enum
196 */
197 void UpdateStatus(uint8_t CurrentStatus)
198 {
199 uint8_t LEDMask = LEDS_NO_LEDS;
200
201 /* Set the LED mask to the appropriate LED mask based on the given status code */
202 switch (CurrentStatus)
203 {
204 case Status_USBNotReady:
205 LEDMask = (LEDS_LED1);
206 break;
207 case Status_USBEnumerating:
208 LEDMask = (LEDS_LED1 | LEDS_LED2);
209 break;
210 case Status_USBReady:
211 LEDMask = (LEDS_LED2 | LEDS_LED4);
212 break;
213 case Status_CommandBlockError:
214 LEDMask = (LEDS_LED1);
215 break;
216 case Status_ProcessingCommandBlock:
217 LEDMask = (LEDS_LED1 | LEDS_LED2);
218 break;
219 }
220
221 /* Set the board LEDs to the new LED mask */
222 LEDs_SetAllLEDs(LEDMask);
223 }
224
225 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
226 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
227 */
228 TASK(USB_MassStorage)
229 {
230 /* Check if the USB System is connected to a Host */
231 if (USB_IsConnected)
232 {
233 /* Select the Data Out Endpoint */
234 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
235
236 /* Check to see if a command from the host has been issued */
237 if (Endpoint_ReadWriteAllowed())
238 {
239 /* Indicate busy */
240 UpdateStatus(Status_ProcessingCommandBlock);
241
242 /* Process sent command block from the host */
243 if (ReadInCommandBlock())
244 {
245 /* Check direction of command, select Data IN endpoint if data is from the device */
246 if (CommandBlock.Flags & COMMAND_DIRECTION_DATA_IN)
247 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
248
249 /* Decode the received SCSI command */
250 SCSI_DecodeSCSICommand();
251
252 /* Load in the CBW tag into the CSW to link them together */
253 CommandStatus.Tag = CommandBlock.Tag;
254
255 /* Load in the data residue counter into the CSW */
256 CommandStatus.DataTransferResidue = CommandBlock.DataTransferLength;
257
258 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
259 if ((CommandStatus.Status == Command_Fail) && (CommandStatus.DataTransferResidue))
260 Endpoint_StallTransaction();
261
262 /* Return command status block to the host */
263 ReturnCommandStatus();
264
265 /* Check if a Mass Storage Reset ocurred */
266 if (IsMassStoreReset)
267 {
268 /* Reset the data endpoint banks */
269 Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM);
270 Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM);
271
272 /* Clear the abort transfer flag */
273 IsMassStoreReset = false;
274 }
275
276 /* Indicate ready */
277 UpdateStatus(Status_USBReady);
278 }
279 else
280 {
281 /* Indicate error reading in the command block from the host */
282 UpdateStatus(Status_CommandBlockError);
283 }
284 }
285 }
286 }
287
288 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
289 * if one has been issued, and performs validation to ensure that the block command is valid.
290 *
291 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
292 */
293 static bool ReadInCommandBlock(void)
294 {
295 /* Select the Data Out endpoint */
296 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
297
298 /* Read in command block header */
299 Endpoint_Read_Stream_LE(&CommandBlock, (sizeof(CommandBlock) - sizeof(CommandBlock.SCSICommandData)),
300 AbortOnMassStoreReset);
301
302 /* Check if the current command is being aborted by the host */
303 if (IsMassStoreReset)
304 return false;
305
306 /* Verify the command block - abort if invalid */
307 if ((CommandBlock.Signature != CBW_SIGNATURE) ||
308 (CommandBlock.LUN >= TOTAL_LUNS) ||
309 (CommandBlock.SCSICommandLength > MAX_SCSI_COMMAND_LENGTH))
310 {
311 /* Stall both data pipes until reset by host */
312 Endpoint_StallTransaction();
313 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
314 Endpoint_StallTransaction();
315
316 return false;
317 }
318
319 /* Read in command block command data */
320 Endpoint_Read_Stream_LE(&CommandBlock.SCSICommandData,
321 CommandBlock.SCSICommandLength,
322 AbortOnMassStoreReset);
323
324 /* Check if the current command is being aborted by the host */
325 if (IsMassStoreReset)
326 return false;
327
328 /* Finalize the stream transfer to send the last packet */
329 Endpoint_ClearCurrentBank();
330
331 return true;
332 }
333
334 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
335 * stalled data endpoints as needed.
336 */
337 static void ReturnCommandStatus(void)
338 {
339 /* Select the Data Out endpoint */
340 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
341
342 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
343 while (Endpoint_IsStalled())
344 {
345 /* Check if the current command is being aborted by the host */
346 if (IsMassStoreReset)
347 return;
348 }
349
350 /* Select the Data In endpoint */
351 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
352
353 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
354 while (Endpoint_IsStalled())
355 {
356 /* Check if the current command is being aborted by the host */
357 if (IsMassStoreReset)
358 return;
359 }
360
361 /* Write the CSW to the endpoint */
362 Endpoint_Write_Stream_LE(&CommandStatus, sizeof(CommandStatus),
363 AbortOnMassStoreReset);
364
365 /* Check if the current command is being aborted by the host */
366 if (IsMassStoreReset)
367 return;
368
369 /* Finalize the stream transfer to send the last packet */
370 Endpoint_ClearCurrentBank();
371 }
372
373 /** Stream callback function for the Endpoint stream read and write functions. This callback will abort the current stream transfer
374 * if a Mass Storage Reset request has been issued to the control endpoint.
375 */
376 STREAM_CALLBACK(AbortOnMassStoreReset)
377 {
378 /* Abort if a Mass Storage reset command was received */
379 if (IsMassStoreReset)
380 return STREAMCALLBACK_Abort;
381
382 /* Continue with the current stream operation */
383 return STREAMCALLBACK_Continue;
384 }
385
386 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when a control request has been issued to the control endpoint,
387 * so that the request can be processed. As several elements of the Mass Storage implementation require asynchronous control requests
388 * (such as endpoint stall clearing and Mass Storage Reset requests during data transfers) this is done via interrupts rather than
389 * polling.
390 */
391 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
392 {
393 /* Check if the control endpoint has received a request */
394 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
395 {
396 /* Clear the endpoint interrupt */
397 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
398
399 /* Process the control request */
400 USB_USBTask();
401
402 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
403 USB_INT_Clear(ENDPOINT_INT_SETUP);
404 }
405 }