summaryrefslogtreecommitdiff
path: root/Core/EM/usb/rt/usb.c
blob: b1baa4a1d3cee57848ab7e0ddbdd2014df286bd4 (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
#pragma warning(disable: 4001)
#pragma warning(disable: 4127)
//****************************************************************************
//****************************************************************************
//**                                                                        **
//**             (C)Copyright 1985-2016, American Megatrends, Inc.          **
//**                                                                        **
//**                          All Rights Reserved.                          **
//**                                                                        **
//**                 5555 Oakbrook Pkwy, Norcross, GA 30093                 **
//**                                                                        **
//**                          Phone (770)-246-8600                          **
//**                                                                        **
//****************************************************************************
//****************************************************************************

//****************************************************************************
// $Header: /Alaska/SOURCE/Modules/USB/ALASKA/RT/usb.c 183   10/21/16 1:48a Wilsonlee $
//
// $Revision: 183 $
//
// $Date: 10/21/16 1:48a $
//****************************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Modules/USB/ALASKA/RT/usb.c $
// 
// 183   10/21/16 1:48a Wilsonlee
// Fixed Cppcheck error.
// 
// 182   10/16/16 10:12p Wilsonlee
// [TAG]  		EIP288158
// [Category]  	Improvement
// [Description]  	Check if gUsbData is integrity.
// [Files]  		amiusb.cif, usbsb.c, AmiUsbLib.cif, AmiUsbLib.sdl,
// AmiUsbSmmGlobalDataValidationLib.c,
// AmiUsbSmmGlobalDataValidationLib.cif,
// AmiUsbSmmGlobalDataValidationLib.mak, Crc32.c, amiusb.c, amiusb.h,
// ehci.c, elib.c, ohci.c, syskbc.c, uhci.c, usb.c, usbCCID.c, usbdef.h,
// usbhid.c, usbhub.c, usbkbd.c, usbmass.c, usbms.c, usbrt.mak, xhci.c,
// amiusbhc.c, efiusbccid.c, efiusbmass.c, uhcd.c, usbmisc.c,
// AmiUsbController.h, AmiUsbLibInclude.cif,
// AmiUsbSmmGlobalDataValidationLib.h
// 
// 181   7/28/16 4:56a Wilsonlee
// [TAG]  		EIP264662
// [Category]  	Improvement
// [Description]  	Don't install usb hw smi after reconnecting usb
// controllers.
// [Files]  		uhcd.c, usb.c, ohci.c, amiusb.c, amiusbhc.c
// 
// 180   3/02/16 9:41p Wilsonlee
// [TAG]  		EIP254309
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	GK-FORCE K83 USB KB function abnormal.
// [RootCause]  	This device has an interrupt out endpoint and doesn't
// support "Set Report" request.
// [Solution]  	Use the interrupt out endpoint instead of sending "Set
// Report" request.
// [Files]  		AmiUsbController.h, xhci.c, usbmass.c, usbkbd.h, usbkbd.c,
// usbhub.c, usbhid.c, usbdef.h, usbCCID.c, usb.c, uhci.c, ohci.c, ehci.c,
// amiusb.h, efiusbms,c, amiusbhc.c
// 
// 179   11/04/15 9:51p Wilsonlee
// [TAG]  		EIP241067
// [Category]  	Improvement
// [Description]  	Add the device descriptor to the DEV_INFO structure.
// [Files]  		usb.c, usbdef.h, xhci.c, usbbus.c, AmiUsbController.h
// 
// 178   9/01/15 10:17p Wilsonlee
// [TAG]  		EIP235482
// [Category]  	Improvement
// [Description]  	Select this alternate setting for multiple TTs hubs.
// [Files]  		usbhub.c, usb.c, amiusb.h, usbdef.h
// 
// 177   7/24/15 3:30a Wilsonlee
// [TAG]  		EIP229294
// [Category]  	Improvement
// [Description]  	If the device descriptor returns with a value in its
// length field that is greater 18, it is valid and we should ignore the
// extra bytes.
// [Files]  		usb.c
// 
// 176   5/28/15 4:29a Wilsonlee
// [TAG]  		EIP219785
// [Category]  	Improvement
// [Description]  	Suspend usb devices which are connected to Hubs.
// [Files]  		usb.c, usbdef.h
// 
// 175   4/29/15 11:26p Wilsonlee
// [TAG]  		EIP215031
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Transcend USB 3.0 HDD is disappeared in the setup menu by
// cold boot.
// [RootCause]  	We only can get SerialNumber string descriptor before
// setting configuration for this device, otherwise it is failed at
// getting this descriptor and inquiry command is also failed.
// [Solution]  	Retry inquiry command.
// [Files]  		usb.c, usbmass.c, efiusbmass.c, usbbus.c, usbdef.h
// 
// 174   4/27/15 2:25a Wilsonlee
// [TAG]  		EIP211855
// [Category]  	Improvement
// [Description]  	Set the default interface if the device has alternate
// setting for the interface.
// [Files]  		usb.c, usbdef.h
// 
// 173   4/07/15 4:03a Wilsonlee
// [TAG]  		EIP211598
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Keyboard/Mouse sometimes cannot work when connected to USB
// 3.0 HUB.
// [RootCause]  	It's failed at setting device address.
// [Solution]  	Wait 10 ms for stable before we set device address.
// [Files]  		usb.c
// 
// 172   3/08/15 10:49p Wilsonlee
// [TAG]  		EIP207774
// [Category]  	Improvement
// [Description]  	Set USB_FLAG_DRIVER_STARTED flag when HC is running and
// clear it if we don't start any HC.
// [Files]  		uhci.c, usb.c, ehci.c, ohci.c, xhci.c, amiusb.h
// 
// 171   2/16/15 2:44a Wilsonlee
// [TAG]  		EIP205373
// [Category]  	Improvement
// [Description]  	Cppcheck errors in Usb module.
// [Files]  		usb.c, usbport.c, uhcd.c, usbCCID.c
// 
// 170   1/22/15 10:19p Wilsonlee
// [TAG]  		EIP201434
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Number of connected devices isn't correct if we plug out
// keyboards or mice behind hub in xhci.
// [RootCause]  	The PortConnectChange bit is cleared when we check port
// status for interrupt endpoint transaction error.
// [Solution]  	Don't clear change bits if we check port status for
// interrupt endpoint transaction error.
// [Files]  		xhci.c, usbhub.c, usbdef.h, usb.c, uhci.c, ohci.c, ehci.c,
// amiusbhc.c
// 
// 169   12/15/14 2:16a Wilsonlee
// [TAG]  		EIP194720
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	System shutdown delay when connect with cardreader.
// [RootCause]  	When we reenumerate devices, we still reserve the
// original device info, then we will use the wrong info to send command
// and the device may not respond.
// [Solution]  	Remove the present flag of devices before we reenumerate.
// [Files]  		usb.c
// 
// 168   11/23/14 10:09p Wilsonlee
// [TAG]  		EIP189293
// [Category]  	Improvement
// [Description]  	Implement XHCI key repeat function.
// [Files]  		usb.c, xhci.c , xhci.h, amiusb.c
// 
// 167   9/29/14 11:35p Wilsonlee
// [TAG]  		EIP181169
// [Category]  	Improvement
// [Description]  	Support XHCI 1.1/USB 3.1.
// [Files]  		xhci.c, xhci.h, usb.c, usbbus.c, usbdef.h, UsbHc.h
// 
// 166   9/02/14 3:53a Wilsonlee
// [TAG]  		EIP182567
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	POST B4h sometimes stays about 30 sec if using special
// KB/Ms.
// [RootCause]  	t's timeout in getting config or report descriptor
// commands.
// [Solution]  	Set the timeout to 500 ms.
// [Files]  		usb.c, usbhid.c, usbdef.h
// 
// 165   7/30/14 5:17a Wilsonlee
// [TAG]  		EIP176293
// [Category]  	Improvement
// [Description]  	The changes are for DisplayLink USB Network driver.
// [Files]  		usbbus.c, usb.c
// 
// 164   7/28/14 7:39a Wilsonlee
// [TAG]  		EIP176070
// [Category]  	Improvement
// [Description]  	Add 100 microseconds before we send get configuration
// descriptor command if the device is full speed.
// [Files]  		usb.c
// 
// 163   6/26/14 1:16a Wilsonlee
// [TAG]  		EIP173387
// [Category]  	Improvement
// [Description]  	Remove TODO comments.
// [Files]  		usbsetup.c, xhci.c, usbmass.c, usbCCID.c, usb.c, uhci.c,
// syskbc.c, usbport.c, usbbus.c, uhcd.c, UsbBotPeim.c, PeiXhci.c,
// PeiEhci.c
// 
// 162   6/20/14 2:11a Wilsonlee
// [TAG]  		EIP174589
// [Category]  	Improvement
// [Description]  	Fix build error if USB_HID_KEYREPEAT_USE_SETIDLE is 1.
// [Files]  		usb.c
// 
// 161   5/12/14 4:29a Wilsonlee
// [TAG]  		EIP168515
// [Category]  	New Feature
// [Description]  	Add the token "USB_CONTROLLERS_INITIAL_DELAY_LIST" if
// usb controllers need to delay for stabilization.
// [Files]  		usb.sdl, usb.c
// 
// 160   4/30/14 5:25a Wilsonlee
// [TAG]  		EIP164842
// [Category]  	Improvement
// [Description]  	Check if the devices have put into to our queue before
// we put them.
// [Files]  		UsbInt13.c, amiusb.c, ehci.c, ohci.c, usb.c, usbdef.h,
// usbmass.c, xhci.c, amiusbhc.c, efiusbmass.c, uhcd.c, usbbus.c, usbsb.c
// 
// 159   4/29/14 8:30p Wilsonlee
// [TAG]  		EIP164772
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	System would auto wake up if USB hot-plug in S5 state via
// USB hub.
// [RootCause]  	The usb hubs have connnect / disconnect wakeup function
// if we send remote wakeup command
// [Solution]  	Don't send remote wakeup command to the usb hubs.
// [Files]  		usb.c
// 
// 158   2/26/14 1:55a Wilsonlee
// [TAG]  		EIP149854
// [Category]  	Improvement
// [Description]  	Add data length parameter to polling callback function.
// [Files]  		usbkbd.c, uhci.c, usb.c, usbhub.c, usbCCID.c, usbms.c,
// usbhid.c, usbpoint.c, usbkbd.h, ehci.c, ohci.c, xhci.c, usbdef.h
// 
// 157   11/26/13 1:23a Wilsonlee
// [TAG]  		EIP143251
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	The usb mouse lost if it behinds TI TUSB8040A1 hub under
// BIOS.
// [RootCause]  	The device may connect later, then we clear connect
// change without setting the device is connected.
// [Solution]  	Don't get port status again before we clear the changes.
// [Files]  		usb.c, usbhub.c
// 
// 156   11/04/13 3:26a Wilsonlee
// [TAG]  		EIP139714
// [Category]  	Improvement
// [Description]  	Improve the UsbIoPortReset function to support the xhci
// controller.
// [Files]  		usb.c
// 
// 155   9/04/13 5:46a Wilsonlee
// [TAG]  		EIP134478
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	The devices which behind the hub don't install successfully
// in shell.
// [RootCause]  	Find the wrong root hub port.
// [Solution]  	Check DEV_INFO_VALID_STRUC and DEV_INFO_DEV_PRESENT flag
// to find the root hub port.
// [Files]  		usb.c, xhci.c, usbbus.c
// 
// 154   8/16/13 4:17a Ryanchou
// 
// 153   8/02/13 6:16a Ryanchou
// 
// 152   7/29/13 5:19a Roberthsu
// [TAG]           EIP126741
// [Category]      Bug Fix
// [Severity]      Normal
// [Symptom]       Cannot boot to uefi usb device with Sophos software.
// [RootCause]     When boot into tool. Ownership to os event occur.Usb
// will disconnect device.And record this disconnect event. Then ownership
// to bios,bios will connect all device.Run legacy to efi function. Bios
// run disconnect event first.Then reconnect device.Because usb key behind
// hub. So usb key disconnect also.
// [Solution]      Check device when device reconnect.If device and port
// number the same.Use the same device info.
// [Files]         usb.c,usbmass.c,efiusbmass.c,uhcd.c
// 
// 151   7/22/13 10:31p Wilsonlee
// [TAG]  		EIP125357
// [Category]  	Improvement
// [Description]  	Check if the port releases to a select host controller.
// [Files]  		uhci.c, usb.c, usbhub.c, ehci.c, ohci.c, xhci.c, usbdef.h
// 
// 150   7/17/13 4:14a Roberthsu
// [TAG]           EIP126319
// [Category]      Bug Fix
// [Severity]      Important
// [Symptom]       TEAC floppy can not detect when cold boot.
// [RootCause]     Device need more delay after get config descriptor.
// [Solution]      Add delay to 1ms.
// [Files]         usb.c
// 
// 149   6/26/13 3:36a Roberthsu
// [TAG]           EIP125792
// [Category]      Bug Fix
// [Severity:]     Normal
// [Symptom:]      Keep function not work
// [Root Cause]    When check port change. We can not get baseclass.
// [Solution]      Add Vaild base class flag.
// [Files]         UsbPort.c,Usb.c
// 
// 148   5/01/13 9:54p Wilsonlee
// [TAG]  		EIP121643
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Cannot detect the usb floppy.
// [RootCause]  	This device doesn't return data when we sned
// get-config-descriptor command.
// [Solution]  	We retry to send get-config-descriptor command if there is
// no data.
// [Files]  		usb.c, ehci.c
// 
// 147   4/19/13 12:44a Wilsonlee
// Fix build error if token USB_S5_WAKEUP_SUPPORT is enabled.
// 
// 146   4/18/13 11:22a Ryanchou
// Fix build error if token x64_BUILD is 0.
// 
// 145   3/19/13 3:58a Ryanchou
// [TAG]  		EIP118177
// [Category]  	Improvement
// [Description]  	Dynamically allocate HCStrucTable at runtime.
// [Files]  		usb.sdl, usbport.c, usbsb.c, amiusb.c, ehci.c, ohci.c,
// syskbc.c, sysnokbc.c, uhci.c, usb.c, usbCCID.c, usbdef.h, usbhid.c,
// usbhub.c, usbmass.c, usbrt.mak, usb.sd, amiusbhc.c, efiusbccid.c,
// efiusbhid.c, efiusbmass.c, efiusbms.c, uhcd.c, uhcd.h, uhcd.mak,
// usbmisc.c, usbsrc.sdl
// 
// 144   3/15/13 5:57a Ryanchou
// 
// 143   3/15/13 4:59a Ryanchou
// [TAG]  		EIP117211
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	USB Memory Allocation Failure for Sizes Above 4k
// [RootCause]  	The variable count will be reset when across a page
// boundary.
// [Solution]  	Only reset the variable Count if the allocated blocks less
// than a page.
// [Files]  		usb.c
// 
// 142   3/07/13 9:25p Wilsonlee
// [TAG]  		EIP116044
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	TEAC FDD is not recognized after hot plugging under DOS.
// [RootCause]  	Setting the device configuration is failed.
// [Solution]  	This device configure successfully by that we set the
// device address after sending the first get-device-descriptor command.
// [Files]  		usb.c
// 
// 141   3/07/13 8:52a Ryanchou
// [TAG]  		EIP113218
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	USB keyboard cannot work after ownership change back to
// BIOS
// [RootCause]  	The key repeat SMI does not generated because the HC is
// stopped.
// [Solution]  	Use the other HC to generate key repeat SMI
// [Files]  		usb.c, usbhid.c, usbkbd.c
// 
// 140   1/23/13 8:33p Wilsonlee
// [TAG]  		EIP108891
// [Category]  	Improvement
// [Description]  	For usb wakp up function, we need to add some delay to
// wait the usb devces connect.
// [Files]  		usb.c
// 
// 139   1/22/13 2:38a Wilsonlee
// [TAG]  		EIP110305
// [Category]  	Improvement
// [Description]  	Set the device address after we send the first
// get-device-descriptor command.
// [Files]  		usbmass.c, usb.c, usbdef.h, usbbus.c, efiusbmass.c, uhcd.c,
// usbport.c
// 
// 138   1/11/13 4:15a Ryanchou
// [TAG]  		EIP102491
// [Category]  	Improvement
// [Description]  	Synchronized with Aptio V USB module
// [Files]  		usbport.c, usbsb.c, ehci.c, ehci.h, ohci.c, ohci.h, uhci.h,
// usb.c, usbdef.h, usbhid.c, usbhub.c, usbkbd.c, usbkbd.h, usbmass.c.
// usbms.c, usbpoint.c, xhci.h, usb.sd, amiusbhc.c, componentname.c,
// efiusbkc.c, efiusbmass.c, uhcd.c, uhcd.h, usbbus.c, usbbus.h, usbmisc.c
// 
// 137   12/05/12 4:23a Roberthsu
// [TAG]           EIP96616
// [Category]      Bug Fix
// [Severity]      Normal
// [Symptom]       When Legacy to EFI, USB KB can't be used.
// [RootCause]     Usb device driver content incorrect driver entry.Legacy
// insert a devicet,when legacy to efi,device does not install efi driver.
// [Solution]      When legacy to efi, scan device info table and put it
// to smiqueue.
// [Files]         usb.sdl,uhcd.c,usb.c
// 
// 136   11/29/12 7:47a Ryanchou
// [TAG]  		EIP107586 
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Unplug USB keyboard does not uninstall EFI USB keyboard
// driver properly
// [RootCause]  	The EIP99431 changes clear DEV_INFO.bSubDeviceType in
// runtime keyboard driver, that cause EFI keyboard driver does not know
// what type of the device is.
// [Solution]  	Do not clear DEV_INFO.bSubDeviceType  in runtime keyboard
// driver.
// [Files]  		usb.c, usbhid.c, efiusbhid.c
// 
// 135   11/22/12 9:20p Wilsonlee
// [TAG]  		EIP106887
// [Category]  	New Feature
// [Description]  	Support usb S5 wake up function for UHCI.
// [Files]  		usb.c, uhci.c, uhci.h
// 
// 134   11/13/12 7:11a Wilsonlee
// [TAG]  		EIP82553
// [Category]  	New Feature
// [Description]  	Support usb S5 wake up function for XHCI.
// [Files]  		usb.c, ehci.c, ohci.c, xhci.c, xhci.h
// 
// 133   11/10/12 6:39a Ryanchou
// [TAG]  		EIP99431
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Cannot use the UsbIo's UsbAsyncInterruptTransfer for
// keyboard input
// [RootCause]  	Stopping EFI USB keyboard driver does not stop the
// endpoint polling, then application calls UsbAsyncInterruptTransfer,
// error will be returned.
// [Solution]  	Stops endpoint polling and release resource when
// disconnecting the device driver. And improve the
// UsbSyncInterruptTransfer.
// [Files]  		amiusb.c, amiusb.h, ehci.c, ohci.c, uhci.c, usb.c,
// usbCCID.c, usbdef.h, usbhub.c, usbkbd.c, usbmass.c, usbms.c,
// usbpoint.c, amiusbhc.c, efiusbhid.c, usbbus.c, usbbus.h
// 
// 132   10/25/12 4:14a Wilsonlee
// [TAG]  		EIP82354
// [Category]  	New Feature
// [Description]  	Support usb S5 wake up function for OHCI.
// [Files]  		usb.c, ehci.c, ohci.c
// 
// 131   9/28/12 2:38a Wilsonlee
// [TAG]  		EIP93154
// [Category]  	Improvement
// [Description]  	Change the unit of the FixedDelay from 15 us to 1 us.
// [Files]  		amiusb.h, xhci.c, ehci.c, ohci.c, uhci.c, usb.c, usbCCID.c,
// usbmass.c, usbhub.c, elib.c
// 
// 130   9/03/12 4:55a Roberthsu
// [TAG]           EIP98145
// [Category]      Improvement
// [Description]   Add skip function message.
// [Files]         usb.c,usbsrc.sdl
// 
// 129   8/29/12 9:32a Ryanchou
// [TAG]  		EIP88307
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Key repeat cannot be stopped if the keyboard is connected
// to xHCI.
// [RootCause]  	Periodic timer SMI stop generating when USB SMI and
// periodic timer SMI is generated frequently.
// [Solution]  	Reduces the key repeat rate to avoid this issue.
// [Files]  		ehci.c, usb.c, usb.sdl
// 
// 128   8/29/12 8:18a Ryanchou
// [TAG]  		EIP77262
// [Category]  	New Feature
// [Description]  	Remove SMM dependency of USB.
// [Files]  		usb.sdl, usbport.c, amiusb.c, amiusb.dxs, amiusb.h, ehci.c,
// elib.c, ohci.c, uhci.c, usb.c, usbdef.h, usbrt.mak, xhci.c, amiusbhc.c,
// efiusbccid.c, efiusbhid.c, efiusbkb.c, efiusbmass.c, uhcd.c, uhcd.dxs,
// uhcd.h, usbmisc.c, AmiUsbController.h
// 
// 127   8/22/12 4:59a Wilsonlee
// [TAG]  		EIP98230
// [Category]  	Improvement
// [Description]  	Set the default of the MaxPacket for endpoint 0 by the
// device speed.
// [Files]  		usb.c
// 
// 126   6/13/12 2:39a Roberthsu
// [TAG]       EIP90124
// [Category]  Bug Fix
// [Severity]  Normal
// [Symptom]   Insert barcode when pxe option rom running.Barcode will not
// work under dos.
// [RootCause] Because pxe option under legacy mode.Back to efi mode
// barcode after reinit will fail under dos.
// [Solution]  In function USB_ReConfigDevice check device initial done.
// [Files]     usb.c
// 
// 125   5/22/12 10:04a Ryanchou
// [TAG]  		EIP90154
// [Category]  	Improvement
// [Description]  	Remove the USBSB_EnableSmmPeriodicSmi and
// USBSB_DisableSmmPeriodicSmi hooks.
// [Files]  		amidef.h, amiusb.c, usb.c, usbsb.c
// 
// 124   5/22/12 4:48a Wilsonlee
// [TAG]  		EIP89641
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	USB Keyboard driver overwrites INT0 vector (address 0:0)
// [RootCause]  	The Queue Head cross the page boundary.
// [Solution]  	Added page alignment restriction into memory allocation
// routine.
// [Files]  		usb.c
// 
// 123   5/04/12 6:40a Ryanchou
// [TAG]  		EIP82875
// [Category]  	Improvement
// [Description]  	Support start/stop individual USB host to avoid
// reconnect issues.
// [Files]  		usbport.c, usbsb.c, amiusb.c, amiusb.h, ehci.c, ohci.c,
// uhci.c, uhci.h, usb.c, usbdef.h, xhci.c, amiusbhc.c, uhcd.c, uhcd.h,
// usbbus.c, usbmisc.c
// 
// 122   5/04/12 5:27a Wilsonlee
// [TAG]  		EIP89307
// [Category]  	Improvement
// [Description]  	Modify incorrect #pragma pack directive.
// [Files]  		amidef.h, amiusb.c, ehci.h, ohci.c, ohci.h, uhci.h, usb.c,
// usbdef.h, xhci.h, efiusbmass.c, uhcd.c, uhcd.h, usbbus.c, usbbus.h,
// UsbIo.h
// 
// 121   4/24/12 3:36a Wilsonlee
// [TAG]  		EIP81761
// [Category]  	Improvement
// [Description]  	Determine the limit of devices after checking whether
// this device is reconnected.
// [Files]  		usb.c
// 
// 120   2/16/12 8:53p Wilsonlee
// [TAG]  		EIP81612
// [Category]  	Spec Update
// [Severity]  	Minor
// [Description]  	Add EFI_USB_SPEED_SUPER in EFI_USB2_HC_PROTOCOL
// according to UEFI 2.3.1 spec
// [Files]  		usb.c, usbbus.c, amiusbhc.c
// 
// 119   1/13/12 4:24a Ryanchou
// [TAG]  		EIP47348
// [Category]  	New Feature
// [Description]  	Support for USB Port Reset function.
// [Files]  		amiusb.c, amiusb.h, amiusbhc.c, uhci.c, usb.c, usbbus.c,
// usbbus.h, usbmass.c
// 
// 118   1/04/12 6:23a Ryanchou
// 
// 117   1/04/12 6:22a Ryanchou
// [TAG]  		EIP78861
// [Category]  	Improvement
// [Description]  	Some device will be disconnected after port
// reset, and reconnected for a while, added 100 ms delay in this case.
// [Files]  		usb.c
// 
// 116   12/26/11 2:24a Roberthsu
// [TAG]           EIP74609
// [Category]      Improvement
// [Description]   Add check oemskiplist at check port change.
// [Files]         usbport.c,usb.c,AmiUsbController.h
// 
// 115   12/08/11 1:46a Ryanchou
// [TAG]  		EIP75441
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	System hangs at 0xB4 after restart from Win7
// [RootCause]  	The device does not use standard BOT protocol under
// Windows.
// [Solution]  	Add the device into bad device table.
// [Files]  		usb.c usbport.c
// 
// 114   11/28/11 8:36p Wilsonlee
// [TAG]  		EIP73803
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	The mouse can't work under setup after hot-plug.
// [RootCause]  	The device may fail at the get device descriptor or set
// device configuration.
// [Solution]  	Add 10 msec delay before getting device descriptor if the
// device is low or full speed and add 2 msec delay after setting the
// device's address.
// [Files]  		usb.c
// 
// 113   11/08/11 8:21a Wilsonlee
// [TAG]  		EIP74876
// [Category]  	New Feature
// [Description]  	Add USB API for shutdown single USB controller.
// [Files]  		amiusb.c, amiusb.h, usb.c, usbdef.h, uhcd.c, uhcd.h,
// AmiUsbController.h
// 
// 112   11/05/11 7:36a Wilsonlee
// [TAG]  		EIP64781
// [Category]  	New Feature
// [Description]  	Added SDL token
// SKIP_CARD_READER_CONNECT_BEEP_IF_NO_MEDIA that skip the connect beep if
// no media present in USB card reader.
// [Files]  		usbport.c, usbmass.c, usb.c, usbdef.h, uhcd.c, usbsrc.sdl
// 
// 111   10/25/11 8:23a Wilsonlee
// [TAG]  		EIP71750
// [Category]  	New Feature
// [Description]  	Support extraUSB device driver hook by elink.
// 
// 110   10/25/11 3:51a Ryanchou
// [TAG]  		EIP70933
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	System hangs at checkpoint 0x98 when webcam plugged
// [RootCause]  	The webcam return invalid data in configuration
// descriptor.
// [Solution]  	Get the configuration descriptor twice, the first time is
// to receive the returned configure descriptor to get the total length
// and the second time is to feed the length to the function again.
// [Files]  		usb.c, usbdef.h
// 
// 109   8/08/11 6:59a Ryanchou
// [TAG]  		EIP54018
// [Category]  	New Feature
// [Description]  	Added USB S5 wake up support.
// [Files]  		amiusb.c, ehci.c, ohci.c, uhci.c, usb.c, usb.sdl, usbdef.h,
// usbsb.c xhci.c
// 
// 108   8/08/11 5:17a Ryanchou
// [TAG]  		EIP60561
// [Category]  	New Feature
// [Description]  	Add USB timing policy protocol for timing override.
// [Files]  		ehci.c, guids.c, ohci.c, uhcd.c, uhci.c usb.c, usbdef.h,
// usbhub.c, usbmass.c, UsbPolicy.h, usbport.c usbsrc.sdl
// 
// 107   8/05/11 6:18a Ryanchou
// [TAG]  		EIP60706
// [Category]  	Improvement
// [Description]  	Move gUsbBadDeviceTable into SMRAM.
// [Files]  		usbport.c, amiusb.c, usb.c, uhcd.c, AmiUsbController.h
// 
// 106   7/22/11 5:37a Ryanchou
// [TAG]  		EIP65385
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	USB mouse can not be detected.
// [RootCause]  	The device is connected in disconnect progress, port
// reset is not issued.
// [Solution]  	Remove the code that check device connection in disconnect
// progress.
// [Files]  		usb.c
// 
// 105   7/19/11 5:17a Ryanchou
// [TAG]  		EIP64498
// [Category]  	New Feature
// [Description]  	Implement EHCI key repeat function.
// [Files]  		ehci.c, ehci.h, usb.c, usbdef.h
// 
// 104   7/15/11 6:11a Ryanchou
// [TAG]  		EIP38434
// [Category]  	New Feature
// [Description]  	Added USB HID report protocol support.
// [Files]  		amiusb.c, AmiUsbController.h, amiusbhc.c, efiusbkb.c,
// efiusbkb.h, ehci.c, ohci.c, uhcd.c uhcd.cif, uhci.c, usb.c, usbdef.h,
// usbkbd.c, usbkbd.h, usbms.c, usbrt.cif, usbsb.c, usbsetup.c,
// usbsrc.sdl, xhci.c
// 
// 103   7/13/11 2:47a Ryanchou
// [TAG]  		EIP60460
// [Category]  	Improvement
// [Description]  	Adds a flag when device disconnected during data
// transfer, BIOS will not issue a transfer to the devicce if this flag is
// set. This change is for Fresco USB 3.0 controller.
// [Files]  		usb.c, usbdef.h, xhci.c, xhci.h
// 
// 102   7/12/11 8:09a Ryanchou
// [TAG]  		EIP56918
// [Category]  	New Feature
// [Description]  	Added CCID device support.
// [Files]  		amiusb.c, amiusb.h, amiusbrtCCID.h, ehci.c, ohci.c, uhci.c,
// usb.c, UsbCCID.c, usbdef.h, usbrt.cif, usbsetup.c, efiusbccid.c,
// framework.cif, uhcd.c, uhcd.cif, uhcd.h, usbsrc.sdl, AmiusbCCID.h,
// AmiUsbController.h, AmiUSBProtocols.cif
// 
// 101   6/22/11 9:36a Ryanchou
// [TAG]  		EIP60640
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Logitec USB keyboard has no function in DOS.
// [RootCause]  	The USB keybaord may stall get configuration descriptor
// request or set address request.
// [Solution]  	Retry five times when the device stalls these request.
// [Files]  		usb.c, usbbus.c
// 
// 100   6/22/11 1:44a Ryanchou
// [TAG]  		EIP59738
// [Category]  	Improvement
// [Description]  	Support Block size other than 512 bytes USB HDD in UEFI
// mode.
// [Files]  		efiusbmass.c, uhci.c, usb.c, usbdef.h, usbmass.c
// 
// 99    6/21/11 9:33a Ryanchou
// [TAG]  		EIP59601
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	USB devices can't be detected if webcam is connected. 
// [RootCause]  	The configuration descriptor length is greater than
// buffer length, the causes the last descriptor is invalid.
// [Solution]  	If the next descriptor cross the buffer boundary, skip the
// descriptor.
// [Files]  		usb.c
// 
// 98    4/06/11 5:27a Tonylo
// [TAG]  		EIP52339
// [Category]  	New Feature
// [Description]  	USB changes of USB host safe disabling solution.
// 
// 97    4/06/11 1:33a Ryanchou
// [TAG]  		EIP54782
// [Category]  	Improvement
// [Description]  	Change polling data size of HID devices to max packet
// size of interrupt endpoint.
// [Files]  		ehci.c, ohci.c, uhci.c, usb.c, usbdef.h, xhci.c
// 
// 96    4/06/11 12:49a Ryanchou
// [TAG]  		EIP51653
// [Category]  	New Feature
// [Description]  	Added an interface that skips specific port
// enumeration.
// [Files]  		AmiUsbController.h, uhcd.c, uhcd.h, usb.c, usbdef.h,
// usbport.c
// 
// 95    3/30/11 8:13a Ryanchou
// [TAG]  		EIP54126
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Sometimes system hangs at checkpoint 0xB4.
// [RootCause]  	The bLength field of configuration descriptor is zero.
// [Solution]  	Check wether bLength field is zero before paring next
// descriptor.
// [Files]  		usb.c, usbbus.c, usbhub.c, usbkbd.c, usbmass.c, usbms.c
// 
// 94    3/29/11 10:52p Ryanchou
// [TAG]  		EIP55401
// [Category]  	Improvement
// [Description]  	Improve the USB 3.0 device compatibility.
// [Files]  		ehci.c, ehci.h, ohci.c, uhci.c, usb.c, usbdef.h, usbhub.c,
// xhci.c
// 
// 93    3/29/11 10:08a Ryanchou
// [TAG]  		EIP53518
// [Category]  	Improvement
// [Description]  	Added chipset xHCI chip support.
// [Files]  		amiusb.c, amiusb.h, ehci.c, ohci.c, uhcd.c, uhci.c, usb.c,
// usb.sdl, usbdef.h, usbport, usbsb.c, xhci.c
// 
// 92    1/17/11 3:51a Ryanchou
// [TAG]  		EIP50361
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	Hot plug USB 3.0 flash drive in setup will cause system
// hang.
// [RootCause]  	The memory may be destroyed if the Address Device command
// fails.
// [Solution]  	Check the memory has been allocated when free the memory.
// [Files]  		usb.c xhci.c xhci.h
// 
// 91    11/11/10 11:36p Ryanchou
// [TAG]  		EIP45578
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	USB 3.0 device can't be detected.
// [RootCause]  	Address Device Command fails.
// [Solution]  	Reset the device and attempt the Address Device Command
// again.
// [Files]  		ehci.c, ohci.c, uhci.c, usb.c, usbdef.h, usbhub.c, xhci.c
// 
// 90    10/28/10 12:34a Ryanchou
// EIP46865: Comment out unnecessary ASSERT macro.
// 
// 89    10/28/10 12:24a Ryanchou
// EIP45643: Fixed system hangs when hot plug USB mass storage quickly on
// USB 3.0 port.
// 
// 88    10/21/10 10:12a Ryanchou
// EIP45121: Added xHCI Supported Protocol Capability and fix the problem
// that USB 3.0 device can't be detected.
// 
// 87    10/20/10 10:24a Ryanchou
// EIP44702: Added USB 3.0 hub support.
// 
// 86    10/20/10 12:55a Ryanchou
// EIP45828: If the flag DEV_INFO_MASS_DEV_REGD is set, check if the
// controller type is difference between old DevInfo and new one.
// 
// 85    9/16/10 9:22a Ryanchou
// EIP44149: Disable slot if the Address Device command was unsuccessful. 
// 
// 84    9/07/10 4:12a Tonylo
// Remove user tags for coding standard.
// 
// 83    8/18/10 4:23p Olegi
// Klockwork related fixes; EIP37978
// 
// 82    8/13/10 4:10p Olegi
// Bugfix in CheckDeviceLimit function. EIP41442
// 
// 81    7/15/10 4:39a Tonylo
// EIP15489 - Add USB HandOff function for shurdown/init USB legacy
// through USB API function.
// 
// 80    7/13/10 5:09a Ryanchou
// EIP39838: Fixed configure USB hub fail.
// 
// 79    7/02/10 1:59a Ryanchou
// Update DevMiscInfo field when hot plug USB mass storage.
// 
// 78    6/22/10 9:29a Ryanchou
// EIP39374: Fixed USB mass storage hot plug issue.
// 
// 77    6/11/10 1:43a Ryanchou
// EIP36720: Fixed USB keyboard hot plug in setup issue.
// 
// 76    5/11/10 11:02a Olegi
// Bugfix in USB_InitDeviceDataDummy; EIP37974
// 
// 75    3/19/10 10:05a Olegi
// 
// 74    3/11/10 9:42a Olegi
// 
// 73    3/10/10 6:36p Olegi
// 
// 72    3/10/10 6:35p Olegi
// 
// 71    3/06/10 1:11p Olegi
// 
// 70    2/27/10 11:58a Olegi
// Change in the arguments of pfnHCDInitDeviceData function.
// 
// 69    2/26/10 4:23p Olegi
// 
// 68    2/23/10 1:20p Olegi
// Work around Klockwork issues. EIP34370
// 
// 67    2/08/10 9:38a Olegi
// EIP34448: Bugfix in prepareForLegacyOS.
// 
// 66    1/13/10 3:20p Olegi
// Correction in CheckDeviceLimit routine, EIP32804.
// 
// 65    12/31/09 9:53a Olegi
// 
// 64    12/10/09 10:12a Olegi
// Added UsbControlTimeout setup selection. EIP30079.
// 
// 63    11/12/09 6:09p Olegi
// 
// 62    11/09/09 5:40p Olegi
// 
// 61    10/30/09 5:47p Olegi
// 
// 60    10/13/09 8:55a Olegi
// EIP28323: Change in USBGetProperDeviceInfoStructure:
// - Undo the checking for DEV_INFO_DEV_BUS so that in device structure
// re-used.
// 
// 59    10/09/09 5:57p Olegi
// 
// 58    10/08/09 10:18a Olegi
// EIP28031: USB_SmiQueuePut must not be called after OS booted as it
// modifies the BS memory.
// 
// 57    10/07/09 9:48a Olegi
// USB Hub error handling improvement. EIP#25601.
// 
// 56    10/02/09 10:49a Olegi
// Code cleanup.
// 
// 55    9/15/09 12:21p Olegi
// Added KEY_REPEAT_LOGIC functionality. EIP#25841
// 
// 54    8/26/09 11:41a Olegi
// Changes that prevent collision of keyboard activity and mass storage
// access. EIP#22808
// 
// 53    8/18/09 2:36p Rameshr
// Symptom: When the system is inside the Option rom, connect uSb keyboard
// and it doesn't work.
// Rootcause: In post only EFI driver configure the USB keyboard. So Once
// comes out from option rom Usbkeyboard works.
// Solution: When you are inside the option rom configure the newly
// connected USB keyboard and notify EFI driver.
// 
// 52    8/06/09 4:15p Olegi
// Changes related to EIP#23335: connect status change is not maintained
// properly when device is disconnected while connection is in progress.
// 
// 51    6/11/09 5:29p Olegi
// Increased the default timeout value to 20 sec. Thermlake external HDD
// is not responding to the first READ_10 command for 14 seconds.
// 
// 50    6/04/09 3:42p Olegi
// USB_ConfigureDevice: for the existing devices copy the information
// about the parent controller/hub/port# into the new device structure.
// 
// 49    6/01/09 2:48p Olegi
// EIP#22046: while detecting the new device we get the configuration
// descriptor, assuming it is followed by the interface descriptor; if it
// is not an interface descriptor, we used to think it is not the first
// one, so we never send set address and configuration request.
// 
// 47    5/08/09 8:56a Olegi
// Increased the timeout value from 5 sec to 10 sec. Several types of
// external USB HDDs require this change to be properly enumerated.
// 
// 46    1/29/09 2:32p Olegi
// Added the check for device limit before device is configured.
// 
// 44    9/05/08 4:21p Olegi
// fpCallbackNotify4 is replaced with the local function.
// 
// 42    5/16/08 12:01p Olegi
// Compliance with AMI coding standard.
// 
// 39    10/30/07 12:07p Olegi
// Set configuration one more time: it was found that for some devices
// SET_CONFIGURATION must be the executed right before issuing device
// specific commands. Example is USB Netac Key (VID 0x0644 DID 0x0000).
// 
// 38    10/15/07 5:20p Olegi
// Modified USB_on_identifyDev() routine.
// 
// 37    9/26/07 9:15a Olegi
// Added USB_FORCE_64BIT_ALIGNMENT flag.
// 
// 36    9/06/07 5:59p Olegi
// Added support for 64-byte pool allocation byte alignment.
// 
// 35    7/09/07 2:11p Olegi
// Changed the maximum data size of the BulkTransfer from 1kB to 64kB.
// 
// 32    5/05/07 1:54p Olegi
// Persistent DOS drives.
// 
// 31    4/17/07 8:43a Michaela
// Bugfix in USB_DetectNewDevice function.
// 
// 30    4/17/07 8:24a Olegi
// Device detection algorythm update, in sync with Core8.
// 
// 24    12/22/06 4:05p Olegi
// Timeout implementation.
//
// 17    4/14/06 6:39p Olegi
// Conversion to be able to use x64 compiler.
//
// 16    3/20/06 3:37p Olegi
// Version 8.5 - x64 compatible.
//
// 14    3/06/06 6:24p Olegi
// Lun devices support modifications: supported using the index in
// DEV_INFO table, not through dedicated massLun table.
//
// 13    3/01/06 3:50p Olegi
// USB_FLAG_RUNNING_UNDER_OS flag added.
//
// 11    1/11/06 11:51a Olegi
// Multi-functional devices handling changed.
//
// 10    12/19/05 10:17a Olegi
// USB_StopHostControllers modified to control the sequence of stopping
// (EHCI first, others follow).
//
// 9     11/03/05 6:31p Andriyn
// LUN Support changes
//
// 7     6/20/05 8:55a Olegi
// .NET compiler with highest warning level and warning-as-error
// modification.
//
// 6     6/16/05 12:19p Andriyn
// Fix usb device lost after boot to legacy OS: don't disable port even if
// device is not
// supported by USBRT: there could be another device at the same address
//
// 5     6/15/05 1:59p Andriyn
// Comments were changed
//
// 4     6/01/05 5:34p Olegi
// Bugfix in USB_DetectNewDevice.
//
// 3     5/17/05 7:51p Andriyn
// USB BUS pre-release
//
// 2     5/10/05 4:11p Andriyn
// USBBUS implementation
//
// 1     3/15/05 9:23a Olegi
// Initial VSS check-in.
//
//****************************************************************************

//<AMI_FHDR_START>
//-----------------------------------------------------------------------------
//
//  Name:           Usb.c
//
//  Description:    AMI USB main wrapper
//
//-----------------------------------------------------------------------------
//<AMI_FHDR_END>

#include <Token.h>
#include "amidef.h"
#include "usbdef.h"

#if USB_RUNTIME_DRIVER_IN_SMM
#include <AmiBufferValidationLib.h>
#include <AmiUsbSmmGlobalDataValidationLib.h>
#endif

#include <PCI.h>						//(EIP54018+)

BOOLEAN     gKeyRepeatStatus = FALSE;
extern BOOLEAN  gCheckUsbApiParameter;

BOOLEAN	OEMSkipList(UINT8,UINT8,UINT16,UINT8,UINT8);		//(EIP74609+)

#if USB_DEV_HUB
UINT8   USBHub_EnablePort(HC_STRUC*, UINT8, UINT8);
UINT8   USBHub_DisablePort(HC_STRUC*, UINT8, UINT8);
UINT8   USBHub_ResetPort(HC_STRUC*, UINT8, UINT8);
//VOID    USBHubFillDriverEntries (DEV_DRIVER*);    //(EIP71750-)
UINT8   USBHub_GetPortStatus (HC_STRUC*, UINT8, UINT8, BOOLEAN);
#endif

VOID    SpeakerBeep (UINT8, UINT16, HC_STRUC*);
VOID    FixedDelay(UINTN);
//VOID    BusFillDriverEntries(DEV_DRIVER*);    //(EIP71750-)
										//(EIP38434+)>
//#if USB_DEV_KBD
//VOID    USBKBDFillDriverEntries (DEV_DRIVER*);
//#endif
//#if USB_DEV_MOUSE
//VOID    USBMSFillDriverEntries (DEV_DRIVER*);
//#endif
                                        //(EIP71750-)>                                       
//VOID    USBHIDFillDriverEntries (DEV_DRIVER*);
										//<(EIP38434+)
//#if USB_DEV_MASS
//VOID    USBMassFillDriverEntries (DEV_DRIVER*);
//#endif
//#if USB_DEV_CCID
//VOID    USBCCIDFillDriverEntries (DEV_DRIVER*);
//#endif
                                        //<(EIP71750-)
VOID    MemFill (UINT8*, UINT32, UINT8);
VOID    MemCopy (UINT8*, UINT8*, UINT32);

VOID USBAPI_CheckDevicePresence (URP_STRUC*);

extern  USB_BADDEV_STRUC gUsbBadDeviceTable[];				//(EIP60706)

DEV_INFO*    USB_GetDeviceInfoStruc(UINT8, DEV_INFO*, UINT8, HC_STRUC*);    //(EIP98145)
VOID*       USB_MemAlloc(UINT16);
UINT8       USB_MemFree (VOID*, UINT16);
UINT8*      USB_GetDescriptor (HC_STRUC*, DEV_INFO*, UINT8*, UINT16, UINT8 , UINT8);
UINT8       USB_SetAddress(HC_STRUC*,DEV_INFO*, UINT8);
DEV_INFO*   USBIdentifyAndConfigureDevice (HC_STRUC* , DEV_INFO* , UINT8* , UINT16 ,UINT16 );
UINT8       USB_DisconnectDevice (HC_STRUC*, UINT8, UINT8 );
VOID        USB_InitFrameList (HC_STRUC*, UINT32);
DEV_DRIVER* UsbFindDeviceDriverEntry(DEV_DRIVER*);

UINT8   USB_MemInit (VOID);
UINT8   USBInitHostController(UINT16 *, UINT8);
UINT8   USB_EnumerateRootHubPorts(UINT8);
UINT8   USBLogError(UINT16);
BOOLEAN CheckDeviceLimit(UINT8);
VOID	USB_SmiQueuePutMsg(QUEUE_T*, VOID*, int);

										//(EIP54018+)>
UINT32  ReadPCIConfig(UINT16, UINT8);
#if USB_S5_WAKEUP_SUPPORT
VOID    DwordWritePCIConfig(UINT16, UINT8, UINT32);
VOID    WordWritePCIConfig(UINT16, UINT8, UINT16);
VOID    ByteWritePCIConfig(UINT16, UINT8, UINT8);
VOID    UsbSbEnablePme(VOID);
#endif
										//<(EIP54018+)

extern  USB_GLOBAL_DATA  *gUsbData;  // Defined in AMIUHCD

#ifdef USB_CONTROLLERS_INITIAL_DELAY_LIST
typedef struct {
    UINT16  Vid;
    UINT16  Did;
    UINT16  DelayTime;
} CONTROLLERS_INITIAL_DELAY_LIST;

CONTROLLERS_INITIAL_DELAY_LIST gControllersInitialDelayList[] = {USB_CONTROLLERS_INITIAL_DELAY_LIST};
#endif

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_StartHostControllers
//
// Description: This function initializes the USB host controllers and
//              enumerate the root hub ports for possible USB devices.
//
// Output:      fpGlobalDataArea    Far pointer to the global data area
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_StartHostControllers(UINT8* fpGlobalDataArea)
{
    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       StopControllerType
//
// Description: This function stops all USB host controllers of a given type
//
// Output:      HC type
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
StopControllerType(
    UINT8 hc_type
)
{
    UINT8 i;
    HC_STRUC*   fpHCStruc;

    USB_DEBUG(DEBUG_LEVEL_3, "stopping all HC type %x:", hc_type);
    for (i = 0; i < gUsbData->HcTableCount; i++) {
        fpHCStruc = gUsbData->HcTable[i];
        if (fpHCStruc == NULL) {
            continue;
        }
        if ((fpHCStruc->bHCType == hc_type) &&
            (fpHCStruc->dHCFlag & HC_STATE_RUNNING)) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDStop)(fpHCStruc);
            USB_DEBUG(DEBUG_LEVEL_3, ".");
        }
    }
    USB_DEBUG(DEBUG_LEVEL_3, "\n");
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       StartControllerType
//
// Description: This function start all USB host controllers of a given type
//
// Output:      HC type
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
StartControllerType(
    UINT8 hc_type
)
{
    UINT8 i;
    HC_STRUC*   fpHCStruc;

    USB_DEBUG(DEBUG_LEVEL_3, "starting all HC type %x:", hc_type);
    for (i=0; i<gUsbData->HcTableCount; i++) {
        fpHCStruc = gUsbData->HcTable[i];
        if (fpHCStruc == NULL) {
            continue;
        }
        if (!(fpHCStruc->dHCFlag & HC_STATE_USED)) {
        	continue;
        }
        if ((fpHCStruc->bHCType == hc_type) ) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDStart)(fpHCStruc);
            USB_DEBUG(DEBUG_LEVEL_3, ".");
        }
    }
    USB_DEBUG(DEBUG_LEVEL_3, "\n");
}

										//(EIP74876+)>
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:       StopControllerBdf
//
// Description: This function stops the USB host controllers of a given Bus Dev Function
//
// Input:       BusDevFuncNum
//
// Output:      None
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
StopControllerBdf(
    UINT16 BusDevFuncNum
)
{
    UINT8 i;
    HC_STRUC*   HcStruc;

    for (i = 0; i < gUsbData->HcTableCount; i++) {
        HcStruc = gUsbData->HcTable[i];
        if (HcStruc == NULL) {
            continue;
        }
        if ((HcStruc->wBusDevFuncNum == BusDevFuncNum) &&
            (HcStruc->dHCFlag & HC_STATE_RUNNING)) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDStop)(HcStruc);
            break;
        }
    }
}
										//<(EIP74876+)

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_StopHostControllers
//
// Description: This function stops the USB host controllers and
//              frees the data structures associated with the host controllers
//              In case of USB2.0 first stop USB1.1 controllers, then USB2.0.
//
// Output:      None
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_StopHostControllers (VOID)
{
    // Suppress disconnect beeps as they might be confusing
    gUsbData->dUSBStateFlag  &= (~USB_FLAG_ENABLE_BEEP_MESSAGE);

    StopControllerType(USB_HC_XHCI);    				//(EIP52339+)
    StopControllerType(USB_HC_UHCI);
    StopControllerType(USB_HC_OHCI);
    StopControllerType(USB_HC_EHCI);

    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       UsbHcStart
//
// Description: This function initializes the USB host controller and
//              enumerate the root hub ports for possible USB devices.
//
// Input:		HcStruc		HC struc pointer
//
// Output:		Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
UsbHcStart(HC_STRUC* HcStruc)
{
    UINT8   Index = 0;
    
	USB_DEBUG(DEBUG_LEVEL_3, "Starting HC %X, HCNum %d, type %x\n",
                    HcStruc->wBusDevFuncNum, HcStruc->bHCNumber, HcStruc->bHCType);
	
	// Execute start routine of the host controller driver
	(*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDStart)(HcStruc);

	// Check if the HC is running
	if ((HcStruc->dHCFlag & HC_STATE_RUNNING) == 0) {
		return USB_ERROR;
	}

    for (Index = 0; Index < gUsbData->HcTableCount; Index++) {
        if (gUsbData->HcTable[Index] == NULL) {
            continue;
        }
        if (HcStruc == gUsbData->HcTable[Index]) {
            continue;
        }
        if (HcStruc->BaseAddress == gUsbData->HcTable[Index]->BaseAddress) {
            break;
        }
        if (HcStruc->fpFrameList != NULL) {
            if (HcStruc->fpFrameList == gUsbData->HcTable[Index]->fpFrameList) {
                break;
            }
        }
        if (HcStruc->usbbus_data != NULL) {
            if (HcStruc->usbbus_data == gUsbData->HcTable[Index]->usbbus_data) {
                break;
            }
        }
#if USB_RUNTIME_DRIVER_IN_SMM
        if (HcStruc->wBusDevFuncNum == gUsbData->HcTable[Index]->wBusDevFuncNum) {
            break;
        }
#endif
    }

    if (Index != gUsbData->HcTableCount) {
        HcStruc->dHCFlag &= ~HC_STATE_RUNNING;
        return USB_ERROR;
    }
    
	HcStruc->dHCFlag |= HC_STATE_INITIALIZED;

#if USB_RUNTIME_DRIVER_IN_SMM
#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)
    UpdateAmiUsbSmmGlobalDataCrc32(gUsbData);
#endif
#endif

#ifdef USB_CONTROLLERS_INITIAL_DELAY_LIST
    for (Index = 0; Index < COUNTOF(gControllersInitialDelayList); Index++) {
        if ((gControllersInitialDelayList[Index].Vid == HcStruc->Vid) &&
            (gControllersInitialDelayList[Index].Did == HcStruc->Did)) {
        	if (gControllersInitialDelayList[Index].DelayTime) {
        		FixedDelay(gControllersInitialDelayList[Index].DelayTime * 1000);
        	}
            break;
        }
    }
#endif

	USB_DEBUG(DEBUG_LEVEL_3, "Enumerating HC#%d, type 0x%x\n", HcStruc->bHCNumber, HcStruc->bHCType);
	// Issue enumerate call for this HC
	(*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDEnumeratePorts)(HcStruc);

	return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       UsbHcStop
//
// Description: This function stops the USB host controller.
//
// Input:		HcStruc		HC struc pointer
//
// Output:		Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
UsbHcStop(HC_STRUC* HcStruc)
{
	if ((HcStruc->dHCFlag & HC_STATE_RUNNING) == 0) {
		return USB_ERROR;
	}

	USB_DEBUG(DEBUG_LEVEL_3, "Stopping HC %X, HCNum %d, type %x\n", 
		 		HcStruc->wBusDevFuncNum, HcStruc->bHCNumber, HcStruc->bHCType);
	(*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDStop)(HcStruc);

	return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       CheckBiosOwnedHc
//
// Description: This function checks bios owned hc. 
//              Clear USB_FLAG_DRIVER_STARTED if we don't start 
//              any host controller.              
//
// Input:		None
//
// Output:		None
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
CheckBiosOwnedHc(
    VOID
)
{
    UINT8       Index;
    HC_STRUC    *HcStruc;

    for (Index = 0; Index < gUsbData->HcTableCount; Index++) {
        HcStruc = gUsbData->HcTable[Index];
        if (HcStruc == NULL) {
            continue;
        }
        if (HcStruc->dHCFlag & HC_STATE_RUNNING) {
            return;
        }
    }
    
    gUsbData->dUSBStateFlag &= ~(USB_FLAG_DRIVER_STARTED);

    return;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_EnmumerateRootHubPorts
//
// Description: This function enumerates the root hub ports of the all
//              selected type HCs
//
//
// Output:      bType   - HC type
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_EnumerateRootHubPorts (UINT8 bType)
{
    UINT8		Index;
    HC_STRUC*   fpHCStruc;

    USB_DEBUG(DEBUG_LEVEL_4, "Enumerating HC Ports.\n");
    for (Index = 0; Index < gUsbData->HcTableCount; Index++) {
        //
        // Get the HCStruc pointer associated with this controller
        //
        fpHCStruc = gUsbData->HcTable[Index];
        if (fpHCStruc == NULL) {
              continue;
        }

        if((fpHCStruc->bHCType) == bType && (fpHCStruc->dHCFlag & HC_STATE_RUNNING)) {
            USB_DEBUG(DEBUG_LEVEL_3, "Enumerating HC#%d, type 0x%x\n", fpHCStruc->bHCNumber, bType);
            //
            // Issue enumerate call for this HC
            //
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(bType)].pfnHCDEnumeratePorts)(fpHCStruc);
        }
    }
    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_InitHostControllers
//
// Description: This function initializes the specified type of the HC
//              from the provided list of host controller PCI addresses
//
// Output:      pHCPCIAddrList  Pointer to table of HC PCI addresses in the system
//              bHCType         Type of HC to be initialized (EHCI, OHCI etc)
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USBInitHostController(
    UINT16  * pHCPCIAddrList,
    UINT8   bHCType)
{
    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_GetHubPortStatus
//
// Description: This function returns the hub port status
//
// Input:       HcStruc   HC struc pointer
//              HubAddr   USB device address of the hub or HC number
//                        BIT7 = 1/0  Roothub/Hub
//              PortNum   Port number
//
// Output:      Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_GetHubPortStatus (
    HC_STRUC*	HcStruc,
    UINT8       HubAddr,
    UINT8		PortNum,
    BOOLEAN     ClearChangeBits
)
{
    //
    // Check whether the request is for root hub or generic hub
    //
    if (HubAddr & BIT7) {
		// Root hub
        return (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDGetRootHubStatus)(
                                HcStruc, PortNum, ClearChangeBits);
    } else {
    #if USB_DEV_HUB
        return USBHub_GetPortStatus (HcStruc, HubAddr, PortNum, ClearChangeBits);
    #else
        return 0;
    #endif
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_DisableHubPort
//
// Description: This function disables the hub port
//
// Output:      fpHCStruc   HC struc pointer
//              bHubAddr    USB device address of the hub or HC number
//                          BIT7 = 1/0  Roothub/Hub
//              bPortNum    Port number
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_DisableHubPort(
    HC_STRUC*   fpHCStruc,
    UINT8       bHubAddr,
    UINT8       bPortNum)
{
    //
    // Check whether the request is for root hub or generic hub
    //
    if (bHubAddr & BIT7) {
        //
        // Issue the disable root hub call to disable the hub port
        //
        (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDDisableRootHub)(
                        fpHCStruc,
                        bPortNum);
#if USB_DEV_HUB
    }
    else {
        USBHub_DisablePort (fpHCStruc, bHubAddr, bPortNum);
#endif
    }
    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_EnableHubPort
//
// Description: This function enables the hub port
//
// Output:      fpHCStruc   HC struc pointer
//              bHubAddr    USB device address of the hub or HC number
//                          BIT7 = 1/0  Roothub/Hub
//              bPortNum    Port number
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_EnableHubPort (
    HC_STRUC*   fpHCStruc,
    UINT8       bHubAddr,
    UINT8       bPortNum)
{
    //
    // Check whether the request is for root hub or generic hub
    //
    if (bHubAddr & BIT7) {
        //
        // Root hub
        // Issue the disable root hub call to disable the hub port
        //
        return (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDEnableRootHub)(fpHCStruc, bPortNum);
    } else {
    #if USB_DEV_HUB
        return USBHub_EnablePort (fpHCStruc, bHubAddr, bPortNum);
    #else
        return USB_ERROR;   // Only root hub could be successfully enabled
    #endif
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_ResetHubPort
//
// Description: This function resets the hub port
//
// Input:       HcStruc   HC struc pointer
//              HubAddr   USB device address of the hub or HC number
//                        BIT7 = 1/0  Roothub/Hub
//              PortNum   Port number
//
// Output:      Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_ResetHubPort (
    HC_STRUC*	HcStruc,
    UINT8       HubAddr,
    UINT8		PortNum)
{
    //
    // Check whether the request is for root hub or generic hub
    //
    if (HubAddr & BIT7) {
        //
        // Root hub
        // Issue the reset root hub call to reset the hub port
        //
        return (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDResetRootHub)(HcStruc, PortNum);
    } else {
    #if USB_DEV_HUB
        return USBHub_ResetPort (HcStruc, HubAddr, PortNum);
    #else
        return USB_ERROR;   // Only root hub could be successfully reset
    #endif
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_DetectNewDevice
//
// Description: This function checks the port status provided and depending
//              on the status it invokes device connect/disconnect routine
//
// Output:      fpHCStruc   Pointer to HCStruc
//              bHubAddr    For root port this is the host controller index
//                          in gUsbData->aHCStrucTable combined with BIT7;
//                          For devices connected to a hub this is parent
//                          hub USB address
//              bHubPort    Parent hub port number
//              bPortStatus Port status read
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USB_DetectNewDevice(
    HC_STRUC*   fpHCStruc,
    UINT8   bHubAddr,
    UINT8   bHubPort,
    UINT8   bPortStatus
)
{
    UINT8           bErrorFlag  = 0;
    UINT16          wDescLength;
    UINT8           bDevConfigured;
    UINTN           ConfigLevel = 0;
    UINT16          wTotalLength;
    UINT8           *fpBuffer = NULL;
    DEV_INFO        *fpDevInfo,
                    *fPointer;
    DEV_DESC        *fpDevDesc;
    CNFG_DESC       *fpCnfgDesc;
    INTRF_DESC      *fpIntrfDesc;
    UINT8           *DevMiscInfo;
	UINT8			Status;
    BOOLEAN         SkipConnectBeep = FALSE;   //(EIP64781+)
    UINT16			OrgTimeOutValue;			//(EIP75441+)
    UINT8           DeviceAddress;

    //
    // Get the temporary device info structure pointer (index 0)
    //
    fpDevInfo = gUsbData->aDevInfoTable;

    //
    // Fill the necessary entries in the device info
    //
    fpDevInfo->Flag             = DEV_INFO_VALID_STRUC;
    fpDevInfo->bDeviceAddress   = 0;
    //fpDevInfo->wEndp0MaxPacket  = 0x40;   //(EIP98230-)
    fpDevInfo->bDeviceType      = 0;
    fpDevInfo->wIncompatFlags   = 0;
	fpDevInfo->DevMiscInfo		= NULL;

    //
    // Fill the hub/host controller information
    //
    fpDevInfo->bHubDeviceNumber = bHubAddr;
    fpDevInfo->bHubPortNumber   = bHubPort;

    //
    // Fill the device speed
    //
USB_DEBUG(DEBUG_LEVEL_3, "USB_DetectNewDevice: wPS = %x\n", bPortStatus);
    fpDevInfo->bEndpointSpeed = (bPortStatus & USB_PORT_STAT_DEV_SPEED_MASK) >>
                        USB_PORT_STAT_DEV_SPEED_MASK_SHIFT;

                                        //(EIP98145+)>
#if SHOW_SKIP_PORT_INFORMATION
{
    UINT8   i;
    DEV_INFO   						*tmpDevInfo; 
    tmpDevInfo = fpDevInfo; 	
    USB_DEBUG(3, "==== SHOW_SKIP_PORT_INFORMATION ==== \n"); 				  
    USB_DEBUG(DEBUG_LEVEL_3, "BDF %x \nRoutePath = ",fpHCStruc->wBusDevFuncNum);  
    for(i=0;i<5;i++)
    {
        if(tmpDevInfo->bHubDeviceNumber & BIT7)
        {
            USB_DEBUG(3, "\nRootPort %x \n",tmpDevInfo->bHubPortNumber); 					  
            break;
        }
        USB_DEBUG(3, "%x ",tmpDevInfo->bHubPortNumber); 				  
        tmpDevInfo = USB_GetDeviceInfoStruc(USB_SRCH_DEV_ADDR, 0, tmpDevInfo->bHubDeviceNumber, 0);     
        if(tmpDevInfo == NULL) break;         
    }
    USB_DEBUG(3, "==== SHOW_SKIP_PORT_INFORMATION ==== \n"); 				  
}
#endif
                                        //<(EIP98145+)
                                        //(EIP98230+)>    
    switch (fpDevInfo->bEndpointSpeed) {
        case USB_DEV_SPEED_SUPER_PLUS:
        case USB_DEV_SPEED_SUPER:
            fpDevInfo->wEndp0MaxPacket = 0x200;
            break;
        case USB_DEV_SPEED_HIGH:
            fpDevInfo->wEndp0MaxPacket = 0x40;
            break;
        case USB_DEV_SPEED_FULL:
        case USB_DEV_SPEED_LOW:
            fpDevInfo->wEndp0MaxPacket = 0x08;
            break;
    }
                                        //<(EIP98230+)
    
    //
    // Fill the HC struc index value
    //
    fpDevInfo->bHCNumber = fpHCStruc->bHCNumber;

    bErrorFlag = TRUE;      // Assume as error
    bDevConfigured = FALSE;     // No device configured

    //
    // Allocate memory for device requests
    //
    ConfigLevel = USB_ERR_DEV_INIT_MEM_ALLOC;   // For proper error handling
    fpBuffer = USB_MemAlloc (GET_MEM_BLK_COUNT(MAX_CONTROL_DATA_SIZE));
    if (fpBuffer == NULL) {
		SpeakerBeep(8, 0x2000, fpHCStruc);
		return (DEV_INFO*)ConfigLevel;
    }
    ConfigLevel = USB_ERR_DEV_INIT_GET_DESC_8;

    // Initialize HC specific data before device configuration
    Status = (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDInitDeviceData)(
                        fpHCStruc, fpDevInfo, bPortStatus, &DevMiscInfo);
	if(Status != USB_SUCCESS) {
		USB_MemFree(fpBuffer, (UINT8)(MAX_CONTROL_DATA_SIZE / sizeof(MEM_BLK)));
		SpeakerBeep(8, 0x2000, fpHCStruc);
		return (DEV_INFO*)ConfigLevel;
	}
    fpDevInfo->DevMiscInfo = (VOID*)DevMiscInfo;

//
// Next send a GetDescriptor command to the device to get its Device
// Descriptor. Assume a MaxPacket size of 64 bytes (the device will use 8,
// 16, 32, or 64). Regardless of the packet size used by te device we can
// always get the real MaxPacket size that the device is using, because
// this piece of information is at offset 7 in the device descriptor.
//
	OrgTimeOutValue = gUsbData->wTimeOutValue;	//(EIP75441+)
	gUsbData->wTimeOutValue = 1000;				//(EIP75441+)

    fpDevDesc = (DEV_DESC*)USB_GetDescriptor(
                            fpHCStruc,
                            fpDevInfo,
                            fpBuffer,
                            8,
                            DESC_TYPE_DEVICE,
                            0);

	gUsbData->wTimeOutValue = OrgTimeOutValue;	//(EIP75441+)
    if(fpDevDesc == NULL) {
        goto detection_complete;
    }

    //
    // Get and store the endpoint 0 max packet size
    //
    ConfigLevel = USB_ERR_DEV_INIT_SET_ADDR;
    //
    // Endpoint 0 max packet size check.
    // CyQ've USB modem(Model:MQ4UFM560) return invalid device descriptor after 
    // warm reset.
    //
                                        //(EIP81612)>
    if (fpDevDesc->BcdUsb >= 0x0300) {
        fpDevInfo->wEndp0MaxPacket = (UINT16)1 << fpDevDesc->MaxPacketSize0;
    } else {
        fpDevInfo->wEndp0MaxPacket = (fpDevDesc->MaxPacketSize0)?
                (UINT16)fpDevDesc->MaxPacketSize0 : 0x40;
    }
                                        //<(EIP81612)
                                        //(EIP73803)>
    if((fpDevInfo->bEndpointSpeed == USB_DEV_SPEED_LOW) ||
        (fpDevInfo->bEndpointSpeed == USB_DEV_SPEED_FULL) ||
        (fpDevInfo->bEndpointSpeed == USB_DEV_SPEED_HIGH)){
        FixedDelay(10 * 1000);     // 10msec delay
    }
                                        //<(EIP73803)

    //To assign an address to a USB device, the USB device transitions the state 
    //from the Default to the Address state.
    for (DeviceAddress = 1; DeviceAddress < 64; DeviceAddress++) {
        if (gUsbData->DeviceAddressMap & Shl64(1, DeviceAddress)) {
            break;
        }
    }

    if (DeviceAddress == 64) {
        goto detection_complete;
    }
    Status = USB_SetAddress(fpHCStruc, fpDevInfo, DeviceAddress);
    if (Status == USB_ERROR) {
		goto detection_complete;
    }
    gUsbData->DeviceAddressMap &= ~(Shl64(1, DeviceAddress));
    fpDevInfo->bDeviceAddress = DeviceAddress;
    FixedDelay(2 * 1000);
    
    //
    // Now send a GetDescriptor command to the device to get its device descriptor.
    //
    fpDevDesc = (DEV_DESC*)USB_GetDescriptor(
                            fpHCStruc,
                            fpDevInfo,
                            fpBuffer,
                            18,
                            DESC_TYPE_DEVICE,
                            0);

    //ASSERT(fpDevDesc != NULL);
    if (fpDevDesc == NULL) {
		goto detection_complete;
    }
    // If a descriptor returns with a value in its length field that is 
    // less than defined by USB specification, the descriptor is invalid.
    if (fpDevDesc->DescLength < 18) {
        goto detection_complete;
    }
    if (fpDevDesc->NumConfigs == 0) {
        fpDevDesc->NumConfigs = 1;
    }

    MemCopy((UINT8*)fpDevDesc, (UINT8*)&fpDevInfo->DevDesc, sizeof(DEV_DESC));

    ConfigLevel = USB_ERR_DEV_INIT_GET_DESC_200;
    //
    // Get the relevant information from the descriptor and store it in
    // device information struture
    //
    fpDevInfo->wVendorId    = fpDevDesc->VendorId;
    fpDevInfo->wDeviceId    = fpDevDesc->DeviceId;
//
// Look at each of the device's ConfigDescriptors and InterfaceDescriptors
// until an InterfaceDescriptor is found with BaseClass, SubClass, and
// Protocol fields indicating boot keyboard, mouse, hub or storage support.
//
    fpDevInfo->bConfigNum   = 0;

    if (fpDevInfo->bEndpointSpeed == USB_DEV_SPEED_FULL) {
        FixedDelay(100);
    }

    do {    // For processing multiple configurations
								//(EIP70933+)>
        fpCnfgDesc = (CNFG_DESC*)USB_GetDescriptor(
                        fpHCStruc,
                        fpDevInfo,
                        fpBuffer,
                        0xFF,
                        DESC_TYPE_CONFIG,
                        fpDevInfo->bConfigNum);
		if(fpCnfgDesc == NULL) {
			break;
		}
		wTotalLength = fpCnfgDesc->wTotalLength;
        if (wTotalLength > 0xFF) {
            if(wTotalLength > (MAX_CONTROL_DATA_SIZE - 1)) {
                wTotalLength = MAX_CONTROL_DATA_SIZE - 1;
            }
            fpCnfgDesc = (CNFG_DESC*)USB_GetDescriptor(
                        fpHCStruc,
                        fpDevInfo,
                        fpBuffer,
                        wTotalLength,
                        DESC_TYPE_CONFIG,
                        fpDevInfo->bConfigNum);
								//<(EIP70933+)
            if(fpCnfgDesc == NULL) {
                break;
            }
        }
        if (fpDevInfo->bEndpointSpeed == USB_DEV_SPEED_FULL) {
            FixedDelay(100);
        }
//
// fpCnfgDesc should now point to a ConfigDescriptor.  Verify this and
// then get some fields out of it.  Then point to the next descriptor.
//
        if(fpCnfgDesc->bDescType == DESC_TYPE_CONFIG) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDEnableEndpoints)(
                        fpHCStruc, fpDevInfo, (UINT8*)fpCnfgDesc);

            //wTotalLength = fpCnfgDesc->wTotalLength; //(EIP70933-)
            wDescLength = (UINT8)fpCnfgDesc->bDescLength;
            fpDevInfo->bConfigNum = fpCnfgDesc->bConfigValue;

										//(EIP70933-)>
/*
            if(wTotalLength > (MAX_CONTROL_DATA_SIZE - 1)) {
                wTotalLength = MAX_CONTROL_DATA_SIZE - 1;
            }
*/
										//<(EIP70933-)

            // Check if the device has alternate setting for the interface.
            for (;wDescLength < wTotalLength;) {
                //
                // fpIntrfDesc should now point to an InterfaceDescriptor.  Verify this
                // and then check its BaseClass, SubClass, and Protocol fields for
                // usable devices.
                //
                fpIntrfDesc = (INTRF_DESC*)((UINT8*)fpCnfgDesc + wDescLength);
										//(EIP59601+)>
				if ((fpIntrfDesc->bDescLength == 0) || 
					((fpIntrfDesc->bDescLength + wDescLength) > wTotalLength)) {
					break;
				}
                if ((fpIntrfDesc->bDescType == DESC_TYPE_INTERFACE) && (fpIntrfDesc->bAltSettingNum != 0)) {
                    fpDevInfo->Flag |= DEV_INFO_ALT_SETTING_IF;
                    break;
                }
                if (fpIntrfDesc->bDescLength) {
                    wDescLength += (UINT16)fpIntrfDesc->bDescLength;
                } else {
                    break;
                }
            }

            wDescLength = (UINT8)fpCnfgDesc->bDescLength;

            for (;wDescLength < wTotalLength;) {
                //
                // fpIntrfDesc should now point to an InterfaceDescriptor.  Verify this
                // and then check its BaseClass, SubClass, and Protocol fields for
                // usable devices.
                //
                fpIntrfDesc = (INTRF_DESC*)((UINT8*)fpCnfgDesc + wDescLength);
										//(EIP59601+)>
				if ((fpIntrfDesc->bDescLength == 0) || 
					((fpIntrfDesc->bDescLength + wDescLength) > wTotalLength)) {
					break;
				}
										//<(EIP59601+)
                if ((fpIntrfDesc->bDescType == DESC_TYPE_INTERFACE) && (fpIntrfDesc->bAltSettingNum == 0)) {
                    fpDevInfo->bInterfaceNum    = fpIntrfDesc->bInterfaceNum;
                    fpDevInfo->bAltSettingNum   = 0;
                    //USB_DEBUG(DEBUG_LEVEL_6, "USBIdentifyAndConfigureDevice::fpIntrfDesc %lx\n",fpIntrfDesc);
                    USB_DEBUG(DEBUG_LEVEL_3, "USBIdentifyAndConfigureDevice:: %04x/%04x Intrf %d, AltSetting %d\n",
                            fpDevInfo->wVendorId, fpDevInfo->wDeviceId, fpIntrfDesc->bInterfaceNum, fpIntrfDesc->bAltSettingNum);
                    USB_DEBUG(3, "fpCnfgDesc %x, wDescLength 0x%x, wTotalLength 0x%x\n", fpCnfgDesc, wDescLength, wTotalLength);
                    fPointer = USBIdentifyAndConfigureDevice(
                                    fpHCStruc,
                                    fpDevInfo,
                                    (UINT8*)fpCnfgDesc,
                                    wDescLength,
                                    wTotalLength);
                    if(fPointer != NULL) {
                        fpDevInfo = fPointer;
                        bDevConfigured = TRUE;  // At-least one device is configured
                                        //(EIP64781+)>
                        if(gUsbData->dUSBStateFlag & USB_FLAG_SKIP_CARD_READER_CONNECT_BEEP) {
                            if(fpDevInfo->bBaseClass == BASE_CLASS_MASS_STORAGE) {
                                SkipConnectBeep = TRUE;
                            }
                        }
                                        //<(EIP64781+)
                    }
															//(EIP22046+)>
					//
                    // There is one more config. Set device info structure entry 0 for it
                    //
                    if ((fpCnfgDesc->bNumInterfaces > 1) && bDevConfigured) {
						gUsbData->aDevInfoTable[0].Flag   |= DEV_INFO_MULTI_IF;
                    }
															//<(EIP22046+)
                }
                if (fpIntrfDesc->bDescLength && 
                    !(fpIntrfDesc->bDescType == DESC_TYPE_INTERFACE &&
                            fpIntrfDesc->bBaseClass == BASE_CLASS_HUB)) {
                    wDescLength += (UINT16)fpIntrfDesc->bDescLength;
                    if (wDescLength < wTotalLength) {
															//(EIP22046-)>
                        //
                        // There is one more config. Set device info structure entry 0 for it
                        //
                        /*
                        if (fpDevInfo->bInterfaceNum > 0) {
                            fpDevInfo->Flag |= DEV_INFO_MULTI_IF;
                        }
                        gUsbData->aDevInfoTable[0].Flag   |= DEV_INFO_MULTI_IF;
                        */
															//<(EIP22046-)
                        fpDevInfo = gUsbData->aDevInfoTable;
                    }
                } else {
                    break;   // fpIntrfDesc->bDescLength == 0
                }
            }   // while ()
        }   // if
        //
        // Check if we have at least one usable device
        //
        if (bDevConfigured) {
            bErrorFlag = FALSE; // Device successfully configured
            ConfigLevel = (UINTN)gUsbData->aDevInfoTable;
            goto detection_complete;
        }
        else {
            fpDevInfo->bConfigNum++;
        }
    } while (fpDevInfo->bConfigNum < fpDevInfo->DevDesc.NumConfigs);  // while

detection_complete:
    //
    // At this point, if bErrorFlag is FALSE then we successfully configured
    // atleast a device.
    // If bErrorFlag is TRUE then there is error in configuring the device
    //
    if (bErrorFlag) {
        USBLogError((UINT16)ConfigLevel); // Log configuration level

        SpeakerBeep(8, 0x2000, fpHCStruc);

		(*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDDeinitDeviceData)
 						(fpHCStruc, fpDevInfo);
        if(ConfigLevel != USB_ERR_DEV_INIT_GET_DESC_8) {
            //
            // Disable the hub port
            //
            USB_DisableHubPort(
                fpHCStruc,
                fpDevInfo->bHubDeviceNumber,
                fpDevInfo->bHubPortNumber);
            ConfigLevel = 0;
        }
        if (fpDevInfo->bDeviceAddress) {
            gUsbData->DeviceAddressMap |= Shl64(1, fpDevInfo->bDeviceAddress);
        }
    }
    else {
                                        //(EIP64781+)>
        if(!SkipConnectBeep) {
            SpeakerBeep(4, 0x1000, fpHCStruc);
        }
                                        //<(EIP64781+)
    }
    USB_MemFree(fpBuffer, (UINT8)(MAX_CONTROL_DATA_SIZE / sizeof(MEM_BLK)));

    return (DEV_INFO*)ConfigLevel;

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_StopDevice
//
// Description: This function stops the device:
//              - calls its disconnect function if available
//              - stops polling the device's interrupt endpoint
//              - updates device address memory map
//
//
// Output:      fpHCStruc   Pointer to HCStruc
//              bHCNubAddr  Hub address
//              bHCPort     Port number
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_StopDevice(
    HC_STRUC*   fpHCStruc,
    UINT8       bHubAddr,
    UINT8       bHCPort)
{
    UINT8           bCount;
    DEV_DRIVER* fpDevDriver;
    DEV_INFO*       fpDevice;
    UINT8           Status;

    Status = USB_ERROR;
    //
    // Find the device entry that would match the input.
    //
    for (bCount = 1; bCount < MAX_DEVICES; bCount++)
    {
        fpDevice = &gUsbData->aDevInfoTable[bCount];
        if((fpDevice->Flag & (DEV_INFO_VALID_STRUC | DEV_INFO_DEV_DUMMY)) ==
			DEV_INFO_VALID_STRUC) {
            if((fpDevice->bHubDeviceNumber == bHubAddr) &&
                                    (fpDevice->bHubPortNumber == bHCPort))
            {
                //
                // Device found - issue disconnect call for the device
                //
                if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI) {
                    if (!(fpDevice->Flag & DEV_INFO_IN_QUEUE)) {
                        USB_SmiQueuePut(fpDevice);
                        fpDevice->Flag |= DEV_INFO_IN_QUEUE;
                    }
                }

                fpDevDriver = UsbFindDeviceDriverEntry(fpDevice->fpDeviceDriver);
                //
                // Check disconnect function is valid, if yes - execute it
                //
                if (fpDevDriver && fpDevDriver->pfnDisconnectDevice)
                {
                    fpDevDriver->pfnDisconnectDevice(fpDevice);
					fpDevice->fpDeviceDriver = NULL;
                } else {
					//
					// Stop polling the device's interrupt endpoint
					//
					if (fpDevice->IntInEndpoint) {
						Status = (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDDeactivatePolling)
										(fpHCStruc, fpDevice);
						fpDevice->IntInEndpoint = 0;
					}
                }

                // HC device removal call
                Status = (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDDeinitDeviceData)
                                (fpHCStruc, fpDevice);

				// Reset the disconnecting flag
				fpDevice->Flag &= ~DEV_INFO_DEV_DISCONNECTING;

                //
                // Update Device Address Map, preserving the address for registered devices
                //
                gUsbData->DeviceAddressMap |= Shl64(1, fpDevice->bDeviceAddress);
                fpDevice->Flag &= ~DEV_INFO_DEV_PRESENT;
                if (!(fpDevice->Flag & (DEV_INFO_DEV_BUS | DEV_INFO_MASS_DEV_REGD))) {
					// Reset the device info structure validity ~flag
					fpDevice->Flag &= ~DEV_INFO_VALID_STRUC;
                }
                USB_DEBUG(3, "Release Dev[%d]: %x, flag %x\n", bCount, fpDevice, fpDevice->Flag);
            }
        }
    }
    return Status;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_DisconnectDevice
//
// Description: This function is called when a device disconnect is
//              detected. This routine disables the hub port and stops the
//              device and its children by calling another routine.
//
// Output:      fpHCStruc   Far pointer to HCStruc of the host controller
//              bHubAddr    USB device address of the hub whose status
//                          has changed
//                  bit 7   : 1 - Root hub, 0 for other hubs
//                  bit 6-0 : Device address of the hub
//              bPortNum    Port number
//
// Output:     Status: USB_SUCCESS = Success
//                      USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_DisconnectDevice(
    HC_STRUC*   fpHCStruc,
    UINT8       bHubAddr,
    UINT8       bHCPort)
{
    //
    // A device has been disconnected from the USB.  First disable the hub port
    // that the device was plugged into.  Then free up the device's entry in the
    // DeviceTable.  If there an error occurs while disabling the port, assume
    // that the device is still present an leave its DeviceTable entry in place.
    //
    USB_DisableHubPort(fpHCStruc, bHubAddr, bHCPort);

    USB_StopDevice(fpHCStruc, bHubAddr, bHCPort);

    return USB_SUCCESS;

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   USBCheckPortChange
//
// Description: This routine processes the port status change (like connect,
//              disconnect, etc.) for the root hub and external hubs.
//
// Output:      HcStruc   Pointer to Host Controller structure
//              HubAddr     Device address of the hub whose status
//                          has changed:
//                                bit 7	: 1 - Root hub, 0 for other hubs
//                                bit 6-0	: Device address of the hub
//              PortNum     Hub port number
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USBCheckPortChange (
    HC_STRUC    *HcStruc,
    UINT8       HubAddr,
    UINT8       PortNum
)
{
    UINT8       PortStatus;
    DEV_INFO    *Dev;
    UINT8       Count;

    for (Count = 0; Count < 5; Count++) {
		PortStatus = USB_GetHubPortStatus(HcStruc, HubAddr, PortNum, TRUE);

        //
        // Check the obtained port status
        //
        if (PortStatus == USB_ERROR) {
			return USB_ERROR;
        }
        if (!(PortStatus & USB_PORT_STAT_DEV_OWNER)) {
            return USB_SUCCESS;
        }
        if (OEMSkipList(HubAddr,PortNum,HcStruc->wBusDevFuncNum,0,0)) {
            USB_DEBUG(3, "Match the skip table ; skipping this device.\n");   //(EIP98145)
            return USB_SUCCESS;
        }
        if (!Count && !(PortStatus & USB_PORT_STAT_DEV_CONNECT_CHANGED)) {
			return USB_SUCCESS;
        }
    
        if (PortStatus & USB_PORT_STAT_DEV_CONNECTED) {
            if (gUsbData->bHandOverInProgress) {
                USB_DisableHubPort(HcStruc, HubAddr, PortNum);
                return USB_SUCCESS;
            }
			if ((Count != 0) || !(PortStatus & USB_PORT_STAT_DEV_ENABLED)) {
				// Reset and enable the port
				USB_ResetHubPort(HcStruc, HubAddr, PortNum);
				USB_EnableHubPort(HcStruc, HubAddr, PortNum);
				PortStatus = USB_GetHubPortStatus(HcStruc, HubAddr, PortNum, TRUE);

                if (PortStatus == USB_ERROR) {
			        return USB_ERROR;
                }
                if (!(PortStatus & USB_PORT_STAT_DEV_OWNER)) {
                    return USB_SUCCESS;
                }
				if (!(PortStatus & USB_PORT_STAT_DEV_CONNECTED)) {
					// Some device will be disconnected after 
					// port reset, and reconnected for a while.
					FixedDelay(100 * 1000);
					continue;
				}
				// Check whether port is enabled
				if (!(PortStatus & USB_PORT_STAT_DEV_ENABLED)) {
					FixedDelay(100 * 1000);	 // 100msec delay
					continue;
				}
			}
            Dev = USB_DetectNewDevice(HcStruc, HubAddr, PortNum, PortStatus);
            if ((UINTN)Dev == USB_ERR_DEV_INIT_GET_DESC_8) {
                FixedDelay(100 * 1000);     // 100msec delay
                continue;
            }
			if ((UINTN)Dev == 0) {
				return USB_ERROR;
			}
            if ((UINTN)Dev > USB_ERR_DEV_INIT_GET_DESC_200) {
                return USB_SUCCESS;
            }
            SpeakerBeep(16, 0x4000, HcStruc);  // Issue error beep
            return USB_ERROR;
        } else {  // Disconnect
            USB_DisconnectDevice(HcStruc, HubAddr, PortNum);
            SpeakerBeep(8, 0x1000, HcStruc);
			return USB_SUCCESS;
        }
    }
    if (Count == 5) {
        USB_DisableHubPort(HcStruc, HubAddr, PortNum);
        return USB_ERROR;
    }

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_MemAlloc
//
// Description: This routine allocates blocks of memory from the global
//              memory pool
//
// Output:      bNumBlocks  Number of 32 byte blocks needed
//
// Output:     Start offset to the allocated block (NULL on error)
//
// NOTES:       This routine allocates continuous 32 byte memory blocks.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID _FAR_ *
USB_MemAlloc(UINT16  wNumBlk)
{
    UINT8       bMemIsFound     = FALSE,
                bBitCount       = 0,
                bStart          = 0;
    UINT16      wCount;
    UINT16      Count           = 0;    // Contiguous blocks counter

    UINT16      BlkOffset       = 0,
                wMapDwordPtr;
										//(EIP89641)>
	UINT16		PageCount = 0;
	UINT16		MapDwordCount = 0;
	UINT32		BlksStsDwordsPerPage = 0;

    UINT32      dMask,
                dTemp;

    if (wNumBlk == 0) return NULL;
    
#if USB_FORCE_64BIT_ALIGNMENT
    if (wNumBlk % 2) wNumBlk++;
#endif
	wCount = wNumBlk;

	BlksStsDwordsPerPage = (gUsbData->MemBlkStsBytes >> 2) / gUsbData->MemPages;

    //
    // Locate wNumBlk contiguous blocks from each memory page
    //
    for(PageCount = 0; (PageCount < gUsbData->MemPages) && !bMemIsFound; PageCount++) {

        // Do not reset the counter if the allocated blocks greater than a page.
        if (wNumBlk <= (0x1000 / sizeof(MEM_BLK))) {
		    Count = 0;  // Reset contiguous blocks counter
        }

	    for (MapDwordCount = 0; MapDwordCount < BlksStsDwordsPerPage; MapDwordCount++) {
	        //
	        // Read the next DWORD memory map data
	        //
	        wMapDwordPtr = (PageCount * BlksStsDwordsPerPage) + MapDwordCount;
        	dTemp = gUsbData->aMemBlkSts[wMapDwordPtr];

	        for (bBitCount = 0; bBitCount < 32; bBitCount++)  {
	            BlkOffset++;
	            if (dTemp & (UINT32)(1 << bBitCount))  {
	                Count++;    // Found another free block
	                if(Count == wCount) {
	                    BlkOffset = (UINT16)(BlkOffset-Count);
	                    bMemIsFound = TRUE;
	                    break;  // Found the requested number of free blocks
	                }
	            }
	            else
	            {
	                Count = 0;  // Reset contiguous blocks counter
	            }
	        }
	        if (bMemIsFound) break;
	    }
    }
										//<(EIP89641)
    if (!bMemIsFound) {
        ASSERT(FALSE);
        return NULL;
    }

//
// Change the appropriate bits in the memory map to indicate that some memory
// is being allocated
//
// At this point,
//  bBitCount points to the end of the block within DWORD
//  wMapDwordPtr points to the status dword in question

// We have to reset bCount number of bits starting from
// wMapDwordPtr[bBitCount] to wStsX[BitPosY]
// where wStsX is the status double word of the starting block,
// BitPosY is the bit position of the starting block.
//
    USB_DEBUG(DEBUG_LEVEL_4, "wMapDwordPtr = %d\n", wMapDwordPtr);
//
// Let us have a do loop to do the trick
//
    do {
        //
        // Find out how many bits we can reset in current (pointed by wMapDwordPtr)
        // double word
        //
        Count = (UINT16)((bBitCount >= (wCount-1)) ? wCount : bBitCount+1);
        //
        // Find out the starting bit offset
        //
        bStart = (UINT8)(bBitCount + 1 - Count);
        //
        // Form the 32bit mask for the AND operation
        // First prepare the bits left on the left
        //
        // Note: FFFFFFFF << 32 treated differently by different compilers; it
        // results as 0 for 16 bit compiler and FFFFFFFF for 32 bit. That's why
        // we use caution while preparing the AND mask for the memory map update.
        //
        dMask = ((Count + bStart) < 32) ? (0xFFFFFFFF << (Count + bStart)) : 0;

        //
        // Second, prepare the bits on the right
        //
        if (bStart)
        {
            dMask = dMask | ~(0xFFFFFFFF << bStart);
        }

        //
        // Reset the specified number of bits
        //
        gUsbData->aMemBlkSts[wMapDwordPtr] &= dMask;

        //
        // Update the bCount, StsWordCount & BitCount
        //
        bBitCount = 31;     // End of previous double word where we have to start
        wMapDwordPtr--;     // Previous double word
        wCount = wCount - Count;
    } while ( wCount );

    USB_DEBUG(DEBUG_LEVEL_4, "MemAlloc: %d block(s) at %x %x %x\n",
            wNumBlk,
            gUsbData->fpMemBlockStart + BlkOffset * sizeof(MEM_BLK),
            gUsbData->aMemBlkSts[0],
            gUsbData->aMemBlkSts[1]);

    return  ((VOID _FAR_ *)
        (gUsbData->fpMemBlockStart + (UINT32)BlkOffset * sizeof(MEM_BLK)));
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_MemFree
//
// Description: This routine frees the chunk of memory allocated using
//              the USBMem_Alloc call
//
// Output:      fpPtr       Pointer to the memory block to be freed
//              bNumBlocks  Number of 32 byte blocks to be freed
//
// Output:     Start offset to the allocated block (NULL on error)
//
// NOTES:       This routine frees continuous memory blocks starting
//              from the fpPtr.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_MemFree (
    VOID _FAR_ * fpPtr,
    UINT16    wNumBlk)
{
    UINT8   bOffset, bCount;
    UINT16  wBlkCount, wBlkOffset, wStsWord;

#if USB_FORCE_64BIT_ALIGNMENT
    if (wNumBlk % 2) wNumBlk++;
#endif
    wBlkCount = wNumBlk;
    wBlkOffset = 0;

    //
    // Check for pointer validity
    //
    if (fpPtr == NULL) return USB_ERROR;

    if ((fpPtr < (VOID *)gUsbData->fpMemBlockStart) ||
            (fpPtr > (VOID *)(gUsbData->fpMemBlockStart +
                            (MEM_BLK_COUNT+1)*sizeof(MEM_BLK)))) {
        return  USB_ERROR;
    }

    wBlkOffset = (UINT16)((UINTN)fpPtr - (UINTN)gUsbData->fpMemBlockStart) / sizeof (MEM_BLK);

    if (wBlkOffset >= MEM_BLK_COUNT) {
        return USB_ERROR;
    }

    wStsWord = (UINT16)(wBlkOffset >> 5);   // Divide by 32
    bOffset = (UINT8)(wBlkOffset & 0x1F);   // Mod 32
    bCount = 0;

    do {
        gUsbData->aMemBlkSts[wStsWord] |= ((UINT32)1 << (bCount + bOffset));
        wBlkCount--;
        bCount++;

        if ((bCount + bOffset) && (!((bCount + bOffset) & 0x1F))) {
            wStsWord ++;
            bCount = bOffset = 0;
        }
    } while (wBlkCount);

    USB_DEBUG(DEBUG_LEVEL_4, "MemFree: %d block(s) at %x %x %x\n",
                wNumBlk, fpPtr,
                gUsbData->aMemBlkSts[0], gUsbData->aMemBlkSts[1]);
    //
    // Pointer is valid. Fill the memory with 0's
    //
    MemFill (fpPtr, (UINT32)(wNumBlk * sizeof (MEM_BLK)), 0);

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_InstallCallBackFunction
//
// Description: This function adds a new callback function to the globall
//              callback function list and returns the index of it.
//
// Output:      pfnCallBackFunction     Callback function address
//
// Output:     Callback function index
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_InstallCallBackFunction (
    CALLBACK_FUNC      CallBackFunction
)
{
    UINT8   Index;
    //
    // Check whether this function is already installed or none found
    //
    for (Index = 0; Index < MAX_CALLBACK_FUNCTION; Index++) {
        //
        // Check for null entry
        //
        if (gUsbData->aCallBackFunctionTable[Index] == 0) {
            break;  // No entry found
        }

        if (gUsbData->aCallBackFunctionTable[Index] == CallBackFunction) {
            return (UINT8)(Index+1);
        }
    }

    ASSERT(Index != MAX_CALLBACK_FUNCTION);
    if (Index == MAX_CALLBACK_FUNCTION) {
        EFI_DEADLOOP(); // Exceeding max # of callback function is illegal
    } else {
        //
        // Store the call back function
        //
        gUsbData->aCallBackFunctionTable[Index] = CallBackFunction;
    }

    return (UINT8)(Index + 1);
}

DEV_DRIVER*
UsbFindDeviceDriverEntry(
    DEV_DRIVER* DevDriver
)
{
    UINTN   Index;

    if (DevDriver == NULL) {
        return DevDriver;
    }

    for (Index = 0; Index < MAX_DEVICE_TYPES; Index++) {
        if (DevDriver == &gUsbData->aDevDriverTable[Index]) {
            return &gUsbData->aDevDriverTable[Index];
        }
        if (DevDriver == &gUsbData->aDelayedDrivers[Index]) {
            return &gUsbData->aDelayedDrivers[Index];
        }
    }

    return NULL;
    
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_GetDescriptor
//
// Description: This function executes a get descriptor command to the
//              given USB device and endpoint
//
// Output:      fpHCStruc   HCStruc pointer
//              fpDevInfo   Device info pointer
//              fpBuffer    Buffer to be used for the transfer
//              wLength     Size of the requested descriptor
//              bDescType   Requested descriptor type
//              bDescIndex  Descriptor index
//
// Output:     Pointer to memory buffer containing the descriptor
//              NULL on error
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8*
USB_GetDescriptor(
    HC_STRUC*   fpHCStruc,
    DEV_INFO*   fpDevInfo,
    UINT8*  fpBuffer,
    UINT16  wLength,
    UINT8   bDescType,
    UINT8   bDescIndex)
{
    UINT8           bGetDescIteration;
    UINT16          wReg,
                    wStatus;
    EFI_STATUS      EfiStatus;

    EfiStatus = UsbHcStrucValidation(fpHCStruc);

    if (EFI_ERROR(EfiStatus)) {
        return NULL;
    }

    EfiStatus = UsbDevInfoValidation(fpDevInfo);

    if (EFI_ERROR(EfiStatus)) {
        return NULL;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)fpBuffer, wLength);
        if (EFI_ERROR(EfiStatus)) {
            return NULL;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif
                                        //(EIP60640)>
    for (bGetDescIteration = 0; bGetDescIteration < 5; bGetDescIteration++) {
        wReg = (UINT16)((bDescType << 8) + bDescIndex);
        wStatus = (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDControlTransfer)(
                        fpHCStruc,
                        fpDevInfo,
                        (UINT16)USB_RQ_GET_DESCRIPTOR,
                        (UINT16)0,
                        wReg,
                        fpBuffer,
                        wLength);
        if (wStatus) {
            return fpBuffer;
        }
        if (gUsbData->dLastCommandStatusExtended & USB_TRNSFR_TIMEOUT) {
            break;
        }
        FixedDelay(10 * 1000);
    }
                                        //<(EIP60640)
    return NULL;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_SetAddress
//
// Description: This function sets the USB device address of device 0 to
//              the given value. After this call the USB device will respond
//              at its new address.
//
// Output:      fpHCStruc   Pointer to HCStruc structure
//              fpDevInfo   Pointer to device info structure
//              bNewDevAddr New device address to set
//
// Output:      USB_SUCCESS or USB_ERROR
//
// Notes:       Skip SET_ADDRESS request for XHCI controllers
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_SetAddress(
    HC_STRUC*   fpHCStruc,
    DEV_INFO*   fpDevInfo,
    UINT8       bNewDevAddr)
{
                                        //(EIP60640)>
    UINT8           SetAddressIteration;

    for (SetAddressIteration = 0; SetAddressIteration < 5; SetAddressIteration++) {
        (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDControlTransfer)(
                            fpHCStruc,
                            fpDevInfo,
                            (UINT16)USB_RQ_SET_ADDRESS,
                            0,
                            (UINT16)bNewDevAddr,
                            0,
                            0);
        if (!(gUsbData->bLastCommandStatus & USB_CONTROL_STALLED )) {
            USB_DEBUG(DEBUG_LEVEL_5, "USB_SetAddress#%d\n",bNewDevAddr);
            return USB_SUCCESS;
        }
    }
    return USB_ERROR;
                                        //<(EIP60640)
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_SetConfig
//
// Description: This function sets the device configuration.
//
// Input:       HcStruc   Pointer to HCStruc structure
//              DevInfo   Pointer to device info structure
//              ConfigNum Configuration Value
//
// Output:      USB_SUCCESS or USB_ERROR
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_SetConfig(
    HC_STRUC*   HcStruc,
    DEV_INFO*   DevInfo,
    UINT8       ConfigNum)
{
     (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDControlTransfer)(
                    HcStruc,
                    DevInfo,
                    USB_RQ_SET_CONFIGURATION,
                    0,
                    (UINT16)ConfigNum,
                    0,
                    0);

    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       UsbSetInterface
//
// Description: This function sets the device interface.
//
// Input:       HcStruc   Pointer to HCStruc structure
//              DevInfo   Pointer to device info structure
//              InterfaceNum Interface Value
//
// Output:      USB_SUCCESS or USB_ERROR
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
UsbSetInterface(
    HC_STRUC*   HcStruc,
    DEV_INFO*   DevInfo,
    UINT8       InterfaceNum
)
{
    USB_DEBUG(3, "UsbSetInterface %d\n", InterfaceNum);
    (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDControlTransfer)(
                    HcStruc,
                    DevInfo,
                    USB_RQ_SET_INTERFACE,
                    0,
                    (UINT16)InterfaceNum,
                    0,
                    0);

    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USBLogError
//
// Description: This routine logs the USB error in the data area. This
//              logged errors will be displayed during the POST.
//
// Output:      wErrorCode  Error code to log
//
// Output:     USB_SUCCESS or USB_ERROR
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USBLogError(UINT16  wErrorCode)
{
    //
    // First check for end of the buffer
    //
    if(gUsbData->bErrorLogIndex < MAX_USB_ERRORS_NUM)
    {
        //
        // Still have space to log errors
        //
        gUsbData->aErrorLogBuffer[gUsbData->bErrorLogIndex] = wErrorCode;
        gUsbData->bErrorLogIndex++;
    }
    return USB_ERROR;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_GetDeviceInfoStruc
//
// Description: This function is used to retrieve the device info structure
//              for the particular device address & HCStruc
//
// Output:     bSearchFlag  Flag indicating search type
//                  = USB_SRCH_DEV_ADDR to search by device address and
//                      HCStruc pointer
//                  = USB_SRCH_DEV_TYPE to search by device type
//                  = USB_SRCH_HC_STRUC to search by HC struc pointer
//                  = USB_SRCH_DEV_NUM to count the number of devices connected:
//                      if fpHCStruc is not NULL - count only devices connected to
//                      certain controller, otherwise - all devices of requested
//                      type.
//                  = USB_SERCH_DEV_INDX to search by device location in the DEV_INFO:
//                     a) if fpDevInfo <> 0 return index or the fpDevInfo
//                     b) if bDevAddr <> 0 return the corresponding fpDevInfo
//                     c) if both bDevAddr <> 0 and fpDevInfo <> 0, consider a)
//
//              fpDevInfoPtr    Pointer to the device info structure from where the
//                              search begins (if 0 start from first entry)
//              bDev    Device address/drive number/device type
//              pHCStruc    Pointer to the HCStruc structure
//
// Output:     Depending on bSearchFlag this function returns:
//              - pointer to DEV_INFO structure
//              - table index
//              - number of devices
//              Function returns NULL if device is not found.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USB_GetDeviceInfoStruc(
    UINT8       bSearchFlag,
    DEV_INFO*   fpDev_Info,
    UINT8       bDev,
    HC_STRUC*   fpHcStruc
)
{
    UINT8       Index;
    BOOLEAN     TerminateSearch = FALSE;
    UINT32      dDeviceCounter  = 0;

    if (bSearchFlag == USB_SRCH_DEV_INDX) {
        if (fpDev_Info) {
            for (Index=1; Index < MAX_DEVICES; Index++) {
                if (&gUsbData->aDevInfoTable[Index] == fpDev_Info) {
                    return (DEV_INFO*)(UINTN)Index;
                }
            }
            return NULL;    // Device address not found in the table
        }
        if (bDev == USB_HOTPLUG_FDD_ADDRESS) return &gUsbData->FddHotplugDev;
        if (bDev == USB_HOTPLUG_HDD_ADDRESS) return &gUsbData->HddHotplugDev;
        if (bDev == USB_HOTPLUG_CDROM_ADDRESS) return &gUsbData->CdromHotplugDev;

        if (bDev) return &gUsbData->aDevInfoTable[bDev];
        return NULL;        // Invalid input - both bDev and fpDevInfo are zeroes.
    }

    for (Index = 1; Index < MAX_DEVICES; Index ++) {
        //
        // if fpDev_Info is not null then position the search at the correct
        // index that matches the fpDev_Info
        //
        if (fpDev_Info) {
            if (&gUsbData->aDevInfoTable[Index] != fpDev_Info)
                continue;
            else {
                fpDev_Info = 0;
                continue;
            }
        }
        //
        // For USB_SRCH_DEVBASECLASS_NUM devices are counted regardless of their
        // DEV_INFO_VALID_STRUC flag
        //
        if (bSearchFlag == USB_SRCH_DEVBASECLASS_NUM)
        {
            if(gUsbData->aDevInfoTable[Index].bBaseClass == bDev) {
                if (fpHcStruc) {
                    //
                    // Check if device belongs to the specified HC
                    //
                    if (gUsbData->aDevInfoTable[Index].bHCNumber != fpHcStruc->bHCNumber)
                    {
                        continue;
                    }
                }
                if (gUsbData->aDevInfoTable[Index].Flag & DEV_INFO_DEV_PRESENT)
                {
                    dDeviceCounter++;
                }
            }
            continue;
        }

        if ((gUsbData->aDevInfoTable[Index].Flag & DEV_INFO_VALIDPRESENT) ==
            DEV_INFO_VALIDPRESENT){
            switch(bSearchFlag) {
                case  USB_SRCH_HC_STRUC:
                    if (fpHcStruc == NULL) return NULL;
                    if (gUsbData->HcTable
                        [gUsbData->aDevInfoTable[Index].bHCNumber-1] == fpHcStruc) {
                        TerminateSearch = TRUE;
                    }
                    break;

                case  USB_SRCH_DEV_TYPE:
                    if (gUsbData->aDevInfoTable[Index].bDeviceType == bDev) {
                        TerminateSearch = TRUE;
                    }
                    break;
                case  USB_SRCH_DEV_NUM:
                    if (gUsbData->aDevInfoTable[Index].bDeviceType == bDev) {
                        if (fpHcStruc) {
                            //
                            // Check if device belongs to the specified HC
                            //
                            if (gUsbData->aDevInfoTable[Index].bHCNumber != fpHcStruc->bHCNumber)
                            {
                                break;
                            }
                        }
                        dDeviceCounter++;
                    }
                    break;  // Do not change TerminateSearch so loop continues
                case  USB_SRCH_DEV_ADDR:
                    if (gUsbData->aDevInfoTable[Index].bDeviceAddress == bDev) {
                        if ((fpHcStruc == NULL) ||
                            (gUsbData->HcTable
                                [gUsbData->aDevInfoTable[Index].bHCNumber-1] == fpHcStruc)) {
                            TerminateSearch = TRUE;
                        }
                    }
                    break;

                default:
                    return NULL;
            }
        }
        if (TerminateSearch) return ((DEV_INFO*)&gUsbData->aDevInfoTable[Index]);
    }
    if ( (bSearchFlag == USB_SRCH_DEV_NUM) || (bSearchFlag == USB_SRCH_DEVBASECLASS_NUM) )
         return (DEV_INFO*)(UINTN)dDeviceCounter;

    return NULL;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// PROCEDURE:   UsbAllocDevInfo
//
// Description: Finds a non-used DEV_INFO record in aDevInfoTable and marks it
//              reserved. To free the user need to clear DEV_INFO_VALID_STRUC
//              bit in bFlag of DEV_INFO
//
// Output:     Pointer to new device info. struc. 0 on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
DEV_INFO* UsbAllocDevInfo()
{
    UINT8       bIndex;
    DEV_INFO    *fpNewDevInfo;

    for (bIndex = 1; bIndex < MAX_DEVICES; bIndex ++){
        fpNewDevInfo = gUsbData->aDevInfoTable +bIndex;
        if ((fpNewDevInfo->Flag &
        ( DEV_INFO_VALID_STRUC | DEV_INFO_DEV_BUS)) == 0 ){
            //
            // Free device info structure. Save it if not.
            //
            fpNewDevInfo->Flag |= DEV_INFO_VALID_STRUC |  DEV_INFO_DEV_PRESENT;
            return  fpNewDevInfo;
        }
    }
    return NULL;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBGetProperDeviceInfoStructure
//
// Description: This routine searches for a device info structure that
//              matches the vendor and device id, and LUN of the device
//              found. If such a device info structure not found, then it
//              will return a free device info structure
//
// Input:       Vendor, Device ID, Current LUN
//
// Output:     Pointer to new device info. struc. NULL on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USBGetProperDeviceInfoStructure(
    DEV_INFO*	Dev,
    UINT8   	Lun)
{
    UINT8       bCount;
    DEV_INFO    *fpDevInfo, *fpFreeDevInfo;

    fpFreeDevInfo = NULL;

//
// Scan through the device info table for a free entry. Also if the device
// connected is a mass storage device look for a device info structure whose
// device is disconnected and its vendor & device id matches the one of
// current device. If such a structure found that means this device may be
// reconnected - use the same structure
//
    for (bCount = 1; bCount < MAX_DEVICES; bCount++)
    {
        fpDevInfo   = (DEV_INFO*) &gUsbData->aDevInfoTable[bCount];

        if (fpDevInfo->Flag & DEV_INFO_DEV_DUMMY) {
            continue;
        }

        // Check whether the structure is valid
        if (!(fpDevInfo->Flag & DEV_INFO_VALID_STRUC)) {    
            if (fpFreeDevInfo == NULL) {
                fpFreeDevInfo = fpDevInfo;    // Store the value of the free device info
            }
        } else {
            //
            // Yes, structure is valid. Check for device presence
            //
			if (fpDevInfo->Flag & DEV_INFO_DEV_PRESENT) {
				if ((fpDevInfo->bHubDeviceNumber != Dev->bHubDeviceNumber) ||
					(fpDevInfo->bHubPortNumber != Dev->bHubPortNumber)) {
					continue;
				}
			}
            //
            // Device is not present. Match the vendor, device id  and LUN with
            // current device info
            //
            if ((fpDevInfo->wVendorId == Dev->wVendorId) &&
                (fpDevInfo->wDeviceId == Dev->wDeviceId) &&
                (fpDevInfo->bInterfaceNum == Dev->bInterfaceNum) &&
                (fpDevInfo->bEndpointSpeed == Dev->bEndpointSpeed) &&
                (fpDevInfo->bLUN == Lun)) {
                return fpDevInfo;   // "Abandoned" device entry found
            }
        }
    }
    return fpFreeDevInfo;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// PROCEDURE:   USB_ConfigureDevice
//
// Description: This routine completes the USB device configuration for
//              the devices supported by USB BIOS. This routine
//              handles the generic configuration for the devices.
//
// Output:      pHCStruc    HCStruc pointer
//              pDevInfo    Device information structure pointer
//              pDesc       Pointer to the descriptor structure
//              wStart      Offset within interface descriptor
//                          supported by the device
//              wEnd        End offset of the device descriptor
//
// Output:     Pointer to new device info. struc. 0 on error
//
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USB_ConfigureDevice (
    HC_STRUC*   HcStruc,
    DEV_INFO*   DevInfo,
    UINT8*      Desc,
    UINT16      Start,
    UINT16      End
)
{
    DEV_INFO    *NewDevInfo;

    NewDevInfo = USBGetProperDeviceInfoStructure(DevInfo, 0);

    if (NewDevInfo == NULL) {
        return NULL;
    }
    //
    // Check whether this device is reconnected by checking the valid
    // structure flag
    //
    if (NewDevInfo->Flag & DEV_INFO_VALID_STRUC) {
        USB_DEBUG(DEBUG_LEVEL_3, "USB_ConfigureDevice: Existing device.\n");
        //
        // This device is reconnected. Reuse the old device address so that
        // INT13h can identify this drive properly
        //
        DevInfo->Flag |= NewDevInfo->Flag;
		NewDevInfo->wDataInSync = 0;
		NewDevInfo->wDataOutSync = 0;
    }
    else {
        //
        // Check whether we reached the limit of devices of this type
        //
        if (CheckDeviceLimit(DevInfo->bBaseClass) == TRUE) {
            return NULL;
        }
    }

    //
    // For registered devices skip updating bFlag
    //
    if (!(NewDevInfo->Flag & DEV_INFO_MASS_DEV_REGD)) {
        //
        // Since DeviceInfo[0] already has many fields filled in, the new entry
        // should be initialized with a copy of DeviceInfo[0].  But, the new
        // DeviceInfo should not be  marked as "present" until the device
        // is successfully initialized.
        //
        // Copy old DeviceInfo struc to new DeviceInfo struc and zero device[0]
        //
        MemCopy ((UINT8*)DevInfo, (UINT8*)NewDevInfo, sizeof (DEV_INFO));
		NewDevInfo->Flag &= DEV_INFO_VALID_STRUC | DEV_INFO_DEV_PRESENT |
								DEV_INFO_MASS_DEV_REGD | DEV_INFO_DEV_BUS |
								DEV_INFO_IN_QUEUE | DEV_INFO_ALT_SETTING_IF;
    } else {
        // Change the parent HC number and port number in the existing DEV_INFO
        NewDevInfo->bHCNumber = DevInfo->bHCNumber;
    	NewDevInfo->bHubDeviceNumber = DevInfo->bHubDeviceNumber;
		NewDevInfo->bHubPortNumber = DevInfo->bHubPortNumber;
		NewDevInfo->bEndpointSpeed = DevInfo->bEndpointSpeed;
		NewDevInfo->wEndp0MaxPacket = DevInfo->wEndp0MaxPacket;
    	NewDevInfo->DevMiscInfo = DevInfo->DevMiscInfo;
        NewDevInfo->bDeviceAddress = DevInfo->bDeviceAddress;
    }

    //
    // Do a SetConfiguration command to the device to set it to its
    // HID/Boot configuration.
    //
    NewDevInfo->Flag |= DEV_INFO_VALIDPRESENT;
    if (!(DevInfo->Flag & DEV_INFO_MULTI_IF)) {
	    USB_SetConfig(HcStruc, NewDevInfo, NewDevInfo->bConfigNum);
        if (DevInfo->Flag & DEV_INFO_ALT_SETTING_IF) {
            UsbSetInterface(HcStruc, NewDevInfo, NewDevInfo->bAltSettingNum);
        }
    }

    USB_DEBUG(3, "new dev: %x, flag: %x, addr %d\n",
                NewDevInfo, NewDevInfo->Flag, NewDevInfo->bDeviceAddress);

    return NewDevInfo;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCheckNonCompliantDevice
//
// Description: This function checks for non-compliant USB devices by
//              by comparing the device's vendor and device id with
//              the non-compliant device table list and updates the
//              data structures appropriately to support the device.
//
// Input:       fpHCStruc - HCStruc pointer
//              fpDevInfo - Device information structure pointer
//              fpDesc    - Pointer to the descriptor structure
//              wDescLength - End offset of the device descriptor
//
// Output:     Updated fpDevInfo->wIncompatFlags field
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
USBCheckNonCompliantDevice(
    HC_STRUC*   fpHCStruc,
    DEV_INFO*   fpDevInfo,
    UINT8*      fpDesc,
    UINT16      wLength,
    UINT16      wDescLength
)
{
    USB_BADDEV_STRUC    *fpBadDevice;
    INTRF_DESC          *fpIntrfDesc;

    fpIntrfDesc = (INTRF_DESC*)((UINT8*)fpDesc + wLength);

    //
    // Search the bad device table to get the structure for this device
    //
    for (fpBadDevice = gUsbBadDeviceTable;
         fpBadDevice->wDID | fpBadDevice->wVID; fpBadDevice++) {

        if ((fpBadDevice->wDID != fpDevInfo->wDeviceId) ||
                (fpBadDevice->wVID != fpDevInfo->wVendorId)) {
            continue;
        }
USB_DEBUG(DEBUG_LEVEL_3, "Found non-compatible device: DID=%x, VID=%x\n", fpBadDevice->wDID, fpBadDevice->wVID);
        //
        // Save the incompatibility flag into device info structure
        //
        fpDevInfo->wIncompatFlags = fpBadDevice->wFlags;

        //
        // Check which fields to update in the interface descriptor
        //
        // Check for base class field
        //
        if (fpBadDevice->bBaseClass) {
            //
            // Update base class field in the interface descriptor
            //
            fpIntrfDesc->bBaseClass = fpBadDevice->bBaseClass;
        }
        //
        // Check for base sub class field
        //
        if (fpBadDevice->bSubClass) {
            //
            // Update sub class field in the interface descriptor
            //
            fpIntrfDesc->bSubClass = fpBadDevice->bSubClass;
        }
        //
        // Check for protocol field
        //
        if (fpBadDevice->bProtocol) {
            //
            // Update protocol field in the interface descriptor
            //
            fpIntrfDesc->bProtocol = fpBadDevice->bProtocol;
        }
        break;
    }
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// PROCEDURE:   USBIdentifyAndConfigureDevice
//
// Description: This routine invokes the device drivers 'check device type'
//              routine and identifies the device type.
//
// Output:      pHCStruc    HCStruc pointer
//              pDevInfo    Device information structure pointer
//              pDesc       Pointer to the descriptor structure
//              wStart      Offset within interface descriptor
//                          supported by the device
//              wEnd        End offset of the device descriptor
//
// Output:     Pointer to new device info. struc, NULL on error
//
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USBIdentifyAndConfigureDevice (
    HC_STRUC*   fpHCStruc,
    DEV_INFO*   fpDevInfo,
    UINT8*      fpDesc,
    UINT16      wLength,
    UINT16      wDescLength)
{
    UINT8           bBaseClass, bSubClass, bProtocol,
                    bIndex, bRetValue;
    DEV_INFO*       fpDevInfoLocal;
    DEV_DRIVER*     fpDevDriver;
    INTRF_DESC*     fpIntrfDesc;

    //
    // Check for non-compliant device. If non-compliant device found then
    // the descriptor values will get updated depending on the need.
    //
    USBCheckNonCompliantDevice (
            fpHCStruc,
            fpDevInfo,
            fpDesc,
            wLength,
            wDescLength);

    USB_DEBUG(DEBUG_LEVEL_3, "USBIdentifyAndConfigureDevice...");

    //
    // Check whether device needs to be disable
    //
    if (fpDevInfo->wIncompatFlags & USB_INCMPT_DISABLE_DEVICE) {
        USB_DEBUG(DEBUG_LEVEL_3, "not compatible device.\n");
        return NULL;
    }

    fpIntrfDesc = (INTRF_DESC*)(fpDesc + wLength);

//(EIP74609+)>
	if(OEMSkipList(fpDevInfo->bHubDeviceNumber,fpDevInfo->bHubPortNumber,fpHCStruc->wBusDevFuncNum,fpIntrfDesc->bBaseClass,1)) {
        USB_DEBUG(3, "Match the skip table ; skipping this device.\n");   //(EIP98145) 
		return NULL;
	}	
//<(EIP74609+) 
    //
    // Get the base, sub class & protocol values
    //
    bBaseClass  = fpIntrfDesc->bBaseClass;
    bSubClass   = fpIntrfDesc->bSubClass;
    bProtocol   = fpIntrfDesc->bProtocol;

    //
    // Check for matching device driver
    //
    fpDevInfoLocal = NULL;
    bRetValue = USB_ERROR;
                                        
                                        //(EIP96616+)>
    for (bIndex = 0; bIndex < MAX_DEVICE_TYPES; bIndex ++) {
        fpDevDriver = &gUsbData->aDevDriverTable[bIndex];
        //
        // Check structure validity
        //
        if (!fpDevDriver->bDevType) {
            continue;       // Driver table not valid
        }
        //
        // Verify presence of Check Device routine
        //
        if (fpDevDriver->pfnCheckDeviceType) {
            //
            // Check device type is implemented. Execute it!
            //
            bRetValue = (*fpDevDriver->pfnCheckDeviceType)(
                           fpDevInfo,bBaseClass,
                           bSubClass,bProtocol);
                if (bRetValue != USB_ERROR)
                    break;
            }  else {
            //
            // Check device type is not implemented. Compare the class codes
            //
            if((fpDevDriver->bBaseClass == bBaseClass) ||
                (fpDevDriver->bSubClass == bSubClass) ||
                (fpDevDriver->bProtocol == bProtocol)) {
                //
                // If the class codes match set bRetValue with the bDevType from the Device Driver
                //
                bRetValue = fpDevDriver->bDevType;
                break;
            }
        }
    }
    if(bRetValue != USB_ERROR){
        //
        // Check whether we reached the limit of devices of this type
        //
        //if (CheckDeviceLimit(bBaseClass) == TRUE) continue;   //(EIP81761-)

        //
        // Set the device type in the Device Info structure
        //
        fpDevInfo->bDeviceType  = bRetValue;

        //
        // Set Base Class, Subclass and Protocol information
        //
        fpDevInfo->bBaseClass = bBaseClass;
        fpDevInfo->bProtocol = bProtocol;
        fpDevInfo->bSubClass = bSubClass;

        //
        // Device identified. Issue common configure call
        // Call a common routine to handle the remaining initialization that is done
        // for all devices.
        //
        fpDevInfoLocal = USB_ConfigureDevice(
                            fpHCStruc,
                            fpDevInfo,
                            fpDesc,
                            wLength,
                            wDescLength);

        if (fpDevInfoLocal == NULL) {
            USB_DEBUG(DEBUG_LEVEL_3, "USB: Common configure failed.\n");
            return fpDevInfoLocal;
        }

        if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI) {
            if (!(fpDevInfoLocal->Flag & DEV_INFO_IN_QUEUE)) {
                USB_SmiQueuePut(fpDevInfoLocal);
                fpDevInfoLocal->Flag |= DEV_INFO_IN_QUEUE;
            }
        }

        fpDevInfoLocal->fpDeviceDriver = fpDevDriver;
        fpDevInfoLocal = (*fpDevDriver->pfnConfigureDevice)(
                                fpHCStruc,
                                fpDevInfoLocal,
                                fpDesc,
                                wLength,
                                wDescLength);
        if (!fpDevInfoLocal ||
        !(fpDevInfoLocal->Flag & DEV_INFO_VALID_STRUC) )
        {
            fpDevInfoLocal = 0;
            USB_DEBUG(DEBUG_LEVEL_3, "USB: Device specific configure failed.\n");
            return fpDevInfoLocal;
        }

                                        //<(EIP96616+)
    }

    USB_DEBUG(DEBUG_LEVEL_3, "%x\n", fpDevInfoLocal);

    return fpDevInfoLocal;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       USB_InitFrameList
//
// Description: This routine initializes the frame list pointed by fpPtr
//              with the dValue provided
//
// Output:      fpHCStruc   Pointer to the Host Controller structure
//              dValue  Value to be initialized with
//
// Output:     Nothing
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>


VOID
USB_InitFrameList(
    HC_STRUC*   fpHCStruc,
    UINT32      dValue)
{
    UINT16  wIndex;
    UINT32  *fpPtr = (UINT32*)fpHCStruc->fpFrameList;

    for (wIndex = 0; wIndex < fpHCStruc->wAsyncListSize; wIndex ++) {
        fpPtr[wIndex] = dValue;
    }
    return;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBKeyRepeat
//
// Description: This function handles different key repeat related functions
//              depending on the input
//
// Input:   fpHCStruc - pointer for the HC that implements the key repeat function
//          bAction   - sub-function index:
//              0  Install key repeat HCStruc
//              1  Disable key repeat
//              2  Enable key repeat
//				3  Uninstall key repeat HCStruc
//
// Output:  None
//
// Note:    fpHCStruc is only relevant for sub-function 0.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBKeyRepeat(
    HC_STRUC*   HcStruc,
    UINT8       Action
)
{

//USB_DEBUG(DEBUG_LEVEL_3, "KR%d\n", bAction);
	UINT8		i;

    switch (Action) {
        case 0:     // Sub-function 0: Save the HCStruc value for later use
            if (gKeyRepeatStatus == FALSE) {
                gUsbData->fpKeyRepeatHCStruc = HcStruc;
        	}
            break;
        case 1:     // Sub-function 0: Disable key repeat
			if (gKeyRepeatStatus) {
#if USB_HID_KEYREPEAT_USE_SETIDLE == 1 
	            if (gUsbData->fpKeyRepeatDevInfo != NULL) {
	            //
	            // Set the HID SET_IDLE request to 0
	            //
	            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(gUsbData->HcTable[gUsbData->fpKeyRepeatDevInfo->bHCNumber - 1]->bHCType)].pfnHCDControlTransfer)
	                    (gUsbData->HcTable[gUsbData->fpKeyRepeatDevInfo->bHCNumber - 1],
	                    gUsbData->fpKeyRepeatDevInfo,(UINT16)HID_RQ_SET_IDLE, gUsbData->fpKeyRepeatDevInfo->bInterfaceNum, 0, 0, 0);	//(EIP54782)
	            }
#else
	            if (gUsbData->fpKeyRepeatHCStruc) {
	                (*gUsbData->aHCDriverTable[GET_HCD_INDEX(
	                    gUsbData->fpKeyRepeatHCStruc->bHCType)].pfnHCDDisableKeyRepeat)(
	                        gUsbData->fpKeyRepeatHCStruc);
	            }
#endif
				gKeyRepeatStatus = FALSE;
			}
            break;
        case 2:     // Sub-function 0: Enable key repeat
        	if (!gKeyRepeatStatus) {
#if USB_HID_KEYREPEAT_USE_SETIDLE == 1 
	            if(gUsbData->fpKeyRepeatDevInfo != NULL) {
	                //
	                // Set the HID SET_IDLE request to 0x200 (8ms)
	                //
	                (*gUsbData->aHCDriverTable[GET_HCD_INDEX(gUsbData->HcTable[gUsbData->fpKeyRepeatDevInfo->bHCNumber - 1]->bHCType)].pfnHCDControlTransfer)
	                        (gUsbData->HcTable[gUsbData->fpKeyRepeatDevInfo->bHCNumber - 1],
	                        gUsbData->fpKeyRepeatDevInfo,(UINT16)HID_RQ_SET_IDLE, gUsbData->fpKeyRepeatDevInfo->bInterfaceNum, 0x400, 0, 0);	//(EIP54782)
	            }
#else 
	            if (gUsbData->fpKeyRepeatHCStruc) {
	                (*gUsbData->aHCDriverTable[GET_HCD_INDEX(
	                    gUsbData->fpKeyRepeatHCStruc->bHCType)].pfnHCDEnableKeyRepeat)(
	                        gUsbData->fpKeyRepeatHCStruc);
	            }
#endif
				gKeyRepeatStatus=TRUE;
        	}
            break;
		case 3:
        	if (gUsbData->fpKeyRepeatHCStruc == HcStruc) {
            	gUsbData->fpKeyRepeatHCStruc = NULL;
				for (i = 0; i < gUsbData->HcTableCount; i++) {
                    if (gUsbData->HcTable[i] == NULL) {
                        continue;
                    }
                    if (gUsbData->HcTable[i] == HcStruc) {
                        continue;
                    }
					if (gUsbData->HcTable[i]->dHCFlag & HC_STATE_RUNNING) {
						gUsbData->fpKeyRepeatHCStruc = gUsbData->HcTable[i];
                        if (gKeyRepeatStatus) {
                            gKeyRepeatStatus = FALSE;
                            USBKeyRepeat(NULL, 2);
                        }
                        break;
					}
				}
        	}
			break;
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   BusFillDriverEntries
//
// Description: Install drivers that redirects ...????
//
// Input:   fpDevDriver - record that the routine can use to install the drive
// Output:  None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_bus_interrupt_handler (
    HC_STRUC	*HcStruc,
    DEV_INFO	*DevInfo,
    UINT8		*Td,
    UINT8		*Buffer,
    UINT16      DataLength
)
{
	USBHC_INTERRUPT_DEVNINFO_T *Idi = (USBHC_INTERRUPT_DEVNINFO_T *)DevInfo->pExtra;
    EFI_STATUS  Status = EFI_SUCCESS;
    
	ASSERT(Idi);
	if (Idi == NULL) {
		return USB_SUCCESS;
	}

#if USB_RUNTIME_DRIVER_IN_SMM	
	Status = AmiValidateMemoryBuffer((VOID*)Idi, sizeof(USBHC_INTERRUPT_DEVNINFO_T));
    if (EFI_ERROR(Status)) {
        return USB_ERROR;
    }
#endif

	USB_SmiQueuePutMsg(&Idi->QCompleted, Buffer, (int)Idi->DataLength);
    return USB_SUCCESS;
}

VOID
UsbBusDeviceInit(
    VOID
)
{
    USB_InstallCallBackFunction(USB_bus_interrupt_handler);
    return;
}

DEV_INFO*
USB_on_configDev(
    HC_STRUC    *fpHCStruc,
    DEV_INFO    *fpDevInfo,
    UINT8       *fpDesc,
    UINT16      wStart,
    UINT16      wEnd
)
{
    fpDevInfo->bDeviceType      = (UINT8)BIOS_DEV_TYPE_USBBUS;
    fpDevInfo->bCallBackIndex   = USB_InstallCallBackFunction(USB_bus_interrupt_handler);
    return(fpDevInfo);
}

UINT8
USB_on_identifyDev(
    DEV_INFO*   fpDevInfo,
    UINT8       bBaseClass,
    UINT8       bSubClass,
    UINT8       bProtocol
)
{
                                        //(EIP96616+)>
    if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI)
        return  BIOS_DEV_TYPE_USBBUS;
    else
        return  USB_ERROR;
                                        //<(EIP96616+)
}

UINT8
USB_on_disconnectDev(
    DEV_INFO* fpDevInfo
)
{
    return  USB_SUCCESS;
}

VOID
BusFillDriverEntries(
    DEV_DRIVER  *fpDevDriver
)
{
    fpDevDriver->bDevType               = BIOS_DEV_TYPE_USBBUS;
    fpDevDriver->bBaseClass             = 0;
    fpDevDriver->bSubClass              = 0;
    fpDevDriver->bProtocol              = 0;
    fpDevDriver->pfnDeviceInit          = UsbBusDeviceInit;
    fpDevDriver->pfnCheckDeviceType     = USB_on_identifyDev;
    fpDevDriver->pfnConfigureDevice     = USB_on_configDev;
    fpDevDriver->pfnDisconnectDevice    = USB_on_disconnectDev;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USB_ReConfigDevice, USB_ReConfigDevice2
//
// Description: EFI code will call this function to give a chance for
//              SMI dev driver to complete the configuration of device
//
//              Before call, USB device is connected, address is assigned
//              and configuration is set. DEV_INFO structure is initalized
//              from information parsed from descriptors and linked
//              to USBBUS dev driver. Device driver specific to the type
//              of USB device wasn't called on this device
//
//              After the call returns, a specific device driver
//              initialization was  performed by calling pfnCheckDeviceType
//              and pfnConfigureDevice functions of device driver. Parameters
//              to those functions are taken from descriptors downloaded from
//              the device. Device preserve old address and active configuration
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
int USB_ReConfigDevice2( HC_STRUC* fpHCStruc, DEV_INFO* fpDevInfo,
                        CNFG_DESC   *fpCnfgDesc,
                        INTRF_DESC * fpIntrfDesc );

int USB_ReConfigDevice( HC_STRUC* fpHCStruc, DEV_INFO* fpDevInfo )
{
    INTRF_DESC      *fpIntrfDesc=NULL;

    UINT8           iConfig;
    int             status = USB_SUCCESS;   //(EIP90124)
    UINT8*          fpBuffer;
    CNFG_DESC       *fpCnfgDesc=NULL;
    UINT16			OrgTimeOutValue;

    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(fpHCStruc);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    EfiStatus = UsbDevInfoValidation(fpDevInfo);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    gCheckUsbApiParameter = FALSE;

	if (fpDevInfo->bDeviceType != 0 && 
		fpDevInfo->bDeviceType != BIOS_DEV_TYPE_USBBUS) {
		return USB_SUCCESS;
	}

    fpBuffer = USB_MemAlloc (GET_MEM_BLK_COUNT(MAX_CONTROL_DATA_SIZE));
    if (fpBuffer == NULL) {
        return USB_ERROR;
    }
    //
    // Find configuration desc
    //
    for (iConfig = 0; iConfig < fpDevInfo->DevDesc.NumConfigs;++iConfig){
        
        OrgTimeOutValue = gUsbData->wTimeOutValue;
        gUsbData->wTimeOutValue = USB_GET_CONFIG_DESC_TIMEOUT_MS;
        
        fpCnfgDesc = (CNFG_DESC*)USB_GetDescriptor(
            fpHCStruc,
            fpDevInfo,
            fpBuffer,
            (MAX_CONTROL_DATA_SIZE - 1),
            DESC_TYPE_CONFIG,
            iConfig);
        
        gUsbData->wTimeOutValue = OrgTimeOutValue;
        
        if (fpDevInfo->bEndpointSpeed == USB_DEV_SPEED_FULL) {
            FixedDelay(1000);           
        }
        if(fpCnfgDesc != NULL && fpCnfgDesc->bDescType == DESC_TYPE_CONFIG &&
            fpDevInfo->bConfigNum == fpCnfgDesc->bConfigValue ){
            break;
        }

        fpCnfgDesc = NULL;
    }

    if( fpCnfgDesc ){
        UINT16 offset;
        UINT16 wDescLength;
        INTRF_DESC      *pIntrf;

        if(fpCnfgDesc->wTotalLength > MAX_CONTROL_DATA_SIZE - 1)
            fpCnfgDesc->wTotalLength = MAX_CONTROL_DATA_SIZE - 1;
        wDescLength = fpCnfgDesc->wTotalLength;
        for(offset=(UINT16)fpCnfgDesc->bDescLength;offset <wDescLength ;offset = offset + (UINT16)pIntrf->bDescLength){
            pIntrf  = (INTRF_DESC*)((UINT8*)fpCnfgDesc + offset);
            if(pIntrf->bDescLength == 0) {
                break;
            }
            if (pIntrf->bDescType == DESC_TYPE_INTERFACE &&
                fpDevInfo->bInterfaceNum == pIntrf->bInterfaceNum &&
                fpDevInfo->bAltSettingNum == pIntrf->bAltSettingNum ) {
                fpIntrfDesc =pIntrf;
                break;
            }
        }
    }

    USB_DEBUG(DEBUG_LEVEL_3,
        "USB_reConfigDev:: CfgDsc=%x; IntrfDsc=%x\n",
        fpCnfgDesc, fpIntrfDesc);

    if (fpIntrfDesc && fpCnfgDesc) {
        status = USB_ReConfigDevice2(fpHCStruc, fpDevInfo,
                                    fpCnfgDesc, fpIntrfDesc);
    } else {
        status = USB_ERROR;
    }

    USB_MemFree(fpBuffer, (UINT8)(MAX_CONTROL_DATA_SIZE / sizeof(MEM_BLK)));

    return status;
}

//----------------------------------------------------------------------------
//  USB_ReConfigDevice2
//----------------------------------------------------------------------------
int
USB_ReConfigDevice2(
    HC_STRUC    *fpHCStruc,
    DEV_INFO    *fpDevInfo,
    CNFG_DESC   *fpCnfgDesc,
    INTRF_DESC  *fpIntrfDesc
)
{
//  int             abort=0;
    int             bIndex;
    UINT8               bRetValue = USB_ERROR;
    DEV_DRIVER          *fpDevDriver = NULL;
    DEV_INFO            *fpDevInfoLocal;
    UINT8               bBaseClass, bSubClass, bProtocol;
    EFI_STATUS      EfiStatus;

    USB_DEBUG(DEBUG_LEVEL_3, "USB_ReConfigDevice2.\n");


    EfiStatus = UsbHcStrucValidation(fpHCStruc);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    EfiStatus = UsbDevInfoValidation(fpDevInfo);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }
    
#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)fpCnfgDesc, sizeof(CNFG_DESC));
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
        EfiStatus = AmiValidateMemoryBuffer((VOID*)fpCnfgDesc, fpCnfgDesc->wTotalLength);
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
        EfiStatus = AmiValidateMemoryBuffer((VOID*)fpIntrfDesc, sizeof(INTRF_DESC));
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    //
    // Check for non-compliant device. If non-compliant device found then
    // the descriptor values will get updated depending on the need.
    //
    USBCheckNonCompliantDevice (
        fpHCStruc,
        fpDevInfo,
        (UINT8*)fpCnfgDesc,
        fpCnfgDesc->bDescLength,
        fpCnfgDesc->wTotalLength);

    //
    // Check whether device needs to be disable
    //
    if (fpDevInfo->wIncompatFlags & USB_INCMPT_DISABLE_DEVICE)
    {
        return USB_ERROR;
    }

    //
    // Get the base, sub class & protocol values
    //
    bBaseClass  = fpIntrfDesc->bBaseClass;
    bSubClass   = fpIntrfDesc->bSubClass;
    bProtocol   = fpIntrfDesc->bProtocol;

    //
    // Check for matching device driver
    //
    fpDevInfoLocal = NULL;
    for (bIndex = 0, bRetValue = USB_ERROR;
        bIndex < MAX_DEVICE_TYPES && bRetValue == USB_ERROR; bIndex ++) {
        fpDevDriver = &gUsbData->aDelayedDrivers[bIndex];
        if (!fpDevDriver->bDevType)
            continue;
        if (fpDevDriver->pfnCheckDeviceType){
            bRetValue = (*fpDevDriver->pfnCheckDeviceType)(
                fpDevInfo,bBaseClass,bSubClass,bProtocol);
        }else if((fpDevDriver->bBaseClass == bBaseClass) &&
                (fpDevDriver->bSubClass == bSubClass) &&
                (fpDevDriver->bProtocol == bProtocol)){
            bRetValue = fpDevDriver->bDevType;
        }
    }
    if(bRetValue == USB_ERROR)
        return bRetValue;

    //driver was found

    fpDevInfo->bDeviceType = bRetValue;
    fpDevInfo->fpDeviceDriver = fpDevDriver;
    fpDevInfoLocal = (*fpDevDriver->pfnConfigureDevice)(
        fpHCStruc,fpDevInfo,(UINT8*)fpCnfgDesc,
        (UINT16)(UINTN)((char*)fpIntrfDesc - (char*)fpCnfgDesc),fpCnfgDesc->wTotalLength);
    if (!fpDevInfoLocal)
    {
        USB_DEBUG(DEBUG_LEVEL_0, "USB_ReConfigDevice2: Device specific configure failed.\n");
        return USB_ERROR;
    }
    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   hcnum2hcstruc
//
// Description: Search for the HC_STRUC with specified bHCNumber
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

HC_STRUC*
hcnum2hcstruc(
    UINT8 bHCNumber
)
{
    return gUsbData->HcTable[bHCNumber - 1];
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   prepareForLegacyOS
//
// Description: Changes global state of USBSMI module to function properly
//              in non-EFI OS - without support from EFI drivers
//
//              Before call USB BUS is a driver that handles all devices (
//              except hub) and rest of the drivers are delayed. Number of
//              devices are supported by SUBBUS driver and custom EFI driver
//
//              After call returns, USBBUS driver is removed and all drivers
//              that where
//              delayed became active. All USBBUS devices are reconfigured.
//              Devices that are not supported by now active drivers are decon-
//              figured.
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
prepareForLegacyOS()
{
                                        //(EIP96616)>
    DEV_INFO* di;
    HC_STRUC* fpHCStruc;
    DEV_INFO* e = gUsbData->aDevInfoTable + COUNTOF(gUsbData->aDevInfoTable);
    int status;

    gCheckUsbApiParameter = FALSE;


    //
    //First Reconfigure all USBBUS device (while drivers are in delayed array)
    //
    for( di = &gUsbData->aDevInfoTable[1]; di != e; ++di ){		//(EIP34448)
        if((di->Flag & DEV_INFO_VALIDPRESENT) == DEV_INFO_VALIDPRESENT &&
            di->bDeviceType == BIOS_DEV_TYPE_USBBUS )
        {
            fpHCStruc = hcnum2hcstruc(di->bHCNumber);
            status = USB_ReConfigDevice(fpHCStruc, di );
            if(status == USB_ERROR){
                //
                // Release DEV_INFO
                //
                di->Flag &= ~DEV_INFO_VALIDPRESENT;
            }
        }
		//di->Flag &= ~DEV_INFO_DEV_BUS;
    }
                                        //<(EIP96616)


    USBKeyRepeat(NULL, 1);  // Disable key repeat
    //gUsbData->dUSBStateFlag |= USB_FLAG_RUNNING_UNDER_OS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USB_ResetAndReconfigDev
//
// Description: This routine resets and reconfigures the device.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32
USB_ResetAndReconfigDev(
	HC_STRUC    *HcStruc,
	DEV_INFO    *DevInfo
)
{
	DEV_INFO	*Dev;
	UINT32		Status;
	UINT8		DevAddr;
	UINT8		*Buffer;
    DEV_DESC	*DevDesc;
    CNFG_DESC	*CnfgDesc;
    INTRF_DESC	*IntrfDesc;
	UINT8		ConfigIndx;
	UINT8		IntrfIndx;
	DEV_DRIVER	*DevDriver;
	UINT8		i;
    UINT8       PortStatus;
    UINT8       *DevMiscInfo;
    UINT16      TotalLength;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    gCheckUsbApiParameter = FALSE;

	for (i = 1; i < MAX_DEVICES; i++) {
		Dev = &gUsbData->aDevInfoTable[i];
		if ((Dev->Flag & (DEV_INFO_VALID_STRUC | DEV_INFO_DEV_PRESENT | 
			DEV_INFO_DEV_DUMMY)) != (DEV_INFO_VALID_STRUC | DEV_INFO_DEV_PRESENT)) {
			continue;
		}
		if ((Dev->bHubDeviceNumber == DevInfo->bHubDeviceNumber) && 
			(Dev->bHubPortNumber == DevInfo->bHubPortNumber) &&
			(Dev->bDeviceType != BIOS_DEV_TYPE_USBBUS)) {
			(*gUsbData->aHCDriverTable[GET_HCD_INDEX(
					HcStruc->bHCType)].pfnHCDDeactivatePolling)(HcStruc, Dev);
		}
	}

    Status = (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDDeinitDeviceData)
                                (HcStruc, DevInfo);
	if (Status != USB_SUCCESS) {
		return Status;
	}
	
	Status = USB_ResetHubPort(HcStruc, DevInfo->bHubDeviceNumber, DevInfo->bHubPortNumber);
	if (Status != USB_SUCCESS) {
		return Status;
	}

	Status = USB_EnableHubPort(HcStruc, DevInfo->bHubDeviceNumber, DevInfo->bHubPortNumber);
	if (Status != USB_SUCCESS) {
		return Status;
	}
    
    PortStatus = USB_GetHubPortStatus(HcStruc, DevInfo->bHubDeviceNumber, DevInfo->bHubPortNumber, TRUE);

    if (PortStatus == USB_ERROR) {
        return USB_ERROR;
    }

    if (!(PortStatus & USB_PORT_STAT_DEV_ENABLED)) {
        return USB_ERROR;
    }

    // Initialize HC specific data before device configuration
    Status = (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDInitDeviceData)(
                        HcStruc, DevInfo, PortStatus, &DevMiscInfo);
    if (Status != USB_SUCCESS) {
        return Status;
    }

    DevInfo->DevMiscInfo = (VOID*)DevMiscInfo;

    Buffer = USB_MemAlloc(GET_MEM_BLK_COUNT(sizeof(DEV_DESC)));
    if (Buffer == NULL) {
        return USB_ERROR;
    }

	DevAddr = DevInfo->bDeviceAddress;
	DevInfo->bDeviceAddress = 0;

	DevDesc = (DEV_DESC*)USB_GetDescriptor(HcStruc, DevInfo, Buffer, sizeof(DEV_DESC), 
				DESC_TYPE_DEVICE, 0);
	if(DevDesc == NULL) {
		USB_MemFree(Buffer, GET_MEM_BLK_COUNT(sizeof(DEV_DESC)));
		return USB_ERROR;
	}

	Status = USB_SetAddress(HcStruc, DevInfo, DevAddr);	
	if (Status != USB_SUCCESS) {
		USB_MemFree(DevDesc, GET_MEM_BLK_COUNT(sizeof(DEV_DESC)));
		return Status;
	}	

	DevInfo->bDeviceAddress = DevAddr;

    Buffer = USB_MemAlloc(GET_MEM_BLK_COUNT(MAX_CONTROL_DATA_SIZE));
    if (Buffer == NULL) {
		USB_MemFree(DevDesc, GET_MEM_BLK_COUNT(sizeof(DEV_DESC)));
        return USB_ERROR;
    }

    for (ConfigIndx = 0; ConfigIndx < DevDesc->NumConfigs; ConfigIndx++) {
        CnfgDesc = (CNFG_DESC*)USB_GetDescriptor(HcStruc, DevInfo, Buffer, 
						0xFF, DESC_TYPE_CONFIG, ConfigIndx);
		if (CnfgDesc == NULL) {
			continue;
		}
		TotalLength = CnfgDesc->wTotalLength;
        if (TotalLength > 0xFF) {
            if (TotalLength > (MAX_CONTROL_DATA_SIZE - 1)) {
                TotalLength = MAX_CONTROL_DATA_SIZE - 1;
            }
            CnfgDesc = (CNFG_DESC*)USB_GetDescriptor(HcStruc, DevInfo, Buffer, 
						TotalLength, DESC_TYPE_CONFIG, ConfigIndx);
            if (CnfgDesc == NULL) {
                continue;
            }
        }

        if (CnfgDesc->bDescType == DESC_TYPE_CONFIG) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDEnableEndpoints)(
                        HcStruc, DevInfo, (UINT8*)CnfgDesc);
        }

		USB_SetConfig(HcStruc, DevInfo, CnfgDesc->bConfigValue);
	
		IntrfDesc = (INTRF_DESC*)CnfgDesc;
		for (IntrfIndx = 0; IntrfIndx < CnfgDesc->bNumInterfaces; IntrfIndx++) {
			do {
				IntrfDesc = (INTRF_DESC*)((UINTN)IntrfDesc + IntrfDesc->bDescLength);
				if ((UINTN)IntrfDesc > ((UINTN)CnfgDesc + CnfgDesc->wTotalLength) ||
					(UINTN)IntrfDesc > ((UINTN)CnfgDesc + MAX_CONTROL_DATA_SIZE)) {
					break;
				}
			} while (IntrfDesc->bDescType != DESC_TYPE_INTERFACE);

			if (IntrfDesc->bDescType != DESC_TYPE_INTERFACE) {
				break;
			}

			for (i = 1; i < MAX_DEVICES; i++) {
				Dev = &gUsbData->aDevInfoTable[i];
				if ((Dev->Flag & (DEV_INFO_VALID_STRUC | DEV_INFO_DEV_PRESENT | 
					DEV_INFO_DEV_DUMMY)) != (DEV_INFO_VALID_STRUC | DEV_INFO_DEV_PRESENT)) {
					continue;
				}
				if ((Dev->bHubDeviceNumber == DevInfo->bHubDeviceNumber) && 
					(Dev->bHubPortNumber == DevInfo->bHubPortNumber) &&
					(Dev->bConfigNum == CnfgDesc->bConfigValue) &&
					(Dev->bInterfaceNum == IntrfDesc->bInterfaceNum) &&
					(Dev->bAltSettingNum == IntrfDesc->bAltSettingNum)) {
					break;
				}
			}
			if (i == MAX_DEVICES) {
				continue;
			}

			Dev->wVendorId = DevDesc->VendorId;
			Dev->wDeviceId = DevDesc->DeviceId;

			if (Dev->bDeviceType != BIOS_DEV_TYPE_USBBUS) {
				DevDriver = UsbFindDeviceDriverEntry(Dev->fpDeviceDriver);
                if (DevDriver != NULL) {
    				(*DevDriver->pfnConfigureDevice)(HcStruc, Dev, (UINT8*)CnfgDesc,
    	        		(UINT16)((UINTN)IntrfDesc - (UINTN)CnfgDesc), CnfgDesc->wTotalLength);
                }
			}
		}
	}

	USB_MemFree(DevDesc, GET_MEM_BLK_COUNT(sizeof(DEV_DESC)));
	USB_MemFree(Buffer, GET_MEM_BLK_COUNT(MAX_CONTROL_DATA_SIZE));

	return USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USB_DevDriverDisconnect
//
// Description:  
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32
USB_DevDriverDisconnect(
	HC_STRUC    *HcStruc,
	DEV_INFO    *DevInfo
)
{
	DEV_DRIVER* DevDriver;
	UINT8		Index;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    gCheckUsbApiParameter = FALSE;

	DevDriver = UsbFindDeviceDriverEntry(DevInfo->fpDeviceDriver);

	if (DevDriver && DevDriver->pfnDisconnectDevice) {
		DevDriver->pfnDisconnectDevice(DevInfo);

		DevInfo->bDeviceType = 0;
		DevInfo->fpDeviceDriver = NULL;

		for (Index = 0; Index < MAX_DEVICE_TYPES; Index++) {
			DevDriver = &gUsbData->aDevDriverTable[Index];

			if (DevDriver->bDevType == BIOS_DEV_TYPE_USBBUS) {
				DevInfo->bDeviceType = DevDriver->bDevType;
				DevDriver->pfnConfigureDevice(HcStruc, DevInfo, NULL, 0, 0);
				break;
			}
		}
	} else {
		if (DevInfo->IntInEndpoint) {
			// Stop polling the device's interrupt endpoint
			(*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDDeactivatePolling)
							(HcStruc, DevInfo);
			DevInfo->IntInEndpoint = 0;
		}
	}

	return USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   VALID_DEVINFO
//
// Description:  Checks if DEV_INFO is a valid connected device info
//               Due to hot-plug a DEV_INFO can become invalid in the
//               midle of configuration
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
int VALID_DEVINFO(DEV_INFO* pDevInfo)
{
    return (pDevInfo->Flag & DEV_INFO_VALIDPRESENT)!=0;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   USB_AbortConnectHubChildren
//
// Description: Mark DEV_INFO not valid for all the devices connected to a
//              given hub.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USB_AbortConnectHubChildren(
    UINT8 HubAddr
)
{
    UINT8       i;
    DEV_INFO    *Dev = &gUsbData->aDevInfoTable[1];

    for (i=1;  i<MAX_DEVICES; i++, Dev++) {
        if ((Dev->bHubDeviceNumber == HubAddr) && (Dev->Flag & DEV_INFO_VALIDPRESENT)) {
			Dev->Flag &= ~DEV_INFO_DEV_PRESENT;
			if (!(Dev->Flag & DEV_INFO_MASS_DEV_REGD)) {
            	Dev->Flag &= ~DEV_INFO_VALID_STRUC;
			}

            USB_DEBUG(DEBUG_LEVEL_3, "USB: abort device [%x] connected to hub[%x]\n",
                Dev->bDeviceAddress, HubAddr);

            if (Dev->bDeviceType == BIOS_DEV_TYPE_HUB) {
                USB_AbortConnectHubChildren(Dev->bDeviceAddress);
            }
        }
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   USB_FreeDeviceAddress
//
// Description: This routine releases the given device's address by
//              updating gUsbData->dDeviceAddressMap.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USB_FreeDeviceAddress(
    DEV_INFO    *DevInfo
)
{
    UINT8   i;
    UINT8   Found = 0;

    if (DevInfo->bDeviceAddress)
    {
        for (i=1;  i<MAX_DEVICES; i++) {
            if (gUsbData->aDevInfoTable+i != DevInfo &&
                gUsbData->aDevInfoTable[i].bDeviceAddress == DevInfo->bDeviceAddress)
            {
                Found++;
            }
        }
        if (Found == 0){
            //The DevInfo was the only function with allocated address -
            // return the address to the pool
            gUsbData->DeviceAddressMap |= Shl64(1, DevInfo->bDeviceAddress);
        }
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USB_AbortConnectDev
//
// Description: Mark DEV_INFO not valid and release its device address
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USB_AbortConnectDev(
    DEV_INFO* pDevInfo
)
{
    USB_DEBUG(DEBUG_LEVEL_3, "USB: abort connect [%x].flag = %x\n",
          pDevInfo, pDevInfo->Flag);

	pDevInfo->Flag &= ~DEV_INFO_DEV_PRESENT;

	if (!(pDevInfo->Flag & DEV_INFO_MASS_DEV_REGD)) {
	    pDevInfo->Flag &= ~DEV_INFO_VALID_STRUC;
	    if (pDevInfo->bDeviceAddress == 0) return;

	    USB_FreeDeviceAddress(pDevInfo);
	}

    // Remove children (if any) from aborted parent hub device.
    // Assume the child device has not been connected since
    // the hub has to be connected first.
    if (pDevInfo->bDeviceType == BIOS_DEV_TYPE_HUB) {
        USB_AbortConnectHubChildren(pDevInfo->bDeviceAddress);
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   USB_SmiQueuePut
//
// Description: Puts the pointer pointer into the queue for processing,
//              updates queue head and tail.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USB_SmiQueuePut(VOID * d)
{
    QUEUE_T* q = &gUsbData->QueueCnnctDisc;

    while (q->head >= q->maxsize) {
        q->head -= q->maxsize;
    }

    q->data[q->head++] = d;
    if (q->head == q->maxsize) {
        q->head -= q->maxsize;
    }
    if (q->head == q->tail) {
        //Drop data from queue
        q->tail++;
        while (q->tail >= q->maxsize) {
            q->tail -= q->maxsize;
        }
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:        QueuePutMsg
//
// Description: Add a variable size item to the queue
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USB_SmiQueuePutMsg( QUEUE_T* q, VOID * d, int sz )
{
    EFI_STATUS  Status = EFI_SUCCESS;

    if (q->head + sz > q->maxsize) {
        q->head = 0;
    }
#if USB_RUNTIME_DRIVER_IN_SMM
    Status = AmiValidateMemoryBuffer((VOID*)((UINTN)q->data + q->head), sz);
    if (EFI_ERROR(Status)) {
        return;
    }
#endif
    MemCopy((UINT8*)d, (UINT8*)((UINTN)q->data + q->head), sz);
    q->head += sz;
    if(q->head==q->maxsize) q->head = 0;
    if(q->head==q->tail){
        //Drop data from queue
        q->tail+=sz;
        if( q->tail >= q->maxsize ) q->tail = 0;
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   CheckDeviceLimit
//
// Description: Verifies whether the number of initialized devices of a given
//              class has reached the limit.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

BOOLEAN
CheckDeviceLimit(
    UINT8   BaseClass
)
{
    URP_STRUC Urp;
    UINT8 DevNumber;

    Urp.bFuncNumber = USB_API_CHECK_DEVICE_PRESENCE;
    Urp.bSubFunc = 1;
    Urp.ApiData.ChkDevPrsnc.fpHCStruc = NULL;
    Urp.ApiData.ChkDevPrsnc.bDevType = BaseClass;

    USBAPI_CheckDevicePresence(&Urp);

    if (Urp.bRetValue == USB_SUCCESS)
    {
        DevNumber = Urp.ApiData.ChkDevPrsnc.bNumber;
        if ((BaseClass == BASE_CLASS_HID)
              && ((USB_DEV_HID_COUNT == 0) || (DevNumber == USB_DEV_HID_COUNT)))
        {
            USB_DEBUG(3, "Reached the limit of supported HIDs (%d); skipping this device.\n", USB_DEV_HID_COUNT);
            return TRUE;
        }

        if ((BaseClass == BASE_CLASS_HUB)
              && ((USB_DEV_HUB_COUNT == 0) || (DevNumber == USB_DEV_HUB_COUNT)))
        {
            USB_DEBUG(3, "Reached the limit of supported HUBs (%d); skipping this device.\n", USB_DEV_HUB_COUNT);
            return TRUE;
        }

        if ((BaseClass == BASE_CLASS_MASS_STORAGE)
              && ((USB_DEV_MASS_COUNT == 0) || (DevNumber == USB_DEV_MASS_COUNT)))
        {
            USB_DEBUG(3, "Reached the limit of supported Mass Storage Devices (%d); skipping this device.\n", USB_DEV_MASS_COUNT);
            return TRUE;
        }
        if ((BaseClass == BASE_CLASS_CCID_STORAGE)
              && ((USB_DEV_CCID_COUNT == 0) || (DevNumber == USB_DEV_CCID_COUNT+1)))
        {
            USB_DEBUG(3, "Reached the limit of supported CCID Devices (%d); skipping this device.\n", USB_DEV_CCID_COUNT);
            return TRUE;
        }
    }
    return FALSE;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   UsbControlTransfer
//
// Description: 
//
// Input:  
//
// Output:
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
UsbControlTransfer(
	HC_STRUC*   HcStruc,
    DEV_INFO*	DevInfo,
	DEV_REQ		DevReq,
	UINT16		Timeout,
	VOID*		Buffer)
{
	UINT16	Status;
	UINT16  SavedTimeout;

	SavedTimeout = gUsbData->wTimeOutValue;
	gUsbData->wTimeOutValue = Timeout;

    Status = (*gUsbData->aHCDriverTable[
				GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDControlTransfer)(
                HcStruc,
                DevInfo,
                DevReq.wRequestType,
                DevReq.wIndex,
                DevReq.wValue,
                Buffer,
                DevReq.wDataLength);

	gUsbData->wTimeOutValue = SavedTimeout;

	return DevReq.wDataLength && (Status == 0)? USB_ERROR : USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   UsbInterruptTransfer
//
// Description: This function executes an interrupt transaction on the USB.
//
// Input:  
//  HcStruc     Pointer to HCStruc of the host controller.
//  DevInfo     DeviceInfo structure (if available else 0).
//  EndpointAddress The destination USB device endpoint to which the device request 
//                    is being sent.
//  MaxPktSize  Indicates the maximum packet size the target endpoint is capable 
//              of sending or receiving.
//  Buffer      Buffer containing data to be sent to the device or buffer to be
//              used to receive data.
//  Length      Length request parameter, number of bytes of data to be transferred.
//  Timeout     Indicates the maximum time, in milliseconds, which the transfer 
//              is allowed to complete.
//
// Output: USB_SUCCESS or USB_ERROR
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
UsbInterruptTransfer (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       EndpointAddress,
    UINT16      MaxPktSize,
    VOID        *Buffer,
    UINT16      Length,
    UINT16		Timeout
)
{
    UINT16  SavedTimeout;
    UINT16  BytesTransferred;

    SavedTimeout = gUsbData->wTimeOutValue;
    gUsbData->wTimeOutValue = Timeout;

    BytesTransferred = (*gUsbData->aHCDriverTable[
                GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDInterruptTransfer)(
                HcStruc,
                DevInfo,
                EndpointAddress,
                MaxPktSize,
                Buffer,
                Length);

    gUsbData->wTimeOutValue = SavedTimeout;

    if (BytesTransferred == 0) {
        return USB_ERROR;
    } else {
        return USB_SUCCESS;
    }
    
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   USB_EnableEndpointsDummy
//
// Description: Dummy HC API function used by the HC drivers that do not need
//              to implement enable endpoint function.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USB_EnableEndpointsDummy (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       *Desc
)
{
    return USB_SUCCESS;
}

UINT8
USB_InitDeviceDataDummy (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       PortStatus,
    UINT8       **DeviceData
)
{
    *DeviceData = NULL;
    return USB_SUCCESS;
}

UINT8
USB_DeinitDeviceDataDummy (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo
)
{
    return USB_SUCCESS;
}

										//(EIP54018+)>
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        LocatePwrCapOffset
//
// Description: 
//  This function locate power management capability offset
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
LocatePwrCapOffset (
    IN UINT16 BusDevFunc
)
{
#if USB_RUNTIME_DRIVER_IN_SMM
    UINT16  StatusReg;
    UINT8   CapOffset;
    EFI_PCI_CAPABILITY_HDR CapHeader;

    // Check if device supports extended capabilities
    StatusReg = (UINT16)ReadPCIConfig(BusDevFunc, PCI_STATUS_REGISTER_OFFSET);
    if((StatusReg & PCI_STS_CAPABILITY) == 0) {
        return 0;
    }    
    // Get offset of first capability structure
    CapOffset = (UINT8)ReadPCIConfig(BusDevFunc, EFI_PCI_CAPABILITY_PTR);
    // Check capabilities until PMI is found or no more capabilities
    while (CapOffset) {
        CapHeader.CAP_HDR = (UINT16)ReadPCIConfig(BusDevFunc, CapOffset);
        // If PMI block, return offset 
        if(CapHeader.CapabilityID == PCI_CAP_ID_PMI) {
            return CapOffset;
        }        
        // If not, check for next offset
        CapOffset = CapHeader.NextItemPtr;
    }
#endif
    return 0;
}

#if USB_S5_WAKEUP_SUPPORT
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        ResumePciBridge
//
// Description: 
//  This function resumed PciBridge
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
ResumePciBridge(
    UINT16      BusDevFun
)
{
    UINT32      PmStaCtlReg;
    UINT32      PmCapReg;
    UINT8       PwrCapPtr;
    UINT8       PciCommand;

    PwrCapPtr = LocatePwrCapOffset(BusDevFun);
    
    if (PwrCapPtr) {
        PmCapReg = ReadPCIConfig(BusDevFun, PwrCapPtr);
        PmStaCtlReg = ReadPCIConfig(BusDevFun, PwrCapPtr + 0x04);
        if (PmCapReg & (BIT31 | BIT30)) {
            PmStaCtlReg |= BIT8;
        }
        if (PmStaCtlReg & (BIT0 | BIT1)) {
            PmStaCtlReg &= ~(BIT0 | BIT1);
        }
        DwordWritePCIConfig(BusDevFun, PwrCapPtr + 0x04, PmStaCtlReg);
    }
    
    PciCommand = (UINT8)ReadPCIConfig(BusDevFun, PCI_COMMAND_REGISTER_OFFSET);
    PciCommand |= (PCI_CMD_MEMORY_SPACE + PCI_CMD_BUS_MASTER);
    ByteWritePCIConfig(BusDevFun, PCI_COMMAND_REGISTER_OFFSET, PciCommand);
    
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        StopPciBridge
//
// Description: 
//  This function stopped PciBridge
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
StopPciBridge(
    UINT16      BusDevFun
)
{
    UINT32      PmStaCtlReg;
    UINT8       PwrCapPtr;
    UINT8       PciCommand;
    
    PwrCapPtr = LocatePwrCapOffset(BusDevFun);
    
    if (PwrCapPtr) {
        PmStaCtlReg = ReadPCIConfig(BusDevFun, PwrCapPtr + 0x04);
        PmStaCtlReg |= (BIT0 + BIT1);
        DwordWritePCIConfig(BusDevFun, PwrCapPtr + 0x04, PmStaCtlReg);
    }
    
    PciCommand = (UINT8)ReadPCIConfig(BusDevFun, PCI_COMMAND_REGISTER_OFFSET);
    PciCommand &= (~PCI_CMD_BUS_MASTER);
    ByteWritePCIConfig(BusDevFun, PCI_COMMAND_REGISTER_OFFSET, PciCommand);
    
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        EnablePciBridge
//
// Description: 
//  This function scaned PciBridge
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
ScanPciBridge(
    UINT16      *BridgePciAddr
)
{
    HC_STRUC    *HcStruc;
    UINT8       HcBus[256];
    UINT16      HcBusIndex = 0;
    UINT16      MaxHcBus = 0;
    UINT16      i;
	UINT16	    PciAddr;
    UINT16      PciBus;
    UINT16      PciDev;
    UINT16      PciFun;
    UINT16      BridgeIndex = 255;
    UINT16      DownstreamBus;
    
    for (i = 0; i < gUsbData->HcTableCount; i++) {
        HcStruc = gUsbData->HcTable[i];
        if (HcStruc == NULL) {
            continue;
        }

        if (!(HcStruc->dHCFlag & HC_STATE_USED)) {
        	continue;
        }

        if (HcStruc->dHCFlag & HC_STATE_EXTERNAL) {
            HcBus[HcBusIndex] = (UINT8)(HcStruc->wBusDevFuncNum >> 8);
            if(MaxHcBus < HcBus[HcBusIndex]) {
                MaxHcBus = HcBus[HcBusIndex];
            }
            HcBusIndex++;
        }
    }
    
    for (PciBus = 0; PciBus  < MaxHcBus; PciBus++) {
        for (PciDev = 0; PciDev < 0x20 ; PciDev++) {
            PciAddr = (UINT16)((PciBus << 8) | (PciDev << 3) | 0);  
            if (ReadPCIConfig(PciAddr, PCI_VID) != 0xffffffff) {
                PciFun = ((UINT8)ReadPCIConfig(PciAddr, PCI_HDR) & 0x80) ? 8 : 1;
                do {
                    PciFun--;
                    PciAddr = (UINT16)((PciBus << 8) | (PciDev << 3) | PciFun);
                    if (PciFun != 0) {
                        if (ReadPCIConfig(PciAddr, PCI_VID) == 0xffffffff) {
                            continue;
                        }
                    }
                    if (ReadPCIConfig(PciAddr, PCI_SCC) == 0x0604) {
                        DownstreamBus = (UINT16)ReadPCIConfig(PciAddr, PCI_SBUS);
                        for (i = 0; i < HcBusIndex; i++) {
                            if ((HcBus[i] >= (UINT8)(DownstreamBus)) &&
                                (HcBus[i] <= (UINT8)(DownstreamBus >> 8))) {
                                ResumePciBridge(PciAddr);
                                BridgePciAddr[BridgeIndex] = PciAddr;
                                BridgeIndex--;
                                break;
                            }
                        }
                    }
                } while (PciFun);
            }
        }
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Input:       UsbSuspendHubPort
//
// Description: This function suspends the hub port
//
// Input:     DevInfo   Device info pointer
//
// Output:     Status: EFI_SUCCESS = Success
//                     EFI_DEVICE_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
UsbSuspendHubPort (
    DEV_INFO    *DevInfo
)
{
    UINT32      Index;
    DEV_INFO    *HubDevInfo;
    HC_STRUC    *HcStruc;
	UINT16      OrgTimeOutValue;

    if (DevInfo->bHubDeviceNumber & BIT7) {
        return EFI_SUCCESS;
    }

    for (Index = 1; Index < MAX_DEVICES; Index++) {
        HubDevInfo = &gUsbData->aDevInfoTable[Index];
        if ((HubDevInfo->Flag & DEV_INFO_VALIDPRESENT) != DEV_INFO_VALIDPRESENT) {
			continue;
		}
        if (DevInfo->bHubDeviceNumber == HubDevInfo->bDeviceAddress) {
            HcStruc = gUsbData->HcTable[HubDevInfo->bHCNumber - 1];
            
        	OrgTimeOutValue = gUsbData->wTimeOutValue;
        	gUsbData->wTimeOutValue = USB_SUSPEND_HUB_PORT_TIMEOUT_MS;
            
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(
                    HcStruc->bHCType)].pfnHCDControlTransfer)(
                    HcStruc,
                    HubDevInfo,
                    (UINT16)HUB_RQ_SET_PORT_FEATURE,
                    DevInfo->bHubPortNumber,
                    (UINT16)PortSuspend,
                    0, 0); 
            
            gUsbData->wTimeOutValue = OrgTimeOutValue;
            return EFI_SUCCESS;
        }
    }
    return EFI_DEVICE_ERROR;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        UsbSuspendDevices
//
// Description: 
//  This function suspends usb devices.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
UsbSuspendDevices (
    VOID
)
{
    UINT32      Index;
    DEV_INFO    *DevInfo;
    
    for (Index = MAX_DEVICES; Index > 0; Index--) {

        DevInfo = &gUsbData->aDevInfoTable[Index];
	
        if ((DevInfo->Flag & DEV_INFO_VALIDPRESENT) != DEV_INFO_VALIDPRESENT) {
			continue;
		}
        UsbSuspendHubPort(DevInfo);
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        UsbSuspend
//
// Description: 
//  This function suspend USB
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
UsbSuspend(
    VOID
)
{
    HC_STRUC    *HcStruc;
    DEV_INFO    *DevInfo;
    CNFG_DESC   *CnfgDesc;
    UINT8       *Buffer;
    UINT16      i;
    UINT32      PmStaCtlReg;
    UINT32      PmCapReg;
    UINT16      BridgePciAddr[256];
    UINT32      HcLowBaseAddress;
    UINT32      HcHighBaseAddress;
    UINT16      HcIoAddress;
    UINT16	    OrgTimeOutValue;

    for (i = 0; i < 256; i++) {
        BridgePciAddr[i] = 0;
    }

    ScanPciBridge(BridgePciAddr);

    for (i = 0; i < gUsbData->HcTableCount; i++) {
        HcStruc = gUsbData->HcTable[i];
        if (HcStruc == NULL) {
            continue;
        }

        if (!(HcStruc->dHCFlag & HC_STATE_USED)) {
        	continue;
        }

        HcStruc->PwrCapPtr = LocatePwrCapOffset(HcStruc->wBusDevFuncNum);	
        if (HcStruc->PwrCapPtr) {
            PmCapReg = ReadPCIConfig(HcStruc->wBusDevFuncNum,
                                HcStruc->PwrCapPtr);
            PmStaCtlReg = ReadPCIConfig(HcStruc->wBusDevFuncNum,
                                        HcStruc->PwrCapPtr + 0x04);
            if (PmCapReg & (BIT31 | BIT30)) {
                PmStaCtlReg |= BIT8;
            }
            if (PmStaCtlReg & (BIT0 | BIT1)) {
                PmStaCtlReg &= ~(BIT0 | BIT1);
            }
            DwordWritePCIConfig(HcStruc->wBusDevFuncNum,
                            HcStruc->PwrCapPtr + 0x04, PmStaCtlReg);
		}
        if (HcStruc->bHCType == USB_HC_UHCI) {
            HcIoAddress = (UINT16)ReadPCIConfig(HcStruc->wBusDevFuncNum, USB_IO_BASE_ADDRESS);
            if (HcStruc->BaseAddress != HcIoAddress) {
                WordWritePCIConfig(HcStruc->wBusDevFuncNum,
                        USB_IO_BASE_ADDRESS, (UINT32)HcStruc->BaseAddress);
            }
            ByteWritePCIConfig(HcStruc->wBusDevFuncNum,
	                PCI_CMD, PCI_CMD_IO_SPACE | PCI_CMD_BUS_MASTER);
        } else {       
            HcLowBaseAddress = ReadPCIConfig(HcStruc->wBusDevFuncNum, PCI_BAR0);
            if ((((UINT8)HcLowBaseAddress & (BIT1 |BIT2)) == BIT2) && ((sizeof(VOID*) / sizeof(UINT32)) == 2)) {
                HcHighBaseAddress = ReadPCIConfig(HcStruc->wBusDevFuncNum, PCI_BAR1);
                if(HcStruc->BaseAddress != ((UINTN)(HcLowBaseAddress & 0xFFFFFFF0)) +
                    (Shl64((UINTN)HcHighBaseAddress, 32))) {
                    DwordWritePCIConfig(HcStruc->wBusDevFuncNum,
                        PCI_BAR0, (UINT32)HcStruc->BaseAddress);
                    DwordWritePCIConfig(HcStruc->wBusDevFuncNum,
                        PCI_BAR1, (UINT32)(Shr64(HcStruc->BaseAddress, 32)));
                }
            } else {
                if (HcStruc->BaseAddress != (HcLowBaseAddress & 0xFFFFFFF0)) {
                    DwordWritePCIConfig(HcStruc->wBusDevFuncNum,
                        PCI_BAR0, (UINT32)HcStruc->BaseAddress);
                }
            }
		    ByteWritePCIConfig(HcStruc->wBusDevFuncNum,
	                PCI_CMD, PCI_CMD_MEMORY_SPACE | PCI_CMD_BUS_MASTER);
        }
    }

    // Remove the prsent flag of devices before we reenumerate.
    for (i = 1; i < MAX_DEVICES; i++) {
        DevInfo = &gUsbData->aDevInfoTable[i];
        DevInfo->Flag &= ~DEV_INFO_DEV_PRESENT;
    }

    gUsbData->UsbSetupData.UsbMassDriverSupport = FALSE;
    gUsbData->bHandOverInProgress = FALSE;

    //Start XHCI
    StartControllerType(USB_HC_XHCI);
    //Start EHCI
    StartControllerType(USB_HC_EHCI);
    //Start UHCI
    StartControllerType(USB_HC_UHCI);
    //Start OHCI
    StartControllerType(USB_HC_OHCI);

    //Wait for the usb devices connect.
    FixedDelay(50 * 1000);
    
    USB_EnumerateRootHubPorts(USB_HC_XHCI);
    USB_EnumerateRootHubPorts(USB_HC_EHCI);
    USB_EnumerateRootHubPorts(USB_HC_UHCI);
    USB_EnumerateRootHubPorts(USB_HC_OHCI);
 
    Buffer = USB_MemAlloc(sizeof(CNFG_DESC));

    OrgTimeOutValue = gUsbData->wTimeOutValue;
    gUsbData->wTimeOutValue = 500;
    
    for (i = 1; i < MAX_DEVICES; i++) {

        DevInfo = &gUsbData->aDevInfoTable[i];
        
        if ((DevInfo->Flag & DEV_INFO_VALIDPRESENT) != DEV_INFO_VALIDPRESENT) {
			continue;
		}
        
        if (DevInfo->bDeviceType == BIOS_DEV_TYPE_HUB) {
            continue;
        }
        
        HcStruc = gUsbData->HcTable[DevInfo->bHCNumber - 1];

        CnfgDesc = (CNFG_DESC*)USB_GetDescriptor(
                            HcStruc,
                            DevInfo,
                            Buffer,
                            sizeof(CNFG_DESC),
                            DESC_TYPE_CONFIG,
                            0);

        if (CnfgDesc == NULL) {
            continue;
        }
        
        //Check the device have the capable of remote wakeup
        if (CnfgDesc ->bConfigFlags & BIT5) {
            //Send device wakeup command to the device
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(
                    HcStruc->bHCType)].pfnHCDControlTransfer)(
                    HcStruc,
                    DevInfo,
                    (UINT16)USB_RQ_SET_FEATURE,
                    0,
                    (UINT16)USB_FSEL_DEV_REMOTE_WAKEUP,
                    0, 0); 
        
        }

    }

    gUsbData->wTimeOutValue = OrgTimeOutValue;

    USB_MemFree(Buffer, sizeof(CNFG_DESC));

    UsbSuspendDevices();

    for (i = 0; i < gUsbData->HcTableCount; i++) {
        HcStruc = gUsbData->HcTable[i];
        if (HcStruc == NULL) {
            continue;
        }

        //Global suspend host
        if (HcStruc->dHCFlag & HC_STATE_RUNNING) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(
                HcStruc->bHCType)].pfnHCDGlobalSuspend)(HcStruc);
            if (HcStruc->PwrCapPtr) {
                PmStaCtlReg = ReadPCIConfig(HcStruc->wBusDevFuncNum,
                                        HcStruc->PwrCapPtr + 0x04);
                PmStaCtlReg |= (BIT0 + BIT1);
                DwordWritePCIConfig(HcStruc->wBusDevFuncNum,
                            HcStruc->PwrCapPtr + 0x04, PmStaCtlReg);
            }
        }    
    }

    for (i = 0; i < 256; i++) {
        if (BridgePciAddr[i] != 0) {
            StopPciBridge(BridgePciAddr[i]);
        }
    }

    UsbSbEnablePme();

}

#endif
										//<(EIP54018+)
UINT8
UsbGetDataToggle(
	DEV_INFO	*DevInfo,
	UINT8		EndpointAddr
)
{
    DEV_INFO    *DevInfoToToggle;
    UINT8       ToggleBit = (EndpointAddr & 0xF) - 1;
    UINT16      *DataSync;
    EFI_STATUS  Status;

    if (DevInfo->fpLUN0DevInfoPtr) {
        Status = UsbDevInfoValidation(DevInfo->fpLUN0DevInfoPtr);
        if (EFI_ERROR(Status)) {
            return 0;
        }  
        DevInfoToToggle = DevInfo->fpLUN0DevInfoPtr;
    } else {
        DevInfoToToggle = DevInfo;
    }

    if (EndpointAddr & BIT7) {
        DataSync = &DevInfoToToggle->wDataInSync;
    } else {
        DataSync = &DevInfoToToggle->wDataOutSync;
    }

    return (UINT8)((*DataSync) >> ToggleBit) & 0x1;
}

VOID
UsbUpdateDataToggle(
	DEV_INFO	*DevInfo,
	UINT8		EndpointAddr,
	UINT8		DataToggle
)
{
    DEV_INFO    *DevInfoToToggle;
    UINT8       ToggleBit = (EndpointAddr & 0xF) - 1;
    UINT16      *DataSync;
    EFI_STATUS  Status;

    if (DevInfo->fpLUN0DevInfoPtr) {
        Status = UsbDevInfoValidation(DevInfo->fpLUN0DevInfoPtr);
        if (EFI_ERROR(Status)) {
            return;
        }  
        DevInfoToToggle = DevInfo->fpLUN0DevInfoPtr;
    } else {
        DevInfoToToggle = DevInfo;
    }

    if (EndpointAddr & BIT7) {
        DataSync = &DevInfoToToggle->wDataInSync;
    } else {
        DataSync = &DevInfoToToggle->wDataOutSync;
    }
    
    *DataSync &= (UINT16)~(1 << ToggleBit);
    *DataSync |= (UINT16)(DataToggle << ToggleBit);
    return;
}

//****************************************************************************
//****************************************************************************
//**                                                                        **
//**             (C)Copyright 1985-2016, American Megatrends, Inc.          **
//**                                                                        **
//**                          All Rights Reserved.                          **
//**                                                                        **
//**                 5555 Oakbrook Pkwy, Norcross, GA 30093                 **
//**                                                                        **
//**                          Phone (770)-246-8600                          **
//**                                                                        **
//****************************************************************************
//****************************************************************************