summaryrefslogtreecommitdiff
path: root/IntelFrameworkModulePkg/Bus/Isa/IsaFloppyPei/FloppyPeim.c
blob: d1b7dcf416a1909c336b6a4bc0e5b3965dc55ac3 (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
/** @file
Floppy Peim to support Recovery function from Floppy device.

Copyright (c) 2006 - 2013, Intel Corporation. All rights reserved.<BR>
  
This program and the accompanying materials
are licensed and made available under the terms and conditions
of the BSD License which accompanies this distribution.  The
full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/


#include "FloppyPeim.h"


PEI_DMA_TABLE      mRegisterTable[] = {
  //
  // DMA2: Clear Byte Ptr, Enable
  //
  {
    R_8237_DMA_CBPR_CH4_7,
    0
  },
  {
    R_8237_DMA_COMMAND_CH4_7,
    0
  },
  //
  // DMA1: Clear Byte Ptr, Enable
  //
  {
    R_8237_DMA_CBPR_CH0_3,
    0
  },
  {
    R_8237_DMA_COMMAND_CH0_3,
    0
  },
  //
  // Configure Channel 4 for Cascade Mode
  // Clear DMA Request and enable DREQ
  //
  {
    R_8237_DMA_CHMODE_CH4_7,
    V_8237_DMA_CHMODE_CASCADE | 0
  },
  {
    R_8237_DMA_STA_CH4_7,
    0
  },
  {
    R_8237_DMA_WRSMSK_CH4_7,
    0
  },
  //
  // Configure DMA1 (Channels 0-3) for Single Mode
  // Clear DMA Request and enable DREQ
  //
  {
    R_8237_DMA_CHMODE_CH0_3,
    V_8237_DMA_CHMODE_SINGLE | 0
  },
  {
    R_8237_DMA_STA_CH0_3,
    0
  },
  {
    R_8237_DMA_WRSMSK_CH0_3,
    0
  },
  {
    R_8237_DMA_CHMODE_CH0_3,
    V_8237_DMA_CHMODE_SINGLE | 1
  },
  {
    R_8237_DMA_STA_CH0_3,
    1
  },
  {
    R_8237_DMA_WRSMSK_CH0_3,
    1
  },
  {
    R_8237_DMA_CHMODE_CH0_3,
    V_8237_DMA_CHMODE_SINGLE | 2
  },
  {
    R_8237_DMA_STA_CH0_3,
    2
  },
  {
    R_8237_DMA_WRSMSK_CH0_3,
    2
  },
  {
    R_8237_DMA_CHMODE_CH0_3,
    V_8237_DMA_CHMODE_SINGLE | 3
  },
  {
    R_8237_DMA_STA_CH0_3,
    3
  },
  {
    R_8237_DMA_WRSMSK_CH0_3,
    3
  },
  //
  // Configure DMA2 (Channels 5-7) for Single Mode
  // Clear DMA Request and enable DREQ
  //
  {
    R_8237_DMA_CHMODE_CH4_7,
    V_8237_DMA_CHMODE_SINGLE | 1
  },
  {
    R_8237_DMA_STA_CH4_7,
    1
  },
  {
    R_8237_DMA_WRSMSK_CH4_7,
    1
  },
  {
    R_8237_DMA_CHMODE_CH4_7,
    V_8237_DMA_CHMODE_SINGLE | 2
  },
  {
    R_8237_DMA_STA_CH4_7,
    2
  },
  {
    R_8237_DMA_WRSMSK_CH4_7,
    2
  },
  {
    R_8237_DMA_CHMODE_CH4_7,
    V_8237_DMA_CHMODE_SINGLE | 3
  },
  {
    R_8237_DMA_STA_CH4_7,
    3
  },
  {
    R_8237_DMA_WRSMSK_CH4_7,
    3
  }
};

//
// Table of diskette parameters of various diskette types 
//
DISKET_PARA_TABLE  DiskPara[9] = {
  {
    0x09,
    0x50,
    0xff,
    0x2,
    0x27,
    0x4,
    0x25,
    0x14,
    0x80
  },
  {
    0x09,
    0x2a,
    0xff,
    0x2,
    0x27,
    0x4,
    0x25,
    0x0f,
    0x40
  },
  {
    0x0f,
    0x54,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0x0
  },
  {
    0x09,
    0x50,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0x80
  },
  {
    0x09,
    0x2a,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0x80
  },
  {
    0x12,
    0x1b,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0x0
  },
  {
    0x09,
    0x2a,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0x80
  },
  {
    0x12,
    0x1b,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0x0
  },
  {
    0x24,
    0x1b,
    0xff,
    0x2,
    0x4f,
    0x4,
    0x25,
    0x0f,
    0xc0
  }
};

//
// Byte per sector corresponding to various device types.
//
UINTN    BytePerSector[6] = { 0, 256, 512, 1024, 2048, 4096 };

FDC_BLK_IO_DEV mBlockIoDevTemplate = {
  FDC_BLK_IO_DEV_SIGNATURE,
  {
    FdcGetNumberOfBlockDevices,
    FdcGetBlockDeviceMediaInfo,
    FdcReadBlocks,
  },
  {
    (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
    &gEfiPeiVirtualBlockIoPpiGuid,
    NULL
  },
  0,
  {{0}}
};

/**
  Wait and check if bits for DIO and RQM of FDC Main Status Register
  indicates FDC is ready for read or write.

  Before writing to FDC or reading from FDC, the Host must examine
  the bit7(RQM) and bit6(DIO) of the Main Status Register.
  That is to say:
   Command bytes can not be written to Data Register unless RQM is 1 and DIO is 0.
   Result bytes can not be read from Data Register unless RQM is 1 and DIO is 1.

  @param  FdcBlkIoDev       Instance of FDC_BLK_IO_DEV.
  @param  DataIn            Indicates data input or output.
                            TRUE means input.
                            FALSE means output.
  @param  TimeoutInMseconds  Timeout value to wait.
  
  @retval EFI_SUCCESS       FDC is ready.
  @retval EFI_NOT_READY     FDC is not ready within the specified time period.

**/
EFI_STATUS
FdcDRQReady (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev,
  IN BOOLEAN          DataIn,
  IN UINTN            TimeoutInMseconds
  )
{
  UINTN   Delay;
  UINT8   StatusRegister;
  UINT8   BitInOut;

  //
  // Check bit6 of Main Status Register.
  //
  BitInOut = 0;
  if (DataIn) {
    BitInOut = BIT6;
  }

  Delay = ((TimeoutInMseconds * STALL_1_MSECOND) / FDC_CHECK_INTERVAL) + 1;
  do {
    StatusRegister = IoRead8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_MSR));
    if ((StatusRegister & MSR_RQM) == MSR_RQM && (StatusRegister & MSR_DIO) == BitInOut) {
      //
      // FDC is ready
      //
      break;
    }

    MicroSecondDelay (FDC_SHORT_DELAY);
  } while (--Delay > 0);

  if (Delay == 0) {
    //
    // FDC is not ready within the specified time period
    //
    return EFI_NOT_READY;
  }

  return EFI_SUCCESS;
}

/**
  Read a byte from FDC data register.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Pointer          Pointer to buffer to hold data read from FDC.

  @retval EFI_SUCCESS      Byte successfully read.
  @retval EFI_DEVICE_ERROR FDC is not ready.

**/
EFI_STATUS
DataInByte (
  IN  FDC_BLK_IO_DEV   *FdcBlkIoDev,
  OUT UINT8            *Pointer
  )
{
  UINT8 Data;

  //
  // Wait for 1ms and detect the FDC is ready to be read
  //
  if (FdcDRQReady (FdcBlkIoDev, TRUE, 1) != EFI_SUCCESS) {
    //
    // FDC is not ready.
    //
    return EFI_DEVICE_ERROR;
  }

  Data = IoRead8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DTR));
  MicroSecondDelay (FDC_SHORT_DELAY);
  *Pointer = Data;

  return EFI_SUCCESS;
}

/**
  Write a byte to FDC data register.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Pointer          Pointer to data to write.

  @retval EFI_SUCCESS      Byte successfully written.
  @retval EFI_DEVICE_ERROR FDC is not ready.

**/
EFI_STATUS
DataOutByte (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev,
  IN UINT8            *Pointer
  )
{
  UINT8 Data;

  //
  // Wait for 1ms and detect the FDC is ready to be written
  //
  if (FdcDRQReady (FdcBlkIoDev, FALSE, 1) != EFI_SUCCESS) {
    //
    // FDC is not ready.
    //
    return EFI_DEVICE_ERROR;
  }

  Data = *Pointer;
  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DTR), Data);
  MicroSecondDelay (FDC_SHORT_DELAY);

  return EFI_SUCCESS;
}

/**
  Get Sts0 and Pcn status from FDC

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV
  @param  Sts0             Value of Sts0
  @param  Pcn              Value of Pcn

  @retval EFI_SUCCESS      Successfully retrieved status value of Sts0 and Pcn.
  @retval EFI_DEVICE_ERROR Fail to send SENSE_INT_STATUS_CMD.
  @retval EFI_DEVICE_ERROR Fail to read Sts0.
  @retval EFI_DEVICE_ERROR Fail to read Pcn.

**/
EFI_STATUS
SenseIntStatus (
  IN  FDC_BLK_IO_DEV   *FdcBlkIoDev,
  OUT UINT8            *Sts0,
  OUT UINT8            *Pcn
  )
{
  UINT8 Command;

  Command = SENSE_INT_STATUS_CMD;

  if (DataOutByte (FdcBlkIoDev, &Command) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  if (DataInByte (FdcBlkIoDev, Sts0) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  if (DataInByte (FdcBlkIoDev, Pcn) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  return EFI_SUCCESS;
}

/**
  Issue Specify command.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.

  @retval EFI_SUCCESS      Specify command successfully issued.
  @retval EFI_DEVICE_ERROR FDC device has errors.

**/
EFI_STATUS
Specify (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev
  )
{
  FDC_SPECIFY_CMD Command;
  UINTN           Index;
  UINT8           *Pointer;

  ZeroMem (&Command, sizeof (FDC_SPECIFY_CMD));
  Command.CommandCode = SPECIFY_CMD;
  //
  // set SRT, HUT
  //
  Command.SrtHut = 0xdf;
  //
  // 0xdf;
  // set HLT and DMA
  //
  Command.HltNd = 0x02;

  Pointer            = (UINT8 *) (&Command);
  for (Index = 0; Index < sizeof (FDC_SPECIFY_CMD); Index++) {
    if (DataOutByte (FdcBlkIoDev, Pointer++) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }
  }

  return EFI_SUCCESS;
}

/**
  Wait until busy bit is cleared.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  DevPos           Position of FDC (Driver A or B)
  @param  TimeoutInMseconds Timeout value to wait.

  @retval EFI_SUCCESS      Busy bit has been cleared before timeout.
  @retval EFI_TIMEOUT      Time goes out before busy bit is cleared.

**/
EFI_STATUS
FdcWaitForBSYClear (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev,
  IN UINT8            DevPos,
  IN UINTN            TimeoutInMseconds
  )
{
  UINTN   Delay;
  UINT8   StatusRegister;
  UINT8   Mask;

  //
  // How to determine drive and command are busy or not: by the bits of Main Status Register
  // bit0: Drive 0 busy (drive A)
  // bit1: Drive 1 busy (drive B)
  // bit4: Command busy
  //
  // set mask: for drive A set bit0 & bit4; for drive B set bit1 & bit4
  //
  Mask  = (UINT8) ((DevPos == 0 ? MSR_DAB : MSR_DBB) | MSR_CB);

  Delay = ((TimeoutInMseconds * STALL_1_MSECOND) / FDC_CHECK_INTERVAL) + 1;

  do {
    StatusRegister = IoRead8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_MSR));

    if ((StatusRegister & Mask) == 0x00) {
      //
      // not busy
      //
      break;
    }

    MicroSecondDelay (FDC_SHORT_DELAY);
  } while (--Delay > 0);

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

  return EFI_SUCCESS;
}

/**
  Reset FDC device.

  @param  FdcBlkIoDev  Instance of FDC_BLK_IO_DEV
  @param  DevPos       Index of FDC device.

  @retval EFI_SUCCESS      FDC device successfully reset.
  @retval EFI_DEVICE_ERROR Fail to reset FDC device.

**/
EFI_STATUS
FdcReset (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev,
  IN UINT8            DevPos
  )
{
  UINT8 Data;
  UINT8 Sts0;
  UINT8 Pcn;
  UINTN Index;

  //
  // Reset specified Floppy Logic Drive according to Fdd -> Disk
  // Set Digital Output Register(DOR) to do reset work
  //    bit0 & bit1 of DOR : Drive Select
  //    bit2 : Reset bit
  //    bit3 : DMA and Int bit
  // Reset : A "0" written to bit2 resets the FDC, this reset will remain active until
  //       a "1" is written to this bit.
  // Reset step 1:
  //    use bit0 & bit1 to  select the logic drive
  //    write "0" to bit2
  //
  Data = 0x0;
  Data = (UINT8) (Data | (SELECT_DRV & DevPos));
  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DOR), Data);

  //
  // Wait some time, at least 120us.
  //
  MicroSecondDelay (FDC_RESET_DELAY);
  //
  // Reset step 2:
  //    write "1" to bit2
  //    write "1" to bit3 : enable DMA
  //
  Data |= 0x0C;
  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DOR), Data);

  MicroSecondDelay (FDC_RESET_DELAY);

  //
  // Wait until specified floppy logic drive is not busy
  //
  if (FdcWaitForBSYClear (FdcBlkIoDev, DevPos, 1) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }
  //
  // Set the Transfer Data Rate
  //
  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_CCR), 0x0);

  MicroSecondDelay (FDC_MEDIUM_DELAY);

  //
  // Issue Sense interrupt command for each drive (totally 4 drives)
  //
  for (Index = 0; Index < 4; Index++) {
    if (SenseIntStatus (FdcBlkIoDev, &Sts0, &Pcn) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }
  }
  //
  // Issue Specify command
  //
  if (Specify (FdcBlkIoDev) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  return EFI_SUCCESS;
}

/**
  Turn on the motor of floppy drive.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Info             Information of floppy device.

  @retval EFI_SUCCESS      Motor is successfully turned on.
  @retval EFI_SUCCESS      Motor is already on.
  @retval EFI_DEVICE_ERROR Busy bit of FDC cannot be cleared.

**/
EFI_STATUS
MotorOn (
  IN FDC_BLK_IO_DEV             *FdcBlkIoDev,
  IN OUT PEI_FLOPPY_DEVICE_INFO *Info
  )
{
  UINT8 Data;
  UINT8 DevPos;

  //
  // Control of the floppy drive motors is a big pain. If motor is off, you have to turn it
  // on first. But you can not leave the motor on all the time, since that would wear out the
  // disk. On the other hand, if you turn the motor off after each operation, the system performance
  // will be awful. The compromise used in this driver is to leave the motor on for 2 seconds after
  // each operation. If a new operation is started in that interval(2s), the motor need not be
  // turned on again. If no new operation is started, a timer goes off and the motor is turned off.
  //
  DevPos = Info->DevPos;

  //
  // If the Motor is already on, just return EFI_SUCCESS.
  //
  if (Info->MotorOn) {
    return EFI_SUCCESS;
  }
  //
  // The drive's motor is off, so need turn it on.
  // First check if command and drive are busy or not.
  //
  if (FdcWaitForBSYClear (FdcBlkIoDev, DevPos, 1) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }
  //
  // for drive A: 1CH, drive B: 2DH
  //
  Data = 0x0C;
  Data = (UINT8) (Data | (SELECT_DRV & DevPos));
  if (DevPos == 0) {
    Data |= DRVA_MOTOR_ON;
  } else {
    Data |= DRVB_MOTOR_ON;
  }

  Info->MotorOn = FALSE;

  //
  // Turn on the motor and wait for some time to ensure it takes effect.
  //
  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DOR), Data);
  MicroSecondDelay (FDC_LONG_DELAY);

  Info->MotorOn = TRUE;

  return EFI_SUCCESS;
}

/**
  Turn off the motor of floppy drive.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Info             Information of floppy device.

**/
VOID
MotorOff (
  IN FDC_BLK_IO_DEV             *FdcBlkIoDev,
  IN OUT PEI_FLOPPY_DEVICE_INFO *Info
  )
{
  UINT8 Data;
  UINT8 DevPos;

  DevPos = Info->DevPos;

  if (!Info->MotorOn) {
    return;
  }
  //
  // The motor is on, so need motor off
  //
  Data = 0x0C;
  Data = (UINT8) (Data | (SELECT_DRV & DevPos));

  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DOR), Data);
  MicroSecondDelay (FDC_SHORT_DELAY);

  Info->MotorOn = FALSE;
}

/**
  Recalibrate the FDC device.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Info             Information of floppy device.

  @retval EFI_SUCCESS      FDC successfully recalibrated.
  @retval EFI_DEVICE_ERROR Fail to send RECALIBRATE_CMD.
  @retval EFI_DEVICE_ERROR Fail to get status value of Sts0 and Pcn.
  @retval EFI_DEVICE_ERROR Fail to recalibrate FDC device.

**/
EFI_STATUS
Recalibrate (
  IN FDC_BLK_IO_DEV             *FdcBlkIoDev,
  IN OUT PEI_FLOPPY_DEVICE_INFO *Info
  )
{
  FDC_COMMAND_PACKET2 Command;
  UINTN               Index;
  UINT8               Sts0;
  UINT8               Pcn;
  UINT8               *Pointer;
  UINT8               Count;
  UINT8               DevPos;

  DevPos  = Info->DevPos;

  //
  // We would try twice.
  //
  Count   = 2;
  while (Count > 0) {
    ZeroMem (&Command, sizeof (FDC_COMMAND_PACKET2));
    Command.CommandCode = RECALIBRATE_CMD;
    //
    // drive select
    //
    if (DevPos == 0) {
      Command.DiskHeadSel = 0;
    } else {
      Command.DiskHeadSel = 1;
    }

    Pointer = (UINT8 *) (&Command);
    for (Index = 0; Index < sizeof (FDC_COMMAND_PACKET2); Index++) {
      if (DataOutByte (FdcBlkIoDev, Pointer++) != EFI_SUCCESS) {
        return EFI_DEVICE_ERROR;
      }
    }

    MicroSecondDelay (FDC_RECALIBRATE_DELAY);

    if (SenseIntStatus (FdcBlkIoDev, &Sts0, &Pcn) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }

    if ((Sts0 & 0xf0) == BIT5 && Pcn == 0) {
      //
      // Recalibration is successful. 
      //
      Info->Pcn = 0;
      Info->NeedRecalibrate = FALSE;

      return EFI_SUCCESS;
    } else {
      //
      // Recalibration is not successful. Try again.
      // If trial is used out, return EFI_DEVICE_ERROR.
      //
      Count--;
      if (Count == 0) {
        return EFI_DEVICE_ERROR;
      }
    }
  }

  return EFI_SUCCESS;
}

/**
  Seek for the cylinder according to given LBA.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Info             Information of floppy device.
  @param  Lba              LBA for which to seek for cylinder.

  @retval EFI_SUCCESS      Successfully moved to the destination cylinder.
  @retval EFI_SUCCESS      Destination cylinder is just the present cylinder.
  @retval EFI_DEVICE_ERROR Fail to move to the destination cylinder.

**/
EFI_STATUS
Seek (
  IN     FDC_BLK_IO_DEV         *FdcBlkIoDev,
  IN OUT PEI_FLOPPY_DEVICE_INFO *Info,
  IN     EFI_PEI_LBA            Lba
  )
{
  FDC_SEEK_CMD      Command;
  DISKET_PARA_TABLE *Para;
  UINT8             EndOfTrack;
  UINT8             Head;
  UINT8             Cylinder;
  UINT8             Sts0;
  UINT8             *Pointer;
  UINT8             Pcn;
  UINTN             Index;
  UINT8             Gap;
  UINT8             DevPos;

  DevPos = Info->DevPos;
  if (Info->NeedRecalibrate) {
    if (Recalibrate (FdcBlkIoDev, Info) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }
    //
    // Recalibrate Success
    //
    Info->NeedRecalibrate = FALSE;
  }

  //
  // Get the base of disk parameter information corresponding to its type.
  //
  Para        = (DISKET_PARA_TABLE *) ((UINT8 *) DiskPara + sizeof (DISKET_PARA_TABLE) * Info->Type);
  EndOfTrack  = Para->EndOfTrack;
  //
  // Calculate cylinder based on Lba and EOT
  //
  Cylinder = (UINT8) ((UINTN) Lba / EndOfTrack / 2);

  //
  // If the dest cylinder is the present cylinder, unnecessary to do the seek operation
  //
  if (Info->Pcn == Cylinder) {
    return EFI_SUCCESS;
  }

  //
  // Calculate the head : 0 or 1
  //
  Head = (UINT8) ((UINTN) Lba / EndOfTrack % 2);

  ZeroMem (&Command, sizeof (FDC_SEEK_CMD));
  Command.CommandCode = SEEK_CMD;
  if (DevPos == 0) {
    Command.DiskHeadSel = 0;
  } else {
    Command.DiskHeadSel = 1;
  }

  //
  // Send command to move to destination cylinder.
  //
  Command.DiskHeadSel = (UINT8) (Command.DiskHeadSel | (Head << 2));
  Command.NewCylinder = Cylinder;

  Pointer = (UINT8 *) (&Command);
  for (Index = 0; Index < sizeof (FDC_SEEK_CMD); Index++) {
    if (DataOutByte (FdcBlkIoDev, Pointer++) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }
  }

  MicroSecondDelay (FDC_SHORT_DELAY);

  //
  // Calculate waiting time, which is proportional to the gap between destination
  // cylinder and present cylinder.
  //
  if (Info->Pcn > Cylinder) {
    Gap = (UINT8) (Info->Pcn - Cylinder);
  } else {
    Gap = (UINT8) (Cylinder - Info->Pcn);
  }

  MicroSecondDelay ((Gap + 1) * FDC_LONG_DELAY);

  //
  // Confirm if the new cylinder is the destination and status is correct.
  //
  if (SenseIntStatus (FdcBlkIoDev, &Sts0, &Pcn) != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  if ((Sts0 & 0xf0) == BIT5) {
    Info->Pcn             = Command.NewCylinder;
    Info->NeedRecalibrate = FALSE;
    return EFI_SUCCESS;
  } else {
    Info->NeedRecalibrate = TRUE;
    return EFI_DEVICE_ERROR;
  }
}

/**
  Check if diskette is changed.

  @param  FdcBlkIoDev       Instance of FDC_BLK_IO_DEV
  @param  Info              Information of floppy device.

  @retval EFI_SUCCESS       Diskette is not changed.
  @retval EFI_MEDIA_CHANGED Diskette is changed.
  @retval EFI_NO_MEDIA      No diskette.
  @retval EFI_DEVICE_ERROR  Fail to do the seek or recalibrate operation.

**/
EFI_STATUS
DisketChanged (
  IN FDC_BLK_IO_DEV             *FdcBlkIoDev,
  IN OUT PEI_FLOPPY_DEVICE_INFO *Info
  )
{
  EFI_STATUS  Status;
  UINT8       Data;

  //
  // Check change line
  //
  Data = IoRead8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DIR));

  MicroSecondDelay (FDC_SHORT_DELAY);

  if ((Data & DIR_DCL) == DIR_DCL) {
    if (Info->Pcn != 0) {
      Status = Recalibrate (FdcBlkIoDev, Info);
    } else {
      Status = Seek (FdcBlkIoDev, Info, 0x30);
    }

    if (Status != EFI_SUCCESS) {
      //
      // Fail to do the seek or recalibrate operation
      //
      return EFI_DEVICE_ERROR;
    }

    Data = IoRead8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_DIR));

    MicroSecondDelay (FDC_SHORT_DELAY);

    if ((Data & DIR_DCL) == DIR_DCL) {
      return EFI_NO_MEDIA;
    }

    return EFI_MEDIA_CHANGED;
  }

  return EFI_SUCCESS;
}

/**
  Detects if FDC device exists.

  @param  FdcBlkIoDev  Instance of FDC_BLK_IO_DEV
  @param  Info         Information of floppy device.
  @param  MediaInfo    Information of floppy media.

  @retval TRUE         FDC device exists and is working properly.
  @retval FALSE        FDC device does not exist or cannot work properly.

**/
BOOLEAN
DiscoverFdcDevice (
  IN  FDC_BLK_IO_DEV             *FdcBlkIoDev,
  IN  OUT PEI_FLOPPY_DEVICE_INFO *Info,
  OUT EFI_PEI_BLOCK_IO_MEDIA     *MediaInfo
  )
{
  EFI_STATUS        Status;
  DISKET_PARA_TABLE *Para;

  Status = MotorOn (FdcBlkIoDev, Info);
  if (Status != EFI_SUCCESS) {
    return FALSE;
  }

  Status = Recalibrate (FdcBlkIoDev, Info);

  if (Status != EFI_SUCCESS) {
    MotorOff (FdcBlkIoDev, Info);
    return FALSE;
  }
  //
  // Set Media Parameter
  //
  MediaInfo->DeviceType   = LegacyFloppy;
  MediaInfo->MediaPresent = TRUE;

  //
  // Check Media
  //
  Status = DisketChanged (FdcBlkIoDev, Info);
  if (Status == EFI_NO_MEDIA) {
    //
    // No diskette in floppy.
    //
    MediaInfo->MediaPresent = FALSE;    
  } else if (Status != EFI_MEDIA_CHANGED && Status != EFI_SUCCESS) {
    //
    // EFI_DEVICE_ERROR
    //
    MotorOff (FdcBlkIoDev, Info);
    return FALSE;
  }

  MotorOff (FdcBlkIoDev, Info);

  //
  // Get the base of disk parameter information corresponding to its type.
  //
  Para                  = (DISKET_PARA_TABLE *) ((UINT8 *) DiskPara + sizeof (DISKET_PARA_TABLE) * Info->Type);

  MediaInfo->BlockSize  = BytePerSector[Para->Number];
  MediaInfo->LastBlock  = Para->EndOfTrack * 2 * (Para->MaxTrackNum + 1) - 1;

  return TRUE;
}

/**
  Enumerate floppy device

  @param  FdcBlkIoDev  Instance of floppy device controller

  @return Number of FDC devices.

**/
UINT8
FdcEnumeration (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev
  )
{
  UINT8                   DevPos;
  UINT8                   DevNo;
  EFI_PEI_BLOCK_IO_MEDIA  MediaInfo;
  EFI_STATUS              Status;

  DevNo = 0;

  //
  // DevPos=0 means Drive A, 1 means Drive B.
  //
  for (DevPos = 0; DevPos < 2; DevPos++) {
    //
    // Detecting device presence
    //
    REPORT_STATUS_CODE (EFI_PROGRESS_CODE, EFI_PERIPHERAL_REMOVABLE_MEDIA + EFI_P_PC_PRESENCE_DETECT);

    //
    // Reset FDC
    //
    Status = FdcReset (FdcBlkIoDev, DevPos);

    if (EFI_ERROR (Status)) {
      continue;
    }

    FdcBlkIoDev->DeviceInfo[DevPos].DevPos          = DevPos;
    FdcBlkIoDev->DeviceInfo[DevPos].Pcn             = 0;
    FdcBlkIoDev->DeviceInfo[DevPos].MotorOn         = FALSE;
    FdcBlkIoDev->DeviceInfo[DevPos].NeedRecalibrate = TRUE;
    FdcBlkIoDev->DeviceInfo[DevPos].Type            = FdcType1440K1440K;

    //
    // Discover FDC device
    //
    if (DiscoverFdcDevice (FdcBlkIoDev, &(FdcBlkIoDev->DeviceInfo[DevPos]), &MediaInfo)) {
      FdcBlkIoDev->DeviceInfo[DevNo].DevPos           = DevPos;

      FdcBlkIoDev->DeviceInfo[DevNo].Pcn              = FdcBlkIoDev->DeviceInfo[DevPos].Pcn;
      FdcBlkIoDev->DeviceInfo[DevNo].MotorOn          = FdcBlkIoDev->DeviceInfo[DevPos].MotorOn;
      FdcBlkIoDev->DeviceInfo[DevNo].NeedRecalibrate  = FdcBlkIoDev->DeviceInfo[DevPos].NeedRecalibrate;
      FdcBlkIoDev->DeviceInfo[DevNo].Type             = FdcBlkIoDev->DeviceInfo[DevPos].Type;

      CopyMem (
        &(FdcBlkIoDev->DeviceInfo[DevNo].MediaInfo),
        &MediaInfo,
        sizeof (EFI_PEI_BLOCK_IO_MEDIA)
        );

      DevNo++;
    } else {
      //
      // Assume controller error
      //
      REPORT_STATUS_CODE (
        EFI_ERROR_CODE | EFI_ERROR_MINOR,
        EFI_PERIPHERAL_REMOVABLE_MEDIA + EFI_P_EC_CONTROLLER_ERROR
        );
    }
  }

  FdcBlkIoDev->DeviceCount = DevNo;
  return DevNo;
}

/**
  Checks result reflected by FDC_RESULT_PACKET.

  @param  Result           FDC_RESULT_PACKET read from FDC after certain operation.
  @param  Info             Information of floppy device.

  @retval EFI_SUCCESS      Result is healthy.
  @retval EFI_DEVICE_ERROR Result is not healthy.

**/
EFI_STATUS
CheckResult (
  IN  FDC_RESULT_PACKET         *Result,
  OUT PEI_FLOPPY_DEVICE_INFO    *Info
  )
{
  if ((Result->Status0 & STS0_IC) != IC_NT) {
    if ((Result->Status0 & STS0_SE) == BIT5) {
      //
      // Seek error
      //
      Info->NeedRecalibrate = TRUE;
    }

    Info->NeedRecalibrate = TRUE;
    return EFI_DEVICE_ERROR;
  }
  //
  // Check Status Register1
  //
  if ((Result->Status1 & (STS1_EN | STS1_DE | STS1_OR | STS1_ND | STS1_NW | STS1_MA)) != 0) {
    Info->NeedRecalibrate = TRUE;
    return EFI_DEVICE_ERROR;
  }
  //
  // Check Status Register2
  //
  if ((Result->Status2 & (STS2_CM | STS2_DD | STS2_WC | STS2_BC | STS2_MD)) != 0) {
    Info->NeedRecalibrate = TRUE;
    return EFI_DEVICE_ERROR;
  }

  return EFI_SUCCESS;
}

/**
  Fill parameters for command packet.

  @param  Info    Information of floppy device.
  @param  Lba     Logical block address.
  @param  Command Command for which for fill parameters.

**/
VOID
FillPara (
  IN  PEI_FLOPPY_DEVICE_INFO *Info,
  IN  EFI_PEI_LBA            Lba,
  OUT FDC_COMMAND_PACKET1    *Command
  )
{
  DISKET_PARA_TABLE *Para;
  UINT8             EndOfTrack;
  UINT8             DevPos;

  DevPos      = Info->DevPos;

  //
  // Get the base of disk parameter information corresponding to its type.
  //
  Para        = (DISKET_PARA_TABLE *) ((UINT8 *) DiskPara + sizeof (DISKET_PARA_TABLE) * Info->Type);

  EndOfTrack  = Para->EndOfTrack;

  if (DevPos == 0) {
    Command->DiskHeadSel = 0;
  } else {
    Command->DiskHeadSel = 1;
  }

  Command->Cylinder    = (UINT8) ((UINTN) Lba / EndOfTrack / 2);
  Command->Head        = (UINT8) ((UINTN) Lba / EndOfTrack % 2);
  Command->Sector      = (UINT8) ((UINT8) ((UINTN) Lba % EndOfTrack) + 1);
  Command->DiskHeadSel = (UINT8) (Command->DiskHeadSel | (Command->Head << 2));
  Command->Number      = Para->Number;
  Command->EndOfTrack  = Para->EndOfTrack;
  Command->GapLength   = Para->GapLength;
  Command->DataLength  = Para->DataLength;
}

/**
  Setup specifed FDC device.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  DevPos           Index of FDC device.

  @retval EFI_SUCCESS      FDC device successfully set up.
  @retval EFI_DEVICE_ERROR FDC device has errors.

**/
EFI_STATUS
Setup (
  IN  FDC_BLK_IO_DEV  *FdcBlkIoDev,
  IN  UINT8           DevPos
  )
{
  EFI_STATUS  Status;

  IoWrite8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_CCR), 0x0);

  MicroSecondDelay (FDC_MEDIUM_DELAY);

  Status = Specify (FdcBlkIoDev);
  return Status;
}

/**
  Setup DMA channels to read data.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Buffer           Memory buffer for DMA transfer.
  @param  BlockSize        the number of the bytes in one block.
  @param  NumberOfBlocks   Number of blocks to read.

**/
VOID
SetDMA (
  IN FDC_BLK_IO_DEV   *FdcBlkIoDev,
  IN VOID             *Buffer,
  IN UINTN            BlockSize,
  IN UINTN            NumberOfBlocks
  )
{
  UINT8 Data;
  UINTN Count;

  //
  // Mask DMA channel 2;
  //
  IoWrite8 (R_8237_DMA_WRSMSK_CH0_3, B_8237_DMA_WRSMSK_CMS | 2);

  //
  // Clear first/last flip flop
  //
  IoWrite8 (R_8237_DMA_CBPR_CH0_3, B_8237_DMA_WRSMSK_CMS | 2);

  //
  // Set mode
  //
  IoWrite8 (R_8237_DMA_CHMODE_CH0_3, V_8237_DMA_CHMODE_SINGLE | V_8237_DMA_CHMODE_IO2MEM | 2);

  //
  // Set base address and page register
  //
  Data = (UINT8) (UINTN) Buffer;
  IoWrite8 (R_8237_DMA_BASE_CA_CH2, Data);
  Data = (UINT8) ((UINTN) Buffer >> 8);
  IoWrite8 (R_8237_DMA_BASE_CA_CH2, Data);

  Data = (UINT8) ((UINTN) Buffer >> 16);
  IoWrite8 (R_8237_DMA_MEM_LP_CH2, Data);

  //
  // Set count register
  //
  Count = BlockSize * NumberOfBlocks - 1;
  Data  = (UINT8) (Count & 0xff);
  IoWrite8 (R_8237_DMA_BASE_CC_CH2, Data);
  Data = (UINT8) (Count >> 8);
  IoWrite8 (R_8237_DMA_BASE_CC_CH2, Data);

  //
  // Clear channel 2 mask
  //
  IoWrite8 (R_8237_DMA_WRSMSK_CH0_3, 0x02);
}


/**
  According to the block range specified by Lba and NumberOfBlocks, calculate
  the number of blocks in the same sector, which can be transferred in a batch.

  @param  Info           Information of floppy device.
  @param  Lba            Start address of block range.
  @param  NumberOfBlocks Number of blocks of the range.

  @return Number of blocks in the same sector.

**/
UINTN
GetTransferBlockCount (
  IN  PEI_FLOPPY_DEVICE_INFO *Info,
  IN  EFI_PEI_LBA            Lba,
  IN  UINTN                  NumberOfBlocks
  )
{
  DISKET_PARA_TABLE *Para;
  UINT8             EndOfTrack;
  UINT8             Head;
  UINT8             SectorsInTrack;

  //
  // Get the base of disk parameter information corresponding to its type.
  //
  Para            = (DISKET_PARA_TABLE *) ((UINT8 *) DiskPara + sizeof (DISKET_PARA_TABLE) * Info->Type);

  EndOfTrack      = Para->EndOfTrack;
  Head            = (UINT8) ((UINTN) Lba / EndOfTrack % 2);

  SectorsInTrack  = (UINT8) (EndOfTrack * (2 - Head) - (UINT8) ((UINTN) Lba % EndOfTrack));
  if (SectorsInTrack < NumberOfBlocks) {
    //
    // Not all the block range locates in the same sector
    //
    return SectorsInTrack;
  } else {
    //
    // All the block range is in the same sector.
    //
    return NumberOfBlocks;
  }
}

/**
  Read data sector from FDC device.

  @param  FdcBlkIoDev      Instance of FDC_BLK_IO_DEV.
  @param  Info             Information of floppy device.
  @param  Buffer           Buffer to setup for DMA.
  @param  Lba              The start address to read.
  @param  NumberOfBlocks   Number of blocks to read.

  @retval EFI_SUCCESS      Data successfully read out.
  @retval EFI_DEVICE_ERROR FDC device has errors.
  @retval EFI_TIMEOUT      Command does not take effect in time.

**/
EFI_STATUS
ReadDataSector (
  IN     FDC_BLK_IO_DEV         *FdcBlkIoDev,
  IN OUT PEI_FLOPPY_DEVICE_INFO *Info,
  IN     VOID                   *Buffer,
  IN     EFI_PEI_LBA            Lba,
  IN     UINTN                  NumberOfBlocks
  )
{
  EFI_STATUS          Status;
  FDC_COMMAND_PACKET1 Command;
  FDC_RESULT_PACKET   Result;
  UINTN               Index;
  UINTN               Times;
  UINT8               *Pointer;

  Status = Seek (FdcBlkIoDev, Info, Lba);
  if (Status != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  //
  // Set up DMA
  //
  SetDMA (FdcBlkIoDev, Buffer, Info->MediaInfo.BlockSize, NumberOfBlocks);

  //
  // Allocate Read command packet
  //
  ZeroMem (&Command, sizeof (FDC_COMMAND_PACKET1));
  Command.CommandCode = READ_DATA_CMD | CMD_MT | CMD_MFM | CMD_SK;

  //
  // Fill parameters for command.
  //
  FillPara (Info, Lba, &Command);

  //
  // Write command bytes to FDC
  //
  Pointer = (UINT8 *) (&Command);
  for (Index = 0; Index < sizeof (FDC_COMMAND_PACKET1); Index++) {
    if (DataOutByte (FdcBlkIoDev, Pointer++) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }
  }

  //
  // Wait for some time until command takes effect.
  //
  Times = (STALL_1_SECOND / FDC_CHECK_INTERVAL) + 1;
  do {
    if ((IoRead8 ((UINT16) (PcdGet16 (PcdFdcBaseAddress) + FDC_REGISTER_MSR)) & 0xc0) == 0xc0) {
      break;
    }

    MicroSecondDelay (FDC_SHORT_DELAY);
  } while (--Times > 0);

  if (Times == 0) {
    //
    // Command fails to take effect in time, return EFI_TIMEOUT.
    //
    return EFI_TIMEOUT;
  }

  //
  // Read result bytes from FDC
  //
  Pointer = (UINT8 *) (&Result);
  for (Index = 0; Index < sizeof (FDC_RESULT_PACKET); Index++) {
    if (DataInByte (FdcBlkIoDev, Pointer++) != EFI_SUCCESS) {
      return EFI_DEVICE_ERROR;
    }
  }

  return CheckResult (&Result, Info);
}

/**
  Gets the count of block I/O devices that one specific block driver detects.

  This function is used for getting the count of block I/O devices that one 
  specific block driver detects.  To the PEI ATAPI driver, it returns the number
  of all the detected ATAPI devices it detects during the enumeration process. 
  To the PEI legacy floppy driver, it returns the number of all the legacy 
  devices it finds during its enumeration process. If no device is detected, 
  then the function will return zero.  
  
  @param[in]  PeiServices          General-purpose services that are available 
                                   to every PEIM.
  @param[in]  This                 Indicates the EFI_PEI_RECOVERY_BLOCK_IO_PPI 
                                   instance.
  @param[out] NumberBlockDevices   The number of block I/O devices discovered.

  @retval     EFI_SUCCESS          Operation performed successfully.

**/
EFI_STATUS
EFIAPI
FdcGetNumberOfBlockDevices (
  IN   EFI_PEI_SERVICES                  **PeiServices,
  IN   EFI_PEI_RECOVERY_BLOCK_IO_PPI     *This,
  OUT  UINTN                             *NumberBlockDevices
  )
{
  FDC_BLK_IO_DEV  *FdcBlkIoDev;

  FdcBlkIoDev = NULL;

  FdcBlkIoDev         = PEI_RECOVERY_FDC_FROM_BLKIO_THIS (This);

  *NumberBlockDevices = FdcBlkIoDev->DeviceCount;

  return EFI_SUCCESS;
}

/**
  Gets a block device's media information.

  This function will provide the caller with the specified block device's media 
  information. If the media changes, calling this function will update the media 
  information accordingly.

  @param[in]  PeiServices   General-purpose services that are available to every
                            PEIM
  @param[in]  This          Indicates the EFI_PEI_RECOVERY_BLOCK_IO_PPI instance.
  @param[in]  DeviceIndex   Specifies the block device to which the function wants 
                            to talk. Because the driver that implements Block I/O 
                            PPIs will manage multiple block devices, the PPIs that 
                            want to talk to a single device must specify the 
                            device index that was assigned during the enumeration
                            process. This index is a number from one to 
                            NumberBlockDevices.
  @param[out] MediaInfo     The media information of the specified block media.  
                            The caller is responsible for the ownership of this 
                            data structure.
  
  @retval EFI_SUCCESS        Media information about the specified block device 
                             was obtained successfully.
  @retval EFI_DEVICE_ERROR   Cannot get the media information due to a hardware 
                             error.
  @retval Others             Other failure occurs.

**/
EFI_STATUS
EFIAPI
FdcGetBlockDeviceMediaInfo (
  IN   EFI_PEI_SERVICES                     **PeiServices,
  IN   EFI_PEI_RECOVERY_BLOCK_IO_PPI        *This,
  IN   UINTN                                DeviceIndex,
  OUT  EFI_PEI_BLOCK_IO_MEDIA               *MediaInfo
  )
{
  UINTN           DeviceCount;
  FDC_BLK_IO_DEV  *FdcBlkIoDev;
  BOOLEAN         Healthy;
  UINTN           Index;

  FdcBlkIoDev = NULL;

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

  FdcBlkIoDev = PEI_RECOVERY_FDC_FROM_BLKIO_THIS (This);

  DeviceCount = FdcBlkIoDev->DeviceCount;

  //
  // DeviceIndex is a value from 1 to NumberBlockDevices.
  //
  if ((DeviceIndex < 1) || (DeviceIndex > DeviceCount) || (DeviceIndex > 2)) {
    return EFI_INVALID_PARAMETER;
  }

  Index = DeviceIndex - 1;
  //
  // Probe media and retrieve latest media information
  //
  Healthy = DiscoverFdcDevice (
              FdcBlkIoDev,
              &FdcBlkIoDev->DeviceInfo[Index],
              MediaInfo
              );

  if (!Healthy) {
    return EFI_DEVICE_ERROR;
  }

  CopyMem (
    &(FdcBlkIoDev->DeviceInfo[Index].MediaInfo),
    MediaInfo,
    sizeof (EFI_PEI_BLOCK_IO_MEDIA)
    );

  return EFI_SUCCESS;
}

/**
  Reads the requested number of blocks from the specified block device.

  The function reads the requested number of blocks from the device. All the 
  blocks are read, or an error is returned. If there is no media in the device,
  the function returns EFI_NO_MEDIA.

  @param[in]  PeiServices   General-purpose services that are available to 
                            every PEIM.
  @param[in]  This          Indicates the EFI_PEI_RECOVERY_BLOCK_IO_PPI instance.
  @param[in]  DeviceIndex   Specifies the block device to which the function wants 
                            to talk. Because the driver that implements Block I/O 
                            PPIs will manage multiple block devices, the PPIs that 
                            want to talk to a single device must specify the device 
                            index that was assigned during the enumeration process. 
                            This index is a number from one to NumberBlockDevices.
  @param[in]  StartLBA      The starting logical block address (LBA) to read from
                            on the device
  @param[in]  BufferSize    The size of the Buffer in bytes. This number must be
                            a multiple of the intrinsic block size of the device.
  @param[out] Buffer        A pointer to the destination buffer for the data.
                            The caller is responsible for the ownership of the 
                            buffer.
                         
  @retval EFI_SUCCESS             The data was read correctly from the device.
  @retval EFI_DEVICE_ERROR        The device reported an error while attempting 
                                  to perform the read operation.
  @retval EFI_INVALID_PARAMETER   The read request contains LBAs that are not 
                                  valid, or the buffer is not properly aligned.
  @retval EFI_NO_MEDIA            There is no media in the device.
  @retval EFI_BAD_BUFFER_SIZE     The BufferSize parameter is not a multiple of
                                  the intrinsic block size of the device.

**/
EFI_STATUS
EFIAPI
FdcReadBlocks (
  IN   EFI_PEI_SERVICES                  **PeiServices,
  IN   EFI_PEI_RECOVERY_BLOCK_IO_PPI     *This,
  IN   UINTN                             DeviceIndex,
  IN   EFI_PEI_LBA                       StartLBA,
  IN   UINTN                             BufferSize,
  OUT  VOID                              *Buffer
  )
{
  EFI_PEI_BLOCK_IO_MEDIA MediaInfo;
  EFI_STATUS            Status;
  UINTN                 Count;
  UINTN                 NumberOfBlocks;
  UINTN                 BlockSize;
  FDC_BLK_IO_DEV        *FdcBlkIoDev;
  VOID                  *MemPage;

  FdcBlkIoDev = NULL;

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

  FdcBlkIoDev = PEI_RECOVERY_FDC_FROM_BLKIO_THIS (This);

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

  Status = FdcGetBlockDeviceMediaInfo (PeiServices, This, DeviceIndex, &MediaInfo);
  if (Status != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

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

  BlockSize = MediaInfo.BlockSize;

  //
  // If BufferSize cannot be divided by block size of FDC device,
  // return EFI_BAD_BUFFER_SIZE.
  //
  if (BufferSize % BlockSize != 0) {
    return EFI_BAD_BUFFER_SIZE;
  }

  NumberOfBlocks = BufferSize / BlockSize;

  if ((StartLBA + NumberOfBlocks - 1) > FdcBlkIoDev->DeviceInfo[DeviceIndex - 1].MediaInfo.LastBlock) {
    return EFI_INVALID_PARAMETER;
  }

  MemPage = AllocatePages (EFI_SIZE_TO_PAGES (BufferSize));
  if ((MemPage == NULL) || ((UINTN) MemPage >= ISA_MAX_MEMORY_ADDRESS)) {
    //
    // If fail to allocate memory under ISA_MAX_MEMORY_ADDRESS, designate the address space for DMA
    //
    MemPage = (VOID *) ((UINTN) (UINT32) 0x0f00000);
  }
  Status = MotorOn (FdcBlkIoDev, &(FdcBlkIoDev->DeviceInfo[DeviceIndex - 1]));
  if (Status != EFI_SUCCESS) {
    return EFI_DEVICE_ERROR;
  }

  Status = Setup (FdcBlkIoDev, FdcBlkIoDev->DeviceInfo[DeviceIndex - 1].DevPos);
  if (Status != EFI_SUCCESS) {
    MotorOff (FdcBlkIoDev, &(FdcBlkIoDev->DeviceInfo[DeviceIndex - 1]));
    return EFI_DEVICE_ERROR;
  }
  //
  // Read data in batches.
  // Blocks in the same cylinder are read out in a batch.
  //
  while ((Count = GetTransferBlockCount (
                    &(FdcBlkIoDev->DeviceInfo[DeviceIndex - 1]),
                    StartLBA,
                    NumberOfBlocks
                    )) != 0 && Status == EFI_SUCCESS) {
    Status = ReadDataSector (
               FdcBlkIoDev,
               &(FdcBlkIoDev->DeviceInfo[DeviceIndex - 1]),
               MemPage,
               StartLBA,
               Count
               );
    CopyMem (Buffer, MemPage, BlockSize * Count);
    StartLBA += Count;
    NumberOfBlocks -= Count;
    Buffer = (VOID *) ((UINTN) Buffer + Count * BlockSize);
  }

  MotorOff (FdcBlkIoDev, &(FdcBlkIoDev->DeviceInfo[DeviceIndex - 1]));

  switch (Status) {
  case EFI_SUCCESS:
    return EFI_SUCCESS;

  default:
    FdcReset (FdcBlkIoDev, FdcBlkIoDev->DeviceInfo[DeviceIndex - 1].DevPos);
    return EFI_DEVICE_ERROR;
  }
}

/**
  Initializes the floppy disk controller and installs FDC Block I/O PPI.

  @param  FileHandle            Handle of the file being invoked.
  @param  PeiServices           Describes the list of possible PEI Services.

  @retval EFI_SUCCESS           Successfully initialized FDC and installed PPI.
  @retval EFI_NOT_FOUND         Cannot find FDC device.
  @retval EFI_OUT_OF_RESOURCES  Have no enough memory to create instance or descriptors.
  @retval Other                 Fail to install FDC Block I/O PPI.

**/
EFI_STATUS
EFIAPI
FdcPeimEntry (
  IN  EFI_PEI_FILE_HANDLE         FileHandle,
  IN  CONST EFI_PEI_SERVICES      **PeiServices
  )
{
  EFI_STATUS            Status;
  FDC_BLK_IO_DEV        *FdcBlkIoDev;
  UINTN                 DeviceCount;
  UINT32                Index;

  Status = PeiServicesRegisterForShadow (FileHandle);
  if (!EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Allocate memory for instance of FDC_BLK_IO_DEV and copy initial value
  // from template to it. 
  //
  FdcBlkIoDev = AllocatePages (EFI_SIZE_TO_PAGES(sizeof (FDC_BLK_IO_DEV)));
  if (FdcBlkIoDev == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  CopyMem (FdcBlkIoDev, &mBlockIoDevTemplate, sizeof (mBlockIoDevTemplate));

  //
  // Initialize DMA controller to enable all channels.
  //
  for (Index = 0; Index < sizeof (mRegisterTable) / sizeof (PEI_DMA_TABLE); Index++) {
    IoWrite8 (mRegisterTable[Index].Register, mRegisterTable[Index].Value);
  }
  REPORT_STATUS_CODE (EFI_PROGRESS_CODE, EFI_PERIPHERAL_REMOVABLE_MEDIA + EFI_P_PC_INIT);

  //
  // Enumerate FDC devices.
  //
  DeviceCount = FdcEnumeration (FdcBlkIoDev);
  if (DeviceCount == 0) {
    return EFI_NOT_FOUND;
  }

  FdcBlkIoDev->PpiDescriptor.Ppi = &FdcBlkIoDev->FdcBlkIo;

  return PeiServicesInstallPpi (&FdcBlkIoDev->PpiDescriptor);
}