+/rtos

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

Joseph RyanRe-add usblib files83915e3

master
187.2 KiB5791 linesraw
1//*****************************************************************************
2//
3// usbhostenum.c - Device enumeration code for the USB host library.
4//
5// Copyright (c) 2008-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 "tivaware/hw_ints.h"
26#include "tivaware/hw_memmap.h"
27#include "tivaware/hw_sysctl.h"
28#include "tivaware/hw_types.h"
29#include "tivaware/rom.h"
30#include "tivaware/rom_map.h"
31#include "tivaware/rtos_bindings.h"
32#include "tivaware/sysctl.h"
33#include "tivaware/usb.h"
34#include "usblib/host/usbhhub.h"
35#include "usblib/host/usbhost.h"
36#include "usblib/host/usbhostpriv.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#ifdef INCLUDE_DEBUG_OUTPUT
46#include "utils/uartstdio.h"
47#define DEBUG_OUTPUT UARTprintf
48#else
49#define DEBUG_OUTPUT                                                           \
50    while (0) ((int32_t(*)(char*, ...))0)
51#endif
52
53//*****************************************************************************
54//
55//! \addtogroup usblib_hcd
56//! @{
57//
58//*****************************************************************************
59
60//*****************************************************************************
61//
62// External prototypes.
63//
64//*****************************************************************************
65extern tUSBMode g_iUSBMode;
66
67extern void OTGDeviceDisconnect(uint32_t ui32Index);
68
69//*****************************************************************************
70//
71// Internal function prototypes.
72//
73//*****************************************************************************
74static void USBHCDEP0StateTx(void);
75static void USBHCDEnumHandler(void);
76static void USBHCDClearFeature(uint32_t ui32DevAddress, uint32_t ui32Endpoint,
77                               uint32_t ui32Feature);
78
79//*****************************************************************************
80//
81// Automatic power enable.
82//
83//*****************************************************************************
84#define USB_HOST_PWREN_AUTO 0x00000002
85
86//*****************************************************************************
87//
88// Flags used to signal between the interrupt handler and USBHCDMain().
89//
90//*****************************************************************************
91#define INT_EVENT_VBUS_ERR 0x01
92#define INT_EVENT_CONNECT 0x02
93#define INT_EVENT_DISCONNECT 0x04
94#define INT_EVENT_POWER_FAULT 0x08
95#define INT_EVENT_SOF 0x10
96#define INT_EVENT_ENUM 0x20
97#define INT_EVENT_LPM_PEND 0x40
98#define INT_EVENT_LPM 0x80
99
100//*****************************************************************************
101//
102// Flags used with the tUSBHostDevice.ui32Flags structure member.
103//
104//*****************************************************************************
105#define USBHDEV_FLAG_NOTIFYINT 0x00000001
106#define USBHDEV_FLAG_LPMPEND 0x00000002
107#define USBHDEV_FLAG_LPMERROR 0x00000004
108#define USBHDEV_FLAG_ALLOCATED 0x80000000
109
110//*****************************************************************************
111//
112// This holds the current power configuration that is used when USBHCDInit()
113// is called.
114//
115//*****************************************************************************
116static uint32_t g_ui32PowerConfig = USBHCD_VBUS_AUTO_HIGH;
117
118//*****************************************************************************
119//
120// The states for endpoint 0 during enumeration.
121//
122//*****************************************************************************
123typedef enum {
124    //
125    // The USB device is waiting on a request from the host controller on
126    // endpoint 0.
127    //
128    eEP0StateIdle,
129
130    //
131    // Setup packet is expecting data IN.
132    //
133    eEP0StateSetupIN,
134
135    //
136    // Setup packet is sending data OUT.
137    //
138    eEP0StateSetupOUT,
139
140    //
141    // The USB device is receiving data from the device due to an SETUP IN
142    // request.
143    //
144    eEP0StateRx,
145
146    //
147    // The USB device has completed the IN or OUT request and is now waiting
148    // for the host to acknowledge the end of the IN/OUT transaction.  This
149    // is the status phase for a USB control transaction.
150    //
151    eEP0StateStatus,
152
153    //
154    // This state is for when a response only has a status phase and no
155    // data phase.
156    //
157    eEP0StateStatusIN,
158
159    //
160    // This endpoint has signaled a stall condition and is waiting for the
161    // stall to be acknowledged by the host controller.
162    //
163    eEP0StateStall,
164
165    //
166    // An error has occurred on endpoint 0.
167    //
168    eEP0StateError
169} tEP0State;
170
171//*****************************************************************************
172//
173// This structure holds the full state for the device enumeration.
174//
175//*****************************************************************************
176typedef struct {
177    //
178    // This is the pointer to the current data being sent out or received
179    // on endpoint 0.
180    //
181    uint8_t* pui8Data;
182
183    //
184    // This is the number of bytes that remain to be sent from or received
185    // into the g_DeviceState.pEP0Data data buffer.
186    //
187    volatile uint32_t ui32BytesRemaining;
188
189    //
190    // The amount of data being sent/received due to a request.
191    //
192    uint32_t ui32DataSize;
193
194    //
195    // This is the current device address in use by endpoint 0.
196    //
197    uint32_t ui32DevAddress;
198
199    //
200    // The maximum packet size for the device responding to the setup packet.
201    //
202    uint32_t ui32MaxPacketSize;
203
204    //
205    // The host controller's state.
206    //
207    tEP0State iState;
208} tHostState;
209
210//*****************************************************************************
211//
212// This variable holds the current state of endpoint 0.
213//
214//*****************************************************************************
215static volatile tHostState g_sUSBHEP0State = {
216    0,            // pui8Data
217    0,            // ui32BytesRemaining
218    0,            // ui32DataSize
219    0,            // ui32DevAddress
220    0,            // ui32MaxPacketSize
221    eEP0StateIdle // iState
222};
223
224//*****************************************************************************
225//
226// The global delay time for use by SysCtlDelay() function.  This is
227// initialized to an appropriate value for a 50MHz clock.  The correct value
228// will be set in USBHCDInit().
229//
230//*****************************************************************************
231static uint32_t g_ui32Tickms = 0;
232static volatile uint32_t g_ui32CurrentTick = 0;
233
234//*****************************************************************************
235//
236// This is 480000000/60000000 or a PLL Divide of 8.
237//
238//*****************************************************************************
239static uint32_t g_ui32PLLDiv = 8;
240
241//*****************************************************************************
242//
243// Holds the ULPI configuration.
244//
245//*****************************************************************************
246static uint32_t g_ui32ULPISupport;
247
248//*****************************************************************************
249//
250// The current active drivers.
251//
252//*****************************************************************************
253static int32_t g_pi32USBHActiveDriver[MAX_USB_DEVICES + 1];
254static void* g_ppvDriverInstance[MAX_USB_DEVICES + 1];
255
256//*****************************************************************************
257//
258// This is the structure used to hold the information for a given USB pipe
259// that is attached to a device.
260//
261//*****************************************************************************
262typedef struct {
263    //
264    // The current address for this pipe.
265    //
266    tUSBHostDevice* psDevice;
267
268    //
269    // The current address for this pipe.
270    //
271    uint8_t ui8EPNumber;
272
273    //
274    // The DMA channel assigned to this endpoint.
275    //
276    uint8_t ui8DMAChannel;
277
278    //
279    // The current type for this pipe.
280    //
281    uint32_t ui32Type;
282
283    //
284    // The millisecond interval for this pipe.
285    //
286    uint32_t ui32Interval;
287
288    //
289    // The next tick value to trigger and event on this pipe.
290    //
291    uint32_t ui32NextEventTick;
292
293    //
294    // The current call back for this pipe.
295    //
296    tHCDPipeCallback pfnCallback;
297
298    //
299    // The pointer to which IN data must be copied.
300    //
301    uint8_t* pui8ReadPtr;
302
303    //
304    // The size of the buffer pointed to by pui8ReadPtr.
305    //
306    uint32_t ui32ReadSize;
307
308    //
309    // The number of bytes read, which can be less than ui32ReadSize.
310    //
311    uint32_t ui32DataRead;
312
313    //
314    // The state of a given USB pipe.
315    //
316    volatile enum {
317        ePipeReading,
318        ePipeReadDMA,
319        ePipeReadDMAWait,
320        ePipeReadSingle,
321        ePipeDataReady,
322        ePipeDataSent,
323        ePipeWriting,
324        ePipeWriteDMA,
325        ePipeWriteDMASend,
326        ePipeWriteDMAWait,
327        ePipeWriteSingle,
328        ePipeStalled,
329        ePipeError,
330        ePipeIdle,
331        ePipeDisabled
332    } iState;
333
334    //
335    // The actual FIFO offset allocated to this endpoint.
336    //
337    uint16_t ui16FIFOAddr;
338
339    //
340    // The size of the FIFO entry based on the size parameter.  These are
341    // equivalent to the USB_FIFO_SZ_* values in usb.h.
342    //
343    uint8_t ui8FIFOSize;
344
345    //
346    // The bit offset in the allocation structure.
347    //
348    uint8_t ui8FIFOBitOffset;
349} tUSBHCDPipe;
350
351//*****************************************************************************
352//
353// The internal state of the device.
354//
355//*****************************************************************************
356typedef enum {
357    eHCDDevDisconnected,
358    eHCDDevConnected,
359    eHCDDevConnectedHub,
360    eHCDDevRequest,
361    eHCDDevReset,
362    eHCDDevAddressed,
363    eHCDDevConfigured,
364    eHCDDevGetStrings,
365    eHCDDevError,
366    eHCDVBUSError,
367    eHCDPowerFault,
368    eHCDIdle
369} tUSBHDeviceState;
370
371static void ProcessUSBDeviceStateMachine(tUSBHDeviceState iOldState,
372                                         uint32_t ui32DevIndex);
373
374//*****************************************************************************
375//
376// This is a fixed number as it relates to the maximum number of USB pipes
377// available on any USB controller.  The actual number on a given device may
378// be less than this number.
379//
380//*****************************************************************************
381#define MAX_NUM_PIPES 15
382
383//*****************************************************************************
384//
385// This is a fixed number as it relates to the number of USB pipes available
386// in the USB controller.
387//
388//*****************************************************************************
389#define MAX_NUM_DMA_CHANNELS 6
390
391//*****************************************************************************
392//
393// Marker for an unused DMA channel slot.
394//
395//*****************************************************************************
396#define USBHCD_DMA_UNUSED 0xff
397
398//*****************************************************************************
399//
400// These definitions are used to manipulate the values returned as allocated
401// USB pipes.
402//
403//*****************************************************************************
404#define EP_PIPE_TYPE_LOW_SPEED 0x02000000
405#define EP_PIPE_USE_UDMA 0x01000000
406#define EP_PIPE_TYPE_ISOC 0x00800000
407#define EP_PIPE_TYPE_INTR 0x00400000
408#define EP_PIPE_TYPE_BULK 0x00200000
409#define EP_PIPE_TYPE_CONTROL 0x00100000
410#define EP_PIPE_TYPE_IN 0x00020000
411#define EP_PIPE_TYPE_OUT 0x00010000
412#define EP_PIPE_IDX_M 0x0000ffff
413
414//*****************************************************************************
415//
416// This creates a USB pipe handle from an index.
417//
418//*****************************************************************************
419#define OUT_PIPE_HANDLE(ui32Idx)                                               \
420    (g_sUSBHCD.psUSBOUTPipes[ui32Idx].ui32Type | ui32Idx)
421#define IN_PIPE_HANDLE(ui32Idx)                                                \
422    (g_sUSBHCD.psUSBINPipes[ui32Idx].ui32Type | ui32Idx)
423
424//*****************************************************************************
425//
426// Converts from an endpoint specifier to the offset of the endpoint's
427// control/status registers.
428//
429//*****************************************************************************
430#define EP_OFFSET(Endpoint) (Endpoint - 0x10)
431
432//*****************************************************************************
433//
434// This structure holds the state information for a given host controller.
435//
436//*****************************************************************************
437typedef struct {
438    uint32_t ui32USBBase;
439
440    tUSBHCDPipe sUSBControlPipe;
441    tUSBHCDPipe psUSBOUTPipes[MAX_NUM_PIPES];
442    tUSBHCDPipe psUSBINPipes[MAX_NUM_PIPES];
443
444    //
445    // Each devices state.  We support a total of (MAX_USB_DEVICES + 1) devices
446    // to allow for the use if MAX_USB_DEVICES through a single hub (which is
447    // itself a device).
448    //
449    tUSBHostDevice psUSBDevice[MAX_USB_DEVICES + 1];
450
451    //
452    // Holds the current state of the device.
453    //
454    volatile tUSBHDeviceState piDeviceState[MAX_USB_DEVICES + 1];
455
456    //
457    // Pointer to the memory pool for this controller.
458    //
459    void* pvPool;
460
461    //
462    // The pool size for this controller.
463    //
464    uint32_t ui32PoolSize;
465
466    //
467    // The number of endpoint pairs supported by the controller.
468    //
469    uint32_t ui32NumEndpoints;
470
471    //
472    // The class drivers for this controller.
473    //
474    const tUSBHostClassDriver* const* ppsClassDrivers;
475
476    //
477    // The number of class drivers.
478    //
479    uint32_t ui32NumClassDrivers;
480
481    //
482    // This is the index in the driver list of the event driver.
483    //
484    int32_t i32EventDriver;
485
486    //
487    // These are the generic event information used by the event driver.
488    //
489    uint32_t ui32EventEnables;
490
491    uint32_t ui32Class;
492
493    //
494    // The DMA instance information for this class.
495    //
496    tUSBDMAInstance* psDMAInstance;
497
498    //
499    // The interrupt number for this instance.
500    //
501    uint32_t ui32IntNum;
502
503    //
504    // The pending interrupt events that are processed in USBHCDMain().
505    //
506    uint32_t ui32IntEvents;
507
508    //
509    // Features.
510    //
511    uint32_t ui32Features;
512
513    //
514    // The host initiated resume duration in us.
515    //
516    uint32_t ui32LPMHIRD;
517} tUSBHCD;
518
519//*****************************************************************************
520//
521// The global to hold all of the state information for a given host controller.
522//
523//*****************************************************************************
524static tUSBHCD g_sUSBHCD;
525
526//*****************************************************************************
527//
528// Allocates the memory needed to support configuration descriptors for
529// devices.
530//
531//*****************************************************************************
532uint32_t ConfigDescAlloc(tUSBHostDevice* psDevice, uint32_t ui32Size) {
533    uint32_t ui32Idx, ui32BlockSize, ui32PoolSize;
534    uint8_t* pui8Pool;
535
536    if (g_sUSBHCD.psUSBDevice[0].psConfigDescriptor == 0) {
537        //
538        // 32 bit align the allocation.
539        //
540        ui32Size = (ui32Size + 3) & ~3;
541
542        if (g_sUSBHCD.ui32PoolSize < ui32Size) {
543            return (0);
544        }
545
546        //
547        // Allocate the root connection to the device.
548        //
549        g_sUSBHCD.psUSBDevice[0].psConfigDescriptor = g_sUSBHCD.pvPool;
550        g_sUSBHCD.psUSBDevice[0].ui32ConfigDescriptorSize = ui32Size;
551
552        //
553        // Allocate the hub memory pools (these can end up null).
554        //
555        pui8Pool = (uint8_t*)g_sUSBHCD.pvPool + ui32Size;
556        ui32PoolSize = g_sUSBHCD.ui32PoolSize - ui32Size;
557
558        //
559        // Divide the pool up into blocks, one for each supported port.  We make
560        // sure that each block is a multiple of 4 bytes.
561        //
562        ui32BlockSize = (ui32PoolSize / MAX_USB_DEVICES) & ~3;
563        for (ui32Idx = 1; ui32Idx < MAX_USB_DEVICES; ui32Idx++) {
564            g_sUSBHCD.psUSBDevice[ui32Idx].psConfigDescriptor =
565                (tConfigDescriptor*)(pui8Pool + (ui32Idx * ui32BlockSize));
566            g_sUSBHCD.psUSBDevice[ui32Idx].ui32ConfigDescriptorSize =
567                ui32BlockSize;
568        }
569    }
570    return (ui32Size);
571}
572
573//*****************************************************************************
574//
575// Frees the memory needed to support configuration descriptors for
576// devices.
577//
578//*****************************************************************************
579void ConfigDescFree(tUSBHostDevice* psDevice) {
580    uint32_t ui32Idx;
581
582    //
583    // If this is the root device then deallocate.
584    //
585    if (&g_sUSBHCD.psUSBDevice[0] == psDevice) {
586        for (ui32Idx = 0; ui32Idx < MAX_USB_DEVICES; ui32Idx++) {
587            g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags &= ~USBHDEV_FLAG_ALLOCATED;
588            g_sUSBHCD.psUSBDevice[ui32Idx].psConfigDescriptor = 0;
589            g_sUSBHCD.psUSBDevice[ui32Idx].ui32ConfigDescriptorSize = 0;
590        }
591    }
592}
593
594//*****************************************************************************
595//
596// Return the device index from a ui32Instance value passed from an external
597// source.
598//
599//*****************************************************************************
600static uint8_t HCDInstanceToDevIndex(uint32_t ui32Instance) {
601    uint32_t ui32DevIndex;
602
603    //
604    // Get the device instance from the instance value.
605    //
606    ui32DevIndex = (ui32Instance & 0xff);
607
608    //
609    // If the above math went negative or is too large just return 0xff.
610    //
611    if (ui32DevIndex > MAX_USB_DEVICES) {
612        ui32DevIndex = 0xff;
613    }
614
615    return (ui32DevIndex);
616}
617
618//=============================================================================
619//
620// This is the internal function that will map an event to a valid event flag.
621//
622// \param ui32Event specifies which event flag to retrieve.
623//
624// \return The event flag or 0 if there is no support event flag for the
625// event specified by the \e ui32Event parameter.
626//
627//=============================================================================
628static uint32_t GetEventFlag(uint32_t ui32Event) {
629    uint32_t ui32EventFlag;
630
631    ui32EventFlag = 0;
632
633    //
634    // Search for a valid event flag for the requested event.
635    //
636    switch (ui32Event) {
637    case USB_EVENT_SOF: {
638        ui32EventFlag |= USBHCD_EVFLAG_SOF;
639        break;
640    }
641    case USB_EVENT_CONNECTED: {
642        ui32EventFlag |= USBHCD_EVFLAG_CONNECT;
643        break;
644    }
645    case USB_EVENT_DISCONNECTED: {
646        ui32EventFlag |= USBHCD_EVFLAG_DISCNCT;
647        break;
648    }
649    case USB_EVENT_UNKNOWN_CONNECTED: {
650        ui32EventFlag |= USBHCD_EVFLAG_UNKCNCT;
651        break;
652    }
653    case USB_EVENT_POWER_FAULT: {
654        ui32EventFlag |= USBHCD_EVFLAG_PWRFAULT;
655        break;
656    }
657    case USB_EVENT_POWER_DISABLE: {
658        ui32EventFlag |= USBHCD_EVFLAG_PWRDIS;
659        break;
660    }
661    case USB_EVENT_POWER_ENABLE: {
662        ui32EventFlag |= USBHCD_EVFLAG_PWREN;
663        break;
664    }
665    default: {
666        break;
667    }
668    }
669    return (ui32EventFlag);
670}
671
672//=============================================================================
673//
674//! This function is called to enable a specific USB HCD event notification.
675//!
676//! \param ui32Index specifies which USB controller to use.
677//! \param pvEventDriver is the event driver structure that was passed into
678//! the USBHCDRegisterDrivers() function as part of the array of
679//! tUSBHostClassDriver structures.
680//! \param ui32Event is the event to enable.
681//!
682//! This function is called to enable event callbacks for a specific USB HCD
683//! event.  The requested event is passed in the \e ui32Event parameter.  Not
684//! all events can be enables so the function will return zero if the event
685//! provided cannot be enabled.  The \e pvEventDriver is a pointer to the
686//! event driver structure that the caller passed into the
687//! USBHCDRegisterDrivers() function.  This structure is typically declared
688//! with the DECLARE_EVENT_DRIVER() macro and included as part of the array
689//! of pointers to tUSBHostClassDriver structures that is passed to the
690//! USBHCDRegisterDrivers() function.
691//!
692//! \return This function returns a non-zero number if the event was
693//! successfully enabled and returns zero if the event cannot be enabled.
694//
695//=============================================================================
696int32_t USBHCDEventEnable(uint32_t ui32Index, void* pvEventDriver,
697                          uint32_t ui32Event) {
698    int32_t i32Ret;
699    uint32_t ui32EventFlag;
700
701    ASSERT(ui32Index == 0);
702
703    //
704    // Default the return to fail the call unless a valid event is found.
705    //
706    i32Ret = 0;
707
708    //
709    // Get the event flag for this event.
710    //
711    ui32EventFlag = GetEventFlag(ui32Event);
712
713    //
714    // Check if there was an event flag for the corresponding event.
715    //
716    if (ui32EventFlag) {
717        //
718        // Set the enable for this event.
719        //
720        g_sUSBHCD.ui32EventEnables |= ui32EventFlag;
721
722        //
723        // Indicate that the event was valid and is now enabled.
724        //
725        i32Ret = 1;
726    }
727
728    return (i32Ret);
729}
730
731//=============================================================================
732//
733//! This function is called to disable a specific USB HCD event notification.
734//!
735//! \param ui32Index specifies which USB controller to use.
736//! \param pvEventDriver is the event driver structure that was passed into
737//! the USBHCDRegisterDrivers() function as part of the array of
738//! tUSBHostClassDriver structures.
739//! \param ui32Event is the event to disable.
740//!
741//! This function is called to disable event callbacks for a specific USB HCD
742//! event.  The requested event is passed in the \e ui32Event parameter.  Not
743//! all events can be enables so the function will return zero if the event
744//! provided cannot be enabled.  The \e pvEventDriver is a pointer to the
745//! event driver structure that the caller passed into the
746//! USBHCDRegisterDrivers() function.  This structure is typically declared
747//! with the DECLARE_EVENT_DRIVER() macro and included as part of the array
748//! of pointers to tUSBHostClassDriver structures that is passed to the
749//! USBHCDRegisterDrivers() function.
750//!
751//! \return This function returns a non-zero number if the event was
752//! successfully disabled and returns zero if the event cannot be disabled.
753//
754//=============================================================================
755int32_t USBHCDEventDisable(uint32_t ui32Index, void* pvEventDriver,
756                           uint32_t ui32Event) {
757    int32_t i32Ret;
758    uint32_t ui32EventFlag;
759
760    ASSERT(ui32Index == 0);
761
762    //
763    // Default the return to fail the call unless a valid event is found.
764    //
765    i32Ret = 0;
766
767    //
768    // Get the event flag for this event.
769    //
770    ui32EventFlag = GetEventFlag(ui32Event);
771
772    //
773    // Check if there was an event flag for the corresponding event.
774    //
775    if (ui32EventFlag) {
776        //
777        // Clear the enable for this event.
778        //
779        g_sUSBHCD.ui32EventEnables &= ~ui32EventFlag;
780
781        //
782        // Indicate that the event was valid and is now disabled.
783        //
784        i32Ret = 1;
785    }
786
787    return (i32Ret);
788}
789
790//*****************************************************************************
791//
792// If there is an event driver this function will send out a generic connection
793// event USB_EVENT_UNKNOWN_CONNECTED indicating that an unknown connection
794// event has occurred.
795//
796//*****************************************************************************
797static void SendUnknownConnect(uint32_t ui32Index, uint32_t ui32Class) {
798    tEventInfo sEvent;
799
800    //
801    // If there is an event driver registered and it has a event handler and
802    // the USBHCD_EVFLAG_UNKCNCT is enabled then call the function.
803    //
804    sEvent.ui32Event = USB_EVENT_UNKNOWN_CONNECTED;
805    sEvent.ui32Instance = ui32Class;
806    InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_UNKCNCT);
807}
808
809//*****************************************************************************
810//
811// Internal memory allocation space is two 32-bit values where each
812// bit represents a 64 byte block in the FIFO.  This requires 64 bits for
813// the 4096 bytes of FIFO available.
814//
815//*****************************************************************************
816static uint32_t g_pui32Alloc[2];
817
818//*****************************************************************************
819//
820// This function handles freeing FIFO memory that has been allocated using the
821// FIFOAlloc() function.
822//
823//*****************************************************************************
824static void FIFOFree(tUSBHCDPipe* psUSBPipe) {
825    uint32_t ui32Mask;
826
827    //
828    // Calculate the mask value to use to clear off the allocated blocks used
829    // by the USB pipe specified by psUSBPipe.
830    //
831    ui32Mask = (1 << (psUSBPipe->ui8FIFOSize - 2)) - 1;
832    ui32Mask = ui32Mask << psUSBPipe->ui8FIFOBitOffset;
833
834    //
835    // Determine which 32 bit word to access based on the size.
836    //
837    if (psUSBPipe->ui8FIFOSize > USB_FIFO_SZ_64) {
838        //
839        // If the FIFO size is greater than 64 then use the upper 32 bits.
840        //
841        g_pui32Alloc[1] &= ~ui32Mask;
842    } else {
843        //
844        // If the FIFO size is less than or equal to 64 then use the lower
845        // 32 bits.
846        //
847        g_pui32Alloc[0] &= ~ui32Mask;
848    }
849}
850
851//*****************************************************************************
852//
853// This function is used to allocate FIFO memory to a given USB pipe.
854//
855// \param psUSBPipe is the USB pipe that needs FIFO memory allocated.
856// \param ui32Size is the minimum size in bytes of the FIFO to allocate.
857//
858// This function will allocate \e ui32Size bytes to the USB pipe in the
859// \e psUSBPipe parameter.  The function will fill the psUSBPipe structure
860// members ui8FIFOSize and ui8FIFOAddr with values that can be used with the
861// USBFIFOConfigSet() API.  This allocation uses a first fit algorithm.
862//
863// \return This function returns the size of the block allocated.
864//
865//*****************************************************************************
866static uint32_t FIFOAlloc(tUSBHCDPipe* psUSBPipe, uint32_t ui32Size) {
867    uint32_t ui32Blocks, ui32Start, ui32BlockSize, ui32Temp, ui32Index;
868    uint16_t ui16FIFOAddr;
869
870    //
871    // Save which 32 bit value to access, the upper is for blocks greater
872    // than 64 and the lower is for block 64 or less.
873    //
874    if (ui32Size > 64) {
875        ui32Index = 1;
876    } else {
877        ui32Index = 0;
878    }
879
880    //
881    // Initial FIFO address is 0.
882    //
883    ui16FIFOAddr = 0;
884
885    //
886    // Initialize the bit pattern and bit location.
887    //
888    ui32Blocks = 1;
889    ui32Start = 0;
890
891    //
892    // The initial block size is always the minimum size of 64 bytes.
893    //
894    ui32BlockSize = 64;
895
896    //
897    // The initial size and offset are 64 and 0.
898    //
899    psUSBPipe->ui8FIFOBitOffset = 0;
900    psUSBPipe->ui8FIFOSize = 3;
901
902    //
903    // Scan through 32 bits looking for a memory block large enough to fill
904    // the request.
905    //
906    while (ui16FIFOAddr <= 32) {
907        //
908        // If the pattern is zero then it is a possible match.
909        //
910        if ((g_pui32Alloc[ui32Index] & ui32Blocks) == 0) {
911            //
912            // If the size is large enough then save it and break out of the
913            // loop.
914            //
915            if (ui32BlockSize >= ui32Size) {
916                //
917                // Mark the memory as allocated.
918                //
919                g_pui32Alloc[ui32Index] |= ui32Blocks;
920
921                break;
922            }
923
924            //
925            // Increment the size of the FIFO block.
926            //
927            psUSBPipe->ui8FIFOSize++;
928
929            //
930            // Add in a new bit to the size of the allocation.
931            //
932            ui32Blocks = ui32Blocks | (ui32Blocks << 1);
933
934            //
935            // Double the current size.
936            //
937            ui32BlockSize <<= 1;
938
939        } else {
940            //
941            // Need to start over looking because the last allocation match
942            // failed, so reset the bit offset to the current location and the
943            // size to 64 bytes.
944            //
945            psUSBPipe->ui8FIFOBitOffset = ui16FIFOAddr;
946            psUSBPipe->ui8FIFOSize = 3;
947
948            //
949            // Reset the block size to the minimum (64 bytes).
950            //
951            ui32BlockSize = 64;
952
953            //
954            // Store the current starting bit location and set the block mask
955            // to this value.
956            //
957            ui32Start = 1 << ui16FIFOAddr;
958            ui32Blocks = ui32Start;
959        }
960
961        //
962        // Increase the address of the FIFO offset.
963        //
964        ui16FIFOAddr++;
965    }
966
967    //
968    // If there was no block large enough then fail this call.
969    //
970    if (ui16FIFOAddr > 32) {
971        ui32BlockSize = 0;
972        psUSBPipe->ui16FIFOAddr = 0;
973        psUSBPipe->ui8FIFOBitOffset = 0;
974        psUSBPipe->ui8FIFOSize = 0;
975    } else {
976        //
977        // Calculate the offset in the FIFO.
978        //
979        ui32Temp = psUSBPipe->ui8FIFOBitOffset * 64;
980
981        //
982        // Sizes greater than 64 are allocated in the second half of the FIFO
983        // memory space.
984        //
985        if (ui32Size > 64) {
986            ui32Temp += 2048;
987        }
988
989        //
990        // Convert this to the value that can be set in the USB controller.
991        //
992        psUSBPipe->ui16FIFOAddr = (uint16_t)ui32Temp;
993    }
994    return (ui32BlockSize);
995}
996
997//*****************************************************************************
998//
999//! This function returns the current byte count of a USB HCD pipe.
1000//!
1001//! \param ui32Pipe is the allocated endpoint to modify.
1002//!
1003//! This call returns the current or last byte count for a transfer using the
1004//! pipe specified by the \e ui32Pipe parameter.  This is typically used to
1005//! determine the actual byte count received when a \b USB_EVENT_RX_AVAILABLE
1006//! occurs.
1007//!
1008//! \return If the call was successful, this function returns the number of
1009//! bytes transfered by the USB pipe.
1010//
1011//*****************************************************************************
1012uint32_t USBHCDPipeTransferSizeGet(uint32_t ui32Pipe) {
1013    uint32_t ui32Index;
1014
1015    //
1016    // Get the index number from the allocated pipe.
1017    //
1018    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);
1019
1020    return (g_sUSBHCD.psUSBINPipes[ui32Index].ui32DataRead);
1021}
1022
1023//*****************************************************************************
1024//
1025//! This function is used to allocate a USB HCD pipe.
1026//!
1027//! \param ui32Index specifies which USB controller to use.
1028//! \param ui32EndpointType is the type of endpoint that this pipe will be
1029//! communicating with.
1030//! \param psDevice is the device instance associated with this endpoint.
1031//! \param ui32Size is the size of the FIFO in bytes.
1032//! \param pfnCallback is the function that will be called when events occur on
1033//! this USB Pipe.
1034//!
1035//! Since there are a limited number of USB HCD pipes that can be used in the
1036//! host controller, this function is used to temporarily or permanently
1037//! acquire one of the endpoints.  Unlike the USBHCDPipeAlloc() function this
1038//! function allows the caller to specify the size of the FIFO allocated to
1039//! this endpoint in the \e ui32Size parameter.  This function also provides a
1040//! method to register a callback for status changes on this endpoint.  If no
1041//! callbacks are desired then the \e pfnCallback function should be set to 0.
1042//! The callback should be used when using the USBHCDPipeSchedule() function
1043//! so that the caller is notified when the action is complete.
1044//!
1045//! \return This function returns a value indicating which pipe was reserved.
1046//! If the value is 0 then there were no pipes currently available.  This value
1047//! should be passed to any USBHCDPipe APIs to indicate which pipe is being
1048//! accessed.
1049//
1050//*****************************************************************************
1051uint32_t USBHCDPipeAllocSize(uint32_t ui32Index, uint32_t ui32EndpointType,
1052                             tUSBHostDevice* psDevice, uint32_t ui32Size,
1053                             tHCDPipeCallback pfnCallback) {
1054    int32_t i32Idx;
1055
1056    uint32_t ui32HubAddr;
1057
1058    ASSERT(ui32Index == 0);
1059
1060    //
1061    // Find a USB pipe that is free.
1062    //
1063    for (i32Idx = 0; i32Idx < MAX_NUM_PIPES; i32Idx++) {
1064        //
1065        // Handle OUT Pipes.
1066        //
1067        if (ui32EndpointType & EP_PIPE_TYPE_OUT) {
1068            //
1069            // A zero address indicates free.
1070            //
1071            if (g_sUSBHCD.psUSBOUTPipes[i32Idx].psDevice == 0) {
1072                //
1073                // Set up uDMA for the pipe.
1074                //
1075                if (ui32EndpointType & EP_PIPE_USE_UDMA) {
1076                    //
1077                    // Allocate a DMA channel to the endpoint.
1078                    //
1079                    g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8DMAChannel =
1080                        USBLibDMAChannelAllocate(
1081                            g_sUSBHCD.psDMAInstance, IndexToUSBEP(i32Idx + 1),
1082                            ui32Size, USB_DMA_EP_TX | USB_DMA_EP_HOST);
1083
1084                    //
1085                    // If no DMA channel was available then just disable DMA
1086                    // on this pipe.
1087                    //
1088                    if (g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8DMAChannel == 0) {
1089                        ui32EndpointType &= ~EP_PIPE_USE_UDMA;
1090                    }
1091                }
1092
1093                //
1094                // Save the endpoint type and device address and callback
1095                // function.
1096                //
1097                g_sUSBHCD.psUSBOUTPipes[i32Idx].ui32Type = ui32EndpointType;
1098                g_sUSBHCD.psUSBOUTPipes[i32Idx].psDevice = psDevice;
1099                g_sUSBHCD.psUSBOUTPipes[i32Idx].pfnCallback = pfnCallback;
1100
1101                //
1102                // Clear out any pending status on this endpoint in case it
1103                // was in use before a allowing a new device class to use it.
1104                //
1105                MAP_USBHostEndpointStatusClear(
1106                    USB0_BASE, IndexToUSBEP(i32Idx + 1), USB_HOST_OUT_STATUS);
1107
1108                //
1109                // Make sure to reset the data toggle.
1110                //
1111                USBEndpointDataToggleClear(USB0_BASE, IndexToUSBEP(i32Idx + 1),
1112                                           USB_EP_HOST_OUT);
1113
1114                //
1115                // Initialize the endpoint as idle.
1116                //
1117                g_sUSBHCD.psUSBOUTPipes[i32Idx].iState = ePipeIdle;
1118
1119                //
1120                // Allocate space in the FIFO for this endpoint.
1121                //
1122                if (FIFOAlloc(&g_sUSBHCD.psUSBOUTPipes[i32Idx], ui32Size) !=
1123                    0) {
1124                    //
1125                    // Configure the FIFO.
1126                    //
1127                    MAP_USBFIFOConfigSet(
1128                        USB0_BASE, IndexToUSBEP(i32Idx + 1),
1129                        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui16FIFOAddr,
1130                        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8FIFOSize,
1131                        USB_EP_HOST_OUT);
1132                }
1133
1134                //
1135                // Set the function address for this endpoint.
1136                //
1137                MAP_USBHostAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
1138                                   psDevice->ui32Address, USB_EP_HOST_OUT);
1139
1140                //
1141                // Set the hub and port address for the endpoint.
1142                //
1143                ui32HubAddr = psDevice->ui8Hub | (psDevice->ui8HubPort << 8);
1144                USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
1145                                  ui32HubAddr,
1146                                  (USB_EP_HOST_OUT | psDevice->ui32Speed));
1147                break;
1148            }
1149        }
1150        //
1151        // Handle IN Pipes.
1152        //
1153        else if (ui32EndpointType & EP_PIPE_TYPE_IN) {
1154            //
1155            // A zero address indicates free.
1156            //
1157            if (g_sUSBHCD.psUSBINPipes[i32Idx].psDevice == 0) {
1158                //
1159                // Set up uDMA for the pipe.
1160                //
1161                if (ui32EndpointType & EP_PIPE_USE_UDMA) {
1162                    //
1163                    // Allocate a DMA channel to the endpoint.
1164                    //
1165                    g_sUSBHCD.psUSBINPipes[i32Idx].ui8DMAChannel =
1166                        USBLibDMAChannelAllocate(
1167                            g_sUSBHCD.psDMAInstance, IndexToUSBEP(i32Idx + 1),
1168                            ui32Size, USB_DMA_EP_RX | USB_DMA_EP_HOST);
1169
1170                    //
1171                    // If no DMA channel was available then just disable DMA
1172                    // on this pipe.
1173                    //
1174                    if (g_sUSBHCD.psUSBINPipes[i32Idx].ui8DMAChannel == 0) {
1175                        ui32EndpointType &= ~EP_PIPE_USE_UDMA;
1176                    }
1177                }
1178
1179                //
1180                // Save the endpoint type and device address and callback
1181                // function.
1182                //
1183                g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type = ui32EndpointType;
1184                g_sUSBHCD.psUSBINPipes[i32Idx].psDevice = psDevice;
1185                g_sUSBHCD.psUSBINPipes[i32Idx].pfnCallback = pfnCallback;
1186
1187                //
1188                // Clear out any pending status on this endpoint in case it
1189                // was in use before a allowing a new device class to use it.
1190                //
1191                MAP_USBHostEndpointStatusClear(
1192                    USB0_BASE, IndexToUSBEP(i32Idx + 1), USB_HOST_IN_STATUS);
1193
1194                //
1195                // Make sure to reset the data toggle.
1196                //
1197                USBEndpointDataToggleClear(USB0_BASE, IndexToUSBEP(i32Idx + 1),
1198                                           USB_EP_HOST_IN);
1199
1200                //
1201                // Allocate space in the FIFO for this endpoint.
1202                //
1203                if (FIFOAlloc(&g_sUSBHCD.psUSBINPipes[i32Idx], ui32Size) != 0) {
1204                    //
1205                    // Configure the FIFO.
1206                    //
1207                    MAP_USBFIFOConfigSet(
1208                        USB0_BASE, IndexToUSBEP(i32Idx + 1),
1209                        g_sUSBHCD.psUSBINPipes[i32Idx].ui16FIFOAddr,
1210                        g_sUSBHCD.psUSBINPipes[i32Idx].ui8FIFOSize,
1211                        USB_EP_HOST_IN);
1212                }
1213
1214                //
1215                // Set the function address for this endpoint.
1216                //
1217                MAP_USBHostAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
1218                                   psDevice->ui32Address, USB_EP_HOST_IN);
1219
1220                //
1221                // Set the hub and port address for the endpoint.
1222                //
1223                ui32HubAddr = psDevice->ui8Hub | (psDevice->ui8HubPort << 8);
1224                USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
1225                                  ui32HubAddr,
1226                                  (USB_EP_HOST_IN | psDevice->ui32Speed));
1227
1228                //
1229                // Reset the state of the pipe to idle.
1230                //
1231                g_sUSBHCD.psUSBINPipes[i32Idx].iState = ePipeIdle;
1232
1233                break;
1234            }
1235        }
1236    }
1237
1238    //
1239    // Did not find a free pipe.
1240    //
1241    if (i32Idx == MAX_NUM_PIPES) {
1242        return (0);
1243    }
1244
1245    //
1246    // Return the pipe index and type that was allocated.
1247    //
1248    return (ui32EndpointType | i32Idx);
1249}
1250
1251//*****************************************************************************
1252//
1253//! This function is used to allocate a USB HCD pipe.
1254//!
1255//! \param ui32Index specifies which USB controller to use.
1256//! \param ui32EndpointType is the type of endpoint that this pipe will be
1257//! communicating with.
1258//! \param psDevice is the device instance associated with this endpoint.
1259//! \param pfnCallback is the function that will be called when events occur on
1260//! this USB Pipe.
1261//!
1262//! Since there are a limited number of USB HCD pipes that can be used in the
1263//! host controller, this function is used to temporarily or permanently
1264//! acquire one of the endpoints.  It also provides a method to register a
1265//! callback for status changes on this endpoint.  If no callbacks are desired
1266//! then the \e pfnCallback function should be set to 0.  The callback should
1267//! be used when using the USBHCDPipeSchedule() function so that the caller is
1268//! notified when the action is complete.
1269//!
1270//! \return This function returns a value indicating which pipe was reserved.
1271//! If the value is 0 then there were no pipes currently available.  This value
1272//! should be passed to any USBHCDPipe APIs to indicate which pipe is being
1273//! accessed.
1274//
1275//*****************************************************************************
1276uint32_t USBHCDPipeAlloc(uint32_t ui32Index, uint32_t ui32EndpointType,
1277                         tUSBHostDevice* psDevice,
1278                         tHCDPipeCallback pfnCallback) {
1279    //
1280    // The old API allocated only 64 bytes to each endpoint.
1281    //
1282    return (USBHCDPipeAllocSize(ui32Index, ui32EndpointType, psDevice, 64,
1283                                pfnCallback));
1284}
1285
1286//*****************************************************************************
1287//
1288//! This function is used to configure a USB HCD pipe.
1289//!
1290//! This should be called after allocating a USB pipe with a call to
1291//! USBHCDPipeAlloc().  It is used to set the configuration associated with an
1292//! endpoint like the max payload and target endpoint.  The \e ui32MaxPayload
1293//! parameter is typically read directly from the devices endpoint descriptor
1294//! and is expressed in bytes.
1295//!
1296//! Setting the \e ui32Interval parameter depends on the type of endpoint being
1297//! configured.  For endpoints that do not need to use the \e ui32Interval
1298//! parameter \e ui32Interval should be set to 0.  For Bulk \e ui32Interval is
1299//! a value from 2-16 and will set the NAK timeout value as
1300//! 2^(\e ui32Interval-1) frames.  For interrupt endpoints \e ui32Interval is a
1301//! value from 1-255 and is the count in frames between polling the endpoint.
1302//! For isochronous endpoints \e ui32Interval ranges from 1-16 and is the
1303//! polling interval in frames represented as 2^(\e ui32Interval-1) frames.
1304//!
1305//! \param ui32Pipe is the allocated endpoint to modify.
1306//! \param ui32MaxPayload is maximum data that can be handled per transaction.
1307//! \param ui32Interval is the polling interval for data transfers expressed in
1308//! frames.
1309//! \param ui32TargetEndpoint is the target endpoint on the device to
1310//! communicate with.
1311//!
1312//! \return If the call was successful, this function returns zero any other
1313//! value indicates an error.
1314//
1315//*****************************************************************************
1316uint32_t USBHCDPipeConfig(uint32_t ui32Pipe, uint32_t ui32MaxPayload,
1317                          uint32_t ui32Interval, uint32_t ui32TargetEndpoint) {
1318    uint32_t ui32Flags;
1319    uint32_t ui32Index;
1320
1321    //
1322    // Get the index number from the allocated pipe.
1323    //
1324    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);
1325
1326    //
1327    // Set the direction.
1328    //
1329    if (ui32Pipe & EP_PIPE_TYPE_OUT) {
1330        //
1331        // Set the mode for this endpoint.
1332        //
1333        if (g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type & EP_PIPE_TYPE_BULK) {
1334            ui32Flags = USB_EP_MODE_BULK;
1335        } else if (g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type &
1336                   EP_PIPE_TYPE_INTR) {
1337            ui32Flags = USB_EP_MODE_INT;
1338        } else if (g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type &
1339                   EP_PIPE_TYPE_ISOC) {
1340            ui32Flags = USB_EP_MODE_ISOC;
1341        } else {
1342            ui32Flags = USB_EP_MODE_CTRL;
1343        }
1344
1345        ui32Flags |= USB_EP_HOST_OUT;
1346
1347        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8EPNumber =
1348            (uint8_t)ui32TargetEndpoint;
1349
1350        //
1351        // Save the interval and the next tick to trigger a scheduler event.
1352        //
1353        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Interval = ui32Interval;
1354        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32NextEventTick =
1355            ui32Interval + g_ui32CurrentTick;
1356
1357        //
1358        // Set the device speed.
1359        //
1360        ui32Flags |= (g_sUSBHCD.psUSBOUTPipes[ui32Index].psDevice->ui32Speed);
1361
1362        //
1363        // Set up the appropriate flags if uDMA is used.
1364        //
1365        if (ui32Pipe & EP_PIPE_USE_UDMA) {
1366            ui32Flags |= USB_EP_DMA_MODE_0 | USB_EP_AUTO_SET;
1367        }
1368    } else {
1369        //
1370        // Set the mode for this endpoint.
1371        //
1372        if (g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type & EP_PIPE_TYPE_BULK) {
1373            ui32Flags = USB_EP_MODE_BULK;
1374        } else if (g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type &
1375                   EP_PIPE_TYPE_INTR) {
1376            ui32Flags = USB_EP_MODE_INT;
1377        } else if (g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type &
1378                   EP_PIPE_TYPE_ISOC) {
1379            ui32Flags = USB_EP_MODE_ISOC;
1380        } else {
1381            ui32Flags = USB_EP_MODE_CTRL;
1382        }
1383        ui32Flags |= USB_EP_HOST_IN;
1384
1385        g_sUSBHCD.psUSBINPipes[ui32Index].ui8EPNumber =
1386            (uint8_t)ui32TargetEndpoint;
1387
1388        //
1389        // Save the interval and the next tick to trigger a scheduler event.
1390        //
1391        g_sUSBHCD.psUSBINPipes[ui32Index].ui32Interval = ui32Interval;
1392        g_sUSBHCD.psUSBINPipes[ui32Index].ui32NextEventTick =
1393            ui32Interval + g_ui32CurrentTick;
1394
1395        //
1396        // Set the device speed.
1397        //
1398        ui32Flags |= g_sUSBHCD.psUSBINPipes[ui32Index].psDevice->ui32Speed;
1399        //
1400        // Set up the appropriate flags if uDMA is used.
1401        //
1402        if (ui32Pipe & EP_PIPE_USE_UDMA) {
1403            ui32Flags |=
1404                USB_EP_DMA_MODE_1 | USB_EP_AUTO_CLEAR | USB_EP_AUTO_REQUEST;
1405        }
1406    }
1407
1408    //
1409    // Configure the endpoint according to the flags determined above.
1410    //
1411    USBHostEndpointConfig(
1412        USB0_BASE, IndexToUSBEP((ui32Pipe & EP_PIPE_IDX_M) + 1), ui32MaxPayload,
1413        ui32Interval, ui32TargetEndpoint, ui32Flags);
1414
1415    return (0);
1416}
1417
1418//*****************************************************************************
1419//
1420//! This function is used to return the current status of a USB HCD pipe.
1421//!
1422//! This function will return the current status for a given USB pipe.  If
1423//! there is no status to report this call will simply return
1424//! \b USBHCD_PIPE_NO_CHANGE.
1425//!
1426//! \param ui32Pipe is the USB pipe for this status request.
1427//!
1428//! \return This function returns the current status for the given endpoint.
1429//! This will be one of the \b USBHCD_PIPE_* values.
1430//
1431//*****************************************************************************
1432uint32_t USBHCDPipeStatus(uint32_t ui32Pipe) {
1433    return (0);
1434}
1435
1436//*****************************************************************************
1437//
1438//! This function is used to write data to a USB HCD pipe.
1439//!
1440//! \param ui32Pipe is the USB pipe to put data into.
1441//! \param pui8Data is a pointer to the data to send.
1442//! \param ui32Size is the amount of data to send.
1443//!
1444//! This function will block until it has sent as much data as was
1445//! requested using the USB pipe's FIFO.  The caller should have registered a
1446//! callback with the USBHCDPipeAlloc() call in order to be informed when the
1447//! data has been transmitted.  The value returned by this function can be less
1448//! than the \e ui32Size requested if the USB pipe has less space available
1449//! than this request is making.
1450//!
1451//! \return This function returns the number of bytes that were scheduled to
1452//! be sent on the given USB pipe.
1453//
1454//*****************************************************************************
1455uint32_t USBHCDPipeWrite(uint32_t ui32Pipe, uint8_t* pui8Data,
1456                         uint32_t ui32Size) {
1457    uint32_t ui32Endpoint, ui32RemainingBytes, ui32ByteToSend, ui32PipeIdx;
1458    bool bUseDMA;
1459
1460    //
1461    // Determine which endpoint interface that this pipe is using.
1462    //
1463    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);
1464
1465    //
1466    // Get index used for looking up pipe data
1467    //
1468    ui32PipeIdx = ui32Pipe & EP_PIPE_IDX_M;
1469
1470    //
1471    // Set the total number of bytes to send out.
1472    //
1473    ui32RemainingBytes = ui32Size;
1474
1475    //
1476    // Default to using DMA.
1477    //
1478    bUseDMA = false;
1479
1480    //
1481    // Initialize the bytes to send to all of the remaining bytes.
1482    //
1483    ui32ByteToSend = ui32RemainingBytes;
1484
1485    //
1486    // Send all of the requested data.
1487    //
1488    while (ui32RemainingBytes != 0) {
1489        //
1490        // If uDMA is not enabled for this pipe, or if the uDMA workaround
1491        // is applied, then don't use uDMA for this transfer.
1492        //
1493        if (ui32Pipe & EP_PIPE_USE_UDMA) {
1494            //
1495            // Disable the USB interrupt.
1496            //
1497            OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
1498
1499            //
1500            // Start the DMA transfer.
1501            //
1502            if (USBLibDMATransfer(
1503                    g_sUSBHCD.psDMAInstance,
1504                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].ui8DMAChannel,
1505                    pui8Data, ui32RemainingBytes) != 0) {
1506                if (ui32RemainingBytes < 64) {
1507                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState =
1508                        ePipeWriteDMASend;
1509                } else if ((ui32RemainingBytes % 64) == 0) {
1510                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeWriteDMA;
1511                } else {
1512                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState =
1513                        ePipeWriteDMASend;
1514                }
1515
1516                bUseDMA = true;
1517            }
1518
1519            //
1520            // Enable the USB interrupt.
1521            //
1522            OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
1523        }
1524
1525        if (bUseDMA == false) {
1526            //
1527            // Only send 64 bytes at a time if not using DMA.
1528            //
1529            if (ui32ByteToSend > 64) {
1530                ui32ByteToSend = 64;
1531            } else {
1532                //
1533                // Send the requested number of bytes.
1534                //
1535                ui32ByteToSend = ui32RemainingBytes;
1536            }
1537
1538            //
1539            // Start a write request.
1540            //
1541            g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeWriting;
1542
1543            //
1544            // Disable uDMA on the USB endpoint
1545            //
1546            MAP_USBEndpointDMADisable(USB0_BASE, ui32Endpoint, USB_EP_HOST_OUT);
1547
1548            //
1549            // Put the data in the buffer.
1550            //
1551            MAP_USBEndpointDataPut(USB0_BASE, ui32Endpoint, pui8Data,
1552                                   ui32ByteToSend);
1553
1554            //
1555            // Schedule the data to be sent.
1556            //
1557            MAP_USBEndpointDataSend(USB0_BASE, ui32Endpoint, USB_TRANS_OUT);
1558        }
1559
1560        //
1561        // Wait for a status change.
1562        //
1563        while (1) {
1564            //
1565            // If an error event occurs then exit out of the loop.
1566            //
1567            if (g_sUSBHCD.ui32IntEvents &
1568                (INT_EVENT_DISCONNECT | INT_EVENT_VBUS_ERR |
1569                 INT_EVENT_POWER_FAULT)) {
1570                //
1571                // Set the pipe state to error.
1572                //
1573                g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeError;
1574
1575                //
1576                // Needs to be set to exit out of large while loop.
1577                //
1578                ui32RemainingBytes = 0;
1579
1580                break;
1581            }
1582            //
1583            // If the data was successfully sent then decrement the count and
1584            // continue.
1585            //
1586            else if (g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState ==
1587                     ePipeDataSent) {
1588                //
1589                // Decrement the remaining data and advance the pointer.
1590                //
1591                ui32RemainingBytes -= ui32ByteToSend;
1592                pui8Data += ui32ByteToSend;
1593
1594                //
1595                // If there are less than 64 bytes to send then this is the
1596                // last of the data to go out.
1597                //
1598                if (ui32RemainingBytes < 64) {
1599                    ui32ByteToSend = ui32RemainingBytes;
1600                }
1601                break;
1602            } else if (g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState ==
1603                       ePipeStalled) {
1604                //
1605                // Zero out the size so that the caller knows that no data was
1606                // written.
1607                //
1608                ui32Size = 0;
1609
1610                //
1611                // Needs to be set to exit out of large while loop.
1612                //
1613                ui32RemainingBytes = 0;
1614
1615                //
1616                // If DMA is being used, then disable the channel.
1617                //
1618                if (bUseDMA == true) {
1619                    //
1620                    // Disable the DMA channel.
1621                    //
1622                    USBLibDMAChannelDisable(
1623                        g_sUSBHCD.psDMAInstance,
1624                        g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].ui8DMAChannel);
1625                }
1626
1627                //
1628                // This is the actual endpoint number.
1629                //
1630                USBHCDClearFeature(
1631                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].psDevice->ui32Address,
1632                    ui32Pipe, USB_FEATURE_EP_HALT);
1633
1634                //
1635                // If there was a stall, then no more data is coming so break
1636                // out.
1637                //
1638                break;
1639            } else if (g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState ==
1640                       ePipeError) {
1641                //
1642                // An error occurred so stop this transaction and set the
1643                // number of bytes to zero.
1644                //
1645                ui32Size = 0;
1646
1647                //
1648                // Needs to be set to exit out of large while loop.
1649                //
1650                ui32RemainingBytes = 0;
1651
1652                break;
1653            }
1654        }
1655    }
1656
1657    //
1658    // Go Idle once this state has been reached.
1659    //
1660    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeIdle;
1661
1662    return (ui32Size);
1663}
1664
1665//*****************************************************************************
1666//
1667//! This function is used to schedule and IN transaction on a USB HCD pipe.
1668//!
1669//! \param ui32Pipe is the USB pipe to read data from.
1670//! \param pui8Data is a pointer to store the data that is received.
1671//! \param ui32Size is the size in bytes of the buffer pointed to by
1672//! \e pui8Data.
1673//!
1674//! This function will not block depending on the type of pipe passed in will
1675//! schedule either a send of data to the device or a read of data from the
1676//! device.  In either case the amount of data will be limited to what will
1677//! fit in the FIFO for a given endpoint.
1678//!
1679//! \return This function returns the number of bytes that were sent in the
1680//! case of a transfer of data or it will return 0 for a request on a USB IN
1681//! pipe.
1682//
1683//*****************************************************************************
1684uint32_t USBHCDPipeSchedule(uint32_t ui32Pipe, uint8_t* pui8Data,
1685                            uint32_t ui32Size) {
1686    uint32_t ui32Endpoint, ui32PipeIdx;
1687
1688    //
1689    // Get index used for looking up pipe data
1690    //
1691    ui32PipeIdx = ui32Pipe & EP_PIPE_IDX_M;
1692
1693    //
1694    // Determine which endpoint interface that this pipe is using.
1695    //
1696    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);
1697
1698    if (ui32Pipe & EP_PIPE_TYPE_OUT) {
1699        //
1700        // Check if uDMA is enabled on this pipe.
1701        //
1702        if (ui32Pipe & EP_PIPE_USE_UDMA) {
1703            //
1704            // Start a write request.
1705            //
1706            g_sUSBHCD.psUSBOUTPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
1707                ePipeWriteDMASend;
1708
1709            USBLibDMATransfer(
1710                g_sUSBHCD.psDMAInstance,
1711                g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].ui8DMAChannel, pui8Data,
1712                ui32Size);
1713        } else {
1714            //
1715            // Start a write request.
1716            //
1717            g_sUSBHCD.psUSBOUTPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
1718                ePipeWriting;
1719
1720            //
1721            // Put the data in the buffer.
1722            //
1723            MAP_USBEndpointDataPut(USB0_BASE, ui32Endpoint, pui8Data, ui32Size);
1724
1725            //
1726            // Schedule the data to be sent.
1727            //
1728            MAP_USBEndpointDataSend(USB0_BASE, ui32Endpoint, USB_TRANS_OUT);
1729        }
1730    } else {
1731        //
1732        // If uDMA is not enabled for this pipe, or if the uDMA workaround
1733        // is applied, then do not use uDMA for this transfer.
1734        //
1735        if ((ui32Pipe & EP_PIPE_USE_UDMA) == 0) {
1736            //
1737            // Start a read request.
1738            //
1739            g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
1740                ePipeReading;
1741
1742            //
1743            // Disable uDMA on the endpoint
1744            //
1745            MAP_USBEndpointDMADisable(USB0_BASE, ui32Endpoint, USB_EP_HOST_IN);
1746        }
1747        //
1748        // Otherwise, uDMA should be used for this transfer, so set up
1749        // the uDMA channel in advance of triggering the IN request.
1750        //
1751        else {
1752            g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
1753                ePipeReadDMA;
1754
1755            USBLibDMATransfer(g_sUSBHCD.psDMAInstance,
1756                              g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel,
1757                              pui8Data, ui32Size);
1758        }
1759
1760        //
1761        // Remember details of the buffer into which the data will be read.
1762        //
1763        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].pui8ReadPtr = pui8Data;
1764        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui32ReadSize = ui32Size;
1765
1766        //
1767        // Trigger a request for data from the device.
1768        //
1769        MAP_USBHostRequestIN(USB0_BASE, ui32Endpoint);
1770
1771        //
1772        // No data was put into or read from the buffer.
1773        //
1774        ui32Size = 0;
1775    }
1776    return (ui32Size);
1777}
1778
1779//*****************************************************************************
1780//
1781//! This function is used to read data from a USB HCD pipe.
1782//!
1783//! \param ui32Pipe is the USB pipe to read data from.
1784//! \param pui8Data is a pointer to store the data that is received.
1785//! \param ui32Size is the size in bytes of the buffer pointed to by
1786//! \e pui8Data.
1787//!
1788//! This function will not block and will only read as much data as requested
1789//! or as much data is currently available from the USB pipe.  The caller
1790//! should have registered a callback with the USBHCDPipeAlloc() call in order
1791//! to be informed when the data has been received.  The value returned by this
1792//! function can be less than the \e ui32Size requested if the USB pipe has
1793//! less data available than was requested.
1794//!
1795//! \return This function returns the number of bytes that were returned in the
1796//! \e pui8Data buffer.
1797//
1798//*****************************************************************************
1799uint32_t USBHCDPipeReadNonBlocking(uint32_t ui32Pipe, uint8_t* pui8Data,
1800                                   uint32_t ui32Size) {
1801    uint32_t ui32Endpoint;
1802
1803    //
1804    // Determine which endpoint interface that this pipe is using.
1805    //
1806    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);
1807
1808    //
1809    // Read the data out of the USB endpoint interface.
1810    //
1811    MAP_USBEndpointDataGet(USB0_BASE, ui32Endpoint, pui8Data, &ui32Size);
1812
1813    //
1814    // Acknowledge that the data was read from the endpoint.
1815    //
1816    MAP_USBHostEndpointDataAck(USB0_BASE, ui32Endpoint);
1817
1818    //
1819    // Go Idle once this state has been reached.
1820    //
1821    g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState = ePipeIdle;
1822
1823    return (ui32Size);
1824}
1825
1826//*****************************************************************************
1827//
1828//! This function acknowledges data received via an interrupt IN pipe.
1829//!
1830//! \param ui32Pipe is the USB INT pipe whose last packet is to be
1831//! acknowledged.
1832//!
1833//! This function is used to acknowledge reception of data on an interrupt IN
1834//! pipe.  A transfer on an interrupt IN endpoint is scheduled via a call to
1835//! USBHCDPipeSchedule() and the application is notified when data is received
1836//! using a \b USB_EVENT_RX_AVAILABLE event.  In the handler for this event,
1837//! the application must call USBHCDPipeDataAck() to have the USB controller
1838//! ACK the data from the device and complete the transaction.
1839//!
1840//! \return None.
1841//
1842//*****************************************************************************
1843void USBHCDPipeDataAck(uint32_t ui32Pipe) {
1844    uint32_t ui32Endpoint;
1845
1846    //
1847    // Determine which endpoint interface that this pipe is using.
1848    //
1849    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);
1850
1851    //
1852    // Acknowledge that the data was read from the endpoint.
1853    //
1854    USBHostEndpointDataAck(USB0_BASE, ui32Endpoint);
1855
1856    //
1857    // Go Idle once this state has been reached.
1858    //
1859    g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState = ePipeIdle;
1860}
1861
1862//*****************************************************************************
1863//
1864//! This function is used to read data from a USB HCD pipe.
1865//!
1866//! \param ui32Pipe is the USB pipe to read data from.
1867//! \param pui8Data is a pointer to store the data that is received.
1868//! \param ui32Size is the size in bytes of the buffer pointed to by
1869//! \e pui8Data.
1870//!
1871//! This function will block and will only return when it has read as much data
1872//! as requested from the USB pipe.  The caller must register a callback with
1873//! the USBHCDPipeAlloc() call in order to be informed when the data has been
1874//! received.  If the caller provides a non-zero pointer in the \e pui8Data
1875//! parameter then the data is copied into the buffer before the callback
1876//! occurs.  If the caller provides a zero in \e pui8Data parameter
1877//! then the caller is responsible for reading the data out of the FIFO when
1878//! the \b USB_EVENT_RX_AVAILABLE callback event occurs.   The value returned
1879//! by this function can be less than the \e ui32Size requested if the USB pipe
1880//! has less data available than was requested.
1881//!
1882//! \return This function returns the number of bytes that were returned in the
1883//! \e pui8Data buffer.
1884//
1885//*****************************************************************************
1886uint32_t USBHCDPipeRead(uint32_t ui32Pipe, uint8_t* pui8Data,
1887                        uint32_t ui32Size) {
1888    uint32_t ui32Endpoint, ui32RemainingBytes, ui32BytesRead, ui32PipeIdx;
1889    bool bUseDMA;
1890
1891    //
1892    // Get index used for looking up pipe data
1893    //
1894    ui32PipeIdx = ui32Pipe & EP_PIPE_IDX_M;
1895
1896    //
1897    // Initialized the number of bytes read.
1898    //
1899    ui32BytesRead = 0;
1900
1901    //
1902    // Determine which endpoint interface that this pipe is using.
1903    //
1904    ui32Endpoint = IndexToUSBEP(ui32PipeIdx + 1);
1905
1906    //
1907    // Set the remaining bytes to received.
1908    //
1909    ui32RemainingBytes = ui32Size;
1910
1911    //
1912    // Default to using DMA.
1913    //
1914    bUseDMA = true;
1915
1916    //
1917    // Continue until all data requested has been received.
1918    //
1919    while (ui32RemainingBytes != 0) {
1920        //
1921        // Start a read request.
1922        //
1923        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeReading;
1924
1925        //
1926        // Try the DMA transfer should be used for this transfer, so set up
1927        // the uDMA channel in advance of triggering the IN request.
1928        //
1929        if (ui32Pipe & EP_PIPE_USE_UDMA) {
1930            //
1931            // Disable the USB interrupt.
1932            //
1933            OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
1934
1935            if (USBLibDMATransfer(
1936                    g_sUSBHCD.psDMAInstance,
1937                    g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel, pui8Data,
1938                    ui32Size) != 0) {
1939                g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeReadDMA;
1940
1941                ui32BytesRead = ui32Size;
1942            } else {
1943                bUseDMA = false;
1944            }
1945
1946            //
1947            // Disable the USB interrupt.
1948            //
1949            OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
1950        }
1951
1952        //
1953        // If unable to use DMA then get ready to transfer without DMA.
1954        //
1955        if (bUseDMA == false) {
1956            //
1957            // Disable uDMA on the endpoint
1958            //
1959            MAP_USBEndpointDMADisable(USB0_BASE, ui32Endpoint, USB_EP_HOST_IN);
1960
1961            //
1962            // Set up for the next transaction.
1963            //
1964            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].pui8ReadPtr = pui8Data;
1965            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui32ReadSize =
1966                (ui32RemainingBytes < 64) ? ui32RemainingBytes : 64;
1967        }
1968
1969        //
1970        // Trigger a request for data from the device.
1971        //
1972        MAP_USBHostRequestIN(USB0_BASE, ui32Endpoint);
1973
1974        //
1975        // Wait for a status change.
1976        //
1977        while (1) {
1978            //
1979            // Check if the device stalled the request.
1980            //
1981            if (g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState == ePipeStalled) {
1982                //
1983                // Zero out the size so that the caller knows that no data was
1984                // read.
1985                //
1986                ui32Size = 0;
1987
1988                //
1989                // There are also no remaining bytes to read.
1990                //
1991                ui32RemainingBytes = 0;
1992
1993                //
1994                // If DMA is being used, then disable the channel.
1995                //
1996                if (bUseDMA == true) {
1997                    USBLibDMAChannelDisable(
1998                        g_sUSBHCD.psDMAInstance,
1999                        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel);
2000                }
2001
2002                //
2003                // This is the actual endpoint number.
2004                //
2005                USBHCDClearFeature(
2006                    g_sUSBHCD.psUSBINPipes[ui32PipeIdx].psDevice->ui32Address,
2007                    ui32Pipe, USB_FEATURE_EP_HALT);
2008
2009                //
2010                // If there was a stall, then no more data is coming so break
2011                // out.
2012                //
2013                break;
2014            }
2015
2016            //
2017            // If any error event occurs then exit out of the loop.
2018            //
2019            if (g_sUSBHCD.ui32IntEvents &
2020                (INT_EVENT_DISCONNECT | INT_EVENT_VBUS_ERR |
2021                 INT_EVENT_POWER_FAULT)) {
2022                //
2023                // Set the pipe state to error.
2024                //
2025                g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeError;
2026
2027                //
2028                // Needs to be set to exit out of large while loop.
2029                //
2030                ui32RemainingBytes = 0;
2031
2032                break;
2033            }
2034
2035            //
2036            // If data is ready then return it.
2037            //
2038            if (g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState == ePipeDataReady) {
2039                //
2040                // If not using DMA then read the data from the USB.  Otherwise
2041                // the data will already be in the buffer.
2042                //
2043                if (bUseDMA == false) {
2044                    //
2045                    // Compute bytes to transfer and set up transfer
2046                    //
2047                    ui32BytesRead =
2048                        ui32RemainingBytes > 64 ? 64 : ui32RemainingBytes;
2049
2050                    //
2051                    // Acknowledge that the data was read from the endpoint.
2052                    //
2053                    MAP_USBHostEndpointDataAck(USB0_BASE, ui32Endpoint);
2054                }
2055
2056                //
2057                // Subtract the number of bytes read from the bytes remaining.
2058                //
2059                ui32RemainingBytes -= ui32BytesRead;
2060
2061                //
2062                // If there were less than 64 bytes read, then this was a short
2063                // packet and no more data will be returned.
2064                //
2065                if (ui32BytesRead < 64) {
2066                    //
2067                    // Subtract off the bytes that were not received and exit
2068                    // the loop.
2069                    //
2070                    ui32Size = ui32Size - ui32RemainingBytes;
2071                    break;
2072                } else {
2073                    //
2074                    // Move the buffer ahead to receive more data into the
2075                    // buffer.
2076                    //
2077                    pui8Data += 64;
2078                }
2079                break;
2080            } else if (g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState ==
2081                       ePipeError) {
2082                //
2083                // An error occurred so stop this transaction and set the
2084                // number of bytes to zero.
2085                //
2086                ui32Size = 0;
2087                ui32RemainingBytes = 0;
2088
2089                break;
2090            } else if ((g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState ==
2091                        ePipeReadDMAWait) &&
2092                       (USBLibDMAChannelStatus(
2093                            g_sUSBHCD.psDMAInstance,
2094                            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel) &
2095                        USBLIBSTATUS_DMA_COMPLETE)) {
2096                break;
2097            }
2098        }
2099    }
2100
2101    //
2102    // Go Idle once this state has been reached.
2103    //
2104    g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeIdle;
2105
2106    return (ui32Size);
2107}
2108
2109//*****************************************************************************
2110//
2111//! This function is used to release a USB pipe.
2112//!
2113//! \param ui32Pipe is the allocated USB pipe to release.
2114//!
2115//! This function is used to release a USB pipe that was allocated by a call to
2116//! USBHCDPipeAlloc() for use by some other device endpoint in the system.
2117//! Freeing an unallocated or invalid pipe will not generate an error and will
2118//! instead simply return.
2119//!
2120//! \return None.
2121//
2122//*****************************************************************************
2123void USBHCDPipeFree(uint32_t ui32Pipe) {
2124    uint32_t ui32Index;
2125
2126    //
2127    // Get the index number from the allocated pipe.
2128    //
2129    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);
2130
2131    if (ui32Pipe & EP_PIPE_TYPE_OUT) {
2132        //
2133        // Clear the address and type for this endpoint to free it up.
2134        //
2135        g_sUSBHCD.psUSBOUTPipes[ui32Index].psDevice = 0;
2136        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type = 0;
2137        g_sUSBHCD.psUSBOUTPipes[ui32Index].pfnCallback = 0;
2138
2139        //
2140        // Check if this pipe has allocated a DMA channel.
2141        //
2142        if (g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8DMAChannel !=
2143            USBHCD_DMA_UNUSED) {
2144            //
2145            // Release the DMA channel associated with this endpoint.
2146            //
2147            USBLibDMAChannelRelease(
2148                g_sUSBHCD.psDMAInstance,
2149                g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8DMAChannel);
2150
2151            //
2152            // Clear out the current channel in use by this pipe.
2153            //
2154            g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8DMAChannel =
2155                USBHCD_DMA_UNUSED;
2156        }
2157
2158        //
2159        // Free up the FIFO memory used by this endpoint.
2160        //
2161        if (g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8FIFOSize) {
2162            FIFOFree(&g_sUSBHCD.psUSBOUTPipes[ui32Index]);
2163        }
2164
2165        //
2166        // Set the function address for this endpoint back to zero.
2167        //
2168        USBHostAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1), 0,
2169                       USB_EP_HOST_OUT);
2170
2171        //
2172        // Set the hub and port address for the endpoint back to zero and the
2173        // speed back to LOW.
2174        //
2175        USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1), 0,
2176                          (USB_EP_HOST_OUT | USB_EP_SPEED_LOW));
2177    } else if (ui32Pipe & EP_PIPE_TYPE_IN) {
2178        //
2179        // Clear the address and type for this endpoint to free it up.
2180        //
2181        g_sUSBHCD.psUSBINPipes[ui32Index].psDevice = 0;
2182        g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type = 0;
2183        g_sUSBHCD.psUSBINPipes[ui32Index].pfnCallback = 0;
2184
2185        //
2186        // Check if this pipe has allocated a DMA channel.
2187        //
2188        if (g_sUSBHCD.psUSBINPipes[ui32Index].ui8DMAChannel !=
2189            USBHCD_DMA_UNUSED) {
2190            //
2191            // Release the DMA channel associated with this endpoint.
2192            //
2193            USBLibDMAChannelRelease(
2194                g_sUSBHCD.psDMAInstance,
2195                g_sUSBHCD.psUSBINPipes[ui32Index].ui8DMAChannel);
2196
2197            //
2198            // Clear out the current channel in use by this pipe.
2199            //
2200            g_sUSBHCD.psUSBINPipes[ui32Index].ui8DMAChannel = USBHCD_DMA_UNUSED;
2201        }
2202
2203        //
2204        // Free up the FIFO memory used by this endpoint.
2205        //
2206        if (g_sUSBHCD.psUSBINPipes[ui32Pipe & EP_PIPE_IDX_M].ui8FIFOSize) {
2207            FIFOFree(&g_sUSBHCD.psUSBINPipes[ui32Pipe & EP_PIPE_IDX_M]);
2208        }
2209
2210        //
2211        // Set the function address for this endpoint back to zero.
2212        //
2213        USBHostAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1), 0,
2214                       USB_EP_HOST_IN);
2215
2216        //
2217        // Set the hub and port address for the endpoint back to zero and the
2218        // speed back to LOW.
2219        //
2220        USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1), 0,
2221                          (USB_EP_HOST_IN | USB_EP_SPEED_LOW));
2222
2223        //
2224        // Clear any pending IN transactions.
2225        //
2226        USBHostRequestINClear(USB0_BASE, IndexToUSBEP(ui32Index + 1));
2227    }
2228}
2229
2230//*****************************************************************************
2231//
2232// This internal function initializes the HCD code.
2233//
2234// \param ui32Index specifies which USB controller to use.
2235// \param pvPool is a pointer to the data to use as a memory pool for this
2236// controller.
2237// \param ui32PoolSize is the size in bytes of the buffer passed in as pvPool.
2238//
2239// This function will perform all the necessary operations to allow the USB
2240// host controller to begin enumeration and communication with a device.  This
2241// function should typically be called once at the start of an application
2242// before any other calls are made to the host controller.
2243//
2244// \return None.
2245//
2246//*****************************************************************************
2247static void USBHCDInitInternal(uint32_t ui32Index, void* pvPool,
2248                               uint32_t ui32PoolSize) {
2249    int32_t i32Idx;
2250
2251    ASSERT(ui32Index == 0);
2252
2253    //
2254    // Get the number of endpoints supported by this device.
2255    //
2256    g_sUSBHCD.ui32NumEndpoints = USBNumEndpointsGet(USB0_BASE);
2257
2258    //
2259    // The first 64 Bytes are allocated to endpoint 0.
2260    //
2261    g_pui32Alloc[0] = 1;
2262    g_pui32Alloc[1] = 0;
2263
2264    //
2265    // Save the base address for this controller.
2266    //
2267    g_sUSBHCD.ui32USBBase = USB0_BASE;
2268
2269    //
2270    // Save the USB interrupt number.
2271    //
2272    g_sUSBHCD.ui32IntNum = INT_USB0_TM4C123;
2273
2274    //
2275    // These devices have a different USB interrupt number.
2276    //
2277    if (CLASS_IS_TM4C129) {
2278        g_sUSBHCD.ui32IntNum = INT_USB0_TM4C129;
2279    }
2280
2281    //
2282    // All Pipes are unused at start.
2283    //
2284    for (i32Idx = 0; i32Idx < MAX_NUM_PIPES; i32Idx++) {
2285        g_sUSBHCD.psUSBINPipes[i32Idx].psDevice = 0;
2286        g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
2287        g_sUSBHCD.psUSBINPipes[i32Idx].ui8DMAChannel = USBHCD_DMA_UNUSED;
2288        g_sUSBHCD.psUSBOUTPipes[i32Idx].psDevice = 0;
2289        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
2290        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8DMAChannel = USBHCD_DMA_UNUSED;
2291    }
2292
2293    //
2294    // Make sure that the hub driver is initialized since it is called even
2295    // if it is not present in the system.
2296    //
2297    USBHHubInit();
2298
2299    //
2300    // Initialize the DMA interface.
2301    //
2302    g_sUSBHCD.psDMAInstance = USBLibDMAInit(ui32Index);
2303
2304    //
2305    // Initialized the device structures.
2306    //
2307    for (i32Idx = 0; i32Idx <= MAX_USB_DEVICES; i32Idx++) {
2308        //
2309        // Clear the configuration descriptor and state.
2310        //
2311        g_sUSBHCD.piDeviceState[i32Idx] = eHCDIdle;
2312        g_sUSBHCD.psUSBDevice[i32Idx].psConfigDescriptor = 0;
2313        g_sUSBHCD.psUSBDevice[i32Idx].bConfigRead = false;
2314
2315        //
2316        // Initialize the device descriptor.
2317        //
2318        g_sUSBHCD.psUSBDevice[i32Idx].sDeviceDescriptor.bLength = 0;
2319        g_sUSBHCD.psUSBDevice[i32Idx].sDeviceDescriptor.bMaxPacketSize0 = 0;
2320
2321        //
2322        // Initialize the device address.
2323        //
2324        g_sUSBHCD.psUSBDevice[i32Idx].ui32Address = 0;
2325
2326        //
2327        // Set the current interface to 0.
2328        //
2329        g_sUSBHCD.psUSBDevice[i32Idx].ui32Interface = 0;
2330
2331        //
2332        // Clear the active driver for the device.
2333        //
2334        g_pi32USBHActiveDriver[i32Idx] = -1;
2335
2336        //
2337        // Initialize the device flags.
2338        //
2339        g_sUSBHCD.psUSBDevice[i32Idx].ui32Flags = 0;
2340    }
2341
2342    //
2343    // Allocate the memory needed for reading descriptors.
2344    //
2345    g_sUSBHCD.pvPool = pvPool;
2346    g_sUSBHCD.ui32PoolSize = ui32PoolSize;
2347
2348    //
2349    // Initialize the device class.
2350    //
2351    g_sUSBHCD.ui32Class = USB_CLASS_EVENTS;
2352
2353    //
2354    // Default enable connect, disconnect, unknown device and power fault
2355    // event notifications.
2356    //
2357    g_sUSBHCD.ui32EventEnables =
2358        USBHCD_EVFLAG_CONNECT | USBHCD_EVFLAG_UNKCNCT | USBHCD_EVFLAG_DISCNCT |
2359        USBHCD_EVFLAG_PWRFAULT | USBHCD_EVFLAG_PWREN | USBHCD_EVFLAG_PWRDIS;
2360
2361    //
2362    // Initialize the USB tick module.
2363    //
2364    InternalUSBTickInit();
2365
2366    //
2367    // Only do hardware update if the stack is in Host mode, do not touch the
2368    // hardware for OTG mode operation.
2369    //
2370    if ((g_iUSBMode == eUSBModeHost) || (g_iUSBMode == eUSBModeForceHost)) {
2371        //
2372        // Configure the End point 0.
2373        //
2374        USBHostEndpointConfig(
2375            USB0_BASE, USB_EP_0, 64, 0, 0,
2376            (USB_EP_MODE_CTRL | USB_EP_SPEED_FULL | USB_EP_HOST_OUT));
2377
2378        //
2379        // Enable USB Interrupts.
2380        //
2381        MAP_USBIntEnableControl(
2382            USB0_BASE, USB_INTCTRL_RESET | USB_INTCTRL_DISCONNECT |
2383                           USB_INTCTRL_SOF | USB_INTCTRL_SESSION |
2384                           USB_INTCTRL_BABBLE | USB_INTCTRL_CONNECT |
2385                           USB_INTCTRL_RESUME | USB_INTCTRL_SUSPEND |
2386                           USB_INTCTRL_VBUS_ERR | USB_INTCTRL_POWER_FAULT);
2387
2388        MAP_USBIntEnableEndpoint(USB0_BASE, USB_INTEP_ALL);
2389
2390        //
2391        // Enable the USB interrupt.
2392        //
2393        OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
2394
2395        //
2396        // There is no automatic power in pure host mode.
2397        //
2398        USBHCDPowerConfigSet(ui32Index,
2399                             (g_ui32PowerConfig & ~USB_HOST_PWREN_AUTO));
2400
2401        //
2402        // Force the power on as well as this point.
2403        //
2404        MAP_USBHostPwrEnable(USB0_BASE);
2405
2406        //
2407        // This is required to get into host mode on some parts.
2408        //
2409        USBOTGSessionRequest(USB0_BASE, true);
2410    }
2411
2412    //
2413    // Configure LPM if it is enabled.
2414    //
2415    if (g_sUSBHCD.ui32Features & USBLIB_FEATURE_LPM_EN) {
2416        if (g_sUSBHCD.ui32Features & USBLIB_FEATURE_LPM_RMT_WAKE) {
2417            USBHostLPMConfig(USB0_BASE, g_sUSBHCD.ui32LPMHIRD,
2418                             USB_DEV_LPM_LS_L1 | USB_DEV_LPM_LS_RMTWAKE);
2419        } else {
2420            USBHostLPMConfig(USB0_BASE, g_sUSBHCD.ui32LPMHIRD,
2421                             USB_DEV_LPM_LS_L1);
2422        }
2423
2424        //
2425        // Enable USB interrupts for LPM mode, these enables have no effect on
2426        // devices that do not support LPM.
2427        //
2428        USBLPMIntEnable(USB0_BASE, USB_INTLPM_ERROR | USB_INTLPM_RESUME |
2429                                       USB_INTLPM_INCOMPLETE | USB_INTLPM_ACK |
2430                                       USB_INTLPM_NYET | USB_INTLPM_STALL);
2431    }
2432}
2433
2434//*****************************************************************************
2435//
2436//! This function is used to set the power pin and power fault configuration.
2437//!
2438//! \param ui32Index specifies which USB controller to use.
2439//! \param ui32PwrConfig is the power configuration to use for the application.
2440//!
2441//! This function must be called before HCDInit() is called so that the power
2442//! pin configuration can be set before power is enabled.  The \e ui32PwrConfig
2443//! flags specify the power fault level sensitivity, the power fault action,
2444//! and the power enable pin level and source.
2445//!
2446//! One of the following can be selected as the power fault level sensitivity:
2447//!
2448//! - \b USBHCD_FAULT_LOW - An external power fault is indicated by the pin
2449//!                         being driven low.
2450//! - \b USBHCD_FAULT_HIGH - An external power fault is indicated by the pin
2451//!                          being driven high.
2452//!
2453//! One of the following can be selected as the power fault action:
2454//!
2455//! - \b USBHCD_FAULT_VBUS_NONE - No automatic action when power fault
2456//!   detected.
2457//! - \b USBHCD_FAULT_VBUS_TRI - Automatically Tri-state the USBnEPEN pin on a
2458//!                              power fault.
2459//! - \b USBHCD_FAULT_VBUS_DIS - Automatically drive the USBnEPEN pin to it's
2460//!                              inactive state on a power fault.
2461//!
2462//! One of the following can be selected as the power enable level and source:
2463//!
2464//! - \b USBHCD_VBUS_MANUAL - Power control is completely managed by the
2465//!                           application, the USB library will provide a
2466//!                           power callback to request power state changes.
2467//! - \b USBHCD_VBUS_AUTO_LOW - USBEPEN is driven low by the USB controller
2468//!                             automatically if USBOTGSessionRequest() has
2469//!                             enabled a session.
2470//! - \b USBHCD_VBUS_AUTO_HIGH - USBEPEN is driven high by the USB controller
2471//!                              automatically if USBOTGSessionRequest() has
2472//!                              enabled a session.
2473//!
2474//! If \b USBHCD_VBUS_MANUAL is used then the application must provide an
2475//! event driver to receive the \b USB_EVENT_POWER_ENABLE and
2476//! \b USB_EVENT_POWER_DISABLE events and enable and disable power to VBUS when
2477//! requested by the USB library.  The application should respond to a power
2478//! control callback by enabling or disabling VBUS as soon as possible and
2479//! before returning from the callback function.
2480//!
2481//! \note The following values should no longer be used with the USB
2482//! library: \b USB_HOST_PWRFLT_LOW, \b USB_HOST_PWRFLT_HIGH,
2483//! \b USB_HOST_PWRFLT_EP_NONE, \b USB_HOST_PWRFLT_EP_TRI,
2484//! \b USB_HOST_PWRFLT_EP_LOW, \b USB_HOST_PWRFLT_EP_HIGH,
2485//! \b USB_HOST_PWREN_LOW, \b USB_HOST_PWREN_HIGH, \b USB_HOST_PWREN_VBLOW, and
2486//! \b USB_HOST_PWREN_VBHIGH.
2487//!
2488//! \return None.
2489//
2490//*****************************************************************************
2491void USBHCDPowerConfigInit(uint32_t ui32Index, uint32_t ui32PwrConfig) {
2492    ASSERT(ui32Index == 0);
2493
2494    //
2495    // Save the value as it will be used later.
2496    //
2497    g_ui32PowerConfig = ui32PwrConfig;
2498}
2499
2500//*****************************************************************************
2501//
2502//! This function is used to get the power pin and power fault configuration.
2503//!
2504//! \param ui32Index specifies which USB controller to use.
2505//!
2506//! This function will return the current power control pin configuration as
2507//! set by the USBHCDPowerConfigInit() function or the defaults if not yet set.
2508//! See the USBHCDPowerConfigInit() documentation for the meaning of the bits
2509//! that are returned by this function.
2510//!
2511//! \return The configuration of the power control pins.
2512//!
2513//*****************************************************************************
2514uint32_t USBHCDPowerConfigGet(uint32_t ui32Index) {
2515    ASSERT(ui32Index == 0);
2516
2517    //
2518    // Save the value as it will be used later.
2519    //
2520    return (g_ui32PowerConfig);
2521}
2522
2523//*****************************************************************************
2524//
2525//! This function is used to set the power pin and power fault configuration.
2526//!
2527//! \param ui32Index specifies which USB controller to use.
2528//! \param ui32Config specifies which USB power configuration to use.
2529//!
2530//! This function will set the current power control pin configuration as
2531//! set by the USBHCDPowerConfigInit() function or the defaults if not yet set.
2532//! See the USBHCDPowerConfigInit() documentation for the meaning of the bits
2533//! that are set by this function.
2534//!
2535//! \return Returns zero to indicate the power setting is now active.
2536//!
2537//*****************************************************************************
2538uint32_t USBHCDPowerConfigSet(uint32_t ui32Index, uint32_t ui32Config) {
2539    ASSERT(ui32Index == 0);
2540
2541    //
2542    // Remember the current setting.
2543    //
2544    g_ui32PowerConfig = ui32Config;
2545
2546    //
2547    // Clear out the two flag bits.
2548    //
2549    ui32Config =
2550        g_ui32PowerConfig & ~(USBHCD_VBUS_MANUAL | USBHCD_FAULT_VBUS_DIS);
2551
2552    //
2553    // If there is an automatic disable power action specified then set the
2554    // polarity of the signal to match EPEN.
2555    //
2556    if (g_ui32PowerConfig & USBHCD_FAULT_VBUS_DIS) {
2557        //
2558        // Insure that the assumption below is true.
2559        //
2560        ASSERT((USBHCD_VBUS_AUTO_HIGH & 1) == 1);
2561        ASSERT((USBHCD_VBUS_AUTO_LOW & 1) == 0);
2562
2563        //
2564        // This is taking advantage of the difference between
2565        // USBHCD_VBUS_AUTO_LOW and USBHCD_VBUS_AUTO_HIGH being that bit
2566        // one is set when EPEN is active high.
2567        //
2568        if (g_ui32PowerConfig & 1) {
2569            g_ui32PowerConfig |= USB_HOST_PWRFLT_EP_LOW;
2570            ui32Config |= USB_HOST_PWRFLT_EP_LOW;
2571        } else {
2572            g_ui32PowerConfig |= USB_HOST_PWRFLT_EP_HIGH;
2573            ui32Config |= USB_HOST_PWRFLT_EP_HIGH;
2574        }
2575    }
2576
2577    //
2578    // Initialize the power configuration.
2579    //
2580    MAP_USBHostPwrConfig(USB0_BASE, ui32Config);
2581
2582    //
2583    // If not in manual mode then just turn on power.
2584    //
2585    if ((g_ui32PowerConfig & USBHCD_VBUS_MANUAL) == 0) {
2586        //
2587        // Power the USB bus.
2588        //
2589        MAP_USBHostPwrEnable(USB0_BASE);
2590    }
2591
2592    //
2593    // Return success.
2594    //
2595    return (0);
2596}
2597
2598//*****************************************************************************
2599//
2600//! This function returns if the current power settings will automatically
2601//! handle enabling and disabling VBUS power.
2602//!
2603//! \param ui32Index specifies which USB controller to query.
2604//!
2605//! This function returns if the current power control pin configuration will
2606//! automatically apply power or whether it will be left to the application
2607//! to turn on power when it is notified.
2608//!
2609//! \return A non-zero value indicates that power is automatically applied and
2610//! a value of zero indicates that the application must manually apply power.
2611//!
2612//*****************************************************************************
2613uint32_t USBHCDPowerAutomatic(uint32_t ui32Index) {
2614    //
2615    // Check if the controller is automatically applying power or not.
2616    //
2617    if (g_ui32PowerConfig & USBHCD_VBUS_MANUAL) {
2618        return (0);
2619    }
2620    return (1);
2621}
2622
2623//*****************************************************************************
2624//
2625//! This function is used to initialize the HCD code.
2626//!
2627//! \param ui32Index specifies which USB controller to use.
2628//! \param pvPool is a pointer to the data to use as a memory pool for this
2629//! controller.
2630//! \param ui32PoolSize is the size in bytes of the buffer passed in as
2631//! \e pvPool.
2632//!
2633//! This function will perform all the necessary operations to allow the USB
2634//! host controller to begin enumeration and communication with devices.  This
2635//! function should typically be called once at the start of an application
2636//! once all of the device and class drivers are ready for normal operation.
2637//! This call will start up the USB host controller and any connected device
2638//! will immediately start the enumeration sequence.
2639//!
2640//! The USBStackModeSet() function can be called with eUSBModeHost in order to
2641//! cause the USB library to force the USB operating mode to a host controller.
2642//! This allows the application to used the USBVBUS and USBID pins as GPIOs on
2643//! devices that support forcing OTG to operate as a host only controller.  By
2644//! default the USB library will assume that the USBVBUS and USBID pins are
2645//! configured as USB pins and not GPIOs.
2646//!
2647//! The memory pool passed to this function must be at least as large as a
2648//! typical configuration descriptor for devices that are to be supported.
2649//! This value is application-dependent however it should never be less than 32
2650//! bytes and, in most cases, should be at least 64 bytes.  If there is not
2651//! sufficient memory to load a configuration descriptor from a device, the
2652//! device will not be recognized by the USB library's host controller driver.
2653//!
2654//! \return None.
2655//
2656//*****************************************************************************
2657void USBHCDInit(uint32_t ui32Index, void* pvPool, uint32_t ui32PoolSize) {
2658    int32_t i32Driver;
2659
2660    //
2661    // Check the arguments.
2662    //
2663    ASSERT(ui32Index == 0);
2664
2665    //
2666    // Make sure there is at least enough to read the configuration descriptor.
2667    //
2668    ASSERT(ui32PoolSize >= sizeof(tConfigDescriptor));
2669
2670    //
2671    // Should not call this if the stack is in device mode.
2672    //
2673    ASSERT(g_iUSBMode != eUSBModeDevice);
2674    ASSERT(g_iUSBMode != eUSBModeForceDevice);
2675
2676    //
2677    // If the mode was not set then default to eUSBModeHost.
2678    //
2679    if (g_iUSBMode == eUSBModeNone) {
2680        g_iUSBMode = eUSBModeHost;
2681    }
2682
2683    //
2684    // Reset the USB controller.
2685    //
2686    MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_USB0);
2687
2688    //
2689    // Enable Clocking to the USB controller.
2690    //
2691    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0);
2692
2693    //
2694    // Turn on USB Phy clock.
2695    //
2696    MAP_SysCtlUSBPLLEnable();
2697
2698    //
2699    // Set the PLL to USB clock divider.
2700    //
2701    if (g_ui32PLLDiv == 0) {
2702        USBClockEnable(USB0_BASE, g_ui32PLLDiv, USB_CLOCK_EXTERNAL);
2703    } else {
2704        USBClockEnable(USB0_BASE, g_ui32PLLDiv, USB_CLOCK_INTERNAL);
2705    }
2706
2707    //
2708    // Configure ULPI support.
2709    //
2710    if (g_ui32ULPISupport != USBLIB_FEATURE_ULPI_NONE) {
2711        USBULPIEnable(USB0_BASE);
2712
2713        if (g_ui32ULPISupport & USBLIB_FEATURE_ULPI_HS) {
2714            ULPIConfigSet(USB0_BASE, ULPI_CFG_HS);
2715        } else {
2716            ULPIConfigSet(USB0_BASE, ULPI_CFG_FS);
2717        }
2718    } else {
2719        USBULPIDisable(USB0_BASE);
2720    }
2721
2722    //
2723    // If the application not requesting OTG mode then set the mode to forced
2724    // host mode.  If the mode is actually eUSBModeHost, this will be switched
2725    // off when ID pin detection is complete and the ID is no longer in use.
2726    //
2727    if (g_iUSBMode != eUSBModeOTG) {
2728        //
2729        // Force Host mode on devices that support force host mode.
2730        //
2731        MAP_USBHostMode(USB0_BASE);
2732    }
2733
2734    //
2735    // Call our internal function to perform the initialization.
2736    //
2737    USBHCDInitInternal(ui32Index, pvPool, ui32PoolSize);
2738
2739    //
2740    // No event driver is present by default.
2741    //
2742    g_sUSBHCD.i32EventDriver = -1;
2743
2744    //
2745    // Search through the Host Class driver list for the devices class.
2746    //
2747    for (i32Driver = 0; i32Driver < g_sUSBHCD.ui32NumClassDrivers;
2748         i32Driver++) {
2749        if (g_sUSBHCD.ppsClassDrivers[i32Driver]->ui32InterfaceClass ==
2750            USB_CLASS_EVENTS) {
2751            //
2752            // Event driver was found so remember it.
2753            //
2754            g_sUSBHCD.i32EventDriver = i32Driver;
2755        }
2756    }
2757
2758    //
2759    // Get the number of ticks per millisecond, this is only used by blocking
2760    // delays using the SysCtlDelay() function.
2761    //
2762    if (g_ui32Tickms == 0) {
2763        if (CLASS_IS_TM4C129) {
2764            g_ui32Tickms = 120000000 / 3000;
2765        } else {
2766            g_ui32Tickms = 80000000 / 3000;
2767        }
2768    }
2769}
2770
2771//*****************************************************************************
2772//
2773//! This function is used to initialize the HCD class driver list.
2774//!
2775//! \param ui32Index specifies which USB controller to use.
2776//! \param ppsHClassDrvs is an array of host class drivers that are
2777//! supported on this controller.
2778//! \param ui32NumDrivers is the number of entries in the \e pHostClassDrivers
2779//! array.
2780//!
2781//! This function will set the host classes supported by the host controller
2782//! specified by the \e ui32Index parameter.  This function should be called
2783//! before enabling the host controller driver with the USBHCDInit() function.
2784//!
2785//! \return None.
2786//
2787//*****************************************************************************
2788void USBHCDRegisterDrivers(uint32_t ui32Index,
2789                           const tUSBHostClassDriver* const* ppsHClassDrvs,
2790                           uint32_t ui32NumDrivers) {
2791    ASSERT(ui32Index == 0);
2792
2793    //
2794    // Save the class drivers.
2795    //
2796    g_sUSBHCD.ppsClassDrivers = ppsHClassDrvs;
2797
2798    //
2799    // Save the number of class drivers.
2800    //
2801    g_sUSBHCD.ui32NumClassDrivers = ui32NumDrivers;
2802}
2803
2804//*****************************************************************************
2805//
2806//! This function is used to terminate the HCD code.
2807//!
2808//! \param ui32Index specifies which USB controller to release.
2809//!
2810//! This function will clean up the USB host controller and disable it in
2811//! preparation for shutdown or a switch to USB device mode.  Once this call is
2812//! made, \e USBHCDInit() may be called to reinitialize the controller and
2813//! prepare for host mode operation.
2814//!
2815//! \return None.
2816//
2817//*****************************************************************************
2818void USBHCDTerm(uint32_t ui32Index) {
2819    int32_t i32Idx;
2820
2821    ASSERT(ui32Index == 0);
2822
2823    //
2824    // End the session.
2825    //
2826    USBOTGSessionRequest(USB0_BASE, false);
2827
2828    //
2829    // Remove power from the USB bus.
2830    //
2831    MAP_USBHostPwrDisable(USB0_BASE);
2832
2833    //
2834    // Disable USB interrupts.
2835    //
2836    OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
2837
2838    MAP_USBIntDisableControl(USB0_BASE, USB_INTCTRL_ALL);
2839
2840    MAP_USBIntDisableEndpoint(USB0_BASE, USB_INTEP_ALL);
2841
2842    //
2843    // Set the host controller state back to it's initial values.
2844    //
2845    for (i32Idx = 0; i32Idx < MAX_NUM_PIPES; i32Idx++) {
2846        g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
2847        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
2848    }
2849
2850    //
2851    // Free the memory used by the configuration descriptor.
2852    //
2853    ConfigDescFree(&g_sUSBHCD.psUSBDevice[0]);
2854
2855    g_sUSBHCD.piDeviceState[0] = eHCDIdle;
2856    g_sUSBHCD.psUSBDevice[0].psConfigDescriptor = 0;
2857    g_sUSBHCD.psUSBDevice[0].bConfigRead = false;
2858    g_sUSBHCD.psUSBDevice[0].sDeviceDescriptor.bLength = 0;
2859    g_sUSBHCD.psUSBDevice[0].sDeviceDescriptor.bMaxPacketSize0 = 0;
2860    g_sUSBHCD.psUSBDevice[0].ui32Address = 0;
2861    g_sUSBHCD.psUSBDevice[0].ui32Interface = 0;
2862    g_sUSBHCD.pvPool = 0;
2863    g_sUSBHCD.ui32PoolSize = 0;
2864}
2865
2866//*****************************************************************************
2867//
2868//! This function generates reset signaling on the USB bus.
2869//!
2870//! \param ui32Index specifies which USB controller to use.
2871//!
2872//! This function handles sending out reset signaling on the USB bus.  After
2873//! returning from this function, any attached device on the USB bus should
2874//! have returned to it's reset state.
2875//!
2876//! \return None.
2877//
2878//*****************************************************************************
2879void USBHCDReset(uint32_t ui32Index) {
2880    ASSERT(ui32Index == 0);
2881
2882    //
2883    // Start the reset signaling.
2884    //
2885    MAP_USBHostReset(USB0_BASE, 1);
2886
2887    //
2888    // Wait 20ms
2889    //
2890    OS_DELAY(g_ui32Tickms * 20);
2891
2892    //
2893    // End reset signaling on the bus.
2894    //
2895    MAP_USBHostReset(USB0_BASE, 0);
2896
2897    //
2898    // Need to wait at least 10ms to let the device recover from
2899    // the reset.  This is the delay specified in the USB 2.0 spec.
2900    // We will hold the reset for 20ms.
2901    //
2902    OS_DELAY(g_ui32Tickms * 20);
2903}
2904
2905//*****************************************************************************
2906//
2907//! This function will generate suspend signaling on the USB bus.
2908//!
2909//! \param ui32Index specifies which USB controller to use.
2910//!
2911//! This function is used to generate suspend signaling on the USB bus.  In
2912//! order to leave the suspended state, the application should call
2913//! USBHCDResume().
2914//!
2915//! \return None.
2916//
2917//*****************************************************************************
2918void USBHCDSuspend(uint32_t ui32Index) {
2919    ASSERT(ui32Index == 0);
2920
2921    //
2922    // Start the suspend signaling.
2923    //
2924    MAP_USBHostSuspend(USB0_BASE);
2925}
2926
2927//*****************************************************************************
2928//
2929//! This function will generate resume signaling on the USB bus.
2930//!
2931//! \param ui32Index specifies which USB controller to use.
2932//!
2933//! This function is used to generate resume signaling on the USB bus in order
2934//! to cause  USB devices to leave their suspended state.  This call should
2935//! not be made unless a preceding call to USBHCDSuspend() has been made.
2936//!
2937//! \return None.
2938//
2939//*****************************************************************************
2940void USBHCDResume(uint32_t ui32Index) {
2941    ASSERT(ui32Index == 0);
2942
2943    //
2944    // Start the resume signaling.
2945    //
2946    MAP_USBHostResume(USB0_BASE, 1);
2947
2948    //
2949    // Wait 100ms
2950    //
2951    OS_DELAY(g_ui32Tickms * 100);
2952
2953    //
2954    // End reset signaling on the bus.
2955    //
2956    MAP_USBHostResume(USB0_BASE, 0);
2957}
2958
2959//*****************************************************************************
2960//
2961//! This function issues a request for the current configuration descriptor
2962//! from a device.
2963//!
2964//! \param ui32Index specifies which USB controller to use.
2965//! \param psDevice is a pointer to the device structure that holds the buffer
2966//! to store the configuration descriptor.
2967//!
2968//! This function will request the configuration descriptor from the device.
2969//! The \e psDevice->ConfigDescriptor member variable is used to hold the data
2970//! for this request.  This buffer will be allocated from the pool provided by
2971//! the HCDInit() function.  \e psDevice->sDeviceDescriptor.bMaxPacketSize0
2972//! should be valid prior to this call in order to correctly receive the
2973//! configuration descriptor.  If this variable is not valid then this call
2974//! will not return accurate data.
2975//!
2976//! \return The number of bytes returned due to the request.  This value can be
2977//! zero if the device did not respond.
2978//
2979//*****************************************************************************
2980static uint32_t USBHCDGetConfigDescriptor(uint32_t ui32Index,
2981                                          tUSBHostDevice* psDevice) {
2982    tUSBRequest sSetupPacket;
2983    uint32_t ui32Bytes;
2984    tConfigDescriptor sConfigDescriptor;
2985
2986    ASSERT(ui32Index == 0);
2987
2988    ui32Bytes = 0;
2989
2990    //
2991    // This is a Standard Device IN request.
2992    //
2993    sSetupPacket.bmRequestType =
2994        USB_RTYPE_DIR_IN | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;
2995
2996    //
2997    // Request a Device Descriptor.
2998    //
2999    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;
3000    sSetupPacket.wValue = USB_DTYPE_CONFIGURATION << 8;
3001
3002    //
3003    // Index is always 0 for device configurations requests.
3004    //
3005    sSetupPacket.wIndex = 0;
3006
3007    //
3008    // Only ask for the configuration header first to see how big the
3009    // whole thing is.
3010    //
3011    if (!psDevice->bConfigRead) {
3012        //
3013        // Only request the space available.
3014        //
3015        sSetupPacket.wLength = sizeof(tConfigDescriptor);
3016
3017        //
3018        // Put the setup packet in the buffer.
3019        //
3020        ui32Bytes = USBHCDControlTransfer(
3021            0, &sSetupPacket, psDevice, (uint8_t*)&sConfigDescriptor,
3022            sizeof(tConfigDescriptor),
3023            psDevice->sDeviceDescriptor.bMaxPacketSize0);
3024    }
3025
3026    //
3027    // If the Configuration header was successfully returned then get the
3028    // full configuration descriptor.
3029    //
3030    if (ui32Bytes == sizeof(tConfigDescriptor)) {
3031        //
3032        // Save the total size and request the full configuration descriptor.
3033        //
3034        sSetupPacket.wLength = sConfigDescriptor.wTotalLength;
3035
3036        //
3037        // Not enough space to hold this configuration descriptor.
3038        //
3039        if (ConfigDescAlloc(psDevice, sConfigDescriptor.wTotalLength) == 0) {
3040            return (0);
3041        }
3042
3043        //
3044        // Don't allow the buffer to be larger than was allocated.
3045        //
3046        if (sSetupPacket.wLength > psDevice->ui32ConfigDescriptorSize) {
3047            return (0);
3048        }
3049
3050        //
3051        // Put the setup packet in the buffer.
3052        //
3053        ui32Bytes = USBHCDControlTransfer(
3054            0, &sSetupPacket, psDevice, (uint8_t*)psDevice->psConfigDescriptor,
3055            sSetupPacket.wLength, psDevice->sDeviceDescriptor.bMaxPacketSize0);
3056
3057        //
3058        // If we read the descriptor, remember the fact.
3059        //
3060        if (ui32Bytes) {
3061            psDevice->bConfigRead = true;
3062        }
3063    }
3064
3065    return (ui32Bytes);
3066}
3067
3068//*****************************************************************************
3069//
3070//! This function issues a request for a device descriptor from a device.
3071//!
3072//! \param ui32Index specifies which USB controller to use.
3073//! \param psDevice is a pointer to the device structure that holds the buffer
3074//! to store the device descriptor into.
3075//!
3076//! This function will request the device descriptor from the device.  The
3077//! \e psDevice->sDeviceDescriptor descriptor is used to hold the data for this
3078//! request.  \e psDevice->sDeviceDescriptor.bMaxPacketSize0 should be
3079//! initialized to zero or to the valid maximum packet size if it is known.  If
3080//! this variable is not set to zero, then this call will determine the maximum
3081//! packet size for endpoint 0 and save it in the structure member
3082//! bMaxPacketSize0.
3083//!
3084//! \return The number of bytes returned due to the request.  This value can be
3085//! zero if the device did not respond.
3086//
3087//*****************************************************************************
3088static uint32_t USBHCDGetDeviceDescriptor(uint32_t ui32Index,
3089                                          tUSBHostDevice* psDevice) {
3090    tUSBRequest sSetupPacket;
3091    uint32_t ui32Bytes;
3092
3093    ASSERT(ui32Index == 0);
3094
3095    //
3096    // This is a Standard Device IN request.
3097    //
3098    sSetupPacket.bmRequestType =
3099        USB_RTYPE_DIR_IN | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;
3100
3101    //
3102    // Request a Device Descriptor.
3103    //
3104    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;
3105    sSetupPacket.wValue = USB_DTYPE_DEVICE << 8;
3106
3107    //
3108    // Index is always 0 for device requests.
3109    //
3110    sSetupPacket.wIndex = 0;
3111
3112    //
3113    // All devices must have at least an 8 byte max packet size so just ask
3114    // for 8 bytes to start with.
3115    //
3116    sSetupPacket.wLength = sizeof(tDeviceDescriptor);
3117
3118    ui32Bytes = 0;
3119
3120    //
3121    // Discover the max packet size for endpoint 0.
3122    //
3123    if (psDevice->sDeviceDescriptor.bMaxPacketSize0 == 0) {
3124        //
3125        // Put the setup packet in the buffer.
3126        //
3127        ui32Bytes =
3128            USBHCDControlTransfer(ui32Index, &sSetupPacket, psDevice,
3129                                  (uint8_t*)&(psDevice->sDeviceDescriptor),
3130                                  sizeof(tDeviceDescriptor), 8);
3131    }
3132
3133    //
3134    // Now get the full descriptor now that the actual maximum packet size
3135    // is known.
3136    //
3137    if (ui32Bytes < sizeof(tDeviceDescriptor)) {
3138        sSetupPacket.wLength = (uint16_t)sizeof(tDeviceDescriptor);
3139
3140        ui32Bytes = USBHCDControlTransfer(
3141            ui32Index, &sSetupPacket, psDevice,
3142            (uint8_t*)&(psDevice->sDeviceDescriptor), sizeof(tDeviceDescriptor),
3143            psDevice->sDeviceDescriptor.bMaxPacketSize0);
3144    }
3145
3146    return (ui32Bytes);
3147}
3148
3149//*****************************************************************************
3150//
3151//! This function issues a request for a string descriptor from a device.
3152//!
3153//! \param psDevice is the device for this request.
3154//! \param pui8Buffer is the pointer to the buffer to store the requested
3155//! string descriptor.
3156//! \param ui32Size is the size of the buffer passed in the buffer that will
3157//! be used for this request.
3158//! \param ui32LangID is the ID of the language for the requested string.
3159//! \param ui32StringIndex is the index for the request.
3160//!
3161//! This function will request a string descriptor from the device of the type
3162//! specified in the \e ui32DescriptorType parameter.  The \e pui8Descriptor
3163//! pointer is the location where the request results will be stored.  The
3164//! \e ui32Size should be passed in to indicate the size of the
3165//! \e pui8Descriptor buffer.  The \e ui32DevAddress parameter is used to
3166//! specify the device address to communicate with on the USB bus.  This value
3167//! should be specified as 0 for any non-configured device on the USB bus and
3168//! be changed to the address set by a call to USBHCDSetAddress().
3169//!
3170//! \return The number of bytes returned in the \e pui8Buffer due to the
3171//! request.  This value can be zero if the device did not respond.
3172//
3173//*****************************************************************************
3174uint32_t USBHCDStringDescriptorGet(tUSBHostDevice* psDevice,
3175                                   uint8_t* pui8Buffer, uint32_t ui32Size,
3176                                   uint32_t ui32LangID,
3177                                   uint32_t ui32StringIndex) {
3178    uint32_t ui32BytesReturned;
3179    tUSBRequest sSetupPacket;
3180
3181    //
3182    // Default the number of bytes to zero.
3183    //
3184    ui32BytesReturned = 0;
3185
3186    //
3187    // This is a Standard Device IN request.
3188    //
3189    sSetupPacket.bmRequestType =
3190        USB_RTYPE_DIR_IN | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;
3191
3192    //
3193    // Request a Device Descriptor.
3194    //
3195    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;
3196
3197    //
3198    // Request for a string descriptor.
3199    //
3200    sSetupPacket.wValue = (USB_DTYPE_STRING << 8) | (uint16_t)ui32StringIndex;
3201
3202    //
3203    // Set the language ID.
3204    //
3205    sSetupPacket.wIndex = ui32LangID;
3206
3207    //
3208    // Only request the space available.
3209    //
3210    sSetupPacket.wLength = (uint16_t)ui32Size;
3211
3212    //
3213    // Put the setup packet in the buffer.
3214    //
3215    ui32BytesReturned =
3216        USBHCDControlTransfer(0, &sSetupPacket, psDevice, pui8Buffer, ui32Size,
3217                              psDevice->sDeviceDescriptor.bMaxPacketSize0);
3218
3219    //
3220    // Return the number of bytes in the string.
3221    //
3222    return (ui32BytesReturned);
3223}
3224
3225//*****************************************************************************
3226//
3227//! This function is used to send the set address command to a device.
3228//!
3229//! \param ui32DevIndex is the index of the device whose address is to be
3230//! set.  This value must be 0 to indicate that the device is connected
3231//! directly to the host controller.  Higher values indicate devices connected
3232//!  via a hub.
3233//! \param ui32DevAddress is the new device address to use for a device.
3234//!
3235//! The USBHCDSetAddress() function is used to set the USB device address, once
3236//! a device has been discovered on the bus.  This call is typically issued
3237//! following a USB reset triggered by a call the USBHCDReset().  The
3238//! address passed into this function via the \e ui32DevAddress parameter is
3239//! used for all further communications with the device after this function
3240//! returns.
3241//!
3242//! \return None.
3243//
3244//*****************************************************************************
3245void USBHCDSetAddress(uint32_t ui32DevIndex, uint32_t ui32DevAddress) {
3246    tUSBRequest sSetupPacket;
3247
3248    //
3249    // This is a Standard Device OUT request.
3250    //
3251    sSetupPacket.bmRequestType =
3252        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;
3253
3254    //
3255    // Request a Device Descriptor.
3256    //
3257    sSetupPacket.bRequest = USBREQ_SET_ADDRESS;
3258    sSetupPacket.wValue = ui32DevAddress;
3259
3260    //
3261    // Index is always 0 for device requests.
3262    //
3263    sSetupPacket.wIndex = 0;
3264
3265    //
3266    // Only request the space available.
3267    //
3268    sSetupPacket.wLength = 0;
3269
3270    //
3271    // Put the setup packet in the buffer.
3272    //
3273    USBHCDControlTransfer(0, &sSetupPacket,
3274                          &g_sUSBHCD.psUSBDevice[ui32DevIndex], 0, 0,
3275                          MAX_PACKET_SIZE_EP0);
3276
3277    //
3278    // Must delay 2ms after setting the address.
3279    //
3280    OS_DELAY(g_ui32Tickms * 2);
3281}
3282
3283//*****************************************************************************
3284//
3285//! This function is used to send a Clear Feature request to a device.
3286//!
3287//! \param ui32DevAddress is the USB bus address of the device that will
3288//! receive this request.
3289//! \param ui32Pipe is the pipe that will be used to send the request.
3290//! \param ui32Feature is one of the USB_FEATURE_* definitions.
3291//!
3292//! This function will issue a Clear Feature request to the device indicated
3293//! by the \e ui32DevAddress parameter.  The \e ui32Pipe parameter is the USB
3294//! pipe that should be used to send this request.  The \e ui32Feature
3295//! parameter should be one of the following values:
3296//!
3297//! * \b USB_FEATURE_EP_HALT is used to end a HALT condition on a devices
3298//!   endpoint.
3299//! * \b USB_FEATURE_REMOTE_WAKE is used to disable a device's remote wake
3300//!   feature.
3301//! * \b USB_FEATURE_TEST_MODE is used take the USB device out of test mode.
3302//!
3303//! \return None.
3304//
3305//*****************************************************************************
3306void USBHCDClearFeature(uint32_t ui32DevAddress, uint32_t ui32Pipe,
3307                        uint32_t ui32Feature) {
3308    tUSBRequest sSetupPacket;
3309    uint32_t ui32Index;
3310
3311    //
3312    // Get the index number from the allocated pipe.
3313    //
3314    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);
3315
3316    //
3317    // This is a Standard Device OUT request.
3318    //
3319    sSetupPacket.bmRequestType =
3320        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_ENDPOINT;
3321
3322    //
3323    // Request a Device Descriptor.
3324    //
3325    sSetupPacket.bRequest = USBREQ_CLEAR_FEATURE;
3326    sSetupPacket.wValue = ui32Feature;
3327
3328    //
3329    // Set the endpoint to access.
3330    //
3331    if (ui32Pipe & EP_PIPE_TYPE_IN) {
3332        sSetupPacket.wIndex =
3333            g_sUSBHCD.psUSBINPipes[ui32Index].ui8EPNumber | 0x80;
3334    } else {
3335        sSetupPacket.wIndex = g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8EPNumber;
3336    }
3337
3338    //
3339    // This is always 0.
3340    //
3341    sSetupPacket.wLength = 0;
3342
3343    //
3344    // Put the setup packet in the buffer.
3345    //
3346    USBHCDControlTransfer(0, &sSetupPacket,
3347                          &g_sUSBHCD.psUSBDevice[ui32DevAddress - 1], 0, 0,
3348                          MAX_PACKET_SIZE_EP0);
3349
3350    //
3351    // Set the endpoint to access.
3352    //
3353    if (ui32Pipe & EP_PIPE_TYPE_IN) {
3354        MAP_USBEndpointDataToggleClear(USB0_BASE, IndexToUSBEP(ui32Index + 1),
3355                                       USB_EP_HOST_IN);
3356    } else {
3357        MAP_USBEndpointDataToggleClear(USB0_BASE, IndexToUSBEP(ui32Index + 1),
3358                                       USB_EP_HOST_OUT);
3359    }
3360
3361    //
3362    // Must delay 2ms after clearing the feature.
3363    //
3364    OS_DELAY(g_ui32Tickms * 2);
3365}
3366
3367//*****************************************************************************
3368//
3369//! This function is used to set the current configuration for a device.
3370//!
3371//! \param ui32Index specifies which USB controller to use.
3372//! \param ui32Device is the USB device for this function.
3373//! \param ui32Configuration is one of the devices valid configurations.
3374//!
3375//! This function is used to set the current device configuration for a USB
3376//! device.  The \e ui32Configuration value must be one of the configuration
3377//! indexes that was returned in the configuration descriptor from the device,
3378//! or a value of 0.  If 0 is passed in, the device will return to it's
3379//! addressed state and no longer be in a configured state.  If the value is
3380//! non-zero then the device will change to the requested configuration.
3381//!
3382//! \return None.
3383//
3384//*****************************************************************************
3385void USBHCDSetConfig(uint32_t ui32Index, uint32_t ui32Device,
3386                     uint32_t ui32Configuration) {
3387    tUSBRequest sSetupPacket;
3388    tUSBHostDevice* psDevice;
3389
3390    ASSERT(ui32Index == 0);
3391
3392    psDevice = (tUSBHostDevice*)ui32Device;
3393
3394    //
3395    // This is a Standard Device OUT request.
3396    //
3397    sSetupPacket.bmRequestType =
3398        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;
3399
3400    //
3401    // Request a Device Descriptor.
3402    //
3403    sSetupPacket.bRequest = USBREQ_SET_CONFIG;
3404    sSetupPacket.wValue = ui32Configuration;
3405
3406    //
3407    // Index is always 0 for device requests.
3408    //
3409    sSetupPacket.wIndex = 0;
3410
3411    //
3412    // Only request the space available.
3413    //
3414    sSetupPacket.wLength = 0;
3415
3416    //
3417    // Put the setup packet in the buffer.
3418    //
3419    USBHCDControlTransfer(0, &sSetupPacket, psDevice, 0, 0,
3420                          MAX_PACKET_SIZE_EP0);
3421}
3422
3423//*****************************************************************************
3424//
3425//! This function is used to set the current interface and alternate setting
3426//! for an interface on a device.
3427//!
3428//! \param ui32Index specifies which USB controller to use.
3429//! \param ui32Device is the USB device for this function.
3430//! \param ui32Interface is one of the valid interface numbers for a device.
3431//! \param ui32AltSetting is one of the valid alternate interfaces for the
3432//! \e ui32Interface number.
3433//!
3434//! This function is used to change the alternate setting for one of the valid
3435//! interfaces on a USB device.  The \e ui32Device specifies the device
3436//! instance that was returned when the device was connected.  This call will
3437//! set the USB device's interface based on the \e ui32Interface and
3438//! \e ui32AltSetting.
3439//!
3440//! \b Example: Set the USB device interface 2 to alternate setting 1.
3441//!
3442//! \verbatim
3443//! USBHCDSetInterface(0, ui32Device, 2, 1);
3444//! \endverbatim
3445//!
3446//! \return None.
3447//
3448//*****************************************************************************
3449void USBHCDSetInterface(uint32_t ui32Index, uint32_t ui32Device,
3450                        uint32_t ui32Interface, uint32_t ui32AltSetting) {
3451    tUSBRequest sSetupPacket;
3452    tUSBHostDevice* psDevice;
3453
3454    ASSERT(ui32Index == 0);
3455
3456    psDevice = (tUSBHostDevice*)ui32Device;
3457
3458    //
3459    // This is a Standard Device OUT request.
3460    //
3461    sSetupPacket.bmRequestType =
3462        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_INTERFACE;
3463
3464    //
3465    // Request a Device Descriptor.
3466    //
3467    sSetupPacket.bRequest = USBREQ_SET_INTERFACE;
3468
3469    //
3470    // Index is the interface to access.
3471    //
3472    sSetupPacket.wIndex = ui32Interface;
3473
3474    //
3475    // wValue is the alternate setting.
3476    //
3477    sSetupPacket.wValue = ui32AltSetting;
3478
3479    //
3480    // Only request the space available.
3481    //
3482    sSetupPacket.wLength = 0;
3483
3484    //
3485    // Put the setup packet in the buffer.
3486    //
3487    USBHCDControlTransfer(0, &sSetupPacket, psDevice, 0, 0,
3488                          MAX_PACKET_SIZE_EP0);
3489}
3490
3491//*****************************************************************************
3492//
3493// The internal function to see if a new schedule event should occur.
3494//
3495// This function is called by the main interrupt handler due to start of frame
3496// interrupts to determine if a new scheduler event should be sent to the USB
3497// pipe.
3498//
3499// \return None.
3500//
3501//*****************************************************************************
3502void USBHostCheckPipes(void) {
3503    int32_t i32Idx;
3504
3505    g_ui32CurrentTick++;
3506
3507    for (i32Idx = 0; i32Idx < g_sUSBHCD.ui32NumEndpoints; i32Idx++) {
3508        //
3509        // Skip unused pipes.
3510        //
3511        if (g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type == USBHCD_PIPE_UNUSED) {
3512            continue;
3513        }
3514
3515        //
3516        // If the tick has expired and it has an interval then update it.
3517        //
3518        if ((g_sUSBHCD.psUSBINPipes[i32Idx].ui32Interval != 0) &&
3519            (g_sUSBHCD.psUSBINPipes[i32Idx].ui32NextEventTick ==
3520             g_ui32CurrentTick)) {
3521            //
3522            // Schedule the next event.
3523            //
3524            g_sUSBHCD.psUSBINPipes[i32Idx].ui32NextEventTick +=
3525                g_sUSBHCD.psUSBINPipes[i32Idx].ui32Interval;
3526
3527            //
3528            // If the pipe is IDLE and there is a callback, let the higher
3529            // level drivers know that a new transfer can be scheduled.
3530            //
3531            if ((g_sUSBHCD.psUSBINPipes[i32Idx].iState == ePipeIdle) &&
3532                (g_sUSBHCD.psUSBINPipes[i32Idx].pfnCallback)) {
3533                g_sUSBHCD.psUSBINPipes[i32Idx].pfnCallback(
3534                    IN_PIPE_HANDLE(i32Idx), USB_EVENT_SCHEDULER);
3535            }
3536        }
3537    }
3538}
3539
3540//*****************************************************************************
3541//
3542// The internal USB host mode interrupt handler.
3543//
3544// \param ui32Index is the USB controller associated with this interrupt.
3545// \param ui32Status is the current interrupt status as read via a call to
3546// \e USBIntStatusControl().
3547//
3548// This the main USB interrupt handler called when operating in host mode.
3549// This handler will branch the interrupt off to the appropriate handlers
3550// depending on the current status of the USB controller.
3551//
3552// The two-tiered structure for the interrupt handler ensures that it is
3553// possible to use the same handler code in both host and OTG modes and
3554// means that device code can be excluded from applications that only require
3555// support for USB host mode operation.
3556//
3557// \return None.
3558//
3559//*****************************************************************************
3560void USBHostIntHandlerInternal(uint32_t ui32Index, uint32_t ui32Status) {
3561    uint32_t ui32EPStatus, ui32DMAIntStatus, ui32Idx, ui32DevIndex;
3562    static uint32_t ui32SOFDivide = 0;
3563    int32_t i32ClassDrvr;
3564
3565    //
3566    // By default, assume we are dealing with the device directly connected
3567    // to the host controller and that we need to notify its class driver of
3568    // this interrupt.
3569    //
3570    g_sUSBHCD.psUSBDevice[0].ui32Flags |= USBHDEV_FLAG_NOTIFYINT;
3571
3572    if (ui32Status & USB_INTCTRL_SOF) {
3573        //
3574        // Indicate that a start of frame has occurred.
3575        //
3576        g_sUSBHCD.ui32IntEvents |= INT_EVENT_SOF;
3577    }
3578
3579    //
3580    // A power fault has occurred so notify the application.
3581    //
3582    if (ui32Status & USB_INTCTRL_POWER_FAULT) {
3583        //
3584        // Indicate that a power fault has occurred.
3585        //
3586        g_sUSBHCD.ui32IntEvents |= INT_EVENT_POWER_FAULT;
3587
3588        //
3589        // Turn off power to the bus.
3590        //
3591        MAP_USBHostPwrDisable(USB0_BASE);
3592
3593        //
3594        // Disable USB interrupts.
3595        //
3596        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
3597
3598        return;
3599    }
3600
3601    //
3602    // In the event of a USB VBUS error, end the session and remove power to
3603    // the device.
3604    //
3605    if (ui32Status & USB_INTCTRL_VBUS_ERR) {
3606        //
3607        // Set the VBUS error event.  We deliberately clear all other events
3608        // since this one means anything else that is outstanding is
3609        // irrelevant.
3610        //
3611        g_sUSBHCD.ui32IntEvents = INT_EVENT_VBUS_ERR;
3612        return;
3613    }
3614
3615    //
3616    // Received a reset from the host.
3617    //
3618    if (ui32Status & USB_INTCTRL_BABBLE) {}
3619
3620    //
3621    // Suspend was signaled on the bus.
3622    //
3623    if (ui32Status & USB_INTCTRL_SUSPEND) {}
3624
3625    //
3626    // Start the session.
3627    //
3628    if (ui32Status & USB_INTCTRL_SESSION) {
3629        //
3630        // Power the USB bus.
3631        //
3632        MAP_USBHostPwrEnable(USB0_BASE);
3633
3634        USBOTGSessionRequest(USB0_BASE, true);
3635    }
3636
3637    //
3638    // Resume was signaled on the bus.
3639    //
3640    if (ui32Status & USB_INTCTRL_RESUME) {}
3641
3642    //
3643    // Device connected so tell the main routine to issue a reset.
3644    //
3645    if (ui32Status & USB_INTCTRL_CONNECT) {
3646        //
3647        // Set the connect flag and clear disconnect if it happens to be set.
3648        //
3649        g_sUSBHCD.ui32IntEvents |= INT_EVENT_CONNECT;
3650        g_sUSBHCD.ui32IntEvents &= ~INT_EVENT_DISCONNECT;
3651
3652        //
3653        // Power the USB bus.
3654        //
3655        MAP_USBHostPwrEnable(USB0_BASE);
3656    }
3657
3658    //
3659    // Handle the ID detection so that the ID pin can be used as a
3660    // GPIO in eUSBModeHost.
3661    //
3662    if (ui32Status & USB_INTCTRL_MODE_DETECT) {
3663        //
3664        // If in eUSBModeHost mode then switch back to OTG detection
3665        // so that VBUS can be monitored but free up the ID pin.
3666        //
3667        if (g_iUSBMode == eUSBModeHost) {
3668            USBOTGMode(USB0_BASE);
3669        }
3670    }
3671
3672    //
3673    // Device was unplugged.
3674    //
3675    if (ui32Status & USB_INTCTRL_DISCONNECT) {
3676        //
3677        // Set the disconnect flag and clear connect if it happens to be set.
3678        //
3679        g_sUSBHCD.ui32IntEvents |= INT_EVENT_DISCONNECT;
3680        g_sUSBHCD.ui32IntEvents &= ~INT_EVENT_CONNECT;
3681    }
3682
3683    //
3684    // Start of Frame was received.
3685    //
3686    if (ui32Status & USB_INTCTRL_SOF) {
3687        //
3688        // Increment the global Start of Frame counter.
3689        //
3690        g_ui32USBSOFCount++;
3691
3692        //
3693        // Increment our SOF divider.
3694        //
3695        ui32SOFDivide++;
3696
3697        //
3698        // Have we counted enough SOFs to allow us to call the tick function?
3699        //
3700        if (ui32SOFDivide == USB_SOF_TICK_DIVIDE) {
3701            //
3702            // Yes - reset the divider and call the SOF tick handler.
3703            //
3704            ui32SOFDivide = 0;
3705            InternalUSBStartOfFrameTick(USB_SOF_TICK_DIVIDE);
3706        }
3707    }
3708
3709    //
3710    // Handle the LPM interrupt
3711    //
3712    ui32Status = USBLPMIntStatus(USB0_BASE);
3713
3714    if (ui32Status) {
3715        //
3716        // Set the LPM interrupt event and clear the pending event.
3717        //
3718        g_sUSBHCD.ui32IntEvents |= INT_EVENT_LPM;
3719        g_sUSBHCD.ui32IntEvents &= ~INT_EVENT_LPM_PEND;
3720
3721        //
3722        // Anything other than and acknowledge means that the transfer
3723        // was not complete for some reason.
3724        //
3725        for (ui32Idx = 0; ui32Idx < (MAX_USB_DEVICES + 1); ui32Idx++) {
3726            if ((ui32Status != USB_INTLPM_ACK) &&
3727                (g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags &
3728                 USBHDEV_FLAG_LPMPEND)) {
3729                g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags |=
3730                    USBHDEV_FLAG_LPMERROR;
3731            }
3732            g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags &= ~USBHDEV_FLAG_LPMPEND;
3733        }
3734    }
3735
3736    //
3737    // Check to see if any DMA transfers are pending
3738    //
3739    ui32DMAIntStatus = USBLibDMAIntStatus(g_sUSBHCD.psDMAInstance);
3740
3741    if (ui32DMAIntStatus) {
3742        //
3743        // Handle any DMA interrupt processing.
3744        //
3745        USBLibDMAIntHandler(g_sUSBHCD.psDMAInstance, ui32DMAIntStatus);
3746
3747        for (ui32Idx = 0; ui32Idx < MAX_NUM_PIPES; ui32Idx++) {
3748            if ((g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReadDMAWait) ||
3749                (g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReadDMA)) {
3750                //
3751                // If the DMA channel transfer is complete, send an ack.
3752                //
3753                if (USBLibDMAChannelStatus(
3754                        g_sUSBHCD.psDMAInstance,
3755                        g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel) ==
3756                    USBLIBSTATUS_DMA_COMPLETE) {
3757                    //
3758                    // Acknowledge the IN request.
3759                    //
3760                    MAP_USBHostEndpointDataAck(USB0_BASE,
3761                                               IndexToUSBEP(ui32Idx + 1));
3762
3763                    //
3764                    // If using uDMA then the endpoint status interrupt will
3765                    // not occur.  So process the data ready event here.
3766                    //
3767                    g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeDataReady;
3768
3769                    //
3770                    // Only call a handler if one is present.
3771                    //
3772                    if (g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback) {
3773                        g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
3774                            IN_PIPE_HANDLE(ui32Idx), USB_EVENT_RX_AVAILABLE);
3775                    }
3776
3777                    //
3778                    // Remember that we need to notify this device's class
3779                    // driver that an interrupt occurred.
3780                    //
3781                    g_sUSBHCD.psUSBINPipes[ui32Idx].psDevice->ui32Flags |=
3782                        USBHDEV_FLAG_NOTIFYINT;
3783                }
3784            }
3785            if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState == ePipeWriteDMASend) {
3786                //
3787                // If the uDMA channel transfer is complete, then tell
3788                // the USB controller to go ahead and send the data
3789                //
3790                if (USBLibDMAChannelStatus(
3791                        g_sUSBHCD.psDMAInstance,
3792                        g_sUSBHCD.psUSBOUTPipes[ui32Idx].ui8DMAChannel) &
3793                    USBLIBSTATUS_DMA_COMPLETE) {
3794                    MAP_USBEndpointDataSend(
3795                        USB0_BASE, IndexToUSBEP(ui32Idx + 1), USB_TRANS_OUT);
3796
3797                    //
3798                    // Now waiting on the final endpoint interrupt.
3799                    //
3800                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeWriteDMAWait;
3801                }
3802            } else if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState ==
3803                       ePipeWriteDMA) {
3804                //
3805                // Data was transmitted successfully.
3806                //
3807                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeDataSent;
3808
3809                //
3810                // Only call a handler if one is present.
3811                //
3812                if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback) {
3813                    //
3814                    // Notify the pipe that its last transaction was completed.
3815                    //
3816                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
3817                        OUT_PIPE_HANDLE(ui32Idx), USB_EVENT_TX_COMPLETE);
3818                }
3819            }
3820        }
3821    }
3822
3823    //
3824    // Get the current endpoint interrupt status.
3825    //
3826    ui32Status = MAP_USBIntStatusEndpoint(USB0_BASE);
3827
3828    //
3829    // Handle end point 0 interrupts.
3830    //
3831    if (ui32Status & USB_INTEP_0) {
3832        //
3833        // Indicate that a start of frame has occurred.
3834        //
3835        g_sUSBHCD.ui32IntEvents |= INT_EVENT_ENUM;
3836    }
3837
3838    for (ui32Idx = 0; ui32Idx < MAX_NUM_PIPES; ui32Idx++) {
3839        //
3840        // Check the next pipe, the first time through this will clear out
3841        // any interrupts dealing with endpoint zero since it was handled
3842        // above.
3843        //
3844        ui32Status >>= 1;
3845
3846        //
3847        // Break out if there are no more pending interrupts.
3848        //
3849        if (ui32Status == 0) {
3850            break;
3851        }
3852
3853        //
3854        // Check the status of the receive(IN) pipes.
3855        //
3856        if (ui32Status & 0x10000) {
3857            //
3858            // Clear the status flag for the IN Pipe.
3859            //
3860            ui32Status &= ~0x10000;
3861
3862            //
3863            // Read the status of the endpoint connected to this pipe.
3864            //
3865            ui32EPStatus =
3866                MAP_USBEndpointStatus(USB0_BASE, IndexToUSBEP(ui32Idx + 1));
3867
3868            //
3869            // Check if the device stalled the request.
3870            //
3871            if (ui32EPStatus & USB_HOST_IN_STALL) {
3872                //
3873                // Clear the stall condition on this endpoint pipe.
3874                //
3875                MAP_USBHostEndpointStatusClear(
3876                    USB0_BASE, IndexToUSBEP(ui32Idx + 1), USB_HOST_IN_STALL);
3877
3878                //
3879                // Save the STALLED state.
3880                //
3881                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeStalled;
3882
3883                //
3884                // Notify the pipe that it was stalled.
3885                //
3886                if (g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback) {
3887                    g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
3888                        IN_PIPE_HANDLE(ui32Idx), USB_EVENT_STALL);
3889                }
3890            } else if (ui32EPStatus & USB_HOST_IN_ERROR) {
3891                //
3892                // We can no longer communicate with this device for some
3893                // reason.  It may have been disconnected from a hub, for
3894                // example.  Merely clear the status and continue.
3895                //
3896                USBHostEndpointStatusClear(USB0_BASE, IndexToUSBEP(ui32Idx + 1),
3897                                           USB_HOST_IN_ERROR);
3898
3899                //
3900                // Save the STALLED state.
3901                //
3902                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeError;
3903
3904                //
3905                // Notify the pipe that it was stalled.
3906                //
3907                if (g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback) {
3908                    g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
3909                        IN_PIPE_HANDLE(ui32Idx), USB_EVENT_ERROR);
3910                }
3911            }
3912            //
3913            // Handle the case where the pipe is reading a single packet.
3914            //
3915            else if (g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReadDMA) {
3916                void* pvAddr;
3917
3918                //
3919                // Enable the DMA channel and wait for it to complete.
3920                //
3921                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeReadDMAWait;
3922
3923                pvAddr = USBLibDMAAddrGet(
3924                    g_sUSBHCD.psDMAInstance,
3925                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel);
3926
3927                //
3928                // Save the amount of data available.
3929                //
3930                g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead =
3931                    USBEndpointDataAvail(USB0_BASE, IndexToUSBEP(ui32Idx + 1));
3932
3933                //
3934                // Only request what is available.
3935                //
3936                if (g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead <=
3937                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui32ReadSize) {
3938                    //
3939                    // Reset the transfer size.
3940                    //
3941                    USBLibDMATransfer(
3942                        g_sUSBHCD.psDMAInstance,
3943                        g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel, pvAddr,
3944                        g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead);
3945                } else {
3946                    //
3947                    // The transfer size did not change, this leaves some
3948                    // data in the FIFO.
3949                    //
3950                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead =
3951                        g_sUSBHCD.psUSBINPipes[ui32Idx].ui32ReadSize;
3952                }
3953
3954                USBLibDMAChannelEnable(
3955                    g_sUSBHCD.psDMAInstance,
3956                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel);
3957            } else if (g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReading) {
3958                //
3959                // Data is available.
3960                //
3961                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeDataReady;
3962
3963                //
3964                // Read the data out of the USB endpoint interface into the
3965                // buffer provided by the caller to USBHCDPipeRead() or
3966                // USBHCDPipeSchedule() if a buffer was provided already.
3967                //
3968                if (g_sUSBHCD.psUSBINPipes[ui32Idx].pui8ReadPtr) {
3969                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead =
3970                        g_sUSBHCD.psUSBINPipes[ui32Idx].ui32ReadSize;
3971
3972                    USBEndpointDataGet(
3973                        USB0_BASE, IndexToUSBEP(ui32Idx + 1),
3974                        g_sUSBHCD.psUSBINPipes[ui32Idx].pui8ReadPtr,
3975                        &g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead);
3976                }
3977
3978                //
3979                // Notify the pipe that its last transaction was completed.
3980                //
3981                if (g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback) {
3982                    g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
3983                        IN_PIPE_HANDLE(ui32Idx), USB_EVENT_RX_AVAILABLE);
3984                }
3985            }
3986
3987            //
3988            // Remember that we need to notify this device's class
3989            // driver that an interrupt occurred.
3990            //
3991            g_sUSBHCD.psUSBINPipes[ui32Idx].psDevice->ui32Flags |=
3992                USBHDEV_FLAG_NOTIFYINT;
3993        }
3994
3995        //
3996        // Check the status of the transmit(OUT) pipes.
3997        //
3998        if (ui32Status & 1) {
3999            //
4000            // Read the status of the endpoint connected to this pipe.
4001            //
4002            ui32EPStatus =
4003                MAP_USBEndpointStatus(USB0_BASE, IndexToUSBEP(ui32Idx + 1));
4004
4005            //
4006            // Check if the device stalled the request.
4007            //
4008            if (ui32EPStatus & USB_HOST_OUT_STALL) {
4009                //
4010                // Clear the stall condition on this endpoint pipe.
4011                //
4012                MAP_USBHostEndpointStatusClear(
4013                    USB0_BASE, IndexToUSBEP(ui32Idx + 1), USB_HOST_OUT_STALL);
4014
4015                //
4016                // Save the STALLED state.
4017                //
4018                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeStalled;
4019
4020                //
4021                // Only call a handler if one is present.
4022                //
4023                if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback) {
4024                    //
4025                    // Notify the pipe that it was stalled.
4026                    //
4027                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
4028                        OUT_PIPE_HANDLE(ui32Idx), USB_EVENT_STALL);
4029                }
4030            } else if (ui32EPStatus & USB_HOST_OUT_ERROR) {
4031                //
4032                // Clear the error condition on this endpoint pipe.
4033                //
4034                MAP_USBHostEndpointStatusClear(
4035                    USB0_BASE, IndexToUSBEP(ui32Idx + 1), USB_HOST_OUT_ERROR);
4036
4037                //
4038                // Save the Pipes error state.
4039                //
4040                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeError;
4041
4042                //
4043                // Only call a handler if one is present.
4044                //
4045                if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback) {
4046                    //
4047                    // Notify the pipe that had an error.
4048                    //
4049                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
4050                        OUT_PIPE_HANDLE(ui32Idx), USB_EVENT_ERROR);
4051                }
4052            } else if ((g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState ==
4053                        ePipeWriting) ||
4054                       (g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState ==
4055                        ePipeWriteDMAWait)) {
4056                //
4057                // Data was transmitted successfully.
4058                //
4059                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeDataSent;
4060
4061                //
4062                // Only call a handler if one is present.
4063                //
4064                if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback) {
4065                    //
4066                    // Notify the pipe that its last transaction was completed.
4067                    //
4068                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
4069                        OUT_PIPE_HANDLE(ui32Idx), USB_EVENT_TX_COMPLETE);
4070                }
4071            }
4072
4073            //
4074            // Clear the stall condition on this endpoint pipe.
4075            //
4076            MAP_USBHostEndpointStatusClear(USB0_BASE, IndexToUSBEP(ui32Idx + 1),
4077                                           ui32EPStatus & USB_HOST_OUT_STATUS);
4078            //
4079            // Remember that we need to notify this device's class
4080            // driver that an interrupt occurred.
4081            //
4082            if (g_sUSBHCD.psUSBOUTPipes[ui32Idx].psDevice) {
4083                g_sUSBHCD.psUSBINPipes[ui32Idx].psDevice->ui32Flags |=
4084                    USBHDEV_FLAG_NOTIFYINT;
4085            }
4086        }
4087    }
4088
4089    //
4090    // Send back notifications to any class driver whose endpoint required
4091    // service during the handler.
4092    //
4093    for (ui32DevIndex = 0; ui32DevIndex <= MAX_USB_DEVICES; ui32DevIndex++) {
4094        //
4095        // Which class driver does this device use?
4096        //
4097        i32ClassDrvr = g_pi32USBHActiveDriver[ui32DevIndex];
4098
4099        //
4100        // If a class driver is in use, and one of its endpoints was serviced
4101        // and the class driver has an interrupt callback...
4102        //
4103        if ((i32ClassDrvr >= 0) &&
4104            (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags &
4105             USBHDEV_FLAG_NOTIFYINT) &&
4106            (g_sUSBHCD.ppsClassDrivers[i32ClassDrvr]->pfnIntHandler)) {
4107            //
4108            // ...call the class driver's interrupt notification callback.
4109            //
4110            g_sUSBHCD.ppsClassDrivers[i32ClassDrvr]->pfnIntHandler(
4111                g_ppvDriverInstance[ui32DevIndex]);
4112        }
4113    }
4114}
4115
4116//*****************************************************************************
4117//
4118//! The USB host mode interrupt handler for controller index 0.
4119//!
4120//! This the main USB interrupt handler entry point.  This handler will branch
4121//! the interrupt off to the appropriate handlers depending on the current
4122//! status of the USB controller.   This function must be placed in the
4123//! interrupt table in order for the USB Library host stack to function.
4124//!
4125//! \return None.
4126//
4127//*****************************************************************************
4128void USB0HostIntHandler(void) {
4129    uint32_t ui32Status;
4130
4131    //
4132    // Get the control interrupt status.
4133    //
4134    ui32Status = MAP_USBIntStatusControl(USB0_BASE);
4135
4136    //
4137    // Call the internal handler to process the interrupts.
4138    //
4139    USBHostIntHandlerInternal(0, ui32Status);
4140}
4141
4142//*****************************************************************************
4143//
4144//! This function opens the class driver.
4145//!
4146//! \param ui32Index specifies which USB controller to use.
4147//! \param ui32DeviceNum is the device number for the driver to load.
4148//!
4149//! This function opens the driver needed based on the class value found in
4150//! the device's interface descriptor.
4151//!
4152//! \return This function returns -1 if no driver is found, or it returns the
4153//! index of the driver found in the list of host class drivers.
4154//
4155//*****************************************************************************
4156static int32_t USBHCDOpenDriver(uint32_t ui32Index, uint32_t ui32DeviceNum) {
4157    int32_t i32Driver;
4158    uint32_t ui32Class;
4159    tInterfaceDescriptor* psInterface;
4160    tEventInfo sEvent;
4161
4162    ASSERT(ui32Index == 0);
4163
4164    //
4165    // Get the interface descriptor.
4166    //
4167    psInterface = USBDescGetInterface(
4168        g_sUSBHCD.psUSBDevice[ui32DeviceNum].psConfigDescriptor,
4169        g_sUSBHCD.psUSBDevice[ui32DeviceNum].ui32Interface, USB_DESC_ANY);
4170
4171    //
4172    // Read the interface class.
4173    //
4174    ui32Class = psInterface->bInterfaceClass;
4175
4176    //
4177    // Search through the Host Class driver list for the devices class.
4178    //
4179    for (i32Driver = 0; i32Driver < g_sUSBHCD.ui32NumClassDrivers;
4180         i32Driver++) {
4181        //
4182        // If a driver was found call the open for this driver and save which
4183        // driver is in use.
4184        //
4185        if (g_sUSBHCD.ppsClassDrivers[i32Driver]->ui32InterfaceClass ==
4186            ui32Class) {
4187            //
4188            // Call the open function for the class driver.
4189            //
4190            g_ppvDriverInstance[ui32DeviceNum] =
4191                g_sUSBHCD.ppsClassDrivers[i32Driver]->pfnOpen(
4192                    &g_sUSBHCD.psUSBDevice[ui32DeviceNum]);
4193
4194            //
4195            // If the driver was successfully loaded then break out of the
4196            // loop.
4197            //
4198            if (g_ppvDriverInstance[ui32DeviceNum] != 0) {
4199                break;
4200            }
4201        }
4202    }
4203
4204    //
4205    // If no drivers were found then return -1 to indicate an invalid
4206    // driver instance.
4207    //
4208    if (i32Driver == g_sUSBHCD.ui32NumClassDrivers) {
4209        //
4210        // Send an unknown connection event.
4211        //
4212        SendUnknownConnect(ui32Index, (ui32Index << 16) | ui32DeviceNum);
4213
4214        //
4215        // Indicate that no driver was found.
4216        //
4217        i32Driver = -1;
4218    } else {
4219        //
4220        // If the connect event is enabled then send the event.
4221        //
4222        sEvent.ui32Event = USB_EVENT_CONNECTED;
4223        sEvent.ui32Instance = (ui32Index << 16) | ui32DeviceNum;
4224        InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_CONNECT);
4225    }
4226
4227    return (i32Driver);
4228}
4229
4230//*****************************************************************************
4231//
4232// This function will send an event to a registered event driver.
4233//
4234// \param ui32Index specifies which USB controller to use.
4235// \param psEvent is a pointer to the event structure to send.
4236//
4237// This function is only used internally to the USB library and will check
4238// if an event driver is registered and send on the event.
4239//
4240// Note: This function should not be called outside of the USB library.
4241//
4242// \return None.
4243//
4244//*****************************************************************************
4245void InternalUSBHCDSendEvent(uint32_t ui32Index, tEventInfo* psEvent,
4246                             uint32_t ui32EvFlag) {
4247    //
4248    // Make sure that an event driver has been registered.
4249    //
4250    if ((g_sUSBHCD.i32EventDriver != -1) &&
4251        (g_sUSBHCD.ppsClassDrivers[g_sUSBHCD.i32EventDriver]->pfnIntHandler) &&
4252        (g_sUSBHCD.ui32EventEnables & ui32EvFlag)) {
4253        g_sUSBHCD.ppsClassDrivers[g_sUSBHCD.i32EventDriver]->pfnIntHandler(
4254            psEvent);
4255    }
4256}
4257
4258//*****************************************************************************
4259//
4260// This function handles the necessary clean up for device disconnect.
4261//
4262// \param ui32Index is the device number for the device that was disconnected.
4263//
4264// This function handles all of the necessary clean up after a device
4265// disconnect has been detected by the stack.  This includes calling back the
4266// appropriate driver if necessary.
4267//
4268// \return None.
4269//
4270//*****************************************************************************
4271static void USBHCDDeviceDisconnected(uint32_t ui32Index,
4272                                     uint32_t ui32DevIndex) {
4273    tEventInfo sEvent;
4274
4275    ASSERT(ui32Index == 0);
4276    ASSERT(ui32DevIndex <= MAX_USB_DEVICES);
4277
4278    //
4279    // If there is an event driver with a valid event handler and the
4280    // USBHCD_EVFLAG_DISCNCT is enabled, then call the registered event
4281    // handler.
4282    //
4283    sEvent.ui32Event = USB_EVENT_DISCONNECTED;
4284    sEvent.ui32Instance = (ui32Index << 16) | ui32DevIndex;
4285    InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_DISCNCT);
4286
4287    //
4288    // Reset the class.
4289    //
4290    g_sUSBHCD.ui32Class = USB_CLASS_EVENTS;
4291
4292    //
4293    // Free the memory used by the configuration descriptor.
4294    //
4295    ConfigDescFree(&g_sUSBHCD.psUSBDevice[ui32DevIndex]);
4296
4297    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags = 0;
4298    g_sUSBHCD.psUSBDevice[ui32DevIndex].bConfigRead = false;
4299
4300    //
4301    // Reset the max packet size so that this will be re-read from new devices.
4302    //
4303    g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bMaxPacketSize0 = 0;
4304
4305    //
4306    // No longer have a device descriptor.
4307    //
4308    g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bLength = 0;
4309
4310    //
4311    // No longer addressed.
4312    //
4313    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address = 0;
4314
4315    //
4316    // If this was an active driver then close it out.
4317    //
4318    if (g_pi32USBHActiveDriver[ui32DevIndex] >= 0) {
4319        //
4320        // Call the driver Close entry point.
4321        //
4322        g_sUSBHCD.ppsClassDrivers[g_pi32USBHActiveDriver[ui32DevIndex]]
4323            ->pfnClose(g_ppvDriverInstance[ui32DevIndex]);
4324
4325        //
4326        // No active driver now present.
4327        //
4328        g_pi32USBHActiveDriver[ui32DevIndex] = -1;
4329        g_ppvDriverInstance[ui32DevIndex] = 0;
4330    }
4331
4332    //
4333    // This call is necessary for OTG controllers to know that the host
4334    // stack has completed handling the disconnect of the device before
4335    // removing power and returning to a state that can allow OTG
4336    // negotiations once again.
4337    // We only do this if the disconnected device
4338    // was attached directly to us (device index 0).
4339    //
4340    if ((ui32DevIndex == 0) && (g_iUSBMode == eUSBModeOTG)) {
4341        OTGDeviceDisconnect(0);
4342    }
4343}
4344
4345//*****************************************************************************
4346//
4347//! This function is the main routine for the Host Controller Driver.
4348//!
4349//! This function is the main routine for the host controller driver, and must
4350//! be called periodically by the main application outside of a callback
4351//! context.  This allows for a simple cooperative system to access the the
4352//! host controller driver interface without the need for an RTOS.  All time
4353//! critical operations are handled in interrupt context but all blocking
4354//! operations are run from the this function to allow them to block and wait
4355//! for completion without holding off other interrupts.
4356//!
4357//! \return None.
4358//
4359//*****************************************************************************
4360void USBHCDMain(void) {
4361    tUSBHDeviceState iOldState;
4362    int32_t i32Dev;
4363    tEventInfo sEvent;
4364
4365    //
4366    // Save the old state to detect changes properly.
4367    //
4368    iOldState = g_sUSBHCD.piDeviceState[0];
4369
4370    //
4371    // Fix up the state if any important interrupt events occurred.
4372    //
4373    if (g_sUSBHCD.ui32IntEvents) {
4374        //
4375        // Disable the USB interrupt.
4376        //
4377        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
4378
4379        if (g_sUSBHCD.ui32IntEvents & INT_EVENT_POWER_FAULT) {
4380            //
4381            // A power fault has occurred so notify the application if there
4382            // is an event handler and the event has been enabled.
4383            //
4384            sEvent.ui32Event = USB_EVENT_POWER_FAULT;
4385            sEvent.ui32Instance = 0;
4386            InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_PWRFAULT);
4387
4388            g_sUSBHCD.piDeviceState[0] = eHCDPowerFault;
4389        } else if (g_sUSBHCD.ui32IntEvents & INT_EVENT_VBUS_ERR) {
4390            //
4391            // A VBUS error has occurred.  This event trumps connect and
4392            // disconnect since it will cause a controller reset.
4393            //
4394            g_sUSBHCD.piDeviceState[0] = eHCDVBUSError;
4395        } else {
4396            //
4397            // Has a device connected?
4398            //
4399            if (g_sUSBHCD.ui32IntEvents & INT_EVENT_CONNECT) {
4400                g_sUSBHCD.piDeviceState[0] = eHCDDevReset;
4401                g_sUSBHCD.psUSBDevice[0].ui8Hub = 0;
4402                g_sUSBHCD.psUSBDevice[0].ui8HubPort = 0;
4403            } else {
4404                //
4405                // Has a device disconnected?
4406                //
4407                if (g_sUSBHCD.ui32IntEvents & INT_EVENT_DISCONNECT) {
4408                    g_sUSBHCD.piDeviceState[0] = eHCDDevDisconnected;
4409                }
4410            }
4411
4412            //
4413            // Handle the start of frame event
4414            //
4415            if (g_sUSBHCD.ui32IntEvents & INT_EVENT_SOF) {
4416                //
4417                // If the connect event is enabled then send the event.
4418                //
4419                sEvent.ui32Event = USB_EVENT_SOF;
4420                sEvent.ui32Instance = 0;
4421                InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_SOF);
4422
4423                USBHostCheckPipes();
4424
4425                //
4426                // Call the hub driver to have it perform any necessary
4427                // processing to handle downstream devices.
4428                //
4429                USBHHubMain();
4430            }
4431
4432            //
4433            // Handle LPM interrupt events.
4434            //
4435            if (g_sUSBHCD.ui32IntEvents & INT_EVENT_LPM) {
4436                //
4437                // There should be a pending LPM request.
4438                //
4439                ASSERT((g_sUSBHCD.ui32IntEvents & INT_EVENT_LPM_PEND) != 0);
4440
4441                for (i32Dev = 0; i32Dev < MAX_USB_DEVICES + 1; i32Dev++) {
4442                    //
4443                    // Find the device with the pending LPM request.
4444                    //
4445                    if (g_sUSBHCD.psUSBDevice[i32Dev].ui32Flags &
4446                        USBHDEV_FLAG_LPMPEND) {
4447                        //
4448                        // Clear the pending event at the device level, this
4449                        // leaves the error set if it was already set.
4450                        //
4451                        g_sUSBHCD.psUSBDevice[i32Dev].ui32Flags &=
4452                            ~USBHDEV_FLAG_LPMPEND;
4453
4454                        //
4455                        // Clear the pending request and event at the host
4456                        // controller level.
4457                        //
4458                        g_sUSBHCD.ui32IntEvents &=
4459                            ~(INT_EVENT_LPM_PEND | INT_EVENT_LPM);
4460                    }
4461                }
4462            }
4463        }
4464
4465        //
4466        // Clear the flags.
4467        //
4468        g_sUSBHCD.ui32IntEvents = 0;
4469
4470        //
4471        // Enable the USB interrupt.
4472        //
4473        OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
4474    }
4475
4476    //
4477    // Process the state machine for each connected device.  Yes, the exit
4478    // condition for this loop is correct since we support (MAX_USB_DEVICES+1)
4479    // devices (the hub counts as one).
4480    //
4481    for (i32Dev = 0; i32Dev <= MAX_USB_DEVICES; i32Dev++) {
4482        //
4483        // If this is not the first device (i.e. the one directly connected to
4484        // the host controller) then set the old state to the current state
4485        // since we won't have mucked with it in any of the previous code.
4486        //
4487        if (i32Dev != 0) {
4488            iOldState = g_sUSBHCD.piDeviceState[i32Dev];
4489        }
4490
4491        //
4492        // Process the state machine for this device.
4493        //
4494        ProcessUSBDeviceStateMachine(iOldState, i32Dev);
4495    }
4496}
4497
4498static void ProcessUSBDeviceStateMachine(tUSBHDeviceState iOldState,
4499                                         uint32_t ui32DevIndex) {
4500    switch (g_sUSBHCD.piDeviceState[ui32DevIndex]) {
4501    //
4502    // There was a power fault condition so shut down and wait for the
4503    // application to re-initialized the system.
4504    //
4505    case eHCDPowerFault: {
4506        break;
4507    }
4508
4509    //
4510    // There was a VBUS error so handle it.
4511    //
4512    case eHCDVBUSError: {
4513        //
4514        // Disable USB interrupts.
4515        //
4516        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
4517
4518        //
4519        // If there was a device in any state of connection then indicate
4520        // that it has been disconnected.
4521        //
4522        if ((iOldState != eHCDIdle) && (iOldState != eHCDPowerFault)) {
4523            //
4524            // Handle device disconnect.
4525            //
4526            USBHCDDeviceDisconnected(0, ui32DevIndex);
4527        }
4528
4529        //
4530        // Reset the controller.
4531        //
4532        MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_USB0);
4533
4534        //
4535        // Wait for 100ms before trying to re-power the device.
4536        //
4537        OS_DELAY(g_ui32Tickms * 100);
4538
4539        //
4540        // Re-initialize the HCD.
4541        //
4542        USBHCDInitInternal(0, g_sUSBHCD.pvPool, g_sUSBHCD.ui32PoolSize);
4543
4544        break;
4545    }
4546    //
4547    // Trigger a reset to the connected device.
4548    //
4549    case eHCDDevReset: {
4550        if (!ui32DevIndex) {
4551            //
4552            // Trigger a Reset.  This is only ever done for devices
4553            // attached directly to the controller.
4554            //
4555            DEBUG_OUTPUT("USB reset.\n");
4556            USBHCDReset(0);
4557        }
4558
4559        //
4560        // The state moves to connected but not configured.
4561        //
4562        g_sUSBHCD.piDeviceState[0] = eHCDDevConnected;
4563
4564        //
4565        // Remember that we don't have a valid configuration descriptor
4566        // yet.
4567        //
4568        g_sUSBHCD.psUSBDevice[0].bConfigRead = false;
4569
4570        break;
4571    }
4572    //
4573    // Device connection has been established now start enumerating
4574    // the device.
4575    //
4576    case eHCDDevConnected:
4577    case eHCDDevConnectedHub: {
4578        //
4579        // First check if we have read the device descriptor at all
4580        // before proceeding.
4581        //
4582        if (g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bLength ==
4583            0) {
4584            //
4585            // Initialize a request for the device descriptor.
4586            //
4587            DEBUG_OUTPUT("Connection %d - getting device descriptor\n",
4588                         ui32DevIndex);
4589
4590            //
4591            // Hub enumeration has already set the speed so do not
4592            // override the setting here.
4593            //
4594            if (g_sUSBHCD.piDeviceState[ui32DevIndex] == eHCDDevConnected) {
4595                //
4596                // Remember the speed of this device to ensure endpoints
4597                // are properly configured.
4598                //
4599                switch (USBHostSpeedGet(USB0_BASE)) {
4600                case USB_HIGH_SPEED: {
4601                    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed =
4602                        USB_EP_SPEED_HIGH;
4603                    break;
4604                }
4605                case USB_FULL_SPEED: {
4606                    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed =
4607                        USB_EP_SPEED_FULL;
4608                    break;
4609                }
4610                default: {
4611                    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed =
4612                        USB_EP_SPEED_LOW;
4613                    break;
4614                }
4615                }
4616            }
4617
4618            if (USBHCDGetDeviceDescriptor(
4619                    0, &g_sUSBHCD.psUSBDevice[ui32DevIndex]) == 0) {
4620                //
4621                // If the device descriptor cannot be read then the device
4622                // will be treated as unknown.
4623                //
4624                g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevError;
4625
4626                DEBUG_OUTPUT("Connection %d - failed to get descriptor\n",
4627                             ui32DevIndex);
4628
4629                //
4630                // Send an unknown connection event to let the application
4631                // know that there is a device connected but return no
4632                // zero for the instance.
4633                //
4634                SendUnknownConnect(0, 0);
4635
4636                //
4637                // If the device is connected via a hub, tell the hub
4638                // driver that we experienced an error enumerating the
4639                // device.
4640                //
4641                if (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub) {
4642                    USBHHubEnumerationError(
4643                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
4644                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
4645                }
4646            }
4647        }
4648        //
4649        // If we have the device descriptor then move on to setting
4650        // the address of the device.
4651        //
4652        else if (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address == 0) {
4653            DEBUG_OUTPUT("Connection %d - setting address %d\n", ui32DevIndex,
4654                         ui32DevIndex + 1);
4655
4656            //
4657            // Send the set address command.
4658            //
4659            USBHCDSetAddress(ui32DevIndex, (ui32DevIndex + 1));
4660
4661            //
4662            // Save the address.
4663            //
4664            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address =
4665                (ui32DevIndex + 1);
4666
4667            //
4668            // Move on to the addressed state.
4669            //
4670            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevAddressed;
4671        }
4672        break;
4673    }
4674    case eHCDDevAddressed: {
4675        //
4676        // First check if we have read the configuration descriptor.
4677        //
4678        if (!g_sUSBHCD.psUSBDevice[ui32DevIndex].bConfigRead) {
4679            DEBUG_OUTPUT("Connection %d - getting config descriptor\n",
4680                         ui32DevIndex);
4681
4682            //
4683            // Initialize a request for the configuration descriptor.
4684            //
4685            if (USBHCDGetConfigDescriptor(
4686                    0, &g_sUSBHCD.psUSBDevice[ui32DevIndex]) == 0) {
4687                //
4688                // If the device descriptor cannot be read then the device
4689                // will be treated as unknown.
4690                //
4691                g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevError;
4692
4693                DEBUG_OUTPUT("Connection %d - failed to get descriptor\n",
4694                             ui32DevIndex);
4695
4696                //
4697                // Send an unknown connection event to let the application
4698                // know that there is a device connected but return no
4699                // zero for the instance.
4700                //
4701                SendUnknownConnect(0, 0);
4702
4703                //
4704                // If the device is connected via a hub, tell the hub
4705                // driver that we experienced an error enumerating the
4706                // device.
4707                //
4708                if (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub) {
4709                    USBHHubEnumerationError(
4710                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
4711                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
4712                }
4713            }
4714        }
4715        //
4716        // Now have addressed and received the device configuration,
4717        // so get ready to set the device configuration.
4718        //
4719        else {
4720            DEBUG_OUTPUT("Connection %d - setting configuration.\n",
4721                         ui32DevIndex);
4722
4723            //
4724            // Use the first configuration to set the device
4725            // configuration.
4726            //
4727            USBHCDSetConfig(0, (uint32_t)&g_sUSBHCD.psUSBDevice[ui32DevIndex],
4728                            1);
4729
4730            //
4731            // Move on to the configured state.
4732            //
4733            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevConfigured;
4734
4735            //
4736            // Open the driver for the device.
4737            //
4738            g_pi32USBHActiveDriver[ui32DevIndex] =
4739                USBHCDOpenDriver(0, ui32DevIndex);
4740
4741            //
4742            // If the device is connected via a hub, tell the hub
4743            // driver that enumeration is complete.
4744            //
4745            if (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub) {
4746                USBHHubEnumerationComplete(
4747                    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
4748                    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
4749            }
4750        }
4751        break;
4752    }
4753    //
4754    // The device was making a request and is now complete.
4755    //
4756    case eHCDDevRequest: {
4757        g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevConnected;
4758        break;
4759    }
4760    //
4761    // The strings are currently not accessed.
4762    //
4763    case eHCDDevGetStrings: {
4764        break;
4765    }
4766    //
4767    // Basically Idle at this point.
4768    //
4769    case eHCDDevDisconnected: {
4770        DEBUG_OUTPUT("Connection %d - disconnected.\n", ui32DevIndex);
4771
4772        //
4773        // Handle device disconnect.
4774        //
4775        USBHCDDeviceDisconnected(0, ui32DevIndex);
4776
4777        //
4778        // Return to the Idle state.
4779        //
4780        g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDIdle;
4781        break;
4782    }
4783
4784    //
4785    // Connection and enumeration is complete so allow this function
4786    // to exit.
4787    //
4788    case eHCDDevConfigured: {
4789        break;
4790    }
4791
4792    //
4793    // Poorly behaving device are in limbo in this state until removed.
4794    //
4795    case eHCDDevError: {
4796        DEBUG_OUTPUT("Connection %d - Error!\n", ui32DevIndex);
4797
4798        //
4799        // If this device is connected directly to us, tidy up and ignore
4800        // it until it is removed.  If the device is connected to a hub,
4801        // we just leave it in the error state until it is removed.
4802        //
4803        if (ui32DevIndex == 0) {
4804            g_sUSBHCD.ui32IntEvents |= INT_EVENT_DISCONNECT;
4805            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDIdle;
4806        }
4807        break;
4808    }
4809    default: {
4810        break;
4811    }
4812    }
4813}
4814
4815//*****************************************************************************
4816//
4817//! This function completes a control transaction to a device.
4818//!
4819//! \param ui32Index is the controller index to use for this transfer.
4820//! \param psSetupPacket is the setup request to be sent.
4821//! \param psDevice is the device instance pointer for this request.
4822//! \param pui8Data is the data to send for OUT requests or the receive buffer
4823//! for IN requests.
4824//! \param ui32Size is the size of the buffer in \e pui8Data.
4825//! \param ui32MaxPacketSize is the maximum packet size for the device for this
4826//! request.
4827//!
4828//! This function handles the state changes necessary to send a control
4829//! transaction to a device.  This function should not be called from within
4830//! an interrupt callback as it is a blocking function.
4831//!
4832//! \return The number of bytes of data that were sent or received as a result
4833//! of this request.
4834//
4835//*****************************************************************************
4836uint32_t USBHCDControlTransfer(uint32_t ui32Index, tUSBRequest* psSetupPacket,
4837                               tUSBHostDevice* psDevice, uint8_t* pui8Data,
4838                               uint32_t ui32Size, uint32_t ui32MaxPacketSize) {
4839    uint32_t ui32Remaining;
4840    uint32_t ui32DataSize;
4841
4842    //
4843    // Debug sanity check.
4844    //
4845    ASSERT(g_sUSBHEP0State.iState == eEP0StateIdle);
4846    ASSERT(ui32Index == 0);
4847
4848    //
4849    // Initialize the state of the data for this request.
4850    //
4851    g_sUSBHEP0State.pui8Data = pui8Data;
4852    g_sUSBHEP0State.ui32BytesRemaining = ui32Size;
4853    g_sUSBHEP0State.ui32DataSize = ui32Size;
4854
4855    //
4856    // Set the maximum packet size.
4857    //
4858    g_sUSBHEP0State.ui32MaxPacketSize = ui32MaxPacketSize;
4859
4860    //
4861    // Save the current address.
4862    //
4863    g_sUSBHEP0State.ui32DevAddress = psDevice->ui32Address;
4864
4865    //
4866    // Set the address the host will used to communicate with the device.
4867    //
4868    MAP_USBHostAddrSet(USB0_BASE, USB_EP_0, g_sUSBHEP0State.ui32DevAddress,
4869                       USB_EP_HOST_OUT);
4870
4871    //
4872    // Make sure that endpoint 0 has the proper speed setting.
4873    //
4874    USBHostEndpointConfig(
4875        USB0_BASE, USB_EP_0, 64, 0, 0,
4876        (USB_EP_MODE_CTRL | psDevice->ui32Speed | USB_EP_HOST_OUT));
4877
4878    //
4879    // Put the data in the correct FIFO.
4880    //
4881    MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, (uint8_t*)psSetupPacket,
4882                           sizeof(tUSBRequest));
4883
4884    //
4885    // If this is an IN request, change to that state.
4886    //
4887    if (psSetupPacket->bmRequestType & USB_RTYPE_DIR_IN) {
4888        g_sUSBHEP0State.iState = eEP0StateSetupIN;
4889    } else {
4890        //
4891        // If there is no data then this is not an OUT request.
4892        //
4893        if (ui32Size != 0) {
4894            //
4895            // Since there is data, this is an OUT request.
4896            //
4897            g_sUSBHEP0State.iState = eEP0StateSetupOUT;
4898        } else {
4899            //
4900            // Otherwise this request has no data and just a status phase.
4901            //
4902            g_sUSBHEP0State.iState = eEP0StateStatusIN;
4903        }
4904    }
4905
4906    //
4907    // Make sure we are talking to the correct device.
4908    //
4909    if (psDevice->ui8Hub == 0) {
4910        USBHostHubAddrSet(USB0_BASE, USB_EP_0, 0,
4911                          USB_EP_HOST_OUT | psDevice->ui32Speed);
4912    } else {
4913        USBHostHubAddrSet(USB0_BASE, USB_EP_0,
4914                          (psDevice->ui8Hub | (psDevice->ui8HubPort << 8)),
4915                          USB_EP_HOST_OUT | psDevice->ui32Speed);
4916    }
4917
4918    //
4919    // Send the Setup packet.
4920    //
4921    MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_SETUP);
4922
4923    //
4924    // Block until endpoint 0 returns to the IDLE state.
4925    //
4926    while (g_sUSBHEP0State.iState != eEP0StateIdle) {
4927        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
4928
4929        if ((g_sUSBHCD.ui32IntEvents & (INT_EVENT_ENUM | INT_EVENT_SOF)) ==
4930            (INT_EVENT_ENUM | INT_EVENT_SOF)) {
4931            g_sUSBHCD.ui32IntEvents &= ~(INT_EVENT_ENUM | INT_EVENT_SOF);
4932
4933            USBHCDEnumHandler();
4934        }
4935
4936        OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
4937
4938        if (g_sUSBHEP0State.iState == eEP0StateError) {
4939            return (0xffffffff);
4940        }
4941
4942        //
4943        // If we aborted the transfer due to an error, tell the caller
4944        // that no bytes were transferred.
4945        //
4946        if (g_sUSBHCD.ui32IntEvents &
4947            (INT_EVENT_VBUS_ERR | INT_EVENT_DISCONNECT)) {
4948            return (0xffffffff);
4949        }
4950    }
4951
4952    //
4953    // Calculate and return the number of bytes that were sent or received.
4954    // The extra copy into local variables is required to prevent some
4955    // compilers from warning about undefined order of volatile access.
4956    //
4957    ui32DataSize = g_sUSBHEP0State.ui32DataSize;
4958    ui32Remaining = g_sUSBHEP0State.ui32BytesRemaining;
4959
4960    return (ui32DataSize - ui32Remaining);
4961}
4962
4963//*****************************************************************************
4964//
4965// Starts enumerating a new device connected via the hub.
4966//
4967// \param ui32Index is the index of the USB controller to use.
4968// \param ui32Hub is the hub address from which the connection is being made.
4969// \param ui32Port is the hub port number that the new device is connected to.
4970// \param pui8ConfigPool is memory to be used to store the device's
4971// configuration descriptor.
4972// \param ui32ConfigSize is the number of bytes available in the buffer pointed
4973// to by pui8ConfigPool.
4974//
4975// This function is called by the hub class driver after it has detected a new
4976// device connection and reset the device.
4977//
4978// \return Returns the index of the device allocated or 0 if no resources are
4979//         available. Device index 0 is the hub itself.
4980//
4981//*****************************************************************************
4982uint32_t USBHCDHubDeviceConnected(uint32_t ui32Index, uint8_t ui8Hub,
4983                                  uint8_t ui8Port, uint32_t ui32Speed) {
4984    uint32_t ui32DevIndex;
4985
4986    //
4987    // Debug sanity checks.
4988    //
4989    ASSERT(ui32Index == 0);
4990    ASSERT(ui8Port);
4991
4992    DEBUG_OUTPUT("Connection from hub %d, port %d.\n", ui8Hub, ui8Port);
4993
4994    //
4995    // Look for a free slot in the device table.
4996    //
4997    for (ui32DevIndex = 1; ui32DevIndex <= MAX_USB_DEVICES; ui32DevIndex++) {
4998        if ((g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags &
4999             USBHDEV_FLAG_ALLOCATED) == 0) {
5000            //
5001            // We found one. Set the state to ensure that it gets enumerated.
5002            //
5003            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags =
5004                USBHDEV_FLAG_ALLOCATED;
5005            g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor->bLength = 0;
5006            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub = ui8Hub;
5007            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort = ui8Port;
5008            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed = ui32Speed;
5009            g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bLength = 0;
5010
5011            //
5012            // Set the state to ensure enumeration begins.
5013            //
5014            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevConnectedHub;
5015
5016            DEBUG_OUTPUT("Allocating device %d\n", ui32DevIndex);
5017
5018            //
5019            // Pass the device index back to the hub driver.
5020            //
5021            return (ui32DevIndex);
5022        }
5023    }
5024
5025    //
5026    // If we get here, there are device slots available so send back an invalid
5027    // device index to tell the caller to ignore this device.
5028    //
5029    return (0);
5030}
5031
5032//*****************************************************************************
5033//
5034// Called when a device is disconnected from a hub.
5035//
5036// \param ui32Index is the index of the USB controller to use.
5037// \param ui32DevIndex is the device index for the USB device that was
5038// disconnected.
5039//
5040//*****************************************************************************
5041void USBHCDHubDeviceDisconnected(uint32_t ui32Index, uint32_t ui32DevIndex) {
5042    //
5043    // Debug sanity checks.
5044    //
5045    ASSERT(ui32Index == 0);
5046    ASSERT(ui32DevIndex && (ui32DevIndex <= MAX_USB_DEVICES));
5047
5048    DEBUG_OUTPUT("Disconnection from hub %d, port %d, device %d\n",
5049                 g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
5050                 g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort, ui32DevIndex);
5051
5052    //
5053    // Set the device state to ensure that USBHCDMain cleans it up.
5054    //
5055    g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevDisconnected;
5056}
5057
5058//*****************************************************************************
5059//
5060// This is the endpoint 0 interrupt handler.
5061//
5062// \return None.
5063//
5064//*****************************************************************************
5065static void USBHCDEnumHandler(void) {
5066    uint32_t ui32EPStatus;
5067    uint32_t ui32DataSize;
5068
5069    //
5070    // Get the end point 0 status.
5071    //
5072    ui32EPStatus = MAP_USBEndpointStatus(USB0_BASE, USB_EP_0);
5073
5074    //
5075    // If there was an error then go to the error state.
5076    //
5077    if (ui32EPStatus == USB_HOST_EP0_ERROR) {
5078        //
5079        // Clear this status indicating that the status packet was
5080        // received.
5081        //
5082        MAP_USBHostEndpointStatusClear(USB0_BASE, USB_EP_0, USB_HOST_EP0_ERROR);
5083        MAP_USBFIFOFlush(USB0_BASE, USB_EP_0, 0);
5084
5085        //
5086        // Just go back to the idle state.
5087        //
5088        g_sUSBHEP0State.iState = eEP0StateError;
5089
5090        return;
5091    }
5092
5093    switch (g_sUSBHEP0State.iState) {
5094    //
5095    // Handle the status state, this is a transitory state from
5096    // USB_STATE_TX or USB_STATE_RX back to USB_STATE_IDLE.
5097    //
5098    case eEP0StateStatus: {
5099        //
5100        // Handle the case of a received status packet.
5101        //
5102        if (ui32EPStatus & (USB_HOST_EP0_RXPKTRDY | USB_HOST_EP0_STATUS)) {
5103            //
5104            // Clear this status indicating that the status packet was
5105            // received.
5106            //
5107            MAP_USBHostEndpointStatusClear(
5108                USB0_BASE, USB_EP_0,
5109                (USB_HOST_EP0_RXPKTRDY | USB_HOST_EP0_STATUS));
5110        }
5111
5112        //
5113        // Just go back to the idle state.
5114        //
5115        g_sUSBHEP0State.iState = eEP0StateIdle;
5116
5117        break;
5118    }
5119
5120    //
5121    // This state triggers a STATUS IN request from the device.
5122    //
5123    case eEP0StateStatusIN: {
5124        //
5125        // Generate an IN request from the device.
5126        //
5127        MAP_USBHostRequestStatus(USB0_BASE);
5128
5129        //
5130        // Change to the status phase and wait for the response.
5131        //
5132        g_sUSBHEP0State.iState = eEP0StateStatus;
5133
5134        break;
5135    }
5136
5137    //
5138    // In the IDLE state the code is waiting to receive data from the host.
5139    //
5140    case eEP0StateIdle: {
5141        break;
5142    }
5143
5144    //
5145    // Data is still being sent to the host so handle this in the
5146    // EP0StateTx() function.
5147    //
5148    case eEP0StateSetupOUT: {
5149        //
5150        // Send remaining data if necessary.
5151        //
5152        USBHCDEP0StateTx();
5153
5154        break;
5155    }
5156
5157    //
5158    // Handle the receive state for commands that are receiving data on
5159    // endpoint 0.
5160    //
5161    case eEP0StateSetupIN: {
5162        //
5163        // Generate a new IN request to the device.
5164        //
5165        MAP_USBHostRequestIN(USB0_BASE, USB_EP_0);
5166
5167        //
5168        // Proceed to the RX state to receive the requested data.
5169        //
5170        g_sUSBHEP0State.iState = eEP0StateRx;
5171
5172        break;
5173    }
5174
5175    //
5176    // The endpoint remains in this state until all requested data has
5177    // been received.
5178    //
5179    case eEP0StateRx: {
5180        //
5181        // There was a stall on endpoint 0 so go back to the idle state
5182        // as this command has been terminated.
5183        //
5184        if (ui32EPStatus & USB_HOST_EP0_RX_STALL) {
5185            g_sUSBHEP0State.iState = eEP0StateIdle;
5186
5187            //
5188            // Clear the stalled state on endpoint 0.
5189            //
5190            MAP_USBHostEndpointStatusClear(USB0_BASE, USB_EP_0,
5191                                           ui32EPStatus & USB_HOST_IN_STATUS);
5192            break;
5193        }
5194
5195        //
5196        // Set the number of bytes to get out of this next packet.
5197        //
5198        ui32DataSize = g_sUSBHEP0State.ui32BytesRemaining;
5199        if (ui32DataSize > g_sUSBHEP0State.ui32MaxPacketSize) {
5200            //
5201            // Don't send more than EP0_MAX_PACKET_SIZE bytes.
5202            //
5203            ui32DataSize = MAX_PACKET_SIZE_EP0;
5204        }
5205
5206        if (ui32DataSize != 0) {
5207            //
5208            // Get the data from the USB controller end point 0.
5209            //
5210            MAP_USBEndpointDataGet(USB0_BASE, USB_EP_0,
5211                                   g_sUSBHEP0State.pui8Data, &ui32DataSize);
5212        }
5213
5214        //
5215        // Advance the pointer.
5216        //
5217        g_sUSBHEP0State.pui8Data += ui32DataSize;
5218
5219        //
5220        // Decrement the number of bytes that are being waited on.
5221        //
5222        g_sUSBHEP0State.ui32BytesRemaining -= ui32DataSize;
5223
5224        //
5225        // Need to ack the data on end point 0 in this case
5226        // without setting data end.
5227        //
5228        MAP_USBHostEndpointDataAck(USB0_BASE, USB_EP_0);
5229
5230        //
5231        // If there was not more than the maximum packet size bytes of data
5232        // the this was a int16_t packet and indicates that this transfer
5233        // is complete.  If there were exactly
5234        // g_sUSBHEP0State.ui32MaxPacketSize remaining then there still
5235        // needs to be null packet sent before this transfer is complete.
5236        //
5237        if ((ui32DataSize < g_sUSBHEP0State.ui32MaxPacketSize) ||
5238            (g_sUSBHEP0State.ui32BytesRemaining == 0)) {
5239            //
5240            // Return to the idle state.
5241            //
5242            g_sUSBHEP0State.iState = eEP0StateStatus;
5243
5244            //
5245            // No more data.
5246            //
5247            g_sUSBHEP0State.pui8Data = 0;
5248
5249            //
5250            // Send a null packet to acknowledge that all data was
5251            // received.
5252            //
5253            MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_STATUS);
5254        } else {
5255            //
5256            // Request more data.
5257            //
5258            MAP_USBHostRequestIN(USB0_BASE, USB_EP_0);
5259        }
5260        break;
5261    }
5262
5263    //
5264    // The device stalled endpoint zero so check if the stall needs to be
5265    // cleared once it has been successfully sent.
5266    //
5267    case eEP0StateStall: {
5268        //
5269        // Reset the global end point 0 state to IDLE.
5270        //
5271        g_sUSBHEP0State.iState = eEP0StateIdle;
5272
5273        break;
5274    }
5275
5276    //
5277    // Halt on an unknown state, but only in DEBUG builds.
5278    //
5279    default: {
5280        ASSERT(0);
5281        break;
5282    }
5283    }
5284}
5285
5286//*****************************************************************************
5287//
5288// This internal function handles sending data on endpoint 0.
5289//
5290// \return None.
5291//
5292//*****************************************************************************
5293static void USBHCDEP0StateTx(void) {
5294    uint32_t ui32NumBytes;
5295    uint8_t* pui8Data;
5296
5297    //
5298    // In the TX state on endpoint 0.
5299    //
5300    g_sUSBHEP0State.iState = eEP0StateSetupOUT;
5301
5302    //
5303    // Set the number of bytes to send this iteration.
5304    //
5305    ui32NumBytes = g_sUSBHEP0State.ui32BytesRemaining;
5306
5307    //
5308    // Limit individual transfers to 64 bytes.
5309    //
5310    if (ui32NumBytes > 64) {
5311        ui32NumBytes = 64;
5312    }
5313
5314    //
5315    // Save the pointer so that it can be passed to the USBEndpointDataPut()
5316    // function.
5317    //
5318    pui8Data = (uint8_t*)g_sUSBHEP0State.pui8Data;
5319
5320    //
5321    // Advance the data pointer and counter to the next data to be sent.
5322    //
5323    g_sUSBHEP0State.ui32BytesRemaining -= ui32NumBytes;
5324    g_sUSBHEP0State.pui8Data += ui32NumBytes;
5325
5326    //
5327    // Put the data in the correct FIFO.
5328    //
5329    MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, pui8Data, ui32NumBytes);
5330
5331    //
5332    // If this is exactly 64 then don't set the last packet yet.
5333    //
5334    if (ui32NumBytes == 64) {
5335        //
5336        // There is more data to send or exactly 64 bytes were sent, this
5337        // means that there is either more data coming or a null packet needs
5338        // to be sent to complete the transaction.
5339        //
5340        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_OUT);
5341    } else {
5342        //
5343        // Send the last bit of data.
5344        //
5345        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_OUT);
5346
5347        //
5348        // Now go to the status state and wait for the transmit to complete.
5349        //
5350        g_sUSBHEP0State.iState = eEP0StateStatusIN;
5351    }
5352}
5353
5354//*****************************************************************************
5355//
5356//! This function returns the USB hub port for the requested device instance.
5357//!
5358//! \param ui32Instance is a unique value indicating which device to query.
5359//!
5360//! This function returns the USB hub port for the device that is associated
5361//! with the \e ui32Instance parameter.  The caller must use the value for
5362//! \e ui32Instance was passed to the application when it receives a
5363//! \b USB_EVENT_CONNECTED event.  The function returns the USB hub port for
5364//! the interface number specified by the \e ui32Interface parameter.
5365//!
5366//! \return The USB hub port for the requested interface.
5367//
5368//*****************************************************************************
5369uint8_t USBHCDDevHubPort(uint32_t ui32Instance) {
5370    uint32_t ui32DevIndex;
5371
5372    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);
5373
5374    if (ui32DevIndex == 0xff) {
5375        return (ui32DevIndex);
5376    }
5377
5378    return (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
5379}
5380
5381//*****************************************************************************
5382//
5383//! This function will return the USB address for the requested device
5384//! instance.
5385//!
5386//! \param ui32Instance is a unique value indicating which device to query.
5387//!
5388//! This function returns the USB address for the device that is associated
5389//! with the \e ui32Instance parameter.  The caller must use a value for
5390//! \e ui32Instance have been passed to the application when it receives a
5391//! \b USB_EVENT_CONNECTED event.  The function will return the USB address for
5392//! the interface number specified by the \e ui32Interface parameter.
5393//!
5394//! \return The USB address for the requested interface.
5395//
5396//*****************************************************************************
5397uint8_t USBHCDDevAddress(uint32_t ui32Instance) {
5398    uint32_t ui32DevIndex;
5399
5400    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);
5401
5402    if (ui32DevIndex == 0xff) {
5403        return (ui32DevIndex);
5404    }
5405
5406    return (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address);
5407}
5408
5409//*****************************************************************************
5410//
5411//! This function will return the USB class for the requested device
5412//! instance.
5413//!
5414//! \param ui32Instance is a unique value indicating which device to query.
5415//! \param ui32Interface is the interface number to query for the USB class.
5416//!
5417//! This function returns the USB class for the device that is associated
5418//! with the \e ui32Instance parameter.  The caller must use a value for
5419//! \e ui32Instance have been passed to the application when it receives a
5420//! \b USB_EVENT_CONNECTED event.  The function will return the USB class for
5421//! the interface number specified by the \e ui32Interface parameter.  If
5422//! \e ui32Interface is set to 0xFFFFFFFF then the function will return the USB
5423//! class for the first interface that is found in the device's USB
5424//! descriptors.
5425//!
5426//! \return The USB class for the requested interface.
5427//
5428//*****************************************************************************
5429uint8_t USBHCDDevClass(uint32_t ui32Instance, uint32_t ui32Interface) {
5430    uint32_t ui32DevIndex;
5431    tInterfaceDescriptor* psInterface;
5432
5433    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);
5434
5435    //
5436    // If the instance was not valid return an undefined class.
5437    //
5438    if (ui32DevIndex == 0xff) {
5439        return (USB_CLASS_DEVICE);
5440    }
5441
5442    //
5443    // Get the interface descriptor.
5444    //
5445    psInterface = USBDescGetInterface(
5446        g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor,
5447        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Interface, ui32Interface);
5448
5449    //
5450    // Make sure that the interface requested actually exists.
5451    //
5452    if (psInterface) {
5453        //
5454        // Return the interface class.
5455        //
5456        return (psInterface->bInterfaceClass);
5457    }
5458
5459    //
5460    // No valid interface so return an undefined class.
5461    //
5462    return (USB_CLASS_DEVICE);
5463}
5464
5465//*****************************************************************************
5466//
5467//! This function will return the USB subclass for the requested device
5468//! instance.
5469//!
5470//! \param ui32Instance is a unique value indicating which device to query.
5471//! \param ui32Interface is the interface number to query for the USB subclass.
5472//!
5473//! This function returns the USB subclass for the device that is associated
5474//! with the \e ui32Instance parameter.  The caller must use a value for
5475//! \e ui32Instance have been passed to the application when it receives a
5476//! \b USB_EVENT_CONNECTED event.  The function will return the USB subclass
5477//! for the interface number specified by the \e ui32Interface parameter.  If
5478//! \e ui32Interface is set to 0xFFFFFFFF then the function will return the USB
5479//! subclass for the first interface that is found in the device's USB
5480//! descriptors.
5481//!
5482//! \return The USB subclass for the requested interface.
5483//
5484//*****************************************************************************
5485uint8_t USBHCDDevSubClass(uint32_t ui32Instance, uint32_t ui32Interface) {
5486    uint32_t ui32DevIndex;
5487    tInterfaceDescriptor* psInterface;
5488
5489    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);
5490
5491    //
5492    // If the instance was not valid return an undefined subclass.
5493    //
5494    if (ui32DevIndex == 0xff) {
5495        return (USB_SUBCLASS_UNDEFINED);
5496    }
5497
5498    //
5499    // Get the interface descriptor.
5500    //
5501    psInterface = USBDescGetInterface(
5502        g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor,
5503        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Interface, ui32Interface);
5504
5505    //
5506    // Make sure that the interface requested actually exists.
5507    //
5508    if (psInterface) {
5509        //
5510        // Return the interface subclass.
5511        //
5512        return (psInterface->bInterfaceSubClass);
5513    }
5514
5515    //
5516    // No valid interface so return an undefined subclass.
5517    //
5518    return (USB_SUBCLASS_UNDEFINED);
5519}
5520
5521//*****************************************************************************
5522//
5523//! This function returns the USB protocol for the requested device instance.
5524//!
5525//! \param ui32Instance is a unique value indicating which device to query.
5526//! \param ui32Interface is the interface number to query for the USB protocol.
5527//!
5528//! This function returns the USB protocol for the device that is associated
5529//! with the \e ui32Instance parameter.  The caller must use a value for
5530//! \e ui32Instance have been passed to the application when it receives a
5531//! \b USB_EVENT_CONNECTED event.  The function will return the USB protocol
5532//! for the interface number specified by the \e ui32Interface parameter.  If
5533//! \e ui32Interface is set to 0xFFFFFFFF then the function will return the USB
5534//! protocol for the first interface that is found in the device's USB
5535//! descriptors.
5536//!
5537//! \return The USB protocol for the requested interface.
5538//
5539//*****************************************************************************
5540uint8_t USBHCDDevProtocol(uint32_t ui32Instance, uint32_t ui32Interface) {
5541    uint32_t ui32DevIndex;
5542    tInterfaceDescriptor* psInterface;
5543
5544    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);
5545
5546    //
5547    // If the instance was not valid return an undefined protocol.
5548    //
5549    if (ui32DevIndex == 0xff) {
5550        return (USB_PROTOCOL_UNDEFINED);
5551    }
5552
5553    //
5554    // Get the interface descriptor.
5555    //
5556    psInterface = USBDescGetInterface(
5557        g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor,
5558        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Interface, ui32Interface);
5559
5560    //
5561    // Make sure that the interface requested actually exists.
5562    //
5563    if (psInterface) {
5564        //
5565        // Return the interface protocol.
5566        //
5567        return (psInterface->bInterfaceProtocol);
5568    }
5569
5570    //
5571    // No valid interface so return an undefined protocol.
5572    //
5573    return (USB_PROTOCOL_UNDEFINED);
5574}
5575
5576//*****************************************************************************
5577//
5578//! This function sets one of the \b USBLIB_FEATURE_ requests.
5579//!
5580//! \param ui32Index is the index of the USB controller to access.
5581//! \param ui32Feature is one of the \b USBLIB_FEATURE_ defines.
5582//! \param pvFeature is a pointer to the data for the \b USBLIB_FEATURE
5583//!        request.
5584//!
5585//! This function sends the requested feature request to the USB library.
5586//! Not all features are supported by all devices so see the documentation
5587//! for the \b USBLIB_FEATURE_ to determine if the feature is supported.
5588//!
5589//! \return Returns \b true if the feature was set and \b false if the feature
5590//! is not supported or could not be changed to the requested value.
5591//
5592//*****************************************************************************
5593bool USBHCDFeatureSet(uint32_t ui32Index, uint32_t ui32Feature,
5594                      void* pvFeature) {
5595    bool bRetCode;
5596    tLPMFeature* psLPMFeature;
5597
5598    bRetCode = true;
5599
5600    switch (ui32Feature) {
5601    case USBLIB_FEATURE_CPUCLK: {
5602        //
5603        // Set the ticks per millisecond.
5604        //
5605        g_ui32Tickms = (*(uint32_t*)pvFeature / 3000);
5606        break;
5607    }
5608    case USBLIB_FEATURE_LPM: {
5609        psLPMFeature = (tLPMFeature*)pvFeature;
5610
5611        if (psLPMFeature->ui32Features & USBLIB_FEATURE_LPM_EN) {
5612            g_sUSBHCD.ui32Features |= USBLIB_FEATURE_LPM_EN;
5613
5614            if (psLPMFeature->ui32Features & USBLIB_FEATURE_LPM_RMT_WAKE) {
5615                g_sUSBHCD.ui32Features |= USBLIB_FEATURE_LPM_RMT_WAKE;
5616            }
5617            g_sUSBHCD.ui32LPMHIRD = psLPMFeature->ui32HIRD;
5618        } else {
5619            psLPMFeature->ui32Features &= ~USBLIB_FEATURE_LPM_EN;
5620        }
5621        break;
5622    }
5623    case USBLIB_FEATURE_USBPLL: {
5624        //
5625        // If the PLL rate is not evenly divisible by 60MHz then
5626        // do not set it.
5627        //
5628        if ((*(uint32_t*)pvFeature % 60000000) != 0) {
5629            bRetCode = false;
5630        } else {
5631            //
5632            // Save the new PLL rate.
5633            //
5634            g_ui32PLLDiv = (*(uint32_t*)pvFeature / 60000000);
5635        }
5636        break;
5637    }
5638    case USBLIB_FEATURE_USBULPI: {
5639        //
5640        // Save the ULPI support level.
5641        //
5642        g_ui32ULPISupport = *(uint32_t*)pvFeature;
5643
5644        break;
5645    }
5646    default: {
5647        bRetCode = false;
5648        break;
5649    }
5650    }
5651    return (bRetCode);
5652}
5653
5654//*****************************************************************************
5655//
5656//! This function returns the current status of an LPM request.
5657//!
5658//! \param psDevice is the device to query.
5659//!
5660//! This function returns the current status of LPM requests for a given
5661//! device.  This is called to determine if a previous request completed
5662//! successfully or if there was an error.
5663//!
5664//! \return This function returns the following values:
5665//! - \b USBHCD_LPM_AVAIL - There are no pending LPM requests on this specific
5666//!   device or the last request completed successfully.
5667//! - \b USBHCD_LPM_ERROR - The last LPM request for this device did not
5668//!   complete successfully.
5669//! - \b USBHCD_LPM_PENDING - The last LPM request has not completed.
5670//
5671//*****************************************************************************
5672uint32_t USBHCDLPMStatus(tUSBHostDevice* psDevice) {
5673    uint32_t ui32Ret;
5674
5675    ASSERT(psDevice != 0);
5676
5677    //
5678    // Should never have both USBHDEV_FLAG_LPMERROR and USBHDEV_FLAG_LPMPEND
5679    // set at the same time.
5680    //
5681    ASSERT((psDevice->ui32Flags &
5682            (USBHDEV_FLAG_LPMERROR | USBHDEV_FLAG_LPMPEND)) !=
5683           (USBHDEV_FLAG_LPMERROR | USBHDEV_FLAG_LPMPEND));
5684
5685    //
5686    // Default to no pending transfers or errors.
5687    //
5688    ui32Ret = USBHCD_LPM_AVAIL;
5689
5690    if (psDevice->ui32Flags & USBHDEV_FLAG_LPMERROR) {
5691        //
5692        // An error occurred after the last call to send an LPM command.
5693        //
5694        ui32Ret = USBHCD_LPM_ERROR;
5695    } else if (psDevice->ui32Flags & USBHDEV_FLAG_LPMPEND) {
5696        //
5697        // Still have a pending transfer.
5698        //
5699        ui32Ret = USBHCD_LPM_PENDING;
5700    }
5701
5702    return (ui32Ret);
5703}
5704
5705//*****************************************************************************
5706//
5707//! This function generates an LPM request for a device to enter L1 sleep
5708//! state.
5709//!
5710//! \param psDevice is the device to query.
5711//!
5712//! This function sends a request to a device to enter the LPM L1 sleep state.
5713//! The caller must check the return value to see if the request can be
5714//! attempted at this time.  If another LPM transaction is busy on another
5715//! device this function will return \b USBHCD_LPM_PENDING or
5716//! \b USBHCD_LPM_AVAIL if the LPM request was scheduled to be sent.  The
5717//! caller should check the USBHCDLPMStatus() function to determine if the
5718//! request has completed.
5719//!
5720//! \return This function returns the following values:
5721//! - USBHCD_LPM_AVAIL - The transition to L1 state is scheduled to be sent.
5722//! - USBHCD_LPM_PENDING - There is already an LPM request pending.
5723//
5724//*****************************************************************************
5725uint32_t USBHCDLPMSleep(tUSBHostDevice* psDevice) {
5726    uint32_t ui32Ret;
5727
5728    ASSERT(psDevice != 0);
5729
5730    //
5731    // Disable the USB interrupt.
5732    //
5733    OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);
5734
5735    //
5736    // If there is no current LPM pending then send the request.
5737    //
5738    if ((g_sUSBHCD.ui32IntEvents & INT_EVENT_LPM_PEND) ||
5739        (psDevice->ui32Flags & USBHDEV_FLAG_LPMPEND)) {
5740        ui32Ret = USBHCD_LPM_PENDING;
5741    } else {
5742        //
5743        // New pending LPM transfer at the host controller level.
5744        //
5745        g_sUSBHCD.ui32IntEvents |= INT_EVENT_LPM_PEND;
5746
5747        //
5748        // New pending request and clear any previous error for this
5749        // device in case it was already set.
5750        //
5751        psDevice->ui32Flags |= USBHDEV_FLAG_LPMPEND;
5752        psDevice->ui32Flags &= ~USBHDEV_FLAG_LPMERROR;
5753
5754        USBHostLPMSend(USB0_BASE, psDevice->ui32Address, USB_EP_0);
5755
5756        ui32Ret = USBHCD_LPM_AVAIL;
5757    }
5758
5759    //
5760    // Disable the USB interrupt.
5761    //
5762    OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
5763
5764    return (ui32Ret);
5765}
5766
5767//*****************************************************************************
5768//
5769//! This function generates an LPM request for a device to exit L1 sleep state.
5770//!
5771//! \param ui32Index specifies which USB controller to use.
5772//!
5773//! This function will start LPM resume signaling on the USB bus.  This wakes
5774//! all devices and is similar to USBHCDResume() call but is triggered by an
5775//! LPM request.
5776//!
5777//! \return None.
5778//
5779//*****************************************************************************
5780void USBHCDLPMResume(uint32_t ui32Index) {
5781    ASSERT(ui32Index == 0);
5782
5783    USBHostLPMResume(USB0_BASE);
5784}
5785
5786//*****************************************************************************
5787//
5788// Close the Doxygen group.
5789//! @}
5790//
5791//*****************************************************************************