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 /** Structure to hold the latest Command Block Wrapper issued by the host, containing a SCSI command to execute. */
41 CommandBlockWrapper_t CommandBlock
;
43 /** Structure to hold the latest Command Status Wrapper to return to the host, containing the status of the last issued command. */
44 CommandStatusWrapper_t CommandStatus
= { .Signature
= CSW_SIGNATURE
};
46 /** Flag to asynchronously abort any in-progress data transfers upon the reception of a mass storage reset command. */
47 volatile bool IsMassStoreReset
= false;
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.
57 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
66 /** Configures the board hardware and chip peripherals for the demo's functionality. */
67 void SetupHardware(void)
69 /* Disable watchdog if enabled by bootloader/fuses */
70 MCUSR
&= ~(1 << WDRF
);
73 /* Disable clock division */
74 clock_prescale_set(clock_div_1
);
76 /* Hardware Initialization */
78 SPI_Init(SPI_SPEED_FCPU_DIV_2
| SPI_SCK_LEAD_FALLING
| SPI_SAMPLE_TRAILING
| SPI_MODE_MASTER
);
82 /* Clear Dataflash sector protections, if enabled */
83 DataflashManager_ResetDataflashProtections();
86 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */
87 void EVENT_USB_Device_Connect(void)
89 /* Indicate USB enumerating */
90 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
92 /* Reset the MSReset flag upon connection */
93 IsMassStoreReset
= false;
96 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
97 * the status LEDs and stops the Mass Storage management task.
99 void EVENT_USB_Device_Disconnect(void)
101 /* Indicate USB not ready */
102 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
105 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
106 * of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started.
108 void EVENT_USB_Device_ConfigurationChanged(void)
110 /* Indicate USB connected and ready */
111 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
113 /* Setup Mass Storage In and Out Endpoints */
114 if (!(Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM
, EP_TYPE_BULK
,
115 ENDPOINT_DIR_IN
, MASS_STORAGE_IO_EPSIZE
,
116 ENDPOINT_BANK_DOUBLE
)))
118 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
121 if (!(Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM
, EP_TYPE_BULK
,
122 ENDPOINT_DIR_OUT
, MASS_STORAGE_IO_EPSIZE
,
123 ENDPOINT_BANK_DOUBLE
)))
125 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
129 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
130 * control requests that are not handled internally by the USB library (including the Mass Storage class-specific
131 * requests) so that they can be handled appropriately for the application.
133 void EVENT_USB_Device_UnhandledControlRequest(void)
135 /* Process UFI specific control requests */
136 switch (USB_ControlRequest
.bRequest
)
138 case REQ_MassStorageReset
:
139 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
141 Endpoint_ClearSETUP();
143 /* Indicate that the current transfer should be aborted */
144 IsMassStoreReset
= true;
146 Endpoint_ClearStatusStage();
151 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
153 Endpoint_ClearSETUP();
155 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */
156 Endpoint_Write_Byte(TOTAL_LUNS
- 1);
160 Endpoint_ClearStatusStage();
167 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they
168 * contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command.
170 void MassStorage_Task(void)
172 /* Device must be connected and configured for the task to run */
173 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
176 /* Select the Data Out Endpoint */
177 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
179 /* Check to see if a command from the host has been issued */
180 if (Endpoint_IsReadWriteAllowed())
183 LEDs_SetAllLEDs(LEDMASK_USB_BUSY
);
185 /* Process sent command block from the host */
186 if (ReadInCommandBlock())
188 /* Check direction of command, select Data IN endpoint if data is from the device */
189 if (CommandBlock
.Flags
& COMMAND_DIRECTION_DATA_IN
)
190 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
192 /* Decode the received SCSI command, set returned status code */
193 CommandStatus
.Status
= SCSI_DecodeSCSICommand() ? Command_Pass
: Command_Fail
;
195 /* Load in the CBW tag into the CSW to link them together */
196 CommandStatus
.Tag
= CommandBlock
.Tag
;
198 /* Load in the data residue counter into the CSW */
199 CommandStatus
.DataTransferResidue
= CommandBlock
.DataTransferLength
;
201 /* Stall the selected data pipe if command failed (if data is still to be transferred) */
202 if ((CommandStatus
.Status
== Command_Fail
) && (CommandStatus
.DataTransferResidue
))
203 Endpoint_StallTransaction();
205 /* Return command status block to the host */
206 ReturnCommandStatus();
208 /* Check if a Mass Storage Reset occurred */
209 if (IsMassStoreReset
)
211 /* Reset the data endpoint banks */
212 Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM
);
213 Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM
);
215 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
216 Endpoint_ClearStall();
217 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
218 Endpoint_ClearStall();
222 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
226 /* Indicate error reading in the command block from the host */
227 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
231 /* Clear the abort transfer flag */
232 IsMassStoreReset
= false;
235 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block
236 * if one has been issued, and performs validation to ensure that the block command is valid.
238 * \return Boolean true if a valid command block has been read in from the endpoint, false otherwise
240 static bool ReadInCommandBlock(void)
242 /* Select the Data Out endpoint */
243 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
245 /* Read in command block header */
246 Endpoint_Read_Stream_LE(&CommandBlock
, (sizeof(CommandBlock
) - sizeof(CommandBlock
.SCSICommandData
)),
247 StreamCallback_AbortOnMassStoreReset
);
249 /* Check if the current command is being aborted by the host */
250 if (IsMassStoreReset
)
253 /* Verify the command block - abort if invalid */
254 if ((CommandBlock
.Signature
!= CBW_SIGNATURE
) ||
255 (CommandBlock
.LUN
>= TOTAL_LUNS
) ||
256 (CommandBlock
.Flags
& 0x1F) ||
257 (CommandBlock
.SCSICommandLength
== 0) ||
258 (CommandBlock
.SCSICommandLength
> MAX_SCSI_COMMAND_LENGTH
))
260 /* Stall both data pipes until reset by host */
261 Endpoint_StallTransaction();
262 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
263 Endpoint_StallTransaction();
268 /* Read in command block command data */
269 Endpoint_Read_Stream_LE(&CommandBlock
.SCSICommandData
,
270 CommandBlock
.SCSICommandLength
,
271 StreamCallback_AbortOnMassStoreReset
);
273 /* Check if the current command is being aborted by the host */
274 if (IsMassStoreReset
)
277 /* Finalize the stream transfer to send the last packet */
283 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any
284 * stalled data endpoints as needed.
286 static void ReturnCommandStatus(void)
288 /* Select the Data Out endpoint */
289 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
);
291 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
292 while (Endpoint_IsStalled())
294 /* Check if the current command is being aborted by the host */
295 if (IsMassStoreReset
)
299 /* Select the Data In endpoint */
300 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
);
302 /* While data pipe is stalled, wait until the host issues a control request to clear the stall */
303 while (Endpoint_IsStalled())
305 /* Check if the current command is being aborted by the host */
306 if (IsMassStoreReset
)
310 /* Write the CSW to the endpoint */
311 Endpoint_Write_Stream_LE(&CommandStatus
, sizeof(CommandStatus
),
312 StreamCallback_AbortOnMassStoreReset
);
314 /* Check if the current command is being aborted by the host */
315 if (IsMassStoreReset
)
318 /* Finalize the stream transfer to send the last packet */
322 /** Stream callback function for the Endpoint stream read and write functions. This callback will abort the current stream transfer
323 * if a Mass Storage Reset request has been issued to the control endpoint.
325 uint8_t StreamCallback_AbortOnMassStoreReset(void)
327 /* Abort if a Mass Storage reset command was received */
328 if (IsMassStoreReset
)
329 return STREAMCALLBACK_Abort
;
331 /* Continue with the current stream operation */
332 return STREAMCALLBACK_Continue
;