summaryrefslogtreecommitdiff
path: root/usblib/host/usbhostenum.c
blob: 69b8c39f568711b170adf0d0cf019945060313af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
//*****************************************************************************
//
// usbhostenum.c - Device enumeration code for the USB host library.
//
// Copyright (c) 2008-2014 Texas Instruments Incorporated.  All rights reserved.
// Software License Agreement
// 
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
// 
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
// 
// This is part of revision 2.1.0.12573 of the Tiva USB Library.
//
//*****************************************************************************

#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_sysctl.h"
#include "inc/hw_types.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/debug.h"
#include "driverlib/interrupt.h"
#include "driverlib/sysctl.h"
#include "driverlib/usb.h"
#include "driverlib/rtos_bindings.h"
#include "usblib/usblib.h"
#include "usblib/usblibpriv.h"
#include "usblib/usbulpi.h"
#include "usblib/host/usbhost.h"
#include "usblib/host/usbhostpriv.h"
#include "usblib/host/usbhhub.h"

#ifdef INCLUDE_DEBUG_OUTPUT
#include "utils/uartstdio.h"
#define DEBUG_OUTPUT UARTprintf
#else
#define DEBUG_OUTPUT while(0)((int32_t (*)(char *, ...))0)
#endif

//*****************************************************************************
//
//! \addtogroup usblib_hcd
//! @{
//
//*****************************************************************************

//*****************************************************************************
//
// External prototypes.
//
//*****************************************************************************
extern tUSBMode g_iUSBMode;

extern void OTGDeviceDisconnect(uint32_t ui32Index);

//*****************************************************************************
//
// Internal function prototypes.
//
//*****************************************************************************
static void USBHCDEP0StateTx(void);
static void USBHCDEnumHandler(void);
static void USBHCDClearFeature(uint32_t ui32DevAddress, uint32_t ui32Endpoint,
                               uint32_t ui32Feature);

//*****************************************************************************
//
// Automatic power enable.
//
//*****************************************************************************
#define USB_HOST_PWREN_AUTO     0x00000002

//*****************************************************************************
//
// Flags used to signal between the interrupt handler and USBHCDMain().
//
//*****************************************************************************
#define INT_EVENT_VBUS_ERR      0x01
#define INT_EVENT_CONNECT       0x02
#define INT_EVENT_DISCONNECT    0x04
#define INT_EVENT_POWER_FAULT   0x08
#define INT_EVENT_SOF           0x10
#define INT_EVENT_ENUM          0x20
#define INT_EVENT_LPM_PEND      0x40
#define INT_EVENT_LPM           0x80

//*****************************************************************************
//
// Flags used with the tUSBHostDevice.ui32Flags structure member.
//
//*****************************************************************************
#define USBHDEV_FLAG_NOTIFYINT  0x00000001
#define USBHDEV_FLAG_LPMPEND    0x00000002
#define USBHDEV_FLAG_LPMERROR   0x00000004
#define USBHDEV_FLAG_ALLOCATED  0x80000000

//*****************************************************************************
//
// This holds the current power configuration that is used when USBHCDInit()
// is called.
//
//*****************************************************************************
static uint32_t g_ui32PowerConfig = USBHCD_VBUS_AUTO_HIGH;

//*****************************************************************************
//
// The states for endpoint 0 during enumeration.
//
//*****************************************************************************
typedef enum
{
    //
    // The USB device is waiting on a request from the host controller on
    // endpoint 0.
    //
    eEP0StateIdle,

    //
    // Setup packet is expecting data IN.
    //
    eEP0StateSetupIN,

    //
    // Setup packet is sending data OUT.
    //
    eEP0StateSetupOUT,

    //
    // The USB device is receiving data from the device due to an SETUP IN
    // request.
    //
    eEP0StateRx,

    //
    // The USB device has completed the IN or OUT request and is now waiting
    // for the host to acknowledge the end of the IN/OUT transaction.  This
    // is the status phase for a USB control transaction.
    //
    eEP0StateStatus,

    //
    // This state is for when a response only has a status phase and no
    // data phase.
    //
    eEP0StateStatusIN,

    //
    // This endpoint has signaled a stall condition and is waiting for the
    // stall to be acknowledged by the host controller.
    //
    eEP0StateStall,

    //
    // An error has occurred on endpoint 0.
    //
    eEP0StateError
}
tEP0State;

//*****************************************************************************
//
// This structure holds the full state for the device enumeration.
//
//*****************************************************************************
typedef struct
{
    //
    // This is the pointer to the current data being sent out or received
    // on endpoint 0.
    //
    uint8_t *pui8Data;

    //
    // This is the number of bytes that remain to be sent from or received
    // into the g_DeviceState.pEP0Data data buffer.
    //
    volatile uint32_t ui32BytesRemaining;

    //
    // The amount of data being sent/received due to a request.
    //
    uint32_t ui32DataSize;

    //
    // This is the current device address in use by endpoint 0.
    //
    uint32_t ui32DevAddress;

    //
    // The maximum packet size for the device responding to the setup packet.
    //
    uint32_t ui32MaxPacketSize;

    //
    // The host controller's state.
    //
    tEP0State iState;
}
tHostState;

//*****************************************************************************
//
// This variable holds the current state of endpoint 0.
//
//*****************************************************************************
static volatile tHostState g_sUSBHEP0State =
{
    0,                          // pui8Data
    0,                          // ui32BytesRemaining
    0,                          // ui32DataSize
    0,                          // ui32DevAddress
    0,                          // ui32MaxPacketSize
    eEP0StateIdle               // iState
};

//*****************************************************************************
//
// The global delay time for use by SysCtlDelay() function.  This is
// initialized to an appropriate value for a 50MHz clock.  The correct value
// will be set in USBHCDInit().
//
//*****************************************************************************
static uint32_t g_ui32Tickms = 0;
static volatile uint32_t g_ui32CurrentTick = 0;

//*****************************************************************************
//
// This is 480000000/60000000 or a PLL Divide of 8.
//
//*****************************************************************************
static uint32_t g_ui32PLLDiv = 8;

//*****************************************************************************
//
// Holds the ULPI configuration.
//
//*****************************************************************************
static uint32_t g_ui32ULPISupport;

//*****************************************************************************
//
// The current active drivers.
//
//*****************************************************************************
static int32_t g_pi32USBHActiveDriver[MAX_USB_DEVICES + 1];
static void *g_ppvDriverInstance[MAX_USB_DEVICES + 1];

//*****************************************************************************
//
// This is the structure used to hold the information for a given USB pipe
// that is attached to a device.
//
//*****************************************************************************
typedef struct
{
    //
    // The current address for this pipe.
    //
    tUSBHostDevice *psDevice;

    //
    // The current address for this pipe.
    //
    uint8_t ui8EPNumber;

    //
    // The DMA channel assigned to this endpoint.
    //
    uint8_t ui8DMAChannel;

    //
    // The current type for this pipe.
    //
    uint32_t ui32Type;

    //
    // The millisecond interval for this pipe.
    //
    uint32_t ui32Interval;

    //
    // The next tick value to trigger and event on this pipe.
    //
    uint32_t ui32NextEventTick;

    //
    // The current call back for this pipe.
    //
    tHCDPipeCallback pfnCallback;

    //
    // The pointer to which IN data must be copied.
    //
    uint8_t *pui8ReadPtr;

    //
    // The size of the buffer pointed to by pui8ReadPtr.
    //
    uint32_t ui32ReadSize;

    //
    // The number of bytes read, which can be less than ui32ReadSize.
    //
    uint32_t ui32DataRead;

    //
    // The state of a given USB pipe.
    //
    volatile enum
    {
        ePipeReading,
        ePipeReadDMA,
        ePipeReadDMAWait,
        ePipeReadSingle,
        ePipeDataReady,
        ePipeDataSent,
        ePipeWriting,
        ePipeWriteDMA,
        ePipeWriteDMASend,
        ePipeWriteDMAWait,
        ePipeWriteSingle,
        ePipeStalled,
        ePipeError,
        ePipeIdle,
        ePipeDisabled
    }
    iState;

    //
    // The actual FIFO offset allocated to this endpoint.
    //
    uint16_t ui16FIFOAddr;

    //
    // The size of the FIFO entry based on the size parameter.  These are
    // equivalent to the USB_FIFO_SZ_* values in usb.h.
    //
    uint8_t ui8FIFOSize;

    //
    // The bit offset in the allocation structure.
    //
    uint8_t ui8FIFOBitOffset;
}
tUSBHCDPipe;

//*****************************************************************************
//
// The internal state of the device.
//
//*****************************************************************************
typedef enum
{
    eHCDDevDisconnected,
    eHCDDevConnected,
    eHCDDevConnectedHub,
    eHCDDevRequest,
    eHCDDevReset,
    eHCDDevAddressed,
    eHCDDevConfigured,
    eHCDDevGetStrings,
    eHCDDevError,
    eHCDVBUSError,
    eHCDPowerFault,
    eHCDIdle
}
tUSBHDeviceState;

static void ProcessUSBDeviceStateMachine(tUSBHDeviceState iOldState,
                                         uint32_t ui32DevIndex);

//*****************************************************************************
//
// This is a fixed number as it relates to the maximum number of USB pipes
// available on any USB controller.  The actual number on a given device may
// be less than this number.
//
//*****************************************************************************
#define MAX_NUM_PIPES           15

//*****************************************************************************
//
// This is a fixed number as it relates to the number of USB pipes available
// in the USB controller.
//
//*****************************************************************************
#define MAX_NUM_DMA_CHANNELS    6

//*****************************************************************************
//
// Marker for an unused DMA channel slot.
//
//*****************************************************************************
#define USBHCD_DMA_UNUSED       0xff

//*****************************************************************************
//
// These definitions are used to manipulate the values returned as allocated
// USB pipes.
//
//*****************************************************************************
#define EP_PIPE_TYPE_LOW_SPEED  0x02000000
#define EP_PIPE_USE_UDMA        0x01000000
#define EP_PIPE_TYPE_ISOC       0x00800000
#define EP_PIPE_TYPE_INTR       0x00400000
#define EP_PIPE_TYPE_BULK       0x00200000
#define EP_PIPE_TYPE_CONTROL    0x00100000
#define EP_PIPE_TYPE_IN         0x00020000
#define EP_PIPE_TYPE_OUT        0x00010000
#define EP_PIPE_IDX_M           0x0000ffff

//*****************************************************************************
//
// This creates a USB pipe handle from an index.
//
//*****************************************************************************
#define OUT_PIPE_HANDLE(ui32Idx)                                              \
                                (g_sUSBHCD.psUSBOUTPipes[ui32Idx].ui32Type |  \
                                 ui32Idx)
#define IN_PIPE_HANDLE(ui32Idx) (g_sUSBHCD.psUSBINPipes[ui32Idx].ui32Type |   \
                                 ui32Idx)

//*****************************************************************************
//
// Converts from an endpoint specifier to the offset of the endpoint's
// control/status registers.
//
//*****************************************************************************
#define EP_OFFSET(Endpoint)     (Endpoint - 0x10)

//*****************************************************************************
//
// This structure holds the state information for a given host controller.
//
//*****************************************************************************
typedef struct
{
    uint32_t ui32USBBase;

    tUSBHCDPipe sUSBControlPipe;
    tUSBHCDPipe psUSBOUTPipes[MAX_NUM_PIPES];
    tUSBHCDPipe psUSBINPipes[MAX_NUM_PIPES];

    //
    // Each devices state.  We support a total of (MAX_USB_DEVICES + 1) devices
    // to allow for the use if MAX_USB_DEVICES through a single hub (which is
    // itself a device).
    //
    tUSBHostDevice psUSBDevice[MAX_USB_DEVICES + 1];

    //
    // Holds the current state of the device.
    //
    volatile tUSBHDeviceState piDeviceState[MAX_USB_DEVICES + 1];

    //
    // Pointer to the memory pool for this controller.
    //
    void *pvPool;

    //
    // The pool size for this controller.
    //
    uint32_t ui32PoolSize;

    //
    // The number of endpoint pairs supported by the controller.
    //
    uint32_t ui32NumEndpoints;

    //
    // The class drivers for this controller.
    //
    const tUSBHostClassDriver * const *ppsClassDrivers;

    //
    // The number of class drivers.
    //
    uint32_t ui32NumClassDrivers;

    //
    // This is the index in the driver list of the event driver.
    //
    int32_t i32EventDriver;

    //
    // These are the generic event information used by the event driver.
    //
    uint32_t ui32EventEnables;

    uint32_t ui32Class;

    //
    // The DMA instance information for this class.
    //
    tUSBDMAInstance *psDMAInstance;

    //
    // The interrupt number for this instance.
    //
    uint32_t ui32IntNum;

    //
    // The pending interrupt events that are processed in USBHCDMain().
    //
    uint32_t ui32IntEvents;

    //
    // Features.
    //
    uint32_t ui32Features;

    //
    // The host initiated resume duration in us.
    //
    uint32_t ui32LPMHIRD;
}
tUSBHCD;

//*****************************************************************************
//
// The global to hold all of the state information for a given host controller.
//
//*****************************************************************************
static tUSBHCD g_sUSBHCD;

//*****************************************************************************
//
// Allocates the memory needed to support configuration descriptors for
// devices.
//
//*****************************************************************************
uint32_t
ConfigDescAlloc(tUSBHostDevice *psDevice, uint32_t ui32Size)
{
    uint32_t ui32Idx, ui32BlockSize, ui32PoolSize;
    uint8_t *pui8Pool;

    if(g_sUSBHCD.psUSBDevice[0].psConfigDescriptor == 0)
    {
        //
        // 32 bit align the allocation.
        //
        ui32Size = (ui32Size + 3) & ~3;

        if(g_sUSBHCD.ui32PoolSize < ui32Size)
        {
            return(0);
        }

        //
        // Allocate the root connection to the device.
        //
        g_sUSBHCD.psUSBDevice[0].psConfigDescriptor = g_sUSBHCD.pvPool;
        g_sUSBHCD.psUSBDevice[0].ui32ConfigDescriptorSize = ui32Size;

        //
        // Allocate the hub memory pools (these can end up null).
        //
        pui8Pool = (uint8_t *)g_sUSBHCD.pvPool + ui32Size;
        ui32PoolSize = g_sUSBHCD.ui32PoolSize - ui32Size;

        //
        // Divide the pool up into blocks, one for each supported port.  We make
        // sure that each block is a multiple of 4 bytes.
        //
        ui32BlockSize = (ui32PoolSize / MAX_USB_DEVICES) & ~3;
        for(ui32Idx = 1; ui32Idx < MAX_USB_DEVICES; ui32Idx++)
        {
            g_sUSBHCD.psUSBDevice[ui32Idx].psConfigDescriptor =
                        (tConfigDescriptor *)(pui8Pool +
                                              (ui32Idx * ui32BlockSize));
            g_sUSBHCD.psUSBDevice[ui32Idx].ui32ConfigDescriptorSize =
                            ui32BlockSize;
        }
    }
    return(ui32Size);
}

//*****************************************************************************
//
// Frees the memory needed to support configuration descriptors for
// devices.
//
//*****************************************************************************
void
ConfigDescFree(tUSBHostDevice *psDevice)
{
    uint32_t ui32Idx;

    //
    // If this is the root device then deallocate.
    //
    if(&g_sUSBHCD.psUSBDevice[0] == psDevice)
    {
        for(ui32Idx = 0; ui32Idx < MAX_USB_DEVICES; ui32Idx++)
        {
            g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags &=
                                                    ~USBHDEV_FLAG_ALLOCATED;
            g_sUSBHCD.psUSBDevice[ui32Idx].psConfigDescriptor = 0;
            g_sUSBHCD.psUSBDevice[ui32Idx].ui32ConfigDescriptorSize = 0;
        }
    }
}

//*****************************************************************************
//
// Return the device index from a ui32Instance value passed from an external
// source.
//
//*****************************************************************************
static uint8_t
HCDInstanceToDevIndex(uint32_t ui32Instance)
{
    uint32_t ui32DevIndex;

    //
    // Get the device instance from the instance value.
    //
    ui32DevIndex = (ui32Instance & 0xff);

    //
    // If the above math went negative or is too large just return 0xff.
    //
    if(ui32DevIndex > MAX_USB_DEVICES)
    {
        ui32DevIndex = 0xff;
    }

    return(ui32DevIndex);
}

//=============================================================================
//
// This is the internal function that will map an event to a valid event flag.
//
// \param ui32Event specifies which event flag to retrieve.
//
// \return The event flag or 0 if there is no support event flag for the
// event specified by the \e ui32Event parameter.
//
//=============================================================================
static uint32_t
GetEventFlag(uint32_t ui32Event)
{
    uint32_t ui32EventFlag;

    ui32EventFlag = 0;

    //
    // Search for a valid event flag for the requested event.
    //
    switch(ui32Event)
    {
        case USB_EVENT_SOF:
        {
            ui32EventFlag |= USBHCD_EVFLAG_SOF;
            break;
        }
        case USB_EVENT_CONNECTED:
        {
            ui32EventFlag |= USBHCD_EVFLAG_CONNECT;
            break;
        }
        case USB_EVENT_DISCONNECTED:
        {
            ui32EventFlag |= USBHCD_EVFLAG_DISCNCT;
            break;
        }
        case USB_EVENT_UNKNOWN_CONNECTED:
        {
            ui32EventFlag |= USBHCD_EVFLAG_UNKCNCT;
            break;
        }
        case USB_EVENT_POWER_FAULT:
        {
            ui32EventFlag |= USBHCD_EVFLAG_PWRFAULT;
            break;
        }
        case USB_EVENT_POWER_DISABLE:
        {
            ui32EventFlag |= USBHCD_EVFLAG_PWRDIS;
            break;
        }
        case USB_EVENT_POWER_ENABLE:
        {
            ui32EventFlag |= USBHCD_EVFLAG_PWREN;
            break;
        }
        default:
        {
            break;
        }
    }
    return(ui32EventFlag);
}

//=============================================================================
//
//! This function is called to enable a specific USB HCD event notification.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param pvEventDriver is the event driver structure that was passed into
//! the USBHCDRegisterDrivers() function as part of the array of
//! tUSBHostClassDriver structures.
//! \param ui32Event is the event to enable.
//!
//! This function is called to enable event callbacks for a specific USB HCD
//! event.  The requested event is passed in the \e ui32Event parameter.  Not
//! all events can be enables so the function will return zero if the event
//! provided cannot be enabled.  The \e pvEventDriver is a pointer to the
//! event driver structure that the caller passed into the
//! USBHCDRegisterDrivers() function.  This structure is typically declared
//! with the DECLARE_EVENT_DRIVER() macro and included as part of the array
//! of pointers to tUSBHostClassDriver structures that is passed to the
//! USBHCDRegisterDrivers() function.
//!
//! \return This function returns a non-zero number if the event was
//! successfully enabled and returns zero if the event cannot be enabled.
//
//=============================================================================
int32_t
USBHCDEventEnable(uint32_t ui32Index, void *pvEventDriver, uint32_t ui32Event)
{
    int32_t i32Ret;
    uint32_t ui32EventFlag;

    ASSERT(ui32Index == 0);

    //
    // Default the return to fail the call unless a valid event is found.
    //
    i32Ret = 0;

    //
    // Get the event flag for this event.
    //
    ui32EventFlag = GetEventFlag(ui32Event);

    //
    // Check if there was an event flag for the corresponding event.
    //
    if(ui32EventFlag)
    {
        //
        // Set the enable for this event.
        //
        g_sUSBHCD.ui32EventEnables |= ui32EventFlag;

        //
        // Indicate that the event was valid and is now enabled.
        //
        i32Ret = 1;
    }

    return(i32Ret);
}

//=============================================================================
//
//! This function is called to disable a specific USB HCD event notification.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param pvEventDriver is the event driver structure that was passed into
//! the USBHCDRegisterDrivers() function as part of the array of
//! tUSBHostClassDriver structures.
//! \param ui32Event is the event to disable.
//!
//! This function is called to disable event callbacks for a specific USB HCD
//! event.  The requested event is passed in the \e ui32Event parameter.  Not
//! all events can be enables so the function will return zero if the event
//! provided cannot be enabled.  The \e pvEventDriver is a pointer to the
//! event driver structure that the caller passed into the
//! USBHCDRegisterDrivers() function.  This structure is typically declared
//! with the DECLARE_EVENT_DRIVER() macro and included as part of the array
//! of pointers to tUSBHostClassDriver structures that is passed to the
//! USBHCDRegisterDrivers() function.
//!
//! \return This function returns a non-zero number if the event was
//! successfully disabled and returns zero if the event cannot be disabled.
//
//=============================================================================
int32_t
USBHCDEventDisable(uint32_t ui32Index, void *pvEventDriver, uint32_t ui32Event)
{
    int32_t i32Ret;
    uint32_t ui32EventFlag;

    ASSERT(ui32Index == 0);

    //
    // Default the return to fail the call unless a valid event is found.
    //
    i32Ret = 0;

    //
    // Get the event flag for this event.
    //
    ui32EventFlag = GetEventFlag(ui32Event);

    //
    // Check if there was an event flag for the corresponding event.
    //
    if(ui32EventFlag)
    {
        //
        // Clear the enable for this event.
        //
        g_sUSBHCD.ui32EventEnables &= ~ui32EventFlag;

        //
        // Indicate that the event was valid and is now disabled.
        //
        i32Ret = 1;
    }

    return(i32Ret);
}

//*****************************************************************************
//
// If there is an event driver this function will send out a generic connection
// event USB_EVENT_UNKNOWN_CONNECTED indicating that an unknown connection
// event has occurred.
//
//*****************************************************************************
static void
SendUnknownConnect(uint32_t ui32Index, uint32_t ui32Class)
{
    tEventInfo sEvent;

    //
    // If there is an event driver registered and it has a event handler and
    // the USBHCD_EVFLAG_UNKCNCT is enabled then call the function.
    //
    sEvent.ui32Event = USB_EVENT_UNKNOWN_CONNECTED;
    sEvent.ui32Instance = ui32Class;
    InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_UNKCNCT);
}

//*****************************************************************************
//
// Internal memory allocation space is two 32-bit values where each
// bit represents a 64 byte block in the FIFO.  This requires 64 bits for
// the 4096 bytes of FIFO available.
//
//*****************************************************************************
static uint32_t g_pui32Alloc[2];

//*****************************************************************************
//
// This function handles freeing FIFO memory that has been allocated using the
// FIFOAlloc() function.
//
//*****************************************************************************
static void
FIFOFree(tUSBHCDPipe *psUSBPipe)
{
    uint32_t ui32Mask;

    //
    // Calculate the mask value to use to clear off the allocated blocks used
    // by the USB pipe specified by psUSBPipe.
    //
    ui32Mask = (1 << (psUSBPipe->ui8FIFOSize - 2)) - 1;
    ui32Mask = ui32Mask << psUSBPipe->ui8FIFOBitOffset;

    //
    // Determine which 32 bit word to access based on the size.
    //
    if(psUSBPipe->ui8FIFOSize > USB_FIFO_SZ_64)
    {
        //
        // If the FIFO size is greater than 64 then use the upper 32 bits.
        //
        g_pui32Alloc[1] &= ~ui32Mask;
    }
    else
    {
        //
        // If the FIFO size is less than or equal to 64 then use the lower
        // 32 bits.
        //
        g_pui32Alloc[0] &= ~ui32Mask;
    }
}

//*****************************************************************************
//
// This function is used to allocate FIFO memory to a given USB pipe.
//
// \param psUSBPipe is the USB pipe that needs FIFO memory allocated.
// \param ui32Size is the minimum size in bytes of the FIFO to allocate.
//
// This function will allocate \e ui32Size bytes to the USB pipe in the
// \e psUSBPipe parameter.  The function will fill the psUSBPipe structure
// members ui8FIFOSize and ui8FIFOAddr with values that can be used with the
// USBFIFOConfigSet() API.  This allocation uses a first fit algorithm.
//
// \return This function returns the size of the block allocated.
//
//*****************************************************************************
static uint32_t
FIFOAlloc(tUSBHCDPipe *psUSBPipe, uint32_t ui32Size)
{
    uint32_t ui32Blocks, ui32Start, ui32BlockSize, ui32Temp, ui32Index;
    uint16_t ui16FIFOAddr;

    //
    // Save which 32 bit value to access, the upper is for blocks greater
    // than 64 and the lower is for block 64 or less.
    //
    if(ui32Size > 64)
    {
        ui32Index = 1;
    }
    else
    {
        ui32Index = 0;
    }

    //
    // Initial FIFO address is 0.
    //
    ui16FIFOAddr = 0;

    //
    // Initialize the bit pattern and bit location.
    //
    ui32Blocks = 1;
    ui32Start = 0;

    //
    // The initial block size is always the minimum size of 64 bytes.
    //
    ui32BlockSize = 64;

    //
    // The initial size and offset are 64 and 0.
    //
    psUSBPipe->ui8FIFOBitOffset = 0;
    psUSBPipe->ui8FIFOSize = 3;

    //
    // Scan through 32 bits looking for a memory block large enough to fill
    // the request.
    //
    while(ui16FIFOAddr <= 32)
    {
        //
        // If the pattern is zero then it is a possible match.
        //
        if((g_pui32Alloc[ui32Index] & ui32Blocks) == 0)
        {
            //
            // If the size is large enough then save it and break out of the
            // loop.
            //
            if(ui32BlockSize >= ui32Size)
            {
                //
                // Mark the memory as allocated.
                //
                g_pui32Alloc[ui32Index] |= ui32Blocks;

                break;
            }

            //
            // Increment the size of the FIFO block.
            //
            psUSBPipe->ui8FIFOSize++;

            //
            // Add in a new bit to the size of the allocation.
            //
            ui32Blocks = ui32Blocks | (ui32Blocks << 1) ;

            //
            // Double the current size.
            //
            ui32BlockSize <<= 1;

        }
        else
        {
            //
            // Need to start over looking because the last allocation match
            // failed, so reset the bit offset to the current location and the
            // size to 64 bytes.
            //
            psUSBPipe->ui8FIFOBitOffset = ui16FIFOAddr;
            psUSBPipe->ui8FIFOSize = 3;

            //
            // Reset the block size to the minimum (64 bytes).
            //
            ui32BlockSize = 64;

            //
            // Store the current starting bit location and set the block mask
            // to this value.
            //
            ui32Start = 1 << ui16FIFOAddr;
            ui32Blocks = ui32Start;
        }

        //
        // Increase the address of the FIFO offset.
        //
        ui16FIFOAddr++;
    }

    //
    // If there was no block large enough then fail this call.
    //
    if(ui16FIFOAddr > 32)
    {
        ui32BlockSize = 0;
        psUSBPipe->ui16FIFOAddr = 0;
        psUSBPipe->ui8FIFOBitOffset = 0;
        psUSBPipe->ui8FIFOSize = 0;
    }
    else
    {
        //
        // Calculate the offset in the FIFO.
        //
        ui32Temp = psUSBPipe->ui8FIFOBitOffset * 64;

        //
        // Sizes greater than 64 are allocated in the second half of the FIFO
        // memory space.
        //
        if(ui32Size > 64)
        {
            ui32Temp += 2048;
        }

        //
        // Convert this to the value that can be set in the USB controller.
        //
        psUSBPipe->ui16FIFOAddr = (uint16_t)ui32Temp;
    }
    return(ui32BlockSize);
}

//*****************************************************************************
//
//! This function returns the current byte count of a USB HCD pipe.
//!
//! \param ui32Pipe is the allocated endpoint to modify.
//!
//! This call returns the current or last byte count for a transfer using the
//! pipe specified by the \e ui32Pipe parameter.  This is typically used to
//! determine the actual byte count received when a \b USB_EVENT_RX_AVAILABLE
//! occurs.
//!
//! \return If the call was successful, this function returns the number of
//! bytes transfered by the USB pipe.
//
//*****************************************************************************
uint32_t
USBHCDPipeTransferSizeGet(uint32_t ui32Pipe)
{
    uint32_t ui32Index;

    //
    // Get the index number from the allocated pipe.
    //
    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);

    return(g_sUSBHCD.psUSBINPipes[ui32Index].ui32DataRead);
}

//*****************************************************************************
//
//! This function is used to allocate a USB HCD pipe.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32EndpointType is the type of endpoint that this pipe will be
//! communicating with.
//! \param psDevice is the device instance associated with this endpoint.
//! \param ui32Size is the size of the FIFO in bytes.
//! \param pfnCallback is the function that will be called when events occur on
//! this USB Pipe.
//!
//! Since there are a limited number of USB HCD pipes that can be used in the
//! host controller, this function is used to temporarily or permanently
//! acquire one of the endpoints.  Unlike the USBHCDPipeAlloc() function this
//! function allows the caller to specify the size of the FIFO allocated to
//! this endpoint in the \e ui32Size parameter.  This function also provides a
//! method to register a callback for status changes on this endpoint.  If no
//! callbacks are desired then the \e pfnCallback function should be set to 0.
//! The callback should be used when using the USBHCDPipeSchedule() function
//! so that the caller is notified when the action is complete.
//!
//! \return This function returns a value indicating which pipe was reserved.
//! If the value is 0 then there were no pipes currently available.  This value
//! should be passed to any USBHCDPipe APIs to indicate which pipe is being
//! accessed.
//
//*****************************************************************************
uint32_t
USBHCDPipeAllocSize(uint32_t ui32Index, uint32_t ui32EndpointType,
                    tUSBHostDevice *psDevice, uint32_t ui32Size,
                    tHCDPipeCallback pfnCallback)
{
    int32_t i32Idx;

    uint32_t ui32HubAddr;

    ASSERT(ui32Index == 0);

    //
    // Find a USB pipe that is free.
    //
    for(i32Idx = 0; i32Idx < MAX_NUM_PIPES; i32Idx++)
    {
        //
        // Handle OUT Pipes.
        //
        if(ui32EndpointType & EP_PIPE_TYPE_OUT)
        {
            //
            // A zero address indicates free.
            //
            if(g_sUSBHCD.psUSBOUTPipes[i32Idx].psDevice == 0)
            {
                //
                // Set up uDMA for the pipe.
                //
                if(ui32EndpointType & EP_PIPE_USE_UDMA)
                {
                    //
                    // Allocate a DMA channel to the endpoint.
                    //
                    g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8DMAChannel =
                        USBLibDMAChannelAllocate(g_sUSBHCD.psDMAInstance,
                                                 IndexToUSBEP(i32Idx + 1),
                                                 ui32Size,
                                                 USB_DMA_EP_TX |
                                                 USB_DMA_EP_HOST);

                    //
                    // If no DMA channel was available then just disable DMA
                    // on this pipe.
                    //
                    if(g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8DMAChannel == 0)
                    {
                        ui32EndpointType &= ~EP_PIPE_USE_UDMA;
                    }
                }

                //
                // Save the endpoint type and device address and callback
                // function.
                //
                g_sUSBHCD.psUSBOUTPipes[i32Idx].ui32Type = ui32EndpointType;
                g_sUSBHCD.psUSBOUTPipes[i32Idx].psDevice = psDevice;
                g_sUSBHCD.psUSBOUTPipes[i32Idx].pfnCallback = pfnCallback;

                //
                // Clear out any pending status on this endpoint in case it
                // was in use before a allowing a new device class to use it.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE,
                                               IndexToUSBEP(i32Idx + 1),
                                               USB_HOST_OUT_STATUS);

                //
                // Make sure to reset the data toggle.
                //
                USBEndpointDataToggleClear(USB0_BASE, IndexToUSBEP(i32Idx + 1),
                                           USB_EP_HOST_OUT);

                //
                // Initialize the endpoint as idle.
                //
                g_sUSBHCD.psUSBOUTPipes[i32Idx].iState = ePipeIdle;

                //
                // Allocate space in the FIFO for this endpoint.
                //
                if(FIFOAlloc(&g_sUSBHCD.psUSBOUTPipes[i32Idx], ui32Size) != 0)
                {
                    //
                    // Configure the FIFO.
                    //
                    MAP_USBFIFOConfigSet(USB0_BASE,
                                IndexToUSBEP(i32Idx + 1),
                                g_sUSBHCD.psUSBOUTPipes[i32Idx].ui16FIFOAddr,
                                g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8FIFOSize,
                                USB_EP_HOST_OUT);
                }

                //
                // Set the function address for this endpoint.
                //
                MAP_USBHostAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
                                   psDevice->ui32Address, USB_EP_HOST_OUT);

                //
                // Set the hub and port address for the endpoint.
                //
                ui32HubAddr = psDevice->ui8Hub | (psDevice->ui8HubPort << 8);
                USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
                                  ui32HubAddr, (USB_EP_HOST_OUT |
                                                psDevice->ui32Speed));
                break;
            }
        }
        //
        // Handle IN Pipes.
        //
        else if(ui32EndpointType & EP_PIPE_TYPE_IN)
        {
            //
            // A zero address indicates free.
            //
            if(g_sUSBHCD.psUSBINPipes[i32Idx].psDevice == 0)
            {
                //
                // Set up uDMA for the pipe.
                //
                if(ui32EndpointType & EP_PIPE_USE_UDMA)
                {
                    //
                    // Allocate a DMA channel to the endpoint.
                    //
                    g_sUSBHCD.psUSBINPipes[i32Idx].ui8DMAChannel =
                            USBLibDMAChannelAllocate(g_sUSBHCD.psDMAInstance,
                                                     IndexToUSBEP(i32Idx + 1),
                                                     ui32Size,
                                                     USB_DMA_EP_RX |
                                                     USB_DMA_EP_HOST);

                    //
                    // If no DMA channel was available then just disable DMA
                    // on this pipe.
                    //
                    if(g_sUSBHCD.psUSBINPipes[i32Idx].ui8DMAChannel == 0)
                    {
                        ui32EndpointType &= ~EP_PIPE_USE_UDMA;
                    }
                }

                //
                // Save the endpoint type and device address and callback
                // function.
                //
                g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type = ui32EndpointType;
                g_sUSBHCD.psUSBINPipes[i32Idx].psDevice = psDevice;
                g_sUSBHCD.psUSBINPipes[i32Idx].pfnCallback = pfnCallback;

                //
                // Clear out any pending status on this endpoint in case it
                // was in use before a allowing a new device class to use it.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE,
                                               IndexToUSBEP(i32Idx + 1),
                                               USB_HOST_IN_STATUS);

                //
                // Make sure to reset the data toggle.
                //
                USBEndpointDataToggleClear(USB0_BASE, IndexToUSBEP(i32Idx + 1),
                                           USB_EP_HOST_IN);

                //
                // Allocate space in the FIFO for this endpoint.
                //
                if(FIFOAlloc(&g_sUSBHCD.psUSBINPipes[i32Idx], ui32Size) != 0)
                {
                    //
                    // Configure the FIFO.
                    //
                    MAP_USBFIFOConfigSet(USB0_BASE,
                                IndexToUSBEP(i32Idx + 1),
                                g_sUSBHCD.psUSBINPipes[i32Idx].ui16FIFOAddr,
                                g_sUSBHCD.psUSBINPipes[i32Idx].ui8FIFOSize,
                                USB_EP_HOST_IN);
                }

                //
                // Set the function address for this endpoint.
                //
                MAP_USBHostAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
                                   psDevice->ui32Address, USB_EP_HOST_IN);

                //
                // Set the hub and port address for the endpoint.
                //
                ui32HubAddr = psDevice->ui8Hub | (psDevice->ui8HubPort << 8);
                USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(i32Idx + 1),
                                  ui32HubAddr, (USB_EP_HOST_IN |
                                                psDevice->ui32Speed));

                //
                // Reset the state of the pipe to idle.
                //
                g_sUSBHCD.psUSBINPipes[i32Idx].iState = ePipeIdle;

                break;
            }
        }
    }

    //
    // Did not find a free pipe.
    //
    if(i32Idx == MAX_NUM_PIPES)
    {
        return(0);
    }

    //
    // Return the pipe index and type that was allocated.
    //
    return(ui32EndpointType | i32Idx);
}

//*****************************************************************************
//
//! This function is used to allocate a USB HCD pipe.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32EndpointType is the type of endpoint that this pipe will be
//! communicating with.
//! \param psDevice is the device instance associated with this endpoint.
//! \param pfnCallback is the function that will be called when events occur on
//! this USB Pipe.
//!
//! Since there are a limited number of USB HCD pipes that can be used in the
//! host controller, this function is used to temporarily or permanently
//! acquire one of the endpoints.  It also provides a method to register a
//! callback for status changes on this endpoint.  If no callbacks are desired
//! then the \e pfnCallback function should be set to 0.  The callback should
//! be used when using the USBHCDPipeSchedule() function so that the caller is
//! notified when the action is complete.
//!
//! \return This function returns a value indicating which pipe was reserved.
//! If the value is 0 then there were no pipes currently available.  This value
//! should be passed to any USBHCDPipe APIs to indicate which pipe is being
//! accessed.
//
//*****************************************************************************
uint32_t
USBHCDPipeAlloc(uint32_t ui32Index, uint32_t ui32EndpointType,
                tUSBHostDevice *psDevice, tHCDPipeCallback pfnCallback)
{
    //
    // The old API allocated only 64 bytes to each endpoint.
    //
    return(USBHCDPipeAllocSize(ui32Index, ui32EndpointType, psDevice, 64,
                               pfnCallback));
}

//*****************************************************************************
//
//! This function is used to configure a USB HCD pipe.
//!
//! This should be called after allocating a USB pipe with a call to
//! USBHCDPipeAlloc().  It is used to set the configuration associated with an
//! endpoint like the max payload and target endpoint.  The \e ui32MaxPayload
//! parameter is typically read directly from the devices endpoint descriptor
//! and is expressed in bytes.
//!
//! Setting the \e ui32Interval parameter depends on the type of endpoint being
//! configured.  For endpoints that do not need to use the \e ui32Interval
//! parameter \e ui32Interval should be set to 0.  For Bulk \e ui32Interval is
//! a value from 2-16 and will set the NAK timeout value as
//! 2^(\e ui32Interval-1) frames.  For interrupt endpoints \e ui32Interval is a
//! value from 1-255 and is the count in frames between polling the endpoint.
//! For isochronous endpoints \e ui32Interval ranges from 1-16 and is the
//! polling interval in frames represented as 2^(\e ui32Interval-1) frames.
//!
//! \param ui32Pipe is the allocated endpoint to modify.
//! \param ui32MaxPayload is maximum data that can be handled per transaction.
//! \param ui32Interval is the polling interval for data transfers expressed in
//! frames.
//! \param ui32TargetEndpoint is the target endpoint on the device to
//! communicate with.
//!
//! \return If the call was successful, this function returns zero any other
//! value indicates an error.
//
//*****************************************************************************
uint32_t
USBHCDPipeConfig(uint32_t ui32Pipe, uint32_t ui32MaxPayload,
                 uint32_t ui32Interval, uint32_t ui32TargetEndpoint)
{
    uint32_t ui32Flags;
    uint32_t ui32Index;

    //
    // Get the index number from the allocated pipe.
    //
    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);

    //
    // Set the direction.
    //
    if(ui32Pipe & EP_PIPE_TYPE_OUT)
    {
        //
        // Set the mode for this endpoint.
        //
        if(g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type & EP_PIPE_TYPE_BULK)
        {
            ui32Flags = USB_EP_MODE_BULK;
        }
        else if(g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type &
                EP_PIPE_TYPE_INTR)
        {
            ui32Flags = USB_EP_MODE_INT;
        }
        else if(g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type &
                EP_PIPE_TYPE_ISOC)
        {
            ui32Flags = USB_EP_MODE_ISOC;
        }
        else
        {
            ui32Flags = USB_EP_MODE_CTRL;
        }

        ui32Flags |= USB_EP_HOST_OUT;

        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8EPNumber =
                                                (uint8_t)ui32TargetEndpoint;

        //
        // Save the interval and the next tick to trigger a scheduler event.
        //
        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Interval = ui32Interval;
        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32NextEventTick =
                                            ui32Interval + g_ui32CurrentTick;

        //
        // Set the device speed.
        //
        ui32Flags |= (g_sUSBHCD.psUSBOUTPipes[ui32Index].psDevice->ui32Speed);

        //
        // Set up the appropriate flags if uDMA is used.
        //
        if(ui32Pipe & EP_PIPE_USE_UDMA)
        {
            ui32Flags |= USB_EP_DMA_MODE_0 | USB_EP_AUTO_SET;
        }
    }
    else
    {
        //
        // Set the mode for this endpoint.
        //
        if(g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type & EP_PIPE_TYPE_BULK)
        {
            ui32Flags = USB_EP_MODE_BULK;
        }
        else if(g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type & EP_PIPE_TYPE_INTR)
        {
            ui32Flags = USB_EP_MODE_INT;
        }
        else if(g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type & EP_PIPE_TYPE_ISOC)
        {
            ui32Flags = USB_EP_MODE_ISOC;
        }
        else
        {
            ui32Flags = USB_EP_MODE_CTRL;
        }
        ui32Flags |= USB_EP_HOST_IN;

        g_sUSBHCD.psUSBINPipes[ui32Index].ui8EPNumber =
                                                (uint8_t)ui32TargetEndpoint;

        //
        // Save the interval and the next tick to trigger a scheduler event.
        //
        g_sUSBHCD.psUSBINPipes[ui32Index].ui32Interval = ui32Interval;
        g_sUSBHCD.psUSBINPipes[ui32Index].ui32NextEventTick =
                                            ui32Interval + g_ui32CurrentTick;

        //
        // Set the device speed.
        //
        ui32Flags |= g_sUSBHCD.psUSBINPipes[ui32Index].psDevice->ui32Speed;
        //
        // Set up the appropriate flags if uDMA is used.
        //
        if(ui32Pipe & EP_PIPE_USE_UDMA)
        {
            ui32Flags |= USB_EP_DMA_MODE_1 | USB_EP_AUTO_CLEAR |
                         USB_EP_AUTO_REQUEST;
        }
    }


    //
    // Configure the endpoint according to the flags determined above.
    //
    USBHostEndpointConfig(USB0_BASE,
                          IndexToUSBEP((ui32Pipe & EP_PIPE_IDX_M) + 1),
                          ui32MaxPayload, ui32Interval, ui32TargetEndpoint,
                          ui32Flags);

    return(0);
}

//*****************************************************************************
//
//! This function is used to return the current status of a USB HCD pipe.
//!
//! This function will return the current status for a given USB pipe.  If
//! there is no status to report this call will simply return
//! \b USBHCD_PIPE_NO_CHANGE.
//!
//! \param ui32Pipe is the USB pipe for this status request.
//!
//! \return This function returns the current status for the given endpoint.
//! This will be one of the \b USBHCD_PIPE_* values.
//
//*****************************************************************************
uint32_t
USBHCDPipeStatus(uint32_t ui32Pipe)
{
    return(0);
}

//*****************************************************************************
//
//! This function is used to write data to a USB HCD pipe.
//!
//! \param ui32Pipe is the USB pipe to put data into.
//! \param pui8Data is a pointer to the data to send.
//! \param ui32Size is the amount of data to send.
//!
//! This function will block until it has sent as much data as was
//! requested using the USB pipe's FIFO.  The caller should have registered a
//! callback with the USBHCDPipeAlloc() call in order to be informed when the
//! data has been transmitted.  The value returned by this function can be less
//! than the \e ui32Size requested if the USB pipe has less space available
//! than this request is making.
//!
//! \return This function returns the number of bytes that were scheduled to
//! be sent on the given USB pipe.
//
//*****************************************************************************
uint32_t
USBHCDPipeWrite(uint32_t ui32Pipe, uint8_t *pui8Data, uint32_t ui32Size)
{
    uint32_t ui32Endpoint, ui32RemainingBytes, ui32ByteToSend, ui32PipeIdx;
    bool bUseDMA;

    //
    // Determine which endpoint interface that this pipe is using.
    //
    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);

    //
    // Get index used for looking up pipe data
    //
    ui32PipeIdx = ui32Pipe & EP_PIPE_IDX_M;

    //
    // Set the total number of bytes to send out.
    //
    ui32RemainingBytes = ui32Size;

    //
    // Default to using DMA.
    //
    bUseDMA = false;

    //
    // Initialize the bytes to send to all of the remaining bytes.
    //
    ui32ByteToSend = ui32RemainingBytes;

    //
    // Send all of the requested data.
    //
    while(ui32RemainingBytes != 0)
    {
        //
        // If uDMA is not enabled for this pipe, or if the uDMA workaround
        // is applied, then don't use uDMA for this transfer.
        //
        if(ui32Pipe & EP_PIPE_USE_UDMA)
        {
            //
            // Disable the USB interrupt.
            //
            OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

            //
            // Start the DMA transfer.
            //
            if(USBLibDMATransfer(g_sUSBHCD.psDMAInstance,
                            g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].ui8DMAChannel,
                            pui8Data, ui32RemainingBytes) != 0)
            {
                if(ui32RemainingBytes < 64)
                {
                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState =
                                                            ePipeWriteDMASend;
                }
                else if((ui32RemainingBytes % 64) == 0)
                {
                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState =
                                                                ePipeWriteDMA;
                }
                else
                {
                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState =
                                                        ePipeWriteDMASend;
                }

                bUseDMA = true;
            }

            //
            // Enable the USB interrupt.
            //
            OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
        }

        if(bUseDMA == false)
        {
            //
            // Only send 64 bytes at a time if not using DMA.
            //
            if(ui32ByteToSend > 64)
            {
                ui32ByteToSend = 64;
            }
            else
            {
                //
                // Send the requested number of bytes.
                //
                ui32ByteToSend = ui32RemainingBytes;
            }

            //
            // Start a write request.
            //
            g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeWriting;

            //
            // Disable uDMA on the USB endpoint
            //
            MAP_USBEndpointDMADisable(USB0_BASE, ui32Endpoint,
                                      USB_EP_HOST_OUT);

            //
            // Put the data in the buffer.
            //
            MAP_USBEndpointDataPut(USB0_BASE, ui32Endpoint, pui8Data,
                                   ui32ByteToSend);

            //
            // Schedule the data to be sent.
            //
            MAP_USBEndpointDataSend(USB0_BASE, ui32Endpoint, USB_TRANS_OUT);
        }

        //
        // Wait for a status change.
        //
        while(1)
        {
            //
            // If an error event occurs then exit out of the loop.
            //
            if(g_sUSBHCD.ui32IntEvents & (INT_EVENT_DISCONNECT |
                                          INT_EVENT_VBUS_ERR |
                                          INT_EVENT_POWER_FAULT))
            {
                //
                // Set the pipe state to error.
                //
                g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeError;

                //
                // Needs to be set to exit out of large while loop.
                //
                ui32RemainingBytes = 0;

                break;
            }
            //
            // If the data was successfully sent then decrement the count and
            // continue.
            //
            else if(g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState ==
                    ePipeDataSent)
            {
                //
                // Decrement the remaining data and advance the pointer.
                //
                ui32RemainingBytes -= ui32ByteToSend;
                pui8Data += ui32ByteToSend;

                //
                // If there are less than 64 bytes to send then this is the
                // last of the data to go out.
                //
                if(ui32RemainingBytes < 64)
                {
                    ui32ByteToSend = ui32RemainingBytes;
                }
                break;
            }
            else if(g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState ==
                    ePipeStalled)
            {
                //
                // Zero out the size so that the caller knows that no data was
                // written.
                //
                ui32Size = 0;

                //
                // Needs to be set to exit out of large while loop.
                //
                ui32RemainingBytes = 0;

                //
                // If DMA is being used, then disable the channel.
                //
                if(bUseDMA == true)
                {
                    //
                    // Disable the DMA channel.
                    //
                    USBLibDMAChannelDisable(g_sUSBHCD.psDMAInstance,
                        g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].ui8DMAChannel);
                }

                //
                // This is the actual endpoint number.
                //
                USBHCDClearFeature(
                    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].psDevice->ui32Address,
                    ui32Pipe, USB_FEATURE_EP_HALT);

                //
                // If there was a stall, then no more data is coming so break
                // out.
                //
                break;
            }
            else if(g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState == ePipeError)
            {
                //
                // An error occurred so stop this transaction and set the
                // number of bytes to zero.
                //
                ui32Size = 0;

                //
                // Needs to be set to exit out of large while loop.
                //
                ui32RemainingBytes = 0;

                break;
            }
        }
    }

    //
    // Go Idle once this state has been reached.
    //
    g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].iState = ePipeIdle;

    return(ui32Size);
}

//*****************************************************************************
//
//! This function is used to schedule and IN transaction on a USB HCD pipe.
//!
//! \param ui32Pipe is the USB pipe to read data from.
//! \param pui8Data is a pointer to store the data that is received.
//! \param ui32Size is the size in bytes of the buffer pointed to by
//! \e pui8Data.
//!
//! This function will not block depending on the type of pipe passed in will
//! schedule either a send of data to the device or a read of data from the
//! device.  In either case the amount of data will be limited to what will
//! fit in the FIFO for a given endpoint.
//!
//! \return This function returns the number of bytes that were sent in the
//! case of a transfer of data or it will return 0 for a request on a USB IN
//! pipe.
//
//*****************************************************************************
uint32_t
USBHCDPipeSchedule(uint32_t ui32Pipe, uint8_t *pui8Data, uint32_t ui32Size)
{
    uint32_t ui32Endpoint, ui32PipeIdx;

    //
    // Get index used for looking up pipe data
    //
    ui32PipeIdx = ui32Pipe & EP_PIPE_IDX_M;

    //
    // Determine which endpoint interface that this pipe is using.
    //
    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);

    if(ui32Pipe & EP_PIPE_TYPE_OUT)
    {
        //
        // Check if uDMA is enabled on this pipe.
        //
        if(ui32Pipe & EP_PIPE_USE_UDMA)
        {
            //
            // Start a write request.
            //
            g_sUSBHCD.psUSBOUTPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
                                                            ePipeWriteDMASend;

            USBLibDMATransfer(g_sUSBHCD.psDMAInstance,
                            g_sUSBHCD.psUSBOUTPipes[ui32PipeIdx].ui8DMAChannel,
                            pui8Data, ui32Size);
        }
        else
        {
            //
            // Start a write request.
            //
            g_sUSBHCD.psUSBOUTPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
                                                                ePipeWriting;

            //
            // Put the data in the buffer.
            //
            MAP_USBEndpointDataPut(USB0_BASE, ui32Endpoint, pui8Data,
                                   ui32Size);

            //
            // Schedule the data to be sent.
            //
            MAP_USBEndpointDataSend(USB0_BASE, ui32Endpoint, USB_TRANS_OUT);
        }
    }
    else
    {
        //
        // If uDMA is not enabled for this pipe, or if the uDMA workaround
        // is applied, then do not use uDMA for this transfer.
        //
        if((ui32Pipe & EP_PIPE_USE_UDMA) == 0)
        {
            //
            // Start a read request.
            //
            g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
                                                                ePipeReading;

            //
            // Disable uDMA on the endpoint
            //
            MAP_USBEndpointDMADisable(USB0_BASE, ui32Endpoint, USB_EP_HOST_IN);
        }
        //
        // Otherwise, uDMA should be used for this transfer, so set up
        // the uDMA channel in advance of triggering the IN request.
        //
        else
        {
            g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState =
                                                                ePipeReadDMA;

            USBLibDMATransfer(g_sUSBHCD.psDMAInstance,
                            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel,
                            pui8Data, ui32Size);
        }

        //
        // Remember details of the buffer into which the data will be read.
        //
        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].pui8ReadPtr = pui8Data;
        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui32ReadSize = ui32Size;

        //
        // Trigger a request for data from the device.
        //
        MAP_USBHostRequestIN(USB0_BASE, ui32Endpoint);

        //
        // No data was put into or read from the buffer.
        //
        ui32Size = 0;
    }
    return(ui32Size);
}

//*****************************************************************************
//
//! This function is used to read data from a USB HCD pipe.
//!
//! \param ui32Pipe is the USB pipe to read data from.
//! \param pui8Data is a pointer to store the data that is received.
//! \param ui32Size is the size in bytes of the buffer pointed to by
//! \e pui8Data.
//!
//! This function will not block and will only read as much data as requested
//! or as much data is currently available from the USB pipe.  The caller
//! should have registered a callback with the USBHCDPipeAlloc() call in order
//! to be informed when the data has been received.  The value returned by this
//! function can be less than the \e ui32Size requested if the USB pipe has
//! less data available than was requested.
//!
//! \return This function returns the number of bytes that were returned in the
//! \e pui8Data buffer.
//
//*****************************************************************************
uint32_t
USBHCDPipeReadNonBlocking(uint32_t ui32Pipe, uint8_t *pui8Data,
                          uint32_t ui32Size)
{
    uint32_t ui32Endpoint;

    //
    // Determine which endpoint interface that this pipe is using.
    //
    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);

    //
    // Read the data out of the USB endpoint interface.
    //
    MAP_USBEndpointDataGet(USB0_BASE, ui32Endpoint, pui8Data, &ui32Size);

    //
    // Acknowledge that the data was read from the endpoint.
    //
    MAP_USBHostEndpointDataAck(USB0_BASE, ui32Endpoint);

    //
    // Go Idle once this state has been reached.
    //
    g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState = ePipeIdle;

    return(ui32Size);
}

//*****************************************************************************
//
//! This function acknowledges data received via an interrupt IN pipe.
//!
//! \param ui32Pipe is the USB INT pipe whose last packet is to be
//! acknowledged.
//!
//! This function is used to acknowledge reception of data on an interrupt IN
//! pipe.  A transfer on an interrupt IN endpoint is scheduled via a call to
//! USBHCDPipeSchedule() and the application is notified when data is received
//! using a \b USB_EVENT_RX_AVAILABLE event.  In the handler for this event,
//! the application must call USBHCDPipeDataAck() to have the USB controller
//! ACK the data from the device and complete the transaction.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDPipeDataAck(uint32_t ui32Pipe)
{
    uint32_t ui32Endpoint;

    //
    // Determine which endpoint interface that this pipe is using.
    //
    ui32Endpoint = IndexToUSBEP((EP_PIPE_IDX_M & ui32Pipe) + 1);

    //
    // Acknowledge that the data was read from the endpoint.
    //
    USBHostEndpointDataAck(USB0_BASE, ui32Endpoint);

    //
    // Go Idle once this state has been reached.
    //
    g_sUSBHCD.psUSBINPipes[EP_PIPE_IDX_M & ui32Pipe].iState = ePipeIdle;
}

//*****************************************************************************
//
//! This function is used to read data from a USB HCD pipe.
//!
//! \param ui32Pipe is the USB pipe to read data from.
//! \param pui8Data is a pointer to store the data that is received.
//! \param ui32Size is the size in bytes of the buffer pointed to by
//! \e pui8Data.
//!
//! This function will block and will only return when it has read as much data
//! as requested from the USB pipe.  The caller must register a callback with
//! the USBHCDPipeAlloc() call in order to be informed when the data has been
//! received.  If the caller provides a non-zero pointer in the \e pui8Data
//! parameter then the data is copied into the buffer before the callback
//! occurs.  If the caller provides a zero in \e pui8Data parameter
//! then the caller is responsible for reading the data out of the FIFO when
//! the \b USB_EVENT_RX_AVAILABLE callback event occurs.   The value returned
//! by this function can be less than the \e ui32Size requested if the USB pipe
//! has less data available than was requested.
//!
//! \return This function returns the number of bytes that were returned in the
//! \e pui8Data buffer.
//
//*****************************************************************************
uint32_t
USBHCDPipeRead(uint32_t ui32Pipe, uint8_t *pui8Data, uint32_t ui32Size)
{
    uint32_t ui32Endpoint, ui32RemainingBytes, ui32BytesRead, ui32PipeIdx;
    bool bUseDMA;

    //
    // Get index used for looking up pipe data
    //
    ui32PipeIdx = ui32Pipe & EP_PIPE_IDX_M;

    //
    // Initialized the number of bytes read.
    //
    ui32BytesRead = 0;

    //
    // Determine which endpoint interface that this pipe is using.
    //
    ui32Endpoint = IndexToUSBEP(ui32PipeIdx + 1);

    //
    // Set the remaining bytes to received.
    //
    ui32RemainingBytes = ui32Size;

    //
    // Default to using DMA.
    //
    bUseDMA = true;

    //
    // Continue until all data requested has been received.
    //
    while(ui32RemainingBytes != 0)
    {
        //
        // Start a read request.
        //
        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeReading;

        //
        // Try the DMA transfer should be used for this transfer, so set up
        // the uDMA channel in advance of triggering the IN request.
        //
        if(ui32Pipe & EP_PIPE_USE_UDMA)
        {
            //
            // Disable the USB interrupt.
            //
            OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

            if(USBLibDMATransfer(g_sUSBHCD.psDMAInstance,
                            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel,
                            pui8Data, ui32Size) != 0)
            {
                g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeReadDMA;

                ui32BytesRead = ui32Size;
            }
            else
            {
                bUseDMA = false;
            }

            //
            // Disable the USB interrupt.
            //
            OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
        }

        //
        // If unable to use DMA then get ready to transfer without DMA.
        //
        if(bUseDMA == false)
        {
            //
            // Disable uDMA on the endpoint
            //
            MAP_USBEndpointDMADisable(USB0_BASE, ui32Endpoint, USB_EP_HOST_IN);

            //
            // Set up for the next transaction.
            //
            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].pui8ReadPtr = pui8Data;
            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui32ReadSize =
                        (ui32RemainingBytes < 64) ? ui32RemainingBytes : 64;
        }

        //
        // Trigger a request for data from the device.
        //
        MAP_USBHostRequestIN(USB0_BASE, ui32Endpoint);

        //
        // Wait for a status change.
        //
        while(1)
        {
            //
            // Check if the device stalled the request.
            //
            if(g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState == ePipeStalled)
            {
                //
                // Zero out the size so that the caller knows that no data was
                // read.
                //
                ui32Size = 0;

                //
                // There are also no remaining bytes to read.
                //
                ui32RemainingBytes = 0;

                //
                // If DMA is being used, then disable the channel.
                //
                if(bUseDMA == true)
                {
                    USBLibDMAChannelDisable(
                            g_sUSBHCD.psDMAInstance,
                            g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel);
                }

                //
                // This is the actual endpoint number.
                //
                USBHCDClearFeature(
                    g_sUSBHCD.psUSBINPipes[ui32PipeIdx].psDevice->ui32Address,
                    ui32Pipe, USB_FEATURE_EP_HALT);

                //
                // If there was a stall, then no more data is coming so break
                // out.
                //
                break;
            }

            //
            // If any error event occurs then exit out of the loop.
            //
            if(g_sUSBHCD.ui32IntEvents & (INT_EVENT_DISCONNECT |
                                          INT_EVENT_VBUS_ERR |
                                          INT_EVENT_POWER_FAULT))
            {
                //
                // Set the pipe state to error.
                //
                g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeError;
                break;
            }

            //
            // If data is ready then return it.
            //
            if(g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState == ePipeDataReady)
            {
                //
                // If not using DMA then read the data from the USB.  Otherwise
                // the data will already be in the buffer.
                //
                if(bUseDMA == false)
                {
                    //
                    // Compute bytes to transfer and set up transfer
                    //
                    ui32BytesRead =
                            ui32RemainingBytes > 64 ? 64 : ui32RemainingBytes;

                    //
                    // Acknowledge that the data was read from the endpoint.
                    //
                    MAP_USBHostEndpointDataAck(USB0_BASE, ui32Endpoint);
                }

                //
                // Subtract the number of bytes read from the bytes remaining.
                //
                ui32RemainingBytes -= ui32BytesRead;

                //
                // If there were less than 64 bytes read, then this was a short
                // packet and no more data will be returned.
                //
                if(ui32BytesRead < 64)
                {
                    //
                    // Subtract off the bytes that were not received and exit
                    // the loop.
                    //
                    ui32Size = ui32Size - ui32RemainingBytes;
                    break;
                }
                else
                {
                    //
                    // Move the buffer ahead to receive more data into the
                    // buffer.
                    //
                    pui8Data += 64;
                }
                break;
            }
            else if(g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState == ePipeError)
            {
                //
                // An error occurred so stop this transaction and set the
                // number of bytes to zero.
                //
                ui32Size = 0;
                ui32RemainingBytes = 0;

                break;
            }
            else if((g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState ==
                     ePipeReadDMAWait) &&
                    (USBLibDMAChannelStatus(g_sUSBHCD.psDMAInstance,
                        g_sUSBHCD.psUSBINPipes[ui32PipeIdx].ui8DMAChannel) &
                     USBLIBSTATUS_DMA_COMPLETE))
            {
                break;
            }
        }
    }

    //
    // Go Idle once this state has been reached.
    //
    g_sUSBHCD.psUSBINPipes[ui32PipeIdx].iState = ePipeIdle;

    return(ui32Size);
}

//*****************************************************************************
//
//! This function is used to release a USB pipe.
//!
//! \param ui32Pipe is the allocated USB pipe to release.
//!
//! This function is used to release a USB pipe that was allocated by a call to
//! USBHCDPipeAlloc() for use by some other device endpoint in the system.
//! Freeing an unallocated or invalid pipe will not generate an error and will
//! instead simply return.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDPipeFree(uint32_t ui32Pipe)
{
    uint32_t ui32Index;

    //
    // Get the index number from the allocated pipe.
    //
    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);

    if(ui32Pipe & EP_PIPE_TYPE_OUT)
    {
        //
        // Clear the address and type for this endpoint to free it up.
        //
        g_sUSBHCD.psUSBOUTPipes[ui32Index].psDevice = 0;
        g_sUSBHCD.psUSBOUTPipes[ui32Index].ui32Type = 0;
        g_sUSBHCD.psUSBOUTPipes[ui32Index].pfnCallback = 0;

        //
        // Check if this pipe has allocated a DMA channel.
        //
        if(g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8DMAChannel !=
           USBHCD_DMA_UNUSED)
        {
            //
            // Release the DMA channel associated with this endpoint.
            //
            USBLibDMAChannelRelease(g_sUSBHCD.psDMAInstance,
                    g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8DMAChannel);

            //
            // Clear out the current channel in use by this pipe.
            //
            g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8DMAChannel =
                                                            USBHCD_DMA_UNUSED;
        }

        //
        // Free up the FIFO memory used by this endpoint.
        //
        if(g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8FIFOSize)
        {
            FIFOFree(&g_sUSBHCD.psUSBOUTPipes[ui32Index]);
        }

        //
        // Set the function address for this endpoint back to zero.
        //
        USBHostAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1),
                       0, USB_EP_HOST_OUT);

        //
        // Set the hub and port address for the endpoint back to zero and the
        // speed back to LOW.
        //
        USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1),
                          0, (USB_EP_HOST_OUT | USB_EP_SPEED_LOW));
    }
    else if(ui32Pipe & EP_PIPE_TYPE_IN)
    {
        //
        // Clear the address and type for this endpoint to free it up.
        //
        g_sUSBHCD.psUSBINPipes[ui32Index].psDevice = 0;
        g_sUSBHCD.psUSBINPipes[ui32Index].ui32Type = 0;
        g_sUSBHCD.psUSBINPipes[ui32Index].pfnCallback = 0;

        //
        // Check if this pipe has allocated a DMA channel.
        //
        if(g_sUSBHCD.psUSBINPipes[ui32Index].ui8DMAChannel !=
           USBHCD_DMA_UNUSED)
        {
            //
            // Release the DMA channel associated with this endpoint.
            //
            USBLibDMAChannelRelease(g_sUSBHCD.psDMAInstance,
                    g_sUSBHCD.psUSBINPipes[ui32Index].ui8DMAChannel);

            //
            // Clear out the current channel in use by this pipe.
            //
            g_sUSBHCD.psUSBINPipes[ui32Index].ui8DMAChannel =
                                                            USBHCD_DMA_UNUSED;
        }

        //
        // Free up the FIFO memory used by this endpoint.
        //
        if(g_sUSBHCD.psUSBINPipes[ui32Pipe & EP_PIPE_IDX_M].ui8FIFOSize)
        {
            FIFOFree(&g_sUSBHCD.psUSBINPipes[ui32Pipe & EP_PIPE_IDX_M]);
        }

        //
        // Set the function address for this endpoint back to zero.
        //
        USBHostAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1),
                       0, USB_EP_HOST_IN);

        //
        // Set the hub and port address for the endpoint back to zero and the
        // speed back to LOW.
        //
        USBHostHubAddrSet(USB0_BASE, IndexToUSBEP(ui32Index + 1),
                          0, (USB_EP_HOST_IN | USB_EP_SPEED_LOW));

        //
        // Clear any pending IN transactions.
        //
        USBHostRequestINClear(USB0_BASE, IndexToUSBEP(ui32Index + 1));
    }
}

//*****************************************************************************
//
// This internal function initializes the HCD code.
//
// \param ui32Index specifies which USB controller to use.
// \param pvPool is a pointer to the data to use as a memory pool for this
// controller.
// \param ui32PoolSize is the size in bytes of the buffer passed in as pvPool.
//
// This function will perform all the necessary operations to allow the USB
// host controller to begin enumeration and communication with a device.  This
// function should typically be called once at the start of an application
// before any other calls are made to the host controller.
//
// \return None.
//
//*****************************************************************************
static void
USBHCDInitInternal(uint32_t ui32Index, void *pvPool, uint32_t ui32PoolSize)
{
    int32_t i32Idx;

    ASSERT(ui32Index == 0);

    //
    // Get the number of endpoints supported by this device.
    //
    g_sUSBHCD.ui32NumEndpoints = USBNumEndpointsGet(USB0_BASE);

    //
    // The first 64 Bytes are allocated to endpoint 0.
    //
    g_pui32Alloc[0] = 1;
    g_pui32Alloc[1] = 0;

    //
    // Save the base address for this controller.
    //
    g_sUSBHCD.ui32USBBase = USB0_BASE;

    //
    // Save the USB interrupt number.
    //
    g_sUSBHCD.ui32IntNum = INT_USB0_TM4C123;

    //
    // These devices have a different USB interrupt number.
    //
    if(CLASS_IS_TM4C129)
    {
        g_sUSBHCD.ui32IntNum = INT_USB0_TM4C129;
    }

    //
    // All Pipes are unused at start.
    //
    for(i32Idx = 0; i32Idx < MAX_NUM_PIPES; i32Idx++)
    {
        g_sUSBHCD.psUSBINPipes[i32Idx].psDevice = 0;
        g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
        g_sUSBHCD.psUSBINPipes[i32Idx].ui8DMAChannel = USBHCD_DMA_UNUSED;
        g_sUSBHCD.psUSBOUTPipes[i32Idx].psDevice = 0;
        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui8DMAChannel = USBHCD_DMA_UNUSED;
    }

    //
    // Make sure that the hub driver is initialized since it is called even
    // if it is not present in the system.
    //
    USBHHubInit();

    //
    // Initialize the DMA interface.
    //
    g_sUSBHCD.psDMAInstance = USBLibDMAInit(g_sUSBHCD.ui32USBBase);

    //
    // Initialized the device structures.
    //
    for(i32Idx = 0; i32Idx <= MAX_USB_DEVICES; i32Idx++)
    {
        //
        // Clear the configuration descriptor and state.
        //
        g_sUSBHCD.piDeviceState[i32Idx] = eHCDIdle;
        g_sUSBHCD.psUSBDevice[i32Idx].psConfigDescriptor = 0;
        g_sUSBHCD.psUSBDevice[i32Idx].bConfigRead = false;

        //
        // Initialize the device descriptor.
        //
        g_sUSBHCD.psUSBDevice[i32Idx].sDeviceDescriptor.bLength = 0;
        g_sUSBHCD.psUSBDevice[i32Idx].sDeviceDescriptor.bMaxPacketSize0 = 0;

        //
        // Initialize the device address.
        //
        g_sUSBHCD.psUSBDevice[i32Idx].ui32Address = 0;

        //
        // Set the current interface to 0.
        //
        g_sUSBHCD.psUSBDevice[i32Idx].ui32Interface = 0;

        //
        // Clear the active driver for the device.
        //
        g_pi32USBHActiveDriver[i32Idx] = -1;

        //
        // Initialize the device flags.
        //
        g_sUSBHCD.psUSBDevice[i32Idx].ui32Flags = 0;
    }

    //
    // Allocate the memory needed for reading descriptors.
    //
    g_sUSBHCD.pvPool = pvPool;
    g_sUSBHCD.ui32PoolSize = ui32PoolSize;

    //
    // Initialize the device class.
    //
    g_sUSBHCD.ui32Class = USB_CLASS_EVENTS;

    //
    // Default enable connect, disconnect, unknown device and power fault
    // event notifications.
    //
    g_sUSBHCD.ui32EventEnables = USBHCD_EVFLAG_CONNECT |
                                 USBHCD_EVFLAG_UNKCNCT |
                                 USBHCD_EVFLAG_DISCNCT |
                                 USBHCD_EVFLAG_PWRFAULT |
                                 USBHCD_EVFLAG_PWREN |
                                 USBHCD_EVFLAG_PWRDIS;

    //
    // Initialize the USB tick module.
    //
    InternalUSBTickInit();

    //
    // Only do hardware update if the stack is in Host mode, do not touch the
    // hardware for OTG mode operation.
    //
    if((g_iUSBMode == eUSBModeHost) || (g_iUSBMode == eUSBModeForceHost))
    {
        //
        // Configure the End point 0.
        //
        USBHostEndpointConfig(USB0_BASE, USB_EP_0, 64, 0, 0,
                              (USB_EP_MODE_CTRL | USB_EP_SPEED_FULL |
                               USB_EP_HOST_OUT));

        //
        // Enable USB Interrupts.
        //
        MAP_USBIntEnableControl(USB0_BASE, USB_INTCTRL_RESET |
                                           USB_INTCTRL_DISCONNECT |
                                           USB_INTCTRL_SOF |
                                           USB_INTCTRL_SESSION |
                                           USB_INTCTRL_BABBLE |
                                           USB_INTCTRL_CONNECT |
                                           USB_INTCTRL_RESUME |
                                           USB_INTCTRL_SUSPEND |
                                           USB_INTCTRL_VBUS_ERR |
                                           USB_INTCTRL_POWER_FAULT);

        MAP_USBIntEnableEndpoint(USB0_BASE, USB_INTEP_ALL);

        //
        // Enable the USB interrupt.
        //
        OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);

        //
        // There is no automatic power in pure host mode.
        //
        USBHCDPowerConfigSet(ui32Index, (g_ui32PowerConfig &
                                         ~USB_HOST_PWREN_AUTO));

        //
        // Force the power on as well as this point.
        //
        MAP_USBHostPwrEnable(USB0_BASE);

        //
        // This is required to get into host mode on some parts.
        //
        USBOTGSessionRequest(USB0_BASE, true);
    }

    //
    // Configure LPM if it is enabled.
    //
    if(g_sUSBHCD.ui32Features & USBLIB_FEATURE_LPM_EN)
    {
        if(g_sUSBHCD.ui32Features & USBLIB_FEATURE_LPM_RMT_WAKE)
        {
            USBHostLPMConfig(USB0_BASE, g_sUSBHCD.ui32LPMHIRD,
                             USB_DEV_LPM_LS_L1 | USB_DEV_LPM_LS_RMTWAKE);
        }
        else
        {
            USBHostLPMConfig(USB0_BASE, g_sUSBHCD.ui32LPMHIRD,
                             USB_DEV_LPM_LS_L1);
        }

        //
        // Enable USB interrupts for LPM mode, these enables have no effect on
        // devices that do not support LPM.
        //
        USBLPMIntEnable(USB0_BASE, USB_INTLPM_ERROR | USB_INTLPM_RESUME |
                                   USB_INTLPM_INCOMPLETE | USB_INTLPM_ACK |
                                   USB_INTLPM_NYET | USB_INTLPM_STALL);
    }
}

//*****************************************************************************
//
//! This function is used to set the power pin and power fault configuration.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32PwrConfig is the power configuration to use for the application.
//!
//! This function must be called before HCDInit() is called so that the power
//! pin configuration can be set before power is enabled.  The \e ui32PwrConfig
//! flags specify the power fault level sensitivity, the power fault action,
//! and the power enable pin level and source.
//!
//! One of the following can be selected as the power fault level sensitivity:
//!
//! - \b USBHCD_FAULT_LOW - An external power fault is indicated by the pin
//!                         being driven low.
//! - \b USBHCD_FAULT_HIGH - An external power fault is indicated by the pin
//!                          being driven high.
//!
//! One of the following can be selected as the power fault action:
//!
//! - \b USBHCD_FAULT_VBUS_NONE - No automatic action when power fault
//!   detected.
//! - \b USBHCD_FAULT_VBUS_TRI - Automatically Tri-state the USBnEPEN pin on a
//!                              power fault.
//! - \b USBHCD_FAULT_VBUS_DIS - Automatically drive the USBnEPEN pin to it's
//!                              inactive state on a power fault.
//!
//! One of the following can be selected as the power enable level and source:
//!
//! - \b USBHCD_VBUS_MANUAL - Power control is completely managed by the
//!                           application, the USB library will provide a
//!                           power callback to request power state changes.
//! - \b USBHCD_VBUS_AUTO_LOW - USBEPEN is driven low by the USB controller
//!                             automatically if USBOTGSessionRequest() has
//!                             enabled a session.
//! - \b USBHCD_VBUS_AUTO_HIGH - USBEPEN is driven high by the USB controller
//!                              automatically if USBOTGSessionRequest() has
//!                              enabled a session.
//!
//! If \b USBHCD_VBUS_MANUAL is used then the application must provide an
//! event driver to receive the \b USB_EVENT_POWER_ENABLE and
//! \b USB_EVENT_POWER_DISABLE events and enable and disable power to VBUS when
//! requested by the USB library.  The application should respond to a power
//! control callback by enabling or disabling VBUS as soon as possible and
//! before returning from the callback function.
//!
//! \note The following values should no longer be used with the USB
//! library: \b USB_HOST_PWRFLT_LOW, \b USB_HOST_PWRFLT_HIGH,
//! \b USB_HOST_PWRFLT_EP_NONE, \b USB_HOST_PWRFLT_EP_TRI,
//! \b USB_HOST_PWRFLT_EP_LOW, \b USB_HOST_PWRFLT_EP_HIGH,
//! \b USB_HOST_PWREN_LOW, \b USB_HOST_PWREN_HIGH, \b USB_HOST_PWREN_VBLOW, and
//! \b USB_HOST_PWREN_VBHIGH.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDPowerConfigInit(uint32_t ui32Index, uint32_t ui32PwrConfig)
{
    ASSERT(ui32Index == 0);

    //
    // Save the value as it will be used later.
    //
    g_ui32PowerConfig = ui32PwrConfig;
}

//*****************************************************************************
//
//! This function is used to get the power pin and power fault configuration.
//!
//! \param ui32Index specifies which USB controller to use.
//!
//! This function will return the current power control pin configuration as
//! set by the USBHCDPowerConfigInit() function or the defaults if not yet set.
//! See the USBHCDPowerConfigInit() documentation for the meaning of the bits
//! that are returned by this function.
//!
//! \return The configuration of the power control pins.
//!
//*****************************************************************************
uint32_t
USBHCDPowerConfigGet(uint32_t ui32Index)
{
    ASSERT(ui32Index == 0);

    //
    // Save the value as it will be used later.
    //
    return(g_ui32PowerConfig);
}

//*****************************************************************************
//
//! This function is used to set the power pin and power fault configuration.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32Config specifies which USB power configuration to use.
//!
//! This function will set the current power control pin configuration as
//! set by the USBHCDPowerConfigInit() function or the defaults if not yet set.
//! See the USBHCDPowerConfigInit() documentation for the meaning of the bits
//! that are set by this function.
//!
//! \return Returns zero to indicate the power setting is now active.
//!
//*****************************************************************************
uint32_t
USBHCDPowerConfigSet(uint32_t ui32Index, uint32_t ui32Config)
{
    ASSERT(ui32Index == 0);

    //
    // Remember the current setting.
    //
    g_ui32PowerConfig = ui32Config;

    //
    // Clear out the two flag bits.
    //
    ui32Config = g_ui32PowerConfig & ~(USBHCD_VBUS_MANUAL |
                                       USBHCD_FAULT_VBUS_DIS);

    //
    // If there is an automatic disable power action specified then set the
    // polarity of the signal to match EPEN.
    //
    if(g_ui32PowerConfig & USBHCD_FAULT_VBUS_DIS)
    {
        //
        // Insure that the assumption below is true.
        //
        ASSERT((USBHCD_VBUS_AUTO_HIGH & 1) == 1);
        ASSERT((USBHCD_VBUS_AUTO_LOW & 1) == 0);

        //
        // This is taking advantage of the difference between
        // USBHCD_VBUS_AUTO_LOW and USBHCD_VBUS_AUTO_HIGH being that bit
        // one is set when EPEN is active high.
        //
        if(g_ui32PowerConfig & 1)
        {
            g_ui32PowerConfig |= USB_HOST_PWRFLT_EP_LOW;
            ui32Config |= USB_HOST_PWRFLT_EP_LOW;
        }
        else
        {
            g_ui32PowerConfig |= USB_HOST_PWRFLT_EP_HIGH;
            ui32Config |= USB_HOST_PWRFLT_EP_HIGH;
        }
    }

    //
    // Initialize the power configuration.
    //
    MAP_USBHostPwrConfig(USB0_BASE, ui32Config);

    //
    // If not in manual mode then just turn on power.
    //
    if((g_ui32PowerConfig & USBHCD_VBUS_MANUAL) == 0)
    {
        //
        // Power the USB bus.
        //
        MAP_USBHostPwrEnable(USB0_BASE);
    }

    //
    // Return success.
    //
    return(0);
}

//*****************************************************************************
//
//! This function returns if the current power settings will automatically
//! handle enabling and disabling VBUS power.
//!
//! \param ui32Index specifies which USB controller to query.
//!
//! This function returns if the current power control pin configuration will
//! automatically apply power or whether it will be left to the application
//! to turn on power when it is notified.
//!
//! \return A non-zero value indicates that power is automatically applied and
//! a value of zero indicates that the application must manually apply power.
//!
//*****************************************************************************
uint32_t
USBHCDPowerAutomatic(uint32_t ui32Index)
{
    //
    // Check if the controller is automatically applying power or not.
    //
    if(g_ui32PowerConfig & USBHCD_VBUS_MANUAL)
    {
        return(0);
    }
    return(1);
}

//*****************************************************************************
//
//! This function is used to initialize the HCD code.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param pvPool is a pointer to the data to use as a memory pool for this
//! controller.
//! \param ui32PoolSize is the size in bytes of the buffer passed in as
//! \e pvPool.
//!
//! This function will perform all the necessary operations to allow the USB
//! host controller to begin enumeration and communication with devices.  This
//! function should typically be called once at the start of an application
//! once all of the device and class drivers are ready for normal operation.
//! This call will start up the USB host controller and any connected device
//! will immediately start the enumeration sequence.
//!
//! The USBStackModeSet() function can be called with eUSBModeHost in order to
//! cause the USB library to force the USB operating mode to a host controller.
//! This allows the application to used the USBVBUS and USBID pins as GPIOs on
//! devices that support forcing OTG to operate as a host only controller.  By
//! default the USB library will assume that the USBVBUS and USBID pins are
//! configured as USB pins and not GPIOs.
//!
//! The memory pool passed to this function must be at least as large as a
//! typical configuration descriptor for devices that are to be supported.
//! This value is application-dependent however it should never be less than 32
//! bytes and, in most cases, should be at least 64 bytes.  If there is not
//! sufficient memory to load a configuration descriptor from a device, the
//! device will not be recognized by the USB library's host controller driver.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDInit(uint32_t ui32Index, void *pvPool, uint32_t ui32PoolSize)
{
    int32_t i32Driver;

    //
    // Check the arguments.
    //
    ASSERT(ui32Index == 0);

    //
    // Make sure there is at least enough to read the configuration descriptor.
    //
    ASSERT(ui32PoolSize >= sizeof(tConfigDescriptor));

    //
    // Should not call this if the stack is in device mode.
    //
    ASSERT(g_iUSBMode != eUSBModeDevice);
    ASSERT(g_iUSBMode != eUSBModeForceDevice);

    //
    // If the mode was not set then default to eUSBModeHost.
    //
    if(g_iUSBMode == eUSBModeNone)
    {
        g_iUSBMode = eUSBModeHost;
    }

    //
    // Reset the USB controller.
    //
    MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_USB0);

    //
    // Enable Clocking to the USB controller.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0);

    //
    // Turn on USB Phy clock.
    //
    MAP_SysCtlUSBPLLEnable();

    //
    // Set the PLL to USB clock divider.
    //
    if(g_ui32PLLDiv == 0)
    {
        USBClockEnable(USB0_BASE, g_ui32PLLDiv, USB_CLOCK_EXTERNAL);
    }
    else
    {
        USBClockEnable(USB0_BASE, g_ui32PLLDiv, USB_CLOCK_INTERNAL);
    }

    //
    // Configure ULPI support.
    //
    if(g_ui32ULPISupport != USBLIB_FEATURE_ULPI_NONE)
    {
        USBULPIEnable(USB0_BASE);

        if(g_ui32ULPISupport & USBLIB_FEATURE_ULPI_HS)
        {
            ULPIConfigSet(USB0_BASE, ULPI_CFG_HS);
        }
        else
        {
            ULPIConfigSet(USB0_BASE, ULPI_CFG_FS);
        }
    }
    else
    {
        USBULPIDisable(USB0_BASE);
    }

    //
    // If the application not requesting OTG mode then set the mode to forced
    // host mode.  If the mode is actually eUSBModeHost, this will be switched
    // off when ID pin detection is complete and the ID is no longer in use.
    //
    if(g_iUSBMode != eUSBModeOTG)
    {
        //
        // Force Host mode on devices that support force host mode.
        //
        MAP_USBHostMode(USB0_BASE);
    }

    //
    // Call our internal function to perform the initialization.
    //
    USBHCDInitInternal(ui32Index, pvPool, ui32PoolSize);

    //
    // No event driver is present by default.
    //
    g_sUSBHCD.i32EventDriver = -1;

    //
    // Search through the Host Class driver list for the devices class.
    //
    for(i32Driver = 0; i32Driver < g_sUSBHCD.ui32NumClassDrivers; i32Driver++)
    {
        if(g_sUSBHCD.ppsClassDrivers[i32Driver]->ui32InterfaceClass ==
           USB_CLASS_EVENTS)
        {
            //
            // Event driver was found so remember it.
            //
            g_sUSBHCD.i32EventDriver = i32Driver;
        }
    }

    //
    // Get the number of ticks per millisecond, this is only used by blocking
    // delays using the SysCtlDelay() function.
    //
    if(g_ui32Tickms == 0)
    {
        if(CLASS_IS_TM4C129)
        {
            g_ui32Tickms = 120000000 / 3000;
        }
        else
        {
            g_ui32Tickms = 80000000 / 3000;
        }
    }
}

//*****************************************************************************
//
//! This function is used to initialize the HCD class driver list.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ppsHClassDrvs is an array of host class drivers that are
//! supported on this controller.
//! \param ui32NumDrivers is the number of entries in the \e pHostClassDrivers
//! array.
//!
//! This function will set the host classes supported by the host controller
//! specified by the \e ui32Index parameter.  This function should be called
//! before enabling the host controller driver with the USBHCDInit() function.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDRegisterDrivers(uint32_t ui32Index,
                      const tUSBHostClassDriver * const *ppsHClassDrvs,
                      uint32_t ui32NumDrivers)
{
    ASSERT(ui32Index == 0);

    //
    // Save the class drivers.
    //
    g_sUSBHCD.ppsClassDrivers = ppsHClassDrvs;

    //
    // Save the number of class drivers.
    //
    g_sUSBHCD.ui32NumClassDrivers = ui32NumDrivers;
}

//*****************************************************************************
//
//! This function is used to terminate the HCD code.
//!
//! \param ui32Index specifies which USB controller to release.
//!
//! This function will clean up the USB host controller and disable it in
//! preparation for shutdown or a switch to USB device mode.  Once this call is
//! made, \e USBHCDInit() may be called to reinitialize the controller and
//! prepare for host mode operation.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDTerm(uint32_t ui32Index)
{
    int32_t i32Idx;

    ASSERT(ui32Index == 0);

    //
    // End the session.
    //
    USBOTGSessionRequest(USB0_BASE, false);

    //
    // Remove power from the USB bus.
    //
    MAP_USBHostPwrDisable(USB0_BASE);

    //
    // Disable USB interrupts.
    //
    OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

    MAP_USBIntDisableControl(USB0_BASE, USB_INTCTRL_ALL);

    MAP_USBIntDisableEndpoint(USB0_BASE, USB_INTEP_ALL);

    //
    // Set the host controller state back to it's initial values.
    //
    for(i32Idx = 0; i32Idx < MAX_NUM_PIPES; i32Idx++)
    {
        g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
        g_sUSBHCD.psUSBOUTPipes[i32Idx].ui32Type = USBHCD_PIPE_UNUSED;
    }

    //
    // Free the memory used by the configuration descriptor.
    //
    ConfigDescFree(&g_sUSBHCD.psUSBDevice[0]);

    g_sUSBHCD.piDeviceState[0] = eHCDIdle;
    g_sUSBHCD.psUSBDevice[0].psConfigDescriptor = 0;
    g_sUSBHCD.psUSBDevice[0].bConfigRead = false;
    g_sUSBHCD.psUSBDevice[0].sDeviceDescriptor.bLength = 0;
    g_sUSBHCD.psUSBDevice[0].sDeviceDescriptor.bMaxPacketSize0 = 0;
    g_sUSBHCD.psUSBDevice[0].ui32Address = 0;
    g_sUSBHCD.psUSBDevice[0].ui32Interface = 0;
    g_sUSBHCD.pvPool = 0;
    g_sUSBHCD.ui32PoolSize = 0;
}

//*****************************************************************************
//
//! This function generates reset signaling on the USB bus.
//!
//! \param ui32Index specifies which USB controller to use.
//!
//! This function handles sending out reset signaling on the USB bus.  After
//! returning from this function, any attached device on the USB bus should
//! have returned to it's reset state.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDReset(uint32_t ui32Index)
{
    ASSERT(ui32Index == 0);

    //
    // Start the reset signaling.
    //
    MAP_USBHostReset(USB0_BASE, 1);

    //
    // Wait 20ms
    //
    OS_DELAY(g_ui32Tickms * 20);

    //
    // End reset signaling on the bus.
    //
    MAP_USBHostReset(USB0_BASE, 0);

    //
    // Need to wait at least 10ms to let the device recover from
    // the reset.  This is the delay specified in the USB 2.0 spec.
    // We will hold the reset for 20ms.
    //
    OS_DELAY(g_ui32Tickms * 20);
}

//*****************************************************************************
//
//! This function will generate suspend signaling on the USB bus.
//!
//! \param ui32Index specifies which USB controller to use.
//!
//! This function is used to generate suspend signaling on the USB bus.  In
//! order to leave the suspended state, the application should call
//! USBHCDResume().
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDSuspend(uint32_t ui32Index)
{
    ASSERT(ui32Index == 0);

    //
    // Start the suspend signaling.
    //
    MAP_USBHostSuspend(USB0_BASE);
}

//*****************************************************************************
//
//! This function will generate resume signaling on the USB bus.
//!
//! \param ui32Index specifies which USB controller to use.
//!
//! This function is used to generate resume signaling on the USB bus in order
//! to cause  USB devices to leave their suspended state.  This call should
//! not be made unless a preceding call to USBHCDSuspend() has been made.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDResume(uint32_t ui32Index)
{
    ASSERT(ui32Index == 0);

    //
    // Start the resume signaling.
    //
    MAP_USBHostResume(USB0_BASE, 1);

    //
    // Wait 100ms
    //
    OS_DELAY(g_ui32Tickms * 100);

    //
    // End reset signaling on the bus.
    //
    MAP_USBHostResume(USB0_BASE, 0);
}

//*****************************************************************************
//
//! This function issues a request for the current configuration descriptor
//! from a device.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param psDevice is a pointer to the device structure that holds the buffer
//! to store the configuration descriptor.
//!
//! This function will request the configuration descriptor from the device.
//! The \e psDevice->ConfigDescriptor member variable is used to hold the data
//! for this request.  This buffer will be allocated from the pool provided by
//! the HCDInit() function.  \e psDevice->sDeviceDescriptor.bMaxPacketSize0
//! should be valid prior to this call in order to correctly receive the
//! configuration descriptor.  If this variable is not valid then this call
//! will not return accurate data.
//!
//! \return The number of bytes returned due to the request.  This value can be
//! zero if the device did not respond.
//
//*****************************************************************************
static uint32_t
USBHCDGetConfigDescriptor(uint32_t ui32Index, tUSBHostDevice *psDevice)
{
    tUSBRequest sSetupPacket;
    uint32_t ui32Bytes;
    tConfigDescriptor sConfigDescriptor;

    ASSERT(ui32Index == 0);

    ui32Bytes = 0;

    //
    // This is a Standard Device IN request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_IN | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;
    sSetupPacket.wValue = USB_DTYPE_CONFIGURATION << 8;

    //
    // Index is always 0 for device configurations requests.
    //
    sSetupPacket.wIndex = 0;

    //
    // Only ask for the configuration header first to see how big the
    // whole thing is.
    //
    if(!psDevice->bConfigRead)
    {
        //
        // Only request the space available.
        //
        sSetupPacket.wLength = sizeof(tConfigDescriptor);

        //
        // Put the setup packet in the buffer.
        //
        ui32Bytes =
            USBHCDControlTransfer(0, &sSetupPacket, psDevice,
                                  (uint8_t *)&sConfigDescriptor,
                                  sizeof(tConfigDescriptor),
                                  psDevice->sDeviceDescriptor.bMaxPacketSize0);
    }

    //
    // If the Configuration header was successfully returned then get the
    // full configuration descriptor.
    //
    if(ui32Bytes == sizeof(tConfigDescriptor))
    {
        //
        // Save the total size and request the full configuration descriptor.
        //
        sSetupPacket.wLength = sConfigDescriptor.wTotalLength;

        //
        // Not enough space to hold this configuration descriptor.
        //
        if(ConfigDescAlloc(psDevice, sConfigDescriptor.wTotalLength) == 0)
        {
            return(0);
        }

        //
        // Don't allow the buffer to be larger than was allocated.
        //
        if(sSetupPacket.wLength > psDevice->ui32ConfigDescriptorSize)
        {
            return(0);
        }

        //
        // Put the setup packet in the buffer.
        //
        ui32Bytes =
            USBHCDControlTransfer(0, &sSetupPacket, psDevice,
                                  (uint8_t *)psDevice->psConfigDescriptor,
                                  sSetupPacket.wLength,
                                  psDevice->sDeviceDescriptor.bMaxPacketSize0);

        //
        // If we read the descriptor, remember the fact.
        //
        if(ui32Bytes)
        {
            psDevice->bConfigRead = true;
        }
    }

    return(ui32Bytes);
}

//*****************************************************************************
//
//! This function issues a request for a device descriptor from a device.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param psDevice is a pointer to the device structure that holds the buffer
//! to store the device descriptor into.
//!
//! This function will request the device descriptor from the device.  The
//! \e psDevice->sDeviceDescriptor descriptor is used to hold the data for this
//! request.  \e psDevice->sDeviceDescriptor.bMaxPacketSize0 should be
//! initialized to zero or to the valid maximum packet size if it is known.  If
//! this variable is not set to zero, then this call will determine the maximum
//! packet size for endpoint 0 and save it in the structure member
//! bMaxPacketSize0.
//!
//! \return The number of bytes returned due to the request.  This value can be
//! zero if the device did not respond.
//
//*****************************************************************************
static uint32_t
USBHCDGetDeviceDescriptor(uint32_t ui32Index, tUSBHostDevice *psDevice)
{
    tUSBRequest sSetupPacket;
    uint32_t ui32Bytes;

    ASSERT(ui32Index == 0);

    //
    // This is a Standard Device IN request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_IN | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;
    sSetupPacket.wValue = USB_DTYPE_DEVICE << 8;

    //
    // Index is always 0 for device requests.
    //
    sSetupPacket.wIndex = 0;

    //
    // All devices must have at least an 8 byte max packet size so just ask
    // for 8 bytes to start with.
    //
    sSetupPacket.wLength = sizeof(tDeviceDescriptor);

    ui32Bytes = 0;

    //
    // Discover the max packet size for endpoint 0.
    //
    if(psDevice->sDeviceDescriptor.bMaxPacketSize0 == 0)
    {
        //
        // Put the setup packet in the buffer.
        //
        ui32Bytes =
            USBHCDControlTransfer(ui32Index, &sSetupPacket, psDevice,
                                  (uint8_t *)&(psDevice->sDeviceDescriptor),
                                  sizeof(tDeviceDescriptor), 8);
    }

    //
    // Now get the full descriptor now that the actual maximum packet size
    // is known.
    //
    if(ui32Bytes < sizeof(tDeviceDescriptor))
    {
        sSetupPacket.wLength = (uint16_t)sizeof(tDeviceDescriptor);

        ui32Bytes =
            USBHCDControlTransfer(ui32Index, &sSetupPacket, psDevice,
                                  (uint8_t *)&(psDevice->sDeviceDescriptor),
                                  sizeof(tDeviceDescriptor),
                                  psDevice->sDeviceDescriptor.bMaxPacketSize0);
    }

    return(ui32Bytes);
}

//*****************************************************************************
//
//! This function issues a request for a string descriptor from a device.
//!
//! \param psDevice is the device for this request.
//! \param pui8Buffer is the pointer to the buffer to store the requested
//! string descriptor.
//! \param ui32Size is the size of the buffer passed in the buffer that will
//! be used for this request.
//! \param ui32LangID is the ID of the language for the requested string.
//! \param ui32StringIndex is the index for the request.
//!
//! This function will request a string descriptor from the device of the type
//! specified in the \e ui32DescriptorType parameter.  The \e pui8Descriptor
//! pointer is the location where the request results will be stored.  The
//! \e ui32Size should be passed in to indicate the size of the
//! \e pui8Descriptor buffer.  The \e ui32DevAddress parameter is used to
//! specify the device address to communicate with on the USB bus.  This value
//! should be specified as 0 for any non-configured device on the USB bus and
//! be changed to the address set by a call to USBHCDSetAddress().
//!
//! \return The number of bytes returned in the \e pui8Buffer due to the
//! request.  This value can be zero if the device did not respond.
//
//*****************************************************************************
uint32_t
USBHCDStringDescriptorGet(tUSBHostDevice *psDevice, uint8_t *pui8Buffer,
                          uint32_t ui32Size, uint32_t ui32LangID,
                          uint32_t ui32StringIndex)
{
    uint32_t ui32BytesReturned;
    tUSBRequest sSetupPacket;

    //
    // Default the number of bytes to zero.
    //
    ui32BytesReturned = 0;

    //
    // This is a Standard Device IN request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_IN | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_GET_DESCRIPTOR;

    //
    // Request for a string descriptor.
    //
    sSetupPacket.wValue = (USB_DTYPE_STRING << 8) |
                         (uint16_t)ui32StringIndex;

    //
    // Set the language ID.
    //
    sSetupPacket.wIndex = ui32LangID;

    //
    // Only request the space available.
    //
    sSetupPacket.wLength = (uint16_t)ui32Size;

    //
    // Put the setup packet in the buffer.
    //
    ui32BytesReturned =
        USBHCDControlTransfer(0, &sSetupPacket, psDevice, pui8Buffer, ui32Size,
                              psDevice->sDeviceDescriptor.bMaxPacketSize0);

    //
    // Return the number of bytes in the string.
    //
    return(ui32BytesReturned);
}

//*****************************************************************************
//
//! This function is used to send the set address command to a device.
//!
//! \param ui32DevIndex is the index of the device whose address is to be
//! set.  This value must be 0 to indicate that the device is connected
//! directly to the host controller.  Higher values indicate devices connected
//!  via a hub.
//! \param ui32DevAddress is the new device address to use for a device.
//!
//! The USBHCDSetAddress() function is used to set the USB device address, once
//! a device has been discovered on the bus.  This call is typically issued
//! following a USB reset triggered by a call the USBHCDReset().  The
//! address passed into this function via the \e ui32DevAddress parameter is
//! used for all further communications with the device after this function
//! returns.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDSetAddress(uint32_t ui32DevIndex, uint32_t ui32DevAddress)
{
    tUSBRequest sSetupPacket;

    //
    // This is a Standard Device OUT request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_SET_ADDRESS;
    sSetupPacket.wValue = ui32DevAddress;

    //
    // Index is always 0 for device requests.
    //
    sSetupPacket.wIndex = 0;

    //
    // Only request the space available.
    //
    sSetupPacket.wLength = 0;

    //
    // Put the setup packet in the buffer.
    //
    USBHCDControlTransfer(0, &sSetupPacket,
                          &g_sUSBHCD.psUSBDevice[ui32DevIndex], 0,
                          0, MAX_PACKET_SIZE_EP0);

    //
    // Must delay 2ms after setting the address.
    //
    OS_DELAY(g_ui32Tickms * 2);
}

//*****************************************************************************
//
//! This function is used to send a Clear Feature request to a device.
//!
//! \param ui32DevAddress is the USB bus address of the device that will
//! receive this request.
//! \param ui32Pipe is the pipe that will be used to send the request.
//! \param ui32Feature is one of the USB_FEATURE_* definitions.
//!
//! This function will issue a Clear Feature request to the device indicated
//! by the \e ui32DevAddress parameter.  The \e ui32Pipe parameter is the USB
//! pipe that should be used to send this request.  The \e ui32Feature
//! parameter should be one of the following values:
//!
//! * \b USB_FEATURE_EP_HALT is used to end a HALT condition on a devices
//!   endpoint.
//! * \b USB_FEATURE_REMOTE_WAKE is used to disable a device's remote wake
//!   feature.
//! * \b USB_FEATURE_TEST_MODE is used take the USB device out of test mode.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDClearFeature(uint32_t ui32DevAddress, uint32_t ui32Pipe,
                   uint32_t ui32Feature)
{
    tUSBRequest sSetupPacket;
    uint32_t ui32Index;

    //
    // Get the index number from the allocated pipe.
    //
    ui32Index = (ui32Pipe & EP_PIPE_IDX_M);

    //
    // This is a Standard Device OUT request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_ENDPOINT;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_CLEAR_FEATURE;
    sSetupPacket.wValue = ui32Feature;

    //
    // Set the endpoint to access.
    //
    if(ui32Pipe & EP_PIPE_TYPE_IN)
    {
        sSetupPacket.wIndex = g_sUSBHCD.psUSBINPipes[ui32Index].ui8EPNumber |
                              0x80;
    }
    else
    {
        sSetupPacket.wIndex = g_sUSBHCD.psUSBOUTPipes[ui32Index].ui8EPNumber;
    }

    //
    // This is always 0.
    //
    sSetupPacket.wLength = 0;

    //
    // Put the setup packet in the buffer.
    //
    USBHCDControlTransfer(0, &sSetupPacket,
                          &g_sUSBHCD.psUSBDevice[ui32DevAddress - 1], 0, 0,
                          MAX_PACKET_SIZE_EP0);

    //
    // Set the endpoint to access.
    //
    if(ui32Pipe & EP_PIPE_TYPE_IN)
    {
        MAP_USBEndpointDataToggleClear(USB0_BASE,
                                       IndexToUSBEP(ui32Index + 1),
                                       USB_EP_HOST_IN);
    }
    else
    {
        MAP_USBEndpointDataToggleClear(USB0_BASE,
                                       IndexToUSBEP(ui32Index + 1),
                                       USB_EP_HOST_OUT);
    }

    //
    // Must delay 2ms after clearing the feature.
    //
    OS_DELAY(g_ui32Tickms * 2);
}

//*****************************************************************************
//
//! This function is used to set the current configuration for a device.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32Device is the USB device for this function.
//! \param ui32Configuration is one of the devices valid configurations.
//!
//! This function is used to set the current device configuration for a USB
//! device.  The \e ui32Configuration value must be one of the configuration
//! indexes that was returned in the configuration descriptor from the device,
//! or a value of 0.  If 0 is passed in, the device will return to it's
//! addressed state and no longer be in a configured state.  If the value is
//! non-zero then the device will change to the requested configuration.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDSetConfig(uint32_t ui32Index, uint32_t ui32Device,
                uint32_t ui32Configuration)
{
    tUSBRequest sSetupPacket;
    tUSBHostDevice *psDevice;

    ASSERT(ui32Index == 0);

    psDevice = (tUSBHostDevice *)ui32Device;

    //
    // This is a Standard Device OUT request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_DEVICE;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_SET_CONFIG;
    sSetupPacket.wValue = ui32Configuration;

    //
    // Index is always 0 for device requests.
    //
    sSetupPacket.wIndex = 0;

    //
    // Only request the space available.
    //
    sSetupPacket.wLength = 0;

    //
    // Put the setup packet in the buffer.
    //
    USBHCDControlTransfer(0, &sSetupPacket, psDevice, 0, 0,
                          MAX_PACKET_SIZE_EP0);
}

//*****************************************************************************
//
//! This function is used to set the current interface and alternate setting
//! for an interface on a device.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32Device is the USB device for this function.
//! \param ui32Interface is one of the valid interface numbers for a device.
//! \param ui32AltSetting is one of the valid alternate interfaces for the
//! \e ui32Interface number.
//!
//! This function is used to change the alternate setting for one of the valid
//! interfaces on a USB device.  The \e ui32Device specifies the device
//! instance that was returned when the device was connected.  This call will
//! set the USB device's interface based on the \e ui32Interface and
//! \e ui32AltSetting.
//!
//! \b Example: Set the USB device interface 2 to alternate setting 1.
//!
//! \verbatim
//! USBHCDSetInterface(0, ui32Device, 2, 1);
//! \endverbatim
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDSetInterface(uint32_t ui32Index, uint32_t ui32Device,
                   uint32_t ui32Interface, uint32_t ui32AltSetting)
{
    tUSBRequest sSetupPacket;
    tUSBHostDevice *psDevice;

    ASSERT(ui32Index == 0);

    psDevice = (tUSBHostDevice *)ui32Device;

    //
    // This is a Standard Device OUT request.
    //
    sSetupPacket.bmRequestType =
        USB_RTYPE_DIR_OUT | USB_RTYPE_STANDARD | USB_RTYPE_INTERFACE;

    //
    // Request a Device Descriptor.
    //
    sSetupPacket.bRequest = USBREQ_SET_INTERFACE;

    //
    // Index is the interface to access.
    //
    sSetupPacket.wIndex = ui32Interface;

    //
    // wValue is the alternate setting.
    //
    sSetupPacket.wValue = ui32AltSetting;


    //
    // Only request the space available.
    //
    sSetupPacket.wLength = 0;

    //
    // Put the setup packet in the buffer.
    //
    USBHCDControlTransfer(0, &sSetupPacket, psDevice, 0, 0,
                          MAX_PACKET_SIZE_EP0);
}

//*****************************************************************************
//
// The internal function to see if a new schedule event should occur.
//
// This function is called by the main interrupt handler due to start of frame
// interrupts to determine if a new scheduler event should be sent to the USB
// pipe.
//
// \return None.
//
//*****************************************************************************
void
USBHostCheckPipes(void)
{
    int32_t i32Idx;

    g_ui32CurrentTick++;

    for(i32Idx = 0; i32Idx < g_sUSBHCD.ui32NumEndpoints; i32Idx++)
    {
        //
        // Skip unused pipes.
        //
        if(g_sUSBHCD.psUSBINPipes[i32Idx].ui32Type == USBHCD_PIPE_UNUSED)
        {
            continue;
        }

        //
        // If the tick has expired and it has an interval then update it.
        //
        if((g_sUSBHCD.psUSBINPipes[i32Idx].ui32Interval != 0) &&
           (g_sUSBHCD.psUSBINPipes[i32Idx].ui32NextEventTick ==
            g_ui32CurrentTick))
        {
            //
            // Schedule the next event.
            //
            g_sUSBHCD.psUSBINPipes[i32Idx].ui32NextEventTick +=
                g_sUSBHCD.psUSBINPipes[i32Idx].ui32Interval;

            //
            // If the pipe is IDLE and there is a callback, let the higher
            // level drivers know that a new transfer can be scheduled.
            //
            if((g_sUSBHCD.psUSBINPipes[i32Idx].iState == ePipeIdle) &&
               (g_sUSBHCD.psUSBINPipes[i32Idx].pfnCallback))
            {
                g_sUSBHCD.psUSBINPipes[i32Idx].pfnCallback(
                                                        IN_PIPE_HANDLE(i32Idx),
                                                        USB_EVENT_SCHEDULER);
            }
        }
    }
}

//*****************************************************************************
//
// The internal USB host mode interrupt handler.
//
// \param ui32Index is the USB controller associated with this interrupt.
// \param ui32Status is the current interrupt status as read via a call to
// \e USBIntStatusControl().
//
// This the main USB interrupt handler called when operating in host mode.
// This handler will branch the interrupt off to the appropriate handlers
// depending on the current status of the USB controller.
//
// The two-tiered structure for the interrupt handler ensures that it is
// possible to use the same handler code in both host and OTG modes and
// means that device code can be excluded from applications that only require
// support for USB host mode operation.
//
// \return None.
//
//*****************************************************************************
void
USBHostIntHandlerInternal(uint32_t ui32Index, uint32_t ui32Status)
{
    uint32_t ui32EPStatus, ui32DMAIntStatus, ui32Idx, ui32DevIndex;
    static uint32_t ui32SOFDivide = 0;
    int32_t i32ClassDrvr;

    //
    // By default, assume we are dealing with the device directly connected
    // to the host controller and that we need to notify its class driver of
    // this interrupt.
    //
    g_sUSBHCD.psUSBDevice[0].ui32Flags |= USBHDEV_FLAG_NOTIFYINT;

    if(ui32Status & USB_INTCTRL_SOF)
    {
        //
        // Indicate that a start of frame has occurred.
        //
        g_sUSBHCD.ui32IntEvents |= INT_EVENT_SOF;
    }

    //
    // A power fault has occurred so notify the application.
    //
    if(ui32Status & USB_INTCTRL_POWER_FAULT)
    {
        //
        // Indicate that a power fault has occurred.
        //
        g_sUSBHCD.ui32IntEvents |= INT_EVENT_POWER_FAULT;

        //
        // Turn off power to the bus.
        //
        MAP_USBHostPwrDisable(USB0_BASE);

        //
        // Disable USB interrupts.
        //
        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

        return;
    }

    //
    // In the event of a USB VBUS error, end the session and remove power to
    // the device.
    //
    if(ui32Status & USB_INTCTRL_VBUS_ERR)
    {
        //
        // Set the VBUS error event.  We deliberately clear all other events
        // since this one means anything else that is outstanding is
        // irrelevant.
        //
        g_sUSBHCD.ui32IntEvents = INT_EVENT_VBUS_ERR;
        return;
    }

    //
    // Received a reset from the host.
    //
    if(ui32Status & USB_INTCTRL_BABBLE)
    {
    }

    //
    // Suspend was signaled on the bus.
    //
    if(ui32Status & USB_INTCTRL_SUSPEND)
    {
    }

    //
    // Start the session.
    //
    if(ui32Status & USB_INTCTRL_SESSION)
    {
        //
        // Power the USB bus.
        //
        MAP_USBHostPwrEnable(USB0_BASE);

        USBOTGSessionRequest(USB0_BASE, true);
    }

    //
    // Resume was signaled on the bus.
    //
    if(ui32Status & USB_INTCTRL_RESUME)
    {
    }

    //
    // Device connected so tell the main routine to issue a reset.
    //
    if(ui32Status & USB_INTCTRL_CONNECT)
    {
        //
        // Set the connect flag and clear disconnect if it happens to be set.
        //
        g_sUSBHCD.ui32IntEvents |= INT_EVENT_CONNECT;
        g_sUSBHCD.ui32IntEvents &= ~INT_EVENT_DISCONNECT;

        //
        // Power the USB bus.
        //
        MAP_USBHostPwrEnable(USB0_BASE);
    }

    //
    // Handle the ID detection so that the ID pin can be used as a
    // GPIO in eUSBModeHost.
    //
    if(ui32Status & USB_INTCTRL_MODE_DETECT)
    {
        //
        // If in eUSBModeHost mode then switch back to OTG detection
        // so that VBUS can be monitored but free up the ID pin.
        //
        if(g_iUSBMode == eUSBModeHost)
        {
            USBOTGMode(USB0_BASE);
        }
    }

    //
    // Device was unplugged.
    //
    if(ui32Status & USB_INTCTRL_DISCONNECT)
    {
        //
        // Set the disconnect flag and clear connect if it happens to be set.
        //
        g_sUSBHCD.ui32IntEvents |= INT_EVENT_DISCONNECT;
        g_sUSBHCD.ui32IntEvents &= ~INT_EVENT_CONNECT;
    }

    //
    // Start of Frame was received.
    //
    if(ui32Status & USB_INTCTRL_SOF)
    {
        //
        // Increment the global Start of Frame counter.
        //
        g_ui32USBSOFCount++;

        //
        // Increment our SOF divider.
        //
        ui32SOFDivide++;

        //
        // Have we counted enough SOFs to allow us to call the tick function?
        //
        if(ui32SOFDivide == USB_SOF_TICK_DIVIDE)
        {
            //
            // Yes - reset the divider and call the SOF tick handler.
            //
            ui32SOFDivide = 0;
            InternalUSBStartOfFrameTick(USB_SOF_TICK_DIVIDE);
        }
    }

    //
    // Handle the LPM interrupt
    //
    ui32Status = USBLPMIntStatus(USB0_BASE);

    if(ui32Status)
    {
        //
        // Set the LPM interrupt event and clear the pending event.
        //
        g_sUSBHCD.ui32IntEvents |= INT_EVENT_LPM;
        g_sUSBHCD.ui32IntEvents &= ~INT_EVENT_LPM_PEND;

        //
        // Anything other than and acknowledge means that the transfer
        // was not complete for some reason.
        //
        for(ui32Idx = 0; ui32Idx < (MAX_USB_DEVICES + 1); ui32Idx++)
        {
            if((ui32Status != USB_INTLPM_ACK) &&
               (g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags &
                USBHDEV_FLAG_LPMPEND))
            {
                g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags |=
                                                        USBHDEV_FLAG_LPMERROR;
            }
            g_sUSBHCD.psUSBDevice[ui32Idx].ui32Flags &= ~USBHDEV_FLAG_LPMPEND;
        }
    }

    //
    // Check to see if any DMA transfers are pending
    //
    ui32DMAIntStatus = USBLibDMAIntStatus(g_sUSBHCD.psDMAInstance);

    if(ui32DMAIntStatus)
    {
        //
        // Handle any DMA interrupt processing.
        //
        USBLibDMAIntHandler(g_sUSBHCD.psDMAInstance, ui32DMAIntStatus);

        for(ui32Idx = 0; ui32Idx < MAX_NUM_PIPES; ui32Idx++)
        {
            if((g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReadDMAWait) ||
               (g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReadDMA))
            {
                //
                // If the DMA channel transfer is complete, send an ack.
                //
                if(USBLibDMAChannelStatus(g_sUSBHCD.psDMAInstance,
                       g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel) ==
                   USBLIBSTATUS_DMA_COMPLETE)
                {
                    //
                    // Acknowledge the IN request.
                    //
                    MAP_USBHostEndpointDataAck(USB0_BASE,
                                               IndexToUSBEP(ui32Idx + 1));

                    //
                    // If using uDMA then the endpoint status interrupt will
                    // not occur.  So process the data ready event here.
                    //
                    g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeDataReady;

                    //
                    // Only call a handler if one is present.
                    //
                    if(g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback)
                    {
                        g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
                            IN_PIPE_HANDLE(ui32Idx), USB_EVENT_RX_AVAILABLE);
                    }

                    //
                    // Remember that we need to notify this device's class
                    // driver that an interrupt occurred.
                    //
                    g_sUSBHCD.psUSBINPipes[ui32Idx].psDevice->ui32Flags |=
                                                    USBHDEV_FLAG_NOTIFYINT;
                }
            }
            else if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState ==
                    ePipeWriteDMASend)
            {
                //
                // If the uDMA channel transfer is complete, then tell
                // the USB controller to go ahead and send the data
                //
                if(USBLibDMAChannelStatus(g_sUSBHCD.psDMAInstance,
                       g_sUSBHCD.psUSBOUTPipes[ui32Idx].ui8DMAChannel) &
                   USBLIBSTATUS_DMA_COMPLETE)
                {
                    MAP_USBEndpointDataSend(USB0_BASE,
                                            IndexToUSBEP(ui32Idx + 1),
                                            USB_TRANS_OUT);

                    //
                    // Now waiting on the final endpoint interrupt.
                    //
                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState =
                                                            ePipeWriteDMAWait;
                }
            }
            else if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState == ePipeWriteDMA)
            {
                //
                // Data was transmitted successfully.
                //
                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeDataSent;

                //
                // Only call a handler if one is present.
                //
                if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback)
                {
                    //
                    // Notify the pipe that its last transaction was completed.
                    //
                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
                            OUT_PIPE_HANDLE(ui32Idx),
                            USB_EVENT_TX_COMPLETE);
                }
            }
        }
    }

    //
    // Get the current endpoint interrupt status.
    //
    ui32Status = MAP_USBIntStatusEndpoint(USB0_BASE);

    //
    // Handle end point 0 interrupts.
    //
    if(ui32Status & USB_INTEP_0)
    {
        //
        // Indicate that a start of frame has occurred.
        //
        g_sUSBHCD.ui32IntEvents |= INT_EVENT_ENUM;
    }

    for(ui32Idx = 0; ui32Idx < MAX_NUM_PIPES; ui32Idx++)
    {
        //
        // Check the next pipe, the first time through this will clear out
        // any interrupts dealing with endpoint zero since it was handled
        // above.
        //
        ui32Status >>= 1;

        //
        // Break out if there are no more pending interrupts.
        //
        if(ui32Status == 0)
        {
            break;
        }

        //
        // Check the status of the receive(IN) pipes.
        //
        if(ui32Status & 0x10000)
        {
            //
            // Clear the status flag for the IN Pipe.
            //
            ui32Status &= ~0x10000;

            //
            // Read the status of the endpoint connected to this pipe.
            //
            ui32EPStatus = MAP_USBEndpointStatus(USB0_BASE,
                                               IndexToUSBEP(ui32Idx + 1));

            //
            // Check if the device stalled the request.
            //
            if(ui32EPStatus & USB_HOST_IN_STALL)
            {
                //
                // Clear the stall condition on this endpoint pipe.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE,
                                               IndexToUSBEP(ui32Idx + 1),
                                               USB_HOST_IN_STALL);

                //
                // Save the STALLED state.
                //
                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeStalled;

                //
                // Notify the pipe that it was stalled.
                //
                if(g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback)
                {
                    g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
                                                    IN_PIPE_HANDLE(ui32Idx),
                                                    USB_EVENT_STALL);
                }
            }
            else if(ui32EPStatus & USB_HOST_IN_ERROR)
            {
                //
                // We can no longer communicate with this device for some
                // reason.  It may have been disconnected from a hub, for
                // example.  Merely clear the status and continue.
                //
                USBHostEndpointStatusClear(USB0_BASE,
                                           IndexToUSBEP(ui32Idx + 1),
                                           USB_HOST_IN_ERROR);

                //
                // Save the STALLED state.
                //
                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeError;

                //
                // Notify the pipe that it was stalled.
                //
                if(g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback)
                {
                    g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
                                                    IN_PIPE_HANDLE(ui32Idx),
                                                    USB_EVENT_ERROR);
                }
            }
            //
            // Handle the case where the pipe is reading a single packet.
            //
            else if(g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReadDMA)
            {
                void *pvAddr;

                //
                // Enable the DMA channel and wait for it to complete.
                //
                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeReadDMAWait;

                pvAddr = USBLibDMAAddrGet(g_sUSBHCD.psDMAInstance,
                                g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel);

                //
                // Save the amount of data available.
                //
                g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead =
                            USBEndpointDataAvail(USB0_BASE,
                                                 IndexToUSBEP(ui32Idx + 1));

                //
                // Only request what is available.
                //
                if(g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead <=
                   g_sUSBHCD.psUSBINPipes[ui32Idx].ui32ReadSize)
                {
                    //
                    // Reset the transfer size.
                    //
                    USBLibDMATransfer(g_sUSBHCD.psDMAInstance,
                                 g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel,
                                 pvAddr,
                                 g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead);
                }
                else
                {
                    //
                    // The transfer size did not change, this leaves some
                    // data in the FIFO.
                    //
                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead =
                            g_sUSBHCD.psUSBINPipes[ui32Idx].ui32ReadSize;
                }

                USBLibDMAChannelEnable(
                        g_sUSBHCD.psDMAInstance,
                        g_sUSBHCD.psUSBINPipes[ui32Idx].ui8DMAChannel);
            }
            else if(g_sUSBHCD.psUSBINPipes[ui32Idx].iState == ePipeReading)
            {
                //
                // Data is available.
                //
                g_sUSBHCD.psUSBINPipes[ui32Idx].iState = ePipeDataReady;

                //
                // Read the data out of the USB endpoint interface into the
                // buffer provided by the caller to USBHCDPipeRead() or
                // USBHCDPipeSchedule() if a buffer was provided already.
                //
                if(g_sUSBHCD.psUSBINPipes[ui32Idx].pui8ReadPtr)
                {
                    g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead =
                                g_sUSBHCD.psUSBINPipes[ui32Idx].ui32ReadSize;

                    USBEndpointDataGet(USB0_BASE, IndexToUSBEP(ui32Idx + 1),
                                g_sUSBHCD.psUSBINPipes[ui32Idx].pui8ReadPtr,
                                &g_sUSBHCD.psUSBINPipes[ui32Idx].ui32DataRead);
                }

                //
                // Notify the pipe that its last transaction was completed.
                //
                if(g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback)
                {
                    g_sUSBHCD.psUSBINPipes[ui32Idx].pfnCallback(
                                                    IN_PIPE_HANDLE(ui32Idx),
                                                    USB_EVENT_RX_AVAILABLE);
                }

            }

            //
            // Remember that we need to notify this device's class
            // driver that an interrupt occurred.
            //
            g_sUSBHCD.psUSBINPipes[ui32Idx].psDevice->ui32Flags |=
                                                    USBHDEV_FLAG_NOTIFYINT;
        }

        //
        // Check the status of the transmit(OUT) pipes.
        //
        if(ui32Status & 1)
        {
            //
            // Read the status of the endpoint connected to this pipe.
            //
            ui32EPStatus = MAP_USBEndpointStatus(USB0_BASE,
                                               IndexToUSBEP(ui32Idx + 1));

            //
            // Check if the device stalled the request.
            //
            if(ui32EPStatus & USB_HOST_OUT_STALL)
            {
                //
                // Clear the stall condition on this endpoint pipe.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE,
                                               IndexToUSBEP(ui32Idx + 1),
                                               USB_HOST_OUT_STALL);

                //
                // Save the STALLED state.
                //
                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeStalled;

                //
                // Only call a handler if one is present.
                //
                if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback)
                {
                    //
                    // Notify the pipe that it was stalled.
                    //
                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
                            OUT_PIPE_HANDLE(ui32Idx),
                            USB_EVENT_STALL);
                }
            }
            else if(ui32EPStatus & USB_HOST_OUT_ERROR)
            {
                //
                // Clear the error condition on this endpoint pipe.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE,
                                               IndexToUSBEP(ui32Idx + 1),
                                               USB_HOST_OUT_ERROR);

                //
                // Save the Pipes error state.
                //
                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeError;

                //
                // Only call a handler if one is present.
                //
                if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback)
                {
                    //
                    // Notify the pipe that had an error.
                    //
                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
                            OUT_PIPE_HANDLE(ui32Idx),
                            USB_EVENT_ERROR);
                }
            }
            else if((g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState ==
                     ePipeWriting) ||
                    (g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState ==
                     ePipeWriteDMAWait))
            {
                //
                // Data was transmitted successfully.
                //
                g_sUSBHCD.psUSBOUTPipes[ui32Idx].iState = ePipeDataSent;

                //
                // Only call a handler if one is present.
                //
                if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback)
                {
                    //
                    // Notify the pipe that its last transaction was completed.
                    //
                    g_sUSBHCD.psUSBOUTPipes[ui32Idx].pfnCallback(
                            OUT_PIPE_HANDLE(ui32Idx),
                            USB_EVENT_TX_COMPLETE);
                }
            }

            //
            // Clear the stall condition on this endpoint pipe.
            //
            MAP_USBHostEndpointStatusClear(USB0_BASE,
                                           IndexToUSBEP(ui32Idx + 1),
                                           ui32EPStatus & USB_HOST_OUT_STATUS);
            //
            // Remember that we need to notify this device's class
            // driver that an interrupt occurred.
            //
            if(g_sUSBHCD.psUSBOUTPipes[ui32Idx].psDevice)
            {
                g_sUSBHCD.psUSBINPipes[ui32Idx].psDevice->ui32Flags |=
                                                    USBHDEV_FLAG_NOTIFYINT;
            }
        }
    }

    //
    // Send back notifications to any class driver whose endpoint required
    // service during the handler.
    //
    for(ui32DevIndex = 0; ui32DevIndex <= MAX_USB_DEVICES; ui32DevIndex++)
    {
        //
        // Which class driver does this device use?
        //
        i32ClassDrvr = g_pi32USBHActiveDriver[ui32DevIndex];

        //
        // If a class driver is in use, and one of its endpoints was serviced
        // and the class driver has an interrupt callback...
        //
        if((i32ClassDrvr >= 0) &&
           (g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags &
            USBHDEV_FLAG_NOTIFYINT) &&
           (g_sUSBHCD.ppsClassDrivers[i32ClassDrvr]->pfnIntHandler))
        {
            //
            // ...call the class driver's interrupt notification callback.
            //
            g_sUSBHCD.ppsClassDrivers[i32ClassDrvr]->pfnIntHandler(
                                            g_ppvDriverInstance[ui32DevIndex]);
        }
    }
}

//*****************************************************************************
//
//! The USB host mode interrupt handler for controller index 0.
//!
//! This the main USB interrupt handler entry point.  This handler will branch
//! the interrupt off to the appropriate handlers depending on the current
//! status of the USB controller.   This function must be placed in the
//! interrupt table in order for the USB Library host stack to function.
//!
//! \return None.
//
//*****************************************************************************
void
USB0HostIntHandler(void)
{
    uint32_t ui32Status;

    //
    // Get the control interrupt status.
    //
    ui32Status = MAP_USBIntStatusControl(USB0_BASE);

    //
    // Call the internal handler to process the interrupts.
    //
    USBHostIntHandlerInternal(0, ui32Status);
}

//*****************************************************************************
//
//! This function opens the class driver.
//!
//! \param ui32Index specifies which USB controller to use.
//! \param ui32DeviceNum is the device number for the driver to load.
//!
//! This function opens the driver needed based on the class value found in
//! the device's interface descriptor.
//!
//! \return This function returns -1 if no driver is found, or it returns the
//! index of the driver found in the list of host class drivers.
//
//*****************************************************************************
static int32_t
USBHCDOpenDriver(uint32_t ui32Index, uint32_t ui32DeviceNum)
{
    int32_t i32Driver;
    uint32_t ui32Class;
    tInterfaceDescriptor *psInterface;
    tEventInfo sEvent;

    ASSERT(ui32Index == 0);

    //
    // Get the interface descriptor.
    //
    psInterface = USBDescGetInterface(
                    g_sUSBHCD.psUSBDevice[ui32DeviceNum].psConfigDescriptor,
                    g_sUSBHCD.psUSBDevice[ui32DeviceNum].ui32Interface,
                    USB_DESC_ANY);

    //
    // Read the interface class.
    //
    ui32Class = psInterface->bInterfaceClass;

    //
    // Search through the Host Class driver list for the devices class.
    //
    for(i32Driver = 0; i32Driver < g_sUSBHCD.ui32NumClassDrivers; i32Driver++)
    {
        //
        // If a driver was found call the open for this driver and save which
        // driver is in use.
        //
        if(g_sUSBHCD.ppsClassDrivers[i32Driver]->ui32InterfaceClass ==
           ui32Class)
        {
            //
            // Call the open function for the class driver.
            //
            g_ppvDriverInstance[ui32DeviceNum] =
                    g_sUSBHCD.ppsClassDrivers[i32Driver]->pfnOpen(
                            &g_sUSBHCD.psUSBDevice[ui32DeviceNum]);

            //
            // If the driver was successfully loaded then break out of the
            // loop.
            //
            if(g_ppvDriverInstance[ui32DeviceNum] != 0)
            {
                break;
            }
        }
    }

    //
    // If no drivers were found then return -1 to indicate an invalid
    // driver instance.
    //
    if(i32Driver == g_sUSBHCD.ui32NumClassDrivers)
    {
        //
        // Send an unknown connection event.
        //
        SendUnknownConnect(ui32Index, (ui32Index << 16) | ui32DeviceNum);

        //
        // Indicate that no driver was found.
        //
        i32Driver = -1;
    }
    else
    {
        //
        // If the connect event is enabled then send the event.
        //
        sEvent.ui32Event = USB_EVENT_CONNECTED;
        sEvent.ui32Instance = (ui32Index << 16) | ui32DeviceNum;
        InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_CONNECT);
    }

    return(i32Driver);
}

//*****************************************************************************
//
// This function will send an event to a registered event driver.
//
// \param ui32Index specifies which USB controller to use.
// \param psEvent is a pointer to the event structure to send.
//
// This function is only used internally to the USB library and will check
// if an event driver is registered and send on the event.
//
// Note: This function should not be called outside of the USB library.
//
// \return None.
//
//*****************************************************************************
void
InternalUSBHCDSendEvent(uint32_t ui32Index, tEventInfo *psEvent,
                        uint32_t ui32EvFlag)
{
    //
    // Make sure that an event driver has been registered.
    //
    if((g_sUSBHCD.i32EventDriver != -1) &&
       (g_sUSBHCD.ppsClassDrivers[g_sUSBHCD.i32EventDriver]->pfnIntHandler) &&
       (g_sUSBHCD.ui32EventEnables & ui32EvFlag))
    {
        g_sUSBHCD.ppsClassDrivers[g_sUSBHCD.i32EventDriver]->pfnIntHandler(
                                                                    psEvent);
    }
}

//*****************************************************************************
//
// This function handles the necessary clean up for device disconnect.
//
// \param ui32Index is the device number for the device that was disconnected.
//
// This function handles all of the necessary clean up after a device
// disconnect has been detected by the stack.  This includes calling back the
// appropriate driver if necessary.
//
// \return None.
//
//*****************************************************************************
static void
USBHCDDeviceDisconnected(uint32_t ui32Index, uint32_t ui32DevIndex)
{
    tEventInfo sEvent;

    ASSERT(ui32Index == 0);
    ASSERT(ui32DevIndex <= MAX_USB_DEVICES);

    //
    // If there is an event driver with a valid event handler and the
    // USBHCD_EVFLAG_DISCNCT is enabled, then call the registered event
    // handler.
    //
    sEvent.ui32Event = USB_EVENT_DISCONNECTED;
    sEvent.ui32Instance = (ui32Index << 16) | ui32DevIndex;
    InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_DISCNCT);

    //
    // Reset the class.
    //
    g_sUSBHCD.ui32Class = USB_CLASS_EVENTS;

    //
    // Free the memory used by the configuration descriptor.
    //
    ConfigDescFree(&g_sUSBHCD.psUSBDevice[ui32DevIndex]);

    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags = 0;
    g_sUSBHCD.psUSBDevice[ui32DevIndex].bConfigRead = false;

    //
    // Reset the max packet size so that this will be re-read from new devices.
    //
    g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bMaxPacketSize0 = 0;

    //
    // No longer have a device descriptor.
    //
    g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bLength = 0;

    //
    // No longer addressed.
    //
    g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address = 0;

    //
    // If this was an active driver then close it out.
    //
    if(g_pi32USBHActiveDriver[ui32DevIndex] >= 0)
    {
        //
        // Call the driver Close entry point.
        //
        g_sUSBHCD.ppsClassDrivers[g_pi32USBHActiveDriver[ui32DevIndex]]->
            pfnClose(g_ppvDriverInstance[ui32DevIndex]);

        //
        // No active driver now present.
        //
        g_pi32USBHActiveDriver[ui32DevIndex] = -1;
        g_ppvDriverInstance[ui32DevIndex] = 0;
    }

    //
    // This call is necessary for OTG controllers to know that the host
    // stack has completed handling the disconnect of the device before
    // removing power and returning to a state that can allow OTG
    // negotiations once again.
    // We only do this if the disconnected device
    // was attached directly to us (device index 0).
    //
    if((ui32DevIndex == 0) && (g_iUSBMode == eUSBModeOTG))
    {
        OTGDeviceDisconnect(0);
    }
}

//*****************************************************************************
//
//! This function is the main routine for the Host Controller Driver.
//!
//! This function is the main routine for the host controller driver, and must
//! be called periodically by the main application outside of a callback
//! context.  This allows for a simple cooperative system to access the the
//! host controller driver interface without the need for an RTOS.  All time
//! critical operations are handled in interrupt context but all blocking
//! operations are run from the this function to allow them to block and wait
//! for completion without holding off other interrupts.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDMain(void)
{
    tUSBHDeviceState iOldState;
    int32_t i32Dev;
    tEventInfo sEvent;

    //
    // Save the old state to detect changes properly.
    //
    iOldState = g_sUSBHCD.piDeviceState[0];

    //
    // Fix up the state if any important interrupt events occurred.
    //
    if(g_sUSBHCD.ui32IntEvents)
    {
        //
        // Disable the USB interrupt.
        //
        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

        if(g_sUSBHCD.ui32IntEvents & INT_EVENT_POWER_FAULT)
        {
            //
            // A power fault has occurred so notify the application if there
            // is an event handler and the event has been enabled.
            //
            sEvent.ui32Event = USB_EVENT_POWER_FAULT;
            sEvent.ui32Instance = 0;
            InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_PWRFAULT);

            g_sUSBHCD.piDeviceState[0] = eHCDPowerFault;
        }
        else if(g_sUSBHCD.ui32IntEvents & INT_EVENT_VBUS_ERR)
        {
            //
            // A VBUS error has occurred.  This event trumps connect and
            // disconnect since it will cause a controller reset.
            //
            g_sUSBHCD.piDeviceState[0] = eHCDVBUSError;
        }
        else
        {
            //
            // Has a device connected?
            //
            if(g_sUSBHCD.ui32IntEvents & INT_EVENT_CONNECT)
            {
                g_sUSBHCD.piDeviceState[0] = eHCDDevReset;
                g_sUSBHCD.psUSBDevice[0].ui8Hub = 0;
                g_sUSBHCD.psUSBDevice[0].ui8HubPort = 0;
            }
            else
            {
                //
                // Has a device disconnected?
                //
                if(g_sUSBHCD.ui32IntEvents & INT_EVENT_DISCONNECT)
                {
                    g_sUSBHCD.piDeviceState[0] = eHCDDevDisconnected;
                }
            }

            //
            // Handle the start of frame event
            //
            if(g_sUSBHCD.ui32IntEvents & INT_EVENT_SOF)
            {
                //
                // If the connect event is enabled then send the event.
                //
                sEvent.ui32Event = USB_EVENT_SOF;
                sEvent.ui32Instance = 0;
                InternalUSBHCDSendEvent(0, &sEvent, USBHCD_EVFLAG_SOF);

                USBHostCheckPipes();

                //
                // Call the hub driver to have it perform any necessary
                // processing to handle downstream devices.
                //
                USBHHubMain();
            }

            //
            // Handle LPM interrupt events.
            //
            if(g_sUSBHCD.ui32IntEvents & INT_EVENT_LPM)
            {
                //
                // There should be a pending LPM request.
                //
                ASSERT((g_sUSBHCD.ui32IntEvents & INT_EVENT_LPM_PEND) != 0);

                for(i32Dev = 0; i32Dev < MAX_USB_DEVICES + 1; i32Dev++)
                {
                    //
                    // Find the device with the pending LPM request.
                    //
                    if(g_sUSBHCD.psUSBDevice[i32Dev].ui32Flags &
                       USBHDEV_FLAG_LPMPEND)
                    {
                        //
                        // Clear the pending event at the device level, this
                        // leaves the error set if it was already set.
                        //
                        g_sUSBHCD.psUSBDevice[i32Dev].ui32Flags &=
                                                    ~USBHDEV_FLAG_LPMPEND;

                        //
                        // Clear the pending request and event at the host
                        // controller level.
                        //
                        g_sUSBHCD.ui32IntEvents &= ~(INT_EVENT_LPM_PEND |
                                                     INT_EVENT_LPM);
                    }
                }
            }
        }

        //
        // Clear the flags.
        //
        g_sUSBHCD.ui32IntEvents = 0;

        //
        // Enable the USB interrupt.
        //
        OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);
    }

    //
    // Process the state machine for each connected device.  Yes, the exit
    // condition for this loop is correct since we support (MAX_USB_DEVICES+1)
    // devices (the hub counts as one).
    //
    for(i32Dev = 0; i32Dev <= MAX_USB_DEVICES; i32Dev++)
    {
        //
        // If this is not the first device (i.e. the one directly connected to
        // the host controller) then set the old state to the current state
        // since we won't have mucked with it in any of the previous code.
        //
        if(i32Dev != 0)
        {
            iOldState = g_sUSBHCD.piDeviceState[i32Dev];
        }

        //
        // Process the state machine for this device.
        //
        ProcessUSBDeviceStateMachine(iOldState, i32Dev);
    }
}

static void
ProcessUSBDeviceStateMachine(tUSBHDeviceState iOldState,
                             uint32_t ui32DevIndex)
{
    switch(g_sUSBHCD.piDeviceState[ui32DevIndex])
    {
        //
        // There was a power fault condition so shut down and wait for the
        // application to re-initialized the system.
        //
        case eHCDPowerFault:
        {
            break;
        }

        //
        // There was a VBUS error so handle it.
        //
        case eHCDVBUSError:
        {
            //
            // Disable USB interrupts.
            //
            OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

            //
            // If there was a device in any state of connection then indicate
            // that it has been disconnected.
            //
            if((iOldState != eHCDIdle) && (iOldState != eHCDPowerFault))
            {
                //
                // Handle device disconnect.
                //
                USBHCDDeviceDisconnected(0, ui32DevIndex);
            }

            //
            // Reset the controller.
            //
            MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_USB0);

            //
            // Wait for 100ms before trying to re-power the device.
            //
            OS_DELAY(g_ui32Tickms * 100);

            //
            // Re-initialize the HCD.
            //
            USBHCDInitInternal(0, g_sUSBHCD.pvPool, g_sUSBHCD.ui32PoolSize);

            break;
        }
        //
        // Trigger a reset to the connected device.
        //
        case eHCDDevReset:
        {
            if(!ui32DevIndex)
            {
                //
                // Trigger a Reset.  This is only ever done for devices
                // attached directly to the controller.
                //
                DEBUG_OUTPUT("USB reset.\n");
                USBHCDReset(0);
            }

            //
            // The state moves to connected but not configured.
            //
            g_sUSBHCD.piDeviceState[0] = eHCDDevConnected;

            //
            // Remember that we don't have a valid configuration descriptor
            // yet.
            //
            g_sUSBHCD.psUSBDevice[0].bConfigRead = false;

            break;
        }
        //
        // Device connection has been established now start enumerating
        // the device.
        //
        case eHCDDevConnected:
        case eHCDDevConnectedHub:
        {
            //
            // First check if we have read the device descriptor at all
            // before proceeding.
            //
            if(g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bLength ==
               0)
            {
                //
                // Initialize a request for the device descriptor.
                //
                DEBUG_OUTPUT("Connection %d - getting device descriptor\n",
                             ui32DevIndex);

                //
                // Hub enumeration has already set the speed so do not
                // override the setting here.
                //
                if(g_sUSBHCD.piDeviceState[ui32DevIndex] == eHCDDevConnected)
                {
                    //
                    // Remember the speed of this device to ensure endpoints
                    // are properly configured.
                    //
                    switch(USBHostSpeedGet(USB0_BASE))
                    {
                        case USB_HIGH_SPEED:
                        {
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed =
                                                            USB_EP_SPEED_HIGH;
                            break;
                        }
                        case USB_FULL_SPEED:
                        {
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed =
                                                            USB_EP_SPEED_FULL;
                            break;
                        }
                        default:
                        {
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed =
                                                            USB_EP_SPEED_LOW;
                            break;
                        }
                    }
                }

                if(USBHCDGetDeviceDescriptor(0,
                        &g_sUSBHCD.psUSBDevice[ui32DevIndex]) == 0)
                {
                    //
                    // If the device descriptor cannot be read then the device
                    // will be treated as unknown.
                    //
                    g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevError;

                    DEBUG_OUTPUT("Connection %d - failed to get descriptor\n",
                                 ui32DevIndex);

                    //
                    // Send an unknown connection event to let the application
                    // know that there is a device connected but return no
                    // zero for the instance.
                    //
                    SendUnknownConnect(0, 0);

                    //
                    // If the device is connected via a hub, tell the hub
                    // driver that we experienced an error enumerating the
                    // device.
                    //
                    if(g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub)
                    {
                        USBHHubEnumerationError(
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
                    }
                }
            }
            //
            // If we have the device descriptor then move on to setting
            // the address of the device.
            //
            else if(g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address == 0)
            {
                DEBUG_OUTPUT("Connection %d - setting address %d\n",
                             ui32DevIndex, ui32DevIndex + 1);

                //
                // Send the set address command.
                //
                USBHCDSetAddress(ui32DevIndex, (ui32DevIndex + 1));

                //
                // Save the address.
                //
                g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address =
                                                            (ui32DevIndex + 1);

                //
                // Move on to the addressed state.
                //
                g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevAddressed;
            }
            break;
        }
        case eHCDDevAddressed:
        {
            //
            // First check if we have read the configuration descriptor.
            //
            if(!g_sUSBHCD.psUSBDevice[ui32DevIndex].bConfigRead)
            {
                DEBUG_OUTPUT("Connection %d - getting config descriptor\n",
                             ui32DevIndex);

                //
                // Initialize a request for the configuration descriptor.
                //
                if(USBHCDGetConfigDescriptor(0,
                                    &g_sUSBHCD.psUSBDevice[ui32DevIndex]) == 0)
                {
                    //
                    // If the device descriptor cannot be read then the device
                    // will be treated as unknown.
                    //
                    g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevError;

                    DEBUG_OUTPUT("Connection %d - failed to get descriptor\n",
                                 ui32DevIndex);

                    //
                    // Send an unknown connection event to let the application
                    // know that there is a device connected but return no
                    // zero for the instance.
                    //
                    SendUnknownConnect(0, 0);

                    //
                    // If the device is connected via a hub, tell the hub
                    // driver that we experienced an error enumerating the
                    // device.
                    //
                    if(g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub)
                    {
                        USBHHubEnumerationError(
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
                    }
                }
            }
            //
            // Now have addressed and received the device configuration,
            // so get ready to set the device configuration.
            //
            else
            {
                DEBUG_OUTPUT("Connection %d - setting configuration.\n",
                             ui32DevIndex);

                //
                // Use the first configuration to set the device
                // configuration.
                //
                USBHCDSetConfig(0,
                            (uint32_t)&g_sUSBHCD.psUSBDevice[ui32DevIndex], 1);

                //
                // Move on to the configured state.
                //
                g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevConfigured;

                //
                // Open the driver for the device.
                //
                g_pi32USBHActiveDriver[ui32DevIndex] = USBHCDOpenDriver(0,
                                                                ui32DevIndex);

                //
                // If the device is connected via a hub, tell the hub
                // driver that enumeration is complete.
                //
                if(g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub)
                {
                    USBHHubEnumerationComplete(
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
                            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
                }
            }
            break;
        }
        //
        // The device was making a request and is now complete.
        //
        case eHCDDevRequest:
        {
            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevConnected;
            break;
        }
        //
        // The strings are currently not accessed.
        //
        case eHCDDevGetStrings:
        {
            break;
        }
        //
        // Basically Idle at this point.
        //
        case eHCDDevDisconnected:
        {
            DEBUG_OUTPUT("Connection %d - disconnected.\n",
                         ui32DevIndex);

            //
            // Handle device disconnect.
            //
            USBHCDDeviceDisconnected(0, ui32DevIndex);

            //
            // Return to the Idle state.
            //
            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDIdle;
            break;
        }

        //
        // Connection and enumeration is complete so allow this function
        // to exit.
        //
        case eHCDDevConfigured:
        {
            break;
        }

        //
        // Poorly behaving device are in limbo in this state until removed.
        //
        case eHCDDevError:
        {
            DEBUG_OUTPUT("Connection %d - Error!\n", ui32DevIndex);

            //
            // If this device is connected directly to us, tidy up and ignore
            // it until it is removed.  If the device is connected to a hub,
            // we just leave it in the error state until it is removed.
            //
            if(ui32DevIndex == 0)
            {
                g_sUSBHCD.ui32IntEvents |= INT_EVENT_DISCONNECT;
                g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDIdle;
            }
            break;
        }
        default:
        {
            break;
        }
    }
}

//*****************************************************************************
//
//! This function completes a control transaction to a device.
//!
//! \param ui32Index is the controller index to use for this transfer.
//! \param psSetupPacket is the setup request to be sent.
//! \param psDevice is the device instance pointer for this request.
//! \param pui8Data is the data to send for OUT requests or the receive buffer
//! for IN requests.
//! \param ui32Size is the size of the buffer in \e pui8Data.
//! \param ui32MaxPacketSize is the maximum packet size for the device for this
//! request.
//!
//! This function handles the state changes necessary to send a control
//! transaction to a device.  This function should not be called from within
//! an interrupt callback as it is a blocking function.
//!
//! \return The number of bytes of data that were sent or received as a result
//! of this request.
//
//*****************************************************************************
uint32_t
USBHCDControlTransfer(uint32_t ui32Index, tUSBRequest *psSetupPacket,
                      tUSBHostDevice *psDevice, uint8_t *pui8Data,
                      uint32_t ui32Size, uint32_t ui32MaxPacketSize)
{
    uint32_t ui32Remaining;
    uint32_t ui32DataSize;

    //
    // Debug sanity check.
    //
    ASSERT(g_sUSBHEP0State.iState == eEP0StateIdle);
    ASSERT(ui32Index == 0);

    //
    // Initialize the state of the data for this request.
    //
    g_sUSBHEP0State.pui8Data = pui8Data;
    g_sUSBHEP0State.ui32BytesRemaining = ui32Size;
    g_sUSBHEP0State.ui32DataSize = ui32Size;

    //
    // Set the maximum packet size.
    //
    g_sUSBHEP0State.ui32MaxPacketSize = ui32MaxPacketSize;

    //
    // Save the current address.
    //
    g_sUSBHEP0State.ui32DevAddress = psDevice->ui32Address;

    //
    // Set the address the host will used to communicate with the device.
    //
    MAP_USBHostAddrSet(USB0_BASE, USB_EP_0, g_sUSBHEP0State.ui32DevAddress,
                       USB_EP_HOST_OUT);

    //
    // Make sure that endpoint 0 has the proper speed setting.
    //
    USBHostEndpointConfig(USB0_BASE, USB_EP_0, 64, 0, 0,
                          (USB_EP_MODE_CTRL | psDevice->ui32Speed |
                           USB_EP_HOST_OUT));

    //
    // Put the data in the correct FIFO.
    //
    MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, (uint8_t *)psSetupPacket,
                           sizeof(tUSBRequest));

    //
    // If this is an IN request, change to that state.
    //
    if(psSetupPacket->bmRequestType & USB_RTYPE_DIR_IN)
    {
        g_sUSBHEP0State.iState = eEP0StateSetupIN;
    }
    else
    {
        //
        // If there is no data then this is not an OUT request.
        //
        if(ui32Size != 0)
        {
            //
            // Since there is data, this is an OUT request.
            //
            g_sUSBHEP0State.iState = eEP0StateSetupOUT;
        }
        else
        {
            //
            // Otherwise this request has no data and just a status phase.
            //
            g_sUSBHEP0State.iState = eEP0StateStatusIN;
        }
    }

    //
    // Make sure we are talking to the correct device.
    //
    if(psDevice->ui8Hub == 0)
    {
        USBHostHubAddrSet(USB0_BASE, USB_EP_0, 0,
                          USB_EP_HOST_OUT | psDevice->ui32Speed);
    }
    else
    {
        USBHostHubAddrSet(USB0_BASE, USB_EP_0,
                          (psDevice->ui8Hub | (psDevice->ui8HubPort << 8)),
                          USB_EP_HOST_OUT | psDevice->ui32Speed);
    }

    //
    // Send the Setup packet.
    //
    MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_SETUP);

    //
    // Block until endpoint 0 returns to the IDLE state.
    //
    while(g_sUSBHEP0State.iState != eEP0StateIdle)
    {
        OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

        if((g_sUSBHCD.ui32IntEvents & (INT_EVENT_ENUM | INT_EVENT_SOF)) ==
           (INT_EVENT_ENUM | INT_EVENT_SOF))
        {
            g_sUSBHCD.ui32IntEvents &= ~(INT_EVENT_ENUM | INT_EVENT_SOF);

            USBHCDEnumHandler();
        }

        OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);

        if(g_sUSBHEP0State.iState == eEP0StateError)
        {
            return(0xffffffff);
        }

        //
        // If we aborted the transfer due to an error, tell the caller
        // that no bytes were transferred.
        //
        if(g_sUSBHCD.ui32IntEvents & (INT_EVENT_VBUS_ERR |
                                      INT_EVENT_DISCONNECT))
        {
            return(0xffffffff);
        }
    }

    //
    // Calculate and return the number of bytes that were sent or received.
    // The extra copy into local variables is required to prevent some
    // compilers from warning about undefined order of volatile access.
    //
    ui32DataSize = g_sUSBHEP0State.ui32DataSize;
    ui32Remaining = g_sUSBHEP0State.ui32BytesRemaining;

    return(ui32DataSize - ui32Remaining);
}

//*****************************************************************************
//
// Starts enumerating a new device connected via the hub.
//
// \param ui32Index is the index of the USB controller to use.
// \param ui32Hub is the hub address from which the connection is being made.
// \param ui32Port is the hub port number that the new device is connected to.
// \param pui8ConfigPool is memory to be used to store the device's
// configuration descriptor.
// \param ui32ConfigSize is the number of bytes available in the buffer pointed
// to by pui8ConfigPool.
//
// This function is called by the hub class driver after it has detected a new
// device connection and reset the device.
//
// \return Returns the index of the device allocated or 0 if no resources are
//         available. Device index 0 is the hub itself.
//
//*****************************************************************************
uint32_t
USBHCDHubDeviceConnected(uint32_t ui32Index, uint8_t ui8Hub,
                         uint8_t ui8Port, uint32_t ui32Speed)
{
    uint32_t ui32DevIndex;

    //
    // Debug sanity checks.
    //
    ASSERT(ui32Index == 0);
    ASSERT(ui8Port);

    DEBUG_OUTPUT("Connection from hub %d, port %d.\n", ui8Hub, ui8Port);

    //
    // Look for a free slot in the device table.
    //
    for(ui32DevIndex = 1; ui32DevIndex <= MAX_USB_DEVICES; ui32DevIndex++)
    {
        if((g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags &
            USBHDEV_FLAG_ALLOCATED) == 0)
        {
            //
            // We found one. Set the state to ensure that it gets enumerated.
            //
            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Flags =
                                                        USBHDEV_FLAG_ALLOCATED;
            g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor->bLength = 0;
            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub = ui8Hub;
            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort = ui8Port;
            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Speed = ui32Speed;
            g_sUSBHCD.psUSBDevice[ui32DevIndex].sDeviceDescriptor.bLength = 0;

            //
            // Set the state to ensure enumeration begins.
            //
            g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevConnectedHub;

            DEBUG_OUTPUT("Allocating device %d\n", ui32DevIndex);

            //
            // Pass the device index back to the hub driver.
            //
            return(ui32DevIndex);
        }
    }

    //
    // If we get here, there are device slots available so send back an invalid
    // device index to tell the caller to ignore this device.
    //
    return(0);
}

//*****************************************************************************
//
// Called when a device is disconnected from a hub.
//
// \param ui32Index is the index of the USB controller to use.
// \param ui32DevIndex is the device index for the USB device that was
// disconnected.
//
//*****************************************************************************
void
USBHCDHubDeviceDisconnected(uint32_t ui32Index, uint32_t ui32DevIndex)
{
    //
    // Debug sanity checks.
    //
    ASSERT(ui32Index == 0);
    ASSERT(ui32DevIndex && (ui32DevIndex <= MAX_USB_DEVICES));

    DEBUG_OUTPUT("Disconnection from hub %d, port %d, device %d\n",
            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8Hub,
            g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort, ui32DevIndex);

    //
    // Set the device state to ensure that USBHCDMain cleans it up.
    //
    g_sUSBHCD.piDeviceState[ui32DevIndex] = eHCDDevDisconnected;
}

//*****************************************************************************
//
// This is the endpoint 0 interrupt handler.
//
// \return None.
//
//*****************************************************************************
static void
USBHCDEnumHandler(void)
{
    uint32_t ui32EPStatus;
    uint32_t ui32DataSize;

    //
    // Get the end point 0 status.
    //
    ui32EPStatus = MAP_USBEndpointStatus(USB0_BASE, USB_EP_0);

    //
    // If there was an error then go to the error state.
    //
    if(ui32EPStatus == USB_HOST_EP0_ERROR)
    {
        //
        // Clear this status indicating that the status packet was
        // received.
        //
        MAP_USBHostEndpointStatusClear(USB0_BASE, USB_EP_0,
                                       USB_HOST_EP0_ERROR);
        MAP_USBFIFOFlush(USB0_BASE, USB_EP_0, 0);

        //
        // Just go back to the idle state.
        //
        g_sUSBHEP0State.iState = eEP0StateError;

        return;
    }

    switch(g_sUSBHEP0State.iState)
    {
        //
        // Handle the status state, this is a transitory state from
        // USB_STATE_TX or USB_STATE_RX back to USB_STATE_IDLE.
        //
        case eEP0StateStatus:
        {
            //
            // Handle the case of a received status packet.
            //
            if(ui32EPStatus & (USB_HOST_EP0_RXPKTRDY | USB_HOST_EP0_STATUS))
            {
                //
                // Clear this status indicating that the status packet was
                // received.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE, USB_EP_0,
                                               (USB_HOST_EP0_RXPKTRDY |
                                                USB_HOST_EP0_STATUS));
            }

            //
            // Just go back to the idle state.
            //
            g_sUSBHEP0State.iState = eEP0StateIdle;

            break;
        }

        //
        // This state triggers a STATUS IN request from the device.
        //
        case eEP0StateStatusIN:
        {
            //
            // Generate an IN request from the device.
            //
            MAP_USBHostRequestStatus(USB0_BASE);

            //
            // Change to the status phase and wait for the response.
            //
            g_sUSBHEP0State.iState =  eEP0StateStatus;

            break;
        }

        //
        // In the IDLE state the code is waiting to receive data from the host.
        //
        case eEP0StateIdle:
        {
            break;
        }

        //
        // Data is still being sent to the host so handle this in the
        // EP0StateTx() function.
        //
        case eEP0StateSetupOUT:
        {
            //
            // Send remaining data if necessary.
            //
            USBHCDEP0StateTx();

            break;
        }

        //
        // Handle the receive state for commands that are receiving data on
        // endpoint 0.
        //
        case eEP0StateSetupIN:
        {
            //
            // Generate a new IN request to the device.
            //
            MAP_USBHostRequestIN(USB0_BASE, USB_EP_0);

            //
            // Proceed to the RX state to receive the requested data.
            //
            g_sUSBHEP0State.iState =  eEP0StateRx;

            break;
        }

        //
        // The endpoint remains in this state until all requested data has
        // been received.
        //
        case eEP0StateRx:
        {
            //
            // There was a stall on endpoint 0 so go back to the idle state
            // as this command has been terminated.
            //
            if(ui32EPStatus & USB_HOST_EP0_RX_STALL)
            {
                g_sUSBHEP0State.iState = eEP0StateIdle;

                //
                // Clear the stalled state on endpoint 0.
                //
                MAP_USBHostEndpointStatusClear(USB0_BASE, USB_EP_0,
                                           ui32EPStatus & USB_HOST_IN_STATUS);
                break;
            }

            //
            // Set the number of bytes to get out of this next packet.
            //
            ui32DataSize = g_sUSBHEP0State.ui32BytesRemaining;
            if(ui32DataSize > g_sUSBHEP0State.ui32MaxPacketSize)
            {
                //
                // Don't send more than EP0_MAX_PACKET_SIZE bytes.
                //
                ui32DataSize = MAX_PACKET_SIZE_EP0;
            }

            if(ui32DataSize != 0)
            {
                //
                // Get the data from the USB controller end point 0.
                //
                MAP_USBEndpointDataGet(USB0_BASE, USB_EP_0,
                                       g_sUSBHEP0State.pui8Data,
                                       &ui32DataSize);
            }

            //
            // Advance the pointer.
            //
            g_sUSBHEP0State.pui8Data += ui32DataSize;

            //
            // Decrement the number of bytes that are being waited on.
            //
            g_sUSBHEP0State.ui32BytesRemaining -= ui32DataSize;

            //
            // Need to ack the data on end point 0 in this case
            // without setting data end.
            //
            MAP_USBHostEndpointDataAck(USB0_BASE, USB_EP_0);

            //
            // If there was not more than the maximum packet size bytes of data
            // the this was a int16_t packet and indicates that this transfer
            // is complete.  If there were exactly
            // g_sUSBHEP0State.ui32MaxPacketSize remaining then there still
            // needs to be null packet sent before this transfer is complete.
            //
            if((ui32DataSize < g_sUSBHEP0State.ui32MaxPacketSize) ||
               (g_sUSBHEP0State.ui32BytesRemaining == 0))
            {
                //
                // Return to the idle state.
                //
                g_sUSBHEP0State.iState =  eEP0StateStatus;

                //
                // No more data.
                //
                g_sUSBHEP0State.pui8Data = 0;

                //
                // Send a null packet to acknowledge that all data was
                // received.
                //
                MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_STATUS);
            }
            else
            {
                //
                // Request more data.
                //
                MAP_USBHostRequestIN(USB0_BASE, USB_EP_0);
            }
            break;
        }

        //
        // The device stalled endpoint zero so check if the stall needs to be
        // cleared once it has been successfully sent.
        //
        case eEP0StateStall:
        {
            //
            // Reset the global end point 0 state to IDLE.
            //
            g_sUSBHEP0State.iState = eEP0StateIdle;

            break;
        }

        //
        // Halt on an unknown state, but only in DEBUG builds.
        //
        default:
        {
            ASSERT(0);
            break;
        }
    }
}

//*****************************************************************************
//
// This internal function handles sending data on endpoint 0.
//
// \return None.
//
//*****************************************************************************
static void
USBHCDEP0StateTx(void)
{
    uint32_t ui32NumBytes;
    uint8_t *pui8Data;

    //
    // In the TX state on endpoint 0.
    //
    g_sUSBHEP0State.iState = eEP0StateSetupOUT;

    //
    // Set the number of bytes to send this iteration.
    //
    ui32NumBytes = g_sUSBHEP0State.ui32BytesRemaining;

    //
    // Limit individual transfers to 64 bytes.
    //
    if(ui32NumBytes > 64)
    {
        ui32NumBytes = 64;
    }

    //
    // Save the pointer so that it can be passed to the USBEndpointDataPut()
    // function.
    //
    pui8Data = (uint8_t *)g_sUSBHEP0State.pui8Data;

    //
    // Advance the data pointer and counter to the next data to be sent.
    //
    g_sUSBHEP0State.ui32BytesRemaining -= ui32NumBytes;
    g_sUSBHEP0State.pui8Data += ui32NumBytes;

    //
    // Put the data in the correct FIFO.
    //
    MAP_USBEndpointDataPut(USB0_BASE, USB_EP_0, pui8Data, ui32NumBytes);

    //
    // If this is exactly 64 then don't set the last packet yet.
    //
    if(ui32NumBytes == 64)
    {
        //
        // There is more data to send or exactly 64 bytes were sent, this
        // means that there is either more data coming or a null packet needs
        // to be sent to complete the transaction.
        //
        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_OUT);
    }
    else
    {
        //
        // Send the last bit of data.
        //
        MAP_USBEndpointDataSend(USB0_BASE, USB_EP_0, USB_TRANS_OUT);

        //
        // Now go to the status state and wait for the transmit to complete.
        //
        g_sUSBHEP0State.iState = eEP0StateStatusIN;
    }
}

//*****************************************************************************
//
//! This function returns the USB hub port for the requested device instance.
//!
//! \param ui32Instance is a unique value indicating which device to query.
//!
//! This function returns the USB hub port for the device that is associated
//! with the \e ui32Instance parameter.  The caller must use the value for
//! \e ui32Instance was passed to the application when it receives a
//! \b USB_EVENT_CONNECTED event.  The function returns the USB hub port for
//! the interface number specified by the \e ui32Interface parameter.
//!
//! \return The USB hub port for the requested interface.
//
//*****************************************************************************
uint8_t
USBHCDDevHubPort(uint32_t ui32Instance)
{
    uint32_t ui32DevIndex;

    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);

    if(ui32DevIndex == 0xff)
    {
        return(ui32DevIndex);
    }

    return(g_sUSBHCD.psUSBDevice[ui32DevIndex].ui8HubPort);
}

//*****************************************************************************
//
//! This function will return the USB address for the requested device
//! instance.
//!
//! \param ui32Instance is a unique value indicating which device to query.
//!
//! This function returns the USB address for the device that is associated
//! with the \e ui32Instance parameter.  The caller must use a value for
//! \e ui32Instance have been passed to the application when it receives a
//! \b USB_EVENT_CONNECTED event.  The function will return the USB address for
//! the interface number specified by the \e ui32Interface parameter.
//!
//! \return The USB address for the requested interface.
//
//*****************************************************************************
uint8_t
USBHCDDevAddress(uint32_t ui32Instance)
{
    uint32_t ui32DevIndex;

    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);

    if(ui32DevIndex == 0xff)
    {
        return(ui32DevIndex);
    }

    return(g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Address);
}

//*****************************************************************************
//
//! This function will return the USB class for the requested device
//! instance.
//!
//! \param ui32Instance is a unique value indicating which device to query.
//! \param ui32Interface is the interface number to query for the USB class.
//!
//! This function returns the USB class for the device that is associated
//! with the \e ui32Instance parameter.  The caller must use a value for
//! \e ui32Instance have been passed to the application when it receives a
//! \b USB_EVENT_CONNECTED event.  The function will return the USB class for
//! the interface number specified by the \e ui32Interface parameter.  If
//! \e ui32Interface is set to 0xFFFFFFFF then the function will return the USB
//! class for the first interface that is found in the device's USB
//! descriptors.
//!
//! \return The USB class for the requested interface.
//
//*****************************************************************************
uint8_t
USBHCDDevClass(uint32_t ui32Instance, uint32_t ui32Interface)
{
    uint32_t ui32DevIndex;
    tInterfaceDescriptor *psInterface;

    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);

    //
    // If the instance was not valid return an undefined class.
    //
    if(ui32DevIndex == 0xff)
    {
        return(USB_CLASS_DEVICE);
    }

    //
    // Get the interface descriptor.
    //
    psInterface = USBDescGetInterface(
                        g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor,
                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Interface,
                        ui32Interface);

    //
    // Make sure that the interface requested actually exists.
    //
    if(psInterface)
    {
        //
        // Return the interface class.
        //
        return(psInterface->bInterfaceClass);
    }

    //
    // No valid interface so return an undefined class.
    //
    return(USB_CLASS_DEVICE);
}

//*****************************************************************************
//
//! This function will return the USB subclass for the requested device
//! instance.
//!
//! \param ui32Instance is a unique value indicating which device to query.
//! \param ui32Interface is the interface number to query for the USB subclass.
//!
//! This function returns the USB subclass for the device that is associated
//! with the \e ui32Instance parameter.  The caller must use a value for
//! \e ui32Instance have been passed to the application when it receives a
//! \b USB_EVENT_CONNECTED event.  The function will return the USB subclass
//! for the interface number specified by the \e ui32Interface parameter.  If
//! \e ui32Interface is set to 0xFFFFFFFF then the function will return the USB
//! subclass for the first interface that is found in the device's USB
//! descriptors.
//!
//! \return The USB subclass for the requested interface.
//
//*****************************************************************************
uint8_t
USBHCDDevSubClass(uint32_t ui32Instance, uint32_t ui32Interface)
{
    uint32_t ui32DevIndex;
    tInterfaceDescriptor *psInterface;

    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);

    //
    // If the instance was not valid return an undefined subclass.
    //
    if(ui32DevIndex == 0xff)
    {
        return(USB_SUBCLASS_UNDEFINED);
    }

    //
    // Get the interface descriptor.
    //
    psInterface = USBDescGetInterface(
                        g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor,
                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Interface,
                        ui32Interface);

    //
    // Make sure that the interface requested actually exists.
    //
    if(psInterface)
    {
        //
        // Return the interface subclass.
        //
        return(psInterface->bInterfaceSubClass);
    }

    //
    // No valid interface so return an undefined subclass.
    //
    return(USB_SUBCLASS_UNDEFINED);
}

//*****************************************************************************
//
//! This function returns the USB protocol for the requested device instance.
//!
//! \param ui32Instance is a unique value indicating which device to query.
//! \param ui32Interface is the interface number to query for the USB protocol.
//!
//! This function returns the USB protocol for the device that is associated
//! with the \e ui32Instance parameter.  The caller must use a value for
//! \e ui32Instance have been passed to the application when it receives a
//! \b USB_EVENT_CONNECTED event.  The function will return the USB protocol
//! for the interface number specified by the \e ui32Interface parameter.  If
//! \e ui32Interface is set to 0xFFFFFFFF then the function will return the USB
//! protocol for the first interface that is found in the device's USB
//! descriptors.
//!
//! \return The USB protocol for the requested interface.
//
//*****************************************************************************
uint8_t
USBHCDDevProtocol(uint32_t ui32Instance, uint32_t ui32Interface)
{
    uint32_t ui32DevIndex;
    tInterfaceDescriptor *psInterface;

    ui32DevIndex = HCDInstanceToDevIndex(ui32Instance);

    //
    // If the instance was not valid return an undefined protocol.
    //
    if(ui32DevIndex == 0xff)
    {
        return(USB_PROTOCOL_UNDEFINED);
    }

    //
    // Get the interface descriptor.
    //
    psInterface = USBDescGetInterface(
                        g_sUSBHCD.psUSBDevice[ui32DevIndex].psConfigDescriptor,
                        g_sUSBHCD.psUSBDevice[ui32DevIndex].ui32Interface,
                        ui32Interface);

    //
    // Make sure that the interface requested actually exists.
    //
    if(psInterface)
    {
        //
        // Return the interface protocol.
        //
        return(psInterface->bInterfaceProtocol);
    }

    //
    // No valid interface so return an undefined protocol.
    //
    return(USB_PROTOCOL_UNDEFINED);
}

//*****************************************************************************
//
//! This function sets one of the \b USBLIB_FEATURE_ requests.
//!
//! \param ui32Index is the index of the USB controller to access.
//! \param ui32Feature is one of the \b USBLIB_FEATURE_ defines.
//! \param pvFeature is a pointer to the data for the \b USBLIB_FEATURE
//!        request.
//!
//! This function sends the requested feature request to the USB library.
//! Not all features are supported by all devices so see the documentation
//! for the \b USBLIB_FEATURE_ to determine if the feature is supported.
//!
//! \return Returns \b true if the feature was set and \b false if the feature
//! is not supported or could not be changed to the requested value.
//
//*****************************************************************************
bool
USBHCDFeatureSet(uint32_t ui32Index, uint32_t ui32Feature,
                 void *pvFeature)
{
    bool bRetCode;
    tLPMFeature *psLPMFeature;

    bRetCode = true;

    switch(ui32Feature)
    {
        case USBLIB_FEATURE_CPUCLK:
        {
            //
            // Set the ticks per millisecond.
            //
            g_ui32Tickms = (*(uint32_t *)pvFeature / 3000);
            break;
        }
        case USBLIB_FEATURE_LPM:
        {
            psLPMFeature = (tLPMFeature *)pvFeature;

            if(psLPMFeature->ui32Features & USBLIB_FEATURE_LPM_EN)
            {
                g_sUSBHCD.ui32Features |= USBLIB_FEATURE_LPM_EN;

                if(psLPMFeature->ui32Features & USBLIB_FEATURE_LPM_RMT_WAKE)
                {
                    g_sUSBHCD.ui32Features |= USBLIB_FEATURE_LPM_RMT_WAKE;
                }
                g_sUSBHCD.ui32LPMHIRD = psLPMFeature->ui32HIRD;
            }
            else
            {
                psLPMFeature->ui32Features &= ~USBLIB_FEATURE_LPM_EN;
            }
            break;
        }
        case USBLIB_FEATURE_USBPLL:
        {
            //
            // If the PLL rate is not evenly divisible by 60MHz then
            // do not set it.
            //
            if((*(uint32_t *)pvFeature % 60000000) != 0)
            {
                bRetCode = false;
            }
            else
            {
                //
                // Save the new PLL rate.
                //
                g_ui32PLLDiv = (*(uint32_t *)pvFeature / 60000000);
            }
            break;
        }
        case USBLIB_FEATURE_USBULPI:
        {
            //
            // Save the ULPI support level.
            //
            g_ui32ULPISupport = *(uint32_t *)pvFeature;

            break;
        }
        default:
        {
            bRetCode = false;
            break;
        }
    }
    return(bRetCode);
}

//*****************************************************************************
//
//! This function returns the current status of an LPM request.
//!
//! \param psDevice is the device to query.
//!
//! This function returns the current status of LPM requests for a given
//! device.  This is called to determine if a previous request completed
//! successfully or if there was an error.
//!
//! \return This function returns the following values:
//! - \b USBHCD_LPM_AVAIL - There are no pending LPM requests on this specific
//!   device or the last request completed successfully.
//! - \b USBHCD_LPM_ERROR - The last LPM request for this device did not
//!   complete successfully.
//! - \b USBHCD_LPM_PENDING - The last LPM request has not completed.
//
//*****************************************************************************
uint32_t
USBHCDLPMStatus(tUSBHostDevice *psDevice)
{
    uint32_t ui32Ret;

    ASSERT(psDevice != 0);

    //
    // Should never have both USBHDEV_FLAG_LPMERROR and USBHDEV_FLAG_LPMPEND
    // set at the same time.
    //
    ASSERT((psDevice->ui32Flags &
            (USBHDEV_FLAG_LPMERROR | USBHDEV_FLAG_LPMPEND)) !=
           (USBHDEV_FLAG_LPMERROR | USBHDEV_FLAG_LPMPEND));

    //
    // Default to no pending transfers or errors.
    //
    ui32Ret = USBHCD_LPM_AVAIL;

    if(psDevice->ui32Flags & USBHDEV_FLAG_LPMERROR)
    {
        //
        // An error occurred after the last call to send an LPM command.
        //
        ui32Ret = USBHCD_LPM_ERROR;
    }
    else if(psDevice->ui32Flags & USBHDEV_FLAG_LPMPEND)
    {
        //
        // Still have a pending transfer.
        //
        ui32Ret = USBHCD_LPM_PENDING;
    }

    return(ui32Ret);
}

//*****************************************************************************
//
//! This function generates an LPM request for a device to enter L1 sleep
//! state.
//!
//! \param psDevice is the device to query.
//!
//! This function sends a request to a device to enter the LPM L1 sleep state.
//! The caller must check the return value to see if the request can be
//! attempted at this time.  If another LPM transaction is busy on another
//! device this function will return \b USBHCD_LPM_PENDING or
//! \b USBHCD_LPM_AVAIL if the LPM request was scheduled to be sent.  The
//! caller should check the USBHCDLPMStatus() function to determine if the
//! request has completed.
//!
//! \return This function returns the following values:
//! - USBHCD_LPM_AVAIL - The transition to L1 state is scheduled to be sent.
//! - USBHCD_LPM_PENDING - There is already an LPM request pending.
//
//*****************************************************************************
uint32_t
USBHCDLPMSleep(tUSBHostDevice *psDevice)
{
    uint32_t ui32Ret;

    ASSERT(psDevice != 0);

     //
     // Disable the USB interrupt.
     //
     OS_INT_DISABLE(g_sUSBHCD.ui32IntNum);

     //
     // If there is no current LPM pending then send the request.
     //
     if((g_sUSBHCD.ui32IntEvents & INT_EVENT_LPM_PEND) ||
        (psDevice->ui32Flags & USBHDEV_FLAG_LPMPEND))
     {
         ui32Ret = USBHCD_LPM_PENDING;
     }
     else
     {
         //
         // New pending LPM transfer at the host controller level.
         //
         g_sUSBHCD.ui32IntEvents |= INT_EVENT_LPM_PEND;

         //
         // New pending request and clear any previous error for this
         // device in case it was already set.
         //
         psDevice->ui32Flags |= USBHDEV_FLAG_LPMPEND;
         psDevice->ui32Flags &= ~USBHDEV_FLAG_LPMERROR;

         USBHostLPMSend(USB0_BASE, psDevice->ui32Address, USB_EP_0);

         ui32Ret = USBHCD_LPM_AVAIL;
     }

     //
     // Disable the USB interrupt.
     //
     OS_INT_ENABLE(g_sUSBHCD.ui32IntNum);

    return(ui32Ret);
}

//*****************************************************************************
//
//! This function generates an LPM request for a device to exit L1 sleep state.
//!
//! \param ui32Index specifies which USB controller to use.
//!
//! This function will start LPM resume signaling on the USB bus.  This wakes
//! all devices and is similar to USBHCDResume() call but is triggered by an
//! LPM request.
//!
//! \return None.
//
//*****************************************************************************
void
USBHCDLPMResume(uint32_t ui32Index)
{
    ASSERT(ui32Index == 0);

    USBHostLPMResume(USB0_BASE);
}

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************