Fix typo in the Atmel Studio integration Getting Started page.
[pub/USBasp.git] / Demos / Device / LowLevel / MassStorage / MassStorage.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2013.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2013 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 disclaims 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 GlobalInterruptEnable();
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 #if (ARCH == ARCH_AVR8)
71 /* Disable watchdog if enabled by bootloader/fuses */
72 MCUSR &= ~(1 << WDRF);
73 wdt_disable();
74
75 /* Disable clock division */
76 clock_prescale_set(clock_div_1);
77 #elif (ARCH == ARCH_XMEGA)
78 /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
79 XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
80 XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
81
82 /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
83 XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
84 XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
85
86 PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
87 #endif
88
89 /* Hardware Initialization */
90 LEDs_Init();
91 SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_ORDER_MSB_FIRST | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER);
92 Dataflash_Init();
93 USB_Init();
94
95 /* Check if the Dataflash is working, abort if not */
96 if (!(DataflashManager_CheckDataflashOperation()))
97 {
98 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
99 for(;;);
100 }
101
102 /* Clear Dataflash sector protections, if enabled */
103 DataflashManager_ResetDataflashProtections();
104 }
105
106 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
107 void EVENT_USB_Device_Connect(void)
108 {
109 /* Indicate USB enumerating */
110 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
111
112 /* Reset the MSReset flag upon connection */
113 IsMassStoreReset = false;
114 }
115
116 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
117 * the status LEDs and stops the Mass Storage management task.
118 */
119 void EVENT_USB_Device_Disconnect(void)
120 {
121 /* Indicate USB not ready */
122 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
123 }
124
125 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
126 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
127 */
128 void EVENT_USB_Device_ConfigurationChanged(void)
129 {
130 bool ConfigSuccess = true;
131
132 /* Setup Mass Storage Data Endpoints */
133 ConfigSuccess &= Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPADDR, EP_TYPE_BULK, MASS_STORAGE_IO_EPSIZE, 1);
134 ConfigSuccess &= Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPADDR, EP_TYPE_BULK, MASS_STORAGE_IO_EPSIZE, 1);
135
136 /* Indicate endpoint configuration success or failure */
137 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
138 }
139
140 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
141 * the device from the USB host before passing along unhandled control requests to the library for processing
142 * internally.
143 */
144 void EVENT_USB_Device_ControlRequest(void)
145 {
146 /* Process UFI specific control requests */
147 switch (USB_ControlRequest.bRequest)
148 {
149 case MS_REQ_MassStorageReset:
150 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
151 {
152 Endpoint_ClearSETUP();
153 Endpoint_ClearStatusStage();
154
155 /* Indicate that the current transfer should be aborted */
156 IsMassStoreReset = true;
157 }
158
159 break;
160 case MS_REQ_GetMaxLUN:
161 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
162 {
163 Endpoint_ClearSETUP();
164
165 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
166 Endpoint_Write_8(TOTAL_LUNS - 1);
167
168 Endpoint_ClearIN();
169 Endpoint_ClearStatusStage();
170 }
171
172 break;
173 }
174 }
175
176 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
177 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
178 */
179 void MassStorage_Task(void)
180 {
181 /* Device must be connected and configured for the task to run */
182 if (USB_DeviceState != DEVICE_STATE_Configured)
183 return;
184
185 /* Process sent command block from the host if one has been sent */
186 if (ReadInCommandBlock())
187 {
188 /* Indicate busy */
189 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
190
191 /* Check direction of command, select Data IN endpoint if data is from the device */
192 if (CommandBlock.Flags & MS_COMMAND_DIR_DATA_IN)
193 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR);
194
195 /* Decode the received SCSI command, set returned status code */
196 CommandStatus.Status = SCSI_DecodeSCSICommand() ? MS_SCSI_COMMAND_Pass : MS_SCSI_COMMAND_Fail;
197
198 /* Load in the CBW tag into the CSW to link them together */
199 CommandStatus.Tag = CommandBlock.Tag;
200
201 /* Load in the data residue counter into the CSW */
202 CommandStatus.DataTransferResidue = CommandBlock.DataTransferLength;
203
204 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
205 if ((CommandStatus.Status == MS_SCSI_COMMAND_Fail) && (CommandStatus.DataTransferResidue))
206 Endpoint_StallTransaction();
207
208 /* Return command status block to the host */
209 ReturnCommandStatus();
210
211 /* Indicate ready */
212 LEDs_SetAllLEDs(LEDMASK_USB_READY);
213 }
214
215 /* Check if a Mass Storage Reset occurred */
216 if (IsMassStoreReset)
217 {
218 /* Reset the data endpoint banks */
219 Endpoint_ResetEndpoint(MASS_STORAGE_OUT_EPADDR);
220 Endpoint_ResetEndpoint(MASS_STORAGE_IN_EPADDR);
221
222 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPADDR);
223 Endpoint_ClearStall();
224 Endpoint_ResetDataToggle();
225 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR);
226 Endpoint_ClearStall();
227 Endpoint_ResetDataToggle();
228
229 /* Clear the abort transfer flag */
230 IsMassStoreReset = false;
231 }
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 \c true if a valid command block has been read in from the endpoint, \c false otherwise
238 */
239 static bool ReadInCommandBlock(void)
240 {
241 uint16_t BytesTransferred;
242
243 /* Select the Data Out endpoint */
244 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPADDR);
245
246 /* Abort if no command has been sent from the host */
247 if (!(Endpoint_IsOUTReceived()))
248 return false;
249
250 /* Read in command block header */
251 BytesTransferred = 0;
252 while (Endpoint_Read_Stream_LE(&CommandBlock, (sizeof(CommandBlock) - sizeof(CommandBlock.SCSICommandData)),
253 &BytesTransferred) == ENDPOINT_RWSTREAM_IncompleteTransfer)
254 {
255 /* Check if the current command is being aborted by the host */
256 if (IsMassStoreReset)
257 return false;
258 }
259
260 /* Verify the command block - abort if invalid */
261 if ((CommandBlock.Signature != MS_CBW_SIGNATURE) ||
262 (CommandBlock.LUN >= TOTAL_LUNS) ||
263 (CommandBlock.Flags & 0x1F) ||
264 (CommandBlock.SCSICommandLength == 0) ||
265 (CommandBlock.SCSICommandLength > sizeof(CommandBlock.SCSICommandData)))
266 {
267 /* Stall both data pipes until reset by host */
268 Endpoint_StallTransaction();
269 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR);
270 Endpoint_StallTransaction();
271
272 return false;
273 }
274
275 /* Read in command block command data */
276 BytesTransferred = 0;
277 while (Endpoint_Read_Stream_LE(&CommandBlock.SCSICommandData, CommandBlock.SCSICommandLength,
278 &BytesTransferred) == ENDPOINT_RWSTREAM_IncompleteTransfer)
279 {
280 /* Check if the current command is being aborted by the host */
281 if (IsMassStoreReset)
282 return false;
283 }
284
285 /* Finalize the stream transfer to send the last packet */
286 Endpoint_ClearOUT();
287
288 return true;
289 }
290
291 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
292 * stalled data endpoints as needed.
293 */
294 static void ReturnCommandStatus(void)
295 {
296 uint16_t BytesTransferred;
297
298 /* Select the Data Out endpoint */
299 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPADDR);
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 /* Select the Data In endpoint */
310 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR);
311
312 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
313 while (Endpoint_IsStalled())
314 {
315 /* Check if the current command is being aborted by the host */
316 if (IsMassStoreReset)
317 return;
318 }
319
320 /* Write the CSW to the endpoint */
321 BytesTransferred = 0;
322 while (Endpoint_Write_Stream_LE(&CommandStatus, sizeof(CommandStatus),
323 &BytesTransferred) == ENDPOINT_RWSTREAM_IncompleteTransfer)
324 {
325 /* Check if the current command is being aborted by the host */
326 if (IsMassStoreReset)
327 return;
328 }
329
330 /* Finalize the stream transfer to send the last packet */
331 Endpoint_ClearIN();
332 }
333