1 /** @file
2   This driver module produces IDE_CONTROLLER_INIT protocol for Sata Controllers.
3 
4   Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
5   SPDX-License-Identifier: BSD-2-Clause-Patent
6 
7 **/
8 
9 #include "SataController.h"
10 
11 ///
12 /// EFI_DRIVER_BINDING_PROTOCOL instance
13 ///
14 EFI_DRIVER_BINDING_PROTOCOL gSataControllerDriverBinding = {
15   SataControllerSupported,
16   SataControllerStart,
17   SataControllerStop,
18   0xa,
19   NULL,
20   NULL
21 };
22 
23 /**
24   Read AHCI Operation register.
25 
26   @param PciIo      The PCI IO protocol instance.
27   @param Offset     The operation register offset.
28 
29   @return The register content read.
30 
31 **/
32 UINT32
33 EFIAPI
AhciReadReg(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT32 Offset)34 AhciReadReg (
35   IN EFI_PCI_IO_PROTOCOL    *PciIo,
36   IN UINT32                 Offset
37   )
38 {
39   UINT32    Data;
40 
41   ASSERT (PciIo != NULL);
42 
43   Data = 0;
44 
45   PciIo->Mem.Read (
46                PciIo,
47                EfiPciIoWidthUint32,
48                AHCI_BAR_INDEX,
49                (UINT64) Offset,
50                1,
51                &Data
52                );
53 
54   return Data;
55 }
56 
57 /**
58   Write AHCI Operation register.
59 
60   @param PciIo      The PCI IO protocol instance.
61   @param Offset     The operation register offset.
62   @param Data       The data used to write down.
63 
64 **/
65 VOID
66 EFIAPI
AhciWriteReg(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT32 Offset,IN UINT32 Data)67 AhciWriteReg (
68   IN EFI_PCI_IO_PROTOCOL    *PciIo,
69   IN UINT32                 Offset,
70   IN UINT32                 Data
71   )
72 {
73   ASSERT (PciIo != NULL);
74 
75   PciIo->Mem.Write (
76                PciIo,
77                EfiPciIoWidthUint32,
78                AHCI_BAR_INDEX,
79                (UINT64) Offset,
80                1,
81                &Data
82                );
83 
84   return;
85 }
86 
87 /**
88   This function is used to calculate the best PIO mode supported by specific IDE device
89 
90   @param IdentifyData   The identify data of specific IDE device.
91   @param DisPioMode     Disqualified PIO modes collection.
92   @param SelectedMode   Available PIO modes collection.
93 
94   @retval EFI_SUCCESS       Best PIO modes are returned.
95   @retval EFI_UNSUPPORTED   The device doesn't support PIO mode,
96                             or all supported modes have been disqualified.
97 **/
98 EFI_STATUS
CalculateBestPioMode(IN EFI_IDENTIFY_DATA * IdentifyData,IN UINT16 * DisPioMode OPTIONAL,OUT UINT16 * SelectedMode)99 CalculateBestPioMode (
100   IN EFI_IDENTIFY_DATA  *IdentifyData,
101   IN UINT16             *DisPioMode OPTIONAL,
102   OUT UINT16            *SelectedMode
103   )
104 {
105   UINT16    PioMode;
106   UINT16    AdvancedPioMode;
107   UINT16    Temp;
108   UINT16    Index;
109   UINT16    MinimumPioCycleTime;
110 
111   Temp = 0xff;
112 
113   PioMode = (UINT8) (((ATA5_IDENTIFY_DATA *) (&(IdentifyData->AtaData)))->pio_cycle_timing >> 8);
114 
115   //
116   // See whether Identify Data word 64 - 70 are valid
117   //
118   if ((IdentifyData->AtaData.field_validity & 0x02) == 0x02) {
119 
120     AdvancedPioMode = IdentifyData->AtaData.advanced_pio_modes;
121     DEBUG ((DEBUG_INFO, "CalculateBestPioMode: AdvancedPioMode = %x\n", AdvancedPioMode));
122 
123     for (Index = 0; Index < 8; Index++) {
124       if ((AdvancedPioMode & 0x01) != 0) {
125         Temp = Index;
126       }
127 
128       AdvancedPioMode >>= 1;
129     }
130 
131     //
132     // If Temp is modified, mean the advanced_pio_modes is not zero;
133     // if Temp is not modified, mean there is no advanced PIO mode supported,
134     // the best PIO Mode is the value in pio_cycle_timing.
135     //
136     if (Temp != 0xff) {
137       AdvancedPioMode = (UINT16) (Temp + 3);
138     } else {
139       AdvancedPioMode = PioMode;
140     }
141 
142     //
143     // Limit the PIO mode to at most PIO4.
144     //
145     PioMode = (UINT16) MIN (AdvancedPioMode, 4);
146 
147     MinimumPioCycleTime = IdentifyData->AtaData.min_pio_cycle_time_with_flow_control;
148 
149     if (MinimumPioCycleTime <= 120) {
150       PioMode = (UINT16) MIN (4, PioMode);
151     } else if (MinimumPioCycleTime <= 180) {
152       PioMode = (UINT16) MIN (3, PioMode);
153     } else if (MinimumPioCycleTime <= 240) {
154       PioMode = (UINT16) MIN (2, PioMode);
155     } else {
156       PioMode = 0;
157     }
158 
159     //
160     // Degrade the PIO mode if the mode has been disqualified
161     //
162     if (DisPioMode != NULL) {
163       if (*DisPioMode < 2) {
164         return EFI_UNSUPPORTED; // no mode below ATA_PIO_MODE_BELOW_2
165       }
166 
167       if (PioMode >= *DisPioMode) {
168         PioMode = (UINT16) (*DisPioMode - 1);
169       }
170     }
171 
172     if (PioMode < 2) {
173       *SelectedMode = 1;        // ATA_PIO_MODE_BELOW_2;
174     } else {
175       *SelectedMode = PioMode;  // ATA_PIO_MODE_2 to ATA_PIO_MODE_4;
176     }
177 
178   } else {
179     //
180     // Identify Data word 64 - 70 are not valid
181     // Degrade the PIO mode if the mode has been disqualified
182     //
183     if (DisPioMode != NULL) {
184       if (*DisPioMode < 2) {
185         return EFI_UNSUPPORTED; // no mode below ATA_PIO_MODE_BELOW_2
186       }
187 
188       if (PioMode == *DisPioMode) {
189         PioMode--;
190       }
191     }
192 
193     if (PioMode < 2) {
194       *SelectedMode = 1;        // ATA_PIO_MODE_BELOW_2;
195     } else {
196       *SelectedMode = 2;        // ATA_PIO_MODE_2;
197     }
198 
199   }
200 
201   return EFI_SUCCESS;
202 }
203 
204 /**
205   This function is used to calculate the best UDMA mode supported by specific IDE device
206 
207   @param IdentifyData   The identify data of specific IDE device.
208   @param DisUDmaMode     Disqualified UDMA modes collection.
209   @param SelectedMode   Available UDMA modes collection.
210 
211   @retval EFI_SUCCESS       Best UDMA modes are returned.
212   @retval EFI_UNSUPPORTED   The device doesn't support UDMA mode,
213                             or all supported modes have been disqualified.
214 **/
215 EFI_STATUS
CalculateBestUdmaMode(IN EFI_IDENTIFY_DATA * IdentifyData,IN UINT16 * DisUDmaMode OPTIONAL,OUT UINT16 * SelectedMode)216 CalculateBestUdmaMode (
217   IN EFI_IDENTIFY_DATA  *IdentifyData,
218   IN UINT16             *DisUDmaMode OPTIONAL,
219   OUT UINT16            *SelectedMode
220   )
221 {
222   UINT16    TempMode;
223   UINT16    DeviceUDmaMode;
224 
225   DeviceUDmaMode = 0;
226 
227   //
228   // Check whether the WORD 88 (supported UltraDMA by drive) is valid
229   //
230   if ((IdentifyData->AtaData.field_validity & 0x04) == 0x00) {
231     return EFI_UNSUPPORTED;
232   }
233 
234   DeviceUDmaMode = IdentifyData->AtaData.ultra_dma_mode;
235   DEBUG ((DEBUG_INFO, "CalculateBestUdmaMode: DeviceUDmaMode = %x\n", DeviceUDmaMode));
236   DeviceUDmaMode &= 0x3f;
237   TempMode = 0;                 // initialize it to UDMA-0
238 
239   while ((DeviceUDmaMode >>= 1) != 0) {
240     TempMode++;
241   }
242 
243   //
244   // Degrade the UDMA mode if the mode has been disqualified
245   //
246   if (DisUDmaMode != NULL) {
247     if (*DisUDmaMode == 0) {
248       *SelectedMode = 0;
249       return EFI_UNSUPPORTED;   // no mode below ATA_UDMA_MODE_0
250     }
251 
252     if (TempMode >= *DisUDmaMode) {
253       TempMode = (UINT16) (*DisUDmaMode - 1);
254     }
255   }
256 
257   //
258   // Possible returned mode is between ATA_UDMA_MODE_0 and ATA_UDMA_MODE_5
259   //
260   *SelectedMode = TempMode;
261 
262   return EFI_SUCCESS;
263 }
264 
265 /**
266   The Entry Point of module. It follows the standard UEFI driver model.
267 
268   @param[in] ImageHandle    The firmware allocated handle for the EFI image.
269   @param[in] SystemTable    A pointer to the EFI System Table.
270 
271   @retval EFI_SUCCESS   The entry point is executed successfully.
272   @retval other         Some error occurs when executing this entry point.
273 
274 **/
275 EFI_STATUS
276 EFIAPI
InitializeSataControllerDriver(IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE * SystemTable)277 InitializeSataControllerDriver (
278   IN EFI_HANDLE         ImageHandle,
279   IN EFI_SYSTEM_TABLE   *SystemTable
280   )
281 {
282   EFI_STATUS    Status;
283 
284   //
285   // Install driver model protocol(s).
286   //
287   Status = EfiLibInstallDriverBindingComponentName2 (
288              ImageHandle,
289              SystemTable,
290              &gSataControllerDriverBinding,
291              ImageHandle,
292              &gSataControllerComponentName,
293              &gSataControllerComponentName2
294              );
295   ASSERT_EFI_ERROR (Status);
296 
297   return Status;
298 }
299 
300 /**
301   Supported function of Driver Binding protocol for this driver.
302   Test to see if this driver supports ControllerHandle.
303 
304   @param This                   Protocol instance pointer.
305   @param Controller             Handle of device to test.
306   @param RemainingDevicePath    A pointer to the device path.
307                                 it should be ignored by device driver.
308 
309   @retval EFI_SUCCESS           This driver supports this device.
310   @retval EFI_ALREADY_STARTED   This driver is already running on this device.
311   @retval other                 This driver does not support this device.
312 
313 **/
314 EFI_STATUS
315 EFIAPI
SataControllerSupported(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath)316 SataControllerSupported (
317   IN EFI_DRIVER_BINDING_PROTOCOL    *This,
318   IN EFI_HANDLE                     Controller,
319   IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
320   )
321 {
322   EFI_STATUS            Status;
323   EFI_PCI_IO_PROTOCOL   *PciIo;
324   PCI_TYPE00            PciData;
325 
326   //
327   // Attempt to open PCI I/O Protocol
328   //
329   Status = gBS->OpenProtocol (
330                   Controller,
331                   &gEfiPciIoProtocolGuid,
332                   (VOID **) &PciIo,
333                   This->DriverBindingHandle,
334                   Controller,
335                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
336                   );
337   if (EFI_ERROR (Status)) {
338     return Status;
339   }
340 
341   //
342   // Now further check the PCI header: Base Class (offset 0x0B) and
343   // Sub Class (offset 0x0A). This controller should be an SATA controller
344   //
345   Status = PciIo->Pci.Read (
346                         PciIo,
347                         EfiPciIoWidthUint8,
348                         PCI_CLASSCODE_OFFSET,
349                         sizeof (PciData.Hdr.ClassCode),
350                         PciData.Hdr.ClassCode
351                         );
352   if (EFI_ERROR (Status)) {
353     return EFI_UNSUPPORTED;
354   }
355 
356   if (IS_PCI_IDE (&PciData) || IS_PCI_SATADPA (&PciData)) {
357     return EFI_SUCCESS;
358   }
359 
360   return EFI_UNSUPPORTED;
361 }
362 
363 /**
364   This routine is called right after the .Supported() called and
365   Start this driver on ControllerHandle.
366 
367   @param This                   Protocol instance pointer.
368   @param Controller             Handle of device to bind driver to.
369   @param RemainingDevicePath    A pointer to the device path.
370                                 it should be ignored by device driver.
371 
372   @retval EFI_SUCCESS           This driver is added to this device.
373   @retval EFI_ALREADY_STARTED   This driver is already running on this device.
374   @retval other                 Some error occurs when binding this driver to this device.
375 
376 **/
377 EFI_STATUS
378 EFIAPI
SataControllerStart(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath)379 SataControllerStart (
380   IN EFI_DRIVER_BINDING_PROTOCOL    *This,
381   IN EFI_HANDLE                     Controller,
382   IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
383   )
384 {
385   UINTN                             BailLogMask;
386   EFI_STATUS                        Status;
387   EFI_PCI_IO_PROTOCOL               *PciIo;
388   UINT64                            OriginalPciAttributes;
389   PCI_TYPE00                        PciData;
390   EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData;
391   UINT32                            Data32;
392   UINTN                             ChannelDeviceCount;
393 
394   DEBUG ((DEBUG_INFO, "SataControllerStart START\n"));
395 
396   BailLogMask = DEBUG_ERROR;
397   SataPrivateData = NULL;
398 
399   //
400   // Now test and open PCI I/O Protocol
401   //
402   Status = gBS->OpenProtocol (
403                   Controller,
404                   &gEfiPciIoProtocolGuid,
405                   (VOID **) &PciIo,
406                   This->DriverBindingHandle,
407                   Controller,
408                   EFI_OPEN_PROTOCOL_BY_DRIVER
409                   );
410   if (EFI_ERROR (Status)) {
411     if (Status == EFI_ALREADY_STARTED) {
412       //
413       // This is an expected condition for OpenProtocol() / BY_DRIVER, in a
414       // DriverBindingStart() member function; degrade the log mask to
415       // DEBUG_INFO.
416       //
417       BailLogMask = DEBUG_INFO;
418     }
419     goto Bail;
420   }
421 
422   //
423   // Save original PCI attributes, and enable IO space access, memory space
424   // access, and Bus Master (DMA).
425   //
426   Status = PciIo->Attributes (PciIo, EfiPciIoAttributeOperationGet, 0,
427                     &OriginalPciAttributes);
428   if (EFI_ERROR (Status)) {
429     goto ClosePciIo;
430   }
431   Status = PciIo->Attributes (PciIo, EfiPciIoAttributeOperationEnable,
432                     EFI_PCI_DEVICE_ENABLE, NULL);
433   if (EFI_ERROR (Status)) {
434     goto ClosePciIo;
435   }
436 
437   //
438   // Allocate Sata Private Data structure
439   //
440   SataPrivateData = AllocateZeroPool (sizeof (EFI_SATA_CONTROLLER_PRIVATE_DATA));
441   if (SataPrivateData == NULL) {
442     Status = EFI_OUT_OF_RESOURCES;
443     goto RestorePciAttributes;
444   }
445 
446   //
447   // Initialize Sata Private Data
448   //
449   SataPrivateData->Signature = SATA_CONTROLLER_SIGNATURE;
450   SataPrivateData->PciIo = PciIo;
451   SataPrivateData->OriginalPciAttributes = OriginalPciAttributes;
452   SataPrivateData->IdeInit.GetChannelInfo = IdeInitGetChannelInfo;
453   SataPrivateData->IdeInit.NotifyPhase = IdeInitNotifyPhase;
454   SataPrivateData->IdeInit.SubmitData = IdeInitSubmitData;
455   SataPrivateData->IdeInit.DisqualifyMode = IdeInitDisqualifyMode;
456   SataPrivateData->IdeInit.CalculateMode = IdeInitCalculateMode;
457   SataPrivateData->IdeInit.SetTiming = IdeInitSetTiming;
458   SataPrivateData->IdeInit.EnumAll = SATA_ENUMER_ALL;
459 
460   Status = PciIo->Pci.Read (
461                         PciIo,
462                         EfiPciIoWidthUint8,
463                         PCI_CLASSCODE_OFFSET,
464                         sizeof (PciData.Hdr.ClassCode),
465                         PciData.Hdr.ClassCode
466                         );
467   if (EFI_ERROR (Status)) {
468     goto FreeSataPrivateData;
469   }
470 
471   if (IS_PCI_IDE (&PciData)) {
472     SataPrivateData->IdeInit.ChannelCount = IDE_MAX_CHANNEL;
473     SataPrivateData->DeviceCount = IDE_MAX_DEVICES;
474   } else if (IS_PCI_SATADPA (&PciData)) {
475     //
476     // Read Host Capability Register(CAP) to get Number of Ports(NPS) and Supports Port Multiplier(SPM)
477     //   NPS is 0's based value indicating the maximum number of ports supported by the HBA silicon.
478     //   A maximum of 32 ports can be supported. A value of '0h', indicating one port, is the minimum requirement.
479     //
480     Data32 = AhciReadReg (PciIo, R_AHCI_CAP);
481     SataPrivateData->IdeInit.ChannelCount = (UINT8) ((Data32 & B_AHCI_CAP_NPS) + 1);
482     SataPrivateData->DeviceCount = AHCI_MAX_DEVICES;
483     if ((Data32 & B_AHCI_CAP_SPM) == B_AHCI_CAP_SPM) {
484       SataPrivateData->DeviceCount = AHCI_MULTI_MAX_DEVICES;
485     }
486   }
487 
488   ChannelDeviceCount = (UINTN) (SataPrivateData->IdeInit.ChannelCount) * (UINTN) (SataPrivateData->DeviceCount);
489   SataPrivateData->DisqualifiedModes = AllocateZeroPool ((sizeof (EFI_ATA_COLLECTIVE_MODE)) * ChannelDeviceCount);
490   if (SataPrivateData->DisqualifiedModes == NULL) {
491     Status = EFI_OUT_OF_RESOURCES;
492     goto FreeSataPrivateData;
493   }
494 
495   SataPrivateData->IdentifyData = AllocateZeroPool ((sizeof (EFI_IDENTIFY_DATA)) * ChannelDeviceCount);
496   if (SataPrivateData->IdentifyData == NULL) {
497     Status = EFI_OUT_OF_RESOURCES;
498     goto FreeDisqualifiedModes;
499   }
500 
501   SataPrivateData->IdentifyValid = AllocateZeroPool ((sizeof (BOOLEAN)) * ChannelDeviceCount);
502   if (SataPrivateData->IdentifyValid == NULL) {
503     Status = EFI_OUT_OF_RESOURCES;
504     goto FreeIdentifyData;
505   }
506 
507   //
508   // Install IDE Controller Init Protocol to this instance
509   //
510   Status = gBS->InstallMultipleProtocolInterfaces (
511                   &Controller,
512                   &gEfiIdeControllerInitProtocolGuid,
513                   &(SataPrivateData->IdeInit),
514                   NULL
515                   );
516 
517   if (EFI_ERROR (Status)) {
518     goto FreeIdentifyValid;
519   }
520 
521   DEBUG ((DEBUG_INFO, "SataControllerStart END status = %r\n", Status));
522   return Status;
523 
524 FreeIdentifyValid:
525   FreePool (SataPrivateData->IdentifyValid);
526 
527 FreeIdentifyData:
528   FreePool (SataPrivateData->IdentifyData);
529 
530 FreeDisqualifiedModes:
531   FreePool (SataPrivateData->DisqualifiedModes);
532 
533 FreeSataPrivateData:
534   FreePool (SataPrivateData);
535 
536 RestorePciAttributes:
537   PciIo->Attributes (PciIo, EfiPciIoAttributeOperationSet,
538            OriginalPciAttributes, NULL);
539 
540 ClosePciIo:
541   gBS->CloseProtocol (
542          Controller,
543          &gEfiPciIoProtocolGuid,
544          This->DriverBindingHandle,
545          Controller
546          );
547 
548 Bail:
549   DEBUG ((BailLogMask, "SataControllerStart error return status = %r\n",
550     Status));
551   return Status;
552 }
553 
554 /**
555   Stop this driver on ControllerHandle.
556 
557   @param This               Protocol instance pointer.
558   @param Controller         Handle of device to stop driver on.
559   @param NumberOfChildren   Not used.
560   @param ChildHandleBuffer  Not used.
561 
562   @retval EFI_SUCCESS   This driver is removed from this device.
563   @retval other         Some error occurs when removing this driver from this device.
564 
565 **/
566 EFI_STATUS
567 EFIAPI
SataControllerStop(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN UINTN NumberOfChildren,IN EFI_HANDLE * ChildHandleBuffer)568 SataControllerStop (
569   IN EFI_DRIVER_BINDING_PROTOCOL    *This,
570   IN EFI_HANDLE                     Controller,
571   IN UINTN                          NumberOfChildren,
572   IN EFI_HANDLE                     *ChildHandleBuffer
573   )
574 {
575   EFI_STATUS                        Status;
576   EFI_IDE_CONTROLLER_INIT_PROTOCOL  *IdeInit;
577   EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData;
578   EFI_PCI_IO_PROTOCOL               *PciIo;
579   UINT64                            OriginalPciAttributes;
580 
581   //
582   // Open the produced protocol
583   //
584   Status = gBS->OpenProtocol (
585                   Controller,
586                   &gEfiIdeControllerInitProtocolGuid,
587                   (VOID **) &IdeInit,
588                   This->DriverBindingHandle,
589                   Controller,
590                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
591                   );
592   if (EFI_ERROR (Status)) {
593     return EFI_UNSUPPORTED;
594   }
595 
596   SataPrivateData = SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS (IdeInit);
597   ASSERT (SataPrivateData != NULL);
598 
599   PciIo                 = SataPrivateData->PciIo;
600   OriginalPciAttributes = SataPrivateData->OriginalPciAttributes;
601 
602   //
603   // Uninstall the IDE Controller Init Protocol from this instance
604   //
605   Status = gBS->UninstallMultipleProtocolInterfaces (
606                   Controller,
607                   &gEfiIdeControllerInitProtocolGuid,
608                   &(SataPrivateData->IdeInit),
609                   NULL
610                   );
611   if (EFI_ERROR (Status)) {
612     return Status;
613   }
614 
615   if (SataPrivateData->DisqualifiedModes != NULL) {
616     FreePool (SataPrivateData->DisqualifiedModes);
617   }
618   if (SataPrivateData->IdentifyData != NULL) {
619     FreePool (SataPrivateData->IdentifyData);
620   }
621   if (SataPrivateData->IdentifyValid != NULL) {
622     FreePool (SataPrivateData->IdentifyValid);
623   }
624   FreePool (SataPrivateData);
625 
626   //
627   // Restore original PCI attributes
628   //
629   PciIo->Attributes (
630            PciIo,
631            EfiPciIoAttributeOperationSet,
632            OriginalPciAttributes,
633            NULL
634            );
635 
636   //
637   // Close protocols opened by Sata Controller driver
638   //
639   return gBS->CloseProtocol (
640                 Controller,
641                 &gEfiPciIoProtocolGuid,
642                 This->DriverBindingHandle,
643                 Controller
644                 );
645 }
646 
647 /**
648   Calculate the flat array subscript of a (Channel, Device) pair.
649 
650   @param[in] SataPrivateData  The private data structure corresponding to the
651                               SATA controller that attaches the device for
652                               which the flat array subscript is being
653                               calculated.
654 
655   @param[in] Channel          The channel (ie. port) number on the SATA
656                               controller that the device is attached to.
657 
658   @param[in] Device           The device number on the channel.
659 
660   @return  The flat array subscript suitable for indexing DisqualifiedModes,
661            IdentifyData, and IdentifyValid.
662 **/
663 STATIC
664 UINTN
FlatDeviceIndex(IN CONST EFI_SATA_CONTROLLER_PRIVATE_DATA * SataPrivateData,IN UINTN Channel,IN UINTN Device)665 FlatDeviceIndex (
666   IN CONST EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData,
667   IN UINTN                                   Channel,
668   IN UINTN                                   Device
669   )
670 {
671   ASSERT (SataPrivateData != NULL);
672   ASSERT (Channel < SataPrivateData->IdeInit.ChannelCount);
673   ASSERT (Device < SataPrivateData->DeviceCount);
674 
675   return Channel * SataPrivateData->DeviceCount + Device;
676 }
677 
678 //
679 // Interface functions of IDE_CONTROLLER_INIT protocol
680 //
681 /**
682   Returns the information about the specified IDE channel.
683 
684   This function can be used to obtain information about a particular IDE channel.
685   The driver entity uses this information during the enumeration process.
686 
687   If Enabled is set to FALSE, the driver entity will not scan the channel. Note
688   that it will not prevent an operating system driver from scanning the channel.
689 
690   For most of today's controllers, MaxDevices will either be 1 or 2. For SATA
691   controllers, this value will always be 1. SATA configurations can contain SATA
692   port multipliers. SATA port multipliers behave like SATA bridges and can support
693   up to 16 devices on the other side. If a SATA port out of the IDE controller
694   is connected to a port multiplier, MaxDevices will be set to the number of SATA
695   devices that the port multiplier supports. Because today's port multipliers
696   support up to fifteen SATA devices, this number can be as large as fifteen. The IDE
697   bus driver is required to scan for the presence of port multipliers behind an SATA
698   controller and enumerate up to MaxDevices number of devices behind the port
699   multiplier.
700 
701   In this context, the devices behind a port multiplier constitute a channel.
702 
703   @param[in]  This         The pointer to the EFI_IDE_CONTROLLER_INIT_PROTOCOL instance.
704   @param[in]  Channel      Zero-based channel number.
705   @param[out] Enabled      TRUE if this channel is enabled.  Disabled channels
706                            are not scanned to see if any devices are present.
707   @param[out] MaxDevices   The maximum number of IDE devices that the bus driver
708                            can expect on this channel.  For the ATA/ATAPI
709                            specification, version 6, this number will either be
710                            one or two. For Serial ATA (SATA) configurations with a
711                            port multiplier, this number can be as large as fifteen.
712 
713   @retval EFI_SUCCESS             Information was returned without any errors.
714   @retval EFI_INVALID_PARAMETER   Channel is invalid (Channel >= ChannelCount).
715 
716 **/
717 EFI_STATUS
718 EFIAPI
IdeInitGetChannelInfo(IN EFI_IDE_CONTROLLER_INIT_PROTOCOL * This,IN UINT8 Channel,OUT BOOLEAN * Enabled,OUT UINT8 * MaxDevices)719 IdeInitGetChannelInfo (
720   IN EFI_IDE_CONTROLLER_INIT_PROTOCOL   *This,
721   IN UINT8                              Channel,
722   OUT BOOLEAN                           *Enabled,
723   OUT UINT8                             *MaxDevices
724   )
725 {
726   EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData;
727   SataPrivateData = SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS (This);
728   ASSERT (SataPrivateData != NULL);
729 
730   if (Channel < This->ChannelCount) {
731     *Enabled = TRUE;
732     *MaxDevices = SataPrivateData->DeviceCount;
733     return EFI_SUCCESS;
734   }
735 
736   *Enabled = FALSE;
737   return EFI_INVALID_PARAMETER;
738 }
739 
740 /**
741   The notifications from the driver entity that it is about to enter a certain
742   phase of the IDE channel enumeration process.
743 
744   This function can be used to notify the IDE controller driver to perform
745   specific actions, including any chipset-specific initialization, so that the
746   chipset is ready to enter the next phase. Seven notification points are defined
747   at this time.
748 
749   More synchronization points may be added as required in the future.
750 
751   @param[in] This      The pointer to the EFI_IDE_CONTROLLER_INIT_PROTOCOL instance.
752   @param[in] Phase     The phase during enumeration.
753   @param[in] Channel   Zero-based channel number.
754 
755   @retval EFI_SUCCESS             The notification was accepted without any errors.
756   @retval EFI_UNSUPPORTED         Phase is not supported.
757   @retval EFI_INVALID_PARAMETER   Channel is invalid (Channel >= ChannelCount).
758   @retval EFI_NOT_READY           This phase cannot be entered at this time; for
759                                   example, an attempt was made to enter a Phase
760                                   without having entered one or more previous
761                                   Phase.
762 
763 **/
764 EFI_STATUS
765 EFIAPI
IdeInitNotifyPhase(IN EFI_IDE_CONTROLLER_INIT_PROTOCOL * This,IN EFI_IDE_CONTROLLER_ENUM_PHASE Phase,IN UINT8 Channel)766 IdeInitNotifyPhase (
767   IN EFI_IDE_CONTROLLER_INIT_PROTOCOL   *This,
768   IN EFI_IDE_CONTROLLER_ENUM_PHASE      Phase,
769   IN UINT8                              Channel
770   )
771 {
772   return EFI_SUCCESS;
773 }
774 
775 /**
776   Submits the device information to the IDE controller driver.
777 
778   This function is used by the driver entity to pass detailed information about
779   a particular device to the IDE controller driver. The driver entity obtains
780   this information by issuing an ATA or ATAPI IDENTIFY_DEVICE command. IdentifyData
781   is the pointer to the response data buffer. The IdentifyData buffer is owned
782   by the driver entity, and the IDE controller driver must make a local copy
783   of the entire buffer or parts of the buffer as needed. The original IdentifyData
784   buffer pointer may not be valid when
785 
786     - EFI_IDE_CONTROLLER_INIT_PROTOCOL.CalculateMode() or
787     - EFI_IDE_CONTROLLER_INIT_PROTOCOL.DisqualifyMode() is called at a later point.
788 
789   The IDE controller driver may consult various fields of EFI_IDENTIFY_DATA to
790   compute the optimum mode for the device. These fields are not limited to the
791   timing information. For example, an implementation of the IDE controller driver
792   may examine the vendor and type/mode field to match known bad drives.
793 
794   The driver entity may submit drive information in any order, as long as it
795   submits information for all the devices belonging to the enumeration group
796   before EFI_IDE_CONTROLLER_INIT_PROTOCOL.CalculateMode() is called for any device
797   in that enumeration group. If a device is absent, EFI_IDE_CONTROLLER_INIT_PROTOCOL.SubmitData()
798   should be called with IdentifyData set to NULL.  The IDE controller driver may
799   not have any other mechanism to know whether a device is present or not. Therefore,
800   setting IdentifyData to NULL does not constitute an error condition.
801   EFI_IDE_CONTROLLER_INIT_PROTOCOL.SubmitData() can be called only once for a
802   given (Channel, Device) pair.
803 
804   @param[in] This           A pointer to the EFI_IDE_CONTROLLER_INIT_PROTOCOL instance.
805   @param[in] Channel        Zero-based channel number.
806   @param[in] Device         Zero-based device number on the Channel.
807   @param[in] IdentifyData   The device's response to the ATA IDENTIFY_DEVICE command.
808 
809   @retval EFI_SUCCESS             The information was accepted without any errors.
810   @retval EFI_INVALID_PARAMETER   Channel is invalid (Channel >= ChannelCount).
811   @retval EFI_INVALID_PARAMETER   Device is invalid.
812 
813 **/
814 EFI_STATUS
815 EFIAPI
IdeInitSubmitData(IN EFI_IDE_CONTROLLER_INIT_PROTOCOL * This,IN UINT8 Channel,IN UINT8 Device,IN EFI_IDENTIFY_DATA * IdentifyData)816 IdeInitSubmitData (
817   IN EFI_IDE_CONTROLLER_INIT_PROTOCOL   *This,
818   IN UINT8                              Channel,
819   IN UINT8                              Device,
820   IN EFI_IDENTIFY_DATA                  *IdentifyData
821   )
822 {
823   EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData;
824   UINTN                             DeviceIndex;
825 
826   SataPrivateData = SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS (This);
827   ASSERT (SataPrivateData != NULL);
828 
829   if ((Channel >= This->ChannelCount) || (Device >= SataPrivateData->DeviceCount)) {
830     return EFI_INVALID_PARAMETER;
831   }
832 
833   DeviceIndex = FlatDeviceIndex (SataPrivateData, Channel, Device);
834 
835   //
836   // Make a local copy of device's IdentifyData and mark the valid flag
837   //
838   if (IdentifyData != NULL) {
839     CopyMem (
840       &(SataPrivateData->IdentifyData[DeviceIndex]),
841       IdentifyData,
842       sizeof (EFI_IDENTIFY_DATA)
843       );
844 
845     SataPrivateData->IdentifyValid[DeviceIndex] = TRUE;
846   } else {
847     SataPrivateData->IdentifyValid[DeviceIndex] = FALSE;
848   }
849 
850   return EFI_SUCCESS;
851 }
852 
853 /**
854   Disqualifies specific modes for an IDE device.
855 
856   This function allows the driver entity or other drivers (such as platform
857   drivers) to reject certain timing modes and request the IDE controller driver
858   to recalculate modes. This function allows the driver entity and the IDE
859   controller driver to negotiate the timings on a per-device basis. This function
860   is useful in the case of drives that lie about their capabilities. An example
861   is when the IDE device fails to accept the timing modes that are calculated
862   by the IDE controller driver based on the response to the Identify Drive command.
863 
864   If the driver entity does not want to limit the ATA timing modes and leave that
865   decision to the IDE controller driver, it can either not call this function for
866   the given device or call this function and set the Valid flag to FALSE for all
867   modes that are listed in EFI_ATA_COLLECTIVE_MODE.
868 
869   The driver entity may disqualify modes for a device in any order and any number
870   of times.
871 
872   This function can be called multiple times to invalidate multiple modes of the
873   same type (e.g., Programmed Input/Output [PIO] modes 3 and 4). See the ATA/ATAPI
874   specification for more information on PIO modes.
875 
876   For Serial ATA (SATA) controllers, this member function can be used to disqualify
877   a higher transfer rate mode on a given channel. For example, a platform driver
878   may inform the IDE controller driver to not use second-generation (Gen2) speeds
879   for a certain SATA drive.
880 
881   @param[in] This       The pointer to the EFI_IDE_CONTROLLER_INIT_PROTOCOL instance.
882   @param[in] Channel    The zero-based channel number.
883   @param[in] Device     The zero-based device number on the Channel.
884   @param[in] BadModes   The modes that the device does not support and that
885                         should be disqualified.
886 
887   @retval EFI_SUCCESS             The modes were accepted without any errors.
888   @retval EFI_INVALID_PARAMETER   Channel is invalid (Channel >= ChannelCount).
889   @retval EFI_INVALID_PARAMETER   Device is invalid.
890   @retval EFI_INVALID_PARAMETER   IdentifyData is NULL.
891 
892 **/
893 EFI_STATUS
894 EFIAPI
IdeInitDisqualifyMode(IN EFI_IDE_CONTROLLER_INIT_PROTOCOL * This,IN UINT8 Channel,IN UINT8 Device,IN EFI_ATA_COLLECTIVE_MODE * BadModes)895 IdeInitDisqualifyMode (
896   IN EFI_IDE_CONTROLLER_INIT_PROTOCOL   *This,
897   IN UINT8                              Channel,
898   IN UINT8                              Device,
899   IN EFI_ATA_COLLECTIVE_MODE            *BadModes
900   )
901 {
902   EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData;
903   UINTN                             DeviceIndex;
904 
905   SataPrivateData = SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS (This);
906   ASSERT (SataPrivateData != NULL);
907 
908   if ((Channel >= This->ChannelCount) || (BadModes == NULL) || (Device >= SataPrivateData->DeviceCount)) {
909     return EFI_INVALID_PARAMETER;
910   }
911 
912   DeviceIndex = FlatDeviceIndex (SataPrivateData, Channel, Device);
913 
914   //
915   // Record the disqualified modes per channel per device. From ATA/ATAPI spec,
916   // if a mode is not supported, the modes higher than it is also not supported.
917   //
918   CopyMem (
919     &(SataPrivateData->DisqualifiedModes[DeviceIndex]),
920     BadModes,
921     sizeof (EFI_ATA_COLLECTIVE_MODE)
922     );
923 
924   return EFI_SUCCESS;
925 }
926 
927 /**
928   Returns the information about the optimum modes for the specified IDE device.
929 
930   This function is used by the driver entity to obtain the optimum ATA modes for
931   a specific device.  The IDE controller driver takes into account the following
932   while calculating the mode:
933     - The IdentifyData inputs to EFI_IDE_CONTROLLER_INIT_PROTOCOL.SubmitData()
934     - The BadModes inputs to EFI_IDE_CONTROLLER_INIT_PROTOCOL.DisqualifyMode()
935 
936   The driver entity is required to call EFI_IDE_CONTROLLER_INIT_PROTOCOL.SubmitData()
937   for all the devices that belong to an enumeration group before calling
938   EFI_IDE_CONTROLLER_INIT_PROTOCOL.CalculateMode() for any device in the same group.
939 
940   The IDE controller driver will use controller- and possibly platform-specific
941   algorithms to arrive at SupportedModes.  The IDE controller may base its
942   decision on user preferences and other considerations as well. This function
943   may be called multiple times because the driver entity may renegotiate the mode
944   with the IDE controller driver using EFI_IDE_CONTROLLER_INIT_PROTOCOL.DisqualifyMode().
945 
946   The driver entity may collect timing information for various devices in any
947   order. The driver entity is responsible for making sure that all the dependencies
948   are satisfied. For example, the SupportedModes information for device A that
949   was previously returned may become stale after a call to
950   EFI_IDE_CONTROLLER_INIT_PROTOCOL.DisqualifyMode() for device B.
951 
952   The buffer SupportedModes is allocated by the callee because the caller does
953   not necessarily know the size of the buffer. The type EFI_ATA_COLLECTIVE_MODE
954   is defined in a way that allows for future extensibility and can be of variable
955   length. This memory pool should be deallocated by the caller when it is no
956   longer necessary.
957 
958   The IDE controller driver for a Serial ATA (SATA) controller can use this
959   member function to force a lower speed (first-generation [Gen1] speeds on a
960   second-generation [Gen2]-capable hardware).  The IDE controller driver can
961   also allow the driver entity to stay with the speed that has been negotiated
962   by the physical layer.
963 
964   @param[in]  This             The pointer to the EFI_IDE_CONTROLLER_INIT_PROTOCOL instance.
965   @param[in]  Channel          A zero-based channel number.
966   @param[in]  Device           A zero-based device number on the Channel.
967   @param[out] SupportedModes   The optimum modes for the device.
968 
969   @retval EFI_SUCCESS             SupportedModes was returned.
970   @retval EFI_INVALID_PARAMETER   Channel is invalid (Channel >= ChannelCount).
971   @retval EFI_INVALID_PARAMETER   Device is invalid.
972   @retval EFI_INVALID_PARAMETER   SupportedModes is NULL.
973   @retval EFI_NOT_READY           Modes cannot be calculated due to a lack of
974                                   data.  This error may happen if
975                                   EFI_IDE_CONTROLLER_INIT_PROTOCOL.SubmitData()
976                                   and EFI_IDE_CONTROLLER_INIT_PROTOCOL.DisqualifyData()
977                                   were not called for at least one drive in the
978                                   same enumeration group.
979 
980 **/
981 EFI_STATUS
982 EFIAPI
IdeInitCalculateMode(IN EFI_IDE_CONTROLLER_INIT_PROTOCOL * This,IN UINT8 Channel,IN UINT8 Device,OUT EFI_ATA_COLLECTIVE_MODE ** SupportedModes)983 IdeInitCalculateMode (
984   IN EFI_IDE_CONTROLLER_INIT_PROTOCOL   *This,
985   IN UINT8                              Channel,
986   IN UINT8                              Device,
987   OUT EFI_ATA_COLLECTIVE_MODE           **SupportedModes
988   )
989 {
990   EFI_SATA_CONTROLLER_PRIVATE_DATA  *SataPrivateData;
991   EFI_IDENTIFY_DATA                 *IdentifyData;
992   BOOLEAN                           IdentifyValid;
993   EFI_ATA_COLLECTIVE_MODE           *DisqualifiedModes;
994   UINT16                            SelectedMode;
995   EFI_STATUS                        Status;
996   UINTN                             DeviceIndex;
997 
998   SataPrivateData = SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS (This);
999   ASSERT (SataPrivateData != NULL);
1000 
1001   if ((Channel >= This->ChannelCount) || (SupportedModes == NULL) || (Device >= SataPrivateData->DeviceCount)) {
1002     return EFI_INVALID_PARAMETER;
1003   }
1004 
1005   *SupportedModes = AllocateZeroPool (sizeof (EFI_ATA_COLLECTIVE_MODE));
1006   if (*SupportedModes == NULL) {
1007     ASSERT (*SupportedModes != NULL);
1008     return EFI_OUT_OF_RESOURCES;
1009   }
1010 
1011   DeviceIndex = FlatDeviceIndex (SataPrivateData, Channel, Device);
1012 
1013   IdentifyData = &(SataPrivateData->IdentifyData[DeviceIndex]);
1014   IdentifyValid = SataPrivateData->IdentifyValid[DeviceIndex];
1015   DisqualifiedModes = &(SataPrivateData->DisqualifiedModes[DeviceIndex]);
1016 
1017   //
1018   // Make sure we've got the valid identify data of the device from SubmitData()
1019   //
1020   if (!IdentifyValid) {
1021     FreePool (*SupportedModes);
1022     return EFI_NOT_READY;
1023   }
1024 
1025   Status = CalculateBestPioMode (
1026             IdentifyData,
1027             (DisqualifiedModes->PioMode.Valid ? ((UINT16 *) &(DisqualifiedModes->PioMode.Mode)) : NULL),
1028             &SelectedMode
1029             );
1030   if (!EFI_ERROR (Status)) {
1031     (*SupportedModes)->PioMode.Valid = TRUE;
1032     (*SupportedModes)->PioMode.Mode = SelectedMode;
1033 
1034   } else {
1035     (*SupportedModes)->PioMode.Valid = FALSE;
1036   }
1037   DEBUG ((DEBUG_INFO, "IdeInitCalculateMode: PioMode = %x\n", (*SupportedModes)->PioMode.Mode));
1038 
1039   Status = CalculateBestUdmaMode (
1040             IdentifyData,
1041             (DisqualifiedModes->UdmaMode.Valid ? ((UINT16 *) &(DisqualifiedModes->UdmaMode.Mode)) : NULL),
1042             &SelectedMode
1043             );
1044 
1045   if (!EFI_ERROR (Status)) {
1046     (*SupportedModes)->UdmaMode.Valid = TRUE;
1047     (*SupportedModes)->UdmaMode.Mode  = SelectedMode;
1048 
1049   } else {
1050     (*SupportedModes)->UdmaMode.Valid = FALSE;
1051   }
1052   DEBUG ((DEBUG_INFO, "IdeInitCalculateMode: UdmaMode = %x\n", (*SupportedModes)->UdmaMode.Mode));
1053 
1054   //
1055   // The modes other than PIO and UDMA are not supported
1056   //
1057   return EFI_SUCCESS;
1058 }
1059 
1060 /**
1061   Commands the IDE controller driver to program the IDE controller hardware
1062   so that the specified device can operate at the specified mode.
1063 
1064   This function is used by the driver entity to instruct the IDE controller
1065   driver to program the IDE controller hardware to the specified modes. This
1066   function can be called only once for a particular device. For a Serial ATA
1067   (SATA) Advanced Host Controller Interface (AHCI) controller, no controller-
1068   specific programming may be required.
1069 
1070   @param[in] This      Pointer to the EFI_IDE_CONTROLLER_INIT_PROTOCOL instance.
1071   @param[in] Channel   Zero-based channel number.
1072   @param[in] Device    Zero-based device number on the Channel.
1073   @param[in] Modes     The modes to set.
1074 
1075   @retval EFI_SUCCESS             The command was accepted without any errors.
1076   @retval EFI_INVALID_PARAMETER   Channel is invalid (Channel >= ChannelCount).
1077   @retval EFI_INVALID_PARAMETER   Device is invalid.
1078   @retval EFI_NOT_READY           Modes cannot be set at this time due to lack of data.
1079   @retval EFI_DEVICE_ERROR        Modes cannot be set due to hardware failure.
1080                                   The driver entity should not use this device.
1081 
1082 **/
1083 EFI_STATUS
1084 EFIAPI
IdeInitSetTiming(IN EFI_IDE_CONTROLLER_INIT_PROTOCOL * This,IN UINT8 Channel,IN UINT8 Device,IN EFI_ATA_COLLECTIVE_MODE * Modes)1085 IdeInitSetTiming (
1086   IN EFI_IDE_CONTROLLER_INIT_PROTOCOL   *This,
1087   IN UINT8                              Channel,
1088   IN UINT8                              Device,
1089   IN EFI_ATA_COLLECTIVE_MODE            *Modes
1090   )
1091 {
1092   return EFI_SUCCESS;
1093 }
1094