summaryrefslogtreecommitdiff
path: root/Core/EM/Recovery/IdeRecovery.c
blob: 8ece24c934974e33453a03bedd909c106bea0e25 (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
//**********************************************************************
//**********************************************************************
//**                                                                  **
//**        (C)Copyright 1985-2011, American Megatrends, Inc.         **
//**                                                                  **
//**                       All Rights Reserved.                       **
//**                                                                  **
//**      5555 Oakbrook Parkway, Suite 200, Norcross, GA 30093        **
//**                                                                  **
//**                       Phone: (770)-246-8600                      **
//**                                                                  **
//**********************************************************************
//**********************************************************************
//**********************************************************************
// $Header: /Alaska/SOURCE/Core/Modules/Recovery/IdeRecovery.c 15    4/02/12 12:54a Srilathasc $
//
// $Revision: 15 $
//
// $Date: 4/02/12 12:54a $
//**********************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Core/Modules/Recovery/IdeRecovery.c $
// 
// 15    4/02/12 12:54a Srilathasc
// [TAG]  		EIP81405
// [Category]  	Bug Fix
// [Symptom]  	Recovery mode did not work in hard disk
// [RootCause]  	Sufficient timeout to wait for DRQ was not given after
// command was written in AtaPioDataIn()
// [Solution]  	Increase the TIMEOUT to 10 seconds after the command is
// complete 
// 
// [Files]  		IdeRecovery.c
// 
// 14    2/21/12 5:04a Rameshr
// [TAG]  		EIP75596
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Boot to recovery mode without media in the CD drive.First
// time it will fail and next time while inserting Media , still recovery
// not success from CD.
// [RootCause]  	Atapi_DetectMedia will get called and irrespective of
// device status LookedForMedia flag getting updated
// [Solution]  	LookedForMedia flag updated only when the success
// detection of Media in the ODD
// [Files]  		IdeRecovery.c
// 
// 13    7/07/11 3:20a Lavanyap
// [TAG]  		EIP59029 
// [Category]  	Bug Fix
// [Symptom]  	Recovery failed in IDE mode in VIA platform.
// [RootCause]  	BSY/DRQ status checking was not done on the right port.
// [Solution]  	Select the proper device before checking the device
// status.
// [Files]  		IdeRecovery.c
// 
// 12    5/04/11 12:20p Artems
// Bug fix: rollback previous check-in changes
// 
// 11    2/14/11 4:06p Yul
// [TAG]  		EIP38288
// [Category]  	Enhanced
// [Description]  	Klocwork Issues II - Recovery
// 
// 10    1/07/10 12:01p Robert
// In Ata_ReadSectors()  Change the SectorCount variable to UINT16,
// removed the typecasting when setting this variable and added a
// typecasting to UINT8 when call the AtaPioDataIn()
// Removed previous changes for clearer functionality
// 
// 9     1/05/10 12:13p Robert
// in Ata_ReadSectors() if the need arises to call AtaPioDataIn with
// SectorCount == MaxBlock, no data was ever read.  A special case had to
// be created to handle the case when SectorCount == MaxBlock.
// Refer to EIP #33174 for more details
// 
// 8     7/01/09 4:19p Rameshr
// Coding Standard and File header updated.
//
// 7     3/04/09 1:32p Felixp
// Address in the file header is updated.
//
// 6     2/26/09 5:38p Felixp
// File header is updated (no code changes).
//
//**********************************************************************
//<AMI_FHDR_START>
//
// Name:	IdeRecovery.c
//
// Description:	IDE Recovery Implementation
//
//<AMI_FHDR_END>
//**********************************************************************

//<AMI_FHDR_START>
//----------------------------------------------------------------------
//
// Name: IdeRecovery.c - PEI driver
//
// Description:	Implements EFI_PEI_RECOVERY_BLOCK_IO_PPI for ATA and ATAPI devices.
//
//----------------------------------------------------------------------
//<AMI_FHDR_END>

#include <PEI.h>
#include <AmiPeiLib.h> 
#include <AmiLib.h> 
#include <Ppi\DeviceRecoveryBlockIo.h>
#include <Ppi\Stall.h>
#include <Protocol\BlockIo.h>
#include <Ppi\AtaController.h>


EFI_GUID gPeiStallPpiGuid              = EFI_PEI_STALL_PPI_GUID;
EFI_GUID gPeiAtaControllerPpiGuid      = PEI_ATA_CONTROLLER_PPI_GUID;
EFI_GUID gPeiBlockIoPpiGuid            = EFI_PEI_VIRTUAL_BLOCK_IO_PPI;
EFI_GUID gIdeRecoveryNativeModePpiGuid = PEI_IDE_RECOVERY_NATIVE_MODE_PPI_GUID;

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

//Atapi command definitions

#define EFI_MIN( a, b )       (((a) < (b)) ? (a) : (b))

#define ATAPI_SIGNATURE 0xEB14

#define CD_ROM_DEVICE 0x5

#define SK_NO_SENSE 0
#define SK_NOT_READY    2
#define SK_UNIT_ATTENTION   6

#define MAX_SENSE_KEY_COUNT 6

#pragma pack(1)

typedef struct
{
    UINT16 GeneralConfiguration_0;
    UINT16 Data_1_58[58];
    UINT32 TotalUserAddressableSectors_60;
    UINT16 Data_61_255[195];
} ATA_IDENTIFY_DATA;

typedef struct
{
    UINT8 PeripheralDeviceType_0 : 5;
    UINT8 Reserved_0             : 3;
    UINT8 Data_1_95[95];
} INQUIRY_DATA;

typedef struct
{
    UINT8 Data_0_1[2];
    UINT8 SenseKey_2 : 4;
    UINT8 Data_2     : 4;
    UINT8 Data_3_6[4];
    UINT8 AdditionalSenseLength_7;
    UINT8 Data_8_11[4];
    UINT8 AdditionalSenseCode_12;
    UINT8 AdditionalSenseCodeQualifier_13;
    UINT8 Data_14_17[4];
} REQUEST_SENSE_DATA;

typedef struct
{
    UINT8 LastLba0;
    UINT8 LastLba1;
    UINT8 LastLba2;
    UINT8 LastLba3;
    UINT8 BlockSize3;
    UINT8 BlockSize2;
    UINT8 BlockSize1;
    UINT8 BlockSize0;
} READ_CAPACITY_DATA;

#pragma pack()

#define PACKET_CMD                0xA0
#define ATA_IDENTIFY_DEVICE_CMD     0xEC
#define ATA_READ_SECTOR_CMD       0x20

#pragma pack(1)

typedef struct
{
    UINT8 OperationCode_0;
    UINT8 Data_1_3[3];
    UINT8 AllocationLength_4;
    UINT8 Data_5_11[7];
} GENERIC_CMD;

typedef struct
{
    UINT8 OperationCode_0;
    UINT8 Data_1;
    UINT8 Lba0;
    UINT8 Lba1;
    UINT8 Lba2;
    UINT8 Lba3;
    UINT8 Data_6;
    UINT8 TransferLengthMSB;
    UINT8 TransferLengthLSB;
    UINT8 Data_9_11[3];
} READ10_CMD;

typedef union
{
    UINT16      Data16[6];
    GENERIC_CMD Cmd;
    READ10_CMD  Read10;
} ATAPI_PACKET_COMMAND;

#pragma pack()

#define TEST_UNIT_READY       0x00
#define REQUEST_SENSE         0x03
#define INQUIRY               0x12
#define READ_CAPACITY         0x25
#define READ_10               0x28

#define DEFAULT_CTL           (0x0a)  // default content of device control register, disable INT
#define DEFAULT_CMD           (0xa0)

#define MAX_ATAPI_BYTE_COUNT  (0xfffe)

#pragma pack(1)

// IDE registers bit definitions

// Err Reg
#define ABRT_ERR  BIT02 //  Aborted Command


// Device/Head Reg
#define LBA_MODE  BIT06

// Status Reg
#define BSY   BIT07 // Controller Busy
#define DRDY  BIT06 // Drive Ready
#define DWF   BIT05 // Drive Write Fault
#define DRQ   BIT03 // Data Request
#define CORR  BIT02 // Corrected Data
#define ERR   BIT00 // Error

#pragma pack()

#define STALL_1_MILLI_SECOND  1000  // stall 1 ms

#define TIMEOUT  1000  // 1 second
#define COMMAND_COMPLETE_TIMEOUT 10000  // 10 seconds
#define LONGTIMEOUT  5000  // 5 seconds

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

typedef enum {
    EnumerateAtapi, EnumerateAta
} ENUMERATE_TYPE;
typedef enum {
    IdeLegacy, IdeNative, IdeMaxMode
} EFI_IDE_MODE;
typedef enum {
    IdePrimary, IdeSecondary, IdeMaxChannel
} EFI_IDE_CHANNEL;
typedef enum {
    IdeMaster, IdeSlave, IdeMaxDevice
} EFI_IDE_DEVICE;

// IDE Registers
typedef union
{
    UINT16 Command;       // when write
    UINT16 Status;        // when read
} IDE_CMD_OR_STATUS;

typedef union
{
    UINT16 Error;         // when read
    UINT16 Feature;       // when write
} IDE_ERROR_OR_FEATURE;

typedef union
{
    UINT16 AltStatus;     // when read
    UINT16 DeviceControl; // when write
} IDE_AltStatus_OR_DeviceControl;


// IDE registers set
typedef struct
{
    UINT16               Data;
    IDE_ERROR_OR_FEATURE Reg1;
    UINT16               SectorCount;
    UINT16               SectorNumber;
    UINT16               CylinderLsb;
    UINT16               CylinderMsb;
    UINT16               Head;
    IDE_CMD_OR_STATUS    Reg;

    IDE_AltStatus_OR_DeviceControl Alt;
    UINT16                         DriveAddress;
} IDE_BASE_REGISTERS;

typedef struct
{
    UINT8                  Device;
    BOOLEAN                LookedForMedia;
    IDE_BASE_REGISTERS     *IdeIoPortRegisters;
    EFI_PEI_BLOCK_IO_MEDIA MediaInfo;
} IDE_RECOVERY_DEVICE_INFO;

#define MAX_DEVICE_COUNT    8

typedef struct
{
    EFI_PEI_RECOVERY_BLOCK_IO_PPI RecoveryBlkIo;

    BOOLEAN                  HaveEnumeratedDevices;
    UINTN                    DeviceCount;
    IDE_RECOVERY_DEVICE_INFO *DeviceInfo[MAX_DEVICE_COUNT];
} IDE_RECOVERY_BLK_IO_DEV;

// IDE registers' fixed address
IDE_BASE_REGISTERS PrimaryChannelLegacyIdeIoPortRegisters = {
    0x1f0, 0x1f1, 0x1f2, 0x1f3, 0x1f4, 0x1f5, 0x1f6, 0x1f7, 0x3f6, 0x3f7
};

IDE_BASE_REGISTERS SecondaryChannelLegacyIdeIoPortRegisters = {
    0x170, 0x171, 0x172, 0x173, 0x174, 0x175, 0x176, 0x177, 0x376, 0x377
};

//AtaAtapiCommonInit should only be called once
BOOLEAN            gHaveCalledAtaAtapiCommonInit = FALSE;

BOOLEAN            gIdeRecoveryNativeModeSupport = FALSE;

IDE_BASE_REGISTERS PrimaryChannelNativeIdeIoPortRegisters = {
    0, 1, 2, 3, 4, 5, 6, 7,
    0, 1
};

IDE_BASE_REGISTERS SecondaryChannelNativeIdeIoPortRegisters = {
    0, 1, 2, 3, 4, 5, 6, 7,
    0, 1
};

IDE_BASE_REGISTERS *gNativeModePortRegsiters;
UINT8              gNativeIdeCount = 0;


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

// PEI Recovery Block I/O PPI

EFI_STATUS AtaAtapiCommonInit (
    IN EFI_PEI_SERVICES **PeiServices );

EFI_STATUS Atapi_GetNumberOfBlockDevices (
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    OUT UINTN                        *NumberBlockDevices );
EFI_STATUS Atapi_GetBlockDeviceMediaInfo (
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    OUT EFI_PEI_BLOCK_IO_MEDIA       *MediaInfo );
EFI_STATUS Atapi_ReadBlocks (
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    IN EFI_PEI_LBA                   StartLba,
    IN UINTN                         BufferSize,
    OUT VOID                         *Buffer );

EFI_STATUS Ata_GetNumberOfBlockDevices (
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    OUT UINTN                        *NumberBlockDevices );
EFI_STATUS Ata_GetBlockDeviceMediaInfo (
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    OUT EFI_PEI_BLOCK_IO_MEDIA       *MediaInfo );
EFI_STATUS Ata_ReadBlocks (
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    IN EFI_PEI_LBA                   StartLba,
    IN UINTN                         BufferSize,
    OUT VOID                         *Buffer );

// Private functions
VOID EnumerateDevices (
    IN OUT IDE_RECOVERY_BLK_IO_DEV *IdeRecoveryBlkIoDev,
    IN ENUMERATE_TYPE              EnumerateType );
BOOLEAN Atapi_DiscoverDevice (
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo );
BOOLEAN Ata_DiscoverDevice (
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo );

EFI_STATUS AtapiPacketCommandIn (
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    IN ATAPI_PACKET_COMMAND     *Packet,
    IN UINT16                   *Buffer,
    IN UINT32                   ByteCount,
    IN UINTN                    TimeoutInMilliSeconds );
EFI_STATUS Inquiry (
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo );
EFI_STATUS Atapi_DetectMedia (
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo );
EFI_STATUS TestUnitReady (
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo );
EFI_STATUS RequestSense (
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    OUT REQUEST_SENSE_DATA      *SenseBuffers,
    OUT UINT8                   *SenseCounts );
EFI_STATUS ReadCapacity (
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo );
EFI_STATUS Atapi_ReadSectors (
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    OUT VOID                    *Buffer,
    IN EFI_PEI_LBA              StartLba,
    IN UINTN                    NumberOfBlocks,
    IN UINTN                    BlockSize );

EFI_STATUS AtaPioDataIn (
    IN IDE_BASE_REGISTERS *IdeIoPortRegisters,
    OUT VOID              *Buffer,
    IN UINT32             ByteCount,
    IN UINT8              SectorCount,
    IN UINT8              SectorNumber,
    IN UINT8              CylinderLsb,
    IN UINT8              CylinderMsb,
    IN UINT8              Device,
    IN UINT8              Command );
EFI_STATUS AtaIdentify (
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    OUT ATA_IDENTIFY_DATA       *AtaIdentifyData );
EFI_STATUS Ata_ReadSectors (
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    OUT VOID                    *Buffer,
    IN EFI_PEI_LBA              StartLba,
    IN UINTN                    NumberOfBlocks,
    IN UINTN                    BlockSize );

EFI_STATUS WaitForBitsToClear (
    IN UINT16 Register,
    IN UINT8  Bits,
    IN UINTN  TimeoutInMilliSeconds );
EFI_STATUS WaitForBSYClear (
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds );
EFI_STATUS DRQClear (
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds );
EFI_STATUS DRQClear2 (
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds );

EFI_STATUS DRQReadyHelper (
    IN UINT16 StatusRegister,
    IN UINT16 ErrorRegister,
    IN UINTN  TimeoutInMilliSeconds );
EFI_STATUS DRQReady (
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds );
EFI_STATUS DRQReady2 (
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds );

EFI_STATUS CheckErrorStatus (
    IN UINT16 StatusReg );

VOID ZeroMem (
    OUT VOID *Buffer,
    IN UINTN Size );

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

EFI_PEI_PPI_DESCRIPTOR   Atapi_PpiDescriptor = {
    (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
    &gPeiBlockIoPpiGuid,
    NULL
};

EFI_PEI_PPI_DESCRIPTOR   Ata_PpiDescriptor = {
    (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
    &gPeiBlockIoPpiGuid,
    NULL
};

static EFI_PEI_SERVICES  **gPeiServices = NULL;
static EFI_PEI_STALL_PPI *gStallPpi     = NULL;


//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_RecoveryPeimEntry
//
// Description:	Installs EFI_PEI_RECOVERY_BLOCK_IO_PPI for ATAPI devices.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Atapi_RecoveryPeimEntry(
    IN EFI_FFS_FILE_HEADER *FfsHeader,
    IN EFI_PEI_SERVICES    **PeiServices )
{
    EFI_STATUS              Status          = EFI_SUCCESS;
    IDE_RECOVERY_BLK_IO_DEV *Atapi_BlkIoDev = NULL;

    if ( !gPeiServices ) {
        gPeiServices = PeiServices;
    }

    Status = (**PeiServices).AllocatePool( PeiServices, sizeof(IDE_RECOVERY_BLK_IO_DEV), &Atapi_BlkIoDev );

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

    Atapi_BlkIoDev->HaveEnumeratedDevices = FALSE;
    Atapi_BlkIoDev->DeviceCount           = 0;

    Atapi_BlkIoDev->RecoveryBlkIo.GetNumberOfBlockDevices = Atapi_GetNumberOfBlockDevices;
    Atapi_BlkIoDev->RecoveryBlkIo.GetBlockDeviceMediaInfo = Atapi_GetBlockDeviceMediaInfo;
    Atapi_BlkIoDev->RecoveryBlkIo.ReadBlocks              = Atapi_ReadBlocks;
    Atapi_PpiDescriptor.Ppi = &Atapi_BlkIoDev->RecoveryBlkIo;

    Status = (**PeiServices).InstallPpi( PeiServices, &Atapi_PpiDescriptor );

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

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Ata_RecoveryPeimEntry
//
// Description:	Installs EFI_PEI_RECOVERY_BLOCK_IO_PPI for ATA devices.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Ata_RecoveryPeimEntry(
    IN EFI_FFS_FILE_HEADER *FfsHeader,
    IN EFI_PEI_SERVICES    **PeiServices )
{
    EFI_STATUS              Status        = EFI_SUCCESS;
    IDE_RECOVERY_BLK_IO_DEV *Ata_BlkIoDev = NULL;

    if ( !gPeiServices ) {
        gPeiServices = PeiServices;
    }

    Status = (**PeiServices).AllocatePool( PeiServices, sizeof(IDE_RECOVERY_BLK_IO_DEV), &Ata_BlkIoDev );

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

    Ata_BlkIoDev->HaveEnumeratedDevices = FALSE;
    Ata_BlkIoDev->DeviceCount           = 0;

    Ata_BlkIoDev->RecoveryBlkIo.GetNumberOfBlockDevices = Ata_GetNumberOfBlockDevices;
    Ata_BlkIoDev->RecoveryBlkIo.GetBlockDeviceMediaInfo = Ata_GetBlockDeviceMediaInfo;
    Ata_BlkIoDev->RecoveryBlkIo.ReadBlocks              = Ata_ReadBlocks;
    Ata_PpiDescriptor.Ppi = &Ata_BlkIoDev->RecoveryBlkIo;

    Status = (**PeiServices).InstallPpi( PeiServices, &Ata_PpiDescriptor );

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

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	AtaAtapiCommonInit
//
// Description:	Called by Atapi_RecoveryPeimEntry and Ata_RecoveryPeimEntry
//              functions. Initializes stuff, including
//              gIdeRecoveryNativeModeSupport,
//              PrimaryChannelNativeIdeIoPortRegisters,
//              SecondaryChannelNativeIdeIoPortRegisters.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS AtaAtapiCommonInit(
    IN EFI_PEI_SERVICES **PeiServices )
{
    EFI_STATUS                       Status                    = EFI_SUCCESS;
    EFI_STATUS                       LegacyStatus              = EFI_NOT_FOUND;
    PEI_ATA_CONTROLLER_PPI           *AtaControllerPpi         = NULL;
    PEI_IDE_RECOVERY_NATIVE_MODE_PPI *IdeRecoveryNativeModePpi = NULL;
    UINT8 i     = 0;
    UINT8 Index = 0;


    Status = (**PeiServices).LocatePpi( PeiServices, &gPeiStallPpiGuid, 0, NULL, &gStallPpi );

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

    Status = (**PeiServices).LocatePpi( PeiServices, &gPeiAtaControllerPpiGuid, 0, NULL, &AtaControllerPpi );

    if ( !(EFI_ERROR( Status ))) {
        LegacyStatus = AtaControllerPpi->EnableAtaChannel( PeiServices, AtaControllerPpi, PEI_ICH_IDE_PRIMARY | PEI_ICH_IDE_SECONDARY );
    }

    //
    //Find Number of Native mode IDE ppi installed
    //
    Index = 0;

    do
    {
        Status = (**PeiServices).LocatePpi( PeiServices, &gIdeRecoveryNativeModePpiGuid, Index, NULL, &IdeRecoveryNativeModePpi );

        if ( !(EFI_ERROR( Status ))) {
            Index++;
            gNativeIdeCount++;
        }
    } while ( Status == EFI_SUCCESS );

    //
    //if Legacy mode init fails and if there is no native PPI return with error.
    //
    if ((gNativeIdeCount == 00) && (LegacyStatus != EFI_SUCCESS)) {
        return EFI_UNSUPPORTED;
    }

    Status = (**PeiServices).AllocatePool( PeiServices, sizeof(IDE_BASE_REGISTERS) * 2 * gNativeIdeCount, &gNativeModePortRegsiters );

    //
    //Fill the base address values in gNativeModePortRegsiters
    //
    Index = 0;

    do
    {
        Status = (**PeiServices).LocatePpi( PeiServices, &gIdeRecoveryNativeModePpiGuid, Index, NULL, &IdeRecoveryNativeModePpi );

        if ( !(EFI_ERROR( Status ))) {
            gIdeRecoveryNativeModeSupport             = TRUE;
            gNativeModePortRegsiters[i].Data          = PrimaryChannelNativeIdeIoPortRegisters.Data + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].Reg1.Error    = PrimaryChannelNativeIdeIoPortRegisters.Reg1.Error + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].SectorCount   = PrimaryChannelNativeIdeIoPortRegisters.SectorCount + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].SectorNumber  = PrimaryChannelNativeIdeIoPortRegisters.SectorNumber + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].CylinderLsb   = PrimaryChannelNativeIdeIoPortRegisters.CylinderLsb + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].CylinderMsb   = PrimaryChannelNativeIdeIoPortRegisters.CylinderMsb + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].Head          = PrimaryChannelNativeIdeIoPortRegisters.Head + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].Reg.Command   = PrimaryChannelNativeIdeIoPortRegisters.Reg.Command + IdeRecoveryNativeModePpi->PCMDBarAddress;
            gNativeModePortRegsiters[i].Alt.AltStatus = PrimaryChannelNativeIdeIoPortRegisters.Alt.AltStatus + IdeRecoveryNativeModePpi->PCNLBarAddress;
            gNativeModePortRegsiters[i].DriveAddress  = PrimaryChannelNativeIdeIoPortRegisters.DriveAddress + IdeRecoveryNativeModePpi->PCNLBarAddress;

            gNativeModePortRegsiters[i + 1].Data          = SecondaryChannelNativeIdeIoPortRegisters.Data + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].Reg1.Error    = SecondaryChannelNativeIdeIoPortRegisters.Reg1.Error + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].SectorCount   = SecondaryChannelNativeIdeIoPortRegisters.SectorCount + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].SectorNumber  = SecondaryChannelNativeIdeIoPortRegisters.SectorNumber += IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].CylinderLsb   = SecondaryChannelNativeIdeIoPortRegisters.CylinderLsb + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].CylinderMsb   = SecondaryChannelNativeIdeIoPortRegisters.CylinderMsb + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].Head          = SecondaryChannelNativeIdeIoPortRegisters.Head + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].Reg.Command   = SecondaryChannelNativeIdeIoPortRegisters.Reg.Command + IdeRecoveryNativeModePpi->SCMDBarAddress;
            gNativeModePortRegsiters[i + 1].Alt.AltStatus = SecondaryChannelNativeIdeIoPortRegisters.Alt.AltStatus + IdeRecoveryNativeModePpi->SCNLBarAddress;
            gNativeModePortRegsiters[i + 1].DriveAddress  = SecondaryChannelNativeIdeIoPortRegisters.DriveAddress + IdeRecoveryNativeModePpi->SCNLBarAddress;
            i = i + 2;
            Index++;
        }
    } while ( Status == EFI_SUCCESS );

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_GetNumberOfBlockDevices
//
// Description:	GetNumberOfBlockDevices function of
//              EFI_PEI_RECOVERY_BLOCK_IO_PPI.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Atapi_GetNumberOfBlockDevices(
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    OUT UINTN                        *NumberBlockDevices )
{
    IDE_RECOVERY_BLK_IO_DEV *Atapi_BlkIoDev = NULL;

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

    Atapi_BlkIoDev = (IDE_RECOVERY_BLK_IO_DEV*)This;

    if ( !Atapi_BlkIoDev->HaveEnumeratedDevices ) {
        EnumerateDevices( Atapi_BlkIoDev, EnumerateAtapi );
        Atapi_BlkIoDev->HaveEnumeratedDevices = TRUE;
    }
    *NumberBlockDevices = Atapi_BlkIoDev->DeviceCount;

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_GetBlockDeviceMediaInfo
//
// Description:	GetBlockDeviceMediaInfo function of
//              EFI_PEI_RECOVERY_BLOCK_IO_PPI.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Atapi_GetBlockDeviceMediaInfo(
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    OUT EFI_PEI_BLOCK_IO_MEDIA       *MediaInfo )
{
    IDE_RECOVERY_BLK_IO_DEV *Atapi_BlkIoDev = NULL;
    EFI_STATUS              Status          = EFI_SUCCESS;

    if ((This == NULL) || (MediaInfo == NULL)) {
        return EFI_INVALID_PARAMETER;
    }

    Atapi_BlkIoDev = (IDE_RECOVERY_BLK_IO_DEV*)This;

    if ( !Atapi_BlkIoDev->HaveEnumeratedDevices ) {
        EnumerateDevices( Atapi_BlkIoDev, EnumerateAtapi );
        Atapi_BlkIoDev->HaveEnumeratedDevices = TRUE;
    }

    if ( DeviceIndex > (Atapi_BlkIoDev->DeviceCount - 1)) {
        return EFI_INVALID_PARAMETER;
    }

    if ( !Atapi_BlkIoDev->DeviceInfo[DeviceIndex]->LookedForMedia ) {
        Status = Atapi_DetectMedia( Atapi_BlkIoDev->DeviceInfo[DeviceIndex] );
        
        if ( Status != EFI_SUCCESS ) {
            return EFI_DEVICE_ERROR;
        }
        Atapi_BlkIoDev->DeviceInfo[DeviceIndex]->LookedForMedia = TRUE;
    }

    *MediaInfo = Atapi_BlkIoDev->DeviceInfo[DeviceIndex]->MediaInfo;

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_ReadBlocks
//
// Description:	ReadBlocks function of EFI_PEI_RECOVERY_BLOCK_IO_PPI.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Atapi_ReadBlocks(
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    IN EFI_PEI_LBA                   StartLba,
    IN UINTN                         BufferSize,
    OUT VOID                         *Buffer )
{
    EFI_PEI_BLOCK_IO_MEDIA  MediaInfo;
    EFI_STATUS              Status          = EFI_SUCCESS;
    UINTN                   NumberOfBlocks  = 0;
    UINTN                   BlockSize       = 0;
    IDE_RECOVERY_BLK_IO_DEV *Atapi_BlkIoDev = NULL;

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

    Atapi_BlkIoDev = (IDE_RECOVERY_BLK_IO_DEV*)This;

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

    if ( BufferSize == 0 ) {
        return EFI_SUCCESS;
    }

    if ( !Atapi_BlkIoDev->HaveEnumeratedDevices ) {
        EnumerateDevices( Atapi_BlkIoDev, EnumerateAtapi );
        Atapi_BlkIoDev->HaveEnumeratedDevices = TRUE;
    }

    if ( !Atapi_BlkIoDev->DeviceInfo[DeviceIndex]->LookedForMedia ) {
        Status = Atapi_GetBlockDeviceMediaInfo( PeiServices, This, DeviceIndex, &MediaInfo );

        if ( Status != EFI_SUCCESS ) {
            return Status;
        }
    } else {
        MediaInfo = Atapi_BlkIoDev->DeviceInfo[DeviceIndex]->MediaInfo;
    }

    BlockSize = MediaInfo.BlockSize;

    if ((BufferSize % BlockSize) != 0 ) {
        return EFI_INVALID_PARAMETER;
    }

    if ( !MediaInfo.MediaPresent ) {
        return EFI_NO_MEDIA;
    }

    NumberOfBlocks = BufferSize / BlockSize;

    Status = Atapi_ReadSectors(
        Atapi_BlkIoDev->DeviceInfo[DeviceIndex],
        Buffer,
        StartLba,
        NumberOfBlocks,
        BlockSize
        );

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Ata_GetNumberOfBlockDevices
//
// Description:	GetNumberOfBlockDevices function of
//              EFI_PEI_RECOVERY_BLOCK_IO_PPI.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Ata_GetNumberOfBlockDevices(
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    OUT UINTN                        *NumberBlockDevices )
{
    IDE_RECOVERY_BLK_IO_DEV *Ata_BlkIoDev = NULL;

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

    Ata_BlkIoDev = (IDE_RECOVERY_BLK_IO_DEV*)This;

    if ( !Ata_BlkIoDev->HaveEnumeratedDevices ) {
        EnumerateDevices( Ata_BlkIoDev, EnumerateAta );
        Ata_BlkIoDev->HaveEnumeratedDevices = TRUE;
    }
    *NumberBlockDevices = Ata_BlkIoDev->DeviceCount;

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Ata_GetBlockDeviceMediaInfo
//
// Description:	GetBlockDeviceMediaInfo function of
//              EFI_PEI_RECOVERY_BLOCK_IO_PPI.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Ata_GetBlockDeviceMediaInfo(
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    OUT EFI_PEI_BLOCK_IO_MEDIA       *MediaInfo )
{
    IDE_RECOVERY_BLK_IO_DEV *Ata_BlkIoDev          = NULL;
    EFI_STATUS              Status                 = EFI_SUCCESS;
    UINT8                   *Buffer                = NULL;
    UINT32                  SectorOfFirstPartition = 0;
    UINT16                  LowByte                = 0, HighByte = 0, BlockSize = 0;

    if ((This == NULL) || (MediaInfo == NULL)) {
        return EFI_INVALID_PARAMETER;
    }

    Ata_BlkIoDev = (IDE_RECOVERY_BLK_IO_DEV*)This;

    if ( !Ata_BlkIoDev->HaveEnumeratedDevices ) {
        EnumerateDevices( Ata_BlkIoDev, EnumerateAta );
        Ata_BlkIoDev->HaveEnumeratedDevices = TRUE;
    }

    if ( DeviceIndex > (Ata_BlkIoDev->DeviceCount - 1)) {
        return EFI_INVALID_PARAMETER;
    }

    if ( !Ata_BlkIoDev->DeviceInfo[DeviceIndex]->LookedForMedia ) {
        Ata_BlkIoDev->DeviceInfo[DeviceIndex]->LookedForMedia = TRUE;

    }

    *MediaInfo = Ata_BlkIoDev->DeviceInfo[DeviceIndex]->MediaInfo;

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Ata_ReadBlocks
//
// Description:	ReadBlocks function of EFI_PEI_RECOVERY_BLOCK_IO_PPI.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Ata_ReadBlocks(
    IN EFI_PEI_SERVICES              **PeiServices,
    IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This,
    IN UINTN                         DeviceIndex,
    IN EFI_PEI_LBA                   StartLba,
    IN UINTN                         BufferSize,
    OUT VOID                         *Buffer )
{
    EFI_PEI_BLOCK_IO_MEDIA  MediaInfo;
    EFI_STATUS              Status         = EFI_SUCCESS;
    UINTN                   NumberOfBlocks = 0;
    UINTN                   BlockSize      = 0;
    IDE_RECOVERY_BLK_IO_DEV *Ata_BlkIoDev  = NULL;

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

    Ata_BlkIoDev = (IDE_RECOVERY_BLK_IO_DEV*)This;

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

    if ( BufferSize == 0 ) {
        return EFI_SUCCESS;
    }

    if ( !Ata_BlkIoDev->HaveEnumeratedDevices ) {
        EnumerateDevices( Ata_BlkIoDev, EnumerateAta );
        Ata_BlkIoDev->HaveEnumeratedDevices = TRUE;
    }

    if ( !Ata_BlkIoDev->DeviceInfo[DeviceIndex]->LookedForMedia ) {
        Status = Ata_GetBlockDeviceMediaInfo(
                                    PeiServices,
                                    This,
                                    DeviceIndex,
                                    &MediaInfo
                                    );

        if ( Status != EFI_SUCCESS ) {
            return Status;
        }
    }  else {
        MediaInfo = Ata_BlkIoDev->DeviceInfo[DeviceIndex]->MediaInfo;
    }

    BlockSize = MediaInfo.BlockSize;

    if ( BufferSize % BlockSize != 0 ) {
        return EFI_INVALID_PARAMETER;
    }

    if ( !MediaInfo.MediaPresent ) {
        return EFI_NO_MEDIA;
    }

    NumberOfBlocks = BufferSize / BlockSize;

    if ( StartLba > MediaInfo.LastBlock ) {
        return EFI_INVALID_PARAMETER;
    }

    if ((StartLba + NumberOfBlocks) > (MediaInfo.LastBlock + 1)) {
        return EFI_INVALID_PARAMETER;
    }

    Status = Ata_ReadSectors(
                        Ata_BlkIoDev->DeviceInfo[DeviceIndex],
                        Buffer,
                        StartLba,
                        NumberOfBlocks,
                        BlockSize
                        );
    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	EnumerateDevices
//
// Description:	Enumerates Ata or Atapi devices.  Called by
//              Ata_GetNumberOfBlockDevices or
//              Atapi_GetNumberOfBlockDevices.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
VOID EnumerateDevices(
    IN IDE_RECOVERY_BLK_IO_DEV *IdeRecoveryBlkIoDev,
    ENUMERATE_TYPE             EnumerateType )
{
    EFI_STATUS               Status      = EFI_SUCCESS;
    UINT8                    MaxModes    = IdeMaxMode;
    EFI_IDE_MODE             Mode        = 0;
    UINT8                    Channel     = 0;
    UINT8                    Device      = 0;
    UINTN                    DeviceCount = 0;
    IDE_RECOVERY_DEVICE_INFO DeviceInfo;
    UINT8                    NativeIdeModeCount = 0;


    if ( !gHaveCalledAtaAtapiCommonInit ) {
        AtaAtapiCommonInit( gPeiServices );
        gHaveCalledAtaAtapiCommonInit = TRUE;
    }

    if ( gIdeRecoveryNativeModeSupport ) {
        //
        //Based on the number of Nativemode PPI maximum mode support is adjusted
        //
        MaxModes = IdeMaxMode + gNativeIdeCount - 1;
    }  else {
        MaxModes = IdeNative;
    }

    for ( Mode = IdeLegacy; Mode < MaxModes; Mode++ ) {
        for ( Channel = IdePrimary; Channel < IdeMaxChannel; Channel++ ) {
            for ( Device = IdeMaster; Device < IdeMaxDevice; Device++ ) {

                DeviceInfo.Device = Device;
                if ( Mode == IdeLegacy ) {
                    if ( Channel == IdePrimary ) {
                        DeviceInfo.IdeIoPortRegisters = &PrimaryChannelLegacyIdeIoPortRegisters;
                    } else { //IdeSecondary
                        DeviceInfo.IdeIoPortRegisters = &SecondaryChannelLegacyIdeIoPortRegisters;
                    }
                } else { //IdeNative
                    if ( Channel == IdePrimary ) {
                        DeviceInfo.IdeIoPortRegisters = &gNativeModePortRegsiters[NativeIdeModeCount];
                    } else { //IdeSecondary
                        DeviceInfo.IdeIoPortRegisters = &gNativeModePortRegsiters[NativeIdeModeCount + 1];
                    }
                }

                if ( EnumerateType == EnumerateAtapi ) {
                    if ( Atapi_DiscoverDevice( &DeviceInfo )) {
                        Status = (**gPeiServices).AllocatePool( gPeiServices, sizeof(IDE_RECOVERY_DEVICE_INFO), &(IdeRecoveryBlkIoDev->DeviceInfo[DeviceCount]));

                        if ( EFI_ERROR( Status )) {
                            return;
                        }
                        DeviceInfo.MediaInfo.MediaPresent                            = FALSE;
                        DeviceInfo.MediaInfo.LastBlock                               = 0;
                        DeviceInfo.LookedForMedia                                    = FALSE;
                        *(IdeRecoveryBlkIoDev->DeviceInfo[DeviceCount])              = DeviceInfo;
                        DeviceCount++;
                    }
                } else { 
                    //
                    //EnumerateAta
                    //
                    if ( Ata_DiscoverDevice( &DeviceInfo )) {
                        Status = (**gPeiServices).AllocatePool( gPeiServices, sizeof(IDE_RECOVERY_DEVICE_INFO), &(IdeRecoveryBlkIoDev->DeviceInfo[DeviceCount]));

                        if ( EFI_ERROR( Status )) {
                            return;
                        }
                        DeviceInfo.MediaInfo.MediaPresent                            = TRUE;
                        DeviceInfo.MediaInfo.BlockSize                               = 0x200;
                        DeviceInfo.LookedForMedia                                    = FALSE;
                        *(IdeRecoveryBlkIoDev->DeviceInfo[DeviceCount])              = DeviceInfo;
                        DeviceCount++;
                    }
                }
            }
        }

        if ( Mode == IdeNative ) {
            //
            //index to the Next native mode PPI base address
            //
            NativeIdeModeCount = NativeIdeModeCount + 2;
        }
    }

    IdeRecoveryBlkIoDev->DeviceCount = DeviceCount;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_DiscoverDevice
//
// Description:	Called by EnumerateDevices.  Looks for ATAPI_SIGNATURE.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
BOOLEAN Atapi_DiscoverDevice(
    IDE_RECOVERY_DEVICE_INFO *DeviceInfo )
{
    EFI_STATUS Status = EFI_SUCCESS;
    UINT8      Device      = DeviceInfo->Device;
    UINT16     HeadReg     = DeviceInfo->IdeIoPortRegisters->Head;
    UINT16     StatusReg   = DeviceInfo->IdeIoPortRegisters->Reg.Status;
    UINT16     CylinderLsb = DeviceInfo->IdeIoPortRegisters->CylinderLsb;
    UINT16     CylinderMsb = DeviceInfo->IdeIoPortRegisters->CylinderMsb;
    UINT8      StatusValue = 0;
    UINT8      Data8       = 0;

    //
    //	Select Device
    //
    IoWrite8( HeadReg, Device << 4 );
    StatusValue = IoRead8( StatusReg );

    if ((StatusValue == 0x7f) || (StatusValue == 0xff)) {
        return FALSE;
    }

    Status      = WaitForBSYClear( DeviceInfo->IdeIoPortRegisters, 31000 );
    StatusValue = IoRead8( StatusReg );

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

    Data8 = IoRead8( CylinderLsb );

    if ( Data8 == (ATAPI_SIGNATURE & 0xff)) {
        Data8 = IoRead8( CylinderMsb );

        if ( Data8 == (ATAPI_SIGNATURE >> 8)) {
            Status = Inquiry( DeviceInfo );

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

    return FALSE;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Ata_DiscoverDevice
//
// Description:	Called by EnumerateDevices.  Looks at IDENTIFY data.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
BOOLEAN Ata_DiscoverDevice(
    IDE_RECOVERY_DEVICE_INFO *DeviceInfo )
{
    EFI_STATUS        Status = EFI_SUCCESS;
    UINT8             Device      = DeviceInfo->Device;
    UINT16            HeadReg     = DeviceInfo->IdeIoPortRegisters->Head;
    UINT16            StatusReg   = DeviceInfo->IdeIoPortRegisters->Reg.Status;
    UINT16            CylinderLsb = DeviceInfo->IdeIoPortRegisters->CylinderLsb;
    UINT16            CylinderMsb = DeviceInfo->IdeIoPortRegisters->CylinderMsb;
    UINT8             StatusValue = 0;
    UINT8             Data8       = 0;

    ATA_IDENTIFY_DATA AtaIdentifyData;


    //
    //Select Device
    //
    IoWrite8( HeadReg, Device << 4 );
    StatusValue = IoRead8( StatusReg );

    if ((StatusValue == 0x7f) || (StatusValue == 0xff)) {
        return FALSE;
    }

    Status      = WaitForBSYClear( DeviceInfo->IdeIoPortRegisters, 31000 );
    StatusValue = IoRead8( StatusReg );

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

    Data8 = IoRead8( CylinderLsb );

    if ( Data8 == (ATAPI_SIGNATURE & 0xff)) {
        Data8 = IoRead8( CylinderMsb );

        if ( Data8 == (ATAPI_SIGNATURE >> 8)) {
            return FALSE;
        }
    }

    if ( AtaIdentify( DeviceInfo, &AtaIdentifyData ) == EFI_SUCCESS ) {
        if ((AtaIdentifyData.GeneralConfiguration_0 & 0x8000) == 0 ) {
            DeviceInfo->MediaInfo.DeviceType = MaxDeviceType;
            DeviceInfo->MediaInfo.LastBlock  = AtaIdentifyData.TotalUserAddressableSectors_60;
            return TRUE;
        }
    }

    return FALSE;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	AtapiPacketCommandIn
//
// Description:	Executes various ATAPI packet commands
//      (TEST_UNIT_READY, INQUIRY, REQUEST_SENSE, READ_CAPACITY, etc).
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS AtapiPacketCommandIn(
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    IN ATAPI_PACKET_COMMAND     *Packet,
    IN UINT16                   *Buffer,
    IN UINT32                   ByteCount,
    IN UINTN                    TimeoutInMilliSeconds )
{
    IDE_BASE_REGISTERS *IdeIoPortRegisters = DeviceInfo->IdeIoPortRegisters;

    UINT8              Device           = DeviceInfo->Device;
    UINT16             StatusReg        = IdeIoPortRegisters->Reg.Status;
    UINT16             HeadReg          = IdeIoPortRegisters->Head;
    UINT16             CommandReg       = IdeIoPortRegisters->Reg.Command;
    UINT16             FeatureReg       = IdeIoPortRegisters->Reg1.Feature;
    UINT16             CylinderLsbReg   = IdeIoPortRegisters->CylinderLsb;
    UINT16             CylinderMsbReg   = IdeIoPortRegisters->CylinderMsb;
    UINT16             DeviceControlReg = IdeIoPortRegisters->Alt.DeviceControl;
    UINT16             DataReg          = IdeIoPortRegisters->Data;
    EFI_STATUS         Status           = EFI_SUCCESS;
    UINT32             Count            = 0;
    UINT16             *CommandIndex    = NULL;
    UINT16             *ptrBuffer       = Buffer;
    UINT32             Index            = 0;
    UINT8              StatusValue      = 0;
    UINT32             WordCount        = 0;

    //
    // required transfer data in word unit.
    //
    UINT32             RequiredWordCount = 0;

    //
    // actual transfer data in word unit.
    //
    UINT32             ActualWordCount = 0;

    //
    // Select device via Device/Head Register.
    // DEFAULT_CMD: 0xa0 (1010,0000)
    //
    IoWrite8( HeadReg, (UINT8) ((Device << 4) | DEFAULT_CMD ));

    //
    // Set all the command parameters by fill related registers.
    // Before write to all the following registers, BSY and DRQ must be 0.
    //
    if ( DRQClear2(
             DeviceInfo->IdeIoPortRegisters,
             TIMEOUT
             ) != EFI_SUCCESS ) {
        return EFI_DEVICE_ERROR;
    }


    //
    // No OVL; No DMA
    //
    IoWrite8( FeatureReg, 0x00 );

    //
    // set the transfersize to MAX_ATAPI_BYTE_COUNT to let the device
    // determine how many data should be transfered.
    //
    IoWrite8( CylinderLsbReg, (UINT8) ( MAX_ATAPI_BYTE_COUNT & 0x00ff ));
    IoWrite8( CylinderMsbReg, (UINT8) ( MAX_ATAPI_BYTE_COUNT >> 8 ));

    //
    //  DEFAULT_CTL:0x0a (0000,1010)
    //  Disable interrupt
    //
    IoWrite8( DeviceControlReg, DEFAULT_CTL );

    //
    // Send Packet command to inform device
    // that the following data bytes are command packet.
    //
    IoWrite8( CommandReg, PACKET_CMD );

    Status = DRQReady( IdeIoPortRegisters, TimeoutInMilliSeconds );

    if ( Status != EFI_SUCCESS ) {
        return Status;
    }
    //
    // Send out command packet
    //
    CommandIndex = Packet->Data16;

    for ( Count = 0; Count < 6; Count++, CommandIndex++ ) {
        IoWrite16( DataReg, *CommandIndex );
        gStallPpi->Stall( gPeiServices, gStallPpi, 10 );
    }

    StatusValue = IoRead8( StatusReg );
    WaitForBSYClear( IdeIoPortRegisters, LONGTIMEOUT );
    StatusValue = IoRead8( StatusReg );

    if ((StatusValue & ERR) == ERR ) {
        //
        // Trouble! Something's wrong here... Wait some time and return. 3 second is
        // supposed to be long enough for a device reset latency or error recovery
        //
        gStallPpi->Stall( gPeiServices, gStallPpi, 100000 );

        return EFI_DEVICE_ERROR;
    }

    if ( Buffer == NULL || ByteCount == 0 ) {
        return EFI_SUCCESS;
    }
    //
    // call PioReadWriteData() function to get
    // requested transfer data form device.
    //
    ptrBuffer         = Buffer;
    RequiredWordCount = ByteCount / 2;
    //
    // ActuralWordCount means the word count of data really transfered.
    //
    ActualWordCount = 0;

    Status = EFI_SUCCESS;
    while ((Status == EFI_SUCCESS) && (ActualWordCount < RequiredWordCount))
    {
        //
        // before each data transfer stream, the host should poll DRQ bit ready,
        // which informs device is ready to transfer data.
        //
        if ( DRQReady2( IdeIoPortRegisters, TimeoutInMilliSeconds ) != EFI_SUCCESS ) {
            return CheckErrorStatus( StatusReg );
        }
        //
        // read Status Register will clear interrupt
        //
        StatusValue = IoRead8( StatusReg );

        //
        // get current data transfer size from Cylinder Registers.
        //
        WordCount = (( IoRead8( CylinderMsbReg ) << 8) | IoRead8( CylinderLsbReg )) & 0xffff;
        WordCount /= 2;

        //
        // perform a series data In/Out.
        //
        for ( Index = 0; (Index < WordCount) && (ActualWordCount < RequiredWordCount); Index++, ActualWordCount++ )
        {
            *ptrBuffer = IoRead16( DataReg );

            ptrBuffer++;
        }

        if (((GENERIC_CMD*) Packet)->OperationCode_0 == REQUEST_SENSE && ActualWordCount >= 4 ) {
            RequiredWordCount = EFI_MIN( RequiredWordCount,
                                (UINT32) ( 4 + (((REQUEST_SENSE_DATA*) Buffer)->AdditionalSenseLength_7 / 2))
                                );
        }
    }
    //
    // After data transfer is completed, normally, DRQ bit should clear.
    //
    Status = DRQClear2( IdeIoPortRegisters, TimeoutInMilliSeconds );

    if ( Status != EFI_SUCCESS ) {
        return EFI_DEVICE_ERROR;
    }
    //
    // read status register to check whether error happens.
    //
    Status = CheckErrorStatus( StatusReg );
    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Inquiry
//
// Description:	ATAPI packet command INQUIRY.   Uses AtapiPacketCommandIn.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Inquiry(
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo )
{
    ATAPI_PACKET_COMMAND Packet;
    EFI_STATUS           Status;
    INQUIRY_DATA         Idata;

    ZeroMem( &Packet, sizeof (ATAPI_PACKET_COMMAND));

    Packet.Cmd.OperationCode_0    = INQUIRY;
    Packet.Cmd.AllocationLength_4 = sizeof (INQUIRY_DATA);

    Status = AtapiPacketCommandIn(
        DeviceInfo,
        &Packet,
        (UINT16*)(&Idata),
        sizeof (INQUIRY_DATA),
        TIMEOUT
        );

    if ( Status != EFI_SUCCESS ) {
        return EFI_DEVICE_ERROR;
    }

    if ( Idata.PeripheralDeviceType_0 == CD_ROM_DEVICE ) {
        DeviceInfo->MediaInfo.DeviceType   = IdeCDROM;
        DeviceInfo->MediaInfo.MediaPresent = FALSE;
        DeviceInfo->MediaInfo.LastBlock    = 0;
        DeviceInfo->MediaInfo.BlockSize    = 0x800;
        return EFI_SUCCESS;
    } else {
        return EFI_UNSUPPORTED;
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_DetectMedia
//
// Description:
//      -Loop: Issues ATAPI packet command TEST_UNIT_READY.
//      If this is not successful, then look at SENSE data.
//      If you get the sense data for (1) becoming ready, (2) media
//      changed, or (3) power on reset, then stall for some time and
//      continue looping with TEST_UNIT_READY and REQUEST_SENSE.
//      -If TEST_UNIT_READY is successful, then issue READ_CAPACITY
//      packet command, which should get device info.
//      -If TEST_UNIT_READY is not succesful or if the SENSE data
//      contains some other error (not one of the three listed above),
//      then return an error.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Atapi_DetectMedia(
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo )
{
    UINTN              Index = 0;
    REQUEST_SENSE_DATA SenseBuffers[MAX_SENSE_KEY_COUNT];
    EFI_STATUS         Status        = EFI_SUCCESS;
    UINT8              SenseCounts   = 0;
    BOOLEAN            DeviceIsReady = FALSE;

    DeviceInfo->MediaInfo.MediaPresent = FALSE;
    DeviceInfo->MediaInfo.LastBlock    = 0;

    DeviceIsReady = FALSE;

    for ( Index = 0; Index < 50; Index++ ) {
        Status = TestUnitReady( DeviceInfo );

        if ( Status == EFI_SUCCESS ) {
            DeviceIsReady = TRUE;
            break;
        }

        SenseCounts = MAX_SENSE_KEY_COUNT;
        Status      = RequestSense( DeviceInfo, SenseBuffers, &SenseCounts );

        if ( SenseCounts == 0 ) {
            gStallPpi->Stall( gPeiServices, gStallPpi, 250000 );
            continue;
        }

        if (((SenseBuffers[0].SenseKey_2 == SK_NOT_READY) && (SenseBuffers[0].AdditionalSenseCode_12 == 4) && (SenseBuffers[0].AdditionalSenseCodeQualifier_13 == 1))     // Becoming ready
            || ((SenseBuffers[0].SenseKey_2 == SK_UNIT_ATTENTION) && (SenseBuffers[0].AdditionalSenseCode_12 == 0x28) && (SenseBuffers[0].AdditionalSenseCodeQualifier_13 == 0))     // Media Changed
            || ((SenseBuffers[0].SenseKey_2 == SK_UNIT_ATTENTION) && (SenseBuffers[0].AdditionalSenseCode_12 == 0x29) && (SenseBuffers[0].AdditionalSenseCodeQualifier_13 == 0))) {   // Power on Reset
            gStallPpi->Stall( gPeiServices, gStallPpi, 250000 );
        } else {
            break;
        }
    }

    if ( DeviceIsReady ) {
        Status = ReadCapacity( DeviceInfo );
        return Status;
    }

    return EFI_DEVICE_ERROR;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	TestUnitReady
//
// Description:	ATAPI command TEST_UINT_READY.  Uses AtapiPacketCommandIn.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS TestUnitReady(
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo )
{
    ATAPI_PACKET_COMMAND Packet;
    EFI_STATUS           Status;

    ZeroMem( &Packet, sizeof (ATAPI_PACKET_COMMAND));
    Packet.Cmd.OperationCode_0 = TEST_UNIT_READY;

    Status = AtapiPacketCommandIn( DeviceInfo, &Packet, NULL, 0, TIMEOUT );
    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	RequestSense
//
// Description:	Send Request sense command
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS RequestSense(
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    IN REQUEST_SENSE_DATA           *SenseBuffers,
    IN OUT UINT8                    *SenseCounts )
{
    EFI_STATUS           Status = EFI_SUCCESS;
    REQUEST_SENSE_DATA   *Sense = SenseBuffers;
    ATAPI_PACKET_COMMAND Packet;

    ZeroMem( SenseBuffers, sizeof (REQUEST_SENSE_DATA) * (*SenseCounts));

    ZeroMem( &Packet,      sizeof (ATAPI_PACKET_COMMAND));
    Packet.Cmd.OperationCode_0    = REQUEST_SENSE;
    Packet.Cmd.AllocationLength_4 = sizeof (REQUEST_SENSE_DATA);

    *SenseCounts = 0;

    while ( TRUE ) {
        Status = AtapiPacketCommandIn(
            DeviceInfo,
            &Packet,
            (UINT16*) Sense,
            sizeof (REQUEST_SENSE_DATA),
            TIMEOUT
            );

        if ( Status != EFI_SUCCESS ) {
            if ( *SenseCounts == 0 ) {
                return EFI_DEVICE_ERROR;
            } else {
                return EFI_SUCCESS;
            }
        }

        (*SenseCounts)++;

        if ( *SenseCounts == MAX_SENSE_KEY_COUNT ) {
            return EFI_SUCCESS;
        }

        //
        // We limit MAX sense data count to 20 in order to avoid dead loop. Some
        // incompatible ATAPI devices don't retrive NO_SENSE when there is no media.
        // In this case, dead loop occurs if we don't have a gatekeeper. 20 is
        // supposed to be large enough for any ATAPI device.
        // (Actually 6, not 20).
        if ( Sense->SenseKey_2 != SK_NO_SENSE ) {
            Sense++;
        } else {
            return EFI_SUCCESS;
        }
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	ReadCapacity
//
// Description:	ATAPI packet command READ_CAPACITY.
//      Uses AtapiPacketCommandIn.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS ReadCapacity(
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo )
{
    EFI_STATUS           Status;
    ATAPI_PACKET_COMMAND Packet;
    READ_CAPACITY_DATA   Data;

    ZeroMem( &Data,   sizeof (Data));

    if ( DeviceInfo->MediaInfo.DeviceType == IdeCDROM ) {
        ZeroMem( &Packet, sizeof (ATAPI_PACKET_COMMAND));
        Packet.Cmd.OperationCode_0 = READ_CAPACITY;
        Status                     = AtapiPacketCommandIn(
                                                    DeviceInfo,
                                                    &Packet,
                                                    (UINT16*)(&Data),
                                                    sizeof (READ_CAPACITY_DATA),
                                                    LONGTIMEOUT
                                                    );

        if ( Status == EFI_SUCCESS ) {
            if ( DeviceInfo->MediaInfo.DeviceType == IdeCDROM ) {
                DeviceInfo->MediaInfo.LastBlock    = (Data.LastLba0 << 24) | (Data.LastLba1 << 16) | (Data.LastLba2 << 8) | Data.LastLba3;
                DeviceInfo->MediaInfo.MediaPresent = TRUE;
                DeviceInfo->MediaInfo.BlockSize    = 0x800;
            }
            return EFI_SUCCESS;
        } else {
            return EFI_DEVICE_ERROR;
        }
    } else {
        return EFI_UNSUPPORTED;
    }
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Atapi_ReadSectors
//
// Description:	Helper function called by Atapi_ReadBlocks.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Atapi_ReadSectors(
    IN OUT IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    IN VOID                         *Buffer,
    IN EFI_PEI_LBA                  StartLba,
    IN UINTN                        NumberOfBlocks,
    IN UINTN                        BlockSize )
{
    ATAPI_PACKET_COMMAND Packet;
    READ10_CMD           *Read10Packet   = NULL;
    EFI_STATUS           Status          = EFI_SUCCESS;
    UINTN                BlocksRemaining = 0;
    UINT32               Lba32           = 0;
    UINT32               ByteCount       = 0;
    UINT16               SectorCount     = 0;
    VOID                 *ptrBuffer      = NULL;
    UINT16               MaxBlock        = 0;

    ZeroMem( &Packet, sizeof (ATAPI_PACKET_COMMAND));

    Read10Packet = &Packet.Read10;
    Lba32        = (UINT32) StartLba;
    ptrBuffer    = Buffer;

    //
    // limit the data bytes that can be transfered by one Read(10) Command
    //
    MaxBlock = (UINT16) ( 0x10000 / BlockSize );
    //
    // (64k bytes)
    //
    BlocksRemaining = NumberOfBlocks;

    Status = EFI_SUCCESS;
    while ( BlocksRemaining > 0 ) {
        if ( BlocksRemaining <= MaxBlock ) {
            SectorCount = (UINT16) BlocksRemaining;
        } else {
            SectorCount = MaxBlock;
        }

        Read10Packet->OperationCode_0 = READ_10;

        //
        // Lba0 ~ Lba3 specify the start logical block address of the data transfer.
        // Lba0 is MSB, Lba3 is LSB
        //
        Read10Packet->Lba3 = (UINT8) ( Lba32 & 0xff );
        Read10Packet->Lba2 = (UINT8) ( Lba32 >> 8 );
        Read10Packet->Lba1 = (UINT8) ( Lba32 >> 16 );
        Read10Packet->Lba0 = (UINT8) ( Lba32 >> 24 );

        //
        // TransferLengthMSB ~ TransferLengthLSB specify the transfer length in block unit.
        //
        Read10Packet->TransferLengthLSB = (UINT8) ( SectorCount & 0xff );
        Read10Packet->TransferLengthMSB = (UINT8) ( SectorCount >> 8 );

        ByteCount = (UINT32) ( SectorCount * BlockSize );

        Status = AtapiPacketCommandIn(
            DeviceInfo,
            &Packet,
            (UINT16*) ptrBuffer,
            ByteCount,
            LONGTIMEOUT
            );

        if ( Status != EFI_SUCCESS ) {
            return Status;
        }

        Lba32           += SectorCount;
        ptrBuffer        = (UINT8*) ptrBuffer + SectorCount * BlockSize;
        BlocksRemaining -= SectorCount;
    }

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	AtaPioDataIn
//
// Description:	Does ATA protocol Pio In with data.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS AtaPioDataIn(
    IN IDE_BASE_REGISTERS *IdeIoPortRegisters,
    OUT VOID              *Buffer,
    IN UINT32             ByteCount,
    IN UINT8              SectorCount,
    IN UINT8              SectorNumber,
    IN UINT8              CylinderLsb,
    IN UINT8              CylinderMsb,
    IN UINT8              Device,
    IN UINT8              Command )
{
    EFI_STATUS Status = EFI_SUCCESS;

    UINT16     HeadReg           = IdeIoPortRegisters->Head;
    UINT16     SectorCountReg    = IdeIoPortRegisters->SectorCount;
    UINT16     SectorNumberReg   = IdeIoPortRegisters->SectorNumber;
    UINT16     CylinderLsbReg    = IdeIoPortRegisters->CylinderLsb;
    UINT16     CylinderMsbReg    = IdeIoPortRegisters->CylinderMsb;
    UINT16     CommandReg        = IdeIoPortRegisters->Reg.Command;
    UINT16     AltStatusRegister = IdeIoPortRegisters->Alt.AltStatus;
    UINT16     StatusReg         = IdeIoPortRegisters->Reg.Status;
    UINT16     DataReg           = IdeIoPortRegisters->Data;

    UINT32     WordCount = 0;
    UINT32     Increment = 0;
    UINT32     Index     = 0;
    UINT16     *Buffer16 = (UINT16*)Buffer;
    ;

    IoWrite8( HeadReg, Device );

    Status = WaitForBSYClear( IdeIoPortRegisters, TIMEOUT );

    if ( Status != EFI_SUCCESS ) {
        return EFI_DEVICE_ERROR;
    }

    Status = DRQClear2( IdeIoPortRegisters, TIMEOUT );

    if ( Status != EFI_SUCCESS ) {
        return EFI_DEVICE_ERROR;
    }

    Status = DRQClear2( IdeIoPortRegisters, TIMEOUT );

    if ( Status != EFI_SUCCESS ) {
        return EFI_DEVICE_ERROR;
    }

    IoWrite8( SectorCountReg,  SectorCount );
    IoWrite8( SectorNumberReg, SectorNumber );
    IoWrite8( CylinderLsbReg,  CylinderLsb );
    IoWrite8( CylinderMsbReg,  CylinderMsb );

    IoWrite8( CommandReg,      Command );

    IoRead8( AltStatusRegister );

    Increment = 256;
    WordCount = 0;

    while ( WordCount < ByteCount / 2 ) {
        Status = DRQReady2( IdeIoPortRegisters, COMMAND_COMPLETE_TIMEOUT );

        if ( Status != EFI_SUCCESS ) {
            return Status;
        }

        if ( CheckErrorStatus( StatusReg ) != EFI_SUCCESS ) {
            return EFI_DEVICE_ERROR;
        }

        if ((WordCount + Increment) > ByteCount / 2 ) {
            Increment = ByteCount / 2 - WordCount;
        }

        for ( Index = 0; Index < Increment; Index++ )
        {
            *Buffer16++ = IoRead16( DataReg );
        }

        WordCount += Increment;
    }

    Status = DRQClear( IdeIoPortRegisters, TIMEOUT );

    if ( Status != EFI_SUCCESS ) {
        return CheckErrorStatus( StatusReg );
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	AtaIdentify
//
// Description:	ATA Identify command.  Uses AtaPioDataIn
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS AtaIdentify(
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    OUT ATA_IDENTIFY_DATA       *AtaIdentifyData )
{
    return       AtaPioDataIn( DeviceInfo->IdeIoPortRegisters,
                               AtaIdentifyData,
                               sizeof (ATA_IDENTIFY_DATA),
                               0,
                               0,
                               0,
                               0,
                               DeviceInfo->Device << 4,
                               ATA_IDENTIFY_DEVICE_CMD
                               );
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	Ata_ReadSectors
//
// Description:	Helper function called by Ata_ReadBlocks.
//
// Input:
//  IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo - pointer to the device info structure
//  IN OUT VOID *Buffer - Pointer to a buffer that will hold the Data that is read
//  IN EFI_PEI_LBA StartLba - the first LBA to read
//  IN UINTN NumberOfBlocks - total number of blocks to read
//  IN UINTN BlockSize - size of the blocks to be read
//
// Output:
//  EFI_SUCCESS - Read happened correctly
//  OTHER - any valid error from AtaPioDataIn() 
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS Ata_ReadSectors(
    IN IDE_RECOVERY_DEVICE_INFO *DeviceInfo,
    IN OUT VOID                 *Buffer,
    IN EFI_PEI_LBA              StartLba,
    IN UINTN                    NumberOfBlocks,
    IN UINTN                    BlockSize )
{
    EFI_STATUS Status          = EFI_SUCCESS;
    UINTN      BlocksRemaining = 0;
    UINT32     Lba32           = 0;
    UINT8      LbaLow          = 0;
    UINT8      LbaMid          = 0;
    UINT8      LbaHigh         = 0;
    UINT32     ByteCount       = 0;
    UINT16     SectorCount     = 0;
    VOID       *ptrBuffer      = NULL;
    UINT16     MaxBlock        = 0;
    UINT8      Dev             = 0;
    UINT8      Device          = 0;

    Lba32     = (UINT32) StartLba;
    ptrBuffer = Buffer;

    MaxBlock = (UINT16) ( 0x20000 / BlockSize );

    BlocksRemaining = NumberOfBlocks;

    Status = EFI_SUCCESS;
    Dev    = (DeviceInfo->Device << 4) | LBA_MODE;
    while ( BlocksRemaining > 0 ) {
        if ( BlocksRemaining < MaxBlock ) {
            SectorCount = BlocksRemaining;
        } else {
            SectorCount = MaxBlock;
        }
        LbaLow  = (UINT8) ( Lba32 & 0xff );
        LbaMid  = (UINT8) ( Lba32 >> 8 );
        LbaHigh = (UINT8) ( Lba32 >> 16 );

        ByteCount = (UINT32) ( SectorCount * BlockSize );

        Dev   |= (Lba32 >> 24);
        Status = AtaPioDataIn( DeviceInfo->IdeIoPortRegisters,
                               ptrBuffer,
                               ByteCount,
                               (UINT8) SectorCount, //sector count
                               LbaLow, //sector number
                               LbaMid, //lsb
                               LbaHigh, //msb
                               Dev,
                               ATA_READ_SECTOR_CMD
                               );

        if ( Status != EFI_SUCCESS ) {
            return Status;
        }

        Lba32           += SectorCount;
        ptrBuffer        = (UINT8*) ptrBuffer + SectorCount * BlockSize;
        BlocksRemaining -= SectorCount;
    }

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	WaitForBitsToClear
//
// Description:	Helper functin used by WaitForBSYClear, DRQClear, DRQClear2.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS WaitForBitsToClear(
    UINT16 Register,
    UINT8  Bits,
    UINTN  TimeoutInMilliSeconds )
{
    UINTN Delay       = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1;
    UINT8 StatusValue = 0;

    do {
        StatusValue = IoRead8( Register );

        if ((StatusValue & Bits) == 0x00 ) {
            break;
        }

        gStallPpi->Stall( gPeiServices, gStallPpi, 250 );

        Delay--;
    } while ( Delay );

    if ( Delay == 0 ) {
        return EFI_TIMEOUT;
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	WaitForBSYClear
//
// Description: Wait for busy bit to clear
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS WaitForBSYClear(
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds )
{
    return WaitForBitsToClear( IdeIoRegisters->Reg.Status, BSY, TimeoutInMilliSeconds );
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	DRQClear
//
// Description: Wait for the DRQ bit clear
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DRQClear(
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds )
{
    return WaitForBitsToClear( IdeIoRegisters->Reg.Status, DRQ | BSY, TimeoutInMilliSeconds );
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	DRQClear2
//
// Description: Wait for the DRQ bit clear in Alternate Status Reg
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DRQClear2(
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds )
{
    return WaitForBitsToClear( IdeIoRegisters->Alt.AltStatus, DRQ | BSY, TimeoutInMilliSeconds );
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	DRQReadyHelper
//
// Description:
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DRQReadyHelper(
    UINT16   StatusRegister,
    UINT16   ErrorRegister,
    IN UINTN TimeoutInMilliSeconds )
{
    UINTN Delay       = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1;
    UINT8 StatusValue = 0;
    UINT8 ErrValue    = 0;

    do
    {
        //
        //  read Status Register will clear interrupt
        //
        StatusValue =  IoRead8( StatusRegister );

        //
        //  BSY==0,DRQ==1
        //
        if ((StatusValue & (BSY | DRQ)) == DRQ ) {
            break;
        }

        if ((StatusValue & (BSY | ERR)) == ERR ) {
            ErrValue = IoRead8( ErrorRegister );

            if ((ErrValue & ABRT_ERR) == ABRT_ERR ) {
                return EFI_ABORTED;
            }
        }

        gStallPpi->Stall( gPeiServices, gStallPpi, 250 );

        Delay--;
    } while ( Delay );

    if ( Delay == 0 ) {
        return EFI_TIMEOUT;
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	DRQReady
//
// Description: Wait for the DRQ ready 
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DRQReady(
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds )
{
    return DRQReadyHelper( IdeIoRegisters->Reg.Status, IdeIoRegisters->Reg1.Error, TimeoutInMilliSeconds );
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	DRQReady2
//
// Description: Wait for the DRQ Ready in Alternate Status Reg
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DRQReady2(
    IN IDE_BASE_REGISTERS *IdeIoRegisters,
    IN UINTN              TimeoutInMilliSeconds )
{
    return DRQReadyHelper( IdeIoRegisters->Alt.AltStatus, IdeIoRegisters->Reg1.Error, TimeoutInMilliSeconds );
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	CheckErrorStatus
//
// Description: Check for the Errros.
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS CheckErrorStatus(
    IN UINT16 StatusReg )
{
    UINT8 StatusValue = IoRead8( StatusReg );

    if ((StatusValue & (ERR | DWF | CORR)) == 0 ) {
        return EFI_SUCCESS;
    }

    return EFI_DEVICE_ERROR;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------
//
// Procedure:	ZeroMem
//
// Description: Clear the Memory
//
//----------------------------------------------------------------------
//<AMI_PHDR_END>
static
VOID ZeroMem(
    IN VOID  *Buffer,
    IN UINTN Size )
{
    UINT8 *ptr;

    ptr = Buffer;
    while ( Size-- )
    {
        *(ptr++) = 0;
    }
}

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