]> git.proxmox.com Git - mirror_edk2.git/blobdiff - UefiCpuPkg/Library/MpInitLib/MpLib.c
UefiCpuPkg: Change complex DEBUG_CODE() to DEBUG_CODE_BEGIN/END()
[mirror_edk2.git] / UefiCpuPkg / Library / MpInitLib / MpLib.c
index 64a4c3546e22f254b463a2b4ee279b6e118aba64..b390c558d4bd51f158e4a5ade038be42223af10c 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   CPU MP Initialize Library common functions.\r
 \r
-  Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.<BR>\r
+  Copyright (c) 2016 - 2021, Intel Corporation. All rights reserved.<BR>\r
   Copyright (c) 2020, AMD Inc. All rights reserved.<BR>\r
 \r
   SPDX-License-Identifier: BSD-2-Clause-Patent\r
@@ -9,33 +9,13 @@
 **/\r
 \r
 #include "MpLib.h"\r
+#include <Library/VmgExitLib.h>\r
+#include <Register/Amd/Fam17Msr.h>\r
+#include <Register/Amd/Ghcb.h>\r
 \r
 EFI_GUID mCpuInitMpLibHobGuid = CPU_INIT_MP_LIB_HOB_GUID;\r
 \r
 \r
-/**\r
-  Determine if the standard CPU signature is "AuthenticAMD".\r
-\r
-  @retval TRUE  The CPU signature matches.\r
-  @retval FALSE The CPU signature does not match.\r
-\r
-**/\r
-STATIC\r
-BOOLEAN\r
-StandardSignatureIsAuthenticAMD (\r
-  VOID\r
-  )\r
-{\r
-  UINT32  RegEbx;\r
-  UINT32  RegEcx;\r
-  UINT32  RegEdx;\r
-\r
-  AsmCpuid (CPUID_SIGNATURE, NULL, &RegEbx, &RegEcx, &RegEdx);\r
-  return (RegEbx == CPUID_SIGNATURE_AUTHENTIC_AMD_EBX &&\r
-          RegEcx == CPUID_SIGNATURE_AUTHENTIC_AMD_ECX &&\r
-          RegEdx == CPUID_SIGNATURE_AUTHENTIC_AMD_EDX);\r
-}\r
-\r
 /**\r
   The function will check if BSP Execute Disable is enabled.\r
 \r
@@ -314,6 +294,14 @@ GetApLoopMode (
       //\r
       ApLoopMode = ApInHltLoop;\r
     }\r
+\r
+    if (PcdGetBool (PcdSevEsIsEnabled)) {\r
+      //\r
+      // For SEV-ES, force AP in Hlt-loop mode in order to use the GHCB\r
+      // protocol for starting APs\r
+      //\r
+      ApLoopMode = ApInHltLoop;\r
+    }\r
   }\r
 \r
   if (ApLoopMode != ApInMwaitLoop) {\r
@@ -497,14 +485,12 @@ CollectProcessorCount (
   CpuMpData->InitFlag = ApInitConfig;\r
   WakeUpAP (CpuMpData, TRUE, 0, NULL, NULL, TRUE);\r
   CpuMpData->InitFlag = ApInitDone;\r
-  ASSERT (CpuMpData->CpuCount <= PcdGet32 (PcdCpuMaxLogicalProcessorNumber));\r
   //\r
-  // Wait for all APs finished the initialization\r
+  // When InitFlag == ApInitConfig, WakeUpAP () guarantees all APs are checked in.\r
+  // FinishedCount is the number of check-in APs.\r
   //\r
-  while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) {\r
-    CpuPause ();\r
-  }\r
-\r
+  CpuMpData->CpuCount = CpuMpData->FinishedCount + 1;\r
+  ASSERT (CpuMpData->CpuCount <= PcdGet32 (PcdCpuMaxLogicalProcessorNumber));\r
 \r
   //\r
   // Enable x2APIC mode if\r
@@ -610,6 +596,117 @@ InitializeApData (
   SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateIdle);\r
 }\r
 \r
+/**\r
+  Get Protected mode code segment with 16-bit default addressing\r
+  from current GDT table.\r
+\r
+  @return  Protected mode 16-bit code segment value.\r
+**/\r
+STATIC\r
+UINT16\r
+GetProtectedMode16CS (\r
+  VOID\r
+  )\r
+{\r
+  IA32_DESCRIPTOR          GdtrDesc;\r
+  IA32_SEGMENT_DESCRIPTOR  *GdtEntry;\r
+  UINTN                    GdtEntryCount;\r
+  UINT16                   Index;\r
+\r
+  Index = (UINT16) -1;\r
+  AsmReadGdtr (&GdtrDesc);\r
+  GdtEntryCount = (GdtrDesc.Limit + 1) / sizeof (IA32_SEGMENT_DESCRIPTOR);\r
+  GdtEntry = (IA32_SEGMENT_DESCRIPTOR *) GdtrDesc.Base;\r
+  for (Index = 0; Index < GdtEntryCount; Index++) {\r
+    if (GdtEntry->Bits.L == 0 &&\r
+        GdtEntry->Bits.DB == 0 &&\r
+        GdtEntry->Bits.Type > 8) {\r
+      break;\r
+    }\r
+    GdtEntry++;\r
+  }\r
+  ASSERT (Index != GdtEntryCount);\r
+  return Index * 8;\r
+}\r
+\r
+/**\r
+  Get Protected mode code segment with 32-bit default addressing\r
+  from current GDT table.\r
+\r
+  @return  Protected mode 32-bit code segment value.\r
+**/\r
+STATIC\r
+UINT16\r
+GetProtectedMode32CS (\r
+  VOID\r
+  )\r
+{\r
+  IA32_DESCRIPTOR          GdtrDesc;\r
+  IA32_SEGMENT_DESCRIPTOR  *GdtEntry;\r
+  UINTN                    GdtEntryCount;\r
+  UINT16                   Index;\r
+\r
+  Index = (UINT16) -1;\r
+  AsmReadGdtr (&GdtrDesc);\r
+  GdtEntryCount = (GdtrDesc.Limit + 1) / sizeof (IA32_SEGMENT_DESCRIPTOR);\r
+  GdtEntry = (IA32_SEGMENT_DESCRIPTOR *) GdtrDesc.Base;\r
+  for (Index = 0; Index < GdtEntryCount; Index++) {\r
+    if (GdtEntry->Bits.L == 0 &&\r
+        GdtEntry->Bits.DB == 1 &&\r
+        GdtEntry->Bits.Type > 8) {\r
+      break;\r
+    }\r
+    GdtEntry++;\r
+  }\r
+  ASSERT (Index != GdtEntryCount);\r
+  return Index * 8;\r
+}\r
+\r
+/**\r
+  Reset an AP when in SEV-ES mode.\r
+\r
+  If successful, this function never returns.\r
+\r
+  @param[in] Ghcb                 Pointer to the GHCB\r
+  @param[in] CpuMpData            Pointer to CPU MP Data\r
+\r
+**/\r
+STATIC\r
+VOID\r
+MpInitLibSevEsAPReset (\r
+  IN GHCB                         *Ghcb,\r
+  IN CPU_MP_DATA                  *CpuMpData\r
+  )\r
+{\r
+  EFI_STATUS       Status;\r
+  UINTN            ProcessorNumber;\r
+  UINT16           Code16, Code32;\r
+  AP_RESET         *APResetFn;\r
+  UINTN            BufferStart;\r
+  UINTN            StackStart;\r
+\r
+  Status = GetProcessorNumber (CpuMpData, &ProcessorNumber);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  Code16 = GetProtectedMode16CS ();\r
+  Code32 = GetProtectedMode32CS ();\r
+\r
+  if (CpuMpData->WakeupBufferHigh != 0) {\r
+    APResetFn = (AP_RESET *) (CpuMpData->WakeupBufferHigh + CpuMpData->AddressMap.SwitchToRealNoNxOffset);\r
+  } else {\r
+    APResetFn = (AP_RESET *) (CpuMpData->MpCpuExchangeInfo->BufferStart + CpuMpData->AddressMap.SwitchToRealOffset);\r
+  }\r
+\r
+  BufferStart = CpuMpData->MpCpuExchangeInfo->BufferStart;\r
+  StackStart = CpuMpData->SevEsAPResetStackStart -\r
+                 (AP_RESET_STACK_SIZE * ProcessorNumber);\r
+\r
+  //\r
+  // This call never returns.\r
+  //\r
+  APResetFn (BufferStart, Code16, Code32, StackStart);\r
+}\r
+\r
 /**\r
   This function will be called from AP reset code if BSP uses WakeUpAP.\r
 \r
@@ -652,10 +749,6 @@ ApWakeupFunction (
   CurrentApicMode = GetApicMode ();\r
   while (TRUE) {\r
     if (CpuMpData->InitFlag == ApInitConfig) {\r
-      //\r
-      // Add CPU number\r
-      //\r
-      InterlockedIncrement ((UINT32 *) &CpuMpData->CpuCount);\r
       ProcessorNumber = ApIndex;\r
       //\r
       // This is first time AP wakeup, get BIST information from AP stack\r
@@ -670,8 +763,6 @@ ApWakeupFunction (
       RestoreVolatileRegisters (&CpuMpData->CpuData[0].VolatileRegisters, FALSE);\r
       InitializeApData (CpuMpData, ProcessorNumber, BistData, ApTopOfStack);\r
       ApStartupSignalBuffer = CpuMpData->CpuData[ProcessorNumber].StartupApSignal;\r
-\r
-      InterlockedDecrement ((UINT32 *) &CpuMpData->MpCpuExchangeInfo->NumApsExecuting);\r
     } else {\r
       //\r
       // Execute AP function if AP is ready\r
@@ -686,18 +777,31 @@ ApWakeupFunction (
         WAKEUP_AP_SIGNAL,\r
         0\r
         );\r
-      if (CpuMpData->ApLoopMode == ApInHltLoop) {\r
-        //\r
-        // Restore AP's volatile registers saved\r
-        //\r
-        RestoreVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters, TRUE);\r
-      } else {\r
+\r
+      if (CpuMpData->InitFlag == ApInitReconfig) {\r
         //\r
-        // The CPU driver might not flush TLB for APs on spot after updating\r
-        // page attributes. AP in mwait loop mode needs to take care of it when\r
-        // woken up.\r
+        // ApInitReconfig happens when:\r
+        // 1. AP is re-enabled after it's disabled, in either PEI or DXE phase.\r
+        // 2. AP is initialized in DXE phase.\r
+        // In either case, use the volatile registers value derived from BSP.\r
+        // NOTE: IDTR.BASE stored in CpuMpData->CpuData[0].VolatileRegisters points to a\r
+        //   different IDT shared by all APs.\r
         //\r
-        CpuFlushTlb ();\r
+        RestoreVolatileRegisters (&CpuMpData->CpuData[0].VolatileRegisters, FALSE);\r
+      }  else {\r
+        if (CpuMpData->ApLoopMode == ApInHltLoop) {\r
+          //\r
+          // Restore AP's volatile registers saved before AP is halted\r
+          //\r
+          RestoreVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters, TRUE);\r
+        } else {\r
+          //\r
+          // The CPU driver might not flush TLB for APs on spot after updating\r
+          // page attributes. AP in mwait loop mode needs to take care of it when\r
+          // woken up.\r
+          //\r
+          CpuFlushTlb ();\r
+        }\r
       }\r
 \r
       if (GetApState (&CpuMpData->CpuData[ProcessorNumber]) == CpuStateReady) {\r
@@ -747,25 +851,83 @@ ApWakeupFunction (
       }\r
     }\r
 \r
+    if (CpuMpData->ApLoopMode == ApInHltLoop) {\r
+      //\r
+      // Save AP volatile registers\r
+      //\r
+      SaveVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters);\r
+    }\r
+\r
     //\r
     // AP finished executing C code\r
     //\r
     InterlockedIncrement ((UINT32 *) &CpuMpData->FinishedCount);\r
 \r
+    if (CpuMpData->InitFlag == ApInitConfig) {\r
+      //\r
+      // Delay decrementing the APs executing count when SEV-ES is enabled\r
+      // to allow the APs to issue an AP_RESET_HOLD before the BSP possibly\r
+      // performs another INIT-SIPI-SIPI sequence.\r
+      //\r
+      if (!CpuMpData->SevEsIsEnabled) {\r
+        InterlockedDecrement ((UINT32 *) &CpuMpData->MpCpuExchangeInfo->NumApsExecuting);\r
+      }\r
+    }\r
+\r
     //\r
     // Place AP is specified loop mode\r
     //\r
     if (CpuMpData->ApLoopMode == ApInHltLoop) {\r
-      //\r
-      // Save AP volatile registers\r
-      //\r
-      SaveVolatileRegisters (&CpuMpData->CpuData[ProcessorNumber].VolatileRegisters);\r
       //\r
       // Place AP in HLT-loop\r
       //\r
       while (TRUE) {\r
         DisableInterrupts ();\r
-        CpuSleep ();\r
+        if (CpuMpData->SevEsIsEnabled) {\r
+          MSR_SEV_ES_GHCB_REGISTER  Msr;\r
+          GHCB                      *Ghcb;\r
+          UINT64                    Status;\r
+          BOOLEAN                   DoDecrement;\r
+          BOOLEAN                   InterruptState;\r
+\r
+          DoDecrement = (BOOLEAN) (CpuMpData->InitFlag == ApInitConfig);\r
+\r
+          while (TRUE) {\r
+            Msr.GhcbPhysicalAddress = AsmReadMsr64 (MSR_SEV_ES_GHCB);\r
+            Ghcb = Msr.Ghcb;\r
+\r
+            VmgInit (Ghcb, &InterruptState);\r
+\r
+            if (DoDecrement) {\r
+              DoDecrement = FALSE;\r
+\r
+              //\r
+              // Perform the delayed decrement just before issuing the first\r
+              // VMGEXIT with AP_RESET_HOLD.\r
+              //\r
+              InterlockedDecrement ((UINT32 *) &CpuMpData->MpCpuExchangeInfo->NumApsExecuting);\r
+            }\r
+\r
+            Status = VmgExit (Ghcb, SVM_EXIT_AP_RESET_HOLD, 0, 0);\r
+            if ((Status == 0) && (Ghcb->SaveArea.SwExitInfo2 != 0)) {\r
+              VmgDone (Ghcb, InterruptState);\r
+              break;\r
+            }\r
+\r
+            VmgDone (Ghcb, InterruptState);\r
+          }\r
+\r
+          //\r
+          // Awakened in a new phase? Use the new CpuMpData\r
+          //\r
+          if (CpuMpData->NewCpuMpData != NULL) {\r
+            CpuMpData = CpuMpData->NewCpuMpData;\r
+          }\r
+\r
+          MpInitLibSevEsAPReset (Ghcb, CpuMpData);\r
+        } else {\r
+          CpuSleep ();\r
+        }\r
         CpuPause ();\r
       }\r
     }\r
@@ -844,7 +1006,6 @@ FillExchangeInfoData (
   IA32_CR4                         Cr4;\r
 \r
   ExchangeInfo                  = CpuMpData->MpCpuExchangeInfo;\r
-  ExchangeInfo->Lock            = 0;\r
   ExchangeInfo->StackStart      = CpuMpData->Buffer;\r
   ExchangeInfo->StackSize       = CpuMpData->CpuApStackSize;\r
   ExchangeInfo->BufferStart     = CpuMpData->WakeupBuffer;\r
@@ -878,6 +1039,9 @@ FillExchangeInfoData (
   ExchangeInfo->Enable5LevelPaging = (BOOLEAN) (Cr4.Bits.LA57 == 1);\r
   DEBUG ((DEBUG_INFO, "%a: 5-Level Paging = %d\n", gEfiCallerBaseName, ExchangeInfo->Enable5LevelPaging));\r
 \r
+  ExchangeInfo->SevEsIsEnabled  = CpuMpData->SevEsIsEnabled;\r
+  ExchangeInfo->GhcbBase        = (UINTN) CpuMpData->GhcbBase;\r
+\r
   //\r
   // Get the BSP's data of GDT and IDT\r
   //\r
@@ -904,8 +1068,9 @@ FillExchangeInfoData (
   // EfiBootServicesCode to avoid page fault if NX memory protection is enabled.\r
   //\r
   if (CpuMpData->WakeupBufferHigh != 0) {\r
-    Size = CpuMpData->AddressMap.RendezvousFunnelSize -\r
-           CpuMpData->AddressMap.ModeTransitionOffset;\r
+    Size = CpuMpData->AddressMap.RendezvousFunnelSize +\r
+             CpuMpData->AddressMap.SwitchToRealSize -\r
+             CpuMpData->AddressMap.ModeTransitionOffset;\r
     CopyMem (\r
       (VOID *)CpuMpData->WakeupBufferHigh,\r
       CpuMpData->AddressMap.RendezvousFunnelAddress +\r
@@ -958,7 +1123,8 @@ BackupAndPrepareWakeupBuffer(
   CopyMem (\r
     (VOID *) CpuMpData->WakeupBuffer,\r
     (VOID *) CpuMpData->AddressMap.RendezvousFunnelAddress,\r
-    CpuMpData->AddressMap.RendezvousFunnelSize\r
+    CpuMpData->AddressMap.RendezvousFunnelSize +\r
+      CpuMpData->AddressMap.SwitchToRealSize\r
     );\r
 }\r
 \r
@@ -979,6 +1145,28 @@ RestoreWakeupBuffer(
     );\r
 }\r
 \r
+/**\r
+  Calculate the size of the reset vector.\r
+\r
+  @param[in]  AddressMap  The pointer to Address Map structure.\r
+\r
+  @return                 Total amount of memory required for the AP reset area\r
+**/\r
+STATIC\r
+UINTN\r
+GetApResetVectorSize (\r
+  IN MP_ASSEMBLY_ADDRESS_MAP  *AddressMap\r
+  )\r
+{\r
+  UINTN  Size;\r
+\r
+  Size = AddressMap->RendezvousFunnelSize +\r
+           AddressMap->SwitchToRealSize +\r
+           sizeof (MP_CPU_EXCHANGE_INFO);\r
+\r
+  return Size;\r
+}\r
+\r
 /**\r
   Allocate reset vector buffer.\r
 \r
@@ -990,18 +1178,55 @@ AllocateResetVector (
   )\r
 {\r
   UINTN           ApResetVectorSize;\r
+  UINTN           ApResetStackSize;\r
 \r
   if (CpuMpData->WakeupBuffer == (UINTN) -1) {\r
-    ApResetVectorSize = CpuMpData->AddressMap.RendezvousFunnelSize +\r
-                          sizeof (MP_CPU_EXCHANGE_INFO);\r
+    ApResetVectorSize = GetApResetVectorSize (&CpuMpData->AddressMap);\r
 \r
     CpuMpData->WakeupBuffer      = GetWakeupBuffer (ApResetVectorSize);\r
     CpuMpData->MpCpuExchangeInfo = (MP_CPU_EXCHANGE_INFO *) (UINTN)\r
-                    (CpuMpData->WakeupBuffer + CpuMpData->AddressMap.RendezvousFunnelSize);\r
+                    (CpuMpData->WakeupBuffer +\r
+                       CpuMpData->AddressMap.RendezvousFunnelSize +\r
+                       CpuMpData->AddressMap.SwitchToRealSize);\r
     CpuMpData->WakeupBufferHigh  = GetModeTransitionBuffer (\r
-                                    CpuMpData->AddressMap.RendezvousFunnelSize -\r
+                                    CpuMpData->AddressMap.RendezvousFunnelSize +\r
+                                    CpuMpData->AddressMap.SwitchToRealSize -\r
                                     CpuMpData->AddressMap.ModeTransitionOffset\r
                                     );\r
+    //\r
+    // The AP reset stack is only used by SEV-ES guests. Do not allocate it\r
+    // if SEV-ES is not enabled.\r
+    //\r
+    if (PcdGetBool (PcdSevEsIsEnabled)) {\r
+      //\r
+      // Stack location is based on ProcessorNumber, so use the total number\r
+      // of processors for calculating the total stack area.\r
+      //\r
+      ApResetStackSize = (AP_RESET_STACK_SIZE *\r
+                          PcdGet32 (PcdCpuMaxLogicalProcessorNumber));\r
+\r
+      //\r
+      // Invoke GetWakeupBuffer a second time to allocate the stack area\r
+      // below 1MB. The returned buffer will be page aligned and sized and\r
+      // below the previously allocated buffer.\r
+      //\r
+      CpuMpData->SevEsAPResetStackStart = GetWakeupBuffer (ApResetStackSize);\r
+\r
+      //\r
+      // Check to be sure that the "allocate below" behavior hasn't changed.\r
+      // This will also catch a failed allocation, as "-1" is returned on\r
+      // failure.\r
+      //\r
+      if (CpuMpData->SevEsAPResetStackStart >= CpuMpData->WakeupBuffer) {\r
+        DEBUG ((\r
+          DEBUG_ERROR,\r
+          "SEV-ES AP reset stack is not below wakeup buffer\n"\r
+          ));\r
+\r
+        ASSERT (FALSE);\r
+        CpuDeadLoop ();\r
+      }\r
+    }\r
   }\r
   BackupAndPrepareWakeupBuffer (CpuMpData);\r
 }\r
@@ -1016,7 +1241,80 @@ FreeResetVector (
   IN CPU_MP_DATA              *CpuMpData\r
   )\r
 {\r
-  RestoreWakeupBuffer (CpuMpData);\r
+  //\r
+  // If SEV-ES is enabled, the reset area is needed for AP parking and\r
+  // and AP startup in the OS, so the reset area is reserved. Do not\r
+  // perform the restore as this will overwrite memory which has data\r
+  // needed by SEV-ES.\r
+  //\r
+  if (!CpuMpData->SevEsIsEnabled) {\r
+    RestoreWakeupBuffer (CpuMpData);\r
+  }\r
+}\r
+\r
+/**\r
+  Allocate the SEV-ES AP jump table buffer.\r
+\r
+  @param[in, out]  CpuMpData  The pointer to CPU MP Data structure.\r
+**/\r
+VOID\r
+AllocateSevEsAPMemory (\r
+  IN OUT CPU_MP_DATA          *CpuMpData\r
+  )\r
+{\r
+  if (CpuMpData->SevEsAPBuffer == (UINTN) -1) {\r
+    CpuMpData->SevEsAPBuffer =\r
+      CpuMpData->SevEsIsEnabled ? GetSevEsAPMemory () : 0;\r
+  }\r
+}\r
+\r
+/**\r
+  Program the SEV-ES AP jump table buffer.\r
+\r
+  @param[in]  SipiVector  The SIPI vector used for the AP Reset\r
+**/\r
+VOID\r
+SetSevEsJumpTable (\r
+  IN UINTN  SipiVector\r
+  )\r
+{\r
+  SEV_ES_AP_JMP_FAR *JmpFar;\r
+  UINT32            Offset, InsnByte;\r
+  UINT8             LoNib, HiNib;\r
+\r
+  JmpFar = (SEV_ES_AP_JMP_FAR *) (UINTN) FixedPcdGet32 (PcdSevEsWorkAreaBase);\r
+  ASSERT (JmpFar != NULL);\r
+\r
+  //\r
+  // Obtain the address of the Segment/Rip location in the workarea.\r
+  // This will be set to a value derived from the SIPI vector and will\r
+  // be the memory address used for the far jump below.\r
+  //\r
+  Offset = FixedPcdGet32 (PcdSevEsWorkAreaBase);\r
+  Offset += sizeof (JmpFar->InsnBuffer);\r
+  LoNib = (UINT8) Offset;\r
+  HiNib = (UINT8) (Offset >> 8);\r
+\r
+  //\r
+  // Program the workarea (which is the initial AP boot address) with\r
+  // far jump to the SIPI vector (where XX and YY represent the\r
+  // address of where the SIPI vector is stored.\r
+  //\r
+  //   JMP FAR [CS:XXYY] => 2E FF 2E YY XX\r
+  //\r
+  InsnByte = 0;\r
+  JmpFar->InsnBuffer[InsnByte++] = 0x2E;  // CS override prefix\r
+  JmpFar->InsnBuffer[InsnByte++] = 0xFF;  // JMP (FAR)\r
+  JmpFar->InsnBuffer[InsnByte++] = 0x2E;  // ModRM (JMP memory location)\r
+  JmpFar->InsnBuffer[InsnByte++] = LoNib; // YY offset ...\r
+  JmpFar->InsnBuffer[InsnByte++] = HiNib; // XX offset ...\r
+\r
+  //\r
+  // Program the Segment/Rip based on the SIPI vector (always at least\r
+  // 16-byte aligned, so Rip is set to 0).\r
+  //\r
+  JmpFar->Rip = 0;\r
+  JmpFar->Segment = (UINT16) (SipiVector >> 4);\r
 }\r
 \r
 /**\r
@@ -1035,8 +1333,8 @@ WakeUpAP (
   IN CPU_MP_DATA               *CpuMpData,\r
   IN BOOLEAN                   Broadcast,\r
   IN UINTN                     ProcessorNumber,\r
-  IN EFI_AP_PROCEDURE          Procedure,              OPTIONAL\r
-  IN VOID                      *ProcedureArgument,     OPTIONAL\r
+  IN EFI_AP_PROCEDURE          Procedure               OPTIONAL,\r
+  IN VOID                      *ProcedureArgument      OPTIONAL,\r
   IN BOOLEAN                   WakeUpDisabledAps\r
   )\r
 {\r
@@ -1053,6 +1351,7 @@ WakeUpAP (
       CpuMpData->InitFlag   != ApInitDone) {\r
     ResetVectorRequired = TRUE;\r
     AllocateResetVector (CpuMpData);\r
+    AllocateSevEsAPMemory (CpuMpData);\r
     FillExchangeInfoData (CpuMpData);\r
     SaveLocalApicTimerSetting (CpuMpData);\r
   }\r
@@ -1089,6 +1388,15 @@ WakeUpAP (
       }\r
     }\r
     if (ResetVectorRequired) {\r
+      //\r
+      // For SEV-ES, the initial AP boot address will be defined by\r
+      // PcdSevEsWorkAreaBase. The Segment/Rip must be the jump address\r
+      // from the original INIT-SIPI-SIPI.\r
+      //\r
+      if (CpuMpData->SevEsIsEnabled) {\r
+        SetSevEsJumpTable (ExchangeInfo->BufferStart);\r
+      }\r
+\r
       //\r
       // Wakeup all APs\r
       //\r
@@ -1180,6 +1488,16 @@ WakeUpAP (
     *(UINT32 *) CpuData->StartupApSignal = WAKEUP_AP_SIGNAL;\r
     if (ResetVectorRequired) {\r
       CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;\r
+\r
+      //\r
+      // For SEV-ES, the initial AP boot address will be defined by\r
+      // PcdSevEsWorkAreaBase. The Segment/Rip must be the jump address\r
+      // from the original INIT-SIPI-SIPI.\r
+      //\r
+      if (CpuMpData->SevEsIsEnabled) {\r
+        SetSevEsJumpTable (ExchangeInfo->BufferStart);\r
+      }\r
+\r
       SendInitSipiSipi (\r
         CpuInfoInHob[ProcessorNumber].ApicId,\r
         (UINT32) ExchangeInfo->BufferStart\r
@@ -1656,7 +1974,7 @@ MpInitLibInitialize (
   ASSERT (MaxLogicalProcessorNumber != 0);\r
 \r
   AsmGetAddressMap (&AddressMap);\r
-  ApResetVectorSize = AddressMap.RendezvousFunnelSize + sizeof (MP_CPU_EXCHANGE_INFO);\r
+  ApResetVectorSize = GetApResetVectorSize (&AddressMap);\r
   ApStackSize = PcdGet32(PcdCpuApStackSize);\r
   ApLoopMode  = GetApLoopMode (&MonitorFilterSize);\r
 \r
@@ -1714,6 +2032,9 @@ MpInitLibInitialize (
   CpuMpData->CpuData          = (CPU_AP_DATA *) (CpuMpData + 1);\r
   CpuMpData->CpuInfoInHob     = (UINT64) (UINTN) (CpuMpData->CpuData + MaxLogicalProcessorNumber);\r
   InitializeSpinLock(&CpuMpData->MpLock);\r
+  CpuMpData->SevEsIsEnabled = PcdGetBool (PcdSevEsIsEnabled);\r
+  CpuMpData->SevEsAPBuffer  = (UINTN) -1;\r
+  CpuMpData->GhcbBase       = PcdGet64 (PcdGhcbBase);\r
 \r
   //\r
   // Make sure no memory usage outside of the allocated buffer.\r
@@ -1772,6 +2093,7 @@ MpInitLibInitialize (
     // APs have been wakeup before, just get the CPU Information\r
     // from HOB\r
     //\r
+    OldCpuMpData->NewCpuMpData = CpuMpData;\r
     CpuMpData->CpuCount  = OldCpuMpData->CpuCount;\r
     CpuMpData->BspNumber = OldCpuMpData->BspNumber;\r
     CpuMpData->CpuInfoInHob = OldCpuMpData->CpuInfoInHob;\r
@@ -1780,7 +2102,6 @@ MpInitLibInitialize (
       InitializeSpinLock(&CpuMpData->CpuData[Index].ApLock);\r
       CpuMpData->CpuData[Index].CpuHealthy = (CpuInfoInHob[Index].Health == 0)? TRUE:FALSE;\r
       CpuMpData->CpuData[Index].ApFunction = 0;\r
-      CopyMem (&CpuMpData->CpuData[Index].VolatileRegisters, &VolatileRegisters, sizeof (CPU_VOLATILE_REGISTERS));\r
     }\r
   }\r
 \r
@@ -1808,7 +2129,14 @@ MpInitLibInitialize (
   // Wakeup APs to do some AP initialize sync (Microcode & MTRR)\r
   //\r
   if (CpuMpData->CpuCount > 1) {\r
-    CpuMpData->InitFlag = ApInitReconfig;\r
+    if (OldCpuMpData != NULL) {\r
+      //\r
+      // Only needs to use this flag for DXE phase to update the wake up\r
+      // buffer. Wakeup buffer allocated in PEI phase is no longer valid\r
+      // in DXE.\r
+      //\r
+      CpuMpData->InitFlag = ApInitReconfig;\r
+    }\r
     WakeUpAP (CpuMpData, TRUE, 0, ApInitializeSync, CpuMpData, TRUE);\r
     //\r
     // Wait for all APs finished initialization\r
@@ -1816,12 +2144,39 @@ MpInitLibInitialize (
     while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) {\r
       CpuPause ();\r
     }\r
-    CpuMpData->InitFlag = ApInitDone;\r
+    if (OldCpuMpData != NULL) {\r
+      CpuMpData->InitFlag = ApInitDone;\r
+    }\r
     for (Index = 0; Index < CpuMpData->CpuCount; Index++) {\r
       SetApState (&CpuMpData->CpuData[Index], CpuStateIdle);\r
     }\r
   }\r
 \r
+  //\r
+  // Dump the microcode revision for each core.\r
+  //\r
+  DEBUG_CODE_BEGIN ();\r
+    UINT32 ThreadId;\r
+    UINT32 ExpectedMicrocodeRevision;\r
+    CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;\r
+    for (Index = 0; Index < CpuMpData->CpuCount; Index++) {\r
+      GetProcessorLocationByApicId (CpuInfoInHob[Index].InitialApicId, NULL, NULL, &ThreadId);\r
+      if (ThreadId == 0) {\r
+        //\r
+        // MicrocodeDetect() loads microcode in first thread of each core, so,\r
+        // CpuMpData->CpuData[Index].MicrocodeEntryAddr is initialized only for first thread of each core.\r
+        //\r
+        ExpectedMicrocodeRevision = 0;\r
+        if (CpuMpData->CpuData[Index].MicrocodeEntryAddr != 0) {\r
+          ExpectedMicrocodeRevision = ((CPU_MICROCODE_HEADER *)(UINTN)CpuMpData->CpuData[Index].MicrocodeEntryAddr)->UpdateRevision;\r
+        }\r
+        DEBUG ((\r
+          DEBUG_INFO, "CPU[%04d]: Microcode revision = %08x, expected = %08x\n",\r
+          Index, CpuMpData->CpuData[Index].MicrocodeRevision, ExpectedMicrocodeRevision\r
+          ));\r
+      }\r
+    }\r
+  DEBUG_CODE_END ();\r
   //\r
   // Initialize global data for MP support\r
   //\r
@@ -1858,10 +2213,17 @@ MpInitLibGetProcessorInfo (
   CPU_MP_DATA            *CpuMpData;\r
   UINTN                  CallerNumber;\r
   CPU_INFO_IN_HOB        *CpuInfoInHob;\r
+  UINTN                  OriginalProcessorNumber;\r
 \r
   CpuMpData = GetCpuMpData ();\r
   CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob;\r
 \r
+  //\r
+  // Lower 24 bits contains the actual processor number.\r
+  //\r
+  OriginalProcessorNumber = ProcessorNumber;\r
+  ProcessorNumber &= BIT24 - 1;\r
+\r
   //\r
   // Check whether caller processor is BSP\r
   //\r
@@ -1902,6 +2264,18 @@ MpInitLibGetProcessorInfo (
     &ProcessorInfoBuffer->Location.Thread\r
     );\r
 \r
+  if ((OriginalProcessorNumber & CPU_V2_EXTENDED_TOPOLOGY) != 0) {\r
+    GetProcessorLocation2ByApicId (\r
+      CpuInfoInHob[ProcessorNumber].ApicId,\r
+      &ProcessorInfoBuffer->ExtendedInformation.Location2.Package,\r
+      &ProcessorInfoBuffer->ExtendedInformation.Location2.Die,\r
+      &ProcessorInfoBuffer->ExtendedInformation.Location2.Tile,\r
+      &ProcessorInfoBuffer->ExtendedInformation.Location2.Module,\r
+      &ProcessorInfoBuffer->ExtendedInformation.Location2.Core,\r
+      &ProcessorInfoBuffer->ExtendedInformation.Location2.Thread\r
+      );\r
+  }\r
+\r
   if (HealthData != NULL) {\r
     HealthData->Uint32 = CpuInfoInHob[ProcessorNumber].Health;\r
   }\r
@@ -2160,7 +2534,7 @@ MpInitLibWhoAmI (
 EFI_STATUS\r
 EFIAPI\r
 MpInitLibGetNumberOfProcessors (\r
-  OUT UINTN                     *NumberOfProcessors,       OPTIONAL\r
+  OUT UINTN                     *NumberOfProcessors        OPTIONAL,\r
   OUT UINTN                     *NumberOfEnabledProcessors OPTIONAL\r
   )\r
 {\r