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 /* Scheduler Task List */ 
  43         { .Task 
= USB_MassStorage      
, .TaskStatus 
= TASK_STOP 
}, 
  46 /* Global Variables */ 
  47 /** Structure to hold the latest Command Block Wrapper issued by the host, containing a SCSI command to execute. */ 
  48 CommandBlockWrapper_t  CommandBlock
; 
  50 /** Structure to hold the latest Command Status Wrapper to return to the host, containing the status of the last issued command. */ 
  51 CommandStatusWrapper_t CommandStatus 
= { .Signature 
= CSW_SIGNATURE 
}; 
  53 /** Flag to asynchronously abort any in-progress data transfers upon the reception of a mass storage reset command. */ 
  54 volatile bool          IsMassStoreReset 
= false; 
  56 /** Main program entry point. This routine configures the hardware required by the application, then 
  57  *  starts the scheduler to run the application tasks. 
  61         /* Disable watchdog if enabled by bootloader/fuses */ 
  62         MCUSR 
&= ~(1 << WDRF
); 
  65         /* Disable clock division */ 
  66         clock_prescale_set(clock_div_1
); 
  68         /* Hardware Initialization */ 
  70         Dataflash_Init(SPI_SPEED_FCPU_DIV_2
); 
  72         /* Clear Dataflash sector protections, if enabled */ 
  73         DataflashManager_ResetDataflashProtections(); 
  75         /* Indicate USB not ready */ 
  76         UpdateStatus(Status_USBNotReady
); 
  78         /* Initialize Scheduler so that it can be used */ 
  81         /* Initialize USB Subsystem */ 
  84         /* Scheduling - routine never returns, so put this last in the main function */ 
  88 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the 
  89  *  enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled 
  90  *  asynchronously when they arrive rather than when the control endpoint is polled manually. 
  92 EVENT_HANDLER(USB_Reset
) 
  94         /* Select the control endpoint */ 
  95         Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
); 
  97         /* Enable the endpoint SETUP interrupt ISR for the control endpoint */ 
  98         USB_INT_Enable(ENDPOINT_INT_SETUP
); 
 101 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */ 
 102 EVENT_HANDLER(USB_Connect
) 
 104         /* Indicate USB enumerating */ 
 105         UpdateStatus(Status_USBEnumerating
); 
 107         /* Reset the MSReset flag upon connection */ 
 108         IsMassStoreReset 
= false; 
 111 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 112  *  the status LEDs and stops the Mass Storage management task. 
 114 EVENT_HANDLER(USB_Disconnect
) 
 116         /* Stop running mass storage task */ 
 117         Scheduler_SetTaskMode(USB_MassStorage
, TASK_STOP
); 
 119         /* Indicate USB not ready */ 
 120         UpdateStatus(Status_USBNotReady
); 
 123 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration 
 124  *  of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started. 
 126 EVENT_HANDLER(USB_ConfigurationChanged
) 
 128         /* Setup Mass Storage In and Out Endpoints */ 
 129         Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPNUM
, EP_TYPE_BULK
, 
 130                                        ENDPOINT_DIR_IN
, MASS_STORAGE_IO_EPSIZE
, 
 131                                    ENDPOINT_BANK_DOUBLE
); 
 133         Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPNUM
, EP_TYPE_BULK
, 
 134                                        ENDPOINT_DIR_OUT
, MASS_STORAGE_IO_EPSIZE
, 
 135                                    ENDPOINT_BANK_DOUBLE
); 
 137         /* Indicate USB connected and ready */ 
 138         UpdateStatus(Status_USBReady
); 
 140         /* Start mass storage task */ 
 141         Scheduler_SetTaskMode(USB_MassStorage
, TASK_RUN
); 
 144 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific 
 145  *  control requests that are not handled internally by the USB library (including the Mass Storage class-specific 
 146  *  requests) so that they can be handled appropriately for the application. 
 148 EVENT_HANDLER(USB_UnhandledControlPacket
) 
 150         /* Process UFI specific control requests */ 
 151         switch (USB_ControlRequest
.bRequest
) 
 153                 case REQ_MassStorageReset
: 
 154                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 156                                 Endpoint_ClearSETUP(); 
 158                                 /* Indicate that the current transfer should be aborted */ 
 159                                 IsMassStoreReset 
= true;                         
 161                                 /* Acknowledge status stage */ 
 162                                 while (!(Endpoint_IsINReady())); 
 168                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 170                                 Endpoint_ClearSETUP(); 
 172                                 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */ 
 173                                 Endpoint_Write_Byte(TOTAL_LUNS 
- 1); 
 177                                 /* Acknowledge status stage */ 
 178                                 while (!(Endpoint_IsOUTReceived())); 
 186 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to 
 187  *  log to a serial port, or anything else that is suitable for status updates. 
 189  *  \param CurrentStatus  Current status of the system, from the MassStorage_StatusCodes_t enum 
 191 void UpdateStatus(uint8_t CurrentStatus
) 
 193         uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 195         /* Set the LED mask to the appropriate LED mask based on the given status code */ 
 196         switch (CurrentStatus
) 
 198                 case Status_USBNotReady
: 
 199                         LEDMask 
= (LEDS_LED1
); 
 201                 case Status_USBEnumerating
: 
 202                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 204                 case Status_USBReady
: 
 205                         LEDMask 
= (LEDS_LED2 
| LEDS_LED4
); 
 207                 case Status_CommandBlockError
: 
 208                         LEDMask 
= (LEDS_LED1
); 
 210                 case Status_ProcessingCommandBlock
: 
 211                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 215         /* Set the board LEDs to the new LED mask */ 
 216         LEDs_SetAllLEDs(LEDMask
); 
 219 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they 
 220  *  contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command. 
 222 TASK(USB_MassStorage
) 
 224         /* Check if the USB System is connected to a Host */ 
 227                 /* Select the Data Out Endpoint */ 
 228                 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
); 
 230                 /* Check to see if a command from the host has been issued */ 
 231                 if (Endpoint_IsReadWriteAllowed()) 
 234                         UpdateStatus(Status_ProcessingCommandBlock
); 
 236                         /* Process sent command block from the host */ 
 237                         if (ReadInCommandBlock()) 
 239                                 /* Check direction of command, select Data IN endpoint if data is from the device */ 
 240                                 if (CommandBlock
.Flags 
& COMMAND_DIRECTION_DATA_IN
) 
 241                                   Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
); 
 243                                 /* Decode the received SCSI command */ 
 244                                 SCSI_DecodeSCSICommand(); 
 246                                 /* Load in the CBW tag into the CSW to link them together */ 
 247                                 CommandStatus
.Tag 
= CommandBlock
.Tag
; 
 249                                 /* Load in the data residue counter into the CSW */ 
 250                                 CommandStatus
.DataTransferResidue 
= CommandBlock
.DataTransferLength
; 
 252                                 /* Stall the selected data pipe if command failed (if data is still to be transferred) */ 
 253                                 if ((CommandStatus
.Status 
== Command_Fail
) && (CommandStatus
.DataTransferResidue
)) 
 254                                   Endpoint_StallTransaction(); 
 256                                 /* Return command status block to the host */ 
 257                                 ReturnCommandStatus(); 
 259                                 /* Check if a Mass Storage Reset occurred */ 
 260                                 if (IsMassStoreReset
) 
 262                                         /* Reset the data endpoint banks */ 
 263                                         Endpoint_ResetFIFO(MASS_STORAGE_OUT_EPNUM
); 
 264                                         Endpoint_ResetFIFO(MASS_STORAGE_IN_EPNUM
); 
 266                                         /* Clear the abort transfer flag */ 
 267                                         IsMassStoreReset 
= false; 
 271                                 UpdateStatus(Status_USBReady
); 
 275                                 /* Indicate error reading in the command block from the host */ 
 276                                 UpdateStatus(Status_CommandBlockError
); 
 282 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block 
 283  *  if one has been issued, and performs validation to ensure that the block command is valid. 
 285  *  \return Boolean true if a valid command block has been read in from the endpoint, false otherwise 
 287 static bool ReadInCommandBlock(void) 
 289         /* Select the Data Out endpoint */ 
 290         Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
); 
 292         /* Read in command block header */ 
 293         Endpoint_Read_Stream_LE(&CommandBlock
, (sizeof(CommandBlock
) - sizeof(CommandBlock
.SCSICommandData
)), 
 294                                 AbortOnMassStoreReset
); 
 296         /* Check if the current command is being aborted by the host */ 
 297         if (IsMassStoreReset
) 
 300         /* Verify the command block - abort if invalid */ 
 301         if ((CommandBlock
.Signature 
!= CBW_SIGNATURE
) || 
 302             (CommandBlock
.LUN 
>= TOTAL_LUNS
) || 
 303                 (CommandBlock
.SCSICommandLength 
> MAX_SCSI_COMMAND_LENGTH
)) 
 305                 /* Stall both data pipes until reset by host */ 
 306                 Endpoint_StallTransaction(); 
 307                 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
); 
 308                 Endpoint_StallTransaction(); 
 313         /* Read in command block command data */ 
 314         Endpoint_Read_Stream_LE(&CommandBlock
.SCSICommandData
, 
 315                                 CommandBlock
.SCSICommandLength
, 
 316                                 AbortOnMassStoreReset
); 
 318         /* Check if the current command is being aborted by the host */ 
 319         if (IsMassStoreReset
) 
 322         /* Finalize the stream transfer to send the last packet */ 
 328 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any 
 329  *  stalled data endpoints as needed. 
 331 static void ReturnCommandStatus(void) 
 333         /* Select the Data Out endpoint */ 
 334         Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPNUM
); 
 336         /* While data pipe is stalled, wait until the host issues a control request to clear the stall */ 
 337         while (Endpoint_IsStalled()) 
 339                 /* Check if the current command is being aborted by the host */ 
 340                 if (IsMassStoreReset
) 
 344         /* Select the Data In endpoint */ 
 345         Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPNUM
); 
 347         /* While data pipe is stalled, wait until the host issues a control request to clear the stall */ 
 348         while (Endpoint_IsStalled()) 
 350                 /* Check if the current command is being aborted by the host */ 
 351                 if (IsMassStoreReset
) 
 355         /* Write the CSW to the endpoint */ 
 356         Endpoint_Write_Stream_LE(&CommandStatus
, sizeof(CommandStatus
), 
 357                                   AbortOnMassStoreReset
); 
 359         /* Check if the current command is being aborted by the host */ 
 360         if (IsMassStoreReset
) 
 363         /* Finalize the stream transfer to send the last packet */ 
 367 /** Stream callback function for the Endpoint stream read and write functions. This callback will abort the current stream transfer 
 368  *  if a Mass Storage Reset request has been issued to the control endpoint. 
 370 STREAM_CALLBACK(AbortOnMassStoreReset
) 
 372         /* Abort if a Mass Storage reset command was received */ 
 373         if (IsMassStoreReset
) 
 374           return STREAMCALLBACK_Abort
; 
 376         /* Continue with the current stream operation */ 
 377         return STREAMCALLBACK_Continue
; 
 380 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when a control request has been issued to the control endpoint, 
 381  *  so that the request can be processed. As several elements of the Mass Storage implementation require asynchronous control requests 
 382  *  (such as endpoint stall clearing and Mass Storage Reset requests during data transfers) this is done via interrupts rather than 
 383  *  polling so that they can be processed regardless of the rest of the application's state. 
 385 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
) 
 387         /* Check if the control endpoint has received a request */ 
 388         if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
)) 
 390                 /* Clear the endpoint interrupt */ 
 391                 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP
); 
 393                 /* Process the control request */ 
 396                 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */ 
 397                 USB_INT_Clear(ENDPOINT_INT_SETUP
);