summaryrefslogtreecommitdiff
path: root/Core/EM/Ahci/AhciController.c
blob: 73d6c31ed16afd3b2b771c3cc310626fd74449bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
//**********************************************************************
//**********************************************************************
//**                                                                  **
//**        (C)Copyright 1985-2011, American Megatrends, Inc.         **
//**                                                                  **
//**                       All Rights Reserved.                       **
//**                                                                  **
//**         5555 Oakbrook Pkwy, Suite 200, Norcross, GA 30093        **
//**                                                                  **
//**                       Phone: (770)-246-8600                      **
//**                                                                  **
//**********************************************************************
//**********************************************************************

//**********************************************************************
// $Header: /Alaska/SOURCE/Modules/AHCI/AhciController.c 41    1/27/14 4:57a Rameshr $
//
// $Revision: 41 $
//
// $Date: 1/27/14 4:57a $
//**********************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Modules/AHCI/AhciController.c $
// 
// 41    1/27/14 4:57a Rameshr
// [TAG]  		EIP148180
// [Category]  	Improvement
// [Description]  	Change from EFI_MBR_WRITE_PROTECTION_PROTOCOL to
// AMI_BLOCKIO_WRITE_PROTECTION_PROTOCOL
// [Files]  		Ahcibus.c, Ahcibus.h, AhciComponentName.c, AhciController.c
// 
// 40    12/20/13 4:06a Rameshr
// [TAG]  		EIP126640
// [Category]  	Improvement
// [Description]  	AHCIBUS driver need to preserve the port settings in
// GeneratePortReset 
// [Files]  		Ahcibus.c, AhciController.c
// 
// 39    8/27/13 4:16a Rameshr
// [TAG]  		EIP125560
// [Category]  	Improvement
// [Description]  	MbrWriteProtectionProtocol file name changesd to
// AmiMbrWriteProtectionProtocol.h
// [Files]  		AhciController.c, AhciBus.h, Ahcibus.c
// 
// 38    7/01/13 5:32a Kapilporwal
// [TAG]  		EIP125560
// [Category]  	Improvement
// [Description]  	 	Please support Boot Sector Virus Protection for CSM
// Disabled Mode
// [Files]  		VirusProtect.c, VirusProtect.dxs, AhciBus.c,
// AhciController.c, CsmBlockIo.c, CsmInt13.c, Ata.c, IdeBus.c,
// SdioBlkIo.c, SdioDriver.c, efiusbmass.c
// 
// 37    11/18/12 11:45p Rameshr
// [TAG]  		EIP102518
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	SCT failure for ATAPI BlockIO
// [RootCause]  	BufferSize and IOAllign checking not added for Atapi
// BlockIO protocol functions
// [Solution]  	Added BufferSize and IOAllign checking for Atapi BlockIO
// protocol functions
// [Files]  		AhciController.c
// 
// 36    9/17/12 12:52a Rameshr
// [TAG]  		EIP100335
// [Category]  	Improvement
// [Description]  	Port Multiplier spend long time to connect device.
// [Files]  		Ahcibus.c , AhciController.c
// 
// 35    9/17/12 12:43a Anandakrishnanl
// [TAG]  		EIP100847
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	System hangs when Memory allocation >4Gb in AHCI Mode
// [RootCause]  	DBAU not programmed for AhciController
// [Solution]  	Fixed by Programming DBAU in PRDT Table
// [Files]  		AhciController.c
// 
// 34    8/21/12 2:28a Rameshr
// [TAG]  		EIP98526
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	FIS and CommandList Base address store and restore wont
// work incase of recursive call
// [RootCause]  	FIS and CommandList Base address store and restore wont
// work incase of recursive call
// [Solution]  	FIS and Command List base Address save and restore done
// properly when the function called recursively.
// [Files]  		Ahcicontroller.c
// 
// 33    8/17/12 3:10a Srikantakumarp
// [TAG]  		EIP95863
// [Category]  	Bug Fix
// [Symptom]  	AhciSmm doesnt save and restore the upper 32bits of FBU and
// CLBU
// [RootCause]  	As Windows uses the 64bit address for FIS Base Address
// and Command List Base Address, and AHCISMM driver doesn't take care of
// the upper 32bit value of those which cause the failure in AhciSMM
// driver.
// [Solution]  	Save and Restore the upper 32bits of FBU and CLBU in
// AhciSmm Driver.
// [Files]  		AhciController.c, AhciSmm.c
// 
// 32    8/16/12 3:06a Rajeshms
// [TAG]  		EIP97048
// [Category]  	New Feature
// [Description]  	ATAPI PassThru Support using
// EFI_EXT_SCSI_PASS_THRU_PROTOCOL.
// [Files]  		AhciBus.c, AhciController.c, IdeBus.c, Atapi.c, PIDEBus.h,
// PAhciBus.h, ScsiPassThruAtapi.sdl, ScsiPassThruAtapi.mak,
// ScsiPassThruAtapi.c, ScsiPassThruAtapiSupport.h, ScsiPassThruAtapi.chm,
// ScsiPassThruExt.h
// 
// 31    2/03/12 3:23a Rameshr
// [TAG]  		EIP82275
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	SataReadWritePio doesn't work if the ReadSector count is
// more than 256 sectors
// [RootCause]  	Buffer Address not incremented for the next Read
// [Solution]  	Handled the buffer address properly for the next Pio Read
// [Files]  		AhciController.c
// 
// 30    11/08/11 5:19a Deepthins
// [TAG]  		EIP74607
// [Category]  	Improvement
// [Description]  	Block IO Read/Write function, the alignment should be
// proper. IoAlign value is 0 or 1 means that the buffer can be placed
// anywhere in memory. Otherwise, IoAlign must be a power of 2, and the
// requirement is that the start address of a buffer must be evenly
// divisible by IoAlign with no remainder.
// [Files]  		Ata.c, Atapi.c and AhciController.c
// 
// 29    11/07/11 4:31a Deepthins
// [TAG]  		EIP74607
// [Category]  	Improvement
// [Description]  	IoAlign value is 0 or 1 means that the buffer can be
// placed anywhere in memory. Otherwise, IoAlign must be a power of 2, and
// the requirement is that the start address of a buffer must be
// evenlydivisible by 2 to the power of IoAlign with no remainder.
// [Files]  		AhciController.c
// 
// 28    11/07/11 2:30a Deepthins
// [TAG]  		EIP73941
// [Category]  	Improvement
// [Description]  	BufferSize is 0, ReadBlock function should return
// EFI_SUCCESS without actual reading.
// [Files]  		AhciController.c
// 
// 27    5/09/11 6:29a Anandv
// [TAG] - EIP59552
// [Category] - BUG FIX
// [Severity] - Normal
// [Symptom] -AhciController.c file in Ahci driver needs modification to
// Support Index/Data Port access method for getting the FIS Address.
// [RootCause] - FISAddress was Obtained using MMIO method irrespective of
// "INDEX_DATA_PORT_ACCESS" SDL token.
// [Solution] - FISAddress is now obtained using Port I/O or MMIO method
// depending on 
// "INDEX_DATA_PORT_ACCESS" SDL token.
// [Files] - AhciController.c
// 
// 26    3/29/11 1:03a Lavanyap
// [TAG] - EIP53849
// [Category] - BUG FIX
// [Severity] - Normal
// [Symptom] - Ide Bus Sources cannot build in IA32 DEBUG mode.
// [RootCause] - It happened because of usage of << and * with UINT64
// values in AtaPioDataOut() and SataPioDataOut().
// [Solution] - Shl64 and Mul64 functions have been implemented to operate
// UINT64 values.
// [Files] - Ata.c, AhciController.c
// 
// 25    2/21/11 3:38a Rameshr
// Helpbuilder Issue Resolved
// 
// 24    2/18/11 5:06a Rameshr
// [TAG]- EIP 37975
// [Category]-IMPROVEMENT
// [Description]- Klocwork Issues II - IDE/Ahci module
// [Files]- AhciBus.c, AhciController.c
// 
// 23    2/11/11 4:22a Rameshr
// [TAG]  		EIP53730
// [Category]  	Improvement
// [Description]  	Add Odd Loading type information into ATAPI_DEVICE
// structure in AHCI mode
// [Files]  		AhciBus.c
// AhciController.c
// AhciBus.h
// 
// 22    2/10/11 10:35a Rameshr
// [TAG]  		EIP53704
// [Category]  	Improvement
// [Description]  	AMI headers update for Alaska Ahci Driver
// [Files]  		AhciSrc.mak
// AhciBus.c
// AhciController.c
// AhciComponentName.c
// AhciBus.h
// AhciController.h
// 
// 21    12/23/10 3:59a Lavanyap
// [TAG] - EIP41445
// [Category] - NEW FEATURE
// [Description] - Created SataPioDataOut and AtaPioDataOut protocol
// function that can accept additional input parameters.
// [Files] - AhciBus.h, AhciBus.c, AhciController.c, Ata.c, IdeBus.c,
//           IdeBus.h, IdeBusMaster.c,PAhciBus.h, PIdeBus.h
// 
// 20    4/16/10 4:15p Pats
// EIP 30719: Support for the HDD with sector size more than 512bytes.
// 
// 19    9/22/09 10:53a Krishnakumarg
// Code modified to update SataDevInterface->identifydata in
// GetIdentifyData function instead of returning in global variable -
// EIP26411
// 
// 18    9/21/09 12:34p Krishnakumarg
// It takes a long time to detect large size HDD(eg. 500GB, 1TB size)
// under AHCI mode-EIP26499.
// Replaced TAB with spaces for AMI code standard
// 
// 17    8/12/09 5:07p Davidd
// Corrected command parameter error in all PACKET_COMMAND - EIP 24817
// 
// 16    6/22/09 11:35a Rameshr
// Odd Type information Saved in Atapi Device Structure.
// EIP:21548
// 
// 15    6/18/09 4:27p Rameshr
// if the Erase command timeout value is 0 or 255, wait for the Erase
// command completion without timeout value
// EIP:20630
// 
// 14    4/29/09 10:54a Rameshr
// 
// 13    4/28/09 3:51p Rameshr
// 
// HDD password support in RAID mode
// EIP:20421
// 
// 12    3/29/09 11:08a Rameshr
// Security Erase command timeout value should be from the Identify packet
// command word 89
// EIP 20630
// 
// 11    12/11/08 1:55p Srinin
// After COMRESET, wait for shadow status register to get synced up with
// D2H FIS
// 
// 10    26/09/08 12:32p Anandakrishnanl
// Fixed Ahci Block Write Issue Which Exceeds 4MB. Added the Proper Offset
// of Descriptor and Fixed Valid  PRDT_I Bit.
// 
// 9     13/08/08 2:24p Anandakrishnanl
// Fixed the Minor error that occured in Previous Checkin for EfiDiag NO
// Media Issue
// 
// 8     12/08/08 11:26a Anandakrishnanl
// Fixed the error reported by EFI Diag r(CD/DVD test) to return
// EFI_NO_MEDIA.
// 
// 7     5/28/08 9:38a Rameshraju
// Based on the SDL token index/data or MMIO method used to access the
// AHCI configuration space.
// 
// 6     5/09/08 10:05a Rameshraju
// Default status initilized.
// 
// 5     4/10/08 12:52p Srinin
// PMPort field in Command header and in FIS is set to zero instead of 0xF
// when PORT 0 is accessed.
// 
// 4     4/03/08 4:40p Srinin
// In ReadytoAcceptCmd Status was not initialized. Fixed it.
// 
// 3     3/24/08 6:19p Fasihm
// Fixed issue that few HDDs not detected because of PhyRdy Change bit.
// 
// 2     7/03/08 5:31p Anandakrishnanl
// Added Smart Support as a seperate Driver and Corresponding changes to
// invoke Smart Protocols and removed SDL-Token
// 
// 1     28/02/08 6:03p Anandakrishnanl
// AHCI Bus Driver initial check-in.
// 
// 
// 
//**********************************************************************
//<AMI_FHDR_START>
//
// Name: AhciController.c
//
// Description: Provides Access to AHCI Controller
//
//<AMI_FHDR_END>
//**********************************************************************

#include "AhciBus.h"

#if defined CORE_COMBINED_VERSION && (CORE_COMBINED_VERSION > 0x4028E)
extern AMI_BLOCKIO_WRITE_PROTECTION_PROTOCOL *AmiBlkWriteProtection;
#endif

BOOLEAN gPortReset = FALSE;             // Avoid Re-entry
BOOLEAN gSoftReset = FALSE;             // Avoid Re-entry
UINT32  gCommandListBaseAddress = 0;
UINT32  gFisBaseAddress;
UINT32  gCommandListBaseAddress2;
UINT32  gFisBaseAddress2;

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   SataBlkRead
//
// Description: Read from the Sata ATA Device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN UINT32                       MediaId,
//  IN EFI_LBA                      LBA,
//  IN UINTN                        BufferSize,
//  OUT VOID                        *Buffer
//
// Output:
//      EFI_STATUS
//
// Modified:
//      
// Referrals: SataAtaBlkReadWrite 
//
// Notes:   
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataBlkRead(
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN UINT32                       MediaId,
    IN EFI_LBA                      LBA,
    IN UINTN                        BufferSize,
    OUT VOID                        *Buffer
 )
{

    EFI_STATUS  Status;

    Status =  SataAtaBlkReadWrite(This, MediaId, LBA, BufferSize, Buffer, 0);
 
    TRACE((TRACE_ALWAYS,"AHCI Read: LBA : %lx ByteCount : %lx\n", LBA, BufferSize));

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   SataBlkWrite
//
// Description: Write to Sata ATA Device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN UINT32                       MediaId,
//  IN EFI_LBA                      LBA,
//  IN UINTN                        BufferSize,
//  OUT VOID                        *Buffer
//
// Output:
//      EFI_STATUS
//
// Modified:
//      
// Referrals: SataAtaBlkReadWrite 
//
// Notes:   
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataBlkWrite(
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN UINT32                       MediaId,
    IN EFI_LBA                      LBA,
    IN UINTN                        BufferSize,
    OUT VOID                        *Buffer
 )
{

    EFI_STATUS  Status;

#if defined CORE_COMBINED_VERSION && (CORE_COMBINED_VERSION > 0x4028E)
    if(AmiBlkWriteProtection != NULL) {
        // Get user input
        Status = AmiBlkWriteProtection->BlockIoWriteProtectionCheck( 
                                                    AmiBlkWriteProtection,
                                                    This,
                                                    LBA,
                                                    BufferSize
                                                    );
        // Abort operation if denied
        if(Status == EFI_ACCESS_DENIED) {
            return Status;
        }
    } 
#endif

    Status =  SataAtaBlkReadWrite(This, MediaId, LBA, BufferSize, Buffer, 1);

    TRACE((TRACE_ALWAYS,"AHCI Write: LBA : %lx ByteCount : %lx\n", LBA, BufferSize));

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   SataAtaBlkReadWrite
//
// Description: Read/Write to/from Sata ATA Device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN UINT32                       MediaId,
//  IN EFI_LBA                      LBA,
//  IN UINTN                        BufferSize,
//  OUT VOID                        *Buffer,
//  BOOLEAN                         READWRITE
//
// Output:
//      EFI_STATUS
//
// Modified:
//      
// Referrals: SataReadWriteBusMaster, SataReadWritePio 
//
// Notes:   
//  1. Check for validity of the input
//  2. Issue DMA or PIO Read/Write call.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataAtaBlkReadWrite (
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN UINT32                       MediaId,
    IN EFI_LBA                      LBA,
    IN UINTN                        BufferSize,
    OUT VOID                        *Buffer,
    BOOLEAN                         READWRITE
)
{

    EFI_STATUS  Status = EFI_DEVICE_ERROR;
    SATA_DEVICE_INTERFACE   *SataDevInterface = ((SATA_BLOCK_IO *)This)->SataDevInterface;
    EFI_BLOCK_IO_MEDIA      *BlkMedia = This->Media;
    UINTN                   DataN;
    UINTN                   BufferAddress;

    // Check if Media ID matches
    if (BlkMedia->MediaId != MediaId) return EFI_MEDIA_CHANGED;

    if (BufferSize == 0) return EFI_SUCCESS;
    
    //
    // If IoAlign values is 0 or 1, means that the buffer can be placed 
    // anywhere in memory or else IoAlign value should be power of 2. To be
    // properly aligned the buffer address should be divisible by IoAlign  
    // with no remainder. 
    // 
    (VOID *)BufferAddress = Buffer;
    if((BlkMedia->IoAlign > 1 ) && (BufferAddress % BlkMedia->IoAlign)) {
        return EFI_INVALID_PARAMETER;
    }

    // Check whether the block size is multiple of BlkMedia->BlockSize
    DataN = BufferSize % BlkMedia->BlockSize;
    if (DataN) return EFI_BAD_BUFFER_SIZE;

    // Check for Valid start LBA #
    if (LBA > BlkMedia->LastBlock) return EFI_INVALID_PARAMETER;

    // Check for Valid End LBA #
    DataN = BufferSize / BlkMedia->BlockSize;
    if (LBA + DataN > BlkMedia->LastBlock + 1) return EFI_INVALID_PARAMETER;

    #if IDEBUSMASTER_SUPPORT
    if (DMACapable(SataDevInterface)) {     
    Status = SataReadWriteBusMaster (SataDevInterface, Buffer, BufferSize, LBA, 
                        READWRITE ? SataDevInterface->WriteCommand : SataDevInterface->ReadCommand, 
                        READWRITE);
        return Status;
    }
    #endif

    Status = SataReadWritePio (SataDevInterface, Buffer, BufferSize, LBA, 
                        READWRITE ? SataDevInterface->WriteCommand : SataDevInterface->ReadCommand, 
                        READWRITE);

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   SataAtapiBlkRead
//
// Description: Read from the Sata ATAPI Device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN UINT32                       MediaId,
//  IN EFI_LBA                      LBA,
//  IN UINTN                        BufferSize,
//  OUT VOID                        *Buffer
//
// Output:
//      EFI_STATUS
//
// Modified:
// 
// Referrals: SataAtapiBlkReadWrite 
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS
SataAtapiBlkRead(
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN UINT32                       MediaId,
    IN EFI_LBA                      LBA,
    IN UINTN                        BufferSize,
    OUT VOID                        *Buffer
 )
{

    EFI_STATUS  Status;

    Status =  SataAtapiBlkReadWrite(This, MediaId, LBA, BufferSize, Buffer, 0);

    TRACE((TRACE_ALWAYS,"AHCI ATAPI Read: LBA : %lx ByteCount : %lx\n", LBA, BufferSize));

    return Status;



}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   SataAtapiBlkWrite
//
// Description: Write to Sata ATAPI Device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN UINT32                       MediaId,
//  IN EFI_LBA                      LBA,
//  IN UINTN                        BufferSize,
//  OUT VOID                        *Buffer
//
// Output:
//      EFI_STATUS
//
// Modified:
//      
// Referrals: SataAtapiBlkReadWrite
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataAtapiBlkWrite(
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN UINT32                       MediaId,
    IN EFI_LBA                      LBA,
    IN UINTN                        BufferSize,
    OUT VOID                        *Buffer
 )
{

    EFI_STATUS  Status;

    Status =  SataAtapiBlkReadWrite(This, MediaId, LBA, BufferSize, Buffer, 1);

    TRACE((TRACE_ALWAYS,"AHCI ATAPI Read: LBA : %lx ByteCount : %lx\n", LBA, BufferSize));

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   SataAtapiBlkReadWrite
//
// Description: Read/Write to/from Sata ATAPI Device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN UINT32                       MediaId,
//  IN EFI_LBA                      LBA,
//  IN UINTN                        BufferSize,
//  OUT VOID                        *Buffer
//
// Output:
//      EFI_STATUS
//
// Modified:
//      
// Referrals: 
//
// Notes:   
//  1. Check for validity of Inputs
//  2. Check whether Media is present or not
//  3. Issue ATAPi Packet command
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataAtapiBlkReadWrite(
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN UINT32                       MediaId,
    IN EFI_LBA                      LBA,
    IN UINTN                        BufferSize,
    OUT VOID                        *Buffer,
    BOOLEAN                         READWRITE
 )
{

    EFI_STATUS  Status = EFI_DEVICE_ERROR;
    SATA_DEVICE_INTERFACE   *SataDevInterface = ((SATA_BLOCK_IO *)This)->SataDevInterface;
    EFI_BLOCK_IO_MEDIA      *BlkMedia = This->Media;
    UINTN                   DataN;
    ATAPI_DEVICE            *AtapiDevice = SataDevInterface->AtapiDevice;
    COMMAND_STRUCTURE       CommandStructure;
    INTN                    TotalNumberofBlocks;
    INTN                    TransferLength;
    UINTN                   BytesRemainingTobeRead;
    VOID                    *TempBuffer = Buffer;
    UINTN                   BufferAddress;


    //  Check if Media Present

    if (BlkMedia->MediaPresent == FALSE) {
        Status = DetectAtapiMedia(SataDevInterface);
        if (Status == EFI_SUCCESS) return EFI_MEDIA_CHANGED;
        if (Status == EFI_NO_MEDIA) return Status;
        return EFI_DEVICE_ERROR;
    }

    //  Check if Media ID matches

    if (BlkMedia->MediaId != MediaId) return EFI_MEDIA_CHANGED;

    if (BufferSize == 0) return EFI_SUCCESS;

    // If IoAlign values is 0 or 1, means that the buffer can be placed
    // anywhere in memory or else IoAlign value should be power of 2. To be
    // properly aligned the buffer address should be divisible by IoAlign
    // with no remainder.

    (VOID *)BufferAddress = Buffer;
    if((BlkMedia->IoAlign > 1 ) && (BufferAddress % BlkMedia->IoAlign)) {
        return EFI_INVALID_PARAMETER;
    }

    //  Check whether the block size is multiple of BlkMedia->BlockSize

    DataN = BufferSize % BlkMedia->BlockSize;
    if (DataN) return EFI_BAD_BUFFER_SIZE;

    //  Check for Valid start LBA #

    if (LBA > BlkMedia->LastBlock) return EFI_INVALID_PARAMETER;

    //  Check for Valid End LBA #8

    DataN = BufferSize / BlkMedia->BlockSize;
    if (LBA + DataN > BlkMedia->LastBlock + 1) return EFI_INVALID_PARAMETER;


    TotalNumberofBlocks = BufferSize / AtapiDevice->BlockSize;

    for (; TotalNumberofBlocks >  0; TotalNumberofBlocks -= TransferLength) {  

        ZeroMemory (&CommandStructure, sizeof(CommandStructure));

        // Calculate # of blocks to be transferred

        if (TotalNumberofBlocks > 0xffff) 
            TransferLength = 0xffff;
        else
            TransferLength = TotalNumberofBlocks;

        BytesRemainingTobeRead = TransferLength * AtapiDevice->BlockSize;

        if (READWRITE) CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = SataDevInterface->WriteCommand;
        else CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = SataDevInterface->ReadCommand;
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = AtapiDevice->Lun << 5;
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[2] = (UINT8)(((UINT32) LBA) >>  24);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[3] = (UINT8)(((UINT32) LBA) >> 16);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[4] = (UINT8)(((UINT16) LBA) >> 8);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[5] = (UINT8)(((UINT8) LBA) & 0xff);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[7] = (UINT8) (TransferLength >> 8);        // MSB
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[8] = (UINT8) (TransferLength & 0xff);      // LSB
        CommandStructure.Buffer = TempBuffer;
        CommandStructure.ByteCount = (UINT32)BytesRemainingTobeRead;

        Status = ExecutePacketCommand(SataDevInterface, &CommandStructure, READWRITE);

        if (Status != EFI_SUCCESS) {

            // Some error has occured
            // Check if Device is getting ready. If yes, wait till it gets ready

            if (AtapiDevice->Atapi_Status == BECOMING_READY) {
                Status = TestUnitReady(SataDevInterface);
            }

            if (Status == EFI_MEDIA_CHANGED ) {
                Status = DetectAtapiMedia(SataDevInterface);
                if (Status == EFI_SUCCESS) return EFI_MEDIA_CHANGED;    // Return Media Change
                if (Status == EFI_NO_MEDIA) {
                    SataDevInterface->SataBlkIo->BlkIo.Media->MediaPresent = FALSE;
                    return Status;
                }
            }
            return Status;
        }

        if (CommandStructure.ByteCount != BytesRemainingTobeRead) return EFI_DEVICE_ERROR;

        // Update pointer

        (UINT8 *) TempBuffer += BytesRemainingTobeRead;
        LBA += TransferLength;
    }

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataReset
//
// Description: Reset ATA device
//
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL        *This,
//  IN BOOLEAN                      ExtendedVerification
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals: 
//
// Notes:
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataReset (
    IN EFI_BLOCK_IO_PROTOCOL        *This,
    IN BOOLEAN                      ExtendedVerification
 )
{
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataBlkFlush
//
// Description: Flush the cache
// Input:
//  IN EFI_BLOCK_IO_PROTOCOL            *This,
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals:  
//
// Notes:
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataBlkFlush(
    IN EFI_BLOCK_IO_PROTOCOL        *This
 )
{
    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataReadWritePio
//
// Description: Issues Read/Write Command and Read/Write the data from/to the ATA device
//
// Input:
//  IN IDE_BUS_PROTOCOL             *IdeBusInterface,
//  IN OUT VOID                     *Buffer,
//  UINTN                           ByteCount,
//  UINT64                          LBA
//  IN UINT8                        ReadWriteCommand,
//  IN BOOLEAN                      ReadWrite        Read/Write = 0/1
//
// Output:
//  *Buffer, EFI_STATUS
//
// Modified:
//      
// Referrals: ExecutePioDataCommand 
//
// Notes:   
//  1. Get the Max. number of sectors that can be Read/written in one Read/Write PIO command
//  2. Update the Command Structure
//  3. Issue ExecutePioDataCommand.
//  4. If all the bytes are read exit else goto step 2 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataReadWritePio(
    IN SATA_DEVICE_INTERFACE        *SataDevInterface,
    IN OUT VOID                     *Buffer,
    IN UINTN                        ByteCount,
    IN UINT64                       LBA,
    IN UINT8                        ReadWriteCommand,
    IN BOOLEAN                      READWRITE
 ) 
{
    EFI_STATUS                      Status;
    UINT32                          SectorCount;
    INT64                           MaxSectorCount;
    INT64                           Total_Number_Of_Sectors;
    COMMAND_STRUCTURE               CommandStructure;
    UINT32                          SectorSize = ATA_SECTOR_BYTES;
    UINT8                           *TempBuffer = Buffer;
    if (Check48BitCommand(ReadWriteCommand)) 
        MaxSectorCount = MAX_SECTOR_COUNT_PIO_48BIT;
    else 
        MaxSectorCount = MAX_SECTOR_COUNT_PIO;

    //
    // Calculate Sector Size
    //
    if((SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT14) && // WORD 106 valid? - BIT 14 - 1
       (!(SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT15)) && // WORD 106 valid? - BIT 15 - 0
       (SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT12)) { // WORD 106 bit 12 - Sectorsize > 256 words
        // The sector size is in words 117-118.
        SectorSize = (UINT32)(SataDevInterface->IdentifyData.Reserved_104_126[13] + \
                              (SataDevInterface->IdentifyData.Reserved_104_126[14] << 16)) * 2;
    }

    if (SectorSize > ByteCount) SectorSize = (UINT32)ByteCount;

    // Calculate the total number of Sectors to be transferred
    Total_Number_Of_Sectors = ByteCount / SectorSize ;

    for ( ;Total_Number_Of_Sectors > 0; Total_Number_Of_Sectors -= MaxSectorCount) {

        if (Total_Number_Of_Sectors > MaxSectorCount) SectorCount = 0;
        else SectorCount = (UINT32) Total_Number_Of_Sectors;

        ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

        if (Check48BitCommand (ReadWriteCommand)) {  
            CommandStructure.LBALowExp = (UINT8)Shr64(LBA,24);
            CommandStructure.LBAMidExp = (UINT8)Shr64(LBA,32);
            CommandStructure.LBAHighExp = (UINT8)Shr64(LBA,40);
            CommandStructure.Device = 0x40;                                 // 48Bit LBA
        }
        else {                                                              // 28 Bit LBA
            CommandStructure.Device = ((UINT8) ((UINT32) LBA >> 24) & 0x0f) | 0x40;   
        }
        
        CommandStructure.SectorCount = (UINT16) SectorCount;
        CommandStructure.LBALow = (UINT8)LBA;
        CommandStructure.LBAMid = (UINT8)(((UINT32)LBA >>8) & 0xff);
        CommandStructure.LBAHigh = (UINT8)(((UINT32)LBA >>16) & 0xff);
        CommandStructure.Command = ReadWriteCommand;

        CommandStructure.Buffer = TempBuffer;
        CommandStructure.ByteCount = (UINT32)(SectorCount == 0 ? MaxSectorCount : Total_Number_Of_Sectors) * SectorSize ;

        Status = ExecutePioDataCommand (SataDevInterface, &CommandStructure, READWRITE); // Returns # of bytes read

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

        TempBuffer += CommandStructure.ByteCount;
        SectorCount = CommandStructure.ByteCount / SectorSize ;
        LBA += SectorCount;

    }

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataPioDataOut
//
// Description: Issues Read/Write Command with SubCommand feature
//              and Reads/Writes data to the ATA device.
//
// Input:
//    IN SATA_DEVICE_INTERFACE        *SataDevInterface,
//    IN OUT VOID                     *Buffer,
//    IN UINTN                        ByteCount,
//    IN UINT8                        Features,
//    IN UINT16                       LBALow,
//    IN UINT8                        LBALowExp,
//    IN UINT8                        LBAMid,
//    IN UINT8                        LBAMidExp,
//    IN UINT8                        LBAHigh,
//    IN UINT8                        LBAHighExp,
//    IN UINT8                        ReadWriteCommand
//    IN BOOLEAN                      READWRITE
//
// Output:
//    EFI_STATUS
//
// Modified:
//      
// Referrals: ExecutePioDataCommand 
//
// Notes:   
//  1. Get the Max. number of sectors that can be transferred in one Read/Write PIO command
//  2. Update the Command Structure
//  3. Issue ExecutePioDataCommand.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS SataPioDataOut (
    IN SATA_DEVICE_INTERFACE        *SataDevInterface,
    IN OUT VOID                     *Buffer,
    IN UINTN                        ByteCount,
    IN UINT8                        Features,
    IN UINT8                        LBALow,
    IN UINT8                        LBALowExp,
    IN UINT8                        LBAMid,
    IN UINT8                        LBAMidExp,
    IN UINT8                        LBAHigh,
    IN UINT8                        LBAHighExp,
    IN UINT8                        ReadWriteCommand,
    IN BOOLEAN                      READWRITE
 )
{
    EFI_STATUS                      Status;
    UINT32                          SectorCount;
    INT64                           MaxSectorCount;
    INT64                           Total_Number_Of_Sectors;
    COMMAND_STRUCTURE               CommandStructure;
    UINT32                          SectorSize = ATA_SECTOR_BYTES;
    UINT64                          LBA = 0;
    UINT64                          LBAHighDword = 0;

    if (Check48BitCommand(ReadWriteCommand)) { 
        MaxSectorCount = MAX_SECTOR_COUNT_PIO_48BIT;
        //
        //	if 48 Bit LBA form Upper Dword
        //
        LBAHighDword |= LBAHighExp;
        LBAHighDword = ( Shl64(( Shl64( LBAHighDword, 8)| LBAMidExp), 8)| LBALowExp);
    } else { 
        MaxSectorCount = MAX_SECTOR_COUNT_PIO;
    }
    //
    //	Complete LBA
    //
    LBA |= LBAHigh;
    LBA = (( Shl64(( Shl64( LBA, 8) | LBAMid ), 8)| LBALow)| Shl64( LBAHighDword, 24 ));

    //
    // Calculate Sector Size
    //
    if((SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT14) && // WORD 106 valid? - BIT 14 - 1
       (!(SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT15)) && // WORD 106 valid? - BIT 15 - 0
       (SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT12)) { // WORD 106 bit 12 - Sectorsize > 256 words
        // The sector size is in words 117-118.
        SectorSize = (UINT32)(SataDevInterface->IdentifyData.Reserved_104_126[13] + \
                              (SataDevInterface->IdentifyData.Reserved_104_126[14] << 16)) * 2;
    }

    if (SectorSize > ByteCount) SectorSize = (UINT32)ByteCount;

    // Calculate the total number of Sectors to be transferred
    Total_Number_Of_Sectors = ByteCount / SectorSize ;

    for ( ;Total_Number_Of_Sectors > 0; Total_Number_Of_Sectors -= MaxSectorCount) {

        if ( Total_Number_Of_Sectors > MaxSectorCount ) SectorCount = 0;
        else SectorCount = (UINT32) Total_Number_Of_Sectors;

        ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

        if (Check48BitCommand (ReadWriteCommand)) {
            //
            // If 48Bit LBA then form Upper DWord  
            //
            CommandStructure.LBALowExp  = LBALowExp;
            CommandStructure.LBAMidExp  = LBAMidExp;
            CommandStructure.LBAHighExp = LBAHighExp;
            CommandStructure.Device     = 0x40;
        }
        else {                                                              // 28 Bit LBA
            CommandStructure.Device = ((UINT8) LBAHigh & 0x0f) | 0x40;   
        }

        CommandStructure.Features    = Features;                            // SubCommand
        CommandStructure.SectorCount = (UINT16) SectorCount;
        CommandStructure.LBALow      = LBALow;
        CommandStructure.LBAMid      = LBAMid;
        CommandStructure.LBAHigh     = LBAHigh;
        CommandStructure.Command     = ReadWriteCommand;

        CommandStructure.Buffer    = Buffer;
        CommandStructure.ByteCount = (UINT32)(SectorCount == 0 ? MaxSectorCount : Total_Number_Of_Sectors) * SectorSize ;

        Status = ExecutePioDataCommand (SataDevInterface, &CommandStructure, READWRITE); // Returns # of bytes read
        if (EFI_ERROR(Status)) return EFI_DEVICE_ERROR;

        SectorCount = CommandStructure.ByteCount / SectorSize ;
        LBA += SectorCount;

    }

    return EFI_SUCCESS;

}

//**********************************************************************
//<AMI_PHDR_START>
//
// Procedure:   SataReadWriteBusMaster
//
// Description: Issues Read/Write Command and Read/Write the data from/to the ATA device
//              using BusMaster
//
// Input:
//  SATA_DEVICE_INTERFACE           *SataDevInterface,
//  IN OUT VOID                     *Buffer,
//  IN UINTN                        ByteCount,
//  IN UINT64                       LBA,
//  IN UINT8                        ReadWriteCommand,
//  IN BOOLEAN                      READWRITE
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals: ExecuteDmaDataCommand
//
// Notes:   
//  1. Get the Max. number of sectors that can be Read/written in one Read/Write Bus master command
//  2. Update the Command Structure
//  3. Issue ExecutePioDataCommand.
//  4. If all the bytes are read exit else goto step 2 
//
//<AMI_PHDR_END>
//**********************************************************************                
EFI_STATUS
SataReadWriteBusMaster(
    SATA_DEVICE_INTERFACE           *SataDevInterface,
    IN OUT VOID                     *Buffer,
    IN UINTN                        ByteCount,
    IN UINT64                       LBA,
    IN UINT8                        ReadWriteCommand,
    IN BOOLEAN                      READWRITE
 ) 
{

    EFI_STATUS              Status;
    UINTN                   Total_Number_Of_Sectors,MaxSectorCount;
    UINTN                   CurrentSectorCount,CurrentByteCount;
    UINT8                   *TempBuffer = Buffer;
    COMMAND_STRUCTURE       CommandStructure;
    UINT32                  SectorSize = ATA_SECTOR_BYTES;

    if (Check48BitCommand(ReadWriteCommand)) 
        MaxSectorCount = MAX_SECTOR_COUNT_PIO_48BIT;
    else 
        MaxSectorCount = MAX_SECTOR_COUNT_PIO;

    //
    // Calculate Sector Size
    //
    if((SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT14) && // WORD 106 valid? - BIT 14 - 1
       (!(SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT15)) && // WORD 106 valid? - BIT 15 - 0
       (SataDevInterface->IdentifyData.Reserved_104_126[2] & BIT12)) { // WORD 106 bit 12 - Sectorsize > 256 words
        // The sector size is in words 117-118.
        SectorSize = (UINT32)(SataDevInterface->IdentifyData.Reserved_104_126[13] + \
                              (SataDevInterface->IdentifyData.Reserved_104_126[14] << 16)) * 2;
    }
    if (SectorSize > ByteCount) SectorSize = (UINT32)ByteCount;

    Total_Number_Of_Sectors = ByteCount / SectorSize ;

    do {
        if (Total_Number_Of_Sectors > MaxSectorCount) CurrentSectorCount = 0;
            else CurrentSectorCount = Total_Number_Of_Sectors;
        CurrentByteCount = (CurrentSectorCount == 0 ? MaxSectorCount : CurrentSectorCount) * SectorSize ;

        ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

        CommandStructure.Buffer = TempBuffer;
        CommandStructure.ByteCount = (UINT32)CurrentByteCount;
        CommandStructure.Command = ReadWriteCommand;

        if (Check48BitCommand (ReadWriteCommand)) {  
            // 48 Bit LBA   
            // Write the Upper LBA DWORD and Upper byte of Sector Count
            CommandStructure.LBALowExp = (UINT8)Shr64(LBA,24);
            CommandStructure.LBAMidExp = (UINT8) Shr64(LBA,32);
            CommandStructure.LBAHighExp = (UINT8) Shr64(LBA,40);
            CommandStructure.Device = 0x40;     // 48Bit LBA
        }
        else {                                                  // 28 Bit LBA
            CommandStructure.Device = ((UINT8) ((UINT32) LBA >> 24) & 0x0f) | 0x40;
        }

        CommandStructure.SectorCount = (UINT16) CurrentSectorCount;
        CommandStructure.LBALow = (UINT8)LBA;
        CommandStructure.LBAMid = (UINT8) (((UINT32)LBA >>8) & 0xff);
        CommandStructure.LBAHigh = (UINT8) (((UINT32)LBA >>16) & 0xff);

        Status = ExecuteDmaDataCommand (SataDevInterface, &CommandStructure, READWRITE); // Returns # of bytes read
        if (EFI_ERROR(Status)) return EFI_DEVICE_ERROR;

        CurrentByteCount = CommandStructure.ByteCount;
        CurrentSectorCount = CurrentByteCount / SectorSize;

        TempBuffer += CurrentByteCount;
        Total_Number_Of_Sectors -= (CurrentSectorCount == 0 ? MaxSectorCount : CurrentSectorCount);
        LBA += (CurrentSectorCount == 0 ? MaxSectorCount : CurrentSectorCount);

    } while (Total_Number_Of_Sectors);

    return EFI_SUCCESS;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   Check48BitCommand
//
// Description: Checks if the command is for 48-bit LBA
//
// Input:
//  IN UINT8            Command
//
// Output:
//      TRUE/FLASE
//
// Modified:
//      
// Referrals: 
//
// Notes:   
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
BOOLEAN
Check48BitCommand (
    IN UINT8                        Command
 )
{
    if ( Command == READ_SECTORS_EXT || 
         Command == READ_MULTIPLE_EXT || 
         Command == WRITE_SECTORS_EXT || 
         Command == WRITE_MULTIPLE_EXT ||
         Command == READ_DMA_EXT    ||
         Command == WRITE_DMA_EXT ) 
        return TRUE;
    else
        return FALSE; 
}   

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ExecuteNonDataCommand
//
// Description: Issue a  Non-Data command to the SATA Device
//
// Input:           
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface,  
//  IN COMMAND_STRUCTURE                   CommandStructure
//
// Output: 
//      EFI_STATUS     
//
// Modified:
//
// Referrals: StopController, ReadytoAcceptCmd, StartController, WaitforCommandComplete
//
// Notes:   
//  1. Stop the Controller
//  2. Check if the device is ready to accept a Command. 
//  3. Build Command list
//  4. Start the Controller.
//  5. Wait till command completes. Check for errors.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
ExecuteNonDataCommand (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
    IN COMMAND_STRUCTURE                   CommandStructure
)
{
    EFI_STATUS           Status;
    AHCI_BUS_PROTOCOL    *AhciBusInterface = SataDevInterface->AhciBusInterface; 
    AHCI_COMMAND_LIST    *CommandList = (AHCI_COMMAND_LIST *)(UINTN) SataDevInterface->PortCommandListBaseAddr;
    AHCI_COMMAND_TABLE   *Commandtable = (AHCI_COMMAND_TABLE *)(UINTN)AhciBusInterface->PortCommandTableBaseAddr;

    Status = StopController(AhciBusInterface, SataDevInterface,TRUE);
    if (EFI_ERROR(Status)) return Status;

    Status = ReadytoAcceptCmd(SataDevInterface);
    if (EFI_ERROR(Status)) {
        StopController(AhciBusInterface, SataDevInterface,FALSE);
        return Status;
    }

    BuildCommandList(SataDevInterface, CommandList, AhciBusInterface->PortCommandTableBaseAddr);
    BuildCommandFIS(SataDevInterface, CommandStructure, CommandList, Commandtable);

    // Data-in
    CommandList->Ahci_Cmd_W = 0; 
       
    // Update of Command Register
    Commandtable->CFis.Ahci_CFis_C = 1;

    StartController(AhciBusInterface, SataDevInterface, BIT00);

    Status = WaitforCommandComplete(SataDevInterface, NON_DATA_CMD, ATAPI_BUSY_CLEAR_TIMEOUT );
    
    //  Stop Controller
    StopController(AhciBusInterface, SataDevInterface,FALSE);

    return Status;    

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ExecutePioDataCommand
//
// Description: Ececute PIO Data In/Out command
//
// Input:           
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface,  
//  IN OUT COMMAND_STRUCTURE               *CommandStructure
//  IN BOOLEAN                             READWRITE
//
// Output:      
//         EFI_STATUS, CommandStructure->ByteCount 
//
// Modified:
//
// Referrals: StopController, ReadytoAcceptCmd, BuildCommandList, BuildCommandFIS, BuildAtapiCMD
//            BuildPRDT, StartController, WaitforCommandComplete
//  
// Notes:   
//  1. Stop the Controller
//  2. Check if the device is ready to accept a Command. 
//  3. Build Command list
//  4. Start the Controller.
//  5. Wait till command completes. Check for errors.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
ExecutePioDataCommand (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
    IN OUT COMMAND_STRUCTURE               *CommandStructure,
    IN BOOLEAN                             READWRITE
)
{
    EFI_STATUS              Status;
    AHCI_BUS_PROTOCOL       *AhciBusInterface = SataDevInterface->AhciBusInterface;
    AHCI_COMMAND_LIST       *CommandList = (AHCI_COMMAND_LIST *)(UINTN) SataDevInterface->PortCommandListBaseAddr;
    AHCI_COMMAND_TABLE      *Commandtable = (AHCI_COMMAND_TABLE *)(UINTN)AhciBusInterface->PortCommandTableBaseAddr;


    Status = StopController(AhciBusInterface, SataDevInterface,TRUE);
    if (EFI_ERROR(Status)) return Status;

    Status = ReadytoAcceptCmd(SataDevInterface);
    if (EFI_ERROR(Status)) {
        StopController(AhciBusInterface, SataDevInterface,FALSE);
        return Status;
    }
    BuildCommandList(SataDevInterface, CommandList, AhciBusInterface->PortCommandTableBaseAddr);
    BuildCommandFIS(SataDevInterface, *CommandStructure, CommandList, Commandtable);
    BuildAtapiCMD(SataDevInterface, *CommandStructure, CommandList, Commandtable);
    BuildPRDT(SataDevInterface, *CommandStructure, CommandList, Commandtable);

    if (READWRITE) {
        CommandList->Ahci_Cmd_W = 1;        
    }
    else {
        CommandList->Ahci_Cmd_W = 0;        
    }
    Commandtable->CFis.Ahci_CFis_C = 1;

    StartController(AhciBusInterface, SataDevInterface, BIT00);

    // For Security Erase command the time out value comes from Identify Data.    
    if(CommandStructure->Command == SECURITY_ERASE_UNIT ) {
        UINT32  EraseCommandTimeout;
        EraseCommandTimeout= (UINT32)(SataDevInterface->IdentifyData.Time_security_Earse_89);
        if(EraseCommandTimeout <= 254) {
            EraseCommandTimeout=EraseCommandTimeout * 2 * 1000 * 60; //Value * 2Minitues
        } else {
            EraseCommandTimeout= 0;                                 // No timeout
        }  
        Status = WaitforCommandComplete(SataDevInterface, PIO_DATA_IN_CMD, EraseCommandTimeout);
    } else {
        Status = WaitforCommandComplete(SataDevInterface, PIO_DATA_IN_CMD, 
                    SataDevInterface->DeviceType == ATA? DMA_ATA_COMMAND_COMPLETE_TIMEOUT \
                    : DMA_ATAPI_COMMAND_COMPLETE_TIMEOUT );
    }
    
    CommandStructure->ByteCount = CommandList->Ahci_Cmd_PRDBC;

    //  Stop Controller
    StopController(AhciBusInterface, SataDevInterface,FALSE);

    return Status;    

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ExecuteDmaDataCommand
//
// Description: 
//
// Input:           
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface,  
//  IN COMMAND_STRUCTURE                   *CommandStructure
//  IN BOOLEAN                              READWRITE
//
// Output:      
//  EFI_STATUS
//
// Modified:
//      
// Referrals: StopController, ReadytoAcceptCmd, BuildCommandList, BuildCommandFIS, BuildAtapiCMD
//            BuildPRDT, StartController, WaitforCommandComplete 
//
// Notes:   
//  1. Stop the Controller
//  2. Check if the device is ready to accept a Command. 
//  3. Build Command list
//  4. Start the Controller.
//  5. Wait till command completes. Check for errors.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
ExecuteDmaDataCommand (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
    IN COMMAND_STRUCTURE                   *CommandStructure,
    IN BOOLEAN                             READWRITE
)
{

    EFI_STATUS              Status;
    AHCI_BUS_PROTOCOL       *AhciBusInterface = SataDevInterface->AhciBusInterface;
    AHCI_COMMAND_LIST       *CommandList = (AHCI_COMMAND_LIST *)(UINTN) SataDevInterface->PortCommandListBaseAddr;
    AHCI_COMMAND_TABLE      *Commandtable = (AHCI_COMMAND_TABLE *)(UINTN)AhciBusInterface->PortCommandTableBaseAddr;


    Status = StopController(AhciBusInterface, SataDevInterface,TRUE);
    if (EFI_ERROR(Status)) return Status;

    Status = ReadytoAcceptCmd(SataDevInterface);
    if (EFI_ERROR(Status)) {
        StopController(AhciBusInterface, SataDevInterface,FALSE);
        return Status;
    }
    BuildCommandList(SataDevInterface, CommandList, AhciBusInterface->PortCommandTableBaseAddr);
    BuildCommandFIS(SataDevInterface, *CommandStructure, CommandList, Commandtable);
    BuildAtapiCMD(SataDevInterface, *CommandStructure, CommandList, Commandtable);
    BuildPRDT(SataDevInterface, *CommandStructure, CommandList, Commandtable);

    // Data-in
    if (READWRITE) {
        CommandList->Ahci_Cmd_W = 1;        
    }
    else {
        CommandList->Ahci_Cmd_W = 0  ;        
    }
    Commandtable->CFis.Ahci_CFis_C = 1;

    StartController(AhciBusInterface, SataDevInterface, BIT00);

    Status = WaitforCommandComplete(SataDevInterface, DMA_DATA_IN_CMD, 
                    SataDevInterface->DeviceType == ATA? DMA_ATA_COMMAND_COMPLETE_TIMEOUT \
                    : DMA_ATAPI_COMMAND_COMPLETE_TIMEOUT );
    
    if (!EFI_ERROR(Status)){
        //Check if the required BYTES have been received
        if (CommandList->Ahci_Cmd_PRDBC != CommandStructure->ByteCount){
            Status = EFI_DEVICE_ERROR;
        }
    }
    //  Stop Controller
    StopController(AhciBusInterface, SataDevInterface,FALSE);

    CommandStructure->ByteCount = CommandList->Ahci_Cmd_PRDBC;

    return Status;    

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ExecutePacketCommand
//
// Description: Execute a Atapi Packet command
//
// Input:           
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface,  
//  IN COMMAND_STRUCTURE                   *CommandStructure
//  IN BOOLEAN                              READWRITE
//
// Output:      
//  EFI_STATUS
//
// Modified:
//      
// Referrals: StopController, ReadytoAcceptCmd, BuildCommandList, BuildCommandFIS, BuildAtapiCMD
//            BuildPRDT, StartController, WaitforCommandComplete 
//
// Notes:   
//  1. Stop the Controller
//  2. Check if the device is ready to accept a Command. 
//  3. Build Command list
//  4. Start the Controller.
//  5. Wait till command completes. Check for errors.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS 
ExecutePacketCommand (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
    IN COMMAND_STRUCTURE                   *CommandStructure,
    IN BOOLEAN                             READWRITE
 )
{

    EFI_STATUS              Status;
    AHCI_BUS_PROTOCOL       *AhciBusInterface = SataDevInterface->AhciBusInterface;
    AHCI_COMMAND_LIST       *CommandList = (AHCI_COMMAND_LIST *)(UINTN) SataDevInterface->PortCommandListBaseAddr;
    AHCI_COMMAND_TABLE      *Commandtable = (AHCI_COMMAND_TABLE *)(UINTN)AhciBusInterface->PortCommandTableBaseAddr;
    UINT32                  AhciBaseAddr = (UINT32)AhciBusInterface->AhciBaseAddress;
    ATAPI_DEVICE            *AtapiDevice = SataDevInterface->AtapiDevice;
    UINT8                   Port = SataDevInterface->PortNumber;
    UINT8                   Data8;

    CommandStructure->LBAMid = (UINT8)(CommandStructure->ByteCount);
    CommandStructure->LBAHigh = (UINT8)(CommandStructure->ByteCount >> 8);
    CommandStructure->Command = PACKET_COMMAND;

    Status = StopController(AhciBusInterface, SataDevInterface,TRUE);
    if (EFI_ERROR(Status)) return Status;

    Status = ReadytoAcceptCmd(SataDevInterface);
    if (EFI_ERROR(Status)) {
        StopController(AhciBusInterface, SataDevInterface,FALSE);
        return Status;
    }
    BuildCommandList(SataDevInterface, CommandList, AhciBusInterface->PortCommandTableBaseAddr);
    BuildCommandFIS(SataDevInterface, *CommandStructure, CommandList, Commandtable);
    BuildAtapiCMD(SataDevInterface, *CommandStructure, CommandList, Commandtable);
    BuildPRDT(SataDevInterface, *CommandStructure, CommandList, Commandtable);

    if (READWRITE) {
        CommandList->Ahci_Cmd_W = 1;        
    }
    else {
        CommandList->Ahci_Cmd_W = 0;        
    }
    Commandtable->CFis.Ahci_CFis_C = 1;

    StartController(AhciBusInterface, SataDevInterface, BIT00);

    Status = WaitforCommandComplete(SataDevInterface, PIO_DATA_IN_CMD, 
                    SataDevInterface->DeviceType == ATA? DMA_ATA_COMMAND_COMPLETE_TIMEOUT \
                    : DMA_ATAPI_COMMAND_COMPLETE_TIMEOUT );


    // Handle ATAPI device error
    if (EFI_ERROR(Status) && SataDevInterface->DeviceType == ATAPI) {
        Data8 = HBA_PORT_REG8 (AhciBaseAddr, Port, HBA_PORTS_TFD);
        if (Data8 & CHK ){
            return HandleAtapiError(SataDevInterface);
            
        }        
    }
    AtapiDevice->Atapi_Status = EFI_SUCCESS;

    CommandStructure->ByteCount = CommandList->Ahci_Cmd_PRDBC;

    //  Stop Controller
    StopController(AhciBusInterface, SataDevInterface,FALSE);

    return Status;    

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   HandleAtapiError
//
// Description: Check for ATAPI Errors
//
// Input:           
//    IN SATA_DEVICE_INTERFACE               *SataDevInterface,
//
// Output:      
//  EFI_STATUS  
//
// Modified:
//      
// Referrals: ExecutePacketCommand
//
// Notes:   
//  1. Execute ATAPI Request Sense command.
//  2. Check for Device getting ready, Media Change, No Media and other errors. Update AtapiDevice->Atapi_Status
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
HandleAtapiError (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface
 )
{

    EFI_STATUS              Status;
    UINT8                   Data8 = 0;
    UINT8                   SenseData[256];
    COMMAND_STRUCTURE       CommandStructure;
    ATAPI_DEVICE            *AtapiDevice = SataDevInterface->AtapiDevice;
    AHCI_BUS_PROTOCOL       *AhciBusInterface = SataDevInterface->AhciBusInterface;
    UINT32                  AhciBaseAddr = (UINT32)AhciBusInterface->AhciBaseAddress;
    UINT8                   Port = SataDevInterface->PortNumber;

    AtapiDevice->Atapi_Status = DEVICE_ERROR;

    ZeroMemory (SenseData, 256);
    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

    CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = ATAPI_REQUEST_SENSE;
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[4] = 0xff;

    CommandStructure.ByteCount =  256;
    CommandStructure.Buffer = SenseData;

    Status = ExecutePacketCommand(SataDevInterface, &CommandStructure, 0);

    if (EFI_ERROR(Status)) {
        Data8 = HBA_PORT_REG8 (AhciBaseAddr, Port, HBA_PORTS_TFD);
    }

    SataDevInterface->AtapiSenseDataLength = 0;

    // Check for DF and CHK
    if (Data8 & (DF | CHK)) { 
        goto exit_HandleAtapiError_with_Reset;
    }    

    if (!EFI_ERROR(Status)){
        //
        // Store the SenseData whcih would be used by ScsiPassThruAtapi PassThru Interface.
        //
        pBS->CopyMem( SataDevInterface->AtapiSenseData, SenseData, 256);
        SataDevInterface->AtapiSenseDataLength = CommandStructure.ByteCount;

        AtapiDevice->Atapi_Status = DEVICE_ERROR;
        Status = EFI_DEVICE_ERROR;              // Default Value    

        if (((SenseData[2] & 0xf) == 2) && (SenseData[12] == 0x3a)) {
            Status = EFI_NO_MEDIA;
            AtapiDevice->Atapi_Status = MEDIUM_NOT_PRESENT;
        }
        if (((SenseData[2] & 0xf) == 2) && (SenseData[12] == 0x04) && (SenseData[13] == 0x01)) {
            Status = EFI_MEDIA_CHANGED;
            AtapiDevice->Atapi_Status = BECOMING_READY;
        }
    
        if (((SenseData[2] & 0xf) == 6) && (SenseData[12] == 0x28)){
                Status = EFI_MEDIA_CHANGED;
                AtapiDevice->Atapi_Status = MEDIA_CHANGED;
        }

        if (((SenseData[2] & 0xf) == 7) && (SenseData[12] == 0x27)){
                Status = EFI_WRITE_PROTECTED;
                AtapiDevice->Atapi_Status = WRITE_PROTECTED_MEDIA;
        }

        if (((SenseData[2] & 0xf) == 6) && (SenseData[12] == 0x29)){
                AtapiDevice->Atapi_Status = POWER_ON_OR_DEVICE_RESET;
        }

        if (((SenseData[2] & 0xf) == 5) && (SenseData[0] == 0x70)){
                AtapiDevice->Atapi_Status = ILLEGAL_REQUEST;
        }
    }    

exit_HandleAtapiError_with_Reset:
        return Status;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ReadWritePMPort
//
// Description: Read/Write routine to PM ports
//
// Input:           
//  IN SATA_DEVICE_INTERFACE       *SataDevInterface,
//  IN UINT8                        Port,
//  IN UINT8                        RegNum,
//  IN OUT UINT32                   *Data
//  IN BOOLEAN                      READWRITE       // TRUE for Write
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: StopController, ReadytoAcceptCmd, BuildCommandList, BuildCommandFIS, BuildAtapiCMD
//            BuildPRDT, StartController, WaitforCommandComplete 
//
// Notes:   
//  1. Update Command Structure for READ/Write Port Multiplier command
//  2. Issue command
//  3. Check for errors.
//  4. Read the out data in case of READ.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
ReadWritePMPort (
    IN SATA_DEVICE_INTERFACE        *SataDevInterface,
    IN UINT8                        Port,
    IN UINT8                        RegNum,
    IN OUT UINT32                   *Data,
    IN BOOLEAN                      READWRITE
)
{
    EFI_STATUS                  Status;
    COMMAND_STRUCTURE           CommandStructure;
    AHCI_RECEIVED_FIS           *PortFISBaseAddr = (AHCI_RECEIVED_FIS *)(UINTN)(SataDevInterface->PortFISBaseAddr);
    AHCI_BUS_PROTOCOL           *AhciBusInterface = SataDevInterface->AhciBusInterface; 
    AHCI_COMMAND_LIST           *CommandList = (AHCI_COMMAND_LIST *)(UINTN) SataDevInterface->PortCommandListBaseAddr;
    AHCI_COMMAND_TABLE          *Commandtable = (AHCI_COMMAND_TABLE *)(UINTN)AhciBusInterface->PortCommandTableBaseAddr;

    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

    CommandStructure.Command = READ_PORT_MULTIPLIER;

    if (READWRITE) {
        CommandStructure.SectorCount = (UINT16) (*Data & 0xFF);
        CommandStructure.LBALow = (UINT8) (*Data >> 8);
        CommandStructure.LBAMid = (UINT8)(*Data >> 16);
        CommandStructure.LBAHigh = (UINT8)(*Data >> 24);
        CommandStructure.Command = WRITE_PORT_MULTIPLIER;
    }

    CommandStructure.Device = Port;
    CommandStructure.Features = RegNum;

    Status = StopController(AhciBusInterface, SataDevInterface,TRUE);
    if (EFI_ERROR(Status)) return Status;

    Status = ReadytoAcceptCmd(SataDevInterface);
    if (EFI_ERROR(Status)) {
        StopController(AhciBusInterface, SataDevInterface,FALSE);
        return Status;
    }

    BuildCommandList(SataDevInterface, CommandList, AhciBusInterface->PortCommandTableBaseAddr);
    BuildCommandFIS(SataDevInterface, CommandStructure, CommandList, Commandtable);

    // Data-in
    CommandList->Ahci_Cmd_W = 0; 
       
    // Update of Command Register
    Commandtable->CFis.Ahci_CFis_C = 1;

    // Update the Port Address
    CommandList->Ahci_Cmd_PMP = CONTROL_PORT;
    Commandtable->CFis.AHci_CFis_PmPort = CONTROL_PORT; 

    StartController(AhciBusInterface, SataDevInterface, BIT00);

    Status = WaitforCommandComplete(SataDevInterface, NON_DATA_CMD, TIMEOUT_1SEC);
    
    //  Stop Controller
    StopController(AhciBusInterface, SataDevInterface,FALSE);

    if (!READWRITE) {
        *Data = 0;
        if (!EFI_ERROR(Status)) {
            *Data = PortFISBaseAddr->Ahci_Rfis[12] |    
                    (PortFISBaseAddr->Ahci_Rfis[4] << 8) |  
                    (PortFISBaseAddr->Ahci_Rfis[5] << 16) |     
                    (PortFISBaseAddr->Ahci_Rfis[6] << 24);  
        }
    }
    
    return Status;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   GetIdentifyData
//
// Description: Reaturn Identify data from SATA device
//
// Input:           
//    IN SATA_DEVICE_INTERFACE               *SataDevInterface,  
//
// Output:      
//      gIdentifyDataBuffer
//      EFI_STATUS
// Modified:
//      
// Referrals: 
//
// Notes:   
//  1. Build CommandStructure.
//  2. Issue ExecutePioDataCommand
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
GetIdentifyData (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface 
)
{
    EFI_STATUS                  Status;
    COMMAND_STRUCTURE           CommandStructure;
    IDENTIFY_DATA               tIdentifyData;

    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

    //  Read Identifydata
    CommandStructure.Buffer = &tIdentifyData;
    CommandStructure.ByteCount = sizeof(IDENTIFY_DATA);
    CommandStructure.Device = 0;
    CommandStructure.Command = SataDevInterface->DeviceType == ATA ? IDENTIFY_COMMAND : IDENTIFY_PACKET_COMMAND;

    Status = ExecutePioDataCommand (SataDevInterface, &CommandStructure, FALSE);
    
    if (CommandStructure.ByteCount != sizeof(IDENTIFY_DATA)) { Status = EFI_DEVICE_ERROR; }

    if(!EFI_ERROR(Status))
        pBS->CopyMem(&(SataDevInterface->IdentifyData), &tIdentifyData, sizeof(IDENTIFY_DATA)); 

    return Status;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataAtapiInquiryData
//
// Description: Return ATAPI Inquiry data
//
// Input:
//  IN SATA_DEVICE_INTERFACE           *SataDevInterface,
//  OUT UINT8                          *InquiryData,
//  IN OUT UINT16                      *InquiryDataSize
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals: ExecutePioDataCommand
//
// Notes:   
//  1. Update CommandStructure
//  2. Issue ExecutePioDataCommand
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataAtapiInquiryData (
    IN SATA_DEVICE_INTERFACE           *SataDevInterface,
    OUT UINT8                          *InquiryData,
    IN OUT UINT16                      *InquiryDataSize
)
{

    EFI_STATUS          Status;
    COMMAND_STRUCTURE   CommandStructure;
    
    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
    CommandStructure.Buffer = InquiryData;
    CommandStructure.ByteCount = *InquiryDataSize;
    CommandStructure.Command = PACKET_COMMAND;
    CommandStructure.LBAMid = (UINT8)*InquiryDataSize;
    CommandStructure.LBAHigh = (UINT8)(*InquiryDataSize >> 8);

    CommandStructure.AtapiCmd.Ahci_Atapi_Command[0]=ATAPI_INQUIRY;
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[4]=(UINT8)*InquiryDataSize;

    Status = ExecutePioDataCommand (SataDevInterface, &CommandStructure, 0); 

    if (!EFI_ERROR(Status)) {
        *InquiryDataSize = (UINT16)CommandStructure.ByteCount;
    }

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   DetectAtapiMedia
//
// Description: Detects whether a Media is present in the ATAPI Removable device or not.
//
// Input:
//  IN SATA_DEVICE_INTERFACE           *SataDevInterface,
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals: TestUnitReady, ExecutePacketCommand 
//
// Notes:   
//  1. Issue Read Capacity command for CDROM or Read Format command for other ATAPI devices.
//  2. If step 1  is successfull, update last LBA, Block Size, Read/Write capable, Media ID
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
DetectAtapiMedia(
    IN SATA_DEVICE_INTERFACE           *SataDevInterface
 )
{
    UINT8               *InputData, LoopCount;
    ATAPI_DEVICE        *AtapiDevice = SataDevInterface->AtapiDevice;
    EFI_BLOCK_IO_MEDIA  *BlkMedia = SataDevInterface->SataBlkIo->BlkIo.Media;
    EFI_STATUS          Status = EFI_NOT_FOUND;
    UINT16              ByteCount = 256, Data16;
    COMMAND_STRUCTURE   CommandStructure;
    BOOLEAN             ReadCapacity=FALSE;
    
    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

//  Default Values
    BlkMedia->MediaPresent = FALSE;
    BlkMedia->LastBlock = 0x100;                            // Dummy value
    SataDevInterface->ReadCommand = ATAPI_READ_10;  
    SataDevInterface->WriteCommand = ATAPI_WRITE_10;

    Status = TestUnitReady(SataDevInterface);
    if ((Status != EFI_MEDIA_CHANGED) && (Status != EFI_SUCCESS)) {
        return Status;
    }

//  Issue Read Capacity command
    Status = pBS->AllocatePool (EfiBootServicesData, ByteCount, (VOID**)&InputData);
    if (EFI_ERROR(Status)) return Status;

//  For CDROM use Read Capacity command else use Read Format Command
    if (AtapiDevice->DeviceType == CDROM_DEVICE){
        BlkMedia->BlockSize = CDROM_BLOCK_SIZE;         // Default size
        AtapiDevice->BlockSize = (UINT16)(BlkMedia->BlockSize);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = ATAPI_READ_CAPACITY;
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = AtapiDevice->Lun << 5;
        Data16 = 8;
    }
    else {
        BlkMedia->BlockSize = LS120_BLOCK_SIZE;         // Default Size
        AtapiDevice->BlockSize = (UINT16)(BlkMedia->BlockSize);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = ATAPI_READ_FORMAT_CAPACITIES;
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = AtapiDevice->Lun << 5;
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[7] = (UINT8)(ByteCount >> 8);
        CommandStructure.AtapiCmd.Ahci_Atapi_Command[8] = (UINT8)(ByteCount & 0xff);
        Data16 = ByteCount;
    }

    for (LoopCount  = 0; LoopCount < 5; LoopCount++) {          // 5sec loop
        ByteCount = Data16;
        ZeroMemory (InputData, ByteCount);
        CommandStructure.Buffer  = InputData;
        CommandStructure.ByteCount = ByteCount;
        Status = ExecutePacketCommand(SataDevInterface, &CommandStructure, 0);
        if(CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] == ATAPI_READ_FORMAT_CAPACITIES && 
            AtapiDevice->Atapi_Status == ILLEGAL_REQUEST) {
            //
            //If the Read Format Capacities not supported by device, try 
            //ReadCapacity command
            //
            ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
            BlkMedia->BlockSize = CDROM_BLOCK_SIZE;         // Default size
            AtapiDevice->BlockSize = (UINT16)(BlkMedia->BlockSize);
            CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = ATAPI_READ_CAPACITY;
            CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = AtapiDevice->Lun << 5;
            Data16 = 8;
            ReadCapacity=TRUE;
        }
        if (AtapiDevice->Atapi_Status == EFI_SUCCESS) break;
        if (AtapiDevice->Atapi_Status == MEDIUM_NOT_PRESENT) break;
    } 

    if (Status == EFI_SUCCESS) {
        if(ReadCapacity == TRUE) {
            BlkMedia->LastBlock = InputData[0] << 24 | InputData[1] << 16 | InputData[2] << 8 | InputData[3];
            BlkMedia->LastBlock--; 
            BlkMedia->MediaPresent = TRUE;
            BlkMedia->MediaId ++;
            BlkMedia->BlockSize = InputData[4] << 24 | InputData[5] << 16 | InputData[6] << 8 | InputData[7];
            AtapiDevice->BlockSize = BlkMedia->BlockSize;
            BlkMedia->ReadOnly = FALSE;
        } else if (AtapiDevice->DeviceType == CDROM_DEVICE) {
            BlkMedia->LastBlock = InputData[0] << 24 | InputData[1] << 16 | InputData[2] << 8 | InputData[3];
            BlkMedia->LastBlock--;
            BlkMedia->BlockSize = CDROM_BLOCK_SIZE;
            AtapiDevice->BlockSize = (UINT16)(BlkMedia->BlockSize);
            BlkMedia->MediaPresent = TRUE;
            BlkMedia->MediaId ++;
            BlkMedia->ReadOnly = TRUE;
        } else if (InputData[8] != 3) {         // No media present
            BlkMedia->LastBlock = InputData[4] << 24 | InputData[5] << 16 | InputData[6] << 8 | InputData[7];
            BlkMedia->LastBlock--; 
            BlkMedia->MediaPresent = TRUE;
            BlkMedia->MediaId ++;
            BlkMedia->BlockSize = InputData[9] << 16 | InputData[10] << 8 | InputData[11];
            BlkMedia->ReadOnly = FALSE;
            AtapiDevice->BlockSize = (UINT16)(BlkMedia->BlockSize);
        }

//      Update ReadOnly Status
        if (AtapiDevice->DeviceType != CDROM_DEVICE) {
            ByteCount = 256;
            ZeroMemory (InputData, ByteCount);
            ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
            CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = ATAPI_MODE_SENSE;
            CommandStructure.AtapiCmd.Ahci_Atapi_Command[2] = RETURN_ALL_PAGES;
            CommandStructure.AtapiCmd.Ahci_Atapi_Command[7] = (UINT8)(ByteCount >> 8);
            CommandStructure.AtapiCmd.Ahci_Atapi_Command[8] = (UINT8)(ByteCount & 0xff);
            CommandStructure.Buffer  = InputData;
            CommandStructure.ByteCount= ByteCount;
            Status = ExecutePacketCommand(SataDevInterface, &CommandStructure, 0);
            if ((Status == EFI_SUCCESS) && (ByteCount > 8)) {
                BlkMedia->ReadOnly = (InputData[3] & 0x80) != 0 ? TRUE : FALSE;
            }
        }
    }

    pBS->FreePool(InputData);
    return Status;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataCheckOddType
//
// Description: Return ODD type
//
// Input:
//  IN SATA_DEVICE_INTERFACE           *SataDevInterface,
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals: ExecutePioDataCommand
//
// Notes:   
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataGetOddType (
    IN SATA_DEVICE_INTERFACE           *SataDevInterface,
    IN OUT UINT16                      *OddType
)

{

    EFI_STATUS          Status;
    COMMAND_STRUCTURE   CommandStructure;
    UINT8               *ProfileData;    

    Status = pBS->AllocatePool (EfiBootServicesData,16,(VOID**)&ProfileData);

    if (EFI_ERROR(Status)) {
        return Status;
    }
    
    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
    CommandStructure.Buffer = ProfileData;
    CommandStructure.ByteCount = 16;
    CommandStructure.Command = PACKET_COMMAND;
    CommandStructure.LBAMid = 16;
    CommandStructure.LBAHigh = 0;

    CommandStructure.AtapiCmd.Ahci_Atapi_Command[0]= ATAPI_GET_CONFIGURATION;
    //
    // Get the Feature Discriptor.
    //
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = FEATURE_DISCRIPTOR;
    //
    // Get the Profile list
    //
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[3] = GET_PROFILE_LIST;
    //
    // Responce Data Size
    //
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[8] = 0x10;

    Status = ExecutePioDataCommand (SataDevInterface, &CommandStructure, 0); 

    if (!EFI_ERROR(Status)) {
        //
        // Get the Profile Number
        //
        *OddType=(UINT16 )(((ProfileData[sizeof(GET_CONFIGURATION_HEADER)+4]) << 8) + ProfileData[sizeof(GET_CONFIGURATION_HEADER)+5]);
    }
   
    pBS->FreePool(ProfileData);
    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   SataGetOddLoadingType
//
// Description: Return ODD Loading type information
//
// Input:
//  IN SATA_DEVICE_INTERFACE           *SataDevInterface,
//
// Output:
//  EFI_STATUS
//
// Modified:
//      
// Referrals: ExecutePioDataCommand
//
// Notes:   
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
SataGetOddLoadingType (
    IN SATA_DEVICE_INTERFACE           *SataDevInterface,
    IN OUT UINT8                       *OddLoadingType
)

{

    EFI_STATUS          Status;
    COMMAND_STRUCTURE   CommandStructure;
    UINT8               *ProfileData;    

    Status = pBS->AllocatePool (EfiBootServicesData,16,(VOID**)&ProfileData);

    if (EFI_ERROR(Status)) {
        return Status;
    }
    
    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
    CommandStructure.Buffer = ProfileData;
    CommandStructure.ByteCount = 16;
    CommandStructure.Command = PACKET_COMMAND;
    CommandStructure.LBAMid = 16;
    CommandStructure.LBAHigh = 0;

    CommandStructure.AtapiCmd.Ahci_Atapi_Command[0]= ATAPI_GET_CONFIGURATION;
    //
    // Get the Feature Discriptor.
    //
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = FEATURE_DISCRIPTOR;
    //
    // Get the Removable Medium feature
    //
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[3] = GET_REMOVEABLE_MEDIUM_FEATURE;
    //
    // Responce Data Size
    //
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[8] = 0x10;

    Status = ExecutePioDataCommand (SataDevInterface, &CommandStructure, 0); 

    if (!EFI_ERROR(Status)) {
        //
        // Get the ODD Loading Type
        //
        *OddLoadingType=(UINT8 )(((ProfileData[sizeof(GET_CONFIGURATION_HEADER)+4]) & 0xE0) >> 5);
    }
   
    pBS->FreePool(ProfileData);
    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   TestUnitReady
//
// Description: Issues Start/Stop unit Command
//
// Input:
//  IN SATA_DEVICE_INTERFACE           *SataDevInterface
//
// Output:
//      EFI_STATUS          EFI_SUCCESS           : If Media is accessible
//                          EFI_NO_MEDIA
//                          EFI_MEDIA_CHANGED
//                          EFI_DEVICE_ERROR
//
// Modified:
//      
// Referrals: ExecutePacketCommand
//
// Notes:   
//  1. Update CommandStructure for ATAPI_TEST_UNIT_READY command
//  2. Issue ExecutePacketCommand
//  3. Check if the device is ready to accept command, whether Media is present or not.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
TestUnitReady(
    IN SATA_DEVICE_INTERFACE           *SataDevInterface
 )
{

    EFI_STATUS                      Status = EFI_SUCCESS;
    ATAPI_DEVICE                    *AtapiDevice = SataDevInterface->AtapiDevice;
    UINT16                          LoopCount;
    COMMAND_STRUCTURE               CommandStructure;
    
    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[0] = ATAPI_TEST_UNIT_READY;
    CommandStructure.AtapiCmd.Ahci_Atapi_Command[1] = AtapiDevice->Lun << 5;
    CommandStructure.Buffer  = NULL;
    CommandStructure.ByteCount  =  0x100;

    for (LoopCount  = 0; LoopCount < 1000; LoopCount++) {           // 10sec loop ( 1000 * 10 msec = 10Sec)
        Status = ExecutePacketCommand(SataDevInterface, &CommandStructure, 0);
        if (Status == EFI_SUCCESS) break;
        if (AtapiDevice->Atapi_Status == MEDIUM_NOT_PRESENT) break;
        if (AtapiDevice->Atapi_Status == MEDIA_CHANGED) break;
        pBS->Stall(10000); // 10msec
    } 

    return Status;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   BuildCommandList
//
// Description: Builds command list
//
// Input:           
//  IN SATA_DEVICE_INTERFACE            *SataDevInterface,  
//  IN AHCI_COMMAND_LIST                *CommandList,
//  IN UINT32                           CommandTableBaseAddr
//
// Output:      
//  EFI_STATUS
//  
// Modified:
//      
// Referrals: 
//
// Notes:   
//  1. Update CommandList bits
//  2. Not all fields like Ahci_Cmd_A are updated.
//  3. Port number is set to 0xF (Control port) if PM Port number is 0xFF.  
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
BuildCommandList (
    IN SATA_DEVICE_INTERFACE            *SataDevInterface, 
    IN AHCI_COMMAND_LIST                *CommandList,
    IN UINT32                           CommandTableBaseAddr
)
{

 
    ZeroMemory (CommandList, sizeof(AHCI_COMMAND_LIST));
    // CommandList->Ahci_Cmd_A = SataDevInterface->DeviceType == ATAPI ? 1 : 0;      // set elsewhere 
    CommandList->Ahci_Cmd_P = 0;       
    CommandList->Ahci_Cmd_R = 0;       
    CommandList->Ahci_Cmd_B = 0;       
    CommandList->Ahci_Cmd_Rsvd1 = 0;       
    CommandList->Ahci_Cmd_PMP = SataDevInterface->PMPortNumber == 0xFF ? 0x0 : SataDevInterface->PMPortNumber;       
    CommandList->Ahci_Cmd_PRDTL = 0;       
    CommandList->Ahci_Cmd_PRDBC = 0;       
    CommandList->Ahci_Cmd_CTBA = CommandTableBaseAddr;       
    CommandList->Ahci_Cmd_CTBAU = 0;

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   BuildCommandFIS
//
// Description: Build Command FIS
//
// Input:           
//  IN SATA_DEVICE_INTERFACE                *SataDevInterface,  
//  IN COMMAND_STRUCTURE                    CommandStructure,
//  IN AHCI_COMMAND_LIST                    *CommandList,
//  IN AHCI_COMMAND_TABLE                   *Commandtable
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: 
//
// Notes:   
//  1. Update Command FIS data area.
//  2. Update the Command FIS lenght in Command List table  
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
BuildCommandFIS (
    IN SATA_DEVICE_INTERFACE                *SataDevInterface, 
    IN COMMAND_STRUCTURE                    CommandStructure,
    IN AHCI_COMMAND_LIST                    *CommandList,
    IN AHCI_COMMAND_TABLE                   *Commandtable
)
{


    ZeroMemory (Commandtable, sizeof(AHCI_COMMAND_TABLE));

    Commandtable->CFis.Ahci_CFis_Type = FIS_REGISTER_H2D;
    Commandtable->CFis.AHci_CFis_PmPort = SataDevInterface->PMPortNumber == 0xFF ? 0x0 : SataDevInterface->PMPortNumber;
//  Commandtable->CFis.Ahci_CFis_C = 1;          // Set elsewhere
    Commandtable->CFis.Ahci_CFis_Cmd = CommandStructure.Command;

    Commandtable->CFis.Ahci_CFis_Features = CommandStructure.Features;
    Commandtable->CFis.Ahci_CFis_FeaturesExp = CommandStructure.FeaturesExp;

    Commandtable->CFis.Ahci_CFis_SecNum = CommandStructure.LBALow;
    Commandtable->CFis.Ahci_CFis_SecNumExp = CommandStructure.LBALowExp;

    Commandtable->CFis.Ahci_CFis_ClyLow = CommandStructure.LBAMid;
    Commandtable->CFis.Ahci_CFis_ClyLowExp = CommandStructure.LBAMidExp;

    Commandtable->CFis.Ahci_CFis_ClyHigh = CommandStructure.LBAHigh;
    Commandtable->CFis.Ahci_CFis_ClyHighExp = CommandStructure.LBAHighExp;

    Commandtable->CFis.Ahci_CFis_SecCount = (UINT8)(CommandStructure.SectorCount);
    Commandtable->CFis.Ahci_CFis_SecCountExp = (UINT8)(CommandStructure.SectorCount >> 8);

    Commandtable->CFis.Ahci_CFis_DevHead = CommandStructure.Device;
    Commandtable->CFis.Ahci_CFis_Control = CommandStructure.Control;    

    CommandList->Ahci_Cmd_CFL = FIS_REGISTER_H2D_LENGTH / 4;

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   BuildAtapiCMD
//
// Description: 
//
// Input:           
//  IN SATA_DEVICE_INTERFACE                *SataDevInterface,  
//  IN COMMAND_STRUCTURE                    CommandStructure
//  IN AHCI_COMMAND_LIST                    *CommandList,
//  IN AHCI_COMMAND_TABLE                   *Commandtable
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: 
//
// Notes:
//  1. Copy Packet data to command table
//  2. Set Atapi bit in Command List    
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
BuildAtapiCMD(
    IN SATA_DEVICE_INTERFACE                *SataDevInterface, 
    IN COMMAND_STRUCTURE                    CommandStructure,
    IN AHCI_COMMAND_LIST                    *CommandList,
    IN AHCI_COMMAND_TABLE                   *Commandtable
)
{


    pBS->CopyMem(&(Commandtable->AtapiCmd),&(CommandStructure.AtapiCmd),sizeof(AHCI_ATAPI_COMMAND));

    if (Commandtable->CFis.Ahci_CFis_Cmd == PACKET_COMMAND){ // Is it a packet command?         
        CommandList->Ahci_Cmd_A = 1;
    }

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   BuildPRDT
//
// Description: Build PRDT table
//
// Input:           
//  IN SATA_DEVICE_INTERFACE                *SataDevInterface,  
//  IN COMMAND_STRUCTURE                    CommandStructure
//  IN AHCI_COMMAND_LIST                    *CommandList,
//  IN AHCI_COMMAND_TABLE                   *Commandtable
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: 
//
// Notes:
//  1. Build as many PRDT table entries based on ByteCount.
//  2. Set the I flag for the lasr PRDT table.
//  3. Update PRDT table lenght in CommandList
//  
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
BuildPRDT (
    IN SATA_DEVICE_INTERFACE                *SataDevInterface, 
    IN COMMAND_STRUCTURE                    CommandStructure,
    IN AHCI_COMMAND_LIST                    *CommandList,
    IN AHCI_COMMAND_TABLE                   *Commandtable
)
{

    AHCI_BUS_PROTOCOL       *AhciBusInterface = SataDevInterface->AhciBusInterface; 
    UINT32                  ByteCount = CommandStructure.ByteCount;
    UINT16                  Prdtlength = 0;
    AHCI_COMMAND_PRDT       *PrdtTable = &(Commandtable->PrdtTable);

    for (;ByteCount; (UINT8 *)PrdtTable += sizeof(AHCI_COMMAND_PRDT)){
        PrdtTable->Ahci_Prdt_DBA = (UINT32)(UINTN)CommandStructure.Buffer;
        PrdtTable->Ahci_Prdt_DBAU = (UINT32)Shr64((UINTN)CommandStructure.Buffer, 32);
        PrdtTable->Ahci_Prdt_DBC = ByteCount >= PRD_MAX_DATA_COUNT ? (PRD_MAX_DATA_COUNT - 1) : (ByteCount - 1);
        ByteCount -= (PrdtTable->Ahci_Prdt_DBC + 1);
        PrdtTable->Ahci_Prdt_I = 0;
        Prdtlength+= sizeof(AHCI_COMMAND_PRDT);
        if ((UINT32)(Prdtlength + 0x80) >= AhciBusInterface->PortCommandTableLength) {
            //ASSERT_EFI_ERROR(EFI_OUT_OF_RESOURCES);
            break;
        }
        (UINT8 *)CommandStructure.Buffer += PrdtTable->Ahci_Prdt_DBC + 1;
    }
    //  Set I flag only for the last entry.
    (UINT8 *)PrdtTable -= sizeof(AHCI_COMMAND_PRDT);
    PrdtTable->Ahci_Prdt_I = 1;
    CommandList->Ahci_Cmd_PRDTL = Prdtlength / sizeof(AHCI_COMMAND_PRDT);

    return EFI_SUCCESS;

}

 
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   StartController
//
// Description: 
//
// Input:           
//    IN AHCI_BUS_PROTOCOL                  *AhciBusInterface,
//    IN SATA_DEVICE_INTERFACE              *SataDevInterface,
//    IN UINT32                             CIBitMask
//
// Output:      
//  EFI_STATUS
// Modified:
//
// Referrals: 
//
// Notes:   
//  1. Clear Status register
//  2. Enable FIS and CR running bit
//  3. Enable Start bit
//  4. Update CI bit mask
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
StartController (
    IN AHCI_BUS_PROTOCOL                    *AhciBusInterface, 
    IN SATA_DEVICE_INTERFACE                *SataDevInterface,
    IN UINT32                               CIBitMask
)
{

    UINT32      AhciBaseAddr = (UINT32)(AhciBusInterface->AhciBaseAddress);
    UINT8       Port = SataDevInterface->PortNumber;

    // Clear Status
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_SERR, HBA_PORTS_ERR_CLEAR); 
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_IS, HBA_PORTS_IS_CLEAR); 

    // Enable FIS Receive
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_CMD, HBA_PORTS_CMD_FRE);     

    // Wait till FIS is running
    WaitForMemSet(AhciBaseAddr, Port, HBA_PORTS_CMD,
                                    HBA_PORTS_CMD_FR,
                                    HBA_PORTS_CMD_FR,
                                    HBA_FR_CLEAR_TIMEOUT);

    // Clear FIS Receive area
    ZeroMemory ((VOID *)(UINTN)SataDevInterface->PortFISBaseAddr, RECEIVED_FIS_SIZE);

    // Enable ST
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_CMD, HBA_PORTS_CMD_ST);

    // Enable Command Issued
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_CI, CIBitMask);

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   WaitforCommandComplete
//
// Description: Wait till cmd completes
//
// Input:           
//    IN SATA_DEVICE_INTERFACE               *SataDevInterface,
//    IN COMMAND_TYPE                        CommandType,
//    IN UINTN                               TimeOut
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: 
//
// Notes:
//  1. Check for SError bits. If set return error.
//  2. For PIO IN/Out and Packet IN/OUT command wait till PIO Setup FIS is received
//  3. If D2H register FIS is received, exit the loop.
//  4. Check for SError and TFD bits.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
WaitforCommandComplete  (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface,
    IN COMMAND_TYPE                        CommandType,
    IN UINTN                               TimeOut    
)
{

    AHCI_BUS_PROTOCOL  *AhciBusInterface = SataDevInterface->AhciBusInterface; 
    UINT32      AhciBaseAddr = (UINT32)AhciBusInterface->AhciBaseAddress;
    UINT8       Port = SataDevInterface->PortNumber;
    UINT32      Data32_SERR, Data32_IS, i;
    BOOLEAN     PxSERR_ERROR = FALSE, PIO_SETUP_FIS = FALSE;
    volatile AHCI_RECEIVED_FIS   *FISReceiveAddress = (AHCI_RECEIVED_FIS *)(UINTN)SataDevInterface->PortFISBaseAddr;
    UINTN       TimeOutCount = TimeOut;

    i=0;
    do {
        pBS->Stall(500);

        //  Check for Error bits
        Data32_SERR = HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_SERR);
        if (Data32_SERR & HBA_PORTS_ERR_CHK) {
            PxSERR_ERROR = TRUE;
            break;
        }

        //  Check for Error bits
        Data32_IS = HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_IS);
        if (Data32_IS & HBA_PORTS_IS_ERR_CHK) {
            PxSERR_ERROR = TRUE;
            break;
        }
        
        switch (CommandType) {

            case PIO_DATA_IN_CMD:
            case PIO_DATA_OUT_CMD:
            case PACKET_PIO_DATA_IN_CMD:
            case PACKET_PIO_DATA_OUT_CMD:
                // check if PIO setup received
                if(FISReceiveAddress->Ahci_Psfis[0] == FIS_PIO_SETUP) {
                    FISReceiveAddress->Ahci_Psfis[0] = 0;
                    TimeOutCount = TimeOut;
                    PIO_SETUP_FIS = TRUE;                         
                }
                break;
            default: 
                break;
            
        }

        // check if D2H register FIS is received
        if(FISReceiveAddress->Ahci_Rfis[0] == FIS_REGISTER_D2H) break;

        // For PIO Data in D2H register FIS is not received. So rely on BSY bit
        if ((CommandType == PIO_DATA_IN_CMD) &&  PIO_SETUP_FIS &&
                    !((HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_TFD) & 
                    (HBA_PORTS_TFD_BSY | HBA_PORTS_TFD_DRQ)))){
            break;
        }
        //If the Timeout is 0, Then there is no timeout for command processing  
        if(TimeOut==0) {
            continue;
        }
        i++;
    } while(i < TimeOutCount * 2);

    if (PxSERR_ERROR) {
        // clear the status and return error
        HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_SERR, HBA_PORTS_ERR_CLEAR); 
        HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_IS, HBA_PORTS_IS_CLEAR);         
        return EFI_DEVICE_ERROR;    
    }    

    // check if CI register is zero
    if (HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_CI)){
        return EFI_DEVICE_ERROR;                
    }

    // check for status bits
    if (HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_TFD) & (HBA_PORTS_TFD_ERR | HBA_PORTS_TFD_DRQ)){
        return EFI_DEVICE_ERROR;                
    }

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   StopController
//
// Description: Stop FIS and CR
//
// Input:           
//    IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
//    IN SATA_DEVICE_INTERFACE               *SataDevInterface
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: GeneratePortReset
//
// Notes:
//  1. clear ST bit and wait till CR bits gets reset
//  2. if not generate Port reset
//  3. Clear FIS running bit.
//  4. Clear status register
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
StopController(
    IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
    IN SATA_DEVICE_INTERFACE               *SataDevInterface,
    IN BOOLEAN                              StartOrStop
) 
{

    UINT8       Port = SataDevInterface->PortNumber;
    UINT8       PMPort = SataDevInterface->PMPortNumber;
    UINT32      AhciBaseAddr = (UINT32)(AhciBusInterface->AhciBaseAddress);
    EFI_STATUS  Status;
    UINT32      PortFISBaseAddr = SataDevInterface->PortFISBaseAddr;
    UINT32      CommandListBaseAddress = SataDevInterface->PortCommandListBaseAddr;
    UINT32      Data32;

    if(StartOrStop && (HBA_PORT_REG32(AhciBaseAddr,Port,HBA_PORTS_CLB) != CommandListBaseAddress)) {
        gCommandListBaseAddress=HBA_PORT_REG32(AhciBaseAddr,Port,HBA_PORTS_CLB);
        gFisBaseAddress=HBA_PORT_REG32(AhciBaseAddr,Port,HBA_PORTS_FB);
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_CLB,CommandListBaseAddress);
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_FB,PortFISBaseAddr);
        
        //
        // Saving the Upper 32 bits of FIS and Command List Registers
        //
        gCommandListBaseAddress2=HBA_PORT_REG32(AhciBaseAddr,Port,HBA_PORTS_CLBU);
        gFisBaseAddress2=HBA_PORT_REG32(AhciBaseAddr,Port,HBA_PORTS_FBU);
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_CLBU,0);
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_FBU,0);
    }

    // Clear Start
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_CMD, ~(HBA_PORTS_CMD_ST));
    // Make sure CR is 0 with in 500msec
    Status = WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CMD,
                            HBA_PORTS_CMD_CR,
                            HBA_CR_CLEAR_TIMEOUT);

    if (EFI_ERROR(Status)) { 

        // Get the Port Speed allowed and Interface Power Management Transitions Allowed
        // Pass the values for PortReset. 
        Data32 = HBA_PORT_REG32 ((UINT32)(AhciBusInterface->AhciBaseAddress), Port, HBA_PORTS_SCTL);
        Data32 &= 0xFF0;          

        Status = GeneratePortReset(AhciBusInterface, SataDevInterface, Port, PMPort,
                                    (UINT8)((Data32 & 0xF0) >> 4), (UINT8)(Data32 >> 8));
    };

    if (EFI_ERROR(Status)) {
        goto StopController_ErrorExit;
    }

    //  Clear FIS receive enable.
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, 
                                    HBA_PORTS_CMD, ~(HBA_PORTS_CMD_FRE));
    //  Make sure FR is 0 with in 500msec
    Status = WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CMD,
                            HBA_PORTS_CMD_FR,
                            HBA_FR_CLEAR_TIMEOUT);


StopController_ErrorExit:

    // Clear Status register
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_SERR, HBA_PORTS_ERR_CLEAR); 
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_IS, HBA_PORTS_IS_CLEAR); 

    if(!StartOrStop  && gCommandListBaseAddress) {
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_CLB,gCommandListBaseAddress);
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_FB,gFisBaseAddress);
        //
        // Restoring the Upper 32 bits of FIS and Command List Registers
        //
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_CLBU,gCommandListBaseAddress2);
        HBA_PORT_WRITE_REG32(AhciBaseAddr,Port,HBA_PORTS_FBU,gFisBaseAddress2);

        gCommandListBaseAddress = 0;
    }

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ReadytoAcceptCmd
//
// Description: Check if the device is ready to accept cmd.
//
// Input:           
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface,
//
// Output:
//  EFI_STATUS      
//
// Modified:
//      
// Referrals: GeneratePortReset, ReadWritePMPort
//
// Notes:
//  1. Check the device is ready to accept the command. BSY and DRQ should be de-asserted.  
//  2. If set, generate Port reset
//  3. In case Port Multiplier is connected to the port, enable all the ports of the Port Multiplier.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
ReadytoAcceptCmd (
    IN SATA_DEVICE_INTERFACE               *SataDevInterface
)
{

    EFI_STATUS              Status = EFI_SUCCESS;
    AHCI_BUS_PROTOCOL       *AhciBusInterface = SataDevInterface->AhciBusInterface; 
    UINT32                  AhciBaseAddr = (UINT32)(AhciBusInterface->AhciBaseAddress);
    UINT8                   Port = SataDevInterface->PortNumber;
    UINT8                   PMPort = SataDevInterface->PMPortNumber;
    SATA_DEVICE_INTERFACE   *SataPMDevInterface, *SataPMPortDevInterface;
    UINT32                  Data32 = 0, Init_SStatus = 0;
    UINT8                   PowerManagement, Speed;

    // Is the Device ready to accept the command
    if (HBA_PORT_REG8 (AhciBaseAddr, Port, HBA_PORTS_TFD) & (HBA_PORTS_TFD_BSY | HBA_PORTS_TFD_DRQ)){
        Data32 = HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_SCTL);
        Data32 &= 0xFF0;          
        // make sure the status we read is for the right port
        Status = GeneratePortReset(AhciBusInterface, SataDevInterface, Port, 0xFF,
                          (UINT8)((Data32 & 0xF0) >> 4), (UINT8)(Data32 >> 8));
        if (EFI_ERROR(Status)) return Status;

        // If it is a PMPort, Make sure all the Ports are in enabled state.
        SataPMDevInterface = GetSataDevInterface(AhciBusInterface, Port, 0xFF);
        if (!SataPMDevInterface) { 
            return EFI_DEVICE_ERROR;
        }
        if (SataPMDevInterface->DeviceType == PMPORT) {
            for (PMPort = 0; PMPort < SataPMDevInterface->NumPMPorts; PMPort++){
                SataPMPortDevInterface = GetSataDevInterface(AhciBusInterface, Port, PMPort);
                if (!SataPMPortDevInterface) continue;
                    ReadWritePMPort (SataDevInterface, PMPort, PSCR_0_SSTATUS, &Init_SStatus, FALSE);
                    if ((Init_SStatus & HBA_PORTS_SSTS_DET_MASK) == HBA_PORTS_SSTS_DET_PCE) { 
                        Data32 = SataPMPortDevInterface->SControl;
                        ReadWritePMPort (SataDevInterface, PMPort, PSCR_2_SCONTROL, &Data32, TRUE);
                    }
                    else {
                        Speed = (UINT8)((SataDevInterface->SControl >> 4) & 0xF);
                        PowerManagement = (UINT8)((SataDevInterface->SControl >> 8) & 0xF);
                        GeneratePortReset(AhciBusInterface, SataDevInterface, Port, PMPort, 
                                            Speed, PowerManagement);
                    }
                    Data32 = HBA_PORTS_ERR_CLEAR;
                    ReadWritePMPort (SataDevInterface, PMPort, PSCR_1_SERROR, &Data32, TRUE);
                }
        }
    } 
    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   HostReset
//
// Description: 
//
// Input:           
//  IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
//
// Output:      
//
// Modified:
//      
//
// Referrals: 
//
// Notes:   
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
HostReset (
    IN AHCI_BUS_PROTOCOL                   *AhciBusInterface 
)
{

    return EFI_SUCCESS;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   GeneratePortReset
//
// Description: Issue a Port Reset
//
// Input:           
//  IN AHCI_BUS_PROTOCOL                   *AhciBusInterface
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
//  IN UINT8                               CurrentPort, 
//  IN UINT8                               Speed,
//  IN UINT8                               PowerManagement
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: ReadWritePMPort, HandlePortComReset
//
// Notes:   
//  1. Issue port reset by setting DET bit in SControl register
//  2. Call HandlePortComReset to check the status of the reset.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
GeneratePortReset (
    AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
    SATA_DEVICE_INTERFACE               *SataDevInterface, 
    UINT8                               Port,
    UINT8                               PMPort,
    UINT8                               Speed,
    UINT8                               PowerManagement
)
{

    EFI_STATUS  Status;
    UINT32      AhciBaseAddr = (UINT32) AhciBusInterface->AhciBaseAddress;
    volatile    AHCI_RECEIVED_FIS  *FISAddress =  (AHCI_RECEIVED_FIS *)HBA_PORT_REG32(AhciBaseAddr, Port, HBA_PORTS_FB);
    UINT32      Data32;

    TRACE_AHCI_LEVEL2((-1,"AHCI: PortReset on Port : %x PMPort : %x", Port, PMPort));

    if (!FISAddress) return EFI_DEVICE_ERROR;   // FIS receive address is not programmed.

    if (gPortReset) return EFI_SUCCESS;
    gPortReset = TRUE;

    // Disable Start bit
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_CMD, ~HBA_PORTS_CMD_ST);

    // Wait till CR is cleared    
    Status = WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CMD,
                            HBA_PORTS_CMD_CR,
                            HBA_CR_CLEAR_TIMEOUT);

    // Clear Status register
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_SERR, HBA_PORTS_ERR_CLEAR); 
    if (PMPort != 0xFF) {
        Data32 = HBA_PORTS_ERR_CLEAR;
        ReadWritePMPort (SataDevInterface, PMPort, PSCR_1_SERROR, &Data32, TRUE);
    }
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_IS, HBA_PORTS_IS_CLEAR); 
    
    //  Enable FIS Receive Enable
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_CMD, HBA_PORTS_CMD_FRE);     

    // Wait till FIS is running and then clear the data area
    WaitForMemSet(AhciBaseAddr, Port, HBA_PORTS_CMD,
                                    HBA_PORTS_CMD_FR,
                                    HBA_PORTS_CMD_FR,
                                    HBA_FR_CLEAR_TIMEOUT);

        
    FISAddress->Ahci_Rfis[0] = 0;

    if (PMPort == 0xFF) {
        // Issue Port COMRESET
       HBA_PORT_REG32_AND_OR (AhciBaseAddr, Port, HBA_PORTS_SCTL, 0xFFFFF000, 
                    HBA_PORTS_SCTL_DET_INIT + (Speed << 4) + (PowerManagement << 8));     
        pBS->Stall (1000);                               // 1msec
        HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_SCTL, ~HBA_PORTS_SCTL_DET_MASK);
    }
    else {
        Data32 = HBA_PORTS_SCTL_DET_INIT + (Speed << 4) + (PowerManagement << 8);
        ReadWritePMPort (SataDevInterface, PMPort, PSCR_2_SCONTROL, &Data32, TRUE);
        pBS->Stall (1000);                               // 1msec
        Data32 = (Speed << 4) + (PowerManagement << 8);
        ReadWritePMPort (SataDevInterface, PMPort, PSCR_2_SCONTROL, &Data32, TRUE);
    }
    
    Status = HandlePortComReset(AhciBusInterface, SataDevInterface, Port, PMPort);

    //  Disable FIS Receive Enable
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_CMD, ~HBA_PORTS_CMD_FRE);

    SataDevInterface->SControl = (Speed << 4) + (PowerManagement << 8);

    gPortReset = FALSE;     

    if (EFI_ERROR(Status)) {
        TRACE_AHCI_LEVEL2((-1," Status : %r\n", Status));
        return EFI_DEVICE_ERROR;
    }

    TRACE_AHCI_LEVEL2((-1," Status : %r\n", Status));
    return EFI_SUCCESS;    

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   GenerateSoftReset
//
// Description: Generate Soft Reset
//
// Input:           
//  IN SATA_DEVICE_INTERFACE                *SataDevInterface,
//  In UINT8                                PMPort
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: StopController, ReadytoAcceptCmd, BuildCommandList, BuildCommandFIS, StartController
//
// Notes:   
//  1. Issue a Control register update, H2D register FIS with reset bit set.
//  2. Wait for 100usec
//  3. Issue a Control register update, H2D register FIS with reset bit reset.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
GenerateSoftReset (
    IN SATA_DEVICE_INTERFACE                *SataDevInterface,
    IN UINT8                                PMPort

)
{

    EFI_STATUS           Status;
    AHCI_BUS_PROTOCOL    *AhciBusInterface = SataDevInterface->AhciBusInterface; 
    UINT32               AhciBaseAddr = (UINT32)(AhciBusInterface->AhciBaseAddress);
    AHCI_COMMAND_LIST    *CommandList = (AHCI_COMMAND_LIST *)(UINTN) SataDevInterface->PortCommandListBaseAddr;
    AHCI_COMMAND_TABLE   *Commandtable = (AHCI_COMMAND_TABLE *)(UINTN)AhciBusInterface->PortCommandTableBaseAddr;
    COMMAND_STRUCTURE     CommandStructure;
    UINT32                Data32;
    UINT8                 Port = SataDevInterface->PortNumber;

    TRACE_AHCI_LEVEL2((-1,"AHCI: SoftReset on Port : %x PMPort : %x", Port, PMPort));

    PROGRESS_CODE(DXE_IDE_RESET);

    if (gSoftReset) return EFI_SUCCESS;
    
    gSoftReset = TRUE;

    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));

    Status = StopController(AhciBusInterface, SataDevInterface,TRUE);
    if (EFI_ERROR(Status)) {
        goto GenerateSoftReset_Exit;
    }


    // if Command list Override is supported, set CLO bit
    Data32 = HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_TFD) & (HBA_PORTS_TFD_DRQ | HBA_PORTS_TFD_BSY);
    if ((AhciBusInterface->HBACapability & HBA_CAP_SCLO) && Data32){
        HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_CMD, HBA_PORTS_CMD_CLO);
        Status = WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CMD,
                            HBA_PORTS_CMD_CLO,
                            BUSY_CLEAR_TIMEOUT);
    }

    CommandStructure.Control = 4;
    BuildCommandList(SataDevInterface, CommandList, (UINT32)(UINTN)Commandtable);
    BuildCommandFIS(SataDevInterface, CommandStructure, CommandList, Commandtable);

    CommandList->Ahci_Cmd_W = 0; 
    // Update of Control Register
    Commandtable->CFis.Ahci_CFis_C = 0;
    CommandList->Ahci_Cmd_R = 1;
    CommandList->Ahci_Cmd_C= 1;

    if (PMPort != 0xFF) Commandtable->CFis.AHci_CFis_PmPort = PMPort;

    StartController(AhciBusInterface, SataDevInterface, BIT00);
    // Wait till command is processed
    Status = WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CI,
                            BIT00,
                            ONE_MILLISECOND * 5);

    // Is the command complete?
    if (EFI_ERROR(Status)){
        goto GenerateSoftReset_Exit;
    }
    pBS->Stall (100);               // 100 usec

    ZeroMemory (&CommandStructure, sizeof(COMMAND_STRUCTURE));
    BuildCommandList(SataDevInterface, CommandList, (UINT32)(UINTN)Commandtable);
    BuildCommandFIS(SataDevInterface, CommandStructure, CommandList, Commandtable);

    CommandList->Ahci_Cmd_W = 0; 
    // Update of Control Register
    Commandtable->CFis.Ahci_CFis_C = 0;
    if (PMPort != 0xFF) Commandtable->CFis.AHci_CFis_PmPort = PMPort;

    StartController(AhciBusInterface, SataDevInterface, BIT00);    
    Status = WaitforCommandComplete(SataDevInterface, NON_DATA_CMD, ATAPI_BUSY_CLEAR_TIMEOUT);

    //  Stop Controller
    StopController(AhciBusInterface, SataDevInterface,FALSE);

GenerateSoftReset_Exit:

    gSoftReset = FALSE;
    TRACE_AHCI_LEVEL2((-1," Status : %r\n", Status));
    return Status;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   HandlePortComReset
//
// Description: Check if COM Reset is successful or not
//
// Input:           
//  IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface,
//  IN UINT8                               Port, 
//  IN UINT8                               PMPort, 
//  
// Output:      
//  EFI_STATUS      
//
// Modified:
//
// Referrals: ReadSCRRegister, WriteSCRRegister
//
// Notes:   
//  1. Check if Link is active. If not return error.
//  2. If Link is present, wait for PhyRdy Change bit to be set.
//  3. Clear SError register
//  4. Wait for D2H register FIS
//  5. Check the Status register for errors.
//  6. If COMRESET is success wait for sometime if the device is ATAPI or GEN1
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
HandlePortComReset(
    IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
    IN SATA_DEVICE_INTERFACE               *SataDevInterface,
    IN UINT8                               Port,
    IN UINT8                               PMPort
)
{

    EFI_STATUS Status = EFI_SUCCESS;
    BOOLEAN     DeviceDetected = FALSE;
    UINT32      Data32, i, SStatusData;
    UINT32      AhciBaseAddr = (UINT32)(AhciBusInterface->AhciBaseAddress);
    volatile    AHCI_RECEIVED_FIS  *FISAddress;
    UINT32      SError = 0;
    //  Check if detection is complete
    for (i = 0; i < HBA_PRESENCE_DETECT_TIMEOUT; i++){   // Total delay 10msec
        SStatusData = ReadSCRRegister (AhciBusInterface, SataDevInterface, Port, PMPort, 0); // SStatus
        SStatusData &= HBA_PORTS_SSTS_DET_MASK;            
        if ((SStatusData == HBA_PORTS_SSTS_DET_PCE) || (SStatusData == HBA_PORTS_SSTS_DET)) { 
            DeviceDetected = TRUE;
            break; 
        }
        pBS->Stall (1000);                               // 1msec
    }

    if (DeviceDetected) {
        // Wait till PhyRdy Change bit is set
        if (PMPort == 0xFF) {
            Status = WaitForMemSet(AhciBaseAddr, Port, HBA_PORTS_SERR,
                            HBA_PORTS_SERR_EX,
                            HBA_PORTS_SERR_EX,
                            ATAPI_BUSY_CLEAR_TIMEOUT);
        }
        else {
            Status = WaitforPMMemSet (SataDevInterface, PMPort, PSCR_1_SERROR, 
                    HBA_PORTS_SERR_EX, HBA_PORTS_SERR_EX, ATAPI_BUSY_CLEAR_TIMEOUT);
        }

        FISAddress =  (AHCI_RECEIVED_FIS *)HBA_PORT_REG32(AhciBaseAddr, Port, HBA_PORTS_FB);

        for (i = 0; i < ATAPI_BUSY_CLEAR_TIMEOUT; ) {
            SError = ReadSCRRegister (AhciBusInterface, SataDevInterface, Port, PMPort, 2); // SError
            if (SError & HBA_PORTS_ERR_CHK) {
              WriteSCRRegister (AhciBusInterface, SataDevInterface, Port, PMPort, 1, HBA_PORTS_ERR_CLEAR ); //SError
            }
            if(FISAddress->Ahci_Rfis[0] == FIS_REGISTER_D2H) {break;}
            pBS->Stall (1000);              // 1msec Strange. Delay is needed for read to succeed. 
                if (PMPort != 0xFF) {i+= 100;}  // For device behind PM Port, there is a delay in writing to the register. So count can be decreased.
                    else { i++; }
        } 

        // Wait till PxTFD gets updated from D2H FIS
        for (i = 0; i < 100; i++){   // Total delay 10msec        
            WriteSCRRegister (AhciBusInterface, SataDevInterface, Port, PMPort, 1, HBA_PORTS_ERR_CLEAR); //SError
            if((FISAddress->Ahci_Rfis[2] & HBA_PORTS_TFD_MASK) == (HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_TFD) & HBA_PORTS_TFD_MASK)) break;
            pBS->Stall (100);                               // 100usec
        }

        // check for errors
        if (FISAddress->Ahci_Rfis[2] & (HBA_PORTS_TFD_BSY | HBA_PORTS_TFD_ERR)) Status = EFI_DEVICE_ERROR;

        Data32 = HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_IS); 
        if (Data32 & (BIT30 + BIT29 + BIT28 + BIT27 + BIT26)) Status = EFI_DEVICE_ERROR;

        // Clear the status
        WriteSCRRegister (AhciBusInterface, SataDevInterface, Port, PMPort, 1, HBA_PORTS_ERR_CLEAR); //SError
        HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_IS, HBA_PORTS_IS_CLEAR); 

    }
    else {
        Status = EFI_DEVICE_ERROR;
    }


    return Status;   

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ReadSCRRegister
//
// Description: 
//
// Input:           
//  IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
//  IN UINT8                               Port, 
//  IN UINT8                               PMPort,
//  IN UINT8                               Register (0 : SStatus 1: SError 2: SControl)
//
// Output:      
//      UINT32
// Modified:
//
// Referrals: 
//
// Notes:   
//  1. Check if the device is connected directly to the port
//  2. if yes, read to the AHCI Controller else write to the Port Multiplier register. 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
UINT32
ReadSCRRegister (
    IN AHCI_BUS_PROTOCOL       *AhciBusInterface, 
    IN SATA_DEVICE_INTERFACE   *SataDevInterface,
    IN UINT8                    Port, 
    IN UINT8                    PMPort, 
    IN UINT8                    Register
)
{

    UINT32  Data32 = 0;
    UINT32  Reg = HBA_PORTS_SSTS;

    if (PMPort != 0xFF) {
        ReadWritePMPort (SataDevInterface, PMPort, Register, &Data32, FALSE);
    }
    else {
        if (Register == 1) Reg = HBA_PORTS_SCTL;
        if (Register == 2) Reg = HBA_PORTS_SERR;
        Data32 = HBA_PORT_REG32 (AhciBusInterface->AhciBaseAddress, Port, Reg);
    }

    return Data32;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   WriteSCRRegister
//
// Description: Write to SCONTROL/Serror/SStatus register
//
// Input:           
//  IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
//  IN SATA_DEVICE_INTERFACE               *SataDevInterface, 
//  IN UINT8                               Port, 
//  IN UINT8                               PMPort,
//  IN UINT8                               Register, (0 : SStatus 1: SError 2: SControl)
//  IN UINT32                              Data32
//  
// Output:      
//  EFI_STATUS
//
// Modified:
//      
// Referrals: 
//
// Notes:   
//  1. Check if the device is connected directly to the port
//  2. if yes, write to the AHCI Controller else write to the Port Multiplier register
//  
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS
WriteSCRRegister (
    IN AHCI_BUS_PROTOCOL       *AhciBusInterface, 
    IN SATA_DEVICE_INTERFACE   *SataDevInterface,
    IN UINT8                    Port, 
    IN UINT8                    PMPort, 
    IN UINT8                    Register,
    IN UINT32                   Data32
)
{

    UINT32  Reg = HBA_PORTS_SSTS;

    if (PMPort != 0xFF) {
        ReadWritePMPort (SataDevInterface, PMPort, Register, &Data32, TRUE);
    }
    else {
        if (Register == 2) Reg = HBA_PORTS_SCTL;
        if (Register == 1) Reg = HBA_PORTS_SERR;
        HBA_PORT_REG32_OR (AhciBusInterface->AhciBaseAddress, Port, Reg, Data32); 
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   WaitforPMMemSet
//
// Description: Wait for memory to be set to the test value.
//
// Input:       
//              SATA_DEVICE_INTERFACE   *SataDevInterface,
//              PMPort
//              Register
//              MaskValue        - The mask value of memory
//              TestValue        - The test value of memory
//              WaitTimeInMs     - The time out value for wait memory set
//
// Output:      EFI_SUCCESS      - HBA reset successfully.
//              EFI_DEVICE_ERROR - HBA failed to complete hardware reset.
//
// Modified:
//
// Referrals: 
//
// Notes:   
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS 
WaitforPMMemSet (
    IN SATA_DEVICE_INTERFACE   *SataDevInterface,
    IN UINT8                   PMPort,
    IN UINT8                   Register,
    IN UINT32                  AndMask,
    IN UINT32                  TestValue,
    IN UINT32                  WaitTimeInMs
)
{
    UINT32  Data32;

    while(WaitTimeInMs!=0){ 
        ReadWritePMPort (SataDevInterface, PMPort, Register, &Data32, FALSE);
        if((Data32 & AndMask) == TestValue) {return EFI_SUCCESS;}
        pBS->Stall (1000);  //  1Msec
        WaitTimeInMs--;
   }
   return EFI_DEVICE_ERROR;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   CheckValidDevice
//
// Description: Check for valid ATA/ATAPI/PMPORT signature 
//
// Input:           
//  IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
//  IN UINT8                               Port, 
//  IN UINT8                               PMPort
//
// Output:      
//  EFI_STATUS
//
// Modified:
//
// Referrals: 
//
// Notes:
//  1. Check if Link is active
//  2. Enable FIS and Command list run bits
//  3. Check for valid signature    
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END> 
EFI_STATUS 
CheckValidDevice (
    IN AHCI_BUS_PROTOCOL                   *AhciBusInterface, 
    IN UINT8                               Port,
    IN UINT8                               PMPort
)
{

    UINT8   Data8;
    UINT32  Data32;
    UINT32      AhciBaseAddr = (UINT32)(AhciBusInterface->AhciBaseAddress);

    // Check if Link is active
    Data8 = (UINT8)(HBA_PORT_REG32 (AhciBaseAddr, Port, HBA_PORTS_SSTS) & HBA_PORTS_SSTS_DET_MASK);
    if (Data8 != HBA_PORTS_SSTS_DET_PCE)  return EFI_DEVICE_ERROR;

    // Enable FIS receive and CI so that TFD gets updated properly
    // Clear out the command slot
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_CI, 0);

   // Enable FIS Receive
    HBA_PORT_REG32_OR (AhciBaseAddr, Port, HBA_PORTS_CMD, HBA_PORTS_CMD_FRE | HBA_PORTS_CMD_ST);

    // Wait till FIS is running
    WaitForMemSet(AhciBaseAddr, Port, HBA_PORTS_CMD,
                                    HBA_PORTS_CMD_FR,
                                    HBA_PORTS_CMD_FR,
                                    HBA_FR_CLEAR_TIMEOUT);
    
    // Wait till CR list is running
    WaitForMemSet(AhciBaseAddr, Port, HBA_PORTS_CMD,
                                    HBA_PORTS_CMD_CR,
                                    HBA_PORTS_CMD_CR,
                                    HBA_FR_CLEAR_TIMEOUT);

    // Clear Start Bit
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_CMD, ~(HBA_PORTS_CMD_ST));
    WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CMD,
                            HBA_PORTS_CMD_CR,
                            HBA_CR_CLEAR_TIMEOUT);

    //Clear FIS Receive enable bit
    HBA_PORT_REG32_AND (AhciBaseAddr, Port, HBA_PORTS_CMD, ~(HBA_PORTS_CMD_FRE));
    WaitForMemClear(AhciBaseAddr, Port, HBA_PORTS_CMD,
                            HBA_PORTS_CMD_FR,
                            HBA_FR_CLEAR_TIMEOUT);


    // Check if valid signature is present
    Data32 = HBA_PORT_REG32(AhciBaseAddr, Port, HBA_PORTS_SIG);
    if (Data32 != ATA_SIGNATURE_32 && Data32 != ATAPI_SIGNATURE_32 && Data32 != PMPORT_SIGNATURE)
        return EFI_DEVICE_ERROR;

    Data8 = HBA_PORT_REG8 (AhciBaseAddr, Port, HBA_PORTS_TFD);
    if (Data8 & (HBA_PORTS_TFD_BSY | HBA_PORTS_TFD_DRQ)) return EFI_DEVICE_ERROR;

    return EFI_SUCCESS;

}

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