Removed variable axis support from the HID_DESCRIPTOR_JOYSTICK() macro due to OS...
[pub/USBasp.git] / Demos / Device / LowLevel / MassStorage / MassStorage.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2012.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2012 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 MS_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 MS_CommandStatusWrapper_t CommandStatus = { .Signature = MS_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 sei();
59
60 for (;;)
61 {
62 MassStorage_Task();
63 USB_USBTask();
64 }
65 }
66
67 /** Configures the board hardware and chip peripherals for the demo's functionality. */
68 void SetupHardware(void)
69 {
70 /* Disable watchdog if enabled by bootloader/fuses */
71 MCUSR &= ~(1 << WDRF);
72 wdt_disable();
73
74 /* Disable clock division */
75 clock_prescale_set(clock_div_1);
76
77 /* Hardware Initialization */
78 LEDs_Init();
79 SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_ORDER_MSB_FIRST | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER);
80 Dataflash_Init();
81 USB_Init();
82
83 /* Check if the Dataflash is working, abort if not */
84 if (!(DataflashManager_CheckDataflashOperation()))
85 {
86 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
87 for(;;);
88 }
89
90 /* Clear Dataflash sector protections, if enabled */
91 DataflashManager_ResetDataflashProtections();
92 }
93
94 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
95 void EVENT_USB_Device_Connect(void)
96 {
97 /* Indicate USB enumerating */
98 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
99
100 /* Reset the MSReset flag upon connection */
101 IsMassStoreReset = false;
102 }
103
104 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
105 * the status LEDs and stops the Mass Storage management task.
106 */
107 void EVENT_USB_Device_Disconnect(void)
108 {
109 /* Indicate USB not ready */
110 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
111 }
112
113 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
114 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
115 */
116 void EVENT_USB_Device_ConfigurationChanged(void)
117 {
118 bool ConfigSuccess = true;
119
120 /* Setup Mass Storage Data Endpoints */
121 ConfigSuccess &= Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM, EP_TYPE_BULK, ENDPOINT_DIR_IN,
122 MASS_STORAGE_IO_EPSIZE, ENDPOINT_BANK_SINGLE);
123 ConfigSuccess &= Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM, EP_TYPE_BULK, ENDPOINT_DIR_OUT,
124 MASS_STORAGE_IO_EPSIZE, ENDPOINT_BANK_SINGLE);
125
126 /* Indicate endpoint configuration success or failure */
127 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
128 }
129
130 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
131 * the device from the USB host before passing along unhandled control requests to the library for processing
132 * internally.
133 */
134 void EVENT_USB_Device_ControlRequest(void)
135 {
136 /* Process UFI specific control requests */
137 switch (USB_ControlRequest.bRequest)
138 {
139 case MS_REQ_MassStorageReset:
140 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
141 {
142 Endpoint_ClearSETUP();
143 Endpoint_ClearStatusStage();
144
145 /* Indicate that the current transfer should be aborted */
146 IsMassStoreReset = true;
147 }
148
149 break;
150 case MS_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_8(TOTAL_LUNS - 1);
157
158 Endpoint_ClearIN();
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 /* Process sent command block from the host if one has been sent */
176 if (ReadInCommandBlock())
177 {
178 /* Indicate busy */
179 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
180
181 /* Check direction of command, select Data IN endpoint if data is from the device */
182 if (CommandBlock.Flags & MS_COMMAND_DIR_DATA_IN)
183 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
184
185 /* Decode the received SCSI command, set returned status code */
186 CommandStatus.Status = SCSI_DecodeSCSICommand() ? MS_SCSI_COMMAND_Pass : MS_SCSI_COMMAND_Fail;
187
188 /* Load in the CBW tag into the CSW to link them together */
189 CommandStatus.Tag = CommandBlock.Tag;
190
191 /* Load in the data residue counter into the CSW */
192 CommandStatus.DataTransferResidue = CommandBlock.DataTransferLength;
193
194 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
195 if ((CommandStatus.Status == MS_SCSI_COMMAND_Fail) && (CommandStatus.DataTransferResidue))
196 Endpoint_StallTransaction();
197
198 /* Return command status block to the host */
199 ReturnCommandStatus();
200
201 /* Indicate ready */
202 LEDs_SetAllLEDs(LEDMASK_USB_READY);
203 }
204
205 /* Check if a Mass Storage Reset occurred */
206 if (IsMassStoreReset)
207 {
208 /* Reset the data endpoint banks */
209 Endpoint_ResetEndpoint(MASS_STORAGE_OUT_EPNUM);
210 Endpoint_ResetEndpoint(MASS_STORAGE_IN_EPNUM);
211
212 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
213 Endpoint_ClearStall();
214 Endpoint_ResetDataToggle();
215 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
216 Endpoint_ClearStall();
217 Endpoint_ResetDataToggle();
218
219 /* Clear the abort transfer flag */
220 IsMassStoreReset = false;
221 }
222 }
223
224 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
225 * if one has been issued, and performs validation to ensure that the block command is valid.
226 *
227 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
228 */
229 static bool ReadInCommandBlock(void)
230 {
231 uint16_t BytesTransferred;
232
233 /* Select the Data Out endpoint */
234 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
235
236 /* Abort if no command has been sent from the host */
237 if (!(Endpoint_IsOUTReceived()))
238 return false;
239
240 /* Read in command block header */
241 BytesTransferred = 0;
242 while (Endpoint_Read_Stream_LE(&CommandBlock, (sizeof(CommandBlock) - sizeof(CommandBlock.SCSICommandData)),
243 &BytesTransferred) == ENDPOINT_RWSTREAM_IncompleteTransfer)
244 {
245 /* Check if the current command is being aborted by the host */
246 if (IsMassStoreReset)
247 return false;
248 }
249
250 /* Verify the command block - abort if invalid */
251 if ((CommandBlock.Signature != MS_CBW_SIGNATURE) ||
252 (CommandBlock.LUN >= TOTAL_LUNS) ||
253 (CommandBlock.Flags & 0x1F) ||
254 (CommandBlock.SCSICommandLength == 0) ||
255 (CommandBlock.SCSICommandLength > sizeof(CommandBlock.SCSICommandData)))
256 {
257 /* Stall both data pipes until reset by host */
258 Endpoint_StallTransaction();
259 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
260 Endpoint_StallTransaction();
261
262 return false;
263 }
264
265 /* Read in command block command data */
266 BytesTransferred = 0;
267 while (Endpoint_Read_Stream_LE(&CommandBlock.SCSICommandData, CommandBlock.SCSICommandLength,
268 &BytesTransferred) == ENDPOINT_RWSTREAM_IncompleteTransfer)
269 {
270 /* Check if the current command is being aborted by the host */
271 if (IsMassStoreReset)
272 return false;
273 }
274
275 /* Finalize the stream transfer to send the last packet */
276 Endpoint_ClearOUT();
277
278 return true;
279 }
280
281 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
282 * stalled data endpoints as needed.
283 */
284 static void ReturnCommandStatus(void)
285 {
286 uint16_t BytesTransferred;
287
288 /* Select the Data Out endpoint */
289 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM);
290
291 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
292 while (Endpoint_IsStalled())
293 {
294 /* Check if the current command is being aborted by the host */
295 if (IsMassStoreReset)
296 return;
297 }
298
299 /* Select the Data In endpoint */
300 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM);
301
302 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
303 while (Endpoint_IsStalled())
304 {
305 /* Check if the current command is being aborted by the host */
306 if (IsMassStoreReset)
307 return;
308 }
309
310 /* Write the CSW to the endpoint */
311 BytesTransferred = 0;
312 while (Endpoint_Write_Stream_LE(&CommandStatus, sizeof(CommandStatus),
313 &BytesTransferred) == ENDPOINT_RWSTREAM_IncompleteTransfer)
314 {
315 /* Check if the current command is being aborted by the host */
316 if (IsMassStoreReset)
317 return;
318 }
319
320 /* Finalize the stream transfer to send the last packet */
321 Endpoint_ClearIN();
322 }
323