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

//**********************************************************************
//<AMI_FHDR_START>
//
// Name:        XHCI.C
//
// Description: AMI XHCI driver.
//
//<AMI_FHDR_END>
//**********************************************************************

#include "amiusb.h"
#include "amidef.h"
#include "usbdef.h"
#if USB_RUNTIME_DRIVER_IN_SMM
#include <AmiBufferValidationLib.h>
#endif

UINT8   XHCI_Start (HC_STRUC*);
UINT8   XHCI_Stop (HC_STRUC*);
UINT8   XHCI_EnumeratePorts (HC_STRUC*);
UINT8   XHCI_DisableInterrupts (HC_STRUC*);
UINT8   XHCI_EnableInterrupts (HC_STRUC*);
UINT8   XHCI_ProcessInterrupt(HC_STRUC*);
UINT8   XHCI_GetRootHubStatus (HC_STRUC*, UINT8, BOOLEAN);
UINT8   XHCI_DisableRootHub (HC_STRUC*,UINT8);
UINT8   XHCI_EnableRootHub (HC_STRUC*,UINT8);
UINT16  XHCI_ControlTransfer (HC_STRUC*,DEV_INFO*,UINT16,UINT16,UINT16,UINT8*,UINT16);
UINT32  XHCI_BulkTransfer (HC_STRUC*,DEV_INFO*,UINT8,UINT8*,UINT32);
UINT16  XHCI_InterruptTransfer (HC_STRUC*, DEV_INFO*, UINT8, UINT16, UINT8*, UINT16);
UINT8   XHCI_DeactivatePolling (HC_STRUC*,DEV_INFO*);
UINT8   XHCI_ActivatePolling (HC_STRUC*,DEV_INFO*);
UINT8   XHCI_DisableKeyRepeat (HC_STRUC*);
UINT8   XHCI_EnableKeyRepeat (HC_STRUC*);
UINT8   XHCI_EnableEndpoints (HC_STRUC*, DEV_INFO*, UINT8*);
UINT8   XHCI_InitDeviceData (HC_STRUC*,DEV_INFO*,UINT8,UINT8**);
UINT8   XHCI_DeinitDeviceData (HC_STRUC*,DEV_INFO*);
UINT8   XHCI_ResetRootHub (HC_STRUC*,UINT8);
UINT8	XHCI_ClearEndpointState(HC_STRUC*,DEV_INFO*,UINT8);		//(EIP54283+)
UINT8   XHCI_GlobalSuspend (HC_STRUC*);	//(EIP54018+)

UINT8		XHCI_WaitForEvent(HC_STRUC*,XHCI_TRB*,TRB_TYPE,UINT8,UINT8,UINT8*,UINT16,VOID*);
TRB_RING*   XHCI_InitXfrRing(USB3_HOST_CONTROLLER*, UINT8, UINT8);
TRB_RING*   XHCI_GetXfrRing(USB3_HOST_CONTROLLER*, UINT8, UINT8);
UINT8       XHCI_GetSlotId(USB3_HOST_CONTROLLER*, DEV_INFO*);
UINT64      XHCI_Mmio64Read(HC_STRUC*, USB3_HOST_CONTROLLER*, UINTN);
VOID        XHCI_Mmio64Write(HC_STRUC*, USB3_HOST_CONTROLLER*, UINTN, UINT64);
EFI_STATUS  XHCI_InitRing(TRB_RING*, UINTN, UINT32, BOOLEAN);
UINT32*     XHCI_GetTheDoorbell(USB3_HOST_CONTROLLER*, UINT8);
VOID        UpdatePortStatusSpeed(UINT8, UINT8*);
UINT8		XHCI_ResetPort(USB3_HOST_CONTROLLER*, UINT8, BOOLEAN);
BOOLEAN		XHCI_IsUsb3Port(USB3_HOST_CONTROLLER*, UINT8);
UINT8       XhciRingDoorbell(USB3_HOST_CONTROLLER*, UINT8, UINT8);
EFI_STATUS  XhciExtCapParser(USB3_HOST_CONTROLLER*);
UINT8		XhciAddressDevice (HC_STRUC*, DEV_INFO*, UINT8);

DEV_INFO*   XHCI_GetDevInfo(UINTN);
VOID*		XHCI_GetDeviceContext(USB3_HOST_CONTROLLER*, UINT8);
VOID*		XHCI_GetContextEntry(USB3_HOST_CONTROLLER*, VOID*, UINT8);

UINT8		UsbHubGetHubDescriptor(HC_STRUC*, DEV_INFO*, VOID*, UINT16);

VOID 		MemFill (UINT8*, UINT32, UINT8);
UINT8		USB_ResetHubPort(HC_STRUC*, UINT8, UINT8);
UINT8		USB_DisconnectDevice (HC_STRUC*, UINT8, UINT8);
UINT8       USB_GetHubPortStatus(HC_STRUC*, UINT8, UINT8, BOOLEAN);

UINT32		ReadPCIConfig(UINT16, UINT8);

VOID	    USBKeyRepeat(HC_STRUC*, UINT8);

extern  USB_GLOBAL_DATA     *gUsbData;
extern  BOOLEAN gCheckUsbApiParameter;

#if USB_DEV_KBD
VOID    USBKBDPeriodicInterruptHandler(HC_STRUC*);
#endif

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_FillHCDEntries
//
// Description:
//  This function fills the host controller driver routine pointers.
//
// Input:
//  Ptr to the host controller header structure
//
// Output:
//  Status: USB_SUCCESS = Success, USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_FillHCDEntries (
    HCD_HEADER *fpHCDHeader
)
{
    fpHCDHeader->pfnHCDStart                = XHCI_Start;
    fpHCDHeader->pfnHCDStop                 = XHCI_Stop;
    fpHCDHeader->pfnHCDEnumeratePorts       = XHCI_EnumeratePorts;
    fpHCDHeader->pfnHCDDisableInterrupts    = XHCI_DisableInterrupts;
    fpHCDHeader->pfnHCDEnableInterrupts     = XHCI_EnableInterrupts;
    fpHCDHeader->pfnHCDProcessInterrupt     = XHCI_ProcessInterrupt;
    fpHCDHeader->pfnHCDGetRootHubStatus     = XHCI_GetRootHubStatus;
    fpHCDHeader->pfnHCDDisableRootHub       = XHCI_DisableRootHub;
    fpHCDHeader->pfnHCDEnableRootHub        = XHCI_EnableRootHub;
    fpHCDHeader->pfnHCDControlTransfer      = XHCI_ControlTransfer;
    fpHCDHeader->pfnHCDBulkTransfer         = XHCI_BulkTransfer;
    fpHCDHeader->pfnHCDInterruptTransfer    = XHCI_InterruptTransfer;
    fpHCDHeader->pfnHCDDeactivatePolling    = XHCI_DeactivatePolling;
    fpHCDHeader->pfnHCDActivatePolling      = XHCI_ActivatePolling;
    fpHCDHeader->pfnHCDDisableKeyRepeat     = XHCI_DisableKeyRepeat;
    fpHCDHeader->pfnHCDEnableKeyRepeat      = XHCI_EnableKeyRepeat;
    fpHCDHeader->pfnHCDEnableEndpoints      = XHCI_EnableEndpoints;
    fpHCDHeader->pfnHCDInitDeviceData       = XHCI_InitDeviceData;
    fpHCDHeader->pfnHCDDeinitDeviceData     = XHCI_DeinitDeviceData;
	fpHCDHeader->pfnHCDResetRootHub         = XHCI_ResetRootHub;
	fpHCDHeader->pfnHCDClearEndpointState	= XHCI_ClearEndpointState;	//(EIP54283+)
	fpHCDHeader->pfnHCDGlobalSuspend        = XHCI_GlobalSuspend;	//(EIP54018+)

    return  USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_Start
//
// Description:
//  This API function is called to start a XHCI host controller. The input
//  to the routine is the pointer to the HC structure that defines this host
//  controller. The procedure flow is followed as it is described in 4.2 of
//  XHCI specification.
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_SUCCESS = Success, USB_ERROR = Failure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_Start (
    HC_STRUC    *HcStruc
)
{
    XHCI_INTERRUPTER_REGS   *Interrupter;
    XHCI_ER_SEGMENT_ENTRY   *Erst0Entry;
    UINT32      i;
    BOOLEAN     PpSet = FALSE;
    UINT8       PortNumber;
    volatile XHCI_PORTSC *PortSC;
	UINT32		LegCtlStsReg = 0;
    EFI_STATUS  EfiStatus = EFI_SUCCESS;

    USB3_HOST_CONTROLLER *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    HcStruc->BaseAddress = (UINTN)Usb3Hc->CapRegs;
    HcStruc->bNumPorts = Usb3Hc->MaxPorts;

#if USB_RUNTIME_DRIVER_IN_SMM
    EfiStatus = AmiValidateMmioBuffer((VOID*)HcStruc->BaseAddress, HcStruc->BaseAddressSize);
    if (EFI_ERROR(EfiStatus)) {
        USB_DEBUG(3, "Usb Mmio address is invalid, it is in SMRAM\n");
        return USB_ERROR;
    }
#endif

    if (((VOID*)Usb3Hc->OpRegs < (VOID*)HcStruc->BaseAddress) ||
        ((VOID*)(Usb3Hc->OpRegs + sizeof(XHCI_HC_OP_REGS)) > (VOID*)(HcStruc->BaseAddress + HcStruc->BaseAddressSize))) {
        return USB_ERROR;
    }

	// Wait controller ready
	for (i = 0; i < 1000; i++) {
        if (Usb3Hc->OpRegs->UsbSts.Field.Cnr == 0) break;
		FixedDelay(100);        // 100 us delay
    }
//    ASSERT(Usb3Hc->OpRegs->UsbSts.Field.Cnr == 0);
	if (Usb3Hc->OpRegs->UsbSts.Field.Cnr) return USB_ERROR;

	// Check if the xHC is halted
	if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted == 0) {
		Usb3Hc->OpRegs->UsbCmd.AllBits &= ~XHCI_CMD_RS;
		// The xHC should halt within 16 ms. Section 5.4.1.1
		for (i = 0; i < 160; i++) {
        	if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) break;
            FixedDelay(100);        // 100 us delay
		}
		ASSERT(Usb3Hc->OpRegs->UsbSts.Field.HcHalted);
		if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted == 0) return USB_ERROR;
	}
#if XHCI_COMPLIANCE_MODE_WORKAROUND
	for (PortNumber = 1; PortNumber <= Usb3Hc->MaxPorts; PortNumber++) {
		PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
								XHCI_PORTSC_OFFSET + (0x10 * (PortNumber - 1)));
#if USB_RUNTIME_DRIVER_IN_SMM
        EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
#endif
        if (PortSC->Field.Pls == XHCI_PORT_LINK_COMPLIANCE_MODE) {
            XHCI_ResetPort(Usb3Hc, PortNumber, FALSE);
        }
	}
#endif
    // Reset controller
    if ((Usb3Hc->DbCapRegs == NULL) || (Usb3Hc->DbCapRegs->DcCtrl.Dce == 0)) {
        Usb3Hc->OpRegs->UsbCmd.AllBits |= XHCI_CMD_HCRST;
        for (i = 0; i < 8000; i++) {
            if (Usb3Hc->OpRegs->UsbCmd.Field.HcRst == 0) {
                break;
            }
            FixedDelay(100);    // 100 us delay
        }
        ASSERT(Usb3Hc->OpRegs->UsbCmd.Field.HcRst == 0);
        if (Usb3Hc->OpRegs->UsbCmd.Field.HcRst) {
            return USB_ERROR;  // Controller can not be reset
        }
    }

    if ((Usb3Hc->CapRegs->RtsOff + (sizeof(UINT32) * 8) + (sizeof(XHCI_INTERRUPTER_REGS) * Usb3Hc->CapRegs->HcsParams1.MaxIntrs)) 
        > HcStruc->BaseAddressSize) {
        return USB_ERROR;
    }

    Usb3Hc->RtRegs = (XHCI_HC_RT_REGS*)((UINTN)Usb3Hc->CapRegs + Usb3Hc->CapRegs->RtsOff);
    USB_DEBUG(3, "XHCI: RT registers are at %x\n", Usb3Hc->RtRegs);

    Usb3Hc->OpRegs->Config = Usb3Hc->MaxSlots;  // Max device slots enabled

    XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->DcbAap, (UINT64)(UINTN)Usb3Hc->DcbaaPtr);

	// Check if xHC support 64bit access capability
	if (Usb3Hc->Access64) {
		if(XHCI_Mmio64Read(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->DcbAap) != (UINT64)(UINTN)Usb3Hc->DcbaaPtr) {
			Usb3Hc->Access64 = 0;
			XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->DcbAap, (UINT64)(UINTN)Usb3Hc->DcbaaPtr);
		}
	}
	
    // Define the Command Ring Dequeue Pointer by programming the Command Ring
    // Control Register (5.4.5) with a 64-bit address pointing to the starting
    // address of the first TRB of the Command Ring.

    // Initialize Command Ring Segment: Size TRBS_PER_SEGMENT*16, 64 Bytes aligned
    XHCI_InitRing(&Usb3Hc->CmdRing, (UINTN)Usb3Hc->DcbaaPtr + 0x2000, TRBS_PER_SEGMENT, TRUE);
    USB_DEBUG(3, "CMD Ring is at %x\n", (UINTN)&Usb3Hc->CmdRing);

    // Write CRCR HC register with the allocated address. Set Ring Cycle State to 1.
    XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->Crcr,
            (UINT64)(UINTN)Usb3Hc->CmdRing.Base + CRCR_RING_CYCLE_STATE);

    // Initialize and assign Event Ring
    XHCI_InitRing(&Usb3Hc->EvtRing, (UINTN)Usb3Hc->DcbaaPtr + 0x2400, TRBS_PER_SEGMENT, FALSE);
    USB_DEBUG(3, "EVT Ring is at %x\n", (UINTN)&Usb3Hc->EvtRing);

    // NOTE: This driver supports one Interrupter, hence it uses
    // one Event Ring segment with TRBS_PER_SEGMENT TRBs in it.

    // Initialize ERST[0]
    Erst0Entry = (XHCI_ER_SEGMENT_ENTRY*)((UINTN)Usb3Hc->DcbaaPtr + 0x1200);
    Erst0Entry->RsBase = (UINT64)(UINTN)Usb3Hc->EvtRing.Base;
    Erst0Entry->RsSize = TRBS_PER_SEGMENT;

    Interrupter = Usb3Hc->RtRegs->IntRegs;

    // Initialize Interrupter fields
    Interrupter->Erstz = 1; // # of segments
    // ER dequeue pointer
    XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Interrupter->Erdp, (UINT64)(UINTN)Usb3Hc->EvtRing.QueuePtr);
    // Seg Table location
    XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Interrupter->Erstba, (UINT64)(UINTN)Erst0Entry);
    Interrupter->IMod = XHCI_IMODI; // Max interrupt rate
    Usb3Hc->OpRegs->UsbCmd.AllBits |= XHCI_CMD_INTE;
    Interrupter->IMan |= 2;         // Enable interrupt

    USB_DEBUG(3, "Transfer Rings structures start at %x\n", Usb3Hc->XfrRings);

    // Set PortPower unless PowerPortControl indicates otherwise
    if (Usb3Hc->CapRegs->HccParams1.Ppc != 0) {
		for (PortNumber = 1; PortNumber <= Usb3Hc->MaxPorts; PortNumber++) {
			PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
								XHCI_PORTSC_OFFSET + (0x10 * (PortNumber - 1)));
#if USB_RUNTIME_DRIVER_IN_SMM
            EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
            if (EFI_ERROR(EfiStatus)) {
                return USB_ERROR;
            }
#endif
            if (PortSC->Field.Pp == 0) {
                PortSC->Field.Pp = 1; // Set port power
                PpSet = TRUE;
            }
        }
        if (PpSet) FixedDelay(20 * 1000);   // Wait for 20 ms, Section 5.4.8
    }

	// If xHC doesn't support HW SMI, should not touch USB Legacy Support Capability registers
	//if (((HcStruc->dHCFlag & HC_STATE_EXTERNAL) && (XHCI_EVENT_SERVICE_MODE == 0)) ||
	//	(USB_RUNTIME_DRIVER_IN_SMM == 0)) {
	//	Usb3Hc->ExtLegCap = NULL;
	//}
		
    // Check if USB Legacy Support Capability is present.
	if (Usb3Hc->ExtLegCap) {
		// Set HC BIOS Owned Semaphore flag
		Usb3Hc->ExtLegCap->LegSup.HcBiosOwned = 1;
        //If XHCI doesn't support HW SMI, should not enable USB SMI in Legacy Support Capability register.
        if (((!(HcStruc->dHCFlag & HC_STATE_EXTERNAL)) || (XHCI_EVENT_SERVICE_MODE != 0)) &&
            (USB_RUNTIME_DRIVER_IN_SMM != 0)) {
    		// Enable USB SMI, Ownership Change SMI and clear all status
    		LegCtlStsReg = Usb3Hc->ExtLegCap->LegCtlSts.AllBits;
    		LegCtlStsReg |= XHCI_SMI_ENABLE | XHCI_SMI_OWNERSHIP_CHANGE_ENABLE | 
    						XHCI_SMI_OWNERSHIP_CHANGE | XHCI_SMI_PCI_CMD | XHCI_SMI_PCI_BAR;
    		Usb3Hc->ExtLegCap->LegCtlSts.AllBits = LegCtlStsReg;
        }
    }

    Usb3Hc->OpRegs->UsbCmd.AllBits |= XHCI_CMD_RS;

	for (i = 0; i < 100; i++) {
        if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted == 0) {
            break;
        }
        FixedDelay(100);
	}
    ASSERT(Usb3Hc->OpRegs->UsbSts.Field.HcHalted == 0);

    HcStruc->dHCFlag |= HC_STATE_RUNNING;

    // Set USB_FLAG_DRIVER_STARTED flag when HC is running.
    if (!(gUsbData->dUSBStateFlag & USB_FLAG_DRIVER_STARTED)) {
        gUsbData->dUSBStateFlag |= USB_FLAG_DRIVER_STARTED;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
	if (!(HcStruc->dHCFlag & HC_STATE_EXTERNAL)) {
        UsbInstallHwSmiHandler(HcStruc);
    } else {
        USBSB_InstallXhciHwSmiHandler();
    }
    if (HcStruc->HwSmiHandle != NULL) {
        USBKeyRepeat(HcStruc, 0);
    }
#endif

    return  USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_Stop
//
// Description:
//  This function stops the XHCI controller.
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_SUCCESS or USB_ERROR
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_Stop (
    HC_STRUC    *HcStruc
)
{
	UINT8   Port;
    UINT32  i;
    USB3_HOST_CONTROLLER *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
	XHCI_INTERRUPTER_REGS   *Interrupter = NULL;
	UINT32	LegCtlStsReg = 0;
	UINT8	CompletionCode = 0;
	EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }


    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }

	// Set the flag to aviod port enumeration
	gUsbData->bEnumFlag = TRUE;     // disable recursive enumeration

	for (Port = 1; Port <= Usb3Hc->MaxPorts; Port++) {
		USB_DisconnectDevice(HcStruc, HcStruc->bHCNumber | BIT7, Port);
	}

	// Port Change Detect bit may set by disabling ports.
	//Usb3Hc->OpRegs->UsbSts.AllBits = XHCI_STS_PCD;

	if (XHCI_Mmio64Read(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->Crcr) & CRCR_COMMAND_RUNNING) {
		// Stop the command ring
		XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->Crcr, CRCR_COMMAND_STOP);

		CompletionCode = XHCI_TRB_CMDRINGSTOPPED;
		XHCI_WaitForEvent(
			HcStruc, NULL, XhciTCmdCompleteEvt, 0, 0,
			&CompletionCode, XHCI_CMD_COMPLETE_TIMEOUT_MS, NULL);
	}

	XHCI_ProcessInterrupt(HcStruc);

	// Clear the port enumeration flag
	gUsbData->bEnumFlag = FALSE;

	// Disable interrupt
    Usb3Hc->OpRegs->UsbCmd.AllBits &= ~XHCI_CMD_INTE;
	Interrupter = Usb3Hc->RtRegs->IntRegs;
	Interrupter->IMan &= ~BIT1;

	// Clear the Run/Stop bit
    Usb3Hc->OpRegs->UsbCmd.AllBits &= ~XHCI_CMD_RS;

	// The xHC should halt within 16 ms. Section 5.4.1.1
    for (i = 0; i < 160; i++) {
        if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) break;
        FixedDelay(100);
    }
	ASSERT(Usb3Hc->OpRegs->UsbSts.Field.HcHalted);
    //if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted == 0) return USB_ERROR;

    // Check if USB Legacy Support Capability is present.
    if(Usb3Hc->ExtLegCap != 0) {
		// Clear HC BIOS Owned Semaphore flag
		Usb3Hc->ExtLegCap->LegSup.HcBiosOwned = 0;
        if (((!(HcStruc->dHCFlag & HC_STATE_EXTERNAL)) || (XHCI_EVENT_SERVICE_MODE != 0)) &&
            (USB_RUNTIME_DRIVER_IN_SMM != 0)) {		
    		// Disable USB SMI and Clear all status
    		LegCtlStsReg = Usb3Hc->ExtLegCap->LegCtlSts.AllBits;
    		LegCtlStsReg &= ~XHCI_SMI_ENABLE;
    		LegCtlStsReg |= XHCI_SMI_OWNERSHIP_CHANGE | XHCI_SMI_PCI_CMD | XHCI_SMI_PCI_BAR;
    		Usb3Hc->ExtLegCap->LegCtlSts.AllBits = LegCtlStsReg;
        }
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    if (HcStruc->HwSmiHandle != NULL) {
        USBKeyRepeat(HcStruc, 3);
    }
#endif  
  
    // Set the HC state to stopped
    HcStruc->dHCFlag  &= ~(HC_STATE_RUNNING);

    CheckBiosOwnedHc();

    return  USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_EnumeratePorts
//
// Description:
//  This function enumerates the HC ports for devices.
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_SUCCESS or USB_ERROR
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_EnumeratePorts(
    HC_STRUC    *HcStruc
)
{
										//(EIP60327)>
	UINT8	Count;
    UINT8   Port;
    USB3_HOST_CONTROLLER *Usb3Hc;
    EFI_STATUS  EfiStatus;

    if (gUsbData->bEnumFlag == TRUE) {
        return USB_SUCCESS;
    }

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;;
    }
     
	USB_DEBUG(3, "XHCI_EnumeratePorts..\n");
    gUsbData->bIgnoreConnectStsChng = TRUE; //(EIP71962+)
    gUsbData->bEnumFlag = TRUE;     // disable recursive enumeration

	if (Usb3Hc->Usb2Protocol) {
		for(Count = 0; Count < Usb3Hc->Usb2Protocol->PortCount; Count++) {
			Port = Count + Usb3Hc->Usb2Protocol->PortOffset;
			USBCheckPortChange(HcStruc, HcStruc->bHCNumber | BIT7, Port);
		}
	}

	if (Usb3Hc->Usb3Protocol) {
		for(Count = 0; Count < Usb3Hc->Usb3Protocol->PortCount; Count++) {
			Port = Count + Usb3Hc->Usb3Protocol->PortOffset;
			if (Usb3Hc->Vid == XHCI_VL800_VID && Usb3Hc->Did == XHCI_VL800_DID) {
				XHCI_ResetPort(Usb3Hc, Port , TRUE);
			}
			USBCheckPortChange(HcStruc, HcStruc->bHCNumber | BIT7, Port);
		}
	}
	
//	Usb3Hc->OpRegs->UsbSts.AllBits = XHCI_STS_PCD;	// Clear PortChangeDetect

    gUsbData->bIgnoreConnectStsChng = FALSE;    //(EIP71962+)
    gUsbData->bEnumFlag = FALSE;    // enable enumeration

	XHCI_ProcessInterrupt(HcStruc);
										//<(EIP60327)
    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_EnableInterrupts
//
// Description:
//  This function enables the HC interrupts
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_ERROR   On error, USB_SUCCESS On success
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_EnableInterrupts (
    HC_STRUC* HcStruc
)
{
    return  USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_DisableInterrupts
//
// Description:
//  This function disables the HC interrupts
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_ERROR on error, USB_SUCCESS on success
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_DisableInterrupts (
    HC_STRUC* HcStruc
)
{
    return  USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_AdvanceEnqueuePtr
//
// Description:
//  This function advances returns the pointer to the current TRB and anvances
//  dequeue pointer. If the advance pointer is Link TRB, then it: 1) activates
//  Link TRB by updating its cycle bit, 2) updates dequeue pointer to the value
//  pointed by Link TRB.
//
// Input:
//  Ring - TRB ring to be updated
//
// Output:
//  TRB that can be used for command, transfer, etc.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

XHCI_TRB*
XHCI_AdvanceEnqueuePtr(
    TRB_RING    *Ring
)
{
    XHCI_TRB* Trb = Ring->QueuePtr;
    EFI_STATUS  Status = EFI_SUCCESS;

    if (Trb->TrbType == XhciTLink) {
        Trb->CycleBit = Ring->CycleBit;
        Ring->CycleBit ^= 1;
        Ring->QueuePtr = Ring->Base;

        Trb = Ring->QueuePtr;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    Status = AmiValidateMemoryBuffer((VOID*)Trb, sizeof(XHCI_TRB));
    if (EFI_ERROR(Status)) {
        return NULL;
    }
#endif
    // Clear the TRB
    *(UINT32*)Trb = 0;
	*((UINT32*)Trb + 1) = 0;
	*((UINT32*)Trb + 2) = 0;
	*((UINT32*)Trb + 3) &= BIT0;	// Keep cycle bit

    //Trb->CycleBit = Ring->CycleBit;
    Ring->QueuePtr++;

    return Trb;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_WaitForEvent
//
// Description:
//  This function walks through the active TRBs in the event ring and looks for
//  the command TRB to be complete. If found, returns SlotId and CompletionCode
//  from the completed event TRB. In the end it processes the event ring,
//  adjusting its Dequeue Pointer.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
										//(EIP62376)>
UINT8
XHCI_WaitForEvent(
    HC_STRUC    *HcStruc,
    XHCI_TRB    *TrbToCheck,
    TRB_TYPE    EventType,
    UINT8		SlotId,
    UINT8		Dci,
    UINT8       *CompletionCode,
    UINT16      TimeOutMs,
    VOID        *Data
)
{
    USB3_HOST_CONTROLLER *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    XHCI_TRB    *Trb;
    UINT32      Count;
    UINT8       Status;
    UINT8       CycleBit;
	UINT32		TimeoutValue = ((UINT32)TimeOutMs) * 100;	// in 10 macrosecond unit
    XHCI_NORMAL_XFR_TRB		*ResidualTrb;					//(EIP82555+)
    EFI_STATUS  EfiStatus = EFI_SUCCESS;
	
    for (Count = 0; TimeoutValue == 0 || Count < TimeoutValue; Count++) {
        for (Trb = Usb3Hc->EvtRing.QueuePtr,
			CycleBit = Usb3Hc->EvtRing.CycleBit;;) {
#if USB_RUNTIME_DRIVER_IN_SMM
            EfiStatus = AmiValidateMemoryBuffer((VOID*)Trb, sizeof(XHCI_TRB));
            if (EFI_ERROR(EfiStatus)) {
                break;
            }
#endif
            if (Trb->CycleBit != CycleBit) {
                // Command is not complete, break and retry
                break;
            }

            // Active TRB found
            if (Trb->TrbType == EventType) {
				if (EventType == XhciTCmdCompleteEvt) {
					if (TrbToCheck) {
						if((*(UINTN*)&Trb->Param1) == (UINTN)TrbToCheck) {
							if (Data != NULL) {
								*(UINT8*)Data = ((XHCI_CMDCOMPLETE_EVT_TRB*)Trb)->SlotId;
							}
							*CompletionCode = Trb->CompletionCode;
							Status = Trb->CompletionCode == XHCI_TRB_SUCCESS? USB_SUCCESS:USB_ERROR;
							goto DoneWaiting;
						}
					} else {
						if (*CompletionCode != 0 && Trb->CompletionCode == *CompletionCode) {
							Status = USB_SUCCESS;
							goto DoneWaiting;
						}
					}
				} else if (EventType == XhciTTransferEvt) {
					if (((XHCI_TRANSFER_EVT_TRB*)Trb)->SlotId == SlotId &&
						((XHCI_TRANSFER_EVT_TRB*)Trb)->EndpointId == Dci) {
                        if (Data != NULL) {
                            *(UINT32*)Data = ((XHCI_TRANSFER_EVT_TRB*)Trb)->TransferLength;
                                        //(EIP82555+)>
                            if (Trb->CompletionCode == XHCI_TRB_SHORTPACKET) {
                                ResidualTrb = (XHCI_NORMAL_XFR_TRB*)(UINTN)((XHCI_TRANSFER_EVT_TRB*)Trb)->TrbPtr;
                                  while (1) {
                                    ResidualTrb->Isp = 0;
                                    ResidualTrb->Ioc = 0;
                                    if (ResidualTrb->Chain != 1) {
                                        break;
                                    }                                  
                                    ResidualTrb++;
                                    if (ResidualTrb->TrbType == XhciTLink) {
                                        ResidualTrb = (XHCI_NORMAL_XFR_TRB*)(UINTN)((XHCI_LINK_TRB*)ResidualTrb)->NextSegPtr;
                                    }
                                    *(UINT32*)Data += ResidualTrb->XferLength;
                                }
                             }
                                        //<(EIP82555+)
                        }
						*CompletionCode = Trb->CompletionCode;
						Status = (Trb->CompletionCode == XHCI_TRB_SUCCESS ||
							Trb->CompletionCode == XHCI_TRB_SHORTPACKET)? USB_SUCCESS:USB_ERROR;
						goto DoneWaiting;
					}
				}
            }
            // Advance TRB pointer
            if (Trb == Usb3Hc->EvtRing.LastTrb) {
                Trb = Usb3Hc->EvtRing.Base;
                CycleBit ^= 1;
            } else {
                Trb++;
            }
            if (Trb == Usb3Hc->EvtRing.QueuePtr) {
                // Event ring is full, return error
                USB_DEBUG(3, "XHCI: Event Ring is full...\n");
                ASSERT(0);
                *CompletionCode = XHCI_TRB_EVENTRINGFULL_ERROR;
                Status = USB_ERROR;
                break;
            }
        }
        FixedDelay(10);    // 10 us out of TimeOutMs
    }

    USB_DEBUG(3, "XHCI: execution time-out.\n");

    *CompletionCode = XHCI_TRB_EXECUTION_TIMEOUT_ERROR;
    Status = USB_ERROR;

DoneWaiting:
    XHCI_ProcessInterrupt(HcStruc);

    return Status;
}
										//<(EIP62376)

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ExecuteCommand
//
// Description:
//  This function places a given command in the Command Ring, rings HC doorbell,
//  and waits for the command completion.
//
// Output:
//  USB_ERROR on execution failure, otherwise USB_SUCCESS
//  Params - pointer to the command specific data.
//
// Notes:
//  Caller is responsible for a data placeholder.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ExecuteCommand(
    HC_STRUC    *HcStruc,
    TRB_TYPE    Cmd,
    VOID        *Params
)
{
    volatile UINT32      *Doorbell;
    UINT8       CompletionCode = 0;
    UINT8       SlotId;
    UINT8       Status;
    USB3_HOST_CONTROLLER *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
    XHCI_TRB    *Trb = XHCI_AdvanceEnqueuePtr(&Usb3Hc->CmdRing);
	UINT16		TimeOut = XHCI_CMD_COMPLETE_TIMEOUT_MS;
    EFI_STATUS  EfiStatus = EFI_SUCCESS;

    if (Trb == NULL) {
        return USB_ERROR;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    EfiStatus = AmiValidateMemoryBuffer((VOID*)Trb, sizeof(XHCI_TRB));
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;;
    }    
#endif

    Trb->TrbType = Cmd; // Set TRB type

    // Fill in the command TRB fields
    switch (Cmd) {
        case XhciTAddressDeviceCmd:
            TimeOut = XHCI_ADDR_CMD_COMPLETE_TIMEOUT_MS;
            ((XHCI_ADDRESSDEV_CMD_TRB*)Trb)->InpCtxAddress = (UINT64)(UINTN)Usb3Hc->InputContext;
            ((XHCI_ADDRESSDEV_CMD_TRB*)Trb)->SlotId = *((UINT8*)Params);
            ((XHCI_ADDRESSDEV_CMD_TRB*)Trb)->Bsr = *((UINT8*)Params + 1);
            break;
        case XhciTEvaluateContextCmd:
        case XhciTConfigureEndpointCmd:
            ((XHCI_CONFIGURE_EP_CMD_TRB*)Trb)->InpCtxAddress = (UINT64)(UINTN)Usb3Hc->InputContext;
            ((XHCI_CONFIGURE_EP_CMD_TRB*)Trb)->SlotId = *((UINT8*)Params);
            ((XHCI_CONFIGURE_EP_CMD_TRB*)Trb)->Dc = 0;
            break;
        case XhciTResetEndpointCmd:
			((XHCI_RESET_EP_CMD_TRB*)Trb)->Tsp = 0;
            ((XHCI_RESET_EP_CMD_TRB*)Trb)->SlotId = *((UINT8*)Params);
            ((XHCI_RESET_EP_CMD_TRB*)Trb)->EndpointId = *((UINT8*)Params+1);
            break;
        case XhciTSetTRDequeuePointerCmd:
            ((XHCI_SET_TRPTR_CMD_TRB*)Trb)->TrPointer = ((XHCI_SET_TRPTR_CMD_TRB*)Params)->TrPointer;
            ((XHCI_SET_TRPTR_CMD_TRB*)Trb)->EndpointId = ((XHCI_SET_TRPTR_CMD_TRB*)Params)->EndpointId;
            ((XHCI_SET_TRPTR_CMD_TRB*)Trb)->SlotId = ((XHCI_SET_TRPTR_CMD_TRB*)Params)->SlotId;
            break;
        case XhciTDisableSlotCmd:
            ((XHCI_DISABLESLOT_CMD_TRB*)Trb)->SlotId = *((UINT8*)Params);
            break;
                                                        //(EIP54300+)>
        case XhciTStopEndpointCmd:
            ((XHCI_STOP_EP_CMD_TRB*)Trb)->SlotId = *((UINT8*)Params);
            ((XHCI_STOP_EP_CMD_TRB*)Trb)->EndpointId = *((UINT8*)Params+1);
            break;
                                                        //<(EIP54300+)
    }

	Trb->CycleBit = Usb3Hc->CmdRing.CycleBit;

    // Ring the door bell and see Event Ring update
    Doorbell = (UINT32*)((UINTN)Usb3Hc->CapRegs + Usb3Hc->DbOffset);
    *Doorbell = 0;  // HC doorbell is #0

    Status = XHCI_WaitForEvent(
                HcStruc, Trb, XhciTCmdCompleteEvt, 0, 0,					//(EIP62376)
                &CompletionCode, TimeOut, &SlotId);

    if (Status == USB_ERROR) {
        USB_DEBUG(3, "XHCI command completion error code: %d\n", CompletionCode);
		if (CompletionCode == XHCI_TRB_EXECUTION_TIMEOUT_ERROR) {
			XHCI_Mmio64Write(HcStruc, Usb3Hc, (UINTN)&Usb3Hc->OpRegs->Crcr, CRCR_COMMAND_ABORT);

			CompletionCode = XHCI_TRB_COMMANDABORTED;
			XHCI_WaitForEvent(
				HcStruc, Trb, XhciTCmdCompleteEvt, 0, 0,
				&CompletionCode, XHCI_CMD_COMPLETE_TIMEOUT_MS, NULL);
		}
        return Status;
    }

    switch (Cmd) {
        case XhciTEnableSlotCmd:
            USB_DEBUG(3, "XHCI: Enable Slot command complete, SlotID %d\n", SlotId);
            *((UINT8*)Params) = SlotId;
            break;
        case XhciTEvaluateContextCmd:
            USB_DEBUG(3, "XHCI: Evaluate Context command complete.\n");
            break;
        case XhciTConfigureEndpointCmd:
            USB_DEBUG(3, "XHCI: Configure Endpoint command complete.\n");
            break;
        case XhciTResetEndpointCmd:
            USB_DEBUG(3, "XHCI: Reset Endpoint command complete (slot#%x dci#%x).\n",
                *((UINT8*)Params), *((UINT8*)Params+1));
            // Xhci speci 1.1 4.6.8 Reset Endpoint
            // Software shall be responsible for timing the Reset "recovery interval" required by USB.
            FixedDelay(XHCI_RESET_EP_DELAY_MS * 1000);
            break;
        case XhciTSetTRDequeuePointerCmd:
            USB_DEBUG(3, "XHCI: Set TR pointer command complete.\n");
            break;
        case XhciTDisableSlotCmd:
            USB_DEBUG(3, "XHCI: DisableSlot command complete.\n");
            break;
                                                        //(EIP54300+)>
        case XhciTStopEndpointCmd:
            USB_DEBUG(3, "XHCI: Stop Endpoint command complete (slot#%x dci#%x).\n",
                *((UINT8*)Params), *((UINT8*)Params+1));
            break;
                                                        //<(EIP54300+)
    }

    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ProcessPortChanges
//
// Description:
//  This function process root hub port changes.
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_SUCCESS or USB_ERROR
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ProcessPortChanges(
	HC_STRUC    			*HcStruc,
	USB3_HOST_CONTROLLER    *Usb3Hc
)
{
	UINT8   	Port;
	BOOLEAN		PortChanged;
	volatile XHCI_PORTSC *PortSC;
    EFI_STATUS  EfiStatus = EFI_SUCCESS;


	if (gUsbData->bEnumFlag == TRUE) return USB_SUCCESS;

	gUsbData->bEnumFlag = TRUE;     // disable recursive enumeration

    FixedDelay(XHCI_WAIT_PORT_STABLE_DELAY_MS * 1000);

	do {
		PortChanged = FALSE;

		for (Port = 1; Port <= Usb3Hc->MaxPorts; Port++) {
			PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
									XHCI_PORTSC_OFFSET + (0x10 * (Port - 1)));
#if USB_RUNTIME_DRIVER_IN_SMM
            EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
            if (EFI_ERROR(EfiStatus)) {
                return USB_ERROR;
            }
#endif
			if (PortSC->Field.Csc) {
				USBCheckPortChange(HcStruc, HcStruc->bHCNumber | BIT7, Port);
				PortChanged = TRUE;
			}
		}
	} while (PortChanged);

	Usb3Hc->OpRegs->UsbSts.AllBits = XHCI_STS_PCD;	// Clear PortChangeDetect

    gUsbData->bEnumFlag = FALSE;    // enable enumeration

	return USB_SUCCESS;
}

										//(EIP54283+)>
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_ResetEndpoint
//
// Description:
//  This function is called to reset endpoint.
//
// Input:
//  Stalled EP data - SlotId and DCI
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ResetEndpoint(
    USB3_HOST_CONTROLLER *Usb3Hc,
    HC_STRUC    *HcStruc,
    UINT8       SlotId,
    UINT8       Dci
)
{
	UINT16      EpInfo;
	UINT8       Status = USB_SUCCESS;
    XHCI_EP_CONTEXT *EpCtx;

    EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, 
					XHCI_GetDeviceContext(Usb3Hc, SlotId), Dci);
       
    // The Reset Endpoint Command is issued by software to recover 
    // from a halted condition on an endpoint.
    if (EpCtx->EpState == XHCI_EP_STATE_HALTED) {   
        // Reset stalled endpoint
        EpInfo = (Dci << 8) + SlotId;
        Status = XHCI_ExecuteCommand(HcStruc, XhciTResetEndpointCmd, &EpInfo);
    }
    //ASSERT(Status == USB_SUCCESS);
	return Status;
}
										//<(EIP54283+)

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_ClearStalledEp
//
// Description:
//  This function is called to restart endpoint. After Endpoint STALLs, it
//  transitions from Halted to Stopped state. It is restored back to Running
//  state by moving the endpoint ring dequeue pointer past the failed control
//  transfer with a Set TR Dequeue Pointer. Then it is restarted by ringing the
//  doorbell. Alternatively endpint is restarted using Configure Endpoint command.
//
// Input:
//  Stalled EP data - SlotId and DCI
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ClearStalledEp(
    USB3_HOST_CONTROLLER *Usb3Hc,
    HC_STRUC    *HcStruc,
    UINT8       SlotId,
    UINT8       Dci
)
{
    UINT16      EpInfo;
    TRB_RING    *XfrRing;
    UINT8       Status;
    XHCI_SET_TRPTR_CMD_TRB  Trb;
    XHCI_EP_CONTEXT *EpCtx;
//	volatile UINT32 *Doorbell;	        //(EIP61849-)

/*
Stalled Endpoints       By Sarah Sharp, Linux XHCI driver developer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 When a control endpoint stalls, the next control transfer will clear the stall.
The USB core doesn't call down to the host controller driver's endpoint_reset()
method when control endpoints stall, so the xHCI driver has to do all its stall
handling for internal state in its interrupt handler.

 When the host stalls on a control endpoint, it may stop on the data phase or
status phase of the control transfer. Like other stalled endpoints, the xHCI
driver needs to queue a Reset Endpoint command and move the hardware's control
endpoint ring dequeue pointer past the failed control transfer (with a Set TR
Dequeue Pointer or a Configure Endpoint command).

 Since the USB core doesn't call usb_hcd_reset_endpoint() for control endpoints,
we need to do this in interrupt context when we get notified of the stalled
transfer. URBs may be queued to the hardware before these two commands complete.
The endpoint queue will be restarted once both commands complete. 

 When an endpoint on a device under an xHCI host controller stalls, the host
controller driver must let the hardware know that the USB core has successfully
cleared the halt condition. The HCD submits a Reset Endpoint Command, which will
clear the toggle bit for USB 2.0 devices, and set the sequence number to zero for
USB 3.0 devices.

  The xHCI urb_enqueue will accept new URBs while the endpoint is halted, and
will queue them to the hardware rings. However, the endpoint doorbell will not
be rung until the Reset Endpoint Command completes. Don't queue a reset endpoint
command for root hubs. khubd clears halt conditions on the roothub during the
initialization process, but the roothub isn't a real device, so the xHCI host
controller doesn't need to know about the cleared halt. 
*/
    EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, 
					XHCI_GetDeviceContext(Usb3Hc, SlotId), Dci);
       
    // The Reset Endpoint Command is issued by software to recover 
    // from a halted condition on an endpoint.
    if (EpCtx->EpState == XHCI_EP_STATE_HALTED) {
        // Reset stalled endpoint
        EpInfo = (Dci << 8) + SlotId;
        Status = XHCI_ExecuteCommand(HcStruc, XhciTResetEndpointCmd, &EpInfo);
    }
    //ASSERT(Status == USB_SUCCESS);

    // Set TR Dequeue Pointer command may be executed only if the target 
    // endpoint is in the Error or Stopped state.
    if ((EpCtx->EpState == XHCI_EP_STATE_STOPPED) || 
        (EpCtx->EpState == XHCI_EP_STATE_ERROR)) {

        XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci-1);

        Trb.TrPointer = (UINT64)((UINTN)XfrRing->QueuePtr + XfrRing->CycleBit); // Set up DCS
        Trb.EndpointId = Dci;
        Trb.SlotId = SlotId;

        Status = XHCI_ExecuteCommand(HcStruc, XhciTSetTRDequeuePointerCmd, &Trb);
        //ASSERT(Status == USB_SUCCESS);
    }

//	Doorbell = XHCI_GetTheDoorbell(Usb3Hc, SlotId);		//(EIP61849-)
//	*Doorbell = Dci;									//(EIP61849-)

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ProcessXferEvt
//
// Description:
//  This function processes a transfer event and gives control to the device
//  specific routines.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
XHCI_ProcessXferEvt(
    USB3_HOST_CONTROLLER    *Usb3Hc,
    HC_STRUC                *HcStruc,
    XHCI_TRANSFER_EVT_TRB	*XferEvtTrb
)
{
    DEV_INFO                *DevInfo;
	UINT8                   SlotId = XferEvtTrb->SlotId;
	UINT8                   Dci = XferEvtTrb->EndpointId;
    XHCI_NORMAL_XFR_TRB *Trb = (XHCI_NORMAL_XFR_TRB*)XferEvtTrb->TrbPtr;
    volatile UINT32         *Doorbell = XHCI_GetTheDoorbell(Usb3Hc, SlotId);
    TRB_RING                *XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci-1);
    UINT16                  BytesTransferred;
    UINT8                   PortStatus = USB_PORT_STAT_DEV_ENABLED;
    UINT8                   i;

    DevInfo = XHCI_GetDevInfo((UINTN)Trb->DataBuffer);
    if (DevInfo == NULL) return;

	switch (XferEvtTrb->CompletionCode) {
		case XHCI_TRB_SUCCESS:
		case XHCI_TRB_SHORTPACKET:
		    // Check for the keyboard event

										//(EIP38434+)>
			if ((DevInfo->bCallBackIndex) && 
                (DevInfo->bCallBackIndex <= MAX_CALLBACK_FUNCTION) &&
                (DevInfo->fpPollTDPtr != NULL)) {
                
				if (gUsbData->aCallBackFunctionTable[DevInfo->bCallBackIndex-1]) {

                    if (gUsbData->ProcessingPeriodicList == FALSE) {
                        for (i = 0; i < XHCI_MAX_PENDING_INTERRUPT_TRANSFER; i++) {
                            if (Usb3Hc->PendingInterruptTransfer[i].Trb == NULL) {
                                break;
                            }
                        }
                        if (i != XHCI_MAX_PENDING_INTERRUPT_TRANSFER) {
                            Usb3Hc->PendingInterruptTransfer[i].Trb = Trb;
                            Usb3Hc->PendingInterruptTransfer[i].TransferredLength = 
                                DevInfo->PollingLength - XferEvtTrb->TransferLength;
                            return;
                        }
                    }
                    //
                    // Get the size of data transferred
                    //
                    BytesTransferred = DevInfo->PollingLength - XferEvtTrb->TransferLength;
					(*gUsbData->aCallBackFunctionTable[DevInfo->bCallBackIndex-1])
									(HcStruc, DevInfo, NULL, DevInfo->fpPollTDPtr,
                                    BytesTransferred);
				}
			}
										//<(EIP38434+)
			break;

		case XHCI_TRB_BABBLE_ERROR:
		case XHCI_TRB_TRANSACTION_ERROR:
		case XHCI_TRB_STALL_ERROR:
            // When the device is disconnecting, the transaction will be error, 
            // we need to check the port status
            PortStatus = USB_GetHubPortStatus(HcStruc, DevInfo->bHubDeviceNumber, DevInfo->bHubPortNumber, FALSE);
            if (PortStatus == USB_ERROR) {
                PortStatus = 0;
            }
            if (PortStatus & USB_PORT_STAT_DEV_ENABLED) {
			    XHCI_ClearStalledEp(Usb3Hc, HcStruc, SlotId, Dci);
            }
			break;	
	}
    // Check if this device is still enabled
    if ((PortStatus & USB_PORT_STAT_DEV_ENABLED) && (DevInfo->fpPollTDPtr != NULL)) {
        Trb = (XHCI_NORMAL_XFR_TRB*)XHCI_AdvanceEnqueuePtr(XfrRing);
        if (Trb == NULL) {
            return;
        }
        Trb->TrbType = XhciTNormal;
        Trb->DataBuffer = (UINT64)(UINTN)DevInfo->fpPollTDPtr;
        Trb->XferLength = DevInfo->PollingLength;
    	Trb->Isp = 1;					//(EIP51478+)
    	Trb->Ioc = 1;
    	Trb->CycleBit = XfrRing->CycleBit;

        // Ring the door bell to start polling interrupt endpoint
        *Doorbell = Dci;
    }
}

										//(EIP60460+)>
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ProcessPortStsChgEvt
//
// Description:
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
XHCI_ProcessPortStsChgEvt(
    USB3_HOST_CONTROLLER    *Usb3Hc,
    HC_STRUC                *HcStruc,
    XHCI_PORTSTSCHG_EVT_TRB	*PortStsChgEvtTrb
)
{
	volatile XHCI_PORTSC *PortSC;
    DEV_INFO	*DevInfo;
	UINT8		i;
    EFI_STATUS  EfiStatus = EFI_SUCCESS;

	if (((Usb3Hc->Vid != XHCI_FL100X_VID) || (Usb3Hc->Did != XHCI_FL1000_DID &&
		Usb3Hc->Did != XHCI_FL1009_DID)) && (Usb3Hc->Vid != XHCI_INTEL_VID)) {
		return;
	}

    PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
				XHCI_PORTSC_OFFSET + (0x10 * (PortStsChgEvtTrb->PortId - 1)));

#if USB_RUNTIME_DRIVER_IN_SMM
    EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
    if (EFI_ERROR(EfiStatus)) {
        return;
    }
#endif
	
	if (PortSC->Field.Csc && PortSC->Field.Ccs == 0) {
		for (i = 1; i < MAX_DEVICES; i++) {
			DevInfo = &gUsbData->aDevInfoTable[i];
		    if ((DevInfo->Flag & DEV_INFO_VALIDPRESENT)
                != DEV_INFO_VALIDPRESENT) {
			    continue;
		    }
			if ((DevInfo->bHubDeviceNumber == (HcStruc->bHCNumber | BIT7)) &&
				DevInfo->bHubPortNumber == PortStsChgEvtTrb->PortId) {
				DevInfo->Flag |= DEV_INFO_DEV_DISCONNECTING;
			}
		}
	}
}
										//<(EIP60460+)

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   XHCI_ProcessInterrupt
//
// Description: This is the XHCI controller event handler. It walks through
//  the Event Ring and executes the event associated code if needed. Updates
//  the Event Ring Data Pointer in the xHC to let it know which events are
//  completed.
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_ERROR   - Need more Interrupt processing
//  USB_SUCCESS - No interrupts pending
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ProcessInterrupt(
    HC_STRUC    *HcStruc
)
{
    XHCI_TRB        *Trb;
    UINTN           XhciBaseAddress;
    UINT32          Imod;
    UINT8           i;
	UINT8           SlotId;
	UINT8           Dci;
    volatile UINT32 *Doorbell;
    TRB_RING        *XfrRing;
    DEV_INFO	    *DevInfo;
    XHCI_NORMAL_XFR_TRB *XfrTrb;
    USB3_HOST_CONTROLLER *Usb3Hc;
    EFI_STATUS      EfiStatus = EFI_SUCCESS;
    UINTN       DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

	if (!(ReadPCIConfig(HcStruc->wBusDevFuncNum, USB_REG_COMMAND) & BIT1)) {
		return USB_SUCCESS;
	}

    XhciBaseAddress = ReadPCIConfig(HcStruc->wBusDevFuncNum, USB_MEM_BASE_ADDRESS);
    if (((XhciBaseAddress & (BIT1 | BIT2)) == BIT2) && ((sizeof(VOID*) / sizeof(UINT32) == 2))){
        XhciBaseAddress |= Shl64((UINTN)ReadPCIConfig(HcStruc->wBusDevFuncNum,
                            USB_MEM_BASE_ADDRESS + 0x04), 32);
    }
    
    XhciBaseAddress &= ~(0x7F);

	if (XhciBaseAddress != (UINTN)Usb3Hc->CapRegs) {
#if USB_RUNTIME_DRIVER_IN_SMM
        EfiStatus = AmiValidateMmioBuffer((VOID*)XhciBaseAddress, HcStruc->BaseAddressSize);
        if (EFI_ERROR(EfiStatus)) {
            USB_DEBUG(3, "Usb Mmio address is invalid, it is in SMRAM\n");
            return USB_ERROR;
        }
#endif
        HcStruc->BaseAddress = XhciBaseAddress;
        (UINTN)Usb3Hc->CapRegs = XhciBaseAddress;
        Usb3Hc->OpRegs = (XHCI_HC_OP_REGS*)((UINTN)Usb3Hc->CapRegs + Usb3Hc->CapRegs->CapLength);
        Usb3Hc->RtRegs = (XHCI_HC_RT_REGS*)((UINTN)Usb3Hc->CapRegs + Usb3Hc->CapRegs->RtsOff);
        XhciExtCapParser(Usb3Hc);
	}

    // Check if host controller interface version number is valid.
    if (Usb3Hc->CapRegs->HciVersion == 0xFFFF) {
        return USB_SUCCESS;
    }

	// Check if USB Legacy Support Capability is present.
    if (Usb3Hc->ExtLegCap) {
        // Is ownership change?
        if((Usb3Hc->ExtLegCap->LegCtlSts.UsbOwnershipChangeSmi == 1) && 
        	(Usb3Hc->ExtLegCap->LegCtlSts.UsbOwnershipChangeSmiEnable==1) ) {
            // Clear Ownership change SMI status
        	Usb3Hc->ExtLegCap->LegCtlSts.UsbOwnershipChangeSmi = 1;
            // Process ownership change event
			if (Usb3Hc->ExtLegCap->LegSup.HcOsOwned == 1 && 
				HcStruc->dHCFlag & HC_STATE_RUNNING) {
		        gUsbData->dUSBStateFlag  &= (~USB_FLAG_ENABLE_BEEP_MESSAGE);
		        USB_DEBUG(3, "XHCI: Ownership change to XHCD\n");
		        XHCI_Stop(HcStruc);
		    } else if (Usb3Hc->ExtLegCap->LegSup.HcOsOwned == 0 &&
		    			(HcStruc->dHCFlag & HC_STATE_RUNNING) == 0) {
		        gUsbData->dUSBStateFlag |= USB_FLAG_ENABLE_BEEP_MESSAGE;
		        USB_DEBUG(3, "XHCI: Ownership change to BIOS\n");
				XHCI_Start(HcStruc);
                XHCI_EnumeratePorts(HcStruc);
		    }
			return USB_SUCCESS;
        }
    }
	
    if ((HcStruc->dHCFlag & HC_STATE_RUNNING) == 0) return USB_SUCCESS;

    if ((UINT32)Usb3Hc->OpRegs->DcbAap != (UINT32)Usb3Hc->DcbaaPtr) return USB_SUCCESS;

    if (gUsbData->ProcessingPeriodicList == TRUE) {
        for (i = 0; i < XHCI_MAX_PENDING_INTERRUPT_TRANSFER; i++) {
            if (Usb3Hc->PendingInterruptTransfer[i].Trb != NULL) { 
                DevInfo = XHCI_GetDevInfo((UINTN)Usb3Hc->PendingInterruptTransfer[i].Trb->DataBuffer);
                if (DevInfo == NULL) {
                    continue;
                }
                if ((DevInfo->bCallBackIndex) && 
                    (DevInfo->bCallBackIndex <= MAX_CALLBACK_FUNCTION) &&
                    (DevInfo->fpPollTDPtr != NULL)) {
                    DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

                    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
                        	(DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
                        continue;
                    }
                    SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
                    Dci = (DevInfo->IntInEndpoint & 0xF) * 2;
                    
                    if (DevInfo->IntInEndpoint & BIT7) {
                        Dci++;
                    }
    
                    Doorbell = XHCI_GetTheDoorbell(Usb3Hc, SlotId);
                    
                    XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci - 1);
    
                    Usb3Hc->PendingInterruptTransfer[i].Trb = NULL;
                    
                    if ((DevInfo->bCallBackIndex) && (DevInfo->fpPollTDPtr != NULL)) { 
                        (*gUsbData->aCallBackFunctionTable[DevInfo->bCallBackIndex - 1])
                                            (HcStruc, DevInfo, NULL, DevInfo->fpPollTDPtr,
                                            Usb3Hc->PendingInterruptTransfer[i].TransferredLength);
                            
                        XfrTrb = (XHCI_NORMAL_XFR_TRB*)XHCI_AdvanceEnqueuePtr(XfrRing);
                        if (XfrTrb == NULL) {
                            continue;
                        }
                        XfrTrb->TrbType = XhciTNormal;
                        XfrTrb->DataBuffer = (UINT64)(UINTN)DevInfo->fpPollTDPtr;
                        XfrTrb->XferLength = DevInfo->PollingLength;
                        XfrTrb->Isp = 1;
                        XfrTrb->Ioc = 1;
                        XfrTrb->CycleBit = XfrRing->CycleBit;
                        // Ring the door bell to start polling interrupt endpoint
                        *Doorbell = Dci;
                    }
                } else {
                    Usb3Hc->PendingInterruptTransfer[i].Trb = NULL;                         
                }
            }
        }
    }

    if (Usb3Hc->OpRegs->UsbSts.Field.Pcd) {
        //XHCI_EnumeratePorts(HcStruc);
        XHCI_ProcessPortChanges(HcStruc, Usb3Hc);
    }

//    if (Usb3Hc->OpRegs->UsbSts.Field.Eint == 0) return USB_SUCCESS;
//    Usb3Hc->OpRegs->UsbSts.AllBits = XHCI_STS_EVT_INTERRUPT;    // Clear event interrupt
	if (Usb3Hc->OpRegs->UsbSts.Field.Eint) {
		Usb3Hc->OpRegs->UsbSts.AllBits = XHCI_STS_EVT_INTERRUPT;
        if ((gUsbData->fpKeyRepeatHCStruc == HcStruc) && (gUsbData->ProcessingPeriodicList == TRUE)) {
            Imod = Usb3Hc->RtRegs->IntRegs[0].IMod;
            if ((Imod & XHCI_KEYREPEAT_IMODI) == XHCI_KEYREPEAT_IMODI) {
                USBKBDPeriodicInterruptHandler(HcStruc);
            }
        }
	}

    // Check for pending interrupts:
    // check the USBSTS[3] and IMAN [0] to determine if any interrupt generated
    if (Usb3Hc->EvtRing.QueuePtr->CycleBit != Usb3Hc->EvtRing.CycleBit) {
        if (gUsbData->fpKeyRepeatHCStruc == HcStruc) {
            Imod = Usb3Hc->RtRegs->IntRegs[0].IMod;
            if ((Imod & XHCI_KEYREPEAT_IMODI) == XHCI_KEYREPEAT_IMODI) {
                Usb3Hc->RtRegs->IntRegs[0].IMan |= BIT0;
                XHCI_Mmio64Write(HcStruc, Usb3Hc,
                        (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)0 | BIT3);
            } else {
                Usb3Hc->RtRegs->IntRegs[0].IMan |= BIT0;
                XHCI_Mmio64Write(HcStruc, Usb3Hc,
                (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)Usb3Hc->EvtRing.QueuePtr | BIT3);
            }
        } else {
            Usb3Hc->RtRegs->IntRegs[0].IMan |= BIT0;
            XHCI_Mmio64Write(HcStruc, Usb3Hc,
            (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)Usb3Hc->EvtRing.QueuePtr | BIT3);
        }
        return USB_SUCCESS;
    }

    // See if there are any TRBs waiting in the event ring
    //for (Count = 0; Count < Usb3Hc->EvtRing.Size; Count++) {
    for (;;) {
        Trb = Usb3Hc->EvtRing.QueuePtr;
#if USB_RUNTIME_DRIVER_IN_SMM
        EfiStatus = AmiValidateMemoryBuffer((VOID*)Trb, sizeof(XHCI_TRB));
        if (EFI_ERROR(EfiStatus)) {
            break;
        }
#endif
        if (Trb->CycleBit != Usb3Hc->EvtRing.CycleBit) break;  // past the last

		if (Usb3Hc->EvtRing.QueuePtr == Usb3Hc->EvtRing.LastTrb) {
			// Reached the end of the ring, wrap around
			Usb3Hc->EvtRing.QueuePtr = Usb3Hc->EvtRing.Base;
			Usb3Hc->EvtRing.CycleBit ^= 1;
		} else {
			Usb3Hc->EvtRing.QueuePtr++;
		}
        // error manager
        if (Trb->CompletionCode == XHCI_TRB_SHORTPACKET) {
            USB_DEBUG(3, "XHCI: short packet detected.");
        }

        if (Trb->CompletionCode == XHCI_TRB_STALL_ERROR) {
            USB_DEBUG(3, "XHCI: device STALLs.");
        }

        if (Trb->CompletionCode != XHCI_TRB_SUCCESS
                && Trb->CompletionCode != XHCI_TRB_STALL_ERROR
                && Trb->CompletionCode != XHCI_TRB_SHORTPACKET) {
            USB_DEBUG(3, "Trb completion code: %d\n", Trb->CompletionCode);
            //ASSERT(FALSE);
        }

        switch (Trb->TrbType) {
            case XhciTTransferEvt:
// very frequent, debug message here might affect timings,
// uncomment only when needed
//              USB_DEBUG(3, "TransferEvt\n");
                XHCI_ProcessXferEvt(Usb3Hc, HcStruc, (XHCI_TRANSFER_EVT_TRB*)Trb);
                break;
            case XhciTCmdCompleteEvt:
                USB_DEBUG(3, "CmdCompleteEvt\n");
                break;
            case XhciTPortStatusChgEvt:
                USB_DEBUG(3, "PortStatusChgEvt, port #%d\n", ((XHCI_PORTSTSCHG_EVT_TRB*)Trb)->PortId);
				XHCI_ProcessPortStsChgEvt(Usb3Hc, HcStruc, (XHCI_PORTSTSCHG_EVT_TRB*)Trb);	//(EIP60460+)
                break;
            case XhciTDoorbellEvt:
                USB_DEBUG(3, "DoorbellEvt\n");
                break;
            case XhciTHostControllerEvt:
                USB_DEBUG(3, "HostControllerEvt\n");
                break;
            case XhciTDevNotificationEvt:
                USB_DEBUG(3, "DevNotificationEvt\n");
                break;
            case XhciTMfIndexWrapEvt:
                USB_DEBUG(3, "MfIndexWrapEvt\n");
                break;
            default:
                USB_DEBUG(3, "UNKNOWN EVENT\n");
        }
    }
    //ASSERT(Count<Usb3Hc->EvtRing.Size);    // Event ring is full

	// Update ERDP to inform xHC that we have processed another TRB
    if ((gUsbData->fpKeyRepeatHCStruc == HcStruc) && 
        ((Usb3Hc->RtRegs->IntRegs[0].IMod & XHCI_KEYREPEAT_IMODI) == XHCI_KEYREPEAT_IMODI)) {
        Usb3Hc->RtRegs->IntRegs[0].IMan |= BIT0;
        XHCI_Mmio64Write(HcStruc, Usb3Hc,
                (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)0 | BIT3);
    } else {
        Usb3Hc->RtRegs->IntRegs[0].IMan |= BIT0;
        XHCI_Mmio64Write(HcStruc, Usb3Hc,
        (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)Usb3Hc->EvtRing.QueuePtr | BIT3);
    }

    return  USB_SUCCESS;    // Set as interrupt processed
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_GetRootHubStatus
//
// Description:
//  This function returns the port connect status for the root hub port
//
// Input:
//  HcStruc  - Pointer to the HC structure
//  PortNum  - Port in the HC whose status is requested
//
// Output:
//  Port status flags (see USB_PORT_STAT_XX equates)
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_GetRootHubStatus(
    HC_STRUC*   HcStruc,
    UINT8       PortNum,
    BOOLEAN     ClearChangeBits
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    volatile XHCI_PORTSC *PortSC;
    UINT32  i;
    UINT32  PortStCtl;
    UINT8   PortStatus = USB_PORT_STAT_DEV_OWNER;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    // Find the proper MMIO access offset for a given port

    PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
                            XHCI_PORTSC_OFFSET + (0x10 * (PortNum-1)));
    
#if USB_RUNTIME_DRIVER_IN_SMM
    EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }
#endif

	USB_DEBUG(3, "XHCI port[%d] status: %08x\n", PortNum, PortSC->AllBits);

	for (i = 0; i < 200; i++) {
		if (PortSC->Field.Pr == 0) break;
		FixedDelay(1 * 1000);
	}
	
	switch (PortSC->Field.Pls) {
		case XHCI_PORT_LINK_U0:
		case XHCI_PORT_LINK_RXDETECT:
			break;
		case XHCI_PORT_LINK_RECOVERY:
			for (i = 0; i < 200; i++) {
				FixedDelay(1 * 1000);
				if (PortSC->Field.Pls != XHCI_PORT_LINK_RECOVERY) {
					break;
				}
			}
			break;
		case XHCI_PORT_LINK_POLLING:
			if (!XHCI_IsUsb3Port(Usb3Hc, PortNum)) {
				break;
			}
			for (i = 0; i < 500; i++) {
				FixedDelay(1 * 1000);
				if (PortSC->Field.Pls != XHCI_PORT_LINK_POLLING) {
					break;
				}
			}
			if (PortSC->Field.Pls == XHCI_PORT_LINK_U0 || 
				PortSC->Field.Pls == XHCI_PORT_LINK_RXDETECT) {
				break;
			}
            XHCI_ResetPort(Usb3Hc, PortNum, TRUE);
			break;
		case XHCI_PORT_LINK_INACTIVE:
			for (i = 0; i < 12; i++) {
				FixedDelay(1 * 1000);
				if (PortSC->Field.Pls != XHCI_PORT_LINK_INACTIVE) {
					break;
				}
			}
            if (PortSC->Field.Pls == XHCI_PORT_LINK_RXDETECT) {
                break;
			}
		case XHCI_PORT_LINK_COMPLIANCE_MODE:
			XHCI_ResetPort(Usb3Hc, PortNum, TRUE);
			break;
		default:
			PortStatus |= USB_PORT_STAT_DEV_CONNECTED;
			break;
	}
	
    if (PortSC->Field.Ccs != 0) {
        PortStatus |= USB_PORT_STAT_DEV_CONNECTED;
		UpdatePortStatusSpeed(PortSC->Field.PortSpeed, &PortStatus);

        // USB 3.0 device may not set Connect Status Change bit after reboot,
        // set the connect change flag when we enumerate HC ports for devices.
        if (gUsbData->bIgnoreConnectStsChng == TRUE) {
            PortStatus |= USB_PORT_STAT_DEV_CONNECT_CHANGED;
        }

		if (PortSC->Field.Ped) {
			PortStatus |= USB_PORT_STAT_DEV_ENABLED;
		}
    }

    if (PortSC->Field.Csc != 0) {
        PortStatus |= USB_PORT_STAT_DEV_CONNECT_CHANGED;
		// Clear connect status change bit
        if (ClearChangeBits == TRUE) {
		    PortSC->AllBits = XHCI_PCS_CSC | XHCI_PCS_PP;
        }
    }

	// Clear all status change bits
	if (ClearChangeBits == TRUE) {
    	PortStCtl = PortSC->AllBits;
    	PortSC->AllBits = PortStCtl & ~XHCI_PCS_PED;  // DO NOT TOUCH PED
    }

    return PortStatus;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_EnableRootHub
//
// Description:
//  This function enables the XHCI HC Root hub port.
//
// Input:
//  HcStruc   - Pointer to the HC structure
//  PortNum   - Port in the HC to enable
//
// Output:
//  USB_SUCCESS on success, USB_ERROR on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_EnableRootHub(
    HC_STRUC*   HcStruc,
    UINT8       PortNum
)
{
    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_DisableRootHub
//
// Description:
//  This function disables the XHCI HC Root hub port.
//
// Input:
//  HcStruc - Pointer to the HC structure
//  PortNum - Port in the HC to disable
//
// Output:
//  USB_SUCCESS on success, USB_ERROR on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_DisableRootHub(
    HC_STRUC    *HcStruc,
    UINT8       PortNum
)
{
	USB3_HOST_CONTROLLER *Usb3Hc;
	volatile XHCI_PORTSC *PortSC = NULL;
	UINT8	i = 0;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return 0;
    }
    
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

USB_DEBUG(3, "Disable XHCI root port %d\n", PortNum);

    PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
                            XHCI_PORTSC_OFFSET + (0x10 * (PortNum - 1)));
    
#if USB_RUNTIME_DRIVER_IN_SMM
    EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }
#endif

	if (PortSC->Field.Ped) {
		if (XHCI_IsUsb3Port(Usb3Hc, PortNum)) {
			XHCI_ResetPort(Usb3Hc, PortNum, FALSE);
		} else {
			PortSC->AllBits = XHCI_PCS_PED | XHCI_PCS_PP;
			for (i = 0; i < 200; i++) {
				if (PortSC->Field.Ped == 0) {
					break;
				}
				FixedDelay(100);
			}
		}
	}

    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ResetPort
//
// Description:
//  This function resets the XHCI HC Root hub port.
//
// Input:
//  HcStruc - Pointer to the HC structure
//  PortNum - Port in the HC to disable
//
// Output:
//  USB_SUCCESS on success, USB_ERROR on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ResetPort(
	USB3_HOST_CONTROLLER	*Usb3Hc,
	UINT8					Port,
	BOOLEAN					WarmReset
)
{
	volatile XHCI_PORTSC *PortSC;
	UINT32	i;
    EFI_STATUS EfiStatus = EFI_SUCCESS;

    PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
                            XHCI_PORTSC_OFFSET + (0x10 * (Port - 1)));
    
#if USB_RUNTIME_DRIVER_IN_SMM
    EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }
#endif

	if (WarmReset && XHCI_IsUsb3Port(Usb3Hc, Port)) {
		PortSC->AllBits = XHCI_PCS_WPR | XHCI_PCS_PP;
			
		for (i = 0; i < 6000; i++) {     //(EIP93368)
			if (PortSC->Field.Wrc || PortSC->Field.Prc) {
				break;
			}
            FixedDelay(100);
		}
		//ASSERT(PortSC->Field.Wrc || PortSC->Field.Prc);
		if (PortSC->Field.Wrc == 0 && PortSC->Field.Prc == 0) {
			return USB_ERROR;
		}

		if (Usb3Hc->Vid == XHCI_EJ168A_VID && Usb3Hc->Did == XHCI_EJ168A_DID) {
			FixedDelay(20 * 1000);
		}
	} else {
		PortSC->AllBits = XHCI_PCS_PR | XHCI_PCS_PP;	// Keep port power bit

		for (i = 0; i < 3000; i++) {
			if (PortSC->Field.Prc) break;
            FixedDelay(100);
		}
		//ASSERT(PortSC->Field.Prc);
		if (PortSC->Field.Prc == 0) {
			return USB_ERROR;
		}
	}

	// Clear Warm Port Reset Change and Port Reset Change bits
	PortSC->AllBits = XHCI_PCS_WRC | XHCI_PCS_PRC | XHCI_PCS_PP;
	// The USB System Software guarantees a minimum of 10 ms for reset recovery.
	FixedDelay(XHCI_RESET_PORT_DELAY_MS * 1000);

	return USB_SUCCESS;	
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ResetRootHub
//
// Description:
//  This function resets the XHCI HC Root hub port.
//
// Input:
//  HcStruc - Pointer to the HC structure
//  PortNum - Port in the HC to disable
//
// Output:
//  USB_SUCCESS on success, USB_ERROR on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ResetRootHub(
    HC_STRUC*   HcStruc,
    UINT8		PortNum
)
{
	USB3_HOST_CONTROLLER *Usb3Hc;
	UINT8	Status;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);

    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }
    
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

	Status = XHCI_ResetPort(Usb3Hc, PortNum, FALSE);
	
	if (!XHCI_IsUsb3Port(Usb3Hc, PortNum)) {
		// After a short delay, SS device that was originally connected to HS port 
		// might get reconnected to the SS port...
		FixedDelay(XHCI_SWITCH2SS_DELAY_MS * 1000);
	}

	return Status;
}

										//(EIP54018+)>
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        XHCI_GlobalSuspend
//
// Description: 
//  This function suspend the XHCI HC.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_GlobalSuspend(
    HC_STRUC*	HcStruc
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    volatile XHCI_PORTSC *PortSC;
    UINT32  Port;
    UINT32  i;
    UINT32  PortStCtl;
    EFI_STATUS      EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
	
    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }

    for (Port = 1; Port <= Usb3Hc->MaxPorts; Port++) {

        PortSC = (XHCI_PORTSC*)((UINTN)Usb3Hc->OpRegs +
                            XHCI_PORTSC_OFFSET + (0x10 * (Port - 1)));

#if USB_RUNTIME_DRIVER_IN_SMM
        EfiStatus = AmiValidateMmioBuffer((VOID*)PortSC, sizeof(XHCI_PORTSC));
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
#endif
        
        USB_DEBUG(3, "XHCI port[%d] status: %08x\n", Port, PortSC->AllBits);
        if ((PortSC->Field.Ped) && (PortSC->Field.Pls <XHCI_PORT_LINK_U3)){
            PortStCtl = PortSC->AllBits;
            PortStCtl |= (XHCI_PCS_LWS | (UINT32)(XHCI_PORT_LINK_U3 << 5));
            PortSC->AllBits = PortStCtl & ~XHCI_PCS_PED;
            for (i = 0;i < 10; i++) {
                if (PortSC->Field.Pls == XHCI_PORT_LINK_U3) break;
                FixedDelay(1 * 1000);
            }
        }
    }
    

    Usb3Hc->OpRegs->UsbCmd.AllBits &= ~XHCI_CMD_RS;
    
    for (i = 0; i < 16; i++) {
        FixedDelay(1 * 1000);
        if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) break;
    }

    HcStruc->dHCFlag &= ~(HC_STATE_RUNNING);
    HcStruc->dHCFlag |= HC_STATE_SUSPEND;
   
    return  USB_SUCCESS;
}
										//<(EIP54018+)
										
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_UpdateEp0MaxPacket
//
// Description:
//  This function verifies the MaxPacket size of the control pipe. If it does
//  not match the one received as a part of GET_DESCRIPTOR, then this function
//  updates the MaxPacket data in DeviceContext and HC is notified via
//  EvaluateContext command.
//
// Input:
//  HcStruc Pointer to the HC structure
//  Device  Evaluated device context pointer
//  SlotId  Device context index in DCBAA
//  Endp0MaxPacket  Max packet size obtained from the device
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
XHCI_UpdateEp0MaxPacket(
    HC_STRUC            *HcStruc,
    UINT8               SlotId,
    UINT8               Endp0MaxPacket
)
{
    USB3_HOST_CONTROLLER *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
    UINT8   Status;
	UINT8	*DevCtx;
	XHCI_INPUT_CONTROL_CONTEXT	*CtlCtx;
	XHCI_SLOT_CONTEXT			*SlotCtx;
	XHCI_EP_CONTEXT				*EpCtx;

	DevCtx = (UINT8*)XHCI_GetDeviceContext(Usb3Hc, SlotId);

	SlotCtx = (XHCI_SLOT_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, DevCtx, 0);
	if (SlotCtx->Speed != XHCI_DEVSPEED_FULL) return;

	EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, DevCtx, 1);
	if (EpCtx->MaxPacketSize == Endp0MaxPacket) return;

    // Prepare input context for EvaluateContext comand
    MemFill((UINT8*)Usb3Hc->InputContext, XHCI_INPUT_CONTEXT_ENTRIES * Usb3Hc->ContextSize, 0);

    CtlCtx = (XHCI_INPUT_CONTROL_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)Usb3Hc->InputContext, 0);
    CtlCtx->AddContextFlags = BIT1;

	EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)Usb3Hc->InputContext, 2);
    EpCtx->MaxPacketSize = Endp0MaxPacket;

    Status = XHCI_ExecuteCommand(HcStruc, XhciTEvaluateContextCmd, &SlotId);
    ASSERT(Status == USB_SUCCESS);
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_ControlTransfer
//
// Description:
//  This function executes a device request command transaction on the USB.
//  One setup packet is generated containing the device request parameters
//  supplied by the caller.  The setup packet may be followed by data in or
//  data out packets containing data sent from the host to the device or
//  vice-versa. This function will not return until the request either completes
//  successfully or completes in error (due to time out, etc.)
//
// Input:
//  HcStruc     Pointer to the HC structure
//  DevInfo     DeviceInfo structure (if available else 0)
//  Request     Request type (low byte)
//              Bit 7   : Data direction
//                  0 = Host sending data to device
//                  1 = Device sending data to host
//              Bit 6-5 : Type
//                  00 = Standard USB request
//                  01 = Class specific
//                  10 = Vendor specific
//                  11 = Reserved
//              Bit 4-0 : Recipient
//                  00000 = Device
//                  00001 = Interface
//                  00010 = Endpoint
//                  00100 - 11111 = Reserved
//                  Request code, a one byte code describing the actual
//                  device request to be executed (ex: Get Configuration,
//                  Set Address, etc.)
//  Index   wIndex request parameter (meaning varies)
//  Value   wValue request parameter (meaning varies)
//  Buffer  Buffer containing data to be sent to the device or buffer
//          to be used to receive data
//  Length  wLength request parameter, number of bytes of data to be
//              transferred in or out of the host controller
//
// Output:
//  Number of bytes actually transferred
//
// Notes:
//  DevInfo->DevMiscInfo points to the device context
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT16
XHCI_ControlTransfer (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT16      Request,
    UINT16      Index,
    UINT16      Value,
    UINT8       *Buffer,
    UINT16      Length
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    XHCI_TRB    *Trb;
    UINT8       SlotId;
    UINT8       CompletionCode;
    UINT8       Status;
    TRB_RING    *XfrRing;
    UINT16		TimeoutMs;
    XHCI_SLOT_CONTEXT	*SlotCtx = NULL;
    EFI_STATUS  EfiStatus = EFI_SUCCESS;
    UINTN       DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return 0;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        if (Length != 0) {
            EfiStatus = AmiValidateMemoryBuffer((VOID*)Buffer, Length);
            if (EFI_ERROR(EfiStatus)) {
                USB_DEBUG(3, "Xhci ControlTransfer Invalid Pointer, Buffer is in SMRAM.\n");
                return 0;
            }
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return 0;
    }

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return 0;
    }

    ASSERT(DevInfo != NULL);

	if(DevInfo->Flag & DEV_INFO_DEV_DISCONNECTING) return 0;	//(EIP60460+)
	
	DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;
	
	if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
	        (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
	    return 0;
	}

    SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);

    // Skip SET_ADDRESS request if device is in addressed state
    if (Request == USB_RQ_SET_ADDRESS) {
        SlotCtx = XHCI_GetContextEntry(Usb3Hc, DevInfo->DevMiscInfo, 0);
	
        if (SlotCtx->SlotState == XHCI_SLOT_STATE_DEFAULT) {
            Status = XhciAddressDevice(HcStruc, DevInfo, SlotId);
        }
        return Length;
    }

	TimeoutMs = gUsbData->wTimeOutValue != 0 ? XHCI_CTL_COMPLETE_TIMEOUT_MS : 0;

    gUsbData->bLastCommandStatus &= ~(USB_CONTROL_STALLED);
    gUsbData->dLastCommandStatusExtended = 0;

    // Insert Setup, Data(if needed), and Status TRBs into the transfer ring
    XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, 0);

    // Setup TRB
    Trb = XHCI_AdvanceEnqueuePtr(XfrRing);
    if (Trb == NULL) {
        return 0;
    }
    Trb->TrbType = XhciTSetupStage;
    ((XHCI_SETUP_XFR_TRB*)Trb)->Idt = 1;
    *(UINT16*)&((XHCI_SETUP_XFR_TRB*)Trb)->bmRequestType = Request;
    ((XHCI_SETUP_XFR_TRB*)Trb)->wValue = Value;
    ((XHCI_SETUP_XFR_TRB*)Trb)->wIndex = Index;
    ((XHCI_SETUP_XFR_TRB*)Trb)->wLength = Length;
    ((XHCI_SETUP_XFR_TRB*)Trb)->XferLength = 8;

	if (Usb3Hc->HciVersion >= 0x100) {
		if (Length != 0) {
			if (Request & USB_REQ_TYPE_INPUT) {
				((XHCI_SETUP_XFR_TRB*)Trb)->Trt = XHCI_XFER_TYPE_DATA_IN;
			} else {
				((XHCI_SETUP_XFR_TRB*)Trb)->Trt = XHCI_XFER_TYPE_DATA_OUT;
			}
		} else {
			((XHCI_SETUP_XFR_TRB*)Trb)->Trt = XHCI_XFER_TYPE_NO_DATA;
		}
	}
	 ((XHCI_SETUP_XFR_TRB*)Trb)->CycleBit = XfrRing->CycleBit;
	
    // Data TRB
    if (Length != 0) {
        Trb = XHCI_AdvanceEnqueuePtr(XfrRing);
        if (Trb == NULL) {
            return 0;
        }
        Trb->TrbType = XhciTDataStage;
        ((XHCI_DATA_XFR_TRB*)Trb)->Dir = ((Request & USB_REQ_TYPE_INPUT) != 0)? 1 : 0;
        ((XHCI_DATA_XFR_TRB*)Trb)->XferLength = Length;
        ((XHCI_DATA_XFR_TRB*)Trb)->DataBuffer = (UINT64)(UINTN)Buffer;
		((XHCI_DATA_XFR_TRB*)Trb)->CycleBit = XfrRing->CycleBit;
    }

    // Status TRB
    Trb = XHCI_AdvanceEnqueuePtr(XfrRing);
    if (Trb == NULL) {
        return 0;
    }
    Trb->TrbType = XhciTStatusStage;
    ((XHCI_STATUS_XFR_TRB*)Trb)->Ioc = 1;
    if ((Request & USB_REQ_TYPE_INPUT) == 0) {
        ((XHCI_STATUS_XFR_TRB*)Trb)->Dir = 1;   // Status is IN
    }
	((XHCI_STATUS_XFR_TRB*)Trb)->CycleBit = XfrRing->CycleBit;

    // Ring the doorbell and see Event Ring update
    Status = XhciRingDoorbell(Usb3Hc, SlotId, 1);

    if (Status != USB_SUCCESS) {
        return 0;
    }

    Status = XHCI_WaitForEvent(
                HcStruc, Trb, XhciTTransferEvt, SlotId, 1,					//(EIP62376)
                &CompletionCode, TimeoutMs, NULL);

	if (Status != USB_SUCCESS) {
										//(EIP54283)>
		switch (CompletionCode) {
			case XHCI_TRB_BABBLE_ERROR:								//(EIP62376+)
			case XHCI_TRB_TRANSACTION_ERROR:
				XHCI_ClearStalledEp(Usb3Hc, HcStruc, SlotId, 1);	//(EIP60460+)
				break;												//(EIP60460+)
			case XHCI_TRB_STALL_ERROR:
				XHCI_ClearStalledEp(Usb3Hc, HcStruc, SlotId, 1);
				gUsbData->bLastCommandStatus |= USB_CONTROL_STALLED;
				break;
										//(EIP84790+)>
            case XHCI_TRB_EXECUTION_TIMEOUT_ERROR:
				XHCI_ClearEndpointState(HcStruc, DevInfo, 0);
                gUsbData->dLastCommandStatusExtended |= USB_TRNSFR_TIMEOUT;
                break;
										//<(EIP84790+)
			default:
				break;
		}
										//<(EIP54283)
		return 0;
	}

    if (Request == USB_RQ_GET_DESCRIPTOR && Length == 8) {
        // Full speed device requires the update of MaxPacket size
        XHCI_UpdateEp0MaxPacket(HcStruc, SlotId, ((DEV_DESC*)Buffer)->MaxPacketSize0);
    }


    if ((Request == (UINT16)(ENDPOINT_CLEAR_PORT_FEATURE)) && (Length == 0) &&
        (Value == (UINT16)ENDPOINT_HALT) && (Buffer == NULL)) {
        XHCI_ClearEndpointState(HcStruc, DevInfo, (UINT8)Index);
    }

    return Length;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_BulkTransfer
//
// Description:
//  This function executes a bulk transaction on the USB
//
// Input:
//  HcStruc   Pointer to HCStruc of the host controller
//  DevInfo   DeviceInfo structure (if available else 0)
//  XferDir   Transfer direction
//      Bit 7: Data direction
//          0 Host sending data to device
//          1 Device sending data to host
//      Bit 6-0 : Reserved
//  Buffer    Buffer containing data to be sent to the device or buffer to
//            be used to receive data value
//  Length    Length request parameter, number of bytes of data to be
//            transferred in or out of the HC
//
// Output:
//  Amount of data transferred
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32
XHCI_BulkTransfer(
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       XferDir,
    UINT8       *Buffer,
    UINT32      Length
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    XHCI_TRB    *Trb;
    XHCI_TRB    *FirstTrb;
    UINT8       SlotId;
    UINT8       CompletionCode;
    UINT8       Status;
    TRB_RING    *XfrRing;
    UINT8       Endpoint;
    UINT8       Dci;
    UINT64      DataPointer;
    UINT32      ResidualData;       // Transferred amount return by Transfer Event
    UINT32      TransferredSize;    // Total transfer amount
    UINT32      RingDataSize;       // One TRB ring transfer amount
    UINT32      RemainingXfrSize;
    UINT32      RemainingDataSize;
    UINT32      XfrSize;
    UINT32      XfrTdSize;
	UINT16		MaxPktSize;
	UINT32		TdSize;
	UINT16		TimeoutMs;
    EFI_STATUS  EfiStatus = EFI_SUCCESS;
    UINTN       DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return 0;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(EfiStatus)) {
        return 0;
    }
    
#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)Buffer, Length);
        if (EFI_ERROR(EfiStatus)) {
            USB_DEBUG(3, "Xhci BulkTransfer Invalid Pointer, Buffer is in SMRAM.\n");
            return 0;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return 0;
    }

    // Clear HW source of error
    gUsbData->bLastCommandStatus &= ~(USB_BULK_STALLED | USB_BULK_TIMEDOUT );
    gUsbData->dLastCommandStatusExtended = 0;

	if(DevInfo->Flag & DEV_INFO_DEV_DISCONNECTING) return 0;	//(EIP60460+)
	
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
    
    DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;
    
    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
            (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
        return 0;
    };

	TimeoutMs = gUsbData->wTimeOutValue;
    
    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return 0;
    }
	
    SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
    Endpoint = (XferDir & BIT7)? DevInfo->bBulkInEndpoint : DevInfo->bBulkOutEndpoint;
	MaxPktSize = (XferDir & BIT7)? DevInfo->wBulkInMaxPkt : DevInfo->wBulkOutMaxPkt;
    Dci = (Endpoint & 0xf)* 2;
    if (XferDir & BIT7) Dci++;

    XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci-1);

    // Make a chain of TDs to transfer the requested amount of data. If necessary,
    // make multiple transfers in a loop.

    DataPointer = (UINT64)(UINTN)Buffer;
    RemainingDataSize = Length;

    // Two loops are executing the transfer:
    // The inner loop creates a transfer ring of chained TDs, XHCI_BOT_TD_MAXSIZE
    // bytes each. This makes a ring capable of transferring
    // XHCI_BOT_TD_MAXSIZE * (TRBS_PER_SEGMENT-1) bytes.
    // The outter loop repeats the transfer if the requested transfer size exceeds
    // XHCI_BOT_TD_MAXSIZE * (TRBS_PER_SEGMENT-1).

    for (TransferredSize = 0; TransferredSize < Length;) {
        // Calculate the amount of data to transfer in the ring
        RingDataSize = (RemainingDataSize > XHCI_BOT_MAX_XFR_SIZE)?
            XHCI_BOT_MAX_XFR_SIZE : RemainingDataSize;

        RemainingXfrSize = RingDataSize;

        for (Trb = NULL, XfrSize = 0, FirstTrb = 0; XfrSize < RingDataSize;)
        {
            Trb = XHCI_AdvanceEnqueuePtr(XfrRing);
            if (Trb == NULL) {
                return 0;
            }
            if (FirstTrb == NULL) FirstTrb = Trb;

            Trb->TrbType = XhciTNormal;
            ((XHCI_NORMAL_XFR_TRB*)Trb)->Isp = 1;
            ((XHCI_NORMAL_XFR_TRB*)Trb)->DataBuffer = DataPointer;

            // See if we need a TD chain. Note that we do not need to
            // place the chained TRB into Event Ring, since we will not be
            // looking for it anyway. Set IOC only for the last-in-chain TRB.
            if (RemainingXfrSize > XHCI_BOT_TD_MAXSIZE) {
                XfrTdSize = XHCI_BOT_TD_MAXSIZE;
                ((XHCI_NORMAL_XFR_TRB*)Trb)->Chain = 1;
            } else {
                ((XHCI_NORMAL_XFR_TRB*)Trb)->Ioc = 1;
                XfrTdSize = RemainingXfrSize;
            }
			// Data buffers referenced by Transfer TRBs shall not span 64KB boundaries. 
			// If a physical data buffer spans a 64KB boundary, software shall chain 
			// multiple TRBs to describe the buffer.
			if (XfrTdSize > (UINT32)(0x10000 - (DataPointer & (0x10000 - 1)))) {
				XfrTdSize = (UINT32)(0x10000 - (DataPointer & (0x10000 - 1)));
				((XHCI_NORMAL_XFR_TRB*)Trb)->Chain = 1;
				((XHCI_NORMAL_XFR_TRB*)Trb)->Ioc = 0;
			}

            ((XHCI_NORMAL_XFR_TRB*)Trb)->XferLength = XfrTdSize;

            XfrSize += XfrTdSize;
            DataPointer += XfrTdSize;
            RemainingXfrSize -= XfrTdSize;

			if(Usb3Hc->HciVersion >= 0x100) {
				TdSize = 0;
				if (RemainingXfrSize != 0) {
					TdSize = RemainingXfrSize/MaxPktSize;
					if (RemainingXfrSize % MaxPktSize) {
						TdSize++;
					}
					TdSize = (TdSize > 31)? 31 : TdSize;
				}
			} else {
				TdSize = RemainingXfrSize + XfrTdSize;
				TdSize = (TdSize < 32768)? (TdSize >> 10) : 31;
			}

			((XHCI_NORMAL_XFR_TRB*)Trb)->TdSize = TdSize;
			if (Trb != FirstTrb) {
				((XHCI_NORMAL_XFR_TRB*)Trb)->CycleBit = XfrRing->CycleBit;
			}
        }
#if USB_RUNTIME_DRIVER_IN_SMM
        EfiStatus = AmiValidateMemoryBuffer((VOID*)XfrRing->LastTrb, sizeof(XHCI_NORMAL_XFR_TRB));
        if (EFI_ERROR(EfiStatus)) {
            break;
        }
#endif
        // If transfer ring crossed Link TRB, set its Chain flag
        if (Trb < FirstTrb) {
            ((XHCI_NORMAL_XFR_TRB*)XfrRing->LastTrb)->Chain = 1;
			
        }

		((XHCI_NORMAL_XFR_TRB*)FirstTrb)->CycleBit = XfrRing->CycleBit;
		if (Trb < FirstTrb) {
			((XHCI_NORMAL_XFR_TRB*)FirstTrb)->CycleBit ^= 1;
		}

        // Ring the door bell and see Event Ring update
        Status = XhciRingDoorbell(Usb3Hc, SlotId, Dci);

        if (Status != USB_SUCCESS) {
            break;
        }

        Status = XHCI_WaitForEvent(
                HcStruc, Trb, XhciTTransferEvt, SlotId, Dci,				//(EIP62376)
                &CompletionCode, TimeoutMs, &ResidualData);

        // Clear Link TRB chain flag
        ((XHCI_NORMAL_XFR_TRB*)XfrRing->LastTrb)->Chain = 0;

		if (Status != USB_SUCCESS) {
										//(EIP54283)>
			switch (CompletionCode) {
				case XHCI_TRB_BABBLE_ERROR:								//(EIP62376+)
				case XHCI_TRB_TRANSACTION_ERROR:
					XHCI_ClearStalledEp(Usb3Hc, HcStruc, SlotId, Dci);	//(EIP60460+)
					break;												//(EIP60460+)
				case XHCI_TRB_STALL_ERROR:
					XHCI_ResetEndpoint(Usb3Hc, HcStruc, SlotId, Dci);
					gUsbData->bLastCommandStatus |= USB_BULK_STALLED;
					gUsbData->dLastCommandStatusExtended |= USB_TRSFR_STALLED;
					break;
				case XHCI_TRB_EXECUTION_TIMEOUT_ERROR:
					XHCI_ClearEndpointState(HcStruc, DevInfo, Endpoint | XferDir);
					gUsbData->bLastCommandStatus |= USB_BULK_TIMEDOUT;
                    gUsbData->dLastCommandStatusExtended |= USB_TRNSFR_TIMEOUT;	//(EIP84790+)
					break;
				default:
					break;
			}
										//<(EIP54283)
			break;
		}

        TransferredSize += (RingDataSize - ResidualData);
        if (ResidualData != 0) break;   // Short packet detected, no more transfers
        RemainingDataSize -= RingDataSize;
    }

    return TransferredSize;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_InterruptTransfer
//
// Description:
//  This function executes an interrupt transaction on the USB. The data
//  transfer direction is always DATA_IN. This function wil not return until
//  the request either completes successfully or completes in error (due to
//  time out, etc.)
//
// 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
//
// Output:
//  Number of bytes transferred
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT16
XHCI_InterruptTransfer (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       EndpointAddress,
    UINT16      MaxPktSize,
    UINT8       *Buffer,
    UINT16      Length
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    XHCI_TRB    *Trb;
    UINT8       SlotId;
    UINT8       CompletionCode;
    UINT8       Status;
    TRB_RING    *XfrRing;
    UINT8       Dci;
	UINT16		TimeoutMs;
    UINT32      ResidualData; 
    EFI_STATUS  EfiStatus = EFI_SUCCESS;
    UINTN       DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return 0;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return 0;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)Buffer, Length);
        if (EFI_ERROR(EfiStatus)) {
            USB_DEBUG(3, "Xhci InterruptTransfer Invalid Pointer, Buffer is in SMRAM.\n");
            return 0;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif
	
	gUsbData->dLastCommandStatusExtended = 0;
	
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
	
	DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
            (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
        return 0;
    }

	TimeoutMs = gUsbData->wTimeOutValue;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return 0;
    }
    
    SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
    Dci = (EndpointAddress & 0xF) * 2;
    if (EndpointAddress & BIT7) Dci++;
	
    XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci-1);
	Trb = XHCI_AdvanceEnqueuePtr(XfrRing);
    if (Trb == NULL) {
        return 0;
    }
	Trb->TrbType = XhciTNormal;
	((XHCI_NORMAL_XFR_TRB*)Trb)->DataBuffer = (UINTN)Buffer;
	((XHCI_NORMAL_XFR_TRB*)Trb)->XferLength = Length;
	((XHCI_NORMAL_XFR_TRB*)Trb)->Isp = 1;
	((XHCI_NORMAL_XFR_TRB*)Trb)->Ioc = 1;
	((XHCI_NORMAL_XFR_TRB*)Trb)->CycleBit = XfrRing->CycleBit;
	
    // Ring the doorbell and see Event Ring update
	Status = XhciRingDoorbell(Usb3Hc, SlotId, Dci);

    if (Status != USB_SUCCESS) {
        return 0;
    }
   
    Status = XHCI_WaitForEvent(
                HcStruc, Trb, XhciTTransferEvt, SlotId, Dci,				//(EIP62376)
                &CompletionCode, TimeoutMs, &ResidualData);

	if (Status != USB_SUCCESS) {
										//(EIP54283)>
		switch (CompletionCode) {
										//(EIP62376+)>
			case XHCI_TRB_BABBLE_ERROR:
			case XHCI_TRB_TRANSACTION_ERROR:
				XHCI_ClearStalledEp(Usb3Hc, HcStruc, SlotId, Dci);
				break;
										//<(EIP62376+)
			case XHCI_TRB_STALL_ERROR:
				XHCI_ResetEndpoint(Usb3Hc, HcStruc, SlotId, Dci);
				break;
			case XHCI_TRB_EXECUTION_TIMEOUT_ERROR:
				XHCI_ClearEndpointState(HcStruc, DevInfo, EndpointAddress);
                gUsbData->dLastCommandStatusExtended |= USB_TRNSFR_TIMEOUT;
				break;
			default:
				break;
		}
										//<(EIP54283)
		return 0;
    } else {
        Length = Length - (UINT16)ResidualData;
	}

    return Length;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_DeactivatePolling
//
// Description:
//  This function de-activates the polling QH for the requested device. The
//  device may be a USB keyboard or USB hub.
//
// Input:
//  HcStruc   - Pointer to the HC structure
//  DevInfo   - Pointer to the device information structure
//
// Output:
//  USB_ERROR on error, USB_SUCCESS on success
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_DeactivatePolling(
    HC_STRUC* HcStruc,
    DEV_INFO* DevInfo
)
{
	USB3_HOST_CONTROLLER *Usb3Hc;
	UINT8       SlotId;
	UINT8		Dci;
	UINT16		EpInfo;
    TRB_RING    *XfrRing;
    XHCI_SET_TRPTR_CMD_TRB  Trb;
    XHCI_EP_CONTEXT *EpCtx;
    EFI_STATUS  EfiStatus;
    UINTN       DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }

	if (DevInfo->fpPollTDPtr == NULL) {
		return USB_ERROR;
	}

	USB_MemFree(DevInfo->fpPollTDPtr, GET_MEM_BLK_COUNT(DevInfo->PollingLength));

    DevInfo->fpPollTDPtr = NULL;

	SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
    Dci = (DevInfo->IntInEndpoint & 0xF) * 2;
    if (DevInfo->IntInEndpoint & BIT7) Dci++;

	EpInfo = (Dci << 8) + SlotId;

	DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

	if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
	        (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
	    return USB_ERROR;
	}
    
    EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)DevInfo->DevMiscInfo, Dci);

    if (EpCtx->EpState == XHCI_EP_STATE_RUNNING) {
	    XHCI_ExecuteCommand(HcStruc, XhciTStopEndpointCmd, &EpInfo);
    }
    
    // Set TR Dequeue Pointer command may be executed only if the target 
    // endpoint is in the Error or Stopped state.
    if ((EpCtx->EpState == XHCI_EP_STATE_STOPPED) || 
        (EpCtx->EpState == XHCI_EP_STATE_ERROR)) {
        
    	XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci-1);

    	Trb.TrPointer = (UINT64)((UINTN)XfrRing->QueuePtr + XfrRing->CycleBit); // Set up DCS
    	Trb.EndpointId = Dci;
    	Trb.SlotId = SlotId;
    	XHCI_ExecuteCommand(HcStruc, XhciTSetTRDequeuePointerCmd, &Trb);
    }

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_ActivatePolling
//
// Description:
//  This function activates the polling QH for the requested device. The device
//  may be a USB keyboard or USB hub.
//
// Input:
//  HcStruc   - Pointer to the HC structure
//  DevInfo   - Pointer to the device information structure
//
// Output:
//  USB_ERROR on error, USB_SUCCESS on success
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ActivatePolling(
    HC_STRUC* HcStruc,
    DEV_INFO* DevInfo
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    XHCI_TRB    *Trb;
    volatile UINT32 *Doorbell;
    UINT8       SlotId;
    TRB_RING    *XfrRing;
    UINT8		Dci;
    EFI_STATUS  EfiStatus;
    UINTN       DeviceContextSize;

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }
    
    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }
    
    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }

    DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
    	    (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
    	return USB_ERROR;
    }
    
    SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
    Dci = (DevInfo->IntInEndpoint & 0xF) * 2;
    if (DevInfo->IntInEndpoint & BIT7) Dci++;
    DevInfo->fpPollTDPtr = USB_MemAlloc(GET_MEM_BLK_COUNT(DevInfo->PollingLength));
    XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci - 1);

    Trb = XHCI_AdvanceEnqueuePtr(XfrRing);
    if (Trb == NULL) {
        return USB_ERROR;
    }
    Trb->TrbType = XhciTNormal;
    ((XHCI_NORMAL_XFR_TRB*)Trb)->DataBuffer = (UINT64)(UINTN)DevInfo->fpPollTDPtr;
    ((XHCI_NORMAL_XFR_TRB*)Trb)->XferLength = DevInfo->PollingLength;
	((XHCI_NORMAL_XFR_TRB*)Trb)->Isp = 1;	//(EIP51478+)
    ((XHCI_NORMAL_XFR_TRB*)Trb)->Ioc = 1;
	((XHCI_NORMAL_XFR_TRB*)Trb)->CycleBit = XfrRing->CycleBit;

    // Ring the door bell
    Doorbell = XHCI_GetTheDoorbell(Usb3Hc, SlotId);
    *Doorbell = Dci;

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        XHCI_DisableKeyRepeat
//
// Description:
//  This function disables the keyboard repeat rate logic
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_ERROR on error, USB_SUCCESS on success
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_DisableKeyRepeat (
    HC_STRUC* HcStruc
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }
	
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }

    XHCI_Mmio64Write(HcStruc, Usb3Hc,
        (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)Usb3Hc->EvtRing.QueuePtr | BIT3);

    Usb3Hc->RtRegs->IntRegs[0].IMod = XHCI_IMODI;

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_EnableKeyRepeat
//
// Description:
//  This function disables the keyboard repeat rate logic
//
// Input:
//  HcStruc  - Pointer to the HC structure
//
// Output:
//  USB_ERROR on error, USB_SUCCESS on success
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_EnableKeyRepeat(
    HC_STRUC* HcStruc
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }
	
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }
 
    XHCI_Mmio64Write(HcStruc, Usb3Hc,
        (UINTN)&Usb3Hc->RtRegs->IntRegs->Erdp, (UINT64)(UINTN)0 | BIT3);

    Usb3Hc->RtRegs->IntRegs[0].IMod = (XHCI_KEYREPEAT_IMODC << 16 | XHCI_KEYREPEAT_IMODI);

    return USB_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_InitXfrRing
//
// Description:
//  This function initializes transfer ring of given endpoint
//
// Output:
//  Pointer to the transfer ring
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

TRB_RING*
XHCI_InitXfrRing(
    USB3_HOST_CONTROLLER* Usb3Hc,
    UINT8   Slot,
    UINT8   Ep
)
{
    TRB_RING    *XfrRing = Usb3Hc->XfrRings + (Slot-1)*32 + Ep;
    UINTN       Base = Usb3Hc->XfrTrbs + ((Slot-1)*32+Ep)*RING_SIZE;

    XHCI_InitRing(XfrRing, Base, TRBS_PER_SEGMENT, TRUE);

    return XfrRing;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        Xhci_TranslateInterval
//
// Description:
//  This routine calculates the Interval field to be used in device's endpoint
//  context. Interval is calculated using the following rules (Section 6.2.3.6):
//
//  For SuperSpeed bulk and control endpoints, the Interval field shall not be
//  used by the xHC. For all other endpoint types and speeds, system software
//  shall translate the bInterval field in the USB Endpoint Descriptor to the
//  appropriate value for this field.
//
//  For high-speed and SuperSpeed Interrupt and Isoch endpoints the bInterval
//  field the Endpoint Descriptor is computed as 125æs * 2^(bInterval-1), where
//  bInterval = 1 to 16, therefore Interval = bInterval - 1.
//
//  For low-speed Interrupt and full-speed Interrupt and Isoch endpoints the
//  bInterval field declared by a Full or Low-speed device is computed as
//  bInterval * 1ms., where bInterval = 1 to 255.
//
//  For Full- and Low-speed devices software shall round the value of Endpoint
//  Context Interval field down to the nearest base 2 multiple of bInterval * 8.
//
// Input:
//  EpType      Endpoint type, see XHCI_EP_CONTEXT.DW1.EpType field definitions
//  Speed       Endpoint speed, 1..4 for XHCI_DEVSPEED_FULL, _LOW, _HIGH, _SUPER
//  Interval    Poll interval value from endpoint descriptor
//
// Output:
//  Interval value to be written to the endpoint context
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
Xhci_TranslateInterval(
    UINT8   EpType,
    UINT8   Speed,
    UINT8   Interval
)
{
    UINT8  TempData;
    UINT8  BitCount;

	if (Interval == 0) {
		return 0;
	}

    if (EpType == XHCI_EPTYPE_CTL || 
        EpType == XHCI_EPTYPE_BULK_OUT || 
        EpType == XHCI_EPTYPE_BULK_IN) {

		if (Speed == XHCI_DEVSPEED_HIGH) {
			for (TempData = Interval, BitCount = 0; TempData != 0; BitCount++) {
				TempData >>= 1;
			}
			return BitCount - 1;
		} else {
			return 0; // Interval field will not be used for LS, FS and SS
		}
    }

    // Control and Bulk endpoints are processed; translate intervals for Isoc and Interrupt
    // endpoints

    // Translate SS and HS endpoints
    if (Speed == XHCI_DEVSPEED_SUPER || 
            Speed == XHCI_DEVSPEED_SUPER_PLUS ||
            Speed == XHCI_DEVSPEED_HIGH) {
        return (Interval - 1);
    }

    // Translate interval for FS and LS endpoints
    ASSERT(Interval > 0);

    for (TempData = Interval, BitCount = 0; TempData != 0; BitCount++) {
        TempData >>= 1;
    }
    return (BitCount + 2);  // return value, where Interval = 0.125*2^value
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_EnableEndpoints
//
// Description:
//  This function parses the device descriptor data and enables the endpoints
//  by 1)assigning the Transfer TRB and 2)executing ConfigureEndpoint command
//  for the slot. Section 4.3.5.
//
// Input:
//  DevInfo - A device for which the endpoins are being enabled
//  Desc    - Device Configuration Descriptor data pointer
//
// Output:
//  USB_ERROR on error, USB_SUCCESS on success
//
// Notes:
//  1) DevInfo->DevMiscInfo points to the device context
//  2) This call is executed before SET_CONFIGURATION control transfer
//  3) EP0 information is valid in the Device
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_EnableEndpoints (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       *Desc
)
{
    UINT16          TotalLength;
    UINT16          CurPos;
    UINT8           Dci;
	INTRF_DESC		*IntrfDesc;
    ENDP_DESC       *EpDesc;
    SS_ENDP_COMP_DESC      *SsEpCompDesc = NULL;
	HUB_DESC		*HubDesc; 
    TRB_RING        *XfrRing;
    UINT8           EpType;
    UINT8           Status;
	UINT8			IsHub = 0;			//(EIP73020)
	UINT8			Speed;
	XHCI_INPUT_CONTROL_CONTEXT	*CtlCtx;
	XHCI_SLOT_CONTEXT			*SlotCtx;
	XHCI_EP_CONTEXT 			*EpCtx;
    USB3_HOST_CONTROLLER *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
    UINT8 SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);

    EFI_STATUS  EfiStatus = EFI_SUCCESS;
    UINTN           DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);
    
    if (EFI_ERROR(EfiStatus)) {
        return USB_ERROR;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }
	
#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)Desc, sizeof(CNFG_DESC));
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
    }
#endif

    if (((CNFG_DESC*)Desc)->bDescType != DESC_TYPE_CONFIG) return USB_ERROR;

    DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
            (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
        return USB_ERROR;
    }

	SlotCtx = (XHCI_SLOT_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)DevInfo->DevMiscInfo, 0);
	Speed = SlotCtx->Speed;

    // Note (From 4.6.6): The Add Context flag A1 and Drop Context flags D0 and D1
    // of the Input Control Context (in the Input Context) shall be cleared to 0.
    // Endpoint 0 Context does not apply to the Configure Endpoint Command and
    // shall be ignored by the xHC. A0 shall be set to 1.

    // Note (From 6.2.2.2): If Hub = 1 and Speed = High-Speed (3), then the
    // TT Think Time and Multi-TT (MTT) fields shall be initialized.
    // If Hub = 1, then the Number of Ports field shall be initialized, else
    // Number of Ports = 0.

    // Prepare input context for EvaluateContext comand
    MemFill((UINT8*)Usb3Hc->InputContext, XHCI_INPUT_CONTEXT_ENTRIES * Usb3Hc->ContextSize, 0);

    CtlCtx = (XHCI_INPUT_CONTROL_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)Usb3Hc->InputContext, 0);
    CtlCtx->AddContextFlags = BIT0;    // EP0

	SlotCtx = (XHCI_SLOT_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)Usb3Hc->InputContext, 1);

    // Collect the endpoint information and update the Device Input Context
    TotalLength = ((CNFG_DESC*)Desc)->wTotalLength;

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)Desc, TotalLength);
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    if (TotalLength > (MAX_CONTROL_DATA_SIZE - 1)) {
        TotalLength = MAX_CONTROL_DATA_SIZE - 1;
    }

    for (CurPos = 0; CurPos < TotalLength; CurPos += EpDesc->bDescLength) {
		EpDesc = (ENDP_DESC*)(IntrfDesc = (INTRF_DESC*)(Desc + CurPos));

		if (IntrfDesc->bDescLength == 0) {
			break;
		}
		
		if ((CurPos + IntrfDesc->bDescLength) > TotalLength) {
			break;
		}
	
		if (IntrfDesc->bDescType == DESC_TYPE_INTERFACE) {
			IsHub = IntrfDesc->bBaseClass == BASE_CLASS_HUB;
			continue;
		}
	
        if (EpDesc->bDescType != DESC_TYPE_ENDPOINT) continue;

        // Found Endpoint, fill up the information in the InputContext

        // Calculate Device Context Index (DCI), Section 4.5.1.
        // 1) For Isoch, Interrupt, or Bulk type endpoints the DCI is calculated
        // from the Endpoint Number and Direction with the following formula:
        //  DCI = (Endpoint Number * 2) + Direction, where Direction = 0 for OUT
        // endpoints and 1 for IN endpoints.
        // 2) For Control type endpoints:
        //  DCI = (Endpoint Number * 2) + 1
        //
        // Also calculate XHCI EP type out of EpDesc->bEndpointFlags

        if ((EpDesc->bEndpointFlags & EP_DESC_FLAG_TYPE_BITS) == EP_DESC_FLAG_TYPE_CONT) {
            Dci = (EpDesc->bEndpointAddr & 0xf) * 2 + 1;
            EpType = XHCI_EPTYPE_CTL;
        } else {
            // Isoc, Bulk or Interrupt endpoint
            Dci = (EpDesc->bEndpointAddr & 0xf) * 2;
            EpType = EpDesc->bEndpointFlags & EP_DESC_FLAG_TYPE_BITS;   // 1, 2, or 3

            if (EpDesc->bEndpointAddr & BIT7) {
                Dci++;          // IN
                EpType += 4;    // 5, 6, or 7
            }
        }

        // Update ContextEntries in the Slot context
        if (Dci > SlotCtx->ContextEntries) {
            SlotCtx->ContextEntries = Dci;
        }

        EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)Usb3Hc->InputContext, Dci + 1);

        EpCtx->EpType = EpType;

        // The Endpoint Companion descriptor shall immediately follow the 
        // endpoint descriptor it is associated with in the configuration information. 

        if ((DevInfo->bEndpointSpeed == USB_DEV_SPEED_SUPER) ||
            (DevInfo->bEndpointSpeed == USB_DEV_SPEED_SUPER_PLUS)) {
            SsEpCompDesc = (SS_ENDP_COMP_DESC*)(Desc + CurPos + EpDesc->bDescLength);
            if (SsEpCompDesc->DescType == DESC_TYPE_SS_EP_COMP) {
                EpCtx->MaxBurstSize = SsEpCompDesc->MaxBurst;
            }
        }

        // wMaxPacketSize
        // USB 2.0 spec
        // For all endpoints, bits 10..0 specify the maximum packet size (in bytes).
        // For high-speed isochronous and interrupt endpoints:
        // Bits 12..11 specify the number of additional transaction
        // opportunities per microframe:
        // 00 = None (1 transaction per microframe)
        // 01 = 1 additional (2 per microframe)
        // 10 = 2 additional (3 per microframe)
        // 11 = Reserved
        // Bits 15..13 are reserved and must be set to zero.
        // USB 3.0 & 3.1 spec
        // Maximum packet size this endpoint is capable of sending or receiving 
        // when this configuration is selected. 
        // For control endpoints this field shall be set to 512.  For bulk endpoint 
        // types this field shall be set to 1024. 
        // For interrupt and isochronous endpoints this field shall be set to 1024 if 
        // this endpoint defines a value in the bMaxBurst field greater than zero. 
        // If the value in the bMaxBurst field is set to zero then this field can 
        // have any value from 0 to 1024 for an isochronous endpoint and 1 to 
        // 1024 for an interrupt endpoint. 

        // Only reserve bits 10..0
        EpCtx->MaxPacketSize = (EpDesc->wMaxPacketSize & 0x07FF);

        // 4.14.1.1 System Bus Bandwidth Scheduling
        // Reasonable initial values of Average TRB Length for Control endpoints 
        // Control endpoints would be 8B, Interrupt endpoints 1KB, 
        // and Bulk and Isoch endpoints 3KB.
        
        switch (EpCtx->EpType) {
            case XHCI_EP_TYPE_ISO_OUT:
            case XHCI_EP_TYPE_ISO_IN:
                EpCtx->ErrorCount = 0;
                EpCtx->AvgTrbLength = 0xC00;
                break;
            case XHCI_EP_TYPE_BLK_OUT:
            case XHCI_EP_TYPE_BLK_IN:
                EpCtx->ErrorCount = 3;
                EpCtx->AvgTrbLength = 0xC00;
                break;
            case XHCI_EP_TYPE_INT_OUT:
            case XHCI_EP_TYPE_INT_IN:
                EpCtx->ErrorCount = 3;
                EpCtx->AvgTrbLength = 0x400;
                break;
            case XHCI_EP_TYPE_CONTROL:
                EpCtx->ErrorCount = 3;
                EpCtx->AvgTrbLength = 0x08;
                break;
            default:
                break;
        }
        
        // Set Interval 
        EpCtx->Interval = Xhci_TranslateInterval(EpType, Speed, EpDesc->bPollInterval);

        XfrRing = XHCI_InitXfrRing(Usb3Hc, SlotId, Dci - 1);
        EpCtx->TrDequeuePtr = (UINT64)(UINTN)XfrRing->Base + 1;

        CtlCtx->AddContextFlags |= (1 << Dci);
    }

    // For a HUB update NumberOfPorts and TTT fields in the Slot context. For that get hub descriptor
    // and use bNbrPorts and TT Think time fields (11.23.2.1 of USB2 specification)
    // Notes:
    //  - Slot.Hub field is already updated
    //  - Do not set NumberOfPorts and TTT fields for 0.95 controllers

	if (IsHub) {
		HubDesc = (HUB_DESC*)USB_MemAlloc(sizeof(MEM_BLK));
		UsbHubGetHubDescriptor(HcStruc, DevInfo, HubDesc, sizeof(MEM_BLK));
		//ASSERT(HubDesc->bDescType == DESC_TYPE_HUB || HubDesc->bDescType == DESC_TYPE_SS_HUB);
		if ((HubDesc->bDescType == DESC_TYPE_HUB) || 
			(HubDesc->bDescType == DESC_TYPE_SS_HUB)) {
			SlotCtx->Hub = 1;
			SlotCtx->PortsNum = HubDesc->bNumPorts;
		
			if (Speed == XHCI_DEVSPEED_HIGH) {
				SlotCtx->TThinkTime = (HubDesc->wHubFlags >> 5) & 0x3;
			}
		}
		USB_MemFree(HubDesc, sizeof(MEM_BLK));
	}

    // Input context is updated with the endpoint information. Execute ConfigureEndpoint command.
    Status = XHCI_ExecuteCommand(HcStruc, XhciTConfigureEndpointCmd, &SlotId);
    ASSERT(Status == USB_SUCCESS);

    return Status;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_GetRootHubPort
//
// Description:
//  This function returns a root hub number for a given device. If device is
//  connected to the root through hub(s), it searches the parent's chain up
//  to the root.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_GetRootHubPort(
    DEV_INFO    *DevInfo
)
{
    UINT8       i;

    if ((DevInfo->bHubDeviceNumber & BIT7) != 0) return DevInfo->bHubPortNumber;

    for (i = 1; i < MAX_DEVICES; i++) {
		if ((gUsbData->aDevInfoTable[i].Flag & DEV_INFO_VALIDPRESENT)
            != DEV_INFO_VALIDPRESENT) {
			continue;
		}
        if (gUsbData->aDevInfoTable[i].bDeviceAddress == DevInfo->bHubDeviceNumber) {
            return XHCI_GetRootHubPort(&gUsbData->aDevInfoTable[i]);
        }
    }
    ASSERT(FALSE);  // Device parent hub found
    return 0;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_InitDeviceData
//
// Description:
//  This is an API function for early device initialization.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_InitDeviceData (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       PortStatus,
    UINT8       **DeviceData
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    UINT8	Status;
    UINT8   SlotId;
    VOID	*DevCtx;
    EFI_STATUS  EfiStatus;

    EfiStatus = UsbHcStrucValidation(HcStruc);

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

    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }
	
#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)DeviceData, sizeof(UINT8*));
        if (EFI_ERROR(EfiStatus)) {
            return USB_ERROR;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }

    // Obtain device slot using Enable Slot command, 4.3.2, 4.6.3
    Status = XHCI_ExecuteCommand(HcStruc, XhciTEnableSlotCmd, &SlotId);
    //ASSERT(Status == USB_SUCCESS);
    //ASSERT(SlotId != 0);
    if (Status != USB_SUCCESS) {
        return Status;
    }

    DevCtx = XHCI_GetDeviceContext(Usb3Hc, SlotId);	
    MemSet(DevCtx, XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize, 0);

    // Update DCBAA with the new device pointer (index = SlotId)
    Usb3Hc->DcbaaPtr->DevCntxtAddr[SlotId-1] = (UINT64)(UINTN)DevCtx;
    USB_DEBUG(3, "XHCI: Slot[%d] enabled, device context at %x\n", SlotId, DevCtx);

    Status = XhciAddressDevice(HcStruc, DevInfo, SlotId);
    if (Status != USB_SUCCESS) {
        return Status;
    }

    *DeviceData = (UINT8*)DevCtx;
    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_DeinitDeviceData
//
// Description:
//  This is an API function for removing device related information from HC.
//  For xHCI this means:
//  - execute DisableSlot commnand
//  - clear all endpoint's transfer rings
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_DeinitDeviceData (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo
)
{
    USB3_HOST_CONTROLLER *Usb3Hc;
    UINT8 SlotId;
    UINT8 Dci;
    TRB_RING *XfrRing;
	XHCI_SLOT_CONTEXT	*SlotCtx;
	XHCI_EP_CONTEXT		*EpCtx;
	UINT16	EpInfo;
    EFI_STATUS  EfiStatus;
    UINTN       DeviceContextSize;
    
    EfiStatus = UsbHcStrucValidation(HcStruc);

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

    EfiStatus = UsbDevInfoValidation(DevInfo);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }
	
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }
    
    DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
            (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
        return USB_SUCCESS;
    }

	SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
	if (Usb3Hc->DcbaaPtr->DevCntxtAddr[SlotId-1] == 0) return USB_SUCCESS;

	SlotCtx = (XHCI_SLOT_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)DevInfo->DevMiscInfo, 0);
	
    // Stop transfer rings
    for (Dci = 1; Dci <= SlotCtx->ContextEntries; Dci++) {
		EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, (UINT8*)DevInfo->DevMiscInfo, Dci);
        if (EpCtx->TrDequeuePtr != 0) {
			if (EpCtx->EpState == XHCI_EP_STATE_RUNNING) {
				EpInfo = (Dci << 8) + SlotId;
				XHCI_ExecuteCommand(HcStruc, XhciTStopEndpointCmd, &EpInfo);
        	}

			// Clear transfer rings
            XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci - 1);
			MemFill((UINT8*)XfrRing->Base, RING_SIZE, 0);
        }
    }

    XHCI_ExecuteCommand(HcStruc, XhciTDisableSlotCmd, &SlotId);

	Usb3Hc->DcbaaPtr->DevCntxtAddr[SlotId-1] = 0;
	DevInfo->DevMiscInfo = NULL;

    return USB_SUCCESS;
}

										//(EIP54283+)>
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_ClearEndpointState
//
// Description:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_ClearEndpointState(
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
	UINT8		Endpoint
)
{
	USB3_HOST_CONTROLLER *Usb3Hc;
	UINT8		SlotId;
	UINT8		Dci;
    TRB_RING    *XfrRing;
    UINT8       Status = USB_SUCCESS;
    XHCI_SET_TRPTR_CMD_TRB  Trb;
    XHCI_EP_CONTEXT     *EpCtx;
	UINT16      EpInfo;
    EFI_STATUS  EfiStatus;
    UINTN       DeviceContextSize;

    EfiStatus = UsbHcStrucValidation(HcStruc);

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

    if (!(HcStruc->dHCFlag & HC_STATE_RUNNING)) {
        return USB_ERROR;
    }
	
    Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;

    if (Usb3Hc->OpRegs->UsbSts.Field.HcHalted) {
        return USB_ERROR;
    }

	if (DevInfo->DevMiscInfo == NULL) {
		return Status;
	}

	SlotId = XHCI_GetSlotId(Usb3Hc, DevInfo);
	if (Endpoint != 0) {
		Dci = (Endpoint & 0xF) * 2 + (Endpoint >> 7);
	} else {
		Dci = 1;
	}

    DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

    if ((DevInfo->DevMiscInfo < Usb3Hc->DeviceContext) ||
            (DevInfo->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
        return USB_ERROR;
    }
										//<(EIP60460+)
	EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, DevInfo->DevMiscInfo, Dci);
                                        
    if (EpCtx->EpState == XHCI_EP_STATE_RUNNING) {                                        
        EpInfo = (Dci << 8) + SlotId;
        Status = XHCI_ExecuteCommand(HcStruc, XhciTStopEndpointCmd, &EpInfo);
    }                                   //<(EIP54300+)

    // Set TR Dequeue Pointer command may be executed only if the target 
    // endpoint is in the Error or Stopped state.
    if ((EpCtx->EpState == XHCI_EP_STATE_STOPPED) ||
        (EpCtx->EpState == XHCI_EP_STATE_ERROR)) {
    
    	XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, Dci-1);

    	Trb.TrPointer = (UINT64)((UINTN)XfrRing->QueuePtr + XfrRing->CycleBit); // Set up DCS
    	Trb.EndpointId = Dci;
    	Trb.SlotId = SlotId;

    	Status = XHCI_ExecuteCommand(HcStruc, XhciTSetTRDequeuePointerCmd, &Trb);
    }
	//ASSERT(Status == USB_SUCCESS);

//	Doorbell = XHCI_GetTheDoorbell(Usb3Hc, SlotId);		//(EIP61849-)
// 	*Doorbell = Dci;									//(EIP61849-)

	return Status;
}
										//<(EIP54283+)
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:		XhciAddressDevice
//
// Description:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XhciAddressDevice (
	HC_STRUC    *HcStruc,
	DEV_INFO    *DevInfo,
	UINT8		SlotId
)
{
    USB3_HOST_CONTROLLER        *Usb3Hc = (USB3_HOST_CONTROLLER*)HcStruc->usbbus_data;
    XHCI_INPUT_CONTROL_CONTEXT  *InputCtrl = NULL;
    XHCI_SLOT_CONTEXT           *InputSlot = NULL;
    XHCI_SLOT_CONTEXT           *OutputSlot = NULL;
    XHCI_SLOT_CONTEXT           *ParentHubSlotCtx = NULL;
    XHCI_EP_CONTEXT             *InputEp0 = NULL;
    XHCI_EP_CONTEXT             *OutputEp0 = NULL;
    UINT8                       Status = USB_ERROR;
    VOID                        *DevCtx = XHCI_GetDeviceContext(Usb3Hc, SlotId);
    VOID                        *InputCtx = Usb3Hc->InputContext;
    TRB_RING                    *XfrRing = NULL;
    DEV_INFO                    *ParentHub = NULL;
    UINT8                       HubPortNumber = 0;
    UINT16                      AddrDevParam = 0;
    UINT8                       Bsr = 0;
    UINTN                       DeviceContextSize;

    OutputSlot = XHCI_GetContextEntry(Usb3Hc, DevCtx, 0);
    if (OutputSlot->SlotState >= XHCI_SLOT_STATE_ADDRESSED) {
        return USB_ERROR;
    }

    // Zero the InputContext and DeviceContext
    MemSet(InputCtx, XHCI_INPUT_CONTEXT_ENTRIES * Usb3Hc->ContextSize, 0);

    // Initialize the Input Control Context of the Input Context
    // by setting the A0 flags to 1
    InputCtrl = XHCI_GetContextEntry(Usb3Hc, InputCtx, 0);
    InputCtrl->AddContextFlags = BIT0 | BIT1;

    // Initialize the Input Slot Context data structure
    InputSlot = XHCI_GetContextEntry(Usb3Hc, InputCtx, 1);
    InputSlot->RouteString = 0;
    InputSlot->ContextEntries = 1;
    InputSlot->RootHubPort = XHCI_GetRootHubPort(DevInfo);

    switch (DevInfo->bEndpointSpeed) {
        case USB_DEV_SPEED_SUPER_PLUS:
            InputSlot->Speed = XHCI_DEVSPEED_SUPER_PLUS;
            break;
        case USB_DEV_SPEED_SUPER:
            InputSlot->Speed = XHCI_DEVSPEED_SUPER;
            break;
        case USB_DEV_SPEED_HIGH:
            InputSlot->Speed = XHCI_DEVSPEED_HIGH; 
            break;
        case USB_DEV_SPEED_LOW:
            InputSlot->Speed = XHCI_DEVSPEED_LOW;
            break;
        case USB_DEV_SPEED_FULL:
            InputSlot->Speed = XHCI_DEVSPEED_FULL;
            break;
    }

    // Initialize Route String and TT fields
    ParentHub = USB_GetDeviceInfoStruc(USB_SRCH_DEV_ADDR,
                            0, DevInfo->bHubDeviceNumber, 0);
    if (ParentHub != NULL) {
        DeviceContextSize = (XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize) * Usb3Hc->CapRegs->HcsParams1.MaxSlots;

        if ((ParentHub->DevMiscInfo < Usb3Hc->DeviceContext) ||
                (ParentHub->DevMiscInfo > (VOID*)((UINTN)(Usb3Hc->DeviceContext) + DeviceContextSize))) {
            return 0;
        }
        ParentHubSlotCtx = XHCI_GetContextEntry(Usb3Hc, ParentHub->DevMiscInfo, 0);
        HubPortNumber = (DevInfo->bHubPortNumber > 15)? 15 : DevInfo->bHubPortNumber;
        InputSlot->RouteString = ParentHubSlotCtx->RouteString | 
                                (HubPortNumber << (ParentHub->HubDepth * 4));	//(EIP51503)

        // Update TT fields in the Slot context for LS/FS device connected to HS hub
        if (InputSlot->Speed == XHCI_DEVSPEED_FULL || InputSlot->Speed == XHCI_DEVSPEED_LOW) {
            if (ParentHubSlotCtx->Speed == XHCI_DEVSPEED_HIGH) {
                InputSlot->TtHubSlotId = XHCI_GetSlotId(Usb3Hc, ParentHub);
                InputSlot->TtPortNumber = DevInfo->bHubPortNumber;
                InputSlot->MultiTT = ParentHubSlotCtx->MultiTT;
            } else {
                InputSlot->TtHubSlotId = ParentHubSlotCtx->TtHubSlotId;
                InputSlot->TtPortNumber = ParentHubSlotCtx->TtPortNumber;
                InputSlot->MultiTT = ParentHubSlotCtx->MultiTT;
            }
        }
    }

    OutputEp0 = XHCI_GetContextEntry(Usb3Hc, DevCtx, 1);
    switch (OutputEp0->EpState) {
        case XHCI_EP_STATE_DISABLED:
            XfrRing = XHCI_InitXfrRing(Usb3Hc, SlotId, 0);
            break;
        case XHCI_EP_STATE_RUNNING:
        case XHCI_EP_STATE_STOPPED:
            XfrRing = XHCI_GetXfrRing(Usb3Hc, SlotId, 0);
            break;
        default:
            break;
    }

    // Initialize the Input default control Endpoint 0 Context
    InputEp0 = XHCI_GetContextEntry(Usb3Hc, InputCtx, 2);
    InputEp0->EpType = XHCI_EPTYPE_CTL;
    InputEp0->MaxPacketSize = DevInfo->wEndp0MaxPacket;
    InputEp0->TrDequeuePtr = (UINT64)(UINTN)XfrRing->QueuePtr | XfrRing->CycleBit;
    InputEp0->AvgTrbLength = 8;
    InputEp0->ErrorCount = 3;

    Bsr = (InputSlot->Speed != XHCI_DEVSPEED_SUPER &&
            InputSlot->Speed != XHCI_DEVSPEED_SUPER_PLUS && 
            OutputSlot->SlotState == XHCI_SLOT_STATE_DISABLED) ? 1 : 0;

    AddrDevParam = (UINT16)SlotId | (Bsr << 8);

    // Assign a new address 4.3.4, 4.6.5
    Status = XHCI_ExecuteCommand(HcStruc, XhciTAddressDeviceCmd, &AddrDevParam);
    if (Status != USB_SUCCESS) {
        XHCI_ExecuteCommand(HcStruc, XhciTDisableSlotCmd, &SlotId);
        Usb3Hc->DcbaaPtr->DevCntxtAddr[SlotId-1] = 0;
        return Status;
    }

    if (Bsr == 0) {
        USB_DEBUG(3, "XHCI: new device address %d\n", OutputSlot->DevAddr);
    }

    return USB_SUCCESS;
}
									
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:		XhciRingDoorbell
//
// Description:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XhciRingDoorbell(
	USB3_HOST_CONTROLLER	*Usb3Hc,
	UINT8					SlotId,
	UINT8					Dci
)
{
	volatile UINT32 *Doorbell;
	XHCI_EP_CONTEXT *EpCtx = NULL;
	UINT32	Count;

	Doorbell = XHCI_GetTheDoorbell(Usb3Hc, SlotId);
	*Doorbell = Dci;

	if (SlotId == 0) {
		return USB_ERROR;
	}

	EpCtx = (XHCI_EP_CONTEXT*)XHCI_GetContextEntry(Usb3Hc, 
					XHCI_GetDeviceContext(Usb3Hc, SlotId), Dci);
	// Wait for the endpoint running
	for (Count = 0; Count < 10 * 1000; Count++) {
		if (EpCtx->EpState == XHCI_EP_STATE_RUNNING) {
			break;
		}
		FixedDelay(1);    // 1 us delay
	}
	//ASSERT(EpCtx->EpState == XHCI_EP_STATE_RUNNING);

    if (EpCtx->EpState != XHCI_EP_STATE_RUNNING) {
        return USB_ERROR;
    }

	return USB_SUCCESS;
}
										//<(EIP54283+)

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_Mmio64Write
//
// Description:
//  HC may or may not support 64-bit writes to MMIO area. If it does, write
//  Data directly, otherwise split into two DWORDs.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT64
XHCI_Mmio64Read(
    HC_STRUC    *HcStruc,
	USB3_HOST_CONTROLLER *Usb3Hc,
	UINTN	Address
)
{
	UINT64	Data = 0;
    UINT32  Offset;

    Offset = (UINT32)(Address - HcStruc->BaseAddress);

    if ((Offset + sizeof(UINT64)) > HcStruc->BaseAddressSize) {
        return 0;
    }
    
	if (Usb3Hc->Access64) {
		Data = *(UINT64*)Address;
	}
	else {
		Data = *(UINT32*)Address;
		Data = Shl64(*(UINT32*)(Address + sizeof(UINT32)), 32);
	}
	return Data;
}

VOID
XHCI_Mmio64Write(
    HC_STRUC    *HcStruc,
    USB3_HOST_CONTROLLER *Usb3Hc,
    UINTN   Address,
    UINT64  Data
)
{
    UINT32  Offset;

    Offset = (UINT32)(Address - HcStruc->BaseAddress);

    if ((Offset + sizeof(UINT64)) > HcStruc->BaseAddressSize) {
        return;
    }
    
    if (Usb3Hc->Access64) {
        *(UINT64*)Address = Data;
    }
    else {
        *(UINT32*)Address = (UINT32)Data;
        *(UINT32*)(Address + sizeof(UINT32)) = (UINT32)(Shr64(Data, 32));
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_InitRing
//
// Description:
//  Transfer ring initialization. There is an option to create a Link TRB in
//  the end of the ring.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
XHCI_InitRing (
    IN OUT TRB_RING *Ring,
    IN UINTN    RingBase,
    IN UINT32   RingSize,
    IN BOOLEAN  PlaceLinkTrb
)
{
    XHCI_LINK_TRB   *LinkTrb;
    EFI_STATUS  Status = EFI_SUCCESS;

    Ring->Base = (XHCI_TRB*)RingBase;
    Ring->Size = RingSize;
    Ring->LastTrb = Ring->Base + RingSize - 1;
    Ring->CycleBit = 1;
    Ring->QueuePtr = (XHCI_TRB*)RingBase;

    // Initialize ring with zeroes
    {
        UINT8   *p = (UINT8*)RingBase;
        UINTN   i;
        for (i = 0; i < RingSize*sizeof(XHCI_TRB); i++, p++) *p = 0;
    }

    if (PlaceLinkTrb) {
        // Place a Link TRB in the end of the ring pointing to the beginning
        LinkTrb = (XHCI_LINK_TRB*)Ring->LastTrb;
#if USB_RUNTIME_DRIVER_IN_SMM
        Status = AmiValidateMemoryBuffer((VOID*)LinkTrb, sizeof(XHCI_LINK_TRB));
        if (EFI_ERROR(Status)) {
            return Status;
        }
#endif
        LinkTrb->NextSegPtr = (UINT64)(UINTN)RingBase;
        LinkTrb->ToggleCycle = 1;
        LinkTrb->TrbType = XhciTLink;
    }

    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   UpdatePortStatusSpeed
//
// Description:
//  This function sets USB_PORT_STAT... fields that are related to device
//  speed (LS/FS/HS/SS) in a given PortStatus variable.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
UpdatePortStatusSpeed(
    UINT8   Speed,
    UINT8   *PortStatus
)
{
    UINT8   PortSts = *PortStatus;

    ASSERT(Speed < 6);
	PortSts &= ~USB_PORT_STAT_DEV_SPEED_MASK;

    switch (Speed) {
        case XHCI_DEVSPEED_UNDEFINED:
                break;
        case XHCI_DEVSPEED_FULL:
                PortSts |= USB_PORT_STAT_DEV_FULLSPEED;
                break;
        case XHCI_DEVSPEED_LOW:
                PortSts |= USB_PORT_STAT_DEV_LOWSPEED;
                break;
        case XHCI_DEVSPEED_HIGH:
                PortSts |= USB_PORT_STAT_DEV_HISPEED;
                break;
        case XHCI_DEVSPEED_SUPER:
                PortSts |= USB_PORT_STAT_DEV_SUPERSPEED;
                break;
        case XHCI_DEVSPEED_SUPER_PLUS:
                PortSts |= USB_PORT_STAT_DEV_SUPERSPEED_PLUS;
                break;
        default:
                USB_DEBUG(3, "XHCI ERROR: unknown device speed.\n");
    }

    *PortStatus = PortSts;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XhciExtCapParser
//
// Description:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
XhciExtCapParser(
    IN USB3_HOST_CONTROLLER *Usb3Hc
)
{
	XHCI_EXT_CAP	*CurPtr;

	if (Usb3Hc->CapRegs->HccParams1.Xecp == 0) return EFI_SUCCESS;

	// Starts from first capability
	CurPtr = (XHCI_EXT_CAP *)((UINTN)Usb3Hc->CapRegs + (Usb3Hc->CapRegs->HccParams1.Xecp << 2));

    // Traverse all capability structures
	for(;;) {
		switch (CurPtr->CapId) {
			case XHCI_EXT_CAP_USB_LEGACY:
				Usb3Hc->ExtLegCap = (XHCI_EXT_LEG_CAP *)CurPtr;
				USB_DEBUG(3, "XHCI: USB Legacy Ext Cap Ptr %x\n", Usb3Hc->ExtLegCap);
				break;

			case XHCI_EXT_CAP_SUPPORTED_PROTOCOL:
				if (((XHCI_EXT_PROTOCOL*)CurPtr)->MajorRev == 0x02) {
					Usb3Hc->Usb2Protocol = (XHCI_EXT_PROTOCOL*)CurPtr;
					USB_DEBUG(3, "XHCI: USB2 Support Protocol %x, PortOffset %x PortCount %x\n", 
						Usb3Hc->Usb2Protocol, Usb3Hc->Usb2Protocol->PortOffset, Usb3Hc->Usb2Protocol->PortCount);
				} else if (((XHCI_EXT_PROTOCOL*)CurPtr)->MajorRev == 0x03) {
					Usb3Hc->Usb3Protocol = (XHCI_EXT_PROTOCOL*)CurPtr;
					USB_DEBUG(3, "XHCI: USB3 Support Protocol %x, PortOffset %x PortCount %x\n", 
						Usb3Hc->Usb3Protocol, Usb3Hc->Usb3Protocol->PortOffset, Usb3Hc->Usb3Protocol->PortCount);
				}
				break;

			case XHCI_EXT_CAP_POWERMANAGEMENT:
			case XHCI_EXT_CAP_IO_VIRTUALIZATION:
                break;
			case XHCI_EXT_CAP_USB_DEBUG_PORT:
                Usb3Hc->DbCapRegs = (XHCI_DB_CAP_REGS*)CurPtr;
                USB_DEBUG(3, "XHCI: USB Debug Capability Ptr %x\n", Usb3Hc->DbCapRegs);
				break;
		}
		if(CurPtr->NextCapPtr == 0) break;
	    // Point to next capability
	    CurPtr=(XHCI_EXT_CAP *)((UINTN)CurPtr+ (((UINTN)CurPtr->NextCapPtr) << 2));
	}

	return EFI_SUCCESS;
}

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

BOOLEAN
XHCI_IsUsb3Port(
	USB3_HOST_CONTROLLER	*Usb3Hc,
	UINT8					Port
)
{
	if ((Port >= Usb3Hc->Usb3Protocol->PortOffset) &&
		(Port < Usb3Hc->Usb3Protocol->PortOffset + Usb3Hc->Usb3Protocol->PortCount)) {
		return TRUE;
	}
	return FALSE;
}

//****************************************************************************
// The following set of functions are the helpers to get the proper locations
// of xHCI data structures using the available pointers.
//****************************************************************************

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_GetSlotId
//
// Description:
//  This function calculates the slot ID out of a given DEV_INFO data pointer.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
XHCI_GetSlotId(
    USB3_HOST_CONTROLLER *Usb3Hc,
    DEV_INFO    *DevInfo
)
{
    UINT32 DevCtxSize = XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize;
    return (UINT8)(((UINTN)DevInfo->DevMiscInfo - (UINTN)Usb3Hc->DeviceContext)/DevCtxSize) + 1;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        XHCI_GetXfrRing
//
// Description:
//  This routine calculates the address of the address ring of a particular
//  Slot/Endpoint.
//
// Output:
//  Pointer to the transfer ring
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

TRB_RING*
XHCI_GetXfrRing(
    USB3_HOST_CONTROLLER* Usb3Hc,
    UINT8   Slot,
    UINT8   Ep
)
{
    return Usb3Hc->XfrRings + (Slot-1)*32 + Ep;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_GetTheDoorbell
//
// Description:
//  This function calculates and returns the pointer to a doorbell for a
//  given Slot.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32*
XHCI_GetTheDoorbell(
    USB3_HOST_CONTROLLER    *Usb3Hc,
    UINT8                   SlotId
)
{
    return (UINT32*)((UINTN)Usb3Hc->CapRegs + Usb3Hc->DbOffset + sizeof(UINT32)*SlotId);
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_GetDevInfo
//
// Description:
//  This function searches for DEV_INFO data pointer that belongs to a given XHCI
//  device context.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
XHCI_GetDevInfo(
    UINTN	PollTdPtr
)
{
    UINT8       i;
    DEV_INFO    *DevInfo;

	if (PollTdPtr == 0) return NULL;

    for (i=1; i<MAX_DEVICES; i++) {
        DevInfo = &gUsbData->aDevInfoTable[i];
		if ((DevInfo->Flag & DEV_INFO_VALIDPRESENT) != DEV_INFO_VALIDPRESENT) {
			continue;
		}
		if (DevInfo->fpPollTDPtr == NULL) {
			continue;
		}
        if ((UINTN)DevInfo->fpPollTDPtr == (UINTN)PollTdPtr) {
            return DevInfo;
        }
    }
    return NULL;    // Device not found
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_GetDeviceContext
//
// Description:
//  This function calculates and returns the pointer to a device context for
//  a given Slot.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID*
XHCI_GetDeviceContext(
	USB3_HOST_CONTROLLER	*Usb3Hc,
	UINT8					SlotId
)
{
	UINT32 DevCtxSize = XHCI_DEVICE_CONTEXT_ENTRIES * Usb3Hc->ContextSize;
	return (UINT8*)((UINTN)Usb3Hc->DeviceContext + (SlotId - 1) * DevCtxSize);
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   XHCI_GetContextEntry
//
// Description:
//  This function calculates and returns the pointer to a context entry for
//  a given index.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID*
XHCI_GetContextEntry(
	USB3_HOST_CONTROLLER	*Usb3Hc,
	VOID					*Context,
	UINT8					Index
)
{
	return (UINT8*)((UINTN)Context + Index * Usb3Hc->ContextSize);
}

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