summaryrefslogtreecommitdiff
path: root/Core/EM/IdeBus/Atapi.c
blob: 7230aaca8b0aa62c4b3d88d0faaf94c98dfaee6b (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
//**********************************************************************
//**********************************************************************
//**                                                                  **
//**        (C)Copyright 1985-2010, American Megatrends, Inc.         **
//**                                                                  **
//**                       All Rights Reserved.                       **
//**                                                                  **
//**         5555 Oakbrook Pkwy, Suite 200, Norcross, GA 30093        **
//**                                                                  **
//**                       Phone: (770)-246-8600                      **
//**                                                                  **
//**********************************************************************
//**********************************************************************
// $Header: /Alaska/SOURCE/Core/Modules/IdeBus/Atapi.c 23    8/16/12 3:24a Rajeshms $
//
// $Revision: 23 $
//
// $Date: 8/16/12 3:24a $
//**********************************************************************
// Revision History
// ----------------
// $Log: /Alaska/SOURCE/Core/Modules/IdeBus/Atapi.c $
// 
// 23    8/16/12 3:24a 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
// 
// 22    11/08/11 5:16a Deepthins
// [TAG]  		EIP74607
// [Category]  	Improvement
// [Description]  	Block IO Read/Write function, the alignment should be
// proper. IoAlign value is 0 or 1 means that the buffer can be placed
// anywhere in memory. Otherwise, IoAlign must be a power of 2, and the
// requirement is that the start address of a buffer must be evenly
// divisible by IoAlign with no remainder.
// [Files]  		Ata.c, Atapi.c and AhciController.c
// 
// 21    11/07/11 4:27a Deepthins
// [TAG]  		EIP74607
// [Category]  	Improvement
// [Description]  	 IoAlign values is 0 or 1 means that the buffer can be
// placed anywhere in memory. Otherwise, IoAlign must be a power of 2, and
// the requirement is that the start address of a buffer must be evenly
// divisible by 2 to the power of IoAlign with no remainder.
// [Files]  		Atapi.c
// 
// 20    9/27/11 3:11a Rajeshms
// [TAG]  		EIP69295
// [Category]  	New Feature
// [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
// 
// 19    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
// 
// 18    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 
// 
// 17    10/11/10 11:28a Krishnakumarg
// [TAG] - EIP 43249
// [Category] - IMPROVEMENT
// [Severity] - Minor
// [Symptom]  - Non-Ascii character in comments causing build problem in
// japanese XP
// [RootCause]- Presence of Non-Ascii character
// [Solution] -  Remove Non-Ascii character present in the file
// [Files] - IdeSecurity.c,IDESMM.c, InstallIdeSmi, Ata.c, Atapi.c,
// IDEBusComponentName.c, IdeBusMaster.c, IdeHPA.c, IdePowerManagement.c
// 
// 16    8/25/10 4:08a Rameshr
// New Feature: EIP 37748
// Description: Move all the IDEBus Source driver SDL token into IdeBus
// Bin Driver.
// FilesModified: All.
// 
// 15    7/01/09 12:23p Rameshr
// Coding Standard and File header updated.
//
// 14    6/22/09 11:38a Rameshr
// Odd Type information Saved in Atapi Device Structure.
// EIP:21548
//
// 13    9/30/08 4:43p Felixp
// Bug fix(EIP 15310):Invalid error code (EFI_DEVICE_ERROR instead of
// EFI_NO_MEDIA) was returned for removable devices with no media
//
// 11    8/07/08 10:05a Rameshraju
// Interrupt cleared properly on Atapihandleerror.
//
// 10    4/22/08 4:29p Felixp
// New status codes added
//
// 9     3/06/08 4:42p Ambikas
//
// 8     13/04/07 3:00p Anandakrishnanl
// Ide Bus Module - Update source files to comply with AMI coding
// standard"!!!
//
// 7     3/13/06 2:21a Felixp
//
// 6     3/07/06 8:41a Srinin
// AtapiReset function returns EFI_SUCCESS
//
// 5     3/03/06 11:28a Srinin
// To detect Media not found error, check for Sense key = 2, ASC = 3A
// and ASCQ = 0/1/2.
//
// 4     1/09/06 11:36a Felixp
//
// 2     12/14/05 3:07p Srinin
// For Read Capacity command, available Buffer size is set to 8.
//
// 1     12/01/05 9:43a Felixp
//
// 9     10/21/05 1:38p Srinin
// Fixed Media detection  problem with slow CDROM.
//
// 8     10/06/05 12:59p Felixp
//
// 7     7/25/05 12:52p Srinin
// Delay between successive "TestUnitReady" command changed to 10msec.
//
// 6     7/18/05 4:31p Felixp
// 64-bit compatibility warnings removed
//
// 5     3/04/05 11:34a Mandal
//
// 4     2/24/05 12:21p Felixp
// bug fix in AtapiBlkRead and AtapiBlkWrite functions:
// EFI_INVALID_PARAMETER was returned when last block is read or written
// to
//
// 3     1/18/05 3:22p Felixp
// PrintDebugMessage renamed to Trace
//
// 2     1/05/05 11:21a Srinin
// BusMaster and Password Support added.
//
// 1     12/10/04 1:01p Srinin
// Initial Checkin of IdeBus Driver.
//
//
//<AMI_FHDR_START>
//---------------------------------------------------------------------------
//
// Name: ATAPI.C
//
// Description:	Supports ATAPI devices
//
//---------------------------------------------------------------------------
//<AMI_FHDR_END>


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

//
//External variables
//
extern PLATFORM_IDE_PROTOCOL    *gPlatformIdeProtocol;
extern EFI_GUID                 gEfiBlockIoProtocolGuid;

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	AtapiReset
//
// Description:	Issues ATAPI Reset command.
//
// Input:
//	IN EFI_BLOCK_IO_PROTOCOL				*This,
//	IN BOOLEAN					ExtendedVerification
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals: IssueAtapiReset, InitIdeBlockIO
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS AtapiReset(
    IN EFI_BLOCK_IO_PROTOCOL *This,
    IN BOOLEAN               ExtendedVerification )
{
    return EFI_SUCCESS;
}

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

EFI_STATUS AtapiBlkRead(
    IN EFI_BLOCK_IO_PROTOCOL *This,
    IN UINT32                MediaId,
    IN EFI_LBA               LBA,
    IN UINTN                 BufferSize,
    OUT VOID                 *Buffer )
{
    UINTN              DataN;
    EFI_STATUS         Status;
    IDE_BUS_PROTOCOL   *IdeBusInterface = ((IDE_BLOCK_IO*)This)->IdeBusInterface;
    EFI_BLOCK_IO_MEDIA *BlkMedia = This->Media;
    UINT32             BlockSize = BlkMedia->BlockSize;
    ATAPI_DEVICE       *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;
    UINTN              BufferAddress;

    //
    //Check if Media Present
    //
    if ( BlkMedia->MediaPresent == FALSE ) {
        Status = DetectAtapiMedia( IdeBusInterface );

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

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

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

    //
    //Check whether the block size is multiple of BlkMedia->BlockSize
    //
    DataN = BufferSize % BlkMedia->BlockSize;

    if ( DataN ) {
        return EFI_BAD_BUFFER_SIZE;
    }

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

    //
    //Check for Valid End LBA #
    //
    DataN = BufferSize / BlkMedia->BlockSize;

    if ( LBA + DataN > BlkMedia->LastBlock + 1 ) {
        return EFI_INVALID_PARAMETER;
    }

    if ( ( gPlatformIdeProtocol->IdeBusMasterSupport ) && ( gPlatformIdeProtocol->AtapiBusMasterSupport ) ) {
        if ( DMACapable( IdeBusInterface )) {
            Status = AtapiReadWriteBusMaster(
                        IdeBusInterface,
                        Buffer,
                        BufferSize,
                        LBA,
                        IdeBusInterface->IdeDevice.ReadCommand,
                        FALSE );
            return Status;
        }
    }


    Status = AtapiReadWritePio( IdeBusInterface,
                                Buffer,
                                BufferSize,
                                LBA,
                                IdeBusInterface->IdeDevice.ReadCommand,
                                FALSE );
    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	AtapiBlkWrite
//
// Description:	Write to the Atapi Device
//
// Input:
//	IN EFI_BLOCK_IO_PROTOCOL                        *This,
//	IN UINT32                                       MediaId,
//	IN EFI_LBA                                      LBA,
//	IN UINTN                                        BufferSize,
//	OUT VOID                                        *Buffer
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals: AtapiReadWritePio, InitIdeBlockIO
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS AtapiBlkWrite(
    IN EFI_BLOCK_IO_PROTOCOL *This,
    IN UINT32                MediaId,
    IN EFI_LBA               LBA,
    IN UINTN                 BufferSize,
    IN VOID                  *Buffer )
{
    UINTN              DataN;
    EFI_STATUS         Status;
    IDE_BUS_PROTOCOL   *IdeBusInterface = ((IDE_BLOCK_IO*)This)->IdeBusInterface;
    EFI_BLOCK_IO_MEDIA *BlkMedia = This->Media;
    UINT32             BlockSize = BlkMedia->BlockSize;
    UINTN              BufferAddress;

    //
    //	Check if Media Present
    //
    if ( BlkMedia->MediaPresent == FALSE ) {
        Status = DetectAtapiMedia( IdeBusInterface );

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

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

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

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

    //
    //Check whether the block size is multiple of BlkMedia->BlockSize
    //
    DataN = BufferSize % BlkMedia->BlockSize;

    if ( DataN ) {
        return EFI_BAD_BUFFER_SIZE;
    }

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

    //
    //Check for Valid End LBA #
    //
    DataN = BufferSize / BlkMedia->BlockSize;

    if ( LBA + DataN > BlkMedia->LastBlock + 1 ) {
        return EFI_INVALID_PARAMETER;
    }

    if ( ( gPlatformIdeProtocol->IdeBusMasterSupport ) && ( gPlatformIdeProtocol->AtapiBusMasterSupport ) ) {
        if ( DMACapable( IdeBusInterface )) {
            Status = AtapiReadWriteBusMaster(
                                        IdeBusInterface,
                                        Buffer,
                                        BufferSize,
                                        LBA,
                                        IdeBusInterface->IdeDevice.WriteCommand,
                                        TRUE );
            return Status;
        }
    }


    Status = AtapiReadWritePio( IdeBusInterface,
                                Buffer,
                                BufferSize,
                                LBA,
                                IdeBusInterface->IdeDevice.WriteCommand,
                                TRUE );
    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	AtapiBlkFlush
//
// Description:	Flush the cache
//
// Input:
//	IN EFI_BLOCK_IO_PROTOCOL                        *This,
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeBlockIO
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS AtapiBlkFlush(
    IN EFI_BLOCK_IO_PROTOCOL *This )
{
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	DetectAtapiMedia
//
// Description:	Detects whether a Media is present in the ATAPI Removable device or not.
//
// Input:
//	IDE_BUS_INIT_PROTOCOL			*IdeBusInitInterface
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeBlockIO
//
// Notes:
//	1. Issue Read Capacity command for CDROM or Read Format command for other ATAPI devices.
//	2. If step 1  is successfull, update last LBA, Block Size, Read/Write capable, Media ID
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS DetectAtapiMedia(
    IN OUT IDE_BUS_PROTOCOL *IdeBusInterface )
{
    UINT8              *InputData, *PacketBuffer, LoopCount;
    ATAPI_DEVICE       *AtapiDevice    = IdeBusInterface->IdeDevice.AtapiDevice;
    UINT8              Current_Channel = IdeBusInterface->IdeDevice.Channel;
    UINT8              Current_Device  = IdeBusInterface->IdeDevice.Device;
    EFI_BLOCK_IO_MEDIA *BlkMedia       = IdeBusInterface->IdeBlkIo->BlkIo.Media;
    EFI_STATUS         Status          = EFI_NOT_FOUND;
    UINT16             ByteCount       = 256, Data16;
    BOOLEAN            ReadCapacity    = FALSE;

    PROGRESS_CODE( DXE_REMOVABLE_MEDIA_DETECT );

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

    Status = TestUnitReady( IdeBusInterface );

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

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

    if ( EFI_ERROR( Status )) {
        return Status;
    }
    Status = pBS->AllocatePool( EfiBootServicesData, 16, (VOID**)&PacketBuffer );

    if ( EFI_ERROR( Status )) {
        pBS->FreePool( InputData );
        return Status;
    }

    ZeroMemory( PacketBuffer, 16 );

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

    for ( LoopCount  = 0; LoopCount < 5; LoopCount++ ) {
        ByteCount = Data16;
        ZeroMemory( InputData, ByteCount );
        Status = GeneralAtapiCommandAndData( IdeBusInterface,
                                             PacketBuffer,
                                             InputData,
                                             &ByteCount );

        if ( PacketBuffer[0] == ATAPI_READ_FORMAT_CAPACITIES
             && AtapiDevice->Atapi_Status == ILLEGAL_REQUEST ) {
            //
            //If the Read Format Capacities not supported by device, try
            //ReadCapacity command
            //
            ZeroMemory( PacketBuffer, 16 );
            BlkMedia->BlockSize    = CDROM_BLOCK_SIZE;         // Default size
            AtapiDevice->BlockSize = BlkMedia->BlockSize;
            PacketBuffer[0]        = ATAPI_READ_CAPACITY;
            PacketBuffer[1]        = AtapiDevice->Lun << 5;
            Data16                 = 8;
            ReadCapacity           = TRUE;
        }

        if ( AtapiDevice->Atapi_Status == EFI_SUCCESS ) {
            break;
        }

        if ( AtapiDevice->Atapi_Status == MEDIUM_NOT_PRESENT ) {
            break;
        }
    }

    if ( Status == EFI_SUCCESS ) {
        if ( ReadCapacity == TRUE ) {
            BlkMedia->LastBlock = InputData[0] << 24 | InputData[1] << 16
                                  | InputData[2] << 8 | InputData[3];

            BlkMedia->LastBlock--;
            BlkMedia->MediaPresent = TRUE;
            BlkMedia->MediaId++;
            BlkMedia->BlockSize = InputData[4] << 24 | InputData[5] << 16
                                  | InputData[6] << 8 | InputData[7];

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

        //
        //		Update ReadOnly Status
        //
        if ( AtapiDevice->DeviceType != CDROM_DEVICE ) {
            ByteCount = 256;
            ZeroMemory( PacketBuffer,     16 );
            ZeroMemory( InputData, ByteCount );
            PacketBuffer[0] = ATAPI_MODE_SENSE;
            PacketBuffer[2] = RETURN_ALL_PAGES;
            PacketBuffer[7] = ByteCount >> 8;
            PacketBuffer[8] = ByteCount & 0xff;
            Status          = GeneralAtapiCommandAndData( IdeBusInterface,
                                                          PacketBuffer,
                                                          InputData,
                                                          &ByteCount );

            if ((Status == EFI_SUCCESS) && (ByteCount > 8)) {
                BlkMedia->ReadOnly = (InputData[3] & 0x80) != 0 ? TRUE : FALSE;
            }
        }

        if(pST->Hdr.Revision >= 0x0002001F) {
            //
            // For Atapi Devices, Default set the 1 for logical blocks per PhysicalBlock
            //
            BlkMedia->LogicalBlocksPerPhysicalBlock=1;
    
            //
            // For Atapi Devices, Default value set to 0 for Lowest Aligned LBA
            //
            BlkMedia->LowestAlignedLba=0;
    
            BlkMedia->OptimalTransferLengthGranularity=BlkMedia->BlockSize;
        }
    }

    pBS->FreePool( InputData );
    pBS->FreePool( PacketBuffer );
    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	AtapiInquiryData
//
// Description:	Issues Atapi Inquiry Command and returns the DATA.
//
// Input:
//	IDE_BUS_INIT_PROTOCOL			*IdeBusInitInterface
//	UINT8							*InquiryData,
//	UINT32							*InquiryDataSize
//
// Output:
//	EFI_STATUS
//
// Modified:
//
// Referrals: InitIdeBlockIO
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS AtapiInquiryData(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    OUT UINT8           *InquiryData,
    IN OUT UINT16       *InquiryDataSize )
{
    EFI_STATUS   Status;
    UINT8        *PacketBuffer;
    ATAPI_DEVICE *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;


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

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

    ZeroMemory( PacketBuffer, 16 );
    PacketBuffer[0] = ATAPI_INQUIRY;
    PacketBuffer[1] = AtapiDevice->Lun << 5;
    PacketBuffer[4] = (UINT8) *InquiryDataSize;
    Status = GeneralAtapiCommandAndData( IdeBusInterface,
                                                  PacketBuffer,
                                                  InquiryData,
                                                  InquiryDataSize );
    pBS->FreePool( PacketBuffer );
    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	AtapiReadWritePio
//
// Description:	Read/Write data from/to the ATAPI device
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//	VOID                                                    *Buffer,
//	UINTN							ByteCount,
//	UINT64							LBA,
//	UINT8							ReadWriteCommand,
//	BOOLEAN							READWRITE
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals: AtapiBlkRead, AtapiBlkWrite
//
// Notes:
//	1. Prepare ATAPI Command Packet
//	2. Check for errors. If Media_Change, detect the new atapi media if present and return status accordingly.
//	3. Read/write data if the command packet is issues successfully.
//	4. Repeat from step 1 untill all data has been read/written.
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

EFI_STATUS AtapiReadWritePio(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    IN OUT VOID         *Buffer,
    IN UINTN            ByteCount,
    IN UINT64           LBA,
    IN UINT8            ReadWriteCommand,
    IN BOOLEAN          READWRITE )
{
    EFI_STATUS   Status;
    INTN         TotalNumberofBlocks;
    INTN         TransferLength;
    UINT16       BytesRead;
    UINTN        BytesRemainingTobeRead;
    ATAPI_DEVICE *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;
    VOID         *TempBuffer  = Buffer;
    IO_REGS      Regs         = IdeBusInterface->IdeDevice.Regs;

    //
    //Disable Interrupt
    //
    IdeWriteByte( IdeBusInterface->PciIO, Regs.ControlBlock.DeviceControlReg, 2 );

    //
    //Check for CHK bit in status register before proceeding, if set give ATAPI reset
    //
    Status = CheckCHKonEntry( IdeBusInterface );

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

    TotalNumberofBlocks = ByteCount / AtapiDevice->BlockSize;

    for (; TotalNumberofBlocks >  0; TotalNumberofBlocks -= TransferLength ) {
        //
        //Clear the buffer
        //
        ZeroMemory( AtapiDevice->PacketBuffer, AtapiDevice->PacketSize );

        //
        //Calculate # of blocks to be transferred
        //
        if ( TotalNumberofBlocks > 0xffff ) {
            TransferLength = 0xffff;
        } else {
            TransferLength = TotalNumberofBlocks;
        }

        //		If the ATAPI device is old, below "ATAPI-3" standard, use one block
        //		per transfer. Some of the old devices don't update the ByteCount value
        //		before setting the DRQ bit. Instead of adding delay, we will transfer 1 block at a time.
        //		Even If this enabled, do it only for CDROM. LS120 write will be very slow if 1 block at time is written.
        //		if (IdeBusInterface->IdeDevice.IdentifyData.Major_Revision_80 < 3) TransferLength = 1;

        //		Update the buffer
        AtapiDevice->PacketBuffer[0] = ReadWriteCommand;
        AtapiDevice->PacketBuffer[1] = AtapiDevice->Lun << 5;
        AtapiDevice->PacketBuffer[2] = ((UINT32) LBA) >>  24;
        AtapiDevice->PacketBuffer[3] = ((UINT32) LBA) >> 16;
        AtapiDevice->PacketBuffer[4] = ((UINT16) LBA) >> 8;
        AtapiDevice->PacketBuffer[5] = ((UINT8) LBA) & 0xff;

        AtapiDevice->PacketBuffer[7] = (UINT8)( TransferLength >> 8 );            // MSB
        AtapiDevice->PacketBuffer[8] = (UINT8)( TransferLength & 0xff );      // LSB

        BytesRemainingTobeRead = TransferLength * AtapiDevice->BlockSize;
        Status = IssueAtapiPacketCommand( IdeBusInterface,
                                       (UINT16*) AtapiDevice->PacketBuffer,
                                       0,
                                       0xffff );

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

        do
        {
            //
            //Check for errors
            //
            Status = HandleAtapiError( IdeBusInterface );

            if ( Status != EFI_SUCCESS ) {
                //
                //Check if Device is getting ready. If yes, wait till it gets ready
                //    
                if ( AtapiDevice->Atapi_Status == BECOMING_READY ) {
                    Status = TestUnitReady( IdeBusInterface );
                }

                if ( Status == EFI_MEDIA_CHANGED ) {
                    Status = DetectAtapiMedia( IdeBusInterface );

                    // This may happen during initial power-up also. If ReinstallProtocol  needs to be done,
                    // then differentiate between power-up nad other cases.
                    if ( Status == EFI_SUCCESS ) {
                        return EFI_MEDIA_CHANGED;    // Return Media Change
                    }
                }
                return Status;
            }

            //Check if DRQ asserted, else DEVICE error. Since BSY is cleared (HandleAtapiError) when control comes to this
            //place, a small delay is enough.
            Status = WaitforBitSet( IdeBusInterface->PciIO,
                                    Regs.CommandBlock.StatusReg,
                                    DRQ,
                                    DRQ_SET_TIMEOUT );

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

            if ( READWRITE ) {
                Status = WriteAtapiData( IdeBusInterface,
                                         TempBuffer,
                                         &BytesRead );
            }
            else {
                Status = ReadAtapiData( IdeBusInterface, TempBuffer, &BytesRead );
            }

            //
            //Update pointer
            //
            (UINT8*) TempBuffer    += BytesRead;
            BytesRemainingTobeRead -= BytesRead;
        }   while ( BytesRemainingTobeRead );

        LBA += TransferLength;
        //
        //Check for errors
        //
        Status = HandleAtapiError( IdeBusInterface );

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

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	GeneralAtapiCommandAndData
//
// Description:	Issues the ATAPI cammand and reads the data
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//	UINT8                           *PacketBuffer,
//	UINT8                           *Buffer,
//	IN OUT UINT16					*ByteCount
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS GeneralAtapiCommandAndData(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    UINT8               *PacketBuffer,
    UINT8               *Buffer,
    IN OUT UINT16       *ByteCount )
{
    EFI_STATUS Status;
    IO_REGS    Regs = IdeBusInterface->IdeDevice.Regs;

    Status = IssueAtapiPacketCommand( IdeBusInterface,
                                      (UINT16*)PacketBuffer,
                                      0,
                                      *ByteCount );

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

    //    
    //Check for errors
    //    
    Status = HandleAtapiError( IdeBusInterface );

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

    if ( *ByteCount ) {
        //
        //Check if DRQ asserted, else DEVICE error
        //
        Status = WaitforBitSet( IdeBusInterface->PciIO,
                                Regs.CommandBlock.StatusReg,
                                DRQ,
                                DRQ_TIMEOUT );

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

        //
        //Read the data
        //
        Status = ReadAtapiData( IdeBusInterface, Buffer, ByteCount );
        //
        //Check for errors
        //
        Status = HandleAtapiError( IdeBusInterface );
        return Status;
    } else {
        *ByteCount = 0;
        return Status;
    }
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IssueAtapiPacketCommand
//
// Description:	Issues ATAPI Packet command and send the packet.
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//	UINT16							*PacketBuffer,		// Pointer to packet
//	UINT16							ByteCount		    // Byte count Limit
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:	The Packet Command and the packet are sent. Error is not analysed in this
//			Routine. Once the packet is sent successfully, EFI_SUCCESS is returned.
//			It is the callers responsibilty to check the status.
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IssueAtapiPacketCommand(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    IN UINT16           *PacketBuffer,
    IN UINT8            Features,
    IN UINT16           ByteCount )
{
    IDE_DEVICE_INTERFACE *IdeDevice = &(IdeBusInterface->IdeDevice);
    IO_REGS              Regs       = IdeBusInterface->IdeDevice.Regs;
    UINT8                Data8;
    UINT16               Data16;
    EFI_STATUS           Status;
    ATAPI_DEVICE         *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;

    //
    //	Select the drive
    //
    IdeWriteByte( IdeBusInterface->PciIO,
                  Regs.CommandBlock.DeviceReg,
                  IdeDevice->Device << 4 );
    // 
    //	Before Writing to any register check for BSY and DRQ bit. Should be zero
    //
    Status = WaitforBitClear( IdeBusInterface->PciIO,
                              Regs.ControlBlock.AlternateStatusReg,
                              BSY | DRQ,
                              gPlatformIdeProtocol->AtaPiBusyClearTimeout );

    if ( EFI_ERROR( Status )) {
        Status = IssueAtapiReset( IdeBusInterface, TRUE );

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

    //
    //	Write Feature register. No OVL and DMA
    //    
    IdeWriteByte( IdeBusInterface->PciIO,
                  Regs.CommandBlock.FeatureReg,
                  Features );

    //
    //Write Byte Count
    //
    IdeWriteByte( IdeBusInterface->PciIO, Regs.CommandBlock.LBAMidReg,
                  (ByteCount & 0xff));

    IdeWriteByte( IdeBusInterface->PciIO, Regs.CommandBlock.LBAHighReg,
                  (ByteCount >> 8));

    //
    //Write Command Register
    //
    IdeWriteByte( IdeBusInterface->PciIO,
                  Regs.CommandBlock.CommandReg,
                  PACKET_COMMAND );

    //	Wait for 400nsec before reading the status. To accomplish it, read ATL_STATUS and ignore the result.
    //	Assumption is, this call will take atleast 400nsec to complete.
    IdeReadByte( IdeBusInterface->PciIO,
                 Regs.ControlBlock.AlternateStatusReg,
                 &Data8 );
    //
    //	Check for BSY bit to be clear 30msec
    //
    Data16 = 30;
    Status = WaitforBitClear( IdeBusInterface->PciIO,
                              Regs.ControlBlock.AlternateStatusReg,
                              BSY,
                              (UINT32) Data16 );

    if ( EFI_ERROR( Status )) {
        return EFI_DEVICE_ERROR;
    }
    //
    //	Check for DRQ set
    //
    Status = WaitforBitSet( IdeBusInterface->PciIO,
                            Regs.CommandBlock.StatusReg,
                            DRQ,
                            (UINT32) Data16 );

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

    //	Write the Data
    Status = IdeWriteMultipleWord( IdeBusInterface->PciIO,
                                   Regs.CommandBlock.DataReg,
                                   AtapiDevice->PacketSize / 2,
                                   PacketBuffer );

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	IssueAtapiReset
//
// Description:	Issues ATAPI Reset command
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface
//	IN BOOLEAN						TESTUNITREADY
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//	If TESTUNITREADY is TRUE, after ATAPI Reset, TestUnitReady command is issued.
//	Generally after DEVICE RESET command, ATAPI device respond to and command with
//	POWER ON RESET OCCURRED and followed by MEDIA CHANGE.
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS IssueAtapiReset(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    IN BOOLEAN          TESTUNITREADY )

{
    IDE_DEVICE_INTERFACE *IdeDevice = &(IdeBusInterface->IdeDevice);
    IO_REGS              Regs       = IdeBusInterface->IdeDevice.Regs;
    UINT8                Data8;
    EFI_STATUS           Status;

    PROGRESS_CODE( DXE_REMOVABLE_MEDIA_RESET );

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

    //
    //Disable Interrupt
    //    
    IdeWriteByte( IdeBusInterface->PciIO, Regs.ControlBlock.DeviceControlReg, 2 );

    //
    //Issue Device reset Command
    //
    IdeWriteByte( IdeBusInterface->PciIO,
                  Regs.CommandBlock.CommandReg,
                  DEVICE_RESET );

    //
    //Wait for 400nsec before reading the status. To accomplish it, read ATL_STATUS and ignore the result
    //
    IdeReadByte( IdeBusInterface->PciIO,
                 Regs.ControlBlock.AlternateStatusReg,
                 &Data8 );

    //
    //Check for BSY bit to be clear
    //
    Status = WaitforBitClear( IdeBusInterface->PciIO,
                              Regs.CommandBlock.StatusReg,
                              BSY,
                              gPlatformIdeProtocol->AtaPiResetCommandTimeout );

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

   IdeReadByte( IdeBusInterface->PciIO,
                     Regs.CommandBlock.LBAMidReg,
                     &Data8 );

    if ( Data8 == (ATAPI_SIGNATURE & 0xff)) {
        IdeReadByte( IdeBusInterface->PciIO,
                     Regs.CommandBlock.LBAHighReg,
                     &Data8 );

        if ( Data8 == (ATAPI_SIGNATURE >> 8)) {
            if ( TESTUNITREADY ) {
                return TestUnitReady( IdeBusInterface );
            }
        }
    }
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	HandleAtapiError
//
// Description:	Handle Atapi error if any.
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:	If DF and CHK bits are not set, return EFI_SUCCESS. If either
//			one of the bits are set, analyse the error and return appropraite
//			error message.
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS HandleAtapiError(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    IDE_DEVICE_INTERFACE *IdeDevice   = &(IdeBusInterface->IdeDevice);
    IO_REGS              Regs         = IdeBusInterface->IdeDevice.Regs;
    ATAPI_DEVICE         *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;
    UINT8                Data8;
    EFI_STATUS           Status;
    UINT8                *SenseData;
    UINT8                *SensePacket;
    UINT16               BytesRead;

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

    //
    //Read the status register
    //
    IdeReadByte( IdeBusInterface->PciIO,
                 Regs.ControlBlock.AlternateStatusReg,
                 &Data8 );

    //
    //Check if BSY clear else DEVICE error
    //
    Status = WaitforBitClear( IdeBusInterface->PciIO,
                              Regs.CommandBlock.StatusReg,
                              BSY,
                              gPlatformIdeProtocol->AtaPiBusyClearTimeout );

    IdeBusInterface->AtapiSenseDataLength = 0;

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

    //
    //Read the status register
    //
    IdeReadByte( IdeBusInterface->PciIO,
                 Regs.ControlBlock.AlternateStatusReg,
                 &Data8 );

    //
    //Check for DF
    //
    if ( Data8 & DF ) {
        AtapiDevice->Atapi_Status = DEVICE_ERROR;
        return EFI_DEVICE_ERROR;
    }

    //
    //Check for CHK
    //
    if ( Data8 & CHK ) {
        AtapiDevice->Atapi_Status = DEVICE_ERROR;
        Status = pBS->AllocatePool( EfiBootServicesData,
                                    256,
                                   (VOID**)&SenseData
                                   );

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

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

        if ( EFI_ERROR( Status )) {
            pBS->FreePool( SenseData );
            return Status;
        }

        //
        //Update the buffer
        //
        ZeroMemory( SenseData,  256 );
        ZeroMemory( SensePacket, 16 );

        SensePacket[0] = ATAPI_REQUEST_SENSE;
        SensePacket[4] = 0xff;

        Status = IssueAtapiPacketCommand( IdeBusInterface,
                                          (UINT16*) SensePacket,
                                          0,
                                          256 );

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


        //
        //Wait for BSY to get cleared
        //
        Status = WaitforBitClear( IdeBusInterface->PciIO,
                                  Regs.CommandBlock.StatusReg,
                                  BSY,
                                  gPlatformIdeProtocol->AtaPiBusyClearTimeout );

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

        //    
        //read the status register
        //
        IdeReadByte( IdeBusInterface->PciIO,
                     Regs.ControlBlock.AlternateStatusReg,
                     &Data8 );

        Status = EFI_DEVICE_ERROR;

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

        //
        //Check if DRQ asserted, else DEVICE error
        //
        if ( !(Data8 & DRQ)) {
            goto exit_HandleAtapiError_with_Reset;
        }

        //
        //Read the data
        //
        Status = ReadAtapiData( IdeBusInterface, (UINT16*)SenseData, &BytesRead );

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

        //
        // Store the SenseData whcih would be used by ScsiPassThruAtapi PassThru Interface.
        //
        pBS->CopyMem( IdeBusInterface->AtapiSenseData, SenseData, BytesRead);
        IdeBusInterface->AtapiSenseDataLength = (UINT8)BytesRead;

        if (((SenseData[2] & 0xf) == 2) && (SenseData[12] == 0x3a)) {
            Status = EFI_NO_MEDIA;
            AtapiDevice->Atapi_Status = MEDIUM_NOT_PRESENT;
        }

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

        if (((SenseData[2] & 0xf) == 6) && (SenseData[12] == 0x28)) {
            Status = EFI_MEDIA_CHANGED;
            AtapiDevice->Atapi_Status = MEDIA_CHANGED;
        }

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

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

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

exit_HandleAtapiError:
        pBS->FreePool( SenseData );
        pBS->FreePool( SensePacket );
        return Status;

exit_HandleAtapiError_with_Reset:
        IssueAtapiReset( IdeBusInterface, TRUE );
        goto    exit_HandleAtapiError;
    }

    AtapiDevice->Atapi_Status = EFI_SUCCESS;
    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	TestUnitReady
//
// Description:	Issues Start/Stop unit Command
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//
// Output:
//		EFI_STATUS			EFI_SUCCESS               : If Media is accessible
//							EFI_NO_MEDIA
//							EFI_MEDIA_CHANGED
//							EFI_DEVICE_ERROR
//
// Modified:
//
// Referrals:
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS TestUnitReady(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    EFI_STATUS   Status;
    UINT8        *Packet;
    ATAPI_DEVICE *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;
    UINT16       ByteCount    = 0;
    UINT16       LoopCount;


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

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

    ZeroMemory( Packet, 16 );
    Packet[0] = ATAPI_TEST_UNIT_READY;
    Packet[1] = AtapiDevice->Lun << 5;

    for ( LoopCount  = 0; LoopCount < 1000; LoopCount++ )             
    {
        Status = GeneralAtapiCommandAndData( IdeBusInterface,
                                             Packet,
                                             NULL,
                                             &ByteCount );

        if ( Status == EFI_SUCCESS ) {
            break;
        }

        if ( AtapiDevice->Atapi_Status == MEDIUM_NOT_PRESENT ) {
            break;
        }

        if ( AtapiDevice->Atapi_Status == MEDIA_CHANGED ) {
            break;
        }
        pBS->Stall( 10000 ); // 10msec
    }

    pBS->FreePool( Packet );
    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	GetOddType
//
// Description:	Find the ODD device Type and return it
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//
// Output:
//	OUT UINT16						*OddType
//
// Modified:
//
// Referrals:
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS GetOddType(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    IN OUT UINT16       *OddType )
{
    EFI_STATUS   Status;
    UINT8        *PacketBuffer;
    UINT8        *ProfileData;
    UINT16       ProfileDataSize = 16;
    ATAPI_DEVICE *AtapiDevice    = IdeBusInterface->IdeDevice.AtapiDevice;

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

    if ( EFI_ERROR( Status )) {
        return Status;
    }
    Status = pBS->AllocatePool( EfiBootServicesData, 16, (VOID**)&ProfileData );

    if ( EFI_ERROR( Status )) {
        return Status;
    }
    ZeroMemory( ProfileData,  16 );
    ZeroMemory( PacketBuffer, 16 );
    PacketBuffer[0] = ATAPI_GET_CONFIGURATION;
    //
    // Get the Feature Discriptor.
    //
    PacketBuffer[1] = FEATURE_DISCRIPTOR;
    //
    // Get the Profile list
    //
    PacketBuffer[3] = GET_PROFILE_LIST;
    //
    // Responce Data Size
    //
    PacketBuffer[8] = 0x10;

    Status = GeneralAtapiCommandAndData( IdeBusInterface,
                                         PacketBuffer,
                                         ProfileData,
                                         &ProfileDataSize );

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

    pBS->FreePool( PacketBuffer );
    pBS->FreePool( ProfileData );

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	GetOddLoadingType
//
// Description:	Find the ODD Loading Type information and return it
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//
// Output:
//	OUT UINT16						*OddLoadingType
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS GetOddLoadingType(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    IN OUT UINT8        *OddLoadingType )
{
    EFI_STATUS   Status;
    UINT8        *PacketBuffer;
    UINT8        *ProfileData;
    UINT16       ProfileDataSize = 16;
    ATAPI_DEVICE *AtapiDevice    = IdeBusInterface->IdeDevice.AtapiDevice;

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

    if ( EFI_ERROR( Status )) {
        return Status;
    }
    Status = pBS->AllocatePool( EfiBootServicesData, 16, (VOID**)&ProfileData );

    if ( EFI_ERROR( Status )) {
        return Status;
    }
    ZeroMemory( ProfileData,  16 );
    ZeroMemory( PacketBuffer, 16 );
    PacketBuffer[0] = ATAPI_GET_CONFIGURATION;
    //
    // Get the Feature Discriptor.
    //
    PacketBuffer[1] = FEATURE_DISCRIPTOR;
    //
    // Get the Removable Medium feature 
    //
    PacketBuffer[3] = GET_REMOVEABLE_MEDIUM_FEATURE;
    //
    // Responce Data Size
    //
    PacketBuffer[8] = 0x10;

    Status = GeneralAtapiCommandAndData( IdeBusInterface,
                                         PacketBuffer,
                                         ProfileData,
                                         &ProfileDataSize );

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

    pBS->FreePool( PacketBuffer );
    pBS->FreePool( ProfileData );

    return Status;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	CheckCHKonEntry
//
// Description:	Check for CHK bit. If set Issue ATAPI reset.
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS CheckCHKonEntry(
    IN IDE_BUS_PROTOCOL *IdeBusInterface )
{
    ATAPI_DEVICE         *AtapiDevice = IdeBusInterface->IdeDevice.AtapiDevice;
    IO_REGS              Regs         = IdeBusInterface->IdeDevice.Regs;
    IDE_DEVICE_INTERFACE *IdeDevice   = &(IdeBusInterface->IdeDevice);
    UINT8                Data8;

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

    //
    //Disable Interrupt
    //
    IdeWriteByte( IdeBusInterface->PciIO, Regs.ControlBlock.DeviceControlReg, 2 );

    //
    //Read Status
    //
    IdeReadByte( IdeBusInterface->PciIO,
                 Regs.ControlBlock.AlternateStatusReg,
                 &Data8 );

    if ( Data8 & CHK ) {
        return (IssueAtapiReset( IdeBusInterface, TRUE ));
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	ReadAtapiData
//
// Description:	Read data from the data port based on Byte count value
//
// Input:
//	IN IDE_BUS_PROTOCOL				*IdeBusInterface,
//	OUT UINT8							AtapiCommand
//	OUT UINT16							*BytesRead
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS ReadAtapiData(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    OUT void            *Data,
    OUT UINT16          *BytesRead )
{
    IO_REGS    Regs = IdeBusInterface->IdeDevice.Regs;
    UINT8      Data8;
    UINT16     ByteCount = 0;
    EFI_STATUS Status;

    //
    //Get the number of Bytes to read
    //
    IdeReadByte( IdeBusInterface->PciIO, Regs.CommandBlock.LBAHighReg, &Data8 );
    ByteCount = Data8 << 8;
    IdeReadByte( IdeBusInterface->PciIO, Regs.CommandBlock.LBAMidReg,  &Data8 );
    ByteCount |= Data8;

    *BytesRead = ByteCount;
    Status     = IdeReadMultipleWord( IdeBusInterface->PciIO,
                                      Regs.CommandBlock.DataReg,
                                      ByteCount / 2,
                                      Data );

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:	WriteAtapiData
//
// Description:	Write data to the data port based on Byte count value
//
// Input:
//	IN IDE_BUS_PROTOCOL					*IdeBusInterface,
//	OUT UINT8							AtapiCommand
//	OUT UINT16							*BytesRead
//
// Output:
//		EFI_STATUS
//
// Modified:
//
// Referrals:
//
// Notes:
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS WriteAtapiData(
    IN IDE_BUS_PROTOCOL *IdeBusInterface,
    OUT void            *Data,
    OUT UINT16          *BytesRead )
{
    IO_REGS    Regs = IdeBusInterface->IdeDevice.Regs;
    UINT8      Data8;
    UINT16     ByteCount = 0;
    EFI_STATUS Status;

    //
    //Get the number of Bytes to Write
    //
    IdeReadByte( IdeBusInterface->PciIO, Regs.CommandBlock.LBAHighReg, &Data8 );
    ByteCount = Data8 << 8;
    IdeReadByte( IdeBusInterface->PciIO, Regs.CommandBlock.LBAMidReg,  &Data8 );
    ByteCount |= Data8;

    *BytesRead = ByteCount;
    Status     = IdeWriteMultipleWord( IdeBusInterface->PciIO,
                                       Regs.CommandBlock.DataReg,
                                       ByteCount / 2,
                                       Data );

    return Status;
}

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