1 /** @file
2   This driver is used to manage SD/MMC PCI host controllers which are compliance
3   with SD Host Controller Simplified Specification version 3.00 plus the 64-bit
4   System Addressing support in SD Host Controller Simplified Specification version
5   4.20.
6 
7   It would expose EFI_SD_MMC_PASS_THRU_PROTOCOL for upper layer use.
8 
9   Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
10   Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.<BR>
11   SPDX-License-Identifier: BSD-2-Clause-Patent
12 
13 **/
14 
15 #include "SdMmcPciHcDxe.h"
16 
17 /**
18   Dump the content of SD/MMC host controller's Capability Register.
19 
20   @param[in]  Slot            The slot number of the SD card to send the command to.
21   @param[in]  Capability      The buffer to store the capability data.
22 
23 **/
24 VOID
DumpCapabilityReg(IN UINT8 Slot,IN SD_MMC_HC_SLOT_CAP * Capability)25 DumpCapabilityReg (
26   IN UINT8                Slot,
27   IN SD_MMC_HC_SLOT_CAP   *Capability
28   )
29 {
30   //
31   // Dump Capability Data
32   //
33   DEBUG ((DEBUG_INFO, " == Slot [%d] Capability is 0x%x ==\n", Slot, Capability));
34   DEBUG ((DEBUG_INFO, "   Timeout Clk Freq  %d%a\n", Capability->TimeoutFreq, (Capability->TimeoutUnit) ? "MHz" : "KHz"));
35   DEBUG ((DEBUG_INFO, "   Base Clk Freq     %dMHz\n", Capability->BaseClkFreq));
36   DEBUG ((DEBUG_INFO, "   Max Blk Len       %dbytes\n", 512 * (1 << Capability->MaxBlkLen)));
37   DEBUG ((DEBUG_INFO, "   8-bit Support     %a\n", Capability->BusWidth8 ? "TRUE" : "FALSE"));
38   DEBUG ((DEBUG_INFO, "   ADMA2 Support     %a\n", Capability->Adma2 ? "TRUE" : "FALSE"));
39   DEBUG ((DEBUG_INFO, "   HighSpeed Support %a\n", Capability->HighSpeed ? "TRUE" : "FALSE"));
40   DEBUG ((DEBUG_INFO, "   SDMA Support      %a\n", Capability->Sdma ? "TRUE" : "FALSE"));
41   DEBUG ((DEBUG_INFO, "   Suspend/Resume    %a\n", Capability->SuspRes ? "TRUE" : "FALSE"));
42   DEBUG ((DEBUG_INFO, "   Voltage 3.3       %a\n", Capability->Voltage33 ? "TRUE" : "FALSE"));
43   DEBUG ((DEBUG_INFO, "   Voltage 3.0       %a\n", Capability->Voltage30 ? "TRUE" : "FALSE"));
44   DEBUG ((DEBUG_INFO, "   Voltage 1.8       %a\n", Capability->Voltage18 ? "TRUE" : "FALSE"));
45   DEBUG ((DEBUG_INFO, "   V4 64-bit Sys Bus %a\n", Capability->SysBus64V4 ? "TRUE" : "FALSE"));
46   DEBUG ((DEBUG_INFO, "   V3 64-bit Sys Bus %a\n", Capability->SysBus64V3 ? "TRUE" : "FALSE"));
47   DEBUG ((DEBUG_INFO, "   Async Interrupt   %a\n", Capability->AsyncInt ? "TRUE" : "FALSE"));
48   DEBUG ((DEBUG_INFO, "   SlotType          "));
49   if (Capability->SlotType == 0x00) {
50     DEBUG ((DEBUG_INFO, "%a\n", "Removable Slot"));
51   } else if (Capability->SlotType == 0x01) {
52     DEBUG ((DEBUG_INFO, "%a\n", "Embedded Slot"));
53   } else if (Capability->SlotType == 0x02) {
54     DEBUG ((DEBUG_INFO, "%a\n", "Shared Bus Slot"));
55   } else {
56     DEBUG ((DEBUG_INFO, "%a\n", "Reserved"));
57   }
58   DEBUG ((DEBUG_INFO, "   SDR50  Support    %a\n", Capability->Sdr50 ? "TRUE" : "FALSE"));
59   DEBUG ((DEBUG_INFO, "   SDR104 Support    %a\n", Capability->Sdr104 ? "TRUE" : "FALSE"));
60   DEBUG ((DEBUG_INFO, "   DDR50  Support    %a\n", Capability->Ddr50 ? "TRUE" : "FALSE"));
61   DEBUG ((DEBUG_INFO, "   Driver Type A     %a\n", Capability->DriverTypeA ? "TRUE" : "FALSE"));
62   DEBUG ((DEBUG_INFO, "   Driver Type C     %a\n", Capability->DriverTypeC ? "TRUE" : "FALSE"));
63   DEBUG ((DEBUG_INFO, "   Driver Type D     %a\n", Capability->DriverTypeD ? "TRUE" : "FALSE"));
64   DEBUG ((DEBUG_INFO, "   Driver Type 4     %a\n", Capability->DriverType4 ? "TRUE" : "FALSE"));
65   if (Capability->TimerCount == 0) {
66     DEBUG ((DEBUG_INFO, "   Retuning TimerCnt Disabled\n", 2 * (Capability->TimerCount - 1)));
67   } else {
68     DEBUG ((DEBUG_INFO, "   Retuning TimerCnt %dseconds\n", 2 * (Capability->TimerCount - 1)));
69   }
70   DEBUG ((DEBUG_INFO, "   SDR50 Tuning      %a\n", Capability->TuningSDR50 ? "TRUE" : "FALSE"));
71   DEBUG ((DEBUG_INFO, "   Retuning Mode     Mode %d\n", Capability->RetuningMod + 1));
72   DEBUG ((DEBUG_INFO, "   Clock Multiplier  M = %d\n", Capability->ClkMultiplier + 1));
73   DEBUG ((DEBUG_INFO, "   HS 400            %a\n", Capability->Hs400 ? "TRUE" : "FALSE"));
74   return;
75 }
76 
77 /**
78   Read SlotInfo register from SD/MMC host controller pci config space.
79 
80   @param[in]  PciIo        The PCI IO protocol instance.
81   @param[out] FirstBar     The buffer to store the first BAR value.
82   @param[out] SlotNum      The buffer to store the supported slot number.
83 
84   @retval EFI_SUCCESS      The operation succeeds.
85   @retval Others           The operation fails.
86 
87 **/
88 EFI_STATUS
89 EFIAPI
SdMmcHcGetSlotInfo(IN EFI_PCI_IO_PROTOCOL * PciIo,OUT UINT8 * FirstBar,OUT UINT8 * SlotNum)90 SdMmcHcGetSlotInfo (
91   IN     EFI_PCI_IO_PROTOCOL   *PciIo,
92      OUT UINT8                 *FirstBar,
93      OUT UINT8                 *SlotNum
94   )
95 {
96   EFI_STATUS                   Status;
97   SD_MMC_HC_SLOT_INFO          SlotInfo;
98 
99   Status = PciIo->Pci.Read (
100                         PciIo,
101                         EfiPciIoWidthUint8,
102                         SD_MMC_HC_SLOT_OFFSET,
103                         sizeof (SlotInfo),
104                         &SlotInfo
105                         );
106   if (EFI_ERROR (Status)) {
107     return Status;
108   }
109 
110   *FirstBar = SlotInfo.FirstBar;
111   *SlotNum  = SlotInfo.SlotNum + 1;
112   ASSERT ((*FirstBar + *SlotNum) < SD_MMC_HC_MAX_SLOT);
113   return EFI_SUCCESS;
114 }
115 
116 /**
117   Read/Write specified SD/MMC host controller mmio register.
118 
119   @param[in]      PciIo        The PCI IO protocol instance.
120   @param[in]      BarIndex     The BAR index of the standard PCI Configuration
121                                header to use as the base address for the memory
122                                operation to perform.
123   @param[in]      Offset       The offset within the selected BAR to start the
124                                memory operation.
125   @param[in]      Read         A boolean to indicate it's read or write operation.
126   @param[in]      Count        The width of the mmio register in bytes.
127                                Must be 1, 2 , 4 or 8 bytes.
128   @param[in, out] Data         For read operations, the destination buffer to store
129                                the results. For write operations, the source buffer
130                                to write data from. The caller is responsible for
131                                having ownership of the data buffer and ensuring its
132                                size not less than Count bytes.
133 
134   @retval EFI_INVALID_PARAMETER The PciIo or Data is NULL or the Count is not valid.
135   @retval EFI_SUCCESS           The read/write operation succeeds.
136   @retval Others                The read/write operation fails.
137 
138 **/
139 EFI_STATUS
140 EFIAPI
SdMmcHcRwMmio(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 BarIndex,IN UINT32 Offset,IN BOOLEAN Read,IN UINT8 Count,IN OUT VOID * Data)141 SdMmcHcRwMmio (
142   IN     EFI_PCI_IO_PROTOCOL   *PciIo,
143   IN     UINT8                 BarIndex,
144   IN     UINT32                Offset,
145   IN     BOOLEAN               Read,
146   IN     UINT8                 Count,
147   IN OUT VOID                  *Data
148   )
149 {
150   EFI_STATUS                   Status;
151   EFI_PCI_IO_PROTOCOL_WIDTH    Width;
152 
153   if ((PciIo == NULL) || (Data == NULL))  {
154     return EFI_INVALID_PARAMETER;
155   }
156 
157   switch (Count) {
158     case 1:
159       Width = EfiPciIoWidthUint8;
160       break;
161     case 2:
162       Width = EfiPciIoWidthUint16;
163       Count = 1;
164       break;
165     case 4:
166       Width = EfiPciIoWidthUint32;
167       Count = 1;
168       break;
169     case 8:
170       Width = EfiPciIoWidthUint32;
171       Count = 2;
172       break;
173     default:
174       return EFI_INVALID_PARAMETER;
175   }
176 
177   if (Read) {
178     Status = PciIo->Mem.Read (
179                           PciIo,
180                           Width,
181                           BarIndex,
182                           (UINT64) Offset,
183                           Count,
184                           Data
185                           );
186   } else {
187     Status = PciIo->Mem.Write (
188                           PciIo,
189                           Width,
190                           BarIndex,
191                           (UINT64) Offset,
192                           Count,
193                           Data
194                           );
195   }
196 
197   return Status;
198 }
199 
200 /**
201   Do OR operation with the value of the specified SD/MMC host controller mmio register.
202 
203   @param[in] PciIo             The PCI IO protocol instance.
204   @param[in] BarIndex          The BAR index of the standard PCI Configuration
205                                header to use as the base address for the memory
206                                operation to perform.
207   @param[in] Offset            The offset within the selected BAR to start the
208                                memory operation.
209   @param[in] Count             The width of the mmio register in bytes.
210                                Must be 1, 2 , 4 or 8 bytes.
211   @param[in] OrData            The pointer to the data used to do OR operation.
212                                The caller is responsible for having ownership of
213                                the data buffer and ensuring its size not less than
214                                Count bytes.
215 
216   @retval EFI_INVALID_PARAMETER The PciIo or OrData is NULL or the Count is not valid.
217   @retval EFI_SUCCESS           The OR operation succeeds.
218   @retval Others                The OR operation fails.
219 
220 **/
221 EFI_STATUS
222 EFIAPI
SdMmcHcOrMmio(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 BarIndex,IN UINT32 Offset,IN UINT8 Count,IN VOID * OrData)223 SdMmcHcOrMmio (
224   IN  EFI_PCI_IO_PROTOCOL      *PciIo,
225   IN  UINT8                    BarIndex,
226   IN  UINT32                   Offset,
227   IN  UINT8                    Count,
228   IN  VOID                     *OrData
229   )
230 {
231   EFI_STATUS                   Status;
232   UINT64                       Data;
233   UINT64                       Or;
234 
235   Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, TRUE, Count, &Data);
236   if (EFI_ERROR (Status)) {
237     return Status;
238   }
239 
240   if (Count == 1) {
241     Or = *(UINT8*) OrData;
242   } else if (Count == 2) {
243     Or = *(UINT16*) OrData;
244   } else if (Count == 4) {
245     Or = *(UINT32*) OrData;
246   } else if (Count == 8) {
247     Or = *(UINT64*) OrData;
248   } else {
249     return EFI_INVALID_PARAMETER;
250   }
251 
252   Data  |= Or;
253   Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, FALSE, Count, &Data);
254 
255   return Status;
256 }
257 
258 /**
259   Do AND operation with the value of the specified SD/MMC host controller mmio register.
260 
261   @param[in] PciIo             The PCI IO protocol instance.
262   @param[in] BarIndex          The BAR index of the standard PCI Configuration
263                                header to use as the base address for the memory
264                                operation to perform.
265   @param[in] Offset            The offset within the selected BAR to start the
266                                memory operation.
267   @param[in] Count             The width of the mmio register in bytes.
268                                Must be 1, 2 , 4 or 8 bytes.
269   @param[in] AndData           The pointer to the data used to do AND operation.
270                                The caller is responsible for having ownership of
271                                the data buffer and ensuring its size not less than
272                                Count bytes.
273 
274   @retval EFI_INVALID_PARAMETER The PciIo or AndData is NULL or the Count is not valid.
275   @retval EFI_SUCCESS           The AND operation succeeds.
276   @retval Others                The AND operation fails.
277 
278 **/
279 EFI_STATUS
280 EFIAPI
SdMmcHcAndMmio(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 BarIndex,IN UINT32 Offset,IN UINT8 Count,IN VOID * AndData)281 SdMmcHcAndMmio (
282   IN  EFI_PCI_IO_PROTOCOL      *PciIo,
283   IN  UINT8                    BarIndex,
284   IN  UINT32                   Offset,
285   IN  UINT8                    Count,
286   IN  VOID                     *AndData
287   )
288 {
289   EFI_STATUS                   Status;
290   UINT64                       Data;
291   UINT64                       And;
292 
293   Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, TRUE, Count, &Data);
294   if (EFI_ERROR (Status)) {
295     return Status;
296   }
297 
298   if (Count == 1) {
299     And = *(UINT8*) AndData;
300   } else if (Count == 2) {
301     And = *(UINT16*) AndData;
302   } else if (Count == 4) {
303     And = *(UINT32*) AndData;
304   } else if (Count == 8) {
305     And = *(UINT64*) AndData;
306   } else {
307     return EFI_INVALID_PARAMETER;
308   }
309 
310   Data  &= And;
311   Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, FALSE, Count, &Data);
312 
313   return Status;
314 }
315 
316 /**
317   Wait for the value of the specified MMIO register set to the test value.
318 
319   @param[in]  PciIo         The PCI IO protocol instance.
320   @param[in]  BarIndex      The BAR index of the standard PCI Configuration
321                             header to use as the base address for the memory
322                             operation to perform.
323   @param[in]  Offset        The offset within the selected BAR to start the
324                             memory operation.
325   @param[in]  Count         The width of the mmio register in bytes.
326                             Must be 1, 2, 4 or 8 bytes.
327   @param[in]  MaskValue     The mask value of memory.
328   @param[in]  TestValue     The test value of memory.
329 
330   @retval EFI_NOT_READY     The MMIO register hasn't set to the expected value.
331   @retval EFI_SUCCESS       The MMIO register has expected value.
332   @retval Others            The MMIO operation fails.
333 
334 **/
335 EFI_STATUS
336 EFIAPI
SdMmcHcCheckMmioSet(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 BarIndex,IN UINT32 Offset,IN UINT8 Count,IN UINT64 MaskValue,IN UINT64 TestValue)337 SdMmcHcCheckMmioSet (
338   IN  EFI_PCI_IO_PROTOCOL       *PciIo,
339   IN  UINT8                     BarIndex,
340   IN  UINT32                    Offset,
341   IN  UINT8                     Count,
342   IN  UINT64                    MaskValue,
343   IN  UINT64                    TestValue
344   )
345 {
346   EFI_STATUS            Status;
347   UINT64                Value;
348 
349   //
350   // Access PCI MMIO space to see if the value is the tested one.
351   //
352   Value  = 0;
353   Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, TRUE, Count, &Value);
354   if (EFI_ERROR (Status)) {
355     return Status;
356   }
357 
358   Value &= MaskValue;
359 
360   if (Value == TestValue) {
361     return EFI_SUCCESS;
362   }
363 
364   return EFI_NOT_READY;
365 }
366 
367 /**
368   Wait for the value of the specified MMIO register set to the test value.
369 
370   @param[in]  PciIo         The PCI IO protocol instance.
371   @param[in]  BarIndex      The BAR index of the standard PCI Configuration
372                             header to use as the base address for the memory
373                             operation to perform.
374   @param[in]  Offset        The offset within the selected BAR to start the
375                             memory operation.
376   @param[in]  Count         The width of the mmio register in bytes.
377                             Must be 1, 2, 4 or 8 bytes.
378   @param[in]  MaskValue     The mask value of memory.
379   @param[in]  TestValue     The test value of memory.
380   @param[in]  Timeout       The time out value for wait memory set, uses 1
381                             microsecond as a unit.
382 
383   @retval EFI_TIMEOUT       The MMIO register hasn't expected value in timeout
384                             range.
385   @retval EFI_SUCCESS       The MMIO register has expected value.
386   @retval Others            The MMIO operation fails.
387 
388 **/
389 EFI_STATUS
390 EFIAPI
SdMmcHcWaitMmioSet(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 BarIndex,IN UINT32 Offset,IN UINT8 Count,IN UINT64 MaskValue,IN UINT64 TestValue,IN UINT64 Timeout)391 SdMmcHcWaitMmioSet (
392   IN  EFI_PCI_IO_PROTOCOL       *PciIo,
393   IN  UINT8                     BarIndex,
394   IN  UINT32                    Offset,
395   IN  UINT8                     Count,
396   IN  UINT64                    MaskValue,
397   IN  UINT64                    TestValue,
398   IN  UINT64                    Timeout
399   )
400 {
401   EFI_STATUS            Status;
402   BOOLEAN               InfiniteWait;
403 
404   if (Timeout == 0) {
405     InfiniteWait = TRUE;
406   } else {
407     InfiniteWait = FALSE;
408   }
409 
410   while (InfiniteWait || (Timeout > 0)) {
411     Status = SdMmcHcCheckMmioSet (
412                PciIo,
413                BarIndex,
414                Offset,
415                Count,
416                MaskValue,
417                TestValue
418                );
419     if (Status != EFI_NOT_READY) {
420       return Status;
421     }
422 
423     //
424     // Stall for 1 microsecond.
425     //
426     gBS->Stall (1);
427 
428     Timeout--;
429   }
430 
431   return EFI_TIMEOUT;
432 }
433 
434 /**
435   Get the controller version information from the specified slot.
436 
437   @param[in]  PciIo           The PCI IO protocol instance.
438   @param[in]  Slot            The slot number of the SD card to send the command to.
439   @param[out] Version         The buffer to store the version information.
440 
441   @retval EFI_SUCCESS         The operation executes successfully.
442   @retval Others              The operation fails.
443 
444 **/
445 EFI_STATUS
SdMmcHcGetControllerVersion(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,OUT UINT16 * Version)446 SdMmcHcGetControllerVersion (
447   IN     EFI_PCI_IO_PROTOCOL  *PciIo,
448   IN     UINT8                Slot,
449   OUT    UINT16               *Version
450   )
451 {
452   EFI_STATUS                Status;
453 
454   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CTRL_VER, TRUE, sizeof (UINT16), Version);
455   if (EFI_ERROR (Status)) {
456     return Status;
457   }
458 
459   *Version &= 0xFF;
460 
461   return EFI_SUCCESS;
462 }
463 
464 /**
465   Software reset the specified SD/MMC host controller and enable all interrupts.
466 
467   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
468   @param[in] Slot           The slot number of the SD card to send the command to.
469 
470   @retval EFI_SUCCESS       The software reset executes successfully.
471   @retval Others            The software reset fails.
472 
473 **/
474 EFI_STATUS
SdMmcHcReset(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot)475 SdMmcHcReset (
476   IN SD_MMC_HC_PRIVATE_DATA *Private,
477   IN UINT8                  Slot
478   )
479 {
480   EFI_STATUS                Status;
481   UINT8                     SwReset;
482   EFI_PCI_IO_PROTOCOL       *PciIo;
483 
484   //
485   // Notify the SD/MMC override protocol that we are about to reset
486   // the SD/MMC host controller.
487   //
488   if (mOverride != NULL && mOverride->NotifyPhase != NULL) {
489     Status = mOverride->NotifyPhase (
490                           Private->ControllerHandle,
491                           Slot,
492                           EdkiiSdMmcResetPre,
493                           NULL);
494     if (EFI_ERROR (Status)) {
495       DEBUG ((DEBUG_WARN,
496         "%a: SD/MMC pre reset notifier callback failed - %r\n",
497         __FUNCTION__, Status));
498       return Status;
499     }
500   }
501 
502   PciIo   = Private->PciIo;
503   SwReset = BIT0;
504   Status  = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_SW_RST, sizeof (SwReset), &SwReset);
505 
506   if (EFI_ERROR (Status)) {
507     DEBUG ((DEBUG_ERROR, "SdMmcHcReset: write SW Reset for All fails: %r\n", Status));
508     return Status;
509   }
510 
511   Status = SdMmcHcWaitMmioSet (
512              PciIo,
513              Slot,
514              SD_MMC_HC_SW_RST,
515              sizeof (SwReset),
516              BIT0,
517              0x00,
518              SD_MMC_HC_GENERIC_TIMEOUT
519              );
520   if (EFI_ERROR (Status)) {
521     DEBUG ((DEBUG_INFO, "SdMmcHcReset: reset done with %r\n", Status));
522     return Status;
523   }
524 
525   //
526   // Enable all interrupt after reset all.
527   //
528   Status = SdMmcHcEnableInterrupt (PciIo, Slot);
529   if (EFI_ERROR (Status)) {
530     DEBUG ((DEBUG_INFO, "SdMmcHcReset: SdMmcHcEnableInterrupt done with %r\n",
531       Status));
532     return Status;
533   }
534 
535   //
536   // Notify the SD/MMC override protocol that we have just reset
537   // the SD/MMC host controller.
538   //
539   if (mOverride != NULL && mOverride->NotifyPhase != NULL) {
540     Status = mOverride->NotifyPhase (
541                           Private->ControllerHandle,
542                           Slot,
543                           EdkiiSdMmcResetPost,
544                           NULL);
545     if (EFI_ERROR (Status)) {
546       DEBUG ((DEBUG_WARN,
547         "%a: SD/MMC post reset notifier callback failed - %r\n",
548         __FUNCTION__, Status));
549     }
550   }
551 
552   return Status;
553 }
554 
555 /**
556   Set all interrupt status bits in Normal and Error Interrupt Status Enable
557   register.
558 
559   @param[in] PciIo          The PCI IO protocol instance.
560   @param[in] Slot           The slot number of the SD card to send the command to.
561 
562   @retval EFI_SUCCESS       The operation executes successfully.
563   @retval Others            The operation fails.
564 
565 **/
566 EFI_STATUS
SdMmcHcEnableInterrupt(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot)567 SdMmcHcEnableInterrupt (
568   IN EFI_PCI_IO_PROTOCOL    *PciIo,
569   IN UINT8                  Slot
570   )
571 {
572   EFI_STATUS                Status;
573   UINT16                    IntStatus;
574 
575   //
576   // Enable all bits in Error Interrupt Status Enable Register
577   //
578   IntStatus = 0xFFFF;
579   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus);
580   if (EFI_ERROR (Status)) {
581     return Status;
582   }
583   //
584   // Enable all bits in Normal Interrupt Status Enable Register
585   //
586   IntStatus = 0xFFFF;
587   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus);
588 
589   return Status;
590 }
591 
592 /**
593   Get the capability data from the specified slot.
594 
595   @param[in]  PciIo           The PCI IO protocol instance.
596   @param[in]  Slot            The slot number of the SD card to send the command to.
597   @param[out] Capability      The buffer to store the capability data.
598 
599   @retval EFI_SUCCESS         The operation executes successfully.
600   @retval Others              The operation fails.
601 
602 **/
603 EFI_STATUS
SdMmcHcGetCapability(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,OUT SD_MMC_HC_SLOT_CAP * Capability)604 SdMmcHcGetCapability (
605   IN     EFI_PCI_IO_PROTOCOL  *PciIo,
606   IN     UINT8                Slot,
607      OUT SD_MMC_HC_SLOT_CAP   *Capability
608   )
609 {
610   EFI_STATUS                Status;
611   UINT64                    Cap;
612 
613   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CAP, TRUE, sizeof (Cap), &Cap);
614   if (EFI_ERROR (Status)) {
615     return Status;
616   }
617 
618   CopyMem (Capability, &Cap, sizeof (Cap));
619 
620   return EFI_SUCCESS;
621 }
622 
623 /**
624   Get the maximum current capability data from the specified slot.
625 
626   @param[in]  PciIo           The PCI IO protocol instance.
627   @param[in]  Slot            The slot number of the SD card to send the command to.
628   @param[out] MaxCurrent      The buffer to store the maximum current capability data.
629 
630   @retval EFI_SUCCESS         The operation executes successfully.
631   @retval Others              The operation fails.
632 
633 **/
634 EFI_STATUS
SdMmcHcGetMaxCurrent(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,OUT UINT64 * MaxCurrent)635 SdMmcHcGetMaxCurrent (
636   IN     EFI_PCI_IO_PROTOCOL  *PciIo,
637   IN     UINT8                Slot,
638      OUT UINT64               *MaxCurrent
639   )
640 {
641   EFI_STATUS          Status;
642 
643   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_MAX_CURRENT_CAP, TRUE, sizeof (UINT64), MaxCurrent);
644 
645   return Status;
646 }
647 
648 /**
649   Detect whether there is a SD/MMC card attached at the specified SD/MMC host controller
650   slot.
651 
652   Refer to SD Host Controller Simplified spec 3.0 Section 3.1 for details.
653 
654   @param[in]  PciIo         The PCI IO protocol instance.
655   @param[in]  Slot          The slot number of the SD card to send the command to.
656   @param[out] MediaPresent  The pointer to the media present boolean value.
657 
658   @retval EFI_SUCCESS       There is no media change happened.
659   @retval EFI_MEDIA_CHANGED There is media change happened.
660   @retval Others            The detection fails.
661 
662 **/
663 EFI_STATUS
SdMmcHcCardDetect(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,OUT BOOLEAN * MediaPresent)664 SdMmcHcCardDetect (
665   IN EFI_PCI_IO_PROTOCOL    *PciIo,
666   IN UINT8                  Slot,
667      OUT BOOLEAN            *MediaPresent
668   )
669 {
670   EFI_STATUS                Status;
671   UINT16                    Data;
672   UINT32                    PresentState;
673 
674   //
675   // Check Present State Register to see if there is a card presented.
676   //
677   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_PRESENT_STATE, TRUE, sizeof (PresentState), &PresentState);
678   if (EFI_ERROR (Status)) {
679     return Status;
680   }
681 
682   if ((PresentState & BIT16) != 0) {
683     *MediaPresent = TRUE;
684   } else {
685     *MediaPresent = FALSE;
686   }
687 
688   //
689   // Check Normal Interrupt Status Register
690   //
691   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_NOR_INT_STS, TRUE, sizeof (Data), &Data);
692   if (EFI_ERROR (Status)) {
693     return Status;
694   }
695 
696   if ((Data & (BIT6 | BIT7)) != 0) {
697     //
698     // Clear BIT6 and BIT7 by writing 1 to these two bits if set.
699     //
700     Data  &= BIT6 | BIT7;
701     Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_NOR_INT_STS, FALSE, sizeof (Data), &Data);
702     if (EFI_ERROR (Status)) {
703       return Status;
704     }
705 
706     return EFI_MEDIA_CHANGED;
707   }
708 
709   return EFI_SUCCESS;
710 }
711 
712 /**
713   Stop SD/MMC card clock.
714 
715   Refer to SD Host Controller Simplified spec 3.0 Section 3.2.2 for details.
716 
717   @param[in] PciIo          The PCI IO protocol instance.
718   @param[in] Slot           The slot number of the SD card to send the command to.
719 
720   @retval EFI_SUCCESS       Succeed to stop SD/MMC clock.
721   @retval Others            Fail to stop SD/MMC clock.
722 
723 **/
724 EFI_STATUS
SdMmcHcStopClock(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot)725 SdMmcHcStopClock (
726   IN EFI_PCI_IO_PROTOCOL    *PciIo,
727   IN UINT8                  Slot
728   )
729 {
730   EFI_STATUS                Status;
731   UINT32                    PresentState;
732   UINT16                    ClockCtrl;
733 
734   //
735   // Ensure no SD transactions are occurring on the SD Bus by
736   // waiting for Command Inhibit (DAT) and Command Inhibit (CMD)
737   // in the Present State register to be 0.
738   //
739   Status = SdMmcHcWaitMmioSet (
740              PciIo,
741              Slot,
742              SD_MMC_HC_PRESENT_STATE,
743              sizeof (PresentState),
744              BIT0 | BIT1,
745              0,
746              SD_MMC_HC_GENERIC_TIMEOUT
747              );
748   if (EFI_ERROR (Status)) {
749     return Status;
750   }
751 
752   //
753   // Set SD Clock Enable in the Clock Control register to 0
754   //
755   ClockCtrl = (UINT16)~BIT2;
756   Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl);
757 
758   return Status;
759 }
760 
761 /**
762   Start the SD clock.
763 
764   @param[in] PciIo  The PCI IO protocol instance.
765   @param[in] Slot   The slot number.
766 
767   @retval EFI_SUCCESS  Succeeded to start the SD clock.
768   @retval Others       Failed to start the SD clock.
769 **/
770 EFI_STATUS
SdMmcHcStartSdClock(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot)771 SdMmcHcStartSdClock (
772   IN EFI_PCI_IO_PROTOCOL  *PciIo,
773   IN UINT8                Slot
774   )
775 {
776   UINT16                    ClockCtrl;
777 
778   //
779   // Set SD Clock Enable in the Clock Control register to 1
780   //
781   ClockCtrl = BIT2;
782   return SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl);
783 }
784 
785 /**
786   SD/MMC card clock supply.
787 
788   Refer to SD Host Controller Simplified spec 3.0 Section 3.2.1 for details.
789 
790   @param[in] Private         A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
791   @param[in] Slot            The slot number of the SD card to send the command to.
792   @param[in] BusTiming       BusTiming at which the frequency change is done.
793   @param[in] FirstTimeSetup  Flag to indicate whether the clock is being setup for the first time.
794   @param[in] ClockFreq       The max clock frequency to be set. The unit is KHz.
795 
796   @retval EFI_SUCCESS       The clock is supplied successfully.
797   @retval Others            The clock isn't supplied successfully.
798 
799 **/
800 EFI_STATUS
SdMmcHcClockSupply(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot,IN SD_MMC_BUS_MODE BusTiming,IN BOOLEAN FirstTimeSetup,IN UINT64 ClockFreq)801 SdMmcHcClockSupply (
802   IN SD_MMC_HC_PRIVATE_DATA  *Private,
803   IN UINT8                   Slot,
804   IN SD_MMC_BUS_MODE         BusTiming,
805   IN BOOLEAN                 FirstTimeSetup,
806   IN UINT64                  ClockFreq
807   )
808 {
809   EFI_STATUS                Status;
810   UINT32                    SettingFreq;
811   UINT32                    Divisor;
812   UINT32                    Remainder;
813   UINT16                    ClockCtrl;
814   UINT32                    BaseClkFreq;
815   UINT16                    ControllerVer;
816   EFI_PCI_IO_PROTOCOL       *PciIo;
817 
818   PciIo = Private->PciIo;
819   BaseClkFreq = Private->BaseClkFreq[Slot];
820   ControllerVer = Private->ControllerVersion[Slot];
821 
822   if (BaseClkFreq == 0 || ClockFreq == 0) {
823     return EFI_INVALID_PARAMETER;
824   }
825 
826   if (ClockFreq > (BaseClkFreq * 1000)) {
827     ClockFreq = BaseClkFreq * 1000;
828   }
829 
830   //
831   // Calculate the divisor of base frequency.
832   //
833   Divisor     = 0;
834   SettingFreq = BaseClkFreq * 1000;
835   while (ClockFreq < SettingFreq) {
836     Divisor++;
837 
838     SettingFreq = (BaseClkFreq * 1000) / (2 * Divisor);
839     Remainder   = (BaseClkFreq * 1000) % (2 * Divisor);
840     if ((ClockFreq == SettingFreq) && (Remainder == 0)) {
841       break;
842     }
843     if ((ClockFreq == SettingFreq) && (Remainder != 0)) {
844       SettingFreq ++;
845     }
846   }
847 
848   DEBUG ((DEBUG_INFO, "BaseClkFreq %dMHz Divisor %d ClockFreq %dKhz\n", BaseClkFreq, Divisor, ClockFreq));
849 
850   //
851   // Set SDCLK Frequency Select and Internal Clock Enable fields in Clock Control register.
852   //
853   if ((ControllerVer >= SD_MMC_HC_CTRL_VER_300) &&
854       (ControllerVer <= SD_MMC_HC_CTRL_VER_420)) {
855     ASSERT (Divisor <= 0x3FF);
856     ClockCtrl = ((Divisor & 0xFF) << 8) | ((Divisor & 0x300) >> 2);
857   } else if ((ControllerVer == SD_MMC_HC_CTRL_VER_100) ||
858              (ControllerVer == SD_MMC_HC_CTRL_VER_200)) {
859     //
860     // Only the most significant bit can be used as divisor.
861     //
862     if (((Divisor - 1) & Divisor) != 0) {
863       Divisor = 1 << (HighBitSet32 (Divisor) + 1);
864     }
865     ASSERT (Divisor <= 0x80);
866     ClockCtrl = (Divisor & 0xFF) << 8;
867   } else {
868     DEBUG ((DEBUG_ERROR, "Unknown SD Host Controller Spec version [0x%x]!!!\n", ControllerVer));
869     return EFI_UNSUPPORTED;
870   }
871 
872   //
873   // Stop bus clock at first
874   //
875   Status = SdMmcHcStopClock (PciIo, Slot);
876   if (EFI_ERROR (Status)) {
877     return Status;
878   }
879 
880   //
881   // Supply clock frequency with specified divisor
882   //
883   ClockCtrl |= BIT0;
884   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl);
885   if (EFI_ERROR (Status)) {
886     DEBUG ((DEBUG_ERROR, "Set SDCLK Frequency Select and Internal Clock Enable fields fails\n"));
887     return Status;
888   }
889 
890   //
891   // Wait Internal Clock Stable in the Clock Control register to be 1
892   //
893   Status = SdMmcHcWaitMmioSet (
894              PciIo,
895              Slot,
896              SD_MMC_HC_CLOCK_CTRL,
897              sizeof (ClockCtrl),
898              BIT1,
899              BIT1,
900              SD_MMC_HC_GENERIC_TIMEOUT
901              );
902   if (EFI_ERROR (Status)) {
903     return Status;
904   }
905 
906   Status = SdMmcHcStartSdClock (PciIo, Slot);
907   if (EFI_ERROR (Status)) {
908     return Status;
909   }
910 
911   //
912   // We don't notify the platform on first time setup to avoid changing
913   // legacy behavior. During first time setup we also don't know what type
914   // of the card slot it is and which enum value of BusTiming applies.
915   //
916   if (!FirstTimeSetup && mOverride != NULL && mOverride->NotifyPhase != NULL) {
917     Status = mOverride->NotifyPhase (
918                           Private->ControllerHandle,
919                           Slot,
920                           EdkiiSdMmcSwitchClockFreqPost,
921                           &BusTiming
922                           );
923     if (EFI_ERROR (Status)) {
924       DEBUG ((
925         DEBUG_ERROR,
926         "%a: SD/MMC switch clock freq post notifier callback failed - %r\n",
927         __FUNCTION__,
928         Status
929         ));
930       return Status;
931     }
932   }
933 
934   Private->Slot[Slot].CurrentFreq = ClockFreq;
935 
936   return Status;
937 }
938 
939 /**
940   SD/MMC bus power control.
941 
942   Refer to SD Host Controller Simplified spec 3.0 Section 3.3 for details.
943 
944   @param[in] PciIo          The PCI IO protocol instance.
945   @param[in] Slot           The slot number of the SD card to send the command to.
946   @param[in] PowerCtrl      The value setting to the power control register.
947 
948   @retval TRUE              There is a SD/MMC card attached.
949   @retval FALSE             There is no a SD/MMC card attached.
950 
951 **/
952 EFI_STATUS
SdMmcHcPowerControl(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,IN UINT8 PowerCtrl)953 SdMmcHcPowerControl (
954   IN EFI_PCI_IO_PROTOCOL    *PciIo,
955   IN UINT8                  Slot,
956   IN UINT8                  PowerCtrl
957   )
958 {
959   EFI_STATUS                Status;
960 
961   //
962   // Clr SD Bus Power
963   //
964   PowerCtrl &= (UINT8)~BIT0;
965   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl);
966   if (EFI_ERROR (Status)) {
967     return Status;
968   }
969 
970   //
971   // Set SD Bus Voltage Select and SD Bus Power fields in Power Control Register
972   //
973   PowerCtrl |= BIT0;
974   Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl);
975 
976   return Status;
977 }
978 
979 /**
980   Set the SD/MMC bus width.
981 
982   Refer to SD Host Controller Simplified spec 3.0 Section 3.4 for details.
983 
984   @param[in] PciIo          The PCI IO protocol instance.
985   @param[in] Slot           The slot number of the SD card to send the command to.
986   @param[in] BusWidth       The bus width used by the SD/MMC device, it must be 1, 4 or 8.
987 
988   @retval EFI_SUCCESS       The bus width is set successfully.
989   @retval Others            The bus width isn't set successfully.
990 
991 **/
992 EFI_STATUS
SdMmcHcSetBusWidth(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,IN UINT16 BusWidth)993 SdMmcHcSetBusWidth (
994   IN EFI_PCI_IO_PROTOCOL    *PciIo,
995   IN UINT8                  Slot,
996   IN UINT16                 BusWidth
997   )
998 {
999   EFI_STATUS                Status;
1000   UINT8                     HostCtrl1;
1001 
1002   if (BusWidth == 1) {
1003     HostCtrl1 = (UINT8)~(BIT5 | BIT1);
1004     Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
1005   } else if (BusWidth == 4) {
1006     Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1);
1007     if (EFI_ERROR (Status)) {
1008       return Status;
1009     }
1010     HostCtrl1 |= BIT1;
1011     HostCtrl1 &= (UINT8)~BIT5;
1012     Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1);
1013   } else if (BusWidth == 8) {
1014     Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1);
1015     if (EFI_ERROR (Status)) {
1016       return Status;
1017     }
1018     HostCtrl1 &= (UINT8)~BIT1;
1019     HostCtrl1 |= BIT5;
1020     Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1);
1021   } else {
1022     ASSERT (FALSE);
1023     return EFI_INVALID_PARAMETER;
1024   }
1025 
1026   return Status;
1027 }
1028 
1029 /**
1030   Configure V4 controller enhancements at initialization.
1031 
1032   @param[in] PciIo          The PCI IO protocol instance.
1033   @param[in] Slot           The slot number of the SD card to send the command to.
1034   @param[in] Capability     The capability of the slot.
1035   @param[in] ControllerVer  The version of host controller.
1036 
1037   @retval EFI_SUCCESS       The clock is supplied successfully.
1038 
1039 **/
1040 EFI_STATUS
SdMmcHcInitV4Enhancements(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,IN SD_MMC_HC_SLOT_CAP Capability,IN UINT16 ControllerVer)1041 SdMmcHcInitV4Enhancements (
1042   IN EFI_PCI_IO_PROTOCOL    *PciIo,
1043   IN UINT8                  Slot,
1044   IN SD_MMC_HC_SLOT_CAP     Capability,
1045   IN UINT16                 ControllerVer
1046   )
1047 {
1048   EFI_STATUS                Status;
1049   UINT16                    HostCtrl2;
1050 
1051   //
1052   // Check if controller version V4 or higher
1053   //
1054   if (ControllerVer >= SD_MMC_HC_CTRL_VER_400) {
1055     HostCtrl2 = SD_MMC_HC_V4_EN;
1056     //
1057     // Check if controller version V4.0
1058     //
1059     if (ControllerVer == SD_MMC_HC_CTRL_VER_400) {
1060       //
1061       // Check if 64bit support is available
1062       //
1063       if (Capability.SysBus64V3 != 0) {
1064         HostCtrl2 |= SD_MMC_HC_64_ADDR_EN;
1065         DEBUG ((DEBUG_INFO, "Enabled V4 64 bit system bus support\n"));
1066       }
1067     }
1068     //
1069     // Check if controller version V4.10 or higher
1070     //
1071     else if (ControllerVer >= SD_MMC_HC_CTRL_VER_410) {
1072       //
1073       // Check if 64bit support is available
1074       //
1075       if (Capability.SysBus64V4 != 0) {
1076         HostCtrl2 |= SD_MMC_HC_64_ADDR_EN;
1077         DEBUG ((DEBUG_INFO, "Enabled V4 64 bit system bus support\n"));
1078       }
1079       HostCtrl2 |= SD_MMC_HC_26_DATA_LEN_ADMA_EN;
1080       DEBUG ((DEBUG_INFO, "Enabled V4 26 bit data length ADMA support\n"));
1081     }
1082     Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
1083     if (EFI_ERROR (Status)) {
1084       return Status;
1085     }
1086   }
1087 
1088   return EFI_SUCCESS;
1089 }
1090 
1091 /**
1092   Supply SD/MMC card with maximum voltage at initialization.
1093 
1094   Refer to SD Host Controller Simplified spec 3.0 Section 3.3 for details.
1095 
1096   @param[in] PciIo          The PCI IO protocol instance.
1097   @param[in] Slot           The slot number of the SD card to send the command to.
1098   @param[in] Capability     The capability of the slot.
1099 
1100   @retval EFI_SUCCESS       The voltage is supplied successfully.
1101   @retval Others            The voltage isn't supplied successfully.
1102 
1103 **/
1104 EFI_STATUS
SdMmcHcInitPowerVoltage(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,IN SD_MMC_HC_SLOT_CAP Capability)1105 SdMmcHcInitPowerVoltage (
1106   IN EFI_PCI_IO_PROTOCOL    *PciIo,
1107   IN UINT8                  Slot,
1108   IN SD_MMC_HC_SLOT_CAP     Capability
1109   )
1110 {
1111   EFI_STATUS                Status;
1112   UINT8                     MaxVoltage;
1113   UINT8                     HostCtrl2;
1114 
1115   //
1116   // Calculate supported maximum voltage according to SD Bus Voltage Select
1117   //
1118   if (Capability.Voltage33 != 0) {
1119     //
1120     // Support 3.3V
1121     //
1122     MaxVoltage = 0x0E;
1123   } else if (Capability.Voltage30 != 0) {
1124     //
1125     // Support 3.0V
1126     //
1127     MaxVoltage = 0x0C;
1128   } else if (Capability.Voltage18 != 0) {
1129     //
1130     // Support 1.8V
1131     //
1132     MaxVoltage = 0x0A;
1133     HostCtrl2  = BIT3;
1134     Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
1135     gBS->Stall (5000);
1136     if (EFI_ERROR (Status)) {
1137       return Status;
1138     }
1139   } else {
1140     ASSERT (FALSE);
1141     return EFI_DEVICE_ERROR;
1142   }
1143 
1144   //
1145   // Set SD Bus Voltage Select and SD Bus Power fields in Power Control Register
1146   //
1147   Status = SdMmcHcPowerControl (PciIo, Slot, MaxVoltage);
1148 
1149   return Status;
1150 }
1151 
1152 /**
1153   Initialize the Timeout Control register with most conservative value at initialization.
1154 
1155   Refer to SD Host Controller Simplified spec 3.0 Section 2.2.15 for details.
1156 
1157   @param[in] PciIo          The PCI IO protocol instance.
1158   @param[in] Slot           The slot number of the SD card to send the command to.
1159 
1160   @retval EFI_SUCCESS       The timeout control register is configured successfully.
1161   @retval Others            The timeout control register isn't configured successfully.
1162 
1163 **/
1164 EFI_STATUS
SdMmcHcInitTimeoutCtrl(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot)1165 SdMmcHcInitTimeoutCtrl (
1166   IN EFI_PCI_IO_PROTOCOL    *PciIo,
1167   IN UINT8                  Slot
1168   )
1169 {
1170   EFI_STATUS                Status;
1171   UINT8                     Timeout;
1172 
1173   Timeout = 0x0E;
1174   Status  = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_TIMEOUT_CTRL, FALSE, sizeof (Timeout), &Timeout);
1175 
1176   return Status;
1177 }
1178 
1179 /**
1180   Initial SD/MMC host controller with lowest clock frequency, max power and max timeout value
1181   at initialization.
1182 
1183   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
1184   @param[in] Slot           The slot number of the SD card to send the command to.
1185 
1186   @retval EFI_SUCCESS       The host controller is initialized successfully.
1187   @retval Others            The host controller isn't initialized successfully.
1188 
1189 **/
1190 EFI_STATUS
SdMmcHcInitHost(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot)1191 SdMmcHcInitHost (
1192   IN SD_MMC_HC_PRIVATE_DATA *Private,
1193   IN UINT8                  Slot
1194   )
1195 {
1196   EFI_STATUS                Status;
1197   EFI_PCI_IO_PROTOCOL       *PciIo;
1198   SD_MMC_HC_SLOT_CAP        Capability;
1199 
1200   //
1201   // Notify the SD/MMC override protocol that we are about to initialize
1202   // the SD/MMC host controller.
1203   //
1204   if (mOverride != NULL && mOverride->NotifyPhase != NULL) {
1205     Status = mOverride->NotifyPhase (
1206                           Private->ControllerHandle,
1207                           Slot,
1208                           EdkiiSdMmcInitHostPre,
1209                           NULL);
1210     if (EFI_ERROR (Status)) {
1211       DEBUG ((DEBUG_WARN,
1212         "%a: SD/MMC pre init notifier callback failed - %r\n",
1213         __FUNCTION__, Status));
1214       return Status;
1215     }
1216   }
1217 
1218   PciIo = Private->PciIo;
1219   Capability = Private->Capability[Slot];
1220 
1221   Status = SdMmcHcInitV4Enhancements (PciIo, Slot, Capability, Private->ControllerVersion[Slot]);
1222   if (EFI_ERROR (Status)) {
1223     return Status;
1224   }
1225 
1226   //
1227   // Perform first time clock setup with 400 KHz frequency.
1228   // We send the 0 as the BusTiming value because at this time
1229   // we still do not know the slot type and which enum value will apply.
1230   // Since it is a first time setup SdMmcHcClockSupply won't notify
1231   // the platofrm driver anyway so it doesn't matter.
1232   //
1233   Status = SdMmcHcClockSupply (Private, Slot, 0, TRUE, 400);
1234   if (EFI_ERROR (Status)) {
1235     return Status;
1236   }
1237 
1238   Status = SdMmcHcInitPowerVoltage (PciIo, Slot, Capability);
1239   if (EFI_ERROR (Status)) {
1240     return Status;
1241   }
1242 
1243   Status = SdMmcHcInitTimeoutCtrl (PciIo, Slot);
1244   if (EFI_ERROR (Status)) {
1245     return Status;
1246   }
1247 
1248   //
1249   // Notify the SD/MMC override protocol that we are have just initialized
1250   // the SD/MMC host controller.
1251   //
1252   if (mOverride != NULL && mOverride->NotifyPhase != NULL) {
1253     Status = mOverride->NotifyPhase (
1254                           Private->ControllerHandle,
1255                           Slot,
1256                           EdkiiSdMmcInitHostPost,
1257                           NULL);
1258     if (EFI_ERROR (Status)) {
1259       DEBUG ((DEBUG_WARN,
1260         "%a: SD/MMC post init notifier callback failed - %r\n",
1261         __FUNCTION__, Status));
1262     }
1263   }
1264   return Status;
1265 }
1266 
1267 /**
1268   Set SD Host Controler control 2 registry according to selected speed.
1269 
1270   @param[in] ControllerHandle The handle of the controller.
1271   @param[in] PciIo            The PCI IO protocol instance.
1272   @param[in] Slot             The slot number of the SD card to send the command to.
1273   @param[in] Timing           The timing to select.
1274 
1275   @retval EFI_SUCCESS         The timing is set successfully.
1276   @retval Others              The timing isn't set successfully.
1277 **/
1278 EFI_STATUS
SdMmcHcUhsSignaling(IN EFI_HANDLE ControllerHandle,IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,IN SD_MMC_BUS_MODE Timing)1279 SdMmcHcUhsSignaling (
1280   IN EFI_HANDLE             ControllerHandle,
1281   IN EFI_PCI_IO_PROTOCOL    *PciIo,
1282   IN UINT8                  Slot,
1283   IN SD_MMC_BUS_MODE        Timing
1284   )
1285 {
1286   EFI_STATUS                 Status;
1287   UINT8                      HostCtrl2;
1288 
1289   HostCtrl2 = (UINT8)~SD_MMC_HC_CTRL_UHS_MASK;
1290   Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
1291   if (EFI_ERROR (Status)) {
1292     return Status;
1293   }
1294 
1295   switch (Timing) {
1296     case SdMmcUhsSdr12:
1297       HostCtrl2 = SD_MMC_HC_CTRL_UHS_SDR12;
1298       break;
1299     case SdMmcUhsSdr25:
1300       HostCtrl2 = SD_MMC_HC_CTRL_UHS_SDR25;
1301       break;
1302     case SdMmcUhsSdr50:
1303       HostCtrl2 = SD_MMC_HC_CTRL_UHS_SDR50;
1304       break;
1305     case SdMmcUhsSdr104:
1306       HostCtrl2 = SD_MMC_HC_CTRL_UHS_SDR104;
1307       break;
1308     case SdMmcUhsDdr50:
1309       HostCtrl2 = SD_MMC_HC_CTRL_UHS_DDR50;
1310       break;
1311     case SdMmcMmcLegacy:
1312       HostCtrl2 = SD_MMC_HC_CTRL_MMC_LEGACY;
1313       break;
1314     case SdMmcMmcHsSdr:
1315       HostCtrl2 = SD_MMC_HC_CTRL_MMC_HS_SDR;
1316       break;
1317     case SdMmcMmcHsDdr:
1318       HostCtrl2 = SD_MMC_HC_CTRL_MMC_HS_DDR;
1319       break;
1320     case SdMmcMmcHs200:
1321       HostCtrl2 = SD_MMC_HC_CTRL_MMC_HS200;
1322       break;
1323     case SdMmcMmcHs400:
1324       HostCtrl2 = SD_MMC_HC_CTRL_MMC_HS400;
1325       break;
1326     default:
1327      HostCtrl2 = 0;
1328      break;
1329   }
1330   Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
1331   if (EFI_ERROR (Status)) {
1332     return Status;
1333   }
1334 
1335   if (mOverride != NULL && mOverride->NotifyPhase != NULL) {
1336     Status = mOverride->NotifyPhase (
1337                           ControllerHandle,
1338                           Slot,
1339                           EdkiiSdMmcUhsSignaling,
1340                           &Timing
1341                           );
1342     if (EFI_ERROR (Status)) {
1343       DEBUG ((
1344         DEBUG_ERROR,
1345         "%a: SD/MMC uhs signaling notifier callback failed - %r\n",
1346         __FUNCTION__,
1347         Status
1348         ));
1349       return Status;
1350     }
1351   }
1352 
1353   return EFI_SUCCESS;
1354 }
1355 
1356 /**
1357   Set driver strength in host controller.
1358 
1359   @param[in] PciIo           The PCI IO protocol instance.
1360   @param[in] SlotIndex       The slot index of the card.
1361   @param[in] DriverStrength  DriverStrength to set in the controller.
1362 
1363   @retval EFI_SUCCESS  Driver strength programmed successfully.
1364   @retval Others       Failed to set driver strength.
1365 **/
1366 EFI_STATUS
SdMmcSetDriverStrength(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 SlotIndex,IN SD_DRIVER_STRENGTH_TYPE DriverStrength)1367 SdMmcSetDriverStrength (
1368   IN EFI_PCI_IO_PROTOCOL      *PciIo,
1369   IN UINT8                    SlotIndex,
1370   IN SD_DRIVER_STRENGTH_TYPE  DriverStrength
1371   )
1372 {
1373   EFI_STATUS  Status;
1374   UINT16      HostCtrl2;
1375 
1376   if (DriverStrength == SdDriverStrengthIgnore) {
1377     return EFI_SUCCESS;
1378   }
1379 
1380   HostCtrl2 = (UINT16)~SD_MMC_HC_CTRL_DRIVER_STRENGTH_MASK;
1381   Status = SdMmcHcAndMmio (PciIo, SlotIndex, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
1382   if (EFI_ERROR (Status)) {
1383     return Status;
1384   }
1385 
1386   HostCtrl2 = (DriverStrength << 4) & SD_MMC_HC_CTRL_DRIVER_STRENGTH_MASK;
1387   return SdMmcHcOrMmio (PciIo, SlotIndex, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2);
1388 }
1389 
1390 /**
1391   Turn on/off LED.
1392 
1393   @param[in] PciIo          The PCI IO protocol instance.
1394   @param[in] Slot           The slot number of the SD card to send the command to.
1395   @param[in] On             The boolean to turn on/off LED.
1396 
1397   @retval EFI_SUCCESS       The LED is turned on/off successfully.
1398   @retval Others            The LED isn't turned on/off successfully.
1399 
1400 **/
1401 EFI_STATUS
SdMmcHcLedOnOff(IN EFI_PCI_IO_PROTOCOL * PciIo,IN UINT8 Slot,IN BOOLEAN On)1402 SdMmcHcLedOnOff (
1403   IN EFI_PCI_IO_PROTOCOL    *PciIo,
1404   IN UINT8                  Slot,
1405   IN BOOLEAN                On
1406   )
1407 {
1408   EFI_STATUS                Status;
1409   UINT8                     HostCtrl1;
1410 
1411   if (On) {
1412     HostCtrl1 = BIT0;
1413     Status    = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
1414   } else {
1415     HostCtrl1 = (UINT8)~BIT0;
1416     Status    = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
1417   }
1418 
1419   return Status;
1420 }
1421 
1422 /**
1423   Build ADMA descriptor table for transfer.
1424 
1425   Refer to SD Host Controller Simplified spec 4.2 Section 1.13 for details.
1426 
1427   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
1428   @param[in] ControllerVer  The version of host controller.
1429 
1430   @retval EFI_SUCCESS       The ADMA descriptor table is created successfully.
1431   @retval Others            The ADMA descriptor table isn't created successfully.
1432 
1433 **/
1434 EFI_STATUS
BuildAdmaDescTable(IN SD_MMC_HC_TRB * Trb,IN UINT16 ControllerVer)1435 BuildAdmaDescTable (
1436   IN SD_MMC_HC_TRB          *Trb,
1437   IN UINT16                 ControllerVer
1438   )
1439 {
1440   EFI_PHYSICAL_ADDRESS      Data;
1441   UINT64                    DataLen;
1442   UINT64                    Entries;
1443   UINT32                    Index;
1444   UINT64                    Remaining;
1445   UINT64                    Address;
1446   UINTN                     TableSize;
1447   EFI_PCI_IO_PROTOCOL       *PciIo;
1448   EFI_STATUS                Status;
1449   UINTN                     Bytes;
1450   UINT32                    AdmaMaxDataPerLine;
1451   UINT32                    DescSize;
1452   VOID                      *AdmaDesc;
1453 
1454   AdmaMaxDataPerLine = ADMA_MAX_DATA_PER_LINE_16B;
1455   DescSize           = sizeof (SD_MMC_HC_ADMA_32_DESC_LINE);
1456   AdmaDesc           = NULL;
1457 
1458   Data    = Trb->DataPhy;
1459   DataLen = Trb->DataLen;
1460   PciIo   = Trb->Private->PciIo;
1461 
1462   //
1463   // Check for valid ranges in 32bit ADMA Descriptor Table
1464   //
1465   if ((Trb->Mode == SdMmcAdma32bMode) &&
1466       ((Data >= 0x100000000ul) || ((Data + DataLen) > 0x100000000ul))) {
1467     return EFI_INVALID_PARAMETER;
1468   }
1469   //
1470   // Check address field alignment
1471   //
1472   if (Trb->Mode != SdMmcAdma32bMode) {
1473     //
1474     // Address field shall be set on 64-bit boundary (Lower 3-bit is always set to 0)
1475     //
1476     if ((Data & (BIT0 | BIT1 | BIT2)) != 0) {
1477       DEBUG ((DEBUG_INFO, "The buffer [0x%x] to construct ADMA desc is not aligned to 8 bytes boundary!\n", Data));
1478     }
1479   } else {
1480     //
1481     // Address field shall be set on 32-bit boundary (Lower 2-bit is always set to 0)
1482     //
1483     if ((Data & (BIT0 | BIT1)) != 0) {
1484       DEBUG ((DEBUG_INFO, "The buffer [0x%x] to construct ADMA desc is not aligned to 4 bytes boundary!\n", Data));
1485     }
1486   }
1487 
1488   //
1489   // Configure 64b ADMA.
1490   //
1491   if (Trb->Mode == SdMmcAdma64bV3Mode) {
1492     DescSize = sizeof (SD_MMC_HC_ADMA_64_V3_DESC_LINE);
1493   }else if (Trb->Mode == SdMmcAdma64bV4Mode) {
1494     DescSize = sizeof (SD_MMC_HC_ADMA_64_V4_DESC_LINE);
1495   }
1496   //
1497   // Configure 26b data length.
1498   //
1499   if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1500     AdmaMaxDataPerLine = ADMA_MAX_DATA_PER_LINE_26B;
1501   }
1502 
1503   Entries   = DivU64x32 ((DataLen + AdmaMaxDataPerLine - 1), AdmaMaxDataPerLine);
1504   TableSize = (UINTN)MultU64x32 (Entries, DescSize);
1505   Trb->AdmaPages = (UINT32)EFI_SIZE_TO_PAGES (TableSize);
1506   Status = PciIo->AllocateBuffer (
1507                     PciIo,
1508                     AllocateAnyPages,
1509                     EfiBootServicesData,
1510                     EFI_SIZE_TO_PAGES (TableSize),
1511                     (VOID **)&AdmaDesc,
1512                     0
1513                     );
1514   if (EFI_ERROR (Status)) {
1515     return EFI_OUT_OF_RESOURCES;
1516   }
1517   ZeroMem (AdmaDesc, TableSize);
1518   Bytes  = TableSize;
1519   Status = PciIo->Map (
1520                     PciIo,
1521                     EfiPciIoOperationBusMasterCommonBuffer,
1522                     AdmaDesc,
1523                     &Bytes,
1524                     &Trb->AdmaDescPhy,
1525                     &Trb->AdmaMap
1526                     );
1527 
1528   if (EFI_ERROR (Status) || (Bytes != TableSize)) {
1529     //
1530     // Map error or unable to map the whole RFis buffer into a contiguous region.
1531     //
1532     PciIo->FreeBuffer (
1533              PciIo,
1534              EFI_SIZE_TO_PAGES (TableSize),
1535              AdmaDesc
1536              );
1537     return EFI_OUT_OF_RESOURCES;
1538   }
1539 
1540   if ((Trb->Mode == SdMmcAdma32bMode) &&
1541       (UINT64)(UINTN)Trb->AdmaDescPhy > 0x100000000ul) {
1542     //
1543     // The ADMA doesn't support 64bit addressing.
1544     //
1545     PciIo->Unmap (
1546       PciIo,
1547       Trb->AdmaMap
1548     );
1549     Trb->AdmaMap = NULL;
1550 
1551     PciIo->FreeBuffer (
1552       PciIo,
1553       EFI_SIZE_TO_PAGES (TableSize),
1554       AdmaDesc
1555     );
1556     return EFI_DEVICE_ERROR;
1557   }
1558 
1559   Remaining = DataLen;
1560   Address   = Data;
1561   if (Trb->Mode == SdMmcAdma32bMode) {
1562     Trb->Adma32Desc = AdmaDesc;
1563   } else if (Trb->Mode == SdMmcAdma64bV3Mode) {
1564     Trb->Adma64V3Desc = AdmaDesc;
1565   } else {
1566     Trb->Adma64V4Desc = AdmaDesc;
1567   }
1568 
1569   for (Index = 0; Index < Entries; Index++) {
1570     if (Trb->Mode == SdMmcAdma32bMode) {
1571       if (Remaining <= AdmaMaxDataPerLine) {
1572         Trb->Adma32Desc[Index].Valid = 1;
1573         Trb->Adma32Desc[Index].Act   = 2;
1574         if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1575           Trb->Adma32Desc[Index].UpperLength = (UINT16)RShiftU64 (Remaining, 16);
1576         }
1577         Trb->Adma32Desc[Index].LowerLength = (UINT16)(Remaining & MAX_UINT16);
1578         Trb->Adma32Desc[Index].Address = (UINT32)Address;
1579         break;
1580       } else {
1581         Trb->Adma32Desc[Index].Valid = 1;
1582         Trb->Adma32Desc[Index].Act   = 2;
1583         if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1584           Trb->Adma32Desc[Index].UpperLength  = 0;
1585         }
1586         Trb->Adma32Desc[Index].LowerLength  = 0;
1587         Trb->Adma32Desc[Index].Address = (UINT32)Address;
1588       }
1589     } else if (Trb->Mode == SdMmcAdma64bV3Mode) {
1590       if (Remaining <= AdmaMaxDataPerLine) {
1591         Trb->Adma64V3Desc[Index].Valid = 1;
1592         Trb->Adma64V3Desc[Index].Act   = 2;
1593         if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1594           Trb->Adma64V3Desc[Index].UpperLength  = (UINT16)RShiftU64 (Remaining, 16);
1595         }
1596         Trb->Adma64V3Desc[Index].LowerLength  = (UINT16)(Remaining & MAX_UINT16);
1597         Trb->Adma64V3Desc[Index].LowerAddress = (UINT32)Address;
1598         Trb->Adma64V3Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32);
1599         break;
1600       } else {
1601         Trb->Adma64V3Desc[Index].Valid = 1;
1602         Trb->Adma64V3Desc[Index].Act   = 2;
1603         if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1604           Trb->Adma64V3Desc[Index].UpperLength  = 0;
1605         }
1606         Trb->Adma64V3Desc[Index].LowerLength  = 0;
1607         Trb->Adma64V3Desc[Index].LowerAddress = (UINT32)Address;
1608         Trb->Adma64V3Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32);
1609       }
1610     } else {
1611       if (Remaining <= AdmaMaxDataPerLine) {
1612         Trb->Adma64V4Desc[Index].Valid = 1;
1613         Trb->Adma64V4Desc[Index].Act   = 2;
1614         if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1615           Trb->Adma64V4Desc[Index].UpperLength  = (UINT16)RShiftU64 (Remaining, 16);
1616         }
1617         Trb->Adma64V4Desc[Index].LowerLength  = (UINT16)(Remaining & MAX_UINT16);
1618         Trb->Adma64V4Desc[Index].LowerAddress = (UINT32)Address;
1619         Trb->Adma64V4Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32);
1620         break;
1621       } else {
1622         Trb->Adma64V4Desc[Index].Valid = 1;
1623         Trb->Adma64V4Desc[Index].Act   = 2;
1624         if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) {
1625           Trb->Adma64V4Desc[Index].UpperLength  = 0;
1626         }
1627         Trb->Adma64V4Desc[Index].LowerLength  = 0;
1628         Trb->Adma64V4Desc[Index].LowerAddress = (UINT32)Address;
1629         Trb->Adma64V4Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32);
1630       }
1631     }
1632 
1633     Remaining -= AdmaMaxDataPerLine;
1634     Address   += AdmaMaxDataPerLine;
1635   }
1636 
1637   //
1638   // Set the last descriptor line as end of descriptor table
1639   //
1640   if (Trb->Mode == SdMmcAdma32bMode) {
1641     Trb->Adma32Desc[Index].End = 1;
1642   } else if (Trb->Mode == SdMmcAdma64bV3Mode) {
1643     Trb->Adma64V3Desc[Index].End = 1;
1644   } else {
1645     Trb->Adma64V4Desc[Index].End = 1;
1646   }
1647   return EFI_SUCCESS;
1648 }
1649 
1650 /**
1651   Prints the contents of the command packet to the debug port.
1652 
1653   @param[in] DebugLevel  Debug level at which the packet should be printed.
1654   @param[in] Packet      Pointer to packet to print.
1655 **/
1656 VOID
SdMmcPrintPacket(IN UINT32 DebugLevel,IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET * Packet)1657 SdMmcPrintPacket (
1658   IN UINT32                               DebugLevel,
1659   IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET  *Packet
1660   )
1661 {
1662   if (Packet == NULL) {
1663     return;
1664   }
1665 
1666   DEBUG ((DebugLevel, "Printing EFI_SD_MMC_PASS_THRU_COMMAND_PACKET\n"));
1667   if (Packet->SdMmcCmdBlk != NULL) {
1668     DEBUG ((DebugLevel, "Command index: %d, argument: %X\n", Packet->SdMmcCmdBlk->CommandIndex, Packet->SdMmcCmdBlk->CommandArgument));
1669     DEBUG ((DebugLevel, "Command type: %d, response type: %d\n", Packet->SdMmcCmdBlk->CommandType, Packet->SdMmcCmdBlk->ResponseType));
1670   }
1671   if (Packet->SdMmcStatusBlk != NULL) {
1672     DEBUG ((DebugLevel, "Response 0: %X, 1: %X, 2: %X, 3: %X\n",
1673                            Packet->SdMmcStatusBlk->Resp0,
1674                            Packet->SdMmcStatusBlk->Resp1,
1675                            Packet->SdMmcStatusBlk->Resp2,
1676                            Packet->SdMmcStatusBlk->Resp3
1677                            ));
1678   }
1679   DEBUG ((DebugLevel, "Timeout: %ld\n", Packet->Timeout));
1680   DEBUG ((DebugLevel, "InDataBuffer: %p\n", Packet->InDataBuffer));
1681   DEBUG ((DebugLevel, "OutDataBuffer: %p\n", Packet->OutDataBuffer));
1682   DEBUG ((DebugLevel, "InTransferLength: %d\n", Packet->InTransferLength));
1683   DEBUG ((DebugLevel, "OutTransferLength: %d\n", Packet->OutTransferLength));
1684   DEBUG ((DebugLevel, "TransactionStatus: %r\n", Packet->TransactionStatus));
1685 }
1686 
1687 /**
1688   Prints the contents of the TRB to the debug port.
1689 
1690   @param[in] DebugLevel  Debug level at which the TRB should be printed.
1691   @param[in] Trb         Pointer to the TRB structure.
1692 **/
1693 VOID
SdMmcPrintTrb(IN UINT32 DebugLevel,IN SD_MMC_HC_TRB * Trb)1694 SdMmcPrintTrb (
1695   IN UINT32         DebugLevel,
1696   IN SD_MMC_HC_TRB  *Trb
1697   )
1698 {
1699   if (Trb == NULL) {
1700     return;
1701   }
1702 
1703   DEBUG ((DebugLevel, "Printing SD_MMC_HC_TRB\n"));
1704   DEBUG ((DebugLevel, "Slot: %d\n", Trb->Slot));
1705   DEBUG ((DebugLevel, "BlockSize: %d\n", Trb->BlockSize));
1706   DEBUG ((DebugLevel, "Data: %p\n", Trb->Data));
1707   DEBUG ((DebugLevel, "DataLen: %d\n", Trb->DataLen));
1708   DEBUG ((DebugLevel, "Read: %d\n", Trb->Read));
1709   DEBUG ((DebugLevel, "DataPhy: %lX\n", Trb->DataPhy));
1710   DEBUG ((DebugLevel, "DataMap: %p\n", Trb->DataMap));
1711   DEBUG ((DebugLevel, "Mode: %d\n", Trb->Mode));
1712   DEBUG ((DebugLevel, "AdmaLengthMode: %d\n", Trb->AdmaLengthMode));
1713   DEBUG ((DebugLevel, "Event: %p\n", Trb->Event));
1714   DEBUG ((DebugLevel, "Started: %d\n", Trb->Started));
1715   DEBUG ((DebugLevel, "CommandComplete: %d\n", Trb->CommandComplete));
1716   DEBUG ((DebugLevel, "Timeout: %ld\n", Trb->Timeout));
1717   DEBUG ((DebugLevel, "Retries: %d\n", Trb->Retries));
1718   DEBUG ((DebugLevel, "PioModeTransferCompleted: %d\n", Trb->PioModeTransferCompleted));
1719   DEBUG ((DebugLevel, "PioBlockIndex: %d\n", Trb->PioBlockIndex));
1720   DEBUG ((DebugLevel, "Adma32Desc: %p\n", Trb->Adma32Desc));
1721   DEBUG ((DebugLevel, "Adma64V3Desc: %p\n", Trb->Adma64V3Desc));
1722   DEBUG ((DebugLevel, "Adma64V4Desc: %p\n", Trb->Adma64V4Desc));
1723   DEBUG ((DebugLevel, "AdmaMap: %p\n", Trb->AdmaMap));
1724   DEBUG ((DebugLevel, "AdmaPages: %X\n", Trb->AdmaPages));
1725 
1726   SdMmcPrintPacket (DebugLevel, Trb->Packet);
1727 }
1728 
1729 /**
1730   Sets up host memory to allow DMA transfer.
1731 
1732   @param[in] Private  A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
1733   @param[in] Slot     The slot number of the SD card to send the command to.
1734   @param[in] Packet   A pointer to the SD command data structure.
1735 
1736   @retval EFI_SUCCESS  Memory has been mapped for DMA transfer.
1737   @retval Others       Memory has not been mapped.
1738 **/
1739 EFI_STATUS
SdMmcSetupMemoryForDmaTransfer(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot,IN SD_MMC_HC_TRB * Trb)1740 SdMmcSetupMemoryForDmaTransfer (
1741   IN SD_MMC_HC_PRIVATE_DATA  *Private,
1742   IN UINT8                   Slot,
1743   IN SD_MMC_HC_TRB           *Trb
1744   )
1745 {
1746   EFI_PCI_IO_PROTOCOL_OPERATION Flag;
1747   EFI_PCI_IO_PROTOCOL           *PciIo;
1748   UINTN                         MapLength;
1749   EFI_STATUS                    Status;
1750 
1751   if (Trb->Read) {
1752     Flag = EfiPciIoOperationBusMasterWrite;
1753   } else {
1754     Flag = EfiPciIoOperationBusMasterRead;
1755   }
1756 
1757   PciIo = Private->PciIo;
1758   if (Trb->Data != NULL && Trb->DataLen != 0) {
1759     MapLength = Trb->DataLen;
1760     Status = PciIo->Map (
1761                       PciIo,
1762                       Flag,
1763                       Trb->Data,
1764                       &MapLength,
1765                       &Trb->DataPhy,
1766                       &Trb->DataMap
1767                       );
1768     if (EFI_ERROR (Status) || (Trb->DataLen != MapLength)) {
1769       return EFI_BAD_BUFFER_SIZE;
1770     }
1771   }
1772 
1773   if (Trb->Mode == SdMmcAdma32bMode ||
1774       Trb->Mode == SdMmcAdma64bV3Mode ||
1775       Trb->Mode == SdMmcAdma64bV4Mode) {
1776     Status = BuildAdmaDescTable (Trb, Private->ControllerVersion[Slot]);
1777     if (EFI_ERROR (Status)) {
1778       return Status;
1779     }
1780   }
1781 
1782   return EFI_SUCCESS;
1783 }
1784 
1785 /**
1786   Create a new TRB for the SD/MMC cmd request.
1787 
1788   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
1789   @param[in] Slot           The slot number of the SD card to send the command to.
1790   @param[in] Packet         A pointer to the SD command data structure.
1791   @param[in] Event          If Event is NULL, blocking I/O is performed. If Event is
1792                             not NULL, then nonblocking I/O is performed, and Event
1793                             will be signaled when the Packet completes.
1794 
1795   @return Created Trb or NULL.
1796 
1797 **/
1798 SD_MMC_HC_TRB *
SdMmcCreateTrb(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot,IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET * Packet,IN EFI_EVENT Event)1799 SdMmcCreateTrb (
1800   IN SD_MMC_HC_PRIVATE_DATA              *Private,
1801   IN UINT8                               Slot,
1802   IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet,
1803   IN EFI_EVENT                           Event
1804   )
1805 {
1806   SD_MMC_HC_TRB                 *Trb;
1807   EFI_STATUS                    Status;
1808   EFI_TPL                       OldTpl;
1809 
1810   Trb = AllocateZeroPool (sizeof (SD_MMC_HC_TRB));
1811   if (Trb == NULL) {
1812     return NULL;
1813   }
1814 
1815   Trb->Signature = SD_MMC_HC_TRB_SIG;
1816   Trb->Slot      = Slot;
1817   Trb->BlockSize = 0x200;
1818   Trb->Packet    = Packet;
1819   Trb->Event     = Event;
1820   Trb->Started   = FALSE;
1821   Trb->CommandComplete = FALSE;
1822   Trb->Timeout   = Packet->Timeout;
1823   Trb->Retries   = SD_MMC_TRB_RETRIES;
1824   Trb->PioModeTransferCompleted = FALSE;
1825   Trb->PioBlockIndex = 0;
1826   Trb->Private   = Private;
1827 
1828   if ((Packet->InTransferLength != 0) && (Packet->InDataBuffer != NULL)) {
1829     Trb->Data    = Packet->InDataBuffer;
1830     Trb->DataLen = Packet->InTransferLength;
1831     Trb->Read    = TRUE;
1832   } else if ((Packet->OutTransferLength != 0) && (Packet->OutDataBuffer != NULL)) {
1833     Trb->Data    = Packet->OutDataBuffer;
1834     Trb->DataLen = Packet->OutTransferLength;
1835     Trb->Read    = FALSE;
1836   } else if ((Packet->InTransferLength == 0) && (Packet->OutTransferLength == 0)) {
1837     Trb->Data    = NULL;
1838     Trb->DataLen = 0;
1839   } else {
1840     goto Error;
1841   }
1842 
1843   if ((Trb->DataLen != 0) && (Trb->DataLen < Trb->BlockSize)) {
1844     Trb->BlockSize = (UINT16)Trb->DataLen;
1845   }
1846 
1847   if (((Private->Slot[Trb->Slot].CardType == EmmcCardType) &&
1848        (Packet->SdMmcCmdBlk->CommandIndex == EMMC_SEND_TUNING_BLOCK)) ||
1849       ((Private->Slot[Trb->Slot].CardType == SdCardType) &&
1850        (Packet->SdMmcCmdBlk->CommandIndex == SD_SEND_TUNING_BLOCK))) {
1851     Trb->Mode = SdMmcPioMode;
1852   } else {
1853     if (Trb->DataLen == 0) {
1854       Trb->Mode = SdMmcNoData;
1855     } else if (Private->Capability[Slot].Adma2 != 0) {
1856       Trb->Mode = SdMmcAdma32bMode;
1857       Trb->AdmaLengthMode = SdMmcAdmaLen16b;
1858       if ((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_300) &&
1859           (Private->Capability[Slot].SysBus64V3 == 1)) {
1860         Trb->Mode = SdMmcAdma64bV3Mode;
1861       } else if (((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_400) &&
1862                   (Private->Capability[Slot].SysBus64V3 == 1)) ||
1863                  ((Private->ControllerVersion[Slot] >= SD_MMC_HC_CTRL_VER_410) &&
1864                   (Private->Capability[Slot].SysBus64V4 == 1))) {
1865         Trb->Mode = SdMmcAdma64bV4Mode;
1866       }
1867       if (Private->ControllerVersion[Slot] >= SD_MMC_HC_CTRL_VER_410) {
1868         Trb->AdmaLengthMode = SdMmcAdmaLen26b;
1869       }
1870       Status = SdMmcSetupMemoryForDmaTransfer (Private, Slot, Trb);
1871       if (EFI_ERROR (Status)) {
1872         goto Error;
1873       }
1874     } else if (Private->Capability[Slot].Sdma != 0) {
1875       Trb->Mode = SdMmcSdmaMode;
1876       Status = SdMmcSetupMemoryForDmaTransfer (Private, Slot, Trb);
1877       if (EFI_ERROR (Status)) {
1878         goto Error;
1879       }
1880     } else {
1881       Trb->Mode = SdMmcPioMode;
1882     }
1883   }
1884 
1885   if (Event != NULL) {
1886     OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
1887     InsertTailList (&Private->Queue, &Trb->TrbList);
1888     gBS->RestoreTPL (OldTpl);
1889   }
1890 
1891   return Trb;
1892 
1893 Error:
1894   SdMmcFreeTrb (Trb);
1895   return NULL;
1896 }
1897 
1898 /**
1899   Free the resource used by the TRB.
1900 
1901   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
1902 
1903 **/
1904 VOID
SdMmcFreeTrb(IN SD_MMC_HC_TRB * Trb)1905 SdMmcFreeTrb (
1906   IN SD_MMC_HC_TRB           *Trb
1907   )
1908 {
1909   EFI_PCI_IO_PROTOCOL        *PciIo;
1910 
1911   PciIo = Trb->Private->PciIo;
1912 
1913   if (Trb->AdmaMap != NULL) {
1914     PciIo->Unmap (
1915       PciIo,
1916       Trb->AdmaMap
1917     );
1918   }
1919   if (Trb->Adma32Desc != NULL) {
1920     PciIo->FreeBuffer (
1921       PciIo,
1922       Trb->AdmaPages,
1923       Trb->Adma32Desc
1924     );
1925   }
1926   if (Trb->Adma64V3Desc != NULL) {
1927     PciIo->FreeBuffer (
1928       PciIo,
1929       Trb->AdmaPages,
1930       Trb->Adma64V3Desc
1931     );
1932   }
1933   if (Trb->Adma64V4Desc != NULL) {
1934     PciIo->FreeBuffer (
1935       PciIo,
1936       Trb->AdmaPages,
1937       Trb->Adma64V4Desc
1938     );
1939   }
1940   if (Trb->DataMap != NULL) {
1941     PciIo->Unmap (
1942       PciIo,
1943       Trb->DataMap
1944     );
1945   }
1946   FreePool (Trb);
1947   return;
1948 }
1949 
1950 /**
1951   Check if the env is ready for execute specified TRB.
1952 
1953   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
1954   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
1955 
1956   @retval EFI_SUCCESS       The env is ready for TRB execution.
1957   @retval EFI_NOT_READY     The env is not ready for TRB execution.
1958   @retval Others            Some erros happen.
1959 
1960 **/
1961 EFI_STATUS
SdMmcCheckTrbEnv(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)1962 SdMmcCheckTrbEnv (
1963   IN SD_MMC_HC_PRIVATE_DATA           *Private,
1964   IN SD_MMC_HC_TRB                    *Trb
1965   )
1966 {
1967   EFI_STATUS                          Status;
1968   EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet;
1969   EFI_PCI_IO_PROTOCOL                 *PciIo;
1970   UINT32                              PresentState;
1971 
1972   Packet = Trb->Packet;
1973 
1974   if ((Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc) ||
1975       (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR1b) ||
1976       (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR5b)) {
1977     //
1978     // Wait Command Inhibit (CMD) and Command Inhibit (DAT) in
1979     // the Present State register to be 0
1980     //
1981     PresentState = BIT0 | BIT1;
1982   } else {
1983     //
1984     // Wait Command Inhibit (CMD) in the Present State register
1985     // to be 0
1986     //
1987     PresentState = BIT0;
1988   }
1989 
1990   PciIo  = Private->PciIo;
1991   Status = SdMmcHcCheckMmioSet (
1992              PciIo,
1993              Trb->Slot,
1994              SD_MMC_HC_PRESENT_STATE,
1995              sizeof (PresentState),
1996              PresentState,
1997              0
1998              );
1999 
2000   return Status;
2001 }
2002 
2003 /**
2004   Wait for the env to be ready for execute specified TRB.
2005 
2006   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2007   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
2008 
2009   @retval EFI_SUCCESS       The env is ready for TRB execution.
2010   @retval EFI_TIMEOUT       The env is not ready for TRB execution in time.
2011   @retval Others            Some erros happen.
2012 
2013 **/
2014 EFI_STATUS
SdMmcWaitTrbEnv(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)2015 SdMmcWaitTrbEnv (
2016   IN SD_MMC_HC_PRIVATE_DATA           *Private,
2017   IN SD_MMC_HC_TRB                    *Trb
2018   )
2019 {
2020   EFI_STATUS                          Status;
2021   EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet;
2022   UINT64                              Timeout;
2023   BOOLEAN                             InfiniteWait;
2024 
2025   //
2026   // Wait Command Complete Interrupt Status bit in Normal Interrupt Status Register
2027   //
2028   Packet  = Trb->Packet;
2029   Timeout = Packet->Timeout;
2030   if (Timeout == 0) {
2031     InfiniteWait = TRUE;
2032   } else {
2033     InfiniteWait = FALSE;
2034   }
2035 
2036   while (InfiniteWait || (Timeout > 0)) {
2037     //
2038     // Check Trb execution result by reading Normal Interrupt Status register.
2039     //
2040     Status = SdMmcCheckTrbEnv (Private, Trb);
2041     if (Status != EFI_NOT_READY) {
2042       return Status;
2043     }
2044     //
2045     // Stall for 1 microsecond.
2046     //
2047     gBS->Stall (1);
2048 
2049     Timeout--;
2050   }
2051 
2052   return EFI_TIMEOUT;
2053 }
2054 
2055 /**
2056   Execute the specified TRB.
2057 
2058   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2059   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
2060 
2061   @retval EFI_SUCCESS       The TRB is sent to host controller successfully.
2062   @retval Others            Some erros happen when sending this request to the host controller.
2063 
2064 **/
2065 EFI_STATUS
SdMmcExecTrb(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)2066 SdMmcExecTrb (
2067   IN SD_MMC_HC_PRIVATE_DATA           *Private,
2068   IN SD_MMC_HC_TRB                    *Trb
2069   )
2070 {
2071   EFI_STATUS                          Status;
2072   EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet;
2073   EFI_PCI_IO_PROTOCOL                 *PciIo;
2074   UINT16                              Cmd;
2075   UINT16                              IntStatus;
2076   UINT32                              Argument;
2077   UINT32                              BlkCount;
2078   UINT16                              BlkSize;
2079   UINT16                              TransMode;
2080   UINT8                               HostCtrl1;
2081   UINT64                              SdmaAddr;
2082   UINT64                              AdmaAddr;
2083   BOOLEAN                             AddressingMode64;
2084 
2085   AddressingMode64 = FALSE;
2086 
2087   Packet = Trb->Packet;
2088   PciIo  = Trb->Private->PciIo;
2089   //
2090   // Clear all bits in Error Interrupt Status Register
2091   //
2092   IntStatus = 0xFFFF;
2093   Status    = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_ERR_INT_STS, FALSE, sizeof (IntStatus), &IntStatus);
2094   if (EFI_ERROR (Status)) {
2095     return Status;
2096   }
2097   //
2098   // Clear all bits in Normal Interrupt Status Register excepts for Card Removal & Card Insertion bits.
2099   //
2100   IntStatus = 0xFF3F;
2101   Status    = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_NOR_INT_STS, FALSE, sizeof (IntStatus), &IntStatus);
2102   if (EFI_ERROR (Status)) {
2103     return Status;
2104   }
2105 
2106   if (Private->ControllerVersion[Trb->Slot] >= SD_MMC_HC_CTRL_VER_400) {
2107     Status = SdMmcHcCheckMmioSet(PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL2, sizeof(UINT16),
2108                                  SD_MMC_HC_64_ADDR_EN, SD_MMC_HC_64_ADDR_EN);
2109     if (!EFI_ERROR (Status)) {
2110       AddressingMode64 = TRUE;
2111     }
2112   }
2113 
2114   //
2115   // Set Host Control 1 register DMA Select field
2116   //
2117   if ((Trb->Mode == SdMmcAdma32bMode) ||
2118       (Trb->Mode == SdMmcAdma64bV4Mode)) {
2119     HostCtrl1 = BIT4;
2120     Status = SdMmcHcOrMmio (PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
2121     if (EFI_ERROR (Status)) {
2122       return Status;
2123     }
2124   } else if (Trb->Mode == SdMmcAdma64bV3Mode) {
2125     HostCtrl1 = BIT4|BIT3;
2126     Status = SdMmcHcOrMmio (PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1);
2127     if (EFI_ERROR (Status)) {
2128       return Status;
2129     }
2130   }
2131 
2132   SdMmcHcLedOnOff (PciIo, Trb->Slot, TRUE);
2133 
2134   if (Trb->Mode == SdMmcSdmaMode) {
2135     if ((!AddressingMode64) &&
2136         ((UINT64)(UINTN)Trb->DataPhy >= 0x100000000ul)) {
2137       return EFI_INVALID_PARAMETER;
2138     }
2139 
2140     SdmaAddr = (UINT64)(UINTN)Trb->DataPhy;
2141 
2142     if (Private->ControllerVersion[Trb->Slot] >= SD_MMC_HC_CTRL_VER_400) {
2143       Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_ADMA_SYS_ADDR, FALSE, sizeof (UINT64), &SdmaAddr);
2144     } else {
2145       Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_SDMA_ADDR, FALSE, sizeof (UINT32), &SdmaAddr);
2146     }
2147 
2148     if (EFI_ERROR (Status)) {
2149       return Status;
2150     }
2151   } else if ((Trb->Mode == SdMmcAdma32bMode) ||
2152              (Trb->Mode == SdMmcAdma64bV3Mode) ||
2153              (Trb->Mode == SdMmcAdma64bV4Mode)) {
2154     AdmaAddr = (UINT64)(UINTN)Trb->AdmaDescPhy;
2155     Status   = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_ADMA_SYS_ADDR, FALSE, sizeof (AdmaAddr), &AdmaAddr);
2156     if (EFI_ERROR (Status)) {
2157       return Status;
2158     }
2159   }
2160 
2161   BlkSize = Trb->BlockSize;
2162   if (Trb->Mode == SdMmcSdmaMode) {
2163     //
2164     // Set SDMA boundary to be 512K bytes.
2165     //
2166     BlkSize |= 0x7000;
2167   }
2168 
2169   Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_BLK_SIZE, FALSE, sizeof (BlkSize), &BlkSize);
2170   if (EFI_ERROR (Status)) {
2171     return Status;
2172   }
2173 
2174   BlkCount = 0;
2175   if (Trb->Mode != SdMmcNoData) {
2176     //
2177     // Calcuate Block Count.
2178     //
2179     BlkCount = (Trb->DataLen / Trb->BlockSize);
2180   }
2181   if (Private->ControllerVersion[Trb->Slot] >= SD_MMC_HC_CTRL_VER_410) {
2182     Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_SDMA_ADDR, FALSE, sizeof (UINT32), &BlkCount);
2183   } else {
2184     Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_BLK_COUNT, FALSE, sizeof (UINT16), &BlkCount);
2185   }
2186   if (EFI_ERROR (Status)) {
2187     return Status;
2188   }
2189 
2190   Argument = Packet->SdMmcCmdBlk->CommandArgument;
2191   Status   = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_ARG1, FALSE, sizeof (Argument), &Argument);
2192   if (EFI_ERROR (Status)) {
2193     return Status;
2194   }
2195 
2196   TransMode = 0;
2197   if (Trb->Mode != SdMmcNoData) {
2198     if (Trb->Mode != SdMmcPioMode) {
2199       TransMode |= BIT0;
2200     }
2201     if (Trb->Read) {
2202       TransMode |= BIT4;
2203     }
2204     if (BlkCount > 1) {
2205       TransMode |= BIT5 | BIT1;
2206     }
2207     //
2208     // Only SD memory card needs to use AUTO CMD12 feature.
2209     //
2210     if (Private->Slot[Trb->Slot].CardType == SdCardType) {
2211       if (BlkCount > 1) {
2212         TransMode |= BIT2;
2213       }
2214     }
2215   }
2216 
2217   Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_TRANS_MOD, FALSE, sizeof (TransMode), &TransMode);
2218   if (EFI_ERROR (Status)) {
2219     return Status;
2220   }
2221 
2222   Cmd = (UINT16)LShiftU64(Packet->SdMmcCmdBlk->CommandIndex, 8);
2223   if (Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc) {
2224     Cmd |= BIT5;
2225   }
2226   //
2227   // Convert ResponseType to value
2228   //
2229   if (Packet->SdMmcCmdBlk->CommandType != SdMmcCommandTypeBc) {
2230     switch (Packet->SdMmcCmdBlk->ResponseType) {
2231       case SdMmcResponseTypeR1:
2232       case SdMmcResponseTypeR5:
2233       case SdMmcResponseTypeR6:
2234       case SdMmcResponseTypeR7:
2235         Cmd |= (BIT1 | BIT3 | BIT4);
2236         break;
2237       case SdMmcResponseTypeR2:
2238         Cmd |= (BIT0 | BIT3);
2239        break;
2240       case SdMmcResponseTypeR3:
2241       case SdMmcResponseTypeR4:
2242         Cmd |= BIT1;
2243         break;
2244       case SdMmcResponseTypeR1b:
2245       case SdMmcResponseTypeR5b:
2246         Cmd |= (BIT0 | BIT1 | BIT3 | BIT4);
2247         break;
2248       default:
2249         ASSERT (FALSE);
2250         break;
2251     }
2252   }
2253   //
2254   // Execute cmd
2255   //
2256   Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_COMMAND, FALSE, sizeof (Cmd), &Cmd);
2257   return Status;
2258 }
2259 
2260 /**
2261   Performs SW reset based on passed error status mask.
2262 
2263   @param[in]  Private       Pointer to driver private data.
2264   @param[in]  Slot          Index of the slot to reset.
2265   @param[in]  ErrIntStatus  Error interrupt status mask.
2266 
2267   @retval EFI_SUCCESS  Software reset performed successfully.
2268   @retval Other        Software reset failed.
2269 **/
2270 EFI_STATUS
SdMmcSoftwareReset(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot,IN UINT16 ErrIntStatus)2271 SdMmcSoftwareReset (
2272   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2273   IN UINT8                   Slot,
2274   IN UINT16                  ErrIntStatus
2275   )
2276 {
2277   UINT8       SwReset;
2278   EFI_STATUS  Status;
2279 
2280   SwReset = 0;
2281   if ((ErrIntStatus & 0x0F) != 0) {
2282     SwReset |= BIT1;
2283   }
2284   if ((ErrIntStatus & 0x70) != 0) {
2285     SwReset |= BIT2;
2286   }
2287 
2288   Status  = SdMmcHcRwMmio (
2289               Private->PciIo,
2290               Slot,
2291               SD_MMC_HC_SW_RST,
2292               FALSE,
2293               sizeof (SwReset),
2294               &SwReset
2295               );
2296   if (EFI_ERROR (Status)) {
2297     return Status;
2298   }
2299 
2300   Status = SdMmcHcWaitMmioSet (
2301              Private->PciIo,
2302              Slot,
2303              SD_MMC_HC_SW_RST,
2304              sizeof (SwReset),
2305              0xFF,
2306              0,
2307              SD_MMC_HC_GENERIC_TIMEOUT
2308              );
2309   if (EFI_ERROR (Status)) {
2310     return Status;
2311   }
2312 
2313   return EFI_SUCCESS;
2314 }
2315 
2316 /**
2317   Checks the error status in error status register
2318   and issues appropriate software reset as described in
2319   SD specification section 3.10.
2320 
2321   @param[in] Private    Pointer to driver private data.
2322   @param[in] Slot       Index of the slot for device.
2323   @param[in] IntStatus  Normal interrupt status mask.
2324 
2325   @retval EFI_CRC_ERROR  CRC error happened during CMD execution.
2326   @retval EFI_SUCCESS    No error reported.
2327   @retval Others         Some other error happened.
2328 
2329 **/
2330 EFI_STATUS
SdMmcCheckAndRecoverErrors(IN SD_MMC_HC_PRIVATE_DATA * Private,IN UINT8 Slot,IN UINT16 IntStatus)2331 SdMmcCheckAndRecoverErrors (
2332   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2333   IN UINT8                   Slot,
2334   IN UINT16                  IntStatus
2335   )
2336 {
2337   UINT16      ErrIntStatus;
2338   EFI_STATUS  Status;
2339   EFI_STATUS  ErrorStatus;
2340 
2341   if ((IntStatus & BIT15) == 0) {
2342     return EFI_SUCCESS;
2343   }
2344 
2345   Status = SdMmcHcRwMmio (
2346              Private->PciIo,
2347              Slot,
2348              SD_MMC_HC_ERR_INT_STS,
2349              TRUE,
2350              sizeof (ErrIntStatus),
2351              &ErrIntStatus
2352              );
2353   if (EFI_ERROR (Status)) {
2354     return Status;
2355   }
2356 
2357   DEBUG ((DEBUG_ERROR, "Error reported by SDHCI\n"));
2358   DEBUG ((DEBUG_ERROR, "Interrupt status = %X\n", IntStatus));
2359   DEBUG ((DEBUG_ERROR, "Error interrupt status = %X\n", ErrIntStatus));
2360 
2361   //
2362   // If the data timeout error is reported
2363   // but data transfer is signaled as completed we
2364   // have to ignore data timeout. We also assume that no
2365   // other error is present on the link since data transfer
2366   // completed successfully. Error interrupt status
2367   // register is going to be reset when the next command
2368   // is started.
2369   //
2370   if (((ErrIntStatus & BIT4) != 0) && ((IntStatus & BIT1) != 0)) {
2371     return EFI_SUCCESS;
2372   }
2373 
2374   //
2375   // We treat both CMD and DAT CRC errors and
2376   // end bits errors as EFI_CRC_ERROR. This will
2377   // let higher layer know that the error possibly
2378   // happened due to random bus condition and the
2379   // command can be retried.
2380   //
2381   if ((ErrIntStatus & (BIT1 | BIT2 | BIT5 | BIT6)) != 0) {
2382     ErrorStatus = EFI_CRC_ERROR;
2383   } else {
2384     ErrorStatus = EFI_DEVICE_ERROR;
2385   }
2386 
2387   Status = SdMmcSoftwareReset (Private, Slot, ErrIntStatus);
2388   if (EFI_ERROR (Status)) {
2389     return Status;
2390   }
2391 
2392   return ErrorStatus;
2393 }
2394 
2395 /**
2396   Reads the response data into the TRB buffer.
2397   This function assumes that caller made sure that
2398   command has completed.
2399 
2400   @param[in] Private  A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2401   @param[in] Trb      The pointer to the SD_MMC_HC_TRB instance.
2402 
2403   @retval EFI_SUCCESS  Response read successfully.
2404   @retval Others       Failed to get response.
2405 **/
2406 EFI_STATUS
SdMmcGetResponse(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)2407 SdMmcGetResponse (
2408   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2409   IN SD_MMC_HC_TRB           *Trb
2410   )
2411 {
2412   EFI_SD_MMC_PASS_THRU_COMMAND_PACKET  *Packet;
2413   UINT8                                Index;
2414   UINT32                               Response[4];
2415   EFI_STATUS                           Status;
2416 
2417   Packet = Trb->Packet;
2418 
2419   if (Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeBc) {
2420     return EFI_SUCCESS;
2421   }
2422 
2423   for (Index = 0; Index < 4; Index++) {
2424     Status = SdMmcHcRwMmio (
2425                Private->PciIo,
2426                Trb->Slot,
2427                SD_MMC_HC_RESPONSE + Index * 4,
2428                TRUE,
2429                sizeof (UINT32),
2430                &Response[Index]
2431                );
2432       if (EFI_ERROR (Status)) {
2433         return Status;
2434       }
2435     }
2436   CopyMem (Packet->SdMmcStatusBlk, Response, sizeof (Response));
2437 
2438   return EFI_SUCCESS;
2439 }
2440 
2441 /**
2442   Checks if the command completed. If the command
2443   completed it gets the response and records the
2444   command completion in the TRB.
2445 
2446   @param[in] Private    A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2447   @param[in] Trb        The pointer to the SD_MMC_HC_TRB instance.
2448   @param[in] IntStatus  Snapshot of the normal interrupt status register.
2449 
2450   @retval EFI_SUCCESS   Command completed successfully.
2451   @retval EFI_NOT_READY Command completion still pending.
2452   @retval Others        Command failed to complete.
2453 **/
2454 EFI_STATUS
SdMmcCheckCommandComplete(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb,IN UINT16 IntStatus)2455 SdMmcCheckCommandComplete (
2456   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2457   IN SD_MMC_HC_TRB           *Trb,
2458   IN UINT16                  IntStatus
2459   )
2460 {
2461   UINT16      Data16;
2462   EFI_STATUS  Status;
2463 
2464   if ((IntStatus & BIT0) != 0) {
2465     Data16 = BIT0;
2466     Status = SdMmcHcRwMmio (
2467                Private->PciIo,
2468                Trb->Slot,
2469                SD_MMC_HC_NOR_INT_STS,
2470                FALSE,
2471                sizeof (Data16),
2472                &Data16
2473                );
2474     if (EFI_ERROR (Status)) {
2475       return Status;
2476     }
2477     Status = SdMmcGetResponse (Private, Trb);
2478     if (EFI_ERROR (Status)) {
2479       return Status;
2480     }
2481     Trb->CommandComplete = TRUE;
2482     return EFI_SUCCESS;
2483   }
2484 
2485   return EFI_NOT_READY;
2486 }
2487 
2488 /**
2489   Transfers data from card using PIO method.
2490 
2491   @param[in] Private    A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2492   @param[in] Trb        The pointer to the SD_MMC_HC_TRB instance.
2493   @param[in] IntStatus  Snapshot of the normal interrupt status register.
2494 
2495   @retval EFI_SUCCESS   PIO transfer completed successfully.
2496   @retval EFI_NOT_READY PIO transfer completion still pending.
2497   @retval Others        PIO transfer failed to complete.
2498 **/
2499 EFI_STATUS
SdMmcTransferDataWithPio(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb,IN UINT16 IntStatus)2500 SdMmcTransferDataWithPio (
2501   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2502   IN SD_MMC_HC_TRB           *Trb,
2503   IN UINT16                  IntStatus
2504   )
2505 {
2506   EFI_STATUS                  Status;
2507   UINT16                      Data16;
2508   UINT32                      BlockCount;
2509   EFI_PCI_IO_PROTOCOL_WIDTH  Width;
2510   UINTN                       Count;
2511 
2512   BlockCount = (Trb->DataLen / Trb->BlockSize);
2513   if (Trb->DataLen % Trb->BlockSize != 0) {
2514     BlockCount += 1;
2515   }
2516 
2517   if (Trb->PioBlockIndex >= BlockCount) {
2518     return EFI_SUCCESS;
2519   }
2520 
2521   switch (Trb->BlockSize % sizeof (UINT32)) {
2522     case 0:
2523       Width = EfiPciIoWidthFifoUint32;
2524       Count = Trb->BlockSize / sizeof (UINT32);
2525       break;
2526     case 2:
2527       Width = EfiPciIoWidthFifoUint16;
2528       Count = Trb->BlockSize / sizeof (UINT16);
2529       break;
2530     case 1:
2531     case 3:
2532     default:
2533       Width = EfiPciIoWidthFifoUint8;
2534       Count = Trb->BlockSize;
2535       break;
2536     }
2537 
2538   if (Trb->Read) {
2539     if ((IntStatus & BIT5) == 0) {
2540       return EFI_NOT_READY;
2541     }
2542     Data16 = BIT5;
2543     SdMmcHcRwMmio (Private->PciIo, Trb->Slot, SD_MMC_HC_NOR_INT_STS, FALSE, sizeof (Data16), &Data16);
2544 
2545     Status = Private->PciIo->Mem.Read (
2546                Private->PciIo,
2547                Width,
2548                Trb->Slot,
2549                SD_MMC_HC_BUF_DAT_PORT,
2550                Count,
2551                (VOID*)((UINT8*)Trb->Data + (Trb->BlockSize * Trb->PioBlockIndex))
2552                );
2553     if (EFI_ERROR (Status)) {
2554       return Status;
2555     }
2556     Trb->PioBlockIndex++;
2557   } else {
2558     if ((IntStatus & BIT4) == 0) {
2559       return EFI_NOT_READY;
2560     }
2561     Data16 = BIT4;
2562     SdMmcHcRwMmio (Private->PciIo, Trb->Slot, SD_MMC_HC_NOR_INT_STS, FALSE, sizeof (Data16), &Data16);
2563 
2564     Status = Private->PciIo->Mem.Write (
2565                Private->PciIo,
2566                Width,
2567                Trb->Slot,
2568                SD_MMC_HC_BUF_DAT_PORT,
2569                Count,
2570                (VOID*)((UINT8*)Trb->Data + (Trb->BlockSize * Trb->PioBlockIndex))
2571                );
2572     if (EFI_ERROR (Status)) {
2573       return Status;
2574     }
2575     Trb->PioBlockIndex++;
2576   }
2577 
2578   if (Trb->PioBlockIndex >= BlockCount) {
2579     Trb->PioModeTransferCompleted = TRUE;
2580     return EFI_SUCCESS;
2581   } else {
2582     return EFI_NOT_READY;
2583   }
2584 }
2585 
2586 /**
2587   Update the SDMA address on the SDMA buffer boundary interrupt.
2588 
2589   @param[in] Private    A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2590   @param[in] Trb        The pointer to the SD_MMC_HC_TRB instance.
2591 
2592   @retval EFI_SUCCESS  Updated SDMA buffer address.
2593   @retval Others       Failed to update SDMA buffer address.
2594 **/
2595 EFI_STATUS
SdMmcUpdateSdmaAddress(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)2596 SdMmcUpdateSdmaAddress (
2597   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2598   IN SD_MMC_HC_TRB           *Trb
2599   )
2600 {
2601   UINT64      SdmaAddr;
2602   EFI_STATUS  Status;
2603 
2604   SdmaAddr = SD_MMC_SDMA_ROUND_UP ((UINTN)Trb->DataPhy, SD_MMC_SDMA_BOUNDARY);
2605 
2606   if (Private->ControllerVersion[Trb->Slot] >= SD_MMC_HC_CTRL_VER_400) {
2607     Status = SdMmcHcRwMmio (
2608                Private->PciIo,
2609                Trb->Slot,
2610                SD_MMC_HC_ADMA_SYS_ADDR,
2611                FALSE,
2612                sizeof (UINT64),
2613                &SdmaAddr
2614                );
2615   } else {
2616     Status = SdMmcHcRwMmio (
2617                Private->PciIo,
2618                Trb->Slot,
2619                SD_MMC_HC_SDMA_ADDR,
2620                FALSE,
2621                sizeof (UINT32),
2622                &SdmaAddr
2623                );
2624   }
2625 
2626   if (EFI_ERROR (Status)) {
2627     return Status;
2628   }
2629 
2630   Trb->DataPhy = (UINT64)(UINTN)SdmaAddr;
2631   return EFI_SUCCESS;
2632 }
2633 
2634 /**
2635   Checks if the data transfer completed and performs any actions
2636   neccessary to continue the data transfer such as SDMA system
2637   address fixup or PIO data transfer.
2638 
2639   @param[in] Private    A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2640   @param[in] Trb        The pointer to the SD_MMC_HC_TRB instance.
2641   @param[in] IntStatus  Snapshot of the normal interrupt status register.
2642 
2643   @retval EFI_SUCCESS   Data transfer completed successfully.
2644   @retval EFI_NOT_READY Data transfer completion still pending.
2645   @retval Others        Data transfer failed to complete.
2646 **/
2647 EFI_STATUS
SdMmcCheckDataTransfer(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb,IN UINT16 IntStatus)2648 SdMmcCheckDataTransfer (
2649   IN SD_MMC_HC_PRIVATE_DATA  *Private,
2650   IN SD_MMC_HC_TRB           *Trb,
2651   IN UINT16                  IntStatus
2652   )
2653 {
2654   UINT16      Data16;
2655   EFI_STATUS  Status;
2656 
2657   if ((IntStatus & BIT1) != 0) {
2658     Data16 = BIT1;
2659     Status = SdMmcHcRwMmio (
2660                Private->PciIo,
2661                Trb->Slot,
2662                SD_MMC_HC_NOR_INT_STS,
2663                FALSE,
2664                sizeof (Data16),
2665                &Data16
2666                );
2667     return Status;
2668   }
2669 
2670   if (Trb->Mode == SdMmcPioMode && !Trb->PioModeTransferCompleted) {
2671     Status = SdMmcTransferDataWithPio (Private, Trb, IntStatus);
2672     if (EFI_ERROR (Status)) {
2673       return Status;
2674     }
2675   }
2676 
2677   if ((Trb->Mode == SdMmcSdmaMode) && ((IntStatus & BIT3) != 0)) {
2678     Data16 = BIT3;
2679     Status = SdMmcHcRwMmio (
2680                Private->PciIo,
2681                Trb->Slot,
2682                SD_MMC_HC_NOR_INT_STS,
2683                FALSE,
2684                sizeof (Data16),
2685                &Data16
2686                );
2687     if (EFI_ERROR (Status)) {
2688       return Status;
2689     }
2690     Status = SdMmcUpdateSdmaAddress (Private, Trb);
2691     if (EFI_ERROR (Status)) {
2692       return Status;
2693     }
2694   }
2695 
2696   return EFI_NOT_READY;
2697 }
2698 
2699 /**
2700   Check the TRB execution result.
2701 
2702   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2703   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
2704 
2705   @retval EFI_SUCCESS       The TRB is executed successfully.
2706   @retval EFI_NOT_READY     The TRB is not completed for execution.
2707   @retval Others            Some erros happen when executing this request.
2708 
2709 **/
2710 EFI_STATUS
SdMmcCheckTrbResult(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)2711 SdMmcCheckTrbResult (
2712   IN SD_MMC_HC_PRIVATE_DATA           *Private,
2713   IN SD_MMC_HC_TRB                    *Trb
2714   )
2715 {
2716   EFI_STATUS                          Status;
2717   EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet;
2718   UINT16                              IntStatus;
2719 
2720   Packet  = Trb->Packet;
2721   //
2722   // Check Trb execution result by reading Normal Interrupt Status register.
2723   //
2724   Status = SdMmcHcRwMmio (
2725              Private->PciIo,
2726              Trb->Slot,
2727              SD_MMC_HC_NOR_INT_STS,
2728              TRUE,
2729              sizeof (IntStatus),
2730              &IntStatus
2731              );
2732   if (EFI_ERROR (Status)) {
2733     goto Done;
2734   }
2735 
2736   //
2737   // Check if there are any errors reported by host controller
2738   // and if neccessary recover the controller before next command is executed.
2739   //
2740   Status = SdMmcCheckAndRecoverErrors (Private, Trb->Slot, IntStatus);
2741   if (EFI_ERROR (Status)) {
2742     goto Done;
2743   }
2744 
2745   //
2746   // Tuning commands are the only ones that do not generate command
2747   // complete interrupt. Process them here before entering the code
2748   // that waits for command completion.
2749   //
2750   if (((Private->Slot[Trb->Slot].CardType == EmmcCardType) &&
2751        (Packet->SdMmcCmdBlk->CommandIndex == EMMC_SEND_TUNING_BLOCK)) ||
2752       ((Private->Slot[Trb->Slot].CardType == SdCardType) &&
2753        (Packet->SdMmcCmdBlk->CommandIndex == SD_SEND_TUNING_BLOCK))) {
2754     Status = SdMmcTransferDataWithPio (Private, Trb, IntStatus);
2755     goto Done;
2756   }
2757 
2758   if (!Trb->CommandComplete) {
2759     Status = SdMmcCheckCommandComplete (Private, Trb, IntStatus);
2760     if (EFI_ERROR (Status)) {
2761       goto Done;
2762     }
2763   }
2764 
2765   if (Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc ||
2766       Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR1b ||
2767       Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR5b) {
2768     Status = SdMmcCheckDataTransfer (Private, Trb, IntStatus);
2769   } else {
2770     Status = EFI_SUCCESS;
2771   }
2772 
2773 Done:
2774   if (Status != EFI_NOT_READY) {
2775     SdMmcHcLedOnOff (Private->PciIo, Trb->Slot, FALSE);
2776     if (EFI_ERROR (Status)) {
2777       DEBUG ((DEBUG_ERROR, "TRB failed with %r\n", Status));
2778       SdMmcPrintTrb (DEBUG_ERROR, Trb);
2779     } else {
2780       DEBUG ((DEBUG_VERBOSE, "TRB success\n"));
2781       SdMmcPrintTrb (DEBUG_VERBOSE, Trb);
2782     }
2783   }
2784 
2785   return Status;
2786 }
2787 
2788 /**
2789   Wait for the TRB execution result.
2790 
2791   @param[in] Private        A pointer to the SD_MMC_HC_PRIVATE_DATA instance.
2792   @param[in] Trb            The pointer to the SD_MMC_HC_TRB instance.
2793 
2794   @retval EFI_SUCCESS       The TRB is executed successfully.
2795   @retval Others            Some erros happen when executing this request.
2796 
2797 **/
2798 EFI_STATUS
SdMmcWaitTrbResult(IN SD_MMC_HC_PRIVATE_DATA * Private,IN SD_MMC_HC_TRB * Trb)2799 SdMmcWaitTrbResult (
2800   IN SD_MMC_HC_PRIVATE_DATA           *Private,
2801   IN SD_MMC_HC_TRB                    *Trb
2802   )
2803 {
2804   EFI_STATUS                          Status;
2805   EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet;
2806   UINT64                              Timeout;
2807   BOOLEAN                             InfiniteWait;
2808 
2809   Packet = Trb->Packet;
2810   //
2811   // Wait Command Complete Interrupt Status bit in Normal Interrupt Status Register
2812   //
2813   Timeout = Packet->Timeout;
2814   if (Timeout == 0) {
2815     InfiniteWait = TRUE;
2816   } else {
2817     InfiniteWait = FALSE;
2818   }
2819 
2820   while (InfiniteWait || (Timeout > 0)) {
2821     //
2822     // Check Trb execution result by reading Normal Interrupt Status register.
2823     //
2824     Status = SdMmcCheckTrbResult (Private, Trb);
2825     if (Status != EFI_NOT_READY) {
2826       return Status;
2827     }
2828     //
2829     // Stall for 1 microsecond.
2830     //
2831     gBS->Stall (1);
2832 
2833     Timeout--;
2834   }
2835 
2836   return EFI_TIMEOUT;
2837 }
2838 
2839