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

//****************************************************************************
// $Header: /Alaska/SOURCE/Modules/USB/ALASKA/RT/amiusb.c 121   10/16/16 10:11p Wilsonlee $
//
// $Revision: 121 $
//
// $Date: 10/16/16 10:11p $
//
//****************************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Modules/USB/ALASKA/RT/amiusb.c $
// 
// 121   10/16/16 10:11p Wilsonlee
// [TAG]  		EIP288158
// [Category]  	Improvement
// [Description]  	Check if gUsbData is integrity.
// [Files]  		amiusb.cif, usbsb.c, AmiUsbLib.cif, AmiUsbLib.sdl,
// AmiUsbSmmGlobalDataValidationLib.c,
// AmiUsbSmmGlobalDataValidationLib.cif,
// AmiUsbSmmGlobalDataValidationLib.mak, Crc32.c, amiusb.c, amiusb.h,
// ehci.c, elib.c, ohci.c, syskbc.c, uhci.c, usb.c, usbCCID.c, usbdef.h,
// usbhid.c, usbhub.c, usbkbd.c, usbmass.c, usbms.c, usbrt.mak, xhci.c,
// amiusbhc.c, efiusbccid.c, efiusbmass.c, uhcd.c, usbmisc.c,
// AmiUsbController.h, AmiUsbLibInclude.cif,
// AmiUsbSmmGlobalDataValidationLib.h
// 
// 120   7/29/16 3:13a Wilsonlee
// [TAG]  		EIP264662
// [Category]  	Improvement
// [Description]  	Don't install usb hw smi after reconnecting usb
// controllers.
// [Files]  		uhcd.c, usb.c, ohci.c, amiusb.c, amiusbhc.c
// 
// 119   7/29/16 3:09a Wilsonlee
// [TAG]  		EIP277810
// [Category]  	Improvement
// [Description]  	Validate the memory buffer is entirely outside of SMM.
// [Files]  		usbsb.c, amiusb.c, ehci.c, ohci.c, uhci.c, usbCCID.c,
// usbdef.h, usbmass.c, xhci.c, amiusbhc.c, efiusbccid.c, efiusbmass.c,
// uhcd.c, uhcd.h, usbmisc.c
// 
// 117   7/07/16 1:09a Wilsonlee
// [TAG]  		EIP277810
// [Category]  	Improvement
// [Description]  	Validate the memory buffer is entirely outside of SMM.
// [Files]  		usbsb.c, amiusb.c, ehci.c, ohci.c, uhci.c, usbCCID.c,
// usbdef.h, usbmass.c, xhci.c, amiusbhc.c, efiusbccid.c, efiusbmass.c,
// uhcd.c, uhcd.h, usbmisc.c
// 
// 116   10/16/15 3:34a Wilsonlee
// [TAG]  		EIP241977
// [Category]  	Improvement
// [Description]  	Improve UsbKbcAccessControl api function.
// [Files]  		amiusb.c
// 
// 115   4/10/15 3:12a Wilsonlee
// [TAG]  		EIP207413
// [Category]  	Improvement
// [Description]  	Install UsbApiTable and UsbMassApitTable in
// AmiUsbSmmProtocol.
// [Files]  		amiusbhc.c, AmiUsbController.h, usbdef.h, usbCCID.c, uhci.c,
// ehci.c, amiusbrtCCID.h, amiusb.h, amiusb.c, uhcd.c
// 
// 114   2/10/15 12:20a Wilsonlee
// Fixed build error in non-smm projects.
// 
// 113   12/03/14 9:36p Wilsonlee
// [TAG]  		EIP193805
// [Category]  	Improvement
// [Description]  	Security Enhancement for SMIHandler in USB module.
// [Files]  		amiusb.c, uhcd.c, usbrt.mak, usbdef.h, usbsb.c
// 
// 112   11/23/14 10:10p Wilsonlee
// [TAG]  		EIP189293
// [Category]  	Improvement
// [Description]  	Implement XHCI key repeat function.
// [Files]  		usb.c, xhci.c , xhci.h, amiusb.c
// 
// 111   6/05/14 9:15p Wilsonlee
// [TAG]  		EIP171837
// [Category]  	Bug Fix
// [Severity]  	Critical
// [Symptom]  	When use afuwin update BIOS or read ROMID under pure Win8.1
// OS, sometimes the system will blue screen.
// [RootCause]  	UsbData->EfiKeyboardBuffer is EfiBootServicesData. This
// memory isn't reserved in OS. We can't write data to this memory in OS.
// [Solution]  	We clear the buffer at USBKBDProcessKeyboardData function
// if the system is under EFI.
// [Files]  		amiusb.c
// 
// 110   4/30/14 5:25a Wilsonlee
// [TAG]  		EIP164842
// [Category]  	Improvement
// [Description]  	Check if the devices have put into to our queue before
// we put them.
// [Files]  		UsbInt13.c, amiusb.c, ehci.c, ohci.c, usb.c, usbdef.h,
// usbmass.c, xhci.c, amiusbhc.c, efiusbmass.c, uhcd.c, usbbus.c, usbsb.c
// 
// 109   4/07/14 1:28a Wilsonlee
// [TAG]  		EIP157193
// [Category]  	Improvement
// [Description]  	Stop the usb host controllers at AcpiModeEnable if they
// art extend cards or don't support HW SMI.
// [Files]  		amiusb.c
// 
// 108   2/10/14 1:19a Ryanchou
// [TAG]  		EIP149929
// [Category]  	Improvement
// [Description]  	Stop all external EHCI HCs in ACPI enable call.
// [Files]  		amiusb.c
// 
// 107   12/15/13 10:16p Wilsonlee
// [TAG]  		EIP136594
// [Category]  	New Feature
// [Description]  	Support 64 bits LBA of usb mass storages.
// [Files]  		Bfiusb.asm, Bfiusb.equ, UsbInt13.c, UsbInt13.h, amiusb.c,
// usbdef.h, usbmass.c, UsbMass.h, efiusbmass.c, UI13.bin
// 
// 106   11/05/13 4:46a Ryanchou
// [TAG]  		EIP135636
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	NumLock LED cannot be on/off properly.
// [RootCause]  	It is the side effect of EIP #107429 changes, the
// keyboard does not generate break code when pressing NumLock.
// [Solution]  	Remove the EIP #107429 changes.
// [Files]  		amiusb.c, usbkbd.c, efiusbkb.c
// 
// 105   10/19/13 7:06a Ryanchou
// [TAG]  		EIP138257
// [Category]  	Improvement
// [Description]  	Correct USB HID device type.
// [Files]  		amiusb.c, usbdef.h, usbhid.c, efiusbhid.c, uhcd.c
// 
// 104   8/06/13 4:21a Wilsonlee
// [TAG]  		EIP128970
// [Category]  	Improvement
// [Description]  	UsbInstallHwSmiHandler returns EFI_UNSUPPORTED if
// HCType is invalid.
// [Files]  		amiusb.c
// 
// 103   6/02/13 11:43p Wilsonlee
// [TAG]  		EIP123235
// [Category]  	Improvement
// [Description]  	Stop the usb host controller at ExitBootService if it
// is an extend card or it doesn't support HW SMI.
// [Files]  		xhci.c, ehci.c, uhci.c, ohci.c, amiusb.c, usbdef.h, usbsb.c,
// uhcd.c
// 
// 102   4/10/13 9:29p Wilsonlee
// [TAG]  		EIP120573
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	Afuwinx64/Safuwinx64 hang up issue.
// [RootCause]  	EfiZeroMem is a boot service function, we can't use it
// during runtime.
// [Solution]  	Use MemFill function to clear the KBC buffers.
// [Files]  		amiusb.c
// 
// 101   3/19/13 3:58a Ryanchou
// [TAG]  		EIP118177
// [Category]  	Improvement
// [Description]  	Dynamically allocate HCStrucTable at runtime.
// [Files]  		usb.sdl, usbport.c, usbsb.c, amiusb.c, ehci.c, ohci.c,
// syskbc.c, sysnokbc.c, uhci.c, usb.c, usbCCID.c, usbdef.h, usbhid.c,
// usbhub.c, usbmass.c, usbrt.mak, usb.sd, amiusbhc.c, efiusbccid.c,
// efiusbhid.c, efiusbmass.c, efiusbms.c, uhcd.c, uhcd.h, uhcd.mak,
// usbmisc.c, usbsrc.sdl
// 
// 100   1/23/13 4:15a Ryanchou
// [TAG]  		EIP111280
// [Category]  	Improvement
// [Description]  	Add USB APIs for external driver.
// [Files]  		amiusb.c, amiusb.h, usbdef.h
// 
// 99    1/22/13 3:09a Wilsonlee
// [TAG]  		EIP112938
// [Category]  	Improvement
// [Description]  	Create a header file for usb mass storage driver.
// [Files]  		UsbMass.h, usbmass.c, usbdef.h, amiusb.c, efiusbmass.c
// 
// 98    12/21/12 5:02a Ryanchou
// [TAG]  		EIP71730
// [Category]  	New Feature
// [Description]  	Added OHCI handoff support.
// [Files]  		usb.sdl, usbport.c, amiusb.c, usbdef.h, UsbPolicy.h, usb.sd,
// usb.uni
// 
// 97    12/09/12 12:12a Wilsonlee
// [TAG]  		EIP107429
// [Category]  	Improvement
// [Description]  	Process the make code even if there is no break code.
// [Files]  		efiusbkb.c, amiusb.c
// 
// 96    12/02/12 10:23p Roberthsu
// [TAG]           EIP102150
// [Category]      Bug Fix
// [Severity]      Normal
// [Symptom]       Push key and unplug KB , character  repeat can not.
// stop
// [RootCause]     Because repeat key does not clear when usb keyboard
// unplug.
// [Solution]      When keyboard disconnrct, clear keyboard device id with
// device id buffer and scancode buffer.
// [Files]         amiusb.c,syskbc.c,uhcd.c,usbkbd.c
// 
// 95    11/10/12 6:39a Ryanchou
// [TAG]  		EIP99431
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Cannot use the UsbIo's UsbAsyncInterruptTransfer for
// keyboard input
// [RootCause]  	Stopping EFI USB keyboard driver does not stop the
// endpoint polling, then application calls UsbAsyncInterruptTransfer,
// error will be returned.
// [Solution]  	Stops endpoint polling and release resource when
// disconnecting the device driver. And improve the
// UsbSyncInterruptTransfer.
// [Files]  		amiusb.c, amiusb.h, ehci.c, ohci.c, uhci.c, usb.c,
// usbCCID.c, usbdef.h, usbhub.c, usbkbd.c, usbmass.c, usbms.c,
// usbpoint.c, amiusbhc.c, efiusbhid.c, usbbus.c, usbbus.h
// 
// 94    8/29/12 8:10a Ryanchou
// [TAG]  		EIP77262
// [Category]  	New Feature
// [Description]  	Remove SMM dependency of USB.
// [Files]  		usb.sdl, usbport.c, amiusb.c, amiusb.dxs, amiusb.h, ehci.c,
// elib.c, ohci.c, uhci.c, usb.c, usbdef.h, usbrt.mak, xhci.c, amiusbhc.c,
// efiusbccid.c, efiusbhid.c, efiusbkb.c, efiusbmass.c, uhcd.c, uhcd.dxs,
// uhcd.h, usbmisc.c, AmiUsbController.h
// 
// 93    8/07/12 9:39p Wilsonlee
// [TAG]  		EIP96366
// [Category]  	New Feature
// [Description]  	Add the token "DEFAULT_USB_EMUL6064_OPTION" that
// control the default value of the I/O port 60h/64h emulation support
// option.
// [Files]  		usb.sd, usb.sdl, amiusb.c, amiusb.h
// 
// 92    6/13/12 7:31a Lavanyap
// [TAG]  		EIP89825
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	System get's hangs inside the SMI handler while flashing
// the Bios.
// [RootCause]  	Port 60/64 access SMI will not be generated immediately
// if accessed inside an SMI handler when KbcEmulation is enabled.
// [Solution]  	Emulation is disabled while accessing the Port 60/64.
// [Files]  		amiusb.c
// 
// 91    5/22/12 10:03a Ryanchou
// [TAG]  		EIP90154
// [Category]  	Improvement
// [Description]  	Remove the USBSB_EnableSmmPeriodicSmi and
// USBSB_DisableSmmPeriodicSmi hooks.
// [Files]  		amidef.h, amiusb.c, usb.c, usbsb.c
// 
// 90    5/04/12 6:37a Ryanchou
// [TAG]  		EIP82875
// [Category]  	Improvement
// [Description]  	Support start/stop individual USB host to avoid
// reconnect issues.
// [Files]  		usbport.c, usbsb.c, amiusb.c, amiusb.h, ehci.c, ohci.c,
// uhci.c, uhci.h, usb.c, usbdef.h, xhci.c, amiusbhc.c, uhcd.c, uhcd.h,
// usbbus.c, usbmisc.c
// 
// 89    5/04/12 5:21a Wilsonlee
// [TAG]  		EIP89307
// [Category]  	Improvement
// [Description]  	Modify incorrect #pragma pack directive.
// [Files]  		amidef.h, amiusb.c, ehci.c, ohci.c, ohci.h, uhci.h, usb.c,
// usbdef.h, xhci.h, efiusbmass.c, uhcd.c, uhcd.h, usbbus.c, usbbus.h,
// UsbIo.h
// 
// 88    5/03/12 5:50a Roberthsu
// [TAG]           EIP84455
// [Category]  	Improvement
// [Description]  	Implement usb hid device gencric.
// [Files]  		amiusb.c,amiusbhc.c,efiusbhid.c,efiusbkb.c,ehci.c,ohci.c,uhc
// d.c,uhci.c,usbdef.h,usbhid.c,usbhub.c,usbkbd.c,usbkbd.h,usbms.c,usbsb.c
// ,usbsrc.sdl
// 
// 87    1/16/12 6:01a Ryanchou
// [TAG]  		EIP81132
// [Description]  	Add core version check for EIP80609 solution.
// [Files]  		amiusb.c, usbrt.mak, usbsb.c
// 
// 86    1/14/12 4:09a Ryanchou
// [TAG]  		EIP80609
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	If to enable debug mode and set launch CSM is "Never" in
// setup, system will hang at 0xB1
// [RootCause]  	The pointer AmiUsb is invalid if CSM is not launched,
// that may cause CPU exception.
// [Solution]  	Added USB smm protocol, and use SmmLocateProtocol to get
// the pointer.
// [Files]  		amiusb.c, AmiUsbController.h, usbrt.mak, usbsb.c
// 
// 85    1/13/12 4:23a Ryanchou
// [TAG]  		EIP47348
// [Category]  	New Feature
// [Description]  	Support for USB Port Reset function.
// [Files]  		amiusb.c, amiusb.h, amiusbhc.c, uhci.c, usb.c, usbbus.c,
// usbbus.h, usbmass.c
// 
// 84    12/09/11 3:09p Ryanchou
// [TAG]  		EIP7768
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	USB mass storage can't work after unplug and plug under DOS
// [RootCause]  	The SW SMI handler checks USB_FLAG_RUNNING_UNDER_EFI flag
// to get the URP from USB global data area or EBDA. Legacy boot event
// clears the flag, and UsbPrepareForLegacyOS will not be invoked.
// [Solution]  	Check the URP in USB global data area, if it is not empty,
// get it in USB global data area, or get it in EBDA.
// [Files]  		amiusb.c
// 
// 83    11/08/11 8:22a Wilsonlee
// [TAG]  		EIP74876
// [Category]  	New Feature
// [Description]  	Add USB API for shutdown single USB controller.
// [Files]  		amiusb.c, amiusb.h, usb.c, usbdef.h, uhcd.c, uhcd.h,
// AmiUsbController.h
// 
// 82    11/08/11 1:41a Ryanchou
// [TAG]  		EIP63188
// [Category]  	Improvement
// [Description]  	External USB controller support.
// [Files]  		amidef.h, amiusb.c, ehci.c, ohci.c, uhcd.c, uhcd.h, uhci.c,
// usbdef.h, usbmisc.c, usbsb.c, xhci.c
// 
// 81    11/05/11 3:26a Ryanchou
// [TAG]  		EIP70094
// [Category]  	Improvement
// [Description]  	Microsoft CSM Opt-Out feature implementation.
// [Files]  		amiusb.c, uhcd.c
// 
// 80    10/17/11 2:24a Ryanchou
// [TAG]  		EIP69136
// [Category]  	Improvement
// [Description]  	Remove the dependency of EBDA in USB module for CSM
// disabling.
// [Files]  		amiusb.c, uhcd.c, usbport.c, usbsb.c
// 
// 79    9/28/11 10:45a Ryanchou
// [TAG]  		EIP66064
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	System hangs when waiting for finger swipe
// [RootCause]  	USB driver save the URP pointer to EBDA in function
// UsbSmiCore and UsbSmiHc, the pointer will be destroyed if someone also
// invoke the two functions.
// [Solution]  	Save the URP pointer before generate SW SMI and restore it
// after return from SMI.
// [Files]  		amiusb.c, amiusbhc.c, usbport.c
// 
// 78    8/08/11 6:57a Ryanchou
// [TAG]  		EIP54018
// [Category]  	New Feature
// [Description]  	Added USB S5 wake up support.
// [Files]  		amiusb.c, ehci.c, ohci.c, uhci.c, usb.c, usb.sdl, usbdef.h,
// usbsb.c xhci.c
// 
// 77    8/05/11 6:18a Ryanchou
// [TAG]  		EIP60706
// [Category]  	Improvement
// [Description]  	Move gUsbBadDeviceTable into SMRAM.
// [Files]  		usbport.c, amiusb.c, usb.c, uhcd.c, AmiUsbController.h
// 
// 76    7/15/11 6:11a Ryanchou
// [TAG]  		EIP38434
// [Category]  	New Feature
// [Description]  	Added USB HID report protocol support.
// [Files]  		amiusb.c, AmiUsbController.h, amiusbhc.c, efiusbkb.c,
// efiusbkb.h, ehci.c, ohci.c, uhcd.c uhcd.cif, uhci.c, usb.c, usbdef.h,
// usbkbd.c, usbkbd.h, usbms.c, usbrt.cif, usbsb.c, usbsetup.c,
// usbsrc.sdl, xhci.c
// 
// 75    7/12/11 8:09a Ryanchou
// [TAG]  		EIP56918
// [Category]  	New Feature
// [Description]  	Added CCID device support.
// [Files]  		amiusb.c, amiusb.h, amiusbrtCCID.h, ehci.c, ohci.c, uhci.c,
// usb.c, UsbCCID.c, usbdef.h, usbrt.cif, usbsetup.c, efiusbccid.c,
// framework.cif, uhcd.c, uhcd.cif, uhcd.h, usbsrc.sdl, AmiusbCCID.h,
// AmiUsbController.h, AmiUSBProtocols.cif
// 
// 74    5/03/11 8:44a Ryanchou
// [TAG]  		EIP57521
// [Category]  	Improvement
// [Description]  	Enumerate root hub ports after start host controllers
// in USB_StartLegacy.
// [Files]  		amiusb.c
// 
// 73    3/30/11 9:02a Ryanchou
// [TAG]  		EIP41483
// [Category]  	Improvement
// [Description]  	Stop timer SMI after legacy shutdown.
// [Files]  		amiusb.c, AmiUsbController.h, ohci.c
// 
// 72    3/29/11 10:07a Ryanchou
// [TAG]  		EIP53518
// [Category]  	Improvement
// [Description]  	Added chipset xHCI chip support.
// [Files]  		amiusb.c, amiusb.h, ehci.c, ohci.c, uhcd.c, uhci.c, usb.c,
// usb.sdl, usbdef.h, usbport, usbsb.c, xhci.c
// 
// 71    12/24/10 5:02a Tonylo
// [TAG]  		EIP48323
// [Category]  	Improvement
// [Description]  	Reflush USB keyboard data buffer to avoid junk data
// sent after enable USB keyboard data throughput.
// [Files]  		AMIUSB.C
// 
// 70    11/22/10 8:42a Ryanchou
// [TAG]  		EIP48064
// [Category]  	Improvement
// [Description]  	The SB template implemented elink
// AcpiEnableCallbackList, the XHCI/EHCI hand off function should be
// invoked via the elink AcpiEnableCallbackList.
// [Files]  		amidef.h, amiusb.c, amiusb.dxs, amiusb.h,
// AmiUsbController.h, usb.sdl, usbrt.mak, usbsb.c
// 
// 69    10/07/10 9:32a Ryanchou
// EIP42986: Remove the retry loop in UsbHwSmiHandler.
// 
// 68    8/31/10 8:57a Tonylo
// Remove user tags for coding standard.
// 
// Description:  Remove user tags for coding standard.
// 
// 67    8/18/10 4:22p Olegi
// Klockwork related fixes; EIP37978
// 
// 66    7/27/10 9:11a Ryanchou
// EIP41216: Return correct error code when device isn't present.
// 
// 65    7/15/10 4:33a Tonylo
// EIP21649 - USB mass storage device still appear in BBS menu when USB
// legacy support is disabled.
// 
// 64    6/07/10 8:56a Ryanchou
// EIP38547: Fixed system halt when installing FreeBSD.
// 
// 63    3/31/10 6:26p Olegi
// 
// 62    3/25/10 9:45a Olegi
// 
// 61    3/19/10 10:05a Olegi
// 
// 60    1/27/10 5:19p Olegi
// Added chipset porting hook to initialize timers.
// 
// 59    12/01/09 10:06a Olegi
// EIP31535: RWV error code corrected.
// 
// 58    11/25/09 8:05a Olegi
// EIPEIP29733: Added KBC access control API
// 
// 57    10/30/09 5:47p Olegi
// 
// 56    10/02/09 10:49a Olegi
// Code cleanup.
// 
// 54    9/15/09 10:21a Olegi
// Added USB_INCMPT_HID_DATA_OVERFLOW incompatibility type.
// 
// 53    8/26/09 11:41a Olegi
// Changes that prevent collision of keyboard activity and mass storage
// access. EIP#22808
// 
// 52    5/22/09 1:46p Olegi
// Added the special treatment for in-built hubs.
// 
// 51    5/21/09 5:11p Olegi
// Added checking for hotplug fake drives in Read/Write/Verify functions.
// 
// 50    1/29/09 2:31p Olegi
// USB API CheckDevicePresence is extended with USB_SRCH_DEVBASECLASS_NUM
// search key.
// 
// 49    1/23/09 4:28p Olegi
// Added EXTRA_CHECK_DEVICE_READY condition for the fix to EIP#15037.
// 
// 48    1/05/09 9:40a Olegi
// Changes for EIP#15037. Extra CheckDeviceReady call added to read/write
// functions.
// 
// 46    10/06/08 3:33p Olegi
// EHCI change ownership testing in DOS fix (EIP#14855).
// 
// 44    9/24/08 4:01p Olegi
// Modified USBAPI_ChangeOwner so that it allows multiple calls to
// acquiring the ownership without releasing it.
// 
// 43    7/04/08 1:07p Olegi
// Device "Ultra-X, Inc.: Ultra-X QTP USB HD 1.01" is removed from
// incompatible device list.
// 
// 42    6/27/08 5:52p Olegi
// Added incompatible devices.
// 
// 41    5/16/08 12:01p Olegi
// Compliance with AMI coding standard.
// 
// 40    12/17/07 4:04p Olegi
// KBC emulation support added.
// 
// 39    12/05/07 4:36p Olegi
// Modification in USBSWSMIHandler() related to the 64/32-bit pointers.
// 
// 36    7/09/07 2:11p Olegi
// Changed the maximum data size of the BulkTransfer from 1kB to 64kB.
// 
// 34    6/11/07 2:53p Olegi
// Bugfix in device read/write routine: do not issue RWV command if there
// is no media present.
// 
// 32    3/20/07 12:16p Olegi
// SMITHUNK removed.
//
// 28    10/18/06 9:40a Andriyn
// Fix: race condition on hot-plug in / plug-off
//
// 27    10/12/06 4:41p Olegi
// Modified the method of passing arguments into USBSWSMIHandler: it is
// done through memory location, not using CPU register. This change is
// only valid for CSM16 versions 31 and later.
//
// 26    4/14/06 6:39p Olegi
// Conversion to be able to use x64 compiler.
//
// 24    3/20/06 3:37p Olegi
// Version 8.5 - x64 compatible.
//
// 23    3/06/06 6:22p Olegi
// Lun devices support modifications: supported using the index in
// DEV_INFO table, not through dedicated massLun table.
//
// 21    1/11/06 11:51a Olegi
// LegacyUsbSupport setup question functionality added.
//
// 18    10/20/05 3:08p Olegi
// ReadDevice correction (EST change).
//
// 14    8/25/05 7:19p Andriyn
// USB Keyboard and mouse to use EMUL 60/64 for passing data to KBC.
// Fall-back when EMUL 60/64 is not present
//
// 13    8/23/05 5:50p Olegi
// USBMassGetDeviceParameters function added.
//
// 12    8/11/05 9:53a Olegi
// 60/64 port emulation related fixes for EMU6064 driver.
//
// 11    8/04/05 5:58p Andriyn
// Legacy over LegacyFree
//
// 10    6/20/05 8:55a Olegi
// .NET compiler with highest warning level and warning-as-error
// modification.
//
// 9     6/15/05 1:59p Andriyn
// Comments were changed
//
// 6     6/03/05 6:06p Olegi
// UsbHwSmiHandler modified to be called individually from UHCI, OHCI and
// EHCI drivers.
//
// 5     6/03/05 9:28a Olegi
// ATA Error reporting is corrected in USBWrapGetATAErrorCode.
//
// 4     6/01/05 5:21p Olegi
// Debug message shortened.
//
// 3     5/17/05 7:51p Andriyn
// USB BUS pre-release
//
// 2     5/10/05 4:11p Andriyn
// USBBUS implementation
//
// 1     3/15/05 9:23a Olegi
// Initial VSS check-in.
//
//****************************************************************************

//<AMI_FHDR_START>
//----------------------------------------------------------------------------
//
//  Name:   AMIUSB.C
//
//  Description:    AMI USB API implementation. The following code will be
//                  copied to SMM; only RT functions can be used. gUsbData
//                  is obtained from AMIUHCD in the entry point and can be
//                  used afterwards.
//
//----------------------------------------------------------------------------
//<AMI_FHDR_END>

#include <AmiDxeLib.h>
#include "amiusb.h"
#include "amidef.h"
#include <UsbDevDriverElinks.h>			//(EIP71750+)
#if USB_RUNTIME_DRIVER_IN_SMM
#include <AmiBufferValidationLib.h>
#include <AmiUsbSmmGlobalDataValidationLib.h>
#endif

#if USB_DEV_KBD
#include "usbkbd.h"
#endif
#include "UsbMass.h"

										//(EIP54018+)>
#if USB_S5_WAKEUP_SUPPORT
#include <Protocol\SmmSxDispatch.h>
#include <Protocol\SmmPowerButtonDispatch.h>
#endif
										//<(EIP54018+)
//#pragma warning (disable: 4152)

extern UINT8 IsKbcAccessBlocked;            //(EIP29733+)
EFI_EMUL6064MSINPUT_PROTOCOL* gMsInput = 0;
EFI_EMUL6064KBDINPUT_PROTOCOL* gKbdInput = 0;
EFI_EMUL6064TRAP_PROTOCOL* gEmulationTrap = 0;

USB_GLOBAL_DATA     *gUsbData;
//USB_BADDEV_STRUC    *gUsbBadDeviceTable;			//(EIP60706-)

AMI_USB_SMM_PROTOCOL	gUsbSmmProtocol = {0};

BOOLEAN gLockSmiHandler = FALSE;
BOOLEAN gLockHwSmiHandler = FALSE;
BOOLEAN gCheckUsbApiParameter = FALSE;

VOID    StopControllerType(UINT8);
VOID    StartControllerType(UINT8);
UINT8   USB_StopDevice (HC_STRUC*,  UINT8, UINT8);
UINT8   USB_EnumerateRootHubPorts(UINT8);   //(EIP57521+)              
VOID    StopControllerBdf(UINT16);			//(EIP74876+)

VOID	FillHcdEntries();
										//(EIP71750+)>
typedef VOID USB_DEV_DELAYED_DRIVER_CHECK (DEV_DRIVER*);
extern USB_DEV_DELAYED_DRIVER_CHECK USB_DEV_DELAYED_DRIVER EndOfUsbDevDelayedDriverList;
USB_DEV_DELAYED_DRIVER_CHECK* UsbDevDelayedDrivers[]= {USB_DEV_DELAYED_DRIVER NULL};

typedef VOID USB_DEV_DRIVER_CHECK (DEV_DRIVER*);
extern USB_DEV_DRIVER_CHECK USB_DEV_DRIVER EndOfUsbDevDriverList;
USB_DEV_DRIVER_CHECK* UsbDevDrivers[]= {USB_DEV_DRIVER NULL};
										//<(EIP71750+)
										//(EIP54018+)>
#if USB_S5_WAKEUP_SUPPORT
VOID    UsbSuspend(VOID);
#endif

#if USB_S5_WAKEUP_SUPPORT
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        UsbS5SmiCallback
//
// Description: 
//  This function enter usb s5 callback.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
UsbS5SmiCallback(
    IN EFI_HANDLE DispatchHandle,
    IN EFI_SMM_SX_DISPATCH_CONTEXT *DispatchContext
)
{
    EFI_STATUS  Status = EFI_SUCCESS;
#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)    
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);

    if (EFI_ERROR(Status)) {
        return;
    }
#endif
    UsbSuspend();
}
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name:        UsbPowerButtonSmiCallback
//
// Description: 
//  This function enter s5 callback if press power button.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
UsbPowerButtonSmiCallback(
    IN EFI_HANDLE DispatchHandle,
	IN EFI_SMM_POWER_BUTTON_DISPATCH_CONTEXT *DispatchContext
)
{
    EFI_STATUS  Status = EFI_SUCCESS;
#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)    
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);

    if (EFI_ERROR(Status)) {
        return;
    }
#endif
    UsbSuspend();
}
#endif
										//<(EIP54018+)

//<AMI_THDR_START>
//----------------------------------------------------------------------------
// Name:        aUsbApiTable - USB API Function Dispatch Table
//
// Type:        Function Dispatch Table
//
// Description: This is the table of functions used by USB API
//
// Notes:       This functions are invoked via software SMI
//
//----------------------------------------------------------------------------
//<AMI_THDR_END>

API_FUNC aUsbApiTable[] = {
    USBAPI_CheckPresence,
    USBAPI_Start,
    USBAPI_Stop,
    USBAPI_DisableInterrupts,
    USBAPI_EnableInterrupts,
    USBAPI_MoveDataArea,
    USBAPI_GetDeviceInfo,
    USBAPI_CheckDevicePresence,
    USBAPI_MassDeviceRequest,
    USBAPI_PowerManageUSB,
    USBAPI_PrepareForOS,
    USBAPI_SecureInterface,
    USBAPI_LightenKeyboardLEDs,
    USBAPI_ChangeOwner,
    USBAPI_HC_Proc,
    USBAPI_Core_Proc,
    USBAPI_LightenKeyboardLEDs_Compatible,
    USBAPI_KbcAccessControl,
    USBAPI_LegacyControl,
    USBAPI_GetDeviceAddress,
    USBAPI_ExtDriverRequest,
    USBAPI_CCIDRequest,
    USBAPI_UsbStopController,				//(EIP74876+)
    USBAPI_HcStartStop
};

//<AMI_THDR_START>
//----------------------------------------------------------------------------
// Name:        USBMassAPITable - USB Mass Storage API Function Dispatch Table
//
// Type:        Function Dispatch Table
//
// Description: This is the table of functions used by USB Mass Storage API
//
//----------------------------------------------------------------------------
//<AMI_THDR_END>

API_FUNC aUsbMassApiTable[] = {
    USBMassAPIGetDeviceInformation, // USB Mass API Sub-Func 00h
    USBMassAPIGetDeviceGeometry,    // USB Mass API Sub-Func 01h
    USBMassAPIResetDevice,          // USB Mass API Sub-Func 02h
    USBMassAPIReadDevice,           // USB Mass API Sub-Func 03h
    USBMassAPIWriteDevice,          // USB Mass API Sub-Func 04h
    USBMassAPIVerifyDevice,         // USB Mass API Sub-Func 05h
    USBMassAPIFormatDevice,         // USB Mass API Sub-Func 06h
    USBMassAPICommandPassThru,      // USB Mass API Sub-Func 07h
    USBMassAPIAssignDriveNumber,    // USB BIOS API function 08h
    USBMassAPICheckDevStatus,       // USB BIOS API function 09h
    USBMassAPIGetDevStatus,         // USB BIOS API function 0Ah
    USBMassAPIGetDeviceParameters   // USB BIOS API function 0Bh
};

EFI_DRIVER_ENTRY_POINT(USBDriverEntryPoint)

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   USBDriverEntryPoint
//
// Description: USB Driver entry point
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
USBDriverEntryPoint(
    IN EFI_HANDLE           ImageHandle,
    IN EFI_SYSTEM_TABLE     *SystemTable
)
{
    EFI_STATUS Status;

    InitAmiLib(ImageHandle, SystemTable);

#if USB_RUNTIME_DRIVER_IN_SMM
    Status = InitSmmHandler(ImageHandle, SystemTable, InSmmFunction, NULL);
#else
	Status = InstallUsbProtocols(); 
	InitializeUsbGlobalData();
#endif
    ASSERT_EFI_ERROR(Status);

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:       InitializeUsbGlobalData
//
// Description: This function initializes the USB global data.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
InitializeUsbGlobalData(
	VOID
)
{
	EFI_STATUS	Status;
    UINT8   	bDriverIndex;
    UINT8   	bDelayedIndex;

    //
    // Initialize host controller drivers
    //
    FillHcdEntries();   // This routine is implemented in $(BUILD_DIR)\dummyusbrt.c

    //
    // Initialize the device driver pointers
    //
    bDriverIndex = 0;
    bDelayedIndex = 0;
										//(EIP71750)>
    while(UsbDevDelayedDrivers[bDelayedIndex]) {
        UsbDevDelayedDrivers[bDelayedIndex](&gUsbData->aDelayedDrivers[bDelayedIndex]);
		if (gUsbData->aDelayedDrivers[bDelayedIndex].pfnDeviceInit) {
            (*gUsbData->aDelayedDrivers[bDelayedIndex].pfnDeviceInit)();
        }
        if (gUsbData->aDelayedDrivers[bDelayedIndex].bDevType) {
            bDelayedIndex++;
        }
    }

    while(UsbDevDrivers[bDriverIndex]) {
        UsbDevDrivers[bDriverIndex](&gUsbData->aDevDriverTable[bDriverIndex]);
		if (gUsbData->aDevDriverTable[bDriverIndex].pfnDeviceInit) {
            (*gUsbData->aDevDriverTable[bDriverIndex].pfnDeviceInit)();
        }
        if (gUsbData->aDevDriverTable[bDriverIndex].bDevType) {
            bDriverIndex++;
        }
    }

	//
	// Allocate a block of memory to be used as a temporary
	// buffer for  USB mass transfer
	//
	Status = pBS->AllocatePool (EfiRuntimeServicesData, MAX_CONSUME_BUFFER_SIZE, 
				&gUsbData->fpUSBMassConsumeBuffer);
	ASSERT_EFI_ERROR(Status);
	pBS->SetMem(gUsbData->fpUSBMassConsumeBuffer, MAX_CONSUME_BUFFER_SIZE, 0);

	//
	// Allocate a block of memory for the temporary buffer
	//
	Status = gBS->AllocatePool (EfiRuntimeServicesData, MAX_TEMP_BUFFER_SIZE, 
				&gUsbData->fpUSBTempBuffer);
	ASSERT_EFI_ERROR(Status);
	pBS->SetMem(gUsbData->fpUSBTempBuffer, MAX_TEMP_BUFFER_SIZE, 0);

    //
    // Allow to enumerate ports
    //
    gUsbData->bEnumFlag = FALSE;

	return USB_SUCCESS;
}


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

VOID
UsbApiHandler(VOID* Param)
{
    URP_STRUC   *fpURP = (URP_STRUC*)Param;
    UINT8       bFuncIndex;
    UINT8       bNumberOfFunctions;

	if (fpURP == NULL) {
		return;
	}

    bFuncIndex = fpURP->bFuncNumber;
    bNumberOfFunctions = sizeof aUsbApiTable / sizeof (API_FUNC *);

    //
    // Make sure function number is valid; if function number is not zero
    // check for valid extended USB API function
    //
    if (bFuncIndex && ((bFuncIndex < USB_NEW_API_START_FUNC ) ||
            bFuncIndex > (bNumberOfFunctions + USB_NEW_API_START_FUNC))) {
        //fpURP->bRetValue = USBAPI_INVALID_FUNCTION;
        USB_DEBUG(3, "UsbApiHandler Invalid function#%x\n", bFuncIndex);
        return;
    }

    if (bFuncIndex) {
        bFuncIndex = (UINT8)(bFuncIndex - USB_NEW_API_START_FUNC + 1);
    }

    aUsbApiTable[bFuncIndex](fpURP);    // Call the appropriate function

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:       InstallUsbProtocols
//
// Description: This function initializes the USB global data.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
InstallUsbProtocols(
	VOID
)
{
	EFI_STATUS	Status;
	EFI_USB_PROTOCOL	*UsbProtocol;

    Status = pBS->LocateProtocol(&gEfiUsbProtocolGuid, NULL, &UsbProtocol);
	if (EFI_ERROR(Status)) {
		return Status;
	}
    gUsbData = UsbProtocol->USBDataPtr;

	UsbProtocol->UsbRtKbcAccessControl = UsbKbcAccessControl;

	//Hook USB legacy control function for shutdown/init USB legacy support
	UsbProtocol->UsbLegacyControl = USBRT_LegacyControl;
	UsbProtocol->UsbStopUnsupportedHc = USB_StopUnsupportedHc;
#if !USB_RUNTIME_DRIVER_IN_SMM
	UsbProtocol->UsbInvokeApi = UsbApiHandler;
#endif

	return Status;
}

#if USB_RUNTIME_DRIVER_IN_SMM
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   InSmmFunction
//
// Description: SMM entry point of AMIUSB driver
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
InSmmFunction(
    EFI_HANDLE ImageHandle,
    EFI_SYSTEM_TABLE    *SystemTable
)
{
    EFI_STATUS                      Status;

    EFI_SMM_SW_DISPATCH_CONTEXT     SwSmiContext;
    EFI_HANDLE                      SwSmiHandle = NULL;
    EFI_SMM_SW_DISPATCH_PROTOCOL    *SwSmiDispatch;

    UINT32                          KbcEmulFeature = 0;
    VOID	                        *ProtocolNotifyRegistration;
    EFI_EVENT                       Emul6064Event = NULL;

									//(EIP54018+)>
#if USB_S5_WAKEUP_SUPPORT
    EFI_SMM_SX_DISPATCH_CONTEXT     S5DispatchContext;
    EFI_SMM_SX_DISPATCH_PROTOCOL    *SxDispatchProtocol;
    EFI_SMM_POWER_BUTTON_DISPATCH_CONTEXT   PbDispatchContext;
    EFI_SMM_POWER_BUTTON_DISPATCH_PROTOCOL  *PbDispatchProtocol;
    EFI_HANDLE  S5DispatchHandle;
    EFI_HANDLE  PbDispatchHandle;
#endif
									//<(EIP54018+)
#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)
	EFI_HANDLE	UsbSmmProtocolHandle = NULL;

    Status = InitAmiSmmLib(ImageHandle, SystemTable);
    if (EFI_ERROR(Status)) return Status;
#endif

    InitAmiBufferValidationLib(ImageHandle, SystemTable);

	InstallUsbProtocols();
	InitializeUsbGlobalData();


    Status = pBS->LocateProtocol (&gEmul6064TrapProtocolGuid, NULL, &gEmulationTrap);
    if (EFI_ERROR(Status)) {
        Status = RegisterProtocolCallback(&gEmul6064TrapProtocolGuid,
        							    Emul6064TrapCallback,
                                        NULL,
                                        &Emul6064Event,
                                        &ProtocolNotifyRegistration);
    }

    if(!gUsbData->kbc_support) {
        Status = gBS->LocateProtocol (&gEmul6064MsInputProtocolGuid, NULL, &gMsInput);
        pBS->LocateProtocol (&gEmul6064KbdInputProtocolGuid, NULL, &gKbdInput);

        if (Status == EFI_SUCCESS) {
            gUsbData->dUSBStateFlag |= USB_FLAG_6064EMULATION_ON;
            if(gEmulationTrap) 
                KbcEmulFeature = gEmulationTrap->FeatureSupported(gEmulationTrap);
                if(KbcEmulFeature & IRQ_SUPPORTED) {
                    gUsbData->dUSBStateFlag |= USB_FLAG_6064EMULATION_IRQ_SUPPORT;
                }
        } else {
           InitSysKbc( &gKbdInput, &gMsInput );
        }
    } else {
        //
        //Init Fake Emulation interface
        //
        InitSysKbc( &gKbdInput, &gMsInput );
    }

    Status = USBSB_InstallSmiEventHandlers();

    USB_DEBUG(DEBUG_LEVEL_3,"AMIUSB global data at 0x%x\n", gUsbData);

    //
    // Register the USB SW SMI handler
    //
    Status = pBS->LocateProtocol (&gEfiSmmSwDispatchProtocolGuid, NULL, &SwSmiDispatch);

    if (EFI_ERROR (Status)) {
        USB_DEBUG(DEBUG_LEVEL_0, "SmmSwDispatch protocol: %r\n", Status);
        return Status;
    }

    SwSmiContext.SwSmiInputValue = USB_SWSMI;
    Status = SwSmiDispatch->Register (SwSmiDispatch, USBSWSMIHandler, &SwSmiContext, &SwSmiHandle);

    USB_DEBUG(DEBUG_LEVEL_3, "AMIUSB SW SMI registration:: %r\n", Status);

#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)
    gUsbSmmProtocol.UsbStopUnsupportedHc = USB_StopUnsupportedHc;
    gUsbSmmProtocol.UsbApiTable = aUsbApiTable;
    gUsbSmmProtocol.UsbMassApiTable = aUsbMassApiTable;
    gUsbSmmProtocol.GlobalDataValidation.ConstantDataCrc32 = 0;
    gUsbSmmProtocol.GlobalDataValidation.Crc32Hash = (UINT32)GetCpuTimer();

    Status = pSmst->SmmInstallProtocolInterface(
                    &UsbSmmProtocolHandle,
                    &gAmiUsbSmmProtocolGuid,
                    EFI_NATIVE_INTERFACE,
                    &gUsbSmmProtocol
                    );
	
	USB_DEBUG(DEBUG_LEVEL_3, "AMIUSB SMM protocol: %r\n", Status);
#endif

#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)
    InitAmiUsbSmmGlobalDataValidationLib(ImageHandle, SystemTable);
    UpdateAmiUsbSmmGlobalDataCrc32(gUsbData);
#endif

										//(EIP54018+)>
#if USB_S5_WAKEUP_SUPPORT
    Status = pBS->LocateProtocol(
        &gEfiSmmSxDispatchProtocolGuid,
        NULL,
        &SxDispatchProtocol
    );

    if (EFI_ERROR(Status)) {
        return Status;
    }

    S5DispatchContext.Type  = SxS5;
    S5DispatchContext.Phase = SxEntry;
    Status = SxDispatchProtocol->Register(
        SxDispatchProtocol,
        UsbS5SmiCallback,
        &S5DispatchContext,
        &S5DispatchHandle
    );

    if (EFI_ERROR(Status)) {
        return Status;
    }

    // Locate Power Button Dispatch Protocol
    Status = pBS->LocateProtocol(
        &gEfiSmmPowerButtonDispatchProtocolGuid,
        NULL,
        &PbDispatchProtocol
    );

    if (EFI_ERROR(Status)) {
        return Status;
    }

    // Register the handler for power button presses
    PbDispatchContext.Phase = PowerButtonEntry;
    Status = PbDispatchProtocol->Register(
        PbDispatchProtocol,
        UsbPowerButtonSmiCallback,
        &PbDispatchContext,
        &PbDispatchHandle
    );
#endif
										//<(EIP54018+)

    return Status;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBSWSMIHandler
//
// Description: Invoked on reads from SW SMI port with value USB_SWSMI. This
//              function dispatches the USB Request Packets (URP) to the
//              appropriate functions.
//
// Input:       EBDA:USB_DATA_EBDA_OFFSET - Pointer to the URP (USB Request
//              Packet structure)
//              DispatchHandle  - EFI Handle
//              DispatchContext - Pointer to the EFI_SMM_SW_DISPATCH_CONTEXT
//
// Output:      bRetValue   Zero on successfull completion
//              Non-zero on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBSWSMIHandler (
    EFI_HANDLE                  DispatchHandle,
    EFI_SMM_SW_DISPATCH_CONTEXT *DispatchContext
)
{
    URP_STRUC   *UsbUrp;
    UINT16      EbdaSeg;
    EFI_STATUS  Status;

    if (gLockSmiHandler == TRUE) {
        return;
    }
#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);

    if (EFI_ERROR(Status)) {
        gLockHwSmiHandler = TRUE;
        gLockSmiHandler = TRUE;
        return;
    }
#endif

	if (gUsbData->fpURP) {			// Call from AMIUSB C area
        Status = AmiValidateMemoryBuffer((VOID*)gUsbData->fpURP, sizeof(URP_STRUC));
        if (EFI_ERROR(Status)) {
            USB_DEBUG(3, "UsbApiHandler Invalid Pointer, the address is in SMRAM.\n");
            return;
        }
		UsbUrp = gUsbData->fpURP;
		gUsbData->fpURP = 0;   		// Clear the switch
	} else {
	    if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_OS) {
            return;
        }
        //
        // Get the fpURP pointer from EBDA
        //
        EbdaSeg = *((UINT16*)0x40E);
        UsbUrp = *(URP_STRUC**)(UINTN)(((UINT32)EbdaSeg << 4) + USB_DATA_EBDA_OFFSET);
        UsbUrp = (URP_STRUC*)((UINTN)UsbUrp & 0xFFFFFFFF);
        Status = AmiValidateMemoryBuffer((VOID*)UsbUrp, sizeof(URP_STRUC));
        if (EFI_ERROR(Status)) {
            USB_DEBUG(3, "UsbApiHandler Invalid Pointer, the address is in SMRAM.\n");
            return;
        }
	}

	if (UsbUrp == NULL) {
		return;
	}

    gCheckUsbApiParameter = TRUE;

	UsbApiHandler(UsbUrp);

    gCheckUsbApiParameter = FALSE;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   UsbHwSmiHandler
//
// Description: USB Hardware SMI handler.
//
// Input:       Host controller type.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
UsbHwSmiHandler (UINT8 HcType)
{
    UINT8       Index;
    HC_STRUC    *HcStruc;
    EFI_STATUS  Status;

    if (gLockHwSmiHandler == TRUE) {
        return;
    }

#if defined(PI_SPECIFICATION_VERSION)&&(PI_SPECIFICATION_VERSION>=0x0001000A)&&(CORE_COMBINED_VERSION >= 0x4028B)
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);

    if (EFI_ERROR(Status)) {
        gLockHwSmiHandler = TRUE;
        gLockSmiHandler = TRUE;
        return;
    }
#endif

    for (Index = 0; Index < gUsbData->HcTableCount; Index++) {
        HcStruc = gUsbData->HcTable[Index];
        if (HcStruc == NULL) {
            continue;
        }
        if (!(HcStruc->dHCFlag & HC_STATE_USED)) {
        	continue;
        }
        if (HcStruc->bHCType == HcType) { // Process appropriate interrupt
            (*gUsbData->aHCDriverTable
				[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDProcessInterrupt)(HcStruc);
        }
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   xhciHWSMIHandler
//
// Description: USB Hardware SMI handler.
//
// Input:       DispatchHandle  - EFI Handle
//              DispatchContext - Pointer to the EFI_SMM_SW_DISPATCH_CONTEXT
//
// Output:      Nothing
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
UhciHWSMIHandler (
    EFI_HANDLE                      DispatchHandle,
    EFI_SMM_USB_DISPATCH_CONTEXT    *DispatchContext
    )
{
    UsbHwSmiHandler(USB_HC_UHCI);
}
VOID
OhciHWSMIHandler (
    EFI_HANDLE                      DispatchHandle,
    EFI_SMM_USB_DISPATCH_CONTEXT    *DispatchContext
    )
{
    UsbHwSmiHandler(USB_HC_OHCI);
}
VOID
EhciHWSMIHandler (
    EFI_HANDLE                      DispatchHandle,
    EFI_SMM_USB_DISPATCH_CONTEXT    *DispatchContext
    )
{
    UsbHwSmiHandler(USB_HC_EHCI);
}

VOID
XhciHwSmiHandler (
    EFI_HANDLE	DispatchHandle,
    VOID	    *DispatchContext
    )
{
    UsbHwSmiHandler(USB_HC_XHCI);
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        USBInstallHwSmiHandler
//
// Description:
//  This function registers USB hardware SMI callback function.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
UsbInstallHwSmiHandler(
	HC_STRUC    *HcStruc
)
{
	EFI_STATUS                      Status;
	EFI_SMM_USB_DISPATCH_CONTEXT    UsbContext;
    EFI_SMM_USB_DISPATCH_PROTOCOL   *UsbDispatch;
	EFI_SMM_USB_DISPATCH			UsbCallback;
    EFI_HANDLE                      Handle = NULL;

    if (HcStruc->HwSmiHandle != NULL) {
        return EFI_SUCCESS;
    }
	
    Status = gBS->LocateProtocol(
            &gEfiSmmUsbDispatchProtocolGuid,
            NULL,
            &UsbDispatch);
    ASSERT_EFI_ERROR(Status);
	if (EFI_ERROR(Status)) {
		return Status;
	}

	switch (HcStruc->bHCType) {
		case USB_HC_UHCI:
			UsbCallback = UhciHWSMIHandler;
			break;

		case USB_HC_OHCI:
			UsbCallback = OhciHWSMIHandler;
			break;

		case USB_HC_EHCI:
			UsbCallback = EhciHWSMIHandler;
			break;

		case USB_HC_XHCI:
			UsbCallback = XhciHwSmiHandler;
			break;

        default:
            return EFI_UNSUPPORTED;
	}

    UsbContext.Type = UsbLegacy;
    UsbContext.Device = HcStruc->pHCdp;

    Status = UsbDispatch->Register(
                UsbDispatch,
                UsbCallback,
                &UsbContext,
                &Handle);

    USB_DEBUG(DEBUG_LEVEL_3, "AMIUSB HC type %x HW SMI registation status:: %r\n", HcStruc->bHCType, Status);

	if (!EFI_ERROR(Status)) {
		HcStruc->HwSmiHandle = Handle;
	}

	return Status;
}
#endif

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name:        Emul6064TrapCallback
//
// Description:
//  Update the KbcEmul feature when the Emul6064Trap Protocol becomes available.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
Emul6064TrapCallback (
    EFI_EVENT       Event,
    VOID            *Context
)
{
    EFI_STATUS                      Status;
    UINT32                          KbcEmulFeature = 0;
    
	Status = gBS->LocateProtocol(
				&gEmul6064TrapProtocolGuid,
				NULL,
				&gEmulationTrap);

    if(!gUsbData->kbc_support) {
        	Status = gBS->LocateProtocol(
        			&gEmul6064MsInputProtocolGuid,
        			NULL,
        			&gMsInput);

        	gBS->LocateProtocol(
        			&gEmul6064KbdInputProtocolGuid,
        			NULL,
        			&gKbdInput);

        if (Status == EFI_SUCCESS) {
            gUsbData->dUSBStateFlag |= USB_FLAG_6064EMULATION_ON;
            if(gEmulationTrap) 
                KbcEmulFeature = gEmulationTrap->FeatureSupported(gEmulationTrap);
                if(KbcEmulFeature & IRQ_SUPPORTED) {
                    gUsbData->dUSBStateFlag |= USB_FLAG_6064EMULATION_IRQ_SUPPORT;
                }
        } else {
           InitSysKbc( &gKbdInput, &gMsInput );
        }
    } else {
        //
        //Init Fake Emulation interface
        //
        InitSysKbc( &gKbdInput, &gMsInput );
    }
}

//////////////////////////////////////////////////////////////////////////////
//
// USB API Functions
//
//////////////////////////////////////////////////////////////////////////////

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_MassDeviceRequest
//
// Description: This routine services the USB API function number 27h.  It
//      handles all the mass storage related calls from the higher
//      layer. Different sub-functions are invoked depending on
//      the sub-function number
//
// Input:   fpURPPointer    Pointer to the URP structure
//      fpURPPointer.bSubFunc   Subfunction number
//          00  Get Device Information
//          01  Get Device Parameter
//          02  Reset Device
//          03  Read Device
//          04  Write Device
//          05  Verify Device
//          06  Format Device
//          07  Request Sense
//          08  Test Unit Ready
//          09  Start Stop Unit
//          0A  Read Capacity
//          0B  Mode Sense
//          0C  Device Inquiry
//          0D  Send Command
//          0E  Assign drive number
//
// Output:  URP structure is updated with the relevant information
//
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBAPI_MassDeviceRequest (URP_STRUC *fpURP)
{
    UINT8 bMassFuncIndex = fpURP->bSubFunc;
    UINT8 bNumberOfMassFunctions = sizeof aUsbMassApiTable / sizeof (API_FUNC *);

    //
    // Make sure function number is valid
    //
    if (bMassFuncIndex >= bNumberOfMassFunctions) {
        //fpURP->bRetValue = USBAPI_INVALID_FUNCTION;
        USB_DEBUG(3, "UsbApi MassDeviceRequet Invalid function#%x\n", bMassFuncIndex);
        return;
    }
    gUsbData->bUSBKBC_MassStorage = 01;
    //
    // Function number is valid - call it
    //
    aUsbMassApiTable[bMassFuncIndex](fpURP);
    gUsbData->bUSBKBC_MassStorage = 00;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_CheckPresence
//
// Description: This routine services the USB API function number 0.  It
//              reports the USB BIOS presence, its version number and
//              its current status information
//
// Input: fpURPPointer - Pointer to the URP structure
//
// Output: URP structure is updated with the following information
//            CkPresence.wBiosRev       USB BIOS revision (0210h means r2.10)
//            CkPresence.bBiosActive    0 - if USB BIOS is not running
//            CkPresence.bNumBootDev    Number of USB boot devices found
//            CkPresence.bNumHC         Number of host controller present
//            CkPresence.bNumPorts      Number of root hub ports
//            CkPresence.dUsbDataArea   Current USB data area
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBAPI_CheckPresence (URP_STRUC *fpURP)
{
    fpURP->bRetValue                        = USB_SUCCESS;
    fpURP->ApiData.CkPresence.bBiosActive   = 0;

    fpURP->ApiData.CkPresence.bNumBootDev   = 0;    // Number of USB boot devices found
    fpURP->ApiData.CkPresence.bNumKeyboards = 0;    // Number of USB keyboards present
    fpURP->ApiData.CkPresence.bNumMice      = 0;    // Number of USB mice present
    fpURP->ApiData.CkPresence.bNumPoint		= 0;    // Number of USB Point present    //(EIP38434+)
    fpURP->ApiData.CkPresence.bNumHubs      = 0;    // Number of USB hubs present
    fpURP->ApiData.CkPresence.bNumStorage   = 0;    // Number of USB storage devices present

    fpURP->ApiData.CkPresence.wBiosRev = (USB_DRIVER_MAJOR_VER << 4) + USB_DRIVER_MINOR_VER;
    fpURP->ApiData.CkPresence.bBiosActive = USB_ACTIVE; // Set USB BIOS as active
    if (!(gUsbData->dUSBStateFlag & USB_FLAG_DISABLE_LEGACY_SUPPORT)) {
        fpURP->ApiData.CkPresence.bBiosActive |= USB_LEGACY_ENABLE;
    }
    if (gUsbData->dUSBStateFlag & USB_FLAG_6064EMULATION_ON) {
        fpURP->ApiData.CkPresence.bBiosActive |= USB_6064_ENABLE;
    }
    USBWrap_GetDeviceCount(fpURP);  // Get active USB devices
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_Start
//
// Description: This API routine configures the USB host controllers and
//      enumerate the devices
//
// Input: fpURPPointer  URP structure with input parameters
//        StartHc.wDataAreaFlag Indicates which data area to use
//
// Output: StartHc.wDataAreaFlag Returns current data area pointer
//         bRetValue - USB_SUCCESS on success, USB_ERROR on error.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_Start (URP_STRUC *fpURP)
{
    USB_DEBUG(DEBUG_LEVEL_3, "USBSMI: Start\n");
    USB_DEBUG(DEBUG_LEVEL_3, "\tUSBAPI_HC_Proc:%x\n", &USBAPI_HC_Proc);
    USB_DEBUG(DEBUG_LEVEL_3, "\tUSBAPI_Core_Proc:%x\n", &USBAPI_Core_Proc);
    USB_DEBUG(DEBUG_LEVEL_3, "\tUSB_ReConfigDevice:%x\n", &USB_ReConfigDevice);
    fpURP->bRetValue = USB_StartHostControllers (gUsbData);
    USB_DEBUG(DEBUG_LEVEL_3, "USB_StartHostControllers returns %d\n", fpURP->bRetValue);
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_Stop
//
// Description: This routine stops the USB host controllers
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  bRetValue   USB_SUCCESS on success
//              USB_ERROR on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_Stop (URP_STRUC *fpURP)
{
    gCheckUsbApiParameter = FALSE;
    fpURP->bRetValue = USB_StopHostControllers (gUsbData);
    USB_DEBUG(DEBUG_LEVEL_3, "USB_StopHostControllers returns %d\n", fpURP->bRetValue);
    gUsbData->dUSBStateFlag &= ~(USB_FLAG_DRIVER_STARTED);
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_PowerManageUSB
//
// Description: This routine suspends the USB host controllers
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_PowerManageUSB (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_NOT_SUPPORTED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_PrepareForOS
//
// Description: This routine updates data structures to reflect that
//      POST is completed
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_PrepareForOS (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_NOT_SUPPORTED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_SecureInterface
//
// Description: This routine handles the calls related to security device
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_SecureInterface (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_NOT_SUPPORTED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_DisableInterrupts
//
// Description: This routine stops the USB host controllers interrupts
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  bRetValue   USB_SUCCESS on success
//              USB_ERROR on error (Like data area not found)
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_DisableInterrupts (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_NOT_SUPPORTED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_EnableInterrupts
//
// Description: This routine re-enable the USB host controller interrupts
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  bRetValue   USB_SUCCESS on success
//              USB_ERROR on error (Like data area not found)
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_EnableInterrupts (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_NOT_SUPPORTED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_MoveDataArea
//
// Description: This routine stops the USB host controllers and moves
//      the data area used by host controllers to a new area.
//      The host controller is started from the new place.
//
// Input:   fpURPPointer    URP structure with input parameters
//      StartHc.wDataAreaFlag   Indicates which data area to use
//
// Output:  bRetValue   USB_SUCCESS
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_MoveDataArea(URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_NOT_SUPPORTED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_GetDeviceInfo
//
// Description: This routine returns the information regarding
//      a USB device like keyboard, mouse, floppy drive etc
//
// Input:   fpURPPointer            URP structure with input parameters
//          GetDevInfo.bDevNumber   Device number (1-based) whose
//                  information is requested
//
// Output:  URP structure is updated with the following information
//      GetDevInfo.bHCNumber - HC number in which the device is found
//      GetDevInfo.bDevType  - Type of the device
//      bRetValue will be one of the following value
//      USB_SUCCESS         on successfull completion
//      USB_PARAMETER_ERROR if bDevNumber is invalid
//      USB_ERROR           on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID USBAPI_GetDeviceInfo (URP_STRUC *fpURP)
{
    DEV_INFO* fpDevInfo;

    //
    // Initialize the return values
    //
    fpURP->ApiData.GetDevInfo.bHCNumber = 0;
    fpURP->ApiData.GetDevInfo.bDevType  = 0;
    fpURP->bRetValue                    = USB_ERROR;

    //
    // Check for parameter validity
    //
    if ( !fpURP->ApiData.GetDevInfo.bDevNumber ) return;

    fpURP->bRetValue = USB_PARAMETER_ERROR;

    //
    // Get the device information structure for the 'n'th device
    //
    fpDevInfo = USBWrap_GetnthDeviceInfoStructure(fpURP->ApiData.GetDevInfo.bDevNumber);
//  if (!wRetCode) return;  // USB_PARAMETER_ERROR

    //
    // Return value
    //
    fpURP->ApiData.GetDevInfo.bDevType  = fpDevInfo->bDeviceType;
    fpURP->ApiData.GetDevInfo.bHCNumber = fpDevInfo->bHCNumber;
    fpURP->bRetValue                    = USB_SUCCESS;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_CheckDevicePresence
//
// Description: This routine checks whether a particular type of USB device
//      is installed in the system or not.
//
// Input:   fpURPPointer            URP structure with input parameters
//          ChkDevPrsnc.bDevType    Device type to find
//          ChkDevPrsnc.fpHCStruc   Pointer to HC being checked for device
//            connection; if NULL then the total number of devices
//            connected to ANY controller is returned.
//          ChkDevPrsnc.bNumber     Number of devices connected
//
// Output:  bRetValue will be one of the following value
//          USB_SUCCESS     if device type present, ChkDevPrsnc.bNumber <> 0
//          USB_ERROR       if device type absent, ChkDevPrsnc.bNumber returns 0
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBAPI_CheckDevicePresence (URP_STRUC *fpURP)
{
    UINT8 bSearchFlag;
    UINTN dData;

    bSearchFlag = USB_SRCH_DEV_NUM;
    if (fpURP->bSubFunc == 1)
    {
        bSearchFlag = USB_SRCH_DEVBASECLASS_NUM;
    }
    //
    // The total number of devices connected to ANY controller has been requested
    //
    dData = (UINTN) USB_GetDeviceInfoStruc( bSearchFlag,
            0, fpURP->ApiData.ChkDevPrsnc.bDevType, fpURP->ApiData.ChkDevPrsnc.fpHCStruc);

    fpURP->ApiData.ChkDevPrsnc.bNumber = (UINT8)dData;
    fpURP->bRetValue = (UINT8)((fpURP->ApiData.ChkDevPrsnc.bNumber)?
                                            USB_SUCCESS : USB_ERROR);
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIGetDeviceInformation
//
// Description: This function is part of the USB BIOS MASS API. This function
//      returns the device information of the mass storage device
//
// Input:   fpURPPointer    Pointer to the URP structure
//          bDevAddr    USB device address of the device
//
// Output:  bRetValue   Return value
//      fpURPPointer    Pointer to the URP structure
//          dSenseData  Sense data of the last command
//          bDevType    Device type byte (HDD, CD, Removable)
//          bEmuType    Emulation type used
//          fpDevId     Far pointer to the device ID
//          dInt13Entry INT 13h entry point
//
// Notes:   Initially the bDevAddr should be set to 0 as input. This
//      function returns the information regarding the first mass
//      storage device (if no device found it returns bDevAddr as
//      0FFh) and also updates bDevAddr to the device address of
//      the current mass storage device. If no other mass storage
//      device is found then the routine sets the bit7 to 1
//      indicating current information is valid but no more mass
//      device found in the system. The caller can get the next
//      device info if bDevAddr is not 0FFh and bit7 is not set
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIGetDeviceInformation (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USBMassGetDeviceInfo (&fpURP->ApiData.MassGetDevInfo);
}

VOID
USBMassAPIGetDeviceParameters (URP_STRUC *fpURP)
{
    DEV_INFO    *DevInfo;
    EFI_STATUS  Status;

    DevInfo = fpURP->ApiData.MassGetDevParms.fpDevInfo;

    Status = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(Status)) {
        return;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        Status = AmiValidateMemoryBuffer((VOID*)fpURP->ApiData.MassGetDevParms.fpInqData, sizeof(MASS_INQUIRY));
        if (EFI_ERROR(Status)) {
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif
    
    fpURP->ApiData.MassGetDevParms.fpInqData = USBMassGetDeviceParameters(DevInfo);
    fpURP->bRetValue = (fpURP->ApiData.MassGetDevParms.fpInqData == NULL)? USB_ERROR : USB_SUCCESS;
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBMassAPIGetDevStatus
//
// Description: This function returns the drive status and media presence
//      status
//
// Input:       fpURPPointer    Pointer to the URP structure
//              fpURP->ApiData.fpDevInfo - pointer to USB device that is
//              requested to be checked
//
// Output:  Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USBMassAPIGetDevStatus(URP_STRUC *fpURP)
{
#if USB_DEV_MASS
    fpURP->bRetValue    = USBMassGetDeviceStatus (&fpURP->ApiData.MassGetDevSts);
//    USB_DEBUG(DEBUG_LEVEL_3, "USBMassAPIGetDevStatus ... check function call correct?\n");
#endif
}



//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIGetDeviceGeometry
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   fpURPPointer    Pointer to the URP structure
//          bDevAddr    USB device address of the device
//
// Output:  bRetValue   Return value
//      fpURPPointer    Pointer to the URP structure
//          dSenseData  Sense data of the last command
//          bNumHeads   Number of heads
//          wNumCylinders   Number of cylinders
//          bNumSectors Number of sectors
//          wBytesPerSector Number of bytes per sector
//          bMediaType  Media type
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIGetDeviceGeometry(URP_STRUC *fpURP)
{
    fpURP->bRetValue = USBMassGetDeviceGeometry (&fpURP->ApiData.MassGetDevGeo);
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIResetDevice
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  bRetValue   Return value
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIResetDevice (URP_STRUC *fpURP)
{
    UINT8       bDevAddr;
    DEV_INFO    *fpDevInfo;
    UINT16      wResult;

    bDevAddr = fpURP->ApiData.MassReset.bDevAddr;

    //
    // Get the device info structure for the matching device address
    //
    fpDevInfo   = USB_GetDeviceInfoStruc(USB_SRCH_DEV_INDX, 0, bDevAddr, 0);
    if((fpDevInfo == NULL)|| (!(fpDevInfo->Flag & DEV_INFO_DEV_PRESENT))) {
		fpURP->bRetValue = USB_ATA_TIME_OUT_ERR;
        return;
    }
    //
    // Send Start/Stop Unit command to UFI class device only
    //
    fpURP->bRetValue    = USB_SUCCESS;
    if(fpDevInfo->bSubClass ==  SUB_CLASS_UFI) {
        wResult = USBMassStartUnitCommand (fpDevInfo);
        if (wResult) {
            fpURP->bRetValue  = USBWrapGetATAErrorCode(fpURP->ApiData.MassReset.dSenseData);
        }
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIReadDevice
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   fpURPPointer    Pointer to the URP structure, it contains the following:
//                  bDevAddr      USB device address of the device
//                  dStartLBA     Starting LBA address
//                  wNumBlks      Number of blocks to read
//                  wPreSkipSize  Number of bytes to skip before
//                  wPostSkipSize Number of bytes to skip after
//                  fpBufferPtr   Far buffer pointer
//
// Output: fpURPPointer Pointer to the URP structure
//                  bRetValue    Return value
//                  dSenseData   Sense data of the last command
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIReadDevice (
    URP_STRUC *Urp
)
{
    DEV_INFO    *DevInfo;
    UINT8       DevAddr;
    UINT16      Result;
    UINT32		Data = 0;
    UINT8       OpCode;

    DevAddr = Urp->ApiData.MassRead.DevAddr;

    if (((DevAddr == USB_HOTPLUG_FDD_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_FDD_ENABLED) == FALSE)) ||
        ((DevAddr == USB_HOTPLUG_HDD_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_HDD_ENABLED) == FALSE)) ||
        ((DevAddr == USB_HOTPLUG_CDROM_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_CDROM_ENABLED) == FALSE))) {
        Urp->bRetValue = USB_ATA_DRIVE_NOT_READY_ERR;
        return;
    }

    //
    // Get the device info structure for the matching device address
    //
    DevInfo = USB_GetDeviceInfoStruc(USB_SRCH_DEV_INDX, 0, DevAddr, 0);
    if ((DevInfo == NULL)|| (!(DevInfo->Flag & DEV_INFO_DEV_PRESENT))) {
		Urp->bRetValue = USB_ATA_TIME_OUT_ERR;
        return;
    }

											//(EIP15037+)>
#if EXTRA_CHECK_DEVICE_READY
    //
    // Check device ready
    //
    Data = USBMassCheckDeviceReady(DevInfo);
	if (Data) {
        Urp->ApiData.MassRead.dSenseData = Data;
        Urp->bRetValue = USBWrapGetATAErrorCode(Urp->ApiData.MassRead.dSenseData);	//(EIP31535)
		return;
	}
#endif
											//<(EIP15037+)

    //
    // Issue read command
    //
    if (Shr64(DevInfo->MaxLba, 32)) {
        OpCode = COMMON_READ_16_OPCODE;
    } else {
        OpCode = COMMON_READ_10_OPCODE;
    }
    Result = USBMassRWVCommand(DevInfo, OpCode, &Urp->ApiData.MassRead);
    //USB_DEBUG(DEBUG_LEVEL_3, " wr(%x):%x %x", DevAddr, Result, Urp->ApiData.MassRead.dSenseData);
    if (Result) {
        Urp->bRetValue = USB_SUCCESS;
        return;
    }
    Urp->bRetValue = USBWrapGetATAErrorCode(Urp->ApiData.MassRead.SenseData);
    //USB_DEBUG(DEBUG_LEVEL_3, " er(%x):%x", DevAddr, Urp->bRetValue);
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIWriteDevice
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   fpURPPointer    Pointer to the URP structure
//          bDevAddr    USB device address of the device
//          dStartLBA   Starting LBA address
//          wNumBlks    Number of blocks to write
//          wPreSkipSize    Number of bytes to skip before
//          wPostSkipSize   Number of bytes to skip after
//          fpBufferPtr Far buffer pointer
//
// Output:  fpURPPointer    Pointer to the URP structure
//          bRetValue   Return value
//          dSenseData  Sense data of the last command
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIWriteDevice(
    URP_STRUC *Urp
)
{
    DEV_INFO    *DevInfo;
    UINT8       DevAddr;
    UINT16      Result;
    UINT32		Data = 0;
    UINT8       OpCode;

    DevAddr = Urp->ApiData.MassWrite.DevAddr;

    if (((DevAddr == USB_HOTPLUG_FDD_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_FDD_ENABLED) == FALSE)) ||
        ((DevAddr == USB_HOTPLUG_HDD_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_HDD_ENABLED) == FALSE)) ||
        ((DevAddr == USB_HOTPLUG_CDROM_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_CDROM_ENABLED) == FALSE))) {
        Urp->bRetValue = USB_ATA_DRIVE_NOT_READY_ERR;
        return;
    }

    //
    // Get the device info structure for the matching device address
    //
    DevInfo = USB_GetDeviceInfoStruc(USB_SRCH_DEV_INDX, 0, DevAddr, 0);
    if((DevInfo == NULL)|| (!(DevInfo->Flag & DEV_INFO_DEV_PRESENT))) {
		Urp->bRetValue = USB_ATA_TIME_OUT_ERR;
        return;
    }
/*
    if (!(DevInfo->bLastStatus & USB_MASS_MEDIA_PRESENT)) {
        Urp->bRetValue = USB_ATA_NO_MEDIA_ERR;
        return;
    }
*/
											//(EIP15037+)>
#if EXTRA_CHECK_DEVICE_READY
    //
    // Check device ready
    //
    Data = USBMassCheckDeviceReady(DevInfo);
	if (Data) {
        Urp->ApiData.MassRead.dSenseData = Data;
        Urp->bRetValue = USBWrapGetATAErrorCode(Urp->ApiData.MassWrite.dSenseData);	//(EIP31535)
		return;
	}
#endif
											//<(EIP15037+)

    //
    // Issue write command
    //
    if (Shr64(DevInfo->MaxLba, 32)) {
        OpCode = COMMON_WRITE_16_OPCODE;
    } else {
        OpCode = COMMON_WRITE_10_OPCODE;
    }
    Result = USBMassRWVCommand(DevInfo, OpCode, &Urp->ApiData.MassWrite);
    if (Result) {
        Urp->bRetValue = USB_SUCCESS;
        return;
    }

    Urp->bRetValue = USBWrapGetATAErrorCode(Urp->ApiData.MassWrite.SenseData);
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIVerifyDevice
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   fpURPPointer    Pointer to the URP structure
//          bDevAddr    USB device address of the device
//          dStartLBA   Starting LBA address
//          wNumBlks    Number of blocks to write
//          wPreSkipSize    Number of bytes to skip before
//          wPostSkipSize   Number of bytes to skip after
//          fpBufferPtr Far buffer pointer
//
// Output:  fpURPPointer    Pointer to the URP structure
//          bRetValue   Return value
//          dSenseData  Sense data of the last command
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIVerifyDevice(
    URP_STRUC *Urp
)
{
    DEV_INFO    *DevInfo;
    UINT8       DevAddr;
    UINT16      Result;
    UINT32		Data = 0;
    UINT8       OpCode;

    DevAddr = Urp->ApiData.MassVerify.DevAddr;

    if (((DevAddr == USB_HOTPLUG_FDD_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_FDD_ENABLED) == FALSE)) ||
        ((DevAddr == USB_HOTPLUG_HDD_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_HDD_ENABLED) == FALSE)) ||
        ((DevAddr == USB_HOTPLUG_CDROM_ADDRESS) &&
            ((gUsbData->dUSBStateFlag & USB_HOTPLUG_CDROM_ENABLED) == FALSE))) {
        Urp->bRetValue = USB_ATA_DRIVE_NOT_READY_ERR;
        return;
    }

    //
    // Get the device info structure for the matching device address
    //
    DevInfo = USB_GetDeviceInfoStruc(USB_SRCH_DEV_INDX, 0, DevAddr, 0);
    if ((DevInfo == NULL)|| (!(DevInfo->Flag & DEV_INFO_DEV_PRESENT))) {
		Urp->bRetValue = USB_ATA_TIME_OUT_ERR;
        return;
    }
											//(EIP15037+)>
#if EXTRA_CHECK_DEVICE_READY
    //
    // Check device ready
    //
    Data = USBMassCheckDeviceReady(DevInfo);
	if (Data) {
        Urp->ApiData.MassRead.dSenseData = Data;
        Urp->bRetValue = USBWrapGetATAErrorCode(Urp->ApiData.MassVerify.dSenseData);	//(EIP31535)
		return;
	}
#endif
											//<(EIP15037+)

    //
    // Issue write command
    //
    if (Shr64(DevInfo->MaxLba, 32)) {
        OpCode = COMMON_VERIFY_16_OPCODE;
    } else {
        OpCode = COMMON_VERIFY_10_OPCODE;
    }
    Result = USBMassRWVCommand(DevInfo, OpCode, &Urp->ApiData.MassVerify);
    if (Result) {
        Urp->bRetValue = USB_SUCCESS;
        return;
    }

    Urp->bRetValue = USBWrapGetATAErrorCode(Urp->ApiData.MassVerify.SenseData);

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPIFormatDevice
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  bRetValue   Return value
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPIFormatDevice(URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBMassAPICommandPassThru
//
// Description: This function is part of the USB BIOS MASS API. This
//      function can be used to pass raw command/data sequence to
//      the USB mass storage device
//
// Input:   fpURPPointer    Pointer to the URP structure
//
// Output:  bRetValue   Return value
//
// Modified:    Nothing
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBMassAPICommandPassThru (URP_STRUC *fpURP)
{
    UINT8                   Result;
    MASS_CMD_PASS_THRU      *MassCmdPassThru;
    EFI_STATUS              Status = EFI_SUCCESS;

    MassCmdPassThru = &fpURP->ApiData.MassCmdPassThru;

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        Status = AmiValidateMemoryBuffer((VOID*)MassCmdPassThru->fpCmdBuffer, MassCmdPassThru->wCmdLength);
        if (EFI_ERROR(Status)) {
            return;
        }
        Status = AmiValidateMemoryBuffer((VOID*)MassCmdPassThru->fpDataBuffer, MassCmdPassThru->wDataLength);
        if (EFI_ERROR(Status)) {
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    Result = USBMassCmdPassThru(MassCmdPassThru);
    
    fpURP->bRetValue = Result;
}


//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBMassAPIAssignDriveNumber
//
// Description: This function is part of the USB BIOS MASS API. This function
//      assigns the logical drive device according to the information of the
//      mass storage device
//
// Input:   fpURPPointer    Pointer to the URP structure
//      bDevAddr    USB device address of the device
//      bLogDevNum  Logical Drive Number to assign to the device
//
// Output:  Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USBMassAPIAssignDriveNumber (URP_STRUC *fpURP)
{
    fpURP->bRetValue = USB_SUCCESS; // No errors expected after this point
}


//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBMassAPICheckDevStatus
//
// Description: This function is part of the USB BIOS MASS API. This function
//              invokes USB Mass Storage API handler to check whether device
//              is ready. If called for the first time, this function retrieves
//              the mass storage device geometry and fills the corresponding
//              fpDevInfo fields.
//
// Input:       fpURPPointer    Pointer to the URP structure
//              fpURP->ApiData.fpDevInfo - pointer to USB device that is
//              requested to be checked
//
// Output:  Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USBMassAPICheckDevStatus(URP_STRUC *fpURP)
{
#if USB_DEV_MASS
    UINT32      Result;
    DEV_INFO    *DevInfo;
    EFI_STATUS  Status;

    DevInfo = fpURP->ApiData.MassChkDevReady.fpDevInfo;

    Status = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(Status)) {
        return;
    }
	
	gCheckUsbApiParameter = FALSE;

    Result = USBMassCheckDeviceReady(fpURP->ApiData.MassChkDevReady.fpDevInfo);
    fpURP->bRetValue = (UINT8)Result;
#endif
}


//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_LightenKeyboardLEDs
//
// Description: This function is part of the USB BIOS API. This function
//              controls LED state on the connected USB keyboards
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:  Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USBAPI_LightenKeyboardLEDs(URP_STRUC *fpURP)
{
#if USB_DEV_KBD

    gCheckUsbApiParameter = FALSE;

    if(fpURP->ApiData.KbLedsData.fpLedMap) {
        gUsbData->bUSBKBShiftKeyStatus = 0;
        if(((LED_MAP*)fpURP->ApiData.KbLedsData.fpLedMap)->NumLock) {
            gUsbData->bUSBKBShiftKeyStatus |= KB_NUM_LOCK_BIT_MASK;
        }
        if(((LED_MAP*)fpURP->ApiData.KbLedsData.fpLedMap)->CapsLock) {
            gUsbData->bUSBKBShiftKeyStatus |= KB_CAPS_LOCK_BIT_MASK;
        }
        if(((LED_MAP*)fpURP->ApiData.KbLedsData.fpLedMap)->ScrLock) {
            gUsbData->bUSBKBShiftKeyStatus |= KB_SCROLL_LOCK_BIT_MASK;
        }
    }
    //USB_DEBUG(DEBUG_LEVEL_3," LEDs: %d\n", gUsbData->bUSBKBShiftKeyStatus);
    USBKB_LEDOn();

    fpURP->bRetValue    = USB_SUCCESS;
    return;
#else
    fpURP->bRetValue    = USB_NOT_SUPPORTED;
#endif

}

VOID
USBAPI_LightenKeyboardLEDs_Compatible(URP_STRUC *fpURP)
{
    USBAPI_LightenKeyboardLEDs(fpURP);
}

					                        //(EIP29733+)>
//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_KbcAccessControl
//
// Description: This function is part of the USB BIOS API. This function
//              is used to control whether KBC access in USB module 
//              should be blocked or not.
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>


VOID
UsbKbcAccessControl(
    UINT8 ControlSwitch
)
{
    UINT8       Index;
    HC_STRUC    *HcStruc;
#if USB_RUNTIME_DRIVER_IN_SMM
    EFI_STATUS Status = EFI_SUCCESS;
    
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);
    
    if (EFI_ERROR(Status)) {
        gLockHwSmiHandler = TRUE;
        gLockSmiHandler = TRUE;
        return;
    }
#endif

    gCheckUsbApiParameter = FALSE;

    IsKbcAccessBlocked = (ControlSwitch != 0)? TRUE : FALSE;

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

    if (Index == gUsbData->HcTableCount) {
        return;
    }
/*
    //
    // Check if the USB access in Legacy mode. If it's legacy mode enable/disable
    // the Kbcemulation based on the ControlSwitch  
    //
    if(!(gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI)) {

        if(IsKbcAccessBlocked) {
            if(gEmulationTrap) { 
                //
                // Keyboard access blocked. Disable the Emulation
                //
                gEmulationTrap->TrapDisable(gEmulationTrap);
            }
        } else {
            if(gEmulationTrap) { 
                //
                // Keyboard access enabled. Enable the KbcEmulation
                //
                gEmulationTrap->TrapEnable(gEmulationTrap);
            }
        }
    }
*/
					//(EIP48323+)>
    //Reflush USB data buffer if intend to disable usb keyboard data throughput.
    if (IsKbcAccessBlocked) {
        USBKeyRepeat(NULL, 1);  // Disable Key repeat
        gUsbData->RepeatKey = 0;

		// Clear Legacy USB keyboard buffer
		MemFill(gUsbData->aKBCCharacterBufferStart, sizeof(gUsbData->aKBCCharacterBufferStart), 0);
		gUsbData->fpKBCCharacterBufferHead = gUsbData->aKBCCharacterBufferStart;
		gUsbData->fpKBCCharacterBufferTail = gUsbData->aKBCCharacterBufferStart;
		
		MemFill(gUsbData->aKBCScanCodeBufferStart, sizeof(gUsbData->aKBCScanCodeBufferStart), 0);
		gUsbData->fpKBCScanCodeBufferPtr = gUsbData->aKBCScanCodeBufferStart;
											
		MemFill(gUsbData->aKBCDeviceIDBufferStart, sizeof(gUsbData->aKBCDeviceIDBufferStart), 0);
		MemFill(gUsbData->aKBCShiftKeyStatusBufferStart, sizeof(gUsbData->aKBCShiftKeyStatusBufferStart), 0);
		
		MemFill(gUsbData->aKBInputBuffer, sizeof(gUsbData->aKBInputBuffer), 0);
    }
					//<(EIP48323+)
}


VOID
USBAPI_KbcAccessControl(URP_STRUC *fpURP)
{
    UsbKbcAccessControl(fpURP->ApiData.KbcControlCode);
}
					                        //<(EIP29733+)
//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USB_StopLegacy
//
// Description: This function is part of the USB BIOS API. This function init USB 
//             legacy support.
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      None
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>
VOID
USB_StopLegacy(URP_STRUC *fpURP)
{
    //shutdown device first
    UINT8       bIndex;
    DEV_INFO    *fpDevInfo;
    HC_STRUC    *fpHCStruc;
    
    for (bIndex = 1; bIndex < MAX_DEVICES; bIndex ++){
        fpDevInfo = gUsbData->aDevInfoTable +bIndex;
        if ((fpDevInfo->Flag & 
            (DEV_INFO_VALID_STRUC |DEV_INFO_DEV_PRESENT)    ) ==   
            (DEV_INFO_VALID_STRUC |DEV_INFO_DEV_PRESENT)    ){
            //
            fpHCStruc = gUsbData->HcTable[fpDevInfo->bHCNumber - 1];
            //
            USB_StopDevice (fpHCStruc, fpDevInfo->bHubDeviceNumber, fpDevInfo->bHubPortNumber);
        }
    }

    StopControllerType(USB_HC_XHCI);    //(EIP57521+)
    StopControllerType(USB_HC_EHCI);
    StopControllerType(USB_HC_UHCI);
    StopControllerType(USB_HC_OHCI);
    
    //return as success
    fpURP->bRetValue    = USB_SUCCESS;
    
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USB_StartLegacy
//
// Description: This function is part of the USB BIOS API. This function init USB 
//             legacy support.
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      None
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>
VOID
USB_StartLegacy(URP_STRUC *fpURP)
{
                                        //(EIP57521)>
    gUsbData->bHandOverInProgress = FALSE;
    //Start XHCI
    StartControllerType(USB_HC_XHCI);
    USB_EnumerateRootHubPorts(USB_HC_XHCI);
    //Start EHCI
    StartControllerType(USB_HC_EHCI);
    USB_EnumerateRootHubPorts(USB_HC_EHCI);
    //Start UHCI
    StartControllerType(USB_HC_UHCI);
    USB_EnumerateRootHubPorts(USB_HC_UHCI);
    //Start OHCI
    StartControllerType(USB_HC_OHCI);
    USB_EnumerateRootHubPorts(USB_HC_OHCI);
                                        //<(EIP57521)
    //return as success
  fpURP->bRetValue    = USB_SUCCESS;
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_LegacyControl
//
// Description: This function is part of the USB BIOS API. This function
//              is used to shutdown/init USB legacy support.
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      None
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>
VOID USBAPI_LegacyControl (URP_STRUC *fpURP)
{
    UINT8 bSubLegacyFunc = fpURP->bSubFunc,i;       //(EIP102150+)
    UINT8 Count = (UINT8)(gUsbData->fpKBCScanCodeBufferPtr - 
                  (UINT8*)gUsbData->aKBCScanCodeBufferStart);   //(EIP102150+) 
                  
    gCheckUsbApiParameter = FALSE;

    USB_DEBUG(DEBUG_LEVEL_3, "USBAPI_LegacyControl %d\n", fpURP->bSubFunc);
    if(bSubLegacyFunc==STOP_USB_CONTROLLER){ 		//(EIP43475+)>  	
        USB_StopLegacy (fpURP);
                                        //(EIP102150+)>
    for(i = Count; i > 0; i--)
        USBKB_DiscardCharacter(&gUsbData->aKBCShiftKeyStatusBufferStart[i-1]); 
                                        //<(EIP102150+)
        if(gEmulationTrap) 
            gEmulationTrap->TrapDisable(gEmulationTrap);
    }

    if(bSubLegacyFunc==START_USB_CONTROLLER){
        USB_StartLegacy (fpURP);
        if(gEmulationTrap)
            gEmulationTrap->TrapEnable(gEmulationTrap);
    }												//<(EIP43475+)
    USB_DEBUG(DEBUG_LEVEL_3, "Result %d\n", fpURP->bRetValue);
}
										//(EIP74876+)>
//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_UsbStopController
//
// Description: This function is part of the USB BIOS API. This function stops 
//              the USB host controller.
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      None
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>
VOID USBAPI_UsbStopController (URP_STRUC *fpURP)
{
    gCheckUsbApiParameter = FALSE;
	StopControllerBdf(fpURP->ApiData.HcBusDevFuncNum);
}
										//<(EIP74876+)
//-----------------------------------------------------
//
//-----------------------------------------------------
EFI_STATUS USBRT_LegacyControl (VOID *fpURP)
{
#if USB_RUNTIME_DRIVER_IN_SMM
    EFI_STATUS Status = EFI_SUCCESS;
    
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);
    
    if (EFI_ERROR(Status)) {
        gLockHwSmiHandler = TRUE;
        gLockSmiHandler = TRUE;
        return EFI_SUCCESS;
    }
#endif
  //
  USBAPI_LegacyControl ((URP_STRUC *)fpURP);
  //
  return((EFI_STATUS)(((URP_STRUC *)fpURP)->bRetValue));
}


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

VOID
USBAPI_GetDeviceAddress(
    URP_STRUC *Urp
)
{
	UINT8		i;
	DEV_INFO	*DevInfo = NULL;

	for (i = 1; i < MAX_DEVICES; i++) {
		if (!(gUsbData->aDevInfoTable[i].Flag & DEV_INFO_VALID_STRUC)) {
			continue;
		}
		if ((gUsbData->aDevInfoTable[i].wVendorId == Urp->ApiData.GetDevAddr.Vid) && 
				(gUsbData->aDevInfoTable[i].wDeviceId == Urp->ApiData.GetDevAddr.Did)) {
			DevInfo = &gUsbData->aDevInfoTable[i];
		}
	}
	if (DevInfo == NULL) {
		Urp->bRetValue = USB_ERROR;
		return;
	}

	Urp->ApiData.GetDevAddr.DevAddr = DevInfo->bDeviceAddress;
	Urp->bRetValue = USB_SUCCESS;
}

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

VOID
USBAPI_ExtDriverRequest (
    URP_STRUC *Urp
)
{
    DEV_INFO	*DevInfo = NULL;
    DEV_DRIVER	*DevDriver;

	DevInfo = USB_GetDeviceInfoStruc(USB_SRCH_DEV_ADDR, 0, Urp->ApiData.DevAddr, 0);
	if (DevInfo == NULL) {
		Urp->bRetValue = USB_ERROR;
		return;
	}

    DevDriver = UsbFindDeviceDriverEntry(DevInfo->fpDeviceDriver);

	if (DevDriver != NULL) {
		DevDriver->pfnDriverRequest(DevInfo, Urp);
	}
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USB_StopUnsupportedHc
//
// Description: This routine is called, from host controllers that supports
//				OS handover functionality, when OS wants the BIOS to hand-over 
//				the host controllers to the OS.  This routine will stop HC that 
//				does not support this functionality.
//
// Input:       None
//
// Output:      None
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USB_StopUnsupportedHc()
{

#if USB_RUNTIME_DRIVER_IN_SMM
    UINT8       Index;
    HC_STRUC*   HcStruc;
    EFI_STATUS  Status;
    
    Status = AmiUsbSmmGlobalDataValidation(gUsbData);

    ASSERT_EFI_ERROR(Status);
    
    if (EFI_ERROR(Status)) {
        gLockHwSmiHandler = TRUE;
        gLockSmiHandler = TRUE;
        return;
    }
    
	USBSB_UninstallTimerHandlers();

    USB_DEBUG(DEBUG_LEVEL_3, "Stopping all external HCs");
    for (Index = 0; Index < gUsbData->HcTableCount; Index++) {
        HcStruc = gUsbData->HcTable[Index];
        if (HcStruc == NULL) {
            continue;
        }
        if (HcStruc->HwSmiHandle != NULL) {
            continue;
        }
        if (HcStruc->dHCFlag & HC_STATE_RUNNING) {
            (*gUsbData->aHCDriverTable[GET_HCD_INDEX(HcStruc->bHCType)].pfnHCDStop)(HcStruc);
            USB_DEBUG(DEBUG_LEVEL_3, ".");
        }
    }
    
    USB_DEBUG(DEBUG_LEVEL_3, "\n");

#endif

	if(gUsbData->UsbXhciHandoff) {
		StopControllerType(USB_HC_XHCI);
	}
	if(gUsbData->UsbEhciHandoff) {
		gUsbData->bHandOverInProgress = TRUE;
		StopControllerType(USB_HC_EHCI);
	}
	if(gUsbData->UsbOhciHandoff) {
		StopControllerType(USB_HC_OHCI);
	}
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_ChangeOwner
//
// Description: This function is part of the USB BIOS API. This function
//              updates the global variables according to the new owner
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
// Notes:       It is a caller responsibility to release the keyboard only if it
//              was previously acquired.
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USBAPI_ChangeOwner(URP_STRUC *fpURP)
{
//USB_DEBUG(DEBUG_LEVEL_3, "USBAPI_ChangeOwner..");

    if(fpURP->ApiData.Owner) {  // Changing to Efi driver
//USB_DEBUG(DEBUG_LEVEL_3, "fpURP->ApiData.Owner=%d\n", fpURP->ApiData.Owner);
        if(gEmulationTrap) {
            gEmulationTrap->TrapDisable(gEmulationTrap);
        }
        gUsbData->dUSBStateFlag |= USB_FLAG_RUNNING_UNDER_EFI;
    } else {    // Acquiring - check the current condition first
//USB_DEBUG(DEBUG_LEVEL_3, "fpURP->ApiData.Owner=%d...", fpURP->ApiData.Owner);
        if(gEmulationTrap) {
            gEmulationTrap->TrapEnable(gEmulationTrap);
        }

        if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI) {
//USB_DEBUG(DEBUG_LEVEL_3, "USB_FLAG_RUNNING_UNDER_EFI\n");
            gUsbData->dUSBStateFlag &= ~USB_FLAG_RUNNING_UNDER_EFI;
        } else {
//USB_DEBUG(DEBUG_LEVEL_3, "not USB_FLAG_RUNNING_UNDER_EFI\n");
        }
    }
    fpURP->bRetValue = USB_SUCCESS;
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_HcStartStop
//
// Description: This function is part of the USB BIOS API. This function 
//              starts/stops the USB host controller.
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:      None
//
// Notes:
//
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID
USBAPI_HcStartStop(URP_STRUC *Urp)
{
    HC_STRUC*   HcStruc;
    EFI_STATUS  Status;

    HcStruc = Urp->ApiData.HcStartStop.HcStruc;

    Status = UsbHcStrucValidation(HcStruc);

    if (EFI_ERROR(Status)) {
        return;
    }

    if ((HcStruc->bHCType != USB_HC_UHCI) && (HcStruc->bHCType != USB_HC_OHCI) &&
        (HcStruc->bHCType != USB_HC_EHCI) && (HcStruc->bHCType != USB_HC_XHCI)) {
        return;
    }

    gCheckUsbApiParameter = FALSE;

    if (Urp->ApiData.HcStartStop.Start) {
        Urp->bRetValue = UsbHcStart(HcStruc);
    } else {
        Urp->bRetValue = UsbHcStop(HcStruc);
    }
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_invoke_in_frame
//
// Description: Invokes procedure passing parameters supplied in the buffer
//      It replicates the stack frame so that target procedure can
//      see the parameters passed to the stub.
//
// Output:  Returns result of invoked proc
//
//------------------------------------------------------------------------------
//<AMI_PHDR_END>

//
// The following typedef corresponds to the min width type that can be passed
// into function call as a parameter without padding
//
typedef UINTN STACKWORD;

UINTN 
USBAPI_invoke_in_frame(
    VOID* pProc,
    VOID* buffer,
    UINT32 paramSize )
{
    STACKWORD* params = (STACKWORD*)buffer;

    switch(paramSize/sizeof(STACKWORD)){
    case 0: return ((STACKWORD (*)())pProc)();
    case 1: return ((STACKWORD (*)(STACKWORD))pProc)(params[0]);
    case 2: return ((STACKWORD (*)(STACKWORD,STACKWORD))pProc)(params[0],
                params[1]);
    case 3: return ((STACKWORD (*)(STACKWORD,STACKWORD,STACKWORD))pProc)(
                params[0],params[1],params[2]);
    case 4: return ((STACKWORD (*)(STACKWORD,STACKWORD,STACKWORD,
                STACKWORD))pProc)(
                params[0],params[1],params[2],params[3]);
    case 5: return ((STACKWORD (*)(STACKWORD,STACKWORD,STACKWORD,STACKWORD,
                STACKWORD))pProc)(
                params[0],params[1],params[2],params[3],params[4]);
    case 6: return ((STACKWORD (*)(STACKWORD,STACKWORD,STACKWORD,STACKWORD,
                STACKWORD,STACKWORD))pProc)(
                params[0],params[1],params[2],params[3],params[4],params[5]);
    case 7: return ((STACKWORD (*)(STACKWORD,STACKWORD,STACKWORD,STACKWORD,
                STACKWORD,STACKWORD,STACKWORD))pProc)(
                params[0],params[1],params[2],params[3],params[4],params[5],
                params[6]);
    default:
        ASSERT(paramSize/sizeof(STACKWORD) < 4);
        return 0;
    }
/*  kept for reference
    __asm {
        push    ecx
        push    esi
        pushf
                        //Copy stak frame
        std
        mov     esi, buffer
        mov     ecx, paramSize
        add     esi, ecx
        sub     esi, 4
        shr     ecx, 2
loop1:
        lodsd   //DWORD PTR ds:edi
        push    eax
        loop    loop1
                        //Call proc
        mov     eax, pProc
        cld
        call    eax
                        //Read return value
        mov     retVal, eax

                        //Restore stack and registers
        add     esp, paramSize
        popf
        pop     esi
        pop     ecx
    }
    return retVal;*/
}

//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_HC_Proc
//
// Description: Bridge to a number of procedures supplied by HC driver
//
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:  Return code USB_ERROR - Failure, USB_SUCCESS - Success)
//
// Notes:
//      Assumes that buffer has a correct image of the stack that
//      corresponding function reads argument from
//      Size of the buffer can be biger than actually used.
//
//      Following code copies the buffer (some stack frame) into new
//      stack frame such that invoked dirver proc can read parametes
//      supplied by buffer
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>

VOID USBAPI_HC_Proc(URP_STRUC *fpURP)
{
    VOID* buffer = fpURP->ApiData.HcProc.paramBuffer;
    UINT32 paramSize = // align size on DWORD
        (fpURP->ApiData.HcProc.paramSize + 3) & ~0x3;
    UN_HCD_HEADER* pHdr;

    ASSERT( GET_HCD_INDEX(fpURP->ApiData.HcProc.bHCType) <
        sizeof(gUsbData->aHCDriverTable)/sizeof(HCD_HEADER));
    ASSERT( fpURP->bSubFunc < sizeof(pHdr->asArray.proc)/sizeof(VOID*));

    pHdr = (UN_HCD_HEADER*)(gUsbData->aHCDriverTable +
                GET_HCD_INDEX(fpURP->ApiData.HcProc.bHCType));
    fpURP->ApiData.HcProc.retVal = USBAPI_invoke_in_frame(
        pHdr->asArray.proc[fpURP->bSubFunc],buffer,paramSize);
    fpURP->bRetValue = USB_SUCCESS;
}


//<AMI_PHDR_START>
//-----------------------------------------------------------------------------
// Procedure:   USBAPI_Core_Proc
//
// Description: Bridge to a number of procedures supplied by Core proc table
//
// Input:       fpURP   Pointer to the URP structure
//
// Output:  Return code USB_ERROR - Failure, USB_SUCCESS - Success
//
// Notes:
//      Assumes that buffer has a correct image of the stack that
//      corresponding function reads argument from
//      Size of the buffer can be biger than actually used.
//
//      Following code copies the buffer (some stack frame) into new
//      stack frame such that invoked proc can read parametes
//      supplied by buffer
//------------------------------------------------------------------------------;
//<AMI_PHDR_END>


VOID* core_proc_table[] = {
        USB_GetDescriptor,
        USB_ReConfigDevice,
        USB_ReConfigDevice2,
        UsbAllocDevInfo,
        prepareForLegacyOS,
        USB_ResetAndReconfigDev,
        USB_DevDriverDisconnect,
//        USB_GetDataPtr,
//        MemCopy,
    };

VOID USBAPI_Core_Proc(URP_STRUC *fpURP)
{
    VOID* buffer = fpURP->ApiData.CoreProc.paramBuffer;
    UINT32 paramSize = // align size on DWORD
        (fpURP->ApiData.CoreProc.paramSize + 3) & ~0x3;

    ASSERT( fpURP->bSubFunc < COUNTOF(core_proc_table));

    fpURP->ApiData.CoreProc.retVal = USBAPI_invoke_in_frame(
        core_proc_table[fpURP->bSubFunc],buffer,paramSize);

    fpURP->bRetValue = USB_SUCCESS;
}


//----------------------------------------------------------------------------
//          USB API Procedures Ends
//----------------------------------------------------------------------------


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBWrapGetATAError
//
// Description: This routine converts the sense data information into
//      ATAPI error code
//
// Input:   dSenseData  Sense data obtained from the device
//
// Output:  BYTE - ATAPI error code
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8 USBWrapGetATAErrorCode (UINT32 dSenseData)
{
    UINT8   sc = (UINT8)dSenseData;             // Sense code
    UINT8   asc = (UINT8)(dSenseData >> 16);    // Additional Sense Code (ASC)
    UINT8   ascq = (UINT8)(dSenseData >> 8);    // Additional Sense Code Qualifier (ASCQ)

    if (ascq == 0x28) return USB_ATA_DRIVE_NOT_READY_ERR;
    if (sc == 7) return USB_ATA_WRITE_PROTECT_ERR;
    if ((asc == 0x80) && (ascq == 0x80)) return USB_ATA_TIME_OUT_ERR;
    if (ascq == 0x18) return USB_ATA_DATA_CORRECTED_ERR;
    if ((ascq==6) && (asc == 0)) return USB_ATA_MARK_NOT_FOUND_ERR;
    if ((ascq==0x3a) && (asc == 0)) return USB_ATA_NO_MEDIA_ERR;
    if ((ascq==0x11) && (asc == 0)) return USB_ATA_READ_ERR;
    if ((ascq==0x11) && (asc == 6)) return USB_ATA_UNCORRECTABLE_ERR;
    if (ascq==0x30) return USB_ATA_BAD_SECTOR_ERR;
    if ((ascq<0x20) || (ascq>0x26)) return USB_ATA_GENERAL_FAILURE;

    return USB_ATA_PARAMETER_FAILED;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBWrap_GetnthDeviceInfoStructure
//
// Description: This routine finds the 'n'th device's DeviceInfo entry.
//
// Input:   bDevNumber  Device number (1-based)
//
// Output:  DeviceInfo structure
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USBWrap_GetnthDeviceInfoStructure(UINT8 bDevNumber)
{
    return &gUsbData->aDevInfoTable[bDevNumber];
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBWrap_GetDeviceCount
//
// Description: This routine searches through the device entry table
//      and returns number of active USB devices configured
//      by the BIOS.
//
// Input:   fpURPPointer    Pointer to the URP
//
// Output:  Following fields in the URP are modified
//      CkPresence.bNumBootDev      Number of USB boot devices found
//      CkPresence.bNumKeyboards    Number of USB keyboards present
//      CkPresence.bNumMice         Number of USB mice present
//      CkPresence.bNumHubs         Number of USB hubs present
//      CkPresence.bNumStorage      Number of USB storage devices present
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBWrap_GetDeviceCount(URP_STRUC *fpURP)
{
    DEV_INFO    *fpDevInfo;
    UINT8       i;

    for (i=1; i<MAX_DEVICES; i++) {
        fpDevInfo   = &gUsbData->aDevInfoTable[i];

        if ( (fpDevInfo->Flag & DEV_INFO_VALID_STRUC) &&
            (fpDevInfo->Flag & DEV_INFO_DEV_PRESENT)) {
            fpURP->ApiData.CkPresence.bNumBootDev++;

            switch (fpDevInfo->bDeviceType) {
				case BIOS_DEV_TYPE_HID:
                    if (fpDevInfo->HidDevType & HID_DEV_TYPE_KEYBOARD) {
                        fpURP->ApiData.CkPresence.bNumKeyboards++;
                    }
                    if (fpDevInfo->HidDevType & HID_DEV_TYPE_MOUSE) {
                        fpURP->ApiData.CkPresence.bNumMice++;
                    }
                    if (fpDevInfo->HidDevType & HID_DEV_TYPE_POINT) {
                        fpURP->ApiData.CkPresence.bNumPoint++;
                    }
					break;
										//<(EIP84455+)
                case  BIOS_DEV_TYPE_HUB:
                            fpURP->ApiData.CkPresence.bNumHubs++;
                            break;
                case  BIOS_DEV_TYPE_STORAGE:
                            fpURP->ApiData.CkPresence.bNumStorage++;
                            break;
                case  BIOS_DEV_TYPE_SECURITY:
                            break;
            }
        }
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   MemFill
//
// Description: This routine fills the given memory range with the given value.
//
// Input:
//    fpPtr    - Pointer to the memory region to fill.
//    wSize    - Size in bytes of the area to be filled.
//    Value    - Byte value to fill the given range with.
//
// Output: None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
MemFill (
    UINT8*  fpPtr,
    UINT32  dSize,
    UINT8   Value)
{
    UINT32      dCount;

    if (fpPtr) {    // Check for pointer validity
        for(dCount = 0; dCount < dSize; dCount++) {
            fpPtr[dCount] = Value;
        }
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   MemCopy
//
// Description: This routine copies data from source to destination.
//
// Input:
//    fpSrc    - Pointer to the source.
//    fpDest   - Pointer to the destination.
//    wSize    - Number of bytes to copy.
//
// Output: None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
MemCopy (
    UINT8*  fpSrc,
    UINT8*  fpDest,
    UINT32  dSize)
{
    UINT32  dCount;

    //
    // Check for pointer validity
    //
    if ((fpSrc) && (fpDest)) {
        for(dCount = 0; dCount < dSize; dCount++) {
            fpDest[dCount] = fpSrc[dCount];
        }
    }
}


UINTN DevicePathSize (
  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath
  )
{
    EFI_DEVICE_PATH_PROTOCOL     *Start;

    if (DevicePath == NULL) {
        return 0;
    }

    //
    // Search for the end of the device path structure
    //
    Start = DevicePath;
    while (!EfiIsDevicePathEnd (DevicePath)) {
        DevicePath = EfiNextDevicePathNode (DevicePath);
    }

    //
    // Compute the size and add back in the size of the end device path structure
    //
    return ((UINTN)DevicePath - (UINTN)Start) + sizeof(EFI_DEVICE_PATH_PROTOCOL);
}


EFI_DEVICE_PATH_PROTOCOL *
AppendDevicePath (
    IN EFI_DEVICE_PATH_PROTOCOL  *Src1,
    IN EFI_DEVICE_PATH_PROTOCOL  *Src2
    )
{
    EFI_STATUS                  Status;
    UINTN                       Size;
    UINTN                       Size1;
    UINTN                       Size2;
    EFI_DEVICE_PATH_PROTOCOL    *NewDevicePath;
    EFI_DEVICE_PATH_PROTOCOL    *SecondDevicePath;

    //
    // Allocate space for the combined device path. It only has one end node of
    // length EFI_DEVICE_PATH_PROTOCOL
    //
    Size1 = DevicePathSize (Src1);
    Size2 = DevicePathSize (Src2);
    Size = Size1 + Size2;

    if (Size1 != 0 && Size2 != 0) {
        Size -= sizeof(EFI_DEVICE_PATH_PROTOCOL);
    }

    Status = gBS->AllocatePool (EfiBootServicesData, Size, (VOID **)&NewDevicePath);

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

    gBS->CopyMem (NewDevicePath, Src1, Size1);

    //
    // Over write Src1 EndNode and do the copy
    //
    if (Size1 != 0) {
        SecondDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)((CHAR8 *)NewDevicePath + (Size1 - sizeof(EFI_DEVICE_PATH_PROTOCOL)));
    }
    else {
        SecondDevicePath = NewDevicePath;
    }
    gBS->CopyMem (SecondDevicePath, Src2, Size2);
    return NewDevicePath;
}

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