3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 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.
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
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.
37 #define INCLUDE_FROM_MASSSTORAGE_C
38 #include "MassStorage.h"
40 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName
, "LUFA MassStore App");
42 BUTTLOADTAG(BuildTime
, __TIME__
);
43 BUTTLOADTAG(BuildDate
, __DATE__
);
44 BUTTLOADTAG(LUFAVersion
, "LUFA V" LUFA_VERSION_STRING
);
46 /* Scheduler Task List */
49 { Task
: USB_MassStorage
, TaskStatus
: TASK_STOP
},
52 /* Global Variables */
53 /** Structure to hold the latest Command Block Wrapper issued by the host, containing a SCSI command to execute. */
54 CommandBlockWrapper_t CommandBlock
;
56 /** Structure to hold the latest Command Status Wrapper to return to the host, containing the status of the last issued command. */
57 CommandStatusWrapper_t CommandStatus
= { Signature
: CSW_SIGNATURE
};
59 /** Flag to asyncronously abort any in-progress data transfers upon the reception of a mass storage reset command. */
60 volatile bool IsMassStoreReset
= false;
62 /** Main program entry point. This routine configures the hardware required by the application, then
63 * starts the scheduler to run the application tasks.
67 /* Disable watchdog if enabled by bootloader/fuses */
68 MCUSR
&= ~(1 << WDRF
);
71 /* Disable Clock Division */
72 SetSystemClockPrescaler(0);
74 /* Hardware Initialization */
76 Dataflash_Init(SPI_SPEED_FCPU_DIV_2
);
78 /* Clear Dataflash sector protections, if enabled */
79 DataflashManager_ResetDataflashProtections();
81 /* Indicate USB not ready */
82 UpdateStatus(Status_USBNotReady
);
84 /* Initialize Scheduler so that it can be used */
87 /* Initialize USB Subsystem */
90 /* Scheduling - routine never returns, so put this last in the main function */
94 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
95 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
96 * asynchronously when they arrive rather than when the control endpoint is polled manually.
98 EVENT_HANDLER(USB_Reset
)
100 /* Select the control endpoint */
101 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
);
103 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
104 USB_INT_Enable(ENDPOINT_INT_SETUP
);
107 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
108 EVENT_HANDLER(USB_Connect
)
110 /* Indicate USB enumerating */
111 UpdateStatus(Status_USBEnumerating
);
113 /* Reset the MSReset flag upon connection */
114 IsMassStoreReset
= false;
117 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
118 * the status LEDs and stops the Mass Storage management task.
120 EVENT_HANDLER(USB_Disconnect
)
122 /* Stop running mass storage task */
123 Scheduler_SetTaskMode(USB_MassStorage
, TASK_STOP
);
125 /* Indicate USB not ready */
126 UpdateStatus(Status_USBNotReady
);
129 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
130 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
132 EVENT_HANDLER(USB_ConfigurationChanged
)
134 /* Setup Mass Storage In and Out Endpoints */
135 Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM
, EP_TYPE_BULK
,
136 ENDPOINT_DIR_IN
, MASS_STORAGE_IO_EPSIZE
,
137 ENDPOINT_BANK_DOUBLE
);
139 Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM
, EP_TYPE_BULK
,
140 ENDPOINT_DIR_OUT
, MASS_STORAGE_IO_EPSIZE
,
141 ENDPOINT_BANK_DOUBLE
);
143 /* Indicate USB connected and ready */
144 UpdateStatus(Status_USBReady
);
146 /* Start mass storage task */
147 Scheduler_SetTaskMode(USB_MassStorage
, TASK_RUN
);
150 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
151 * control requests that are not handled internally by the USB library (including the Mass Storage class-specific
152 * requests) so that they can be handled appropriately for the application.
154 EVENT_HANDLER(USB_UnhandledControlPacket
)
156 /* Process UFI specific control requests */
159 case REQ_MassStorageReset
:
160 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
162 /* Indicate that the current transfer should be aborted */
163 IsMassStoreReset
= true;
165 Endpoint_ClearSetupReceived();
166 Endpoint_ClearSetupIN();
171 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
173 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
174 Endpoint_ClearSetupReceived();
175 Endpoint_Write_Byte(TOTAL_LUNS
- 1);
176 Endpoint_ClearSetupIN();
183 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
184 * log to a serial port, or anything else that is suitable for status updates.
186 * \param CurrentStatus Current status of the system, from the MassStorage_StatusCodes_t enum
188 void UpdateStatus(uint8_t CurrentStatus
)
190 uint8_t LEDMask
= LEDS_NO_LEDS
;
192 /* Set the LED mask to the appropriate LED mask based on the given status code */
193 switch (CurrentStatus
)
195 case Status_USBNotReady
:
196 LEDMask
= (LEDS_LED1
);
198 case Status_USBEnumerating
:
199 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
201 case Status_USBReady
:
202 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
204 case Status_CommandBlockError
:
205 LEDMask
= (LEDS_LED1
);
207 case Status_ProcessingCommandBlock
:
208 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
212 /* Set the board LEDs to the new LED mask */
213 LEDs_SetAllLEDs(LEDMask
);
216 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
217 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
219 TASK(USB_MassStorage
)
221 /* Check if the USB System is connected to a Host */
224 /* Select the Data Out Endpoint */
225 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
227 /* Check to see if a command from the host has been issued */
228 if (Endpoint_ReadWriteAllowed())
231 UpdateStatus(Status_ProcessingCommandBlock
);
233 /* Process sent command block from the host */
234 if (ReadInCommandBlock())
236 /* Check direction of command, select Data IN endpoint if data is from the device */
237 if (CommandBlock
.Flags
& COMMAND_DIRECTION_DATA_IN
)
238 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
240 /* Decode the received SCSI command */
241 SCSI_DecodeSCSICommand();
243 /* Load in the CBW tag into the CSW to link them together */
244 CommandStatus
.Tag
= CommandBlock
.Tag
;
246 /* Load in the data residue counter into the CSW */
247 CommandStatus
.DataTransferResidue
= CommandBlock
.DataTransferLength
;
249 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
250 if ((CommandStatus
.Status
== Command_Fail
) && (CommandStatus
.DataTransferResidue
))
251 Endpoint_StallTransaction();
253 /* Return command status block to the host */
254 ReturnCommandStatus();
256 /* Check if a Mass Storage Reset ocurred */
257 if (IsMassStoreReset
)
259 /* Reset the data endpoint banks */
260 Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM
);
261 Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM
);
263 /* Clear the abort transfer flag */
264 IsMassStoreReset
= false;
268 UpdateStatus(Status_USBReady
);
272 /* Indicate error reading in the command block from the host */
273 UpdateStatus(Status_CommandBlockError
);
279 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
280 * if one has been issued, and performs validation to ensure that the block command is valid.
282 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
284 static bool ReadInCommandBlock(void)
286 /* Select the Data Out endpoint */
287 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
289 /* Read in command block header */
290 Endpoint_Read_Stream_LE(&CommandBlock
, (sizeof(CommandBlock
) - sizeof(CommandBlock
.SCSICommandData
)),
291 AbortOnMassStoreReset
);
293 /* Check if the current command is being aborted by the host */
294 if (IsMassStoreReset
)
297 /* Verify the command block - abort if invalid */
298 if ((CommandBlock
.Signature
!= CBW_SIGNATURE
) ||
299 (CommandBlock
.LUN
>= TOTAL_LUNS
) ||
300 (CommandBlock
.SCSICommandLength
> MAX_SCSI_COMMAND_LENGTH
))
302 /* Stall both data pipes until reset by host */
303 Endpoint_StallTransaction();
304 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
305 Endpoint_StallTransaction();
310 /* Read in command block command data */
311 Endpoint_Read_Stream_LE(&CommandBlock
.SCSICommandData
,
312 CommandBlock
.SCSICommandLength
,
313 AbortOnMassStoreReset
);
315 /* Check if the current command is being aborted by the host */
316 if (IsMassStoreReset
)
319 /* Finalize the stream transfer to send the last packet */
320 Endpoint_ClearCurrentBank();
325 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
326 * stalled data endpoints as needed.
328 static void ReturnCommandStatus(void)
330 /* Select the Data Out endpoint */
331 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
333 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
334 while (Endpoint_IsStalled())
336 /* Check if the current command is being aborted by the host */
337 if (IsMassStoreReset
)
341 /* Select the Data In endpoint */
342 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
344 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
345 while (Endpoint_IsStalled())
347 /* Check if the current command is being aborted by the host */
348 if (IsMassStoreReset
)
352 /* Write the CSW to the endpoint */
353 Endpoint_Write_Stream_LE(&CommandStatus
, sizeof(CommandStatus
),
354 AbortOnMassStoreReset
);
356 /* Check if the current command is being aborted by the host */
357 if (IsMassStoreReset
)
360 /* Finalize the stream transfer to send the last packet */
361 Endpoint_ClearCurrentBank();
364 /** Stream callback function for the Endpoint stream read and write functions. This callback will abort the current stream transfer
365 * if a Mass Storage Reset request has been issued to the control endpoint.
367 STREAM_CALLBACK(AbortOnMassStoreReset
)
369 /* Abort if a Mass Storage reset command was received */
370 if (IsMassStoreReset
)
371 return STREAMCALLBACK_Abort
;
373 /* Continue with the current stream operation */
374 return STREAMCALLBACK_Continue
;
377 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when a control request has been issued to the control endpoint,
378 * so that the request can be processed. As several elements of the Mass Storage implementation require asynchronous control requests
379 * (such as endpoint stall clearing and Mass Storage Reset requests during data transfers) this is done via interrupts rather than
382 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
)
384 /* Check if the control endpoint has received a request */
385 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
))
387 /* Clear the endpoint interrupt */
388 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP
);
390 /* Process the control request */
393 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
394 USB_INT_Clear(ENDPOINT_INT_SETUP
);