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

//****************************************************************************
// $Header: /Alaska/SOURCE/Modules/CSM/Generic/Core/CsmHwInfo.c 117   8/26/15 9:49a Olegi $
//
// $Revision: 117 $
//
// $Date: 8/26/15 9:49a $
//
//**********************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Modules/CSM/Generic/Core/CsmHwInfo.c $
// 
// 117   8/26/15 9:49a Olegi
// [TAG]  		EIP235407
// [Description]  	Aptio4 CSM: add error handling for out-of-memory PMM
// initialization
// 
// 116   8/06/15 2:13a Rameshr
// [TAG]  		EIP230079
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Boot option will appear an unknown device "C0::PATA SM:"
// after added the NVMe module and attached the NVMe device
// [RootCause]  	CSM should handle the device that belongs to IDE
// interface. But It handles the all the diskinfo protocol avilable
// [Solution]  	Modified the code to handle only the Ide Interface
// Diskinfo Protocol
// [Files]  		Csmhwinfo.c
// 
// 115   5/25/15 6:01a Rameshr
// [TAG]  		EIP213255
// [Category]  	Improvement
// [Description]  	Dont add Legacy boot option for the Ata device doesnt
// have 512 bytes per sector.
// [Files]  		CsmHwInfo.c
// 
// 114   8/07/14 12:44p Fasihm
// [TAG]           EIP180683
// [Category]      Improvement
// [Severity]      Normal
// [Symptom]       Aptio 4 CSM: CSM build error when disabling
// X64_SUPPORT.
// [Solution]      Changed file to fix the build error.
// [Files]
//         Core\EM\CSM\CsmBsp.c
//         Core/EM/CSM/CsmHwInfo.c
// 
// 113   8/06/14 5:21p Fasihm
// [TAG]           EIP180688
// [Category]      Improvement
// [Severity]      Normal
// [Symptom]       Aptio 4 CSM: PMM high memory life cycle.
// [Solution]      Changed file to address the PMM high memory life cycle.
// [Files]
//         Core/EM/CSM/CsmHwInfo.c
// 
// 112   8/06/14 3:21p Fasihm
// [TAG]           EIP180674
// [Category]      Bug Fix
// [Severity]      Normal
// [Symptom]       Aptio 4 CSM: CSM16: RT PCI function find_device should
// skip buses that do not exist.
// [Solution]      find_device function in RT-PCI.ASM has been modified to
// look for the device on the buses that are physically present in the
// system.
// [Files]
//         Addon/AmiLegacy16.bin
//         Core/EM/CSM/CSM.h
//         Core/EM/CSM/CsmHwInfo.c
// 
// 111   8/06/14 12:31p Fasihm
// [TAG]           EIP180666
// [Category]      Bug Fix
// [Severity]      Normal
// [Symptom]       Aptio4: Sata boot options need to be distinguished when
// there are more than one controller.
// [Solution]      While displaying Boot option in the Set up screen,
// Proposed to display in format ( C<Controller Number> :: P<Port Number>
// - Model Number).
// [Files]
//         Core/EM/CSM/CSM.h
//         Core/EM/CSM/CsmHwInfo.c
// 
// 110   12/18/12 1:44p Olegi
// [TAG]  		EIP108682
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	Invalid Error Code from CSM Functions
// [RootCause]  	BIT31 is used as error indication
// [Solution]  	use EFI_ERROR_BIT macro instead of BIT31
// [Files]  		CSM.c
// CsmHwInfo.c
// 
// 109   12/12/12 2:54p Olegi
// [TAG]  		EIP109283
// [Category]  	Bug Fix
// [Symptom]  	PCI RT32 last bus improperly reported
// [RootCause]  	The last PCI bus is reported based on the chipset
// specific PCI bus configuration.
// [Solution]  	Update RT32 binary with the last bus obtained from PCI Bus
// driver.
// [Files]  		CsmHwInfo.c, rt32core.asm
// 
// 108   6/25/12 3:59p Olegi
// [TAG]  		EIP90257
// [Category]  	Improvement
// [Description]  	In CSM, don't clear allocated memory below 640K - added
// ClearFreeMemory function
// [Files]  		CsmOpROM.c
// CSM.c
// CsmHwInfo.c
// 
// 107   2/09/12 10:19a Olegi
// [TAG]  		EIP71972
// Correction to the original EIP71972 resolution: Slave IDE device was
// not getting proper drive handle.
// 
// 106   11/04/11 12:39p Olegi
// [TAG]  		EIP74722
// [Category]  	Improvement
// [Description]  	IDE drive information is not displayed correctly in the
// Boot page in Setup when both Master and Slave drives are connected
// [Files]  		CsmHwInfo.c
// 
// 105   10/28/11 9:24a Olegi
// [TAG]  		EIP71972
// [Category]  	Improvement
// [Description]  	In some cases HddInfo information is not properly used
// to create BBS entry.
// Cases are:
// - slave drive appears before master in DisdInfo hanle array
// - higher controller PCI function appears before lower function in the
// DiskInfo list
// [Files]  		csmhwinfo.c
// 
// 104   5/04/11 2:15p Olegi
// [TAG]  		EIP59632
// [Category]  	Improvement
// [Description]  	Removed the break from for loop in
// UpdateCsm16Configuration; this allows to finish all COM data
// initialization.
// [Files]  		CsmHwInfo.c
// 
// 103   4/11/11 12:56p Olegi
// [TAG]  		EIP56926
// [Category]  	Improvement
// [Description]  	Added Primary/Secondary Master/Slave information in the
// drive string.
// [Files]  		csmhwinfo.c
// 
// 102   2/04/11 10:19a Olegi
// [TAG]  		EIP53139
// [Category]  	Improvement
// [Description]  	Typo corrected
// [Files]  		csmhwinfo.c
// 
// 101   12/03/10 12:43p Olegi
// [TAG]  		EIP48471
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	COM Port addresses are not filled in correctly in BDA when
// COM 0(First COM port) disabled in setup.
// [RootCause]  	For the COM port resource details in BDA, we should not
// depend on the UID of the Com port.
// [Solution]  	1) Get the 1st COM port details and fill the details in
// CSm16bootable , BDA 40:0 and increment Serial Port count in 40:0x10.
// 2) Get the 2nd Com port details and fill the details in CSm16bootable ,
// BDA 40:2 and increment Serial Port count in 40:0x10..Continue this for
// 4 com ports.
// [Files]  		CsmHwInfo.c
// CsmLib.c
// 
// 100   11/08/10 9:06a Olegi
// Added CloseEvent call in UpdateLastPciBus callback function.
// 
// 99    8/17/10 3:10p Olegi
// Fixes discovered by Klockwork II engine: EIP37977
// 
// 98    7/16/10 12:12p Olegi
// EIP39395: Update CSM16 header checksum after LastPciBus field of it has
// been changed.
// 
// 97    6/18/10 10:29a Olegi
// EIP39149: Bugfix in UpdatePciLastBusCallback function.
// 
// 96    5/07/10 5:04p Felixp
// Bug fix in GetSystemMemoryMap
// 
// 95    5/07/10 5:00p Felixp
// Minor improvement in GetSystemMemoryMap (EIP 38327): 
// use memory map descriptor size returned by the GetMemoryMap instead of
// hard-coded value.
// 
// 94    4/28/10 2:51p Oleksiyy
// EIP 35563  Fixed logic when looking for ACPI 1.1 only tables.
// 
// 93    1/12/10 11:46a Olegi
// Copyright message updated.
// 
// 92    12/28/09 7:46a Olegi
// Added GetLptResource function.
// 
// 91    12/28/09 7:33a Olegi
//
// 90    12/08/09 9:52a Olegi
//
// 89    12/01/09 11:38a Olegi
// Bugfix in EnableDisableNmi function.
//
// 88    8/18/09 2:02p Rameshr
// AhciBus driver doesn't work for Multi Entry.
// Ahci Int13 initilization code moved from AhciBus to CsmHwinfo.c
// EIP: 25369
//
// 87    8/06/09 11:42a Olegi
// MaxPciBus reporting change: do not report FF; this is XP limitation,
// EIP#24852.
//
// 86    6/16/09 4:11p Olegi
// Generic modifications to update LastPciBus field in
// EFI_COMPATIBILITY16_TABLE.
//
// 85    6/16/09 10:09a Olegi
// Resolved the incompatibility with the GenericSio.h definitions.
//
// 84    6/05/09 10:32a Olegi
// EIP20813 - make IRQ7 handler execute from E000 segment, this is the
// workaround for DOS problem, that will take over IRQ7 handler if it is
// located in F000.
//
// 83    4/02/09 2:12p Olegi
// Removed the hardcoding of COM port base address/interrupt.
//
// 82    3/13/09 5:23p Olegi
// Modifications in GetAtaAtapiInfo():
// - removed checking if ABAR (PciCfg[24h]) is 0: under the condition
// where Subclass code is 6 this checking does not make sense
// - added the clarification of checking for SATA device path vs. AE bit
//
// 81    12/02/08 10:20a Olegi
// Changed the logic of extended memory size calculation.
//
// 80    10/10/08 3:36p Olegi
//
// 79    6/04/08 11:09a Olegi
// Bugfix in the previous modification.
//
// 78    6/02/08 6:13p Olegi
// Modified GetAtaAtapiInfo to handle non-IDE mass storage controllers.
//
// 77    3/28/08 3:01p Olegi
// Bugfix in GetAtaAtapiInfo for AHCI enabled controller.
//
// 76    2/25/08 4:48p Olegi
// GetAtaAtapiInfo is modified to handle the situation when SATA
// controller is in RAID mode and RAID OpROM is not handling all connected
// devices (CDROM).
//
// 75    12/10/07 1:34p Olegi
// Bug in the previous checkin is fixed.
//
// 74    12/10/07 12:27p Olegi
// Modified AHCI controller checking.
//
// 73    12/04/07 11:07a Olegi
//
// 72    11/07/07 10:44a Olegi
// Fix in GetExtendedMemSize function: if the amount of memory is 4GB or
// more, some memory is remapped above 4GB by the chipset. In this case
// this function will return the amount of memory before the remapped
// area.
//
// 71    10/02/07 10:34a Olegi
// Modified GetFDDStatus() routine to properly use IsSioDevicePluggedIn().
//
// 2     7/17/07 6:17p Fasihm
//
// 69    6/26/07 9:59a Olegi
// MMIO regions with runtime attribute set will have the corresponding
// E820 reserved entry.
//
// 68    6/18/07 5:46p Olegi
//
// 67    6/06/07 8:16a Olegi
// Added CSM_CREATES_ATA_ATAPI_STRINGS dependency in CreateDriveString
// function.
//
// 66    6/04/07 12:34p Olegi
//
// 65    6/02/07 10:26a Olegi
// Shadow size correction.
//
// 64    5/18/07 11:46a Olegi
// Changed setting BIT2 in 410h (legacy mouse present bit) in
// UpdateCsm16Configuration to avoid clearing this bit if it is already
// set.
//
// 63    5/09/07 1:56p Olegi
//
// 62    4/27/07 5:13p Olegi
// CSM.CHM file preparation.
//
// 61    4/13/07 9:40a Olegi
//
// 60    3/29/07 5:44p Olegi
// Modification in UpdateE820Map function to accomodate Legacy Redirection
// data area.
//
// 59    12/15/06 2:09p Olegi
// Bugfix in DiskInfoHandles usage.
//
// 58    12/14/06 11:06a Olegi
// Adding AGGRESSIVELY_JOINED_E820_ENTRIES flag.
//
// 57    12/12/06 5:33p Olegi
// DiskInfo handles inserted in BBS table as IBV1/IBV2.
//
// 56    9/26/06 4:19p Olegi
// GetFDDStatus is modified to make default number of FDDs 0.
//
// 55    9/20/06 3:11p Olegi
//
// 54    9/13/06 9:34a Felixp
//
// 53    9/13/06 9:32a Felixp
//
// 52    9/12/06 6:10p Markw
// Update EFI_TO_COMPATIBILITY16_BOOT_TABLE structure to UINT32 instead of
// pointer. This structure is used for CSM16 which expects 4 byte
// pointers.
//
// 51    8/28/06 9:49a Olegi
// Bugfix in InstallLegacyMassStorageDevices routine.
//
// 50    8/14/06 11:24a Olegi
//
// 49    8/04/06 12:05p Olegi
// E820 table optimization added.
//
// 48    7/28/06 4:43p Olegi
//
// 47    5/16/06 1:57p Olegi
//
// 45    5/04/06 10:55a Robert
//
// 44    5/04/06 9:42a Olegi
// Removed the logic that fixes the location of PATA/SATA in BBS table.
//
// 43    5/03/06 3:42p Robert
// Added the code to sort out the DiskInfo handles so that PATA goes
// first, SATA next.
//
// 40    3/31/06 2:30p Olegi
//
// 39    3/13/06 2:32p Felixp
//
// 38    12/14/05 4:16p Olegi
// NMI enable/disable changes.
//
// 37    11/29/05 11:38a Olegi
// Bugfix - not all ATAPI devices are CDROMs, as it used to be considered
// in the GetAtaAtapi routine.
//
// 35    10/17/05 8:56a Olegi
//
// 34    10/13/05 6:25p Olegi
//
// 33    10/11/05 11:56a Olegi
//
// 32    10/10/05 7:27p Olegi
//
// 31    10/07/05 5:16p Olegi
//
// 30    10/06/05 8:11p Felixp
//
// 29    10/06/05 11:52a Felixp
//
// 28    9/30/05 6:27p Olegi
// VC7.1 compatibility issues solved.
//
// 27    9/29/05 5:20p Olegi
//
// 26    9/28/05 8:30a Olegi
//
// 25    9/21/05 3:56p Olegi
//
// 24    9/09/05 6:04p Olegi
//
// 23    9/09/05 11:19a Olegi
//
// 22    6/30/05 7:55p Olegi
// PS/2 mouse handling reported correctly.
//
// 21    6/21/05 12:12p Olegi
// LegacyBios and LegacyBiosPlatform are combined into one FFS.
//
// 20    5/12/05 5:15p Yakovlevs
//
// 19    4/22/05 2:10p Olegi
//
// 19    4/21/05 9:00a Olegi
// Modified the rule for inserting E820 entries for regions >4GB
//
// 18    4/19/05 11:12a Olegi
//
// 17    3/30/05 12:28p Olegi
// InstallIdePciHandler - IDE control port calculation corrected.
//
// 16    3/04/05 1:54p Mandal
//
//**********************************************************************
//<AMI_FHDR_START>
//
//  Name:           CsmHwInfo.c
//  Description:    Hardware Information routines
//
//<AMI_FHDR_END>
//****************************************************************************

#include "token.h"
#include "csm.h"
#include <Protocol/PciIo.h>
#include <Protocol/PDiskInfo.h>
#include <Protocol/DevicePath.h>
#include <Protocol/PciRootBridgeIo.h>
#include <Protocol/PIdeController.h>
#include <Protocol/BlockIo.h>
#include <AmiDxeLib.h>
#include "pci.h"
#include "biosdata.h"
#include <Protocol/CsmPlatform.h>
#include <AcpiRes.h>
#ifdef AhciSrc_SUPPORT
#if AhciSrc_SUPPORT
#include <Protocol/LegacyAhci.h>
#endif
#endif

#define MASTER_DRIVE        0
#define SLAVE_DRIVE         1
#define PRIMARY_CHANNEL     0
#define SECONDARY_CHANNEL   1
#define MAX_IDE_PCI_CONTROLLER (MAX_IDE_CONTROLLER << 1)

// Controller information where IDE devices are connected
IDE_CONTROLLER_INFO_STRUC          IdeControllerInfo[MAX_IDE_PCI_CONTROLLER];
UINT8                              gIdeController = 0;

UINT16 aInstalledPciIrq[MAX_IDE_PCI_CONTROLLER];

EFI_GUID    gDiskInfoProtocol = EFI_DISK_INFO_PROTOCOL_GUID;
EFI_GUID    gEfiBlockIoProtocolGuid = EFI_BLOCK_IO_PROTOCOL_GUID;
EFI_GUID    gSataControllerProtocol = SATA_CONTROLLER_PROTOCOL_GUID;
EFI_GUID    gAcpiRsdtPtr = ACPI_20_TABLE_GUID;
EFI_GUID    gAcpiRsdtPtr1_0 = ACPI_10_TABLE_GUID;
EFI_GUID    gSmbiosTable = SMBIOS_TABLE_GUID;

typedef struct {
  ATAPI_IDENTIFY    *IdentifyPtr;
  EFI_HANDLE        DriveHandle;            
} CSM_DRIVE_HANDLE_LIST;

CSM_DRIVE_HANDLE_LIST DriveHandle[MAX_IDE_CONTROLLER*2] ;

EFI_STATUS UpdateCsm16Configuration(EFI_TO_COMPATIBILITY16_BOOT_TABLE*);
VOID GetExtendedMemSize(UINT32*);
VOID GetSioDeviceStatus(SIO_DEV_STATUS *devices);
BOOLEAN IsSioDevicePluggedIn(SIO_DEV_STATUS *plugged_devices, EFI_HANDLE *Handle);

extern  BIOS_INFO *CoreBiosInfo;
extern  BOOLEAN gIsMassStorageInstalled;
extern  UINTN gMaxOpRomAddress;


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Name:        UpdateCsm16Configuration
//
// Description:
//  This function updates Csm16BootTable and BDA. It can be called multiple
//  times during POST as the new hardware is discovered and configured.
//
// Input:
//  Csm16BootTable  pointer to EFI_TO_COMPATIBILITY16_BOOT_TABLE
//
// Output:
//  EFI_SUCCESS Table is updated successfully.
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
UpdateCsm16Configuration(
    IN OUT EFI_TO_COMPATIBILITY16_BOOT_TABLE    *Csm16BootTable
)
{
    SIO_DEV_STATUS sio_devices;
    SIO_DEV_STATUS sio_devices_plugged_in;
    BDA_DATA    *bda;
    UINT16      machineconfig = 0;
    EFI_HANDLE  Handle;
    EFI_STATUS  Status;
    UINT16      Address;
    UINT8       Irq;
    UINT8       ComPortIndex;
    
    //
    // Fill in EFI_TO_COMPATIBILITY16_BOOT_TABLE
    // Note: CSM specification 0.96 defines the pointer as UINT32 - it is
    //       assumed BbsTable pointer is within 4GB address space.
    Csm16BootTable->BbsTable = (UINT32)CoreBiosInfo->BbsTable;
    Csm16BootTable->NumberBbsEntries = CoreBiosInfo->BbsEntriesNo;

    //
    // Updade SIO status in Csm16BootTable->SioData and in BDA
    //
    bda = (BDA_DATA*)((UINTN) 0x400);

// The following definitions are from the up-to-date GenericSio.h
// they can be used after GenericSio.h will be labeled with these changes.
//#define SIO_DEV_COM3        0x1000
//#define SIO_DEV_COM4        0x2000

    sio_devices.DEV_STATUS = SIO_DEV_COM1 | SIO_DEV_COM2 | 0x1000 | 0x2000 |
                            SIO_DEV_LPT  | SIO_DEV_FDC | SIO_DEV_PS2MS;
    GetSioDeviceStatus(&sio_devices);

    if (sio_devices.Fdd) {
        Csm16BootTable->SioData.Floppy.NumberOfFloppy = 1;
        machineconfig |= 1;
    }

    for(ComPortIndex = 0; ComPortIndex < 4; ComPortIndex ++){
        Status = GetComPortResource(ComPortIndex, &Address, &Irq);
        if (!EFI_ERROR(Status))
        {
            Csm16BootTable->SioData.Serial[ComPortIndex].Address = Address;
            Csm16BootTable->SioData.Serial[ComPortIndex].Irq = Irq;
            Csm16BootTable->SioData.Serial[ComPortIndex].Mode = DEVICE_SERIAL_MODE_NORMAL;
            bda->rs_232_address[ComPortIndex] = Address;
            machineconfig += 0x200;
        }
    }
    // Note that SIO_DEV_STATUS limits the number of LPT to one
    if (sio_devices.Lpt) {
        Status = GetLptResource(&Address, &Irq);
        if (!EFI_ERROR(Status)){
           Csm16BootTable->SioData.Parallel[0].Address = Address;
           Csm16BootTable->SioData.Parallel[0].Irq = Irq;
           Csm16BootTable->SioData.Parallel[0].Mode = DEVICE_PARALLEL_MODE_MODE_OUTPUT_ONLY;
           bda->printer_address[0] = Address;
           machineconfig |= 0x4000;
       }
    }

    if ((bda->machine_config & 4) || sio_devices.Ps2Mouse) {
        machineconfig |= 0x4;

        sio_devices_plugged_in.DEV_STATUS = 0;
        sio_devices_plugged_in.Ps2Mouse = 1;
        if (IsSioDevicePluggedIn(&sio_devices_plugged_in, &Handle)) {
            Csm16BootTable->SioData.MousePresent = 1;
        }
    }

    machineconfig |= 2; // coprocessor is always reported present

    bda->machine_config = machineconfig;

    GetExtendedMemSize(&Csm16BootTable->OsMemoryAbove1Mb);
    Csm16BootTable->NumberE820Entries = CoreBiosInfo->NumberE820Entries;

    //
    // Get ACPI&SMBIOS pointers
    //
//TODOx64: What is these pointers are more the 4G in 64 bit mode?
//CSM specification 0.96 defines the pointers as UINT32
    Csm16BootTable->AcpiTable = (UINT32)GetEfiConfigurationTable(pST, &gAcpiRsdtPtr);
    if (Csm16BootTable->AcpiTable == 0)
         Csm16BootTable->AcpiTable = (UINT32)GetEfiConfigurationTable(pST, &gAcpiRsdtPtr1_0);

    TRACE((-1,"CSM - GetEfiConfigurationTable: ACPI table is at %x\n", Csm16BootTable->AcpiTable));

    Csm16BootTable->SmbiosTable = (UINT32)GetEfiConfigurationTable(pST, &gSmbiosTable);

    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  GetFDDStatus
//
// DESCRIPTION: This function returns the status of the floppy drive.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

FDD_STATUS GetFDDStatus()
{
    SIO_DEV_STATUS      sio_devices;
    EFI_STATUS          Status;
    FDD_STATUS          DriveStatus = NO_FLOPPY_DRIVE;
    EFI_HANDLE          Handle;
    EFI_BLOCK_IO_PROTOCOL *blkiop;

    sio_devices.DEV_STATUS = 0;
    sio_devices.Fdd = 1;

    if (!IsSioDevicePluggedIn(&sio_devices, &Handle)) return NO_FLOPPY_DRIVE;

    Status = pBS->HandleProtocol(Handle,&gEfiBlockIoProtocolGuid, &blkiop);
    ASSERT_EFI_ERROR(Status);

    if (!EFI_ERROR(Status)) {
        DriveStatus = blkiop->Media->MediaPresent? FLOPPY_INSERTED : NO_FLOPPY_DISK;
    }

    return DriveStatus;

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  InstallIdePciHandler
//
// DESCRIPTION: This function makes InstallPciHandler CSM16 call
//
// PARAMETERS:  PCI IDE controller data needed for the IRQ installation
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
InstallIdePciHandler(
    HDD_INFO* HddInfo1,
    HDD_INFO* HddInfo2
)
{
    EFI_IA32_REGISTER_SET RegSet;
    EFI_STATUS Status;
    UINT8 i;
    EFI_LEGACY_INSTALL_PCI_HANDLER *PciHandlerData = &CoreBiosInfo->Thunk->PciHandler;
    UINT16 wPciDev = 0xFFFF;
    BOOLEAN IsNativeMode;
    //
    // Check whether PCI IRQ handler for this PCI device has been installed, exit if so.
    //
    for (i = 0; i < MAX_IDE_PCI_CONTROLLER; i++) {
        wPciDev = (UINT16)((HddInfo1->Bus << 8) | (HddInfo1->Device << 3) | HddInfo1->Function);
        if (!aInstalledPciIrq[i]) break;    // New entry found
        if (wPciDev == aInstalledPciIrq[i]) return EFI_SUCCESS;
    }
    ASSERT(i < MAX_IDE_PCI_CONTROLLER);
    if (i == MAX_IDE_PCI_CONTROLLER) return EFI_OUT_OF_RESOURCES;   // Error - no free entries

    //
    // Prepare PCI handler data in Thunk memory
    //
    PciHandlerData->PciBus = (UINT8)HddInfo1->Bus;
    PciHandlerData->PciDeviceFun = (UINT8)((HddInfo1->Device << 3) | HddInfo1->Function);
    PciHandlerData->PciSegment = 0;
    PciHandlerData->PciClass = PCI_CL_MASS_STOR;
    PciHandlerData->PciSubclass = PCI_CL_MASS_STOR_SCL_IDE;
    IsNativeMode = HddInfo1->HddIrq != 14;
    PciHandlerData->PciInterface = (IsNativeMode)?0x8F:0x8A;

    //
    // Primary section
    //
    PciHandlerData->PrimaryIrq = HddInfo1->HddIrq;
    PciHandlerData->PrimaryReserved = 0;
    PciHandlerData->PrimaryControl = HddInfo1->ControlBaseAddress;
    PciHandlerData->PrimaryBase = HddInfo1->CommandBaseAddress;
    PciHandlerData->PrimaryBusMaster = HddInfo1->BusMasterAddress;
    //
    // Secondary section
    //
    PciHandlerData->SecondaryIrq = HddInfo2->HddIrq;
    PciHandlerData->SecondaryReserved = 0;
    PciHandlerData->SecondaryControl = HddInfo2->ControlBaseAddress;
    PciHandlerData->SecondaryBase = HddInfo2->CommandBaseAddress;
    PciHandlerData->SecondaryBusMaster = HddInfo2->BusMasterAddress;

    pBS->SetMem(&RegSet, sizeof (EFI_IA32_REGISTER_SET), 0);
    RegSet.X.AX = Compatibility16InstallPciHandler;
    RegSet.X.ES = EFI_SEGMENT (PciHandlerData);
    RegSet.X.BX = EFI_OFFSET (PciHandlerData);

    Status = CoreBiosInfo->iRegion->UnLock (CoreBiosInfo->iRegion,
        (UINT32)gMaxOpRomAddress+1,
        0xFFFFF-(UINT32)gMaxOpRomAddress,
        NULL
    );
    ASSERT_EFI_ERROR(Status);

    FarCall86 (&CoreBiosInfo->iBios,
                CoreBiosInfo->Csm16EntrySeg,
                CoreBiosInfo->Csm16EntryOfs,
                &RegSet,
                NULL,
                0);
    Status = (RegSet.X.AX)? ((RegSet.X.AX & 0x7FFF) | EFI_ERROR_BIT) : EFI_SUCCESS;
    ASSERT_EFI_ERROR(Status);
    if (!EFI_ERROR(Status)) {
        aInstalledPciIrq[i] = wPciDev;  // Save the new PCI device entry
    }

    Status = CoreBiosInfo->iRegion->Lock (CoreBiosInfo->iRegion,
        (UINT32)gMaxOpRomAddress+1,
        0xFFFFF-(UINT32)gMaxOpRomAddress,
        NULL
    );
    ASSERT_EFI_ERROR(Status);

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
// Procedure:    UpdateIdeControllerInfo
//
// Description:  This function will check if the BusDevFunc is existing in 
//               Idecontrollerinfo structure array,if it exist then it return. 
//               If it is not exist, it will add BusDevFunc into IdeControllerInfo structure.
//
// Input:        IdeBusDevFun  - It contain the BusDevFunc number for a device
//
// Output:       VOID
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

void UpdateIdeControllerInfo(UINT16 IdeBusDevFun)
{
    UINTN   i;
    
    for(i=0; i < gIdeController ; i++) {
        if(IdeControllerInfo[i].BusDevFun == IdeBusDevFun) {
            /// Controller detected 
            return;
        }
    }

    //
    // A new controller is found so BusDevFunc and ControllerNo is added
    // into the array of structure.
    //
    IdeControllerInfo[gIdeController].BusDevFun = IdeBusDevFun;
    IdeControllerInfo[gIdeController].ControllerNo = gIdeController++;
    
    return;
    
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  GetAtaAtapiInfo
//
// DESCRIPTION: This function collects the information about currently connected
//              ATA/ATAPI devices. It stores this information in the HDD_INFO data
//              structure and installs legacy interrupt handlers.
//
// PARAMETERS:  DiskInfoHandles - array of handles with DiskInfo protocol
//              Info - pointer to HDD_INFO array to be updated
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS GetAtaAtapiInfo(
    IN OUT  EFI_HANDLE  **DiskInfoHandles,
    OUT HDD_INFO* Info
)
{
    EFI_STATUS  Status;
    UINTN       i, j, HandlesNo;
    EFI_DISK_INFO_PROTOCOL      *pDiskInfo;
    EFI_DEVICE_PATH_PROTOCOL    *pDevicePath;
    EFI_PCI_IO_PROTOCOL         *pPciIo;
    EFI_BLOCK_IO_PROTOCOL 		*BlkIo;
    EFI_HANDLE  Handle;
    UINTN       Seg, Bus, Dev, Func;
    HDD_INFO    *HddInfo;
    UINT32      PriSec, MasterSlave;
    UINT8       pciCfg[0x40];
    UINT16      priCmdIoAddr, secCmdIoAddr;
    UINT16      priCtlIoAddr, secCtlIoAddr;
    UINT16      bmIoAddr;
    UINT8       priIrq, secIrq;
    BOOLEAN     IsNativeMode, IsAtapiDevice, IsSataDevice;
    ATAPI_IDENTIFY  *pAtapiIdentifyBuffer;
    UINT32      DataCount = sizeof (ATAPI_IDENTIFY);
    CSM_DRIVE_HANDLE_LIST *pDriveHandle = DriveHandle;
	
    // Clear drive handles list
    pBS->SetMem(pDriveHandle, sizeof(CSM_DRIVE_HANDLE_LIST)*MAX_IDE_CONTROLLER*2, 0);

    //
    // Get the list of DiskInfo handles
    //
    Status = pBS->LocateHandleBuffer(
                    ByProtocol,
                    &gDiskInfoProtocol,
                    NULL,
                    &HandlesNo,
                    DiskInfoHandles);
    if (EFI_ERROR(Status)) return EFI_NOT_FOUND;

    for (i = 0; i < HandlesNo; i++) {

        // Check DiskInfo.Interface field
        static EFI_GUID DiIntrfGuid = EFI_DISK_INFO_IDE_INTERFACE_GUID;

        Status = pBS->HandleProtocol (
                                (*DiskInfoHandles)[i],
                                &gDiskInfoProtocol,
                                &pDiskInfo);    // Get DiskInfo protocol

        ASSERT_EFI_ERROR (Status);

        if (guidcmp(&pDiskInfo->Interface, &DiIntrfGuid)) continue;

        Status = pBS->HandleProtocol((*DiskInfoHandles)[i],
        								&gEfiBlockIoProtocolGuid, 
        								&BlkIo);
        ASSERT_EFI_ERROR(Status);
        if (EFI_ERROR(Status)) { 
        	continue;    
        }

        Status = pBS->HandleProtocol ((*DiskInfoHandles)[i],
                                        &gEfiDevicePathProtocolGuid,
                                        (VOID*)&pDevicePath);

        ASSERT_EFI_ERROR(Status);

        //
        // Get PCI device/function info out of DiskInfo device path
        //
        Status = pBS->LocateDevicePath(
            &gEfiPciIoProtocolGuid,    // Search key
            &pDevicePath,       // Will be updated with PCI device path
            &Handle);           // Will be updated with PCI device handle
        if (EFI_ERROR(Status)) continue;    // PCI device path is not found

        // check if SataController protocol is installed
        Status = pBS->HandleProtocol (
            Handle,
            &gSataControllerProtocol,
            &pPciIo);           //Dummy. Interface is null.
        IsSataDevice = !(BOOLEAN)EFI_ERROR(Status);

        Status = pBS->HandleProtocol (
            Handle,
            &gEfiPciIoProtocolGuid,
            &pPciIo);           // Get PciIo protocol
        ASSERT_EFI_ERROR (Status);


        pDiskInfo->WhichIde(pDiskInfo, &PriSec, &MasterSlave);  // Device/Channel info
        Status = pPciIo->GetLocation(pPciIo, &Seg, &Bus, &Dev, &Func);   // Location on PCI bus      
        ASSERT_EFI_ERROR(Status);                         
       
        /// Update controller Number for the IDE device
        UpdateIdeControllerInfo(((UINT16)Bus<<8) + ((UINT16)Dev<<3) + (UINT16)Func);
                
        pPciIo->Pci.Read(
            pPciIo,
            EfiPciIoWidthUint32,
            0,
            0x10,
            &pciCfg);   // Get 40h bytes of PCI device configuration registers

        if (pciCfg[0xB] != PCI_CL_MASS_STOR) continue;

        if (pciCfg[0xA] == PCI_CL_MASS_STOR_SCL_RAID) continue;

        if (pciCfg[0xA] == 6) {

            EFI_DEVICE_PATH_PROTOCOL *DevicePath;
            //
            // SATA controller is in AHCI mode; we can only handle it if
            // AE bit is not set and controller is operated using legacy ATA/ATAPI
            // mechanisms, not AHCI descriptors. Verify this by checking if
            // SATA device path is installed on this device.
            //
            // Note: previously we were checking for the status of AE in controller's
            // MMIO (ABAR at PciCfg[0x24]+4, Bit31). It was found that for some
            // controllers it is not safe to access MMIO directly. Example: Intel
            // ESB2 controller loses index/data access functionality after any
            // AHCI MMIO register is read directly.
            //
            DevicePath = DPGetLastNode(pDevicePath);
            if (DevicePath->Type == MESSAGING_DEVICE_PATH &&
                DevicePath->SubType == MSG_USB_SATA_DP) {
                continue;
            }
        }

        IsNativeMode = pciCfg[9] & 1;

        if (IsNativeMode) { // for native mode get data from PCI config space
            priCmdIoAddr = *(UINT16*)&pciCfg[0x10] & 0xFFFE;
            secCmdIoAddr = *(UINT16*)&pciCfg[0x18] & 0xFFFE;
            priCtlIoAddr = (*(UINT16*)&pciCfg[0x14] & 0xFFFE) + 2;
            secCtlIoAddr = (*(UINT16*)&pciCfg[0x1C] & 0xFFFE) + 2;
            priIrq = secIrq = pciCfg[0x3C];
        }
        else {  // for legacy mode use hardcoded data
            priCmdIoAddr = 0x1F0;
            secCmdIoAddr = 0x170;
            priCtlIoAddr = 0x3F6;
            secCtlIoAddr = 0x376;
            priIrq = 0xE;
            secIrq = 0xF;
        }
        bmIoAddr =  *(UINT16*)&pciCfg[0x20] & 0xFFFE;

        //
        // All necessary HW data is received; the following loop searches for the
        // next available HddInfo, fills in HDD_INFO structure and installs legacy
        // PCI interrupt if needed.
        //
        for (j = 0, HddInfo = Info; j < MAX_IDE_CONTROLLER; j++, HddInfo++) {
            if (!HddInfo->Bus && !HddInfo->Device && !HddInfo->Function) {
                HddInfo->Status = HDD_PRIMARY;
                HddInfo->Bus = (UINT32)Bus;
                HddInfo->Device = (UINT32)Dev;
                HddInfo->Function = (UINT32)Func;
                HddInfo->CommandBaseAddress = priCmdIoAddr;
                HddInfo->ControlBaseAddress = priCtlIoAddr;
                HddInfo->BusMasterAddress = bmIoAddr;
                HddInfo->HddIrq = priIrq;
                HddInfo++;
                HddInfo->Status = HDD_SECONDARY;
                HddInfo->Bus = (UINT32)Bus;
                HddInfo->Device = (UINT32)Dev;
                HddInfo->Function = (UINT32)Func;
                HddInfo->CommandBaseAddress = secCmdIoAddr;
                HddInfo->ControlBaseAddress = secCtlIoAddr;
                HddInfo->BusMasterAddress = bmIoAddr+8;
                HddInfo->HddIrq = secIrq;
                if (PriSec == PRIMARY_CHANNEL) HddInfo--;
                break;
            }
            if (Bus == HddInfo->Bus && Dev == HddInfo->Device && Func == HddInfo->Function) {
                if (PriSec == SECONDARY_CHANNEL) HddInfo++;
                break;
            }
        }

        //
        // Copy the IDENTIFY_DRIVE information into appropriate HDD_INFO field
        //
        pAtapiIdentifyBuffer = HddInfo->IdentifyDrive;
        if (MasterSlave != MASTER_DRIVE) pAtapiIdentifyBuffer++;
        pDiskInfo->Identify(pDiskInfo, pAtapiIdentifyBuffer, &DataCount);

        //
        // Check whether device is ATA or ATAPI - WORD 0 bits 14 and 15
        //
        IsAtapiDevice = (BOOLEAN)((*(UINT16*)pAtapiIdentifyBuffer & 0xC000) == 0x8000);

        // If the device Block size is more than 512 bytes and ATA device
        // Don't add the device as INT13 device ( Legacy supported device).
        if( IsAtapiDevice == FALSE ) {
            if(BlkIo->Media->BlockSize != 512) {
                continue;
            }
        }


        pDriveHandle->IdentifyPtr = pAtapiIdentifyBuffer;
        pDriveHandle->DriveHandle = (*DiskInfoHandles)[i];
        pDriveHandle++;
        //
        // Update HDD_INFO status
        //
        if (PriSec == PRIMARY_CHANNEL) {
            HddInfo->Status |= HDD_PRIMARY;
        } else {
            HddInfo->Status |= HDD_SECONDARY;
        }
        if (MasterSlave == MASTER_DRIVE) {
            if (IsAtapiDevice) {
                HddInfo->Status |= HDD_MASTER_ATAPI;
            } else {
                HddInfo->Status |= HDD_MASTER_IDE;
            }
        } else {    // SLAVE_DRIVE
            if (IsAtapiDevice) {
                HddInfo->Status |= HDD_SLAVE_ATAPI;
            } else {
                HddInfo->Status |= HDD_SLAVE_IDE;
            }
        }
        if (IsSataDevice) HddInfo->Status |= HDD_SATA_PATA;
        CoreBiosInfo->HddCount++;
    }

    return EFI_SUCCESS;
}

            //(EIP20813+)>
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Name:        SetINT0F_E0000
//
// Description: Change INT0F Vector To E000 Segment
//
// Output:      EFI_STATUS Success of failure of the operation.
//
// Notes:       If the IRQ7 vector is in F000 segment, MS-DOS will take over
//              the IRQ7 ISR and cause HDDs not working. This routine places IRQ7
//              handler in E000 segment to avoid this problem.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

#pragma pack(1)
typedef struct
{
    UINT8  Far_JMP;
    UINT32 Address;
}E0000_Int0f;
#pragma pack()

EFI_STATUS
SetINT0F_E0000()
{
    EFI_STATUS  Status;
    E0000_Int0f *P_E0000_Int0f;
    UINT32      LockUnlockAddr, LockUnlockSize;
    UINT32      *PInt15;

    PInt15=(UINT32*)(0x0f*4);

    //
    // Allocate legacy region in E000 segment; store SEG:OFS of the allocated
    // memory in global variables
    //
    Status =GetLegacyRegion(&CoreBiosInfo->iBios, sizeof(E0000_Int0f), E0000_BIT, 0x10, &P_E0000_Int0f);

    if(EFI_ERROR(Status)) return Status;

    UnlockShadow((UINT8*)P_E0000_Int0f, sizeof(E0000_Int0f), &LockUnlockAddr, &LockUnlockSize);

    P_E0000_Int0f->Far_JMP=0xEA;        //far jump
    P_E0000_Int0f->Address=*PInt15;     //save original vector
    *PInt15= EFI_SEGMENT(P_E0000_Int0f) * 0x10000 | EFI_OFFSET (P_E0000_Int0f); //Set New INT0F Vector

    LockShadow(LockUnlockAddr, LockUnlockSize);

    return EFI_SUCCESS;
}

            //<(EIP20813+)

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  InstallIdeInterrupts
//
// DESCRIPTION: This function installs PCI interrupts for all PATA and SATA
//              controllers.
//
// PARAMETERS:  HDD_INFO
//
// NOTES:       HDD_INFO is expected to be populated before this call.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS  InstallIdeInterrupts(
    IN HDD_INFO *HddInfo
)
{
    UINT8 j;
    UINT8 hdd_irq7_set=0;
    HDD_INFO *HddInfo1 = HddInfo;
    HDD_INFO *HddInfo2 = HddInfo;
    EFI_STATUS Status;

    for (j = 0; j < (MAX_IDE_CONTROLLER/2); j++) {
        HddInfo2 = HddInfo1+1;
        if ((HddInfo1->Status &
                (HDD_MASTER_ATAPI | HDD_SLAVE_ATAPI |
                    HDD_MASTER_IDE | HDD_SLAVE_IDE))||
            (HddInfo2->Status &
                (HDD_MASTER_ATAPI | HDD_SLAVE_ATAPI |
                    HDD_MASTER_IDE | HDD_SLAVE_IDE)))
        {
            Status = InstallIdePciHandler(HddInfo1, HddInfo2);
            ASSERT_EFI_ERROR(Status);

            //if (EFI_ERROR(Status)) return Status; //(EIP20813-)

                        //(EIP20813+)>

            if( HddInfo1->HddIrq==0x07 || HddInfo2->HddIrq==0x07)
                hdd_irq7_set=1;

            if (EFI_ERROR(Status)) break;

                        //<(EIP20813+)
        }
        HddInfo1+=2;
    }
                        //(EIP20813+)>
    if(hdd_irq7_set)
        SetINT0F_E0000();

                        //<(EIP20813+)
    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  CreateDriveString
//
// DESCRIPTION: This function prepares the description string for the ATA/ATAPI
//              drive and places its pointer in the BBS entry.
//
// PARAMETERS:  IdentifyDriveData - IDENTIFY_DRIVE data for this device
//              DriveDisplayName - pointer to the string to be updated
//              BbsDescStringOffset - pointer to the string description offset
//              in the corresponding BBS entry
//
// NOTE:        1) DriveDisplayName must be located below 1MB
//              2) BbsDescStringSegment is UINT16 followed by BbsDescStringOffset
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
CreateDriveString (
    IN UINT16   *IdentifyDriveData,
    IN UINT16   ChannelInfo,
    OUT DRIVE_DISPLAY_NAME  *DriveDisplayName,
    OUT UINT16  *BbsDescStringOffset,
    UINTN       DeviceAddress
)
{
#if CSM_CREATES_ATA_ATAPI_STRINGS
    UINT8   i, data8;
    UINT16  data16 = IdentifyDriveData[76];	
    UINT8   s[MAX_DRIVE_NAME] = {0};
    // Temp variable introduced in order to reduce the Code length
    UINTN    Temp = 0;

    if(gIdeController > 1) {
        pBS->CopyMem(&s[0], "xC::APAT     :",14);          // "PATA: "
        Temp = 4;
      
        /// find and replace the Controller Number in String
        for(i=0;i<gIdeController;i++) {
            if(IdeControllerInfo[i].BusDevFun == DeviceAddress) {            
                //// Controller for the AHCI Device found            
                s[0] = IdeControllerInfo[i].ControllerNo + 0x30; 
                break;
            }
        }  
    }    
    else {
        pBS->CopyMem(&s[0], "APAT     :",10);               // "PATA: "   
    }
      
    // Check Word76 for BIT1 and BIT2; set for SATA drives
    if ((data16 != 0xFFFF) && (data16 & 6)) {
        s[1 + Temp] = 'S';
    }

    if(ChannelInfo & HDD_PRIMARY) {
        s[7 + Temp]='P';
        if(ChannelInfo & (HDD_MASTER_IDE | HDD_MASTER_ATAPI )) {
            s[6 + Temp]='M';
        } else {
            s[6 + Temp]='S';
        }
    } else if(ChannelInfo & HDD_SECONDARY) {
        s[7 + Temp]='S';
        if(ChannelInfo & (HDD_MASTER_IDE | HDD_MASTER_ATAPI )) {
            s[6 + Temp]='M';
        } else {
            s[6 + Temp]='S';
        }
    }
    
    // Get the drive name out of IdentifyDrive data word 27..46 (upto 40 chars)
    pBS->CopyMem(&s[10 + Temp], IdentifyDriveData+27, MAX_DRIVE_NAME- (11+Temp) );
    // Swap the bytes
    for (i=0; i<MAX_DRIVE_NAME; i+=2) {
        data8=s[i];
        s[i]=s[i+1];
        s[i+1]=data8;
    }

    pBS->CopyMem(DriveDisplayName, s, MAX_DRIVE_NAME);
    // Update string pointer in BBS after converting it to SEG:OFS format
    *BbsDescStringOffset = (UINT16)(UINTN)DriveDisplayName;
    *(BbsDescStringOffset+1) = (UINT16)(((UINTN)DriveDisplayName >> 4) & 0xF000);
#endif
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  GetAtapiDeviceType
//
// DESCRIPTION: This function returns ATAPI device type depending on the information
//              provided by IDENDIFY_DRIVE data. It could call CSM platform functions
//              to return platform specific ATAPI device type or if the type is
//              selectable in System Setup.
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT16
GetAtapiDeviceType(
    IN ATAPI_IDENTIFY *IdentifyDriveData
)
{
    UINT16      DevType;
    EFI_STATUS  Status;
    CSM_PLATFORM_PROTOCOL *CsmPlatformProtocol;

    pBS->LocateProtocol(&gCsmPlatformProtocolGuid, NULL, &CsmPlatformProtocol);
    //
    // LocateProtocol will return CsmPlatformProtocol = NULL if protocol is not found.
    //
    if (CsmPlatformProtocol) {
        Status = CsmPlatformProtocol->GetAtapiDeviceType(CsmPlatformProtocol, IdentifyDriveData, &DevType);
        if (!EFI_ERROR(Status)) return DevType; // Identified
    }
    //
    // Use default, "generic" method of device identification
    //
    DevType = BBS_FLOPPY;

    if ((IdentifyDriveData->Raw[0] & 0x1F00) == 0x500)
    {
        DevType = BBS_CDROM;
    }
    return DevType;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:  GetDriveHandle
//
// Description:
//  This function searches for the IDE mass storage device handle in the list
//  of handles and returns the one that matches with the given IdentifyDrive
//  information.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_HANDLE  GetDriveHandle(ATAPI_IDENTIFY *IdentifyPtr)
{
    UINT8   i;
    for (i=0; i<MAX_IDE_CONTROLLER*2; i++){
        if (DriveHandle[i].IdentifyPtr == IdentifyPtr)
            return DriveHandle[i].DriveHandle;
    }

    return NULL;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  InstallLegacyMassStorageDevices
//
// DESCRIPTION: This function prepares BBS table, inserts FDD/IDE/SATA entries
//              in the table and calls CSM16->UpdateBbs function to bring up
//              non-BBS compliant entries as well.
//
// NOTE:        This function should be executed only once, when DiskInfo handles
//              are ready.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID InstallLegacyMassStorageDevices()
{
    HDD_INFO    *AtaAtapiInfo;
    UINT8       IdeCtl, Indx;
    EFI_STATUS  Status;
    UINT8       count = 0;
    EFI_HANDLE  *DiskInfoHandles = 0;

    BBS_TABLE   *BbsEntry = CoreBiosInfo->BbsTable;

    //
    // Insert ATA/ATAPI devices into CoreBiosInfo->Thunk->Csm16BootTable.HddInfo
    //
    for (Indx = 0; Indx < MAX_IDE_PCI_CONTROLLER; Indx++) aInstalledPciIrq[Indx] = 0;
    AtaAtapiInfo = CoreBiosInfo->Thunk->Csm16BootTable.HddInfo;

    Status = GetAtaAtapiInfo(&DiskInfoHandles, AtaAtapiInfo);

    if (!EFI_ERROR(Status)) {   // some IDE device are connected
        InstallIdeInterrupts(AtaAtapiInfo);
        //
        // Update BBS table with controller/device information
        //
        for (IdeCtl = 0; IdeCtl < MAX_IDE_CONTROLLER; IdeCtl++) {
            if (!(AtaAtapiInfo[IdeCtl].Status &
                ( HDD_MASTER_ATAPI | HDD_SLAVE_ATAPI | HDD_MASTER_IDE | HDD_SLAVE_IDE ))) {
                continue;
            }
            Indx = IdeCtl*2 + 1;    // 1st entry is taken for floppy

            BbsEntry[Indx].Bus = BbsEntry[Indx+1].Bus = AtaAtapiInfo[IdeCtl].Bus;
            BbsEntry[Indx].Device = BbsEntry[Indx+1].Device = AtaAtapiInfo[IdeCtl].Device;
            BbsEntry[Indx].Function = BbsEntry[Indx+1].Function = AtaAtapiInfo[IdeCtl].Function;
            BbsEntry[Indx].Class = BbsEntry[Indx+1].Class = 1;
            BbsEntry[Indx].SubClass = BbsEntry[Indx+1].SubClass = 1;

            if (AtaAtapiInfo[IdeCtl].CommandBaseAddress) {  // real controller
                //
                // Create entry for master device connected to this controller
                //
                if (AtaAtapiInfo[IdeCtl].Status & (HDD_MASTER_IDE | HDD_MASTER_ATAPI)) {
                    BbsEntry[Indx].BootPriority = BBS_UNPRIORITIZED_ENTRY;
                    if (AtaAtapiInfo[IdeCtl].Status & HDD_MASTER_ATAPI) {
                        BbsEntry[Indx].DeviceType = GetAtapiDeviceType(&AtaAtapiInfo[IdeCtl].IdentifyDrive[0]);
                    } else {
                        BbsEntry[Indx].DeviceType = BBS_HARDDISK;
                    }
                    CreateDriveString(
                        AtaAtapiInfo[IdeCtl].IdentifyDrive[0].Raw,
                        AtaAtapiInfo[IdeCtl].Status & ~(HDD_SLAVE_IDE | HDD_SLAVE_ATAPI),
                        &CoreBiosInfo->Thunk->DriveDisplayName[count++],
                        &BbsEntry[Indx].DescStringOffset,                        
                        ((UINT16)AtaAtapiInfo[IdeCtl].Bus << 8) +((UINT16)AtaAtapiInfo[IdeCtl].Device<<3)\
                          + ((UINT16) AtaAtapiInfo[IdeCtl].Function )                      
                    );
                    //TRACE((-1, "i=%d, bbsentry=%x, diskinfo=%x\n", Indx, &BbsEntry[Indx], *DiskInfoHandles));
                    *(UINTN*)(&BbsEntry[Indx].IBV1) = (UINTN)GetDriveHandle(AtaAtapiInfo[IdeCtl].IdentifyDrive);//(EIP71972)
                }
                //
                // Create entry for slave device connected to this controller
                //
                if (AtaAtapiInfo[IdeCtl].Status & (HDD_SLAVE_IDE | HDD_SLAVE_ATAPI)) {
                    BbsEntry[Indx+1].BootPriority = BBS_UNPRIORITIZED_ENTRY;
                    if (AtaAtapiInfo[IdeCtl].Status & HDD_SLAVE_ATAPI) {
                        BbsEntry[Indx+1].DeviceType = GetAtapiDeviceType(&AtaAtapiInfo[IdeCtl].IdentifyDrive[1]);
                    } else {
                        BbsEntry[Indx+1].DeviceType = BBS_HARDDISK;
                    }
                    CreateDriveString(
                        AtaAtapiInfo[IdeCtl].IdentifyDrive[1].Raw,
                        AtaAtapiInfo[IdeCtl].Status & ~(HDD_MASTER_IDE | HDD_MASTER_ATAPI),
                        &CoreBiosInfo->Thunk->DriveDisplayName[count++],
                        &BbsEntry[Indx+1].DescStringOffset,                       
                        ((UINT16)AtaAtapiInfo[IdeCtl].Bus << 8) +((UINT16)AtaAtapiInfo[IdeCtl].Device<<3)\
                          + ((UINT16) AtaAtapiInfo[IdeCtl].Function )                   
                    );
                    //TRACE((-1, "i=%d, bbsentry=%x, diskinfo=%x\n", Indx, &BbsEntry[Indx+1], *DiskInfoHandles));
                    *(UINTN*)(&BbsEntry[Indx+1].IBV1) = (UINTN)GetDriveHandle(&AtaAtapiInfo[IdeCtl].IdentifyDrive[1]);//(EIP71972)
                }
            }
        }
    }

#ifdef AhciSrc_SUPPORT
#if AhciSrc_SUPPORT
{
    EFI_AHCI_INT13_INIT_PROTOCOL    *Aint13;

    //
    // Initialize legacy AHCI support
    //
    Status = pBS->LocateProtocol(&gAint13ProtocolGuid, NULL, &Aint13);
    if (!EFI_ERROR(Status)) {
        Aint13->InitAhciInt13Support();
    }

}
#endif
#endif

    gIsMassStorageInstalled = TRUE;

    return;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  GetSystemMemoryMap
//
// DESCRIPTION: This function returns system memory map and count of the memory
//              entries in the map.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS GetSystemMemoryMap(
    OUT EFI_MEMORY_DESCRIPTOR **MemMap,
    OUT UINTN *MemDescSize,
    OUT UINTN *MemEntriesCount
)
{
    EFI_STATUS Status;
    UINTN MemMapSize, MemMapKey;
    UINT32 MemDescVer;

    if (MemMap == NULL || MemDescSize == NULL || MemEntriesCount == NULL)
    {
        ASSERT(FALSE);
        return EFI_INVALID_PARAMETER;
    }

    *MemMap = NULL;
    MemMapSize = 0; // GetMemoryMap will return the size needed for the map
    Status = pBS->GetMemoryMap(&MemMapSize, *MemMap,
                    &MemMapKey, MemDescSize, &MemDescVer);

    ASSERT(Status == EFI_BUFFER_TOO_SMALL);
    if (Status != EFI_BUFFER_TOO_SMALL) {
        *MemEntriesCount = 0;
        return EFI_INVALID_PARAMETER;
    }

    // The following memory allocation may alter memory map.
    // Let's add space for 5 more descriptors to be sure buffer is big enough
    MemMapSize += 5 * *MemDescSize;
    Status = pBS->AllocatePool(EfiBootServicesData, MemMapSize, MemMap);
    ASSERT_EFI_ERROR(Status);

    Status = pBS->GetMemoryMap(&MemMapSize, *MemMap,
                    &MemMapKey, MemDescSize, &MemDescVer);
    ASSERT_EFI_ERROR(Status);

    *MemEntriesCount = (UINT16)(MemMapSize / *MemDescSize);

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  GetExtendedMemSize
//
// DESCRIPTION: This function looks through the system memory map, finds the
//              available memory regions and returns the size in bytes of the
//              system memory above 1 MB.
// NOTE:        If there is more than 4 GB of memory installed, then function
//              will return 4GB-1MB.
//              If the amount of memory is 4GB or more, some memory is remapped
//              above 4GB by the chipset. In this case this function will return
//              the amount of memory before the remapped area.
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID GetExtendedMemSize(UINT32* ExtMemSize)
{
    UINTN MemDescSize;
    EFI_MEMORY_DESCRIPTOR *MemMap;
    EFI_MEMORY_DESCRIPTOR *mm;
    UINTN count = 0;
    UINTN MemEntriesCount;
    UINT64 cs = 0x100000;

    GetSystemMemoryMap(&MemMap, &MemDescSize, &MemEntriesCount);

    for (mm = MemMap; count < MemEntriesCount; mm=(EFI_MEMORY_DESCRIPTOR*)((UINT8*)mm+MemDescSize), count++) {
        if (mm->PhysicalStart < 0x100000) continue; // skip low memory entries

        if (mm->Type == EfiReservedMemoryType ||
            mm->Type == EfiMemoryMappedIO ||
            mm->Type == EfiMemoryMappedIOPortSpace ||
            mm->Type == EfiRuntimeServicesCode ||
            mm->Type == EfiRuntimeServicesData ||
            mm->Type == EfiUnusableMemory ||
            mm->Type == EfiPalCode ||
            mm->Type == EfiACPIReclaimMemory ||
            mm->Type == EfiACPIMemoryNVS)
        {
            break;
        }

        cs = mm->PhysicalStart + Shl64(mm->NumberOfPages, EFI_PAGE_SHIFT);
    }
    pBS->FreePool(MemMap);

    *ExtMemSize = (UINT32)cs - 0x100000;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  InsertE820Entry
//
// DESCRIPTION: This function fills in the E820 table entry and adjusts
//              the input entry pointer. If the new entry is the extension of
//              the previous one, then entry is "extended".
// PARAMETERS:  Pointer to E820 entry to be filled.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
InsertE820Entry (
    E820_ENTRY **Entry,
    UINT64 Address,
    UINT64 Size,
    E820_MEMORY_TYPE Type,
    UINT16 *Count)
{
    E820_ENTRY *E820Entry = *Entry;
    E820_ENTRY *PrevE820Entry = E820Entry - 1;

    if (((PrevE820Entry->Adr + PrevE820Entry->Len) == Address) &&
        ((PrevE820Entry->Type == Type)
#if AGGRESSIVELY_JOINED_E820_ENTRIES
        || ((Type == MemRangeAvl) && (Address != 0x100000))
#endif
))
    {
        // extend the current entry without touching Adr and Type
        E820Entry = PrevE820Entry;
        E820Entry->Len += Size;
    } else {    // new entry
        E820Entry->Adr = Address;
        E820Entry->Len = Size;
        E820Entry->Type = Type;
        (*Count)++;
    }
    E820Entry->ExtendedAttr = E820_EXTATTR_ADDRESS_RANGE_ENABLED;
    *Entry = ++E820Entry;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  UpdateE820Map
//
// DESCRIPTION: This function retrieves the system memory map and converts it
//              into E820 map format.
// PARAMETERS:  Pointer to the 1st E820 entry in BIOS_INFO data structure
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32
UpdateE820Map(E820_ENTRY *e820_entry)
{
    UINT16 Count = 0;
    UINTN MemDescSize;
    EFI_MEMORY_DESCRIPTOR *MemMap;
    EFI_MEMORY_DESCRIPTOR *mm;
    UINTN MemEntriesCount;
    UINTN i;
    E820_ENTRY *E820Entry = e820_entry;
    E820_MEMORY_TYPE MemType;
    UINT32                  EbdaAddress;
    BDA_DATA                *bda;

    GetSystemMemoryMap(&MemMap, &MemDescSize, &MemEntriesCount);

    bda = (BDA_DATA*)((UINTN) 0x400);   // 40:0

    EbdaAddress = (bda->ext_bios_data_seg)<<4; // 40:0e
    //
    // Start creating E820 table entries
    //
    InsertE820Entry(&E820Entry, 0,  (640 - ((UINT8)((0xA0000 - EbdaAddress) >> 10)) )<< 10, MemRangeAvl, &Count);
    InsertE820Entry(&E820Entry, (640 - ((UINT8)((0xA0000 - EbdaAddress) >> 10)) ) << 10, ((UINT8)((0xA0000 - EbdaAddress) >> 10)) << 10, MemRangeRes, &Count);
    InsertE820Entry(&E820Entry, 0xE0000, 0x20000, MemRangeRes, &Count);     // E0000..FFFFF
    //
    // Insert entries according to memory map; EFI memory types are mapped to ACPI address
    // range types according to ACPI 3.0 Specification, Chapter 14.3.
    //
    for (mm = MemMap, i = 0; i < MemEntriesCount; i++, mm=(EFI_MEMORY_DESCRIPTOR*)((UINT8*)mm+MemDescSize)) {
        if (mm->PhysicalStart < 0x100000) continue; // skip low memory entries
        switch (mm->Type) {
            case EfiMemoryMappedIO:
                    if (!(mm->Attribute & EFI_MEMORY_RUNTIME)) continue;
            case EfiReservedMemoryType:
            case EfiRuntimeServicesCode:
            case EfiRuntimeServicesData:
            case EfiUnusableMemory:
            case EfiMemoryMappedIOPortSpace:
            case EfiPalCode:
                    MemType = MemRangeRes;
                    break;
            case EfiACPIReclaimMemory:
                    MemType = MemRangeAcpiReclaim;
                    break;
            case EfiACPIMemoryNVS:
                    MemType = MemRangeAcpiNVS;
                    break;
            default: MemType = MemRangeAvl;
        }
        InsertE820Entry(&E820Entry,
                        mm->PhysicalStart,
                        Shl64(mm->NumberOfPages, EFI_PAGE_SHIFT),
                        MemType,
                        &Count);
        if (Count == MAX_E820_ENTRIES) break;
    }
    pBS->FreePool(MemMap);
    return Count;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  CmosRW
//
// DESCRIPTION: CMOS access helper
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS CmosRW(
    BOOLEAN rw,
    UINT32 reg,
    UINT8 *data
)
{
    UINT32 reg_;
    UINT8 data_;
    EFI_STATUS Status;
    EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRB;

    Status = pBS->LocateProtocol (&gEfiPciRootBridgeIoProtocolGuid,
        NULL,
        &PciRB
    );
    ASSERT_EFI_ERROR(Status);
    if (EFI_ERROR (Status)) return Status;

    reg_ = reg;

    PciRB->Io.Write (PciRB, EfiPciWidthUint8, 0x70, 1, &reg_);  // Set index

    if (rw) {   // read
        PciRB->Io.Read (PciRB, EfiPciWidthUint8, 0x71, 1, &data_);
        *data = data_;
    } else {        // write
        data_ = *data;
        PciRB->Io.Write (PciRB, EfiPciWidthUint8, 0x71, 1, &data_);
    }
    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:    UpdateCmos
//
// DESCRIPTION: This function updates CMOS before booting to Legacy OS
//
// NOTE:        This function enables NMI
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS UpdateCmos()
{
//  UINT8 reg;
    UINT8 data;
    //
    // Clear bits 0..3 on the CMOS ofs 0xE
    //
    CmosRW(TRUE, 0xE, &data);   // Read register E
    data &= 0xF0;
    CmosRW(FALSE, 0xE, &data);

    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  NmiToBeEnabled
//
// DESCRIPTION: This function returns the current selection of NMI to be
//              enabled/disabled.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

BOOLEAN NmiToBeEnabled()
{
    return TRUE;    // TODO::Currently hardcoded, could be setup driven
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// FUNCTION:  EnableDisableNmi
//
// DESCRIPTION: This function enables or disables NMI according to setup
//              question.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
EnableDisableNmi()
{
    UINT16 data16;
    UINT8 data8;
    EFI_STATUS Status;
    EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRB;

    Status = pBS->LocateProtocol (&gEfiPciRootBridgeIoProtocolGuid,
        NULL,
        &PciRB
    );
    ASSERT_EFI_ERROR(Status);
    if (EFI_ERROR (Status)) return Status;

    //
    // Update IO reg 61h - NMI_SC-NMI Status and Control Register
    //
    PciRB->Io.Read (PciRB, EfiPciWidthUint8, 0x61, 1, &data8);
    data8 &= 0xF3;
    data16 = NmiToBeEnabled()? 0xD : 0xC8D;
    data8 |= (data16 >> 8);
    PciRB->Io.Write (PciRB, EfiPciWidthUint8, 0x61, 1, &data8);
    //
    // Update IO reg 70h - NMI_EN-NMI Enable(and Real Time Clock Index)
    //
    data8 = (UINT8)data16;
    PciRB->Io.Write (PciRB, EfiPciWidthUint8, 0x70, 1, &data8);

    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//------------------------------------------------------------------------------------
//
//  Name:       UpdatePciLastBusCallback
//
// Description: This callback function then will process the list of root bridges
//              and will update the LastPciBus field of EFI_COMPATIBILITY16_TABLE
//              accordingly.
//
//------------------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
UpdatePciLastBusCallback (
    IN EFI_EVENT        Event,
    IN VOID             *Context
)
{
    EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL   *RBProtocol;
    ASLR_QWORD_ASD      *Descriptors;
    UINTN               Count=0,i=0;
    EFI_HANDLE          *Buffer;
    UINT8               MaxBus=0;
    EFI_STATUS          Status;

    LEGACY16_TO_EFI_DATA_TABLE_EXT *Csm16Data;
    UINT8               *NextRootBridgeBus;
    UINT8               CsmRbCount = 0;
    BOOLEAN             Csm16Is75Plus;
    //
    // UnLock E000 and F000 segments
    //
    Status = CoreBiosInfo->iRegion->UnLock (
             CoreBiosInfo->iRegion,
             (UINT32)0xe0000,
             (UINT32)0x20000,
             NULL
             );
    ASSERT_EFI_ERROR(Status);

    //
    //Locate the RootBridge protocol
    //
    Status = pBS->LocateHandleBuffer (
                  ByProtocol,
                  &gEfiPciRootBridgeIoProtocolGuid,
                  NULL,
                  &Count,
                  &Buffer
                  );
    ASSERT_EFI_ERROR(Status);
    if (EFI_ERROR(Status)) return;

    Csm16Is75Plus = *(UINT8*)0xf0019 > 0x75;   // CSM version 76 or later

    if (Csm16Is75Plus) {
        Csm16Data = (LEGACY16_TO_EFI_DATA_TABLE_EXT*)(UINTN)(0xf0000 + *(UINT16*)0xfff4c);
        NextRootBridgeBus = (UINT8*)((UINTN)Csm16Data->RbMinBusArrayOfs + 0xf0000);
    }

    for (i = 0; i < Count; i++) {
        Status = pBS->HandleProtocol (
                    Buffer[i],
                    &gEfiPciRootBridgeIoProtocolGuid,
                    &RBProtocol
                    );

        if (EFI_ERROR(Status)) continue;
        //
        // Get the Configuration
        //
        RBProtocol->Configuration(
                  RBProtocol,
                  &Descriptors
                  );

        if ((Descriptors)->Hdr.HDR != ASLV_END_TAG_HDR) {
            //
            // go till we get the Resource type = Bus Number range
            //
            while (Descriptors->Hdr.HDR != ASLV_END_TAG_HDR) {

                if (Descriptors->Type == ASLRV_SPC_TYPE_BUS) {
                    //
                    // We got the type;update the LastPCiBus of csm16header
                    //
                    if (Csm16Is75Plus) {
                        if (++CsmRbCount < Csm16Data->RbArrayCount) {
                            *NextRootBridgeBus++ = (UINT8)Descriptors->_MIN;
                        }
                    }
                    if((UINT8)Descriptors->_MAX > MaxBus ) {
                        MaxBus =(UINT8)Descriptors->_MAX;
                    }
                }
                Descriptors++;
            }
        }
    }

    // Update Pci Last Bus in Csm16 header
    // Note: do not report FF; this is XP limitation, EIP#24852
    CoreBiosInfo->Csm16Header->LastPciBus = (MaxBus == 0xff)? 0xfe : MaxBus;

    // Update CSM16 header checksum as LastPciBus field of it has been changed
    ChecksumCSM16Header(CoreBiosInfo->Csm16Header);

    // Look for _32_ structure and update offset 16 (0x10) with the MaxBus
    {
        UINTN Adr = 0xe0000;

        TRACE((-1,"CSM - Attempting to update RT32 binary with the MaxBus (0x%x)\n", MaxBus));

        for (; Adr < 0x100000; Adr += 0x10) {
            if (*(UINT32*)Adr == 0x5f32335f) {
                // found '_32_', verify checksum
                UINT8 i;
                UINT8 CheckSum = 0;
                TRACE((-1,"_32_ signature is found at %x,", Adr));
                for (i=0; i<0x10; i++) {
                    CheckSum += *((UINT8*)Adr+i);
                }
                if (CheckSum == 0) {
                    TRACE((-1,"checksum is OK\n"));
                    *((UINT8*)Adr+0x10) = MaxBus;
                }
                else {
                    TRACE((-1,"checksum is invalid.\n"));
                }
            }
        }
    }
    
    //
    // Lock E000 and F000 segments
    //
    Status = CoreBiosInfo->iRegion->Lock (
            CoreBiosInfo->iRegion,
            (UINT32)0xe0000,
            (UINT32)0x20000,
            NULL
            );
    ASSERT_EFI_ERROR (Status);

    // Close event, this function is to be executed once.
    if (Event != NULL) {
        pBS->CloseEvent(Event);
    }
}

/**
 * Goes through memory map looking for the requested memory block within 1MB..2GB range
 * 
 * @param[in] MemDesc   Starting memory descriptor of the memory map
 * @param[in] MemEntriesCount   Count of the memory map entries
 * @param[in] MemDescSize       Size of the memory descriptor
 * @param[in] DesiredBlockSize  Number of pages requested to be found
 * @param[out] MemAddress       Found memory block
 * @param[out] NumberOfPages    Found memory block size
 * @retval EFI_SUCCESS          Memory block is found
 * @retval EFI_NOT_FOUND        Memory block is not found
 */
EFI_STATUS FindMemoryBlockForHiPmm(
    EFI_MEMORY_DESCRIPTOR *MemMap,
    UINTN MemEntriesCount,
    UINTN MemDescSize,
    UINTN DesiredBlockSize,
    EFI_PHYSICAL_ADDRESS *MemAddress,
    UINT64 *NumberOfPages
)
{
    EFI_MEMORY_DESCRIPTOR *mm;
    UINTN count = 0;
    
    for (mm = MemMap; count < MemEntriesCount; mm=(EFI_MEMORY_DESCRIPTOR*)((UINT8*)mm+MemDescSize), count++) {
        if (mm->PhysicalStart < 0x100000) continue; // skip low memory entries
        // Skip above 2GB memory entries:
        // CORE0292.1 - value above 2GB will be assumed a negative number in find_free_memory algorithm
        if (mm->PhysicalStart > 0x7fffffff) continue; 

        if (mm->Type == EfiConventionalMemory && (mm->NumberOfPages >= DesiredBlockSize))
        {
            *MemAddress = mm->PhysicalStart;
            *NumberOfPages = mm->NumberOfPages;
            break;
        }
    }

    return (count == MemEntriesCount)? EFI_NOT_FOUND : EFI_SUCCESS;
}

/**
  Allocates the memory at 1MB..2GB that can be used for high memory PMM allocations.

  This EfiBootServicesData memory block should be outside the "main" BS memory
  so that it can be freed during READY_TO_BOOT. For that we go through EFI memory
  map looking for unallocated region of a given size.

  @param[in]    BlockSize     The number of pages to be allocated.
  @param[out]   BlockAddr     The address of the allocated block.

  @retval EFI_SUCCESS   Memory block is allocated.
  @retval Error Value   Memory can not be allocated.

*/
EFI_STATUS AllocateHiMemPmmBlock(
    IN  UINTN   BlockSize,
    OUT UINTN   *BlockAddr
)
{
    UINTN MemDescSize;
    EFI_MEMORY_DESCRIPTOR *MemMap;
    EFI_MEMORY_DESCRIPTOR *mm;
    UINTN count = 0;
    UINTN MemEntriesCount;
    EFI_PHYSICAL_ADDRESS HiPmmMemory;
    EFI_STATUS Status;
    UINT64 NumberOfPages;
    UINT64 BlockLength;
    
    GetSystemMemoryMap(&MemMap, &MemDescSize, &MemEntriesCount);

    // print memory map
    for (mm = MemMap; count < MemEntriesCount; mm=(EFI_MEMORY_DESCRIPTOR*)((UINT8*)mm+MemDescSize), count++) {
        TRACE((-1, "%02d: %08x, %05x, ", count, mm->PhysicalStart, mm->NumberOfPages));
        switch (mm->Type) {
            case EfiReservedMemoryType: TRACE((-1, "EfiReservedMemoryType\n")); break;
            case EfiLoaderCode: TRACE((-1, "EfiLoaderCode\n")); break;
            case EfiLoaderData: TRACE((-1, "EfiLoaderData\n")); break;
            case EfiBootServicesCode: TRACE((-1, "EfiBootServicesCode\n")); break;
            case EfiBootServicesData: TRACE((-1, "EfiBootServicesData\n")); break;
            case EfiRuntimeServicesCode: TRACE((-1, "EfiRuntimeServicesCode\n")); break;
            case EfiRuntimeServicesData: TRACE((-1, "EfiRuntimeServicesData\n")); break;
            case EfiConventionalMemory: TRACE((-1, "EfiConventionalMemory\n")); break;
            case EfiUnusableMemory: TRACE((-1, "EfiUnusableMemory\n")); break;
            case EfiACPIReclaimMemory: TRACE((-1, "EfiACPIReclaimMemory\n")); break;
            case EfiACPIMemoryNVS: TRACE((-1, "EfiACPIMemoryNVS\n")); break;
            case EfiMemoryMappedIO: TRACE((-1, "EfiMemoryMappedIO\n")); break;
            case EfiMemoryMappedIOPortSpace: TRACE((-1, "EfiMemoryMappedIOPortSpace\n")); break;
            case EfiPalCode: TRACE((-1, "EfiPalCode\n")); break;
            default: TRACE((-1, "%x\n", mm->Type));
        }
    }

    // Try to allocate Size*4 block and use the middle of it; if not found, then try to allocate Size*2
    // and use the end
    Status = FindMemoryBlockForHiPmm(MemMap, MemEntriesCount, MemDescSize, BlockSize*4, &HiPmmMemory, &NumberOfPages);
    if (!EFI_ERROR(Status)) {
        BlockLength = Shl64(NumberOfPages, 11); // Middle of the block
    } else {
        Status = FindMemoryBlockForHiPmm(MemMap, MemEntriesCount, MemDescSize, BlockSize*2, &HiPmmMemory, &NumberOfPages);
        BlockLength = Shl64(NumberOfPages, 12); // End of the block
    }

    pBS->FreePool(MemMap);
    
    if (EFI_ERROR(Status)) return Status;
        
    HiPmmMemory += BlockLength;

    Status = pBS->AllocatePages(AllocateMaxAddress, EfiBootServicesData, BlockSize*2, &HiPmmMemory);
    *BlockAddr = (UINTN)HiPmmMemory;

    return Status;
}

// TODO: The following definition is from DebugLib.h; currently it can not be included
// as it clashes with AmiDxeLib.h definitions
#define DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED       0x08
BOOLEAN
ClearMemoryEnabled (
  VOID
  )
{
  // In AptioV this feature is controlled by DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugPropertyMask
  // In Aptio4 this is project specific. By default we will return TRUE
  return TRUE;
}

/**
  READY_TO_BOOT notification callback that frees high memory PMM allocations.
  
  Hi memory PMM is a double buffer. First half is a real PMM memory, second half is
  a backup. Before freeing make a backup copy, then free the first block, then restore
  memory, then free the backup block. This is done to prevent clearing memory while
  executing FreePages.
  Note: double buffering is only needed when DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED is 
  set in PcdDebugPropertyMask.
*/
VOID  FreePmmBeforeBoot (  
    IN EFI_EVENT            Event,
    IN VOID                 *Context
)
{
    EFI_STATUS Status;
    UINTN   NumberOfPages = (CoreBiosInfo->Thunk->Csm16InitTable.HiPmmMemorySizeInBytes >> 12) + 1;
    UINTN   Size = NumberOfPages << 12;
    UINTN   Address = CoreBiosInfo->Thunk->Csm16InitTable.HiPmmMemory;

    if (Address != 0)
    {
        if (ClearMemoryEnabled ())
        {
            pBS->CopyMem((VOID*)(Address+Size), (VOID*)Address, Size);
            Status = pBS->FreePages(Address, NumberOfPages);
            ASSERT_EFI_ERROR(Status);
            pBS->CopyMem((VOID*)Address, (VOID*)(Address+Size), Size);
            Status = pBS->FreePages(Address+Size, NumberOfPages);
            ASSERT_EFI_ERROR(Status);
        }
        else 
        {
            Status = pBS->FreePages(Address, NumberOfPages*2);
            ASSERT_EFI_ERROR(Status);
        }
        TRACE((-1, "Free HI PMM memory: %r\n", Status));
    }
    pBS->CloseEvent(Event);
}

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