]> git.proxmox.com Git - mirror_edk2.git/blobdiff - SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgent/SecPeiDebugAgentLib.c
SourceLevelDebugPkg/DebugAgent: Fix various typos
[mirror_edk2.git] / SourceLevelDebugPkg / Library / DebugAgent / SecPeiDebugAgent / SecPeiDebugAgentLib.c
index ea702e654834e48ad7b3bae69ac9a85a984cb610..51e07f70e7bb7ed92da0a36f42f4fcdd2aa825e3 100644 (file)
@@ -1,20 +1,53 @@
 /** @file\r
-  SEC Core Debug Agent Library instance implementition.\r
+  SEC Core Debug Agent Library instance implementation.\r
 \r
-  Copyright (c) 2010 - 2012, 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
-  http://opensource.org/licenses/bsd-license.php.\r
-\r
-  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
-  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+  Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.<BR>\r
+  SPDX-License-Identifier: BSD-2-Clause-Patent\r
 \r
 **/\r
 \r
 #include "SecPeiDebugAgentLib.h"\r
 \r
-CONST BOOLEAN                MultiProcessorDebugSupport = FALSE;\r
+GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN  mSkipBreakpoint = FALSE;\r
+\r
+\r
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_PEI_VECTOR_HANDOFF_INFO_PPI mVectorHandoffInfoPpi = {\r
+  &mVectorHandoffInfoDebugAgent[0]\r
+};\r
+\r
+//\r
+// Ppis to be installed\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_PEI_PPI_DESCRIPTOR           mVectorHandoffInfoPpiList[] = {\r
+  {\r
+    (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),\r
+    &gEfiVectorHandoffInfoPpiGuid,\r
+    &mVectorHandoffInfoPpi\r
+  }\r
+};\r
+\r
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_PEI_NOTIFY_DESCRIPTOR mDebugAgentMemoryDiscoveredNotifyList[1] = {\r
+  {\r
+    (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),\r
+    &gEfiPeiMemoryDiscoveredPpiGuid,\r
+    DebugAgentCallbackMemoryDiscoveredPpi\r
+  }\r
+};\r
+\r
+/**\r
+  Check if debug agent support multi-processor.\r
+\r
+  @retval TRUE    Multi-processor is supported.\r
+  @retval FALSE   Multi-processor is not supported.\r
+\r
+**/\r
+BOOLEAN\r
+MultiProcessorDebugSupport (\r
+  VOID\r
+  )\r
+{\r
+  return FALSE;\r
+}\r
 \r
 /**\r
   Read the Attach/Break-in symbols from the debug port.\r
@@ -32,82 +65,101 @@ DebugReadBreakSymbol (
   OUT UINT8                  *BreakSymbol\r
   )\r
 {\r
+  EFI_STATUS                 Status;\r
+  DEBUG_PACKET_HEADER        DebugHeader;\r
+  UINT8                      *Data8;\r
+\r
   *BreakSymbol = 0;\r
   //\r
-  // If Debug Port buffer has data, read it till it was break symbol or Debug Port buffer emty.\r
+  // If Debug Port buffer has data, read it till it was break symbol or Debug Port buffer empty.\r
   //\r
-  while (DebugPortPollBuffer (Handle)) {\r
-    DebugPortReadBuffer (Handle, BreakSymbol, 1, 0);\r
-    if (*BreakSymbol == DEBUG_STARTING_SYMBOL_ATTACH || *BreakSymbol == DEBUG_STARTING_SYMBOL_BREAK) {\r
+  Data8 = (UINT8 *) &DebugHeader;\r
+  while (TRUE) {\r
+    //\r
+    // If start symbol is not received\r
+    //\r
+    if (!DebugPortPollBuffer (Handle)) {\r
+      //\r
+      // If no data in Debug Port, exit\r
+      //\r
+      break;\r
+    }\r
+    //\r
+    // Try to read the start symbol\r
+    //\r
+    DebugAgentReadBuffer (Handle, Data8, 1, 0);\r
+    if (*Data8 == DEBUG_STARTING_SYMBOL_ATTACH) {\r
+      *BreakSymbol = *Data8;\r
+      DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Debug Timer attach symbol received %x", *BreakSymbol);\r
       return EFI_SUCCESS;\r
     }\r
+    if (*Data8 == DEBUG_STARTING_SYMBOL_NORMAL) {\r
+      Status = ReadRemainingBreakPacket (Handle, &DebugHeader);\r
+      if (Status == EFI_SUCCESS) {\r
+        *BreakSymbol = DebugHeader.Command;\r
+        DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Debug Timer break symbol received %x", *BreakSymbol);\r
+        return EFI_SUCCESS;\r
+      }\r
+      if (Status == EFI_TIMEOUT) {\r
+        break;\r
+      }\r
+    }\r
   }\r
-  \r
+\r
   return EFI_NOT_FOUND;\r
 }\r
 \r
 /**\r
-  Get pointer to Mailbox from IDT entry before memory is ready.\r
+  Get the pointer to location saved Mailbox pointer from IDT entry.\r
 \r
 **/\r
 VOID *\r
-GetMailboxPointerInIdtEntry (\r
+GetLocationSavedMailboxPointerInIdtEntry (\r
   VOID\r
   )\r
 {\r
-  IA32_IDT_GATE_DESCRIPTOR   *IdtEntry;\r
-  IA32_DESCRIPTOR            IdtDescriptor;\r
-  UINTN                      Mailbox;\r
-\r
-  AsmReadIdtr (&IdtDescriptor);\r
-  IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;\r
+  UINTN                     *MailboxLocation;\r
 \r
-  Mailbox = IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow + (IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh << 16);\r
-  return (VOID *) Mailbox;\r
+  MailboxLocation = (UINTN *) GetExceptionHandlerInIdtEntry (DEBUG_MAILBOX_VECTOR);\r
+  //\r
+  // *MailboxLocation is the pointer to Mailbox\r
+  //\r
+  VerifyMailboxChecksum ((DEBUG_AGENT_MAILBOX *) (*MailboxLocation));\r
+  return MailboxLocation;\r
 }\r
 \r
 /**\r
   Set the pointer of Mailbox into IDT entry before memory is ready.\r
 \r
-  @param[in]  Mailbox       The pointer of Mailbox.\r
+  @param[in]  MailboxLocation    Pointer to location saved Mailbox pointer.\r
 \r
 **/\r
 VOID\r
-SetMailboxPointerInIdtEntry (\r
-  IN VOID                    *Mailbox\r
+SetLocationSavedMailboxPointerInIdtEntry (\r
+  IN VOID                  *MailboxLocation\r
   )\r
 {\r
-  IA32_IDT_GATE_DESCRIPTOR   *IdtEntry;\r
-  IA32_DESCRIPTOR            IdtDescriptor;\r
-\r
-  AsmReadIdtr (&IdtDescriptor);\r
-  IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) IdtDescriptor.Base;\r
-\r
-  IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow  = (UINT16)(UINTN)Mailbox;\r
-  IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh = (UINT16)((UINTN)Mailbox >> 16);\r
+  SetExceptionHandlerInIdtEntry (DEBUG_MAILBOX_VECTOR, MailboxLocation);\r
 }\r
 \r
 /**\r
-  Get the pointer to Mailbox from IDT entry and build the Mailbox into GUIDed Hob\r
-  after memory is ready.\r
+  Get the location of Mailbox pointer from the GUIDed HOB.\r
 \r
-  @return Pointer to Mailbox.\r
+  @return Pointer to the location saved Mailbox pointer.\r
 \r
 **/\r
-DEBUG_AGENT_MAILBOX *\r
-BuildMailboxHob (\r
+UINT64 *\r
+GetMailboxLocationFromHob (\r
   VOID\r
   )\r
 {\r
-  DEBUG_AGENT_MAILBOX       *Mailbox;\r
-\r
-  Mailbox = (DEBUG_AGENT_MAILBOX *) GetMailboxPointerInIdtEntry ();\r
+  EFI_HOB_GUID_TYPE        *GuidHob;\r
 \r
-  return BuildGuidDataHob (\r
-           &gEfiDebugAgentGuid,\r
-           Mailbox,\r
-           sizeof (DEBUG_AGENT_MAILBOX)\r
-           );\r
+  GuidHob = GetFirstGuidHob (&gEfiDebugAgentGuid);\r
+  if (GuidHob == NULL) {\r
+    return NULL;\r
+  }\r
+  return (UINT64 *) (GET_GUID_HOB_DATA(GuidHob));\r
 }\r
 \r
 /**\r
@@ -121,7 +173,52 @@ GetMailboxPointer (
   VOID\r
   )\r
 {\r
-  return (DEBUG_AGENT_MAILBOX *) GetMailboxPointerInIdtEntry ();\r
+  UINT64               DebugPortHandle;\r
+  UINT64               *MailboxLocationInIdt;\r
+  UINT64               *MailboxLocationInHob;\r
+  DEBUG_AGENT_MAILBOX  *Mailbox;\r
+\r
+  //\r
+  // Get mailbox from IDT entry firstly\r
+  //\r
+  MailboxLocationInIdt = GetLocationSavedMailboxPointerInIdtEntry ();\r
+  Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocationInIdt);\r
+  //\r
+  // Cannot used GetDebugFlag() to get Debug Flag to avoid GetMailboxPointer() nested\r
+  //\r
+  if (Mailbox->DebugFlag.Bits.CheckMailboxInHob != 1 ||\r
+      Mailbox->DebugFlag.Bits.InitArch != DEBUG_ARCH_SYMBOL) {\r
+    //\r
+    // If mailbox was setup in SEC or the current CPU arch is different from the init arch\r
+    // Debug Agent initialized, return the mailbox from IDT entry directly.\r
+    // Otherwise, we need to check the mailbox location saved in GUIDed HOB further.\r
+    //\r
+    return Mailbox;\r
+  }\r
+\r
+  MailboxLocationInHob = GetMailboxLocationFromHob ();\r
+  //\r
+  // Compare mailbox in IDT entry with mailbox in HOB,\r
+  // need to fix mailbox location if HOB moved by PEI CORE\r
+  //\r
+  if (MailboxLocationInHob != MailboxLocationInIdt && MailboxLocationInHob != NULL) {\r
+    Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocationInHob);\r
+    //\r
+    // Fix up Debug Port handler and save new mailbox in IDT entry\r
+    //\r
+    Mailbox = (DEBUG_AGENT_MAILBOX *)((UINTN)Mailbox + ((UINTN)(MailboxLocationInHob) - (UINTN)MailboxLocationInIdt));\r
+    DebugPortHandle = (UINTN)Mailbox->DebugPortHandle + ((UINTN)(MailboxLocationInHob) - (UINTN)MailboxLocationInIdt);\r
+    UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);\r
+    *MailboxLocationInHob = (UINT64)(UINTN)Mailbox;\r
+    SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationInHob);\r
+    //\r
+    // Clean CheckMailboxInHob flag\r
+    //\r
+    Mailbox->DebugFlag.Bits.CheckMailboxInHob = 0;\r
+    UpdateMailboxChecksum (Mailbox);\r
+  }\r
+\r
+  return Mailbox;\r
 }\r
 \r
 /**\r
@@ -136,50 +233,89 @@ GetDebugPortHandle (
   )\r
 {\r
   DEBUG_AGENT_MAILBOX    *DebugAgentMailbox;\r
-  \r
-  DebugAgentMailbox = (DEBUG_AGENT_MAILBOX *)GetMailboxPointerInIdtEntry ();\r
+\r
+  DebugAgentMailbox = GetMailboxPointer ();\r
 \r
   return (DEBUG_PORT_HANDLE) (UINTN)(DebugAgentMailbox->DebugPortHandle);\r
 }\r
 \r
 /**\r
-  Trigger one software interrupt to debug agent to handle it.\r
+  Debug Agent provided notify callback function on Memory Discovered PPI.\r
+\r
+  @param[in] PeiServices      Indirect reference to the PEI Services Table.\r
+  @param[in] NotifyDescriptor Address of the notification descriptor data structure.\r
+  @param[in] Ppi              Address of the PPI that was installed.\r
 \r
-  @param Signature       Software interrupt signature.\r
+  @retval EFI_SUCCESS If the function completed successfully.\r
 \r
 **/\r
-VOID\r
-TriggerSoftInterrupt (\r
-  UINT32                 Signature\r
+EFI_STATUS\r
+EFIAPI\r
+DebugAgentCallbackMemoryDiscoveredPpi (\r
+  IN EFI_PEI_SERVICES                     **PeiServices,\r
+  IN EFI_PEI_NOTIFY_DESCRIPTOR            *NotifyDescriptor,\r
+  IN VOID                                 *Ppi\r
   )\r
 {\r
-  UINTN                  Dr0;\r
-  UINTN                  Dr1;\r
+  EFI_STATUS                     Status;\r
+  DEBUG_AGENT_MAILBOX            *Mailbox;\r
+  BOOLEAN                        InterruptStatus;\r
+  EFI_PHYSICAL_ADDRESS           Address;\r
+  DEBUG_AGENT_MAILBOX            *NewMailbox;\r
+  UINT64                         *MailboxLocationInHob;\r
 \r
   //\r
-  // Save Debug Register State\r
+  // Save and disable original interrupt status\r
   //\r
-  Dr0 = AsmReadDr0 ();\r
-  Dr1 = AsmReadDr1 ();\r
+  InterruptStatus = SaveAndDisableInterrupts ();\r
 \r
   //\r
-  // DR0 = Signature\r
+  // Allocate ACPI NVS memory for new Mailbox and Debug Port Handle buffer\r
   //\r
-  AsmWriteDr0 (SOFT_INTERRUPT_SIGNATURE);\r
-  AsmWriteDr1 (Signature);\r
-\r
+  Status = PeiServicesAllocatePages (\r
+             EfiACPIMemoryNVS,\r
+             EFI_SIZE_TO_PAGES (sizeof(DEBUG_AGENT_MAILBOX) + PcdGet16(PcdDebugPortHandleBufferSize)),\r
+             &Address\r
+             );\r
+  ASSERT_EFI_ERROR (Status);\r
+  NewMailbox = (DEBUG_AGENT_MAILBOX *) (UINTN) Address;\r
+  //\r
+  // Copy Mailbox and Debug Port Handle buffer to new location in ACPI NVS memory, because original Mailbox\r
+  // and Debug Port Handle buffer in the allocated pool that may be marked as free by DXE Core after DXE Core\r
+  // reallocates the HOB.\r
+  //\r
+  Mailbox = GetMailboxPointer ();\r
+  CopyMem (NewMailbox, Mailbox, sizeof (DEBUG_AGENT_MAILBOX));\r
+  CopyMem (NewMailbox + 1, (VOID *)(UINTN)Mailbox->DebugPortHandle, PcdGet16(PcdDebugPortHandleBufferSize));\r
+  //\r
+  // Update Mailbox Location pointer in GUIDed HOB and IDT entry with new one\r
+  //\r
+  MailboxLocationInHob = GetMailboxLocationFromHob ();\r
+  ASSERT (MailboxLocationInHob != NULL);\r
+  *MailboxLocationInHob = (UINT64)(UINTN)NewMailbox;\r
+  SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationInHob);\r
   //\r
-  // Do INT3 to communicate with HOST side\r
+  // Update Debug Port Handle in new Mailbox\r
   //\r
-  CpuBreakpoint ();\r
+  UpdateMailboxContent (NewMailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, (UINT64)(UINTN)(NewMailbox + 1));\r
+  //\r
+  // Set physical memory ready flag\r
+  //\r
+  SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);\r
+\r
+  if (IsHostAttached ()) {\r
+    //\r
+    // Trigger one software interrupt to inform HOST\r
+    //\r
+    TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);\r
+  }\r
 \r
   //\r
-  // Restore Debug Register State only when Host didn't change it inside exception handler.\r
-  //   Dr registers can only be changed by setting the HW breakpoint.\r
+  // Restore interrupt state.\r
   //\r
-  AsmWriteDr0 (Dr0);\r
-  AsmWriteDr1 (Dr1);\r
+  SetInterruptState (InterruptStatus);\r
 \r
+  return EFI_SUCCESS;\r
 }\r
 \r
 /**\r
@@ -187,7 +323,7 @@ TriggerSoftInterrupt (
 \r
   This function is used to set up debug environment for SEC and PEI phase.\r
 \r
-  If InitFlag is DEBUG_AGENT_INIT_PREMEM_SEC, it will overirde IDT table entries\r
+  If InitFlag is DEBUG_AGENT_INIT_PREMEM_SEC, it will override IDT table entries\r
   and initialize debug port. It will enable interrupt to support break-in feature.\r
   It will set up debug agent Mailbox in cache-as-ramfrom. It will be called before\r
   physical memory is ready.\r
@@ -201,7 +337,7 @@ TriggerSoftInterrupt (
   function and pass it into InitializeDebugAgent(). InitializeDebugAgent() is\r
   responsible to invoke the passing-in function at the end of InitializeDebugAgent().\r
 \r
-  If the parameter Function is not NULL, Debug Agent Libary instance will invoke it by\r
+  If the parameter Function is not NULL, Debug Agent Library instance will invoke it by\r
   passing in the Context to be its parameter.\r
 \r
   If Function() is NULL, Debug Agent Library instance will return after setup debug\r
@@ -222,11 +358,24 @@ InitializeDebugAgent (
   )\r
 {\r
   DEBUG_AGENT_MAILBOX              *Mailbox;\r
+  DEBUG_AGENT_MAILBOX              *NewMailbox;\r
   DEBUG_AGENT_MAILBOX              MailboxInStack;\r
   DEBUG_AGENT_PHASE2_CONTEXT       Phase2Context;\r
   DEBUG_AGENT_CONTEXT_POSTMEM_SEC  *DebugAgentContext;\r
+  EFI_STATUS                       Status;\r
+  IA32_DESCRIPTOR                  *Ia32Idtr;\r
+  IA32_IDT_ENTRY                   *Ia32IdtEntry;\r
+  UINT64                           DebugPortHandle;\r
+  UINT64                           MailboxLocation;\r
+  UINT64                           *MailboxLocationPointer;\r
+  EFI_PHYSICAL_ADDRESS             Address;\r
+  UINT32                           DebugTimerFrequency;\r
+  BOOLEAN                          CpuInterruptState;\r
 \r
-  DisableInterrupts ();\r
+  //\r
+  // Disable interrupts and save current interrupt state\r
+  //\r
+  CpuInterruptState = SaveAndDisableInterrupts();\r
 \r
   switch (InitFlag) {\r
 \r
@@ -234,20 +383,31 @@ InitializeDebugAgent (
 \r
     InitializeDebugIdt ();\r
 \r
+    MailboxLocation = (UINT64)(UINTN)&MailboxInStack;\r
     Mailbox = &MailboxInStack;\r
     ZeroMem ((VOID *) Mailbox, sizeof (DEBUG_AGENT_MAILBOX));\r
-\r
     //\r
     // Get and save debug port handle and set the length of memory block.\r
     //\r
-    SetMailboxPointerInIdtEntry ((VOID *) Mailbox);\r
-\r
-    InitializeDebugTimer ();\r
+    SetLocationSavedMailboxPointerInIdtEntry (&MailboxLocation);\r
+    //\r
+    // Force error message could be printed during the first shakehand between Target/HOST.\r
+    //\r
+    SetDebugFlag (DEBUG_AGENT_FLAG_PRINT_ERROR_LEVEL, DEBUG_AGENT_ERROR);\r
+    //\r
+    // Save init arch type when debug agent initialized\r
+    //\r
+    SetDebugFlag (DEBUG_AGENT_FLAG_INIT_ARCH, DEBUG_ARCH_SYMBOL);\r
+    //\r
+    // Initialize Debug Timer hardware and save its frequency\r
+    //\r
+    InitializeDebugTimer (&DebugTimerFrequency, TRUE);\r
+    UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_TIMER_FREQUENCY, DebugTimerFrequency);\r
 \r
+    Phase2Context.InitFlag = InitFlag;\r
     Phase2Context.Context  = Context;\r
     Phase2Context.Function = Function;\r
     DebugPortInitialize ((VOID *) &Phase2Context, InitializeDebugAgentPhase2);\r
-\r
     //\r
     // If reaches here, it means Debug Port initialization failed.\r
     //\r
@@ -256,59 +416,236 @@ InitializeDebugAgent (
     break;\r
 \r
   case DEBUG_AGENT_INIT_POSTMEM_SEC:\r
-\r
+    Mailbox = GetMailboxPointer ();\r
     //\r
     // Memory has been ready\r
     //\r
-    if (IsHostAttached()) {\r
+    SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);\r
+    if (IsHostAttached ()) {\r
       //\r
       // Trigger one software interrupt to inform HOST\r
       //\r
       TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);\r
     }\r
-\r
+    //\r
+    // Install Vector Handoff Info PPI to persist vectors used by Debug Agent\r
+    //\r
+    Status = PeiServicesInstallPpi (&mVectorHandoffInfoPpiList[0]);\r
+    if (EFI_ERROR (Status)) {\r
+      DEBUG ((EFI_D_ERROR, "DebugAgent: Failed to install Vector Handoff Info PPI!\n"));\r
+      CpuDeadLoop ();\r
+    }\r
+    //\r
+    // Fix up Debug Port handle address and mailbox address\r
+    //\r
     DebugAgentContext = (DEBUG_AGENT_CONTEXT_POSTMEM_SEC *) Context;\r
+    if (DebugAgentContext != NULL) {\r
+      DebugPortHandle = (UINT64)(UINT32)(Mailbox->DebugPortHandle + DebugAgentContext->StackMigrateOffset);\r
+      UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);\r
+      Mailbox = (DEBUG_AGENT_MAILBOX *) ((UINTN) Mailbox + DebugAgentContext->StackMigrateOffset);\r
+      MailboxLocation = (UINT64)(UINTN)Mailbox;\r
+      //\r
+      // Build mailbox location in HOB and fix-up its address\r
+      //\r
+      MailboxLocationPointer = BuildGuidDataHob (\r
+                                 &gEfiDebugAgentGuid,\r
+                                 &MailboxLocation,\r
+                                 sizeof (UINT64)\r
+                                 );\r
+      MailboxLocationPointer = (UINT64 *) ((UINTN) MailboxLocationPointer + DebugAgentContext->HeapMigrateOffset);\r
+    } else {\r
+      //\r
+      // DebugAgentContext is NULL. Then, Mailbox can directly be copied into memory.\r
+      // Allocate ACPI NVS memory for new Mailbox and Debug Port Handle buffer\r
+      //\r
+      Status = PeiServicesAllocatePages (\r
+                 EfiACPIMemoryNVS,\r
+                 EFI_SIZE_TO_PAGES (sizeof(DEBUG_AGENT_MAILBOX) + PcdGet16(PcdDebugPortHandleBufferSize)),\r
+                 &Address\r
+                 );\r
+      if (EFI_ERROR (Status)) {\r
+        DEBUG ((EFI_D_ERROR, "DebugAgent: Failed to allocate pages!\n"));\r
+        CpuDeadLoop ();\r
+      }\r
+      NewMailbox = (DEBUG_AGENT_MAILBOX *) (UINTN) Address;\r
+      //\r
+      // Copy Mailbox and Debug Port Handle buffer to new location in ACPI NVS memory, because original Mailbox\r
+      // and Debug Port Handle buffer in the allocated pool that may be marked as free by DXE Core after DXE Core\r
+      // reallocates the HOB.\r
+      //\r
+      CopyMem (NewMailbox, Mailbox, sizeof (DEBUG_AGENT_MAILBOX));\r
+      CopyMem (NewMailbox + 1, (VOID *)(UINTN)Mailbox->DebugPortHandle, PcdGet16(PcdDebugPortHandleBufferSize));\r
+      UpdateMailboxContent (NewMailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, (UINT64)(UINTN)(NewMailbox + 1));\r
+      MailboxLocation = (UINT64)(UINTN)NewMailbox;\r
+      //\r
+      // Build mailbox location in HOB\r
+      //\r
+      MailboxLocationPointer = BuildGuidDataHob (\r
+                                 &gEfiDebugAgentGuid,\r
+                                 &MailboxLocation,\r
+                                 sizeof (UINT64)\r
+                                 );\r
+    }\r
+    //\r
+    // Update IDT entry to save the location saved mailbox pointer\r
+    //\r
+    SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationPointer);\r
+    break;\r
+\r
+  case DEBUG_AGENT_INIT_PEI:\r
+    if (Context == NULL) {\r
+      DEBUG ((EFI_D_ERROR, "DebugAgent: Input parameter Context cannot be NULL!\n"));\r
+      CpuDeadLoop ();\r
+    }\r
+    //\r
+    // Check if Debug Agent has initialized before\r
+    //\r
+    if (IsDebugAgentInitialzed()) {\r
+      DEBUG ((EFI_D_WARN, "Debug Agent: It has already initialized in SEC Core!\n"));\r
+      break;\r
+    }\r
+    //\r
+    // Install Vector Handoff Info PPI to persist vectors used by Debug Agent\r
+    //\r
+    Status = PeiServicesInstallPpi (&mVectorHandoffInfoPpiList[0]);\r
+    if (EFI_ERROR (Status)) {\r
+      DEBUG ((EFI_D_ERROR, "DebugAgent: Failed to install Vector Handoff Info PPI!\n"));\r
+      CpuDeadLoop ();\r
+    }\r
+    //\r
+    // Set up IDT entries\r
+    //\r
+    InitializeDebugIdt ();\r
+    //\r
+    // Build mailbox in HOB and setup Mailbox Set In Pei flag\r
+    //\r
+    Mailbox = AllocateZeroPool (sizeof (DEBUG_AGENT_MAILBOX));\r
+    if (Mailbox == NULL) {\r
+      DEBUG ((EFI_D_ERROR, "DebugAgent: Failed to allocate memory!\n"));\r
+      CpuDeadLoop ();\r
+    } else {\r
+      MailboxLocation = (UINT64)(UINTN)Mailbox;\r
+      MailboxLocationPointer = BuildGuidDataHob (\r
+                                 &gEfiDebugAgentGuid,\r
+                                 &MailboxLocation,\r
+                                 sizeof (UINT64)\r
+                                 );\r
+      //\r
+      // Initialize Debug Timer hardware and save its frequency\r
+      //\r
+      InitializeDebugTimer (&DebugTimerFrequency, TRUE);\r
+      UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_TIMER_FREQUENCY, DebugTimerFrequency);\r
+      //\r
+      // Update IDT entry to save the location pointer saved mailbox pointer\r
+      //\r
+      SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationPointer);\r
+    }\r
+    //\r
+    // Save init arch type when debug agent initialized\r
+    //\r
+    SetDebugFlag (DEBUG_AGENT_FLAG_INIT_ARCH, DEBUG_ARCH_SYMBOL);\r
+    //\r
+    // Register for a callback once memory has been initialized.\r
+    // If memory has been ready, the callback function will be invoked immediately\r
+    //\r
+    Status = PeiServicesNotifyPpi (&mDebugAgentMemoryDiscoveredNotifyList[0]);\r
+    if (EFI_ERROR (Status)) {\r
+      DEBUG ((EFI_D_ERROR, "DebugAgent: Failed to register memory discovered callback function!\n"));\r
+      CpuDeadLoop ();\r
+    }\r
+    //\r
+    // Set HOB check flag if memory has not been ready yet\r
+    //\r
+    if (GetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY) == 0) {\r
+      SetDebugFlag (DEBUG_AGENT_FLAG_CHECK_MAILBOX_IN_HOB, 1);\r
+    }\r
 \r
-    Mailbox = (DEBUG_AGENT_MAILBOX *) GetMailboxPointerInIdtEntry ();\r
-    Mailbox->DebugPortHandle = (UINT64)(UINT32)(Mailbox->DebugPortHandle + DebugAgentContext->StackMigrateOffset);\r
-    Mailbox->DebugFlag.MemoryReady = 1;\r
+    Phase2Context.InitFlag = InitFlag;\r
+    Phase2Context.Context  = Context;\r
+    Phase2Context.Function = Function;\r
+    DebugPortInitialize ((VOID *) &Phase2Context, InitializeDebugAgentPhase2);\r
 \r
-    Mailbox = BuildMailboxHob ();\r
-    Mailbox = (DEBUG_AGENT_MAILBOX *) ((UINTN) Mailbox + DebugAgentContext->HeapMigrateOffset);\r
+    FindAndReportModuleImageInfo (4);\r
 \r
-    SetMailboxPointerInIdtEntry ((VOID *) Mailbox);\r
+    break;\r
 \r
-    EnableInterrupts ();\r
+  case DEBUG_AGENT_INIT_THUNK_PEI_IA32TOX64:\r
+    if (Context == NULL) {\r
+      DEBUG ((EFI_D_ERROR, "DebugAgent: Input parameter Context cannot be NULL!\n"));\r
+      CpuDeadLoop ();\r
+    } else {\r
+      Ia32Idtr =  (IA32_DESCRIPTOR *) Context;\r
+      Ia32IdtEntry = (IA32_IDT_ENTRY *)(Ia32Idtr->Base);\r
+      MailboxLocationPointer = (UINT64 *) ((UINTN) Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetLow +\r
+                                          ((UINTN) Ia32IdtEntry[DEBUG_MAILBOX_VECTOR].Bits.OffsetHigh << 16));\r
+      Mailbox = (DEBUG_AGENT_MAILBOX *) (UINTN)(*MailboxLocationPointer);\r
+      //\r
+      // Mailbox should valid and setup before executing thunk code\r
+      //\r
+      VerifyMailboxChecksum (Mailbox);\r
 \r
+      DebugPortHandle = (UINT64) (UINTN)DebugPortInitialize ((VOID *)(UINTN)Mailbox->DebugPortHandle, NULL);\r
+      UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, DebugPortHandle);\r
+      //\r
+      // Set up IDT entries\r
+      //\r
+      InitializeDebugIdt ();\r
+      //\r
+      // Update IDT entry to save location pointer saved the mailbox pointer\r
+      //\r
+      SetLocationSavedMailboxPointerInIdtEntry (MailboxLocationPointer);\r
+\r
+      FindAndReportModuleImageInfo (4);\r
+    }\r
     break;\r
 \r
   default:\r
-\r
     //\r
-    // Only DEBUG_AGENT_INIT_PREMEM_SEC and DEBUG_AGENT_INIT_POSTMEM_SEC are allowed for this \r
+    // Only DEBUG_AGENT_INIT_PREMEM_SEC and DEBUG_AGENT_INIT_POSTMEM_SEC are allowed for this\r
     // Debug Agent library instance.\r
     //\r
     DEBUG ((EFI_D_ERROR, "Debug Agent: The InitFlag value is not allowed!\n"));\r
     CpuDeadLoop ();\r
     break;\r
-\r
   }\r
 \r
+  if (InitFlag == DEBUG_AGENT_INIT_POSTMEM_SEC) {\r
+    //\r
+    // Restore CPU Interrupt state and keep debug timer interrupt state as is\r
+    // in DEBUG_AGENT_INIT_POSTMEM_SEC case\r
+    //\r
+    SetInterruptState (CpuInterruptState);\r
+  } else {\r
+    //\r
+    // Enable Debug Timer interrupt\r
+    //\r
+    SaveAndSetDebugTimerInterrupt (TRUE);\r
+    //\r
+    // Enable CPU interrupts so debug timer interrupts can be delivered\r
+    //\r
+    EnableInterrupts ();\r
+  }\r
   //\r
-  // If Function is not NULL, invoke it always whatever debug agent was initialized sucesssfully or not.\r
+  // If Function is not NULL, invoke it always whatever debug agent was initialized successfully or not.\r
   //\r
   if (Function != NULL) {\r
     Function (Context);\r
   }\r
+  //\r
+  // Set return status for DEBUG_AGENT_INIT_PEI\r
+  //\r
+  if (InitFlag == DEBUG_AGENT_INIT_PEI && Context != NULL) {\r
+    *(EFI_STATUS *)Context = EFI_SUCCESS;\r
+  }\r
 }\r
 \r
 /**\r
   Caller provided function to be invoked at the end of DebugPortInitialize().\r
 \r
-  Refer to the descrption for DebugPortInitialize() for more details.\r
+  Refer to the description for DebugPortInitialize() for more details.\r
 \r
   @param[in] Context           The first input argument of DebugPortInitialize().\r
-  @param[in] DebugPortHandle   Debug port handle created by Debug Communication Libary.\r
+  @param[in] DebugPortHandle   Debug port handle created by Debug Communication Library.\r
 \r
 **/\r
 VOID\r
@@ -319,36 +656,49 @@ InitializeDebugAgentPhase2 (
   )\r
 {\r
   DEBUG_AGENT_PHASE2_CONTEXT *Phase2Context;\r
+  UINT64                     *MailboxLocation;\r
   DEBUG_AGENT_MAILBOX        *Mailbox;\r
   EFI_SEC_PEI_HAND_OFF       *SecCoreData;\r
+  UINT16                     BufferSize;\r
+  UINT64                     NewDebugPortHandle;\r
 \r
-  Mailbox = GetMailboxPointerInIdtEntry ();\r
-  Mailbox->DebugPortHandle = (UINT64) (UINTN)DebugPortHandle;\r
-\r
-  //\r
-  // Trigger one software interrupt to inform HOST\r
-  //\r
-  TriggerSoftInterrupt (SYSTEM_RESET_SIGNATURE);\r
-\r
-  //\r
-  // If Temporary RAM region is below 128 MB, then send message to \r
-  // host to disable low memory filtering.\r
-  //\r
   Phase2Context = (DEBUG_AGENT_PHASE2_CONTEXT *) Context;\r
-  SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Phase2Context->Context;\r
-  if ((UINTN)SecCoreData->TemporaryRamBase < BASE_128MB && IsHostAttached ()) {\r
-    TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);\r
+  MailboxLocation = GetLocationSavedMailboxPointerInIdtEntry ();\r
+  Mailbox = (DEBUG_AGENT_MAILBOX *)(UINTN)(*MailboxLocation);\r
+  BufferSize = PcdGet16(PcdDebugPortHandleBufferSize);\r
+  if (Phase2Context->InitFlag == DEBUG_AGENT_INIT_PEI && BufferSize != 0) {\r
+    NewDebugPortHandle = (UINT64)(UINTN)AllocateCopyPool (BufferSize, DebugPortHandle);\r
+  } else {\r
+    NewDebugPortHandle = (UINT64)(UINTN)DebugPortHandle;\r
   }\r
+  UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_DEBUG_PORT_HANDLE_INDEX, NewDebugPortHandle);\r
 \r
   //\r
-  // Enable CPU interrupts so debug timer interrupts can be delivered\r
+  // Trigger one software interrupt to inform HOST\r
   //\r
-  EnableInterrupts ();\r
+  TriggerSoftInterrupt (SYSTEM_RESET_SIGNATURE);\r
 \r
-  //\r
-  // Call continuation function if it is not NULL.\r
-  //\r
-  if (Phase2Context->Function != NULL) {\r
+  if (Phase2Context->InitFlag == DEBUG_AGENT_INIT_PREMEM_SEC) {\r
+    //\r
+    // If Temporary RAM region is below 128 MB, then send message to\r
+    // host to disable low memory filtering.\r
+    //\r
+    SecCoreData = (EFI_SEC_PEI_HAND_OFF *)Phase2Context->Context;\r
+    if ((UINTN)SecCoreData->TemporaryRamBase < BASE_128MB && IsHostAttached ()) {\r
+      SetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY, 1);\r
+      TriggerSoftInterrupt (MEMORY_READY_SIGNATURE);\r
+    }\r
+    //\r
+    // Enable Debug Timer interrupt\r
+    //\r
+    SaveAndSetDebugTimerInterrupt (TRUE);\r
+    //\r
+    // Enable CPU interrupts so debug timer interrupts can be delivered\r
+    //\r
+    EnableInterrupts ();\r
+    //\r
+    // Call continuation function if it is not NULL.\r
+    //\r
     Phase2Context->Function (Phase2Context->Context);\r
   }\r
 }\r