New revision Benito hardware will be 16MHz, and use the ATMEGA32U2. Change makefile...
[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
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 SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER);
79 Dataflash_Init();
80 USB_Init();
81
82 /* Clear Dataflash sector protections, if enabled */
83 DataflashManager_ResetDataflashProtections();
84 }
85
86 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
87 void EVENT_USB_Device_Connect(void)
88 {
89 /* Indicate USB enumerating */
90 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
91
92 /* Reset the MSReset flag upon connection */
93 IsMassStoreReset = false;
94 }
95
96 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
97 * the status LEDs and stops the Mass Storage management task.
98 */
99 void EVENT_USB_Device_Disconnect(void)
100 {
101 /* Indicate USB not ready */
102 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
103 }
104
105 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
106 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
107 */
108 void EVENT_USB_Device_ConfigurationChanged(void)
109 {
110 /* Indicate USB connected and ready */
111 LEDs_SetAllLEDs(LEDMASK_USB_READY);
112
113 /* Setup Mass Storage In and Out Endpoints */
114 if (!(Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM, EP_TYPE_BULK,
115 ENDPOINT_DIR_IN, MASS_STORAGE_IO_EPSIZE,
116 ENDPOINT_BANK_DOUBLE)))
117 {
118 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
119 }
120
121 if (!(Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM, EP_TYPE_BULK,
122 ENDPOINT_DIR_OUT, MASS_STORAGE_IO_EPSIZE,
123 ENDPOINT_BANK_DOUBLE)))
124 {
125 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
126 }
127 }
128
129 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
130 * control requests that are not handled internally by the USB library (including the Mass Storage class-specific
131 * requests) so that they can be handled appropriately for the application.
132 */
133 void EVENT_USB_Device_UnhandledControlRequest(void)
134 {
135 /* Process UFI specific control requests */
136 switch (USB_ControlRequest.bRequest)
137 {
138 case REQ_MassStorageReset:
139 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
140 {
141 Endpoint_ClearSETUP();
142
143 /* Indicate that the current transfer should be aborted */
144 IsMassStoreReset = true;
145
146 Endpoint_ClearStatusStage();
147 }
148
149 break;
150 case REQ_GetMaxLUN:
151 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
152 {
153 Endpoint_ClearSETUP();
154
155 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
156 Endpoint_Write_Byte(TOTAL_LUNS - 1);
157
158 Endpoint_ClearIN();
159
160 Endpoint_ClearStatusStage();
161 }
162
163 break;
164 }
165 }
166
167 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
168 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
169 */
170 void MassStorage_Task(void)
171 {
172 /* Device must be connected and configured for the task to run */
173 if (USB_DeviceState != DEVICE_STATE_Configured)
174 return;
175
176 /* Select the Data Out Endpoint */
177 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
178
179 /* Check to see if a command from the host has been issued */
180 if (Endpoint_IsReadWriteAllowed())
181 {
182 /* Indicate busy */
183 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
184
185 /* Process sent command block from the host */
186 if (ReadInCommandBlock())
187 {
188 /* Check direction of command, select Data IN endpoint if data is from the device */
189 if (CommandBlock.Flags & COMMAND_DIRECTION_DATA_IN)
190 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
191
192 /* Decode the received SCSI command, set returned status code */
193 CommandStatus.Status = SCSI_DecodeSCSICommand() ? Command_Pass : Command_Fail;
194
195 /* Load in the CBW tag into the CSW to link them together */
196 CommandStatus.Tag = CommandBlock.Tag;
197
198 /* Load in the data residue counter into the CSW */
199 CommandStatus.DataTransferResidue = CommandBlock.DataTransferLength;
200
201 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
202 if ((CommandStatus.Status == Command_Fail) && (CommandStatus.DataTransferResidue))
203 Endpoint_StallTransaction();
204
205 /* Return command status block to the host */
206 ReturnCommandStatus();
207
208 /* Indicate ready */
209 LEDs_SetAllLEDs(LEDMASK_USB_READY);
210 }
211 else
212 {
213 /* Indicate error reading in the command block from the host */
214 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
215 }
216 }
217
218 /* Check if a Mass Storage Reset occurred */
219 if (IsMassStoreReset)
220 {
221 /* Reset the data endpoint banks */
222 Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM);
223 Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM);
224
225 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
226 Endpoint_ClearStall();
227 Endpoint_ResetDataToggle();
228 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
229 Endpoint_ClearStall();
230 Endpoint_ResetDataToggle();
231
232 /* Clear the abort transfer flag */
233 IsMassStoreReset = false;
234 }
235 }
236
237 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
238 * if one has been issued, and performs validation to ensure that the block command is valid.
239 *
240 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
241 */
242 static bool ReadInCommandBlock(void)
243 {
244 /* Select the Data Out endpoint */
245 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
246
247 /* Read in command block header */
248 Endpoint_Read_Stream_LE(&CommandBlock, (sizeof(CommandBlock) - sizeof(CommandBlock.SCSICommandData)),
249 StreamCallback_AbortOnMassStoreReset);
250
251 /* Check if the current command is being aborted by the host */
252 if (IsMassStoreReset)
253 return false;
254
255 /* Verify the command block - abort if invalid */
256 if ((CommandBlock.Signature != CBW_SIGNATURE) ||
257 (CommandBlock.LUN >= TOTAL_LUNS) ||
258 (CommandBlock.Flags & 0x1F) ||
259 (CommandBlock.SCSICommandLength == 0) ||
260 (CommandBlock.SCSICommandLength > MAX_SCSI_COMMAND_LENGTH))
261 {
262 /* Stall both data pipes until reset by host */
263 Endpoint_StallTransaction();
264 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
265 Endpoint_StallTransaction();
266
267 return false;
268 }
269
270 /* Read in command block command data */
271 Endpoint_Read_Stream_LE(&CommandBlock.SCSICommandData,
272 CommandBlock.SCSICommandLength,
273 StreamCallback_AbortOnMassStoreReset);
274
275 /* Check if the current command is being aborted by the host */
276 if (IsMassStoreReset)
277 return false;
278
279 /* Finalize the stream transfer to send the last packet */
280 Endpoint_ClearOUT();
281
282 return true;
283 }
284
285 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
286 * stalled data endpoints as needed.
287 */
288 static void ReturnCommandStatus(void)
289 {
290 /* Select the Data Out endpoint */
291 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
292
293 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
294 while (Endpoint_IsStalled())
295 {
296 /* Check if the current command is being aborted by the host */
297 if (IsMassStoreReset)
298 return;
299 }
300
301 /* Select the Data In endpoint */
302 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
303
304 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
305 while (Endpoint_IsStalled())
306 {
307 /* Check if the current command is being aborted by the host */
308 if (IsMassStoreReset)
309 return;
310 }
311
312 /* Write the CSW to the endpoint */
313 Endpoint_Write_Stream_LE(&CommandStatus, sizeof(CommandStatus),
314 StreamCallback_AbortOnMassStoreReset);
315
316 /* Check if the current command is being aborted by the host */
317 if (IsMassStoreReset)
318 return;
319
320 /* Finalize the stream transfer to send the last packet */
321 Endpoint_ClearIN();
322 }
323
324 /** Stream callback function for the Endpoint stream read and write functions. This callback will abort the current stream transfer
325 * if a Mass Storage Reset request has been issued to the control endpoint.
326 */
327 uint8_t StreamCallback_AbortOnMassStoreReset(void)
328 {
329 /* Abort if a Mass Storage reset command was received */
330 if (IsMassStoreReset)
331 return STREAMCALLBACK_Abort;
332
333 /* Continue with the current stream operation */
334 return STREAMCALLBACK_Continue;
335 }