]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c
MdeModulePkg/AtaAtapiPassThru: Revert patch to disable Bus Master
[mirror_edk2.git] / MdeModulePkg / Bus / Ata / AtaAtapiPassThru / AtaAtapiPassThru.c
index 526590718aa0e43fe2f2496103c7f6052eaed7ee..09064dda18b70753d6a100ad21e9855c90291e78 100644 (file)
@@ -1,8 +1,8 @@
 /** @file\r
   This file implements ATA_PASSTHRU_PROCTOCOL and EXT_SCSI_PASSTHRU_PROTOCOL interfaces\r
   for managed ATA controllers.\r
-    \r
-  Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>\r
+\r
+  Copyright (c) 2010 - 2016, Intel Corporation. All rights reserved.<BR>\r
   This program and the accompanying materials\r
   are licensed and made available under the terms and conditions of the BSD License\r
   which accompanies this distribution.  The full text of the license may be found at\r
@@ -46,14 +46,14 @@ ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = {
     sizeof (UINTN)\r
   },\r
   {                   // AtaPassThru\r
-    NULL,  \r
+    NULL,\r
     AtaPassThruPassThru,\r
     AtaPassThruGetNextPort,\r
     AtaPassThruGetNextDevice,\r
     AtaPassThruBuildDevicePath,\r
     AtaPassThruGetDevice,\r
     AtaPassThruResetPort,\r
-    AtaPassThruResetDevice  \r
+    AtaPassThruResetDevice\r
   },\r
   {                   // ExtScsiPassThruMode\r
     //\r
@@ -65,7 +65,7 @@ ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = {
     // both EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_PHYSICAL and EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_LOGICAL\r
     // bits.\r
     // Note that the driver doesn't support ExtScsiPassThru non blocking I/O.\r
-    // \r
+    //\r
     EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_PHYSICAL | EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_LOGICAL,\r
     //\r
     // IoAlign\r
@@ -94,6 +94,7 @@ ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = {
     NULL,\r
     NULL\r
   },\r
+  0,                  // EnabledPciAttributes\r
   0,                  // OriginalAttributes\r
   0,                  // PreviousPort\r
   0,                  // PreviousPortMultiplier\r
@@ -101,17 +102,20 @@ ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = {
   0,                  // PreviousLun\r
   NULL,               // Timer event\r
   {                   // NonBlocking TaskList\r
-    NULL,             \r
+    NULL,\r
     NULL\r
-  }\r
+  },\r
+  NULL,               // ExitBootEvent\r
 };\r
 \r
 ATAPI_DEVICE_PATH    mAtapiDevicePathTemplate = {\r
   {\r
     MESSAGING_DEVICE_PATH,\r
     MSG_ATAPI_DP,\r
-    (UINT8) (sizeof (ATAPI_DEVICE_PATH)),\r
-    (UINT8) ((sizeof (ATAPI_DEVICE_PATH)) >> 8),\r
+    {\r
+      (UINT8) (sizeof (ATAPI_DEVICE_PATH)),\r
+      (UINT8) ((sizeof (ATAPI_DEVICE_PATH)) >> 8)\r
+    }\r
   },\r
   0,\r
   0,\r
@@ -122,8 +126,10 @@ SATA_DEVICE_PATH    mSataDevicePathTemplate = {
   {\r
     MESSAGING_DEVICE_PATH,\r
     MSG_SATA_DP,\r
-    (UINT8) (sizeof (SATA_DEVICE_PATH)),\r
-    (UINT8) ((sizeof (SATA_DEVICE_PATH)) >> 8),\r
+    {\r
+      (UINT8) (sizeof (SATA_DEVICE_PATH)),\r
+      (UINT8) ((sizeof (SATA_DEVICE_PATH)) >> 8)\r
+    }\r
   },\r
   0,\r
   0,\r
@@ -142,9 +148,9 @@ UINT8 mScsiId[TARGET_MAX_BYTES] = {
   supports both blocking I/O and non-blocking I/O. The blocking I/O functionality is required,\r
   and the non-blocking I/O functionality is optional.\r
 \r
-  @param[in]      Port               The port number of the ATA device to send the command. \r
+  @param[in]      Port               The port number of the ATA device to send the command.\r
   @param[in]      PortMultiplierPort The port multiplier port number of the ATA device to send the command.\r
-                                     If there is no port multiplier, then specify 0.\r
+                                     If there is no port multiplier, then specify 0xFFFF.\r
   @param[in, out] Packet             A pointer to the ATA command to send to the ATA device specified by Port\r
                                      and PortMultiplierPort.\r
   @param[in]      Instance           Pointer to the ATA_ATAPI_PASS_THRU_INSTANCE.\r
@@ -178,14 +184,14 @@ AtaPassThruPassThruExecute (
   IN     UINT16                           Port,\r
   IN     UINT16                           PortMultiplierPort,\r
   IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet,\r
-  IN     ATA_ATAPI_PASS_THRU_INSTANCE     *Instance, \r
+  IN     ATA_ATAPI_PASS_THRU_INSTANCE     *Instance,\r
   IN     ATA_NONBLOCK_TASK                *Task OPTIONAL\r
   )\r
 {\r
   EFI_ATA_PASS_THRU_CMD_PROTOCOL  Protocol;\r
   EFI_ATA_HC_WORK_MODE            Mode;\r
   EFI_STATUS                      Status;\r
-  \r
+\r
   Protocol = Packet->Protocol;\r
 \r
   Mode = Instance->Mode;\r
@@ -195,11 +201,11 @@ AtaPassThruPassThruExecute (
       // Reassign IDE mode io port registers' base addresses\r
       //\r
       Status = GetIdeRegisterIoAddr (Instance->PciIo, Instance->IdeRegisters);\r
-      \r
+\r
       if (EFI_ERROR (Status)) {\r
         return Status;\r
       }\r
-      \r
+\r
       switch (Protocol) {\r
         case EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA:\r
           Status = AtaNonDataCommandIn (\r
@@ -207,7 +213,7 @@ AtaPassThruPassThruExecute (
                      &Instance->IdeRegisters[Port],\r
                      Packet->Acb,\r
                      Packet->Asb,\r
-                     Packet->Timeout, \r
+                     Packet->Timeout,\r
                      Task\r
                      );\r
           break;\r
@@ -268,6 +274,14 @@ AtaPassThruPassThruExecute (
       }\r
       break;\r
     case EfiAtaAhciMode :\r
+      if (PortMultiplierPort == 0xFFFF) {\r
+        //\r
+        // If there is no port multiplier, PortMultiplierPort will be 0xFFFF\r
+        // according to UEFI spec. Here, we convert its value to 0 to follow\r
+        // AHCI spec.\r
+        //\r
+        PortMultiplierPort = 0;\r
+      }\r
       switch (Protocol) {\r
         case EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA:\r
           Status = AhciNonDataTransfer (\r
@@ -313,7 +327,7 @@ AtaPassThruPassThruExecute (
                      Packet->Asb,\r
                      Packet->OutDataBuffer,\r
                      Packet->OutTransferLength,\r
-                     Packet->Timeout, \r
+                     Packet->Timeout,\r
                      Task\r
                      );\r
           break;\r
@@ -360,7 +374,7 @@ AtaPassThruPassThruExecute (
       Status = EFI_DEVICE_ERROR;\r
       break;\r
   }\r
-  \r
+\r
   return Status;\r
 }\r
 \r
@@ -369,11 +383,11 @@ AtaPassThruPassThruExecute (
 \r
   @param[in]  Event     The Event this notify function registered to.\r
   @param[in]  Context   Pointer to the context data registered to the\r
-                        Event. \r
\r
+                        Event.\r
+\r
 **/\r
 VOID\r
-EFIAPI \r
+EFIAPI\r
 AsyncNonBlockingTransferRoutine (\r
   EFI_EVENT  Event,\r
   VOID*      Context\r
@@ -388,7 +402,7 @@ AsyncNonBlockingTransferRoutine (
   Instance   = (ATA_ATAPI_PASS_THRU_INSTANCE *) Context;\r
   EntryHeader = &Instance->NonBlockingTaskList;\r
   //\r
-  // Get the Taks from the Taks List and execute it, until there is \r
+  // Get the Taks from the Taks List and execute it, until there is\r
   // no task in the list or the device is busy with task (EFI_NOT_READY).\r
   //\r
   while (TRUE) {\r
@@ -408,23 +422,24 @@ AsyncNonBlockingTransferRoutine (
                );\r
 \r
     //\r
-    // If the data transfer meet a error which is not dumped into the status block\r
-    // set the Status block related bit.\r
+    // If the data transfer meet a error, remove all tasks in the list since these tasks are\r
+    // associated with one task from Ata Bus and signal the event with error status.\r
     //\r
     if ((Status != EFI_NOT_READY) && (Status != EFI_SUCCESS)) {\r
-      Task->Packet->Asb->AtaStatus = 0x01;\r
+      DestroyAsynTaskList (Instance, TRUE);\r
+      break;\r
     }\r
+\r
     //\r
     // For Non blocking mode, the Status of EFI_NOT_READY means the operation\r
-    // is not finished yet. Other Status indicate the operation is either\r
-    // successful or failed. \r
+    // is not finished yet. Otherwise the operation is successful.\r
     //\r
-    if (Status != EFI_NOT_READY) {\r
+    if (Status == EFI_NOT_READY) {\r
+      break;\r
+    } else {\r
       RemoveEntryList (&Task->Link);\r
       gBS->SignalEvent (Task->Event);\r
       FreePool (Task);\r
-    } else {\r
-      break;\r
     }\r
   }\r
 }\r
@@ -465,33 +480,65 @@ InitializeAtaAtapiPassThru (
 }\r
 \r
 /**\r
-  Tests to see if this driver supports a given controller. If a child device is provided, \r
+  Disable the device (especially Bus Master DMA) when exiting the boot\r
+  services.\r
+\r
+  @param[in] Event    Event for which this notification function is being\r
+                      called.\r
+  @param[in] Context  Pointer to the ATA_ATAPI_PASS_THRU_INSTANCE that\r
+                      represents the HBA.\r
+**/\r
+VOID\r
+EFIAPI\r
+AtaPassThruExitBootServices (\r
+  IN EFI_EVENT Event,\r
+  IN VOID      *Context\r
+  )\r
+{\r
+  ATA_ATAPI_PASS_THRU_INSTANCE *Instance;\r
+  EFI_PCI_IO_PROTOCOL          *PciIo;\r
+\r
+  DEBUG ((DEBUG_VERBOSE, "%a: Context=0x%p\n", __FUNCTION__, Context));\r
+\r
+  Instance = Context;\r
+  PciIo = Instance->PciIo;\r
+\r
+  PciIo->Attributes (\r
+           PciIo,\r
+           EfiPciIoAttributeOperationDisable,\r
+           Instance->EnabledPciAttributes,\r
+           NULL\r
+           );\r
+}\r
+\r
+/**\r
+  Tests to see if this driver supports a given controller. If a child device is provided,\r
   it further tests to see if this driver supports creating a handle for the specified child device.\r
 \r
-  This function checks to see if the driver specified by This supports the device specified by \r
-  ControllerHandle. Drivers will typically use the device path attached to \r
-  ControllerHandle and/or the services from the bus I/O abstraction attached to \r
-  ControllerHandle to determine if the driver supports ControllerHandle. This function \r
-  may be called many times during platform initialization. In order to reduce boot times, the tests \r
-  performed by this function must be very small, and take as little time as possible to execute. This \r
-  function must not change the state of any hardware devices, and this function must be aware that the \r
-  device specified by ControllerHandle may already be managed by the same driver or a \r
-  different driver. This function must match its calls to AllocatePages() with FreePages(), \r
-  AllocatePool() with FreePool(), and OpenProtocol() with CloseProtocol().  \r
-  Because ControllerHandle may have been previously started by the same driver, if a protocol is \r
-  already in the opened state, then it must not be closed with CloseProtocol(). This is required \r
+  This function checks to see if the driver specified by This supports the device specified by\r
+  ControllerHandle. Drivers will typically use the device path attached to\r
+  ControllerHandle and/or the services from the bus I/O abstraction attached to\r
+  ControllerHandle to determine if the driver supports ControllerHandle. This function\r
+  may be called many times during platform initialization. In order to reduce boot times, the tests\r
+  performed by this function must be very small, and take as little time as possible to execute. This\r
+  function must not change the state of any hardware devices, and this function must be aware that the\r
+  device specified by ControllerHandle may already be managed by the same driver or a\r
+  different driver. This function must match its calls to AllocatePages() with FreePages(),\r
+  AllocatePool() with FreePool(), and OpenProtocol() with CloseProtocol().\r
+  Because ControllerHandle may have been previously started by the same driver, if a protocol is\r
+  already in the opened state, then it must not be closed with CloseProtocol(). This is required\r
   to guarantee the state of ControllerHandle is not modified by this function.\r
 \r
   @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.\r
-  @param[in]  ControllerHandle     The handle of the controller to test. This handle \r
-                                   must support a protocol interface that supplies \r
+  @param[in]  ControllerHandle     The handle of the controller to test. This handle\r
+                                   must support a protocol interface that supplies\r
                                    an I/O abstraction to the driver.\r
-  @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This \r
-                                   parameter is ignored by device drivers, and is optional for bus \r
-                                   drivers. For bus drivers, if this parameter is not NULL, then \r
-                                   the bus driver must determine if the bus controller specified \r
-                                   by ControllerHandle and the child controller specified \r
-                                   by RemainingDevicePath are both supported by this \r
+  @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This\r
+                                   parameter is ignored by device drivers, and is optional for bus\r
+                                   drivers. For bus drivers, if this parameter is not NULL, then\r
+                                   the bus driver must determine if the bus controller specified\r
+                                   by ControllerHandle and the child controller specified\r
+                                   by RemainingDevicePath are both supported by this\r
                                    bus driver.\r
 \r
   @retval EFI_SUCCESS              The device specified by ControllerHandle and\r
@@ -614,8 +661,8 @@ AtaAtapiPassThruSupported (
   Starts a device controller or a bus controller.\r
 \r
   The Start() function is designed to be invoked from the EFI boot service ConnectController().\r
-  As a result, much of the error checking on the parameters to Start() has been moved into this \r
-  common boot service. It is legal to call Start() from other locations, \r
+  As a result, much of the error checking on the parameters to Start() has been moved into this\r
+  common boot service. It is legal to call Start() from other locations,\r
   but the following calling restrictions must be followed, or the system behavior will not be deterministic.\r
   1. ControllerHandle must be a valid EFI_HANDLE.\r
   2. If RemainingDevicePath is not NULL, then it must be a pointer to a naturally aligned\r
@@ -624,18 +671,18 @@ AtaAtapiPassThruSupported (
      have been called with the same calling parameters, and Supported() must have returned EFI_SUCCESS.\r
 \r
   @param[in]  This                 A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.\r
-  @param[in]  ControllerHandle     The handle of the controller to start. This handle \r
-                                   must support a protocol interface that supplies \r
+  @param[in]  ControllerHandle     The handle of the controller to start. This handle\r
+                                   must support a protocol interface that supplies\r
                                    an I/O abstraction to the driver.\r
-  @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This \r
-                                   parameter is ignored by device drivers, and is optional for bus \r
-                                   drivers. For a bus driver, if this parameter is NULL, then handles \r
+  @param[in]  RemainingDevicePath  A pointer to the remaining portion of a device path.  This\r
+                                   parameter is ignored by device drivers, and is optional for bus\r
+                                   drivers. For a bus driver, if this parameter is NULL, then handles\r
                                    for all the children of Controller are created by this driver.\r
-                                   If this parameter is not NULL and the first Device Path Node is \r
-                                   not the End of Device Path Node, then only the handle for the \r
-                                   child device specified by the first Device Path Node of \r
+                                   If this parameter is not NULL and the first Device Path Node is\r
+                                   not the End of Device Path Node, then only the handle for the\r
+                                   child device specified by the first Device Path Node of\r
                                    RemainingDevicePath is created by this driver.\r
-                                   If the first Device Path Node of RemainingDevicePath is \r
+                                   If the first Device Path Node of RemainingDevicePath is\r
                                    the End of Device Path Node, no child handle is created by this\r
                                    driver.\r
 \r
@@ -657,14 +704,12 @@ AtaAtapiPassThruStart (
   EFI_IDE_CONTROLLER_INIT_PROTOCOL  *IdeControllerInit;\r
   ATA_ATAPI_PASS_THRU_INSTANCE      *Instance;\r
   EFI_PCI_IO_PROTOCOL               *PciIo;\r
-  UINT64                            Supports;\r
-  BOOLEAN                           PciAttributesSaved;\r
+  UINT64                            EnabledPciAttributes;\r
   UINT64                            OriginalPciAttributes;\r
 \r
   Status                = EFI_SUCCESS;\r
   IdeControllerInit     = NULL;\r
   Instance              = NULL;\r
-  PciAttributesSaved    = FALSE;\r
   OriginalPciAttributes = 0;\r
 \r
   DEBUG ((EFI_D_INFO, "==AtaAtapiPassThru Start== Controller = %x\n", Controller));\r
@@ -706,20 +751,19 @@ AtaAtapiPassThruStart (
   if (EFI_ERROR (Status)) {\r
     goto ErrorExit;\r
   }\r
-  PciAttributesSaved = TRUE;\r
 \r
   Status = PciIo->Attributes (\r
                     PciIo,\r
                     EfiPciIoAttributeOperationSupported,\r
                     0,\r
-                    &Supports\r
+                    &EnabledPciAttributes\r
                     );\r
   if (!EFI_ERROR (Status)) {\r
-    Supports &= EFI_PCI_DEVICE_ENABLE;\r
+    EnabledPciAttributes &= (UINT64)EFI_PCI_DEVICE_ENABLE;\r
     Status = PciIo->Attributes (\r
                       PciIo,\r
                       EfiPciIoAttributeOperationEnable,\r
-                      Supports,\r
+                      EnabledPciAttributes,\r
                       NULL\r
                       );\r
   }\r
@@ -739,12 +783,24 @@ AtaAtapiPassThruStart (
   Instance->ControllerHandle      = Controller;\r
   Instance->IdeControllerInit     = IdeControllerInit;\r
   Instance->PciIo                 = PciIo;\r
+  Instance->EnabledPciAttributes  = EnabledPciAttributes;\r
   Instance->OriginalPciAttributes = OriginalPciAttributes;\r
   Instance->AtaPassThru.Mode      = &Instance->AtaPassThruMode;\r
   Instance->ExtScsiPassThru.Mode  = &Instance->ExtScsiPassThruMode;\r
   InitializeListHead(&Instance->DeviceList);\r
   InitializeListHead(&Instance->NonBlockingTaskList);\r
 \r
+  Status = gBS->CreateEvent (\r
+                  EVT_SIGNAL_EXIT_BOOT_SERVICES,\r
+                  TPL_CALLBACK,\r
+                  AtaPassThruExitBootServices,\r
+                  Instance,\r
+                  &Instance->ExitBootEvent\r
+                  );\r
+  if (EFI_ERROR (Status)) {\r
+    goto ErrorExit;\r
+  }\r
+\r
   Instance->TimerEvent = NULL;\r
 \r
   Status = gBS->CreateEvent (\r
@@ -757,7 +813,7 @@ AtaAtapiPassThruStart (
   if (EFI_ERROR (Status)) {\r
     goto ErrorExit;\r
   }\r
-  \r
+\r
   //\r
   // Set 1ms timer.\r
   //\r
@@ -798,6 +854,10 @@ ErrorExit:
     gBS->CloseEvent (Instance->TimerEvent);\r
   }\r
 \r
+  if ((Instance != NULL) && (Instance->ExitBootEvent != NULL)) {\r
+    gBS->CloseEvent (Instance->ExitBootEvent);\r
+  }\r
+\r
   //\r
   // Remove all inserted ATA devices.\r
   //\r
@@ -811,10 +871,10 @@ ErrorExit:
 \r
 /**\r
   Stops a device controller or a bus controller.\r
-  \r
-  The Stop() function is designed to be invoked from the EFI boot service DisconnectController(). \r
-  As a result, much of the error checking on the parameters to Stop() has been moved \r
-  into this common boot service. It is legal to call Stop() from other locations, \r
+\r
+  The Stop() function is designed to be invoked from the EFI boot service DisconnectController().\r
+  As a result, much of the error checking on the parameters to Stop() has been moved\r
+  into this common boot service. It is legal to call Stop() from other locations,\r
   but the following calling restrictions must be followed, or the system behavior will not be deterministic.\r
   1. ControllerHandle must be a valid EFI_HANDLE that was used on a previous call to this\r
      same driver's Start() function.\r
@@ -822,13 +882,13 @@ ErrorExit:
      EFI_HANDLE. In addition, all of these handles must have been created in this driver's\r
      Start() function, and the Start() function must have called OpenProtocol() on\r
      ControllerHandle with an Attribute of EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER.\r
-  \r
+\r
   @param[in]  This              A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.\r
-  @param[in]  ControllerHandle  A handle to the device being stopped. The handle must \r
-                                support a bus specific I/O protocol for the driver \r
+  @param[in]  ControllerHandle  A handle to the device being stopped. The handle must\r
+                                support a bus specific I/O protocol for the driver\r
                                 to use to stop the device.\r
   @param[in]  NumberOfChildren  The number of child device handles in ChildHandleBuffer.\r
-  @param[in]  ChildHandleBuffer An array of child handles to be freed. May be NULL \r
+  @param[in]  ChildHandleBuffer An array of child handles to be freed. May be NULL\r
                                 if NumberOfChildren is 0.\r
 \r
   @retval EFI_SUCCESS           The device was stopped.\r
@@ -849,7 +909,6 @@ AtaAtapiPassThruStop (
   EFI_ATA_PASS_THRU_PROTOCOL        *AtaPassThru;\r
   EFI_PCI_IO_PROTOCOL               *PciIo;\r
   EFI_AHCI_REGISTERS                *AhciRegisters;\r
-  UINT64                            Supports;\r
 \r
   DEBUG ((EFI_D_INFO, "==AtaAtapiPassThru Stop== Controller = %x\n", Controller));\r
 \r
@@ -868,6 +927,27 @@ AtaAtapiPassThruStop (
 \r
   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (AtaPassThru);\r
 \r
+  Status = gBS->UninstallMultipleProtocolInterfaces (\r
+                  Controller,\r
+                  &gEfiAtaPassThruProtocolGuid, &(Instance->AtaPassThru),\r
+                  &gEfiExtScsiPassThruProtocolGuid, &(Instance->ExtScsiPassThru),\r
+                  NULL\r
+                  );\r
+\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_DEVICE_ERROR;\r
+  }\r
+\r
+  //\r
+  // Close protocols opened by AtaAtapiPassThru controller driver\r
+  //\r
+  gBS->CloseProtocol (\r
+         Controller,\r
+         &gEfiIdeControllerInitProtocolGuid,\r
+         This->DriverBindingHandle,\r
+         Controller\r
+         );\r
+\r
   //\r
   // Close Non-Blocking timer and free Task list.\r
   //\r
@@ -875,60 +955,32 @@ AtaAtapiPassThruStop (
     gBS->CloseEvent (Instance->TimerEvent);\r
     Instance->TimerEvent = NULL;\r
   }\r
-  DestroyAsynTaskList (Instance);\r
+  DestroyAsynTaskList (Instance, FALSE);\r
 \r
   //\r
-  // Disable this ATA host controller.\r
+  // Close event signaled at gBS->ExitBootServices().\r
   //\r
-  PciIo  = Instance->PciIo;\r
-  Status = PciIo->Attributes (\r
-                    PciIo,\r
-                    EfiPciIoAttributeOperationSupported,\r
-                    0,\r
-                    &Supports\r
-                    );\r
-  if (!EFI_ERROR (Status)) {\r
-    Supports &= EFI_PCI_DEVICE_ENABLE;\r
-    PciIo->Attributes (\r
-             PciIo,\r
-             EfiPciIoAttributeOperationDisable,\r
-             Supports,\r
-             NULL\r
-             );\r
+  if (Instance->ExitBootEvent != NULL) {\r
+    gBS->CloseEvent (Instance->ExitBootEvent);\r
+    Instance->ExitBootEvent = NULL;\r
   }\r
 \r
   //\r
-  // Restore original PCI attributes\r
+  // Free allocated resource\r
   //\r
-  Status = PciIo->Attributes (\r
-                    PciIo,\r
-                    EfiPciIoAttributeOperationSet,\r
-                    Instance->OriginalPciAttributes,\r
-                    NULL\r
-                    );\r
-  ASSERT_EFI_ERROR (Status);\r
+  DestroyDeviceInfoList (Instance);\r
 \r
-  gBS->UninstallMultipleProtocolInterfaces (\r
-         Controller,\r
-         &gEfiAtaPassThruProtocolGuid, &(Instance->AtaPassThru),\r
-         &gEfiExtScsiPassThruProtocolGuid, &(Instance->ExtScsiPassThru),\r
-         NULL\r
-         );\r
+  PciIo = Instance->PciIo;\r
 \r
   //\r
-  // Close protocols opened by AtaAtapiPassThru controller driver\r
-  //\r
-  gBS->CloseProtocol (\r
-         Controller,\r
-         &gEfiIdeControllerInitProtocolGuid,\r
-         This->DriverBindingHandle,\r
-         Controller\r
-         );\r
-\r
-  //\r
-  // Free allocated resource\r
+  // Disable this ATA host controller.\r
   //\r
-  DestroyDeviceInfoList(Instance);\r
+  PciIo->Attributes (\r
+           PciIo,\r
+           EfiPciIoAttributeOperationDisable,\r
+           Instance->EnabledPciAttributes,\r
+           NULL\r
+           );\r
 \r
   //\r
   // If the current working mode is AHCI mode, then pre-allocated resource\r
@@ -964,6 +1016,18 @@ AtaAtapiPassThruStop (
              AhciRegisters->AhciRFis\r
              );\r
   }\r
+\r
+  //\r
+  // Restore original PCI attributes\r
+  //\r
+  Status = PciIo->Attributes (\r
+                    PciIo,\r
+                    EfiPciIoAttributeOperationSet,\r
+                    Instance->OriginalPciAttributes,\r
+                    NULL\r
+                    );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
   FreePool (Instance);\r
 \r
   return Status;\r
@@ -971,13 +1035,13 @@ AtaAtapiPassThruStop (
 \r
 /**\r
   Traverse the attached ATA devices list to find out the device to access.\r
-  \r
+\r
   @param[in]  Instance            A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.\r
-  @param[in]  Port                The port number of the ATA device to send the command. \r
+  @param[in]  Port                The port number of the ATA device to send the command.\r
   @param[in]  PortMultiplierPort  The port multiplier port number of the ATA device to send the command.\r
-                                  If there is no port multiplier, then specify 0.\r
+                                  If there is no port multiplier, then specify 0xFFFF.\r
   @param[in]  DeviceType          The device type of the ATA device.\r
-  \r
+\r
   @retval     The pointer to the data structure of the device info to access.\r
 \r
 **/\r
@@ -997,8 +1061,20 @@ SearchDeviceInfoList (
   while (!IsNull (&Instance->DeviceList, Node)) {\r
     DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);\r
 \r
+    //\r
+    // For CD-ROM working in the AHCI mode, only 8 bits are used to record\r
+    // the PortMultiplier information. If the CD-ROM is directly attached\r
+    // on a SATA port, the PortMultiplier should be translated from 0xFF\r
+    // to 0xFFFF according to the UEFI spec.\r
+    //\r
+    if ((Instance->Mode == EfiAtaAhciMode) &&\r
+        (DeviceInfo->Type == EfiIdeCdrom) &&\r
+        (PortMultiplier == 0xFF)) {\r
+        PortMultiplier = 0xFFFF;\r
+    }\r
+\r
     if ((DeviceInfo->Type == DeviceType) &&\r
-        (Port == DeviceInfo->Port) && \r
+        (Port == DeviceInfo->Port) &&\r
         (PortMultiplier == DeviceInfo->PortMultiplier)) {\r
       return Node;\r
     }\r
@@ -1012,11 +1088,11 @@ SearchDeviceInfoList (
 /**\r
   Allocate device info data structure to contain device info.\r
   And insert the data structure to the tail of device list for tracing.\r
-    \r
+\r
   @param[in]  Instance            A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.\r
-  @param[in]  Port                The port number of the ATA device to send the command. \r
+  @param[in]  Port                The port number of the ATA device to send the command.\r
   @param[in]  PortMultiplierPort  The port multiplier port number of the ATA device to send the command.\r
-                                  If there is no port multiplier, then specify 0.\r
+                                  If there is no port multiplier, then specify 0xFFFF.\r
   @param[in]  DeviceType          The device type of the ATA device.\r
   @param[in]  IdentifyData        The data buffer to store the output of the IDENTIFY cmd.\r
 \r
@@ -1062,7 +1138,7 @@ CreateNewDeviceInfo (
 \r
 /**\r
   Destroy all attached ATA devices info.\r
-  \r
+\r
   @param[in]  Instance          A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.\r
 \r
 **/\r
@@ -1091,14 +1167,17 @@ DestroyDeviceInfoList (
 \r
 /**\r
   Destroy all pending non blocking tasks.\r
-  \r
-  @param[in]  Instance  A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.\r
+\r
+  @param[in]  Instance    A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.\r
+  @param[in]  IsSigEvent  Indicate whether signal the task event when remove the\r
+                          task.\r
 \r
 **/\r
 VOID\r
 EFIAPI\r
 DestroyAsynTaskList (\r
-  IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance\r
+  IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance,\r
+  IN BOOLEAN                       IsSigEvent\r
   )\r
 {\r
   LIST_ENTRY           *Entry;\r
@@ -1111,7 +1190,7 @@ DestroyAsynTaskList (
     //\r
     // Free the Subtask list.\r
     //\r
-    for (Entry = (&Instance->NonBlockingTaskList)->ForwardLink; \r
+    for (Entry = (&Instance->NonBlockingTaskList)->ForwardLink;\r
         Entry != (&Instance->NonBlockingTaskList);\r
        ) {\r
       DelEntry = Entry;\r
@@ -1119,6 +1198,10 @@ DestroyAsynTaskList (
       Task     = ATA_NON_BLOCK_TASK_FROM_ENTRY (DelEntry);\r
 \r
       RemoveEntryList (DelEntry);\r
+      if (IsSigEvent) {\r
+        Task->Packet->Asb->AtaStatus = 0x01;\r
+        gBS->SignalEvent (Task->Event);\r
+      }\r
       FreePool (Task);\r
     }\r
   }\r
@@ -1127,9 +1210,9 @@ DestroyAsynTaskList (
 \r
 /**\r
   Enumerate all attached ATA devices at IDE mode or AHCI mode separately.\r
-  \r
-  The function is designed to enumerate all attached ATA devices. \r
-  \r
+\r
+  The function is designed to enumerate all attached ATA devices.\r
+\r
   @param[in]  Instance          A pointer to the ATA_ATAPI_PASS_THRU_INSTANCE instance.\r
 \r
   @retval EFI_SUCCESS           Successfully enumerate attached ATA devices.\r
@@ -1199,10 +1282,10 @@ Done:
   supports both blocking I/O and non-blocking I/O. The blocking I/O functionality is required,\r
   and the non-blocking I/O functionality is optional.\r
 \r
-  @param[in]      This               A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance. \r
-  @param[in]      Port               The port number of the ATA device to send the command. \r
+  @param[in]      This               A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.\r
+  @param[in]      Port               The port number of the ATA device to send the command.\r
   @param[in]      PortMultiplierPort The port multiplier port number of the ATA device to send the command.\r
-                                     If there is no port multiplier, then specify 0.\r
+                                     If there is no port multiplier, then specify 0xFFFF.\r
   @param[in, out] Packet             A pointer to the ATA command to send to the ATA device specified by Port\r
                                      and PortMultiplierPort.\r
   @param[in]      Event               If non-blocking I/O is not supported then Event is ignored, and blocking\r
@@ -1210,11 +1293,11 @@ Done:
                                      Event is not NULL and non blocking I/O is supported, then non-blocking\r
                                      I/O is performed, and Event will be signaled when the ATA command completes.\r
 \r
-  @retval EFI_SUCCESS                The ATA command was sent by the host. For bi-directional commands, \r
+  @retval EFI_SUCCESS                The ATA command was sent by the host. For bi-directional commands,\r
                                      InTransferLength bytes were transferred from InDataBuffer. For write and\r
                                      bi-directional commands, OutTransferLength bytes were transferred by OutDataBuffer.\r
   @retval EFI_BAD_BUFFER_SIZE        The ATA command was not executed. The number of bytes that could be transferred\r
-                                     is returned in InTransferLength. For write and bi-directional commands, \r
+                                     is returned in InTransferLength. For write and bi-directional commands,\r
                                      OutTransferLength bytes were transferred by OutDataBuffer.\r
   @retval EFI_NOT_READY              The ATA command could not be sent because there are too many ATA commands\r
                                      already queued. The caller may retry again later.\r
@@ -1241,6 +1324,7 @@ AtaPassThruPassThru (
   UINT32                          MaxSectorCount;\r
   ATA_NONBLOCK_TASK               *Task;\r
   EFI_TPL                         OldTpl;\r
+  UINT32                          BlockSize;\r
 \r
   Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);\r
 \r
@@ -1256,32 +1340,19 @@ AtaPassThruPassThru (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  //\r
-  // convert the transfer length from sector count to byte.\r
-  //\r
-  if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) && \r
-       (Packet->InTransferLength != 0)) {\r
-    Packet->InTransferLength = Packet->InTransferLength * 0x200;\r
-  }\r
-\r
-  //\r
-  // convert the transfer length from sector count to byte.\r
-  //\r
-  if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) &&\r
-       (Packet->OutTransferLength != 0)) {\r
-    Packet->OutTransferLength = Packet->OutTransferLength * 0x200;\r
-  }\r
-\r
   Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeHarddisk);\r
 \r
   if (Node == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
+    Node = SearchDeviceInfoList(Instance, Port, PortMultiplierPort, EfiIdeCdrom);\r
+    if (Node == NULL) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
   }\r
 \r
   //\r
   // Check whether this device needs 48-bit addressing (ATAPI-6 ata device).\r
   // Per ATA-6 spec, word83: bit15 is zero and bit14 is one.\r
-  // If bit10 is one, it means the ata device support 48-bit addressing. \r
+  // If bit10 is one, it means the ata device support 48-bit addressing.\r
   //\r
   DeviceInfo     = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);\r
   IdentifyData   = DeviceInfo->IdentifyData;\r
@@ -1297,13 +1368,39 @@ AtaPassThruPassThru (
     }\r
   }\r
 \r
+  BlockSize = 0x200;\r
+  if ((IdentifyData->AtaData.phy_logic_sector_support & (BIT14 | BIT15)) == BIT14) {\r
+    //\r
+    // Check logical block size\r
+    //\r
+    if ((IdentifyData->AtaData.phy_logic_sector_support & BIT12) != 0) {\r
+      BlockSize = (UINT32) (((IdentifyData->AtaData.logic_sector_size_hi << 16) | IdentifyData->AtaData.logic_sector_size_lo) * sizeof (UINT16));\r
+    }\r
+  }\r
+\r
+  //\r
+  // convert the transfer length from sector count to byte.\r
+  //\r
+  if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) &&\r
+       (Packet->InTransferLength != 0)) {\r
+    Packet->InTransferLength = Packet->InTransferLength * BlockSize;\r
+  }\r
+\r
+  //\r
+  // convert the transfer length from sector count to byte.\r
+  //\r
+  if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) &&\r
+       (Packet->OutTransferLength != 0)) {\r
+    Packet->OutTransferLength = Packet->OutTransferLength * BlockSize;\r
+  }\r
+\r
   //\r
   // If the data buffer described by InDataBuffer/OutDataBuffer and InTransferLength/OutTransferLength\r
   // is too big to be transferred in a single command, then no data is transferred and EFI_BAD_BUFFER_SIZE\r
-  // is returned. \r
+  // is returned.\r
   //\r
-  if (((Packet->InTransferLength != 0) && (Packet->InTransferLength > MaxSectorCount * 0x200)) || \r
-      ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * 0x200))) {\r
+  if (((Packet->InTransferLength != 0) && (Packet->InTransferLength > MaxSectorCount * BlockSize)) ||\r
+      ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * BlockSize))) {\r
     return EFI_BAD_BUFFER_SIZE;\r
   }\r
 \r
@@ -1315,14 +1412,19 @@ AtaPassThruPassThru (
     if (Task == NULL) {\r
       return EFI_OUT_OF_RESOURCES;\r
     }\r
-    \r
+\r
     Task->Signature      = ATA_NONBLOCKING_TASK_SIGNATURE;\r
     Task->Port           = Port;\r
     Task->PortMultiplier = PortMultiplierPort;\r
     Task->Packet         = Packet;\r
     Task->Event          = Event;\r
     Task->IsStart        = FALSE;\r
-    Task->RetryTimes     = 0;\r
+    Task->RetryTimes     = DivU64x32(Packet->Timeout, 1000) + 1;\r
+    if (Packet->Timeout == 0) {\r
+      Task->InfiniteWait = TRUE;\r
+    } else {\r
+      Task->InfiniteWait = FALSE;\r
+    }\r
 \r
     OldTpl = gBS->RaiseTPL (TPL_NOTIFY);\r
     InsertTailList (&Instance->NonBlockingTaskList, &Task->Link);\r
@@ -1359,7 +1461,7 @@ AtaPassThruPassThru (
   If Port is the port number of the last port on the ATA controller, then EFI_NOT_FOUND is\r
   returned.\r
 \r
-  @param[in]      This          A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance. \r
+  @param[in]      This          A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.\r
   @param[in, out] Port          On input, a pointer to the port number on the ATA controller.\r
                                 On output, a pointer to the next port number on the ATA\r
                                 controller. An input value of 0xFFFF retrieves the first port\r
@@ -1439,36 +1541,36 @@ Exit:
 }\r
 \r
 /**\r
-  Used to retrieve the list of legal port multiplier port numbers for ATA devices on a port of an ATA \r
-  controller. These can either be the list of port multiplier ports where ATA devices are actually \r
-  present on port or the list of legal port multiplier ports on that port. Regardless, the caller of this \r
-  function must probe the port number and port multiplier port number returned to see if an ATA \r
+  Used to retrieve the list of legal port multiplier port numbers for ATA devices on a port of an ATA\r
+  controller. These can either be the list of port multiplier ports where ATA devices are actually\r
+  present on port or the list of legal port multiplier ports on that port. Regardless, the caller of this\r
+  function must probe the port number and port multiplier port number returned to see if an ATA\r
   device is actually present.\r
 \r
-  The GetNextDevice() function retrieves the port multiplier port number of an ATA device \r
+  The GetNextDevice() function retrieves the port multiplier port number of an ATA device\r
   present on a port of an ATA controller.\r
 \r
-  If PortMultiplierPort points to a port multiplier port number value that was returned on a \r
+  If PortMultiplierPort points to a port multiplier port number value that was returned on a\r
   previous call to GetNextDevice(), then the port multiplier port number of the next ATA device\r
   on the port of the ATA controller is returned in PortMultiplierPort, and EFI_SUCCESS is\r
   returned.\r
 \r
-  If PortMultiplierPort points to 0xFFFF, then the port multiplier port number of the first \r
-  ATA device on port of the ATA controller is returned in PortMultiplierPort and \r
+  If PortMultiplierPort points to 0xFFFF, then the port multiplier port number of the first\r
+  ATA device on port of the ATA controller is returned in PortMultiplierPort and\r
   EFI_SUCCESS is returned.\r
 \r
   If PortMultiplierPort is not 0xFFFF and the value pointed to by PortMultiplierPort\r
   was not returned on a previous call to GetNextDevice(), then EFI_INVALID_PARAMETER\r
   is returned.\r
 \r
-  If PortMultiplierPort is the port multiplier port number of the last ATA device on the port of \r
+  If PortMultiplierPort is the port multiplier port number of the last ATA device on the port of\r
   the ATA controller, then EFI_NOT_FOUND is returned.\r
 \r
   @param[in]      This               A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.\r
   @param[in]      Port               The port number present on the ATA controller.\r
   @param[in, out] PortMultiplierPort On input, a pointer to the port multiplier port number of an\r
-                                     ATA device present on the ATA controller. \r
-                                     If on input a PortMultiplierPort of 0xFFFF is specified, \r
+                                     ATA device present on the ATA controller.\r
+                                     If on input a PortMultiplierPort of 0xFFFF is specified,\r
                                      then the port multiplier port number of the first ATA device\r
                                      is returned. On output, a pointer to the port multiplier port\r
                                      number of the next ATA device present on an ATA controller.\r
@@ -1498,17 +1600,25 @@ AtaPassThruGetNextDevice (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  if (*PortMultiplierPort == 0xFFFF) {\r
+  if (Instance->PreviousPortMultiplier == 0xFFFF) {\r
     //\r
-    // If the PortMultiplierPort is all 0xFF's, start to traverse the device list from the beginning\r
+    // If a device is directly attached on a port, previous call to this\r
+    // function will return the value 0xFFFF for PortMultiplierPort. In\r
+    // this case, there should be no more device on the port multiplier.\r
     //\r
+    Instance->PreviousPortMultiplier = 0;\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
+  if (*PortMultiplierPort == Instance->PreviousPortMultiplier) {\r
     Node = GetFirstNode (&Instance->DeviceList);\r
 \r
     while (!IsNull (&Instance->DeviceList, Node)) {\r
       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);\r
 \r
       if ((DeviceInfo->Type == EfiIdeHarddisk) &&\r
-           (DeviceInfo->Port == Port)){\r
+           (DeviceInfo->Port == Port) &&\r
+           (DeviceInfo->PortMultiplier > *PortMultiplierPort)){\r
         *PortMultiplierPort = DeviceInfo->PortMultiplier;\r
         goto Exit;\r
       }\r
@@ -1517,15 +1627,17 @@ AtaPassThruGetNextDevice (
     }\r
 \r
     return EFI_NOT_FOUND;\r
-  } else if (*PortMultiplierPort == Instance->PreviousPortMultiplier) {\r
+  } else if (*PortMultiplierPort == 0xFFFF) {\r
+    //\r
+    // If the PortMultiplierPort is all 0xFF's, start to traverse the device list from the beginning\r
+    //\r
     Node = GetFirstNode (&Instance->DeviceList);\r
 \r
     while (!IsNull (&Instance->DeviceList, Node)) {\r
       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);\r
 \r
       if ((DeviceInfo->Type == EfiIdeHarddisk) &&\r
-           (DeviceInfo->Port == Port) &&\r
-           (DeviceInfo->PortMultiplier > *PortMultiplierPort)){\r
+           (DeviceInfo->Port == Port)){\r
         *PortMultiplierPort = DeviceInfo->PortMultiplier;\r
         goto Exit;\r
       }\r
@@ -1568,7 +1680,7 @@ Exit:
                                      device path node is to be allocated and built.\r
   @param[in]      PortMultiplierPort The port multiplier port number of the ATA device for which a\r
                                      device path node is to be allocated and built. If there is no\r
-                                     port multiplier, then specify 0.\r
+                                     port multiplier, then specify 0xFFFF.\r
   @param[in, out] DevicePath         A pointer to a single device path node that describes the ATA\r
                                      device specified by Port and PortMultiplierPort. This function\r
                                      is responsible for allocating the buffer DevicePath with the\r
@@ -1638,7 +1750,7 @@ AtaPassThruBuildDevicePath (
 \r
   The GetDevice() function determines the port and port multiplier port number associated with\r
   the ATA device described by DevicePath. If DevicePath is a device path node type that the\r
-  ATA Pass Thru driver supports, then the ATA Pass Thru driver will attempt to translate the contents \r
+  ATA Pass Thru driver supports, then the ATA Pass Thru driver will attempt to translate the contents\r
   DevicePath into a port number and port multiplier port number.\r
 \r
   If this translation is successful, then that port number and port multiplier port number are returned\r
@@ -1646,11 +1758,11 @@ AtaPassThruBuildDevicePath (
 \r
   If DevicePath, Port, or PortMultiplierPort are NULL, then EFI_INVALID_PARAMETER is returned.\r
 \r
-  If DevicePath is not a device path node type that the ATA Pass Thru driver supports, then \r
+  If DevicePath is not a device path node type that the ATA Pass Thru driver supports, then\r
   EFI_UNSUPPORTED is returned.\r
 \r
-  If DevicePath is a device path node type that the ATA Pass Thru driver supports, but there is not \r
-  a valid translation from DevicePath to a port number and port multiplier port number, then \r
+  If DevicePath is a device path node type that the ATA Pass Thru driver supports, but there is not\r
+  a valid translation from DevicePath to a port number and port multiplier port number, then\r
   EFI_NOT_FOUND is returned.\r
 \r
   @param[in]  This                A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.\r
@@ -1752,7 +1864,10 @@ AtaPassThruResetPort (
   IN UINT16                     Port\r
   )\r
 {\r
-  return EFI_UNSUPPORTED;\r
+  //\r
+  // Return success directly then upper layer driver could think reset port operation is done.\r
+  //\r
+  return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
@@ -1762,7 +1877,7 @@ AtaPassThruResetPort (
   If this ATA controller does not support a device reset operation, then EFI_UNSUPPORTED is\r
   returned.\r
 \r
-  If Port or PortMultiplierPort are not in a valid range for this ATA controller, then \r
+  If Port or PortMultiplierPort are not in a valid range for this ATA controller, then\r
   EFI_INVALID_PARAMETER is returned.\r
 \r
   If a device error occurs while executing that device reset operation, then EFI_DEVICE_ERROR\r
@@ -1776,7 +1891,7 @@ AtaPassThruResetPort (
   @param[in] This                A pointer to the EFI_ATA_PASS_THRU_PROTOCOL instance.\r
   @param[in] Port                Port represents the port number of the ATA device to be reset.\r
   @param[in] PortMultiplierPort  The port multiplier port number of the ATA device to reset.\r
-                                 If there is no port multiplier, then specify 0.\r
+                                 If there is no port multiplier, then specify 0xFFFF.\r
   @retval EFI_SUCCESS            The ATA device specified by Port and PortMultiplierPort was reset.\r
   @retval EFI_UNSUPPORTED        The ATA controller does not support a device reset operation.\r
   @retval EFI_INVALID_PARAMETER  Port or PortMultiplierPort are invalid.\r
@@ -1794,13 +1909,78 @@ AtaPassThruResetDevice (
   IN UINT16                     PortMultiplierPort\r
   )\r
 {\r
-  return EFI_UNSUPPORTED;\r
+  ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;\r
+  LIST_ENTRY                      *Node;\r
+\r
+  Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);\r
+\r
+  Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeHarddisk);\r
+\r
+  if (Node == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Return success directly then upper layer driver could think reset device operation is done.\r
+  //\r
+  return EFI_SUCCESS;\r
+}\r
+\r
+/**\r
+  Submit ATAPI request sense command.\r
+\r
+  @param[in] This            A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.\r
+  @param[in] Target          The Target is an array of size TARGET_MAX_BYTES and it represents\r
+                             the id of the SCSI device to send the SCSI Request Packet. Each\r
+                             transport driver may choose to utilize a subset of this size to suit the needs\r
+                             of transport target representation. For example, a Fibre Channel driver\r
+                             may use only 8 bytes (WWN) to represent an FC target.\r
+  @param[in] Lun             The LUN of the SCSI device to send the SCSI Request Packet.\r
+  @param[in] SenseData       A pointer to store sense data.\r
+  @param[in] SenseDataLength The sense data length.\r
+  @param[in] Timeout         The timeout value to execute this cmd, uses 100ns as a unit.\r
+\r
+  @retval EFI_SUCCESS        Send out the ATAPI packet command successfully.\r
+  @retval EFI_DEVICE_ERROR   The device failed to send data.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+AtaPacketRequestSense (\r
+  IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL         *This,\r
+  IN  UINT8                                   *Target,\r
+  IN  UINT64                                  Lun,\r
+  IN  VOID                                    *SenseData,\r
+  IN  UINT8                                   SenseDataLength,\r
+  IN  UINT64                                  Timeout\r
+  )\r
+{\r
+  EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET  Packet;\r
+  UINT8                                       Cdb[12];\r
+  EFI_STATUS                                  Status;\r
+\r
+  ZeroMem (&Packet, sizeof (EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET));\r
+  ZeroMem (Cdb, 12);\r
+\r
+  Cdb[0] = ATA_CMD_REQUEST_SENSE;\r
+  Cdb[4] = SenseDataLength;\r
+\r
+  Packet.Timeout          = Timeout;\r
+  Packet.Cdb              = Cdb;\r
+  Packet.CdbLength        = 12;\r
+  Packet.DataDirection    = EFI_EXT_SCSI_DATA_DIRECTION_READ;\r
+  Packet.InDataBuffer     = SenseData;\r
+  Packet.InTransferLength = SenseDataLength;\r
+\r
+  Status = ExtScsiPassThruPassThru (This, Target, Lun, &Packet, NULL);\r
+\r
+  return Status;\r
 }\r
 \r
 /**\r
-  Sends a SCSI Request Packet to a SCSI device that is attached to the SCSI channel. This function   \r
+  Sends a SCSI Request Packet to a SCSI device that is attached to the SCSI channel. This function\r
   supports both blocking I/O and nonblocking I/O. The blocking I/O functionality is required, and the\r
-  nonblocking I/O functionality is optional.                                                             \r
+  nonblocking I/O functionality is optional.\r
 \r
   @param  This    A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.\r
   @param  Target  The Target is an array of size TARGET_MAX_BYTES and it represents\r
@@ -1855,8 +2035,13 @@ ExtScsiPassThruPassThru (
   EFI_ATA_HC_WORK_MODE            Mode;\r
   LIST_ENTRY                      *Node;\r
   EFI_ATA_DEVICE_INFO             *DeviceInfo;\r
+  BOOLEAN                         SenseReq;\r
+  EFI_SCSI_SENSE_DATA             *PtrSenseData;\r
+  UINTN                           SenseDataLen;\r
+  EFI_STATUS                      SenseStatus;\r
 \r
-  Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);\r
+  SenseDataLen = 0;\r
+  Instance     = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);\r
 \r
   if ((Packet == NULL) || (Packet->Cdb == NULL)) {\r
     return EFI_INVALID_PARAMETER;\r
@@ -1869,7 +2054,11 @@ ExtScsiPassThruPassThru (
       (Packet->CdbLength != 12) && (Packet->CdbLength != 16)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
-  \r
+\r
+  if ((Packet->SenseDataLength != 0) && (Packet->SenseData == NULL)) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
   if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->InDataBuffer, This->Mode->IoAlign)) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
@@ -1889,7 +2078,7 @@ ExtScsiPassThruPassThru (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  // \r
+  //\r
   // The layout of Target array:\r
   //  ________________________________________________________________________\r
   // |       Byte 0        |       Byte 1        | ... | TARGET_MAX_BYTES - 1 |\r
@@ -1917,6 +2106,10 @@ ExtScsiPassThruPassThru (
   //\r
   if (*((UINT8*)Packet->Cdb) == ATA_CMD_IDENTIFY_DEVICE) {\r
     CopyMem (Packet->InDataBuffer, DeviceInfo->IdentifyData, sizeof (EFI_IDENTIFY_DATA));\r
+    //\r
+    // For IDENTIFY DEVICE cmd, we don't need to get sense data.\r
+    //\r
+    Packet->SenseDataLength = 0;\r
     return EFI_SUCCESS;\r
   }\r
 \r
@@ -1935,6 +2128,13 @@ ExtScsiPassThruPassThru (
       Status = AtaPacketCommandExecute (Instance->PciIo, &Instance->IdeRegisters[Port], Port, PortMultiplier, Packet);\r
       break;\r
     case EfiAtaAhciMode:\r
+      if (PortMultiplier == 0xFF) {\r
+        //\r
+        // If there is no port multiplier, the PortMultiplier will be 0xFF\r
+        // Here, we convert its value to 0 to follow the AHCI spec.\r
+        //\r
+        PortMultiplier = 0;\r
+      }\r
       Status = AhciPacketCommandExecute (Instance->PciIo, &Instance->AhciRegisters, Port, PortMultiplier, Packet);\r
       break;\r
     default :\r
@@ -1942,14 +2142,54 @@ ExtScsiPassThruPassThru (
       break;\r
   }\r
 \r
+  //\r
+  // If the cmd doesn't get executed correctly, then check sense data.\r
+  //\r
+  if (EFI_ERROR (Status) && (Packet->SenseDataLength != 0) && (*((UINT8*)Packet->Cdb) != ATA_CMD_REQUEST_SENSE)) {\r
+    PtrSenseData = AllocateAlignedPages (EFI_SIZE_TO_PAGES (sizeof (EFI_SCSI_SENSE_DATA)), This->Mode->IoAlign);\r
+    if (PtrSenseData == NULL) {\r
+      return EFI_DEVICE_ERROR;\r
+    }\r
+\r
+    for (SenseReq = TRUE; SenseReq;) {\r
+      SenseStatus = AtaPacketRequestSense (\r
+                      This,\r
+                      Target,\r
+                      Lun,\r
+                      PtrSenseData,\r
+                      sizeof (EFI_SCSI_SENSE_DATA),\r
+                      Packet->Timeout\r
+                      );\r
+      if (EFI_ERROR (SenseStatus)) {\r
+        break;\r
+      }\r
+\r
+      CopyMem ((UINT8*)Packet->SenseData + SenseDataLen, PtrSenseData, sizeof (EFI_SCSI_SENSE_DATA));\r
+      SenseDataLen += sizeof (EFI_SCSI_SENSE_DATA);\r
+\r
+      //\r
+      // no more sense key or number of sense keys exceeds predefined,\r
+      // skip the loop.\r
+      //\r
+      if ((PtrSenseData->Sense_Key == EFI_SCSI_SK_NO_SENSE) ||\r
+          (SenseDataLen + sizeof (EFI_SCSI_SENSE_DATA) > Packet->SenseDataLength)) {\r
+        SenseReq = FALSE;\r
+      }\r
+    }\r
+    FreeAlignedPages (PtrSenseData, EFI_SIZE_TO_PAGES (sizeof (EFI_SCSI_SENSE_DATA)));\r
+  }\r
+  //\r
+  // Update the SenseDataLength field to the data length received.\r
+  //\r
+  Packet->SenseDataLength = (UINT8)SenseDataLen;\r
   return Status;\r
 }\r
 \r
 /**\r
-  Used to retrieve the list of legal Target IDs and LUNs for SCSI devices on a SCSI channel. These       \r
+  Used to retrieve the list of legal Target IDs and LUNs for SCSI devices on a SCSI channel. These\r
   can either be the list SCSI devices that are actually present on the SCSI channel, or the list of legal\r
-  Target Ids and LUNs for the SCSI channel. Regardless, the caller of this function must probe the       \r
-  Target ID and LUN returned to see if a SCSI device is actually present at that location on the SCSI    \r
+  Target Ids and LUNs for the SCSI channel. Regardless, the caller of this function must probe the\r
+  Target ID and LUN returned to see if a SCSI device is actually present at that location on the SCSI\r
   channel.\r
 \r
   @param  This   A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.\r
@@ -2030,8 +2270,9 @@ ExtScsiPassThruGetNextTargetLun (
       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);\r
 \r
       if ((DeviceInfo->Type == EfiIdeCdrom) &&\r
-         ((Target8[0] < DeviceInfo->Port) || \r
-          (Target8[1] < DeviceInfo->PortMultiplier))) {\r
+         ((Target8[0] < DeviceInfo->Port) ||\r
+          ((Target8[0] == DeviceInfo->Port) &&\r
+           (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) {\r
         Target8[0] = (UINT8)DeviceInfo->Port;\r
         Target8[1] = (UINT8)DeviceInfo->PortMultiplier;\r
         goto Exit;\r
@@ -2069,7 +2310,7 @@ Exit:
   //\r
   Instance->PreviousTargetId = *Target16;\r
   Instance->PreviousLun      = *Lun;\r
-  \r
+\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -2136,7 +2377,7 @@ ExtScsiPassThruBuildDevicePath (
   if (SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom) == NULL) {\r
     return EFI_NOT_FOUND;\r
   }\r
-  \r
+\r
   if (Instance->Mode == EfiAtaIdeMode) {\r
     DevicePathNode = AllocateCopyPool (sizeof (ATAPI_DEVICE_PATH), &mAtapiDevicePathTemplate);\r
     if (DevicePathNode == NULL) {\r
@@ -2153,7 +2394,13 @@ ExtScsiPassThruBuildDevicePath (
     }\r
 \r
     DevicePathNode->Sata.HBAPortNumber            = Port;\r
-    DevicePathNode->Sata.PortMultiplierPortNumber = PortMultiplier;\r
+    //\r
+    // For CD-ROM working in the AHCI mode, only 8 bits are used to record\r
+    // the PortMultiplier information. If the CD-ROM is directly attached\r
+    // on a SATA port, the PortMultiplier should be translated from 0xFF\r
+    // to 0xFFFF according to the UEFI spec.\r
+    //\r
+    DevicePathNode->Sata.PortMultiplierPortNumber = PortMultiplier == 0xFF ? 0xFFFF : PortMultiplier;\r
     DevicePathNode->Sata.Lun                      = (UINT16) Lun;\r
   }\r
 \r
@@ -2261,7 +2508,10 @@ ExtScsiPassThruResetChannel (
   IN  EFI_EXT_SCSI_PASS_THRU_PROTOCOL   *This\r
   )\r
 {\r
-  return EFI_UNSUPPORTED;\r
+  //\r
+  // Return success directly then upper layer driver could think reset channel operation is done.\r
+  //\r
+  return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
@@ -2291,14 +2541,48 @@ ExtScsiPassThruResetTargetLun (
   IN UINT64                             Lun\r
   )\r
 {\r
-  return EFI_UNSUPPORTED;\r
+  ATA_ATAPI_PASS_THRU_INSTANCE    *Instance;\r
+  LIST_ENTRY                      *Node;\r
+  UINT8                           Port;\r
+  UINT8                           PortMultiplier;\r
+\r
+  Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This);\r
+  //\r
+  // For ATAPI device, doesn't support multiple LUN device.\r
+  //\r
+  if (Lun != 0) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  //\r
+  // The layout of Target array:\r
+  //  ________________________________________________________________________\r
+  // |       Byte 0        |       Byte 1        | ... | TARGET_MAX_BYTES - 1 |\r
+  // |_____________________|_____________________|_____|______________________|\r
+  // |                     | The port multiplier |     |                      |\r
+  // |   The port number   |    port number      | N/A |         N/A          |\r
+  // |_____________________|_____________________|_____|______________________|\r
+  //\r
+  // For ATAPI device, 2 bytes is enough to represent the location of SCSI device.\r
+  //\r
+  Port           = Target[0];\r
+  PortMultiplier = Target[1];\r
+\r
+  Node = SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom);\r
+  if (Node == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  //\r
+  // Return success directly then upper layer driver could think reset target LUN operation is done.\r
+  //\r
+  return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
-  Used to retrieve the list of legal Target IDs for SCSI devices on a SCSI channel. These can either     \r
+  Used to retrieve the list of legal Target IDs for SCSI devices on a SCSI channel. These can either\r
   be the list SCSI devices that are actually present on the SCSI channel, or the list of legal Target IDs\r
-  for the SCSI channel. Regardless, the caller of this function must probe the Target ID returned to     \r
-  see if a SCSI device is actually present at that location on the SCSI channel.                         \r
+  for the SCSI channel. Regardless, the caller of this function must probe the Target ID returned to\r
+  see if a SCSI device is actually present at that location on the SCSI channel.\r
 \r
   @param  This   A pointer to the EFI_EXT_SCSI_PASS_THRU_PROTOCOL instance.\r
   @param  Target (TARGET_MAX_BYTES) of a SCSI device present on the SCSI channel.\r
@@ -2368,8 +2652,9 @@ ExtScsiPassThruGetNextTarget (
       DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node);\r
 \r
       if ((DeviceInfo->Type == EfiIdeCdrom) &&\r
-         ((Target8[0] < DeviceInfo->Port) || \r
-          (Target8[1] < DeviceInfo->PortMultiplier))) {\r
+         ((Target8[0] < DeviceInfo->Port) ||\r
+          ((Target8[0] == DeviceInfo->Port) &&\r
+           (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) {\r
         Target8[0] = (UINT8)DeviceInfo->Port;\r
         Target8[1] = (UINT8)DeviceInfo->PortMultiplier;\r
         goto Exit;\r