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