3      Copyright (C) Dean Camera, 2013. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2013  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  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. 
  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 
  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 MS_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 MS_CommandStatusWrapper_t CommandStatus 
= { .Signature 
= MS_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
); 
  58         GlobalInterruptEnable(); 
  67 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  68 void SetupHardware(void) 
  70         /* Disable watchdog if enabled by bootloader/fuses */ 
  71         MCUSR 
&= ~(1 << WDRF
); 
  74         /* Disable clock division */ 
  75         clock_prescale_set(clock_div_1
); 
  77         /* Hardware Initialization */ 
  79         SPI_Init(SPI_SPEED_FCPU_DIV_2 
| SPI_ORDER_MSB_FIRST 
| SPI_SCK_LEAD_FALLING 
| SPI_SAMPLE_TRAILING 
| SPI_MODE_MASTER
); 
  83         /* Check if the Dataflash is working, abort if not */ 
  84         if (!(DataflashManager_CheckDataflashOperation())) 
  86                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
  90         /* Clear Dataflash sector protections, if enabled */ 
  91         DataflashManager_ResetDataflashProtections(); 
  94 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs. */ 
  95 void EVENT_USB_Device_Connect(void) 
  97         /* Indicate USB enumerating */ 
  98         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
 100         /* Reset the MSReset flag upon connection */ 
 101         IsMassStoreReset 
= false; 
 104 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 105  *  the status LEDs and stops the Mass Storage management task. 
 107 void EVENT_USB_Device_Disconnect(void) 
 109         /* Indicate USB not ready */ 
 110         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 113 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration 
 114  *  of the USB device after enumeration - the device endpoints are configured and the Mass Storage management task started. 
 116 void EVENT_USB_Device_ConfigurationChanged(void) 
 118         bool ConfigSuccess 
= true; 
 120         /* Setup Mass Storage Data Endpoints */ 
 121         ConfigSuccess 
&= Endpoint_ConfigureEndpoint(MASS_STORAGE_IN_EPADDR
,  EP_TYPE_BULK
, MASS_STORAGE_IO_EPSIZE
, 1); 
 122         ConfigSuccess 
&= Endpoint_ConfigureEndpoint(MASS_STORAGE_OUT_EPADDR
, EP_TYPE_BULK
, MASS_STORAGE_IO_EPSIZE
, 1); 
 124         /* Indicate endpoint configuration success or failure */ 
 125         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY 
: LEDMASK_USB_ERROR
); 
 128 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to 
 129  *  the device from the USB host before passing along unhandled control requests to the library for processing 
 132 void EVENT_USB_Device_ControlRequest(void) 
 134         /* Process UFI specific control requests */ 
 135         switch (USB_ControlRequest
.bRequest
) 
 137                 case MS_REQ_MassStorageReset
: 
 138                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 140                                 Endpoint_ClearSETUP(); 
 141                                 Endpoint_ClearStatusStage(); 
 143                                 /* Indicate that the current transfer should be aborted */ 
 144                                 IsMassStoreReset 
= true; 
 148                 case MS_REQ_GetMaxLUN
: 
 149                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 151                                 Endpoint_ClearSETUP(); 
 153                                 /* Indicate to the host the number of supported LUNs (virtual disks) on the device */ 
 154                                 Endpoint_Write_8(TOTAL_LUNS 
- 1); 
 157                                 Endpoint_ClearStatusStage(); 
 164 /** Task to manage the Mass Storage interface, reading in Command Block Wrappers from the host, processing the SCSI commands they 
 165  *  contain, and returning Command Status Wrappers back to the host to indicate the success or failure of the last issued command. 
 167 void MassStorage_Task(void) 
 169         /* Device must be connected and configured for the task to run */ 
 170         if (USB_DeviceState 
!= DEVICE_STATE_Configured
) 
 173         /* Process sent command block from the host if one has been sent */ 
 174         if (ReadInCommandBlock()) 
 177                 LEDs_SetAllLEDs(LEDMASK_USB_BUSY
); 
 179                 /* Check direction of command, select Data IN endpoint if data is from the device */ 
 180                 if (CommandBlock
.Flags 
& MS_COMMAND_DIR_DATA_IN
) 
 181                   Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR
); 
 183                 /* Decode the received SCSI command, set returned status code */ 
 184                 CommandStatus
.Status 
= SCSI_DecodeSCSICommand() ? MS_SCSI_COMMAND_Pass 
: MS_SCSI_COMMAND_Fail
; 
 186                 /* Load in the CBW tag into the CSW to link them together */ 
 187                 CommandStatus
.Tag 
= CommandBlock
.Tag
; 
 189                 /* Load in the data residue counter into the CSW */ 
 190                 CommandStatus
.DataTransferResidue 
= CommandBlock
.DataTransferLength
; 
 192                 /* Stall the selected data pipe if command failed (if data is still to be transferred) */ 
 193                 if ((CommandStatus
.Status 
== MS_SCSI_COMMAND_Fail
) && (CommandStatus
.DataTransferResidue
)) 
 194                   Endpoint_StallTransaction(); 
 196                 /* Return command status block to the host */ 
 197                 ReturnCommandStatus(); 
 200                 LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 203         /* Check if a Mass Storage Reset occurred */ 
 204         if (IsMassStoreReset
) 
 206                 /* Reset the data endpoint banks */ 
 207                 Endpoint_ResetEndpoint(MASS_STORAGE_OUT_EPADDR
); 
 208                 Endpoint_ResetEndpoint(MASS_STORAGE_IN_EPADDR
); 
 210                 Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPADDR
); 
 211                 Endpoint_ClearStall(); 
 212                 Endpoint_ResetDataToggle(); 
 213                 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR
); 
 214                 Endpoint_ClearStall(); 
 215                 Endpoint_ResetDataToggle(); 
 217                 /* Clear the abort transfer flag */ 
 218                 IsMassStoreReset 
= false; 
 222 /** Function to read in a command block from the host, via the bulk data OUT endpoint. This function reads in the next command block 
 223  *  if one has been issued, and performs validation to ensure that the block command is valid. 
 225  *  \return Boolean \c true if a valid command block has been read in from the endpoint, \c false otherwise 
 227 static bool ReadInCommandBlock(void) 
 229         uint16_t BytesTransferred
; 
 231         /* Select the Data Out endpoint */ 
 232         Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPADDR
); 
 234         /* Abort if no command has been sent from the host */ 
 235         if (!(Endpoint_IsOUTReceived())) 
 238         /* Read in command block header */ 
 239         BytesTransferred 
= 0; 
 240         while (Endpoint_Read_Stream_LE(&CommandBlock
, (sizeof(CommandBlock
) - sizeof(CommandBlock
.SCSICommandData
)), 
 241                                        &BytesTransferred
) == ENDPOINT_RWSTREAM_IncompleteTransfer
) 
 243                 /* Check if the current command is being aborted by the host */ 
 244                 if (IsMassStoreReset
) 
 248         /* Verify the command block - abort if invalid */ 
 249         if ((CommandBlock
.Signature         
!= MS_CBW_SIGNATURE
) || 
 250             (CommandBlock
.LUN               
>= TOTAL_LUNS
)       || 
 251                 (CommandBlock
.Flags              
& 0x1F)             || 
 252                 (CommandBlock
.SCSICommandLength 
== 0)                || 
 253                 (CommandBlock
.SCSICommandLength 
>  sizeof(CommandBlock
.SCSICommandData
))) 
 255                 /* Stall both data pipes until reset by host */ 
 256                 Endpoint_StallTransaction(); 
 257                 Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR
); 
 258                 Endpoint_StallTransaction(); 
 263         /* Read in command block command data */ 
 264         BytesTransferred 
= 0; 
 265         while (Endpoint_Read_Stream_LE(&CommandBlock
.SCSICommandData
, CommandBlock
.SCSICommandLength
, 
 266                                        &BytesTransferred
) == ENDPOINT_RWSTREAM_IncompleteTransfer
) 
 268                 /* Check if the current command is being aborted by the host */ 
 269                 if (IsMassStoreReset
) 
 273         /* Finalize the stream transfer to send the last packet */ 
 279 /** Returns the filled Command Status Wrapper back to the host via the bulk data IN endpoint, waiting for the host to clear any 
 280  *  stalled data endpoints as needed. 
 282 static void ReturnCommandStatus(void) 
 284         uint16_t BytesTransferred
; 
 286         /* Select the Data Out endpoint */ 
 287         Endpoint_SelectEndpoint(MASS_STORAGE_OUT_EPADDR
); 
 289         /* While data pipe is stalled, wait until the host issues a control request to clear the stall */ 
 290         while (Endpoint_IsStalled()) 
 292                 /* Check if the current command is being aborted by the host */ 
 293                 if (IsMassStoreReset
) 
 297         /* Select the Data In endpoint */ 
 298         Endpoint_SelectEndpoint(MASS_STORAGE_IN_EPADDR
); 
 300         /* While data pipe is stalled, wait until the host issues a control request to clear the stall */ 
 301         while (Endpoint_IsStalled()) 
 303                 /* Check if the current command is being aborted by the host */ 
 304                 if (IsMassStoreReset
) 
 308         /* Write the CSW to the endpoint */ 
 309         BytesTransferred 
= 0; 
 310         while (Endpoint_Write_Stream_LE(&CommandStatus
, sizeof(CommandStatus
), 
 311                                         &BytesTransferred
) == ENDPOINT_RWSTREAM_IncompleteTransfer
) 
 313                 /* Check if the current command is being aborted by the host */ 
 314                 if (IsMassStoreReset
) 
 318         /* Finalize the stream transfer to send the last packet */