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