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