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