summaryrefslogtreecommitdiff
path: root/Core/EM/IdeBus/IdeBus.c
blob: 9a91cc757a39b0f18acde5011df2d6f24816151f (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
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
//**********************************************************************
//**********************************************************************
//**                                                                  **
//**        (C)Copyright 1985-2012, American Megatrends, Inc.         **
//**                                                                  **
//**                       All Rights Reserved.                       **
//**                                                                  **
//**         5555 Oakbrook Pkwy, Suite 200, Norcross, GA 30093        **
//**                                                                  **
//**                       Phone: (770)-246-8600                      **
//**                                                                  **
//**********************************************************************
//**********************************************************************
// $Header: /Alaska/SOURCE/Core/Modules/IdeBus/IdeBus.c 65    8/16/12 3:01a Rajeshms $
//
// $Revision: 65 $
//
// $Date: 8/16/12 3:01a $
//**********************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Core/Modules/IdeBus/IdeBus.c $
// 
// 65    8/16/12 3:01a 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
// 
// 64    8/16/12 2:25a Anandakrishnanl
// [TAG]  		EIP97113
// [Category]  	Improvement
// [Description]  	AtaPassThru - Module Enhancement
// [Files]  		AtaPassThru.c,
// AtaPassThruSupport.h,AtaPassThru.mak,IdeBus.c,AhciBus.c
// 
// 63    8/13/12 10:19a Artems
// [TAG]  		EIP97928
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	System doesn't detect drives in IDE mode
// [RootCause]  	Ide driver returns EFI_ERROR if AtaPassThru protocol is
// absent
// [Solution]  	Make driver to return EFI_SUCCESS as long as there are no
// IDE-related errors
// [Files]  		Idebus.c
// 
// 62    7/20/12 6:13a Anandakrishnanl
// [TAG]  		EIP88683
// [Category]  	New Feature
// [Description]  	EFI_ATA_PASS_THRU_PROTOCOL Support for Aptio IDE
// [Files]  		AhciBus.c
// AhciBus.h
// AInt13.h
// IdeBus.c
// IdeBus.h
// PIDEBus.h
// PAhciBus.h
// AtaPassThru.sdl
// AtaPassThru.mak	
// AtaPassThru.c	
// AtaPassThruSupport.h
// AtaPassThru.chm
// 
// 61    6/13/12 8:49a Anandakrishnanl
// [TAG]  		EIP92381
// [Category]  	Improvement
// [Description]  	A slip of pen in function IdeBusStart
// [Files]  		IdeBus.c
// 
// 60    12/05/11 6:12p Rajkumarkc
// [TAG]  		EIP77142 
// [Category]  	Improvement
// [Description]	Added the function 'IdeNonDataCommandExp' in the
// 'IDE_BUS_PROTOCOL' and removed
//               the existing function 'IdeNonDataCommand' for supporting
// the upper 24bits of LBA.
// [Files]
//     Ata.c
//     IdeBus.c
//     Idebus.h
//     PIDEBus.h
// 
// 59    11/16/11 12:35a Rameshr
// [TAG]  		EIP74970
// [Category]  	Improvement
// [Description]  	Generic GUID variables should be defined as static, or
// not used at all
// [Files]  		Idebus.c
// 
// 57    11/04/11 5:45a Rameshr
// [TAG]  		EIP73035
// [Category]  	Improvement
// [Description]  	Status used on line 2561, conditionally not set.
// Initilized to EFI_SUCCESS to avoid Junk values.
// [Files]  		Idebus.c
// 
// 56    11/03/11 6:07a Rajeshms
// [TAG]  		EIP73260
// [Category]  	Improvement
// [Description]  	IDE Driver Follow the UEFI Driver Model as per the UEFI
// Spec. and STOP function was Verified.
// [Files]  		IdeBus.c
// 
// 55    9/27/11 3:13a Rajeshms
// [TAG]  		EIP69295
// [Category]  	Improvement
// [Description]  	The Timeout values used by IDE and AHCI drivers are
// made as SDL tokens, so that the timeout values can be varied.
// [Files]  		IdeBusBoard.c, CORE_DXE.sdl, AhciSmm.h, AhciBus.h, IDESMM.h,
// Ata.c, Atapi.c, IdeBus.c, IdeBus.h, IdeBusMaster.c, IdeBusBoard.h
// 
// 54    8/22/11 2:56a Anandakrishnanl
// [TAG]  		EIP62912
// [Category]  	Improvement
// [Description]  	Opal Security Definitions Should be Moved to PIDEBUS.h
// from StorageSecurityProtocol.h
// StorageSecurityProtocol.h included in OPAL security driver module will
// give build error when disabled without sdl token #if
// OpalSecurity_SUPPORT properly placed in Ahcibus and IdeBus drivers. But
// Bus driver should not depend on any tokens. For this reason need to
// move OPAL_SEC_INIT_PROTOCOL_GUID in Pidebus.h
// [Files]  		IdeBus.c
// Pidebus.h
// OpalSecurity.cif
// OpalSecurity.h
// IdeOpalSec.c
// AhciOpalSec.c
// 
// 53    7/07/11 2:04a Lavanyap
// [TAG]  		EIP60503
// [Description]  	Added proper comment in InitAcousticSupport() function
// header
// [Files]  		IdeBus.c
// 
// 52    7/07/11 1:56a Lavanyap
// [TAG]  		EIP55207 
// [Category]  	Improvement
// [Description]  	Ide Bus Drive Component Name does not remove trailing
// spaces from drive name
// [Files]  		IdeBus.c
// 
// 51    6/13/11 1:27p Artems
// Made file build when OpalSecurity module is absent
// 
// 50    5/19/11 3:10a Anandakrishnanl
// [TAG]  		EIP53565
// [Category]  	New Feature
// [Description]  	UEFI2.3+ Specifications defines Storage Security
// protocol which needs to be implemented.
// [Files]  		AhciBus.c,IdeBus.c,AHCIOpalSec.c,IDEOpalSec.c,OpalSecurity.c
// ,OpalSecurity.chm,OpalSecurity.cif,OpalSecurity.h,OpalSecurity.mak,Opal
// Security.sdl,PIDEBus.h,StorageSecurityProtocol.CIF,StorageSecurityProto
// col.h
// 
// 49    5/02/11 12:38a Rameshr
// [TAG]- EIP 58703
// [Category]-IMPROVEMENT
// [Description]- Implement correct behavior when RemainingDevicePath
// passed to Supported() function consist only of end node, as described
// in UEFI specification Version 2.3.1, page 10.1
// EFI_DRIVER_BINDING_PROTOCOL.Supported() and Start() 
// [Files]- Idebus.c
// 
// 48    5/02/11 12:23a Rameshr
// [TAG]- EIP 58686
// [Category]-IMPROVEMENT
// [Description]- Update implementation of EFI_BLOCK_IO_PROTOCOL as
// described in UEFI specification Version 2.3.1, page 12.8
// [Files]- Idebus.c, Atapi.c
// 
// 47    4/12/11 4:05a Rameshr
// [TAG]- EIP 53710
// [Category]- New Feature
// [Description]- ATAPI ODD loading type information added into ATAPI
// device structure 
// [Files]- Atapi.c, Idebus.c, IdeBus.h 
// 
// 46    12/23/10 3:54a 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
// 
// 45    9/24/10 2:43a Rameshr
// [TAG]- EIP 42817
// [Category]-IMPROVEMENT
// [Description]- Ide Smart checks HDDs for errors moved after Idebus
// Device path has been installed.
// [Files]- AhciBus.c, IdeBus.c
// 
// 44    8/25/10 4:16a Rameshr
// New Feature: EIP 37748
// Description: Move all the IDEBus Source driver SDL token into IdeBus
// Bin Driver.
// FilesModified: Ata.c, Atapi.c, idebus.c, IdeBus.h,
// IdebuscomponentName.c, IdeBusmaster.c IdeBusSrc.mak IdebusSrc.sdl
// IdeHpa.c, IdePowerManagement.c
// 
// 43    7/20/10 4:18p Pats
// EIP 38384: Sytem will get halt with the P-ATA to S-ATA transfer card on
// APTIO 4.6.4.
// Problem: Feature and Sector Count values are reversed in the invocation
// of IdeNonDataCommand to set DEV_CONFIG_FREEZE_LOCK.
// Solution: Fixed Feature and Sector Count values.
// 
// 42    5/26/10 6:02a Rameshr
// Checked the Device Configuration Overlay feature set supported status
// before sending the DEV_CONFIG_FREEZE_LOCK 
// EIP 38384
// 
// 41    4/16/10 4:05p Pats
// EIP 30719: Support for the HDD with sector size more than 512bytes.
// 
// 40    1/11/10 12:10p Krishnakumarg
// Update for Eip 11835 - To implement Acoustic Management function
// Eip 30041 - Aptio 4 Device Initiated Power Management (DipM) support
// for SATA devices
// 
// 39    9/04/09 3:29p Krishnakumarg
// Acoustic Management function updated to set acoustic level according to
// setup option EIP:11835
// CreateIdeDevicePath will now use EFI_OPEN_PROTOCOL_GET_PROTOCOL instead
// of EFI_OPEN_PROTOCOL_BY_DRIVER in openprotocol function.
// 
// 38    8/28/09 11:21a Felixp
// Component Name protocol implementation is upadted  to support both 
// ComponentName and ComponentName2 protocols
// (based on value of the EFI_SPECIFICATION_VERSION SDL token).
// 
// 37    7/01/09 12:23p Rameshr
// Coding Standard and File header updated.
//
// 36    6/22/09 11:38a Rameshr
// Odd Type information Saved in Atapi Device Structure.
// EIP:21548
//
// 35    5/01/09 11:01a Rameshr
// Symptom: Disconnect the IDE controller, make system to hang on debug
// mode
// Solution: IdeBlockIoDev pointer has wrong address, that make Freepool
// to hang the system. Corrected the IdeBlockIoDev address
//
// 34    4/28/09 7:17p Rameshr
// HDD password support in RAID mode
// EIP:20421
//
// 33    4/14/09 1:01p Rameshr
// When INTEL_IDE_PROTOCOL = 1, the IdeBus driver does not check if modes
// are valid in the SupportedModes data before assigning them to
// IdeBusInterface
// EIP 21195
//
// 32    11/02/09 11:16a Anandakrishnanl
// BUGFIX: Removed ASSERT Since AhciBus Driver presence may return Status
// Other than Success
//
// 31    12/31/08 3:07p Rameshraju
// BugFix- Validate the PIO mode before programming the PIO mode into the
// device EIP:17885
//
// 30    14/08/08 10:52a Anandakrishnanl
// Compatible Mode AHCI Support Added and Sdl Token Added in IdeBusSrc.sdl
//
// 29    8/06/08 10:37a Rameshraju
// Corrected problem in debug info print.
//
// 28    5/14/08 4:43p Rameshraju
// Error code added if error happens while configuring device or
// controller.
//
// 27    4/22/08 2:02p Felixp
// DXE_IDE_DETECT progress code moved from ATA.c to IdeBus.c
// DXE_IDE_ENABLE progress code added
//
// 26    3/27/08 11:21a Srinin
// CreateIdeDevicePath() modified to create a devicepath
// even if Remaining devicepath is not NULL.
//
// 25    7/03/08 5:45p Anandakrishnanl
// Added Smart related Changes since Smart is a seperate driver now and
// smart calls are now made protocol driven. Removed Sdl tokens that are
// used previously
//
// 24    3/06/08 5:20p Ambikas
//
// 23    3/06/08 4:41p Ambikas
//
// 22    3/04/08 7:51p Felixp
//
// 20    28/02/08 7:07p Anandakrishnanl
// Added HddSecurity Protocol to support security module as a separate
// driver.
//
// 19    10/23/07 4:17p Felixp
// IDE Security support moved from Sources to Binary
//
// 18    22/06/07 12:40p Anandakrishnanl
// HardDisk Security Support Module Added.
// Need ACPI Module and SB Module and under Core\Include we updated
// Setup.h.
// Also New IdeBus bin module.
//
// 17    5/04/07 12:53p Srinin
// In AHCI and RAID mode, PI reg is ignored. Always controller is in
// Native mode.
//
// 16    4/19/07 12:55p Felixp
//  - Minor bug fix: initialize block size by default with
// CDROM_BLOCK_SIZE for ATAPI devices (along with DiskIo.c changes
// resolves SCT failure)
//  - File reformatted to comply with AMI coding standards
//
// 13    4/16/07 6:29p Felixp
// Minor bug fix: initialize block size by default with CDROM_BLOCK_SIZE
// for ATAPI devices
//
// 12    13/04/07 3:01p Anandakrishnanl
// Ide Bus Module - Update source files to comply with AMI coding
// standard"!!!
//
// 11    12/19/06 6:12p Srinin
// Software setting Preserve bit set for SATA devices.
//
// 10    11/17/06 3:05p Ambikas
//
// 9     10/27/06 4:20p Felixp
// enable IDE interrupts at the exit boot services event handler
// (required to boot EFI vista)
//
// 8     8/09/06 3:34p Pavell
//
// 7     5/19/06 10:30p Felixp
// Device Path code updated to use NODE_LENGTH macros to remove direct
// access to the Length field
//
// 6     3/21/06 4:42p Srinin
// Build error Fixed.
//
// 5     3/13/06 2:20a Felixp
//
// 4     1/09/06 11:36a Felixp
//
// 2     12/14/05 3:04p Srinin
// CallBack added to support HDD password support during S3 Resume.
//
// 1     12/01/05 9:43a Felixp
//
// 16    11/03/05 10:55a Srinin
// For Busmaster transfer, Buffer should be DWORD aligned.
//
// 15    10/21/05 1:39p Srinin
// Removed Media detection for Atapi devices during Detection process.
//
// 14    8/22/05 4:31p Srinin
// ATA/ATAPI identification changed.
//
// 13    2/11/05 6:16p Felixp
// - Cleanup (duplication of library functions removed)
// - Code optimized by using DPAddNode instead of DPAdd
// - AllocatePool + ZeroMem replaced with MallocZ
//
// 12    2/01/05 12:58p Srinin
// IDE HotPlug Support added.
//
// 11    1/31/05 11:14a Srinin
// Fixed ComponentName display issue for IDE devices.
//
// 10    1/28/05 1:19p Felixp
// IdeBus is linked together with CORE_DXE
//
// 9     1/18/05 3:22p Felixp
// PrintDebugMessage renamed to Trace
//
// 8     1/13/05 4:23p Srinin
// Host Protection Area Support added.
//
// 7     1/11/05 2:26p Srinin
// IDE Power Management Support added.
//
// 5     1/10/05 11:29a Srinin
// SMART Support added.
//
// 4     1/05/05 3:55p Srinin
// Acoustic management Support added.
//
// 3     1/05/05 11:21a Srinin
// BusMaster and Password Support added.
//
// 2     12/21/04 4:57p Markw
// Modified device path defines for consistency.
//
// 1     12/10/04 1:01p Srinin
// Initial Checkin of IdeBus Driver.
//
//
//<AMI_FHDR_START>
//----------------------------------------------------------------------------
//
// Name: IdeBus.c
//
// Description:	Provides IDE Block IO protocol
//
//----------------------------------------------------------------------------
//<AMI_FHDR_END>


#include "IdeBus.h"
#include <Protocol\IdeBusBoard.h>

static EFI_GUID     gEfiIdeBusInitProtocolGuid      = IDE_BUS_INIT_PROTOCOL_GUID;
static EFI_GUID     gIdeBusDriverBindingProtocolGuid = EFI_DRIVER_BINDING_PROTOCOL_GUID;
static EFI_GUID     gEfiDiskInfoProtocolGuid        = EFI_DISK_INFO_PROTOCOL_GUID;
static EFI_GUID     gEfiIdeDiskInfoProtocolGuid     = EFI_DISK_INFO_IDE_INTERFACE_GUID;
static EFI_GUID     gIdeSetupProtocolguid           = IDE_SETUP_PROTOCOL_GUID;
static EFI_GUID     gEfiBootScriptSaveGuid          = EFI_BOOT_SCRIPT_SAVE_GUID;
static EFI_GUID     gDevicePathProtocolGuid         = EFI_DEVICE_PATH_PROTOCOL_GUID;
static EFI_GUID     gEfiBlockIoProtocolGuid         = EFI_BLOCK_IO_PROTOCOL_GUID;
static EFI_GUID     gHddSecurityInitProtocolGuid    = HDD_SECURITY_INIT_PROTOCOL_GUID;
static EFI_GUID     gHddSmartInitProtocolGuid       = HDD_SMART_INIT_PROTOCOL_GUID;
static EFI_GUID     gHddSecurityEndProtocolGuid     = HDD_SECURITY_END_PROTOCOL_GUID;
static EFI_GUID     gPlatformIdeProtocolGuid        = PLATFORM_IDE_PROTOCOL_GUID;
static EFI_GUID     gOpalSecInitProtocolGuid        = OPAL_SEC_INIT_PROTOCOL_GUID;
static EFI_GUID     gSMARTProtocolGuid              = IDE_SMART_INTERFACE_GUID;
static EFI_GUID     gAtaPassThruInitProtocolGuid    = ATA_PASS_THRU_INIT_PROTOCOL_GUID; 
static EFI_GUID     gScsiPassThruAtapiInitProtocolGuid = SCSI_PASS_THRU_ATAPI_INIT_PROTOCOL_GUID;

EFI_GUID            gSecurityModeProtocolGuid       = IDE_SECURITY_INTERFACE_GUID;
EFI_GUID            gPowerMgmtProtocolGuid          = IDE_POWER_MGMT_INTERFACE_GUID;
EFI_GUID            gHPAProtocolGuid                = IDE_HPA_INTERFACE_GUID;


EFI_EVENT                          gIDEBusEvtBootScript      = NULL;
EFI_EVENT                          gIDEBusEvtMiscSmmFeatures = NULL;

SCSI_PASS_THRU_ATAPI_INIT_PROTOCOL   *gScsiPassThruAtapiInitProtocol; 
ATA_PASS_THRU_INIT_PROTOCOL        *AtaPassThruInitProtocol;  
OPAL_SECURITY_INIT_PROTOCOL        *OpalSecInitProtocol;
HDD_SECURITY_INIT_PROTOCOL         *HddSecurityInitProtocol;
HDD_SMART_INIT_PROTOCOL            *HddSmartInitProtocol;
IDE_SETUP_PROTOCOL		           *gIdeSetupProtocol;
PLATFORM_IDE_PROTOCOL              *gPlatformIdeProtocol;

extern EFI_COMPONENT_NAME_PROTOCOL gIdeBusControllerDriverName;

//
// Instantiate PLATFORM_IDE_PROTOCOL with default SDL Token values 
//

PLATFORM_IDE_PROTOCOL        gPlatformIdeProtocolInstance = {
    2,                                       //Protocol Revision
    1,                                       //MasterSlaveEnumeration
    1,                                       //IdeBusMasterSupport
    1,                                       //AtapiBusMasterSupport
    1,                                       //AcousticManagementSupport
    0,                                       //IdePowerManagementSupport
    5,                                       //StandbyTimeout
    0,                                       //AdvPowerManagementSupport
    1,                                       //AdvPowerManagementLevel
    0,                                       //PowerupInStandbySupport
    0,                                       //PowerupInStandbyMode
    0,                                       //IdePwrManagementInterfaceSupport
    0,                                       //HostProtectedAreaSupport
    0,                                       //IdeHPSupport
    1,                                       //EfiIdeProtocol
    0,                                       //AhciCompatibleMode
    0,                                       //SBIdeSupport
    1,                                       //HddPowerLossInS3
    0,                                       //DiPMSupport
    0,                                       //DisableSoftSetPrev
    0,                                       //ForceHddPasswordPrompt
    EFI_IDE_CONTROLLER_INIT_PROTOCOL_GUID,   //gIdeControllerProtocolGuid
    EFI_COMPONENT_NAME_PROTOCOL_GUID,        //gComponentNameProtocolGuid
    10000,                                   //S3BusyClearTimeout
    5000,                                    //DmaAtaCompleteCommandTimeout
    16000,                                   //DmaAtaPiCompleteCommandTimeout
    5000,                                    //AtaPiResetCommandTimeout
    16000,                                   //AtaPiBusyClearTimeout
    10000                                    //PoweonBusyClearTimeout 
};

EFI_DRIVER_BINDING_PROTOCOL        gIdeBusDriverBinding = {
    IdeBusSupported,
    IdeBusStart,
    IdeBusStop,
    IDE_BUS_DRIVER_VERSION,  // version
    NULL,                    // ImageHandle
    NULL                     // DriverBindingHandle
};

// Global Buffer pointer used for Bus Mastering
VOID                               *gDescriptorBuffer = NULL;

VOID InitMiscConfig (
    IN IDE_BUS_PROTOCOL    *IdeBusInterface
);

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IdeBusExitBootServices
//
// Description:	  Enables IDE controller interrupt on ExitBootServices
//
// Input:
//      Event   - The Event that is being processed
//      Context - Event Context
//
// Output: None
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID EFIAPI IdeBusExitBootServices(
    IN EFI_EVENT Event,
    IN VOID      *Context )
{
    EFI_STATUS            Status;
    UINTN                 Count;
    EFI_HANDLE            Buffer[0x100];
    UINTN                 BufferSize = sizeof(Buffer);
    UINT8                 i;
    UINT8                 j;
    UINT8                 k;
    IDE_BUS_INIT_PROTOCOL *IdeBusInitProtocol;
    IDE_BUS_PROTOCOL      *pIdeBusProtocol;
    UINT64                IdeDevControlReg;
    UINT64                IdeDevReg;
    UINT8                 Data8 = 0;

    Status = pBS->LocateHandle(
        ByProtocol,
        &gEfiIdeBusInitProtocolGuid,
        NULL,
        &BufferSize,
        Buffer
        );

    if ( !EFI_ERROR( Status )) {
        Count = BufferSize / sizeof(EFI_HANDLE);

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

            if ( !Status ) {
                for ( j = 0; j < 2; j++ )
                {
                    for ( k = 0; k < 2; k++ )
                    {
                        if ( IdeBusInitProtocol->pIdeBusProtocol[j][k] ) {
                            if ( IdeBusInitProtocol->IdeBusInitData[j][k] == DEVICE_CONFIGURED_SUCCESSFULLY ) {
                                pIdeBusProtocol = IdeBusInitProtocol->pIdeBusProtocol[j][k];

                                //
                                //Dev select
                                //  
                                Data8     = pIdeBusProtocol->IdeDevice.Device << 4;
                                IdeDevReg = (UINT64)pIdeBusProtocol->IdeDevice.Regs.CommandBlock.DeviceReg;
                                pIdeBusProtocol->PciIO->Io.Write(
                                    pIdeBusProtocol->PciIO,
                                    EfiPciIoWidthUint8,
                                    EFI_PCI_IO_PASS_THROUGH_BAR,
                                    IdeDevReg,
                                    1,
                                    &Data8
                                    );


                                Data8 = 0;
                                //  
                                //Enable IDE Controller interrupt
                                //
                                IdeDevControlReg = (UINT64)pIdeBusProtocol->IdeDevice.Regs.ControlBlock.AlternateStatusReg;
                                pIdeBusProtocol->PciIO->Io.Write(
                                    pIdeBusProtocol->PciIO,
                                    EfiPciIoWidthUint8,
                                    EFI_PCI_IO_PASS_THROUGH_BAR,
                                    IdeDevControlReg,
                                    1,
                                    &Data8
                                    );
                            }
                        }
                    }
                }
            }
        }
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IdeBusEntryPoint
//
// Description:	Installs gIdeBusDriverBinding protocol
//
// Input:
//	IN EFI_HANDLE        ImageHandle,
//	IN EFI_SYSTEM_TABLE  *SystemTable
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitAmiLib InstallMultipleProtocolInterfaces
//
// Notes:
//  Here is the control flow of this function:
//  1. Initialize Ami Lib.
//	2. Install Driver Binding Protocol
//  3. Return EFI_SUCCESS.
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IdeBusEntryPoint(
    IN EFI_HANDLE       ImageHandle,
    IN EFI_SYSTEM_TABLE *SystemTable )
{
    EFI_STATUS Status;
    EFI_EVENT  ExitBootServicesNotifyEvent;

    gIdeBusDriverBinding.DriverBindingHandle = NULL;
    gIdeBusDriverBinding.ImageHandle         = ImageHandle;

    InitAmiLib( ImageHandle, SystemTable );
    //
    //Register our ExitBootServices () callback function
    //  
    Status = pBS->CreateEvent(
        EFI_EVENT_SIGNAL_EXIT_BOOT_SERVICES,
        TPL_CALLBACK,
        IdeBusExitBootServices,
        NULL,
        &ExitBootServicesNotifyEvent
        );
    ASSERT_EFI_ERROR( Status );

    Status = pBS->LocateProtocol(
                    &gPlatformIdeProtocolGuid,
                    NULL,
                    &gPlatformIdeProtocol
                    );
    if (EFI_ERROR (Status)) {
        //
        // if EFI_ERROR then Assign Default values Instance to gPlatformIdeProtocol.
        //
        gPlatformIdeProtocol = (PLATFORM_IDE_PROTOCOL *)&gPlatformIdeProtocolInstance;
    }
    //
    // Assert when PLATFORM_IDE_PROTOCOL's revision is not supported 
    //
    ASSERT(!(gPlatformIdeProtocol->Revision > PLATFORM_IDE_PROTOCOL_SUPPORTED_REVISION))

    Status = pBS->InstallMultipleProtocolInterfaces(
        &gIdeBusDriverBinding.DriverBindingHandle,
        &gIdeBusDriverBindingProtocolGuid, &gIdeBusDriverBinding,
        &(gPlatformIdeProtocol->gComponentNameProtocolGuid), &gIdeBusControllerDriverName,
        NULL
        );

#ifdef Debug_Level_1
    EfiDebugPrint( -1, "IdeBusEntryPoint Exit Status %x\n", Status );
#endif

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IdeBusSupported
//
// Description:	Checks whether IDE_PROTOCOL_INTERFACE is installed on the controller.
//				If 'yes', return SUCCESS else ERROR
//
// Input:
//	IN EFI_DRIVER_BINDING_PROTOCOL    *This,
//	IN EFI_HANDLE                     Controller,
//	IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: OpenProtocol CloseProtocol
//
// Notes:
//  Here is the control flow of this function:
// 1. If Devicepath is NULL, check "gEfiIdeControllerProtocolGuid" is installed by IdeController device driver,
// if yes, it is the IDE controller that this Bus will manage. Then return Success.
// 2. If Devicepath is valid, check if "gEfiIdeBusInitProtocolGuid" is already installed by this BUS driver,
// if yes, check whether it is OK to configure this device. if not installed goto step 1.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IdeBusSupported(
    IN EFI_DRIVER_BINDING_PROTOCOL *This,
    IN EFI_HANDLE                  Controller,
    IN EFI_DEVICE_PATH_PROTOCOL    *RemainingDevicePath )
{
    EFI_STATUS                       Status;

    VOID                             *IdeControllerInterface = NULL ;
    ATAPI_DEVICE_PATH                *AtapiRemainingDevicePath = (ATAPI_DEVICE_PATH*) RemainingDevicePath;
    IDE_BUS_INIT_PROTOCOL            *IdeBusInitInterface;
    EFI_PCI_IO_PROTOCOL              *PciIO;
    UINT8 PciConfig[256];

#ifdef Debug_Level_1
    EfiDebugPrint( -1, "IdeBusSupported Entry\n" );
#endif

    //
    //Check for Valid ATAPI Device Path. If no return UNSUPPORTED
    //
    if ( !(AtapiRemainingDevicePath == NULL)) {

        //
        // RemainingDevicePath is not NULL and begins with the End of Device Path node, 
        // then the driver must not enumerate any of the children of Controller nor create any child device handle. 
        // Only the controller initialization should be performed. UEFI specification V 2.3.1, P. 10.1
        //
        if(isEndNode(RemainingDevicePath)) {
            return EFI_SUCCESS;
        }

        //
        // Check if the AtapiRemainingDevicePath is valid 8.3.4.1
        //
        if ( AtapiRemainingDevicePath->Header.Type != MESSAGING_DEVICE_PATH
             || AtapiRemainingDevicePath->Header.SubType != MSG_ATAPI_DP
             && NODE_LENGTH( &AtapiRemainingDevicePath->Header ) != ATAPI_DEVICE_PATH_LENGTH ) {
#ifdef Debug_Level_3
            EfiDebugPrint( -1, "AtapiRemainingDevicePath not Valid\n" );
#endif
            return EFI_UNSUPPORTED;
        }

        //
        //Now check whether it is OK to enumerate the specified device.
        //
        Status = pBS->OpenProtocol( Controller,
                                    &gEfiIdeBusInitProtocolGuid,
                                    (VOID**)&IdeBusInitInterface,
                                    This->DriverBindingHandle,
                                    Controller,
                                    EFI_OPEN_PROTOCOL_BY_DRIVER );

        if ( Status == EFI_SUCCESS || Status == EFI_ALREADY_STARTED ) {
            pBS->CloseProtocol(
                Controller,
                &gEfiIdeBusInitProtocolGuid,
                This->DriverBindingHandle,
                Controller
                );

            if ( AtapiRemainingDevicePath->PrimarySecondary == PRIMARY_CHANNEL && AtapiRemainingDevicePath->SlaveMaster == MASTER_DRIVE ) {
                if ( IdeBusInitInterface->IdeBusInitData[PRIMARY_CHANNEL][MASTER_DRIVE] >= DEVICE_DETECTION_FAILED ) {
                    return EFI_ALREADY_STARTED;
                }
            }

            if ( AtapiRemainingDevicePath->PrimarySecondary == PRIMARY_CHANNEL && AtapiRemainingDevicePath->SlaveMaster == SLAVE_DRIVE ) {
                if ( IdeBusInitInterface->IdeBusInitData[PRIMARY_CHANNEL][SLAVE_DRIVE] >= DEVICE_DETECTION_FAILED ) {
                    return EFI_ALREADY_STARTED;
                }
            }

            if ( AtapiRemainingDevicePath->PrimarySecondary == SECONDARY_CHANNEL && AtapiRemainingDevicePath->SlaveMaster == MASTER_DRIVE ) {
                if ( IdeBusInitInterface->IdeBusInitData[SECONDARY_CHANNEL][MASTER_DRIVE] >= DEVICE_DETECTION_FAILED ) {
                    return EFI_ALREADY_STARTED;
                }
            }

            if ( AtapiRemainingDevicePath->PrimarySecondary == SECONDARY_CHANNEL && AtapiRemainingDevicePath->SlaveMaster == SLAVE_DRIVE ) {
                if ( IdeBusInitInterface->IdeBusInitData[SECONDARY_CHANNEL][SLAVE_DRIVE] >= DEVICE_DETECTION_FAILED ) {
                    return EFI_ALREADY_STARTED;
                }
            }
        }
    }

    //
    //Check whether IDE_CONTROLLER_PROTOCOL  has been installed on this controller
    //
    Status = pBS->OpenProtocol( Controller,
                                &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                                (VOID**)&IdeControllerInterface,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_BY_DRIVER );

#ifdef Debug_Level_3

    if ( EFI_ERROR( Status )) {
        if ( gPlatformIdeProtocol->EfiIdeProtocol )
            EfiDebugPrint( -1, "Error opening gEfiIdeControllerInitProtocolGuid\n" );
        else
            EfiDebugPrint( -1, "Error opening gEfiIdeControllerProtocolGuid\n" );
    }
#endif

    //
    //IDE_CONTROLLER_PROTOCOL will be opened by each device. So EFI_ALREADY_STARTED is not an error
    //
    if  ( !(Status == EFI_SUCCESS || Status == EFI_ALREADY_STARTED)) {
        return EFI_UNSUPPORTED;
    }

    //
    //Close IDE_CONTROLLER_PROTOCOL
    //
    pBS->CloseProtocol(
        Controller,
        &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
        This->DriverBindingHandle,
        Controller
        );

#ifdef Debug_Level_1
    EfiDebugPrint( -1, "IdeBusSupported Exit Success\n" );
#endif
    //
    // Check if Controller is in AHCI mode or not?
    //
    Status = pBS->OpenProtocol( Controller,
                                &gEfiPciIoProtocolGuid,
                                (VOID**)&PciIO,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_GET_PROTOCOL );

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

    Status = PciIO->Pci.Read( PciIO,
                              EfiPciIoWidthUint8,
                              0,
                              sizeof (PciConfig),
                              PciConfig
                              );

    if ((PciConfig [IDE_SUB_CLASS_CODE] == SCC_AHCI_CONTROLLER) || (PciConfig [IDE_SUB_CLASS_CODE] == SCC_RAID_CONTROLLER)) {
        if ( !(gPlatformIdeProtocol->AhciCompatibleMode) )
            return EFI_UNSUPPORTED;
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IdeBusStart
//
// Description:	Installs IDE Block IO Protocol
//
// Input:
//	IN EFI_DRIVER_BINDING_PROTOCOL    *This,
//	IN EFI_HANDLE                     Controller,
//	IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: OpenProtocol CloseProtocol InstallProtocolInterface AllocatePool
//
// Notes:
//  Here is the control flow of this function:
// 1.  Check if "gEfiIdeBusInitProtocolGuid" is already installed. If not, install it "InstallBusInitProtocol".
// 2.  If Devicepath is valid, initialize so that only particular device will be detected and
//	   confgiured, else all devices will be detected and configured.
// 3.  check whether the device has not been already detected. If yes, skip it and go for next device
// 4.  IdeBusInterface is initialized for this device. Update Base address.
// 5.  Do the detection "DetectIdeDevice". Update the status in "IdeBusInitProtocol". If failure undo the process "IdeBusInterface".
// 6.  Repeat for all devices from step 3.
// 7.  Start the configuration process for devices which are detected successfully "DEVICE_DETECTED_SUCCESSFULLY".
// 8.  "ConfigureIdeDeviceAndController" will do the configuration.
// 9.  If above step is success, build Devicepath "CreateIdeDevicePath"
// 10. Create the Block_io_Protocol"InitIdeBlockIO". Install it only if Device is not Password protected.
// 11. Create the DISK_INFO_PROTOCOL "InitIdeDiskInfo". Install it only if Device is not Password protected.
// 12. Install a child device with the above three protocols.
// 13. Open "gEfiIdeControllerProtocolGuid" with the child handle.
// 14. Repeat from step 8 for the remaining devices.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IdeBusStart(
    IN EFI_DRIVER_BINDING_PROTOCOL *This,
    IN EFI_HANDLE                  Controller,
    IN EFI_DEVICE_PATH_PROTOCOL    *RemainingDevicePath )
{
    EFI_STATUS                       Status;
    EFI_PCI_IO_PROTOCOL              *PciIO;

    IDE_BLK_IO_DEV                   *IdeBlockIoDev = NULL;
    VOID                             *IdeControllerInterface = NULL ;
    IDE_BUS_INIT_PROTOCOL            *IdeBusInitInterface;
    IDE_BUS_PROTOCOL                 *IdeBusInterface;
    UINT8 Enumeration_Process = ENUMERATE_ALL;
    ATAPI_DEVICE_PATH                *AtapiRemainingDevicePath = (ATAPI_DEVICE_PATH*)RemainingDevicePath;

    UINT8 Start_Channel = PRIMARY_CHANNEL;
    UINT8 End_Channel   = SECONDARY_CHANNEL;
    UINT8 Start_Device  = MASTER_DRIVE;
    UINT8 End_Device    = SLAVE_DRIVE;

    INT8 TotalDevice = 0;
    INT8 Current_Channel;
    INT8 Current_Device;
    UINT16                           SecurityStatus = 0;

#ifdef Debug_Level_1
    EfiDebugPrint( -1, "IdeBusStart Entry\n" );
#endif

    PROGRESS_CODE( DXE_IDE_BEGIN );

    //
    //Open IDE_CONTROLLER_PROTOCOL. If success or Already opened, It is OK to proceed.
    //
    Status = pBS->OpenProtocol( Controller,
                                &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                                (VOID**)&IdeControllerInterface,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_BY_DRIVER );

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

    //
    //Get the PciIO interface
    //
    Status = pBS->OpenProtocol( Controller,
                                &gEfiPciIoProtocolGuid,
                                (VOID**)&PciIO,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_GET_PROTOCOL );


    //
    //Check if IDE_BUS_INIT_PROTOCOL installed.
    //
    Status = pBS->OpenProtocol( Controller,
                                &gEfiIdeBusInitProtocolGuid,
                                (VOID**)&IdeBusInitInterface,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_BY_DRIVER );


    if  ( !(Status == EFI_SUCCESS || Status == EFI_ALREADY_STARTED)) {
        Status = pBS->AllocatePool( EfiBootServicesData,
                                    sizeof(IDE_BUS_INIT_PROTOCOL),
                                    (VOID**)&IdeBusInitInterface
                                    );

        if ( EFI_ERROR( Status )) {
            return EFI_OUT_OF_RESOURCES; 
        }
        Status = InstallBusInitProtocol( Controller, IdeBusInitInterface, IdeControllerInterface );

        if ( EFI_ERROR( Status )) {
            if ( Status == EFI_OUT_OF_RESOURCES) {
                return EFI_OUT_OF_RESOURCES;
            } else {
                return EFI_DEVICE_ERROR;
            }
        }
    }

    //
    //	Check if AtapiRemainingDevicePath is valid or not
    //
    if ( !(AtapiRemainingDevicePath == NULL)) {

        //
        // RemainingDevicePath is not NULL and begins with the End of Device Path node, 
        // then the driver must not enumerate any of the children of Controller nor create any child device handle. 
        // Only the controller initialization should be performed. UEFI specification V 2.3.1, P. 10.1
        //
        if(isEndNode(RemainingDevicePath)) {
            return EFI_SUCCESS;
        }

        //
        // Check if the AtapiRemainingDevicePath is valid 8.3.4.1
        //
        if ( AtapiRemainingDevicePath->Header.Type != MESSAGING_DEVICE_PATH
             || AtapiRemainingDevicePath->Header.SubType != MSG_ATAPI_DP
             && NODE_LENGTH( &AtapiRemainingDevicePath->Header ) != ATAPI_DEVICE_PATH_LENGTH ) {
#ifdef Debug_Level_3
            EfiDebugPrint( -1, "AtapiRemainingDevicePath not Valid\n" );
#endif
            return EFI_DEVICE_ERROR;
        }

        if ( AtapiRemainingDevicePath->PrimarySecondary == PRIMARY_CHANNEL
             && AtapiRemainingDevicePath->SlaveMaster == MASTER_DRIVE ) {
            Enumeration_Process = ENUMERATE_PRIMARY_MASTER;
        }

        if ( AtapiRemainingDevicePath->PrimarySecondary == PRIMARY_CHANNEL
             && AtapiRemainingDevicePath->SlaveMaster == SLAVE_DRIVE ) {
            Enumeration_Process = ENUMERATE_PRIMARY_SLAVE;
        }

        if ( AtapiRemainingDevicePath->PrimarySecondary == SECONDARY_CHANNEL
             && AtapiRemainingDevicePath->SlaveMaster == MASTER_DRIVE ) {
            Enumeration_Process = ENUMERATE_SECONDARY_MASTER;
        }

        if ( AtapiRemainingDevicePath->PrimarySecondary == SECONDARY_CHANNEL
             && AtapiRemainingDevicePath->SlaveMaster == SLAVE_DRIVE ) {
            Enumeration_Process = ENUMERATE_SECONDARY_SLAVE;
        }

        switch ( Enumeration_Process )
        {
        case ENUMERATE_PRIMARY_MASTER:
            Start_Channel = PRIMARY_CHANNEL;
            End_Channel   = PRIMARY_CHANNEL;
            Start_Device  = MASTER_DRIVE;
            End_Device    = MASTER_DRIVE;
            break;
        case ENUMERATE_PRIMARY_SLAVE:
            Start_Channel = PRIMARY_CHANNEL;
            End_Channel   = PRIMARY_CHANNEL;
            Start_Device  = SLAVE_DRIVE;
            End_Device    = SLAVE_DRIVE;
            break;
        case ENUMERATE_SECONDARY_MASTER:
            Start_Channel = SECONDARY_CHANNEL;
            End_Channel   = SECONDARY_CHANNEL;
            Start_Device  = MASTER_DRIVE;
            End_Device    = MASTER_DRIVE;
            break;
        case ENUMERATE_SECONDARY_SLAVE:
            Start_Channel = SECONDARY_CHANNEL;
            End_Channel   = SECONDARY_CHANNEL;
            Start_Device  = SLAVE_DRIVE;
            End_Device    = SLAVE_DRIVE;
            break;
        default:
            break;
        }
    }


#ifdef Debug_Level_3
            EfiDebugPrint( -1, "Enumerate = %x\n", Enumeration_Process );
#endif

    //---------------------------------------------------------------------------------------------------------
    //	Device Detection Begins
    //---------------------------------------------------------------------------------------------------------
    PROGRESS_CODE( DXE_IDE_DETECT );

    for ( Current_Channel = Start_Channel; Current_Channel <= End_Channel; Current_Channel++ )
    {

        if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
            ( (EFI_IDE_CONTROLLER_INIT_PROTOCOL*)IdeControllerInterface )->NotifyPhase( (EFI_IDE_CONTROLLER_INIT_PROTOCOL*)IdeControllerInterface, EfiIdeBeforeChannelEnumeration, Current_Channel );
        }
        //
        // Calculate the Number of Devices to be detected in single Channel 
        //
        TotalDevice = ( End_Device - Start_Device ) + 1;

        if ( gPlatformIdeProtocol->MasterSlaveEnumeration ) {
            Current_Device = Start_Device;
        } else {
            Current_Device = End_Device;
        }

        while ( TotalDevice ) 
        {
            //
            // Check whether the given device is disabled by USER OR already processed
            //
            if ( IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_DISABLED
                 || IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_DETECTED_SUCCESSFULLY
                 || IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_CONFIGURED_SUCCESSFULLY
                 || IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_DETECTION_FAILED
                 || IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_REMOVED ) {

                if ( gPlatformIdeProtocol->MasterSlaveEnumeration ) {
                    Current_Device++;
                } else {
                    Current_Device--;
                }
                TotalDevice--;
                continue;
            }

            //
            // Allocate memory for IDE_BUS_PROTOCOL
            //
            if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
                IdeBlockIoDev = MallocZ( sizeof(IDE_BLK_IO_DEV));

                if ( !IdeBlockIoDev ) {
                    return EFI_OUT_OF_RESOURCES;
                }
                IdeBlockIoDev->Signature = IDE_BLK_IO_DEV_SIGNATURE;
                IdeBusInterface          = (IDE_BUS_PROTOCOL*)&(IdeBlockIoDev->BlkIo);
            } else {
                IdeBusInterface = MallocZ( sizeof(IDE_BUS_PROTOCOL));

                if ( !IdeBusInterface ) {
                    return EFI_OUT_OF_RESOURCES;
                }
            }

            //
            // Initialize the fields
            //

            if ( gPlatformIdeProtocol->EfiIdeProtocol ) { 
                IdeBusInterface->EfiIdeControllerInterface =(EFI_IDE_CONTROLLER_INIT_PROTOCOL*) IdeControllerInterface;
                IdeBusInterface->IdeControllerInterfaceHandle = Controller;
            } else {
                IdeBusInterface->IdeControllerInterface =(IDE_CONTROLLER_PROTOCOL*) IdeControllerInterface;
            }
            IdeBusInterface->IdeBusInitInterface  = IdeBusInitInterface;
            IdeBusInterface->PciIO                = PciIO;
            IdeBusInterface->IdeDevice.PciIO      = PciIO;
            IdeBusInterface->IdeDevice.Channel    = Current_Channel;
            IdeBusInterface->IdeDevice.Device     = Current_Device;
            IdeBusInterface->AtaReadWritePio      = AtaReadWritePio;
            IdeBusInterface->AtaPioDataIn         = AtaPioDataIn;
            IdeBusInterface->AtaPioDataOut        = AtaPioDataOut;
            IdeBusInterface->IdeNonDataCommand    = IdeNonDataCommandExp;
            IdeBusInterface->WaitForCmdCompletion = WaitForCmdCompletion;
            IdeBusInterface->GeneralAtapiCommandAndData = GeneralAtapiCommandAndData;
            Status = UpdateBaseAddress( IdeBusInterface );

            if ( Status == EFI_SUCCESS ) {
                Status = DetectIdeDevice( IdeBusInterface );
            }

            if ( EFI_ERROR( Status ) ) {
                //
                // Update IdeBusInitInterface
                //
                IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] = DEVICE_DETECTION_FAILED;
                if ( gPlatformIdeProtocol->EfiIdeProtocol )
                    pBS->FreePool( IdeBlockIoDev );
                else
                    pBS->FreePool( IdeBusInterface );
 
                if ( gPlatformIdeProtocol->MasterSlaveEnumeration ) {
                    Current_Device++;
                } else {
                    Current_Device--;
                }
                TotalDevice--;
                continue;
            } else {
                IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device]  = DEVICE_DETECTED_SUCCESSFULLY;
                IdeBusInitInterface->pIdeBusProtocol[Current_Channel][Current_Device] = IdeBusInterface; // Save the Pointer
            }

            if ( gPlatformIdeProtocol->MasterSlaveEnumeration ) {
                Current_Device++;
            } else {
                Current_Device--;
            }
            TotalDevice--;
        }                                                               // Loop for Master/Slave
    }                                                                   // Loop for Primary/Secondary

    //---------------------------------------------------------------------------------------------------------
    //	Device Detection Ends
    //---------------------------------------------------------------------------------------------------------
    //	Configuration Starts
    //---------------------------------------------------------------------------------------------------------
    PROGRESS_CODE( DXE_IDE_ENABLE );

    for ( Current_Channel = Start_Channel; Current_Channel <= End_Channel; Current_Channel++ )
    {
        for ( Current_Device = Start_Device; Current_Device <= End_Device; Current_Device++ )
        {

            //  
            //Check whether the given device is detected successfully
            //
            if ( IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_DETECTED_SUCCESSFULLY ) {
                IdeBusInterface = IdeBusInitInterface->pIdeBusProtocol[Current_Channel][Current_Device];

                Status = ConfigureIdeDeviceAndController( IdeBusInterface, IdeControllerInterface, IdeBusInitInterface );

                if ( EFI_ERROR( Status )) {
                    ERROR_CODE( DXE_IDE_DEVICE_FAILURE, EFI_ERROR_MAJOR );

                    if ( gPlatformIdeProtocol->EfiIdeProtocol )
                        pBS->FreePool( IdeBlockIoDev );
                    else
                        pBS->FreePool( IdeBusInterface );

                    IdeBusInitInterface->pIdeBusProtocol[Current_Channel][Current_Device] = NULL;
                    continue;
                }

                //
                //Device has been successfully detected and configured.
                //

                //
                //Create the Devicepath
                //  
                Status = CreateIdeDevicePath( This, Controller, IdeBusInitInterface, IdeBusInterface, RemainingDevicePath, Current_Channel, Current_Device );

                if ( EFI_ERROR( Status )) {
                    if ( gPlatformIdeProtocol->EfiIdeProtocol )
                        pBS->FreePool( IdeBlockIoDev );
                    else
                        pBS->FreePool( IdeBusInterface );
                    continue;
                }

                //
                //Initialize Block_IO Protocol
                //
                Status = InitIdeBlockIO( IdeBusInterface );

                if ( EFI_ERROR( Status )) {
                    if ( gPlatformIdeProtocol->EfiIdeProtocol )
                        pBS->FreePool( IdeBlockIoDev );
                    else
                        pBS->FreePool( IdeBusInterface );
                    continue;
                }

                //
                //Initialize IDE EFI_DISK_INFO_PROTOCOL
                //
                Status = InitIdeDiskInfo( IdeBusInterface );

                if ( EFI_ERROR( Status )) {
                    if ( gPlatformIdeProtocol->EfiIdeProtocol )
                        pBS->FreePool( IdeBlockIoDev );
                    else
                        pBS->FreePool( IdeBusInterface );
                    continue;
                }

                //
                //Install Devicepath
                //
                Status = pBS->InstallMultipleProtocolInterfaces(
                                            &(IdeBusInterface->IdeDeviceHandle),
                                            &gDevicePathProtocolGuid, IdeBusInterface->DevicePathProtocol,
                                            NULL );

                if ( EFI_ERROR( Status )) {
                    IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] = DEVICE_DETECTION_FAILED;
                    if ( gPlatformIdeProtocol->EfiIdeProtocol )
                        pBS->FreePool( IdeBlockIoDev );
                    else
                        pBS->FreePool( IdeBusInterface );
                    continue;
                }

                //
                //Open IdeControllerProtocol
                //
                Status = pBS->OpenProtocol( Controller,
                                            &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                                            (VOID**)&IdeControllerInterface,
                                            This->DriverBindingHandle,
                                            IdeBusInterface->IdeDeviceHandle,
                                            EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER );


                //
                //Install other optional Protocols - Hdd Security
                //
                Status = pBS->LocateProtocol(
                                &gHddSecurityInitProtocolGuid,
                                 NULL,
                                 &HddSecurityInitProtocol
                                );

                if ( !EFI_ERROR( Status )) {
                    if ( HddSecurityInitProtocol != NULL ) {
                        HddSecurityInitProtocol->InstallSecurityInterface( IdeBusInterface, FALSE );
                    }
                } else {
                    //
                    // If Security Feature support is not enabled, always freeze lock the security feature
                    //
                    if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_82 & 0x2 ) {
                        Status = IdeNonDataCommand( IdeBusInterface, 0, 0,
                                                    0, 0, 0,
                                                    IdeBusInterface->IdeDevice.Device << 4,
                                                    SECURITY_FREEZE_LOCK );
                        //
                        // if Device Configuration Overlay feature set supported then issue the
                        // Dev config Free lock command.
                        //
                        if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_83 & 0x800 ) {
                            Status = IdeNonDataCommand( IdeBusInterface, DEV_CONFIG_FREEZE_LOCK_FEATURES, 0,
                                                        0, 0, 0,
                                                        IdeBusInterface->IdeDevice.Device << 4,
                                                        DEV_CONFIG_FREEZE_LOCK );
                        }
                        // Update the Identify device buffer
                        GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));
                    }
                }

                //
                // Install other optional Protocols - OpalSecurity
                //

                Status = pBS->LocateProtocol (
                                    &gOpalSecInitProtocolGuid,
                                    NULL,
                                    &OpalSecInitProtocol
                                );

                if(!EFI_ERROR(Status)) {
                    if(OpalSecInitProtocol != NULL) {
                        OpalSecInitProtocol->InstallOpalSecurityInterface(IdeBusInterface, FALSE);
                    }
                }

                //
                //Install other optional Protocols - SMART
                //
                Status = pBS->LocateProtocol(
                                    &gHddSmartInitProtocolGuid,
                                    NULL,
                                    &HddSmartInitProtocol
                                    );

                if ( !EFI_ERROR( Status )) {
                    if ( HddSmartInitProtocol != NULL ) {
                        HddSmartInitProtocol->InitSMARTSupport( IdeBusInterface, FALSE );
                        //
                        //Get the updated IdentifyData
                        //
                        GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));
                        if ( HddSmartInitProtocol->SmartDiagonasticFlag ) {
                            HddSmartInitProtocol->InstallSMARTInterface( IdeBusInterface, FALSE );
                        }
                    }
                }

                if ( gPlatformIdeProtocol->IdePwrManagementInterfaceSupport ) {
                    InstallIDEPowerMgmtInterface( IdeBusInterface );
                }

                if ( gPlatformIdeProtocol->HostProtectedAreaSupport ) {
                    InstallHPAInterface( IdeBusInterface );
                }

#ifdef Debug_Level_3
                PrintIdeDeviceInfo( IdeBusInterface );
#endif
            }                                               // DEVICE_CONFIGURED_SUCCESSFULLY

            //Before installing BlockIO and DiskInfo protocol, check whether the device has been
            //password protected. If yes, BlockIO and DiskInfo will not be installed.
            IdeBusInterface = IdeBusInitInterface->pIdeBusProtocol[Current_Channel][Current_Device];

            if ( IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_CONFIGURED_SUCCESSFULLY ) {
                //
                //Check BlockIO has been installed or not.
                //
                Status = pBS->OpenProtocol( IdeBusInterface->IdeDeviceHandle,
                                            &gEfiBlockIoProtocolGuid,
                                            NULL,
                                            This->DriverBindingHandle,
                                            IdeBusInterface->IdeDeviceHandle,
                                            EFI_OPEN_PROTOCOL_TEST_PROTOCOL );

                if ( EFI_ERROR( Status )) {
                    //
                    //BLOCKIO not installed and device has been configured successfully
                    //  
                    Status = EFI_UNSUPPORTED;
                    Status = pBS->InstallMultipleProtocolInterfaces(
                                        &(IdeBusInterface->IdeDeviceHandle),
                                        &gEfiBlockIoProtocolGuid, (EFI_BLOCK_IO_PROTOCOL*)(IdeBusInterface->IdeBlkIo),
                                        &gEfiDiskInfoProtocolGuid, (EFI_DISK_INFO_PROTOCOL*)(IdeBusInterface->IdeDiskInfo),
                                        NULL );
                }                                                       // If BlockIO not Installed
            }                                                           // End of installing BlockIO and DiskInfo
        }                                                               // Loop for Master/Slave
    }                                                                   // Loop for Primary/Secondary

    //---------------------------------------------------------------------------------------------------------
    //	Configuration Ends
    //---------------------------------------------------------------------------------------------------------

    // Check HP Support and Ide Controller protocol to create an HP event
    if ( gPlatformIdeProtocol->IdeHPSupport == 1 && gPlatformIdeProtocol->EfiIdeProtocol == 0 ) {

        // 
        // Check whether already HP Event has been created and also HP is supported
        //  
        if ( IdeBusInitInterface->HPEvent == NULL && IdeBusInitInterface->HPMask ) {
            //
            // Create and Event
            //
            Status = pBS->CreateEvent( EFI_EVENT_TIMER | EFI_EVENT_NOTIFY_SIGNAL,
                                   TPL_CALLBACK,
                                   IdeHPTimer,
                                   IdeBusInitInterface,
                                   &(IdeBusInitInterface->HPEvent));

            if ( Status == EFI_SUCCESS ) {
                pBS->SetTimer( IdeBusInitInterface->HPEvent, TimerPeriodic, 20000000 ); // 2sec
            }
        }
    }

    Status = pBS->LocateProtocol (
                                &gAtaPassThruInitProtocolGuid,
                                NULL,
                                &AtaPassThruInitProtocol
                        );

    if(!EFI_ERROR(Status)) {
        if(AtaPassThruInitProtocol != NULL) {
            AtaPassThruInitProtocol->InstallAtaPassThru(Controller, FALSE);
        }
    }

    // SCSIPassThruAtapi install
    Status = pBS->LocateProtocol (
                                &gScsiPassThruAtapiInitProtocolGuid,
                                NULL,
                                &gScsiPassThruAtapiInitProtocol
                        );

    if(!EFI_ERROR(Status)) {
        if(gScsiPassThruAtapiInitProtocol != NULL) {
            gScsiPassThruAtapiInitProtocol->InstallScsiPassThruAtapi(Controller, FALSE);
        }
    }

    //
    // This will notify AMITSE to invoke the HDD password Screen
    //
    Status = pBS->InstallProtocolInterface(
        &Controller,
        &gHddSecurityEndProtocolGuid, EFI_NATIVE_INTERFACE, NULL
        );

#ifdef Debug_Level_1
    EfiDebugPrint( -1, "IdeBusStart Exit Success\n" );
#endif

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IdeBusStop
//
// Description:	Uninstall all devices installed in start procedure.
//
// Input:
//	IN EFI_DRIVER_BINDING_PROTOCOL    *This,
//	IN EFI_HANDLE                     Controller,
//	IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: OpenProtocol CloseProtocol
//
// Notes:
//  Here is the control flow of this function:
// 1.  Check whether "gEfiIdeBusInitProtocolGuid" is installed on this controller. If not exit with error.
// 2.  If "NumberOfChildren" is zero, check wether all child devices have been stopped. If not exit with error.
//                      if all child devices have been stopped, then close "gEfiIdeControllerProtocolGuid" and "gEfiIdeBusInitProtocolGuid",
//		        uninstall "gEfiIdeBusInitProtocolGuid" and then exit with success.
// 3.  If "NumberOfChildren" is non-zero,	close "gEfiIdeControllerProtocolGuid" opened by the child device in start function.
//			uninstall all protocols installed on this child device in start function,
//			free up all resources allocated in start function. Repeat step	3 for all child devices and	return success at the end.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IdeBusStop(
    IN EFI_DRIVER_BINDING_PROTOCOL *This,
    IN EFI_HANDLE                  Controller,
    IN UINTN                       NumberOfChildren,
    IN EFI_HANDLE                  *ChildHandleBuffer )
{
    IDE_BUS_INIT_PROTOCOL            *IdeBusInitInterface;
    IDE_BUS_PROTOCOL                 *IdeBusInterface = NULL;
    EFI_STATUS                       Status;
    IDE_BLK_IO_DEV                   *IdeBlockIoDev = NULL;
    VOID                             *IdeControllerInterface = NULL ;
 
    UINT8 Current_Channel                 = 0xff;
    UINT8 Current_Device                  = 0xff;
    UINT8 Index                           = 0;
    BOOLEAN                          Flag = TRUE;
    EFI_DEVICE_PATH_PROTOCOL         *DevicePath;

    //
    //Check if IDE_BUS_INIT_PROTOCOL is installed on the Controller.
    //
    Status = pBS->OpenProtocol( Controller,
                                &gEfiIdeBusInitProtocolGuid,
                                (VOID**)&IdeBusInitInterface,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_GET_PROTOCOL );

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

    //
    //Check if ChildHandleBuffer is valid
    //
    if ( NumberOfChildren ) {
        while ( NumberOfChildren )
        {
            Status = pBS->OpenProtocol(
                ChildHandleBuffer[Index],
                &gDevicePathProtocolGuid,
                (VOID**)&DevicePath,
                This->DriverBindingHandle,
                Controller,
                EFI_OPEN_PROTOCOL_GET_PROTOCOL );

            //Lookout for ATAPI device path
            //ACPI_DEVICE path, PCI Device path and then ATAPI device path will be the sequence
            do
            {
                if ((DevicePath->Type == MESSAGING_DEVICE_PATH) && (DevicePath->SubType == MSG_ATAPI_DP)) {
                    Current_Channel = ((ATAPI_DEVICE_PATH*)DevicePath)->PrimarySecondary;
                    Current_Device  = ((ATAPI_DEVICE_PATH*)DevicePath)->SlaveMaster;
                    break;
                } else {
                    DevicePath = NEXT_NODE( DevicePath );
                }
            } while ( DevicePath->Type != END_DEVICE_PATH );

            if ( Current_Channel == 0xff || Current_Device == 0xff ) {
                return EFI_DEVICE_ERROR;
            }

            //
            //Get the pointer to IDE_BUS_PROTOCOL
            //
            IdeBusInterface = IdeBusInitInterface->pIdeBusProtocol[Current_Channel][Current_Device];

            //
            //Close all the protocols opened by this Child Device
            //
            pBS->CloseProtocol(
                        Controller,
                        &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                        This->DriverBindingHandle,
                        ChildHandleBuffer[Index] );

            //Before uninstalling BLOCKIO check whether it is installed or not
            Status = pBS->OpenProtocol( ChildHandleBuffer[Index],
                                        &gEfiBlockIoProtocolGuid,
                                        NULL,
                                        This->DriverBindingHandle,
                                        ChildHandleBuffer[Index],
                                        EFI_OPEN_PROTOCOL_TEST_PROTOCOL );

            if ( Status == EFI_SUCCESS ) {
                Status = pBS->UninstallMultipleProtocolInterfaces(
                                    ChildHandleBuffer[Index],
                                    &gEfiBlockIoProtocolGuid, (EFI_BLOCK_IO_PROTOCOL*)(IdeBusInterface->IdeBlkIo),
                                    &gEfiDiskInfoProtocolGuid, (EFI_DISK_INFO_PROTOCOL*)(IdeBusInterface->IdeDiskInfo),
                                    NULL );
            }

            Status = pBS->    UninstallMultipleProtocolInterfaces(
                ChildHandleBuffer[Index],
                &gDevicePathProtocolGuid, IdeBusInterface->DevicePathProtocol,
                NULL );

            if ( EFI_ERROR( Status )) {
                pBS->OpenProtocol( Controller,
                                   &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                                   (VOID**)&IdeControllerInterface,
                                   This->DriverBindingHandle,
                                   ChildHandleBuffer[Index],
                                   EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER );

                return EFI_DEVICE_ERROR;
            }  else {
                //
                //Now free up all resources allocated.
                //
                if ( IdeBusInterface->IdeDevice.AtapiDevice != NULL ) {
                    pBS->FreePool( IdeBusInterface->IdeDevice.AtapiDevice->PacketBuffer );
                    pBS->FreePool( IdeBusInterface->IdeDevice.AtapiDevice->InquiryData );
                    pBS->FreePool( IdeBusInterface->IdeDevice.AtapiDevice );
                }

                //
                //Freeup resources allocated for component names
                //
                if ( IdeBusInterface->IdeDevice.UDeviceName != NULL ) {
                    pBS->FreePool( IdeBusInterface->IdeDevice.UDeviceName->Language );
                    pBS->FreePool( IdeBusInterface->IdeDevice.UDeviceName->UnicodeString );
                    pBS->FreePool( IdeBusInterface->IdeDevice.UDeviceName );
                }

                // Uninstall optional protocols

                //
                //Before uninstalling HDD security check whether it is installed or not
                //
                Status = pBS->OpenProtocol( ChildHandleBuffer[Index],
                                            &gHddSecurityInitProtocolGuid,
                                            (VOID**)&HddSecurityInitProtocol,
                                            This->DriverBindingHandle,
                                            ChildHandleBuffer[Index],
                                            EFI_OPEN_PROTOCOL_TEST_PROTOCOL );

                if ( !EFI_ERROR( Status )) {
                    if ( HddSecurityInitProtocol != NULL ) {
                        HddSecurityInitProtocol->StopSecurityModeSupport( IdeBusInterface, FALSE );
                    }
                }

                //
                //Before uninstalling Hdd Smart check whether it is installed or not
                //
                Status = pBS->OpenProtocol( ChildHandleBuffer[Index],
                                            &gHddSmartInitProtocolGuid,
                                            (VOID**)&HddSmartInitProtocol,
                                            This->DriverBindingHandle,
                                            ChildHandleBuffer[Index],
                                            EFI_OPEN_PROTOCOL_TEST_PROTOCOL );

                if ( !EFI_ERROR( Status )) {
                    if ( HddSmartInitProtocol != NULL ) {
                        if ( HddSmartInitProtocol->SmartDiagonasticFlag ) {
                            HddSmartInitProtocol->UnInstallSMARTInterface( IdeBusInterface, FALSE );
                        }
                    }
                }

                //
                //Before uninstalling OPAL security Interface check whether it is installed or not.
                //
                Status = pBS->OpenProtocol( ChildHandleBuffer[Index],
                                            &gOpalSecInitProtocolGuid,
                                            (VOID**)&OpalSecInitProtocol,
                                            This->DriverBindingHandle,
                                            ChildHandleBuffer[Index],
                                            EFI_OPEN_PROTOCOL_TEST_PROTOCOL );

                if ( !EFI_ERROR( Status )) {
                    if ( OpalSecInitProtocol != NULL ) {
                        OpalSecInitProtocol->UnInstallOpalSecurityInterface( IdeBusInterface, FALSE );
                    }
                }

	            if ( gPlatformIdeProtocol->IdePwrManagementInterfaceSupport ) {
	                StopIDEPowerMgmtInterface( IdeBusInterface );
	            }

	            if ( gPlatformIdeProtocol->HostProtectedAreaSupport ) {
	                StopHPAInterface( IdeBusInterface );
	            }

	            if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
	                IdeBlockIoDev = IDE_BLOCK_IO_DEV_FROM_THIS( &(IdeBusInterface->IdeBlkIo));
                }
                pBS->FreePool( IdeBusInterface->IdeBlkIo->BlkIo.Media );
                pBS->FreePool( IdeBusInterface->IdeBlkIo );
                pBS->FreePool( IdeBusInterface->IdeDiskInfo );
                Current_Channel = IdeBusInterface->IdeDevice.Channel;
                Current_Device  = IdeBusInterface->IdeDevice.Device;
                IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] = DEVICE_IN_RESET_STATE;
                pBS->FreePool( IdeBusInterface->DevicePathProtocol );

	            if ( gPlatformIdeProtocol->EfiIdeProtocol )
	                pBS->FreePool( IdeBlockIoDev );
	            else
	                pBS->FreePool( IdeBusInterface );
            }
            NumberOfChildren--;
            Index++;
        }

        return EFI_SUCCESS;
    } else {
        //   
        //Check if IDE_BUS_INIT_PROTOCOL can be removed
        //
        for ( Current_Channel = PRIMARY_CHANNEL; Current_Channel <= SECONDARY_CHANNEL; Current_Channel++ )
        {
            for ( Current_Device = MASTER_DRIVE; Current_Device <= SLAVE_DRIVE; Current_Device++ )
            {
                if ( IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] == DEVICE_CONFIGURED_SUCCESSFULLY ) {
                    Flag = FALSE;
                }
            }
        }

        //
        // Can't uninstall IDE_BUS_INIT_PROTOCOL if any one of the IDE devices are in "CONFIGURED" state.
        //
        if ( Flag == TRUE ) {
            if ( gPlatformIdeProtocol->IdeHPSupport ) {

	            //
	            // Check whether already HP Event has been created and also HP is supported
	            //    
	            if ( IdeBusInitInterface->HPEvent != NULL ) {
	                pBS->CloseEvent( IdeBusInitInterface->HPEvent );
                }
            }
            //    
            //Close all the protocols opened in Start Function
            //
            Status = pBS->CloseProtocol( Controller,
                                         &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                                         This->DriverBindingHandle,
                                         Controller );
            //
            // AtaPass Thru uninstall
            //
            Status = pBS->LocateProtocol (
                                &gAtaPassThruInitProtocolGuid,
                                NULL,
                                &AtaPassThruInitProtocol
                        );

            if(!EFI_ERROR(Status)) {
                 if(AtaPassThruInitProtocol != NULL) {
                     AtaPassThruInitProtocol->StopAtaPassThruSupport(Controller, FALSE);
                 }
             }
            //
            // ScsiPassThruAtapi uninstall
            //
            Status = pBS->LocateProtocol (
                                &gScsiPassThruAtapiInitProtocolGuid,
                                NULL,
                                &gScsiPassThruAtapiInitProtocol);

             if(!EFI_ERROR(Status)) {
                 if(gScsiPassThruAtapiInitProtocol != NULL) {
                     gScsiPassThruAtapiInitProtocol->StopScsiPassThruAtapiSupport(Controller, FALSE);
                 }
             }


            Status = pBS->CloseProtocol( Controller,
                                         &gEfiIdeBusInitProtocolGuid,
                                         This->DriverBindingHandle,
                                         Controller );

            Status = pBS->UninstallProtocolInterface( Controller,
                                                      &gEfiIdeBusInitProtocolGuid,
                                                      IdeBusInitInterface );

            if ( EFI_ERROR( Status ))  {
                Status = pBS->OpenProtocol( Controller,
                                            &gEfiIdeBusInitProtocolGuid,
                                            (VOID**)&IdeBusInitInterface,
                                            This->DriverBindingHandle,
                                            Controller,
                                            EFI_OPEN_PROTOCOL_BY_DRIVER );

                Status = pBS->OpenProtocol( Controller,
                                            &(gPlatformIdeProtocol->gIdeControllerProtocolGuid),
                                            (VOID**)&IdeControllerInterface,
                                            This->DriverBindingHandle,
                                            Controller,
                                            EFI_OPEN_PROTOCOL_BY_DRIVER );

                return EFI_DEVICE_ERROR;
            }

	        if ( gPlatformIdeProtocol->EfiIdeProtocol )
	            pBS->FreePool( IdeBlockIoDev );
	        else
	            pBS->FreePool( IdeBusInterface );

            if ( gDescriptorBuffer != NULL ) {
                pBS->FreePool( gDescriptorBuffer );
            }
            gDescriptorBuffer = NULL;
            return EFI_SUCCESS;
        } else {
            return EFI_DEVICE_ERROR;
        }
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	InstallBusInitProtocol
//
// Description:	Installs BUS Init Protocol on the IDE controller Handle
//
// Input:
//	IN EFI_HANDLE                     Controller,
//	IDE_BUS_INIT_PROTOCOL			*IdeBusInitInterface;
//	IDE_CONTROLLER_PROTOCOL			*IdeControllerInterface
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: AllocatePool, InstallProtocolInterface, IdeGetControllerInfo
//
// Notes:
//  Here is the control flow of this function:
//	1. Call "IdeGetControllerInfo", to get channel information from IdeController driver.
//  2. Install "gEfiIdeBusInitProtocolGuid" on the IDE controller.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS InstallBusInitProtocol(
    IN EFI_HANDLE                Controller,
    IN OUT IDE_BUS_INIT_PROTOCOL *IdeBusInitInterface,
    IN VOID *IdeControllerInterfaceIn
    )
{
    CONTROLLER_INFO *ControllerInfo;
    EFI_IDE_CONTROLLER_INIT_PROTOCOL    *EfiIdeControllerInterface = NULL ;
    IDE_CONTROLLER_PROTOCOL             *IdeControllerInterface = NULL ;
    EFI_STATUS      Status;

    //
    // Initialize IdeControllerInterface
    //
    if ( gPlatformIdeProtocol->EfiIdeProtocol )
        EfiIdeControllerInterface = ( EFI_IDE_CONTROLLER_INIT_PROTOCOL *) IdeControllerInterfaceIn;
    else
        IdeControllerInterface = ( IDE_CONTROLLER_PROTOCOL *) IdeControllerInterfaceIn;

    //
    //Initialize the default Values
    //
    ZeroMemory( IdeBusInitInterface, sizeof(IDE_BUS_INIT_PROTOCOL));

    Status = pBS->AllocatePool( EfiBootServicesData,
                                sizeof(CONTROLLER_INFO),
                                (VOID**)&ControllerInfo
                                );

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

    ZeroMemory( ControllerInfo, sizeof(CONTROLLER_INFO));

    if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
        ControllerInfo->Flags = 0; // ACOUSTIC_SUPPORT_DISABLE

        if ( gPlatformIdeProtocol->SBIdeSupport ) {
            Status = pBS->LocateProtocol(&gIdeSetupProtocolguid, NULL, &gIdeSetupProtocol);

            if ( gPlatformIdeProtocol->AcousticManagementSupport ) {  

                if (!EFI_ERROR(Status)) {

                    if(gIdeSetupProtocol->AcousticPwrMgmt)
                        ControllerInfo->Flags |= ACOUSTIC_SUPPORT_ENABLE;
                    else
                        ControllerInfo->Flags &= ~ACOUSTIC_SUPPORT_ENABLE;
                    ControllerInfo->Acoustic_Management_Level   = gIdeSetupProtocol->AcousticLevel;
                } else {
                    ControllerInfo->Flags &= ~ACOUSTIC_SUPPORT_ENABLE ;
                    ControllerInfo->Acoustic_Management_Level   = ACOUSTIC_LEVEL_BYPASS;
                }
            } //End of ACOUSTIC_MANAGEMENT_SUPPORT   
        } //End of SBIDE_SUPPORT

        if ( gPlatformIdeProtocol->HddPowerLossInS3 ) {
            ControllerInfo->Flags |= S3_RESUME_UNLOCK_HDD_PASSWORD;
        }

        ControllerInfo->PrimaryChannel        = PRIMARY_CHANNEL_ENABLE;
        ControllerInfo->PrimaryMasterDevice   = PRIMARY_MASTER_DRIVE_ENABLE;
        ControllerInfo->PrimarySlaveDevice    = PRIMARY_SLAVE_DRIVE_ENABLE;
        ControllerInfo->SecondaryChannel      = SECONDARY_CHANNEL_ENABLE;
        ControllerInfo->SecondaryMasterDevice = SECONDARY_MASTER_DRIVE_ENABLE;
        ControllerInfo->SecondarySlaveDevice  = SECONDARY_SLAVE_DRIVE_ENABLE;
        ControllerInfo->BusMasterEnable       = BUSMASTER_ENABLE;
        ControllerInfo->HPMask                = 0;           // Hot Plug Mask

    } else {
		IdeControllerInterface->IdeGetControllerInfo( Controller, ControllerInfo );
    }

    if ( ControllerInfo->PrimaryChannel == DEVICE_DISABLED ) {
        IdeBusInitInterface->IdeBusInitData[PRIMARY_CHANNEL][MASTER_DRIVE] = DEVICE_DISABLED;
        IdeBusInitInterface->IdeBusInitData[PRIMARY_CHANNEL][SLAVE_DRIVE]  = DEVICE_DISABLED;
    } else {
        IdeBusInitInterface->IdeBusInitData[PRIMARY_CHANNEL][MASTER_DRIVE] = ControllerInfo->PrimaryMasterDevice;
        IdeBusInitInterface->IdeBusInitData[PRIMARY_CHANNEL][SLAVE_DRIVE]  = ControllerInfo->PrimarySlaveDevice;
    }

    if ( ControllerInfo->SecondaryChannel == DEVICE_DISABLED ) {
        IdeBusInitInterface->IdeBusInitData[SECONDARY_CHANNEL][MASTER_DRIVE] = DEVICE_DISABLED;
        IdeBusInitInterface->IdeBusInitData[SECONDARY_CHANNEL][SLAVE_DRIVE]  = DEVICE_DISABLED;
    } else {
        IdeBusInitInterface->IdeBusInitData[SECONDARY_CHANNEL][MASTER_DRIVE] = ControllerInfo->SecondaryMasterDevice;
        IdeBusInitInterface->IdeBusInitData[SECONDARY_CHANNEL][SLAVE_DRIVE]  = ControllerInfo->SecondarySlaveDevice;
    }

    IdeBusInitInterface->BusMasterSelection        = ControllerInfo->BusMasterEnable;
    IdeBusInitInterface->HPMask                    = ControllerInfo->HPMask;
    if ( gPlatformIdeProtocol->EfiIdeProtocol )
        IdeBusInitInterface->EfiIdeControllerInterface = EfiIdeControllerInterface;
    else
        IdeBusInitInterface->IdeControllerInterface   	 = IdeControllerInterface;

    IdeBusInitInterface->Flags                     = ControllerInfo->Flags;
    IdeBusInitInterface->Acoustic_Management_Level = ControllerInfo->Acoustic_Management_Level;

    Status = pBS->FreePool( ControllerInfo );

    // Initialize PrevPortNum and PrevPortMultiplierPortNum for AtaPassThru to 0xFFFF

    IdeBusInitInterface->PrevPortNum = 0xffff;
    IdeBusInitInterface->PrevPortMultiplierPortNum = 0xffff;

    Status = pBS->InstallProtocolInterface(
        &Controller,
        &gEfiIdeBusInitProtocolGuid,
        EFI_NATIVE_INTERFACE,
        IdeBusInitInterface );

    if ((IdeBusInitInterface->BusMasterSelection) &&  gDescriptorBuffer == NULL ) {
        //Since the PRD table need to be aligned at 64KB to create maximum # of tables
        //allocate 128KB and use the 64KB aligned address,
        Status = pBS->AllocatePool( EfiBootServicesData,
                                    2 * 64 * 1024,
                                    (VOID**)&gDescriptorBuffer
                                    );

        if ( EFI_ERROR( Status )) {
            IdeBusInitInterface->BusMasterSelection = 0;
        }
    }

#ifdef Debug_Level_3
    EfiDebugPrint( -1, "Installed IDE_BUS_INIT_PROTOCOL\n" );
#endif

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	ConfigureIdeDeviceAndController
//
// Description:	PIO and DMA mode programming both on the Controller as well as on the Device is done
//
// Input:
//	IDE_BUS_INIT_PROTOCOL			*IdeBusInitInterface
//	IDE_CONTROLLER_PROTOCOL			*IdeControllerInterface
//	IDE_BUS_INIT_PROTOCOL			*IdeBusInitInterface
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: ConfigureIdeDevice, GetIdentifyData
//
// Notes:
//  Here is the control flow of this function:
// 1. Get the Best PIO and DMA mode supported by the device from Identify Data
// 2. Set the PIO and DMA mode in the IDE controller.
// 3. Configure the IDE device with the PIO and DMA mode.
// 4. Update the Identify Data.
// 5. Based on the IDE device select the proper Read/Write commands.
// 6. Construct a unicode string for the IDE device.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS ConfigureIdeDeviceAndController(
    IN IDE_BUS_PROTOCOL                 *IdeBusInterface,
    IN VOID              *IdeControllerInterfaceIn,
    IN IDE_BUS_INIT_PROTOCOL            *IdeBusInitInterface )
{
    EFI_STATUS              Status;
    UINT8                   Current_Channel = IdeBusInterface->IdeDevice.Channel;
    UINT8                   Current_Device  = IdeBusInterface->IdeDevice.Device;

    EFI_ATA_COLLECTIVE_MODE *SupportedModes = NULL;
    EFI_IDE_CONTROLLER_INIT_PROTOCOL       *EfiIdeControllerInterface = NULL ;
    IDE_CONTROLLER_PROTOCOL    *IdeControllerInterface = NULL ;


    if ( gPlatformIdeProtocol->EfiIdeProtocol )
        EfiIdeControllerInterface = (EFI_IDE_CONTROLLER_INIT_PROTOCOL*) IdeControllerInterfaceIn;
    else
        IdeControllerInterface = (IDE_CONTROLLER_PROTOCOL *) IdeControllerInterfaceIn;

    if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
        GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));
        Status = EfiIdeControllerInterface->SubmitData( EfiIdeControllerInterface, IdeBusInterface->IdeDevice.Channel,
                                                 IdeBusInterface->IdeDevice.Device, (EFI_IDENTIFY_DATA*)&(IdeBusInterface->IdeDevice.IdentifyData));

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

	    Status = EfiIdeControllerInterface->CalculateMode( EfiIdeControllerInterface, IdeBusInterface->IdeDevice.Channel,
                                                    IdeBusInterface->IdeDevice.Device, &SupportedModes );

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

	    Status = EfiIdeControllerInterface->SetTiming( EfiIdeControllerInterface, IdeBusInterface->IdeDevice.Channel,
                                                IdeBusInterface->IdeDevice.Device, SupportedModes );

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

	    IdeBusInterface->IdeDevice.PIOMode = 0xff;
	    IdeBusInterface->IdeDevice.SWDma   = 0xff;
	    IdeBusInterface->IdeDevice.MWDma   = 0xff;
	    IdeBusInterface->IdeDevice.UDma    = 0xff;

        if ( SupportedModes->PioMode.Valid ) {
            IdeBusInterface->IdeDevice.PIOMode = SupportedModes->PioMode.Mode;
        }

        if ( SupportedModes->SingleWordDmaMode.Valid ) {
            IdeBusInterface->IdeDevice.SWDma = SupportedModes->SingleWordDmaMode.Mode;
        }

        if ( SupportedModes->MultiWordDmaMode.Valid ) {
             IdeBusInterface->IdeDevice.MWDma = SupportedModes->MultiWordDmaMode.Mode;
        }

        if ( SupportedModes->UdmaMode.Valid ) {
            IdeBusInterface->IdeDevice.UDma = SupportedModes->UdmaMode.Mode;
        }

	    IdeBusInterface->IdeDevice.IORdy = ((EFI_IDENTIFY_DATA*)&(IdeBusInterface->IdeDevice.IdentifyData))->AtaData.capabilities & 0x800;

    } else {
        //    
        // Get the best PIO and DMA mode from the IDE device
        //    
	    IdeControllerInterface->GetbestPioDmaMode( &(IdeBusInterface->IdeDevice));

        //
        // Program PIO mode Timing in the controller
        //
	    IdeControllerInterface->IdeSetPioMode( &(IdeBusInterface->IdeDevice));

        // See if Bus Master has been enabled
	    IdeControllerInterface->IdeSetDmaMode( &(IdeBusInterface->IdeDevice)); 
    }

    //	Issue SET feature command to set the PIO and DMA mode
    Status = ConfigureIdeDevice( IdeBusInterface, IdeBusInitInterface );

    if ( EFI_ERROR( Status )) {
        return Status;
    } else {
        //
        //Get the updated IdentifyData
        //
        GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));

        //
        //Check if UDMA and MWDMA are programmed successfully
        //    
        if ( IdeBusInterface->IdeDevice.UDma != 0xff ) {
            if ( !(ReturnMSBset((IdeBusInterface->IdeDevice.IdentifyData.UDMA_Mode_88 >> 8)) == IdeBusInterface->IdeDevice.UDma)) {
                IdeBusInterface->IdeDevice.UDma = ReturnMSBset((IdeBusInterface->IdeDevice.IdentifyData.UDMA_Mode_88 >> 8));
                if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
                    SupportedModes->UdmaMode.Mode = IdeBusInterface->IdeDevice.UDma;
                    EfiIdeControllerInterface->SetTiming( EfiIdeControllerInterface, IdeBusInterface->IdeDevice.Channel,
                                                             IdeBusInterface->IdeDevice.Device, SupportedModes );
                } else {
                    IdeControllerInterface->IdeSetDmaMode( &(IdeBusInterface->IdeDevice));
                }
            }
        } else {
            if ( IdeBusInterface->IdeDevice.MWDma != 0xff ) {
                if ( !(ReturnMSBset( IdeBusInterface->IdeDevice.IdentifyData.MultiWord_DMA_63 >> 8 ) == IdeBusInterface->IdeDevice.MWDma)) {
                    IdeBusInterface->IdeDevice.MWDma = ReturnMSBset( (IdeBusInterface->IdeDevice.IdentifyData.MultiWord_DMA_63 >> 8));
                    if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
                        SupportedModes->MultiWordDmaMode.Mode = IdeBusInterface->IdeDevice.MWDma;
                        EfiIdeControllerInterface-> SetTiming( EfiIdeControllerInterface, IdeBusInterface->IdeDevice.Channel,
                                                        IdeBusInterface->IdeDevice.Device, SupportedModes );
                    } else {
                        IdeControllerInterface->IdeSetDmaMode( &(IdeBusInterface->IdeDevice));
                    } 
                }
            }
        }

        //		Check for ATA
        if ( IdeBusInterface->IdeDevice.DeviceType == ATA ) {
            //			Update IDE Read/Write Command
            if  ((IdeBusInterface->IdeDevice.IdentifyData.Valid_Bits_59 & 0x100)
                 && (IdeBusInterface->IdeDevice.IdentifyData.Valid_Bits_59 & 0xff)) {  // Check if Multiple Read/Write
                if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_83 & 0x400 ) {
                    //					48Bit LBA supported
                    IdeBusInterface->IdeDevice.ReadCommand  = READ_MULTIPLE_EXT;
                    IdeBusInterface->IdeDevice.WriteCommand = WRITE_MULTIPLE_EXT;
                } else {
                    IdeBusInterface->IdeDevice.ReadCommand  = READ_MULTIPLE;
                    IdeBusInterface->IdeDevice.WriteCommand = WRITE_MULTIPLE;
                }
            } else {                      // 1 Block = 1 Sector
                if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_83 & 0x400 ) {
                    //					48Bit LBA supported
                    IdeBusInterface->IdeDevice.ReadCommand  = READ_SECTORS_EXT;
                    IdeBusInterface->IdeDevice.WriteCommand = WRITE_SECTORS_EXT;
                } else {
                    IdeBusInterface->IdeDevice.ReadCommand  = READ_SECTORS;
                    IdeBusInterface->IdeDevice.WriteCommand = WRITE_SECTORS;
                }
            }

            if ( DMACapable( IdeBusInterface )) {
                if ( gPlatformIdeProtocol->IdeBusMasterSupport ) {
                    IdeBusInterface->IdeDevice.ReadCommand  = READ_DMA;
                    IdeBusInterface->IdeDevice.WriteCommand = WRITE_DMA;

                    if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_83 & 0x400 ) {
                    //
                    // 48Bit LBA supported
                    //
                        IdeBusInterface->IdeDevice.ReadCommand  = READ_DMA_EXT;
                        IdeBusInterface->IdeDevice.WriteCommand = WRITE_DMA_EXT;
	                }
 			    }
            }
        }    
        IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] = DEVICE_CONFIGURED_SUCCESSFULLY;
    }

    if ( gPlatformIdeProtocol->DisableSoftSetPrev || gPlatformIdeProtocol->ForceHddPasswordPrompt ) {

        //
        // Software settings preserved
        //
        if ((IdeBusInterface->IdeDevice.IdentifyData.Reserved_76_79[0] != 0xFFFF)
            && (IdeBusInterface->IdeDevice.IdentifyData.Reserved_76_79[2] & 0x0040)) {
            Status = IdeSetFeatureCommand( IdeBusInterface, DISABLE_SATA2_SOFTPREV, 6 );
            //
            // Get the updated IdentifyData
            //
            GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));
        }
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	InitIdeBlockIO
//
// Description:	Initializes IDE Block IO interface
//
// Input:
//
//	IDE_BUS_PROTOCOL				*IdeBusInterface,
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: AllocatePool, OpenProtocol, DetectAtapiMedia, AtapiInquiryData
//
// Notes:
//  Here is the control flow of this function:
//  1. Initialize EFI_BLOCK_IO_PROTOCOL Protocol.
//	2. In case of Removable devices, detect Media presence.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS InitIdeBlockIO(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    EFI_STATUS            Status;
    EFI_BLOCK_IO_PROTOCOL *BlkIo;
    IDE_BLOCK_IO          *IdeBlkIo;
    EFI_BLOCK_IO_MEDIA    *BlkMedia;
    ATAPI_DEVICE          *AtapiDevice;
    UINT8                 *Data;
    UINT8                 *InquiryData;
    UINT16                InquiryDataSize;
    UINT8                 Current_Channel;
    UINT8                 Current_Device;
    UINT8                 bTemp;
    UINT16                OddType = 0;
    UINT8                 OddLoadingType =0xFF;
    UINT32                SectorSize = ATA_SECTOR_BYTES;

    Status = pBS->AllocatePool( EfiBootServicesData,
                                sizeof(IDE_BLOCK_IO),
                                (VOID**)&IdeBlkIo );

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


    BlkMedia = MallocZ( sizeof(EFI_BLOCK_IO_MEDIA));

    if ( !BlkMedia ) {
        pBS->FreePool( IdeBlkIo );
        return EFI_OUT_OF_RESOURCES;
    }

    //
    //Initialize the IdeBlkIo pointer in IDE_BUS_PROTOCOL (IdeBusInterface)
    //
    IdeBusInterface->IdeBlkIo = IdeBlkIo;

    //
    //Initialize the fields in IdeBlkIo (IDE_BLOCK_IO)
    //    
    IdeBlkIo->IdeBusInterface = IdeBusInterface;

    if ( IdeBusInterface->IdeDevice.DeviceType == ATA ) {
        //    
        //ATA
        //    
        BlkIo              = &(IdeBlkIo->BlkIo);
        //
        // UEFI2.3.1 Supports the BlockIo Revision 3
        //
        if(pST->Hdr.Revision >= 0x0002001F) {
            BlkIo->Revision    = EFI_BLOCK_IO_PROTOCOL_REVISION3;
        } else {
            BlkIo->Revision    = BLKIO_REVISION;
        }
        BlkIo->Media       = BlkMedia;
        BlkIo->Reset       = AtaReset;
        BlkIo->ReadBlocks  = AtaBlkRead;
        BlkIo->WriteBlocks = AtaBlkWrite;
        BlkIo->FlushBlocks = AtaBlkFlush;

        BlkMedia->MediaId        = 0;
        BlkMedia->RemovableMedia = (IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 0x80) == 0x80 ? TRUE : FALSE;

        //Check if Hot plug supported for this device
        Current_Channel = IdeBusInterface->IdeDevice.Channel;
        Current_Device  = IdeBusInterface->IdeDevice.Device;
        bTemp           = Current_Channel == 0 ? 1 : 4;       // BIT MASK

        if ( Current_Device ) {
            bTemp <<= 1;
        }

        if ( bTemp & IdeBusInterface->IdeBusInitInterface->HPMask ) {
            BlkMedia->RemovableMedia = TRUE;
        }

        BlkMedia->MediaPresent     = TRUE;
        BlkMedia->LogicalPartition = FALSE;
        BlkMedia->ReadOnly         = FALSE;
        BlkMedia->WriteCaching     = FALSE;


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

        BlkMedia->BlockSize = SectorSize;

        //If BusMaster Support is Enabled for the device, IO Alignment should be DWORD

        if ( DMACapable( IdeBusInterface )) {
            BlkMedia->IoAlign = 4;
        } else {
            BlkMedia->IoAlign = 0;
        }

        if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_83 & 0x400 ) {
            BlkMedia->LastBlock = IdeBusInterface->IdeDevice.IdentifyData.LBA_48 - 1;
        } else {
            BlkMedia->LastBlock = IdeBusInterface->IdeDevice.IdentifyData.Addressable_Sector_60 - 1;
        }

        if(pST->Hdr.Revision >= 0x0002001F) {

            BlkMedia->OptimalTransferLengthGranularity=BlkMedia->BlockSize;
            //
            // bit 14 of word 106 is set to one and bit 15 of word 106 is cleared to zero, 
            // then the contents of word 106 contain valid information . 
            // Otherwise, information is not valid in this word.
            //
            if ( (IdeBusInterface->IdeDevice.IdentifyData.Reserved_104_126[2] & 0xC000) == 0x4000 ) {
                //
                // If bit 13 of word 106 is set to one, then the device has more than one 
                // logical sector per physical sector and bits (3:0) of word 106 are valid
                //
                if ( IdeBusInterface->IdeDevice.IdentifyData.Reserved_104_126[2] & 0x2000 ) {
    
                    BlkMedia->LogicalBlocksPerPhysicalBlock = 1 << 
                                    (IdeBusInterface->IdeDevice.IdentifyData.Reserved_104_126[2] & 0xF);
    
                    //
                    // Bits 13:0 of word 209 indicate the Logical sector offset within the first physical 
                    // sector where the first logical sector is placed
                    //
                    BlkMedia->LowestAlignedLba =IdeBusInterface->IdeDevice.IdentifyData.Reserved_206_254[3] & 0x3FFF;
    
                } else {
                    //
                    // Default set the 1 logical blocks per PhysicalBlock
                    //
                    BlkMedia->LogicalBlocksPerPhysicalBlock=1;
    
                    //
                    // Default value set to 0 for Lowest Aligned LBA
                    //
                    BlkMedia->LowestAlignedLba=0;
                }
            } else {
                    //
                    // Default set the 1 logical blocks per PhysicalBlock
                    //
                    BlkMedia->LogicalBlocksPerPhysicalBlock=1;
                    //
                    // Default value set to 0 for Lowest Aligned LBA
                    //
                    BlkMedia->LowestAlignedLba=0;
            }
        }
    } else {
        //
        //If it is an ATAPI device, check whether it is a CDROM or not. Currently only CDROM/Direct access Devices are supported.
        //
        if ((IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 0x1f00) == (CDROM_DEVICE << 8)
            || (IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 0x1f00) == (DIRECT_ACCESS_DEVICE << 8)
            || (IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 0x1f00) == (OPTICAL_MEMORY_DEVICE << 8)) {
            AtapiDevice = MallocZ( sizeof (ATAPI_DEVICE));

            if ( !AtapiDevice ) {
                return EFI_OUT_OF_RESOURCES;
            }

            IdeBusInterface->IdeDevice.AtapiDevice = AtapiDevice;

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

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

            AtapiDevice->PacketBuffer = Data;
            AtapiDevice->DeviceType   = (IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 0x1f00) >> 8;
            AtapiDevice->PacketSize   = (IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 3) == 1 ? 16 : 12;

            BlkIo              = &(IdeBlkIo->BlkIo);
            //
            // UEFI2.3.1 Supports the BlockIo Revision 3
            //
            if(pST->Hdr.Revision >= 0x0002001F) {
                BlkIo->Revision    = EFI_BLOCK_IO_PROTOCOL_REVISION3;
            } else {
                BlkIo->Revision    = BLKIO_REVISION;
            }
            BlkIo->Media       = BlkMedia;
            BlkIo->Reset       = AtapiReset;
            BlkIo->ReadBlocks  = AtapiBlkRead;
            BlkIo->WriteBlocks = AtapiBlkWrite;
            BlkIo->FlushBlocks = AtapiBlkFlush;
            //
            //Initialize with default value. Later on it will be updated if needed.
            //
            BlkMedia->BlockSize = CDROM_BLOCK_SIZE;


            //
            //Update Inquiry Data
            //
            Status = pBS->AllocatePool( EfiBootServicesData,
                                        INQUIRY_DATA_LENGTH,
                                        (VOID**)&InquiryData );

            if ( EFI_ERROR( Status )) {
                return Status;
            }
            InquiryDataSize = INQUIRY_DATA_LENGTH;
            AtapiInquiryData( IdeBusInterface, InquiryData, &InquiryDataSize );
            AtapiDevice->InquiryData     = InquiryData;
            AtapiDevice->InquiryDataSize = InquiryDataSize;

            //
            // Get the ATAPI drive Type information and save it ATAPI_DEVICE
            //
            Status = GetOddType( IdeBusInterface, &OddType );

            if ( !EFI_ERROR( Status )) {
                AtapiDevice->OddType = GetEnumOddType( OddType );
            }

            //
            // Get the ATAPI drive Loading information and save it ATAPI_DEVICE
            //
            Status = GetOddLoadingType( IdeBusInterface, &OddLoadingType );

            if ( !EFI_ERROR( Status )) {
                AtapiDevice->OddLoadingType = (ODD_LOADING_TYPE)OddLoadingType;
            } else {
                AtapiDevice->OddLoadingType = (ODD_LOADING_TYPE)0xFF;
            }

            BlkMedia->RemovableMedia   = (IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 0x80) == 0x80 ? TRUE : FALSE;
            BlkMedia->LogicalPartition = FALSE;
            BlkMedia->WriteCaching     = FALSE;

            //
            //If BusMaster Support is Enabled for the device, IO Alignment should be DWORD
            //
            if ( DMACapable( IdeBusInterface )) {
                BlkMedia->IoAlign = 4;
            } else {
                BlkMedia->IoAlign = 0;
            }
        }
    }
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	GetEnumOddType
//
// Description:	Get the Enum value for ODD type found on profile
//
// Input:
//
//      UINT16      Oddtype
// Output:
//      ODD_TYPE    EnumValue
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
ODD_TYPE GetEnumOddType(
    UINT16 OddType )
{
    switch ( OddType )
    {
    case 1:
    case 3:
    case 4:
    case 5:
        return Obsolete;

    case 2:
        return Removabledisk;

    case 8:
        return CDROM;

    case 9:
        return CDR;

    case 0xa:
        return CDRW;

    case 0x10:
        return DVDROM;

    case 0x11:
        return DVDRSequentialrecording;

    case 0x12:
        return DVDRAM;

    case 0x13:
        return DVDRWRestrictedOverwrite;

    case 0x15:
        return DVDRWSequentialrecording;

    case 0x16:
        return DVDRDualLayerJumprecording;

    case 0x17:
        return DVDRWDualLayer;

    case 0x18:
        return DVDDownloaddiscrecording;

    case 0x1a:
        return DVDRW;

    case 0x1b:
        return DVDR;

    case 0x40:
        return BDROM;

    case 0x41:
        return BDRSequentialRecording;

    case 0x42:
        return BDRRandomRecordingMode;

    case 0x43:
        return BDRE;

    case 0x50:
        return HDDVDROM;

    case 0x51:
        return HDDVDR;

    case 0x52:
        return HDDVDRAM;

    case 0x53:
        return HDDVDRW;

    case 0x58:
        return HDDVDRDualLayer;

    case 0x5a:
        return HDDVDRWDualLayer;

    default:
        return UnknownType;
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	InitIdeDiskInfo
//
// Description:	Initializes IDE DiskInfo Interface
//
// Input:
//
//	IDE_BUS_PROTOCOL		*IdeBusInterface,
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: AllocatePool OpenProtocol
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS InitIdeDiskInfo(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    EFI_STATUS    Status;
    IDE_DISK_INFO *IdeDiskInfo;

    Status = pBS->AllocatePool( EfiBootServicesData,
                                sizeof(IDE_DISK_INFO),
                                (VOID**)&IdeDiskInfo );

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

    //
    //Initialize the IdeBlkIo pointer in IDE_BUS_PROTOCOL (IdeBusInterface)
    //
    IdeBusInterface->IdeDiskInfo = IdeDiskInfo;

    //
    //Initialize the fields in IdeDiskInfo (IDE_DISK_INFO)
    //
    IdeDiskInfo->IdeBusInterface = IdeBusInterface;

    pBS->CopyMem( &(IdeDiskInfo->DiskInfo.Interface), &gEfiIdeDiskInfoProtocolGuid, sizeof (EFI_GUID));
    IdeDiskInfo->DiskInfo.Inquiry   = DiskInfoInquiry;
    IdeDiskInfo->DiskInfo.Identify  = DiskInfoIdentify;
    IdeDiskInfo->DiskInfo.SenseData = DiskInfoSenseData;
    IdeDiskInfo->DiskInfo.WhichIde  = DiskInfoWhichIDE;
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	CreateIdeDevicePath
//
// Description:	Creates a IDE device devicepath and adds it to IdeBusInterface
//
// Input:
//	IN EFI_DRIVER_BINDING_PROTOCOL  *This,
//	IN EFI_HANDLE                   Controller,
//	IDE_BUS_INIT_PROTOCOL			*IdeBusInitInterface;
//	IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
//	UINT8							Current_Channel
//	UINT8							Current_Device
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: AllocatePool, OpenProtocol, IdeBusStart
//
// Notes:
//  Here is the control flow of this function:
//  1.  If Remaining Devicepath is not NULL, we have already verified that it is a
//			valid Atapi device path in IdeBusStart. So nothing to do. Just exit.
//	2.	Build a Atapi devicepath and a End devce path.
//	3.  Get the Devicepath for the IDE controller.
//	3.  Append Atapi devicepath to  IDE controller devicepath.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS CreateIdeDevicePath(
    IN EFI_DRIVER_BINDING_PROTOCOL  *This,
    IN EFI_HANDLE                   Controller,
    IDE_BUS_INIT_PROTOCOL           *IdeBusInitInterface,
    IDE_BUS_PROTOCOL                *IdeBusInterface,
    IN OUT EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath,
    IN UINT8                        Current_Channel,
    IN UINT8                        Current_Device )
{
    EFI_STATUS               Status;
    ATAPI_DEVICE_PATH        NewDevicePath;
    EFI_DEVICE_PATH_PROTOCOL *TempDevicePath;

    NewDevicePath.Header.Type    = MESSAGING_DEVICE_PATH;
    NewDevicePath.Header.SubType = MSG_ATAPI_DP;
    SET_NODE_LENGTH( &NewDevicePath.Header, ATAPI_DEVICE_PATH_LENGTH );
    NewDevicePath.PrimarySecondary = Current_Channel;
    NewDevicePath.SlaveMaster      = Current_Device;
    NewDevicePath.Lun              = 0;

    //
    //Append the Device Path
    //
    Status = pBS->OpenProtocol( Controller,
                                &gDevicePathProtocolGuid,
                                (VOID**)&TempDevicePath,
                                This->DriverBindingHandle,
                                Controller,
                                EFI_OPEN_PROTOCOL_GET_PROTOCOL );

    IdeBusInterface->DevicePathProtocol = DPAddNode( TempDevicePath, &NewDevicePath.Header );
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	ConfigureIdeDevice
//
// Description:	Issues SET FEATURE Command
//
// Input:
//		IDE_BUS_PROTOCOL			*IdeBusInterface,
//		IDE_BUS_INIT_PROTOCOL		*IdeBusInitInterface
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: ConfigureIdeDeviceAndController, IdeSetFeatureCommand
//
// Notes:
//  Here is the control flow of this function:
//  1. Issue Set feature commend to set PIO mode if needed.
//	2. Set Multiple Mode command for ATA devices if needed.
//  3. Issue Set feature commend to set UDMA/MWDMA. If it fails, disable Busmaster support.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS ConfigureIdeDevice(
    IN IDE_BUS_PROTOCOL      *IdeBusInterface,
    IN IDE_BUS_INIT_PROTOCOL *IdeBusInitInterface )
{
    EFI_STATUS               Status= EFI_SUCCESS;
    UINT8                    DMACapability;
    UINT8                    Data8;
    IO_REGS                  Regs = IdeBusInterface->IdeDevice.Regs;
    UINT16                   DeviceName[41];
    UINT16                   Index;

    EFI_UNICODE_STRING_TABLE *tempUnicodeTable;
    CHAR8                    Language[] = "Eng";

    //
    //Check if Device need spin-up
    //
    if ((IdeBusInterface->IdeDevice.IdentifyData.General_Config_0 & 4)
        && (IdeBusInterface->IdeDevice.IdentifyData.Special_Config_2 == SPIN_UP_REQUIRED1
            || IdeBusInterface->IdeDevice.IdentifyData.Special_Config_2 == SPIN_UP_REQUIRED2)) {
        Status = IdeSetFeatureCommand( IdeBusInterface, SET_DEVICE_SPINUP, 0 );

        if ( EFI_ERROR( Status )) {    
            //
            //Some HDD may take a long time to spin up. Wait for additional time
            //
            Status = WaitforBitClear( IdeBusInterface->PciIO, Regs.ControlBlock.AlternateStatusReg, BSY | DRQ, gPlatformIdeProtocol->PoweonBusyClearTimeout );
        }
        //
        //Get the Identify Command once more
        //
        GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));
    }

    //
    //	Check if PIO mode needs to be programmed
    //    
    if ((IdeBusInterface->IdeDevice.IdentifyData.Valid_Bits_53 & 0x2) && (IdeBusInterface->IdeDevice.PIOMode != 0xff)) {
        Status = IdeSetFeatureCommand( IdeBusInterface, SET_TRANSFER_MODE, PIO_FLOW_CONTROL | IdeBusInterface->IdeDevice.PIOMode );
    }

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

    //
    //Issue Set Multiple Mode Command only for ATA device
    //
    if  ( IdeBusInterface->IdeDevice.DeviceType == ATA ) {
        Data8 = IdeBusInterface->IdeDevice.IdentifyData.Maximum_Sector_Multiple_Command_47 & 0xff;

        if ( Data8 & 0x2 ) {
            Data8 = 2;
        }

        if ( Data8 & 0x4 ) {
            Data8 = 0x4;
        }

        if ( Data8 & 0x8 ) {
            Data8 = 0x8;
        }

        if ( Data8 & 0x10 ) {
            Data8 = 0x10;
        }

        if ( Data8 & 0x20 ) {
            Data8 = 0x20;
        }

        if ( Data8 & 0x40 ) {
            Data8 = 0x40;
        }

        if ( Data8 & 0x80 ) {
            Data8 = 0x80;
        }

        if ( Data8 > 1 ) {
            Status = IdeNonDataCommand(
                IdeBusInterface,
                0,              // Features
                Data8,          // Sector Count
                0,              // LBA Low
                0,              // LBA Mid
                0,              // LBA High
                IdeBusInterface->IdeDevice.Device << 4, // Device
                SET_MULTIPLE_MODE );                     // Command
        }
    }

    //Check if Busmaster Enabled
    //Status = EFI_NOT_FOUND;
    //Check if  UDMA is supported
    if  ( IdeBusInterface->IdeDevice.UDma != 0xff ) {
        Status =     IdeSetFeatureCommand( IdeBusInterface, SET_TRANSFER_MODE, UDMA_MODE | IdeBusInterface->IdeDevice.UDma );
    } else {
        if ( IdeBusInterface->IdeDevice.MWDma != 0xff ) {
            Status = IdeSetFeatureCommand( IdeBusInterface, SET_TRANSFER_MODE, MWDMA_MODE | IdeBusInterface->IdeDevice.MWDma );
        }
    }

    if ( EFI_ERROR( Status )) {
        //
        //No DMA support
        //
        IdeBusInterface->IdeDevice.UDma  = 0xff;
        IdeBusInterface->IdeDevice.MWDma = 0xff;
    } else {
        //
        //Enable DMA capable bit
        //
        DMACapability = 0x20;

        if ( IdeBusInterface->IdeDevice.Device ) {
            DMACapability = 0x40;
        }

        if ( DMACapable( IdeBusInterface )) {
            IdeReadByte( IdeBusInterface->PciIO,
                         IdeBusInterface->IdeDevice.Regs.BusMasterBlock.BMStatusRegister,
                         &Data8 );
            Data8 |= DMACapability;
            IdeWriteByte( IdeBusInterface->PciIO,
                          IdeBusInterface->IdeDevice.Regs.BusMasterBlock.BMStatusRegister,
                          Data8 );
        }
    }

    //
    //Convert the Device string from Engligh to Unicode
    //
    IdeBusInterface->IdeDevice.UDeviceName = NULL;
	if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
	    IdeBusInterface->ControllerNameTable = IdeBusInterface->IdeDevice.UDeviceName;
	} 

    for ( Index = 0; Index < 40; Index += 2 ) {

            DeviceName[Index]     = ((UINT8*)IdeBusInterface->IdeDevice.IdentifyData.Model_Number_27)[Index + 1];
            DeviceName[Index + 1] = ((UINT8*)IdeBusInterface->IdeDevice.IdentifyData.Model_Number_27)[Index];
    }

    for ( Index = 39; Index >= 0; Index-- ) {
        if ( DeviceName[Index] == 0x20 )
            continue;
        else 
            break;
    }

    DeviceName[Index + 1] = 0;        // Terminate string
    Index += 2;

    //
    //This is a patch to make it work for both in Aptio and Alaska
    //
    tempUnicodeTable = MallocZ( sizeof (EFI_UNICODE_STRING_TABLE) * 2 );

    Status = pBS->AllocatePool( EfiBootServicesData,
                                sizeof (Language),
                                (VOID**)&tempUnicodeTable[0].Language
                                );

    Status = pBS->AllocatePool( EfiBootServicesData,
                                Index * (sizeof (UINT16)),
                                (VOID**)&tempUnicodeTable[0].UnicodeString
                                );


    pBS->CopyMem( tempUnicodeTable[0].Language, &Language,  sizeof(Language));
    pBS->CopyMem( tempUnicodeTable[0].UnicodeString, DeviceName, Index * (sizeof (UINT16)));
    tempUnicodeTable[1].Language           = NULL;
    tempUnicodeTable[1].UnicodeString      = NULL;
    IdeBusInterface->IdeDevice.UDeviceName = tempUnicodeTable;
	if ( gPlatformIdeProtocol->EfiIdeProtocol ) {
	    IdeBusInterface->ControllerNameTable = IdeBusInterface->IdeDevice.UDeviceName;
	} 
    if ( gPlatformIdeProtocol->SBIdeSupport ) {
        InitMiscConfig(IdeBusInterface);
    }

	if ( gPlatformIdeProtocol->IdePowerManagementSupport ) {
	    Status = InitIDEPowerManagement( IdeBusInterface );
	}

    return EFI_SUCCESS;
}

//**********************************************************************
//<AMI_PHDR_START>
//
// Procedure:	InitMiscConfig
//
// Description:	Initialize misc IDE configurations.
//
// Input:
//	IN SATA_DEVICE_INTERFACE	*SataDevInterface	
//
// Output:
//	None
//
//<AMI_PHDR_END>
//**********************************************************************
VOID InitMiscConfig (
    IN IDE_BUS_PROTOCOL    *IdeBusInterface
)
{
    if ( gPlatformIdeProtocol->DiPMSupport ) {

        if(IdeBusInterface->IdeDevice.IdentifyData.Reserved_76_79[2] & \
                IDENTIFY_DiPM__SUPPORT) { // DiPM supported?
            //
            // Always disable DiPM in IDE mode
            //
            IdeSetFeatureCommand (IdeBusInterface, DiPM_DISABLE, DiPM_SUB_COMMAND);
        }
    }
    if ( gPlatformIdeProtocol->AcousticManagementSupport ) {
    	InitAcousticSupport (IdeBusInterface);
	}

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	InitAcousticSupport
//
// Description:	Initializes Acoustic Management Support functionality
//
// Input:
//		IDE_BUS_PROTOCOL			*IdeBusInterface,
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: IdeSetFeatureCommand
//
// Notes:
// 1. Check if the device support Acoustic management.
// 2. Check the desired state Vs the current state.
// 3. If both are equal nothing to do exit else program the desired level
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS InitAcousticSupport(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    UINT8 Data8;

    //
    //	Check if the device supports Acoustic Management
    //
    if  ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_83 & 0x200 ) {
        //
        //Check if Acoustic Level need to be enabled or Disabled
        //
        if ( IdeBusInterface->IdeBusInitInterface->Flags & ACOUSTIC_SUPPORT_ENABLE ) {
            Data8 = IdeBusInterface->IdeBusInitInterface->Acoustic_Management_Level;

            //
            // Do we need to program the recommended value
            //
			if ( Data8 == ACOUSTIC_LEVEL_BYPASS ) {
                //
                // Get the rcommended value
                //
				Data8 = (UINT8)(IdeBusInterface->IdeDevice.IdentifyData.Acoustic_Level_94 >> 8);
			}

				IdeSetFeatureCommand (IdeBusInterface, ACOUSTIC_MANAGEMENT_ENABLE, Data8);
		} else {
                //
                // If already disabled, nothing to do
                //
			if	(IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Enabled_86 & 0x200) 			
				IdeSetFeatureCommand (IdeBusInterface, ACOUSTIC_MANAGEMENT_DISABLE, 0);
		}
	}
	return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	UpdateBaseAddress
//
// Description:	Updates Command and Control reg address.
//
// Input:
//	IDE_BUS_PROTOCOL			*IdeBusInterface;
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: IdeBusStart
//
// Notes:
//  Here is the control flow of this function:
//  1. Using PCI_IO_PROTOCOL, update the Command, control and Busmaster reg address.
//	Make use of Channel number while updating. Also check whether controller is running in Legacy/Native mode
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS UpdateBaseAddress(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    EFI_PCI_IO_PROTOCOL *PciIO;
    UINT8               PciConfig[0x40];
    UINT16              CommandReg;
    UINT16              ControlReg;
    UINT16              BusMasterReg;


    PciIO = IdeBusInterface->PciIO;
    PciIO->Pci.Read(
        PciIO,
        EfiPciIoWidthUint8,
        0,
        sizeof (PciConfig),
        PciConfig );

    if ((PciConfig [PROGRAMMING_INTERFACE_OFFSET] & (IdeBusInterface->IdeDevice.Channel == 0 ? 1 : 4))
        || (PciConfig [IDE_SUB_CLASS_CODE] == SCC_AHCI_CONTROLLER)
        || (PciConfig [IDE_SUB_CLASS_CODE] == SCC_RAID_CONTROLLER)) {
        //   
        //Native Mode Secondary
        //    
        if ( IdeBusInterface->IdeDevice.Channel ) {
            CommandReg   =    (*(UINT16*)(PciConfig + SECONDARY_COMMAND_BLOCK_OFFSET)) & 0xfffe;
            ControlReg   =   ((*(UINT16*)(PciConfig + SECONDARY_CONTROL_BLOCK_OFFSET)) & 0xfffe) + 2;
            BusMasterReg = ((*(UINT16*)(PciConfig + LEGACY_BUS_MASTER_OFFSET)) & 0xfffe) + 8;
        } else {  
            //
            // Native mode Primary
            //   
            CommandReg   =   (*(UINT16*)(PciConfig + PRIMARY_COMMAND_BLOCK_OFFSET)) & 0xfffe;
            ControlReg   =  ((*(UINT16*)(PciConfig + PRIMARY_CONTROL_BLOCK_OFFSET)) & 0xfffe) + 2;
            BusMasterReg = (*(UINT16*)(PciConfig + LEGACY_BUS_MASTER_OFFSET)) & 0xfffe;
        }
    } else {
        //
        //Legacy Mode Secondary
        //
        if ( IdeBusInterface->IdeDevice.Channel ) {
            CommandReg   = SECONDARY_COMMAND_BLOCK;
            ControlReg   = SECONDARY_CONTROL_BLOCK;
            BusMasterReg = (*(UINT16*)(PciConfig + LEGACY_BUS_MASTER_OFFSET) & 0xfffe) + 8;
        } else {      
            //
            //Legacy mode Primary
            //
            CommandReg   = PRIMARY_COMMAND_BLOCK;
            ControlReg   = PRIMARY_CONTROL_BLOCK;
            BusMasterReg = (*(UINT16*)(PciConfig + LEGACY_BUS_MASTER_OFFSET) & 0xfffe);
        }
    }

    //
    //	Validate the Address
    //
    if ( CommandReg == 0 || ControlReg == 0 ) {
        return EFI_DEVICE_ERROR;
    }

    if ( CommandReg == 0xfffe || ControlReg == 0xfffe ) {
        return EFI_DEVICE_ERROR;
    }

    //
    //Update the Command block registers
    //
    IdeBusInterface->IdeDevice.Regs.CommandBlock.DataReg        = CommandReg;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.FeatureReg     = CommandReg + 1;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.ErrorReg       = CommandReg + 1;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.SectorCountReg = CommandReg + 2;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.LBALowReg      = CommandReg + 3;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.LBAMidReg      = CommandReg + 4;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.LBAHighReg     = CommandReg + 5;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.DeviceReg      = CommandReg + 6;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.CommandReg     = CommandReg + 7;
    IdeBusInterface->IdeDevice.Regs.CommandBlock.StatusReg      = CommandReg + 7;

    //
    //Update the Control Block Register address
    //
    IdeBusInterface->IdeDevice.Regs.ControlBlock.DeviceControlReg   = ControlReg;
    IdeBusInterface->IdeDevice.Regs.ControlBlock.AlternateStatusReg = ControlReg;


    //
    //Update the Bus Master register address
    //
    IdeBusInterface->IdeDevice.Regs.BusMasterBlock.BMCommandRegister           = BusMasterReg;
    IdeBusInterface->IdeDevice.Regs.BusMasterBlock.BMStatusRegister            = BusMasterReg + 2;
    IdeBusInterface->IdeDevice.Regs.BusMasterBlock.BMDescriptorTablePointerReg = BusMasterReg + 4;

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	DMACapable
//
// Description:	Check if DMA is supported
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//
// Output:
//		TRUE : DMA Capable
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
BOOLEAN DMACapable(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    if ( IdeBusInterface->IdeDevice.DeviceType == ATAPI ) {
        //
        // For Atapi Devices check Bit 8 in Word 49 =  DMA	Supported or not
        //
        if ((IdeBusInterface->IdeDevice.IdentifyData.Capabilities_49 & 0x100) == 0 ) {
            return FALSE;
        }
    }

    if ((IdeBusInterface->IdeDevice.UDma != 0xff)
        || (IdeBusInterface->IdeDevice.MWDma != 0xff)) {
        return TRUE;
    } else {
        return FALSE;
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	DiskInfoInquiry
//
// Description:
//
// Input:
//	IN EFI_DISK_INFO_PROTOCOL	*This,
//	IN OUT VOID					*InquiryData,
//	IN OUT UINT32				*InquiryDataSize
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeDiskInfo
//
// Notes:
//	1. Check for Atapi Device. If not exit
//	2. COpy the Inquiry Data from AtapiDevice->InquiryData to the input pointer.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DiskInfoInquiry(
    IN EFI_DISK_INFO_PROTOCOL *This,
    IN OUT VOID               *InquiryData,
    IN OUT UINT32             *InquiryDataSize )
{
    IDE_BUS_PROTOCOL *IdeBusInterface = ((IDE_BLOCK_IO*)This)->IdeBusInterface;
    ATAPI_DEVICE     *AtapiDevice     = IdeBusInterface->IdeDevice.AtapiDevice;


    //
    //	Check for ATAPI device. If not return EFI_NOT_FOUND
    //
    if ( IdeBusInterface->IdeDevice.DeviceType == ATA ) {
        return EFI_NOT_FOUND;               
    } else {
        if ( *InquiryDataSize < AtapiDevice->InquiryDataSize ) {
            *InquiryDataSize = AtapiDevice->InquiryDataSize;
            return EFI_BUFFER_TOO_SMALL;
        }

        if ( AtapiDevice->InquiryData != NULL ) {
            pBS->CopyMem( InquiryData, AtapiDevice->InquiryData, AtapiDevice->InquiryDataSize );
            *InquiryDataSize = AtapiDevice->InquiryDataSize;
            return EFI_SUCCESS;
        } else {
            return EFI_NOT_FOUND;
        }
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	DiskInfoIdentify
//
// Description:	Return Identify Data
//
// Input:
//	EFI_DISK_INFO_PROTOCOL			*This,
//	IN OUT VOID						*IdentifyData,
//	IN OUT UINT32					*IdentifyDataSize
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeDiskInfo
//
// Notes:
//	1. Return the Identify command data.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DiskInfoIdentify(
    EFI_DISK_INFO_PROTOCOL *This,
    IN OUT VOID            *IdentifyData,
    IN OUT UINT32          *IdentifyDataSize )
{
    IDE_BUS_PROTOCOL *IdeBusInterface = ((IDE_BLOCK_IO*)This)->IdeBusInterface;

    if ( *IdentifyDataSize < sizeof (IDENTIFY_DATA)) {
        *IdentifyDataSize = sizeof (IDENTIFY_DATA);
        return EFI_BUFFER_TOO_SMALL;
    }

    pBS->CopyMem( IdentifyData, &(IdeBusInterface->IdeDevice.IdentifyData), sizeof (IDENTIFY_DATA));
    *IdentifyDataSize =  sizeof (IDENTIFY_DATA);
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	DiskInfoSenseData
//
// Description:	Return InfoSenseData.
//
// Input:
//	EFI_DISK_INFO_PROTOCOL          *This,
//	VOID						*SenseData,
//	UINT32						*SenseDataSize,
//	UINT8						*SenseDataNumber
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeDiskInfo
//
// Notes:
//	1. Return the Sense data for the Atapi device.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS DiskInfoSenseData(
    IN EFI_DISK_INFO_PROTOCOL *This,
    OUT VOID                  *SenseData,
    OUT UINT32                *SenseDataSize,
    OUT UINT8                 *SenseDataNumber )
{
    return EFI_NOT_FOUND;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	DiskInfoWhichIDE
//
// Description:	Returns whether the device is PM/PS/SM/SS
//
// Input:
//	IN EFI_DISK_INFO_PROTOCOL	*This,
//	OUT UINT32					*IdeChannel,
//	OUT UINT32					*IdeDevice
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeDiskInfo
//
// Notes:
//	1. Return information about the Primary/Secondary channel and Master/Slave information.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS DiskInfoWhichIDE(
    IN EFI_DISK_INFO_PROTOCOL *This,
    OUT UINT32                *IdeChannel,
    OUT UINT32                *IdeDevice )
{
    IDE_BUS_PROTOCOL *IdeBusInterface = ((IDE_BLOCK_IO*)This)->IdeBusInterface;

    *IdeChannel = IdeBusInterface->IdeDevice.Channel;
    *IdeDevice  = IdeBusInterface->IdeDevice.Device;
    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IdeHPTimer
//
// Description:	Checks for any HP IDE device
//
// Input:
//	IN EFI_EVENT            Event,
//	IN VOID                         *Context
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID IdeHPTimer(
    IN EFI_EVENT Event,
    IN VOID      *Context )
{
    EFI_STATUS                       Status;
    UINT8                            DeviceStatus;
    UINT8                            CurrentState;
    UINT8                            Current_Channel;
    UINT8                            Current_Device;
    IDE_BUS_INIT_PROTOCOL            *IdeBusInitInterface = (IDE_BUS_INIT_PROTOCOL*)Context;

    IDE_BUS_PROTOCOL                 *IdeBusInterface;
    IN IDE_CONTROLLER_PROTOCOL       *IdeControllerInterface = IdeBusInitInterface->IdeControllerInterface;

    IdeControllerInterface->HPCheckForDeviceChange( IdeControllerInterface->PciIO,
                                                    IdeBusInitInterface->HPMask,
                                                    &DeviceStatus );

    for ( Current_Channel = PRIMARY_CHANNEL; Current_Channel <= SECONDARY_CHANNEL; Current_Channel++ )
    {
        for ( Current_Device = MASTER_DRIVE; Current_Device <= SLAVE_DRIVE; Current_Device++ )
        {
            CurrentState    = IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device];
            IdeBusInterface = IdeBusInitInterface->pIdeBusProtocol[Current_Channel][Current_Device];

            if ((CurrentState == DEVICE_CONFIGURED_SUCCESSFULLY) && ((DeviceStatus & 01) == 0)) {
                //
                //Handle Device Removal
                //
                    Status = pBS->DisconnectController( IdeControllerInterface->ControllerHandle, NULL, IdeBusInterface->IdeDeviceHandle );


                if ( Status == EFI_SUCCESS ) {
                    IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] = DEVICE_IN_RESET_STATE;
                }
            }

            if ((CurrentState != DEVICE_CONFIGURED_SUCCESSFULLY) && ((DeviceStatus & 01) == 1)) {
                //Handle device insertion
                //Force IdeBusStart to Enumerate this device.
                IdeBusInitInterface->IdeBusInitData[Current_Channel][Current_Device] = DEVICE_IN_RESET_STATE;
             
                pBS->ConnectController( IdeControllerInterface->ControllerHandle, NULL, NULL, TRUE );
            }
            DeviceStatus >>= 1;
        }
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	CheckHPControllerPresence
//
// Description:	A quick check to see if ports are still decoded.
//
// Input:
//	IN IDE_BUS_PROTOCOL			*IdeBusInterface
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS CheckHPControllerPresence(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    UINT8   Device = IdeBusInterface->IdeDevice.Device;
    IO_REGS Regs   = IdeBusInterface->IdeDevice.Regs;
    UINT8   Data8;

    //
    //Select the drive
    //
    IdeWriteByte( IdeBusInterface->PciIO, Regs.CommandBlock.DeviceReg, Device << 4 );

    //
    //Read the status Register
    //
    IdeReadByte( IdeBusInterface->PciIO, Regs.CommandBlock.StatusReg, &Data8 );

    if ( Data8 == 0xff ) {
        return EFI_NOT_FOUND;
    }

    if ( Data8 == 0x7f ) {
        return EFI_NOT_FOUND;
    }

    return EFI_SUCCESS;
}

                         // IDE_HP_SUPPORT
//---------------------------------------------------------------------------

#ifdef Debug_Level_3
//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	PrintIdeDeviceInfo
//
// Description:	Prints Debug Level 3 Trace Messages
//
// Input:
//	IN IDE_BUS_PROTOCOL			*IdeBusInterface
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
void PrintIdeDeviceInfo(
    IDE_BUS_PROTOCOL *IdeBusInterface )
{
    UINT16 Data8;
    UINT16 *pIdentifyData;

    //		Print the Channel and Device Number
    EfiDebugPrint( -1, "-----------------IDE Device Info Start-----------------\n" );
    EfiDebugPrint( -1, "Channel   : %x   Device    : %x\n", IdeBusInterface->IdeDevice.Channel, IdeBusInterface->IdeDevice.Device );
    EfiDebugPrint( -1, "PIOMode   : %x   UDMAMode  : %x\n", IdeBusInterface->IdeDevice.PIOMode, IdeBusInterface->IdeDevice.UDma );
    EfiDebugPrint( -1, "SWDMAMode : %x   MWDMAMode : %x\n", IdeBusInterface->IdeDevice.SWDma,   IdeBusInterface->IdeDevice.MWDma );
    EfiDebugPrint( -1, "IORDY		: %x   \n",                  IdeBusInterface->IdeDevice.IORdy );
    pIdentifyData = (UINT16*) &(IdeBusInterface->IdeDevice.IdentifyData);

    for ( Data8 = 0; Data8 < 0xff; Data8 += 4 )
    {
        EfiDebugPrint( -1, "%X %X %X %X\n", pIdentifyData[Data8 + 0], pIdentifyData[Data8 + 1], pIdentifyData[Data8 + 2], pIdentifyData[Data8 + 3] );
    }
        EfiDebugPrint( -1, "-----------------IDE Device Info End-------------------\n" );
}

#endif          /* Debug_Level_3 */

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	CheckAhciMode
//
// Description:	Checks If the controller is in AHCI MODE.
//
// Input:
//	IDE_BUS_PROTOCOL			*IdeBusInterface;
//
// Output:
//	BOOLEAN                     TRUE  - AHCI Mode
//                              FALSE - IDE Mode
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
BOOLEAN CheckAhciMode(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    EFI_PCI_IO_PROTOCOL *PciIO;
    UINT8               PciConfig[0x40];
    BOOLEAN             AhciFlag = FALSE;

    PciIO = IdeBusInterface->PciIO;
    PciIO->Pci.Read(
        PciIO,
        EfiPciIoWidthUint8,
        0,
        sizeof (PciConfig),
        PciConfig );

    AhciFlag = (BOOLEAN)((PciConfig [IDE_SUB_CLASS_CODE] & SCC_AHCI_CONTROLLER) ? TRUE : FALSE );

    return AhciFlag;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IssueFreezeLockCommand
//
// Description:	Issue the Freeze lock command.
//
// Input:
//	IDE_BUS_PROTOCOL			*IdeBusInterface;
//
// Output:
//
// Modified:
//
// Referrals:
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IssueFreezeLockCommand(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    EFI_STATUS Status = EFI_SUCCESS;

    if ( IdeBusInterface->IdeDevice.IdentifyData.Command_Set_Supported_82 & 0x2 ) {
        Status = IdeNonDataCommand( IdeBusInterface, 0, 0,
                                    0, 0, 0,
                                    IdeBusInterface->IdeDevice.Device << 4,
                                    SECURITY_FREEZE_LOCK );
        //    
        //Update the Identify device buffer
        //
        GetIdentifyData( IdeBusInterface, &(IdeBusInterface->IdeDevice));
    }
    return Status;
}

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