1 /** @file
2   This file implements ATA_PASSTHRU_PROCTOCOL and EXT_SCSI_PASSTHRU_PROTOCOL interfaces
3   for managed ATA controllers.
4 
5   Copyright (c) 2010 - 2016, Intel Corporation. All rights reserved.<BR>
6   This program and the accompanying materials
7   are licensed and made available under the terms and conditions of the BSD License
8   which accompanies this distribution.  The full text of the license may be found at
9   http://opensource.org/licenses/bsd-license.php
10 
11   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13 
14 **/
15 
16 #include "AtaAtapiPassThru.h"
17 
18 //
19 //  EFI_DRIVER_BINDING_PROTOCOL instance
20 //
21 EFI_DRIVER_BINDING_PROTOCOL gAtaAtapiPassThruDriverBinding = {
22   AtaAtapiPassThruSupported,
23   AtaAtapiPassThruStart,
24   AtaAtapiPassThruStop,
25   0x10,
26   NULL,
27   NULL
28 };
29 
30 ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = {
31   ATA_ATAPI_PASS_THRU_SIGNATURE,
32   0,                  // Controller Handle
33   NULL,               // PciIo Protocol
34   NULL,               // IdeControllerInit Protocol
35   {                   // AtaPassThruMode
36     //
37     // According to UEFI2.3 spec Section 12.10, Drivers for non-RAID ATA controllers should set
38     // both EFI_ATA_PASS_THRU_ATTRIBUTES_PHYSICAL and EFI_ATA_PASS_THRU_ATTRIBUTES_LOGICAL
39     // bits.
40     // Note that the driver doesn't support AtaPassThru non blocking I/O.
41     //
42     EFI_ATA_PASS_THRU_ATTRIBUTES_PHYSICAL | EFI_ATA_PASS_THRU_ATTRIBUTES_LOGICAL | EFI_ATA_PASS_THRU_ATTRIBUTES_NONBLOCKIO,
43     //
44     // IoAlign
45     //
46     sizeof (UINTN)
47   },
48   {                   // AtaPassThru
49     NULL,
50     AtaPassThruPassThru,
51     AtaPassThruGetNextPort,
52     AtaPassThruGetNextDevice,
53     AtaPassThruBuildDevicePath,
54     AtaPassThruGetDevice,
55     AtaPassThruResetPort,
56     AtaPassThruResetDevice
57   },
58   {                   // ExtScsiPassThruMode
59     //
60     // AdapterId
61     //
62     0,
63     //
64     // According to UEFI2.3 spec Section 14.7, Drivers for non-RAID SCSI controllers should set
65     // both EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_PHYSICAL and EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_LOGICAL
66     // bits.
67     // Note that the driver doesn't support ExtScsiPassThru non blocking I/O.
68     //
69     EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_PHYSICAL | EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_LOGICAL,
70     //
71     // IoAlign
72     //
73     sizeof (UINTN)
74   },
75   {                   // ExtScsiPassThru
76     NULL,
77     ExtScsiPassThruPassThru,
78     ExtScsiPassThruGetNextTargetLun,
79     ExtScsiPassThruBuildDevicePath,
80     ExtScsiPassThruGetTargetLun,
81     ExtScsiPassThruResetChannel,
82     ExtScsiPassThruResetTargetLun,
83     ExtScsiPassThruGetNextTarget
84   },
85   EfiAtaUnknownMode,  // Work Mode
86   {                   // IdeRegisters
87     {0},
88     {0}
89   },
90   {                   // AhciRegisters
91     0
92   },
93   {                   // DeviceList
94     NULL,
95     NULL
96   },
97   0,                  // OriginalAttributes
98   0,                  // PreviousPort
99   0,                  // PreviousPortMultiplier
100   0,                  // PreviousTargetId
101   0,                  // PreviousLun
102   NULL,               // Timer event
103   {                   // NonBlocking TaskList
104     NULL,
105     NULL
106   }
107 };
108 
109 ATAPI_DEVICE_PATH    mAtapiDevicePathTemplate = {
110   {
111     MESSAGING_DEVICE_PATH,
112     MSG_ATAPI_DP,
113     {
114       (UINT8) (sizeof (ATAPI_DEVICE_PATH)),
115       (UINT8) ((sizeof (ATAPI_DEVICE_PATH)) >> 8)
116     }
117   },
118   0,
119   0,
120   0
121 };
122 
123 SATA_DEVICE_PATH    mSataDevicePathTemplate = {
124   {
125     MESSAGING_DEVICE_PATH,
126     MSG_SATA_DP,
127     {
128       (UINT8) (sizeof (SATA_DEVICE_PATH)),
129       (UINT8) ((sizeof (SATA_DEVICE_PATH)) >> 8)
130     }
131   },
132   0,
133   0,
134   0
135 };
136 
137 UINT8 mScsiId[TARGET_MAX_BYTES] = {
138   0xFF, 0xFF, 0xFF, 0xFF,
139   0xFF, 0xFF, 0xFF, 0xFF,
140   0xFF, 0xFF, 0xFF, 0xFF,
141   0xFF, 0xFF, 0xFF, 0xFF
142 };
143 
144 /**
145   Sends an ATA command to an ATA device that is attached to the ATA controller. This function
146   supports both blocking I/O and non-blocking I/O. The blocking I/O functionality is required,
147   and the non-blocking I/O functionality is optional.
148 
149   @param[in]      Port               The port number of the ATA device to send the command.
150   @param[in]      PortMultiplierPort The port multiplier port number of the ATA device to send the command.
151                                      If there is no port multiplier, then specify 0xFFFF.
152   @param[in, out] Packet             A pointer to the ATA command to send to the ATA device specified by Port
153                                      and PortMultiplierPort.
154   @param[in]      Instance           Pointer to the ATA_ATAPI_PASS_THRU_INSTANCE.
155   @param[in]      Task               Optional. Pointer to the ATA_NONBLOCK_TASK
156                                      used by non-blocking mode.
157 
158   @retval EFI_SUCCESS                The ATA command was sent by the host. For
159                                      bi-directional commands, InTransferLength bytes
160                                      were transferred from InDataBuffer. For
161                                      write and bi-directional commands, OutTransferLength
162                                      bytes were transferred by OutDataBuffer.
163   @retval EFI_BAD_BUFFER_SIZE        The ATA command was not executed. The number
164                                      of bytes that could be transferred is returned
165                                      in InTransferLength. For write and bi-directional
166                                      commands, OutTransferLength bytes were transferred
167                                      by OutDataBuffer.
168   @retval EFI_NOT_READY              The ATA command could not be sent because
169                                      there are too many ATA commands already
170                                      queued. The caller may retry again later.
171   @retval EFI_DEVICE_ERROR           A device error occurred while attempting
172                                      to send the ATA command.
173   @retval EFI_INVALID_PARAMETER      Port, PortMultiplierPort, or the contents
174                                      of Acb are invalid. The ATA command was
175                                      not sent, so no additional status information
176                                      is available.
177 
178 **/
179 EFI_STATUS
180 EFIAPI
AtaPassThruPassThruExecute(IN UINT16 Port,IN UINT16 PortMultiplierPort,IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET * Packet,IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN ATA_NONBLOCK_TASK * Task OPTIONAL)181 AtaPassThruPassThruExecute (
182   IN     UINT16                           Port,
183   IN     UINT16                           PortMultiplierPort,
184   IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet,
185   IN     ATA_ATAPI_PASS_THRU_INSTANCE     *Instance,
186   IN     ATA_NONBLOCK_TASK                *Task OPTIONAL
187   )
188 {
189   EFI_ATA_PASS_THRU_CMD_PROTOCOL  Protocol;
190   EFI_ATA_HC_WORK_MODE            Mode;
191   EFI_STATUS                      Status;
192 
193   Protocol = Packet->Protocol;
194 
195   Mode = Instance->Mode;
196   switch (Mode) {
197     case EfiAtaIdeMode:
198       //
199       // Reassign IDE mode io port registers' base addresses
200       //
201       Status = GetIdeRegisterIoAddr (Instance->PciIo, Instance->IdeRegisters);
202 
203       if (EFI_ERROR (Status)) {
204         return Status;
205       }
206 
207       switch (Protocol) {
208         case EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA:
209           Status = AtaNonDataCommandIn (
210                      Instance->PciIo,
211                      &Instance->IdeRegisters[Port],
212                      Packet->Acb,
213                      Packet->Asb,
214                      Packet->Timeout,
215                      Task
216                      );
217           break;
218         case EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN:
219           Status = AtaPioDataInOut (
220                      Instance->PciIo,
221                      &Instance->IdeRegisters[Port],
222                      Packet->InDataBuffer,
223                      Packet->InTransferLength,
224                      TRUE,
225                      Packet->Acb,
226                      Packet->Asb,
227                      Packet->Timeout,
228                      Task
229                      );
230           break;
231         case EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_OUT:
232           Status = AtaPioDataInOut (
233                      Instance->PciIo,
234                      &Instance->IdeRegisters[Port],
235                      Packet->OutDataBuffer,
236                      Packet->OutTransferLength,
237                      FALSE,
238                      Packet->Acb,
239                      Packet->Asb,
240                      Packet->Timeout,
241                      Task
242                      );
243           break;
244         case EFI_ATA_PASS_THRU_PROTOCOL_UDMA_DATA_IN:
245           Status = AtaUdmaInOut (
246                      Instance,
247                      &Instance->IdeRegisters[Port],
248                      TRUE,
249                      Packet->InDataBuffer,
250                      Packet->InTransferLength,
251                      Packet->Acb,
252                      Packet->Asb,
253                      Packet->Timeout,
254                      Task
255                      );
256           break;
257         case EFI_ATA_PASS_THRU_PROTOCOL_UDMA_DATA_OUT:
258           Status = AtaUdmaInOut (
259                      Instance,
260                      &Instance->IdeRegisters[Port],
261                      FALSE,
262                      Packet->OutDataBuffer,
263                      Packet->OutTransferLength,
264                      Packet->Acb,
265                      Packet->Asb,
266                      Packet->Timeout,
267                      Task
268                      );
269           break;
270         default :
271           return EFI_UNSUPPORTED;
272       }
273       break;
274     case EfiAtaAhciMode :
275       if (PortMultiplierPort == 0xFFFF) {
276         //
277         // If there is no port multiplier, PortMultiplierPort will be 0xFFFF
278         // according to UEFI spec. Here, we convert its value to 0 to follow
279         // AHCI spec.
280         //
281         PortMultiplierPort = 0;
282       }
283       switch (Protocol) {
284         case EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA:
285           Status = AhciNonDataTransfer (
286                      Instance->PciIo,
287                      &Instance->AhciRegisters,
288                      (UINT8)Port,
289                      (UINT8)PortMultiplierPort,
290                      NULL,
291                      0,
292                      Packet->Acb,
293                      Packet->Asb,
294                      Packet->Timeout,
295                      Task
296                      );
297           break;
298         case EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN:
299           Status = AhciPioTransfer (
300                      Instance->PciIo,
301                      &Instance->AhciRegisters,
302                      (UINT8)Port,
303                      (UINT8)PortMultiplierPort,
304                      NULL,
305                      0,
306                      TRUE,
307                      Packet->Acb,
308                      Packet->Asb,
309                      Packet->InDataBuffer,
310                      Packet->InTransferLength,
311                      Packet->Timeout,
312                      Task
313                      );
314           break;
315         case EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_OUT:
316           Status = AhciPioTransfer (
317                      Instance->PciIo,
318                      &Instance->AhciRegisters,
319                      (UINT8)Port,
320                      (UINT8)PortMultiplierPort,
321                      NULL,
322                      0,
323                      FALSE,
324                      Packet->Acb,
325                      Packet->Asb,
326                      Packet->OutDataBuffer,
327                      Packet->OutTransferLength,
328                      Packet->Timeout,
329                      Task
330                      );
331           break;
332         case EFI_ATA_PASS_THRU_PROTOCOL_UDMA_DATA_IN:
333           Status = AhciDmaTransfer (
334                      Instance,
335                      &Instance->AhciRegisters,
336                      (UINT8)Port,
337                      (UINT8)PortMultiplierPort,
338                      NULL,
339                      0,
340                      TRUE,
341                      Packet->Acb,
342                      Packet->Asb,
343                      Packet->InDataBuffer,
344                      Packet->InTransferLength,
345                      Packet->Timeout,
346                      Task
347                      );
348           break;
349         case EFI_ATA_PASS_THRU_PROTOCOL_UDMA_DATA_OUT:
350           Status = AhciDmaTransfer (
351                      Instance,
352                      &Instance->AhciRegisters,
353                      (UINT8)Port,
354                      (UINT8)PortMultiplierPort,
355                      NULL,
356                      0,
357                      FALSE,
358                      Packet->Acb,
359                      Packet->Asb,
360                      Packet->OutDataBuffer,
361                      Packet->OutTransferLength,
362                      Packet->Timeout,
363                      Task
364                      );
365           break;
366         default :
367           return EFI_UNSUPPORTED;
368       }
369       break;
370 
371     default:
372       Status = EFI_DEVICE_ERROR;
373       break;
374   }
375 
376   return Status;
377 }
378 
379 /**
380   Call back function when the timer event is signaled.
381 
382   @param[in]  Event     The Event this notify function registered to.
383   @param[in]  Context   Pointer to the context data registered to the
384                         Event.
385 
386 **/
387 VOID
388 EFIAPI
AsyncNonBlockingTransferRoutine(EFI_EVENT Event,VOID * Context)389 AsyncNonBlockingTransferRoutine (
390   EFI_EVENT  Event,
391   VOID*      Context
392   )
393 {
394   LIST_ENTRY                   *Entry;
395   LIST_ENTRY                   *EntryHeader;
396   ATA_NONBLOCK_TASK            *Task;
397   EFI_STATUS                   Status;
398   ATA_ATAPI_PASS_THRU_INSTANCE *Instance;
399 
400   Instance   = (ATA_ATAPI_PASS_THRU_INSTANCE *) Context;
401   EntryHeader = &Instance->NonBlockingTaskList;
402   //
403   // Get the Taks from the Taks List and execute it, until there is
404   // no task in the list or the device is busy with task (EFI_NOT_READY).
405   //
406   while (TRUE) {
407     if (!IsListEmpty (EntryHeader)) {
408       Entry = GetFirstNode (EntryHeader);
409       Task  = ATA_NON_BLOCK_TASK_FROM_ENTRY (Entry);
410     } else {
411       return;
412     }
413 
414     Status = AtaPassThruPassThruExecute (
415                Task->Port,
416                Task->PortMultiplier,
417                Task->Packet,
418                Instance,
419                Task
420                );
421 
422     //
423     // If the data transfer meet a error, remove all tasks in the list since these tasks are
424     // associated with one task from Ata Bus and signal the event with error status.
425     //
426     if ((Status != EFI_NOT_READY) && (Status != EFI_SUCCESS)) {
427       DestroyAsynTaskList (Instance, TRUE);
428       break;
429     }
430 
431     //
432     // For Non blocking mode, the Status of EFI_NOT_READY means the operation
433     // is not finished yet. Otherwise the operation is successful.
434     //
435     if (Status == EFI_NOT_READY) {
436       break;
437     } else {
438       RemoveEntryList (&Task->Link);
439       gBS->SignalEvent (Task->Event);
440       FreePool (Task);
441     }
442   }
443 }
444 
445 /**
446   The Entry Point of module.
447 
448   @param[in] ImageHandle    The firmware allocated handle for the EFI image.
449   @param[in] SystemTable    A pointer to the EFI System Table.
450 
451   @retval EFI_SUCCESS       The entry point is executed successfully.
452   @retval other             Some error occurs when executing this entry point.
453 
454 **/
455 EFI_STATUS
456 EFIAPI
InitializeAtaAtapiPassThru(IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE * SystemTable)457 InitializeAtaAtapiPassThru (
458   IN EFI_HANDLE           ImageHandle,
459   IN EFI_SYSTEM_TABLE     *SystemTable
460   )
461 {
462   EFI_STATUS              Status;
463 
464   //
465   // Install driver model protocol(s).
466   //
467   Status = EfiLibInstallDriverBindingComponentName2 (
468              ImageHandle,
469              SystemTable,
470              &gAtaAtapiPassThruDriverBinding,
471              ImageHandle,
472              &gAtaAtapiPassThruComponentName,
473              &gAtaAtapiPassThruComponentName2
474              );
475   ASSERT_EFI_ERROR (Status);
476 
477   return Status;
478 }
479 
480 /**
481   Tests to see if this driver supports a given controller. If a child device is provided,
482   it further tests to see if this driver supports creating a handle for the specified child device.
483 
484   This function checks to see if the driver specified by This supports the device specified by
485   ControllerHandle. Drivers will typically use the device path attached to
486   ControllerHandle and/or the services from the bus I/O abstraction attached to
487   ControllerHandle to determine if the driver supports ControllerHandle. This function
488   may be called many times during platform initialization. In order to reduce boot times, the tests
489   performed by this function must be very small, and take as little time as possible to execute. This
490   function must not change the state of any hardware devices, and this function must be aware that the
491   device specified by ControllerHandle may already be managed by the same driver or a
492   different driver. This function must match its calls to AllocatePages() with FreePages(),
493   AllocatePool() with FreePool(), and OpenProtocol() with CloseProtocol().
494   Because ControllerHandle may have been previously started by the same driver, if a protocol is
495   already in the opened state, then it must not be closed with CloseProtocol(). This is required
496   to guarantee the state of ControllerHandle is not modified by this function.
497 
498   @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
499   @param[in]  ControllerHandle     The handle of the controller to test. This handle
500                                    must support a protocol interface that supplies
501                                    an I/O abstraction to the driver.
502   @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This
503                                    parameter is ignored by device drivers, and is optional for bus
504                                    drivers. For bus drivers, if this parameter is not NULL, then
505                                    the bus driver must determine if the bus controller specified
506                                    by ControllerHandle and the child controller specified
507                                    by RemainingDevicePath are both supported by this
508                                    bus driver.
509 
510   @retval EFI_SUCCESS              The device specified by ControllerHandle and
511                                    RemainingDevicePath is supported by the driver specified by This.
512   @retval EFI_ALREADY_STARTED      The device specified by ControllerHandle and
513                                    RemainingDevicePath is already being managed by the driver
514                                    specified by This.
515   @retval EFI_ACCESS_DENIED        The device specified by ControllerHandle and
516                                    RemainingDevicePath is already being managed by a different
517                                    driver or an application that requires exclusive access.
518                                    Currently not implemented.
519   @retval EFI_UNSUPPORTED          The device specified by ControllerHandle and
520                                    RemainingDevicePath is not supported by the driver specified by This.
521 **/
522 EFI_STATUS
523 EFIAPI
AtaAtapiPassThruSupported(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath)524 AtaAtapiPassThruSupported (
525   IN EFI_DRIVER_BINDING_PROTOCOL       *This,
526   IN EFI_HANDLE                        Controller,
527   IN EFI_DEVICE_PATH_PROTOCOL          *RemainingDevicePath
528   )
529 {
530   EFI_STATUS                        Status;
531   EFI_DEVICE_PATH_PROTOCOL          *ParentDevicePath;
532   EFI_PCI_IO_PROTOCOL               *PciIo;
533   PCI_TYPE00                        PciData;
534   EFI_IDE_CONTROLLER_INIT_PROTOCOL  *IdeControllerInit;
535 
536   //
537   // SATA Controller is a device driver, and should ingore the
538   // "RemainingDevicePath" according to UEFI spec
539   //
540   Status = gBS->OpenProtocol (
541                   Controller,
542                   &gEfiDevicePathProtocolGuid,
543                   (VOID *) &ParentDevicePath,
544                   This->DriverBindingHandle,
545                   Controller,
546                   EFI_OPEN_PROTOCOL_BY_DRIVER
547                   );
548   if (EFI_ERROR (Status)) {
549     //
550     // EFI_ALREADY_STARTED is also an error
551     //
552     return Status;
553   }
554   //
555   // Close the protocol because we don't use it here
556   //
557   gBS->CloseProtocol (
558                   Controller,
559                   &gEfiDevicePathProtocolGuid,
560                   This->DriverBindingHandle,
561                   Controller
562                   );
563 
564   Status = gBS->OpenProtocol (
565                   Controller,
566                   &gEfiIdeControllerInitProtocolGuid,
567                   (VOID **) &IdeControllerInit,
568                   This->DriverBindingHandle,
569                   Controller,
570                   EFI_OPEN_PROTOCOL_BY_DRIVER
571                   );
572 
573   if (EFI_ERROR (Status)) {
574     //
575     // EFI_ALREADY_STARTED is also an error
576     //
577     return Status;
578   }
579 
580   //
581   // Close the I/O Abstraction(s) used to perform the supported test
582   //
583   gBS->CloseProtocol (
584         Controller,
585         &gEfiIdeControllerInitProtocolGuid,
586         This->DriverBindingHandle,
587         Controller
588         );
589 
590   //
591   // Now test the EfiPciIoProtocol
592   //
593   Status = gBS->OpenProtocol (
594                   Controller,
595                   &gEfiPciIoProtocolGuid,
596                   (VOID **) &PciIo,
597                   This->DriverBindingHandle,
598                   Controller,
599                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
600                   );
601   if (EFI_ERROR (Status)) {
602     return Status;
603   }
604   //
605   // Now further check the PCI header: Base class (offset 0x0B) and
606   // Sub Class (offset 0x0A). This controller should be an ATA controller
607   //
608   Status = PciIo->Pci.Read (
609                         PciIo,
610                         EfiPciIoWidthUint8,
611                         PCI_CLASSCODE_OFFSET,
612                         sizeof (PciData.Hdr.ClassCode),
613                         PciData.Hdr.ClassCode
614                         );
615   if (EFI_ERROR (Status)) {
616     return EFI_UNSUPPORTED;
617   }
618 
619   if (IS_PCI_IDE (&PciData) || IS_PCI_SATADPA (&PciData)) {
620     return EFI_SUCCESS;
621   }
622 
623   return EFI_UNSUPPORTED;
624 }
625 
626 /**
627   Starts a device controller or a bus controller.
628 
629   The Start() function is designed to be invoked from the EFI boot service ConnectController().
630   As a result, much of the error checking on the parameters to Start() has been moved into this
631   common boot service. It is legal to call Start() from other locations,
632   but the following calling restrictions must be followed, or the system behavior will not be deterministic.
633   1. ControllerHandle must be a valid EFI_HANDLE.
634   2. If RemainingDevicePath is not NULL, then it must be a pointer to a naturally aligned
635      EFI_DEVICE_PATH_PROTOCOL.
636   3. Prior to calling Start(), the Supported() function for the driver specified by This must
637      have been called with the same calling parameters, and Supported() must have returned EFI_SUCCESS.
638 
639   @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
640   @param[in]  ControllerHandle     The handle of the controller to start. This handle
641                                    must support a protocol interface that supplies
642                                    an I/O abstraction to the driver.
643   @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This
644                                    parameter is ignored by device drivers, and is optional for bus
645                                    drivers. For a bus driver, if this parameter is NULL, then handles
646                                    for all the children of Controller are created by this driver.
647                                    If this parameter is not NULL and the first Device Path Node is
648                                    not the End of Device Path Node, then only the handle for the
649                                    child device specified by the first Device Path Node of
650                                    RemainingDevicePath is created by this driver.
651                                    If the first Device Path Node of RemainingDevicePath is
652                                    the End of Device Path Node, no child handle is created by this
653                                    driver.
654 
655   @retval EFI_SUCCESS              The device was started.
656   @retval EFI_DEVICE_ERROR         The device could not be started due to a device error.Currently not implemented.
657   @retval EFI_OUT_OF_RESOURCES     The request could not be completed due to a lack of resources.
658   @retval Others                   The driver failded to start the device.
659 
660 **/
661 EFI_STATUS
662 EFIAPI
AtaAtapiPassThruStart(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath)663 AtaAtapiPassThruStart (
664   IN EFI_DRIVER_BINDING_PROTOCOL        *This,
665   IN EFI_HANDLE                         Controller,
666   IN EFI_DEVICE_PATH_PROTOCOL           *RemainingDevicePath
667   )
668 {
669   EFI_STATUS                        Status;
670   EFI_IDE_CONTROLLER_INIT_PROTOCOL  *IdeControllerInit;
671   ATA_ATAPI_PASS_THRU_INSTANCE      *Instance;
672   EFI_PCI_IO_PROTOCOL               *PciIo;
673   UINT64                            Supports;
674   UINT64                            OriginalPciAttributes;
675 
676   Status                = EFI_SUCCESS;
677   IdeControllerInit     = NULL;
678   Instance              = NULL;
679   OriginalPciAttributes = 0;
680 
681   DEBUG ((EFI_D_INFO, "==AtaAtapiPassThru Start== Controller = %x\n", Controller));
682 
683   Status  = gBS->OpenProtocol (
684                    Controller,
685                    &gEfiIdeControllerInitProtocolGuid,
686                    (VOID **) &IdeControllerInit,
687                    This->DriverBindingHandle,
688                    Controller,
689                    EFI_OPEN_PROTOCOL_BY_DRIVER
690                    );
691 
692   if (EFI_ERROR (Status)) {
693     DEBUG ((EFI_D_ERROR, "Open Ide_Controller_Init Error, Status=%r", Status));
694     goto ErrorExit;
695   }
696 
697   Status = gBS->OpenProtocol (
698                   Controller,
699                   &gEfiPciIoProtocolGuid,
700                   (VOID **) &PciIo,
701                   This->DriverBindingHandle,
702                   Controller,
703                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
704                   );
705   if (EFI_ERROR (Status)) {
706     DEBUG ((EFI_D_ERROR, "Get Pci_Io Protocol Error, Status=%r", Status));
707     goto ErrorExit;
708   }
709 
710   Status = PciIo->Attributes (
711                     PciIo,
712                     EfiPciIoAttributeOperationGet,
713                     0,
714                     &OriginalPciAttributes
715                     );
716 
717   if (EFI_ERROR (Status)) {
718     goto ErrorExit;
719   }
720 
721   Status = PciIo->Attributes (
722                     PciIo,
723                     EfiPciIoAttributeOperationSupported,
724                     0,
725                     &Supports
726                     );
727   if (!EFI_ERROR (Status)) {
728     Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE;
729     Status = PciIo->Attributes (
730                       PciIo,
731                       EfiPciIoAttributeOperationEnable,
732                       Supports,
733                       NULL
734                       );
735   }
736 
737   if (EFI_ERROR (Status)) {
738     goto ErrorExit;
739   }
740 
741   //
742   // Allocate a buffer to store the ATA_ATAPI_PASS_THRU_INSTANCE data structure
743   //
744   Instance = AllocateCopyPool (sizeof (ATA_ATAPI_PASS_THRU_INSTANCE), &gAtaAtapiPassThruInstanceTemplate);
745   if (Instance == NULL) {
746     goto ErrorExit;
747   }
748 
749   Instance->ControllerHandle      = Controller;
750   Instance->IdeControllerInit     = IdeControllerInit;
751   Instance->PciIo                 = PciIo;
752   Instance->OriginalPciAttributes = OriginalPciAttributes;
753   Instance->AtaPassThru.Mode      = &Instance->AtaPassThruMode;
754   Instance->ExtScsiPassThru.Mode  = &Instance->ExtScsiPassThruMode;
755   InitializeListHead(&Instance->DeviceList);
756   InitializeListHead(&Instance->NonBlockingTaskList);
757 
758   Instance->TimerEvent = NULL;
759 
760   Status = gBS->CreateEvent (
761                   EVT_TIMER | EVT_NOTIFY_SIGNAL,
762                   TPL_NOTIFY,
763                   AsyncNonBlockingTransferRoutine,
764                   Instance,
765                   &Instance->TimerEvent
766                   );
767   if (EFI_ERROR (Status)) {
768     goto ErrorExit;
769   }
770 
771   //
772   // Set 1ms timer.
773   //
774   Status = gBS->SetTimer (Instance->TimerEvent, TimerPeriodic, 10000);
775   if (EFI_ERROR (Status)) {
776     goto ErrorExit;
777   }
778 
779   //
780   // Enumerate all inserted ATA devices.
781   //
782   Status = EnumerateAttachedDevice (Instance);
783   if (EFI_ERROR (Status)) {
784     goto ErrorExit;
785   }
786 
787   Status = gBS->InstallMultipleProtocolInterfaces (
788                   &Controller,
789                   &gEfiAtaPassThruProtocolGuid, &(Instance->AtaPassThru),
790                   &gEfiExtScsiPassThruProtocolGuid, &(Instance->ExtScsiPassThru),
791                   NULL
792                   );
793   ASSERT_EFI_ERROR (Status);
794 
795   return Status;
796 
797 ErrorExit:
798   if (IdeControllerInit != NULL) {
799     gBS->CloseProtocol (
800            Controller,
801            &gEfiIdeControllerInitProtocolGuid,
802            This->DriverBindingHandle,
803            Controller
804            );
805   }
806 
807   if ((Instance != NULL) && (Instance->TimerEvent != NULL)) {
808     gBS->CloseEvent (Instance->TimerEvent);
809   }
810 
811   //
812   // Remove all inserted ATA devices.
813   //
814   DestroyDeviceInfoList(Instance);
815 
816   if (Instance != NULL) {
817     FreePool (Instance);
818   }
819   return EFI_UNSUPPORTED;
820 }
821 
822 /**
823   Stops a device controller or a bus controller.
824 
825   The Stop() function is designed to be invoked from the EFI boot service DisconnectController().
826   As a result, much of the error checking on the parameters to Stop() has been moved
827   into this common boot service. It is legal to call Stop() from other locations,
828   but the following calling restrictions must be followed, or the system behavior will not be deterministic.
829   1. ControllerHandle must be a valid EFI_HANDLE that was used on a previous call to this
830      same driver's Start() function.
831   2. The first NumberOfChildren handles of ChildHandleBuffer must all be a valid
832      EFI_HANDLE. In addition, all of these handles must have been created in this driver's
833      Start() function, and the Start() function must have called OpenProtocol() on
834      ControllerHandle with an Attribute of EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER.
835 
836   @param[in]  This              A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
837   @param[in]  ControllerHandle  A handle to the device being stopped. The handle must
838                                 support a bus specific I/O protocol for the driver
839                                 to use to stop the device.
840   @param[in]  NumberOfChildren  The number of child device handles in ChildHandleBuffer.
841   @param[in]  ChildHandleBuffer An array of child handles to be freed. May be NULL
842                                 if NumberOfChildren is 0.
843 
844   @retval EFI_SUCCESS           The device was stopped.
845   @retval EFI_DEVICE_ERROR      The device could not be stopped due to a device error.
846 
847 **/
848 EFI_STATUS
849 EFIAPI
AtaAtapiPassThruStop(IN EFI_DRIVER_BINDING_PROTOCOL * This,IN EFI_HANDLE Controller,IN UINTN NumberOfChildren,IN EFI_HANDLE * ChildHandleBuffer)850 AtaAtapiPassThruStop (
851   IN  EFI_DRIVER_BINDING_PROTOCOL       *This,
852   IN  EFI_HANDLE                        Controller,
853   IN  UINTN                             NumberOfChildren,
854   IN  EFI_HANDLE                        *ChildHandleBuffer
855   )
856 {
857   EFI_STATUS                        Status;
858   ATA_ATAPI_PASS_THRU_INSTANCE      *Instance;
859   EFI_ATA_PASS_THRU_PROTOCOL        *AtaPassThru;
860   EFI_PCI_IO_PROTOCOL               *PciIo;
861   EFI_AHCI_REGISTERS                *AhciRegisters;
862   UINT64                            Supports;
863 
864   DEBUG ((EFI_D_INFO, "==AtaAtapiPassThru Stop== Controller = %x\n", Controller));
865 
866   Status = gBS->OpenProtocol (
867                   Controller,
868                   &gEfiAtaPassThruProtocolGuid,
869                   (VOID **) &AtaPassThru,
870                   This->DriverBindingHandle,
871                   Controller,
872                   EFI_OPEN_PROTOCOL_GET_PROTOCOL
873                   );
874 
875   if (EFI_ERROR (Status)) {
876     return EFI_DEVICE_ERROR;
877   }
878 
879   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (AtaPassThru);
880 
881   Status = gBS->UninstallMultipleProtocolInterfaces (
882                   Controller,
883                   &gEfiAtaPassThruProtocolGuid, &(Instance->AtaPassThru),
884                   &gEfiExtScsiPassThruProtocolGuid, &(Instance->ExtScsiPassThru),
885                   NULL
886                   );
887 
888   if (EFI_ERROR (Status)) {
889     return EFI_DEVICE_ERROR;
890   }
891 
892   //
893   // Close protocols opened by AtaAtapiPassThru controller driver
894   //
895   gBS->CloseProtocol (
896          Controller,
897          &gEfiIdeControllerInitProtocolGuid,
898          This->DriverBindingHandle,
899          Controller
900          );
901 
902   //
903   // Close Non-Blocking timer and free Task list.
904   //
905   if (Instance->TimerEvent != NULL) {
906     gBS->CloseEvent (Instance->TimerEvent);
907     Instance->TimerEvent = NULL;
908   }
909   DestroyAsynTaskList (Instance, FALSE);
910   //
911   // Free allocated resource
912   //
913   DestroyDeviceInfoList (Instance);
914 
915   //
916   // If the current working mode is AHCI mode, then pre-allocated resource
917   // for AHCI initialization should be released.
918   //
919   PciIo = Instance->PciIo;
920 
921   if (Instance->Mode == EfiAtaAhciMode) {
922     AhciRegisters = &Instance->AhciRegisters;
923     PciIo->Unmap (
924              PciIo,
925              AhciRegisters->MapCommandTable
926              );
927     PciIo->FreeBuffer (
928              PciIo,
929              EFI_SIZE_TO_PAGES ((UINTN) AhciRegisters->MaxCommandTableSize),
930              AhciRegisters->AhciCommandTable
931              );
932     PciIo->Unmap (
933              PciIo,
934              AhciRegisters->MapCmdList
935              );
936     PciIo->FreeBuffer (
937              PciIo,
938              EFI_SIZE_TO_PAGES ((UINTN) AhciRegisters->MaxCommandListSize),
939              AhciRegisters->AhciCmdList
940              );
941     PciIo->Unmap (
942              PciIo,
943              AhciRegisters->MapRFis
944              );
945     PciIo->FreeBuffer (
946              PciIo,
947              EFI_SIZE_TO_PAGES ((UINTN) AhciRegisters->MaxReceiveFisSize),
948              AhciRegisters->AhciRFis
949              );
950   }
951 
952   //
953   // Disable this ATA host controller.
954   //
955   Status = PciIo->Attributes (
956                     PciIo,
957                     EfiPciIoAttributeOperationSupported,
958                     0,
959                     &Supports
960                     );
961   if (!EFI_ERROR (Status)) {
962     Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE;
963     PciIo->Attributes (
964              PciIo,
965              EfiPciIoAttributeOperationDisable,
966              Supports,
967              NULL
968              );
969   }
970 
971   //
972   // Restore original PCI attributes
973   //
974   Status = PciIo->Attributes (
975                     PciIo,
976                     EfiPciIoAttributeOperationSet,
977                     Instance->OriginalPciAttributes,
978                     NULL
979                     );
980   ASSERT_EFI_ERROR (Status);
981 
982   FreePool (Instance);
983 
984   return Status;
985 }
986 
987 /**
988   Traverse the attached ATA devices list to find out the device to access.
989 
990   @param[in]  Instance            A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.
991   @param[in]  Port                The port number of the ATA device to send the command.
992   @param[in]  PortMultiplierPort  The port multiplier port number of the ATA device to send the command.
993                                   If there is no port multiplier, then specify 0xFFFF.
994   @param[in]  DeviceType          The device type of the ATA device.
995 
996   @retval     The pointer to the data structure of the device info to access.
997 
998 **/
999 LIST_ENTRY *
1000 EFIAPI
SearchDeviceInfoList(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT16 Port,IN UINT16 PortMultiplier,IN EFI_ATA_DEVICE_TYPE DeviceType)1001 SearchDeviceInfoList (
1002   IN  ATA_ATAPI_PASS_THRU_INSTANCE  *Instance,
1003   IN  UINT16                         Port,
1004   IN  UINT16                         PortMultiplier,
1005   IN  EFI_ATA_DEVICE_TYPE            DeviceType
1006   )
1007 {
1008   EFI_ATA_DEVICE_INFO  *DeviceInfo;
1009   LIST_ENTRY           *Node;
1010 
1011   Node = GetFirstNode (&Instance->DeviceList);
1012   while (!IsNull (&Instance->DeviceList, Node)) {
1013     DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1014 
1015     //
1016     // For CD-ROM working in the AHCI mode, only 8 bits are used to record
1017     // the PortMultiplier information. If the CD-ROM is directly attached
1018     // on a SATA port, the PortMultiplier should be translated from 0xFF
1019     // to 0xFFFF according to the UEFI spec.
1020     //
1021     if ((Instance->Mode == EfiAtaAhciMode) &&
1022         (DeviceInfo->Type == EfiIdeCdrom) &&
1023         (PortMultiplier == 0xFF)) {
1024         PortMultiplier = 0xFFFF;
1025     }
1026 
1027     if ((DeviceInfo->Type == DeviceType) &&
1028         (Port == DeviceInfo->Port) &&
1029         (PortMultiplier == DeviceInfo->PortMultiplier)) {
1030       return Node;
1031     }
1032 
1033     Node = GetNextNode (&Instance->DeviceList, Node);
1034   }
1035 
1036   return NULL;
1037 }
1038 
1039 /**
1040   Allocate device info data structure to contain device info.
1041   And insert the data structure to the tail of device list for tracing.
1042 
1043   @param[in]  Instance            A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.
1044   @param[in]  Port                The port number of the ATA device to send the command.
1045   @param[in]  PortMultiplierPort  The port multiplier port number of the ATA device to send the command.
1046                                   If there is no port multiplier, then specify 0xFFFF.
1047   @param[in]  DeviceType          The device type of the ATA device.
1048   @param[in]  IdentifyData        The data buffer to store the output of the IDENTIFY cmd.
1049 
1050   @retval EFI_SUCCESS             Successfully insert the ata device to the tail of device list.
1051   @retval EFI_OUT_OF_RESOURCES    Can not allocate enough resource for use.
1052 
1053 **/
1054 EFI_STATUS
1055 EFIAPI
CreateNewDeviceInfo(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN UINT16 Port,IN UINT16 PortMultiplier,IN EFI_ATA_DEVICE_TYPE DeviceType,IN EFI_IDENTIFY_DATA * IdentifyData)1056 CreateNewDeviceInfo (
1057   IN  ATA_ATAPI_PASS_THRU_INSTANCE   *Instance,
1058   IN  UINT16                         Port,
1059   IN  UINT16                         PortMultiplier,
1060   IN  EFI_ATA_DEVICE_TYPE            DeviceType,
1061   IN  EFI_IDENTIFY_DATA              *IdentifyData
1062   )
1063 {
1064   EFI_ATA_DEVICE_INFO  *DeviceInfo;
1065 
1066   DeviceInfo = AllocateZeroPool (sizeof (EFI_ATA_DEVICE_INFO));
1067 
1068   if (DeviceInfo == NULL) {
1069     return EFI_OUT_OF_RESOURCES;
1070   }
1071 
1072   DeviceInfo->Signature      = ATA_ATAPI_DEVICE_SIGNATURE;
1073   DeviceInfo->Port           = Port;
1074   DeviceInfo->PortMultiplier = PortMultiplier;
1075   DeviceInfo->Type           = DeviceType;
1076 
1077   if (IdentifyData != NULL) {
1078     DeviceInfo->IdentifyData = AllocateCopyPool (sizeof (EFI_IDENTIFY_DATA), IdentifyData);
1079     if (DeviceInfo->IdentifyData == NULL) {
1080       FreePool (DeviceInfo);
1081       return EFI_OUT_OF_RESOURCES;
1082     }
1083   }
1084 
1085   InsertTailList (&Instance->DeviceList, &DeviceInfo->Link);
1086 
1087   return EFI_SUCCESS;
1088 }
1089 
1090 /**
1091   Destroy all attached ATA devices info.
1092 
1093   @param[in]  Instance          A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.
1094 
1095 **/
1096 VOID
1097 EFIAPI
DestroyDeviceInfoList(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance)1098 DestroyDeviceInfoList (
1099   IN  ATA_ATAPI_PASS_THRU_INSTANCE  *Instance
1100   )
1101 {
1102   EFI_ATA_DEVICE_INFO  *DeviceInfo;
1103   LIST_ENTRY           *Node;
1104 
1105   Node = GetFirstNode (&Instance->DeviceList);
1106   while (!IsNull (&Instance->DeviceList, Node)) {
1107     DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1108 
1109     Node = GetNextNode (&Instance->DeviceList, Node);
1110 
1111     RemoveEntryList (&DeviceInfo->Link);
1112     if (DeviceInfo->IdentifyData != NULL) {
1113       FreePool (DeviceInfo->IdentifyData);
1114     }
1115     FreePool (DeviceInfo);
1116   }
1117 }
1118 
1119 /**
1120   Destroy all pending non blocking tasks.
1121 
1122   @param[in]  Instance    A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.
1123   @param[in]  IsSigEvent  Indicate whether signal the task event when remove the
1124                           task.
1125 
1126 **/
1127 VOID
1128 EFIAPI
DestroyAsynTaskList(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance,IN BOOLEAN IsSigEvent)1129 DestroyAsynTaskList (
1130   IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance,
1131   IN BOOLEAN                       IsSigEvent
1132   )
1133 {
1134   LIST_ENTRY           *Entry;
1135   LIST_ENTRY           *DelEntry;
1136   ATA_NONBLOCK_TASK    *Task;
1137   EFI_TPL              OldTpl;
1138 
1139   OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
1140   if (!IsListEmpty (&Instance->NonBlockingTaskList)) {
1141     //
1142     // Free the Subtask list.
1143     //
1144     for (Entry = (&Instance->NonBlockingTaskList)->ForwardLink;
1145         Entry != (&Instance->NonBlockingTaskList);
1146        ) {
1147       DelEntry = Entry;
1148       Entry    = Entry->ForwardLink;
1149       Task     = ATA_NON_BLOCK_TASK_FROM_ENTRY (DelEntry);
1150 
1151       RemoveEntryList (DelEntry);
1152       if (IsSigEvent) {
1153         Task->Packet->Asb->AtaStatus = 0x01;
1154         gBS->SignalEvent (Task->Event);
1155       }
1156       FreePool (Task);
1157     }
1158   }
1159   gBS->RestoreTPL (OldTpl);
1160 }
1161 
1162 /**
1163   Enumerate all attached ATA devices at IDE mode or AHCI mode separately.
1164 
1165   The function is designed to enumerate all attached ATA devices.
1166 
1167   @param[in]  Instance          A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.
1168 
1169   @retval EFI_SUCCESS           Successfully enumerate attached ATA devices.
1170   @retval EFI_DEVICE_ERROR      The device could not be stopped due to a device error.
1171 
1172 **/
1173 EFI_STATUS
1174 EFIAPI
EnumerateAttachedDevice(IN ATA_ATAPI_PASS_THRU_INSTANCE * Instance)1175 EnumerateAttachedDevice (
1176   IN  ATA_ATAPI_PASS_THRU_INSTANCE      *Instance
1177   )
1178 {
1179   EFI_STATUS                   Status;
1180   PCI_TYPE00                   PciData;
1181   UINT8                        ClassCode;
1182 
1183   Status = EFI_SUCCESS;
1184 
1185   Status = Instance->PciIo->Pci.Read (
1186                                   Instance->PciIo,
1187                                   EfiPciIoWidthUint8,
1188                                   PCI_CLASSCODE_OFFSET,
1189                                   sizeof (PciData.Hdr.ClassCode),
1190                                   PciData.Hdr.ClassCode
1191                                   );
1192   ASSERT_EFI_ERROR (Status);
1193 
1194   ClassCode = PciData.Hdr.ClassCode[1];
1195 
1196   switch (ClassCode) {
1197     case PCI_CLASS_MASS_STORAGE_IDE :
1198       //
1199       // The ATA controller is working at IDE mode
1200       //
1201       Instance->Mode = EfiAtaIdeMode;
1202 
1203       Status = IdeModeInitialization (Instance);
1204       if (EFI_ERROR (Status)) {
1205         Status = EFI_DEVICE_ERROR;
1206         goto Done;
1207       }
1208       break;
1209     case PCI_CLASS_MASS_STORAGE_SATADPA :
1210       //
1211       // The ATA controller is working at AHCI mode
1212       //
1213       Instance->Mode = EfiAtaAhciMode;
1214 
1215       Status = AhciModeInitialization (Instance);
1216 
1217       if (EFI_ERROR (Status)) {
1218         Status = EFI_DEVICE_ERROR;
1219         goto Done;
1220       }
1221 
1222       break;
1223     default :
1224       Status = EFI_UNSUPPORTED;
1225   }
1226 
1227 Done:
1228   return Status;
1229 }
1230 
1231 /**
1232   Sends an ATA command to an ATA device that is attached to the ATA controller. This function
1233   supports both blocking I/O and non-blocking I/O. The blocking I/O functionality is required,
1234   and the non-blocking I/O functionality is optional.
1235 
1236   @param[in]      This               A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1237   @param[in]      Port               The port number of the ATA device to send the command.
1238   @param[in]      PortMultiplierPort The port multiplier port number of the ATA device to send the command.
1239                                      If there is no port multiplier, then specify 0xFFFF.
1240   @param[in, out] Packet             A pointer to the ATA command to send to the ATA device specified by Port
1241                                      and PortMultiplierPort.
1242   @param[in]      Event               If non-blocking I/O is not supported then Event is ignored, and blocking
1243                                      I/O is performed. If Event is NULL, then blocking I/O is performed. If
1244                                      Event is not NULL and non blocking I/O is supported, then non-blocking
1245                                      I/O is performed, and Event will be signaled when the ATA command completes.
1246 
1247   @retval EFI_SUCCESS                The ATA command was sent by the host. For bi-directional commands,
1248                                      InTransferLength bytes were transferred from InDataBuffer. For write and
1249                                      bi-directional commands, OutTransferLength bytes were transferred by OutDataBuffer.
1250   @retval EFI_BAD_BUFFER_SIZE        The ATA command was not executed. The number of bytes that could be transferred
1251                                      is returned in InTransferLength. For write and bi-directional commands,
1252                                      OutTransferLength bytes were transferred by OutDataBuffer.
1253   @retval EFI_NOT_READY              The ATA command could not be sent because there are too many ATA commands
1254                                      already queued. The caller may retry again later.
1255   @retval EFI_DEVICE_ERROR           A device error occurred while attempting to send the ATA command.
1256   @retval EFI_INVALID_PARAMETER      Port, PortMultiplierPort, or the contents of Acb are invalid. The ATA
1257                                      command was not sent, so no additional status information is available.
1258 
1259 **/
1260 EFI_STATUS
1261 EFIAPI
AtaPassThruPassThru(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN UINT16 Port,IN UINT16 PortMultiplierPort,IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET * Packet,IN EFI_EVENT Event OPTIONAL)1262 AtaPassThruPassThru (
1263   IN     EFI_ATA_PASS_THRU_PROTOCOL       *This,
1264   IN     UINT16                           Port,
1265   IN     UINT16                           PortMultiplierPort,
1266   IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet,
1267   IN     EFI_EVENT                        Event OPTIONAL
1268   )
1269 {
1270   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1271   LIST_ENTRY                      *Node;
1272   EFI_ATA_DEVICE_INFO             *DeviceInfo;
1273   EFI_IDENTIFY_DATA               *IdentifyData;
1274   UINT64                          Capacity;
1275   UINT32                          MaxSectorCount;
1276   ATA_NONBLOCK_TASK               *Task;
1277   EFI_TPL                         OldTpl;
1278   UINT32                          BlockSize;
1279 
1280   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1281 
1282   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->InDataBuffer, This->Mode->IoAlign)) {
1283     return EFI_INVALID_PARAMETER;
1284   }
1285 
1286   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->OutDataBuffer, This->Mode->IoAlign)) {
1287     return EFI_INVALID_PARAMETER;
1288   }
1289 
1290   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->Asb, This->Mode->IoAlign)) {
1291     return EFI_INVALID_PARAMETER;
1292   }
1293 
1294   Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeHarddisk);
1295 
1296   if (Node == NULL) {
1297     Node = SearchDeviceInfoList(Instance, Port, PortMultiplierPort, EfiIdeCdrom);
1298     if (Node == NULL) {
1299       return EFI_INVALID_PARAMETER;
1300     }
1301   }
1302 
1303   //
1304   // Check whether this device needs 48-bit addressing (ATAPI-6 ata device).
1305   // Per ATA-6 spec, word83: bit15 is zero and bit14 is one.
1306   // If bit10 is one, it means the ata device support 48-bit addressing.
1307   //
1308   DeviceInfo     = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1309   IdentifyData   = DeviceInfo->IdentifyData;
1310   MaxSectorCount = 0x100;
1311   if ((IdentifyData->AtaData.command_set_supported_83 & (BIT10 | BIT15 | BIT14)) == 0x4400) {
1312     Capacity = *((UINT64 *)IdentifyData->AtaData.maximum_lba_for_48bit_addressing);
1313     if (Capacity > 0xFFFFFFF) {
1314       //
1315       // Capacity exceeds 120GB. 48-bit addressing is really needed
1316       // In this case, the max sector count is 0x10000
1317       //
1318       MaxSectorCount = 0x10000;
1319     }
1320   }
1321 
1322   BlockSize = 0x200;
1323   if ((IdentifyData->AtaData.phy_logic_sector_support & (BIT14 | BIT15)) == BIT14) {
1324     //
1325     // Check logical block size
1326     //
1327     if ((IdentifyData->AtaData.phy_logic_sector_support & BIT12) != 0) {
1328       BlockSize = (UINT32) (((IdentifyData->AtaData.logic_sector_size_hi << 16) | IdentifyData->AtaData.logic_sector_size_lo) * sizeof (UINT16));
1329     }
1330   }
1331 
1332   //
1333   // convert the transfer length from sector count to byte.
1334   //
1335   if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) &&
1336        (Packet->InTransferLength != 0)) {
1337     Packet->InTransferLength = Packet->InTransferLength * BlockSize;
1338   }
1339 
1340   //
1341   // convert the transfer length from sector count to byte.
1342   //
1343   if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) &&
1344        (Packet->OutTransferLength != 0)) {
1345     Packet->OutTransferLength = Packet->OutTransferLength * BlockSize;
1346   }
1347 
1348   //
1349   // If the data buffer described by InDataBuffer/OutDataBuffer and InTransferLength/OutTransferLength
1350   // is too big to be transferred in a single command, then no data is transferred and EFI_BAD_BUFFER_SIZE
1351   // is returned.
1352   //
1353   if (((Packet->InTransferLength != 0) && (Packet->InTransferLength > MaxSectorCount * BlockSize)) ||
1354       ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * BlockSize))) {
1355     return EFI_BAD_BUFFER_SIZE;
1356   }
1357 
1358   //
1359   // For non-blocking mode, queue the Task into the list.
1360   //
1361   if (Event != NULL) {
1362     Task = AllocateZeroPool (sizeof (ATA_NONBLOCK_TASK));
1363     if (Task == NULL) {
1364       return EFI_OUT_OF_RESOURCES;
1365     }
1366 
1367     Task->Signature      = ATA_NONBLOCKING_TASK_SIGNATURE;
1368     Task->Port           = Port;
1369     Task->PortMultiplier = PortMultiplierPort;
1370     Task->Packet         = Packet;
1371     Task->Event          = Event;
1372     Task->IsStart        = FALSE;
1373     Task->RetryTimes     = DivU64x32(Packet->Timeout, 1000) + 1;
1374     if (Packet->Timeout == 0) {
1375       Task->InfiniteWait = TRUE;
1376     } else {
1377       Task->InfiniteWait = FALSE;
1378     }
1379 
1380     OldTpl = gBS->RaiseTPL (TPL_NOTIFY);
1381     InsertTailList (&Instance->NonBlockingTaskList, &Task->Link);
1382     gBS->RestoreTPL (OldTpl);
1383 
1384     return EFI_SUCCESS;
1385   } else {
1386     return AtaPassThruPassThruExecute (
1387              Port,
1388              PortMultiplierPort,
1389              Packet,
1390              Instance,
1391              NULL
1392              );
1393   }
1394 }
1395 
1396 /**
1397   Used to retrieve the list of legal port numbers for ATA devices on an ATA controller.
1398   These can either be the list of ports where ATA devices are actually present or the
1399   list of legal port numbers for the ATA controller. Regardless, the caller of this
1400   function must probe the port number returned to see if an ATA device is actually
1401   present at that location on the ATA controller.
1402 
1403   The GetNextPort() function retrieves the port number on an ATA controller. If on input
1404   Port is 0xFFFF, then the port number of the first port on the ATA controller is returned
1405   in Port and EFI_SUCCESS is returned.
1406 
1407   If Port is a port number that was returned on a previous call to GetNextPort(), then the
1408   port number of the next port on the ATA controller is returned in Port, and EFI_SUCCESS
1409   is returned. If Port is not 0xFFFF and Port was not returned on a previous call to
1410   GetNextPort(), then EFI_INVALID_PARAMETER is returned.
1411 
1412   If Port is the port number of the last port on the ATA controller, then EFI_NOT_FOUND is
1413   returned.
1414 
1415   @param[in]      This          A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1416   @param[in, out] Port          On input, a pointer to the port number on the ATA controller.
1417                                 On output, a pointer to the next port number on the ATA
1418                                 controller. An input value of 0xFFFF retrieves the first port
1419                                 number on the ATA controller.
1420 
1421   @retval EFI_SUCCESS           The next port number on the ATA controller was returned in Port.
1422   @retval EFI_NOT_FOUND         There are no more ports on this ATA controller.
1423   @retval EFI_INVALID_PARAMETER Port is not 0xFFFF and Port was not returned on a previous call
1424                                 to GetNextPort().
1425 
1426 **/
1427 EFI_STATUS
1428 EFIAPI
AtaPassThruGetNextPort(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN OUT UINT16 * Port)1429 AtaPassThruGetNextPort (
1430   IN EFI_ATA_PASS_THRU_PROTOCOL *This,
1431   IN OUT UINT16                 *Port
1432   )
1433 {
1434   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1435   LIST_ENTRY                      *Node;
1436   EFI_ATA_DEVICE_INFO             *DeviceInfo;
1437 
1438   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1439 
1440   if (Port == NULL) {
1441     return EFI_INVALID_PARAMETER;
1442   }
1443 
1444   if (*Port == 0xFFFF) {
1445     //
1446     // If the Port is all 0xFF's, start to traverse the device list from the beginning
1447     //
1448     Node = GetFirstNode (&Instance->DeviceList);
1449 
1450     while (!IsNull (&Instance->DeviceList, Node)) {
1451       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1452 
1453       if (DeviceInfo->Type == EfiIdeHarddisk) {
1454         *Port = DeviceInfo->Port;
1455         goto Exit;
1456       }
1457 
1458       Node = GetNextNode (&Instance->DeviceList, Node);
1459     }
1460 
1461     return EFI_NOT_FOUND;
1462   } else if (*Port == Instance->PreviousPort) {
1463     Node = GetFirstNode (&Instance->DeviceList);
1464 
1465     while (!IsNull (&Instance->DeviceList, Node)) {
1466       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1467 
1468       if ((DeviceInfo->Type == EfiIdeHarddisk) &&
1469            (DeviceInfo->Port > *Port)){
1470         *Port = DeviceInfo->Port;
1471         goto Exit;
1472       }
1473 
1474       Node = GetNextNode (&Instance->DeviceList, Node);
1475     }
1476 
1477     return EFI_NOT_FOUND;
1478   } else {
1479     //
1480     // Port is not equal to 0xFFFF and also not equal to previous return value
1481     //
1482     return EFI_INVALID_PARAMETER;
1483   }
1484 
1485 Exit:
1486   //
1487   // Update the PreviousPort and PreviousPortMultiplier.
1488   //
1489   Instance->PreviousPort = *Port;
1490 
1491   return EFI_SUCCESS;
1492 }
1493 
1494 /**
1495   Used to retrieve the list of legal port multiplier port numbers for ATA devices on a port of an ATA
1496   controller. These can either be the list of port multiplier ports where ATA devices are actually
1497   present on port or the list of legal port multiplier ports on that port. Regardless, the caller of this
1498   function must probe the port number and port multiplier port number returned to see if an ATA
1499   device is actually present.
1500 
1501   The GetNextDevice() function retrieves the port multiplier port number of an ATA device
1502   present on a port of an ATA controller.
1503 
1504   If PortMultiplierPort points to a port multiplier port number value that was returned on a
1505   previous call to GetNextDevice(), then the port multiplier port number of the next ATA device
1506   on the port of the ATA controller is returned in PortMultiplierPort, and EFI_SUCCESS is
1507   returned.
1508 
1509   If PortMultiplierPort points to 0xFFFF, then the port multiplier port number of the first
1510   ATA device on port of the ATA controller is returned in PortMultiplierPort and
1511   EFI_SUCCESS is returned.
1512 
1513   If PortMultiplierPort is not 0xFFFF and the value pointed to by PortMultiplierPort
1514   was not returned on a previous call to GetNextDevice(), then EFI_INVALID_PARAMETER
1515   is returned.
1516 
1517   If PortMultiplierPort is the port multiplier port number of the last ATA device on the port of
1518   the ATA controller, then EFI_NOT_FOUND is returned.
1519 
1520   @param[in]      This               A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1521   @param[in]      Port               The port number present on the ATA controller.
1522   @param[in, out] PortMultiplierPort On input, a pointer to the port multiplier port number of an
1523                                      ATA device present on the ATA controller.
1524                                      If on input a PortMultiplierPort of 0xFFFF is specified,
1525                                      then the port multiplier port number of the first ATA device
1526                                      is returned. On output, a pointer to the port multiplier port
1527                                      number of the next ATA device present on an ATA controller.
1528 
1529   @retval EFI_SUCCESS                The port multiplier port number of the next ATA device on the port
1530                                      of the ATA controller was returned in PortMultiplierPort.
1531   @retval EFI_NOT_FOUND              There are no more ATA devices on this port of the ATA controller.
1532   @retval EFI_INVALID_PARAMETER      PortMultiplierPort is not 0xFFFF, and PortMultiplierPort was not
1533                                      returned on a previous call to GetNextDevice().
1534 
1535 **/
1536 EFI_STATUS
1537 EFIAPI
AtaPassThruGetNextDevice(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN UINT16 Port,IN OUT UINT16 * PortMultiplierPort)1538 AtaPassThruGetNextDevice (
1539   IN EFI_ATA_PASS_THRU_PROTOCOL *This,
1540   IN UINT16                     Port,
1541   IN OUT UINT16                 *PortMultiplierPort
1542   )
1543 {
1544   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1545   LIST_ENTRY                      *Node;
1546   EFI_ATA_DEVICE_INFO             *DeviceInfo;
1547 
1548   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1549 
1550   if (PortMultiplierPort == NULL) {
1551     return EFI_INVALID_PARAMETER;
1552   }
1553 
1554   if (Instance->PreviousPortMultiplier == 0xFFFF) {
1555     //
1556     // If a device is directly attached on a port, previous call to this
1557     // function will return the value 0xFFFF for PortMultiplierPort. In
1558     // this case, there should be no more device on the port multiplier.
1559     //
1560     Instance->PreviousPortMultiplier = 0;
1561     return EFI_NOT_FOUND;
1562   }
1563 
1564   if (*PortMultiplierPort == Instance->PreviousPortMultiplier) {
1565     Node = GetFirstNode (&Instance->DeviceList);
1566 
1567     while (!IsNull (&Instance->DeviceList, Node)) {
1568       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1569 
1570       if ((DeviceInfo->Type == EfiIdeHarddisk) &&
1571            (DeviceInfo->Port == Port) &&
1572            (DeviceInfo->PortMultiplier > *PortMultiplierPort)){
1573         *PortMultiplierPort = DeviceInfo->PortMultiplier;
1574         goto Exit;
1575       }
1576 
1577       Node = GetNextNode (&Instance->DeviceList, Node);
1578     }
1579 
1580     return EFI_NOT_FOUND;
1581   } else if (*PortMultiplierPort == 0xFFFF) {
1582     //
1583     // If the PortMultiplierPort is all 0xFF's, start to traverse the device list from the beginning
1584     //
1585     Node = GetFirstNode (&Instance->DeviceList);
1586 
1587     while (!IsNull (&Instance->DeviceList, Node)) {
1588       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
1589 
1590       if ((DeviceInfo->Type == EfiIdeHarddisk) &&
1591            (DeviceInfo->Port == Port)){
1592         *PortMultiplierPort = DeviceInfo->PortMultiplier;
1593         goto Exit;
1594       }
1595 
1596       Node = GetNextNode (&Instance->DeviceList, Node);
1597     }
1598 
1599     return EFI_NOT_FOUND;
1600   } else {
1601     //
1602     // PortMultiplierPort is not equal to 0xFFFF and also not equal to previous return value
1603     //
1604     return EFI_INVALID_PARAMETER;
1605   }
1606 
1607 Exit:
1608   //
1609   // Update the PreviousPort and PreviousPortMultiplier.
1610   //
1611   Instance->PreviousPortMultiplier = *PortMultiplierPort;
1612 
1613   return EFI_SUCCESS;
1614 }
1615 
1616 /**
1617   Used to allocate and build a device path node for an ATA device on an ATA controller.
1618 
1619   The BuildDevicePath() function allocates and builds a single device node for the ATA
1620   device specified by Port and PortMultiplierPort. If the ATA device specified by Port and
1621   PortMultiplierPort is not present on the ATA controller, then EFI_NOT_FOUND is returned.
1622   If DevicePath is NULL, then EFI_INVALID_PARAMETER is returned. If there are not enough
1623   resources to allocate the device path node, then EFI_OUT_OF_RESOURCES is returned.
1624 
1625   Otherwise, DevicePath is allocated with the boot service AllocatePool(), the contents of
1626   DevicePath are initialized to describe the ATA device specified by Port and PortMultiplierPort,
1627   and EFI_SUCCESS is returned.
1628 
1629   @param[in]      This               A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1630   @param[in]      Port               Port specifies the port number of the ATA device for which a
1631                                      device path node is to be allocated and built.
1632   @param[in]      PortMultiplierPort The port multiplier port number of the ATA device for which a
1633                                      device path node is to be allocated and built. If there is no
1634                                      port multiplier, then specify 0xFFFF.
1635   @param[in, out] DevicePath         A pointer to a single device path node that describes the ATA
1636                                      device specified by Port and PortMultiplierPort. This function
1637                                      is responsible for allocating the buffer DevicePath with the
1638                                      boot service AllocatePool(). It is the caller's responsibility
1639                                      to free DevicePath when the caller is finished with DevicePath.
1640   @retval EFI_SUCCESS                The device path node that describes the ATA device specified by
1641                                      Port and PortMultiplierPort was allocated and returned in DevicePath.
1642   @retval EFI_NOT_FOUND              The ATA device specified by Port and PortMultiplierPort does not
1643                                      exist on the ATA controller.
1644   @retval EFI_INVALID_PARAMETER      DevicePath is NULL.
1645   @retval EFI_OUT_OF_RESOURCES       There are not enough resources to allocate DevicePath.
1646 
1647 **/
1648 EFI_STATUS
1649 EFIAPI
AtaPassThruBuildDevicePath(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN UINT16 Port,IN UINT16 PortMultiplierPort,IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath)1650 AtaPassThruBuildDevicePath (
1651   IN     EFI_ATA_PASS_THRU_PROTOCOL *This,
1652   IN     UINT16                     Port,
1653   IN     UINT16                     PortMultiplierPort,
1654   IN OUT EFI_DEVICE_PATH_PROTOCOL   **DevicePath
1655   )
1656 {
1657   EFI_DEV_PATH                    *DevicePathNode;
1658   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1659   LIST_ENTRY                      *Node;
1660 
1661   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1662 
1663   //
1664   // Validate parameters passed in.
1665   //
1666   if (DevicePath == NULL) {
1667     return EFI_INVALID_PARAMETER;
1668   }
1669 
1670   Node = SearchDeviceInfoList(Instance, Port, PortMultiplierPort, EfiIdeHarddisk);
1671   if (Node == NULL) {
1672     return EFI_NOT_FOUND;
1673   }
1674 
1675   if (Instance->Mode == EfiAtaIdeMode) {
1676     DevicePathNode = AllocateCopyPool (sizeof (ATAPI_DEVICE_PATH), &mAtapiDevicePathTemplate);
1677     if (DevicePathNode == NULL) {
1678       return EFI_OUT_OF_RESOURCES;
1679     }
1680     DevicePathNode->Atapi.PrimarySecondary = (UINT8) Port;
1681     DevicePathNode->Atapi.SlaveMaster      = (UINT8) PortMultiplierPort;
1682     DevicePathNode->Atapi.Lun              = 0;
1683   } else {
1684     DevicePathNode = AllocateCopyPool (sizeof (SATA_DEVICE_PATH), &mSataDevicePathTemplate);
1685     if (DevicePathNode == NULL) {
1686       return EFI_OUT_OF_RESOURCES;
1687     }
1688 
1689     DevicePathNode->Sata.HBAPortNumber            = Port;
1690     DevicePathNode->Sata.PortMultiplierPortNumber = PortMultiplierPort;
1691     DevicePathNode->Sata.Lun                      = 0;
1692   }
1693 
1694   *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) DevicePathNode;
1695 
1696   return EFI_SUCCESS;
1697 }
1698 
1699 /**
1700   Used to translate a device path node to a port number and port multiplier port number.
1701 
1702   The GetDevice() function determines the port and port multiplier port number associated with
1703   the ATA device described by DevicePath. If DevicePath is a device path node type that the
1704   ATA Pass Thru driver supports, then the ATA Pass Thru driver will attempt to translate the contents
1705   DevicePath into a port number and port multiplier port number.
1706 
1707   If this translation is successful, then that port number and port multiplier port number are returned
1708   in Port and PortMultiplierPort, and EFI_SUCCESS is returned.
1709 
1710   If DevicePath, Port, or PortMultiplierPort are NULL, then EFI_INVALID_PARAMETER is returned.
1711 
1712   If DevicePath is not a device path node type that the ATA Pass Thru driver supports, then
1713   EFI_UNSUPPORTED is returned.
1714 
1715   If DevicePath is a device path node type that the ATA Pass Thru driver supports, but there is not
1716   a valid translation from DevicePath to a port number and port multiplier port number, then
1717   EFI_NOT_FOUND is returned.
1718 
1719   @param[in]  This                A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1720   @param[in]  DevicePath          A pointer to the device path node that describes an ATA device on the
1721                                   ATA controller.
1722   @param[out] Port                On return, points to the port number of an ATA device on the ATA controller.
1723   @param[out] PortMultiplierPort  On return, points to the port multiplier port number of an ATA device
1724                                   on the ATA controller.
1725 
1726   @retval EFI_SUCCESS             DevicePath was successfully translated to a port number and port multiplier
1727                                   port number, and they were returned in Port and PortMultiplierPort.
1728   @retval EFI_INVALID_PARAMETER   DevicePath is NULL.
1729   @retval EFI_INVALID_PARAMETER   Port is NULL.
1730   @retval EFI_INVALID_PARAMETER   PortMultiplierPort is NULL.
1731   @retval EFI_UNSUPPORTED         This driver does not support the device path node type in DevicePath.
1732   @retval EFI_NOT_FOUND           A valid translation from DevicePath to a port number and port multiplier
1733                                   port number does not exist.
1734 **/
1735 EFI_STATUS
1736 EFIAPI
AtaPassThruGetDevice(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN EFI_DEVICE_PATH_PROTOCOL * DevicePath,OUT UINT16 * Port,OUT UINT16 * PortMultiplierPort)1737 AtaPassThruGetDevice (
1738   IN  EFI_ATA_PASS_THRU_PROTOCOL *This,
1739   IN  EFI_DEVICE_PATH_PROTOCOL   *DevicePath,
1740   OUT UINT16                     *Port,
1741   OUT UINT16                     *PortMultiplierPort
1742   )
1743 {
1744   EFI_DEV_PATH                    *DevicePathNode;
1745   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1746   LIST_ENTRY                      *Node;
1747 
1748   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1749 
1750   //
1751   // Validate parameters passed in.
1752   //
1753   if (DevicePath == NULL || Port == NULL || PortMultiplierPort == NULL) {
1754     return EFI_INVALID_PARAMETER;
1755   }
1756 
1757   //
1758   // Check whether the DevicePath belongs to SCSI_DEVICE_PATH or ATAPI_DEVICE_PATH
1759   //
1760   if ((DevicePath->Type != MESSAGING_DEVICE_PATH) ||
1761       ((DevicePath->SubType != MSG_SATA_DP) &&
1762       (DevicePath->SubType != MSG_ATAPI_DP)) ||
1763       ((DevicePathNodeLength(DevicePath) != sizeof(ATAPI_DEVICE_PATH)) &&
1764       (DevicePathNodeLength(DevicePath) != sizeof(SATA_DEVICE_PATH)))) {
1765     return EFI_UNSUPPORTED;
1766   }
1767 
1768   DevicePathNode = (EFI_DEV_PATH *) DevicePath;
1769 
1770   if (Instance->Mode == EfiAtaIdeMode) {
1771     *Port               = DevicePathNode->Atapi.PrimarySecondary;
1772     *PortMultiplierPort = DevicePathNode->Atapi.SlaveMaster;
1773   } else {
1774     *Port               = DevicePathNode->Sata.HBAPortNumber;
1775     *PortMultiplierPort = DevicePathNode->Sata.PortMultiplierPortNumber;
1776   }
1777 
1778   Node = SearchDeviceInfoList(Instance, *Port, *PortMultiplierPort, EfiIdeHarddisk);
1779 
1780   if (Node == NULL) {
1781     return EFI_NOT_FOUND;
1782   }
1783 
1784   return EFI_SUCCESS;
1785 }
1786 
1787 /**
1788   Resets a specific port on the ATA controller. This operation also resets all the ATA devices
1789   connected to the port.
1790 
1791   The ResetChannel() function resets an a specific port on an ATA controller. This operation
1792   resets all the ATA devices connected to that port. If this ATA controller does not support
1793   a reset port operation, then EFI_UNSUPPORTED is returned.
1794 
1795   If a device error occurs while executing that port reset operation, then EFI_DEVICE_ERROR is
1796   returned.
1797 
1798   If a timeout occurs during the execution of the port reset operation, then EFI_TIMEOUT is returned.
1799 
1800   If the port reset operation is completed, then EFI_SUCCESS is returned.
1801 
1802   @param[in]  This          A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1803   @param[in]  Port          The port number on the ATA controller.
1804 
1805   @retval EFI_SUCCESS       The ATA controller port was reset.
1806   @retval EFI_UNSUPPORTED   The ATA controller does not support a port reset operation.
1807   @retval EFI_DEVICE_ERROR  A device error occurred while attempting to reset the ATA port.
1808   @retval EFI_TIMEOUT       A timeout occurred while attempting to reset the ATA port.
1809 
1810 **/
1811 EFI_STATUS
1812 EFIAPI
AtaPassThruResetPort(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN UINT16 Port)1813 AtaPassThruResetPort (
1814   IN EFI_ATA_PASS_THRU_PROTOCOL *This,
1815   IN UINT16                     Port
1816   )
1817 {
1818   //
1819   // Return success directly then upper layer driver could think reset port operation is done.
1820   //
1821   return EFI_SUCCESS;
1822 }
1823 
1824 /**
1825   Resets an ATA device that is connected to an ATA controller.
1826 
1827   The ResetDevice() function resets the ATA device specified by Port and PortMultiplierPort.
1828   If this ATA controller does not support a device reset operation, then EFI_UNSUPPORTED is
1829   returned.
1830 
1831   If Port or PortMultiplierPort are not in a valid range for this ATA controller, then
1832   EFI_INVALID_PARAMETER is returned.
1833 
1834   If a device error occurs while executing that device reset operation, then EFI_DEVICE_ERROR
1835   is returned.
1836 
1837   If a timeout occurs during the execution of the device reset operation, then EFI_TIMEOUT is
1838   returned.
1839 
1840   If the device reset operation is completed, then EFI_SUCCESS is returned.
1841 
1842   @param[in] This                A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.
1843   @param[in] Port                Port represents the port number of the ATA device to be reset.
1844   @param[in] PortMultiplierPort  The port multiplier port number of the ATA device to reset.
1845                                  If there is no port multiplier, then specify 0xFFFF.
1846   @retval EFI_SUCCESS            The ATA device specified by Port and PortMultiplierPort was reset.
1847   @retval EFI_UNSUPPORTED        The ATA controller does not support a device reset operation.
1848   @retval EFI_INVALID_PARAMETER  Port or PortMultiplierPort are invalid.
1849   @retval EFI_DEVICE_ERROR       A device error occurred while attempting to reset the ATA device
1850                                  specified by Port and PortMultiplierPort.
1851   @retval EFI_TIMEOUT            A timeout occurred while attempting to reset the ATA device
1852                                  specified by Port and PortMultiplierPort.
1853 
1854 **/
1855 EFI_STATUS
1856 EFIAPI
AtaPassThruResetDevice(IN EFI_ATA_PASS_THRU_PROTOCOL * This,IN UINT16 Port,IN UINT16 PortMultiplierPort)1857 AtaPassThruResetDevice (
1858   IN EFI_ATA_PASS_THRU_PROTOCOL *This,
1859   IN UINT16                     Port,
1860   IN UINT16                     PortMultiplierPort
1861   )
1862 {
1863   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1864   LIST_ENTRY                      *Node;
1865 
1866   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1867 
1868   Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeHarddisk);
1869 
1870   if (Node == NULL) {
1871     return EFI_INVALID_PARAMETER;
1872   }
1873 
1874   //
1875   // Return success directly then upper layer driver could think reset device operation is done.
1876   //
1877   return EFI_SUCCESS;
1878 }
1879 
1880 /**
1881   Submit ATAPI request sense command.
1882 
1883   @param[in] This            A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
1884   @param[in] Target          The Target is an array of size TARGET_MAX_BYTES and it represents
1885                              the id of the SCSI device to send the SCSI Request Packet. Each
1886                              transport driver may choose to utilize a subset of this size to suit the needs
1887                              of transport target representation. For example, a Fibre Channel driver
1888                              may use only 8 bytes (WWN) to represent an FC target.
1889   @param[in] Lun             The LUN of the SCSI device to send the SCSI Request Packet.
1890   @param[in] SenseData       A pointer to store sense data.
1891   @param[in] SenseDataLength The sense data length.
1892   @param[in] Timeout         The timeout value to execute this cmd, uses 100ns as a unit.
1893 
1894   @retval EFI_SUCCESS        Send out the ATAPI packet command successfully.
1895   @retval EFI_DEVICE_ERROR   The device failed to send data.
1896 
1897 **/
1898 EFI_STATUS
1899 EFIAPI
AtaPacketRequestSense(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN UINT8 * Target,IN UINT64 Lun,IN VOID * SenseData,IN UINT8 SenseDataLength,IN UINT64 Timeout)1900 AtaPacketRequestSense (
1901   IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL         *This,
1902   IN  UINT8                                   *Target,
1903   IN  UINT64                                  Lun,
1904   IN  VOID                                    *SenseData,
1905   IN  UINT8                                   SenseDataLength,
1906   IN  UINT64                                  Timeout
1907   )
1908 {
1909   EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET  Packet;
1910   UINT8                                       Cdb[12];
1911   EFI_STATUS                                  Status;
1912 
1913   ZeroMem (&Packet, sizeof (EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET));
1914   ZeroMem (Cdb, 12);
1915 
1916   Cdb[0] = ATA_CMD_REQUEST_SENSE;
1917   Cdb[4] = SenseDataLength;
1918 
1919   Packet.Timeout          = Timeout;
1920   Packet.Cdb              = Cdb;
1921   Packet.CdbLength        = 12;
1922   Packet.DataDirection    = EFI_EXT_SCSI_DATA_DIRECTION_READ;
1923   Packet.InDataBuffer     = SenseData;
1924   Packet.InTransferLength = SenseDataLength;
1925 
1926   Status = ExtScsiPassThruPassThru (This, Target, Lun, &Packet, NULL);
1927 
1928   return Status;
1929 }
1930 
1931 /**
1932   Sends a SCSI Request Packet to a SCSI device that is attached to the SCSI channel. This function
1933   supports both blocking I/O and nonblocking I/O. The blocking I/O functionality is required, and the
1934   nonblocking I/O functionality is optional.
1935 
1936   @param  This    A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
1937   @param  Target  The Target is an array of size TARGET_MAX_BYTES and it represents
1938                   the id of the SCSI device to send the SCSI Request Packet. Each
1939                   transport driver may choose to utilize a subset of this size to suit the needs
1940                   of transport target representation. For example, a Fibre Channel driver
1941                   may use only 8 bytes (WWN) to represent an FC target.
1942   @param  Lun     The LUN of the SCSI device to send the SCSI Request Packet.
1943   @param  Packet  A pointer to the SCSI Request Packet to send to the SCSI device
1944                   specified by Target and Lun.
1945   @param  Event   If nonblocking I/O is not supported then Event is ignored, and blocking
1946                   I/O is performed. If Event is NULL, then blocking I/O is performed. If
1947                   Event is not NULL and non blocking I/O is supported, then
1948                   nonblocking I/O is performed, and Event will be signaled when the
1949                   SCSI Request Packet completes.
1950 
1951   @retval EFI_SUCCESS           The SCSI Request Packet was sent by the host. For bi-directional
1952                                 commands, InTransferLength bytes were transferred from
1953                                 InDataBuffer. For write and bi-directional commands,
1954                                 OutTransferLength bytes were transferred by
1955                                 OutDataBuffer.
1956   @retval EFI_BAD_BUFFER_SIZE   The SCSI Request Packet was not executed. The number of bytes that
1957                                 could be transferred is returned in InTransferLength. For write
1958                                 and bi-directional commands, OutTransferLength bytes were
1959                                 transferred by OutDataBuffer.
1960   @retval EFI_NOT_READY         The SCSI Request Packet could not be sent because there are too many
1961                                 SCSI Request Packets already queued. The caller may retry again later.
1962   @retval EFI_DEVICE_ERROR      A device error occurred while attempting to send the SCSI Request
1963                                 Packet.
1964   @retval EFI_INVALID_PARAMETER Target, Lun, or the contents of ScsiRequestPacket are invalid.
1965   @retval EFI_UNSUPPORTED       The command described by the SCSI Request Packet is not supported
1966                                 by the host adapter. This includes the case of Bi-directional SCSI
1967                                 commands not supported by the implementation. The SCSI Request
1968                                 Packet was not sent, so no additional status information is available.
1969   @retval EFI_TIMEOUT           A timeout occurred while waiting for the SCSI Request Packet to execute.
1970 
1971 **/
1972 EFI_STATUS
1973 EFIAPI
ExtScsiPassThruPassThru(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN UINT8 * Target,IN UINT64 Lun,IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET * Packet,IN EFI_EVENT Event OPTIONAL)1974 ExtScsiPassThruPassThru (
1975   IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL                    *This,
1976   IN UINT8                                              *Target,
1977   IN UINT64                                             Lun,
1978   IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET     *Packet,
1979   IN EFI_EVENT                                          Event OPTIONAL
1980   )
1981 {
1982   EFI_STATUS                      Status;
1983   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
1984   UINT8                           Port;
1985   UINT8                           PortMultiplier;
1986   EFI_ATA_HC_WORK_MODE            Mode;
1987   LIST_ENTRY                      *Node;
1988   EFI_ATA_DEVICE_INFO             *DeviceInfo;
1989   BOOLEAN                         SenseReq;
1990   EFI_SCSI_SENSE_DATA             *PtrSenseData;
1991   UINTN                           SenseDataLen;
1992   EFI_STATUS                      SenseStatus;
1993 
1994   SenseDataLen = 0;
1995   Instance     = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
1996 
1997   if ((Packet == NULL) || (Packet->Cdb == NULL)) {
1998     return EFI_INVALID_PARAMETER;
1999   }
2000 
2001   //
2002   // Don't support variable length CDB
2003   //
2004   if ((Packet->CdbLength != 6) && (Packet->CdbLength != 10) &&
2005       (Packet->CdbLength != 12) && (Packet->CdbLength != 16)) {
2006     return EFI_INVALID_PARAMETER;
2007   }
2008 
2009   if ((Packet->SenseDataLength != 0) && (Packet->SenseData == NULL)) {
2010     return EFI_INVALID_PARAMETER;
2011   }
2012 
2013   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->InDataBuffer, This->Mode->IoAlign)) {
2014     return EFI_INVALID_PARAMETER;
2015   }
2016 
2017   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->OutDataBuffer, This->Mode->IoAlign)) {
2018     return EFI_INVALID_PARAMETER;
2019   }
2020 
2021   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->SenseData, This->Mode->IoAlign)) {
2022     return EFI_INVALID_PARAMETER;
2023   }
2024 
2025   //
2026   // For ATAPI device, doesn't support multiple LUN device.
2027   //
2028   if (Lun != 0) {
2029     return EFI_INVALID_PARAMETER;
2030   }
2031 
2032   //
2033   // The layout of Target array:
2034   //  ________________________________________________________________________
2035   // |       Byte 0        |       Byte 1        | ... | TARGET_MAX_BYTES - 1 |
2036   // |_____________________|_____________________|_____|______________________|
2037   // |                     | The port multiplier |     |                      |
2038   // |   The port number   |    port number      | N/A |         N/A          |
2039   // |_____________________|_____________________|_____|______________________|
2040   //
2041   // For ATAPI device, 2 bytes is enough to represent the location of SCSI device.
2042   //
2043   Port           = Target[0];
2044   PortMultiplier = Target[1];
2045 
2046   Node = SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom);
2047   if (Node == NULL) {
2048     return EFI_INVALID_PARAMETER;
2049   }
2050 
2051   DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
2052 
2053   //
2054   // ATA_CMD_IDENTIFY_DEVICE cmd is a ATA cmd but not a SCSI cmd.
2055   // Normally it should NOT be passed down through ExtScsiPassThru protocol interface.
2056   // But to response EFI_DISK_INFO.Identify() request from ScsiDisk, we should handle this command.
2057   //
2058   if (*((UINT8*)Packet->Cdb) == ATA_CMD_IDENTIFY_DEVICE) {
2059     CopyMem (Packet->InDataBuffer, DeviceInfo->IdentifyData, sizeof (EFI_IDENTIFY_DATA));
2060     //
2061     // For IDENTIFY DEVICE cmd, we don't need to get sense data.
2062     //
2063     Packet->SenseDataLength = 0;
2064     return EFI_SUCCESS;
2065   }
2066 
2067   Mode = Instance->Mode;
2068   switch (Mode) {
2069     case EfiAtaIdeMode:
2070       //
2071       // Reassign IDE mode io port registers' base addresses
2072       //
2073       Status = GetIdeRegisterIoAddr (Instance->PciIo, Instance->IdeRegisters);
2074 
2075       if (EFI_ERROR (Status)) {
2076         return Status;
2077       }
2078 
2079       Status = AtaPacketCommandExecute (Instance->PciIo, &Instance->IdeRegisters[Port], Port, PortMultiplier, Packet);
2080       break;
2081     case EfiAtaAhciMode:
2082       if (PortMultiplier == 0xFF) {
2083         //
2084         // If there is no port multiplier, the PortMultiplier will be 0xFF
2085         // Here, we convert its value to 0 to follow the AHCI spec.
2086         //
2087         PortMultiplier = 0;
2088       }
2089       Status = AhciPacketCommandExecute (Instance->PciIo, &Instance->AhciRegisters, Port, PortMultiplier, Packet);
2090       break;
2091     default :
2092       Status = EFI_DEVICE_ERROR;
2093       break;
2094   }
2095 
2096   //
2097   // If the cmd doesn't get executed correctly, then check sense data.
2098   //
2099   if (EFI_ERROR (Status) && (Packet->SenseDataLength != 0) && (*((UINT8*)Packet->Cdb) != ATA_CMD_REQUEST_SENSE)) {
2100     PtrSenseData = AllocateAlignedPages (EFI_SIZE_TO_PAGES (sizeof (EFI_SCSI_SENSE_DATA)), This->Mode->IoAlign);
2101     if (PtrSenseData == NULL) {
2102       return EFI_DEVICE_ERROR;
2103     }
2104 
2105     for (SenseReq = TRUE; SenseReq;) {
2106       SenseStatus = AtaPacketRequestSense (
2107                       This,
2108                       Target,
2109                       Lun,
2110                       PtrSenseData,
2111                       sizeof (EFI_SCSI_SENSE_DATA),
2112                       Packet->Timeout
2113                       );
2114       if (EFI_ERROR (SenseStatus)) {
2115         break;
2116       }
2117 
2118       CopyMem ((UINT8*)Packet->SenseData + SenseDataLen, PtrSenseData, sizeof (EFI_SCSI_SENSE_DATA));
2119       SenseDataLen += sizeof (EFI_SCSI_SENSE_DATA);
2120 
2121       //
2122       // no more sense key or number of sense keys exceeds predefined,
2123       // skip the loop.
2124       //
2125       if ((PtrSenseData->Sense_Key == EFI_SCSI_SK_NO_SENSE) ||
2126           (SenseDataLen + sizeof (EFI_SCSI_SENSE_DATA) > Packet->SenseDataLength)) {
2127         SenseReq = FALSE;
2128       }
2129     }
2130     FreeAlignedPages (PtrSenseData, EFI_SIZE_TO_PAGES (sizeof (EFI_SCSI_SENSE_DATA)));
2131   }
2132   //
2133   // Update the SenseDataLength field to the data length received.
2134   //
2135   Packet->SenseDataLength = (UINT8)SenseDataLen;
2136   return Status;
2137 }
2138 
2139 /**
2140   Used to retrieve the list of legal Target IDs and LUNs for SCSI devices on a SCSI channel. These
2141   can either be the list SCSI devices that are actually present on the SCSI channel, or the list of legal
2142   Target Ids and LUNs for the SCSI channel. Regardless, the caller of this function must probe the
2143   Target ID and LUN returned to see if a SCSI device is actually present at that location on the SCSI
2144   channel.
2145 
2146   @param  This   A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
2147   @param  Target On input, a pointer to the Target ID (an array of size
2148                  TARGET_MAX_BYTES) of a SCSI device present on the SCSI channel.
2149                  On output, a pointer to the Target ID (an array of
2150                  TARGET_MAX_BYTES) of the next SCSI device present on a SCSI
2151                  channel. An input value of 0xF(all bytes in the array are 0xF) in the
2152                  Target array retrieves the Target ID of the first SCSI device present on a
2153                  SCSI channel.
2154   @param  Lun    On input, a pointer to the LUN of a SCSI device present on the SCSI
2155                  channel. On output, a pointer to the LUN of the next SCSI device present
2156                  on a SCSI channel.
2157 
2158   @retval EFI_SUCCESS           The Target ID and LUN of the next SCSI device on the SCSI
2159                                 channel was returned in Target and Lun.
2160   @retval EFI_INVALID_PARAMETER Target array is not all 0xF, and Target and Lun were
2161                                 not returned on a previous call to GetNextTargetLun().
2162   @retval EFI_NOT_FOUND         There are no more SCSI devices on this SCSI channel.
2163 
2164 **/
2165 EFI_STATUS
2166 EFIAPI
ExtScsiPassThruGetNextTargetLun(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN OUT UINT8 ** Target,IN OUT UINT64 * Lun)2167 ExtScsiPassThruGetNextTargetLun (
2168   IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL    *This,
2169   IN OUT UINT8                           **Target,
2170   IN OUT UINT64                          *Lun
2171   )
2172 {
2173   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
2174   LIST_ENTRY                      *Node;
2175   EFI_ATA_DEVICE_INFO             *DeviceInfo;
2176   UINT8                           *Target8;
2177   UINT16                          *Target16;
2178 
2179   Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
2180 
2181   if (Target == NULL || Lun == NULL) {
2182     return EFI_INVALID_PARAMETER;
2183   }
2184 
2185   if (*Target == NULL) {
2186     return EFI_INVALID_PARAMETER;
2187   }
2188 
2189   Target8  = *Target;
2190   Target16 = (UINT16 *)*Target;
2191 
2192   if (CompareMem(Target8, mScsiId, TARGET_MAX_BYTES) != 0) {
2193     //
2194     // For ATAPI device, we use 2 least significant bytes to represent the location of SCSI device.
2195     // So the higher bytes in Target array should be 0xFF.
2196     //
2197     if (CompareMem (&Target8[2], &mScsiId[2], TARGET_MAX_BYTES - 2) != 0) {
2198       return EFI_INVALID_PARAMETER;
2199     }
2200 
2201     //
2202     // When Target is not all 0xFF's, compare 2 least significant bytes with
2203     // previous target id to see if it is returned by previous call.
2204     //
2205     if ((*Target16 != Instance->PreviousTargetId) ||
2206         (*Lun != Instance->PreviousLun)) {
2207       return EFI_INVALID_PARAMETER;
2208     }
2209 
2210     //
2211     // Traverse the whole device list to find the next cdrom closed to
2212     // the device signified by Target[0] and Target[1].
2213     //
2214     // Note that we here use a tricky way to find the next cdrom :
2215     // All ata devices are detected and inserted into the device list
2216     // sequentially.
2217     //
2218     Node = GetFirstNode (&Instance->DeviceList);
2219 
2220     while (!IsNull (&Instance->DeviceList, Node)) {
2221       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
2222 
2223       if ((DeviceInfo->Type == EfiIdeCdrom) &&
2224          ((Target8[0] < DeviceInfo->Port) ||
2225           ((Target8[0] == DeviceInfo->Port) &&
2226            (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) {
2227         Target8[0] = (UINT8)DeviceInfo->Port;
2228         Target8[1] = (UINT8)DeviceInfo->PortMultiplier;
2229         goto Exit;
2230       }
2231 
2232       Node = GetNextNode (&Instance->DeviceList, Node);
2233     }
2234 
2235     return EFI_NOT_FOUND;
2236   } else {
2237     //
2238     // If the array is all 0xFF's, start to traverse the device list from the beginning
2239     //
2240     Node = GetFirstNode (&Instance->DeviceList);
2241     while (!IsNull (&Instance->DeviceList, Node)) {
2242       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
2243 
2244       if (DeviceInfo->Type == EfiIdeCdrom) {
2245         Target8[0] = (UINT8)DeviceInfo->Port;
2246         Target8[1] = (UINT8)DeviceInfo->PortMultiplier;
2247         goto Exit;
2248       }
2249 
2250       Node = GetNextNode (&Instance->DeviceList, Node);
2251     }
2252 
2253     return EFI_NOT_FOUND;
2254   }
2255 
2256 Exit:
2257   *Lun = 0;
2258 
2259   //
2260   // Update the PreviousTargetId.
2261   //
2262   Instance->PreviousTargetId = *Target16;
2263   Instance->PreviousLun      = *Lun;
2264 
2265   return EFI_SUCCESS;
2266 }
2267 
2268 /**
2269   Used to allocate and build a device path node for a SCSI device on a SCSI channel.
2270 
2271   @param  This       A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
2272   @param  Target     The Target is an array of size TARGET_MAX_BYTES and it specifies the
2273                      Target ID of the SCSI device for which a device path node is to be
2274                      allocated and built. Transport drivers may chose to utilize a subset of
2275                      this size to suit the representation of targets. For example, a Fibre
2276                      Channel driver may use only 8 bytes (WWN) in the array to represent a
2277                      FC target.
2278   @param  Lun        The LUN of the SCSI device for which a device path node is to be
2279                      allocated and built.
2280   @param  DevicePath A pointer to a single device path node that describes the SCSI device
2281                      specified by Target and Lun. This function is responsible for
2282                      allocating the buffer DevicePath with the boot service
2283                      AllocatePool(). It is the caller's responsibility to free
2284                      DevicePath when the caller is finished with DevicePath.
2285 
2286   @retval EFI_SUCCESS           The device path node that describes the SCSI device specified by
2287                                 Target and Lun was allocated and returned in
2288                                 DevicePath.
2289   @retval EFI_INVALID_PARAMETER DevicePath is NULL.
2290   @retval EFI_NOT_FOUND         The SCSI devices specified by Target and Lun does not exist
2291                                 on the SCSI channel.
2292   @retval EFI_OUT_OF_RESOURCES  There are not enough resources to allocate DevicePath.
2293 
2294 **/
2295 EFI_STATUS
2296 EFIAPI
ExtScsiPassThruBuildDevicePath(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN UINT8 * Target,IN UINT64 Lun,IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath)2297 ExtScsiPassThruBuildDevicePath (
2298   IN     EFI_EXT_SCSI_PASS_THRU_PROTOCOL    *This,
2299   IN     UINT8                              *Target,
2300   IN     UINT64                             Lun,
2301   IN OUT EFI_DEVICE_PATH_PROTOCOL           **DevicePath
2302   )
2303 {
2304   EFI_DEV_PATH                    *DevicePathNode;
2305   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
2306   UINT8                           Port;
2307   UINT8                           PortMultiplier;
2308 
2309   Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
2310 
2311   Port           = Target[0];
2312   PortMultiplier = Target[1];
2313 
2314   //
2315   // Validate parameters passed in.
2316   //
2317   if (DevicePath == NULL) {
2318     return EFI_INVALID_PARAMETER;
2319   }
2320 
2321   //
2322   // can not build device path for the SCSI Host Controller.
2323   //
2324   if (Lun != 0) {
2325     return EFI_NOT_FOUND;
2326   }
2327 
2328   if (SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom) == NULL) {
2329     return EFI_NOT_FOUND;
2330   }
2331 
2332   if (Instance->Mode == EfiAtaIdeMode) {
2333     DevicePathNode = AllocateCopyPool (sizeof (ATAPI_DEVICE_PATH), &mAtapiDevicePathTemplate);
2334     if (DevicePathNode == NULL) {
2335       return EFI_OUT_OF_RESOURCES;
2336     }
2337 
2338     DevicePathNode->Atapi.PrimarySecondary = Port;
2339     DevicePathNode->Atapi.SlaveMaster      = PortMultiplier;
2340     DevicePathNode->Atapi.Lun              = (UINT16) Lun;
2341   } else {
2342     DevicePathNode = AllocateCopyPool (sizeof (SATA_DEVICE_PATH), &mSataDevicePathTemplate);
2343     if (DevicePathNode == NULL) {
2344       return EFI_OUT_OF_RESOURCES;
2345     }
2346 
2347     DevicePathNode->Sata.HBAPortNumber            = Port;
2348     //
2349     // For CD-ROM working in the AHCI mode, only 8 bits are used to record
2350     // the PortMultiplier information. If the CD-ROM is directly attached
2351     // on a SATA port, the PortMultiplier should be translated from 0xFF
2352     // to 0xFFFF according to the UEFI spec.
2353     //
2354     DevicePathNode->Sata.PortMultiplierPortNumber = PortMultiplier == 0xFF ? 0xFFFF : PortMultiplier;
2355     DevicePathNode->Sata.Lun                      = (UINT16) Lun;
2356   }
2357 
2358   *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) DevicePathNode;
2359 
2360   return EFI_SUCCESS;
2361 }
2362 
2363 /**
2364   Used to translate a device path node to a Target ID and LUN.
2365 
2366   @param  This       A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
2367   @param  DevicePath A pointer to a single device path node that describes the SCSI device
2368                      on the SCSI channel.
2369   @param  Target     A pointer to the Target Array which represents the ID of a SCSI device
2370                      on the SCSI channel.
2371   @param  Lun        A pointer to the LUN of a SCSI device on the SCSI channel.
2372 
2373   @retval EFI_SUCCESS           DevicePath was successfully translated to a Target ID and
2374                                 LUN, and they were returned in Target and Lun.
2375   @retval EFI_INVALID_PARAMETER DevicePath or Target or Lun is NULL.
2376   @retval EFI_NOT_FOUND         A valid translation from DevicePath to a Target ID and LUN
2377                                 does not exist.
2378   @retval EFI_UNSUPPORTED       This driver does not support the device path node type in
2379                                  DevicePath.
2380 
2381 **/
2382 EFI_STATUS
2383 EFIAPI
ExtScsiPassThruGetTargetLun(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN EFI_DEVICE_PATH_PROTOCOL * DevicePath,OUT UINT8 ** Target,OUT UINT64 * Lun)2384 ExtScsiPassThruGetTargetLun (
2385   IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL    *This,
2386   IN  EFI_DEVICE_PATH_PROTOCOL           *DevicePath,
2387   OUT UINT8                              **Target,
2388   OUT UINT64                             *Lun
2389   )
2390 {
2391   EFI_DEV_PATH                    *DevicePathNode;
2392   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
2393   LIST_ENTRY                      *Node;
2394 
2395   Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
2396 
2397   //
2398   // Validate parameters passed in.
2399   //
2400   if (DevicePath == NULL || Target == NULL || Lun == NULL) {
2401     return EFI_INVALID_PARAMETER;
2402   }
2403 
2404   if (*Target == NULL) {
2405     return EFI_INVALID_PARAMETER;
2406   }
2407   //
2408   // Check whether the DevicePath belongs to SCSI_DEVICE_PATH
2409   //
2410   if ((DevicePath->Type != MESSAGING_DEVICE_PATH) ||
2411       ((DevicePath->SubType != MSG_ATAPI_DP) &&
2412       (DevicePath->SubType != MSG_SATA_DP)) ||
2413       ((DevicePathNodeLength(DevicePath) != sizeof(ATAPI_DEVICE_PATH)) &&
2414       (DevicePathNodeLength(DevicePath) != sizeof(SATA_DEVICE_PATH)))) {
2415     return EFI_UNSUPPORTED;
2416   }
2417 
2418   SetMem (*Target, TARGET_MAX_BYTES, 0xFF);
2419 
2420   DevicePathNode = (EFI_DEV_PATH *) DevicePath;
2421 
2422   if (Instance->Mode == EfiAtaIdeMode) {
2423     (*Target)[0] = (UINT8) DevicePathNode->Atapi.PrimarySecondary;
2424     (*Target)[1] = (UINT8) DevicePathNode->Atapi.SlaveMaster;
2425     *Lun         = (UINT8) DevicePathNode->Atapi.Lun;
2426   } else {
2427     (*Target)[0] = (UINT8) DevicePathNode->Sata.HBAPortNumber;
2428     (*Target)[1] = (UINT8) DevicePathNode->Sata.PortMultiplierPortNumber;
2429     *Lun         = (UINT8) DevicePathNode->Sata.Lun;
2430   }
2431 
2432   Node = SearchDeviceInfoList(Instance, (*Target)[0], (*Target)[1], EfiIdeCdrom);
2433 
2434   if (Node == NULL) {
2435     return EFI_NOT_FOUND;
2436   }
2437 
2438   if (*Lun != 0) {
2439     return EFI_NOT_FOUND;
2440   }
2441 
2442   return EFI_SUCCESS;
2443 }
2444 
2445 /**
2446   Resets a SCSI channel. This operation resets all the SCSI devices connected to the SCSI channel.
2447 
2448   @param  This A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
2449 
2450   @retval EFI_SUCCESS      The SCSI channel was reset.
2451   @retval EFI_DEVICE_ERROR A device error occurred while attempting to reset the SCSI channel.
2452   @retval EFI_TIMEOUT      A timeout occurred while attempting to reset the SCSI channel.
2453   @retval EFI_UNSUPPORTED  The SCSI channel does not support a channel reset operation.
2454 
2455 **/
2456 EFI_STATUS
2457 EFIAPI
ExtScsiPassThruResetChannel(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This)2458 ExtScsiPassThruResetChannel (
2459   IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL   *This
2460   )
2461 {
2462   //
2463   // Return success directly then upper layer driver could think reset channel operation is done.
2464   //
2465   return EFI_SUCCESS;
2466 }
2467 
2468 /**
2469   Resets a SCSI logical unit that is connected to a SCSI channel.
2470 
2471   @param  This   A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
2472   @param  Target The Target is an array of size TARGET_MAX_BYTE and it represents the
2473                  target port ID of the SCSI device containing the SCSI logical unit to
2474                  reset. Transport drivers may chose to utilize a subset of this array to suit
2475                  the representation of their targets.
2476   @param  Lun    The LUN of the SCSI device to reset.
2477 
2478   @retval EFI_SUCCESS           The SCSI device specified by Target and Lun was reset.
2479   @retval EFI_INVALID_PARAMETER Target or Lun is NULL.
2480   @retval EFI_TIMEOUT           A timeout occurred while attempting to reset the SCSI device
2481                                 specified by Target and Lun.
2482   @retval EFI_UNSUPPORTED       The SCSI channel does not support a target reset operation.
2483   @retval EFI_DEVICE_ERROR      A device error occurred while attempting to reset the SCSI device
2484                                  specified by Target and Lun.
2485 
2486 **/
2487 EFI_STATUS
2488 EFIAPI
ExtScsiPassThruResetTargetLun(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN UINT8 * Target,IN UINT64 Lun)2489 ExtScsiPassThruResetTargetLun (
2490   IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL    *This,
2491   IN UINT8                              *Target,
2492   IN UINT64                             Lun
2493   )
2494 {
2495   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
2496   LIST_ENTRY                      *Node;
2497   UINT8                           Port;
2498   UINT8                           PortMultiplier;
2499 
2500   Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
2501   //
2502   // For ATAPI device, doesn't support multiple LUN device.
2503   //
2504   if (Lun != 0) {
2505     return EFI_INVALID_PARAMETER;
2506   }
2507   //
2508   // The layout of Target array:
2509   //  ________________________________________________________________________
2510   // |       Byte 0        |       Byte 1        | ... | TARGET_MAX_BYTES - 1 |
2511   // |_____________________|_____________________|_____|______________________|
2512   // |                     | The port multiplier |     |                      |
2513   // |   The port number   |    port number      | N/A |         N/A          |
2514   // |_____________________|_____________________|_____|______________________|
2515   //
2516   // For ATAPI device, 2 bytes is enough to represent the location of SCSI device.
2517   //
2518   Port           = Target[0];
2519   PortMultiplier = Target[1];
2520 
2521   Node = SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom);
2522   if (Node == NULL) {
2523     return EFI_INVALID_PARAMETER;
2524   }
2525 
2526   //
2527   // Return success directly then upper layer driver could think reset target LUN operation is done.
2528   //
2529   return EFI_SUCCESS;
2530 }
2531 
2532 /**
2533   Used to retrieve the list of legal Target IDs for SCSI devices on a SCSI channel. These can either
2534   be the list SCSI devices that are actually present on the SCSI channel, or the list of legal Target IDs
2535   for the SCSI channel. Regardless, the caller of this function must probe the Target ID returned to
2536   see if a SCSI device is actually present at that location on the SCSI channel.
2537 
2538   @param  This   A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.
2539   @param  Target (TARGET_MAX_BYTES) of a SCSI device present on the SCSI channel.
2540                  On output, a pointer to the Target ID (an array of
2541                  TARGET_MAX_BYTES) of the next SCSI device present on a SCSI
2542                  channel. An input value of 0xF(all bytes in the array are 0xF) in the
2543                  Target array retrieves the Target ID of the first SCSI device present on a
2544                  SCSI channel.
2545 
2546   @retval EFI_SUCCESS           The Target ID of the next SCSI device on the SCSI
2547                                 channel was returned in Target.
2548   @retval EFI_INVALID_PARAMETER Target or Lun is NULL.
2549   @retval EFI_TIMEOUT           Target array is not all 0xF, and Target was not
2550                                 returned on a previous call to GetNextTarget().
2551   @retval EFI_NOT_FOUND         There are no more SCSI devices on this SCSI channel.
2552 
2553 **/
2554 EFI_STATUS
2555 EFIAPI
ExtScsiPassThruGetNextTarget(IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL * This,IN OUT UINT8 ** Target)2556 ExtScsiPassThruGetNextTarget (
2557   IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL    *This,
2558   IN OUT UINT8                           **Target
2559   )
2560 {
2561   ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;
2562   LIST_ENTRY                      *Node;
2563   EFI_ATA_DEVICE_INFO             *DeviceInfo;
2564   UINT8                           *Target8;
2565   UINT16                          *Target16;
2566 
2567   Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);
2568 
2569   if (Target == NULL || *Target == NULL) {
2570     return EFI_INVALID_PARAMETER;
2571   }
2572 
2573   Target8  = *Target;
2574   Target16 = (UINT16 *)*Target;
2575 
2576   if (CompareMem(Target8, mScsiId, TARGET_MAX_BYTES) != 0) {
2577     //
2578     // For ATAPI device, we use 2 least significant bytes to represent the location of SCSI device.
2579     // So the higher bytes in Target array should be 0xFF.
2580     //
2581     if (CompareMem (&Target8[2], &mScsiId[2], TARGET_MAX_BYTES - 2) != 0) {
2582       return EFI_INVALID_PARAMETER;
2583     }
2584 
2585     //
2586     // When Target is not all 0xFF's, compare 2 least significant bytes with
2587     // previous target id to see if it is returned by previous call.
2588     //
2589     if (*Target16 != Instance->PreviousTargetId) {
2590       return EFI_INVALID_PARAMETER;
2591     }
2592 
2593     //
2594     // Traverse the whole device list to find the next cdrom closed to
2595     // the device signified by Target[0] and Target[1].
2596     //
2597     // Note that we here use a tricky way to find the next cdrom :
2598     // All ata devices are detected and inserted into the device list
2599     // sequentially.
2600     //
2601     Node = GetFirstNode (&Instance->DeviceList);
2602     while (!IsNull (&Instance->DeviceList, Node)) {
2603       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
2604 
2605       if ((DeviceInfo->Type == EfiIdeCdrom) &&
2606          ((Target8[0] < DeviceInfo->Port) ||
2607           ((Target8[0] == DeviceInfo->Port) &&
2608            (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) {
2609         Target8[0] = (UINT8)DeviceInfo->Port;
2610         Target8[1] = (UINT8)DeviceInfo->PortMultiplier;
2611         goto Exit;
2612       }
2613 
2614       Node = GetNextNode (&Instance->DeviceList, Node);
2615     }
2616 
2617     return EFI_NOT_FOUND;
2618   } else {
2619     //
2620     // If the array is all 0xFF's, start to traverse the device list from the beginning
2621     //
2622     Node = GetFirstNode (&Instance->DeviceList);
2623 
2624     while (!IsNull (&Instance->DeviceList, Node)) {
2625       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);
2626 
2627       if (DeviceInfo->Type == EfiIdeCdrom) {
2628         Target8[0] = (UINT8)DeviceInfo->Port;
2629         Target8[1] = (UINT8)DeviceInfo->PortMultiplier;
2630         goto Exit;
2631       }
2632 
2633       Node = GetNextNode (&Instance->DeviceList, Node);
2634     }
2635 
2636     return EFI_NOT_FOUND;
2637   }
2638 
2639 Exit:
2640   //
2641   // Update the PreviousTargetId.
2642   //
2643   Instance->PreviousTargetId = *Target16;
2644 
2645   return EFI_SUCCESS;
2646 }
2647 
2648