62c7f21da7831c70dc7fa225f6fe51fcdd958255
[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 /* Setup Mass Storage In and Out Endpoints */
110 Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM, EP_TYPE_BULK,
111 ENDPOINT_DIR_IN, MASS_STORAGE_IO_EPSIZE,
112 ENDPOINT_BANK_DOUBLE);
113
114 Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM, EP_TYPE_BULK,
115 ENDPOINT_DIR_OUT, MASS_STORAGE_IO_EPSIZE,
116 ENDPOINT_BANK_DOUBLE);
117
118 /* Indicate USB connected and ready */
119 LEDs_SetAllLEDs(LEDMASK_USB_READY);
120 }
121
122 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
123 * control requests that are not handled internally by the USB library (including the Mass Storage class-specific
124 * requests) so that they can be handled appropriately for the application.
125 */
126 void EVENT_USB_UnhandledControlPacket(void)
127 {
128 /* Process UFI specific control requests */
129 switch (USB_ControlRequest.bRequest)
130 {
131 case REQ_MassStorageReset:
132 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
133 {
134 Endpoint_ClearSETUP();
135
136 /* Indicate that the current transfer should be aborted */
137 IsMassStoreReset = true;
138
139 /* Acknowledge status stage */
140 while (!(Endpoint_IsINReady()));
141 Endpoint_ClearIN();
142 }
143
144 break;
145 case REQ_GetMaxLUN:
146 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
147 {
148 Endpoint_ClearSETUP();
149
150 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
151 Endpoint_Write_Byte(TOTAL_LUNS - 1);
152
153 Endpoint_ClearIN();
154
155 /* Acknowledge status stage */
156 while (!(Endpoint_IsOUTReceived()));
157 Endpoint_ClearOUT();
158 }
159
160 break;
161 }
162 }
163
164 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
165 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
166 */
167 void MassStorage_Task(void)
168 {
169 /* Check if the USB System is connected to a Host */
170 if (USB_IsConnected)
171 {
172 /* Select the Data Out Endpoint */
173 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
174
175 /* Check to see if a command from the host has been issued */
176 if (Endpoint_IsReadWriteAllowed())
177 {
178 /* Indicate busy */
179 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
180
181 /* Process sent command block from the host */
182 if (ReadInCommandBlock())
183 {
184 /* Check direction of command, select Data IN endpoint if data is from the device */
185 if (CommandBlock.Flags & COMMAND_DIRECTION_DATA_IN)
186 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
187
188 /* Decode the received SCSI command */
189 SCSI_DecodeSCSICommand();
190
191 /* Load in the CBW tag into the CSW to link them together */
192 CommandStatus.Tag = CommandBlock.Tag;
193
194 /* Load in the data residue counter into the CSW */
195 CommandStatus.DataTransferResidue = CommandBlock.DataTransferLength;
196
197 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
198 if ((CommandStatus.Status == Command_Fail) && (CommandStatus.DataTransferResidue))
199 Endpoint_StallTransaction();
200
201 /* Return command status block to the host */
202 ReturnCommandStatus();
203
204 /* Check if a Mass Storage Reset occurred */
205 if (IsMassStoreReset)
206 {
207 /* Reset the data endpoint banks */
208 Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM);
209 Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM);
210
211 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
212 Endpoint_ClearStall();
213 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
214 Endpoint_ClearStall();
215
216 /* Clear the abort transfer flag */
217 IsMassStoreReset = false;
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 }
231
232 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
233 * if one has been issued, and performs validation to ensure that the block command is valid.
234 *
235 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
236 */
237 static bool ReadInCommandBlock(void)
238 {
239 /* Select the Data Out endpoint */
240 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
241
242 /* Read in command block header */
243 Endpoint_Read_Stream_LE(&CommandBlock, (sizeof(CommandBlock) - sizeof(CommandBlock.SCSICommandData)),
244 StreamCallback_AbortOnMassStoreReset);
245
246 /* Check if the current command is being aborted by the host */
247 if (IsMassStoreReset)
248 return false;
249
250 /* Verify the command block - abort if invalid */
251 if ((CommandBlock.Signature != CBW_SIGNATURE) ||
252 (CommandBlock.LUN >= TOTAL_LUNS) ||
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 }