summaryrefslogtreecommitdiff
path: root/Core/EM/PS2CTL/ps2kbd.c
blob: c74ba481295ae6997dd5c4f617680a9bae8c3f66 (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
//**********************************************************************
//**********************************************************************
//**                                                                  **
//**        (C)Copyright 1985-2009, American Megatrends, Inc.         **
//**                                                                  **
//**                       All Rights Reserved.                       **
//**                                                                  **
//**         5555 Oakbrook Pkwy, Suite 200, Norcross, GA 30093        **
//**                                                                  **
//**                       Phone: (770)-246-8600                      **
//**                                                                  **
//**********************************************************************
//**********************************************************************

//**********************************************************************
// $Header: /Alaska/SOURCE/Core/CORE_DXE/PS2CTL/ps2kbd.c 63    11/01/12 6:42a Deepthins $
//
// $Revision: 63 $
//
// $Date: 11/01/12 6:42a $
//**********************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Core/CORE_DXE/PS2CTL/ps2kbd.c $
// 
// 63    11/01/12 6:42a Deepthins
// [TAG]  		EIP101100 
// [Category]  	Improvement
// [Description]  	Multi Language is supported in Ps2ctl driver
// [Files]  		CORE_DXE.sdl, kbc.h, ps2kbd.c and Tokens.c
// 
// 62    10/18/12 9:51a Deepthins
// [TAG]  		EIP95111
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	PS2 mouse is not working in setup.
// [RootCause]  	In stream mode data reporting is disabled by default. The
// mouse will not actually issue any movement data packets until it
// receives the "Enable Data Reporting" (0xF4) command. So even when the
// DETECT_PS2_KEYBOARD and DETECT_PS2_MOUSE token is disabled we need to
// send command 0xf4 to Enable Data Reporting.
// 
// [Solution]  	In MouseReset function, Set sampleRate ,Resolution and
// Enable streaming.
// [Files]  		mouse.c and ps2kbd.c
// 
// 61    10/18/12 9:03a Deepthins
// [TAG]  		EIP70313
// [Category]  	Improvement
// [Description]  	Used CheckIssueLEDCmd in function LEDsOnOff instead of
// OutToKb(Kbd, 0xED)
// [Files]  		kbc.c, ps2kbd.c and kbc.h
// 
// 60    7/13/12 7:21a Rajeshms
// [TAG]  		EIP57005 
// [Category]  	Improvement
// [Description]  	Need to clear Struck Keys in StartKeyboard() &
// KbdReset() for some kinds of Notebook KBC. Implemented this feature
// based on CLEAR_PENDING_KEYS_IN_PS2 token.
// [Files]  		Ps2Kbd.c, CORE_DXE.sdl
// 
// 59    7/09/12 3:13a Rajeshms
// [TAG]  		EIP94186
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	side effect after adding the solution of can not catch F8
// key event on Keyboard - PS2 KB generic implement (EIP6986)
// [RootCause]  	BDA is Checked even when CSM is not launched. So even
// though keys are not pressed Junk Keys are reproted
// [Solution]  	Checked whether CSm is launched based of Presence of
// Legacy BIOS Protocol.
// [Files]  		Ps2Kbd.c
// 
// 58    5/31/12 7:56a Srilathasc
// [TAG]  		EIP89947
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Ps2Keyboard doesn't work after reconnect -r command from
// Shell
// [RootCause]  	The keyboard driver's stop function does not uninstall
// AMIEFIKEYCODE Protocol.
// [Solution]  	AMIEFIKEYCODE Protocol uninstalled in stop function. 
// [Files]  		ps2kbd.c
// 
// 57    5/24/12 6:49a Nimishsv
// [TAG]  		EIP90180
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Ps2driver doesn't return the proper ShiftState if the valid
// Unicode char's are pressed.
// [RootCause]  	Shift State was not cleared for printable characters
// [Solution]  	Shift state is cleared for printable characters
// [Files]  		ps2kbd.c
// 
// 56    5/02/12 2:29a Deepthins
// [TAG]  		EIP63116
// [Category]  	Improvement
// [Description]  	PS/2 Keyboard/Mouse IRQ mode generic support
// [Files]  		Ps2kbd.c, Mouse.c, kbc.h, kbc.c
// 
// 55    4/30/12 2:22a Rajeshms
// [TAG]  		EIP86986 
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	Can not detect F8 key on PS2 Keyboard while booting to EFI
// aware OS.
// [RootCause]  	Make code of F8 key (0x42) is taken by int09h and  EFI
// aware OS calls only one ReadKeyStroke() for any key catch, Now PS2
// driver will take Break Code of F8 key(0xC2) and returns EFI_NOT_READY.
// [Solution]  	Multiple Read from PS2 keyboard is implemented and read
// exits if any valid key is detected. Also, the BDA keyboard buffer is
// checked for any missed key in EFI.
// [Files]  		ps2kbd.c, kbc.c, CORE_DXE.sdl
// 
// 54    4/24/12 2:19a Deepthins
// [TAG]  		EIP85747 
// [Category]  	Improvement
// [Description]  	USB-ReadKeyStrokeEx is returning EFI_SUCCESS with
// KEY_STATE_EXPOSED for Caps, Num and Scroll Lock Key's.
// KEY_STATE_EXPOSED only for the ShiftState Key's and not for togglestate
// key's.
// [Files]  		Efiusbkb.c, ps2kbd.c and kbc.h
// 
// 53    4/23/12 8:52a Jittenkumarp
// [TAG]  		EIP84902 
// [Category]  	Bug Fix
// [Symptom]  	Enter key is not working in PS2 key board
// [RootCause]  	Filling wrong EFI KEY value in
// ScancodeToEfi_table.Therefor Enter key is interpreted wrongly as
// EfiKeyC12.
// [Solution]  	Replaced EfiKeyC12 value with EfiKeyEnter value to
// Interpreted Enter key properly.
// 
// [Files]  		ps2kbd.c
// 
// 52    4/10/12 2:35a Rameshr
// [TAG]  		EIP87058
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Not able to recognise Pause Key Click using ReadKeyStroke
// [RootCause]  	Pause Key detection should be done always and only the
// pause key action should be controlled by PAUSEKEY_SUPPORT SDL token
// [Solution]  	SDL token checking removed for the Pause Key detection
// [Files]  		Ps2kbd.c
// 
// 51    2/01/12 2:01a Deepthins
// [TAG]  		EIP63116
// [Category]  	New Feature
// [Description]  	PS/2 Keyboard/Mouse IRQ mode generic support
// [Files]  		Token.c, Ps2main.c, Ps2kbd.c, Mouse.c, kbc.h, kbc.c,
// CORE_DXE.sdl
// 
// 50    9/22/11 7:39a Rameshr
// [TAG]  		EIP63054
// [Category]  	New Feature
// [Description]  	0000790: Add warning to ReadKeyStrokeEx for partial key
// press
// [Files]  		KeyboardCommonDefinitions.h, In.c, Kbc.h, Ps2Kbd.c,
// Efiusbkb.c, efiusbkb.h
// 
// 49    6/21/11 12:24p Davidd
// [TAG]           EIP55334
// [Category]      New Feature
// [Description]   Add optional code to clear keyboard buffer at
// ReadyToBoot in PS2KB driver
// [Files]         core_dxe.sdl
//                 ps2kbd.c
// 
// 48    4/27/11 4:34a Lavanyap
// [TAG] - EIP49407
// [Category] - IMPROVEMENT
// [Description] - Move the Ps2 driver SDL tokens from Core Source to Core
// Bin,So that we don't need to add Core source for changing the Ps2
// driver SDL tokens.
// [Files] - Ps2Ctl.sdl, ps2kbd.c, ps2main.c, ps2ctl.h, kbc.c, mouse.c,
// hotkey.c, CORE_DXE.sdl, Tokens.c
// 
// 47    1/05/11 12:58a Rameshr
// [TAG]  		EIPEIP 35306
// [Category]  	Improvement
// [Description]  	Report the Ps2 Controller and Device Error Codes.
// [Files]  		AmiStatuscodes.h, Kbc.c, Kbc.h,Ps2ctl.sdl, ps2kbd.c,
// ps2main.c ,Statuscode.h
// 
// 46    8/23/10 4:21a Rameshr
// Bug Fix : EIP 40838
// Symptoms: KBC.C build failed in DetectPS2Keyboard() if
// DETECT_PS2_KEYBOARD=0 & PS2MOUSE_SUPPORT=0
// Files Modified: Efismplpp.c, Kbc.c, Kbc.h, Mouse.c PS2ctl.cif,
// Ps2ctl.sdl, Ps2Kbd.c, Ps2Mouse.c
// Details: 
// 1) Added Detect_PS2_Mouse sdl token and modified the code.
// 2) INSTALL_KEYBOARD_MOUSE_ALWAYS sdl token added.
//    1 - Install the Keyboard- SimpleTextIn, Mouse - AbsPointer Always, 
//    0 - Install the Keyboard- SimpleTextIn, Mouse - AbsPointer only if
// the device is present at the time of detection.
//    This is for Ps2Keyboard Hot plug support in EFI 
// 3) Code clean up in mouse.c EfiSmplpp.c ,ps2mouse.h
// 4) Unused file automaton.h removed.
// 
// 45    8/19/10 8:08a Fredericko
// [TAG]    	  EIP40711 
// [Category]  BUG FIX
// [Severity]	  Normal
// [Symptom]  Keyboard sometimes does not work in DOS if KBD is being
// pressed hapazardly during post.
// [RootCause] After reprogramming of Interrupt Controller base; if
// keyboard is being pressed hapardzadly, KBD IRQ could be missed and KBD
// might not work in DOS.
// [Solution]	Follow proper procedures to Reset KBD controller after
// reprogramming the base of the Interrrupt controller
// [Files] Thunk.c in CSM
// 
// 44    7/20/10 4:31a Rameshr
// Corrected the FreePool call in UnRegisterKeyNotify function
// 
// 43    5/14/10 11:07a Olegi
// Added FreePool call in UnRegisterKeyNotify function.
//
// 42    5/10/10 1:50a Rameshr
// Issue:Shift Key issues in RegsiterkeyNotify function
// Solution: ShiftKeyState and KeyToggleState verified for
// RegisterKeyNotify callback function.
// EIP 38211
//
// 41    5/10/10 1:41a Rameshr
// PrintKey/SysRq key, Menu Key, Left Logo and Right Logo Key support
// added in Ps2 Keyboard driver
// EIP 38212
//
// 40    3/15/10 2:40p Krishnakumarg
// Pressing DEL key continously intermittently or sticking does not enter
// setup. EIP: 34615
//
// 39    1/29/10 2:11p Krishnakumarg
// When user press "Ctrl+Break" key, the Scr Lk LED will turn on - #EIP
// 34317
//
// 38    8/13/09 3:02p Rameshr
// When item "num-lock status" set off, Num-lock will keep open until in
// DOS.
// EIP:21757
//
// 37    7/01/09 12:32p Olegi
// Source is corrected according to the coding standard: function headers,
// copyright messages are updated.
//
// 36    6/26/09 4:03p Rameshr
// Symptom: Shift Key Status get set when DELL key pressed more
// frequently.
// Reason: DELL key scan code E0 taken by Reset Function and Int9. This
// has been handled by modifiying Reset function and using BDA.
// EIP:22611
//
// 35    3/30/09 10:28a Pats
// Issue: EIP 19547 - Pause key support needed in Aptio
// Solution: Function HandleKBDData modified to pass EFI_KEY vaule of
// pause key on rather than rejecting it.
//
// 34    1/23/09 9:54a Rameshr
// Symptom:SCT failure in ReadKeystrokeEx function.
// Solution: Validated the Input parameters Keydata for the
// ReadKeystrokeEx Function.
// Eip: 19039
//
// 33    11/17/08 10:04a Rameshraju
// Problem:SCT failure on RegisterKeyNotify, SetState and
// UnregisterKeyNotify.
// Fix : Validated the input parameters for RegisterKeyNotify, SetState
// and UnregisterKeyNotify.
// EIP:17578
//
// 32    10/08/08 4:56p Olegi
// Implemented the Register/Unregister key notofocation function in
// SimpletextinEx protocol.
//
// 31    8/15/08 10:57a Olegi
// Correction in KbdReset function.
//
// 30    8/13/08 9:54a Olegi
// Change in KbdReset function, EIP#8330.
//
// 29    6/05/08 4:26p Olegi
// Added support for extended keys (EIP#13630)
//
// 28    6/05/08 3:19p Olegi
// Bugfix in processing the '5' key on a keypad when NumLock is off:
// nothing should be reported.
//
// 27    5/09/08 10:11a Olegi
// ProcessByte function modified
//
// 26    4/22/08 4:31p Felixp
// Additional progress codes added
//
// 25    4/21/08 5:49p Olegi
//
// 24    4/09/08 10:19a Olegi
// Changed the key attributes (modifiers and shift state) reporting.
//
// 23    10/25/07 4:48p Olegi
//
// 22    10/24/07 6:00p Olegi
//
// 21    10/23/07 4:04p Olegi
// Lock keys maintenance modifications.
//
// 20    9/18/07 11:51a Olegi
//
// 19    9/18/07 11:47a Olegi
//
// 18    9/17/07 3:56p Olegi
//
// 17    9/10/07 1:14p Olegi
//
// 16    9/07/07 4:34p Olegi
// EFI_KEY code implementation.
//
// 15    8/31/07 2:44p Olegi
// Added SimpleTextInEx definitions.
//
// 14    6/22/07 2:14p Pats
// Fixed problem of right Ctrl and Alt keys "sticking" and causing reset
// when Ctrl-Alt-Del pressed sequentially rather than all at once.
//
// 13    4/19/07 1:00p Felixp
// File reformatted to comply with AMI coding standards
//
// 11    4/17/07 10:34a Pats
// Modified to comply with coding standard. No code changes.
//
// 10    5/05/06 5:23p Ambikas
//
// 9     3/13/06 2:38a Felixp
//
// 8     1/09/06 11:38a Felixp
//
// 6     12/22/05 10:21a Srinin
// Optimized KBD Enable/Disable call
//
// 5     10/27/05 1:04p Srinin
// In KbdReset, KBD driver buffer is cleared.
//
// 4     10/11/05 4:09p Srinin
// KBD reset function implemented and other minor changes done.
//
// 3     8/30/05 1:08p Srinin
// KeyBoard buffer and handling of keys which send 4 scan codes modified.
//
// 2     3/04/05 3:55p Olegi
// Shift states corrected for non-letter keys.
//
// 1     2/01/05 1:10a Felixp
//
// 3     1/18/05 3:22p Felixp
// PrintDebugMessage renamed to Trace
//
// 2     12/16/04 2:28p Olegi
// Fix: Caps-Lock made irrelevant to the upper row of keys.
//
// 1     10/28/04 10:19a Olegi
//
// 10    9/30/04 8:13a Olegi
// HotKeys added.
//
//**********************************************************************

//<AMI_FHDR_START>
//----------------------------------------------------------------------
//
// Name: ps2kbd.c
//
// Description: PS/2 keyboard support routines
//
//----------------------------------------------------------------------
//<AMI_FHDR_END>

//----------------------------------------------------------------------

#include "ps2ctl.h"
#include "kbc.h"


#define     E0_STATUS_IN_BDA        BIT1
#define     E1_STATUS_IN_BDA        BIT0
#define     LEGACY_8259_CONTROL_REGISTER_MASTER 0x20

#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
#include <Protocol/LegacyBios.h>
UINT16      BdaSeg      = 0x400;
UINT16      *BdaKbdHead = (UINT16 *)0x41A;
UINT16      *BdaKbdTail = (UINT16 *)0x41C;
EFI_LEGACY_BIOS_PROTOCOL    *gLegacy=NULL;
BOOLEAN     gLegacyBiosProtocolFound = FALSE;
#endif
#endif

/*
Table 2. PS/2 Scan Codes Supported in Windows 2000/Windows XP and Windows Me

HID usage/ key name  Set 1Make  Set 1Break  Set 2Make  Set 2Break
 Scan Next Track       E0 19       E0 99       E0 4D     E0 F0 4D
 Scan Previous Track   E0 10       E0 90       E0 15     E0 F0 15
 Stop                  E0 24       E0 A4       E0 3B     E0 F0 3B
 Play/ Pause           E0 22       E0 A2       E0 34     E0 F0 34
 Mute                  E0 20       E0 A0       E0 23     E0 F0 23
 Volume Increment      E0 30       E0 B0       E0 32     E0 F0 32
 Volume Decrement      E0 2E       E0 AE       E0 21     E0 F0 21
 AL Email Reader       E0 6C       E0 EC       E0 48     E0 F0 48
 AC Search             E0 65       E0 E5       E0 10     E0 F0 10
 AC Home               E0 32       E0 B2       E0 3A     E0 F0 3A
 AC Back               E0 6A       E0 EA       E0 38     E0 F0 38
 AC Forward            E0 69       E0 E9       E0 30     E0 F0 30
 AC Stop               E0 68       E0 E8       E0 28     E0 F0 28
 AC Refresh            E0 67       E0 E7       E0 20     E0 F0 20
 AC Bookmarks          E0 66       E0 E6       E0 18     E0 F0 18
 AL Calculator*        E0 21       E0 A1       E0 2B     E0 F0 2B
 AL Local Browser*     E0 6B       E0 EB       E0 40     E0 F0 40
 AL Consumer Control Configuration*
                       E0 6D       E0 ED       E0 50     E0 F0 50
*/
static  UINT8 E0EnhancedKeys[] = {0x20,0x30,0x2E};  // only mute, volume-up, down
BOOLEAN IsEnhancedKey( UINT8 data)
{
    UINTN   i;

    data &= 0x7F;   // reset MSB
    for ( i = 0; i < sizeof(E0EnhancedKeys); i++) {
        if ( data == E0EnhancedKeys[i]) {
            return  TRUE;
        }
    }
    return  FALSE;
}

//----------------------------------------------------------------------

extern  BOOLEAN InsideGetMouseData;
extern  BOOLEAN KBDEnableState;
extern  UINT8   LedsAtStartup;
extern  BOOLEAN InsideMouseReset;
BOOLEAN InsideKbdReadKey = FALSE;
BOOLEAN InsideOnWaitingOnKey = FALSE;
BOOLEAN InsideKbdReset = FALSE;
extern BOOLEAN InsidePS2DataDispatcher;
static EFI_GUID gAmiMultiLangSupportGuid = AMI_MULTI_LANG_SUPPORT_PROTOCOL_GUID;
AMI_MULTI_LANG_SUPPORT_PROTOCOL *gPs2MultiLangSupportProtocol=NULL;

EFI_STATUS KbdReset(
    EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This,
    BOOLEAN ExtendedVerification);

EFI_STATUS KbdReadKey(
    EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This,
    EFI_INPUT_KEY *key);

EFI_STATUS KbdResetEx(
    EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL  *This,
    BOOLEAN ExtendedVerification );

EFI_STATUS KbdReadKeyEx (
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    OUT EFI_KEY_DATA *KeyData
);

EFI_STATUS KbdReadEfiKeyEx (
    IN AMI_EFIKEYCODE_PROTOCOL *This,
    OUT AMI_EFI_KEY_DATA *KeyData
);

EFI_STATUS SetState (
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    IN EFI_KEY_TOGGLE_STATE *KeyToggleState
);

EFI_STATUS RegisterKeyNotify(
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    IN EFI_KEY_DATA *KeyData,
    IN EFI_KEY_NOTIFY_FUNCTION KeyNotificationFunction,
    OUT EFI_HANDLE *NotifyHandle
);

EFI_STATUS UnRegisterKeyNotify(
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    IN EFI_HANDLE NotificationHandle
);

void OnWaitingOnKey(EFI_EVENT Event, void *Context);

#if CLEAR_PENDING_KEYS_IN_PS2
VOID Ps2KbdReset ( VOID );
VOID ClearOBF ( VOID );
#endif


typedef struct _KEY_WAITING_RECORD{
  DLINK                                         Link;
  EFI_KEY_DATA                                  Context;
  EFI_KEY_NOTIFY_FUNCTION                       Callback;
} KEY_WAITING_RECORD;

DLIST                               mPs2KeyboardData;
KEY_WAITING_RECORD                  *mPs2KeyboardRecord;
EFI_EVENT                           Ps2KeyEvent;
#define     KEY_POLLING_INTERVAL    500000
VOID StartPollingKey(EFI_EVENT Event, VOID *Context);


extern STATEMACHINEPROC DrivePS2KbdMachine;
void ReadAndProcessKey(void*);
void ProcessByte(KEYBOARD *Kbd, UINT8 data, BOOLEAN fourth_byte);
void ResetStateMachine(KEYBOARD *Kbd);
void LEDsOnOff(KEYBOARD* Kbd);

static UINT8 E0SeqA[4]  = {0x2A, 0xAA, 0x46, 0xB6};
static UINT8 E0SeqB[11] = {0xD3, 0xD0, 0xCF, 0xC7, 0xD2, 0xCB, 0xD1, 0xC9, 0xCD, 0xC8, 0xB5};
static UINT8 E1Seq[5]   = {0x1D, 0x45, 0xE1, 0x9D, 0xC5};

static UINT8 code_table[59] = { // Lower case keys
0, 0, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 8,
9, 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', 13,
0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'','`',
0,'\\','z','x','c','v','b','n','m',',','.','/',0,
'*', 0, ' ', 0};
static UINT8 Code_Table[59] = { // Upper case keys
0, 0, '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', 8,
9, 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', 13,
0, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', '~',
0, '|', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', 0,
'*', 0, ' ',0};

static UINT8 ScancodeToEfi_table[59] = { // EFI keys (UEFI Spec 2.1, Ch.28.4, Pg.1325)
0, EfiKeyEsc, EfiKeyE1, EfiKeyE2, EfiKeyE3,EfiKeyE4, EfiKeyE5, EfiKeyE6,
EfiKeyE7, EfiKeyE8, EfiKeyE9, EfiKeyE10, EfiKeyE11, EfiKeyE12, EfiKeyBackSpace,
EfiKeyTab, EfiKeyD1, EfiKeyD2, EfiKeyD3, EfiKeyD4, EfiKeyD5, EfiKeyD6, EfiKeyD7,
EfiKeyD8, EfiKeyD9, EfiKeyD10, EfiKeyD11, EfiKeyD12, EfiKeyEnter,
EfiKeyCapsLock, EfiKeyC1, EfiKeyC2, EfiKeyC3, EfiKeyC4, EfiKeyC5, EfiKeyC6, EfiKeyC7,
EfiKeyC8, EfiKeyC9, EfiKeyC10, EfiKeyC11, EfiKeyE0,
EfiKeyLShift, EfiKeyD13, EfiKeyB1, EfiKeyB2, EfiKeyB3, EfiKeyB4, EfiKeyB5, EfiKeyB6,
EfiKeyB7, EfiKeyB8, EfiKeyB9, EfiKeyB10, EfiKeyRshift,
0, 0, EfiKeySpaceBar, 0};

typedef struct {
    UINT8 makecode;
    UINT8 efi_scancode;
    UINT8 efi_key;
}EFI_EXTKEY;

static EFI_EXTKEY ScanCode_Table[] = {
    0x3B, EFI_SCAN_F1, EfiKeyF1,
    0x3C, EFI_SCAN_F2, EfiKeyF2,
    0x3D, EFI_SCAN_F3, EfiKeyF3,
    0x3E, EFI_SCAN_F4, EfiKeyF4,
    0x3F, EFI_SCAN_F5, EfiKeyF5,
    0x40, EFI_SCAN_F6, EfiKeyF6,
    0x41, EFI_SCAN_F7, EfiKeyF7,
    0x42, EFI_SCAN_F8, EfiKeyF8,
    0x43, EFI_SCAN_F9, EfiKeyF9,
    0x44, EFI_SCAN_F10, EfiKeyF10,
    0x57, EFI_SCAN_F11, EfiKeyF11,
    0x58, EFI_SCAN_F12, EfiKeyF12,
    0x47, EFI_SCAN_HOME, EfiKeyHome,
    0x48, EFI_SCAN_UP, EfiKeyUpArrow,
    0x49, EFI_SCAN_PGUP, EfiKeyPgUp,
    0x4B, EFI_SCAN_LEFT, EfiKeyLeftArrow,
    0x4D, EFI_SCAN_RIGHT, EfiKeyRightArrow,
    0x4F, EFI_SCAN_END, EfiKeyEnd,
    0x50, EFI_SCAN_DN, EfiKeyDownArrow,
    0x51, EFI_SCAN_PGDN, EfiKeyPgDn,
    0x52, EFI_SCAN_INS, EfiKeyIns,
    0x53, EFI_SCAN_DEL, EfiKeyDel,
    0xFF, 0xFF, 0xFF  // End of table
};

static UINT8 KeyPad_Table[] = {
    '7','8','9','-','4','5','6','+','1','2','3','0','.'
};

static UINT8 KeyPadEfiCode_Table[] = {
    EfiKeySeven, EfiKeyEight, EfiKeyNine, EfiKeyMinus,
    EfiKeyFour, EfiKeyFive, EfiKeySix, EfiKeyPlus,
    EfiKeyOne, EfiKeyTwo, EfiKeyThree,
    EfiKeyZero, EfiKeyPeriod
};

KEYBOARD                    gKbd;
KEYBOARD_IRQ_STORE          gKeyboardIrqBuffer;
EFI_CPU_ARCH_PROTOCOL       *gCpuArch;
EFI_LEGACY_8259_PROTOCOL    *mLegacy8259;
BOOLEAN                     gKeyboardIrqInstall=FALSE;
BOOLEAN                     gKeyboardDriverStart=FALSE;

extern	BOOLEAN             Ps2MouseDetected;
extern  BOOLEAN             KbdIrqSupport;
extern  BOOLEAN             KbRdBeforeInstall; 
extern  BOOLEAN             InsideGetMouseData;
extern  BOOLEAN             KBDEnableState;

#if CLEAR_PS2KB_BUFFER_AT_READYTOBOOT
EFI_EVENT	gClearKbBufferEvent;

// <AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name: ClearKbBuffer
//
// Description:
//  This function clear PS2 KB buffer
//
// Input:   
//  IN EFI_EVENT	Event - signalled event
//  IN VOID 		*Context - pointer to event context
//
// Output:
//      VOID
// 
// Modified:
//
// Referrals:
//
// Notes:
//
//-------------------------------------------------------------------------- 
// <AMI_PHDR_END>

EFI_STATUS
ClearKbBuffer(
    IN EFI_EVENT	Event, 
    IN VOID 		*Context
)
{
    KEYBOARD	*Kbd = &gKbd;
	UINT8		*BdaKbHead = (UINT8*)((UINTN) 0x41a);
	UINT8		*BdaKbTail = (UINT8*)((UINTN) 0x41c);
	UINT8		*BdaKbBuffer = (UINT8*)((UINTN) 0x41e);

    Kbd->pBufHead = Kbd->pBufStart;
    Kbd->pBufTail = Kbd->pBufStart;

    pBS->SetMem(Kbd->pBufStart, BUFFER_SIZE * sizeof (AMI_EFI_KEY_DATA), 0);

	// Empty KB Buffer in BDA
    pBS->SetMem(BdaKbBuffer, 32, 0);
	*BdaKbTail = *BdaKbHead;

	pBS->CloseEvent(Event);

    return EFI_SUCCESS;
}
#endif


// <AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Name: UpdateVariabletoCheckBda
//
// Description:
//  This function updates variable Legacy BIOS Protocol found,to check BDA
//  for pending keys in EFI.
//
// Input:   
//  IN EFI_EVENT Event - signalled event
//  IN VOID *Context - pointer to event context
//
// Output:
//      VOID
// 
// Modified:
//
// Referrals:
//
// Notes:
//
//-------------------------------------------------------------------------- 
// <AMI_PHDR_END>
#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
VOID UpdateVariabletoCheckBda(
    IN EFI_EVENT Event,
    IN VOID *Context
)
{
    EFI_STATUS Status;
    //
    // Update Variable to check BDA if Legacy Bios Protocol Found.
    //
    Status = pBS->LocateProtocol(&gEfiLegacyBiosProtocolGuid, NULL, &gLegacy);        
    if (!EFI_ERROR(Status)) {
        gLegacyBiosProtocolFound = TRUE;
    }
}
#endif
#endif

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       StartKeyboard
//
// Description:     This routine is called from Driver Binding Start function,
//                  it starts the keyboard
//
// Paremeters:      EFI_DRIVER_BINDING_PROTOCOL *This - A pointer to the
//                      EFI_DRIVER_BINDING_PROTOCOL instance
//                  EFI_HANDLE Controller - Handle for this controller
//
// Output:          EFI_STATUS - status of the operation
//
// Referrals:       gEfiSimpleTextInProtocolGuid
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS StartKeyboard(
    EFI_DRIVER_BINDING_PROTOCOL     *This,
    EFI_HANDLE                      Controller)
{

    EFI_STATUS Status;
    EFI_DEVICE_PATH_PROTOCOL *pDummyDevPath;
    KEYBOARD* Kbd = &gKbd;
    KEYBOARD_IRQ_STORE*         KbIrqBuffer = &gKeyboardIrqBuffer;
    UINT8                       Index=0;
#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
    EFI_EVENT 	Event;
	VOID *pRegistration;
#endif
#endif

    if (EFI_ERROR(gSysTable->BootServices->OpenProtocol(
            Controller,
            &gEfiDevicePathProtocolGuid,
            &pDummyDevPath,
            This->DriverBindingHandle,
            Controller,
            EFI_OPEN_PROTOCOL_BY_DRIVER))) {
        return EFI_INVALID_PARAMETER;
    }

#if CLEAR_PENDING_KEYS_IN_PS2
    //
    // Reset the keyboard and Clear Pending Keys as some
    // NoteBook Kbc needs reset and Clearing the OBF.
    //
    Ps2KbdReset();
    ClearOBF ();
#endif

    DetectPS2KeyboardAndMouse();

    if (EFI_ERROR(DetectPS2Keyboard())) {
        gSysTable->BootServices->CloseProtocol(
            Controller,
            &gEfiDevicePathProtocolGuid,
            This->DriverBindingHandle,
            Controller);

        return EFI_DEVICE_ERROR;
    }

    //
    // Initialize keyboard interface functions
    //
    (Kbd->iSimpleIn).Reset = KbdReset;
    (Kbd->iSimpleIn).ReadKeyStroke = KbdReadKey;

    (Kbd->iSimpleInEx).Reset = KbdResetEx;
    (Kbd->iSimpleInEx).ReadKeyStrokeEx = KbdReadKeyEx;
    (Kbd->iSimpleInEx).SetState = SetState;
    (Kbd->iSimpleInEx).RegisterKeyNotify = RegisterKeyNotify;
    (Kbd->iSimpleInEx).UnregisterKeyNotify = UnRegisterKeyNotify;

    (Kbd->iKeycodeInEx).Reset = KbdResetEx;
    (Kbd->iKeycodeInEx).ReadEfikey = KbdReadEfiKeyEx;
    (Kbd->iKeycodeInEx).SetState = SetState;
    (Kbd->iKeycodeInEx).RegisterKeyNotify = RegisterKeyNotify;
    (Kbd->iKeycodeInEx).UnregisterKeyNotify = UnRegisterKeyNotify;

    gSysTable->BootServices->CreateEvent(
        EVT_NOTIFY_WAIT,
        TPL_NOTIFY,
        OnWaitingOnKey,
        Kbd,
        &Kbd->iSimpleIn.WaitForKey);

    gSysTable->BootServices->CreateEvent(
        EVT_NOTIFY_WAIT,
        TPL_NOTIFY,
        OnWaitingOnKey,
        Kbd,
        &Kbd->iSimpleInEx.WaitForKeyEx);

    gSysTable->BootServices->CreateEvent(
        EVT_NOTIFY_WAIT,
        TPL_NOTIFY,
        OnWaitingOnKey,
        Kbd,
        &Kbd->iKeycodeInEx.WaitForKeyEx);

    //
    // Install protocol interfaces for the keyboard device.
    //
    Status = gSysTable->BootServices->InstallMultipleProtocolInterfaces (
        &Controller,
        &gEfiSimpleTextInProtocolGuid, &Kbd->iSimpleIn,
        &gEfiSimpleTextInExProtocolGuid, &Kbd->iSimpleInEx,
        &gAmiEfiKeycodeProtocolGuid, &Kbd->iKeycodeInEx,
        NULL
    );

    if (EFI_ERROR(Status)) {
        gSysTable->BootServices->CloseProtocol(
            Controller,
            &gEfiDevicePathProtocolGuid,
            This->DriverBindingHandle,
            Controller);

        gSysTable->BootServices->CloseEvent(Kbd->iSimpleIn.WaitForKey);
        gSysTable->BootServices->CloseEvent(Kbd->iSimpleInEx.WaitForKeyEx);
        gSysTable->BootServices->CloseEvent(Kbd->iKeycodeInEx.WaitForKeyEx);
    }

    if (!(EFI_ERROR(Status))) {
        //
        // Initialize keyboard device
        //
        Kbd->KeyIsReady = FALSE;
        Kbd->ScannerState = KBST_READY;
        Kbd->KeyData.KeyState.KeyToggleState = LedsAtStartup;
        Kbd->KeyData.KeyState.KeyToggleState |= TOGGLE_STATE_VALID;
        Kbd->KeyData.KeyState.KeyShiftState = SHIFT_STATE_VALID;

        Kbd->pBufStart = MallocZ(BUFFER_SIZE * sizeof (AMI_EFI_KEY_DATA));
        if(!Kbd->pBufStart) return EFI_OUT_OF_RESOURCES;
        Kbd->pBufHead = Kbd->pBufStart;
        Kbd->pBufTail = Kbd->pBufStart;
        Kbd->pBufEnd = Kbd->pBufStart + BUFFER_SIZE;

        DrivePS2KbdMachine = ReadAndProcessKey;

        //
        // Set LED's
        //
        LEDsOnOff(Kbd);

        InitHotKeys(Controller);                // Produce HotKeys protocol

//      for (Count = 3; Count; Count--) {
//          if(IssueCommand(0xF4) == 0xFA) break;       // Clear the KBD buffer
//      }

        Kbd->LEDCommandState = 0;

#if CLEAR_PS2KB_BUFFER_AT_READYTOBOOT
	    gSysTable->BootServices->CreateEvent(
						            EFI_EVENT_SIGNAL_READY_TO_BOOT,
						            TPL_NOTIFY,
						            ClearKbBuffer,
						            NULL,
						            &gClearKbBufferEvent);
#endif

#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
        RegisterProtocolCallback(
		&gEfiLegacyBiosProtocolGuid, UpdateVariabletoCheckBda,
		NULL, &Event,&pRegistration
	    );
        
        //
        // Check whether Legacy BIOS Protocol Installed.
        //
        UpdateVariabletoCheckBda(NULL,NULL);        

#endif
#endif
    }

    DListInit(&mPs2KeyboardData);

    Status = pBS->CreateEvent(
                    EVT_TIMER | EFI_EVENT_NOTIFY_SIGNAL,
                    TPL_NOTIFY,
                    StartPollingKey,
                    Kbd,
                    &Ps2KeyEvent
    );

    //
    // if before keyboard driver starts data is available in buffer
    // it will be collected in local buffer in KeyboardInterrupt?Handler
    // only if KBD_READ_BEFORE_INSTALL = 1, the avalable data in local 
    // buffer is processed.
    //
    if(KbRdBeforeInstall){
        for (Index=0;Index < KbIrqBuffer->KbdIndex; Index++){
            ProcessKBDData(Kbd, KbIrqBuffer->KbdBuffer[Index]);
        }
    }
    gKeyboardDriverStart = TRUE;
    //
    // Re enable keyboard irq as it was previously disabled.
    // if KBD_READ_BEFORE_INSTALL = 0 then initialize keyboard irq here
    //
    if(KbdIrqSupport){
        if(KbRdBeforeInstall){   
            gKeyboardIrqInstall = TRUE;
            //
            // Now enable the interrupt
            //
            mLegacy8259->EnableIrq(mLegacy8259, SYSTEM_KEYBOARD_IRQ, FALSE);
        }
        else {
            InitKeyboardIrq();
        }
    }
    //
    // Enable the Keyboard and Keyboard Interrupt. We must initilize this  
    // one for the Keyboard to work on Legacy mode. And also Legacy mode AMIUSB driver 
    // expects Keyboard and Interrupt should be enabled once Port 60/64 is present.
    //
    Write8042CommandByte(0x65);
    return Status;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       StopKeyboard
//
// Description:     This routine is called from Driver Binding Stop function.
//
// Paremeters:      EFI_DRIVER_BINDING_PROTOCOL *This - A pointer to the
//                      EFI_DRIVER_BINDING_PROTOCOL instance
//                  EFI_HANDLE Controller - Handle for this controller
//
// Output:          EFI_STATUS - status of the operation
//
// Referrals:       gEfiSimpleTextInProtocolGuid
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS StopKeyboard(
    EFI_DRIVER_BINDING_PROTOCOL     *This,
    EFI_HANDLE                      Controller)
{
    KEYBOARD* Kbd = &gKbd;
    EFI_STATUS Status;

    //
    // Uninstall protocol interfaces from the keyboard device.
    //
    Status = gSysTable->BootServices->UninstallMultipleProtocolInterfaces (
        Controller,
        &gEfiSimpleTextInProtocolGuid, &Kbd->iSimpleIn,
        &gEfiSimpleTextInExProtocolGuid, &Kbd->iSimpleInEx,
        &gAmiEfiKeycodeProtocolGuid, &Kbd->iKeycodeInEx,
        NULL
    );

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

    //
    // Close protocols that is open during Start
    //
    Status = gSysTable->BootServices->CloseProtocol(
        Controller,
        &gEfiDevicePathProtocolGuid,
        This->DriverBindingHandle,
        Controller);

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

    //
    // Kill wait event
    //
    gSysTable->BootServices->CloseEvent(Kbd->iSimpleIn.WaitForKey);
    gSysTable->BootServices->CloseEvent(Kbd->iSimpleInEx.WaitForKeyEx);
    gSysTable->BootServices->CloseEvent(Kbd->iKeycodeInEx.WaitForKeyEx);
    gSysTable->BootServices->CloseEvent(Ps2KeyEvent);

    pBS->FreePool(Kbd->pBufStart);


    return Status;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       KbdReset
//
// Description:     Resets the input device hardware. This routine is a part
//                  of SimpleTextIn protocol implementation.
//
// Parameters:      EFI_SIMPLE_TEXT_INPUT_PROTOCOL
//                  *This - A pointer to the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
//                  instance.
//                  BOOLEAN
//                  ExtendedVerification - Indicates that the driver may
//                  perform a more exhaustive verification operation of the
//                  device during reset.
//
// Output:          EFI_SUCCESS The device was reset.
//                  EFI_DEVICE_ERROR The device is not functioning correctly
//                  and could not be reset.
//
// Modified:        KBDEnableState
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS KbdReset(
    EFI_SIMPLE_TEXT_INPUT_PROTOCOL  *This,
    BOOLEAN                         ExtendedVerification )
{
    UINT8   bCount, bData, bBCount;
    KEYBOARD* Kbd = &gKbd;
    EFI_STATUS Status;

    //
    // Check for keyboard IRQ support
    //
    if(KbdIrqSupport && gKeyboardIrqInstall) {
        //
        // Now Disable the interrupt
        //
        mLegacy8259->DisableIrq(mLegacy8259, SYSTEM_KEYBOARD_IRQ);
    }
    InsideKbdReset = TRUE;
    Kbd->KeyIsReady = FALSE;
    Kbd->ScannerState = KBST_READY;

    Kbd->pBufHead = Kbd->pBufStart;
    Kbd->pBufTail = Kbd->pBufStart;

    pBS->SetMem(Kbd->pBufStart, BUFFER_SIZE * sizeof (AMI_EFI_KEY_DATA), 0);

    DisableKeyboard();
    PROGRESS_CODE(DXE_KEYBOARD_RESET);
  
    for (bBCount = 0; bBCount < 4; bBCount++) {
        for (bCount = 0; bCount < 3; bCount++) {
            Status = ReadDevice(KBD_DISABLE_SCANNING, &bData, KB_ACK_COM);
            if (!EFI_ERROR(Status)) {
                break;
            }
        }
        if (EFI_ERROR(Status)) {
            continue;
        }
        for (bCount = 0; bCount < 3; bCount++) {
            Status = ReadDevice(KBD_ENABLE_SCANNING, &bData, KB_ACK_COM);
            if (!EFI_ERROR(Status)) {
                break;
            }
        }
        if (!EFI_ERROR(Status)) {
            break;
        }
    }
    //
    // Report the Buffer FULL error code if there is failure.
    //
    if (EFI_ERROR(Status)) {
        ERROR_CODE (DXE_KEYBOARD_BUFFER_FULL_ERROR, EFI_ERROR_MAJOR);
    }
    
    KBDEnableState = FALSE;
    Status = EnableKeyboard();
    
    if (EFI_ERROR(Status)) {
        //
        // Report the KBC Controller error code.
        //
        ERROR_CODE (DXE_KEYBOARD_CONTROLLER_ERROR, EFI_ERROR_MAJOR);
    }

#if CLEAR_PENDING_KEYS_IN_PS2
    //
    // Clear OBF as some Notebook KBC has some keys even after
    // disabling and enabling scanning.
    //
    ClearOBF ();
#endif
                                           
    if(!gKeyboardIrqInstall){
        LEDsOnOff(Kbd);
    }

    Kbd->LEDCommandState = 0;
    InsideKbdReset = FALSE;

    if(KbdIrqSupport && gKeyboardIrqInstall) {
        

        //
        // Now enable the interrupt
        //
        mLegacy8259->EnableIrq(mLegacy8259, SYSTEM_KEYBOARD_IRQ, FALSE);
    }

    return EFI_SUCCESS;

}


EFI_STATUS KbdResetEx(
    EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL  *This,
    BOOLEAN ExtendedVerification )
{
    return KbdReset(0, ExtendedVerification);
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       KbdReadKey
//
// Description:     Reads the next keystroke from the input device. This
//                  routine is a part of SimpleTextIn protocol
//                  implementation.
//
// Paremeters:      EFI_SIMPLE_TEXT_INPUT_PROTOCOL
//                  This - A pointer to the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
//                      instance.
//                  EFI_INPUT_KEY
//                  InputKey -  A pointer to a buffer that is to be filled in
//                      with the keystroke information for the key that was
//                      pressed.
//
// Output:          EFI_SUCCESS - The keystroke information was returned.
//                  EFI_NOT_READY - There was no keystroke data available.
//                  EFI_DEVICE_ERROR - The keystroke information was not
//                      returned due to hardware errors.
//
// Modified:        InsideKbdReadKey
//
// Referral(s):     InsideGetMouseData, InsideGetMouseData,
//                  InsideOnWaitingOnKey
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS KbdReadKey(
    EFI_SIMPLE_TEXT_INPUT_PROTOCOL  *This,
    EFI_INPUT_KEY                   *InputKey )
{
    KEYBOARD* Kbd = &gKbd;

    if (InsideGetMouseData || InsideKbdReadKey || InsideOnWaitingOnKey || InsideKbdReset || InsideMouseReset) {
        return GetKeyFromBuffer (Kbd, (VOID*)InputKey, sizeof(EFI_INPUT_KEY));
    }

    InsideKbdReadKey = TRUE;

    PS2DataDispatcher(This);

    InsideKbdReadKey = FALSE;

#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
    if( gLegacyBiosProtocolFound ) {
        if (!CheckKeyinBuffer(Kbd)) {
            if( *BdaKbdHead != *BdaKbdTail ) {
                ProcessKBDData (Kbd, *((UINT8 *)(*BdaKbdHead + BdaSeg + 1)));            
                *BdaKbdHead += 2;
                if(*BdaKbdHead == 0x3E) {
                    *BdaKbdHead = 0x1E;
                }
            }
        }
    }
#endif
#endif

    return GetKeyFromBuffer (Kbd, (VOID*)InputKey, sizeof(EFI_INPUT_KEY));

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       KbdReadKeyEx
//
// Description:     Reads the next keystroke from the input device. This
//                  routine is a part of SimpleTextInEx protocol
//                  implementation.
//
// Paremeters:      EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL
//                  *This - A pointer to the EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL
//                      instance.
//
// Output:          EFI_INPUT_KEY
//                  *key -  A pointer to a buffer that is filled in with the
//                          keystroke state data for the key that was pressed.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
KbdReadKeyEx (
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    OUT EFI_KEY_DATA *KeyData
)
{
    EFI_STATUS Status;
    KEYBOARD *Kbd = &gKbd;

    if(KeyData == NULL) {
        return EFI_INVALID_PARAMETER;
    }
    if (!InsideGetMouseData && !InsideKbdReadKey && !InsideOnWaitingOnKey && !InsideKbdReset && !InsideMouseReset) {
        InsideKbdReadKey = TRUE;
        PS2DataDispatcher(This);
        InsideKbdReadKey = FALSE;
    }

#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
    if( gLegacyBiosProtocolFound ) {
        if (!CheckKeyinBuffer(Kbd)) {
            if( *BdaKbdHead != *BdaKbdTail ) {
                ProcessKBDData (Kbd, *((UINT8 *)(*BdaKbdHead + BdaSeg + 1)));            
                *BdaKbdHead += 2;
                if(*BdaKbdHead == 0x3E) {
                    *BdaKbdHead = 0x1E;
                }
            }
        }
    }
#endif
#endif

    Status = GetKeyFromBuffer (Kbd, (VOID*)KeyData, sizeof(EFI_KEY_DATA));
    if (EFI_ERROR(Status)) {

        pBS->SetMem(KeyData, sizeof (EFI_KEY_DATA), 0);
        //
        // Check the partial Key. If found return Success with NULL data 
        // in EFI_INPUT_KEY.
        //
        Status=CheckPartialKey(Kbd, (EFI_KEY_DATA*)KeyData);
        return Status;
    }

    return EFI_SUCCESS;
}

EFI_STATUS KbdReadEfiKeyEx (
    IN AMI_EFIKEYCODE_PROTOCOL *This,
    OUT AMI_EFI_KEY_DATA *KeyData
)
{
    EFI_STATUS Status;
    KEYBOARD *Kbd = &gKbd;

    if (!InsideGetMouseData && !InsideKbdReadKey && !InsideOnWaitingOnKey && !InsideKbdReset && !InsideMouseReset) {
        InsideKbdReadKey = TRUE;
        PS2DataDispatcher(This);
        InsideKbdReadKey = FALSE;
    }


#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
    if( gLegacyBiosProtocolFound ) {        
        //
        // If there is no key, check whether any key is present BDA Keyboard buffer as 
        // we may miss any key in legacy mode.
        //
        if (!CheckKeyinBuffer(Kbd)) {
            if( *BdaKbdHead != *BdaKbdTail ) {
                //
                // Get the scan code from BDA keyboard buffer and process it.
                //
                ProcessKBDData (Kbd, *((UINT8 *)(*BdaKbdHead + BdaSeg + 1)));            
                *BdaKbdHead += 2;
                //
                // Check whether we have reached end of circular buffer, if reached initialize
                // header to beginning of the buffer.
                //
                if(*BdaKbdHead == 0x3E) {
                    *BdaKbdHead = 0x1E;
                }
            }
        }
    }
#endif
#endif

    Status = GetKeyFromBuffer (Kbd, (VOID*)KeyData, sizeof(AMI_EFI_KEY_DATA));
    if (EFI_ERROR(Status)) {
        pBS->SetMem(KeyData, sizeof (AMI_EFI_KEY_DATA), 0);
        //
        // Check the partial Key. If found return Success with NULL data 
        // in EFI_INPUT_KEY.
        //
        Status=CheckPartialKey(Kbd, (EFI_KEY_DATA*)KeyData);
        return Status;
    }

    return Status;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       SetState
//
// Description:     Set certain state for the input device.
//
// Paremeters:      This - A pointer to the EFI_SIMPLE_TEXT_INPUT_PROTOCOL_EX
//                          instance.
//                  KeyToggleState - Pointer to the EFI_KEY_TOGGLE_STATE to
//                          set the state for the input device.
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
SetState (
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    IN EFI_KEY_TOGGLE_STATE *KeyToggleState
)
{
    BOOLEAN ChgSL = FALSE;
    BOOLEAN ChgCL = FALSE;
    BOOLEAN ChgNL = FALSE;

    KEYBOARD* Kbd = &gKbd;

    if(KeyToggleState == NULL ) {
        return EFI_INVALID_PARAMETER;
    }

    if (!(*KeyToggleState & TOGGLE_STATE_VALID) ||
        ((*KeyToggleState & (~(TOGGLE_STATE_VALID | KEY_STATE_EXPOSED | 
                            SCROLL_LOCK_ACTIVE | NUM_LOCK_ACTIVE | CAPS_LOCK_ACTIVE)))) ) {
        return EFI_UNSUPPORTED;
    }


    ChgSL = ((*KeyToggleState & SCROLL_LOCK_ACTIVE)!=0) ^ ((Kbd->KeyData.KeyState.KeyToggleState & SCROLL_LOCK_ACTIVE)!=0);
    ChgNL = ((*KeyToggleState & NUM_LOCK_ACTIVE)!=0) ^ ((Kbd->KeyData.KeyState.KeyToggleState & NUM_LOCK_ACTIVE)!=0);
    ChgCL = ((*KeyToggleState & CAPS_LOCK_ACTIVE)!=0) ^ ((Kbd->KeyData.KeyState.KeyToggleState & CAPS_LOCK_ACTIVE)!=0);

    if (ChgSL || ChgCL || ChgNL) {
        Kbd->KeyData.KeyState.KeyToggleState &= ~(SCROLL_LOCK_ACTIVE | NUM_LOCK_ACTIVE | CAPS_LOCK_ACTIVE);

        if (*KeyToggleState & SCROLL_LOCK_ACTIVE) Kbd->KeyData.KeyState.KeyToggleState |= SCROLL_LOCK_ACTIVE;
        if (*KeyToggleState & NUM_LOCK_ACTIVE) Kbd->KeyData.KeyState.KeyToggleState |= NUM_LOCK_ACTIVE;
        if (*KeyToggleState & CAPS_LOCK_ACTIVE) Kbd->KeyData.KeyState.KeyToggleState |= CAPS_LOCK_ACTIVE;

        LEDsOnOff(Kbd);
    }

    return EFI_SUCCESS;
}

//**********************************************************************
//<AMI_PHDR_START>
//
// Procedure:       StartPollingKey
//
// Description:     Get the keys from the keyboard controller
//
// Paremeters:      IN EFI_EVENT  Event      event that has been signaled
//                  IN VOID       *Context
//
// Output:          None
//
//
//<AMI_PHDR_END>
//**********************************************************************
VOID StartPollingKey(EFI_EVENT Event, VOID *Context)
{
    if (!InsideGetMouseData && !InsideKbdReadKey && !InsideOnWaitingOnKey && !InsideKbdReset && !InsideMouseReset) {
        InsideKbdReadKey = TRUE;
        PS2DataDispatcher(Context);
        InsideKbdReadKey = FALSE;
    }
    return;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       CheckKeyNotify
//
// Description:     Call the notification function based on the key pressed
//
// Input:           Key - Key pressed
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
CheckKeyNotify(AMI_EFI_KEY_DATA *Key)
{

    KEY_WAITING_RECORD *Ps2KeyIn = OUTTER(mPs2KeyboardData.pHead, Link, KEY_WAITING_RECORD);
    BOOLEAN     KeyScanCodeMatch=FALSE;
    BOOLEAN     KeyUniCodeMatch=FALSE;
    BOOLEAN     ShiftKeyMatch=FALSE;
    BOOLEAN     CtrlKeyMatch=FALSE;
    BOOLEAN     AltKeyMatch=FALSE;
    BOOLEAN     LogoKeyMatch=FALSE;
    BOOLEAN     MenuKeyMatch=FALSE;
    BOOLEAN     SysRqKeyMatch=FALSE;
    BOOLEAN     KeyShiftCodeMatch=FALSE;
    BOOLEAN     KeyToggleKeyMatch=FALSE;

    // if the list is empty return the status that was passed in
    if (Ps2KeyIn == NULL)
        return EFI_SUCCESS;

    // check for a handle that was already identified
    while ( Ps2KeyIn != NULL)
    {
        KeyScanCodeMatch=FALSE;
        KeyUniCodeMatch=FALSE;
        ShiftKeyMatch=FALSE;
        CtrlKeyMatch=FALSE;
        AltKeyMatch=FALSE;
        LogoKeyMatch=FALSE;
        MenuKeyMatch=FALSE;
        SysRqKeyMatch=FALSE;
        KeyShiftCodeMatch=FALSE;
        KeyToggleKeyMatch=FALSE;

        //
        // Check the Scan Code if the Scan code is not 0
        //
        if (Ps2KeyIn->Context.Key.ScanCode != 0) {
            if( Ps2KeyIn->Context.Key.ScanCode == Key->Key.ScanCode) {
                KeyScanCodeMatch=TRUE;
            }
        } else {
            KeyScanCodeMatch=TRUE;
        }

        //
        // Check the Uncide Code Matching
        //

        if(Ps2KeyIn->Context.Key.UnicodeChar == Key->Key.UnicodeChar) {
            KeyUniCodeMatch=TRUE;
        }

        if(Ps2KeyIn->Context.KeyState.KeyShiftState & SHIFT_STATE_VALID){

            //
            // Check the ShiftKey Matching. Left Shift Key is matched with
            // Left or Right Shift Key. Same for Right Shift Key
            //
            if (Ps2KeyIn->Context.KeyState.KeyShiftState & (RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED)) {
                if(Key->KeyState.KeyShiftState & (RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED)) {
                    ShiftKeyMatch=TRUE;
                }
            } else {
                ShiftKeyMatch=TRUE;
            }

            //
            // Check the Ctrl Matching. Left Ctrl Key is matched with
            // Left or Right Ctrl Key. Same for Right Ctrl Key
            //
            if (Ps2KeyIn->Context.KeyState.KeyShiftState & (RIGHT_CONTROL_PRESSED | LEFT_CONTROL_PRESSED)) {
                if(Key->KeyState.KeyShiftState & (RIGHT_CONTROL_PRESSED | LEFT_CONTROL_PRESSED)) {
                    CtrlKeyMatch=TRUE;
                }
            } else {
                CtrlKeyMatch=TRUE;
            }

            //
            // Check the Alt Matching. Left Alt Key is matched with
            // Left or Right Alt Key. Same for Right Alt Key
            //
            if (Ps2KeyIn->Context.KeyState.KeyShiftState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) {
                if(Key->KeyState.KeyShiftState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) {
                    AltKeyMatch=TRUE;
                }
            } else {
                AltKeyMatch=TRUE;
            }

            //
            // Check the Logo Matching. Left Logo Key is matched with
            // Left or Right Logo Key. Same for Right Logo Key
            //
            if (Ps2KeyIn->Context.KeyState.KeyShiftState & (RIGHT_LOGO_PRESSED | LEFT_LOGO_PRESSED)) {
                if(Key->KeyState.KeyShiftState & (RIGHT_LOGO_PRESSED | LEFT_LOGO_PRESSED)) {
                    LogoKeyMatch=TRUE;
                }
            } else {
                LogoKeyMatch=TRUE;
            }

            //
            // Check the Menu Key Matching
            //
            if (Ps2KeyIn->Context.KeyState.KeyShiftState & MENU_KEY_PRESSED) {
                if(Key->KeyState.KeyShiftState & MENU_KEY_PRESSED) {
                    MenuKeyMatch=TRUE;
                }
            } else {
                MenuKeyMatch=TRUE;
            }

            //
            // Check the SysRq Key Matching
            //
            if (Ps2KeyIn->Context.KeyState.KeyShiftState & SYS_REQ_PRESSED) {
                if(Key->KeyState.KeyShiftState & SYS_REQ_PRESSED) {
                    SysRqKeyMatch=TRUE;
                }
            } else {
                SysRqKeyMatch=TRUE;
            }

            KeyShiftCodeMatch=ShiftKeyMatch & CtrlKeyMatch & AltKeyMatch
                                & LogoKeyMatch & MenuKeyMatch & SysRqKeyMatch;
        }else {
            KeyShiftCodeMatch=TRUE;
        }
        //
        // Check the Key Toggle State
        //
        if(Ps2KeyIn->Context.KeyState.KeyToggleState & TOGGLE_STATE_VALID){
            if(Ps2KeyIn->Context.KeyState.KeyToggleState == Key->KeyState.KeyToggleState) {
                KeyToggleKeyMatch=TRUE;
            }
        } else {
            KeyToggleKeyMatch=TRUE;
        }

        //
        // If everything matched, call the callback function.
        //
        if(KeyScanCodeMatch & KeyUniCodeMatch & KeyShiftCodeMatch & KeyToggleKeyMatch) {
            //Call the notification function
            //
            Ps2KeyIn->Callback(&Ps2KeyIn->Context);
        }
        // go to the next element in the list
        Ps2KeyIn = OUTTER(Ps2KeyIn->Link.pNext, Link, KEY_WAITING_RECORD);
    }

    // if it is a new handle return the status pass in
    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       RegisterKeyNotify
//
// Description:     Register the callback function for the specific Key
//
// Input:           This - A pointer to the EFI_SIMPLE_TEXT_INPUT_PROTOCOL_EX
//                          instance.
//                  KeyData - Key value
//                  KeyNotificationFunction- Pointer to the Notification Function
//                  NotificationHandle - Handle to be unregisterd
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
RegisterKeyNotify(
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    IN EFI_KEY_DATA *KeyData,
    IN EFI_KEY_NOTIFY_FUNCTION KeyNotificationFunction,
    OUT EFI_HANDLE *NotifyHandle
)
{
    EFI_STATUS                  Status;


    if(KeyData == NULL || KeyNotificationFunction == NULL || NotifyHandle == NULL ) {
        return EFI_INVALID_PARAMETER;
    }

    //
    // Create database record and add to database
    //
    Status = pBS->AllocatePool (
                      EfiRuntimeServicesData,
                      sizeof (KEY_WAITING_RECORD),
                      &mPs2KeyboardRecord
                      );

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

    //
    // Gather information about the registration request
    //

    mPs2KeyboardRecord->Context   = *KeyData;
    mPs2KeyboardRecord->Callback  = KeyNotificationFunction;

    DListAdd (&mPs2KeyboardData, &(mPs2KeyboardRecord->Link));

    //
    // Child's handle will be the address linked list link in the record
    //
    *NotifyHandle = (EFI_HANDLE) (&mPs2KeyboardRecord->Link);

    if(mPs2KeyboardData.Size == 1) {
        pBS->SetTimer(Ps2KeyEvent,
                        TimerPeriodic,
                        KEY_POLLING_INTERVAL);
    }

    return EFI_SUCCESS;
}
//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       UnRegisterKeyNotify
//
// Description:     Unregister the callback function
//
// Input:          This - A pointer to the EFI_SIMPLE_TEXT_INPUT_PROTOCOL_EX
//                          instance.
//                  NotificationHandle - Handle to be unregisterd
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
UnRegisterKeyNotify(
    IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This,
    IN EFI_HANDLE NotificationHandle
)
{

    DLINK               *ListPtr;
    KEY_WAITING_RECORD  *Ps2KeyIn;

    if(NotificationHandle == NULL ) {
        return EFI_INVALID_PARAMETER;
    }

    ListPtr = mPs2KeyboardData.pHead;
    while ( ListPtr != NULL)
    {
        Ps2KeyIn = OUTTER(ListPtr, Link, KEY_WAITING_RECORD);
        if ( (&Ps2KeyIn->Link) == NotificationHandle)
        {
            DListDelete(&mPs2KeyboardData, ListPtr);
            pBS->FreePool(Ps2KeyIn);
            break;
        }

        ListPtr = ListPtr->pNext;
    }

    if(ListPtr == NULL) {
        return EFI_INVALID_PARAMETER;
    }

    if(mPs2KeyboardData.Size == 0) {
        pBS->SetTimer(Ps2KeyEvent,
                        TimerCancel,
                        0);
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       OnWaitingOnKey
//
// Description:     Callback for the EFI_SIMPLE_TEXT_INPUT_PROTOCOL.WaitForKey
//                  event;
//                  checks whether the new key is available and if so -
//                  signals the event.
//
// Input:           EFI_EVENT Event - Event to signal
//                  void Context - Event specific context (pointer to Kbd
//                      device)
//
// Output:          None
//
// Modified:        InsideOnWaitingOnKey
//
// Referrals:       InsideGetMouseData, InsideKbdReadKey,
//                  InsideOnWaitingOnKey
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
OnWaitingOnKey (
    EFI_EVENT   Event,
    VOID        *Context )
{

    if (InsideGetMouseData || InsideKbdReadKey || InsideOnWaitingOnKey || InsideKbdReset || InsideMouseReset) {
        if (CheckKeyinBuffer((KEYBOARD*)Context)) gSysTable->BootServices->SignalEvent(Event);
        return;
    }

    InsideOnWaitingOnKey = TRUE;

    PS2DataDispatcher(Context); // Process new keys if available

    InsideOnWaitingOnKey = FALSE;

    if (CheckKeyinBuffer((KEYBOARD*)Context))
    {
        gSysTable->BootServices->SignalEvent(Event);
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       ReadAndProcessKey
//
// Description:     PS2 keyboard keys processor, called from main PS2
//                  dispatcher.
//                  It gets the key from KBC output buffer and calls
//                  HandleKBDData.
//
// Paremeters:      void *Context - keyboard device pointer
//
// Output:          None
//
// Notes:           PS2 output buffer has data, incoming key is processed,
//                  Context->KeyIsReady is updated.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
ReadAndProcessKey (
    VOID    *Context )
{

    KEYBOARD *Kbd = &gKbd;
    UINT8 data;

    data = KBCGetData();
    ProcessKBDData (Kbd, data);
    return;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       ProcessKBDData
//
// Description:     If key is ready, processes any hotkey, and inserts key
//                  in buffer
//
// Parameters:
//      KEYBOARD    *Kbd - Pointer to key buffer
//      UINT8       data - Key data
//
// Output:          None
//
// Notes:           Incoming key is processed, Context->KeyIsReady is updated
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
ProcessKBDData (
    KEYBOARD    *Kbd,
    UINT8       data
)
{
    EFI_KEY_DATA    DummyKey;

    HandleKBDData(Kbd, data);
    if (Kbd->KeyIsReady) {

        ProcessHotKey(Kbd->KeyData.PS2ScanCode,
            (UINT16)Kbd->KeyData.KeyState.KeyShiftState);
        InsertKeyToBuffer(Kbd, &Kbd->KeyData);
        Kbd->KeyIsReady = FALSE;
    } else {
        if (Kbd->KeyData.Key.ScanCode == 0 && Kbd->KeyData.Key.UnicodeChar == 0 && Kbd->ScannerState == KBST_READY ) {
            //
            // If the Key ShiftState has valid key, report as Partial Key
            //
            if ((Kbd->KeyData.KeyState.KeyShiftState & ~SHIFT_STATE_VALID) != 0) {

                pBS->CopyMem(&DummyKey, &Kbd->KeyData, sizeof(EFI_KEY_DATA)); 
                DummyKey.KeyState.KeyToggleState |= KEY_STATE_EXPOSED;
                CheckKeyNotify((AMI_EFI_KEY_DATA*)&DummyKey);
            }
        }
    }
    return;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       HandleKBDData
//
// Description:     Processes the input data. If a callback function is
//                  associated with the key, then it is executed.
//
// Paremeters:
//      KEYBOARD    *Kbd - Pointer to key buffer
//      UINT8       data - Key data
//
// Output:          None
//
//
// Notes:           This routine can be called re-entrantly from LEDsOnOff(OutToKb)
//                  e.g. when Numlock and Del is pressed continously.
//                  Incoming key is processed, Context->KeyIsReady is updated.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
HandleKBDData (
    KEYBOARD    *Kbd,
    UINT8       data )
{
    //
    // PS2 keyboard could send one, two, four or six bytes in a row.
    // Kbd->ScannerState is ST_READY if it is the first byte
    //
    if (Kbd->ScannerState == KBST_READY)
    {
        switch (data) {
            case 0xE0:
                Kbd->ScannerState = KBST_E0;
                break;
            case 0xE1:
                Kbd->ScannerState = KBST_E1;
                break;
            default:
                ProcessByte(Kbd, data, FALSE);
        }
        return;
    }
    else    // Multi-byte sequence is being processed
    {
        if (Kbd->ScannerState == KBST_E1)   // Processing E1 state
        {
            if (data != E1Seq[Kbd->Count]) {    // Wrong byte in a sequence
                ResetStateMachine(Kbd);
                return;
            }
            //
            // E1 sequence data is correct, proceed
            //
            if  (Kbd->Count == 2) { // The ONLY 2-key sequence starting with E1 is Pause
                Kbd->KeyData.EfiKey = EfiKeyPause;
                Kbd->KeyIsReady = TRUE;
                ResetStateMachine(Kbd);
                return;
            }
            if  (Kbd->Count == 4) { // E1 sequence has finished
                ProcessByte(Kbd, data, FALSE);
                ResetStateMachine(Kbd);
                return;
            }
            //
            // E1 sequence is not complete, update the counter and return
            //
            Kbd->Count++;
            return;
        }
        else    // Kbd->ScannerState == ST_E0 - processing E0 state
        {

            //
            // For E0 state the Count values will be:
            //   0 for 1st and 2nd byte
            //   2 for 3rd byte (if available)
            //   1 for 4th byte (if available)
            // No validity checking will be done for 2nd,3rd and 4th bytes
            //

        if (Kbd->ScannerState == KBST_E0) {
            if ( IsEnhancedKey( data)) {
                ResetStateMachine(Kbd);
                return;
            }
            // Processing E0 state, if data is 2A or AA or MSB bit is
            // set (break key) ignore it.
            if  (data == 0x2A || data == 0xAA || data & 0x80 && \
                // except in special case of alt, ctrl, Print key, Left Logo, Right Logo and Menu Key
                 data != 0xb8 && data != 0x9d && data != 0xB7 && \
                 data != 0xDB && data != 0xDC && data != 0xDD) {
                ResetStateMachine(Kbd);
                return;
            }
            else {
                ProcessByte(Kbd, data, TRUE);
                ResetStateMachine(Kbd);
                return;
            }
        }
        ProcessByte(Kbd, data, FALSE);
        ResetStateMachine(Kbd);
        return;

        }
    }
}



void ResetStateMachine(KEYBOARD *Kbd)
{
    Kbd->ScannerState = KBST_READY;
    Kbd->Count = 0;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       IsLetter
//
// Description:     Returns TRUE if the given make code belongs to the
//                  alphabetical symbol, otherwise returns FALSE.
//
// Paremeters:      UINT8 data - The character to test
//
// Output:          BOOLEAN - True if character is letter
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

BOOLEAN
IsLetter (
    UINT8   data )
{
    if ((data >= 0x10 && data <= 0x19) ||   // Q...P
        (data >= 0x1E && data <= 0x26) ||   // A...L
        (data >= 0x2C && data <= 0x32)) {   // Z...M
        return TRUE;
    }
    return FALSE;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       ProcessByte
//
// Description:     Checks for valid key, updates key modifiers, keyboard
//                  queue head and tail as well as Kbd->KeyIsReady field.
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//                  UINT8 data - byte to process
//                  BOOLEAN long_sequence - the indication of whether it is a
//                  4 byte sequence or not; used to differentiate Shift keys
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
ProcessByte (
    KEYBOARD    *Kbd,
    UINT8       Data,
    BOOLEAN     long_sequence )
{
    BOOLEAN bUpperCase, bShifted;
    EFI_EXTKEY *extkey;
    static BOOLEAN Make_Capslock = FALSE, Make_SCRLOCK = FALSE, Make_NUMLOCK = FALSE;
    UINT8   *KeyboardTypeBda = (UINT8*)((UINTN) 0x496);


    Kbd->KeyData.Key.ScanCode = 0;
    Kbd->KeyData.Key.UnicodeChar = 0;
    Kbd->KeyData.PS2ScanCode = Data;

    //
    // Process ESC key
    //
    if (Data == 1) {
        Kbd->KeyData.Key.ScanCode = EFI_SCAN_ESC;
        Kbd->KeyData.EfiKey = EfiKeyEsc;
        Kbd->KeyIsReady = TRUE;
        return;
    }

    //
    // Get the E0, E1 Status from BDA (40:96). If those bit get set means Int9 processed the E0
    // E1 data and before processing other Scan code it came out of Legacy mode.
    // Now EFI driver sees other scan code that's part of the E0 and E1 scan. So we don't want to Process
    // those data.
    //
#if CHECK_BDA_KEYBOARD_BUFFER
#if CSM_SUPPORT
    if( gLegacyBiosProtocolFound ) {
        if(*KeyboardTypeBda & (E0_STATUS_IN_BDA + E1_STATUS_IN_BDA)) {
            *KeyboardTypeBda &=~(E0_STATUS_IN_BDA + E1_STATUS_IN_BDA);
            return;
        }
    }
#endif
#endif

    //
    // Process key modifiers: xyzLock (update LEDs) and Ctrl/Alt/Shift
    //
    switch (Data) {
        case 0x38:
            if (Kbd->ScannerState == KBST_E0) {
                Kbd->KeyData.KeyState.KeyShiftState |= RIGHT_ALT_PRESSED;
            } else {
                Kbd->KeyData.KeyState.KeyShiftState |= LEFT_ALT_PRESSED;
            }
            return; //break;
        case 0xB8:
            if (Kbd->ScannerState == KBST_E0) {
                Kbd->KeyData.KeyState.KeyShiftState &= ~RIGHT_ALT_PRESSED;
            } else {
                Kbd->KeyData.KeyState.KeyShiftState &= ~LEFT_ALT_PRESSED;
            }
            return; //break;

        case 0x1D:
            if (Kbd->ScannerState == KBST_E0) {
                Kbd->KeyData.KeyState.KeyShiftState |= RIGHT_CONTROL_PRESSED;
            } else {
                Kbd->KeyData.KeyState.KeyShiftState |= LEFT_CONTROL_PRESSED;
            }
            return; //break;
        case 0x9D:
            if (Kbd->ScannerState == KBST_E0) {
                Kbd->KeyData.KeyState.KeyShiftState &= ~RIGHT_CONTROL_PRESSED;
            } else {
                Kbd->KeyData.KeyState.KeyShiftState &= ~LEFT_CONTROL_PRESSED;
            }
            return; //break;

        case 0x2A: {
            Kbd->KeyData.KeyState.KeyShiftState |= LEFT_SHIFT_PRESSED; return; //break;
        }
        case 0xAA: // could be a part of a long break code
            if (!long_sequence) {
                Kbd->KeyData.KeyState.KeyShiftState &= ~LEFT_SHIFT_PRESSED;
            }
            return; //break;

        case 0x36: Kbd->KeyData.KeyState.KeyShiftState |= RIGHT_SHIFT_PRESSED; return; //break;
        case 0xB6: Kbd->KeyData.KeyState.KeyShiftState &= ~RIGHT_SHIFT_PRESSED; return; //break;

        case 0x3A:
                if (!Make_Capslock) {
                    Kbd->KeyData.KeyState.KeyToggleState ^= CAPS_LOCK_ACTIVE;
                    Make_Capslock = TRUE;
                }
                Kbd->KeyData.EfiKey = EfiKeyCapsLock;
                Kbd->KeyIsReady = TRUE;
                break;

        case 0xBA: Make_Capslock = FALSE; break;

        case 0x46:
                if (Kbd->ScannerState != KBST_E0){
                        if (!Make_SCRLOCK) {
                            Kbd->KeyData.KeyState.KeyToggleState ^= SCROLL_LOCK_ACTIVE;
                            Make_SCRLOCK = TRUE;
                        }
                        Kbd->KeyData.EfiKey = EfiKeySLck;
                        Kbd->KeyIsReady = TRUE;
                }
                break;

        case 0xC6:
                if (Kbd->ScannerState != KBST_E0){
                    Make_SCRLOCK = FALSE;
                }
                break;
        case 0x45:
                if (!Make_NUMLOCK) {
                    Kbd->KeyData.KeyState.KeyToggleState ^= NUM_LOCK_ACTIVE;
                    Make_NUMLOCK = TRUE;
                }
                Kbd->KeyData.EfiKey = EfiKeyNLck;
                Kbd->KeyIsReady = TRUE;
                break;

        case 0xC5: Make_NUMLOCK = FALSE; break;
        //
        // Handle the PrintScreen/SysRq make Code
        //
        case 0x37:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState |= SYS_REQ_PRESSED;
                    return;
                }
                break;

        //
        // Handle the PrintScreen/SysRq breakcode
        //
        case 0xB7:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState &= ~ SYS_REQ_PRESSED;
                    return;
                }
                break;

        //
        // Handle the Left Logo make Code
        //
        case 0x5B:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState |= LEFT_LOGO_PRESSED;
                    return;
                }
                break;

        //
        // Handle the Left Logo breakcode
        //
        case 0xDB:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState &= ~ LEFT_LOGO_PRESSED;
                    return;
                }
                break;

        //
        // Handle the Right Logo make Code
        //
        case 0x5C:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState |= RIGHT_LOGO_PRESSED;
                    return;
                }
                break;

        //
        // Handle the Right Logo breakcode
        //
        case 0xDC:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState &= ~ RIGHT_LOGO_PRESSED;
                    return;
                }
                break;

        //
        // Handle the Menu Key make Code
        //
        case 0x5D:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState |= MENU_KEY_PRESSED;
                    return;
                }
                break;

        //
        // Handle the Meny Key breakcode
        //
        case 0xDD:
                if (Kbd->ScannerState == KBST_E0) {
                    Kbd->KeyData.KeyState.KeyShiftState &= ~ MENU_KEY_PRESSED;
                    return;
                }
                break;

        case 0xFA: ProcessKBDResponse(Kbd, Data); break;
        case 0xFE: ProcessKBDResponse(Kbd, Data); break;
        case 0xFF: ProcessKBDResponse(Kbd, Data); break;
    }

    //
    // Process main block of keys
    //
    if (Data < 0x3A && !(Kbd->ScannerState == KBST_E0 && Data == 0x37)) {// Exceptional case is Printscreen/sys req

        bShifted = Kbd->KeyData.KeyState.KeyShiftState & (RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED);

        if (Kbd->ScannerState == KBST_E0) bShifted = 0;  // Check for '/' in Keypad. Otherwise '?' will be sent


        if (IsLetter(Data)) {   // for not-a-letter Caps-Lock must not work
            bUpperCase = (Kbd->KeyData.KeyState.KeyToggleState & CAPS_LOCK_ACTIVE)? !bShifted: bShifted;
        }
        else {
            bUpperCase = bShifted;
        }
        if (bUpperCase) {
            Kbd->KeyData.Key.UnicodeChar = Code_Table[Data];    // UPPER CASE TABLE
        }
        else {
            Kbd->KeyData.Key.UnicodeChar = code_table[Data];    // lower case table
        }
        Kbd->KeyData.EfiKey = ScancodeToEfi_table[Data];
        if (Kbd->KeyData.Key.UnicodeChar != 0) {
            Kbd->KeyIsReady = TRUE;
        }
        return;
    }

// UK Keyboard "|\" (EfiKeyB0)
// data = 0x56(ScanCode Set1), EfiKeyB0, "|\"
    if ( Data == 0x56) {
        bShifted = Kbd->KeyData.KeyState.KeyShiftState & (RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED);
        if ( Kbd->ScannerState == KBST_E0) bShifted = 0;  // Check for '/' in Keypad. Otherwise '?' will be sent
        bUpperCase = bShifted;      // for not-a-letter Caps-Lock must not work
        if (bUpperCase) {
            Kbd->KeyData.Key.UnicodeChar = '|';     // UPPER CASE TABLE
        }
        else {
            Kbd->KeyData.Key.UnicodeChar = '\\';    // lower case
        }
        Kbd->KeyData.EfiKey = EfiKeyB0;
        Kbd->KeyIsReady = TRUE;
        return;
    }

    //
    // Process keypad keys.  Exceptional cases:  -, + on keypad
    // Keypad numbers when NUMLOCK only is ON OR Shift only is pressed.
    if (Kbd->ScannerState != KBST_E0) {
        if ((Data > 0x46) && (Data < 0x54) && !long_sequence) {
            if (((Kbd->KeyData.KeyState.KeyToggleState & NUM_LOCK_ACTIVE)   // Only NUMLOCK in ON
                    && ((Kbd->KeyData.KeyState.KeyShiftState & (RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED)) == 0))
                || (((Kbd->KeyData.KeyState.KeyToggleState & NUM_LOCK_ACTIVE) == 0)   // Only shift key is pressed
                    && (Kbd->KeyData.KeyState.KeyShiftState & (RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED)))
                || Data == 0x4a || Data ==0x4e) // check for -,  + keys in keypad
            {
                Kbd->KeyData.Key.UnicodeChar = KeyPad_Table[Data-0x47];
                Kbd->KeyData.EfiKey = KeyPadEfiCode_Table[Data-0x47];
                Kbd->KeyIsReady = TRUE;
                return;
            }
        }
    }
    //
    // Process F-keys
    //
    for (extkey = ScanCode_Table; extkey->makecode != 0xFF; extkey++) {
        if (Data == extkey->makecode) {
            Kbd->KeyData.Key.ScanCode = extkey->efi_scancode;
            Kbd->KeyData.EfiKey = extkey->efi_key;
            Kbd->KeyIsReady = TRUE;
            return;
        }
    }
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       LEDsOnOff
//
// Description:     Turns keyboard LEDs on and off.
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

void LEDsOnOff (
    KEYBOARD*   Kbd )
{

    UINT8 bIndicators = Kbd->KeyData.KeyState.KeyToggleState & 7;    // SCRL/NUM/CPSL
    
    if (InsidePS2DataDispatcher) return;
    InsidePS2DataDispatcher = TRUE;

    //
    // Check for keyboard IRQ support
    //
    if(KbdIrqSupport){
        if(gKeyboardIrqInstall && KBDEnableState){
            if (bIndicators != Kbd->Indicators){
                //
                // Turn on/off the lights
                //
                Kbd->CommandResponded = NULL;
                //
                // Issue Keyboard LED Command 0xED
                //
                CheckIssueLEDCmd(Kbd);
                if(Kbd->LEDCommandState == ED_COMMAND_ISSUED) {
                    //
                    // LED command "ED" has been issues. Process the Data here itself.
                    //
                    UINT32	Counter; 
                    for (Counter = 1000; Counter > 0; Counter--) {
                        //
                        // The Interrupt handler will handle the response
                        // and set the Kbd->LEDCommandState to zero in both
                        // case with or without error. Exit once the response is
                        // handled.
                        //
                        if(Kbd->LEDCommandState == 0) {
                            break;
                        }
		                gSysTable->BootServices->Stall(1000);
                
                    }
                }
            }
            Kbd->LEDCommandState = NULL;
            InsidePS2DataDispatcher = FALSE;
            return;
        }
    }                                                

     
    if (bIndicators != Kbd->Indicators) {
        //
        // Issue Keyboard LED Command 0xED
        //
        CheckIssueLEDCmd(Kbd);

        //
        //Process the led command and data
        //
        ProcessLEDCommandData(Kbd);
    }

    InsidePS2DataDispatcher = FALSE;
    return;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       GetKeyFromBuffer
//
// Description:     Gets the next key from the circular buffer
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//                  EFI_INPUT_KEY *key - Pointer to input key data
//
// Output:          EFI_SUCCESS - key.ScanCode and key.UnicodeChar updated
//                  EFI_NOT_READY - no key in buffer
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
GetKeyFromBuffer (
    KEYBOARD    *Kbd,
    VOID        *Key,
    UINT8       KeySize
)
{
    AMI_EFI_KEY_DATA    TempKey;

    if (Kbd->pBufHead == Kbd->pBufTail) return EFI_NOT_READY;

    pBS->CopyMem(&TempKey, Kbd->pBufHead, sizeof(AMI_EFI_KEY_DATA));

    
    TempKey.EfiKeyIsValid = 1;
    TempKey.PS2ScanCodeIsValid = 1;

    ProcessMultiLanguage(&TempKey);
    
    if (TempKey.Key.UnicodeChar != 0) {
        TempKey.KeyState.KeyShiftState &= ~(RIGHT_SHIFT_PRESSED | LEFT_SHIFT_PRESSED);
    }

    pBS->CopyMem(Key, &TempKey, KeySize);

    Kbd->pBufHead++;
    if (Kbd->pBufHead >= Kbd->pBufEnd) Kbd->pBufHead = Kbd->pBufStart;  // Point to the beginning

    return EFI_SUCCESS;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       InsertKeyToBuffer
//
// Description:     Insert the key into the circular buffer
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//                  AMI_EFI_INPUT_KEY key - input key data
//
// Output:          EFI_SUCCESS - Key placed in buffer
//                  EFI_WARN_BUFFER_TOO_SMALL - Buffer to small
//
// Notes:           If buffer is full, the EFI_WARN_BUFFER_TOO_SMALL.
//                  Tail points to the new Data.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
InsertKeyToBuffer (
    KEYBOARD            *Kbd,
    AMI_EFI_KEY_DATA    *Key
)
{
    AMI_EFI_KEY_DATA    *Temp = Kbd->pBufTail;

    CheckKeyNotify(Key);
    if (Kbd->pBufTail != Kbd->pBufHead) {   // Check if space available
        Temp++;
        if (Temp >= Kbd->pBufEnd) Temp = Kbd->pBufStart;
        if (Kbd->pBufHead == Temp) return EFI_WARN_BUFFER_TOO_SMALL; // No more space
    }

    *Kbd->pBufTail = *Key;
    Kbd->pBufTail++;

    if (Kbd->pBufTail >= Kbd->pBufEnd) Kbd->pBufTail = Kbd->pBufStart;

    return EFI_SUCCESS;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       CheckKeyinBuffer
//
// Description:     Checks if any key is present in the buffer
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//
// Output:          BOOLEAN - TRUE if a key is in the buffer, FALSE otherwise.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

BOOLEAN
CheckKeyinBuffer (
    KEYBOARD* Kbd
)
{
    if (Kbd->pBufHead == Kbd->pBufTail) return FALSE;
    return TRUE;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       CheckPartialKey
//
// Description:     Gets the next key from the circular buffer
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//                  EFI_INPUT_KEY *key - Pointer to input key data
//
// Output:          EFI_SUCCESS - Partial Key Found
//                  EFI_NOT_READY - no key in buffer
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
CheckPartialKey (
    KEYBOARD        *Kbd,
    EFI_KEY_DATA    *Key
)
{

    if (Kbd->KeyData.Key.ScanCode == 0 && Kbd->KeyData.Key.UnicodeChar == 0) {
        //
        // If the Key ShiftState has valid key, report as Partial Key
        //
        if ((Kbd->KeyData.KeyState.KeyShiftState & ~SHIFT_STATE_VALID) != 0) {

            pBS->CopyMem(Key, &Kbd->KeyData, sizeof(EFI_KEY_DATA)); 
            Key->KeyState.KeyToggleState |= KEY_STATE_EXPOSED;
            CheckKeyNotify((AMI_EFI_KEY_DATA*)Key);
            return EFI_SUCCESS;
        }
    }

     return EFI_NOT_READY;    
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure: KeyboardInterruptHandler
//
// Description: An interrupt handler for keyboard IRQ.
//
//
// Input:     InterruptType  Interrupt type
//            SystemContext  System context
//
// Output:    EFI_SUCCESS
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID KeyboardInterruptHandler(
    IN EFI_EXCEPTION_TYPE   InterruptType,
    IN EFI_SYSTEM_CONTEXT   SystemContext
)
{
    KEYBOARD_IRQ_STORE* KbIrqBuffer = &gKeyboardIrqBuffer;
    KEYBOARD *Kbd = &gKbd;
    UINT8 bIndicators = Kbd->KeyData.KeyState.KeyToggleState & 7;    // SCRL/NUM/CPSL
    UINT8 Data = IoRead8(KBC_DATA_PORT);
 
    gCpuArch->DisableInterrupt(gCpuArch);

    //
    // Stored received acknowledgement
    //
    switch (Data) {
        case 0xFA:
             Kbd->CommandResponded = KB_ACK_COM;
             if (Kbd->LEDCommandState == ED_COMMAND_ISSUED) {
                Kbd->LEDCommandState = ED_DATA_ISSUED;
                Kbd->Indicators = bIndicators;
                WriteKeyboardData(bIndicators);
                break;
             }

             if (Kbd->LEDCommandState == ED_DATA_ISSUED) {
                Kbd->LEDCommandState = 0;
                break;
             }

             break;
        case 0xFE:
             Kbd->CommandResponded = KB_RSND_COM;
             if (Kbd->LEDCommandState == ED_COMMAND_ISSUED || Kbd->LEDCommandState == ED_DATA_ISSUED) {
//              Error occured. Clear out the current indicator bits.
//              Modifiers will have the correct bits that needs to be set.
//              Next Call to CheckIssueLEDCmd will detect the mismatch
//              and start the LED sequence.
                WriteKeyboardData(0xF4);
                Kbd->LEDCommandState = 0;
                Kbd->KeyData.KeyState.KeyToggleState &=
                    ~(SCROLL_LOCK_ACTIVE | NUM_LOCK_ACTIVE | CAPS_LOCK_ACTIVE);
                    Kbd->Indicators &= 0xf0;     
             }
             break;
        case 0xFF:
             Kbd->CommandResponded = KB_RSND_COM;
             Kbd->LEDCommandState = 0;
             break;
        default:
            //
            // If key has been pressed before keyboard start then data will be saved in local buffer
            // else data will be processed
            //
            if(!gKeyboardDriverStart){
                if (KbIrqBuffer->KbdIndex < BUFFER_SIZE){
                    KbIrqBuffer->KbdBuffer[KbIrqBuffer->KbdIndex]=Data;
                    KbIrqBuffer->KbdIndex++;
                }
			}
             else {
                ProcessKBDData (Kbd, Data);
            }
            break;
    }

    //
    // End of interrupt command sent
    //
    mLegacy8259->EndOfInterrupt(mLegacy8259, SYSTEM_KEYBOARD_IRQ);
    gCpuArch->EnableInterrupt(gCpuArch);
}

//**********************************************************************
//<AMI_PHDR_START>
//
// Procedure:       InitKeyboardIrq
//
// Description:     To initialize keyboard interrupt, register keyboard
//                  handler, and enable the keyboard interrupt
// 
// Input:           
//
// Paremeters:      
//
// Output:          None
//
//
//<AMI_PHDR_END>
//**********************************************************************
VOID InitKeyboardIrq(VOID)
{

    EFI_STATUS          Status;
    KEYBOARD_IRQ_STORE* KbIrqBuffer                 = &gKeyboardIrqBuffer;
    EFI_GUID            gEfiLegacy8259ProtocolGuid  = EFI_LEGACY_8259_PROTOCOL_GUID;
    EFI_GUID            gEfiCpuArchProtocolGuid     = EFI_CPU_ARCH_PROTOCOL_GUID;
    UINT32              KeyboardVector              = NULL;
   
    if (!gKeyboardIrqInstall){
        Status = pBS->LocateProtocol(&gEfiLegacy8259ProtocolGuid, NULL, &mLegacy8259);
        if (EFI_ERROR(Status)) {
			return;
		}

        // Find the CPU Arch Protocol
        Status = pBS->LocateProtocol(&gEfiCpuArchProtocolGuid, NULL, &gCpuArch);
        if (EFI_ERROR(Status)) {
			return;
		}

        //
        // Get keyboard Interrupt vector
        //
        Status = mLegacy8259->GetVector(mLegacy8259, SYSTEM_KEYBOARD_IRQ, (UINT8 *) & KeyboardVector);
        if (EFI_ERROR(Status)) {
			return;
		}

        //
        // Register interrupt handler for keyboard
        //
        Status = gCpuArch->RegisterInterruptHandler(gCpuArch, KeyboardVector, KeyboardInterruptHandler);
        if (EFI_ERROR(Status)) {
			return;
		}

        KbIrqBuffer->KbdIndex=0;
        gKeyboardIrqInstall = TRUE;

        //
        // Now enable the interrupt
        //
        mLegacy8259->EnableIrq(mLegacy8259, SYSTEM_KEYBOARD_IRQ, FALSE);
    }
    return;
}

#if CLEAR_PENDING_KEYS_IN_PS2
// <AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name: ClearOBF
//
// Description:
//  Clears any pending keys in Ps2 Output Buffer. 
//
// Input:
//  VOID
//
// Output:  
//  VOID
//  
// Modified:
//
// Referrals:
//
// Notes: This OBF clear is done since some PS2 KBC has pending keys even
//        after resetting the Keyboard.
//--------------------------------------------------------------------------- 
// <AMI_PHDR_END>
VOID
ClearOBF( 
VOID 
)
{
    UINT8 bData;
    UINT8 Counter=200;

    pBS->Stall(10*1000);

    while( IoRead8(KBC_CMDSTS_PORT) & KBC_OBF )
    {
        bData = IoRead8(KBC_DATA_PORT);
        //
        // wait 10 ms for KBC OBF output.
        //
        pBS->Stall(10*1000);
        Counter--;
        //
        // If still keys are present after 2 sec. exit from the loop.
        //
        if(Counter==NULL) {
            break;
        }
    }
    return; 
}

// <AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Name: Ps2KbdReset
//
// Description:
//  Reset the Ps2 Keyboard by sending disabling and Enabling scanning. 
//
// Input:
//  VOID
//
// Output:  
//  VOID
//  
// Modified:
//
// Referrals:
//
// Notes:
//
//--------------------------------------------------------------------------- 
// <AMI_PHDR_END>
VOID
Ps2KbdReset(
VOID
)
{
    EFI_STATUS Status;
    UINT8   bCount, bData, bBCount;

    //
    // Disable and enable keyboard to reset.
    //
    DisableKeyboard();

    for (bBCount = 0; bBCount < 4; bBCount++) {
        for (bCount = 0; bCount < 3; bCount++) {
            Status = ReadDevice(KBD_DISABLE_SCANNING, &bData, KB_ACK_COM);
            if (!EFI_ERROR(Status)) {
                break;
            }    
        }

        if (EFI_ERROR(Status)) {
            continue; 
        }

        for (bCount = 0; bCount < 3; bCount++) {
            Status = ReadDevice(KBD_ENABLE_SCANNING, &bData, KB_ACK_COM);
            if (!EFI_ERROR(Status)) { 
                break;
            }
        }

        if (!EFI_ERROR(Status)) {
            break;
        }
    }

    EnableKeyboard();
    return;
}

#endif

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       ProcessLEDCommandData
//
// Description:     Process the LED command and data.
//
// Input:           KEYBOARD *Kbd - A pointer to the KEYBOARD device.
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
ProcessLEDCommandData(
    KEYBOARD*   Kbd )
{

    UINT32	Counter;
    UINT8   data;

    if(Kbd->LEDCommandState == ED_COMMAND_ISSUED) {
        //
        // LED command "ED" has been issued. Disable the keyboard and 
	    // Process the Data here itself.
        //
 
        DisableKeyboard();

        for (Counter = 1000; Counter > 0; Counter--) {
            for(data = IoRead8(KBC_CMDSTS_PORT); data & KBC_OBF; data = IoRead8(KBC_CMDSTS_PORT)) {
                if (!(data & KBC_AUX_OBF)) {
                    //
                    // Handle the Command or Data Status
                    //
                        DrivePS2KbdMachine(NULL);
                }
            }
 
            //
            // If the command and data is processed with or without error, exit here.
            //
            if(Kbd->LEDCommandState == 0) {
                return;
            }
		    gSysTable->BootServices->Stall(1000);			
        }
        EnableKeyboard();
    }
    return;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:       ProcessMultiLanguage
//
// Description:     It maps the current key to a Unicode character from
//                  the keyboard layout
//
// Paremeters:      KeyData - Pointer to the AMI_EFI_KEY_DATA .
//
// Output:          None
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS ProcessMultiLanguage(
    IN OUT  AMI_EFI_KEY_DATA                *KeyData)
{
    EFI_STATUS Status;

    if(gPs2MultiLangSupportProtocol == NULL) {
        Status= pBS->LocateProtocol (
                  &gAmiMultiLangSupportGuid,
                  NULL,
                  &gPs2MultiLangSupportProtocol
                  );
        if(EFI_ERROR(Status)) {
            return EFI_NOT_FOUND;
        }
    }    
    Status = gPs2MultiLangSupportProtocol->KeyboardLayoutMap(gPs2MultiLangSupportProtocol,KeyData);

    return Status;
}

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