1 /** @file
2   Header file for AHCI mode of ATA host controller.
3 
4   Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
5   SPDX-License-Identifier: BSD-2-Clause-Patent
6 
7 **/
8 
9 #include "AtaAtapiPassThru.h"
10 
11 /**
12   read a one-byte data from a IDE port.
13 
14   @param  PciIo  A pointer to EFI_PCI_IO_PROTOCOL data structure
15   @param  Port   The IDE Port number
16 
17   @return  the one-byte data read from IDE port
18 **/
19 UINT8
20 EFIAPI
IdeReadPortB(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT16 Port)21 IdeReadPortB (
22   IN  EFI_PCI_IO_PROTOCOL   *PciIo,
23   IN  UINT16                Port
24   )
25 {
26   UINT8 Data;
27 
28   ASSERT (PciIo != NULL);
29 
30   Data = 0;
31   //
32   // perform 1-byte data read from register
33   //
34   PciIo->Io.Read (
35               PciIo,
36               EfiPciIoWidthUint8,
37               EFI_PCI_IO_PASS_THROUGH_BAR,
38               (UINT64) Port,
39               1,
40               &Data
41               );
42   return Data;
43 }
44 
45 /**
46   write a 1-byte data to a specific IDE port.
47 
48   @param  PciIo  A pointer to EFI_PCI_IO_PROTOCOL data structure
49   @param  Port   The IDE port to be writen
50   @param  Data   The data to write to the port
51 **/
52 VOID
53 EFIAPI
IdeWritePortB(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT16 Port,IN UINT8 Data)54 IdeWritePortB (
55   IN  EFI_PCI_IO_PROTOCOL   *PciIo,
56   IN  UINT16                Port,
57   IN  UINT8                 Data
58   )
59 {
60   ASSERT (PciIo != NULL);
61 
62   //
63   // perform 1-byte data write to register
64   //
65   PciIo->Io.Write (
66               PciIo,
67               EfiPciIoWidthUint8,
68               EFI_PCI_IO_PASS_THROUGH_BAR,
69               (UINT64) Port,
70               1,
71               &Data
72               );
73 }
74 
75 /**
76   write a 1-word data to a specific IDE port.
77 
78   @param  PciIo  A pointer to EFI_PCI_IO_PROTOCOL data structure
79   @param  Port   The IDE port to be writen
80   @param  Data   The data to write to the port
81 **/
82 VOID
83 EFIAPI
IdeWritePortW(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT16 Port,IN UINT16 Data)84 IdeWritePortW (
85   IN  EFI_PCI_IO_PROTOCOL   *PciIo,
86   IN  UINT16                Port,
87   IN  UINT16                Data
88   )
89 {
90   ASSERT (PciIo != NULL);
91 
92   //
93   // perform 1-word data write to register
94   //
95   PciIo->Io.Write (
96               PciIo,
97               EfiPciIoWidthUint16,
98               EFI_PCI_IO_PASS_THROUGH_BAR,
99               (UINT64) Port,
100               1,
101               &Data
102               );
103 }
104 
105 /**
106   write a 2-word data to a specific IDE port.
107 
108   @param  PciIo  A pointer to EFI_PCI_IO_PROTOCOL data structure
109   @param  Port   The IDE port to be writen
110   @param  Data   The data to write to the port
111 **/
112 VOID
113 EFIAPI
IdeWritePortDW(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT16 Port,IN UINT32 Data)114 IdeWritePortDW (
115   IN  EFI_PCI_IO_PROTOCOL   *PciIo,
116   IN  UINT16                Port,
117   IN  UINT32                Data
118   )
119 {
120   ASSERT (PciIo != NULL);
121 
122   //
123   // perform 2-word data write to register
124   //
125   PciIo->Io.Write (
126               PciIo,
127               EfiPciIoWidthUint32,
128               EFI_PCI_IO_PASS_THROUGH_BAR,
129               (UINT64) Port,
130               1,
131               &Data
132               );
133 }
134 
135 /**
136   Write multiple words of data to the IDE data port.
137   Call the IO abstraction once to do the complete read,
138   not one word at a time
139 
140   @param  PciIo      A pointer to EFI_PCI_IO_PROTOCOL data structure
141   @param  Port       IO port to read
142   @param  Count      No. of UINT16's to read
143   @param  Buffer     Pointer to the data buffer for read
144 
145 **/
146 VOID
147 EFIAPI
IdeWritePortWMultiple(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT16 Port,IN UINTN Count,IN VOID * Buffer)148 IdeWritePortWMultiple (
149   IN  EFI_PCI_IO_PROTOCOL   *PciIo,
150   IN  UINT16                Port,
151   IN  UINTN                 Count,
152   IN  VOID                  *Buffer
153   )
154 {
155   ASSERT (PciIo  != NULL);
156   ASSERT (Buffer != NULL);
157 
158   //
159   // perform UINT16 data write to the FIFO
160   //
161   PciIo->Io.Write (
162               PciIo,
163               EfiPciIoWidthFifoUint16,
164               EFI_PCI_IO_PASS_THROUGH_BAR,
165               (UINT64) Port,
166               Count,
167               (UINT16 *) Buffer
168               );
169 
170 }
171 
172 /**
173   Reads multiple words of data from the IDE data port.
174   Call the IO abstraction once to do the complete read,
175   not one word at a time
176 
177   @param  PciIo    A pointer to EFI_PCI_IO_PROTOCOL data structure
178   @param  Port     IO port to read
179   @param  Count    Number of UINT16's to read
180   @param  Buffer   Pointer to the data buffer for read
181 
182 **/
183 VOID
184 EFIAPI
IdeReadPortWMultiple(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT16 Port,IN UINTN Count,IN VOID * Buffer)185 IdeReadPortWMultiple (
186   IN  EFI_PCI_IO_PROTOCOL   *PciIo,
187   IN  UINT16                Port,
188   IN  UINTN                 Count,
189   IN  VOID                  *Buffer
190   )
191 {
192   ASSERT (PciIo  != NULL);
193   ASSERT (Buffer != NULL);
194 
195   //
196   // Perform UINT16 data read from FIFO
197   //
198   PciIo->Io.Read (
199               PciIo,
200               EfiPciIoWidthFifoUint16,
201               EFI_PCI_IO_PASS_THROUGH_BAR,
202               (UINT64) Port,
203               Count,
204               (UINT16 *) Buffer
205               );
206 
207 }
208 
209 /**
210   This function is used to analyze the Status Register and print out
211   some debug information and if there is ERR bit set in the Status
212   Register, the Error Register's value is also be parsed and print out.
213 
214   @param PciIo            A pointer to EFI_PCI_IO_PROTOCOL data structure.
215   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
216   @param AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
217 
218 **/
219 VOID
220 EFIAPI
DumpAllIdeRegisters(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)221 DumpAllIdeRegisters (
222   IN     EFI_PCI_IO_PROTOCOL      *PciIo,
223   IN     EFI_IDE_REGISTERS        *IdeRegisters,
224   IN OUT EFI_ATA_STATUS_BLOCK     *AtaStatusBlock
225   )
226 {
227   EFI_ATA_STATUS_BLOCK StatusBlock;
228 
229   ASSERT (PciIo != NULL);
230   ASSERT (IdeRegisters != NULL);
231 
232   ZeroMem (&StatusBlock, sizeof (EFI_ATA_STATUS_BLOCK));
233 
234   StatusBlock.AtaStatus          = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus);
235   StatusBlock.AtaError           = IdeReadPortB (PciIo, IdeRegisters->ErrOrFeature);
236   StatusBlock.AtaSectorCount     = IdeReadPortB (PciIo, IdeRegisters->SectorCount);
237   StatusBlock.AtaSectorCountExp  = IdeReadPortB (PciIo, IdeRegisters->SectorCount);
238   StatusBlock.AtaSectorNumber    = IdeReadPortB (PciIo, IdeRegisters->SectorNumber);
239   StatusBlock.AtaSectorNumberExp = IdeReadPortB (PciIo, IdeRegisters->SectorNumber);
240   StatusBlock.AtaCylinderLow     = IdeReadPortB (PciIo, IdeRegisters->CylinderLsb);
241   StatusBlock.AtaCylinderLowExp  = IdeReadPortB (PciIo, IdeRegisters->CylinderLsb);
242   StatusBlock.AtaCylinderHigh    = IdeReadPortB (PciIo, IdeRegisters->CylinderMsb);
243   StatusBlock.AtaCylinderHighExp = IdeReadPortB (PciIo, IdeRegisters->CylinderMsb);
244   StatusBlock.AtaDeviceHead      = IdeReadPortB (PciIo, IdeRegisters->Head);
245 
246   if (AtaStatusBlock != NULL) {
247     //
248     // Dump the content of all ATA registers.
249     //
250     CopyMem (AtaStatusBlock, &StatusBlock, sizeof (EFI_ATA_STATUS_BLOCK));
251   }
252 
253   DEBUG_CODE_BEGIN ();
254   if ((StatusBlock.AtaStatus & ATA_STSREG_DWF) != 0) {
255     DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Write Fault\n", StatusBlock.AtaStatus));
256   }
257 
258   if ((StatusBlock.AtaStatus & ATA_STSREG_CORR) != 0) {
259     DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Corrected Data\n", StatusBlock.AtaStatus));
260   }
261 
262   if ((StatusBlock.AtaStatus & ATA_STSREG_ERR) != 0) {
263     if ((StatusBlock.AtaError & ATA_ERRREG_BBK) != 0) {
264       DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Bad Block Detected\n", StatusBlock.AtaError));
265     }
266 
267     if ((StatusBlock.AtaError & ATA_ERRREG_UNC) != 0) {
268       DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Uncorrectable Data\n", StatusBlock.AtaError));
269     }
270 
271     if ((StatusBlock.AtaError & ATA_ERRREG_MC) != 0) {
272       DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Media Change\n", StatusBlock.AtaError));
273     }
274 
275     if ((StatusBlock.AtaError & ATA_ERRREG_ABRT) != 0) {
276       DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Abort\n", StatusBlock.AtaError));
277     }
278 
279     if ((StatusBlock.AtaError & ATA_ERRREG_TK0NF) != 0) {
280       DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Track 0 Not Found\n", StatusBlock.AtaError));
281     }
282 
283     if ((StatusBlock.AtaError & ATA_ERRREG_AMNF) != 0) {
284       DEBUG ((EFI_D_ERROR, "CheckRegisterStatus()-- %02x : Error : Address Mark Not Found\n", StatusBlock.AtaError));
285     }
286   }
287   DEBUG_CODE_END ();
288 }
289 
290 /**
291   This function is used to analyze the Status Register at the condition that BSY is zero.
292   if there is ERR bit set in the Status Register, then return error.
293 
294   @param PciIo            A pointer to EFI_PCI_IO_PROTOCOL data structure.
295   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
296 
297   @retval EFI_SUCCESS       No err information in the Status Register.
298   @retval EFI_DEVICE_ERROR  Any err information in the Status Register.
299 
300 **/
301 EFI_STATUS
302 EFIAPI
CheckStatusRegister(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters)303 CheckStatusRegister (
304   IN  EFI_PCI_IO_PROTOCOL      *PciIo,
305   IN  EFI_IDE_REGISTERS        *IdeRegisters
306   )
307 {
308   UINT8           StatusRegister;
309 
310   ASSERT (PciIo != NULL);
311   ASSERT (IdeRegisters != NULL);
312 
313   StatusRegister = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus);
314 
315   if ((StatusRegister & ATA_STSREG_BSY) == 0) {
316     if ((StatusRegister & (ATA_STSREG_ERR | ATA_STSREG_DWF | ATA_STSREG_CORR)) == 0) {
317       return EFI_SUCCESS;
318     } else {
319       return EFI_DEVICE_ERROR;
320     }
321   }
322   return EFI_SUCCESS;
323 }
324 
325 /**
326   This function is used to poll for the DRQ bit clear in the Status
327   Register. DRQ is cleared when the device is finished transferring data.
328   So this function is called after data transfer is finished.
329 
330   @param PciIo            A pointer to EFI_PCI_IO_PROTOCOL data structure.
331   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
332   @param Timeout          The time to complete the command, uses 100ns as a unit.
333 
334   @retval EFI_SUCCESS     DRQ bit clear within the time out.
335 
336   @retval EFI_TIMEOUT     DRQ bit not clear within the time out.
337 
338   @note
339   Read Status Register will clear interrupt status.
340 
341 **/
342 EFI_STATUS
343 EFIAPI
DRQClear(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT64 Timeout)344 DRQClear (
345   IN  EFI_PCI_IO_PROTOCOL       *PciIo,
346   IN  EFI_IDE_REGISTERS         *IdeRegisters,
347   IN  UINT64                    Timeout
348   )
349 {
350   UINT64  Delay;
351   UINT8   StatusRegister;
352   BOOLEAN InfiniteWait;
353 
354   ASSERT (PciIo != NULL);
355   ASSERT (IdeRegisters != NULL);
356 
357   if (Timeout == 0) {
358     InfiniteWait = TRUE;
359   } else {
360     InfiniteWait = FALSE;
361   }
362 
363   Delay = DivU64x32(Timeout, 1000) + 1;
364   do {
365     StatusRegister = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus);
366 
367     //
368     // Wait for BSY == 0, then judge if DRQ is clear
369     //
370     if ((StatusRegister & ATA_STSREG_BSY) == 0) {
371       if ((StatusRegister & ATA_STSREG_DRQ) == ATA_STSREG_DRQ) {
372         return EFI_DEVICE_ERROR;
373       } else {
374         return EFI_SUCCESS;
375       }
376     }
377 
378     //
379     // Stall for 100 microseconds.
380     //
381     MicroSecondDelay (100);
382 
383     Delay--;
384 
385   } while (InfiniteWait || (Delay > 0));
386 
387   return EFI_TIMEOUT;
388 }
389 /**
390   This function is used to poll for the DRQ bit clear in the Alternate
391   Status Register. DRQ is cleared when the device is finished
392   transferring data. So this function is called after data transfer
393   is finished.
394 
395   @param PciIo            A pointer to EFI_PCI_IO_PROTOCOL data structure.
396   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
397   @param Timeout          The time to complete the command, uses 100ns as a unit.
398 
399   @retval EFI_SUCCESS     DRQ bit clear within the time out.
400 
401   @retval EFI_TIMEOUT     DRQ bit not clear within the time out.
402   @note   Read Alternate Status Register will not clear interrupt status.
403 
404 **/
405 EFI_STATUS
406 EFIAPI
DRQClear2(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT64 Timeout)407 DRQClear2 (
408   IN  EFI_PCI_IO_PROTOCOL  *PciIo,
409   IN  EFI_IDE_REGISTERS    *IdeRegisters,
410   IN  UINT64               Timeout
411   )
412 {
413   UINT64  Delay;
414   UINT8   AltRegister;
415   BOOLEAN InfiniteWait;
416 
417   ASSERT (PciIo != NULL);
418   ASSERT (IdeRegisters != NULL);
419 
420   if (Timeout == 0) {
421     InfiniteWait = TRUE;
422   } else {
423     InfiniteWait = FALSE;
424   }
425 
426   Delay = DivU64x32(Timeout, 1000) + 1;
427   do {
428     AltRegister = IdeReadPortB (PciIo, IdeRegisters->AltOrDev);
429 
430     //
431     // Wait for BSY == 0, then judge if DRQ is clear
432     //
433     if ((AltRegister & ATA_STSREG_BSY) == 0) {
434       if ((AltRegister & ATA_STSREG_DRQ) == ATA_STSREG_DRQ) {
435         return EFI_DEVICE_ERROR;
436       } else {
437         return EFI_SUCCESS;
438       }
439     }
440 
441     //
442     // Stall for 100 microseconds.
443     //
444     MicroSecondDelay (100);
445 
446     Delay--;
447 
448   } while (InfiniteWait || (Delay > 0));
449 
450   return EFI_TIMEOUT;
451 }
452 
453 /**
454   This function is used to poll for the DRQ bit set in the
455   Status Register.
456   DRQ is set when the device is ready to transfer data. So this function
457   is called after the command is sent to the device and before required
458   data is transferred.
459 
460   @param PciIo            A pointer to EFI_PCI_IO_PROTOCOL data structure.
461   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
462   @param Timeout          The time to complete the command, uses 100ns as a unit.
463 
464   @retval EFI_SUCCESS           BSY bit cleared and DRQ bit set within the
465                                 timeout.
466 
467   @retval EFI_TIMEOUT           BSY bit not cleared within the timeout.
468 
469   @retval EFI_ABORTED           Polling abandoned due to command abort.
470 
471   @retval EFI_DEVICE_ERROR      Polling abandoned due to a non-abort error.
472 
473   @retval EFI_NOT_READY         BSY bit cleared within timeout, and device
474                                 reported "command complete" by clearing DRQ
475                                 bit.
476 
477   @note  Read Status Register will clear interrupt status.
478 
479 **/
480 EFI_STATUS
481 EFIAPI
DRQReady(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT64 Timeout)482 DRQReady (
483   IN  EFI_PCI_IO_PROTOCOL  *PciIo,
484   IN  EFI_IDE_REGISTERS    *IdeRegisters,
485   IN  UINT64               Timeout
486   )
487 {
488   UINT64  Delay;
489   UINT8   StatusRegister;
490   UINT8   ErrorRegister;
491   BOOLEAN InfiniteWait;
492 
493   ASSERT (PciIo != NULL);
494   ASSERT (IdeRegisters != NULL);
495 
496   if (Timeout == 0) {
497     InfiniteWait = TRUE;
498   } else {
499     InfiniteWait = FALSE;
500   }
501 
502   Delay = DivU64x32(Timeout, 1000) + 1;
503   do {
504     //
505     // Read Status Register will clear interrupt
506     //
507     StatusRegister = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus);
508 
509     //
510     // Wait for BSY == 0, then judge if DRQ is clear or ERR is set
511     //
512     if ((StatusRegister & ATA_STSREG_BSY) == 0) {
513       if ((StatusRegister & ATA_STSREG_ERR) == ATA_STSREG_ERR) {
514         ErrorRegister = IdeReadPortB (PciIo, IdeRegisters->ErrOrFeature);
515 
516         if ((ErrorRegister & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) {
517           return EFI_ABORTED;
518         }
519         return EFI_DEVICE_ERROR;
520       }
521 
522       if ((StatusRegister & ATA_STSREG_DRQ) == ATA_STSREG_DRQ) {
523         return EFI_SUCCESS;
524       } else {
525         return EFI_NOT_READY;
526       }
527     }
528 
529     //
530     // Stall for 100 microseconds.
531     //
532     MicroSecondDelay (100);
533 
534     Delay--;
535   } while (InfiniteWait || (Delay > 0));
536 
537   return EFI_TIMEOUT;
538 }
539 /**
540   This function is used to poll for the DRQ bit set in the Alternate Status Register.
541   DRQ is set when the device is ready to transfer data. So this function is called after
542   the command is sent to the device and before required data is transferred.
543 
544   @param PciIo            A pointer to EFI_PCI_IO_PROTOCOL data structure.
545   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
546   @param Timeout          The time to complete the command, uses 100ns as a unit.
547 
548   @retval EFI_SUCCESS           BSY bit cleared and DRQ bit set within the
549                                 timeout.
550 
551   @retval EFI_TIMEOUT           BSY bit not cleared within the timeout.
552 
553   @retval EFI_ABORTED           Polling abandoned due to command abort.
554 
555   @retval EFI_DEVICE_ERROR      Polling abandoned due to a non-abort error.
556 
557   @retval EFI_NOT_READY         BSY bit cleared within timeout, and device
558                                 reported "command complete" by clearing DRQ
559                                 bit.
560 
561   @note  Read Alternate Status Register will not clear interrupt status.
562 
563 **/
564 EFI_STATUS
565 EFIAPI
DRQReady2(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT64 Timeout)566 DRQReady2 (
567   IN  EFI_PCI_IO_PROTOCOL  *PciIo,
568   IN  EFI_IDE_REGISTERS    *IdeRegisters,
569   IN  UINT64               Timeout
570   )
571 {
572   UINT64  Delay;
573   UINT8   AltRegister;
574   UINT8   ErrorRegister;
575   BOOLEAN InfiniteWait;
576 
577   ASSERT (PciIo != NULL);
578   ASSERT (IdeRegisters != NULL);
579 
580   if (Timeout == 0) {
581     InfiniteWait = TRUE;
582   } else {
583     InfiniteWait = FALSE;
584   }
585 
586   Delay = DivU64x32(Timeout, 1000) + 1;
587 
588   do {
589     //
590     // Read Alternate Status Register will not clear interrupt status
591     //
592     AltRegister = IdeReadPortB (PciIo, IdeRegisters->AltOrDev);
593     //
594     // Wait for BSY == 0, then judge if DRQ is clear or ERR is set
595     //
596     if ((AltRegister & ATA_STSREG_BSY) == 0) {
597       if ((AltRegister & ATA_STSREG_ERR) == ATA_STSREG_ERR) {
598         ErrorRegister = IdeReadPortB (PciIo, IdeRegisters->ErrOrFeature);
599 
600         if ((ErrorRegister & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) {
601           return EFI_ABORTED;
602         }
603         return EFI_DEVICE_ERROR;
604       }
605 
606       if ((AltRegister & ATA_STSREG_DRQ) == ATA_STSREG_DRQ) {
607         return EFI_SUCCESS;
608       } else {
609         return EFI_NOT_READY;
610       }
611     }
612 
613     //
614     // Stall for 100 microseconds.
615     //
616     MicroSecondDelay (100);
617 
618     Delay--;
619   } while (InfiniteWait || (Delay > 0));
620 
621   return EFI_TIMEOUT;
622 }
623 
624 
625 
626 
627 /**
628   This function is used to poll for the BSY bit clear in the Status Register. BSY
629   is clear when the device is not busy. Every command must be sent after device is not busy.
630 
631   @param PciIo            A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
632   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
633   @param Timeout          The time to complete the command, uses 100ns as a unit.
634 
635   @retval EFI_SUCCESS          BSY bit clear within the time out.
636   @retval EFI_TIMEOUT          BSY bit not clear within the time out.
637 
638   @note Read Status Register will clear interrupt status.
639 **/
640 EFI_STATUS
641 EFIAPI
WaitForBSYClear(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT64 Timeout)642 WaitForBSYClear (
643   IN  EFI_PCI_IO_PROTOCOL  *PciIo,
644   IN  EFI_IDE_REGISTERS    *IdeRegisters,
645   IN  UINT64               Timeout
646   )
647 {
648   UINT64  Delay;
649   UINT8   StatusRegister;
650   BOOLEAN InfiniteWait;
651 
652   ASSERT (PciIo != NULL);
653   ASSERT (IdeRegisters != NULL);
654 
655   if (Timeout == 0) {
656     InfiniteWait = TRUE;
657   } else {
658     InfiniteWait = FALSE;
659   }
660 
661   Delay = DivU64x32(Timeout, 1000) + 1;
662   do {
663     StatusRegister = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus);
664 
665     if ((StatusRegister & ATA_STSREG_BSY) == 0x00) {
666       return EFI_SUCCESS;
667     }
668 
669     //
670     // Stall for 100 microseconds.
671     //
672     MicroSecondDelay (100);
673 
674     Delay--;
675 
676   } while (InfiniteWait || (Delay > 0));
677 
678   return EFI_TIMEOUT;
679 }
680 
681 
682 /**
683   Get IDE i/o port registers' base addresses by mode.
684 
685   In 'Compatibility' mode, use fixed addresses.
686   In Native-PCI mode, get base addresses from BARs in the PCI IDE controller's
687   Configuration Space.
688 
689   The steps to get IDE i/o port registers' base addresses for each channel
690   as follows:
691 
692   1. Examine the Programming Interface byte of the Class Code fields in PCI IDE
693   controller's Configuration Space to determine the operating mode.
694 
695   2. a) In 'Compatibility' mode, use fixed addresses shown in the Table 1 below.
696    ___________________________________________
697   |           | Command Block | Control Block |
698   |  Channel  |   Registers   |   Registers   |
699   |___________|_______________|_______________|
700   |  Primary  |  1F0h - 1F7h  |  3F6h - 3F7h  |
701   |___________|_______________|_______________|
702   | Secondary |  170h - 177h  |  376h - 377h  |
703   |___________|_______________|_______________|
704 
705   Table 1. Compatibility resource mappings
706 
707   b) In Native-PCI mode, IDE registers are mapped into IO space using the BARs
708   in IDE controller's PCI Configuration Space, shown in the Table 2 below.
709    ___________________________________________________
710   |           |   Command Block   |   Control Block   |
711   |  Channel  |     Registers     |     Registers     |
712   |___________|___________________|___________________|
713   |  Primary  | BAR at offset 0x10| BAR at offset 0x14|
714   |___________|___________________|___________________|
715   | Secondary | BAR at offset 0x18| BAR at offset 0x1C|
716   |___________|___________________|___________________|
717 
718   Table 2. BARs for Register Mapping
719 
720   @param[in]      PciIo          Pointer to the EFI_PCI_IO_PROTOCOL instance
721   @param[in, out] IdeRegisters    Pointer to EFI_IDE_REGISTERS which is used to
722                                  store the IDE i/o port registers' base addresses
723 
724   @retval EFI_UNSUPPORTED        Return this value when the BARs is not IO type
725   @retval EFI_SUCCESS            Get the Base address successfully
726   @retval Other                  Read the pci configureation data error
727 
728 **/
729 EFI_STATUS
730 EFIAPI
GetIdeRegisterIoAddr(IN EFI_PCI_IO_PROTOCOL * PciIo,IN OUT EFI_IDE_REGISTERS * IdeRegisters)731 GetIdeRegisterIoAddr (
732   IN     EFI_PCI_IO_PROTOCOL         *PciIo,
733   IN OUT EFI_IDE_REGISTERS           *IdeRegisters
734   )
735 {
736   EFI_STATUS        Status;
737   PCI_TYPE00        PciData;
738   UINT16            CommandBlockBaseAddr;
739   UINT16            ControlBlockBaseAddr;
740   UINT16            BusMasterBaseAddr;
741 
742   if ((PciIo == NULL) || (IdeRegisters == NULL)) {
743     return EFI_INVALID_PARAMETER;
744   }
745 
746   Status = PciIo->Pci.Read (
747                         PciIo,
748                         EfiPciIoWidthUint8,
749                         0,
750                         sizeof (PciData),
751                         &PciData
752                         );
753 
754   if (EFI_ERROR (Status)) {
755     return Status;
756   }
757 
758   BusMasterBaseAddr    = (UINT16) ((PciData.Device.Bar[4] & 0x0000fff0));
759 
760   if ((PciData.Hdr.ClassCode[0] & IDE_PRIMARY_OPERATING_MODE) == 0) {
761     CommandBlockBaseAddr = 0x1f0;
762     ControlBlockBaseAddr = 0x3f6;
763   } else {
764     //
765     // The BARs should be of IO type
766     //
767     if ((PciData.Device.Bar[0] & BIT0) == 0 ||
768         (PciData.Device.Bar[1] & BIT0) == 0) {
769       return EFI_UNSUPPORTED;
770     }
771 
772     CommandBlockBaseAddr = (UINT16) (PciData.Device.Bar[0] & 0x0000fff8);
773     ControlBlockBaseAddr = (UINT16) ((PciData.Device.Bar[1] & 0x0000fffc) + 2);
774   }
775 
776   //
777   // Calculate IDE primary channel I/O register base address.
778   //
779   IdeRegisters[EfiIdePrimary].Data              = CommandBlockBaseAddr;
780   IdeRegisters[EfiIdePrimary].ErrOrFeature      = (UINT16) (CommandBlockBaseAddr + 0x01);
781   IdeRegisters[EfiIdePrimary].SectorCount       = (UINT16) (CommandBlockBaseAddr + 0x02);
782   IdeRegisters[EfiIdePrimary].SectorNumber      = (UINT16) (CommandBlockBaseAddr + 0x03);
783   IdeRegisters[EfiIdePrimary].CylinderLsb       = (UINT16) (CommandBlockBaseAddr + 0x04);
784   IdeRegisters[EfiIdePrimary].CylinderMsb       = (UINT16) (CommandBlockBaseAddr + 0x05);
785   IdeRegisters[EfiIdePrimary].Head              = (UINT16) (CommandBlockBaseAddr + 0x06);
786   IdeRegisters[EfiIdePrimary].CmdOrStatus       = (UINT16) (CommandBlockBaseAddr + 0x07);
787   IdeRegisters[EfiIdePrimary].AltOrDev          = ControlBlockBaseAddr;
788   IdeRegisters[EfiIdePrimary].BusMasterBaseAddr = BusMasterBaseAddr;
789 
790   if ((PciData.Hdr.ClassCode[0] & IDE_SECONDARY_OPERATING_MODE) == 0) {
791     CommandBlockBaseAddr = 0x170;
792     ControlBlockBaseAddr = 0x376;
793   } else {
794     //
795     // The BARs should be of IO type
796     //
797     if ((PciData.Device.Bar[2] & BIT0) == 0 ||
798         (PciData.Device.Bar[3] & BIT0) == 0) {
799       return EFI_UNSUPPORTED;
800     }
801 
802     CommandBlockBaseAddr = (UINT16) (PciData.Device.Bar[2] & 0x0000fff8);
803     ControlBlockBaseAddr = (UINT16) ((PciData.Device.Bar[3] & 0x0000fffc) + 2);
804   }
805 
806   //
807   // Calculate IDE secondary channel I/O register base address.
808   //
809   IdeRegisters[EfiIdeSecondary].Data              = CommandBlockBaseAddr;
810   IdeRegisters[EfiIdeSecondary].ErrOrFeature      = (UINT16) (CommandBlockBaseAddr + 0x01);
811   IdeRegisters[EfiIdeSecondary].SectorCount       = (UINT16) (CommandBlockBaseAddr + 0x02);
812   IdeRegisters[EfiIdeSecondary].SectorNumber      = (UINT16) (CommandBlockBaseAddr + 0x03);
813   IdeRegisters[EfiIdeSecondary].CylinderLsb       = (UINT16) (CommandBlockBaseAddr + 0x04);
814   IdeRegisters[EfiIdeSecondary].CylinderMsb       = (UINT16) (CommandBlockBaseAddr + 0x05);
815   IdeRegisters[EfiIdeSecondary].Head              = (UINT16) (CommandBlockBaseAddr + 0x06);
816   IdeRegisters[EfiIdeSecondary].CmdOrStatus       = (UINT16) (CommandBlockBaseAddr + 0x07);
817   IdeRegisters[EfiIdeSecondary].AltOrDev          = ControlBlockBaseAddr;
818   IdeRegisters[EfiIdeSecondary].BusMasterBaseAddr = (UINT16) (BusMasterBaseAddr + 0x8);
819 
820   return EFI_SUCCESS;
821 }
822 
823 
824 /**
825   Send ATA Ext command into device with NON_DATA protocol.
826 
827   @param PciIo            A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
828   @param IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
829   @param AtaCommandBlock  A pointer to EFI_ATA_COMMAND_BLOCK data structure.
830   @param Timeout          The time to complete the command, uses 100ns as a unit.
831 
832   @retval  EFI_SUCCESS Reading succeed
833   @retval  EFI_DEVICE_ERROR Error executing commands on this device.
834 
835 **/
836 EFI_STATUS
837 EFIAPI
AtaIssueCommand(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN EFI_ATA_COMMAND_BLOCK * AtaCommandBlock,IN UINT64 Timeout)838 AtaIssueCommand (
839   IN  EFI_PCI_IO_PROTOCOL       *PciIo,
840   IN  EFI_IDE_REGISTERS         *IdeRegisters,
841   IN  EFI_ATA_COMMAND_BLOCK     *AtaCommandBlock,
842   IN  UINT64                    Timeout
843   )
844 {
845   EFI_STATUS  Status;
846   UINT8       DeviceHead;
847   UINT8       AtaCommand;
848 
849   ASSERT (PciIo != NULL);
850   ASSERT (IdeRegisters != NULL);
851   ASSERT (AtaCommandBlock != NULL);
852 
853   DeviceHead = AtaCommandBlock->AtaDeviceHead;
854   AtaCommand = AtaCommandBlock->AtaCommand;
855 
856   Status = WaitForBSYClear (PciIo, IdeRegisters, Timeout);
857   if (EFI_ERROR (Status)) {
858     return EFI_DEVICE_ERROR;
859   }
860 
861   //
862   // Select device (bit4), set LBA mode(bit6) (use 0xe0 for compatibility)
863   //
864   IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8) (0xe0 | DeviceHead));
865 
866   //
867   // set all the command parameters
868   // Before write to all the following registers, BSY and DRQ must be 0.
869   //
870   Status = DRQClear2 (PciIo, IdeRegisters, Timeout);
871   if (EFI_ERROR (Status)) {
872     return EFI_DEVICE_ERROR;
873   }
874 
875   //
876   // Fill the feature register, which is a two-byte FIFO. Need write twice.
877   //
878   IdeWritePortB (PciIo, IdeRegisters->ErrOrFeature, AtaCommandBlock->AtaFeaturesExp);
879   IdeWritePortB (PciIo, IdeRegisters->ErrOrFeature, AtaCommandBlock->AtaFeatures);
880 
881   //
882   // Fill the sector count register, which is a two-byte FIFO. Need write twice.
883   //
884   IdeWritePortB (PciIo, IdeRegisters->SectorCount, AtaCommandBlock->AtaSectorCountExp);
885   IdeWritePortB (PciIo, IdeRegisters->SectorCount, AtaCommandBlock->AtaSectorCount);
886 
887   //
888   // Fill the start LBA registers, which are also two-byte FIFO
889   //
890   IdeWritePortB (PciIo, IdeRegisters->SectorNumber, AtaCommandBlock->AtaSectorNumberExp);
891   IdeWritePortB (PciIo, IdeRegisters->SectorNumber, AtaCommandBlock->AtaSectorNumber);
892 
893   IdeWritePortB (PciIo, IdeRegisters->CylinderLsb, AtaCommandBlock->AtaCylinderLowExp);
894   IdeWritePortB (PciIo, IdeRegisters->CylinderLsb, AtaCommandBlock->AtaCylinderLow);
895 
896   IdeWritePortB (PciIo, IdeRegisters->CylinderMsb, AtaCommandBlock->AtaCylinderHighExp);
897   IdeWritePortB (PciIo, IdeRegisters->CylinderMsb, AtaCommandBlock->AtaCylinderHigh);
898 
899   //
900   // Send command via Command Register
901   //
902   IdeWritePortB (PciIo, IdeRegisters->CmdOrStatus, AtaCommand);
903 
904   //
905   // Stall at least 400 microseconds.
906   //
907   MicroSecondDelay (400);
908 
909   return EFI_SUCCESS;
910 }
911 
912 /**
913   This function is used to send out ATA commands conforms to the PIO Data In Protocol.
914 
915   @param[in]      PciIo            A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data
916                                    structure.
917   @param[in]      IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
918   @param[in, out] Buffer           A pointer to the source buffer for the data.
919   @param[in]      ByteCount        The length of the data.
920   @param[in]      Read             Flag used to determine the data transfer direction.
921                                    Read equals 1, means data transferred from device
922                                    to host;Read equals 0, means data transferred
923                                    from host to device.
924   @param[in]      AtaCommandBlock  A pointer to EFI_ATA_COMMAND_BLOCK data structure.
925   @param[in, out] AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
926   @param[in]      Timeout          The time to complete the command, uses 100ns as a unit.
927   @param[in]      Task             Optional. Pointer to the ATA_NONBLOCK_TASK
928                                    used by non-blocking mode.
929 
930   @retval EFI_SUCCESS      send out the ATA command and device send required data successfully.
931   @retval EFI_DEVICE_ERROR command sent failed.
932 
933 **/
934 EFI_STATUS
935 EFIAPI
AtaPioDataInOut(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN OUT VOID * Buffer,IN UINT64 ByteCount,IN BOOLEAN Read,IN EFI_ATA_COMMAND_BLOCK * AtaCommandBlock,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock,IN UINT64 Timeout,IN ATA_NONBLOCK_TASK * Task)936 AtaPioDataInOut (
937   IN     EFI_PCI_IO_PROTOCOL       *PciIo,
938   IN     EFI_IDE_REGISTERS         *IdeRegisters,
939   IN OUT VOID                      *Buffer,
940   IN     UINT64                    ByteCount,
941   IN     BOOLEAN                   Read,
942   IN     EFI_ATA_COMMAND_BLOCK     *AtaCommandBlock,
943   IN OUT EFI_ATA_STATUS_BLOCK      *AtaStatusBlock,
944   IN     UINT64                    Timeout,
945   IN     ATA_NONBLOCK_TASK         *Task
946   )
947 {
948   UINTN       WordCount;
949   UINTN       Increment;
950   UINT16      *Buffer16;
951   EFI_STATUS  Status;
952 
953   if ((PciIo == NULL) || (IdeRegisters == NULL) || (Buffer == NULL) || (AtaCommandBlock == NULL)) {
954     return EFI_INVALID_PARAMETER;
955   }
956 
957   //
958   // Issue ATA command
959   //
960   Status = AtaIssueCommand (PciIo, IdeRegisters, AtaCommandBlock, Timeout);
961   if (EFI_ERROR (Status)) {
962     Status = EFI_DEVICE_ERROR;
963     goto Exit;
964   }
965 
966   Buffer16 = (UINT16 *) Buffer;
967 
968   //
969   // According to PIO data in protocol, host can perform a series of reads to
970   // the data register after each time device set DRQ ready;
971   // The data size of "a series of read" is command specific.
972   // For most ATA command, data size received from device will not exceed
973   // 1 sector, hence the data size for "a series of read" can be the whole data
974   // size of one command request.
975   // For ATA command such as Read Sector command, the data size of one ATA
976   // command request is often larger than 1 sector, according to the
977   // Read Sector command, the data size of "a series of read" is exactly 1
978   // sector.
979   // Here for simplification reason, we specify the data size for
980   // "a series of read" to 1 sector (256 words) if data size of one ATA command
981   // request is larger than 256 words.
982   //
983   Increment = 256;
984 
985   //
986   // used to record bytes of currently transfered data
987   //
988   WordCount = 0;
989 
990   while (WordCount < RShiftU64(ByteCount, 1)) {
991     //
992     // Poll DRQ bit set, data transfer can be performed only when DRQ is ready
993     //
994     Status = DRQReady2 (PciIo, IdeRegisters, Timeout);
995     if (EFI_ERROR (Status)) {
996       Status = EFI_DEVICE_ERROR;
997       goto Exit;
998     }
999 
1000     //
1001     // Get the byte count for one series of read
1002     //
1003     if ((WordCount + Increment) > RShiftU64(ByteCount, 1)) {
1004       Increment = (UINTN)(RShiftU64(ByteCount, 1) - WordCount);
1005     }
1006 
1007     if (Read) {
1008       IdeReadPortWMultiple (
1009         PciIo,
1010         IdeRegisters->Data,
1011         Increment,
1012         Buffer16
1013         );
1014     } else {
1015       IdeWritePortWMultiple (
1016         PciIo,
1017         IdeRegisters->Data,
1018         Increment,
1019         Buffer16
1020         );
1021     }
1022 
1023     Status = CheckStatusRegister (PciIo, IdeRegisters);
1024     if (EFI_ERROR (Status)) {
1025       Status = EFI_DEVICE_ERROR;
1026       goto Exit;
1027     }
1028 
1029     WordCount += Increment;
1030     Buffer16  += Increment;
1031   }
1032 
1033   Status = DRQClear (PciIo, IdeRegisters, Timeout);
1034   if (EFI_ERROR (Status)) {
1035     Status = EFI_DEVICE_ERROR;
1036     goto Exit;
1037   }
1038 
1039 Exit:
1040   //
1041   // Dump All Ide registers to ATA_STATUS_BLOCK
1042   //
1043   DumpAllIdeRegisters (PciIo, IdeRegisters, AtaStatusBlock);
1044 
1045   //
1046   // Not support the Non-blocking now,just do the blocking process.
1047   //
1048   return Status;
1049 }
1050 
1051 /**
1052   Send ATA command into device with NON_DATA protocol
1053 
1054   @param[in]      PciIo            A pointer to ATA_ATAPI_PASS_THRU_INSTANCE
1055                                    data structure.
1056   @param[in]      IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
1057   @param[in]      AtaCommandBlock  A pointer to EFI_ATA_COMMAND_BLOCK data
1058                                    structure.
1059   @param[in, out] AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
1060   @param[in]      Timeout          The time to complete the command, uses 100ns as a unit.
1061   @param[in]      Task             Optional. Pointer to the ATA_NONBLOCK_TASK
1062                                    used by non-blocking mode.
1063 
1064   @retval  EFI_SUCCESS Reading succeed
1065   @retval  EFI_ABORTED Command failed
1066   @retval  EFI_DEVICE_ERROR Device status error.
1067 
1068 **/
1069 EFI_STATUS
1070 EFIAPI
AtaNonDataCommandIn(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN EFI_ATA_COMMAND_BLOCK * AtaCommandBlock,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock,IN UINT64 Timeout,IN ATA_NONBLOCK_TASK * Task)1071 AtaNonDataCommandIn (
1072   IN     EFI_PCI_IO_PROTOCOL       *PciIo,
1073   IN     EFI_IDE_REGISTERS         *IdeRegisters,
1074   IN     EFI_ATA_COMMAND_BLOCK     *AtaCommandBlock,
1075   IN OUT EFI_ATA_STATUS_BLOCK      *AtaStatusBlock,
1076   IN     UINT64                    Timeout,
1077   IN     ATA_NONBLOCK_TASK         *Task
1078   )
1079 {
1080   EFI_STATUS  Status;
1081 
1082   if ((PciIo == NULL) || (IdeRegisters == NULL) || (AtaCommandBlock == NULL)) {
1083     return EFI_INVALID_PARAMETER;
1084   }
1085 
1086   //
1087   // Issue ATA command
1088   //
1089   Status = AtaIssueCommand (PciIo, IdeRegisters, AtaCommandBlock, Timeout);
1090   if (EFI_ERROR (Status)) {
1091     Status = EFI_DEVICE_ERROR;
1092     goto Exit;
1093   }
1094 
1095   //
1096   // Wait for command completion
1097   //
1098   Status = WaitForBSYClear (PciIo, IdeRegisters, Timeout);
1099   if (EFI_ERROR (Status)) {
1100     Status = EFI_DEVICE_ERROR;
1101     goto Exit;
1102   }
1103 
1104   Status = CheckStatusRegister (PciIo, IdeRegisters);
1105   if (EFI_ERROR (Status)) {
1106     Status = EFI_DEVICE_ERROR;
1107     goto Exit;
1108   }
1109 
1110 Exit:
1111   //
1112   // Dump All Ide registers to ATA_STATUS_BLOCK
1113   //
1114   DumpAllIdeRegisters (PciIo, IdeRegisters, AtaStatusBlock);
1115 
1116   //
1117   // Not support the Non-blocking now,just do the blocking process.
1118   //
1119   return Status;
1120 }
1121 
1122 /**
1123   Wait for memory to be set.
1124 
1125   @param[in]  PciIo           The PCI IO protocol instance.
1126   @param[in]  IdeRegisters    A pointer to EFI_IDE_REGISTERS data structure.
1127   @param[in]  Timeout         The time to complete the command, uses 100ns as a unit.
1128 
1129   @retval EFI_DEVICE_ERROR  The memory is not set.
1130   @retval EFI_TIMEOUT       The memory setting is time out.
1131   @retval EFI_SUCCESS       The memory is correct set.
1132 
1133 **/
1134 EFI_STATUS
AtaUdmStatusWait(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT64 Timeout)1135 AtaUdmStatusWait (
1136   IN  EFI_PCI_IO_PROTOCOL       *PciIo,
1137   IN  EFI_IDE_REGISTERS         *IdeRegisters,
1138   IN  UINT64                    Timeout
1139  )
1140 {
1141   UINT8                         RegisterValue;
1142   EFI_STATUS                    Status;
1143   UINT16                        IoPortForBmis;
1144   UINT64                        Delay;
1145   BOOLEAN                       InfiniteWait;
1146 
1147   if (Timeout == 0) {
1148     InfiniteWait = TRUE;
1149   } else {
1150     InfiniteWait = FALSE;
1151   }
1152 
1153   Delay = DivU64x32 (Timeout, 1000) + 1;
1154 
1155   do {
1156     Status = CheckStatusRegister (PciIo, IdeRegisters);
1157     if (EFI_ERROR (Status)) {
1158       Status = EFI_DEVICE_ERROR;
1159       break;
1160     }
1161 
1162     IoPortForBmis = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET);
1163     RegisterValue = IdeReadPortB (PciIo, IoPortForBmis);
1164     if (((RegisterValue & BMIS_ERROR) != 0) || (Timeout == 0)) {
1165       DEBUG ((EFI_D_ERROR, "ATA UDMA operation fails\n"));
1166       Status = EFI_DEVICE_ERROR;
1167       break;
1168     }
1169 
1170     if ((RegisterValue & BMIS_INTERRUPT) != 0) {
1171       Status = EFI_SUCCESS;
1172       break;
1173     }
1174     //
1175     // Stall for 100 microseconds.
1176     //
1177     MicroSecondDelay (100);
1178     Delay--;
1179   } while (InfiniteWait || (Delay > 0));
1180 
1181   return Status;
1182 }
1183 
1184 /**
1185   Check if the memory to be set.
1186 
1187   @param[in]  PciIo           The PCI IO protocol instance.
1188   @param[in]  Task            Optional. Pointer to the ATA_NONBLOCK_TASK
1189                               used by non-blocking mode.
1190   @param[in]  IdeRegisters    A pointer to EFI_IDE_REGISTERS data structure.
1191 
1192   @retval EFI_DEVICE_ERROR  The memory setting met a issue.
1193   @retval EFI_NOT_READY     The memory is not set.
1194   @retval EFI_TIMEOUT       The memory setting is time out.
1195   @retval EFI_SUCCESS       The memory is correct set.
1196 
1197 **/
1198 EFI_STATUS
AtaUdmStatusCheck(IN EFI_PCI_IO_PROTOCOL * PciIo,IN ATA_NONBLOCK_TASK * Task,IN EFI_IDE_REGISTERS * IdeRegisters)1199 AtaUdmStatusCheck (
1200   IN     EFI_PCI_IO_PROTOCOL        *PciIo,
1201   IN     ATA_NONBLOCK_TASK          *Task,
1202   IN     EFI_IDE_REGISTERS          *IdeRegisters
1203  )
1204 {
1205   UINT8          RegisterValue;
1206   UINT16         IoPortForBmis;
1207   EFI_STATUS     Status;
1208 
1209   Task->RetryTimes--;
1210 
1211   Status = CheckStatusRegister (PciIo, IdeRegisters);
1212   if (EFI_ERROR (Status)) {
1213     return EFI_DEVICE_ERROR;
1214   }
1215 
1216   IoPortForBmis = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET);
1217   RegisterValue = IdeReadPortB (PciIo, IoPortForBmis);
1218 
1219   if ((RegisterValue & BMIS_ERROR) != 0) {
1220     DEBUG ((EFI_D_ERROR, "ATA UDMA operation fails\n"));
1221     return EFI_DEVICE_ERROR;
1222   }
1223 
1224   if ((RegisterValue & BMIS_INTERRUPT) != 0) {
1225     return EFI_SUCCESS;
1226   }
1227 
1228   if (!Task->InfiniteWait && (Task->RetryTimes == 0)) {
1229     return EFI_TIMEOUT;
1230   } else {
1231     //
1232     // The memory is not set.
1233     //
1234     return EFI_NOT_READY;
1235   }
1236 }
1237 
1238 /**
1239   Perform an ATA Udma operation (Read, ReadExt, Write, WriteExt).
1240 
1241   @param[in]      Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data
1242                                    structure.
1243   @param[in]      IdeRegisters     A pointer to EFI_IDE_REGISTERS data structure.
1244   @param[in]      Read             Flag used to determine the data transfer
1245                                    direction. Read equals 1, means data transferred
1246                                    from device to host;Read equals 0, means data
1247                                    transferred from host to device.
1248   @param[in]      DataBuffer       A pointer to the source buffer for the data.
1249   @param[in]      DataLength       The length of  the data.
1250   @param[in]      AtaCommandBlock  A pointer to EFI_ATA_COMMAND_BLOCK data structure.
1251   @param[in, out] AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
1252   @param[in]      Timeout          The time to complete the command, uses 100ns as a unit.
1253   @param[in]      Task             Optional. Pointer to the ATA_NONBLOCK_TASK
1254                                    used by non-blocking mode.
1255 
1256   @retval EFI_SUCCESS          the operation is successful.
1257   @retval EFI_OUT_OF_RESOURCES Build PRD table failed
1258   @retval EFI_UNSUPPORTED      Unknown channel or operations command
1259   @retval EFI_DEVICE_ERROR     Ata command execute failed
1260 
1261 **/
1262 EFI_STATUS
1263 EFIAPI
AtaUdmaInOut(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN EFI_IDE_REGISTERS * IdeRegisters,IN BOOLEAN Read,IN VOID * DataBuffer,IN UINT64 DataLength,IN EFI_ATA_COMMAND_BLOCK * AtaCommandBlock,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock,IN UINT64 Timeout,IN ATA_NONBLOCK_TASK * Task)1264 AtaUdmaInOut (
1265   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
1266   IN     EFI_IDE_REGISTERS             *IdeRegisters,
1267   IN     BOOLEAN                       Read,
1268   IN     VOID                          *DataBuffer,
1269   IN     UINT64                        DataLength,
1270   IN     EFI_ATA_COMMAND_BLOCK         *AtaCommandBlock,
1271   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock,
1272   IN     UINT64                        Timeout,
1273   IN     ATA_NONBLOCK_TASK             *Task
1274   )
1275 {
1276   EFI_STATUS                    Status;
1277   UINT16                        IoPortForBmic;
1278   UINT16                        IoPortForBmis;
1279   UINT16                        IoPortForBmid;
1280 
1281   UINTN                         PrdTableSize;
1282   EFI_PHYSICAL_ADDRESS          PrdTableMapAddr;
1283   VOID                          *PrdTableMap;
1284   EFI_PHYSICAL_ADDRESS          PrdTableBaseAddr;
1285   EFI_ATA_DMA_PRD               *TempPrdBaseAddr;
1286   UINTN                         PrdTableNum;
1287 
1288   UINT8                         RegisterValue;
1289   UINTN                         PageCount;
1290   UINTN                         ByteCount;
1291   UINTN                         ByteRemaining;
1292   UINT8                         DeviceControl;
1293 
1294   VOID                          *BufferMap;
1295   EFI_PHYSICAL_ADDRESS          BufferMapAddress;
1296   EFI_PCI_IO_PROTOCOL_OPERATION PciIoOperation;
1297 
1298   UINT8                         DeviceHead;
1299   EFI_PCI_IO_PROTOCOL           *PciIo;
1300   EFI_TPL                       OldTpl;
1301 
1302   UINTN                         AlignmentMask;
1303   UINTN                         RealPageCount;
1304   EFI_PHYSICAL_ADDRESS          BaseAddr;
1305   EFI_PHYSICAL_ADDRESS          BaseMapAddr;
1306 
1307   Status        = EFI_SUCCESS;
1308   PrdTableMap   = NULL;
1309   BufferMap     = NULL;
1310   PageCount     = 0;
1311   RealPageCount = 0;
1312   BaseAddr      = 0;
1313   PciIo         = Instance->PciIo;
1314 
1315   if ((PciIo == NULL) || (IdeRegisters == NULL) || (DataBuffer == NULL) || (AtaCommandBlock == NULL)) {
1316     return EFI_INVALID_PARAMETER;
1317   }
1318 
1319   //
1320   // Before starting the Blocking BlockIO operation, push to finish all non-blocking
1321   // BlockIO tasks.
1322   // Delay 1ms to simulate the blocking time out checking.
1323   //
1324   OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
1325   while ((Task == NULL) && (!IsListEmpty (&Instance->NonBlockingTaskList))) {
1326     AsyncNonBlockingTransferRoutine (NULL, Instance);
1327     //
1328     // Stall for 1 milliseconds.
1329     //
1330     MicroSecondDelay (1000);
1331   }
1332   gBS->RestoreTPL (OldTpl);
1333 
1334   //
1335   // The data buffer should be even alignment
1336   //
1337   if (((UINTN)DataBuffer & 0x1) != 0) {
1338     return EFI_INVALID_PARAMETER;
1339   }
1340 
1341   //
1342   // Set relevant IO Port address.
1343   //
1344   IoPortForBmic = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIC_OFFSET);
1345   IoPortForBmis = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET);
1346   IoPortForBmid = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMID_OFFSET);
1347 
1348   //
1349   // For Blocking mode, start the command.
1350   // For non-blocking mode, when the command is not started, start it, otherwise
1351   // go to check the status.
1352   //
1353   if (((Task != NULL) && (!Task->IsStart)) || (Task == NULL)) {
1354     //
1355     // Calculate the number of PRD entry.
1356     // Every entry in PRD table can specify a 64K memory region.
1357     //
1358     PrdTableNum   = (UINTN)(RShiftU64(DataLength, 16) + 1);
1359 
1360     //
1361     // Make sure that the memory region of PRD table is not cross 64K boundary
1362     //
1363     PrdTableSize = PrdTableNum * sizeof (EFI_ATA_DMA_PRD);
1364     if (PrdTableSize > 0x10000) {
1365       return EFI_INVALID_PARAMETER;
1366     }
1367 
1368     //
1369     // Allocate buffer for PRD table initialization.
1370     // Note Ide Bus Master spec said the descriptor table must be aligned on a 4 byte
1371     // boundary and the table cannot cross a 64K boundary in memory.
1372     //
1373     PageCount     = EFI_SIZE_TO_PAGES (PrdTableSize);
1374     RealPageCount = PageCount + EFI_SIZE_TO_PAGES (SIZE_64KB);
1375 
1376     //
1377     // Make sure that PageCount plus EFI_SIZE_TO_PAGES (SIZE_64KB) does not overflow.
1378     //
1379     ASSERT (RealPageCount > PageCount);
1380 
1381     Status    = PciIo->AllocateBuffer (
1382                          PciIo,
1383                          AllocateAnyPages,
1384                          EfiBootServicesData,
1385                          RealPageCount,
1386                          (VOID **)&BaseAddr,
1387                          0
1388                          );
1389     if (EFI_ERROR (Status)) {
1390       return EFI_OUT_OF_RESOURCES;
1391     }
1392 
1393     ByteCount = EFI_PAGES_TO_SIZE (RealPageCount);
1394     Status    = PciIo->Map (
1395                          PciIo,
1396                          EfiPciIoOperationBusMasterCommonBuffer,
1397                          (VOID*)(UINTN)BaseAddr,
1398                          &ByteCount,
1399                          &BaseMapAddr,
1400                          &PrdTableMap
1401                          );
1402     if (EFI_ERROR (Status) || (ByteCount != EFI_PAGES_TO_SIZE (RealPageCount))) {
1403       //
1404       // If the data length actually mapped is not equal to the requested amount,
1405       // it means the DMA operation may be broken into several discontinuous smaller chunks.
1406       // Can't handle this case.
1407       //
1408       PciIo->FreeBuffer (PciIo, RealPageCount, (VOID*)(UINTN)BaseAddr);
1409       return EFI_OUT_OF_RESOURCES;
1410     }
1411 
1412     ZeroMem ((VOID *) ((UINTN) BaseAddr), ByteCount);
1413 
1414     //
1415     // Calculate the 64K align address as PRD Table base address.
1416     //
1417     AlignmentMask    = SIZE_64KB - 1;
1418     PrdTableBaseAddr = ((UINTN) BaseAddr + AlignmentMask) & ~AlignmentMask;
1419     PrdTableMapAddr  = ((UINTN) BaseMapAddr + AlignmentMask) & ~AlignmentMask;
1420 
1421     //
1422     // Map the host address of DataBuffer to DMA master address.
1423     //
1424     if (Read) {
1425       PciIoOperation = EfiPciIoOperationBusMasterWrite;
1426     } else {
1427       PciIoOperation = EfiPciIoOperationBusMasterRead;
1428     }
1429 
1430     ByteCount = (UINTN)DataLength;
1431     Status    = PciIo->Map (
1432                          PciIo,
1433                          PciIoOperation,
1434                          DataBuffer,
1435                          &ByteCount,
1436                          &BufferMapAddress,
1437                          &BufferMap
1438                          );
1439     if (EFI_ERROR (Status) || (ByteCount != DataLength)) {
1440       PciIo->Unmap (PciIo, PrdTableMap);
1441       PciIo->FreeBuffer (PciIo, RealPageCount, (VOID*)(UINTN)BaseAddr);
1442       return EFI_OUT_OF_RESOURCES;
1443     }
1444 
1445     //
1446     // According to Ata spec, it requires the buffer address and size to be even.
1447     //
1448     ASSERT ((BufferMapAddress & 0x1) == 0);
1449     ASSERT ((ByteCount & 0x1) == 0);
1450 
1451     //
1452     // Fill the PRD table with appropriate bus master address of data buffer and data length.
1453     //
1454     ByteRemaining   = ByteCount;
1455     TempPrdBaseAddr = (EFI_ATA_DMA_PRD*)(UINTN)PrdTableBaseAddr;
1456     while (ByteRemaining != 0) {
1457       if (ByteRemaining <= 0x10000) {
1458         TempPrdBaseAddr->RegionBaseAddr = (UINT32) ((UINTN) BufferMapAddress);
1459         TempPrdBaseAddr->ByteCount      = (UINT16) ByteRemaining;
1460         TempPrdBaseAddr->EndOfTable     = 0x8000;
1461         break;
1462       }
1463 
1464       TempPrdBaseAddr->RegionBaseAddr = (UINT32) ((UINTN) BufferMapAddress);
1465       TempPrdBaseAddr->ByteCount      = (UINT16) 0x0;
1466 
1467       ByteRemaining    -= 0x10000;
1468       BufferMapAddress += 0x10000;
1469       TempPrdBaseAddr++;
1470     }
1471 
1472     //
1473     // Start to enable the DMA operation
1474     //
1475     DeviceHead = AtaCommandBlock->AtaDeviceHead;
1476 
1477     IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8)(0xe0 | DeviceHead));
1478 
1479     //
1480     // Enable interrupt to support UDMA
1481     //
1482     DeviceControl = 0;
1483     IdeWritePortB (PciIo, IdeRegisters->AltOrDev, DeviceControl);
1484 
1485     //
1486     // Read BMIS register and clear ERROR and INTR bit
1487     //
1488     RegisterValue  = IdeReadPortB(PciIo, IoPortForBmis);
1489     RegisterValue |= (BMIS_INTERRUPT | BMIS_ERROR);
1490     IdeWritePortB (PciIo, IoPortForBmis, RegisterValue);
1491 
1492     //
1493     // Set the base address to BMID register
1494     //
1495     IdeWritePortDW (PciIo, IoPortForBmid, (UINT32)PrdTableMapAddr);
1496 
1497     //
1498     // Set BMIC register to identify the operation direction
1499     //
1500     RegisterValue = IdeReadPortB(PciIo, IoPortForBmic);
1501     if (Read) {
1502       RegisterValue |= BMIC_NREAD;
1503     } else {
1504       RegisterValue &= ~((UINT8) BMIC_NREAD);
1505     }
1506     IdeWritePortB (PciIo, IoPortForBmic, RegisterValue);
1507 
1508     if (Task != NULL) {
1509       Task->Map            = BufferMap;
1510       Task->TableMap       = PrdTableMap;
1511       Task->MapBaseAddress = (EFI_ATA_DMA_PRD*)(UINTN)BaseAddr;
1512       Task->PageCount      = RealPageCount;
1513       Task->IsStart        = TRUE;
1514     }
1515 
1516     //
1517     // Issue ATA command
1518     //
1519     Status = AtaIssueCommand (PciIo, IdeRegisters, AtaCommandBlock, Timeout);
1520 
1521     if (EFI_ERROR (Status)) {
1522       Status = EFI_DEVICE_ERROR;
1523       goto Exit;
1524     }
1525 
1526     Status = CheckStatusRegister (PciIo, IdeRegisters);
1527     if (EFI_ERROR (Status)) {
1528       Status = EFI_DEVICE_ERROR;
1529       goto Exit;
1530     }
1531     //
1532     // Set START bit of BMIC register
1533     //
1534     RegisterValue  = IdeReadPortB(PciIo, IoPortForBmic);
1535     RegisterValue |= BMIC_START;
1536     IdeWritePortB(PciIo, IoPortForBmic, RegisterValue);
1537 
1538   }
1539 
1540   //
1541   // Check the INTERRUPT and ERROR bit of BMIS
1542   //
1543   if (Task != NULL) {
1544     Status = AtaUdmStatusCheck (PciIo, Task, IdeRegisters);
1545   } else {
1546     Status = AtaUdmStatusWait (PciIo, IdeRegisters, Timeout);
1547   }
1548 
1549   //
1550   // For blocking mode, clear registers and free buffers.
1551   // For non blocking mode, when the related registers have been set or time
1552   // out, or a error has been happened, it needs to clear the register and free
1553   // buffer.
1554   //
1555   if ((Task == NULL) || Status != EFI_NOT_READY) {
1556     //
1557     // Read BMIS register and clear ERROR and INTR bit
1558     //
1559     RegisterValue  = IdeReadPortB (PciIo, IoPortForBmis);
1560     RegisterValue |= (BMIS_INTERRUPT | BMIS_ERROR);
1561     IdeWritePortB (PciIo, IoPortForBmis, RegisterValue);
1562 
1563     //
1564     // Read Status Register of IDE device to clear interrupt
1565     //
1566     RegisterValue  = IdeReadPortB(PciIo, IdeRegisters->CmdOrStatus);
1567 
1568     //
1569     // Clear START bit of BMIC register
1570     //
1571     RegisterValue  = IdeReadPortB(PciIo, IoPortForBmic);
1572     RegisterValue &= ~((UINT8) BMIC_START);
1573     IdeWritePortB (PciIo, IoPortForBmic, RegisterValue);
1574 
1575     //
1576     // Disable interrupt of Select device
1577     //
1578     DeviceControl  = IdeReadPortB (PciIo, IdeRegisters->AltOrDev);
1579     DeviceControl |= ATA_CTLREG_IEN_L;
1580     IdeWritePortB (PciIo, IdeRegisters->AltOrDev, DeviceControl);
1581     //
1582     // Stall for 10 milliseconds.
1583     //
1584     MicroSecondDelay (10000);
1585 
1586   }
1587 
1588 Exit:
1589   //
1590   // Free all allocated resource
1591   //
1592   if ((Task == NULL) || Status != EFI_NOT_READY) {
1593     if (Task != NULL) {
1594       PciIo->Unmap (PciIo, Task->TableMap);
1595       PciIo->FreeBuffer (PciIo, Task->PageCount, Task->MapBaseAddress);
1596       PciIo->Unmap (PciIo, Task->Map);
1597     } else {
1598       PciIo->Unmap (PciIo, PrdTableMap);
1599       PciIo->FreeBuffer (PciIo, RealPageCount, (VOID*)(UINTN)BaseAddr);
1600       PciIo->Unmap (PciIo, BufferMap);
1601     }
1602 
1603     //
1604     // Dump All Ide registers to ATA_STATUS_BLOCK
1605     //
1606     DumpAllIdeRegisters (PciIo, IdeRegisters, AtaStatusBlock);
1607   }
1608 
1609   return Status;
1610 }
1611 
1612 /**
1613   This function reads the pending data in the device.
1614 
1615   @param PciIo         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
1616   @param IdeRegisters  A pointer to EFI_IDE_REGISTERS data structure.
1617 
1618   @retval EFI_SUCCESS   Successfully read.
1619   @retval EFI_NOT_READY The BSY is set avoiding reading.
1620 
1621 **/
1622 EFI_STATUS
1623 EFIAPI
AtaPacketReadPendingData(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters)1624 AtaPacketReadPendingData (
1625   IN  EFI_PCI_IO_PROTOCOL       *PciIo,
1626   IN  EFI_IDE_REGISTERS         *IdeRegisters
1627   )
1628 {
1629   UINT8     AltRegister;
1630   UINT16    TempWordBuffer;
1631 
1632   AltRegister = IdeReadPortB (PciIo, IdeRegisters->AltOrDev);
1633   if ((AltRegister & ATA_STSREG_BSY) == ATA_STSREG_BSY) {
1634     return EFI_NOT_READY;
1635   }
1636 
1637   if ((AltRegister & (ATA_STSREG_BSY | ATA_STSREG_DRQ)) == ATA_STSREG_DRQ) {
1638     TempWordBuffer = IdeReadPortB (PciIo, IdeRegisters->AltOrDev);
1639     while ((TempWordBuffer & (ATA_STSREG_BSY | ATA_STSREG_DRQ)) == ATA_STSREG_DRQ) {
1640       IdeReadPortWMultiple (
1641         PciIo,
1642         IdeRegisters->Data,
1643         1,
1644         &TempWordBuffer
1645         );
1646       TempWordBuffer = IdeReadPortB (PciIo, IdeRegisters->AltOrDev);
1647     }
1648   }
1649   return EFI_SUCCESS;
1650 }
1651 
1652 /**
1653   This function is called by AtaPacketCommandExecute().
1654   It is used to transfer data between host and device. The data direction is specified
1655   by the fourth parameter.
1656 
1657   @param PciIo         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
1658   @param IdeRegisters  A pointer to EFI_IDE_REGISTERS data structure.
1659   @param Buffer        Buffer contained data transferred between host and device.
1660   @param ByteCount     Data size in byte unit of the buffer.
1661   @param Read          Flag used to determine the data transfer direction.
1662                        Read equals 1, means data transferred from device to host;
1663                        Read equals 0, means data transferred from host to device.
1664   @param Timeout       Timeout value for wait DRQ ready before each data stream's transfer
1665                        , uses 100ns as a unit.
1666 
1667   @retval EFI_SUCCESS      data is transferred successfully.
1668   @retval EFI_DEVICE_ERROR the device failed to transfer data.
1669 **/
1670 EFI_STATUS
1671 EFIAPI
AtaPacketReadWrite(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN OUT VOID * Buffer,IN OUT UINT32 * ByteCount,IN BOOLEAN Read,IN UINT64 Timeout)1672 AtaPacketReadWrite (
1673   IN     EFI_PCI_IO_PROTOCOL       *PciIo,
1674   IN     EFI_IDE_REGISTERS         *IdeRegisters,
1675   IN OUT VOID                      *Buffer,
1676   IN OUT UINT32                    *ByteCount,
1677   IN     BOOLEAN                   Read,
1678   IN     UINT64                    Timeout
1679   )
1680 {
1681   UINT32      RequiredWordCount;
1682   UINT32      ActualWordCount;
1683   UINT32      WordCount;
1684   EFI_STATUS  Status;
1685   UINT16      *PtrBuffer;
1686 
1687   PtrBuffer         = Buffer;
1688   RequiredWordCount = *ByteCount >> 1;
1689 
1690   //
1691   // No data transfer is premitted.
1692   //
1693   if (RequiredWordCount == 0) {
1694     return EFI_SUCCESS;
1695   }
1696 
1697   //
1698   // ActualWordCount means the word count of data really transferred.
1699   //
1700   ActualWordCount = 0;
1701 
1702   while (ActualWordCount < RequiredWordCount) {
1703     //
1704     // before each data transfer stream, the host should poll DRQ bit ready,
1705     // to see whether indicates device is ready to transfer data.
1706     //
1707     Status = DRQReady2 (PciIo, IdeRegisters, Timeout);
1708     if (EFI_ERROR (Status)) {
1709       if (Status == EFI_NOT_READY) {
1710         //
1711         // Device provided less data than we intended to read, or wanted less
1712         // data than we intended to write, but it may still be successful.
1713         //
1714         break;
1715       } else {
1716         return Status;
1717       }
1718     }
1719 
1720     //
1721     // get current data transfer size from Cylinder Registers.
1722     //
1723     WordCount  = IdeReadPortB (PciIo, IdeRegisters->CylinderMsb) << 8;
1724     WordCount  = WordCount | IdeReadPortB (PciIo, IdeRegisters->CylinderLsb);
1725     WordCount  = WordCount & 0xffff;
1726     WordCount /= 2;
1727 
1728     WordCount = MIN (WordCount, (RequiredWordCount - ActualWordCount));
1729 
1730     if (Read) {
1731       IdeReadPortWMultiple (
1732         PciIo,
1733         IdeRegisters->Data,
1734         WordCount,
1735         PtrBuffer
1736         );
1737     } else {
1738       IdeWritePortWMultiple (
1739         PciIo,
1740         IdeRegisters->Data,
1741         WordCount,
1742         PtrBuffer
1743         );
1744     }
1745 
1746     //
1747     // read status register to check whether error happens.
1748     //
1749     Status = CheckStatusRegister (PciIo, IdeRegisters);
1750     if (EFI_ERROR (Status)) {
1751       return EFI_DEVICE_ERROR;
1752     }
1753 
1754     PtrBuffer       += WordCount;
1755     ActualWordCount += WordCount;
1756   }
1757 
1758   if (Read) {
1759     //
1760     // In the case where the drive wants to send more data than we need to read,
1761     // the DRQ bit will be set and cause delays from DRQClear2().
1762     // We need to read data from the drive until it clears DRQ so we can move on.
1763     //
1764     AtaPacketReadPendingData (PciIo, IdeRegisters);
1765   }
1766 
1767   //
1768   // read status register to check whether error happens.
1769   //
1770   Status = CheckStatusRegister (PciIo, IdeRegisters);
1771   if (EFI_ERROR (Status)) {
1772     return EFI_DEVICE_ERROR;
1773   }
1774 
1775   //
1776   // After data transfer is completed, normally, DRQ bit should clear.
1777   //
1778   Status = DRQClear (PciIo, IdeRegisters, Timeout);
1779   if (EFI_ERROR (Status)) {
1780     return EFI_DEVICE_ERROR;
1781   }
1782 
1783   *ByteCount = ActualWordCount << 1;
1784   return Status;
1785 }
1786 
1787 /**
1788   This function is used to send out ATAPI commands conforms to the Packet Command
1789   with PIO Data In Protocol.
1790 
1791   @param[in] PciIo          Pointer to the EFI_PCI_IO_PROTOCOL instance
1792   @param[in] IdeRegisters   Pointer to EFI_IDE_REGISTERS which is used to
1793                             store the IDE i/o port registers' base addresses
1794   @param[in] Channel        The channel number of device.
1795   @param[in] Device         The device number of device.
1796   @param[in] Packet         A pointer to EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET data structure.
1797 
1798   @retval EFI_SUCCESS       send out the ATAPI packet command successfully
1799                             and device sends data successfully.
1800   @retval EFI_DEVICE_ERROR  the device failed to send data.
1801 
1802 **/
1803 EFI_STATUS
1804 EFIAPI
AtaPacketCommandExecute(IN EFI_PCI_IO_PROTOCOL * PciIo,IN EFI_IDE_REGISTERS * IdeRegisters,IN UINT8 Channel,IN UINT8 Device,IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET * Packet)1805 AtaPacketCommandExecute (
1806   IN  EFI_PCI_IO_PROTOCOL                           *PciIo,
1807   IN  EFI_IDE_REGISTERS                             *IdeRegisters,
1808   IN  UINT8                                         Channel,
1809   IN  UINT8                                         Device,
1810   IN  EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET    *Packet
1811   )
1812 {
1813   EFI_ATA_COMMAND_BLOCK       AtaCommandBlock;
1814   EFI_STATUS                  Status;
1815   UINT8                       Count;
1816   UINT8                       PacketCommand[12];
1817 
1818   ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
1819 
1820   //
1821   // Fill ATAPI Command Packet according to CDB.
1822   // For Atapi cmd, its length should be less than or equal to 12 bytes.
1823   //
1824   if (Packet->CdbLength > 12) {
1825     return EFI_INVALID_PARAMETER;
1826   }
1827 
1828   ZeroMem (PacketCommand, 12);
1829   CopyMem (PacketCommand, Packet->Cdb, Packet->CdbLength);
1830 
1831   //
1832   // No OVL; No DMA
1833   //
1834   AtaCommandBlock.AtaFeatures = 0x00;
1835   //
1836   // set the transfersize to ATAPI_MAX_BYTE_COUNT to let the device
1837   // determine how many data should be transferred.
1838   //
1839   AtaCommandBlock.AtaCylinderLow  = (UINT8) (ATAPI_MAX_BYTE_COUNT & 0x00ff);
1840   AtaCommandBlock.AtaCylinderHigh = (UINT8) (ATAPI_MAX_BYTE_COUNT >> 8);
1841   AtaCommandBlock.AtaDeviceHead   = (UINT8) (Device << 0x4);
1842   AtaCommandBlock.AtaCommand      = ATA_CMD_PACKET;
1843 
1844   IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8)(0xe0 | (Device << 0x4)));
1845   //
1846   //  Disable interrupt
1847   //
1848   IdeWritePortB (PciIo, IdeRegisters->AltOrDev, ATA_DEFAULT_CTL);
1849 
1850   //
1851   // Issue ATA PACKET command firstly
1852   //
1853   Status = AtaIssueCommand (PciIo, IdeRegisters, &AtaCommandBlock, Packet->Timeout);
1854   if (EFI_ERROR (Status)) {
1855     return Status;
1856   }
1857 
1858   Status = DRQReady (PciIo, IdeRegisters, Packet->Timeout);
1859   if (EFI_ERROR (Status)) {
1860     return Status;
1861   }
1862 
1863   //
1864   // Send out ATAPI command packet
1865   //
1866   for (Count = 0; Count < 6; Count++) {
1867     IdeWritePortW (PciIo, IdeRegisters->Data, *((UINT16*)PacketCommand + Count));
1868     //
1869     // Stall for 10 microseconds.
1870     //
1871     MicroSecondDelay (10);
1872   }
1873 
1874   //
1875   // Read/Write the data of ATAPI Command
1876   //
1877   if (Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_READ) {
1878     Status = AtaPacketReadWrite (
1879                PciIo,
1880                IdeRegisters,
1881                Packet->InDataBuffer,
1882                &Packet->InTransferLength,
1883                TRUE,
1884                Packet->Timeout
1885                );
1886   } else {
1887     Status = AtaPacketReadWrite (
1888                PciIo,
1889                IdeRegisters,
1890                Packet->OutDataBuffer,
1891                &Packet->OutTransferLength,
1892                FALSE,
1893                Packet->Timeout
1894                );
1895   }
1896 
1897   return Status;
1898 }
1899 
1900 
1901 /**
1902   Set the calculated Best transfer mode to a detected device.
1903 
1904   @param Instance               A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
1905   @param Channel                The channel number of device.
1906   @param Device                 The device number of device.
1907   @param TransferMode           A pointer to EFI_ATA_TRANSFER_MODE data structure.
1908   @param AtaStatusBlock         A pointer to EFI_ATA_STATUS_BLOCK data structure.
1909 
1910   @retval EFI_SUCCESS          Set transfer mode successfully.
1911   @retval EFI_DEVICE_ERROR     Set transfer mode failed.
1912   @retval EFI_OUT_OF_RESOURCES Allocate memory failed.
1913 
1914 **/
1915 EFI_STATUS
1916 EFIAPI
SetDeviceTransferMode(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 Channel,IN UINT8 Device,IN EFI_ATA_TRANSFER_MODE * TransferMode,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)1917 SetDeviceTransferMode (
1918   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
1919   IN     UINT8                         Channel,
1920   IN     UINT8                         Device,
1921   IN     EFI_ATA_TRANSFER_MODE         *TransferMode,
1922   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock
1923   )
1924 {
1925   EFI_STATUS              Status;
1926   EFI_ATA_COMMAND_BLOCK   AtaCommandBlock;
1927 
1928   ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
1929 
1930   AtaCommandBlock.AtaCommand     = ATA_CMD_SET_FEATURES;
1931   AtaCommandBlock.AtaDeviceHead  = (UINT8)(Device << 0x4);
1932   AtaCommandBlock.AtaFeatures    = 0x03;
1933   AtaCommandBlock.AtaSectorCount = *((UINT8 *)TransferMode);
1934 
1935   //
1936   // Send SET FEATURE command (sub command 0x03) to set pio mode.
1937   //
1938   Status = AtaNonDataCommandIn (
1939              Instance->PciIo,
1940              &Instance->IdeRegisters[Channel],
1941              &AtaCommandBlock,
1942              AtaStatusBlock,
1943              ATA_ATAPI_TIMEOUT,
1944              NULL
1945              );
1946 
1947   return Status;
1948 }
1949 
1950 /**
1951   Set drive parameters for devices not support PACKETS command.
1952 
1953   @param Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
1954   @param Channel          The channel number of device.
1955   @param Device           The device number of device.
1956   @param DriveParameters  A pointer to EFI_ATA_DRIVE_PARMS data structure.
1957   @param AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
1958 
1959   @retval EFI_SUCCESS          Set drive parameter successfully.
1960   @retval EFI_DEVICE_ERROR     Set drive parameter failed.
1961   @retval EFI_OUT_OF_RESOURCES Allocate memory failed.
1962 
1963 **/
1964 EFI_STATUS
1965 EFIAPI
SetDriveParameters(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 Channel,IN UINT8 Device,IN EFI_ATA_DRIVE_PARMS * DriveParameters,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)1966 SetDriveParameters (
1967   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
1968   IN     UINT8                         Channel,
1969   IN     UINT8                         Device,
1970   IN     EFI_ATA_DRIVE_PARMS           *DriveParameters,
1971   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock
1972   )
1973 {
1974   EFI_STATUS              Status;
1975   EFI_ATA_COMMAND_BLOCK   AtaCommandBlock;
1976 
1977   ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
1978 
1979   AtaCommandBlock.AtaCommand     = ATA_CMD_INIT_DRIVE_PARAM;
1980   AtaCommandBlock.AtaSectorCount = DriveParameters->Sector;
1981   AtaCommandBlock.AtaDeviceHead  = (UINT8) ((Device << 0x4) + DriveParameters->Heads);
1982 
1983   //
1984   // Send Init drive parameters
1985   //
1986   Status = AtaNonDataCommandIn (
1987              Instance->PciIo,
1988              &Instance->IdeRegisters[Channel],
1989              &AtaCommandBlock,
1990              AtaStatusBlock,
1991              ATA_ATAPI_TIMEOUT,
1992              NULL
1993              );
1994 
1995   //
1996   // Send Set Multiple parameters
1997   //
1998   AtaCommandBlock.AtaCommand     = ATA_CMD_SET_MULTIPLE_MODE;
1999   AtaCommandBlock.AtaSectorCount = DriveParameters->MultipleSector;
2000   AtaCommandBlock.AtaDeviceHead  = (UINT8)(Device << 0x4);
2001 
2002   Status = AtaNonDataCommandIn (
2003              Instance->PciIo,
2004              &Instance->IdeRegisters[Channel],
2005              &AtaCommandBlock,
2006              AtaStatusBlock,
2007              ATA_ATAPI_TIMEOUT,
2008              NULL
2009              );
2010 
2011   return Status;
2012 }
2013 
2014 /**
2015   Send SMART Return Status command to check if the execution of SMART cmd is successful or not.
2016 
2017   @param Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
2018   @param Channel          The channel number of device.
2019   @param Device           The device number of device.
2020   @param AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
2021 
2022   @retval EFI_SUCCESS     Successfully get the return status of S.M.A.R.T command execution.
2023   @retval Others          Fail to get return status data.
2024 
2025 **/
2026 EFI_STATUS
2027 EFIAPI
IdeAtaSmartReturnStatusCheck(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 Channel,IN UINT8 Device,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)2028 IdeAtaSmartReturnStatusCheck (
2029   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
2030   IN     UINT8                         Channel,
2031   IN     UINT8                         Device,
2032   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock
2033   )
2034 {
2035   EFI_STATUS              Status;
2036   EFI_ATA_COMMAND_BLOCK   AtaCommandBlock;
2037   UINT8                   LBAMid;
2038   UINT8                   LBAHigh;
2039 
2040   ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
2041 
2042   AtaCommandBlock.AtaCommand      = ATA_CMD_SMART;
2043   AtaCommandBlock.AtaFeatures     = ATA_SMART_RETURN_STATUS;
2044   AtaCommandBlock.AtaCylinderLow  = ATA_CONSTANT_4F;
2045   AtaCommandBlock.AtaCylinderHigh = ATA_CONSTANT_C2;
2046   AtaCommandBlock.AtaDeviceHead   = (UINT8) ((Device << 0x4) | 0xe0);
2047 
2048   //
2049   // Send S.M.A.R.T Read Return Status command to device
2050   //
2051   Status = AtaNonDataCommandIn (
2052              Instance->PciIo,
2053              &Instance->IdeRegisters[Channel],
2054              &AtaCommandBlock,
2055              AtaStatusBlock,
2056              ATA_ATAPI_TIMEOUT,
2057              NULL
2058              );
2059 
2060   if (EFI_ERROR (Status)) {
2061     REPORT_STATUS_CODE (
2062       EFI_ERROR_CODE | EFI_ERROR_MINOR,
2063       (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_DISABLED)
2064       );
2065     return EFI_DEVICE_ERROR;
2066   }
2067 
2068   REPORT_STATUS_CODE (
2069     EFI_PROGRESS_CODE,
2070     (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_ENABLE)
2071     );
2072 
2073   LBAMid  = IdeReadPortB (Instance->PciIo, Instance->IdeRegisters[Channel].CylinderLsb);
2074   LBAHigh = IdeReadPortB (Instance->PciIo, Instance->IdeRegisters[Channel].CylinderMsb);
2075 
2076   if ((LBAMid == 0x4f) && (LBAHigh == 0xc2)) {
2077     //
2078     // The threshold exceeded condition is not detected by the device
2079     //
2080     DEBUG ((EFI_D_INFO, "The S.M.A.R.T threshold exceeded condition is not detected\n"));
2081     REPORT_STATUS_CODE (
2082           EFI_PROGRESS_CODE,
2083           (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_UNDERTHRESHOLD)
2084           );
2085   } else if ((LBAMid == 0xf4) && (LBAHigh == 0x2c)) {
2086     //
2087     // The threshold exceeded condition is detected by the device
2088     //
2089     DEBUG ((EFI_D_INFO, "The S.M.A.R.T threshold exceeded condition is detected\n"));
2090     REPORT_STATUS_CODE (
2091          EFI_PROGRESS_CODE,
2092          (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_OVERTHRESHOLD)
2093          );
2094   }
2095 
2096   return EFI_SUCCESS;
2097 }
2098 
2099 /**
2100   Enable SMART command of the disk if supported.
2101 
2102   @param Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
2103   @param Channel          The channel number of device.
2104   @param Device           The device number of device.
2105   @param IdentifyData     A pointer to data buffer which is used to contain IDENTIFY data.
2106   @param AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
2107 
2108 **/
2109 VOID
2110 EFIAPI
IdeAtaSmartSupport(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 Channel,IN UINT8 Device,IN EFI_IDENTIFY_DATA * IdentifyData,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)2111 IdeAtaSmartSupport (
2112   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
2113   IN     UINT8                         Channel,
2114   IN     UINT8                         Device,
2115   IN     EFI_IDENTIFY_DATA             *IdentifyData,
2116   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock
2117   )
2118 {
2119   EFI_STATUS              Status;
2120   EFI_ATA_COMMAND_BLOCK   AtaCommandBlock;
2121 
2122   //
2123   // Detect if the device supports S.M.A.R.T.
2124   //
2125   if ((IdentifyData->AtaData.command_set_supported_82 & 0x0001) != 0x0001) {
2126     //
2127     // S.M.A.R.T is not supported by the device
2128     //
2129     DEBUG ((EFI_D_INFO, "S.M.A.R.T feature is not supported at [%a] channel [%a] device!\n",
2130             (Channel == 1) ? "secondary" : "primary", (Device == 1) ? "slave" : "master"));
2131     REPORT_STATUS_CODE (
2132       EFI_ERROR_CODE | EFI_ERROR_MINOR,
2133       (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_NOTSUPPORTED)
2134       );
2135   } else {
2136     //
2137     // Check if the feature is enabled. If not, then enable S.M.A.R.T.
2138     //
2139     if ((IdentifyData->AtaData.command_set_feature_enb_85 & 0x0001) != 0x0001) {
2140 
2141       REPORT_STATUS_CODE (
2142         EFI_PROGRESS_CODE,
2143         (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_DISABLE)
2144         );
2145 
2146       ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
2147 
2148       AtaCommandBlock.AtaCommand      = ATA_CMD_SMART;
2149       AtaCommandBlock.AtaFeatures     = ATA_SMART_ENABLE_OPERATION;
2150       AtaCommandBlock.AtaCylinderLow  = ATA_CONSTANT_4F;
2151       AtaCommandBlock.AtaCylinderHigh = ATA_CONSTANT_C2;
2152       AtaCommandBlock.AtaDeviceHead   = (UINT8) ((Device << 0x4) | 0xe0);
2153 
2154       //
2155       // Send S.M.A.R.T Enable command to device
2156       //
2157       Status = AtaNonDataCommandIn (
2158                  Instance->PciIo,
2159                  &Instance->IdeRegisters[Channel],
2160                  &AtaCommandBlock,
2161                  AtaStatusBlock,
2162                  ATA_ATAPI_TIMEOUT,
2163                  NULL
2164                  );
2165 
2166       if (!EFI_ERROR (Status)) {
2167         //
2168         // Send S.M.A.R.T AutoSave command to device
2169         //
2170         ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
2171 
2172         AtaCommandBlock.AtaCommand      = ATA_CMD_SMART;
2173         AtaCommandBlock.AtaFeatures     = 0xD2;
2174         AtaCommandBlock.AtaSectorCount  = 0xF1;
2175         AtaCommandBlock.AtaCylinderLow  = ATA_CONSTANT_4F;
2176         AtaCommandBlock.AtaCylinderHigh = ATA_CONSTANT_C2;
2177         AtaCommandBlock.AtaDeviceHead   = (UINT8) ((Device << 0x4) | 0xe0);
2178 
2179         Status = AtaNonDataCommandIn (
2180                    Instance->PciIo,
2181                    &Instance->IdeRegisters[Channel],
2182                    &AtaCommandBlock,
2183                    AtaStatusBlock,
2184                    ATA_ATAPI_TIMEOUT,
2185                    NULL
2186                    );
2187         if (!EFI_ERROR (Status)) {
2188           Status = IdeAtaSmartReturnStatusCheck (
2189                      Instance,
2190                      Channel,
2191                      Device,
2192                      AtaStatusBlock
2193                      );
2194         }
2195       }
2196     }
2197 
2198     DEBUG ((EFI_D_INFO, "Enabled S.M.A.R.T feature at [%a] channel [%a] device!\n",
2199            (Channel == 1) ? "secondary" : "primary", (Device == 1) ? "slave" : "master"));
2200 
2201   }
2202 
2203   return ;
2204 }
2205 
2206 
2207 /**
2208   Sends out an ATA Identify Command to the specified device.
2209 
2210   This function is called by DiscoverIdeDevice() during its device
2211   identification. It sends out the ATA Identify Command to the
2212   specified device. Only ATA device responses to this command. If
2213   the command succeeds, it returns the Identify data structure which
2214   contains information about the device. This function extracts the
2215   information it needs to fill the IDE_BLK_IO_DEV data structure,
2216   including device type, media block size, media capacity, and etc.
2217 
2218   @param Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
2219   @param Channel          The channel number of device.
2220   @param Device           The device number of device.
2221   @param Buffer           A pointer to data buffer which is used to contain IDENTIFY data.
2222   @param AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
2223 
2224   @retval EFI_SUCCESS          Identify ATA device successfully.
2225   @retval EFI_DEVICE_ERROR     ATA Identify Device Command failed or device is not ATA device.
2226   @retval EFI_OUT_OF_RESOURCES Allocate memory failed.
2227 
2228 **/
2229 EFI_STATUS
2230 EFIAPI
AtaIdentify(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 Channel,IN UINT8 Device,IN OUT EFI_IDENTIFY_DATA * Buffer,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)2231 AtaIdentify (
2232   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
2233   IN     UINT8                         Channel,
2234   IN     UINT8                         Device,
2235   IN OUT EFI_IDENTIFY_DATA             *Buffer,
2236   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock
2237   )
2238 {
2239   EFI_STATUS             Status;
2240   EFI_ATA_COMMAND_BLOCK  AtaCommandBlock;
2241 
2242   ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
2243 
2244   AtaCommandBlock.AtaCommand    = ATA_CMD_IDENTIFY_DRIVE;
2245   AtaCommandBlock.AtaDeviceHead = (UINT8)(Device << 0x4);
2246 
2247   Status = AtaPioDataInOut (
2248              Instance->PciIo,
2249              &Instance->IdeRegisters[Channel],
2250              Buffer,
2251              sizeof (EFI_IDENTIFY_DATA),
2252              TRUE,
2253              &AtaCommandBlock,
2254              AtaStatusBlock,
2255              ATA_ATAPI_TIMEOUT,
2256              NULL
2257              );
2258 
2259   return Status;
2260 }
2261 
2262 /**
2263   This function is called by DiscoverIdeDevice() during its device
2264   identification.
2265   Its main purpose is to get enough information for the device media
2266   to fill in the Media data structure of the Block I/O Protocol interface.
2267 
2268   There are 5 steps to reach such objective:
2269   1. Sends out the ATAPI Identify Command to the specified device.
2270   Only ATAPI device responses to this command. If the command succeeds,
2271   it returns the Identify data structure which filled with information
2272   about the device. Since the ATAPI device contains removable media,
2273   the only meaningful information is the device module name.
2274   2. Sends out ATAPI Inquiry Packet Command to the specified device.
2275   This command will return inquiry data of the device, which contains
2276   the device type information.
2277   3. Allocate sense data space for future use. We don't detect the media
2278   presence here to improvement boot performance, especially when CD
2279   media is present. The media detection will be performed just before
2280   each BLK_IO read/write
2281 
2282   @param Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
2283   @param Channel          The channel number of device.
2284   @param Device           The device number of device.
2285   @param Buffer           A pointer to data buffer which is used to contain IDENTIFY data.
2286   @param AtaStatusBlock   A pointer to EFI_ATA_STATUS_BLOCK data structure.
2287 
2288   @retval EFI_SUCCESS          Identify ATAPI device successfully.
2289   @retval EFI_DEVICE_ERROR     ATA Identify Packet Device Command failed or device type
2290                                is not supported by this IDE driver.
2291   @retval EFI_OUT_OF_RESOURCES Allocate memory failed.
2292 
2293 **/
2294 EFI_STATUS
2295 EFIAPI
AtaIdentifyPacket(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 Channel,IN UINT8 Device,IN OUT EFI_IDENTIFY_DATA * Buffer,IN OUT EFI_ATA_STATUS_BLOCK * AtaStatusBlock)2296 AtaIdentifyPacket (
2297   IN     ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
2298   IN     UINT8                         Channel,
2299   IN     UINT8                         Device,
2300   IN OUT EFI_IDENTIFY_DATA             *Buffer,
2301   IN OUT EFI_ATA_STATUS_BLOCK          *AtaStatusBlock
2302   )
2303 {
2304   EFI_STATUS             Status;
2305   EFI_ATA_COMMAND_BLOCK  AtaCommandBlock;
2306 
2307   ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK));
2308 
2309   AtaCommandBlock.AtaCommand    = ATA_CMD_IDENTIFY_DEVICE;
2310   AtaCommandBlock.AtaDeviceHead = (UINT8)(Device << 0x4);
2311 
2312   //
2313   // Send ATAPI Identify Command to get IDENTIFY data.
2314   //
2315   Status = AtaPioDataInOut (
2316              Instance->PciIo,
2317              &Instance->IdeRegisters[Channel],
2318              (VOID *) Buffer,
2319              sizeof (EFI_IDENTIFY_DATA),
2320              TRUE,
2321              &AtaCommandBlock,
2322              AtaStatusBlock,
2323              ATA_ATAPI_TIMEOUT,
2324              NULL
2325              );
2326 
2327   return Status;
2328 }
2329 
2330 
2331 /**
2332   This function is used for detect whether the IDE device exists in the
2333   specified Channel as the specified Device Number.
2334 
2335   There is two IDE channels: one is Primary Channel, the other is
2336   Secondary Channel.(Channel is the logical name for the physical "Cable".)
2337   Different channel has different register group.
2338 
2339   On each IDE channel, at most two IDE devices attach,
2340   one is called Device 0 (Master device), the other is called Device 1
2341   (Slave device). The devices on the same channel co-use the same register
2342   group, so before sending out a command for a specified device via command
2343   register, it is a must to select the current device to accept the command
2344   by set the device number in the Head/Device Register.
2345 
2346   @param Instance         A pointer to ATA_ATAPI_PASS_THRU_INSTANCE data structure.
2347   @param IdeChannel       The channel number of device.
2348 
2349   @retval EFI_SUCCESS successfully detects device.
2350   @retval other       any failure during detection process will return this value.
2351 
2352 **/
2353 EFI_STATUS
2354 EFIAPI
DetectAndConfigIdeDevice(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT8 IdeChannel)2355 DetectAndConfigIdeDevice (
2356   IN  ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
2357   IN  UINT8                         IdeChannel
2358   )
2359 {
2360   EFI_STATUS                        Status;
2361   UINT8                             SectorCountReg;
2362   UINT8                             LBALowReg;
2363   UINT8                             LBAMidReg;
2364   UINT8                             LBAHighReg;
2365   EFI_ATA_DEVICE_TYPE               DeviceType;
2366   UINT8                             IdeDevice;
2367   EFI_IDE_REGISTERS                 *IdeRegisters;
2368   EFI_IDENTIFY_DATA                 Buffer;
2369 
2370   EFI_IDE_CONTROLLER_INIT_PROTOCOL  *IdeInit;
2371   EFI_PCI_IO_PROTOCOL               *PciIo;
2372 
2373   EFI_ATA_COLLECTIVE_MODE           *SupportedModes;
2374   EFI_ATA_TRANSFER_MODE             TransferMode;
2375   EFI_ATA_DRIVE_PARMS               DriveParameters;
2376 
2377   IdeRegisters = &Instance->IdeRegisters[IdeChannel];
2378   IdeInit      = Instance->IdeControllerInit;
2379   PciIo        = Instance->PciIo;
2380 
2381   for (IdeDevice = 0; IdeDevice < EfiIdeMaxDevice; IdeDevice++) {
2382     //
2383     // Select Master or Slave device to get the return signature for ATA DEVICE DIAGNOSTIC cmd.
2384     //
2385     IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8)((IdeDevice << 4) | 0xe0));
2386 
2387     //
2388     // Send ATA Device Execut Diagnostic command.
2389     // This command should work no matter DRDY is ready or not
2390     //
2391     IdeWritePortB (PciIo, IdeRegisters->CmdOrStatus, ATA_CMD_EXEC_DRIVE_DIAG);
2392 
2393     Status = WaitForBSYClear (PciIo, IdeRegisters, 350000000);
2394     if (EFI_ERROR (Status)) {
2395       DEBUG((EFI_D_ERROR, "New detecting method: Send Execute Diagnostic Command: WaitForBSYClear: Status: %d\n", Status));
2396       continue;
2397     }
2398 
2399     //
2400     // Select Master or Slave device to get the return signature for ATA DEVICE DIAGNOSTIC cmd.
2401     //
2402     IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8)((IdeDevice << 4) | 0xe0));
2403     //
2404     // Stall for 1 milliseconds.
2405     //
2406     MicroSecondDelay (1000);
2407 
2408     SectorCountReg = IdeReadPortB (PciIo, IdeRegisters->SectorCount);
2409     LBALowReg      = IdeReadPortB (PciIo, IdeRegisters->SectorNumber);
2410     LBAMidReg      = IdeReadPortB (PciIo, IdeRegisters->CylinderLsb);
2411     LBAHighReg     = IdeReadPortB (PciIo, IdeRegisters->CylinderMsb);
2412 
2413     //
2414     // Refer to ATA/ATAPI 4 Spec, section 9.1
2415     //
2416     if ((SectorCountReg == 0x1) && (LBALowReg == 0x1) && (LBAMidReg == 0x0) && (LBAHighReg == 0x0)) {
2417       DeviceType = EfiIdeHarddisk;
2418     } else if ((LBAMidReg == 0x14) && (LBAHighReg == 0xeb)) {
2419       DeviceType = EfiIdeCdrom;
2420     } else {
2421       continue;
2422     }
2423 
2424     //
2425     // Send IDENTIFY cmd to the device to test if it is really attached.
2426     //
2427     if (DeviceType == EfiIdeHarddisk) {
2428       Status = AtaIdentify (Instance, IdeChannel, IdeDevice, &Buffer, NULL);
2429       //
2430       // if identifying ata device is failure, then try to send identify packet cmd.
2431       //
2432       if (EFI_ERROR (Status)) {
2433         REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_PERIPHERAL_FIXED_MEDIA | EFI_P_EC_NOT_DETECTED));
2434 
2435         DeviceType = EfiIdeCdrom;
2436         Status     = AtaIdentifyPacket (Instance, IdeChannel, IdeDevice, &Buffer, NULL);
2437       }
2438     } else {
2439       Status = AtaIdentifyPacket (Instance, IdeChannel, IdeDevice, &Buffer, NULL);
2440       //
2441       // if identifying atapi device is failure, then try to send identify cmd.
2442       //
2443       if (EFI_ERROR (Status)) {
2444         DeviceType = EfiIdeHarddisk;
2445         Status     = AtaIdentify (Instance, IdeChannel, IdeDevice, &Buffer, NULL);
2446       }
2447     }
2448 
2449     if (EFI_ERROR (Status)) {
2450       //
2451       // No device is found at this port
2452       //
2453       continue;
2454     }
2455 
2456     DEBUG ((EFI_D_INFO, "[%a] channel [%a] [%a] device\n",
2457             (IdeChannel == 1) ? "secondary" : "primary  ", (IdeDevice == 1) ? "slave " : "master",
2458             DeviceType == EfiIdeCdrom ? "cdrom   " : "harddisk"));
2459     //
2460     // If the device is a hard disk, then try to enable S.M.A.R.T feature
2461     //
2462     if ((DeviceType == EfiIdeHarddisk) && PcdGetBool (PcdAtaSmartEnable)) {
2463       IdeAtaSmartSupport (
2464         Instance,
2465         IdeChannel,
2466         IdeDevice,
2467         &Buffer,
2468         NULL
2469         );
2470     }
2471 
2472     //
2473     // Submit identify data to IDE controller init driver
2474     //
2475     IdeInit->SubmitData (IdeInit, IdeChannel, IdeDevice, &Buffer);
2476 
2477     //
2478     // Now start to config ide device parameter and transfer mode.
2479     //
2480     Status = IdeInit->CalculateMode (
2481                         IdeInit,
2482                         IdeChannel,
2483                         IdeDevice,
2484                         &SupportedModes
2485                         );
2486     if (EFI_ERROR (Status)) {
2487       DEBUG ((EFI_D_ERROR, "Calculate Mode Fail, Status = %r\n", Status));
2488       continue;
2489     }
2490 
2491     //
2492     // Set best supported PIO mode on this IDE device
2493     //
2494     if (SupportedModes->PioMode.Mode <= EfiAtaPioMode2) {
2495       TransferMode.ModeCategory = EFI_ATA_MODE_DEFAULT_PIO;
2496     } else {
2497       TransferMode.ModeCategory = EFI_ATA_MODE_FLOW_PIO;
2498     }
2499 
2500     TransferMode.ModeNumber = (UINT8) (SupportedModes->PioMode.Mode);
2501 
2502     if (SupportedModes->ExtModeCount == 0){
2503       Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL);
2504 
2505       if (EFI_ERROR (Status)) {
2506         DEBUG ((EFI_D_ERROR, "Set transfer Mode Fail, Status = %r\n", Status));
2507         continue;
2508       }
2509     }
2510 
2511     //
2512     // Set supported DMA mode on this IDE device. Note that UDMA & MDMA cann't
2513     // be set together. Only one DMA mode can be set to a device. If setting
2514     // DMA mode operation fails, we can continue moving on because we only use
2515     // PIO mode at boot time. DMA modes are used by certain kind of OS booting
2516     //
2517     if (SupportedModes->UdmaMode.Valid) {
2518       TransferMode.ModeCategory = EFI_ATA_MODE_UDMA;
2519       TransferMode.ModeNumber   = (UINT8) (SupportedModes->UdmaMode.Mode);
2520       Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL);
2521 
2522       if (EFI_ERROR (Status)) {
2523         DEBUG ((EFI_D_ERROR, "Set transfer Mode Fail, Status = %r\n", Status));
2524         continue;
2525       }
2526     } else if (SupportedModes->MultiWordDmaMode.Valid) {
2527       TransferMode.ModeCategory = EFI_ATA_MODE_MDMA;
2528       TransferMode.ModeNumber   = (UINT8) SupportedModes->MultiWordDmaMode.Mode;
2529       Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL);
2530 
2531       if (EFI_ERROR (Status)) {
2532         DEBUG ((EFI_D_ERROR, "Set transfer Mode Fail, Status = %r\n", Status));
2533         continue;
2534       }
2535     }
2536 
2537     //
2538     // Set Parameters for the device:
2539     // 1) Init
2540     // 2) Establish the block count for READ/WRITE MULTIPLE (EXT) command
2541     //
2542     if (DeviceType == EfiIdeHarddisk) {
2543       //
2544       // Init driver parameters
2545       //
2546       DriveParameters.Sector         = (UINT8) ((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->sectors_per_track;
2547       DriveParameters.Heads          = (UINT8) (((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->heads - 1);
2548       DriveParameters.MultipleSector = (UINT8) ((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->multi_sector_cmd_max_sct_cnt;
2549 
2550       Status = SetDriveParameters (Instance, IdeChannel, IdeDevice, &DriveParameters, NULL);
2551     }
2552 
2553     //
2554     // Set IDE controller Timing Blocks in the PCI Configuration Space
2555     //
2556     IdeInit->SetTiming (IdeInit, IdeChannel, IdeDevice, SupportedModes);
2557 
2558     //
2559     // IDE controller and IDE device timing is configured successfully.
2560     // Now insert the device into device list.
2561     //
2562     Status = CreateNewDeviceInfo (Instance, IdeChannel, IdeDevice, DeviceType, &Buffer);
2563     if (EFI_ERROR (Status)) {
2564       continue;
2565     }
2566 
2567     if (DeviceType == EfiIdeHarddisk) {
2568       REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_PERIPHERAL_FIXED_MEDIA | EFI_P_PC_ENABLE));
2569     }
2570   }
2571   return EFI_SUCCESS;
2572 }
2573 
2574 
2575 /**
2576   Initialize ATA host controller at IDE mode.
2577 
2578   The function is designed to initialize ATA host controller.
2579 
2580   @param[in]  Instance          A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.
2581 
2582 **/
2583 EFI_STATUS
2584 EFIAPI
IdeModeInitialization(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance)2585 IdeModeInitialization (
2586   IN  ATA_ATAPI_PASS_THRU_INSTANCE    *Instance
2587   )
2588 {
2589   EFI_STATUS                        Status;
2590   EFI_IDE_CONTROLLER_INIT_PROTOCOL  *IdeInit;
2591   EFI_PCI_IO_PROTOCOL               *PciIo;
2592   UINT8                             Channel;
2593   UINT8                             IdeChannel;
2594   BOOLEAN                           ChannelEnabled;
2595   UINT8                             MaxDevices;
2596 
2597   IdeInit = Instance->IdeControllerInit;
2598   PciIo   = Instance->PciIo;
2599   Channel = IdeInit->ChannelCount;
2600 
2601   //
2602   // Obtain IDE IO port registers' base addresses
2603   //
2604   Status = GetIdeRegisterIoAddr (PciIo, Instance->IdeRegisters);
2605   if (EFI_ERROR (Status)) {
2606     goto ErrorExit;
2607   }
2608 
2609   for (IdeChannel = 0; IdeChannel < Channel; IdeChannel++) {
2610     IdeInit->NotifyPhase (IdeInit, EfiIdeBeforeChannelEnumeration, IdeChannel);
2611 
2612     //
2613     // now obtain channel information fron IdeControllerInit protocol.
2614     //
2615     Status = IdeInit->GetChannelInfo (
2616                         IdeInit,
2617                         IdeChannel,
2618                         &ChannelEnabled,
2619                         &MaxDevices
2620                         );
2621     if (EFI_ERROR (Status)) {
2622       DEBUG ((EFI_D_ERROR, "[GetChannel, Status=%x]", Status));
2623       continue;
2624     }
2625 
2626     if (!ChannelEnabled) {
2627       continue;
2628     }
2629 
2630     ASSERT (MaxDevices <= 2);
2631     //
2632     // Now inform the IDE Controller Init Module.
2633     //
2634     IdeInit->NotifyPhase (IdeInit, EfiIdeBeforeChannelReset, IdeChannel);
2635 
2636     //
2637     // No reset channel function implemented.
2638     //
2639     IdeInit->NotifyPhase (IdeInit, EfiIdeAfterChannelReset, IdeChannel);
2640 
2641     //
2642     // Now inform the IDE Controller Init Module.
2643     //
2644     IdeInit->NotifyPhase (IdeInit, EfiIdeBusBeforeDevicePresenceDetection, IdeChannel);
2645 
2646     //
2647     // Detect all attached ATA devices and set the transfer mode for each device.
2648     //
2649     DetectAndConfigIdeDevice (Instance, IdeChannel);
2650   }
2651 
2652   //
2653   // All configurations done! Notify IdeController to do post initialization
2654   // work such as saving IDE controller PCI settings for S3 resume
2655   //
2656   IdeInit->NotifyPhase (IdeInit, EfiIdeBusPhaseMaximum, 0);
2657 
2658 ErrorExit:
2659   return Status;
2660 }
2661 
2662