+/rtos

git clone https://git.julia.blue/+/rtos

Joseph RyanRe-add usblib files83915e3

master
97.5 KiB2981 linesraw
1//*****************************************************************************
2//
3// usbenum.c - Enumeration code to handle all endpoint zero traffic.
4//
5// Copyright (c) 2007-2017 Texas Instruments Incorporated.  All rights reserved.
6// Software License Agreement
7//
8// Texas Instruments (TI) is supplying this software for use solely and
9// exclusively on TI's microcontroller products. The software is owned by
10// TI and/or its suppliers, and is protected under applicable copyright
11// laws. You may not combine this software with "viral" open-source
12// software in order to form a larger program.
13//
14// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
15// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
16// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
18// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
19// DAMAGES, FOR ANY REASON WHATSOEVER.
20//
21// This is part of revision 2.1.4.178 of the Tiva USB Library.
22//
23//*****************************************************************************
24
25#include "std.h"
26#include "tivaware/hw_ints.h"
27#include "tivaware/hw_memmap.h"
28#include "tivaware/hw_sysctl.h"
29#include "tivaware/hw_types.h"
30#include "tivaware/rom.h"
31#include "tivaware/rom_map.h"
32#include "tivaware/rtos_bindings.h"
33#include "tivaware/sysctl.h"
34#include "tivaware/usb.h"
35#include "usblib/device/usbdevice.h"
36#include "usblib/device/usbdevicepriv.h"
37#include "usblib/usblib.h"
38#include "usblib/usblibpriv.h"
39#include "usblib/usbulpi.h"
40#include <stdbool.h>
41#include <stdint.h>
42
43#define ASSERT(X)
44
45//*****************************************************************************
46//
47// External prototypes.
48//
49//*****************************************************************************
50extern tUSBMode g_iUSBMode;
51
52//*****************************************************************************
53//
54// Local functions prototypes.
55//
56//*****************************************************************************
57static void USBDGetStatus(void* pvInstance, tUSBRequest* psUSBRequest);
58static void USBDClearFeature(void* pvInstance, tUSBRequest* psUSBRequest);
59static void USBDSetFeature(void* pvInstance, tUSBRequest* psUSBRequest);
60static void USBDSetAddress(void* pvInstance, tUSBRequest* psUSBRequest);
61static void USBDGetDescriptor(void* pvInstance, tUSBRequest* psUSBRequest);
62static void USBDSetDescriptor(void* pvInstance, tUSBRequest* psUSBRequest);
63static void USBDGetConfiguration(void* pvInstance, tUSBRequest* psUSBRequest);
64static void USBDSetConfiguration(void* pvInstance, tUSBRequest* psUSBRequest);
65static void USBDGetInterface(void* pvInstance, tUSBRequest* psUSBRequest);
66static void USBDSetInterface(void* pvInstance, tUSBRequest* psUSBRequest);
67static void USBDSyncFrame(void* pvInstance, tUSBRequest* psUSBRequest);
68static void USBDEP0StateTx(uint32_t ui32Index);
69static void USBDEP0StateTxConfig(uint32_t ui32Index);
70static int32_t USBDStringIndexFromRequest(uint16_t ui16Lang,
71                                          uint16_t ui16Index);
72
73//*****************************************************************************
74//
75//! \addtogroup device_api
76//! @{
77//
78//*****************************************************************************
79
80//*****************************************************************************
81//
82// Indices into the ppui8Halt array to select the IN or OUT endpoint group.
83//
84//*****************************************************************************
85#define HALT_EP_IN 0
86#define HALT_EP_OUT 1
87
88//*****************************************************************************
89//
90// Define the max packet size for endpoint zero.
91//
92//*****************************************************************************
93#define EP0_MAX_PACKET_SIZE 64
94
95//*****************************************************************************
96//
97// This is a flag used with g_sUSBDeviceState.ui32DevAddress to indicate that a
98// device address change is pending.
99//
100//*****************************************************************************
101#define DEV_ADDR_PENDING 0x80000000
102
103//*****************************************************************************
104//
105// This label defines the default configuration number to use after a bus
106// reset.  This may be overridden by calling USBDCDSetDefaultConfiguration()
107// during processing of the device reset handler if required.
108//
109//*****************************************************************************
110#define DEFAULT_CONFIG_ID 1
111
112//*****************************************************************************
113//
114// This label defines the number of milliseconds that the remote wake up signal
115// must remain asserted before removing it. Section 7.1.7.7 of the USB 2.0 spec
116// states that "the remote wake up device must hold the resume signaling for at
117// least 1ms but for no more than 15ms" so 10mS seems a reasonable choice.
118//
119//*****************************************************************************
120#define REMOTE_WAKEUP_PULSE_MS 10
121
122//*****************************************************************************
123//
124// This label defines the number of milliseconds between the point where we
125// assert the remote wake up signal and calling the client back to tell it that
126// bus operation has been resumed.  This value is based on the timings provided
127// in section 7.1.7.7 of the USB 2.0 specification which indicates that the
128// host (which takes over resume signaling when the device's initial signal is
129// detected) must hold the resume signaling for at least 20mS.
130//
131//*****************************************************************************
132#define REMOTE_WAKEUP_READY_MS 20
133
134//*****************************************************************************
135//
136// The LPM states.
137//
138//*****************************************************************************
139#define USBLIB_LPM_STATE_DISABLED 0x00000000
140#define USBLIB_LPM_STATE_AWAKE 0x00000001
141#define USBLIB_LPM_STATE_SLEEP 0x00000002
142
143//*****************************************************************************
144//
145// The buffer for reading data coming into EP0
146//
147//*****************************************************************************
148static uint8_t g_pui8DataBufferIn[EP0_MAX_PACKET_SIZE];
149
150//*****************************************************************************
151//
152// This is 480000000/60000000 or a PLL Divide of 8.
153//
154//*****************************************************************************
155static uint32_t g_ui32PLLDiv = 8;
156
157//*****************************************************************************
158//
159// Holds the ULPI configuration.
160//
161//*****************************************************************************
162static uint32_t g_ui32ULPISupport;
163
164//*****************************************************************************
165//
166// This is the instance data for the USB controller itself and not a USB
167// device class.
168//
169//*****************************************************************************
170tDCDInstance g_psDCDInst[1];
171
172//*****************************************************************************
173//
174// This is the currently active class in use by USBLib.  There is only one
175// of these per USB controller and no device has more than one controller.
176//
177//*****************************************************************************
178tDeviceInfo* g_ppsDevInfo[1];
179
180//*****************************************************************************
181//
182// Function table to handle standard requests.
183//
184//*****************************************************************************
185static const tStdRequest g_psUSBDStdRequests[] = {USBDGetStatus,
186                                                  USBDClearFeature,
187                                                  0,
188                                                  USBDSetFeature,
189                                                  0,
190                                                  USBDSetAddress,
191                                                  USBDGetDescriptor,
192                                                  USBDSetDescriptor,
193                                                  USBDGetConfiguration,
194                                                  USBDSetConfiguration,
195                                                  USBDGetInterface,
196                                                  USBDSetInterface,
197                                                  USBDSyncFrame};
198
199//*****************************************************************************
200//
201// Functions accessible by USBLIB clients.
202//
203//*****************************************************************************
204
205//*****************************************************************************
206//
207//! Initialize an instance of the tDeviceInfo structure.
208//!
209//! \param ui32Index is the index of the USB controller which is to be
210//! initialized.
211//! \param psDeviceInfo is a pointer to the tDeviceInfo structure that needs
212//! to be initialized.
213//!
214//! This function must be called by a USB device class
215//! instance to initialize the basic tDeviceInfo required for all USB device
216//! class modules.  This is typically called in the initialization routine for
217//! USB device class.  For example in usbdaudio.c that supports USB device
218//! audio classes, this function is called in the USBDAudioCompositeInit()
219//! function which is used for both composite and non-composites instances of
220//! the USB audio class.
221//!
222//! \note This function should not be called directly by applications.
223//!
224//! \return None.
225//
226//*****************************************************************************
227void USBDCDDeviceInfoInit(uint32_t ui32Index, tDeviceInfo* psDeviceInfo) {
228    //
229    // Check the arguments.
230    //
231    ASSERT(ui32Index == 0);
232    ASSERT(psDeviceInfo != 0);
233
234    //
235    // Save the USB interrupt number.
236    //
237    g_psDCDInst[0].ui32IntNum = INT_USB0_TM4C123;
238
239    //
240    // These devices have a different USB interrupt number.
241    //
242    if (CLASS_IS_TM4C129) {
243        g_psDCDInst[0].ui32IntNum = INT_USB0_TM4C129;
244    }
245
246    //
247    // Disable LPM support by default.
248    //
249    g_psDCDInst[0].ui32LPMState = 0;
250
251    //
252    // Initialize a couple of fields in the device state structure.
253    //
254    g_psDCDInst[0].ui32Configuration = DEFAULT_CONFIG_ID;
255    g_psDCDInst[0].ui32DefaultConfiguration = DEFAULT_CONFIG_ID;
256
257    g_psDCDInst[0].iEP0State = eUSBStateIdle;
258
259    //
260    // Default to the state where remote wake up is disabled.
261    //
262    g_psDCDInst[0].ui8Status = 0;
263    g_psDCDInst[0].bRemoteWakeup = false;
264
265    //
266    // Determine the self- or bus-powered state based on the flags the
267    // user provided.
268    //
269    g_psDCDInst[0].bPwrSrcSet = false;
270}
271
272//*****************************************************************************
273//
274//! Initialize the USB library device control driver for a given hardware
275//! controller.
276//!
277//! \param ui32Index is the index of the USB controller which is to be
278//! initialized.
279//! \param psDevice is a pointer to a structure containing information that
280//! the USB library requires to support operation of this application's
281//! device.  The structure contains event handler callbacks and pointers to the
282//! various standard descriptors that the device wishes to publish to the
283//! host.
284//! \param pvDCDCBData is the callback data for any device callbacks.
285//!
286//! This function must be called by a device class which wishes to operate
287//! as a USB device and is not typically called by an application.  This
288//! function initializes the USB device control driver for the given
289//! controller and saves the device information for future use.  Prior to
290//! returning from this function, the device is connected to the USB bus.
291//! Following return, the caller can expect to receive a callback to the
292//! supplied <tt>pfnResetHandler</tt> function when a host connects to the
293//! device.  The \e pvDCDCBData contains a pointer to data that is returned
294//! with the DCD calls back to the function in the psDevice->psCallbacks()
295//! functions.
296//!
297//! The device information structure passed in \e psDevice must remain
298//! unchanged between this call and any matching call to USBDCDTerm() because
299//! it is not copied by the USB library.
300//!
301//! The USBStackModeSet() function can be called with eUSBModeForceDevice in
302//! order to cause the USB library to force the USB operating mode to a device
303//! controller.  This allows the application to used the USBVBUS and USBID pins
304//! as GPIOs on devices that support forcing OTG to operate as a device only
305//! controller.  By default the USB library will assume that the USBVBUS and
306//! USBID pins are configured as USB pins and not GPIOs.
307//!
308//! \return None.
309//
310//*****************************************************************************
311void USBDCDInit(uint32_t ui32Index, tDeviceInfo* psDevice, void* pvDCDCBData) {
312    const tConfigHeader* psHdr;
313    const tConfigDescriptor* psDesc;
314
315    //
316    // Check the arguments.
317    //
318    ASSERT(ui32Index == 0);
319    ASSERT(psDevice != 0);
320
321    g_ppsDevInfo[0] = psDevice;
322    g_psDCDInst[0].pvCBData = pvDCDCBData;
323
324    //
325    // Initialize the Device Info structure for a USB device instance.
326    //
327    USBDCDDeviceInfoInit(ui32Index, psDevice);
328
329    //
330    // Should not call this if the stack is in host mode.
331    //
332    ASSERT(g_iUSBMode != eUSBModeHost);
333    ASSERT(g_iUSBMode != eUSBModeForceHost);
334
335    //
336    // Default to device mode if no mode was set.
337    //
338    if (g_iUSBMode == eUSBModeNone) {
339        g_iUSBMode = eUSBModeDevice;
340    }
341
342    //
343    // Only do hardware update if the stack is in not in OTG mode.
344    //
345    if (g_iUSBMode != eUSBModeOTG) {
346        //
347        // Reset the USB controller.
348        //
349        MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_USB0);
350
351        //
352        // Enable Clocking to the USB controller.
353        //
354        MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0);
355
356        //
357        // Turn on USB Phy clock.
358        //
359        MAP_SysCtlUSBPLLEnable();
360
361        //
362        // Set the PLL to USB clock divider.
363        //
364        if (g_ui32PLLDiv == 0) {
365            USBClockEnable(USB0_BASE, g_ui32PLLDiv, USB_CLOCK_EXTERNAL);
366        } else {
367            USBClockEnable(USB0_BASE, g_ui32PLLDiv, USB_CLOCK_INTERNAL);
368        }
369
370        //
371        // Configure ULPI support.
372        //
373        if (g_ui32ULPISupport != USBLIB_FEATURE_ULPI_NONE) {
374            USBULPIEnable(USB0_BASE);
375
376            if (g_ui32ULPISupport & USBLIB_FEATURE_ULPI_HS) {
377                ULPIConfigSet(USB0_BASE, ULPI_CFG_HS);
378            } else {
379                ULPIConfigSet(USB0_BASE, ULPI_CFG_FS);
380            }
381        } else {
382            USBULPIDisable(USB0_BASE);
383        }
384
385        //
386        // Force device mode if requested.
387        //
388        if (g_iUSBMode == eUSBModeForceDevice) {
389            MAP_USBDevMode(USB0_BASE);
390        } else if (g_iUSBMode == eUSBModeDevice) {
391            //
392            // To run in active device mode the OTG signals must be active.
393            // This allows disconnect to be detected by the controller.
394            //
395            MAP_USBOTGMode(USB0_BASE);
396        }
397
398        //
399        // In all other cases, set the mode to device this function should not
400        // be called in OTG mode.
401        //
402        g_iUSBMode = eUSBModeDevice;
403
404        //
405        // Enable or disable LPM functionality.
406        //
407        if (g_psDCDInst[0].ui32Features & USBLIB_FEATURE_LPM_EN) {
408            //
409            // Enable full LPM support and all LPM related interrupts.
410            // USB_INTLPM_ERROR is not enabled since there is no response to
411            // this interrupt.
412            //
413            USBDevLPMConfig(USB0_BASE, USB_DEV_LPM_EN);
414            USBLPMIntEnable(USB0_BASE, USB_INTLPM_RESUME | USB_INTLPM_ERROR |
415                                           USB_INTLPM_ACK | USB_INTLPM_NYET);
416            USBDevLPMEnable(USB0_BASE);
417
418            //
419            // Awake by default.
420            //
421            g_psDCDInst[0].ui32LPMState = USBLIB_LPM_STATE_AWAKE;
422        } else {
423            USBDevLPMDisable(USB0_BASE);
424            USBDevLPMConfig(USB0_BASE, USB_DEV_LPM_NONE);
425            g_psDCDInst[0].ui32LPMState = USBLIB_LPM_STATE_DISABLED;
426        }
427    }
428
429    //
430    // Initialize the USB DMA interface.
431    //
432    g_psDCDInst[0].psDMAInstance = USBLibDMAInit(0);
433
434    //
435    // Initialize the USB tick module.
436    //
437    InternalUSBTickInit();
438
439    //
440    // Get a pointer to the default configuration descriptor.
441    //
442    psHdr =
443        psDevice
444            ->ppsConfigDescriptors[g_psDCDInst[0].ui32DefaultConfiguration - 1];
445    psDesc = (const tConfigDescriptor*)(psHdr->psSections[0]->pui8Data);
446
447    if ((psDesc->bmAttributes & USB_CONF_ATTR_PWR_M) ==
448        USB_CONF_ATTR_SELF_PWR) {
449        g_psDCDInst[0].ui8Status |= USB_STATUS_SELF_PWR;
450    } else {
451        g_psDCDInst[0].ui8Status &= ~USB_STATUS_SELF_PWR;
452    }
453
454    //
455    // Only do hardware update if the stack is not in OTG mode.
456    //
457    if (g_iUSBMode != eUSBModeOTG) {
458        //
459        // Get the current interrupt status.to clear all pending USB
460        // interrupts.
461        //
462        MAP_USBIntStatusControl(USB0_BASE);
463        MAP_USBIntStatusEndpoint(USB0_BASE);
464
465        //
466        // Enable USB Interrupts.
467        //
468        MAP_USBIntEnableControl(USB0_BASE,
469                                USB_INTCTRL_RESET | USB_INTCTRL_DISCONNECT |
470                                    USB_INTCTRL_RESUME | USB_INTCTRL_SUSPEND |
471                                    USB_INTCTRL_SOF);
472        MAP_USBIntEnableEndpoint(USB0_BASE, USB_INTEP_ALL);
473
474        //
475        // Attach the device using the soft connect.
476        //
477        MAP_USBDevConnect(USB0_BASE);
478
479        //
480        // Enable the USB interrupt.
481        //
482        OS_INT_ENABLE(g_psDCDInst[0].ui32IntNum);
483    }
484}
485
486//*****************************************************************************
487//
488//! Free the USB library device control driver for a given hardware controller.
489//!
490//! \param ui32Index is the index of the USB controller which is to be
491//! freed.
492//!
493//! This function should be called by an application if it no longer requires
494//! the use of a given USB controller to support its operation as a USB device.
495//! It frees the controller for use by another client.
496//!
497//! It is the caller's responsibility to remove its device from the USB bus
498//! prior to calling this function.
499//!
500//! \return None.
501//
502//*****************************************************************************
503void USBDCDTerm(uint32_t ui32Index) {
504    //
505    // Check the arguments.
506    //
507    ASSERT(ui32Index == 0);
508
509    //
510    // Disable the USB interrupts.
511    //
512    OS_INT_DISABLE(g_psDCDInst[0].ui32IntNum);
513
514    //
515    // Reset the tick handlers so that they can be reconfigured when and if
516    // USBDCDInit() is called.
517    //
518    InternalUSBTickReset();
519
520    //
521    // No active device.
522    //
523    g_ppsDevInfo[0] = 0;
524
525    MAP_USBIntDisableControl(USB0_BASE, USB_INTCTRL_ALL);
526    MAP_USBIntDisableEndpoint(USB0_BASE, USB_INTEP_ALL);
527
528    //
529    // Detach the device using the soft connect.
530    //
531    MAP_USBDevDisconnect(USB0_BASE);
532
533    //
534    // Clear any pending interrupts.
535    //
536    MAP_USBIntStatusControl(USB0_BASE);
537    MAP_USBIntStatusEndpoint(USB0_BASE);
538
539    //
540    // Turn off USB Phy clock.
541    //
542    MAP_SysCtlUSBPLLDisable();
543
544    //
545    // Disable the USB peripheral
546    //
547    MAP_SysCtlPeripheralDisable(SYSCTL_PERIPH_USB0);
548}
549
550//*****************************************************************************
551//
552//! This function starts the request for data from the host on endpoint zero.
553//!
554//! \param ui32Index is the index of the USB controller from which the data
555//! is being requested.
556//! \param pui8Data is a pointer to the buffer to fill with data from the USB
557//! host.
558//! \param ui32Size is the size of the buffer or data to return from the USB
559//! host.
560//!
561//! This function handles retrieving data from the host when a custom command
562//! has been issued on endpoint zero.  If the application needs notification
563//! when the data has been received,
564//! <tt>psCallbacks->pfnDataReceived()</tt> in the tDeviceInfo structure
565//! must contain valid function pointer.  In nearly all cases this is necessary
566//! because the caller of this function would likely need to know that the data
567//! requested was received.
568//!
569//! \return None.
570//
571//*****************************************************************************
572void USBDCDRequestDataEP0(uint32_t ui32Index, uint8_t* pui8Data,
573                          uint32_t ui32Size) {
574    ASSERT(ui32Index == 0);
575
576    //
577    // Enter the RX state on end point 0.
578    //
579    g_psDCDInst[0].iEP0State = eUSBStateRx;
580
581    //
582    // Save the pointer to the data.
583    //
584    g_psDCDInst[0].pui8EP0Data = pui8Data;
585
586    //
587    // Location to save the current number of bytes received.
588    //
589    g_psDCDInst[0].ui32OUTDataSize = ui32Size;
590
591    //
592    // Bytes remaining to be received.
593    //
594    g_psDCDInst[0].ui32EP0DataRemain = ui32Size;
595}
596
597//*****************************************************************************
598//
599//! This function requests transfer of data to the host on endpoint zero.
600//!
601//! \param ui32Index is the index of the USB controller which is to be used to
602//! send the data.
603//! \param pui8Data is a pointer to the buffer to send via endpoint zero.
604//! \param ui32Size is the amount of data to send in bytes.
605//!
606//! This function handles sending data to the host when a custom command is
607//! issued or non-standard descriptor has been requested on endpoint zero.  If
608//! the application needs notification when this is complete,
609//! <tt>psCallbacks->pfnDataSent</tt> in the tDeviceInfo structure must
610//! contain a valid function pointer.  This callback could be used to free up
611//! the buffer passed into this function in the \e pui8Data parameter.  The
612//! contents of the \e pui8Data buffer must remain unchanged until the
613//! <tt>pfnDataSent</tt> callback is received.
614//!
615//! \return None.
616//
617//*****************************************************************************
618void USBDCDSendDataEP0(uint32_t ui32Index, uint8_t* pui8Data,
619                       uint32_t ui32Size) {
620    ASSERT(ui32Index == 0);
621
622    //
623    // Return the externally provided device descriptor.
624    //
625    g_psDCDInst[0].pui8EP0Data = pui8Data;
626
627    //
628    // The size of the device descriptor is in the first byte.
629    //
630    g_psDCDInst[0].ui32EP0DataRemain = ui32Size;
631
632    //
633    // Save the total size of the data sent.
634    //
635    g_psDCDInst[0].ui32OUTDataSize = ui32Size;
636
637    //
638    // Now in the transmit data state.
639    //
640    USBDEP0StateTx(0);
641}
642
643//*****************************************************************************
644//
645//! This function sets the default configuration for the device.
646//!
647//! \param ui32Index is the index of the USB controller whose default
648//! configuration is to be set.
649//! \param ui32DefaultConfig is the configuration identifier (byte 6 of the
650//! standard configuration descriptor) which is to be presented to the host
651//! as the default configuration in cases where the configuration descriptor is
652//! queried prior to any specific configuration being set.
653//!
654//! This function allows a device to override the default configuration
655//! descriptor that will be returned to a host whenever it is queried prior
656//! to a specific configuration having been set.  The parameter passed must
657//! equal one of the configuration identifiers found in the
658//! <tt>ppsConfigDescriptors</tt> array for the device.
659//!
660//! If this function is not called, the USB library will return the first
661//! configuration in the <tt>ppsConfigDescriptors</tt> array as the default
662//! configuration.
663//!
664//! \note The USB device stack assumes that the configuration IDs (byte 6 of
665//! the configuration descriptor, <tt>bConfigurationValue</tt>) stored within
666//! the configuration descriptor array, <tt>ppsConfigDescriptors</tt>,
667//! are equal to the array index + 1.  In other words, the first entry in the
668//! array must contain a descriptor with <tt>bConfigurationValue</tt> 1, the
669//! second must have <tt>bConfigurationValue</tt> 2 and so on.
670//!
671//! \return None.
672//
673//*****************************************************************************
674void USBDCDSetDefaultConfiguration(uint32_t ui32Index,
675                                   uint32_t ui32DefaultConfig) {
676    ASSERT(ui32Index == 0);
677
678    g_psDCDInst[0].ui32DefaultConfiguration = ui32DefaultConfig;
679}
680
681//*****************************************************************************
682//
683//! This function generates a stall condition on endpoint zero.
684//!
685//! \param ui32Index is the index of the USB controller whose endpoint zero is
686//! to be stalled.
687//!
688//! This function is typically called to signal an error condition to the host
689//! when an unsupported request is received by the device.  It should be
690//! called from within the callback itself (in interrupt context) and not
691//! deferred until later since it affects the operation of the endpoint zero
692//! state machine in the USB library.
693//!
694//! \return None.
695//
696//*****************************************************************************
697void USBDCDStallEP0(uint32_t ui32Index) {
698    ASSERT(ui32Index == 0);
699
700    //
701    // Stall the endpoint in question.
702    //
703    MAP_USBDevEndpointStall(USB0_BASE, USB_EP_0, USB_EP_DEV_OUT);
704
705    //
706    // Enter the stalled state.
707    //
708    g_psDCDInst[0].iEP0State = eUSBStateStall;
709}
710#ifndef DEPRECATED
711
712//*****************************************************************************
713//
714//! Reports the device power status (bus- or self-powered) to the library.
715//!
716//! \param ui32Index is the index of the USB controller whose device power
717//! status is being reported.
718//! \param ui8Power indicates the current power status, either
719//! \b USB_STATUS_SELF_PWR or \b USB_STATUS_BUS_PWR.
720//!
721//! Applications which support switching between bus- or self-powered
722//! operation should call this function whenever the power source changes
723//! to indicate the current power status to the USB library.  This information
724//! is required by the library to allow correct responses to be provided when
725//! the host requests status from the device.
726//!
727//! \return None.
728//
729//*****************************************************************************
730void USBDCDPowerStatusSet(uint32_t ui32Index, uint8_t ui8Power) {
731    //
732    // Check for valid parameters.
733    //
734    ASSERT((ui8Power == USB_STATUS_BUS_PWR) ||
735           (ui8Power == USB_STATUS_SELF_PWR));
736    ASSERT(ui32Index == 0);
737
738    //
739    // Update the device status with the new power status flag.
740    //
741    g_psDCDInst[0].bPwrSrcSet = true;
742    g_psDCDInst[0].ui8Status &= ~USB_STATUS_PWR_M;
743    g_psDCDInst[0].ui8Status |= ui8Power;
744}
745#endif
746
747//*****************************************************************************
748//
749//! This function is used to enable/disable features of the USB library.
750//!
751//! \param ui32Index is the index of the USB controller whose device power
752//! status is being reported.
753//! \param ui32Feature indicates which feature is being changed.
754//! \param pvFeature holds the data that controls the feature request.
755//!
756//! Applications can change the support levels of some USB library features by
757//! calling this function to enable/disable certain features.  This function
758//! should normally be called before class initialization functions since the
759//! settings need to be in place before enumeration starts.  This allows the
760//! USB library to properly respond to all enumeration requests. The
761//! \e ui32Feature value is one of the \b USBLIB_FEATURE_* defines which
762//! controls the type of request being made.  The \e pvFeature is a feature
763//! specific data structure that is determined by the value passed in the
764//! \e ui32Feature parameter.
765//!
766//! \return Returns \b true if the feature was successfully changed and returns
767//! \b false if the feature was not able to be changed or is not supported.
768//
769//*****************************************************************************
770bool USBDCDFeatureSet(uint32_t ui32Index, uint32_t ui32Feature,
771                      void* pvFeature) {
772    bool bRetCode;
773    tLPMFeature* psLPMFeature;
774
775    bRetCode = true;
776
777    switch (ui32Feature) {
778    case USBLIB_FEATURE_LPM: {
779        //
780        // Save the LPM setting.
781        //
782        psLPMFeature = (tLPMFeature*)pvFeature;
783
784        if (psLPMFeature->ui32Features & USBLIB_FEATURE_LPM_EN) {
785            g_psDCDInst[0].ui32Features |= USBLIB_FEATURE_LPM_EN;
786        } else {
787            g_psDCDInst[0].ui32Features &= ~USBLIB_FEATURE_LPM_EN;
788        }
789
790        break;
791    }
792    case USBLIB_FEATURE_USBPLL: {
793        //
794        // If the PLL rate is not evenly divisible by 60MHz then
795        // do not set it.
796        //
797        if ((*(uint32_t*)pvFeature % 60000000) != 0) {
798            bRetCode = false;
799        } else {
800            //
801            // Save the new PLL rate.
802            //
803            g_ui32PLLDiv = (*(uint32_t*)pvFeature / 60000000);
804        }
805        break;
806    }
807    case USBLIB_FEATURE_USBULPI: {
808        //
809        // Save the ULPI support level.
810        //
811        g_ui32ULPISupport = *(uint32_t*)pvFeature;
812
813        break;
814    }
815    case USBLIB_FEATURE_POWER: {
816        //
817        // Update the device status with the new power status flag.
818        //
819        g_psDCDInst[0].bPwrSrcSet = true;
820        g_psDCDInst[0].ui8Status &= ~USBLIB_FEATURE_POWER_SELF;
821        g_psDCDInst[0].ui8Status |= (uint8_t)(*(uint32_t*)pvFeature);
822
823        break;
824    }
825    default: {
826        bRetCode = false;
827        break;
828    }
829    }
830    return (bRetCode);
831}
832
833//*****************************************************************************
834//
835//! This function is used to get the features of the USB library.
836//!
837//! \param ui32Index is the index of the USB controller whose device power
838//! status is being reported.
839//! \param ui32Feature indicates which feature is being requested.
840//! \param pvFeature holds the data that will be reported for the feature
841//! request.
842//!
843//! Applications can query the support levels of some USB library features by
844//! calling this function to get values of the features.  This function
845//! should normally be called before class initialization functions since the
846//! settings need to be in place during enumeration.  This allows the
847//! USB library to properly respond to all enumeration requests. The
848//! \e ui32Feature value is one of the \b USBLIB_FEATURE_* defines which
849//! controls the type of request being made.  The \e pvFeature is a feature
850//! specific data structure that is determined by the value passed in the
851//! \e ui32Feature parameter.
852//!
853//! \return Returns \b true if the feature was requested for ULPI and returns
854//! \b false if the feature was not for ULPI interface.
855//
856//*****************************************************************************
857bool USBDCDFeatureGet(uint32_t ui32Index, uint32_t ui32Feature,
858                      void* pvFeature) {
859    bool bRetCode = true;
860
861    switch (ui32Feature) {
862    case USBLIB_FEATURE_USBULPI: {
863        //
864        // Save the ULPI support level.
865        //
866        *(uint32_t*)pvFeature = g_ui32ULPISupport;
867
868        break;
869    }
870    default: {
871        bRetCode = false;
872        break;
873    }
874    }
875    return (bRetCode);
876}
877
878//*****************************************************************************
879//
880//! Requests an LPM remote wake up to resume communication when in an LPM sleep
881//! state.
882//!
883//! \param ui32Index is the index of the USB controller that will request
884//! a bus wake up.
885//!
886//! When the host controller puts the device into an LPM sleep state, the
887//! device can call this function to initiate LPM remote wake up signaling to
888//! the host.  If the remote wake up feature has been enabled by the host, this
889//! will cause the host to respond to the LPM remote wake request and resume
890//! normal operation.  If the host has disabled remote wake up, \b false is
891//! returned to indicate that the wake up request was not successful.
892//!
893//! \return Returns \b true if the remote wake up request has been sent or
894//!\b false if LPM remote wake up is disabled.
895//
896//*****************************************************************************
897bool USBDCDRemoteWakeLPM(uint32_t ui32Index) {
898    if (USBLPMRemoteWakeEnabled(USB0_BASE)) {
899        USBDevLPMRemoteWake(USB0_BASE);
900        return (true);
901    }
902    return (false);
903}
904
905//*****************************************************************************
906//
907//! Requests a remote wake up to resume communication when in suspended state.
908//!
909//! \param ui32Index is the index of the USB controller that will request
910//! a bus wake up.
911//!
912//! When the bus is suspended, an application which supports remote wake up
913//! (advertised to the host via the configuration descriptor) may call this
914//! function to initiate remote wake up signaling to the host.  If the remote
915//! wake up feature has not been disabled by the host, this will cause the bus
916//! to resume operation within 20mS.  If the host has disabled remote wake up,
917//! \b false will be returned to indicate that the wake up request was not
918//! successful.
919//!
920//! \return Returns \b true if the remote wake up is not disabled and the
921//! signaling was started or \b false if remote wake up is disabled or if
922//! signaling is currently ongoing following a previous call to this function.
923//
924//*****************************************************************************
925bool USBDCDRemoteWakeupRequest(uint32_t ui32Index) {
926    //
927    // Check for parameter validity.
928    //
929    ASSERT(ui32Index == 0);
930
931    //
932    // Is remote wake up signaling currently enabled?
933    //
934    if (g_psDCDInst[0].ui8Status & USB_STATUS_REMOTE_WAKE) {
935        //
936        // The host has not disabled remote wake up. Are we still in the
937        // middle of a previous wake up sequence?
938        //
939        if (!g_psDCDInst[0].bRemoteWakeup) {
940            //
941            // No - we are not in the middle of a wake up sequence so start
942            // one here.
943            //
944            g_psDCDInst[0].ui8RemoteWakeupCount = 0;
945            g_psDCDInst[0].bRemoteWakeup = true;
946            MAP_USBHostResume(USB0_BASE, true);
947            return (true);
948        }
949    }
950
951    //
952    // If we drop through to here, signaling was not initiated so return
953    // false.
954    return (false);
955}
956
957//*****************************************************************************
958//
959// Internal Functions, not to be called by applications
960//
961//*****************************************************************************
962
963//*****************************************************************************
964//
965// This internal function is called on the SOF interrupt to process any
966// outstanding remote wake up requests.
967//
968// \return None.
969//
970//*****************************************************************************
971void USBDeviceResumeTickHandler(tDCDInstance* psDevInst) {
972    if (g_psDCDInst[0].bRemoteWakeup) {
973        //
974        // Increment the millisecond counter we use to time the resume
975        // signaling.
976        //
977        g_psDCDInst[0].ui8RemoteWakeupCount++;
978
979        //
980        // Have we reached the 10mS mark? If so, we need to turn the signaling
981        // off again.
982        //
983        if (g_psDCDInst[0].ui8RemoteWakeupCount == REMOTE_WAKEUP_PULSE_MS) {
984            MAP_USBHostResume(USB0_BASE, false);
985        }
986
987        //
988        // Have we reached the point at which we can tell the client that the
989        // bus has resumed? The controller does not give us an interrupt if we
990        // initiated the wake up signaling so we just wait until 20mS have
991        // passed then tell the client all is well.
992        //
993        if (g_psDCDInst[0].ui8RemoteWakeupCount == REMOTE_WAKEUP_READY_MS) {
994            //
995            // We are now finished with the remote wake up signaling.
996            //
997            g_psDCDInst[0].bRemoteWakeup = false;
998
999            //
1000            // If the client has registered a resume callback, call it.  In the
1001            // case of a remote wake up request, we do not get a resume
1002            // interrupt from the controller so we need to fake it here.
1003            //
1004            if (g_ppsDevInfo[0]->psCallbacks->pfnResumeHandler) {
1005                g_ppsDevInfo[0]->psCallbacks->pfnResumeHandler(
1006                    g_psDCDInst[0].pvCBData);
1007            }
1008        }
1009    }
1010}
1011
1012//*****************************************************************************
1013//
1014// This internal function reads a request data packet and dispatches it to
1015// either a standard request handler or the registered device request
1016// callback depending upon the request type.
1017//
1018// \return None.
1019//
1020//*****************************************************************************
1021static void USBDReadAndDispatchRequest(uint32_t ui32Index) {
1022    uint32_t ui32Size;
1023    tUSBRequest* psRequest;
1024
1025    //
1026    // Cast the buffer to a request structure.
1027    //
1028    psRequest = (tUSBRequest*)g_pui8DataBufferIn;
1029
1030    //
1031    // Set the buffer size.
1032    //
1033    ui32Size = EP0_MAX_PACKET_SIZE;
1034
1035    //
1036    // Get the data from the USB controller end point 0.
1037    //
1038    MAP_USBEndpointDataGet(USB0_BASE, USB_EP_0, g_pui8DataBufferIn, &ui32Size);
1039
1040    //
1041    // If there was a null setup packet then just return.
1042    //
1043    if (!ui32Size) {
1044        return;
1045    }
1046
1047    //
1048    // See if this is a standard request or not.
1049    //
1050    if ((psRequest->bmRequestType & USB_RTYPE_TYPE_M) != USB_RTYPE_STANDARD) {
1051        //
1052        // Since this is not a standard request, see if there is
1053        // an external handler present.
1054        //
1055        if (g_ppsDevInfo[0]->psCallbacks->pfnRequestHandler) {
1056            g_ppsDevInfo[0]->psCallbacks->pfnRequestHandler(
1057                g_psDCDInst[0].pvCBData, psRequest);
1058        } else {
1059            //
1060            // If there is no handler then stall this request.
1061            //
1062            USBDCDStallEP0(0);
1063        }
1064    } else {
1065        //
1066        // Assure that the jump table is not out of bounds.
1067        //
1068        if ((psRequest->bRequest <
1069             (sizeof(g_psUSBDStdRequests) / sizeof(tStdRequest))) &&
1070            (g_psUSBDStdRequests[psRequest->bRequest] != 0)) {
1071            //
1072            // Jump table to the appropriate handler.
1073            //
1074            g_psUSBDStdRequests[psRequest->bRequest](&g_psDCDInst[0],
1075                                                     psRequest);
1076        } else {
1077            //
1078            // If there is no handler then stall this request.
1079            //
1080            USBDCDStallEP0(0);
1081        }
1082    }
1083}
1084
1085//*****************************************************************************
1086//
1087// This is interrupt handler for endpoint zero.
1088//
1089// This function handles all interrupts on endpoint zero in order to maintain
1090// the state needed for the control endpoint on endpoint zero.  In order to
1091// successfully enumerate and handle all USB standard requests, all requests
1092// on endpoint zero must pass through this function.  The endpoint has the
1093// following states: \b eUSBStateIdle, \b eUSBStateTx, \b eUSBStateRx,
1094// \b eUSBStateStall, and \b eUSBStateStatus.  In the \b eUSBStateIdle
1095// state the USB controller has not received the start of a request, and once
1096// it does receive the data for the request it will either enter the
1097// \b eUSBStateTx, \b eUSBStateRx, or \b eUSBStateStall depending on the
1098// command.  If the controller enters the \b eUSBStateTx or \b eUSBStateRx
1099// then once all data has been sent or received, it must pass through the
1100// \b eUSBStateStatus state to allow the host to acknowledge completion of
1101// the request.  The \b eUSBStateStall is entered from \b eUSBStateIdle in
1102// the event that the USB request was not valid.  Both the \b eUSBStateStall
1103// and \b eUSBStateStatus are transitional states that return to the
1104// \b eUSBStateIdle state.
1105//
1106// \return None.
1107//
1108// eUSBStateIdle -*--> eUSBStateTx -*-> eUSBStateStatus -*->eUSBStateIdle
1109//                |                 |                    |
1110//                |--> eUSBStateRx                       |
1111//                |                                      |
1112//                |--> eUSBStateStall ---------->--------
1113//
1114//  ----------------------------------------------------------------
1115// | Current State       | State 0           | State 1              |
1116// | --------------------|-------------------|----------------------
1117// | eUSBStateIdle       | eUSBStateTx/RX    | eUSBStateStall       |
1118// | eUSBStateTx         | eUSBStateStatus   |                      |
1119// | eUSBStateRx         | eUSBStateStatus   |                      |
1120// | eUSBStateStatus     | eUSBStateIdle     |                      |
1121// | eUSBStateStall      | eUSBStateIdle     |                      |
1122//  ----------------------------------------------------------------
1123//
1124//*****************************************************************************
1125void USBDeviceEnumHandler(tDCDInstance* pDevInstance) {
1126    uint32_t ui32EPStatus, ui32DataSize;
1127
1128    //
1129    // Get the end point 0 status.
1130    //
1131    ui32EPStatus = MAP_USBEndpointStatus(USB0_BASE, USB_EP_0);
1132
1133    switch (pDevInstance->iEP0State) {
1134    //
1135    // Handle the status state, this is a transitory state from
1136    // eUSBStateTx or eUSBStateRx back to eUSBStateIdle.
1137    //
1138    case eUSBStateStatus: {
1139        //
1140        // Just go back to the idle state.
1141        //
1142        pDevInstance->iEP0State = eUSBStateIdle;
1143
1144        //
1145        // If there is a pending address change then set the address.
1146        //
1147        if (pDevInstance->ui32DevAddress & DEV_ADDR_PENDING) {
1148            //
1149            // Clear the pending address change and set the address.
1150            //
1151            pDevInstance->ui32DevAddress &= ~DEV_ADDR_PENDING;
1152            MAP_USBDevAddrSet(USB0_BASE, pDevInstance->ui32DevAddress);
1153        }
1154
1155        //
1156        // If a new packet is already pending, we need to read it
1157        // and handle whatever request it contains.
1158        //
1159        if (ui32EPStatus & USB_DEV_EP0_OUT_PKTRDY) {
1160            //
1161            // Process the newly arrived packet.
1162            //
1163            USBDReadAndDispatchRequest(0);
1164        }
1165        break;
1166    }
1167
1168    //
1169    // In the IDLE state the code is waiting to receive data from the host.
1170    //
1171    case eUSBStateIdle: {
1172        //
1173        // Is there a packet waiting for us?
1174        //
1175        if (ui32EPStatus & USB_DEV_EP0_OUT_PKTRDY) {
1176            //
1177            // Yes - process it.
1178            //
1179            USBDReadAndDispatchRequest(0);
1180        }
1181        break;
1182    }
1183
1184    //
1185    // Data is still being sent to the host so handle this in the
1186    // EP0StateTx() function.
1187    //
1188    case eUSBStateTx: {
1189        USBDEP0StateTx(0);
1190        break;
1191    }
1192
1193    //
1194    // We are still in the middle of sending the configuration descriptor
1195    // so handle this in the EP0StateTxConfig() function.
1196    //
1197    case eUSBStateTxConfig: {
1198        USBDEP0StateTxConfig(0);
1199        break;
1200    }
1201
1202    //
1203    // Handle the receive state for commands that are receiving data on
1204    // endpoint zero.
1205    //
1206    case eUSBStateRx: {
1207        //
1208        // Set the number of bytes to get out of this next packet.
1209        //
1210        if (pDevInstance->ui32EP0DataRemain > EP0_MAX_PACKET_SIZE) {
1211            //
1212            // Don't send more than EP0_MAX_PACKET_SIZE bytes.
1213            //
1214            ui32DataSize = EP0_MAX_PACKET_SIZE;
1215        } else {
1216            //
1217            // There was space so send the remaining bytes.
1218            //
1219            ui32DataSize = pDevInstance->ui32EP0DataRemain;
1220        }
1221
1222        //
1223        // Get the data from the USB controller end point 0.
1224        //
1225        MAP_USBEndpointDataGet(USB0_BASE, USB_EP_0, pDevInstance->pui8EP0Data,
1226                               &ui32DataSize);
1227
1228        //
1229        // If there we not more that EP0_MAX_PACKET_SIZE or more bytes
1230        // remaining then this transfer is complete.  If there were exactly
1231        // EP0_MAX_PACKET_SIZE remaining then there still needs to be
1232        // null packet sent before this is complete.
1233        //
1234        if (pDevInstance->ui32EP0DataRemain < EP0_MAX_PACKET_SIZE) {
1235            //
1236            // Return to the idle state.
1237            //
1238            pDevInstance->iEP0State = eUSBStateStatus;
1239
1240            //
1241            // If there is a receive callback then call it.
1242            //
1243            if ((g_ppsDevInfo[0]->psCallbacks->pfnDataReceived) &&
1244                (pDevInstance->ui32OUTDataSize != 0)) {
1245                //
1246                // Call the custom receive handler to handle the data
1247                // that was received.
1248                //
1249                g_ppsDevInfo[0]->psCallbacks->pfnDataReceived(
1250                    g_psDCDInst[0].pvCBData, pDevInstance->ui32OUTDataSize);
1251
1252                //
1253                // Indicate that there is no longer any data being waited
1254                // on.
1255                //
1256                pDevInstance->ui32OUTDataSize = 0;
1257            }
1258
1259            //
1260            // Need to ACK the data on end point 0 in this case and set the
1261            // data end as this is the last of the data.
1262            //
1263            MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
1264        } else {
1265            //
1266            // Need to ACK the data on end point 0 in this case
1267            // without setting data end because more data is coming.
1268            //
1269            MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, false);
1270        }
1271
1272        //
1273        // Advance the pointer.
1274        //
1275        pDevInstance->pui8EP0Data += ui32DataSize;
1276
1277        //
1278        // Decrement the number of bytes that are being waited on.
1279        //
1280        pDevInstance->ui32EP0DataRemain -= ui32DataSize;
1281
1282        break;
1283    }
1284    //
1285    // The device stalled endpoint zero so check if the stall needs to be
1286    // cleared once it has been successfully sent.
1287    //
1288    case eUSBStateStall: {
1289        //
1290        // If we sent a stall then acknowledge this interrupt.
1291        //
1292        if (ui32EPStatus & USB_DEV_EP0_SENT_STALL) {
1293            //
1294            // Clear the Setup End condition.
1295            //
1296            MAP_USBDevEndpointStatusClear(USB0_BASE, USB_EP_0,
1297                                          USB_DEV_EP0_SENT_STALL);
1298
1299            //
1300            // Reset the global end point 0 state to IDLE.
1301            //
1302            pDevInstance->iEP0State = eUSBStateIdle;
1303        }
1304        break;
1305    }
1306    //
1307    // Halt on an unknown state, but only in DEBUG mode builds.
1308    //
1309    default: {
1310        ASSERT(0);
1311        break;
1312    }
1313    }
1314}
1315
1316//*****************************************************************************
1317//
1318// This function handles bus reset notifications.
1319//
1320// This function is called from the low level USB interrupt handler whenever
1321// a bus reset is detected.  It performs tidy-up as required and resets the
1322// configuration back to defaults in preparation for descriptor queries from
1323// the host.
1324//
1325// \return None.
1326//
1327//*****************************************************************************
1328void USBDeviceEnumResetHandler(tDCDInstance* pDevInstance) {
1329    uint32_t ui32Loop;
1330
1331    //
1332    // Disable remote wake up signaling (as per USB 2.0 spec 9.1.1.6).
1333    //
1334    pDevInstance->ui8Status &= ~USB_STATUS_REMOTE_WAKE;
1335    pDevInstance->bRemoteWakeup = false;
1336
1337    //
1338    // Call the device dependent code to indicate a bus reset has occurred.
1339    //
1340    if (g_ppsDevInfo[0]->psCallbacks->pfnResetHandler) {
1341        g_ppsDevInfo[0]->psCallbacks->pfnResetHandler(g_psDCDInst[0].pvCBData);
1342    }
1343
1344    //
1345    // Reset the default configuration identifier and alternate function
1346    // selections.
1347    //
1348    pDevInstance->ui32Configuration = pDevInstance->ui32DefaultConfiguration;
1349
1350    for (ui32Loop = 0; ui32Loop < USB_MAX_INTERFACES_PER_DEVICE; ui32Loop++) {
1351        pDevInstance->pui8AltSetting[ui32Loop] = (uint8_t)0;
1352    }
1353}
1354
1355//*****************************************************************************
1356//
1357// This function handles the GET_STATUS standard USB request.
1358//
1359// \param pvInstance is the USB device controller instance data.
1360// \param psUSBRequest holds the request type and endpoint number if endpoint
1361// status is requested.
1362//
1363// This function handles responses to a Get Status request from the host
1364// controller.  A status request can be for the device, an interface or an
1365// endpoint.  If any other type of request is made this function will cause
1366// a stall condition to indicate that the command is not supported.  The
1367// \e psUSBRequest structure holds the type of the request in the
1368// bmRequestType field.  If the type indicates that this is a request for an
1369// endpoint's status, then the wIndex field holds the endpoint number.
1370//
1371// \return None.
1372//
1373//*****************************************************************************
1374static void USBDGetStatus(void* pvInstance, tUSBRequest* psUSBRequest) {
1375    uint16_t ui16Data, ui16Index;
1376    uint32_t ui32Dir;
1377    tDCDInstance* psUSBControl;
1378
1379    ASSERT(psUSBRequest != 0);
1380    ASSERT(pvInstance != 0);
1381
1382    //
1383    // Create the device information pointer.
1384    //
1385    psUSBControl = (tDCDInstance*)pvInstance;
1386
1387    //
1388    // Need to ACK the data on end point 0 without setting last data as there
1389    // will be a data phase.
1390    //
1391    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, false);
1392
1393    //
1394    // Determine what type of status was requested.
1395    //
1396    switch (psUSBRequest->bmRequestType & USB_RTYPE_RECIPIENT_M) {
1397    //
1398    // This was a Device Status request.
1399    //
1400    case USB_RTYPE_DEVICE: {
1401        //
1402        // Return the current status for the device.
1403        //
1404        ui16Data = (uint16_t)psUSBControl->ui8Status;
1405
1406        break;
1407    }
1408
1409    //
1410    // This was a Interface status request.
1411    //
1412    case USB_RTYPE_INTERFACE: {
1413        //
1414        // Interface status always returns 0.
1415        //
1416        ui16Data = (uint16_t)0;
1417
1418        break;
1419    }
1420
1421    //
1422    // This was an endpoint status request.
1423    //
1424    case USB_RTYPE_ENDPOINT: {
1425        //
1426        // Which endpoint are we dealing with?
1427        //
1428        ui16Index = psUSBRequest->wIndex & USB_REQ_EP_NUM_M;
1429
1430        //
1431        // Check if this was a valid endpoint request.
1432        //
1433        if ((ui16Index == 0) || (ui16Index >= NUM_USB_EP)) {
1434            USBDCDStallEP0(0);
1435            return;
1436        } else {
1437            //
1438            // Are we dealing with an IN or OUT endpoint?
1439            //
1440            ui32Dir =
1441                ((psUSBRequest->wIndex & USB_REQ_EP_DIR_M) == USB_REQ_EP_DIR_IN)
1442                    ? HALT_EP_IN
1443                    : HALT_EP_OUT;
1444
1445            //
1446            // Get the current halt status for this endpoint.
1447            //
1448            ui16Data =
1449                (uint16_t)psUSBControl->ppui8Halt[ui32Dir][ui16Index - 1];
1450        }
1451        break;
1452    }
1453
1454    //
1455    // This was an unknown request.
1456    //
1457    default: {
1458        //
1459        // Anything else causes a stall condition to indicate that the
1460        // command was not supported.
1461        //
1462        USBDCDStallEP0(0);
1463        return;
1464    }
1465    }
1466
1467    //
1468    // Send the two byte status response.
1469    //
1470    psUSBControl->ui32EP0DataRemain = 2;
1471    psUSBControl->pui8EP0Data = (uint8_t*)&ui16Data;
1472
1473    //
1474    // Send the response.
1475    //
1476    USBDEP0StateTx(0);
1477}
1478
1479//*****************************************************************************
1480//
1481// This function handles the CLEAR_FEATURE standard USB request.
1482//
1483// \param pvInstance is the USB device controller instance data.
1484// \param psUSBRequest holds the options for the Clear Feature USB request.
1485//
1486// This function handles device or endpoint clear feature requests.  The
1487// \e psUSBRequest structure holds the type of the request in the bmRequestType
1488// field and the feature is held in the wValue field.  The device can only
1489// clear the Remote Wake feature.  This device request should only be made if
1490// the descriptor indicates that Remote Wake is implemented by the device.
1491// Endpoints can only clear a halt on a given endpoint.  If any other
1492// requests are made, then the device will stall the request to indicate to
1493// the host that the command was not supported.
1494//
1495// \return None.
1496//
1497//*****************************************************************************
1498static void USBDClearFeature(void* pvInstance, tUSBRequest* psUSBRequest) {
1499    tDCDInstance* psUSBControl;
1500    uint32_t ui32Dir;
1501    uint16_t ui16Index;
1502
1503    ASSERT(psUSBRequest != 0);
1504    ASSERT(pvInstance != 0);
1505
1506    //
1507    // Create the device information pointer.
1508    //
1509    psUSBControl = (tDCDInstance*)pvInstance;
1510
1511    //
1512    // Need to ACK the data on end point 0 with last data set as this has no
1513    // data phase.
1514    //
1515    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
1516
1517    //
1518    // Determine what type of status was requested.
1519    //
1520    switch (psUSBRequest->bmRequestType & USB_RTYPE_RECIPIENT_M) {
1521    //
1522    // This is a clear feature request at the device level.
1523    //
1524    case USB_RTYPE_DEVICE: {
1525        //
1526        // Only remote wake is can be cleared by this function.
1527        //
1528        if (USB_FEATURE_REMOTE_WAKE & psUSBRequest->wValue) {
1529            //
1530            // Clear the remote wake up state.
1531            //
1532            psUSBControl->ui8Status &= ~USB_STATUS_REMOTE_WAKE;
1533        } else {
1534            USBDCDStallEP0(0);
1535        }
1536        break;
1537    }
1538
1539    //
1540    // This is a clear feature request at the endpoint level.
1541    //
1542    case USB_RTYPE_ENDPOINT: {
1543        //
1544        // Which endpoint are we dealing with?
1545        //
1546        ui16Index = psUSBRequest->wIndex & USB_REQ_EP_NUM_M;
1547
1548        //
1549        // Not a valid endpoint.
1550        //
1551        if ((ui16Index == 0) || (ui16Index > NUM_USB_EP)) {
1552            USBDCDStallEP0(0);
1553        } else {
1554            //
1555            // Only the halt feature is supported.
1556            //
1557            if (USB_FEATURE_EP_HALT == psUSBRequest->wValue) {
1558                //
1559                // Are we dealing with an IN or OUT endpoint?
1560                //
1561                ui32Dir = ((psUSBRequest->wIndex & USB_REQ_EP_DIR_M) ==
1562                           USB_REQ_EP_DIR_IN)
1563                              ? HALT_EP_IN
1564                              : HALT_EP_OUT;
1565
1566                //
1567                // Clear the halt condition on this endpoint.
1568                //
1569                psUSBControl->ppui8Halt[ui32Dir][ui16Index - 1] = 0;
1570
1571                if (ui32Dir == HALT_EP_IN) {
1572                    MAP_USBDevEndpointStallClear(
1573                        USB0_BASE, IndexToUSBEP(ui16Index), USB_EP_DEV_IN);
1574                } else {
1575                    MAP_USBDevEndpointStallClear(
1576                        USB0_BASE, IndexToUSBEP(ui16Index), USB_EP_DEV_OUT);
1577                }
1578            } else {
1579                //
1580                // If any other feature is requested, this is an error.
1581                //
1582                USBDCDStallEP0(0);
1583                return;
1584            }
1585        }
1586        break;
1587    }
1588
1589    //
1590    // This is an unknown request.
1591    //
1592    default: {
1593        USBDCDStallEP0(0);
1594        return;
1595    }
1596    }
1597}
1598
1599//*****************************************************************************
1600//
1601// This function handles the SET_FEATURE standard USB request.
1602//
1603// \param pvInstance is the USB device controller instance data.
1604// \param psUSBRequest holds the feature in the wValue field of the USB
1605// request.
1606//
1607// This function handles device or endpoint set feature requests.  The
1608// \e psUSBRequest structure holds the type of the request in the bmRequestType
1609// field and the feature is held in the wValue field.  The device can only
1610// set the Remote Wake feature.  This device request should only be made if the
1611// descriptor indicates that Remote Wake is implemented by the device.
1612// Endpoint requests can only issue a halt on a given endpoint.  If any other
1613// requests are made, then the device will stall the request to indicate to the
1614// host that the command was not supported.
1615//
1616// \return None.
1617//
1618//*****************************************************************************
1619static void USBDSetFeature(void* pvInstance, tUSBRequest* psUSBRequest) {
1620    tDCDInstance* psUSBControl;
1621    uint16_t ui16Index;
1622    uint32_t ui32Dir;
1623
1624    ASSERT(psUSBRequest != 0);
1625    ASSERT(pvInstance != 0);
1626
1627    //
1628    // Create the device information pointer.
1629    //
1630    psUSBControl = (tDCDInstance*)pvInstance;
1631
1632    //
1633    // Need to ACK the data on end point 0 with last data set as this has no
1634    // data phase.
1635    //
1636    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
1637
1638    //
1639    // Determine what type of status was requested.
1640    //
1641    switch (psUSBRequest->bmRequestType & USB_RTYPE_RECIPIENT_M) {
1642    //
1643    // This is a set feature request at the device level.
1644    //
1645    case USB_RTYPE_DEVICE: {
1646        //
1647        // Only remote wake is the only feature that can be set by this
1648        // function.
1649        //
1650        if (USB_FEATURE_REMOTE_WAKE & psUSBRequest->wValue) {
1651            //
1652            // Set the remote wake up state.
1653            //
1654            psUSBControl->ui8Status |= USB_STATUS_REMOTE_WAKE;
1655        } else {
1656            USBDCDStallEP0(0);
1657        }
1658        break;
1659    }
1660
1661    //
1662    // This is a set feature request at the endpoint level.
1663    //
1664    case USB_RTYPE_ENDPOINT: {
1665        //
1666        // Which endpoint are we dealing with?
1667        //
1668        ui16Index = psUSBRequest->wIndex & USB_REQ_EP_NUM_M;
1669
1670        //
1671        // Not a valid endpoint?
1672        //
1673        if ((ui16Index == 0) || (ui16Index >= NUM_USB_EP)) {
1674            USBDCDStallEP0(0);
1675        } else {
1676            //
1677            // Only the Halt feature can be set.
1678            //
1679            if (USB_FEATURE_EP_HALT == psUSBRequest->wValue) {
1680                //
1681                // Are we dealing with an IN or OUT endpoint?
1682                //
1683                ui32Dir = ((psUSBRequest->wIndex & USB_REQ_EP_DIR_M) ==
1684                           USB_REQ_EP_DIR_IN)
1685                              ? HALT_EP_IN
1686                              : HALT_EP_OUT;
1687
1688                //
1689                // Clear the halt condition on this endpoint.
1690                //
1691                psUSBControl->ppui8Halt[ui32Dir][ui16Index - 1] = 1;
1692            } else {
1693                //
1694                // No other requests are supported.
1695                //
1696                USBDCDStallEP0(0);
1697                return;
1698            }
1699        }
1700        break;
1701    }
1702
1703    //
1704    // This is an unknown request.
1705    //
1706    default: {
1707        USBDCDStallEP0(0);
1708        return;
1709    }
1710    }
1711}
1712
1713//*****************************************************************************
1714//
1715// This function handles the SET_ADDRESS standard USB request.
1716//
1717// \param pvInstance is the USB device controller instance data.
1718// \param psUSBRequest holds the new address to use in the wValue field of the
1719// USB request.
1720//
1721// This function is called to handle the change of address request from the
1722// host controller.  This can only start the sequence as the host must
1723// acknowledge that the device has changed address.  Thus this function sets
1724// the address change as pending until the status phase of the request has
1725// been completed successfully.  This prevents the devices address from
1726// changing and not properly responding to the status phase.
1727//
1728// \return None.
1729//
1730//*****************************************************************************
1731static void USBDSetAddress(void* pvInstance, tUSBRequest* psUSBRequest) {
1732    tDCDInstance* psUSBControl;
1733
1734    ASSERT(psUSBRequest != 0);
1735    ASSERT(pvInstance != 0);
1736
1737    //
1738    // Create the device information pointer.
1739    //
1740    psUSBControl = (tDCDInstance*)pvInstance;
1741
1742    //
1743    // Need to ACK the data on end point 0 with last data set as this has no
1744    // data phase.
1745    //
1746    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
1747
1748    //
1749    // Save the device address as we cannot change address until the status
1750    // phase is complete.
1751    //
1752    psUSBControl->ui32DevAddress = psUSBRequest->wValue | DEV_ADDR_PENDING;
1753
1754    //
1755    // Transition directly to the status state since there is no data phase
1756    // for this request.
1757    //
1758    psUSBControl->iEP0State = eUSBStateStatus;
1759}
1760
1761//*****************************************************************************
1762//
1763// This function handles the GET_DESCRIPTOR standard USB request.
1764//
1765// \param pvInstance is the USB device controller instance data.
1766// \param psUSBRequest holds the data for this request.
1767//
1768// This function will return most of the descriptors requested by the host
1769// controller.  The descriptor specified by \e
1770// pvInstance->psInfo->pui8DeviceDescriptor will be returned when the device
1771// descriptor is requested.  If a request for a specific configuration
1772// descriptor is made, then the appropriate descriptor from the \e
1773// g_pConfigDescriptors will be returned.  When a request for a string
1774// descriptor is made, the appropriate string from the
1775// \e pvInstance->psInfo->pStringDescriptors will be returned.  If the
1776// \e pvInstance->psInfo->psCallbacks->GetDescriptor is specified it will be
1777// called to handle the request.  In this case it must call the
1778// USBDCDSendDataEP0() function to send the data to the host controller.  If
1779// the callback is not specified, and the descriptor request is not for a
1780// device, configuration, or string descriptor then this function will stall
1781// the request to indicate that the request was not supported by the device.
1782//
1783// \return None.
1784//
1785//*****************************************************************************
1786static void USBDGetDescriptor(void* pvInstance, tUSBRequest* psUSBRequest) {
1787    bool bConfig;
1788    tDCDInstance* psUSBControl;
1789    tDeviceInfo* psDevice;
1790    const tConfigHeader* psConfig;
1791    const tDeviceDescriptor* psDeviceDesc;
1792    uint8_t ui8Index;
1793    int32_t i32Index;
1794
1795    ASSERT(psUSBRequest != 0);
1796    ASSERT(pvInstance != 0);
1797
1798    //
1799    // Create the device information pointer.
1800    //
1801    psUSBControl = (tDCDInstance*)pvInstance;
1802    psDevice = g_ppsDevInfo[0];
1803
1804    //
1805    // Need to ACK the data on end point 0 without setting last data as there
1806    // will be a data phase.
1807    //
1808    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, false);
1809
1810    //
1811    // Assume we are not sending the configuration descriptor until we
1812    // determine otherwise.
1813    //
1814    bConfig = false;
1815
1816    //
1817    // Which descriptor are we being asked for?
1818    //
1819    switch (psUSBRequest->wValue >> 8) {
1820    //
1821    // This request was for a device descriptor.
1822    //
1823    case USB_DTYPE_DEVICE: {
1824        //
1825        // Return the externally provided device descriptor.
1826        //
1827        psUSBControl->pui8EP0Data = (uint8_t*)psDevice->pui8DeviceDescriptor;
1828
1829        //
1830        // The size of the device descriptor is in the first byte.
1831        //
1832        psUSBControl->ui32EP0DataRemain = psDevice->pui8DeviceDescriptor[0];
1833
1834        break;
1835    }
1836
1837    //
1838    // This request was for a configuration descriptor.
1839    //
1840    case USB_DTYPE_CONFIGURATION: {
1841        //
1842        // Which configuration are we being asked for?
1843        //
1844        ui8Index = (uint8_t)(psUSBRequest->wValue & 0xFF);
1845
1846        //
1847        // Is this valid?
1848        //
1849        psDeviceDesc = (const tDeviceDescriptor*)psDevice->pui8DeviceDescriptor;
1850
1851        if (ui8Index >= psDeviceDesc->bNumConfigurations) {
1852            //
1853            // This is an invalid configuration index.  Stall EP0 to
1854            // indicate a request error.
1855            //
1856            USBDCDStallEP0(0);
1857            psUSBControl->pui8EP0Data = 0;
1858            psUSBControl->ui32EP0DataRemain = 0;
1859        } else {
1860            //
1861            // Return the externally specified configuration descriptor.
1862            //
1863            psConfig = psDevice->ppsConfigDescriptors[ui8Index];
1864
1865            //
1866            // Start by sending data from the beginning of the first
1867            // descriptor.
1868            //
1869            psUSBControl->ui8ConfigSection = 0;
1870            psUSBControl->ui16SectionOffset = 0;
1871            psUSBControl->pui8EP0Data =
1872                (uint8_t*)psConfig->psSections[0]->pui8Data;
1873
1874            //
1875            // Determine the total size of the configuration descriptor
1876            // by counting the sizes of the sections comprising it.
1877            //
1878            psUSBControl->ui32EP0DataRemain = USBDCDConfigDescGetSize(psConfig);
1879
1880            //
1881            // Remember that we need to send the configuration descriptor
1882            // and which descriptor we need to send.
1883            //
1884            psUSBControl->ui8ConfigIndex = ui8Index;
1885
1886            bConfig = true;
1887        }
1888        break;
1889    }
1890
1891    //
1892    // This request was for a string descriptor.
1893    //
1894    case USB_DTYPE_STRING: {
1895        //
1896        // Determine the correct descriptor index based on the requested
1897        // language ID and index.
1898        //
1899        i32Index = USBDStringIndexFromRequest(psUSBRequest->wIndex,
1900                                              psUSBRequest->wValue & 0xFF);
1901
1902        //
1903        // If the mapping function returned -1 then stall the request to
1904        // indicate that the request was not valid.
1905        //
1906        if (i32Index == -1) {
1907            USBDCDStallEP0(0);
1908            break;
1909        }
1910
1911        //
1912        // Return the externally specified configuration descriptor.
1913        //
1914        psUSBControl->pui8EP0Data =
1915            (uint8_t*)psDevice->ppui8StringDescriptors[i32Index];
1916
1917        //
1918        // The total size of a string descriptor is in byte 0.
1919        //
1920        psUSBControl->ui32EP0DataRemain =
1921            psDevice->ppui8StringDescriptors[i32Index][0];
1922
1923        break;
1924    }
1925
1926    //
1927    // Any other request is not handled by the default enumeration handler
1928    // so see if it needs to be passed on to another handler.
1929    //
1930    default: {
1931        //
1932        // If there is a handler for requests that are not handled then
1933        // call it.
1934        //
1935        if (psDevice->psCallbacks->pfnGetDescriptor) {
1936            psDevice->psCallbacks->pfnGetDescriptor(g_psDCDInst[0].pvCBData,
1937                                                    psUSBRequest);
1938        } else {
1939            //
1940            // Whatever this was this handler does not understand it so
1941            // just stall the request.
1942            //
1943            USBDCDStallEP0(0);
1944        }
1945
1946        return;
1947    }
1948    }
1949
1950    //
1951    // If this request has data to send, then send it.
1952    //
1953    if (psUSBControl->pui8EP0Data) {
1954        //
1955        // If there is more data to send than is requested then just
1956        // send the requested amount of data.
1957        //
1958        if (psUSBControl->ui32EP0DataRemain > psUSBRequest->wLength) {
1959            psUSBControl->ui32EP0DataRemain = psUSBRequest->wLength;
1960        }
1961
1962        //
1963        // Now in the transmit data state.  Be careful to call the correct
1964        // function since we need to handle the configuration descriptor
1965        // differently from the others.
1966        //
1967        if (!bConfig) {
1968            USBDEP0StateTx(0);
1969        } else {
1970            USBDEP0StateTxConfig(0);
1971        }
1972    }
1973}
1974
1975//*****************************************************************************
1976//
1977// This function determines which string descriptor to send to satisfy a
1978// request for a given index and language.
1979//
1980// \param ui16Lang is the requested string language ID.
1981// \param ui16Index is the requested string descriptor index.
1982//
1983// When a string descriptor is requested, the host provides a language ID and
1984// index to identify the string ("give me string number 5 in French").  This
1985// function maps these two parameters to an index within our device's string
1986// descriptor array which is arranged as multiple groups of strings with
1987// one group for each language advertised via string descriptor 0.
1988//
1989// We assume that there are an equal number of strings per language and
1990// that the first descriptor is the language descriptor and use this fact to
1991// perform the mapping.
1992//
1993// \return The index of the string descriptor to return or -1 if the string
1994// could not be found.
1995//
1996//*****************************************************************************
1997static int32_t USBDStringIndexFromRequest(uint16_t ui16Lang,
1998                                          uint16_t ui16Index) {
1999    tString0Descriptor* pLang;
2000    uint32_t ui32NumLangs, ui32NumStringi16PerLang, ui32Loop;
2001
2002    //
2003    // Make sure we have a string table at all.
2004    //
2005    if ((g_ppsDevInfo[0] == 0) ||
2006        (g_ppsDevInfo[0]->ppui8StringDescriptors == 0)) {
2007        return (-1);
2008    }
2009
2010    //
2011    // First look for the trivial case where descriptor 0 is being
2012    // requested.  This is the special case since descriptor 0 contains the
2013    // language codes supported by the device.
2014    //
2015    if (ui16Index == 0) {
2016        return (0);
2017    }
2018
2019    //
2020    // How many languages does this device support?  This is determined by
2021    // looking at the length of the first descriptor in the string table,
2022    // subtracting 2 for the header and dividing by two (the size of each
2023    // language code).
2024    //
2025    ui32NumLangs = (g_ppsDevInfo[0]->ppui8StringDescriptors[0][0] - 2) / 2;
2026
2027    //
2028    // We assume that the table includes the same number of strings for each
2029    // supported language.  We know the number of entries in the string table,
2030    // so how many are there for each language?  This may seem an odd way to
2031    // do this (why not just have the application tell us in the device info
2032    // structure?) but it's needed since we didn't want to change the API
2033    // after the first release which did not support multiple languages.
2034    //
2035    ui32NumStringi16PerLang =
2036        ((g_ppsDevInfo[0]->ui32NumStringDescriptors - 1) / ui32NumLangs);
2037
2038    //
2039    // Just to be sure, make sure that the calculation indicates an equal
2040    // number of strings per language.  We expect the string table to contain
2041    // (1 + (strings_per_language * languages)) entries.
2042    //
2043    if ((1 + (ui32NumStringi16PerLang * ui32NumLangs)) !=
2044        g_ppsDevInfo[0]->ui32NumStringDescriptors) {
2045        return (-1);
2046    }
2047
2048    //
2049    // Now determine which language we are looking for.  It is assumed that
2050    // the order of the groups of strings per language in the table is the
2051    // same as the order of the language IDs listed in the first descriptor.
2052    //
2053    pLang = (tString0Descriptor*)(g_ppsDevInfo[0]->ppui8StringDescriptors[0]);
2054
2055    //
2056    // Look through the supported languages looking for the one we were asked
2057    // for.
2058    //
2059    for (ui32Loop = 0; ui32Loop < ui32NumLangs; ui32Loop++) {
2060        //
2061        // Have we found the requested language?
2062        //
2063        if (pLang->wLANGID[ui32Loop] == ui16Lang) {
2064            //
2065            // Yes - calculate the index of the descriptor to send.
2066            //
2067            return ((ui32NumStringi16PerLang * ui32Loop) + ui16Index);
2068        }
2069    }
2070
2071    //
2072    // If we drop out of the loop, the requested language was not found so
2073    // return -1 to indicate the error.
2074    //
2075    return (-1);
2076}
2077
2078//*****************************************************************************
2079//
2080// This function handles the SET_DESCRIPTOR standard USB request.
2081//
2082// \param pvInstance is the USB device controller instance data.
2083// \param psUSBRequest holds the data for this request.
2084//
2085// This function currently is not supported and will respond with a Stall
2086// to indicate that this command is not supported by the device.
2087//
2088// \return None.
2089//
2090//*****************************************************************************
2091static void USBDSetDescriptor(void* pvInstance, tUSBRequest* psUSBRequest) {
2092    //
2093    // Need to ACK the data on end point 0 without setting last data as there
2094    // will be a data phase.
2095    //
2096    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, false);
2097
2098    //
2099    // This function is not handled by default.
2100    //
2101    USBDCDStallEP0(0);
2102}
2103
2104//*****************************************************************************
2105//
2106// This function handles the GET_CONFIGURATION standard USB request.
2107//
2108// \param pvInstance is the USB device controller instance data.
2109// \param psUSBRequest holds the data for this request.
2110//
2111// This function responds to a host request to return the current
2112// configuration of the USB device.  The function will send the configuration
2113// response to the host and return.  This value will either be 0 or the last
2114// value received from a call to SetConfiguration().
2115//
2116// \return None.
2117//
2118//*****************************************************************************
2119static void USBDGetConfiguration(void* pvInstance, tUSBRequest* psUSBRequest) {
2120    uint8_t ui8Value;
2121    tDCDInstance* psUSBControl;
2122
2123    ASSERT(psUSBRequest != 0);
2124    ASSERT(pvInstance != 0);
2125
2126    //
2127    // Create the device information pointer.
2128    //
2129    psUSBControl = (tDCDInstance*)pvInstance;
2130
2131    //
2132    // Need to ACK the data on end point 0 without setting last data as there
2133    // will be a data phase.
2134    //
2135    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, false);
2136
2137    //
2138    // If we still have an address pending then the device is still not
2139    // configured.
2140    //
2141    if (psUSBControl->ui32DevAddress & DEV_ADDR_PENDING) {
2142        ui8Value = 0;
2143    } else {
2144        ui8Value = (uint8_t)psUSBControl->ui32Configuration;
2145    }
2146
2147    psUSBControl->ui32EP0DataRemain = 1;
2148    psUSBControl->pui8EP0Data = &ui8Value;
2149
2150    //
2151    // Send the single byte response.
2152    //
2153    USBDEP0StateTx(0);
2154}
2155
2156//*****************************************************************************
2157//
2158// This function handles the SET_CONFIGURATION standard USB request.
2159//
2160// \param pvInstance is the USB device controller instance data.
2161// \param psUSBRequest holds the data for this request.
2162//
2163// This function responds to a host request to change the current
2164// configuration of the USB device.  The actual configuration number is taken
2165// from the structure passed in via \e psUSBRequest.  This number should be one
2166// of the configurations that was specified in the descriptors.  If the
2167// \e ConfigChange callback is specified in \e pvInstance->psInfo->psCallbacks->
2168// it will be called so that the application can respond to a change in
2169// configuration.
2170//
2171// \return None.
2172//
2173//*****************************************************************************
2174static void USBDSetConfiguration(void* pvInstance, tUSBRequest* psUSBRequest) {
2175    tDCDInstance* psUSBControl;
2176    tDeviceInfo* psDevice;
2177    const tConfigHeader* psHdr;
2178    const tConfigDescriptor* psDesc;
2179
2180    //
2181    // Create the device information pointer.
2182    //
2183    psUSBControl = (tDCDInstance*)pvInstance;
2184    psDevice = g_ppsDevInfo[0];
2185
2186    //
2187    // Need to ACK the data on end point 0 with last data set as this has no
2188    // data phase.
2189    //
2190    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
2191
2192    //
2193    // Cannot set the configuration to one that does not exist so check the
2194    // enumeration structure to see how many valid configurations are present.
2195    //
2196    if (psUSBRequest->wValue > psDevice->pui8DeviceDescriptor[17]) {
2197        //
2198        // The passed configuration number is not valid.  Stall the endpoint to
2199        // signal the error to the host.
2200        //
2201        USBDCDStallEP0(0);
2202    } else {
2203        //
2204        // Save the configuration.
2205        //
2206        psUSBControl->ui32Configuration = psUSBRequest->wValue;
2207
2208        //
2209        // If passed a configuration other than 0 (which tells us that we are
2210        // not currently configured), configure the endpoints (other than EP0)
2211        // appropriately.
2212        //
2213        if (psUSBControl->ui32Configuration) {
2214            //
2215            // Get a pointer to the configuration descriptor.  This will always
2216            // be the first section in the current configuration.
2217            //
2218            psHdr = psDevice->ppsConfigDescriptors[psUSBRequest->wValue - 1];
2219            psDesc = (const tConfigDescriptor*)(psHdr->psSections[0]->pui8Data);
2220
2221            //
2222            // Remember the new self- or bus-powered state if the user has not
2223            // already called us to tell us the state to report.
2224            //
2225            if (!psUSBControl->bPwrSrcSet) {
2226                if ((psDesc->bmAttributes & USB_CONF_ATTR_PWR_M) ==
2227                    USB_CONF_ATTR_SELF_PWR) {
2228                    psUSBControl->ui8Status |= USB_STATUS_SELF_PWR;
2229                } else {
2230                    psUSBControl->ui8Status &= ~USB_STATUS_SELF_PWR;
2231                }
2232            }
2233
2234            //
2235            // Configure endpoints for the new configuration.
2236            //
2237            USBDeviceConfig(
2238                psUSBControl,
2239                psDevice->ppsConfigDescriptors[psUSBRequest->wValue - 1]);
2240        }
2241
2242        //
2243        // If there is a configuration change callback then call it.
2244        //
2245        if (psDevice->psCallbacks->pfnConfigChange) {
2246            psDevice->psCallbacks->pfnConfigChange(
2247                g_psDCDInst[0].pvCBData, psUSBControl->ui32Configuration);
2248        }
2249    }
2250}
2251
2252//*****************************************************************************
2253//
2254// This function handles the GET_INTERFACE standard USB request.
2255//
2256// \param pvInstance is the USB device controller instance data.
2257// \param psUSBRequest holds the data for this request.
2258//
2259// This function is called when the host controller request the current
2260// interface that is in use by the device.  This simply returns the value set
2261// by the last call to SetInterface().
2262//
2263// \return None.
2264//
2265//*****************************************************************************
2266static void USBDGetInterface(void* pvInstance, tUSBRequest* psUSBRequest) {
2267    uint8_t ui8Value;
2268    tDCDInstance* psUSBControl;
2269
2270    ASSERT(psUSBRequest != 0);
2271    ASSERT(pvInstance != 0);
2272
2273    //
2274    // Create the device information pointer.
2275    //
2276    psUSBControl = (tDCDInstance*)pvInstance;
2277
2278    //
2279    // Need to ACK the data on end point 0 without setting last data as there
2280    // will be a data phase.
2281    //
2282    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, false);
2283
2284    //
2285    // If we still have an address pending then the device is still not
2286    // configured.
2287    //
2288    if (psUSBControl->ui32DevAddress & DEV_ADDR_PENDING) {
2289        ui8Value = (uint8_t)0;
2290    } else {
2291        //
2292        // Is the interface number valid?
2293        //
2294        if (psUSBRequest->wIndex < USB_MAX_INTERFACES_PER_DEVICE) {
2295            //
2296            // Read the current alternate setting for the required interface.
2297            //
2298            ui8Value = psUSBControl->pui8AltSetting[psUSBRequest->wIndex];
2299        } else {
2300            //
2301            // An invalid interface number was specified.
2302            //
2303            USBDCDStallEP0(0);
2304            return;
2305        }
2306    }
2307
2308    //
2309    // Send the single byte response.
2310    //
2311    psUSBControl->ui32EP0DataRemain = 1;
2312    psUSBControl->pui8EP0Data = &ui8Value;
2313
2314    //
2315    // Send the single byte response.
2316    //
2317    USBDEP0StateTx(0);
2318}
2319
2320//*****************************************************************************
2321//
2322// This function handles the SET_INTERFACE standard USB request.
2323//
2324// \param pvInstance is the USB device controller instance data.
2325// \param psUSBRequest holds the data for this request.
2326//
2327// This function is called when a standard request for changing the interface
2328// is received from the host controller.  If this is a valid request the
2329// function will call the function specified by the InterfaceChange in the
2330// \e pvInstance->psInfo->psCallbacks->variable to notify the application that
2331// the interface has changed and will pass it the new alternate interface
2332// number.
2333//
2334// \return None.
2335//
2336//*****************************************************************************
2337static void USBDSetInterface(void* pvInstance, tUSBRequest* psUSBRequest) {
2338    const tConfigHeader* psConfig;
2339    tInterfaceDescriptor* psInterface;
2340    uint32_t ui32Loop, ui32Section, ui32NumInterfaces;
2341    uint8_t ui8Interface;
2342    bool bRetcode;
2343    tDCDInstance* psUSBControl;
2344    tDeviceInfo* psDevice;
2345
2346    ASSERT(psUSBRequest != 0);
2347    ASSERT(pvInstance != 0);
2348
2349    //
2350    // Create the device information pointer.
2351    //
2352    psUSBControl = (tDCDInstance*)pvInstance;
2353    psDevice = g_ppsDevInfo[0];
2354
2355    //
2356    // Need to ACK the data on end point 0 with last data set as this has no
2357    // data phase.
2358    //
2359    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
2360
2361    //
2362    // Use the current configuration.
2363    //
2364    psConfig =
2365        psDevice->ppsConfigDescriptors[psUSBControl->ui32Configuration - 1];
2366
2367    //
2368    // How many interfaces are included in the descriptor?
2369    //
2370    ui32NumInterfaces = USBDCDConfigDescGetNum(psConfig, USB_DTYPE_INTERFACE);
2371
2372    //
2373    // Find the interface descriptor for the supplied interface and alternate
2374    // setting numbers.
2375    //
2376    for (ui32Loop = 0; ui32Loop < ui32NumInterfaces; ui32Loop++) {
2377        //
2378        // Get the next interface descriptor in the configuration descriptor.
2379        //
2380        psInterface = USBDCDConfigGetInterface(psConfig, ui32Loop, USB_DESC_ANY,
2381                                               &ui32Section);
2382
2383        //
2384        // Is this the required interface with the correct alternate setting?
2385        //
2386        if (psInterface &&
2387            (psInterface->bInterfaceNumber == psUSBRequest->wIndex) &&
2388            (psInterface->bAlternateSetting == psUSBRequest->wValue)) {
2389            ui8Interface = psInterface->bInterfaceNumber;
2390
2391            //
2392            // Make sure we don't write outside the bounds of the
2393            // pui8AltSetting array (in a debug build, anyway, since this
2394            // indicates an error in the device descriptor).
2395            //
2396            ASSERT(ui8Interface < USB_MAX_INTERFACES_PER_DEVICE);
2397
2398            //
2399            // This is the correct interface descriptor so save the
2400            // setting.
2401            //
2402            psUSBControl->pui8AltSetting[ui8Interface] =
2403                psInterface->bAlternateSetting;
2404
2405            //
2406            // Reconfigure the endpoints to match the requirements of the
2407            // new alternate setting for the interface.
2408            //
2409            bRetcode =
2410                USBDeviceConfigAlternate(psUSBControl, psConfig, ui8Interface,
2411                                         psInterface->bAlternateSetting);
2412
2413            //
2414            // If there is a callback then notify the application of the
2415            // change to the alternate interface.
2416            //
2417            if (bRetcode && psDevice->psCallbacks->pfnInterfaceChange) {
2418                psDevice->psCallbacks->pfnInterfaceChange(
2419                    g_psDCDInst[0].pvCBData, psUSBRequest->wIndex,
2420                    psUSBRequest->wValue);
2421            }
2422
2423            //
2424            // All done.
2425            //
2426            return;
2427        }
2428    }
2429
2430    //
2431    // If we drop out of the loop, we didn't find an interface descriptor
2432    // matching the requested number and alternate setting or there was an
2433    // error while trying to set up for the new alternate setting.
2434    //
2435    USBDCDStallEP0(0);
2436}
2437
2438//*****************************************************************************
2439//
2440// This function handles the SYNC_FRAME standard USB request.
2441//
2442// \param pvInstance is the USB device controller instance data.
2443// \param psUSBRequest holds the data for this request.
2444//
2445// This is currently a stub function that will stall indicating that the
2446// command is not supported.
2447//
2448// \return None.
2449//
2450//*****************************************************************************
2451static void USBDSyncFrame(void* pvInstance, tUSBRequest* psUSBRequest) {
2452    //
2453    // Need to ACK the data on end point 0 with last data set as this has no
2454    // data phase.
2455    //
2456    MAP_USBDevEndpointDataAck(USB0_BASE, USB_EP_0, true);
2457
2458    //
2459    // Not handled yet so stall this request.
2460    //
2461    USBDCDStallEP0(0);
2462}
2463
2464//*****************************************************************************
2465//
2466// This internal function handles sending data on endpoint zero.
2467//
2468// \param ui32Index is the index of the USB controller which is to be
2469// initialized.
2470//
2471// \return None.
2472//
2473//*****************************************************************************
2474static void USBDEP0StateTx(uint32_t ui32Index) {
2475    uint32_t ui32NumBytes;
2476    uint8_t* pui8Data;
2477
2478    ASSERT(ui32Index == 0);
2479
2480    //
2481    // In the TX state on endpoint zero.
2482    //
2483    g_psDCDInst[0].iEP0State = eUSBStateTx;
2484
2485    //
2486    // Set the number of bytes to send this iteration.
2487    //
2488    ui32NumBytes = g_psDCDInst[0].ui32EP0DataRemain;
2489
2490    //
2491    // Limit individual transfers to 64 bytes.
2492    //
2493    if (ui32NumBytes > EP0_MAX_PACKET_SIZE) {
2494        ui32NumBytes = EP0_MAX_PACKET_SIZE;
2495    }
2496
2497    //
2498    // Save the pointer so that it can be passed to the USBEndpointDataPut()
2499    // function.
2500    //
2501    pui8Data = (uint8_t*)g_psDCDInst[0].pui8EP0Data;
2502
2503    //
2504    // Advance the data pointer and counter to the next data to be sent.
2505    //
2506    g_psDCDInst[0].ui32EP0DataRemain -= ui32NumBytes;
2507    g_psDCDInst[0].pui8EP0Data += ui32NumBytes;
2508
2509    //
2510    // Put the data in the correct FIFO.
2511    //
2512    MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, pui8Data, ui32NumBytes);
2513
2514    //
2515    // If this is exactly 64 then don't set the last packet yet.
2516    //
2517    if (ui32NumBytes == EP0_MAX_PACKET_SIZE) {
2518        //
2519        // There is more data to send or exactly 64 bytes were sent, this
2520        // means that there is either more data coming or a null packet needs
2521        // to be sent to complete the transaction.
2522        //
2523        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_IN);
2524    } else {
2525        //
2526        // Now go to the status state and wait for the transmit to complete.
2527        //
2528        g_psDCDInst[0].iEP0State = eUSBStateStatus;
2529
2530        //
2531        // Send the last bit of data.
2532        //
2533        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_IN_LAST);
2534
2535        //
2536        // If there is a sent callback then call it.
2537        //
2538        if ((g_ppsDevInfo[0]->psCallbacks->pfnDataSent) &&
2539            (g_psDCDInst[0].ui32OUTDataSize != 0)) {
2540            //
2541            // Call the custom handler.
2542            //
2543            g_ppsDevInfo[0]->psCallbacks->pfnDataSent(
2544                g_psDCDInst[0].pvCBData, g_psDCDInst[0].ui32OUTDataSize);
2545
2546            //
2547            // There is no longer any data pending to be sent.
2548            //
2549            g_psDCDInst[0].ui32OUTDataSize = 0;
2550        }
2551    }
2552}
2553
2554//*****************************************************************************
2555//
2556// This internal function handles sending the configuration descriptor on
2557// endpoint zero.
2558//
2559// \param ui32Index is the index of the USB controller.
2560//
2561// \return None.
2562//
2563//*****************************************************************************
2564static void USBDEP0StateTxConfig(uint32_t ui32Index) {
2565    uint32_t ui32NumBytes, ui32SecBytes, ui32ToSend;
2566    uint8_t* pui8Data;
2567    tConfigDescriptor sConfDesc;
2568    const tConfigHeader* psConfig;
2569    const tConfigSection* psSection;
2570
2571    ASSERT(ui32Index == 0);
2572
2573    //
2574    // In the TX state on endpoint zero.
2575    //
2576    g_psDCDInst[0].iEP0State = eUSBStateTxConfig;
2577
2578    //
2579    // Find the current configuration descriptor definition.
2580    //
2581    psConfig =
2582        g_ppsDevInfo[0]->ppsConfigDescriptors[g_psDCDInst[0].ui8ConfigIndex];
2583
2584    //
2585    // Set the number of bytes to send this iteration.
2586    //
2587    ui32NumBytes = g_psDCDInst[0].ui32EP0DataRemain;
2588
2589    //
2590    // Limit individual transfers to 64 bytes.
2591    //
2592    if (ui32NumBytes > EP0_MAX_PACKET_SIZE) {
2593        ui32NumBytes = EP0_MAX_PACKET_SIZE;
2594    }
2595
2596    //
2597    // If this is the first call, we need to fix up the total length of the
2598    // configuration descriptor.  This has already been determined and set in
2599    // g_sUSBDeviceState.ui32EP0DataRemain.
2600    //
2601    if ((g_psDCDInst[0].ui16SectionOffset == 0) &&
2602        (g_psDCDInst[0].ui8ConfigSection == 0)) {
2603        //
2604        // Copy the USB configuration descriptor from the beginning of the
2605        // first section of the current configuration.
2606        //
2607        sConfDesc = *(tConfigDescriptor*)g_psDCDInst[0].pui8EP0Data;
2608
2609        //
2610        // Update the total size.
2611        //
2612        sConfDesc.wTotalLength = (uint16_t)USBDCDConfigDescGetSize(psConfig);
2613
2614        //
2615        // Write the descriptor to the USB FIFO.
2616        //
2617        ui32ToSend = (ui32NumBytes < sizeof(tConfigDescriptor))
2618                         ? ui32NumBytes
2619                         : sizeof(tConfigDescriptor);
2620        MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, (uint8_t*)&sConfDesc,
2621                               ui32ToSend);
2622
2623        //
2624        // Did we reach the end of the first section?
2625        //
2626        if (psConfig->psSections[0]->ui16Size == ui32ToSend) {
2627            //
2628            // Update our tracking indices to point to the start of the next
2629            // section.
2630            //
2631            g_psDCDInst[0].ui16SectionOffset = 0;
2632            g_psDCDInst[0].ui8ConfigSection = 1;
2633        } else {
2634            //
2635            // Note that we have sent the first few bytes of the descriptor.
2636            //
2637            g_psDCDInst[0].ui16SectionOffset = (uint8_t)ui32ToSend;
2638        }
2639
2640        //
2641        // How many bytes do we have remaining to send on this iteration?
2642        //
2643        ui32ToSend = ui32NumBytes - ui32ToSend;
2644    } else {
2645        //
2646        // Set the number of bytes we still have to send on this call.
2647        //
2648        ui32ToSend = ui32NumBytes;
2649    }
2650
2651    //
2652    // Add the relevant number of bytes to the USB FIFO
2653    //
2654    while (ui32ToSend) {
2655        //
2656        // Get a pointer to the current configuration section.
2657        //
2658        psSection = psConfig->psSections[g_psDCDInst[0].ui8ConfigSection];
2659
2660        //
2661        // Calculate bytes are available in the current configuration section.
2662        //
2663        ui32SecBytes =
2664            (uint32_t)(psSection->ui16Size - g_psDCDInst[0].ui16SectionOffset);
2665
2666        //
2667        // Save the pointer so that it can be passed to the
2668        // USBEndpointDataPut() function.
2669        //
2670        pui8Data =
2671            (uint8_t*)psSection->pui8Data + g_psDCDInst[0].ui16SectionOffset;
2672
2673        //
2674        // Are there more bytes in this section that we still have to send?
2675        //
2676        if (ui32SecBytes > ui32ToSend) {
2677            //
2678            // Yes - send only the remaining bytes in the transfer.
2679            //
2680            ui32SecBytes = ui32ToSend;
2681        }
2682
2683        //
2684        // Put the data in the correct FIFO.
2685        //
2686        MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, pui8Data, ui32SecBytes);
2687
2688        //
2689        // Fix up our pointers for the next iteration.
2690        //
2691        ui32ToSend -= ui32SecBytes;
2692        g_psDCDInst[0].ui16SectionOffset += (uint8_t)ui32SecBytes;
2693
2694        //
2695        // Have we reached the end of a section?
2696        //
2697        if (g_psDCDInst[0].ui16SectionOffset == psSection->ui16Size) {
2698            //
2699            // Yes - move to the next one.
2700            //
2701            g_psDCDInst[0].ui8ConfigSection++;
2702            g_psDCDInst[0].ui16SectionOffset = 0;
2703        }
2704    }
2705
2706    //
2707    // Fix up the number of bytes remaining to be sent and the start pointer.
2708    //
2709    g_psDCDInst[0].ui32EP0DataRemain -= ui32NumBytes;
2710
2711    //
2712    // If we ran out of bytes in the configuration section, bail and just
2713    // send out what we have.
2714    //
2715    if (psConfig->ui8NumSections <= g_psDCDInst[0].ui8ConfigSection) {
2716        g_psDCDInst[0].ui32EP0DataRemain = 0;
2717    }
2718
2719    //
2720    // If there is no more data don't keep looking or ui8ConfigSection might
2721    // overrun the available space.
2722    //
2723    if (g_psDCDInst[0].ui32EP0DataRemain != 0) {
2724        pui8Data =
2725            (uint8_t*)psConfig->psSections[g_psDCDInst[0].ui8ConfigSection]
2726                ->pui8Data;
2727        ui32ToSend = g_psDCDInst[0].ui16SectionOffset;
2728        g_psDCDInst[0].pui8EP0Data = (pui8Data + ui32ToSend);
2729    }
2730
2731    //
2732    // If this is exactly 64 then don't set the last packet yet.
2733    //
2734    if (ui32NumBytes == EP0_MAX_PACKET_SIZE) {
2735        //
2736        // There is more data to send or exactly 64 bytes were sent, this
2737        // means that there is either more data coming or a null packet needs
2738        // to be sent to complete the transaction.
2739        //
2740        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_IN);
2741    } else {
2742        //
2743        // Send the last bit of data.
2744        //
2745        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_IN_LAST);
2746
2747        //
2748        // If there is a sent callback then call it.
2749        //
2750        if ((g_ppsDevInfo[0]->psCallbacks->pfnDataSent) &&
2751            (g_psDCDInst[0].ui32OUTDataSize != 0)) {
2752            //
2753            // Call the custom handler.
2754            //
2755            g_ppsDevInfo[0]->psCallbacks->pfnDataSent(
2756                g_psDCDInst[0].pvCBData, g_psDCDInst[0].ui32OUTDataSize);
2757
2758            //
2759            // There is no longer any data pending to be sent.
2760            //
2761            g_psDCDInst[0].ui32OUTDataSize = 0;
2762        }
2763
2764        //
2765        // Now go to the status state and wait for the transmit to complete.
2766        //
2767        g_psDCDInst[0].iEP0State = eUSBStateStatus;
2768    }
2769}
2770
2771//*****************************************************************************
2772//
2773// The internal USB device interrupt handler.
2774//
2775// \param ui32Index is the USB controller associated with this interrupt.
2776// \param ui32Status is the current interrupt status as read via a call to
2777// USBIntStatusControl().
2778//
2779// This function is called from either \e USB0DualModeIntHandler() or
2780// \e USB0DeviceIntHandler() to process USB interrupts when in device mode.
2781// This handler will branch the interrupt off to the appropriate application or
2782// stack handlers depending on the current status of the USB controller.
2783//
2784// The two-tiered structure for the interrupt handler ensures that it is
2785// possible to use the same handler code in both device and OTG modes and
2786// means that host code can be excluded from applications that only require
2787// support for USB device mode operation.
2788//
2789// \return None.
2790//
2791//*****************************************************************************
2792void USBDeviceIntHandlerInternal(uint32_t ui32Index, uint32_t ui32Status) {
2793    static uint32_t ui32SOFDivide = 0;
2794    void* pvInstance;
2795    uint32_t ui32DMAIntStatus;
2796    uint32_t ui32LPMStatus;
2797
2798    //
2799    // If device initialization has not been performed then just disconnect
2800    // from the USB bus and return from the handler.
2801    //
2802    if (g_ppsDevInfo[0] == 0) {
2803        MAP_USBDevDisconnect(USB0_BASE);
2804        return;
2805    }
2806
2807    pvInstance = g_psDCDInst[0].pvCBData;
2808
2809    //
2810    // Received a reset from the host.
2811    //
2812    if (ui32Status & USB_INTCTRL_RESET) {
2813        USBDeviceEnumResetHandler(&g_psDCDInst[0]);
2814    }
2815
2816    //
2817    // Suspend was signaled on the bus.
2818    //
2819    if (ui32Status & USB_INTCTRL_SUSPEND) {
2820        //
2821        // Call the SuspendHandler() if it was specified.
2822        //
2823        if (g_ppsDevInfo[0]->psCallbacks->pfnSuspendHandler) {
2824            g_ppsDevInfo[0]->psCallbacks->pfnSuspendHandler(pvInstance);
2825        }
2826    }
2827
2828    //
2829    // Resume was signaled on the bus.
2830    //
2831    if (ui32Status & USB_INTCTRL_RESUME) {
2832        //
2833        // Call the ResumeHandler() if it was specified.
2834        //
2835        if (g_ppsDevInfo[0]->psCallbacks->pfnResumeHandler) {
2836            g_ppsDevInfo[0]->psCallbacks->pfnResumeHandler(pvInstance);
2837        }
2838    }
2839
2840    //
2841    // USB device was disconnected.
2842    //
2843    if (ui32Status & USB_INTCTRL_DISCONNECT) {
2844        //
2845        // Call the DisconnectHandler() if it was specified.
2846        //
2847        if (g_ppsDevInfo[0]->psCallbacks->pfnDisconnectHandler) {
2848            g_ppsDevInfo[0]->psCallbacks->pfnDisconnectHandler(pvInstance);
2849        }
2850    }
2851
2852    //
2853    // Start of Frame was received.
2854    //
2855    if (ui32Status & USB_INTCTRL_SOF) {
2856        //
2857        // Increment the global Start of Frame counter.
2858        //
2859        g_ui32USBSOFCount++;
2860
2861        //
2862        // Increment our SOF divider.
2863        //
2864        ui32SOFDivide++;
2865
2866        //
2867        // Handle resume signaling if required.
2868        //
2869        USBDeviceResumeTickHandler(&g_psDCDInst[0]);
2870
2871        //
2872        // Have we counted enough SOFs to allow us to call the tick function?
2873        //
2874        if (ui32SOFDivide == USB_SOF_TICK_DIVIDE) {
2875            //
2876            // Yes - reset the divider and call the SOF tick handler.
2877            //
2878            ui32SOFDivide = 0;
2879            InternalUSBStartOfFrameTick(USB_SOF_TICK_DIVIDE);
2880        }
2881    }
2882
2883    //
2884    // Handle LPM interrupts.
2885    //
2886    ui32LPMStatus = USBLPMIntStatus(USB0_BASE);
2887
2888    //
2889    // The host LPM resume request has been acknowledged, allow the device
2890    // class to handle the sleep state.
2891    //
2892    if ((g_psDCDInst[0].ui32LPMState == USBLIB_LPM_STATE_SLEEP) &&
2893        ((ui32LPMStatus & (USB_INTLPM_ACK | USB_INTLPM_RESUME)) ==
2894         USB_INTLPM_RESUME)) {
2895        //
2896        // Notify the class of the wake from LPM L1.
2897        //
2898        if (g_ppsDevInfo[0]->psCallbacks->pfnDeviceHandler) {
2899            g_ppsDevInfo[0]->psCallbacks->pfnDeviceHandler(
2900                pvInstance, USB_EVENT_LPM_RESUME, (void*)0);
2901        }
2902
2903        //
2904        // Now back in the awake state.
2905        //
2906        g_psDCDInst[0].ui32LPMState = USBLIB_LPM_STATE_AWAKE;
2907
2908        //
2909        // Enable receiving of LPM packet.
2910        //
2911        USBDevLPMEnable(USB0_BASE);
2912    }
2913    //
2914    // The host LPM sleep request has been acknowledged, allow the device
2915    // class to handle the sleep state.
2916    //
2917    else if ((g_psDCDInst[0].ui32LPMState == USBLIB_LPM_STATE_AWAKE) &&
2918             ((ui32LPMStatus & (USB_INTLPM_ACK | USB_INTLPM_RESUME)) ==
2919              USB_INTLPM_ACK)) {
2920        if (g_ppsDevInfo[0]->psCallbacks->pfnDeviceHandler) {
2921            g_ppsDevInfo[0]->psCallbacks->pfnDeviceHandler(
2922                pvInstance, USB_EVENT_LPM_SLEEP, (void*)0);
2923        }
2924
2925        //
2926        // Now back in the sleep state.
2927        //
2928        g_psDCDInst[0].ui32LPMState = USBLIB_LPM_STATE_SLEEP;
2929    } else if (ui32LPMStatus & USB_INTLPM_NYET) {
2930        //
2931        // The device has held off the sleep state because LPM
2932        // responses are disabled.
2933        //
2934        if (g_ppsDevInfo[0]->psCallbacks->pfnDeviceHandler) {
2935            g_ppsDevInfo[0]->psCallbacks->pfnDeviceHandler(
2936                pvInstance, USB_EVENT_LPM_ERROR, (void*)0);
2937        }
2938    }
2939
2940    //
2941    // Get the controller interrupt status.
2942    //
2943    ui32Status = MAP_USBIntStatusEndpoint(USB0_BASE);
2944
2945    //
2946    // Handle end point 0 interrupts.
2947    //
2948    if (ui32Status & USB_INTEP_0) {
2949        USBDeviceEnumHandler(&g_psDCDInst[0]);
2950        ui32Status &= ~USB_INTEP_0;
2951    }
2952
2953    //
2954    // Check to see if any DMA transfers are pending
2955    //
2956    ui32DMAIntStatus = USBLibDMAIntStatus(g_psDCDInst[0].psDMAInstance);
2957
2958    if (ui32DMAIntStatus) {
2959        //
2960        // Handle any DMA interrupt processing.
2961        //
2962        USBLibDMAIntHandler(g_psDCDInst[0].psDMAInstance, ui32DMAIntStatus);
2963    }
2964
2965    //
2966    // Because there is no way to detect if a uDMA interrupt has occurred,
2967    // check for an endpoint callback and call it if it is available.
2968    //
2969    if ((g_ppsDevInfo[0]->psCallbacks->pfnEndpointHandler) &&
2970        ((ui32Status != 0) || (ui32DMAIntStatus != 0))) {
2971        g_ppsDevInfo[0]->psCallbacks->pfnEndpointHandler(pvInstance,
2972                                                         ui32Status);
2973    }
2974}
2975
2976//*****************************************************************************
2977//
2978// Close the Doxygen group.
2979//! @}
2980//
2981//*****************************************************************************