+/rtos

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

Joseph RyanRe-add usblib files83915e3

master
46.2 KiB1411 linesraw
1//*****************************************************************************
2//
3// usbhhub.c - This file contains the host HID driver.
4//
5// Copyright (c) 2011-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 "usblib/host/usbhhub.h"
26#include "tivaware/hw_ints.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/usb.h"
33#include "usblib/host/usbhost.h"
34#include "usblib/host/usbhostpriv.h"
35#include "usblib/usblib.h"
36#include <stdbool.h>
37#include <stdint.h>
38#ifdef INCLUDE_DEBUG_OUTPUT
39#include "utils/uartstdio.h"
40#define DEBUG_OUTPUT UARTprintf
41#else
42#define DEBUG_OUTPUT                                                           \
43    while (0) ((int (*)(char*, ...))0)
44#endif
45
46//*****************************************************************************
47//
48//! \addtogroup usblib_host_class
49//! @{
50//
51//*****************************************************************************
52
53#ifdef ewarm
54#pragma pack(1)
55#endif
56
57//*****************************************************************************
58//
59//! The USB standard hub descriptor structure.  Full documentation for the
60//! contents of this structure can be found in chapter 11.23.2.1 of the USB
61//! 2.0 specification.
62//
63//*****************************************************************************
64typedef struct {
65    //
66    //! The total number of bytes in the descriptor (including this field).
67    //
68    uint8_t bLength;
69
70    //
71    //! The descriptor type. For a hub descriptor, this will be USB_DTYPE_HUB
72    //! (0x29 or 41 decimal).
73    //
74    uint8_t bDescType;
75
76    //
77    //! The number of downstream-facing ports that the hub supports.
78    //
79    uint8_t bNbrPorts;
80
81    //
82    //! Characteristics of the hub device including its power switching
83    //! capabilities and over-current protection mode.
84    //
85    uint16_t wHubCharacteristics;
86
87    //
88    //! The time between the start of the power-on sequence for a port and
89    //! the power to the port becoming stable.  This is expressed in 2mS units.
90    //
91    uint8_t bPwrOn2PwrGood;
92
93    //
94    //! The maximum current requirement for the hub circuitry in mA.
95    //
96    uint8_t bHubContrCurrent;
97
98    //
99    //! The last two fields in the structure are bit masks indicating which
100    //! downstream ports support removable devices and, following this, another
101    //! obsolete field from USB1.0 related to port power control.  Each field
102    //! is byte aligned and contains a bit for each hub port.  This structure
103    //! definition is set up with enough storage to handle ROOT_HUB_MAX_PORTS
104    //! ports but beware that the actual size of each field is dependent upon
105    //! the bNbrPorts field above.
106    //
107    uint8_t PortInfo[((ROOT_HUB_MAX_PORTS + 7) / 8) * 2];
108} PACKED tUsbHubDescriptor;
109
110#ifdef ewarm
111#pragma pack()
112#endif
113
114//*****************************************************************************
115//
116// This structure holds all data specific to a single hub port.
117//
118//*****************************************************************************
119typedef struct {
120    //
121    // The handle used by the HCD layer to identify this device.
122    //
123    uint32_t ui32DevHandle;
124
125    //
126    // The current state of the port.
127    //
128    volatile tHubPortState iState;
129
130    //
131    // General counter used in various states.
132    //
133    volatile uint32_t ui32Count;
134
135    //
136    // A flag used to indicate that the downstream device is a low speed
137    // device.
138    //
139    bool bLowSpeed;
140
141    //
142    // The speed of the device on this port.
143    //
144    uint32_t ui32Speed;
145
146    //
147    // This flag is set if the hub reports that a change is pending on this
148    // port.
149    //
150    volatile bool bChanged;
151} tHubPort;
152
153//*****************************************************************************
154//
155// USB hub flags values for tHubInstance.ui32Flags.
156//
157//*****************************************************************************
158#define USBLIB_HUB_ACTIVE 0x00000001
159#define USBLIB_HUB_HS 0x00000002
160#define USBLIB_HUB_MULTI_TT 0x00000004
161
162//*****************************************************************************
163//
164// This is the structure that holds all of the data for a given instance of
165// a Hub device.
166//
167//*****************************************************************************
168struct tHubInstance {
169    //
170    // Save the device instance.
171    //
172    tUSBHostDevice* psDevice;
173
174    //
175    // Used to save the callback function pointer.
176    //
177    tUSBHHubCallback pfnCallback;
178
179    //
180    // Callback data provided by caller.
181    //
182    uint32_t ui32CBData;
183
184    //
185    // Interrupt IN pipe.
186    //
187    uint32_t ui32IntInPipe;
188
189    //
190    // Hub characteristics as reported in the class-specific hub descriptor.
191    //
192    uint16_t ui16HubCharacteristics;
193
194    //
195    // The number of downstream-facing ports the hub supports.
196    //
197    uint8_t ui8NumPorts;
198
199    //
200    // The number of ports on the hub that we can actually talk to.  This will
201    // be the smaller of the number of ports on the hub and MAX_USB_DEVICES.
202    //
203    uint8_t ui8NumPortsInUse;
204
205    //
206    // The size of a status change packet sent by the hub.  This is determined
207    // from the number of ports supported by the hub.
208    //
209    uint8_t ui8ReportSize;
210
211    //
212    // Flags indicating whether the hub is connected.
213    //
214    uint32_t ui32Flags;
215
216    //
217    // Flag indicating that a device is currently in process of being
218    // enumerated.
219    //
220    volatile bool bEnumerationBusy;
221
222    //
223    // This is valid if bEnumerationBusy is set and indicates the port
224    // that is in the process of enumeration.
225    //
226    uint8_t ui8EnumIdx;
227
228    //
229    // The state of each of the ports we support on the hub.
230    //
231    tHubPort psPorts[MAX_USB_DEVICES];
232
233    //
234    // The interrupt number for this instance.
235    //
236    uint32_t ui32IntNum;
237};
238
239//*****************************************************************************
240//
241//! Forward references to the hub class driver functions.
242//
243//*****************************************************************************
244static void* HubDriverOpen(tUSBHostDevice* psDevice);
245static void HubDriverClose(void* pvHubDevice);
246
247//*****************************************************************************
248//
249//! This constant global structure defines the Hub Class Driver that is
250//! provided with the USB library.
251//
252//*****************************************************************************
253const tUSBHostClassDriver g_sUSBHubClassDriver = {USB_CLASS_HUB, HubDriverOpen,
254                                                  HubDriverClose, 0};
255
256//*****************************************************************************
257//
258// The instance data storage for attached hub.
259//
260//*****************************************************************************
261static tHubInstance g_sRootHub;
262
263//*****************************************************************************
264//
265// Hub and port state change flags as reported via the hub's IN endpoint.
266//
267//*****************************************************************************
268static volatile uint32_t g_ui32ChangeFlags;
269
270//
271// Note: The following assumes ROOT_HUB_MAX_PORTS is less than 32!
272//
273static uint32_t g_ui32HubChanges;
274
275//*****************************************************************************
276//
277// This function is called to set the operating speed of a given port.
278//
279// \param ui8Port is the port number for this request.
280// \param ui32Speed is one of the HUB_FEATURE_PORT_* values.
281//
282// This function sets the operating speed of the hub port specified in the
283// \e ui8Port parameter.  A \e ui8Port value of 0 is an access to the hub
284// itself and not one of the hub ports.  The \e ui32Speed value is one of the
285// \b USB_EP_SPEED_ values.
286//
287// \return None.
288//
289//*****************************************************************************
290static void USBHubPortSpeedSet(uint8_t ui8Port, uint32_t ui32Speed) {
291    g_sRootHub.psPorts[ui8Port].ui32Speed = ui32Speed;
292}
293
294//*****************************************************************************
295//
296// This function is called to send a request to the hub to set a feature on
297// a given port.
298//
299// \param psHubInstance is the hub device instance.
300// \param ui8Port is the port number for this request.
301// \param ui16Feature is one of the HUB_FEATURE_PORT_* values.
302//
303// This function will send the set feature request to the hub indicated by the
304// \e psHubInstance parameter.  The \e ui8Port value indicates which port
305// number to send this request to and can range from 0 to the number of valid
306// ports on the given hub.  A \e ui8Port value of 0 is an access to the hub
307// itself and not one of the hub ports.  The \e ui16Feature is the feature
308//  request toset on the given port.  For example, a \e ui16Feature value of
309// \e HUB_FEATURE_PORT_RESET and \e ui8Port value of 1 will cause reset
310// signaling to hub port 1.
311//
312// \return None.
313//
314//*****************************************************************************
315static void HubSetPortFeature(tHubInstance* psHubInstance, uint8_t ui8Port,
316                              uint16_t ui16Feature) {
317    tUSBRequest sSetupPacket;
318    tUSBHostDevice* psDevice;
319
320    //
321    // Retrieve the hub instance and device pointer.
322    //
323    psDevice = psHubInstance->psDevice;
324
325    //
326    // This is a standard OUT request.
327    //
328    sSetupPacket.bmRequestType =
329        USB_RTYPE_DIR_OUT | USB_RTYPE_CLASS | USB_RTYPE_OTHER;
330
331    //
332    // Set the field to clear the requested port feature.
333    //
334    sSetupPacket.bRequest = USBREQ_SET_FEATURE;
335    sSetupPacket.wValue = ui16Feature;
336    sSetupPacket.wIndex = ui8Port;
337    sSetupPacket.wLength = 0;
338
339    //
340    // Send the request.
341    //
342    USBHCDControlTransfer(0, &sSetupPacket, psDevice, 0, 0,
343                          psDevice->sDeviceDescriptor.bMaxPacketSize0);
344}
345
346//*****************************************************************************
347//
348// This function is called to send a request to the hub to clear a feature on
349// a given port.
350//
351// \param psHubInstance is the hub device instance.
352// \param ui8Port is the port number for this request.
353// \param ui16Feature is one of the HUB_FEATURE_PORT_* values.
354//
355// This function will send the clear feature request to the hub indicated by
356// the \e psHubInstance parameter.  The \e ui8Port value indicates which port
357// number to send this request to and can range from 0 to the number of valid
358// ports on the given hub.  A \e ui8Port value of 0 is an access to the hub
359// itself and not one of the hub ports.  The \e ui16Feature is the feature
360// request to clear on the given port.  For example, a \e ui16Feature value of
361// \e HUB_FEATURE_C_PORT_RESET and \e ui8Port value of 1 will clear the reset
362// complete signaling on hub port 1.  Values like the reset feature will
363// remain set until actively cleared by this function.
364//
365// \return None.
366//
367//*****************************************************************************
368static void HubClearPortFeature(tHubInstance* psHubInstance, uint8_t ui8Port,
369                                uint16_t ui16Feature) {
370    tUSBRequest sSetupPacket;
371    tUSBHostDevice* psDevice;
372
373    //
374    // Retrieve the hub instance and device pointer.
375    //
376    psDevice = psHubInstance->psDevice;
377
378    //
379    // This is a standard OUT request.
380    //
381    sSetupPacket.bmRequestType =
382        USB_RTYPE_DIR_OUT | USB_RTYPE_CLASS | USB_RTYPE_OTHER;
383
384    //
385    // Set the field to clear the requested port feature.
386    //
387    sSetupPacket.bRequest = USBREQ_CLEAR_FEATURE;
388    sSetupPacket.wValue = ui16Feature;
389    sSetupPacket.wIndex = ui8Port;
390    sSetupPacket.wLength = 0;
391
392    //
393    // Send the request.
394    //
395    USBHCDControlTransfer(0, &sSetupPacket, psDevice, 0, 0,
396                          psDevice->sDeviceDescriptor.bMaxPacketSize0);
397}
398
399//*****************************************************************************
400//
401// This function is used to retrieve the current status of a port on the
402// hub.
403//
404// \param psHubInstance is the hub device instance.
405// \param ui8Port is the port number for this request.
406// \param pui16PortStatus is a pointer to the memory to store the current
407// status of the port.
408// \param pui16PortChange is a pointer to the memory to store the current
409// change status of the ports.
410//
411// This function is used to retrieve the current overall status and change
412// status for the port given in the \e ui8Port parameter.  The \e ui8Port value
413// indicates which port number to send this request to and can range from 0 to
414// the number of valid ports on the given hub.  A \e ui8Port value of 0 is an
415// access to the hub itself and not one of the hub ports.
416//
417// \return None.
418//
419//*****************************************************************************
420static bool HubGetPortStatus(tHubInstance* psHubInstance, uint8_t ui8Port,
421                             uint16_t* pui16PortStatus,
422                             uint16_t* pui16PortChange) {
423    uint32_t ui32Data, ui32Read;
424    tUSBRequest sSetupPacket;
425    tUSBHostDevice* psDevice;
426
427    //
428    // Retrieve the device pointer.
429    //
430    psDevice = psHubInstance->psDevice;
431
432    //
433    // This is a standard OUT request.
434    //
435    sSetupPacket.bmRequestType =
436        USB_RTYPE_DIR_IN | USB_RTYPE_CLASS | USB_RTYPE_OTHER;
437
438    //
439    // Set the fields to get the hub status.
440    //
441    sSetupPacket.bRequest = USBREQ_GET_STATUS;
442    sSetupPacket.wValue = 0;
443    sSetupPacket.wIndex = (uint16_t)ui8Port;
444    sSetupPacket.wLength = 4;
445
446    //
447    // Send the request.
448    //
449    ui32Read =
450        USBHCDControlTransfer(0, &sSetupPacket, psDevice, (uint8_t*)&ui32Data,
451                              4, psDevice->sDeviceDescriptor.bMaxPacketSize0);
452
453    //
454    // Check that we received the correct number of bytes.
455    //
456    if (ui32Read != 4) {
457        return (false);
458    } else {
459        //
460        // We got 4 bytes from the device. Now translate these into the 2
461        // 16-bit values we pass back to the caller.
462        //
463        *pui16PortStatus = (uint16_t)(ui32Data & 0xFFFF);
464        *pui16PortChange = (uint16_t)(ui32Data >> 16);
465
466        DEBUG_OUTPUT("Port %d, status 0x%04x, change 0x%04x\n", ui8Port,
467                     *pui16PortStatus, *pui16PortChange);
468    }
469
470    //
471    // All is well.
472    //
473    return (true);
474}
475
476//*****************************************************************************
477//
478// This function handles callbacks for the interrupt IN endpoint for the hub
479// device.
480//
481//*****************************************************************************
482static void HubIntINCallback(uint32_t ui32Pipe, uint32_t ui32Event) {
483    switch (ui32Event) {
484    //
485    // Handles a request to schedule a new request on the interrupt IN
486    // pipe.
487    //
488    case USB_EVENT_SCHEDULER: {
489        //
490        // Set things up to read the next change indication from the hub.
491        //
492        USBHCDPipeSchedule(ui32Pipe, (uint8_t*)&g_ui32HubChanges,
493                           (uint32_t)g_sRootHub.ui8ReportSize);
494        break;
495    }
496
497    //
498    // Called when new data is available on the interrupt IN pipe.
499    //
500    case USB_EVENT_RX_AVAILABLE: {
501        //
502        // For data transfers on INT IN endpoints, we need to acknowledge
503        // the data from this callback.
504        //
505        USBHCDPipeDataAck(ui32Pipe);
506
507        //
508        // Update our global "ports needing service" flags with the latest
509        // information we have just received.
510        //
511        g_ui32ChangeFlags |= g_ui32HubChanges;
512
513        //
514        // Send the report data to the USB host hub device class driver if
515        // we have been given a callback function.
516        //
517        if (g_sRootHub.pfnCallback) {
518            g_sRootHub.pfnCallback((void*)g_sRootHub.ui32CBData,
519                                   USB_EVENT_RX_AVAILABLE, ui32Pipe,
520                                   &g_ui32HubChanges);
521        }
522
523        break;
524    }
525    case USB_EVENT_ERROR: {
526        break;
527    }
528    }
529}
530
531//*****************************************************************************
532//
533// Query the class-specific hub descriptor.
534//
535//*****************************************************************************
536static bool GetHubDescriptor(tUsbHubDescriptor* psDesc) {
537    uint32_t ui32Read;
538    tUSBRequest sSetupPacket;
539    tUSBHostDevice* psDevice;
540
541    //
542    // Retrieve the device pointer.
543    //
544    psDevice = g_sRootHub.psDevice;
545
546    //
547    // This is a standard OUT request.
548    //
549    sSetupPacket.bmRequestType =
550        USB_RTYPE_DIR_IN | USB_RTYPE_CLASS | USB_RTYPE_DEVICE;
551
552    //
553    // Set the fields to get the hub descriptor.  Initially, we request only
554    // the first 4 bytes of the descriptor.  This will give us the size which
555    // we use to determine how many bytes to read to get the full descriptor.
556    // This is necessary since we don't know how many ports the hub can support
557    // and we only support up to MAX_USB_DEVICES.
558    //
559    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;
560    sSetupPacket.wValue = (USB_DTYPE_HUB << 8);
561    sSetupPacket.wIndex = 0;
562    sSetupPacket.wLength = sizeof(tUsbHubDescriptor);
563
564    //
565    // Send the request.
566    //
567    ui32Read = USBHCDControlTransfer(
568        0, &sSetupPacket, psDevice, (void*)psDesc, sizeof(tUsbHubDescriptor),
569        psDevice->sDeviceDescriptor.bMaxPacketSize0);
570
571    //
572    // Make sure we got at least some data.
573    //
574    if (ui32Read == 0) {
575        return (false);
576    }
577
578    //
579    // All is well.
580    //
581    return (true);
582}
583
584//*****************************************************************************
585//
586// Open an instance of the hub driver.  This is called when the USB host
587// has enumerated a new hub device.
588//
589//*****************************************************************************
590static void* HubDriverOpen(tUSBHostDevice* psDevice) {
591    tEndpointDescriptor* psEndpointDescriptor;
592    tInterfaceDescriptor* psInterface;
593    tUsbHubDescriptor sHubDesc;
594    bool bRetcode;
595    uint32_t ui32Loop;
596
597    //
598    // If we are already talking to a hub, fail the call.  We only support
599    // a single hub.
600    //
601    if (g_sRootHub.ui32Flags & USBLIB_HUB_ACTIVE) {
602        return (0);
603    }
604
605    //
606    // Get pointers to the device descriptors we need to look at.
607    //
608    psInterface = USBDescGetInterface(psDevice->psConfigDescriptor, 0, 0);
609    psEndpointDescriptor = USBDescGetInterfaceEndpoint(
610        psInterface, 0, psDevice->ui32ConfigDescriptorSize);
611
612    //
613    // If there are no endpoints, something is wrong since a hub must have
614    // a single INT endpoint for signaling.
615    //
616    if (psEndpointDescriptor == 0) {
617        return 0;
618    }
619
620    //
621    // Make sure we really are talking to a hub.
622    //
623    if ((psInterface->bInterfaceClass != USB_CLASS_HUB) ||
624        (psInterface->bInterfaceSubClass != 0)) {
625        //
626        // Something is wrong - this isn't a hub or, if it is, we don't
627        // understand the protocol it is using.
628        //
629        return (0);
630    }
631
632    //
633    // Remember that this is a high speed hub with either single or multiple
634    // transaction translators.
635    //
636    if (psInterface->bInterfaceProtocol == USB_HUB_PROTOCOL_SINGLE) {
637        g_sRootHub.ui32Flags |= USBLIB_HUB_HS;
638    } else if (psInterface->bInterfaceProtocol == USB_HUB_PROTOCOL_MULTI) {
639        g_sRootHub.ui32Flags |= USBLIB_HUB_HS | USBLIB_HUB_MULTI_TT;
640    }
641
642    //
643    // Remember the device information for later.
644    //
645    g_sRootHub.psDevice = psDevice;
646
647    //
648    // A hub must support an interrupt endpoint so check this.
649    //
650    if ((psEndpointDescriptor->bmAttributes & USB_EP_ATTR_TYPE_M) ==
651        USB_EP_ATTR_INT) {
652        //
653        // The endpoint is the correct type. Is it an IN endpoint?
654        //
655        if (psEndpointDescriptor->bEndpointAddress & USB_EP_DESC_IN) {
656            //
657            // Yes - all is well with the hub endpoint so allocate a pipe to
658            // handle traffic from the hub.
659            //
660            g_sRootHub.ui32IntInPipe = USBHCDPipeAlloc(
661                0, USBHCD_PIPE_INTR_IN, psDevice, HubIntINCallback);
662            USBHCDPipeConfig(
663                g_sRootHub.ui32IntInPipe, psEndpointDescriptor->wMaxPacketSize,
664                psEndpointDescriptor->bInterval,
665                psEndpointDescriptor->bEndpointAddress & USB_EP_DESC_NUM_M);
666        }
667    }
668
669    //
670    // Did we allocate the endpoint successfully?
671    //
672    if (!g_sRootHub.ui32IntInPipe) {
673        //
674        // No - return an error.
675        //
676        return 0;
677    }
678
679    //
680    // Assuming we have a callback, call it to tell the owner that a hub is
681    // now connected.
682    //
683    if (g_sRootHub.pfnCallback != 0) {
684        g_sRootHub.pfnCallback((void*)g_sRootHub.ui32CBData,
685                               USB_EVENT_CONNECTED, (uint32_t)&g_sRootHub, 0);
686    }
687
688    //
689    // Get the hub descriptor and store information we'll need for later.
690    //
691    bRetcode = GetHubDescriptor(&sHubDesc);
692    if (bRetcode) {
693        //
694        // We read the descriptor successfully so extract the parts we need.
695        //
696        g_sRootHub.ui8NumPorts = sHubDesc.bNbrPorts;
697        g_sRootHub.ui16HubCharacteristics = sHubDesc.wHubCharacteristics;
698        g_sRootHub.ui8NumPortsInUse = (sHubDesc.bNbrPorts > MAX_USB_DEVICES)
699                                          ? MAX_USB_DEVICES
700                                          : sHubDesc.bNbrPorts;
701
702        //
703        // The size of the status change report that the hub sends is dependent
704        // upon the number of ports that the hub supports.  Calculate this by
705        // adding 1 to the number of ports (bit 0 of the report is the hub
706        // status, higher bits are one per port) then dividing by 8 (bits per
707        // byte) and rounding up.
708        //
709        g_sRootHub.ui8ReportSize = ((sHubDesc.bNbrPorts + 1) + 7) / 8;
710
711        //
712        // Enable power to all ports on the hub.
713        //
714        for (ui32Loop = 1; ui32Loop <= sHubDesc.bNbrPorts; ui32Loop++) {
715            //
716            // Turn on power to this port.
717            //
718            HubSetPortFeature(&g_sRootHub, ui32Loop, HUB_FEATURE_PORT_POWER);
719        }
720
721        //
722        // Clear out our port state structures.
723        //
724        for (ui32Loop = 0; ui32Loop < MAX_USB_DEVICES; ui32Loop++) {
725            g_sRootHub.psPorts[ui32Loop].bChanged = false;
726            g_sRootHub.psPorts[ui32Loop].iState = ePortIdle;
727        }
728    } else {
729        //
730        // Oops - we can't read the hub descriptor!  Tidy up and return
731        // an error.
732        //
733        USBHCDPipeFree(g_sRootHub.ui32IntInPipe);
734        g_sRootHub.pfnCallback = 0;
735        g_sRootHub.ui32Flags &= ~USBLIB_HUB_ACTIVE;
736        return (0);
737    }
738
739    //
740    // If we get here, all is well so remember that the hub is connected and
741    // active.
742    //
743    g_sRootHub.ui32Flags |= USBLIB_HUB_ACTIVE;
744
745    //
746    // Return our instance data pointer to the caller to use as a handle.
747    //
748    return ((void*)&g_sRootHub);
749}
750
751//*****************************************************************************
752//
753// Close an instance of the hub driver.
754//
755//*****************************************************************************
756static void HubDriverClose(void* pvHubDevice) {
757    uint32_t ui32Loop;
758
759    //
760    // No device so just exit.
761    //
762    if (g_sRootHub.psDevice == 0) {
763        return;
764    }
765
766    //
767    // Disconnect any devices that are currently connected to the hub.
768    //
769    for (ui32Loop = 0; ui32Loop < MAX_USB_DEVICES; ui32Loop++) {
770        //
771        // Does this port have a device connected to it that we have previously
772        // reported to the host control layer?h
773        //
774        if ((g_sRootHub.psPorts[ui32Loop].iState == ePortActive) ||
775            (g_sRootHub.psPorts[ui32Loop].iState == ePortResetWait) ||
776            (g_sRootHub.psPorts[ui32Loop].iState == ePortEnumerated) ||
777            (g_sRootHub.psPorts[ui32Loop].iState == ePortError)) {
778            //
779            // Yes - tell the host controller to disconnect the device.
780            //
781            USBHCDHubDeviceDisconnected(
782                0, g_sRootHub.psPorts[ui32Loop].ui32DevHandle);
783        }
784
785        //
786        // Make sure that the state returns to idle.
787        //
788        g_sRootHub.psPorts[ui32Loop].iState = ePortIdle;
789    }
790
791    //
792    // Reset the device pointer.
793    //
794    g_sRootHub.psDevice = 0;
795
796    //
797    // Mark the hub as absent.
798    //
799    g_sRootHub.ui32Flags &= ~USBLIB_HUB_ACTIVE;
800
801    //
802    // Note that we are not in the middle of enumerating anything.
803    //
804    g_sRootHub.bEnumerationBusy = false;
805
806    //
807    // Free the Interrupt IN pipe.
808    //
809    if (g_sRootHub.ui32IntInPipe != 0) {
810        USBHCDPipeFree(g_sRootHub.ui32IntInPipe);
811    }
812
813    //
814    // If the callback exists, call it with a DISCONNECTED event.
815    //
816    if (g_sRootHub.pfnCallback != 0) {
817        g_sRootHub.pfnCallback((void*)g_sRootHub.ui32CBData,
818                               USB_EVENT_DISCONNECTED, (uint32_t)&g_sRootHub,
819                               0);
820    }
821}
822
823//*****************************************************************************
824//
825// Perform any processing required as a result of a change in the reset
826// signaling for a given port.
827//
828//*****************************************************************************
829static void HubDriverReset(uint8_t ui8Port, bool bResetActive) {
830    //
831    // Did the reset sequence end or begin?
832    //
833    if (!bResetActive) {
834        //
835        // The reset ended.  Now wait for at least 10ms before signaling
836        // USB enumeration code that a new device is waiting to be enumerated.
837        //
838        g_sRootHub.psPorts[ui8Port].iState = ePortResetWait;
839
840        //
841        // Set the wait to 10ms (10 frames) from now.
842        //
843        g_sRootHub.psPorts[ui8Port].ui32Count = 10;
844    } else {
845        //
846        // Was this device previously active?
847        //
848        if (g_sRootHub.psPorts[ui8Port].iState == ePortActive) {
849            USBHCDHubDeviceDisconnected(
850                0, g_sRootHub.psPorts[ui8Port].ui32DevHandle);
851        }
852
853        //
854        // The reset is active so mark our port as in reset.
855        //
856        g_sRootHub.psPorts[ui8Port].iState = ePortResetActive;
857    }
858}
859
860//*****************************************************************************
861//
862// Start the process of enumerating a new device by issuing a reset to the
863// appropriate downstream port.
864//
865//*****************************************************************************
866static void HubDriverDeviceReset(uint8_t ui8Port) {
867    DEBUG_OUTPUT("Starting enumeration for port %d\n", ui8Port);
868
869    //
870    // Record the fact that we are in the process of enumerating a device.
871    //
872    g_sRootHub.bEnumerationBusy = true;
873
874    //
875    // Save the port that is being enumerated.
876    //
877    g_sRootHub.ui8EnumIdx = ui8Port;
878
879    //
880    // Mark the port as being reset.
881    //
882    g_sRootHub.psPorts[ui8Port].iState = ePortResetActive;
883
884    //
885    // Initiate a reset on the relevant port to start the enumeration process.
886    //
887    HubSetPortFeature(&g_sRootHub, ui8Port, HUB_FEATURE_PORT_RESET);
888}
889
890//*****************************************************************************
891//
892// A new device has been connected to the hub.  Allocate resources to manage
893// it and pass details back to the main USB host enumeration code to have the
894// device enumerated.
895//
896//*****************************************************************************
897static void HubDriverDeviceConnect(uint8_t ui8Port) {
898    DEBUG_OUTPUT("HubDriverDeviceConnect\n");
899
900    //
901    // We've allocated a port table entry so fill it in then initiate a reset
902    // on the device.
903    //
904    g_sRootHub.psPorts[ui8Port].bChanged = false;
905
906    //
907    // Mark the port as having a device present but not enumerated.
908    //
909    DEBUG_OUTPUT("Deferring enumeration for port %d\n", ui8Port);
910    g_sRootHub.psPorts[ui8Port].iState = ePortConnected;
911
912    //
913    // Wait 100ms to reset the device.
914    //
915    g_sRootHub.psPorts[ui8Port].ui32Count = 100;
916}
917
918//*****************************************************************************
919//
920// An existing device has been removed from the hub.  Tidy up and let the main
921// USB host code know so that it can free device resources.
922//
923//*****************************************************************************
924static void HubDriverDeviceDisconnect(uint8_t ui8Port) {
925    //
926    // This is a device we are currently managing.  Have we already informed
927    // the host controller that it is present?
928    //
929    if ((g_sRootHub.psPorts[ui8Port].iState == ePortActive) ||
930        (g_sRootHub.psPorts[ui8Port].iState == ePortResetWait) ||
931        (g_sRootHub.psPorts[ui8Port].iState == ePortEnumerated) ||
932        (g_sRootHub.psPorts[ui8Port].iState == ePortError)) {
933        //
934        // Yes - tell the host controller that the device is not longer
935        // connected.
936        //
937        USBHCDHubDeviceDisconnected(0,
938                                    g_sRootHub.psPorts[ui8Port].ui32DevHandle);
939    }
940
941    //
942    // If the device was being enumerated, make sure we clear the flag
943    // indicating that an enumeration is still ongoing.
944    //
945    if ((g_sRootHub.psPorts[ui8Port].iState == ePortResetActive) ||
946        (g_sRootHub.psPorts[ui8Port].iState == ePortResetWait) ||
947        (g_sRootHub.psPorts[ui8Port].iState == ePortActive)) {
948        g_sRootHub.bEnumerationBusy = false;
949    }
950
951    //
952    // Free up the port state structure.
953    //
954    g_sRootHub.psPorts[ui8Port].iState = ePortIdle;
955}
956
957//*****************************************************************************
958//
959// This function is called periodically by USBHCDMain().  We use it to handle
960// the hub port state machine.
961//
962//*****************************************************************************
963void USBHHubMain(void) {
964    uint16_t ui16Status, ui16Changed;
965    uint_fast8_t ui8Port;
966    bool bRetcode;
967
968    //
969    // If the hub is not present, just return.
970    //
971    if ((g_sRootHub.ui32Flags & USBLIB_HUB_ACTIVE) == 0) {
972        return;
973    }
974
975    //
976    // Initialize the status variables.
977    //
978    ui16Status = 0;
979    ui16Changed = 0;
980
981    //
982    // The hub is active and something changed. Check to see which port changed
983    // state and handle as necessary.
984    //
985    for (ui8Port = 0; ui8Port <= g_sRootHub.ui8NumPortsInUse; ui8Port++) {
986        //
987        // Decrement any wait counter if there is one present.
988        //
989        if (g_sRootHub.psPorts[ui8Port].ui32Count != 0) {
990            g_sRootHub.psPorts[ui8Port].ui32Count--;
991        }
992
993        //
994        // Is this port waiting to be enumerated and is the last device
995        // enumeration finished?
996        //
997        if ((g_sRootHub.psPorts[ui8Port].iState == ePortConnected) &&
998            (!g_sRootHub.bEnumerationBusy) &&
999            (g_sRootHub.psPorts[ui8Port].ui32Count == 0)) {
1000            //
1001            // Yes - start the enumeration processing for this device.
1002            //
1003            HubDriverDeviceReset(ui8Port);
1004        }
1005
1006        //
1007        // If the state is ePortResetWait then the hub is waiting before
1008        // accessing device as the USB 2.0 specification requires.
1009        //
1010        if ((g_sRootHub.psPorts[ui8Port].iState == ePortResetWait) &&
1011            (g_sRootHub.psPorts[ui8Port].ui32Count == 0)) {
1012            //
1013            // Start the enumeration process if the timeout has passed and
1014            // the hub is waiting to start enumerating the device.
1015            //
1016            g_sRootHub.psPorts[ui8Port].iState = ePortActive;
1017
1018            //
1019            // Call the main host controller layer to have it enumerate the
1020            // newly connected device.
1021            //
1022            g_sRootHub.psPorts[ui8Port].ui32DevHandle =
1023                USBHCDHubDeviceConnected(0, 1, ui8Port,
1024                                         g_sRootHub.psPorts[ui8Port].ui32Speed);
1025        }
1026
1027        //
1028        // If an enumeration is in progress and the loop is not on the port
1029        // being enumerated then skip the port.
1030        //
1031        if (g_sRootHub.bEnumerationBusy && (g_sRootHub.ui8EnumIdx != ui8Port)) {
1032            continue;
1033        }
1034
1035        //
1036        // Did something change for this particular port?
1037        //
1038        if (g_ui32ChangeFlags & (1 << ui8Port)) {
1039            //
1040            // Yes - query the port status.
1041            //
1042            bRetcode = HubGetPortStatus(&g_sRootHub, ui8Port, &ui16Status,
1043                                        &ui16Changed);
1044
1045            //
1046            // Clear this change with the USB interrupt temporarily disabled to
1047            // ensure that we do not clear a flag that the interrupt routine
1048            // has just set.
1049            //
1050            OS_INT_DISABLE(g_sRootHub.ui32IntNum);
1051            g_ui32ChangeFlags &= ~(1 << ui8Port);
1052            OS_INT_ENABLE(g_sRootHub.ui32IntNum);
1053
1054            //
1055            // If there was an error, go on and look at the next bit.
1056            //
1057            if (!bRetcode) {
1058                continue;
1059            }
1060
1061            //
1062            // Now consider what changed and handle it as necessary.
1063            //
1064
1065            //
1066            // Was a device connected to or disconnected from the port?
1067            //
1068            if (ui16Changed & HUB_PORT_CHANGE_DEVICE_PRESENT) {
1069                DEBUG_OUTPUT("Connection change on port %d\n", ui8Port);
1070
1071                //
1072                // Clear the condition.
1073                //
1074                HubClearPortFeature(&g_sRootHub, ui8Port,
1075                                    HUB_FEATURE_C_PORT_CONNECTION);
1076
1077                //
1078                // Was a device connected or disconnected?
1079                //
1080                if (ui16Status & HUB_PORT_STATUS_DEVICE_PRESENT) {
1081                    DEBUG_OUTPUT("Connected\n");
1082
1083                    //
1084                    // A device was connected.
1085                    //
1086                    HubDriverDeviceConnect(ui8Port);
1087                } else {
1088                    DEBUG_OUTPUT("Disconnected\n");
1089
1090                    //
1091                    // A device was disconnected.
1092                    //
1093                    HubDriverDeviceDisconnect(ui8Port);
1094                }
1095            }
1096
1097            //
1098            // Did a reset on the port complete?
1099            //
1100            if (ui16Changed & HUB_PORT_CHANGE_RESET) {
1101                //
1102                // Clear the condition.
1103                //
1104                HubClearPortFeature(&g_sRootHub, ui8Port,
1105                                    HUB_FEATURE_C_PORT_RESET);
1106
1107                //
1108                // Yes - query the port status.
1109                //
1110                bRetcode = HubGetPortStatus(&g_sRootHub, ui8Port, &ui16Status,
1111                                            &ui16Changed);
1112
1113                DEBUG_OUTPUT("Reset %s for port %d\n",
1114                             ((ui16Status & HUB_PORT_STATUS_RESET)
1115                                  ? "asserted"
1116                                  : "deasserted"),
1117                             ui8Port);
1118
1119                //
1120                // Handle the reset case.
1121                //
1122                HubDriverReset(ui8Port, (ui16Status & HUB_PORT_STATUS_RESET)
1123                                            ? true
1124                                            : false);
1125
1126                //
1127                // A device was connected.
1128                //
1129                if (ui16Status & HUB_PORT_STATUS_LOW_SPEED) {
1130                    USBHubPortSpeedSet(ui8Port, USB_EP_SPEED_LOW);
1131                } else if (ui16Status & HUB_PORT_STATUS_HIGH_SPEED) {
1132                    USBHubPortSpeedSet(ui8Port, USB_EP_SPEED_HIGH);
1133                } else {
1134                    USBHubPortSpeedSet(ui8Port, USB_EP_SPEED_FULL);
1135                }
1136            }
1137
1138            //
1139            // Did an over-current reset on the port complete?
1140            //
1141            if (ui16Changed & HUB_PORT_CHANGE_OVER_CURRENT) {
1142                DEBUG_OUTPUT("Port %d over current.\n", ui8Port);
1143
1144                //
1145                // Currently we ignore this and just clear the condition.
1146                //
1147                HubClearPortFeature(&g_sRootHub, ui8Port,
1148                                    HUB_FEATURE_C_PORT_OVER_CURRENT);
1149            }
1150
1151            //
1152            // Has the port been enabled or disabled?
1153            //
1154            if (ui16Changed & HUB_PORT_CHANGE_ENABLED) {
1155                DEBUG_OUTPUT("Enable change for port %d.\n", ui8Port);
1156
1157                //
1158                // Currently we ignore this and just clear the condition.
1159                //
1160                HubClearPortFeature(&g_sRootHub, ui8Port,
1161                                    HUB_FEATURE_C_PORT_ENABLE);
1162            }
1163
1164            //
1165            // Has the port been suspended or resumed?
1166            //
1167            if (ui16Changed & HUB_PORT_CHANGE_SUSPENDED) {
1168                DEBUG_OUTPUT("Suspend change for port %d.\n", ui8Port);
1169
1170                //
1171                // Currently we ignore this and just clear the condition.
1172                //
1173                HubClearPortFeature(&g_sRootHub, ui8Port,
1174                                    HUB_FEATURE_C_PORT_SUSPEND);
1175            }
1176        }
1177    }
1178}
1179
1180//*****************************************************************************
1181//
1182//! Informs the hub class driver that a downstream device has been enumerated.
1183//!
1184//! \param ui8Hub is the address of the hub to which the downstream device
1185//! is attached.
1186//! \param ui8Port is the port on the hub to which the downstream device is
1187//! attached.
1188//!
1189//! This function is called by the host controller driver to inform the hub
1190//! class driver that a downstream device has been enumerated successfully.
1191//! The hub driver then moves on and continues enumeration of any other newly
1192//! connected devices.
1193//!
1194//! \return None.
1195//
1196//*****************************************************************************
1197void USBHHubEnumerationComplete(uint8_t ui8Hub, uint8_t ui8Port) {
1198    DEBUG_OUTPUT("Enumeration complete for hub %d, port %d\n", ui8Hub, ui8Port);
1199
1200    //
1201    // Record the fact that the device is up and running.
1202    //
1203    g_sRootHub.psPorts[ui8Port].iState = ePortEnumerated;
1204
1205    //
1206    // Clear the flag we use to defer further enumerations.  This will cause
1207    // the next connected device (if any) to start enumeration on the next
1208    // call to USBHHubMain().
1209    //
1210    g_sRootHub.bEnumerationBusy = false;
1211}
1212
1213//*****************************************************************************
1214//
1215//! Informs the hub class driver that a downstream device failed to enumerate.
1216//!
1217//! \param ui8Hub is the address of the hub to which the downstream device
1218//! is attached.
1219//! \param ui8Port is the port on the hub to which the downstream device is
1220//! attached.
1221//!
1222//! This function is called by the host controller driver to inform the hub
1223//! class driver that an attempt to enumerate a downstream device has failed.
1224//! The hub driver then cleans up and continues enumeration of any other newly
1225//! connected devices.
1226//!
1227//! \return None.
1228//
1229//*****************************************************************************
1230void USBHHubEnumerationError(uint8_t ui8Hub, uint8_t ui8Port) {
1231    DEBUG_OUTPUT("Enumeration error for hub %d, port %d\n", ui8Hub, ui8Port);
1232
1233    //
1234    // Record the fact that the device is not working correctly.
1235    //
1236    g_sRootHub.psPorts[ui8Port].iState = ePortError;
1237
1238    //
1239    // Clear the flag we use to defer further enumerations.  This will cause
1240    // the next connected device (if any) to start enumeration on the next
1241    // call to USBHHubMain().
1242    //
1243    g_sRootHub.bEnumerationBusy = false;
1244}
1245
1246//*****************************************************************************
1247//
1248//! This function is used to enable the host hub class driver before any
1249//! devices are present.
1250//!
1251//! \param pfnCallback is the driver call back for host hub events.
1252//!
1253//! This function is called to open an instance of a host hub device and
1254//! provides a valid callback function for host hub events in the
1255//! \e pfnCallback parameter.  This function must be called before the USB
1256//! host code can successfully enumerate a hub device or any devices attached
1257//! to the hub.  The \e pui8HubPool is memory provided to the hub class to
1258//! manage the devices that are connected to the hub.  The \e ui32PoolSize is
1259//! the number of bytes and should be at least 32 bytes per device including
1260//! the hub device itself.  A simple formula for providing memory to the hub
1261//! class is \b MAX_USB_DEVICES * 32 bytes of data to allow for proper
1262//! enumeration of connected devices.  The value for \b MAX_USB_DEVICES is
1263//! defined in the usblib.h file and controls the number of devices
1264//! supported by the USB library.  The \e ui32NumHubs parameter
1265//! defaults to one and only one buffer of size tHubInstance is required to
1266//! be passed in the \e psHubInstance parameter.
1267//!
1268//! \note Changing the value of \b MAX_USB_DEVICES requires a rebuild of the
1269//! USB library to have an effect on the library.
1270//!
1271//! \return This function returns the driver instance to use for the other
1272//! host hub functions.  If there is no instance available at the time of
1273//! this call, this function returns zero.
1274//
1275//*****************************************************************************
1276tHubInstance* USBHHubOpen(tUSBHHubCallback pfnCallback) {
1277    //
1278    // Only one hub is supported.
1279    //
1280    if (g_sRootHub.pfnCallback) {
1281        DEBUG_OUTPUT("USBHHubOpen failed - already connected.\n");
1282        return (0);
1283    }
1284
1285    //
1286    // Save the instance data for this device.
1287    //
1288    g_sRootHub.pfnCallback = pfnCallback;
1289
1290    DEBUG_OUTPUT("USBHHubOpen completed.\n");
1291
1292    //
1293    // Return the device instance pointer.
1294    //
1295    return (&g_sRootHub);
1296}
1297
1298//*****************************************************************************
1299//
1300//! This function is used to release a hub device instance.
1301//!
1302//! \param psHubInstance is the hub device instance that is to be released.
1303//!
1304//! This function is called when an instance of the hub device must be
1305//! released.  This function is typically made in preparation for shutdown or a
1306//! switch to function as a USB device when in OTG mode.  Following this call,
1307//! the hub device is no longer available, but it can be opened again using a
1308//! call to USBHHubOpen().  After calling USBHHubClose(), the host hub driver
1309//! no longer provides any callbacks or accepts calls to other hub driver APIs.
1310//!
1311//! \return None.
1312//
1313//*****************************************************************************
1314void USBHHubClose(tHubInstance* psHubInstance) {
1315    //
1316    // Forget the instance pointer and callback.
1317    //
1318    psHubInstance->psDevice = 0;
1319    psHubInstance->pfnCallback = 0;
1320
1321    DEBUG_OUTPUT("USBHHubClose completed.\n");
1322}
1323
1324//*****************************************************************************
1325//
1326// This function is used to initialize the Hub driver.  This is an internal
1327// function that should not be called by the application.
1328//
1329//*****************************************************************************
1330void USBHHubInit(void) {
1331    //
1332    // Initialize Hub state.
1333    //
1334    g_ui32ChangeFlags = 0;
1335    g_ui32HubChanges = 0;
1336
1337    if (g_sRootHub.psDevice != 0) {
1338        //
1339        // Save the USB interrupt number.
1340        //
1341        g_sRootHub.ui32IntNum = INT_USB0_TM4C123;
1342
1343        //
1344        // These devices have a different USB interrupt number.
1345        //
1346        if (CLASS_IS_TM4C129) {
1347            g_sRootHub.ui32IntNum = INT_USB0_TM4C129;
1348        }
1349    }
1350}
1351
1352//*****************************************************************************
1353//
1354//! This function forwards an LPM request for a device to enter L1 sleep state.
1355//!
1356//! \param psHubInstance is the hub device instance that was returned
1357//! from the call to USBHHubOpen().
1358//!
1359//! This function forwards a request from an application to the hub device
1360//! class to request that a device enter the LPM L1 sleep state.  The
1361//! caller must check the return value to see if the request can be
1362//! attempted at this time.  If another LPM transaction is busy on this or
1363//! another device, then this function returns \b USBHCD_LPM_PENDING.  If
1364//! the LPM request was scheduled to be sent the function returns
1365//! \b USBHCD_LPM_AVAIL.  The caller should check the USBHCDLPMStatus()
1366//! function to determine if the request completed successfully or if there
1367//! was an error.
1368//!
1369//! \return This function returns the following values:
1370//! - \b USBHCD_LPM_AVAIL - The transition to L1 state is scheduled to be sent.
1371//! - \b USBHCD_LPM_PENDING - There is already an LPM request pending.
1372//
1373//*****************************************************************************
1374uint32_t USBHHubLPMSleep(tHubInstance* psHubInstance) {
1375    //
1376    // Call the host controller function to send the sleep command.
1377    //
1378    return (USBHCDLPMSleep(psHubInstance->psDevice));
1379}
1380
1381//*****************************************************************************
1382//
1383//! This function returns the current status of an LPM request.
1384//!
1385//! \param psHubInstance is the hub device instance that was returned
1386//! from the call to USBHHubOpen().
1387//!
1388//! This function returns the current status of LPM requests for a given
1389//! device.  This is called to determine if a previous request completed
1390//! successfully or if there was an error.
1391//!
1392//! \return This function returns the following values:
1393//! - \b USBHCD_LPM_AVAIL - There are no pending LPM requests on this specific
1394//!   device or the last request completed successfully.
1395//! - \b USBHCD_LPM_ERROR - The last LPM request for this device did not
1396//!   complete successfully.
1397//! - \b USBHCD_LPM_PENDING - The last LPM request has not completed.
1398//
1399//*****************************************************************************
1400uint32_t USBHHubLPMStatus(tHubInstance* psHubInstance) {
1401    //
1402    // Call the host controller function to get the current LPM status.
1403    //
1404    return (USBHCDLPMStatus(psHubInstance->psDevice));
1405}
1406
1407//*****************************************************************************
1408//
1409//! @}
1410//
1411//*****************************************************************************