]> git.proxmox.com Git - mirror_edk2.git/commitdiff
UefiCpuPkg/RegisterCpuFeaturesLib: Add logic to support semaphore type.
authorEric Dong <eric.dong@intel.com>
Wed, 17 Oct 2018 01:31:03 +0000 (09:31 +0800)
committerEric Dong <eric.dong@intel.com>
Mon, 22 Oct 2018 03:19:48 +0000 (11:19 +0800)
V4 changes include:
1. Serial debug message for different threads when program the register table.

V3 changes include:
1. Use global variable instead of internal function to return string for register type
   and dependence type.
2. Add comments for some complicated logic.

V2 changes include:
1. Add more description for the code part which need easy to understand.
2. Refine some code base on feedback for V1 changes.

V1 changes include:
In a system which has multiple cores, current set register value task costs huge times.
After investigation, current set MSR task costs most of the times. Current logic uses
SpinLock to let set MSR task as an single thread task for all cores. Because MSR has
scope attribute which may cause GP fault if multiple APs set MSR at the same time,
current logic use an easiest solution (use SpinLock) to avoid this issue, but it will
cost huge times.

In order to fix this performance issue, new solution will set MSRs base on their scope
attribute. After this, the SpinLock will not needed. Without SpinLock, new issue raised
which is caused by MSR dependence. For example, MSR A depends on MSR B which means MSR A
must been set after MSR B has been set. Also MSR B is package scope level and MSR A is
thread scope level. If system has multiple threads, Thread 1 needs to set the thread level
MSRs and thread 2 needs to set thread and package level MSRs. Set MSRs task for thread 1
and thread 2 like below:

            Thread 1                 Thread 2
MSR B          N                        Y
MSR A          Y                        Y

If driver don't control execute MSR order, for thread 1, it will execute MSR A first, but
at this time, MSR B not been executed yet by thread 2. system may trig exception at this
time.

In order to fix the above issue, driver introduces semaphore logic to control the MSR
execute sequence. For the above case, a semaphore will be add between MSR A and B for
all threads. Semaphore has scope info for it. The possible scope value is core or package.
For each thread, when it meets a semaphore during it set registers, it will 1) release
semaphore (+1) for each threads in this core or package(based on the scope info for this
semaphore) 2) acquire semaphore (-1) for all the threads in this core or package(based
on the scope info for this semaphore). With these two steps, driver can control MSR
sequence. Sample code logic like below:

  //
  // First increase semaphore count by 1 for processors in this package.
  //
  for (ProcessorIndex = 0; ProcessorIndex < PackageThreadsCount ; ProcessorIndex ++) {
    LibReleaseSemaphore ((UINT32 *) &SemaphorePtr[PackageOffset + ProcessorIndex]);
  }
  //
  // Second, check whether the count has reach the check number.
  //
  for (ProcessorIndex = 0; ProcessorIndex < ValidApCount; ProcessorIndex ++) {
    LibWaitForSemaphore (&SemaphorePtr[ApOffset]);
  }

Platform Requirement:
1. This change requires register MSR setting base on MSR scope info. If still register MSR
   for all threads, exception may raised.

Known limitation:
1. Current CpuFeatures driver supports DXE instance and PEI instance. But semaphore logic
   requires Aps execute in async mode which is not supported by PEI driver. So CpuFeature
   PEI instance not works after this change. We plan to support async mode for PEI in phase
   2 for this task.

Cc: Ruiyu Ni <ruiyu.ni@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Eric Dong <eric.dong@intel.com>
Reviewed-by: Ruiyu Ni <ruiyu.ni@intel.com>
UefiCpuPkg/Library/RegisterCpuFeaturesLib/CpuFeaturesInitialize.c
UefiCpuPkg/Library/RegisterCpuFeaturesLib/DxeRegisterCpuFeaturesLib.c
UefiCpuPkg/Library/RegisterCpuFeaturesLib/DxeRegisterCpuFeaturesLib.inf
UefiCpuPkg/Library/RegisterCpuFeaturesLib/PeiRegisterCpuFeaturesLib.c
UefiCpuPkg/Library/RegisterCpuFeaturesLib/RegisterCpuFeatures.h
UefiCpuPkg/Library/RegisterCpuFeaturesLib/RegisterCpuFeaturesLib.c

index ba3fb3250fccef850f6dd0f50a7a74693db58f63..7a5939c966dfa2844ed6614182549d8bc7fb53ce 100644 (file)
@@ -14,6 +14,9 @@
 \r
 #include "RegisterCpuFeatures.h"\r
 \r
+CHAR16 *mDependTypeStr[]   = {L"None", L"Thread", L"Core", L"Package", L"Invalid" };\r
+CHAR16 *mRegisterTypeStr[] = {L"MSR", L"CR", L"MMIO", L"CACHE", L"SEMAP", L"INVALID" };\r
+\r
 /**\r
   Worker function to save PcdCpuFeaturesCapability.\r
 \r
@@ -145,6 +148,19 @@ CpuInitDataInitialize (
   CPU_FEATURES_INIT_ORDER              *InitOrder;\r
   CPU_FEATURES_DATA                    *CpuFeaturesData;\r
   LIST_ENTRY                           *Entry;\r
+  UINT32                               Core;\r
+  UINT32                               Package;\r
+  UINT32                               Thread;\r
+  EFI_CPU_PHYSICAL_LOCATION            *Location;\r
+  BOOLEAN                              *CoresVisited;\r
+  UINTN                                Index;\r
+  ACPI_CPU_DATA                        *AcpiCpuData;\r
+  CPU_STATUS_INFORMATION               *CpuStatus;\r
+  UINT32                               *ValidCoreCountPerPackage;\r
+\r
+  Core    = 0;\r
+  Package = 0;\r
+  Thread  = 0;\r
 \r
   CpuFeaturesData = GetCpuFeaturesData ();\r
   CpuFeaturesData->InitOrder = AllocateZeroPool (sizeof (CPU_FEATURES_INIT_ORDER) * NumberOfCpus);\r
@@ -163,6 +179,17 @@ CpuInitDataInitialize (
     Entry = Entry->ForwardLink;\r
   }\r
 \r
+  CpuFeaturesData->NumberOfCpus = (UINT32) NumberOfCpus;\r
+\r
+  AcpiCpuData = GetAcpiCpuData ();\r
+  ASSERT (AcpiCpuData != NULL);\r
+  CpuFeaturesData->AcpiCpuData= AcpiCpuData;\r
+\r
+  CpuStatus = &AcpiCpuData->CpuStatus;\r
+  Location = AllocateZeroPool (sizeof (EFI_CPU_PHYSICAL_LOCATION) * NumberOfCpus);\r
+  ASSERT (Location != NULL);\r
+  AcpiCpuData->ApLocation = (EFI_PHYSICAL_ADDRESS)(UINTN)Location;\r
+\r
   for (ProcessorNumber = 0; ProcessorNumber < NumberOfCpus; ProcessorNumber++) {\r
     InitOrder = &CpuFeaturesData->InitOrder[ProcessorNumber];\r
     InitOrder->FeaturesSupportedMask = AllocateZeroPool (CpuFeaturesData->BitMaskSize);\r
@@ -175,7 +202,76 @@ CpuInitDataInitialize (
       &ProcessorInfoBuffer,\r
       sizeof (EFI_PROCESSOR_INFORMATION)\r
       );\r
+    CopyMem (\r
+      &Location[ProcessorNumber],\r
+      &ProcessorInfoBuffer.Location,\r
+      sizeof (EFI_CPU_PHYSICAL_LOCATION)\r
+      );\r
+\r
+    //\r
+    // Collect CPU package count info.\r
+    //\r
+    if (Package < ProcessorInfoBuffer.Location.Package) {\r
+      Package = ProcessorInfoBuffer.Location.Package;\r
+    }\r
+    //\r
+    // Collect CPU max core count info.\r
+    //\r
+    if (Core < ProcessorInfoBuffer.Location.Core) {\r
+      Core = ProcessorInfoBuffer.Location.Core;\r
+    }\r
+    //\r
+    // Collect CPU max thread count info.\r
+    //\r
+    if (Thread < ProcessorInfoBuffer.Location.Thread) {\r
+      Thread = ProcessorInfoBuffer.Location.Thread;\r
+    }\r
   }\r
+  CpuStatus->PackageCount    = Package + 1;\r
+  CpuStatus->MaxCoreCount    = Core + 1;\r
+  CpuStatus->MaxThreadCount  = Thread + 1;\r
+  DEBUG ((DEBUG_INFO, "Processor Info: Package: %d, MaxCore : %d, MaxThread: %d\n",\r
+         CpuStatus->PackageCount,\r
+         CpuStatus->MaxCoreCount,\r
+         CpuStatus->MaxThreadCount));\r
+\r
+  //\r
+  // Collect valid core count in each package because not all cores are valid.\r
+  //\r
+  ValidCoreCountPerPackage= AllocateZeroPool (sizeof (UINT32) * CpuStatus->PackageCount);\r
+  ASSERT (ValidCoreCountPerPackage != 0);\r
+  CpuStatus->ValidCoreCountPerPackage = (EFI_PHYSICAL_ADDRESS)(UINTN)ValidCoreCountPerPackage;\r
+  CoresVisited = AllocatePool (sizeof (BOOLEAN) * CpuStatus->MaxCoreCount);\r
+  ASSERT (CoresVisited != NULL);\r
+\r
+  for (Index = 0; Index < CpuStatus->PackageCount; Index ++ ) {\r
+    ZeroMem (CoresVisited, sizeof (BOOLEAN) * CpuStatus->MaxCoreCount);\r
+    //\r
+    // Collect valid cores in Current package.\r
+    //\r
+    for (ProcessorNumber = 0; ProcessorNumber < NumberOfCpus; ProcessorNumber++) {\r
+      Location = &CpuFeaturesData->InitOrder[ProcessorNumber].CpuInfo.ProcessorInfo.Location;\r
+      if (Location->Package == Index && !CoresVisited[Location->Core] ) {\r
+        //\r
+        // The ValidCores position for Location->Core is valid.\r
+        // The possible values in ValidCores[Index] are 0 or 1.\r
+        // FALSE means no valid threads in this Core.\r
+        // TRUE means have valid threads in this core, no matter the thead count is 1 or more.\r
+        //\r
+        CoresVisited[Location->Core] = TRUE;\r
+        ValidCoreCountPerPackage[Index]++;\r
+      }\r
+    }\r
+  }\r
+  FreePool (CoresVisited);\r
+\r
+  for (Index = 0; Index <= Package; Index++) {\r
+    DEBUG ((DEBUG_INFO, "Package: %d, Valid Core : %d\n", Index, ValidCoreCountPerPackage[Index]));\r
+  }\r
+\r
+  CpuFeaturesData->CpuFlags.SemaphoreCount = AllocateZeroPool (sizeof (UINT32) * CpuStatus->PackageCount * CpuStatus->MaxCoreCount * CpuStatus->MaxThreadCount);\r
+  ASSERT (CpuFeaturesData->CpuFlags.SemaphoreCount != NULL);\r
+\r
   //\r
   // Get support and configuration PCDs\r
   //\r
@@ -310,7 +406,7 @@ CollectProcessorData (
   LIST_ENTRY                           *Entry;\r
   CPU_FEATURES_DATA                    *CpuFeaturesData;\r
 \r
-  CpuFeaturesData = GetCpuFeaturesData ();\r
+  CpuFeaturesData = (CPU_FEATURES_DATA *)Buffer;\r
   ProcessorNumber = GetProcessorIndex ();\r
   CpuInfo = &CpuFeaturesData->InitOrder[ProcessorNumber].CpuInfo;\r
   //\r
@@ -416,6 +512,15 @@ DumpRegisterTableOnProcessor (
         RegisterTableEntry->Value\r
         ));\r
       break;\r
+    case Semaphore:\r
+      DEBUG ((\r
+        DebugPrintErrorLevel,\r
+        "Processor: %d: Semaphore: Scope Value: %s\r\n",\r
+        ProcessorNumber,\r
+        mDependTypeStr[MIN (RegisterTableEntry->Value, InvalidDepType)]\r
+        ));\r
+      break;\r
+\r
     default:\r
       break;\r
     }\r
@@ -441,6 +546,11 @@ AnalysisProcessorFeatures (
   REGISTER_CPU_FEATURE_INFORMATION     *CpuInfo;\r
   LIST_ENTRY                           *Entry;\r
   CPU_FEATURES_DATA                    *CpuFeaturesData;\r
+  LIST_ENTRY                           *NextEntry;\r
+  CPU_FEATURES_ENTRY                   *NextCpuFeatureInOrder;\r
+  BOOLEAN                              Success;\r
+  CPU_FEATURE_DEPENDENCE_TYPE          BeforeDep;\r
+  CPU_FEATURE_DEPENDENCE_TYPE          AfterDep;\r
 \r
   CpuFeaturesData = GetCpuFeaturesData ();\r
   CpuFeaturesData->CapabilityPcd = AllocatePool (CpuFeaturesData->BitMaskSize);\r
@@ -517,8 +627,15 @@ AnalysisProcessorFeatures (
     //\r
     CpuInfo = &CpuFeaturesData->InitOrder[ProcessorNumber].CpuInfo;\r
     Entry = GetFirstNode (&CpuInitOrder->OrderList);\r
+    NextEntry = Entry->ForwardLink;\r
     while (!IsNull (&CpuInitOrder->OrderList, Entry)) {\r
       CpuFeatureInOrder = CPU_FEATURE_ENTRY_FROM_LINK (Entry);\r
+      if (!IsNull (&CpuInitOrder->OrderList, NextEntry)) {\r
+        NextCpuFeatureInOrder = CPU_FEATURE_ENTRY_FROM_LINK (NextEntry);\r
+      } else {\r
+        NextCpuFeatureInOrder = NULL;\r
+      }\r
+      Success = FALSE;\r
       if (IsBitMaskMatch (CpuFeatureInOrder->FeatureMask, CpuFeaturesData->SettingPcd)) {\r
         Status = CpuFeatureInOrder->InitializeFunc (ProcessorNumber, CpuInfo, CpuFeatureInOrder->ConfigData, TRUE);\r
         if (EFI_ERROR (Status)) {\r
@@ -532,6 +649,8 @@ AnalysisProcessorFeatures (
             DEBUG ((DEBUG_WARN, "Warning :: Failed to enable Feature: Mask = "));\r
             DumpCpuFeatureMask (CpuFeatureInOrder->FeatureMask);\r
           }\r
+        } else {\r
+          Success = TRUE;\r
         }\r
       } else {\r
         Status = CpuFeatureInOrder->InitializeFunc (ProcessorNumber, CpuInfo, CpuFeatureInOrder->ConfigData, FALSE);\r
@@ -542,9 +661,36 @@ AnalysisProcessorFeatures (
             DEBUG ((DEBUG_WARN, "Warning :: Failed to disable Feature: Mask = "));\r
             DumpCpuFeatureMask (CpuFeatureInOrder->FeatureMask);\r
           }\r
+        } else {\r
+          Success = TRUE;\r
         }\r
       }\r
-      Entry = Entry->ForwardLink;\r
+\r
+      if (Success) {\r
+        //\r
+        // If feature has dependence with the next feature (ONLY care core/package dependency).\r
+        // and feature initialize succeed, add sync semaphere here.\r
+        //\r
+        BeforeDep = DetectFeatureScope (CpuFeatureInOrder, TRUE);\r
+        if (NextCpuFeatureInOrder != NULL) {\r
+          AfterDep  = DetectFeatureScope (NextCpuFeatureInOrder, FALSE);\r
+        } else {\r
+          AfterDep = NoneDepType;\r
+        }\r
+        //\r
+        // Assume only one of the depend is valid.\r
+        //\r
+        ASSERT (!(BeforeDep > ThreadDepType && AfterDep > ThreadDepType));\r
+        if (BeforeDep > ThreadDepType) {\r
+          CPU_REGISTER_TABLE_WRITE32 (ProcessorNumber, Semaphore, 0, BeforeDep);\r
+        }\r
+        if (AfterDep > ThreadDepType) {\r
+          CPU_REGISTER_TABLE_WRITE32 (ProcessorNumber, Semaphore, 0, AfterDep);\r
+        }\r
+      }\r
+\r
+      Entry     = Entry->ForwardLink;\r
+      NextEntry = Entry->ForwardLink;\r
     }\r
 \r
     //\r
@@ -561,27 +707,77 @@ AnalysisProcessorFeatures (
   }\r
 }\r
 \r
+/**\r
+  Increment semaphore by 1.\r
+\r
+  @param      Sem            IN:  32-bit unsigned integer\r
+\r
+**/\r
+VOID\r
+LibReleaseSemaphore (\r
+  IN OUT  volatile UINT32           *Sem\r
+  )\r
+{\r
+  InterlockedIncrement (Sem);\r
+}\r
+\r
+/**\r
+  Decrement the semaphore by 1 if it is not zero.\r
+\r
+  Performs an atomic decrement operation for semaphore.\r
+  The compare exchange operation must be performed using\r
+  MP safe mechanisms.\r
+\r
+  @param      Sem            IN:  32-bit unsigned integer\r
+\r
+**/\r
+VOID\r
+LibWaitForSemaphore (\r
+  IN OUT  volatile UINT32           *Sem\r
+  )\r
+{\r
+  UINT32  Value;\r
+\r
+  do {\r
+    Value = *Sem;\r
+  } while (Value == 0 ||\r
+           InterlockedCompareExchange32 (\r
+             Sem,\r
+             Value,\r
+             Value - 1\r
+             ) != Value);\r
+}\r
+\r
 /**\r
   Initialize the CPU registers from a register table.\r
 \r
-  @param[in]  ProcessorNumber  The index of the CPU executing this function.\r
+  @param[in]  RegisterTable         The register table for this AP.\r
+  @param[in]  ApLocation            AP location info for this ap.\r
+  @param[in]  CpuStatus             CPU status info for this CPU.\r
+  @param[in]  CpuFlags              Flags data structure used when program the register.\r
 \r
   @note This service could be called by BSP/APs.\r
 **/\r
 VOID\r
 ProgramProcessorRegister (\r
-  IN UINTN  ProcessorNumber\r
+  IN CPU_REGISTER_TABLE           *RegisterTable,\r
+  IN EFI_CPU_PHYSICAL_LOCATION    *ApLocation,\r
+  IN CPU_STATUS_INFORMATION       *CpuStatus,\r
+  IN PROGRAM_CPU_REGISTER_FLAGS   *CpuFlags\r
   )\r
 {\r
-  CPU_FEATURES_DATA         *CpuFeaturesData;\r
-  CPU_REGISTER_TABLE        *RegisterTable;\r
   CPU_REGISTER_TABLE_ENTRY  *RegisterTableEntry;\r
   UINTN                     Index;\r
   UINTN                     Value;\r
   CPU_REGISTER_TABLE_ENTRY  *RegisterTableEntryHead;\r
-\r
-  CpuFeaturesData = GetCpuFeaturesData ();\r
-  RegisterTable = &CpuFeaturesData->RegisterTable[ProcessorNumber];\r
+  volatile UINT32           *SemaphorePtr;\r
+  UINT32                    FirstThread;\r
+  UINT32                    PackageThreadsCount;\r
+  UINT32                    CurrentThread;\r
+  UINTN                     ProcessorIndex;\r
+  UINTN                     ThreadIndex;\r
+  UINTN                     ValidThreadCount;\r
+  UINT32                    *ValidCoreCountPerPackage;\r
 \r
   //\r
   // Traverse Register Table of this logical processor\r
@@ -592,6 +788,21 @@ ProgramProcessorRegister (
 \r
     RegisterTableEntry = &RegisterTableEntryHead[Index];\r
 \r
+    DEBUG_CODE_BEGIN ();\r
+      AcquireSpinLock (&CpuFlags->ConsoleLogLock);\r
+      ThreadIndex = ApLocation->Package * CpuStatus->MaxCoreCount * CpuStatus->MaxThreadCount +\r
+              ApLocation->Core * CpuStatus->MaxThreadCount +\r
+              ApLocation->Thread;\r
+      DEBUG ((\r
+        DEBUG_INFO,\r
+        "Processor = %lu, Entry Index %lu, Type = %s!\n",\r
+        (UINT64)ThreadIndex,\r
+        (UINT64)Index,\r
+        mRegisterTypeStr[MIN ((REGISTER_TYPE)RegisterTableEntry->RegisterType, InvalidReg)]\r
+        ));\r
+      ReleaseSpinLock (&CpuFlags->ConsoleLogLock);\r
+    DEBUG_CODE_END ();\r
+\r
     //\r
     // Check the type of specified register\r
     //\r
@@ -654,10 +865,6 @@ ProgramProcessorRegister (
     // The specified register is Model Specific Register\r
     //\r
     case Msr:\r
-      //\r
-      // Get lock to avoid Package/Core scope MSRs programming issue in parallel execution mode\r
-      //\r
-      AcquireSpinLock (&CpuFeaturesData->MsrLock);\r
       if (RegisterTableEntry->ValidBitLength >= 64) {\r
         //\r
         // If length is not less than 64 bits, then directly write without reading\r
@@ -677,20 +884,19 @@ ProgramProcessorRegister (
           RegisterTableEntry->Value\r
           );\r
       }\r
-      ReleaseSpinLock (&CpuFeaturesData->MsrLock);\r
       break;\r
     //\r
     // MemoryMapped operations\r
     //\r
     case MemoryMapped:\r
-      AcquireSpinLock (&CpuFeaturesData->MemoryMappedLock);\r
+      AcquireSpinLock (&CpuFlags->MemoryMappedLock);\r
       MmioBitFieldWrite32 (\r
         (UINTN)(RegisterTableEntry->Index | LShiftU64 (RegisterTableEntry->HighIndex, 32)),\r
         RegisterTableEntry->ValidBitStart,\r
         RegisterTableEntry->ValidBitStart + RegisterTableEntry->ValidBitLength - 1,\r
         (UINT32)RegisterTableEntry->Value\r
         );\r
-      ReleaseSpinLock (&CpuFeaturesData->MemoryMappedLock);\r
+      ReleaseSpinLock (&CpuFlags->MemoryMappedLock);\r
       break;\r
     //\r
     // Enable or disable cache\r
@@ -706,6 +912,90 @@ ProgramProcessorRegister (
       }\r
       break;\r
 \r
+    case Semaphore:\r
+      // Semaphore works logic like below:\r
+      //\r
+      //  V(x) = LibReleaseSemaphore (Semaphore[FirstThread + x]);\r
+      //  P(x) = LibWaitForSemaphore (Semaphore[FirstThread + x]);\r
+      //\r
+      //  All threads (T0...Tn) waits in P() line and continues running\r
+      //  together.\r
+      //\r
+      //\r
+      //  T0             T1            ...           Tn\r
+      //\r
+      //  V(0...n)       V(0...n)      ...           V(0...n)\r
+      //  n * P(0)       n * P(1)      ...           n * P(n)\r
+      //\r
+      SemaphorePtr = CpuFlags->SemaphoreCount;\r
+      switch (RegisterTableEntry->Value) {\r
+      case CoreDepType:\r
+        //\r
+        // Get Offset info for the first thread in the core which current thread belongs to.\r
+        //\r
+        FirstThread = (ApLocation->Package * CpuStatus->MaxCoreCount + ApLocation->Core) * CpuStatus->MaxThreadCount;\r
+        CurrentThread = FirstThread + ApLocation->Thread;\r
+        //\r
+        // First Notify all threads in current Core that this thread has ready.\r
+        //\r
+        for (ProcessorIndex = 0; ProcessorIndex < CpuStatus->MaxThreadCount; ProcessorIndex ++) {\r
+          LibReleaseSemaphore ((UINT32 *) &SemaphorePtr[FirstThread + ProcessorIndex]);\r
+        }\r
+        //\r
+        // Second, check whether all valid threads in current core have ready.\r
+        //\r
+        for (ProcessorIndex = 0; ProcessorIndex < CpuStatus->MaxThreadCount; ProcessorIndex ++) {\r
+          LibWaitForSemaphore (&SemaphorePtr[CurrentThread]);\r
+        }\r
+        break;\r
+\r
+      case PackageDepType:\r
+        ValidCoreCountPerPackage = (UINT32 *)(UINTN)CpuStatus->ValidCoreCountPerPackage;\r
+        //\r
+        // Get Offset info for the first thread in the package which current thread belongs to.\r
+        //\r
+        FirstThread = ApLocation->Package * CpuStatus->MaxCoreCount * CpuStatus->MaxThreadCount;\r
+        //\r
+        // Get the possible threads count for current package.\r
+        //\r
+        PackageThreadsCount = CpuStatus->MaxThreadCount * CpuStatus->MaxCoreCount;\r
+        CurrentThread = FirstThread + CpuStatus->MaxThreadCount * ApLocation->Core + ApLocation->Thread;\r
+        //\r
+        // Get the valid thread count for current package.\r
+        //\r
+        ValidThreadCount = CpuStatus->MaxThreadCount * ValidCoreCountPerPackage[ApLocation->Package];\r
+\r
+        //\r
+        // Different packages may have different valid cores in them. If driver maintail clearly\r
+        // cores number in different packages, the logic will be much complicated.\r
+        // Here driver just simply records the max core number in all packages and use it as expect\r
+        // core number for all packages.\r
+        // In below two steps logic, first current thread will Release semaphore for each thread\r
+        // in current package. Maybe some threads are not valid in this package, but driver don't\r
+        // care. Second, driver will let current thread wait semaphore for all valid threads in\r
+        // current package. Because only the valid threads will do release semaphore for this\r
+        // thread, driver here only need to wait the valid thread count.\r
+        //\r
+\r
+        //\r
+        // First Notify ALL THREADS in current package that this thread has ready.\r
+        //\r
+        for (ProcessorIndex = 0; ProcessorIndex < PackageThreadsCount ; ProcessorIndex ++) {\r
+          LibReleaseSemaphore ((UINT32 *) &SemaphorePtr[FirstThread + ProcessorIndex]);\r
+        }\r
+        //\r
+        // Second, check whether VALID THREADS (not all threads) in current package have ready.\r
+        //\r
+        for (ProcessorIndex = 0; ProcessorIndex < ValidThreadCount; ProcessorIndex ++) {\r
+          LibWaitForSemaphore (&SemaphorePtr[CurrentThread]);\r
+        }\r
+        break;\r
+\r
+      default:\r
+        break;\r
+      }\r
+      break;\r
+\r
     default:\r
       break;\r
     }\r
@@ -724,10 +1014,36 @@ SetProcessorRegister (
   IN OUT VOID            *Buffer\r
   )\r
 {\r
-  UINTN                  ProcessorNumber;\r
+  CPU_FEATURES_DATA         *CpuFeaturesData;\r
+  CPU_REGISTER_TABLE        *RegisterTable;\r
+  CPU_REGISTER_TABLE        *RegisterTables;\r
+  UINT32                    InitApicId;\r
+  UINTN                     ProcIndex;\r
+  UINTN                     Index;\r
+  ACPI_CPU_DATA             *AcpiCpuData;\r
 \r
-  ProcessorNumber = GetProcessorIndex ();\r
-  ProgramProcessorRegister (ProcessorNumber);\r
+  CpuFeaturesData = (CPU_FEATURES_DATA *) Buffer;\r
+  AcpiCpuData = CpuFeaturesData->AcpiCpuData;\r
+\r
+  RegisterTables = (CPU_REGISTER_TABLE *)(UINTN)AcpiCpuData->RegisterTable;\r
+\r
+  InitApicId = GetInitialApicId ();\r
+  RegisterTable = NULL;\r
+  for (Index = 0; Index < AcpiCpuData->NumberOfCpus; Index++) {\r
+    if (RegisterTables[Index].InitialApicId == InitApicId) {\r
+      RegisterTable =  &RegisterTables[Index];\r
+      ProcIndex = Index;\r
+      break;\r
+    }\r
+  }\r
+  ASSERT (RegisterTable != NULL);\r
+\r
+  ProgramProcessorRegister (\r
+    RegisterTable,\r
+    (EFI_CPU_PHYSICAL_LOCATION *)(UINTN)AcpiCpuData->ApLocation + ProcIndex,\r
+    &AcpiCpuData->CpuStatus,\r
+    &CpuFeaturesData->CpuFlags\r
+    );\r
 }\r
 \r
 /**\r
@@ -746,6 +1062,9 @@ CpuFeaturesDetect (
 {\r
   UINTN                  NumberOfCpus;\r
   UINTN                  NumberOfEnabledProcessors;\r
+  CPU_FEATURES_DATA      *CpuFeaturesData;\r
+\r
+  CpuFeaturesData = GetCpuFeaturesData();\r
 \r
   GetNumberOfProcessor (&NumberOfCpus, &NumberOfEnabledProcessors);\r
 \r
@@ -754,49 +1073,13 @@ CpuFeaturesDetect (
   //\r
   // Wakeup all APs for data collection.\r
   //\r
-  StartupAPsWorker (CollectProcessorData);\r
+  StartupAPsWorker (CollectProcessorData, NULL);\r
 \r
   //\r
   // Collect data on BSP\r
   //\r
-  CollectProcessorData (NULL);\r
+  CollectProcessorData (CpuFeaturesData);\r
 \r
   AnalysisProcessorFeatures (NumberOfCpus);\r
 }\r
 \r
-/**\r
-  Performs CPU features Initialization.\r
-\r
-  This service will invoke MP service to perform CPU features\r
-  initialization on BSP/APs per user configuration.\r
-\r
-  @note This service could be called by BSP only.\r
-**/\r
-VOID\r
-EFIAPI\r
-CpuFeaturesInitialize (\r
-  VOID\r
-  )\r
-{\r
-  CPU_FEATURES_DATA      *CpuFeaturesData;\r
-  UINTN                  OldBspNumber;\r
-\r
-  CpuFeaturesData = GetCpuFeaturesData ();\r
-\r
-  OldBspNumber = GetProcessorIndex();\r
-  CpuFeaturesData->BspNumber = OldBspNumber;\r
-  //\r
-  // Wakeup all APs for programming.\r
-  //\r
-  StartupAPsWorker (SetProcessorRegister);\r
-  //\r
-  // Programming BSP\r
-  //\r
-  SetProcessorRegister (NULL);\r
-  //\r
-  // Switch to new BSP if required\r
-  //\r
-  if (CpuFeaturesData->BspNumber != OldBspNumber) {\r
-    SwitchNewBsp (CpuFeaturesData->BspNumber);\r
-  }\r
-}\r
index 1f34a3f48937d5b381c1f2a01eb3118c2f088f63..926698dc95e0ca1bbf69aeafafa39df9e6d4f2ba 100644 (file)
@@ -15,6 +15,7 @@
 #include <PiDxe.h>\r
 \r
 #include <Library/UefiBootServicesTableLib.h>\r
+#include <Library/UefiLib.h>\r
 \r
 #include "RegisterCpuFeatures.h"\r
 \r
@@ -115,14 +116,20 @@ GetProcessorInformation (
 \r
   @param[in]  Procedure               A pointer to the function to be run on\r
                                       enabled APs of the system.\r
+  @param[in]  MpEvent                 A pointer to the event to be used later\r
+                                      to check whether procedure has done.\r
 **/\r
 VOID\r
 StartupAPsWorker (\r
-  IN  EFI_AP_PROCEDURE                 Procedure\r
+  IN  EFI_AP_PROCEDURE                 Procedure,\r
+  IN  EFI_EVENT                        MpEvent\r
   )\r
 {\r
   EFI_STATUS                           Status;\r
   EFI_MP_SERVICES_PROTOCOL             *MpServices;\r
+  CPU_FEATURES_DATA                    *CpuFeaturesData;\r
+\r
+  CpuFeaturesData = GetCpuFeaturesData ();\r
 \r
   MpServices = GetMpProtocol ();\r
   //\r
@@ -132,9 +139,9 @@ StartupAPsWorker (
                  MpServices,\r
                  Procedure,\r
                  FALSE,\r
-                 NULL,\r
+                 MpEvent,\r
                  0,\r
-                 NULL,\r
+                 CpuFeaturesData,\r
                  NULL\r
                  );\r
   ASSERT_EFI_ERROR (Status);\r
@@ -197,3 +204,61 @@ GetNumberOfProcessor (
   ASSERT_EFI_ERROR (Status);\r
 }\r
 \r
+/**\r
+  Performs CPU features Initialization.\r
+\r
+  This service will invoke MP service to perform CPU features\r
+  initialization on BSP/APs per user configuration.\r
+\r
+  @note This service could be called by BSP only.\r
+**/\r
+VOID\r
+EFIAPI\r
+CpuFeaturesInitialize (\r
+  VOID\r
+  )\r
+{\r
+  CPU_FEATURES_DATA          *CpuFeaturesData;\r
+  UINTN                      OldBspNumber;\r
+  EFI_EVENT                  MpEvent;\r
+  EFI_STATUS                 Status;\r
+\r
+  CpuFeaturesData = GetCpuFeaturesData ();\r
+\r
+  OldBspNumber = GetProcessorIndex();\r
+  CpuFeaturesData->BspNumber = OldBspNumber;\r
+\r
+  Status = gBS->CreateEvent (\r
+                  EVT_NOTIFY_WAIT,\r
+                  TPL_CALLBACK,\r
+                  EfiEventEmptyFunction,\r
+                  NULL,\r
+                  &MpEvent\r
+                  );\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Wakeup all APs for programming.\r
+  //\r
+  StartupAPsWorker (SetProcessorRegister, MpEvent);\r
+  //\r
+  // Programming BSP\r
+  //\r
+  SetProcessorRegister (CpuFeaturesData);\r
+\r
+  //\r
+  // Wait all processors to finish the task.\r
+  //\r
+  do {\r
+    Status = gBS->CheckEvent (MpEvent);\r
+  } while (Status == EFI_NOT_READY);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
+  //\r
+  // Switch to new BSP if required\r
+  //\r
+  if (CpuFeaturesData->BspNumber != OldBspNumber) {\r
+    SwitchNewBsp (CpuFeaturesData->BspNumber);\r
+  }\r
+}\r
+\r
index f0f317c945c9c2c49ad1f6bc5476ae912ce78743..362e0c6cd13cdcd4391a53e53dec97a44a756433 100644 (file)
@@ -47,6 +47,8 @@
   SynchronizationLib\r
   UefiBootServicesTableLib\r
   IoLib\r
+  UefiBootServicesTableLib\r
+  UefiLib\r
 \r
 [Protocols]\r
   gEfiMpServiceProtocolGuid                                            ## CONSUMES\r
index 82fe268812af64e35ffe35f36264610e5b7c0510..a688e03152bd07a75b671d65a9a2f5772e85527c 100644 (file)
@@ -149,11 +149,15 @@ GetProcessorInformation (
 **/\r
 VOID\r
 StartupAPsWorker (\r
-  IN  EFI_AP_PROCEDURE                 Procedure\r
+  IN  EFI_AP_PROCEDURE                 Procedure,\r
+  IN  EFI_EVENT                        MpEvent\r
   )\r
 {\r
   EFI_STATUS                           Status;\r
   EFI_PEI_MP_SERVICES_PPI              *CpuMpPpi;\r
+  CPU_FEATURES_DATA                    *CpuFeaturesData;\r
+\r
+  CpuFeaturesData = GetCpuFeaturesData ();\r
 \r
   //\r
   // Get MP Services Protocol\r
@@ -175,7 +179,7 @@ StartupAPsWorker (
                  Procedure,\r
                  FALSE,\r
                  0,\r
-                 NULL\r
+                 CpuFeaturesData\r
                  );\r
   ASSERT_EFI_ERROR (Status);\r
 }\r
@@ -257,3 +261,50 @@ GetNumberOfProcessor (
                          );\r
   ASSERT_EFI_ERROR (Status);\r
 }\r
+\r
+/**\r
+  Performs CPU features Initialization.\r
+\r
+  This service will invoke MP service to perform CPU features\r
+  initialization on BSP/APs per user configuration.\r
+\r
+  @note This service could be called by BSP only.\r
+**/\r
+VOID\r
+EFIAPI\r
+CpuFeaturesInitialize (\r
+  VOID\r
+  )\r
+{\r
+  CPU_FEATURES_DATA          *CpuFeaturesData;\r
+  UINTN                      OldBspNumber;\r
+\r
+  CpuFeaturesData = GetCpuFeaturesData ();\r
+\r
+  OldBspNumber = GetProcessorIndex();\r
+  CpuFeaturesData->BspNumber = OldBspNumber;\r
+\r
+  //\r
+  // Known limitation: In PEI phase, CpuFeatures driver not\r
+  // support async mode execute tasks. So semaphore type\r
+  // register can't been used for this instance, must use\r
+  // DXE type instance.\r
+  //\r
+\r
+  //\r
+  // Wakeup all APs for programming.\r
+  //\r
+  StartupAPsWorker (SetProcessorRegister, NULL);\r
+  //\r
+  // Programming BSP\r
+  //\r
+  SetProcessorRegister (CpuFeaturesData);\r
+\r
+  //\r
+  // Switch to new BSP if required\r
+  //\r
+  if (CpuFeaturesData->BspNumber != OldBspNumber) {\r
+    SwitchNewBsp (CpuFeaturesData->BspNumber);\r
+  }\r
+}\r
+\r
index edd266934fd0ddb994ed698c92cc399dc7e7937a..42a3f91fbfe4aeb6352f4015f7c26e2103e935c4 100644 (file)
@@ -23,6 +23,7 @@
 #include <Library/MemoryAllocationLib.h>\r
 #include <Library/SynchronizationLib.h>\r
 #include <Library/IoLib.h>\r
+#include <Library/LocalApicLib.h>\r
 \r
 #include <AcpiCpuData.h>\r
 \r
@@ -46,16 +47,27 @@ typedef struct {
   CPU_FEATURE_INITIALIZE       InitializeFunc;\r
   UINT8                        *BeforeFeatureBitMask;\r
   UINT8                        *AfterFeatureBitMask;\r
+  UINT8                        *CoreBeforeFeatureBitMask;\r
+  UINT8                        *CoreAfterFeatureBitMask;\r
+  UINT8                        *PackageBeforeFeatureBitMask;\r
+  UINT8                        *PackageAfterFeatureBitMask;\r
   VOID                         *ConfigData;\r
   BOOLEAN                      BeforeAll;\r
   BOOLEAN                      AfterAll;\r
 } CPU_FEATURES_ENTRY;\r
 \r
+//\r
+// Flags used when program the register.\r
+//\r
+typedef struct {\r
+  volatile UINTN           ConsoleLogLock;       // Spinlock used to control console.\r
+  volatile UINTN           MemoryMappedLock;     // Spinlock used to program mmio\r
+  volatile UINT32          *SemaphoreCount;      // Semaphore used to program semaphore.\r
+} PROGRAM_CPU_REGISTER_FLAGS;\r
+\r
 typedef struct {\r
   UINTN                    FeaturesCount;\r
   UINT32                   BitMaskSize;\r
-  SPIN_LOCK                MsrLock;\r
-  SPIN_LOCK                MemoryMappedLock;\r
   LIST_ENTRY               FeatureList;\r
 \r
   CPU_FEATURES_INIT_ORDER  *InitOrder;\r
@@ -64,9 +76,14 @@ typedef struct {
   UINT8                    *ConfigurationPcd;\r
   UINT8                    *SettingPcd;\r
 \r
+  UINT32                   NumberOfCpus;\r
+  ACPI_CPU_DATA            *AcpiCpuData;\r
+\r
   CPU_REGISTER_TABLE       *RegisterTable;\r
   CPU_REGISTER_TABLE       *PreSmmRegisterTable;\r
   UINTN                    BspNumber;\r
+\r
+  PROGRAM_CPU_REGISTER_FLAGS  CpuFlags;\r
 } CPU_FEATURES_DATA;\r
 \r
 #define CPU_FEATURE_ENTRY_FROM_LINK(a) \\r
@@ -118,10 +135,13 @@ GetProcessorInformation (
 \r
   @param[in]  Procedure               A pointer to the function to be run on\r
                                       enabled APs of the system.\r
+  @param[in]  MpEvent                 A pointer to the event to be used later\r
+                                      to check whether procedure has done.\r
 **/\r
 VOID\r
 StartupAPsWorker (\r
-  IN  EFI_AP_PROCEDURE                 Procedure\r
+  IN  EFI_AP_PROCEDURE                 Procedure,\r
+  IN  EFI_EVENT                        MpEvent\r
   );\r
 \r
 /**\r
@@ -170,4 +190,40 @@ DumpCpuFeature (
   IN CPU_FEATURES_ENTRY  *CpuFeature\r
   );\r
 \r
+/**\r
+  Return feature dependence result.\r
+\r
+  @param[in]  CpuFeature        Pointer to CPU feature.\r
+  @param[in]  Before            Check before dependence or after.\r
+\r
+  @retval     return the dependence result.\r
+**/\r
+CPU_FEATURE_DEPENDENCE_TYPE\r
+DetectFeatureScope (\r
+  IN CPU_FEATURES_ENTRY         *CpuFeature,\r
+  IN BOOLEAN                    Before\r
+  );\r
+\r
+/**\r
+  Programs registers for the calling processor.\r
+\r
+  @param[in,out] Buffer  The pointer to private data buffer.\r
+\r
+**/\r
+VOID\r
+EFIAPI\r
+SetProcessorRegister (\r
+  IN OUT VOID            *Buffer\r
+  );\r
+\r
+/**\r
+  Return ACPI_CPU_DATA data.\r
+\r
+  @return  Pointer to ACPI_CPU_DATA data.\r
+**/\r
+ACPI_CPU_DATA *\r
+GetAcpiCpuData (\r
+  VOID\r
+  );\r
+\r
 #endif\r
index fa7e107e39c0ac95dd1448cc6efb3fba9beb87ae..5b49bc450494cca3815894525b74192664bb8ff1 100644 (file)
@@ -112,6 +112,302 @@ IsBitMaskMatchCheck (
   return FALSE;\r
 }\r
 \r
+/**\r
+  Return feature dependence result.\r
+\r
+  @param[in]  CpuFeature        Pointer to CPU feature.\r
+  @param[in]  Before            Check before dependence or after.\r
+\r
+  @retval     return the dependence result.\r
+**/\r
+CPU_FEATURE_DEPENDENCE_TYPE\r
+DetectFeatureScope (\r
+  IN CPU_FEATURES_ENTRY         *CpuFeature,\r
+  IN BOOLEAN                    Before\r
+  )\r
+{\r
+  if (Before) {\r
+    if (CpuFeature->PackageBeforeFeatureBitMask != NULL) {\r
+      return PackageDepType;\r
+    }\r
+\r
+    if (CpuFeature->CoreBeforeFeatureBitMask != NULL) {\r
+      return CoreDepType;\r
+    }\r
+\r
+    if (CpuFeature->BeforeFeatureBitMask != NULL) {\r
+      return ThreadDepType;\r
+    }\r
+\r
+    return NoneDepType;\r
+  }\r
+\r
+  if (CpuFeature->PackageAfterFeatureBitMask != NULL) {\r
+    return PackageDepType;\r
+  }\r
+\r
+  if (CpuFeature->CoreAfterFeatureBitMask != NULL) {\r
+    return CoreDepType;\r
+  }\r
+\r
+  if (CpuFeature->AfterFeatureBitMask != NULL) {\r
+    return ThreadDepType;\r
+  }\r
+\r
+  return NoneDepType;\r
+}\r
+\r
+/**\r
+  Clear dependence for the specified type.\r
+\r
+  @param[in]  CurrentFeature     Cpu feature need to clear.\r
+  @param[in]  Before             Before or after dependence relationship.\r
+\r
+**/\r
+VOID\r
+ClearFeatureScope (\r
+  IN CPU_FEATURES_ENTRY           *CpuFeature,\r
+  IN BOOLEAN                      Before\r
+  )\r
+{\r
+  if (Before) {\r
+    if (CpuFeature->BeforeFeatureBitMask != NULL) {\r
+      FreePool (CpuFeature->BeforeFeatureBitMask);\r
+      CpuFeature->BeforeFeatureBitMask = NULL;\r
+    }\r
+    if (CpuFeature->CoreBeforeFeatureBitMask != NULL) {\r
+      FreePool (CpuFeature->CoreBeforeFeatureBitMask);\r
+      CpuFeature->CoreBeforeFeatureBitMask = NULL;\r
+    }\r
+    if (CpuFeature->PackageBeforeFeatureBitMask != NULL) {\r
+      FreePool (CpuFeature->PackageBeforeFeatureBitMask);\r
+      CpuFeature->PackageBeforeFeatureBitMask = NULL;\r
+    }\r
+  } else {\r
+    if (CpuFeature->PackageAfterFeatureBitMask != NULL) {\r
+      FreePool (CpuFeature->PackageAfterFeatureBitMask);\r
+      CpuFeature->PackageAfterFeatureBitMask = NULL;\r
+    }\r
+    if (CpuFeature->CoreAfterFeatureBitMask != NULL) {\r
+      FreePool (CpuFeature->CoreAfterFeatureBitMask);\r
+      CpuFeature->CoreAfterFeatureBitMask = NULL;\r
+    }\r
+    if (CpuFeature->AfterFeatureBitMask != NULL) {\r
+      FreePool (CpuFeature->AfterFeatureBitMask);\r
+      CpuFeature->AfterFeatureBitMask = NULL;\r
+    }\r
+  }\r
+}\r
+\r
+/**\r
+  Base on dependence relationship to asjust feature dependence.\r
+\r
+  ONLY when the feature before(or after) the find feature also has \r
+  dependence with the find feature. In this case, driver need to base\r
+  on dependce relationship to decide how to insert current feature and\r
+  adjust the feature dependence.\r
+\r
+  @param[in]  PreviousFeature    CPU feature current before the find one.\r
+  @param[in]  CurrentFeature     Cpu feature need to adjust.\r
+  @param[in]  Before             Before or after dependence relationship.\r
+\r
+  @retval   TRUE   means the current feature dependence has been adjusted.\r
+\r
+  @retval   FALSE  means the previous feature dependence has been adjusted.\r
+                   or previous feature has no dependence with the find one.\r
+\r
+**/\r
+BOOLEAN\r
+AdjustFeaturesDependence (\r
+  IN OUT CPU_FEATURES_ENTRY         *PreviousFeature,\r
+  IN OUT CPU_FEATURES_ENTRY         *CurrentFeature,\r
+  IN     BOOLEAN                    Before\r
+  )\r
+{\r
+  CPU_FEATURE_DEPENDENCE_TYPE            PreDependType;\r
+  CPU_FEATURE_DEPENDENCE_TYPE            CurrentDependType;\r
+\r
+  PreDependType     = DetectFeatureScope(PreviousFeature, Before);\r
+  CurrentDependType = DetectFeatureScope(CurrentFeature, Before);\r
+\r
+  //\r
+  // If previous feature has no dependence with the find featue.\r
+  // return FALSE.\r
+  //\r
+  if (PreDependType == NoneDepType) {\r
+    return FALSE;\r
+  }\r
+\r
+  //\r
+  // If both feature have dependence, keep the one which needs use more \r
+  // processors and clear the dependence for the other one.\r
+  //\r
+  if (PreDependType >= CurrentDependType) {\r
+    ClearFeatureScope (CurrentFeature, Before);\r
+    return TRUE;\r
+  } else {\r
+    ClearFeatureScope (PreviousFeature, Before);\r
+    return FALSE;\r
+  }\r
+}\r
+\r
+/**\r
+  Base on dependence relationship to asjust feature order.\r
+\r
+  @param[in]  FeatureList        Pointer to CPU feature list\r
+  @param[in]  FindEntry          The entry this feature depend on.\r
+  @param[in]  CurrentEntry       The entry for this feature.\r
+  @param[in]  Before             Before or after dependence relationship.\r
+\r
+**/\r
+VOID\r
+AdjustEntry (\r
+  IN      LIST_ENTRY                *FeatureList,\r
+  IN OUT  LIST_ENTRY                *FindEntry,\r
+  IN OUT  LIST_ENTRY                *CurrentEntry,\r
+  IN      BOOLEAN                   Before\r
+  )\r
+{\r
+  LIST_ENTRY                *PreviousEntry;\r
+  CPU_FEATURES_ENTRY        *PreviousFeature;\r
+  CPU_FEATURES_ENTRY        *CurrentFeature;\r
+\r
+  //\r
+  // For CPU feature which has core or package type dependence, later code need to insert\r
+  // AcquireSpinLock/ReleaseSpinLock logic to sequency the execute order.\r
+  // So if driver finds both feature A and B need to execute before feature C, driver will\r
+  // base on dependence type of feature A and B to update the logic here.\r
+  // For example, feature A has package type dependence and feature B has core type dependence,\r
+  // because package type dependence need to wait for more processors which has strong dependence\r
+  // than core type dependence. So driver will adjust the feature order to B -> A -> C. and driver \r
+  // will remove the feature dependence in feature B. \r
+  // Driver just needs to make sure before feature C been executed, feature A has finished its task\r
+  // in all all thread. Feature A finished in all threads also means feature B have finshed in all\r
+  // threads.\r
+  //\r
+  if (Before) {\r
+    PreviousEntry = GetPreviousNode (FeatureList, FindEntry);\r
+  } else {\r\r
+    PreviousEntry = GetNextNode (FeatureList, FindEntry);\r
+  }\r
+\r
+  CurrentFeature  = CPU_FEATURE_ENTRY_FROM_LINK (CurrentEntry);\r
+  RemoveEntryList (CurrentEntry);\r
+\r
+  if (IsNull (FeatureList, PreviousEntry)) {\r
+    //\r
+    // If not exist the previous or next entry, just insert the current entry.\r
+    //\r
+    if (Before) {\r
+      InsertTailList (FindEntry, CurrentEntry);\r
+    } else {\r
+      InsertHeadList (FindEntry, CurrentEntry);\r
+    }\r
+  } else {\r
+    //\r
+    // If exist the previous or next entry, need to check it before insert curent entry.\r
+    //\r
+    PreviousFeature = CPU_FEATURE_ENTRY_FROM_LINK (PreviousEntry);\r
+\r
+    if (AdjustFeaturesDependence (PreviousFeature, CurrentFeature, Before)) {\r
+      //\r
+      // Return TRUE means current feature dependence has been cleared and the previous\r
+      // feature dependence has been kept and used. So insert current feature before (or after)\r
+      // the previous feature.\r
+      //\r
+      if (Before) {\r
+        InsertTailList (PreviousEntry, CurrentEntry);\r
+      } else {\r
+        InsertHeadList (PreviousEntry, CurrentEntry);\r
+      }\r
+    } else {\r
+      if (Before) {\r
+        InsertTailList (FindEntry, CurrentEntry);\r
+      } else {\r
+        InsertHeadList (FindEntry, CurrentEntry);\r
+      }\r
+    }\r
+  }\r
+}\r\r
+\r
+/**\r
+  Checks and adjusts current CPU features per dependency relationship.\r
+\r
+  @param[in]  FeatureList        Pointer to CPU feature list\r
+  @param[in]  CurrentEntry       Pointer to current checked CPU feature\r
+  @param[in]  FeatureMask        The feature bit mask.\r
+\r
+  @retval     return Swapped info.\r
+**/\r
+BOOLEAN\r
+InsertToBeforeEntry (\r
+  IN LIST_ENTRY              *FeatureList,\r
+  IN LIST_ENTRY              *CurrentEntry,\r
+  IN UINT8                   *FeatureMask\r
+  )\r
+{\r
+  LIST_ENTRY                 *CheckEntry;\r
+  CPU_FEATURES_ENTRY         *CheckFeature;\r
+  BOOLEAN                    Swapped;\r
+\r
+  Swapped = FALSE;\r
+\r
+  //\r
+  // Check all features dispatched before this entry\r
+  //\r
+  CheckEntry = GetFirstNode (FeatureList);\r
+  while (CheckEntry != CurrentEntry) {\r
+    CheckFeature = CPU_FEATURE_ENTRY_FROM_LINK (CheckEntry);\r
+    if (IsBitMaskMatchCheck (CheckFeature->FeatureMask, FeatureMask)) {\r
+      AdjustEntry (FeatureList, CheckEntry, CurrentEntry, TRUE);\r
+      Swapped = TRUE;\r
+      break;\r
+    }\r
+    CheckEntry = CheckEntry->ForwardLink;\r
+  }\r
+\r
+  return Swapped;\r
+}\r
+\r
+/**\r
+  Checks and adjusts current CPU features per dependency relationship.\r
+\r
+  @param[in]  FeatureList        Pointer to CPU feature list\r
+  @param[in]  CurrentEntry       Pointer to current checked CPU feature\r
+  @param[in]  FeatureMask        The feature bit mask.\r
+\r
+  @retval     return Swapped info.\r
+**/\r
+BOOLEAN\r
+InsertToAfterEntry (\r
+  IN LIST_ENTRY              *FeatureList,\r
+  IN LIST_ENTRY              *CurrentEntry,\r
+  IN UINT8                   *FeatureMask\r
+  )\r
+{\r
+  LIST_ENTRY                 *CheckEntry;\r
+  CPU_FEATURES_ENTRY         *CheckFeature;\r
+  BOOLEAN                    Swapped;\r
+\r
+  Swapped = FALSE;\r
+\r
+  //\r
+  // Check all features dispatched after this entry\r
+  //\r
+  CheckEntry = GetNextNode (FeatureList, CurrentEntry);\r
+  while (!IsNull (FeatureList, CheckEntry)) {\r
+    CheckFeature = CPU_FEATURE_ENTRY_FROM_LINK (CheckEntry);\r
+    if (IsBitMaskMatchCheck (CheckFeature->FeatureMask, FeatureMask)) {\r
+      AdjustEntry (FeatureList, CheckEntry, CurrentEntry, FALSE);\r
+      Swapped = TRUE;\r
+      break;\r
+    }\r
+    CheckEntry = CheckEntry->ForwardLink;\r
+  }\r
+\r
+  return Swapped;\r
+}\r
+\r
 /**\r
   Checks and adjusts CPU features order per dependency relationship.\r
 \r
@@ -128,11 +424,13 @@ CheckCpuFeaturesDependency (
   CPU_FEATURES_ENTRY         *CheckFeature;\r
   BOOLEAN                    Swapped;\r
   LIST_ENTRY                 *TempEntry;\r
+  LIST_ENTRY                 *NextEntry;\r
 \r
   CurrentEntry = GetFirstNode (FeatureList);\r
   while (!IsNull (FeatureList, CurrentEntry)) {\r
     Swapped = FALSE;\r
     CpuFeature = CPU_FEATURE_ENTRY_FROM_LINK (CurrentEntry);\r
+    NextEntry = CurrentEntry->ForwardLink;\r
     if (CpuFeature->BeforeAll) {\r
       //\r
       // Check all features dispatched before this entry\r
@@ -153,6 +451,7 @@ CheckCpuFeaturesDependency (
         CheckEntry = CheckEntry->ForwardLink;\r
       }\r
       if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
         continue;\r
       }\r
     }\r
@@ -179,60 +478,59 @@ CheckCpuFeaturesDependency (
         CheckEntry = CheckEntry->ForwardLink;\r
       }\r
       if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
         continue;\r
       }\r
     }\r
 \r
     if (CpuFeature->BeforeFeatureBitMask != NULL) {\r
-      //\r
-      // Check all features dispatched before this entry\r
-      //\r
-      CheckEntry = GetFirstNode (FeatureList);\r
-      while (CheckEntry != CurrentEntry) {\r
-        CheckFeature = CPU_FEATURE_ENTRY_FROM_LINK (CheckEntry);\r
-        if (IsBitMaskMatchCheck (CheckFeature->FeatureMask, CpuFeature->BeforeFeatureBitMask)) {\r
-          //\r
-          // If there is dependency, swap them\r
-          //\r
-          RemoveEntryList (CurrentEntry);\r
-          InsertTailList (CheckEntry, CurrentEntry);\r
-          Swapped = TRUE;\r
-          break;\r
-        }\r
-        CheckEntry = CheckEntry->ForwardLink;\r
-      }\r
+      Swapped = InsertToBeforeEntry (FeatureList, CurrentEntry, CpuFeature->BeforeFeatureBitMask);\r
       if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
         continue;\r
       }\r
     }\r
 \r
     if (CpuFeature->AfterFeatureBitMask != NULL) {\r
-      //\r
-      // Check all features dispatched after this entry\r
-      //\r
-      CheckEntry = GetNextNode (FeatureList, CurrentEntry);\r
-      while (!IsNull (FeatureList, CheckEntry)) {\r
-        CheckFeature = CPU_FEATURE_ENTRY_FROM_LINK (CheckEntry);\r
-        if (IsBitMaskMatchCheck (CheckFeature->FeatureMask, CpuFeature->AfterFeatureBitMask)) {\r
-          //\r
-          // If there is dependency, swap them\r
-          //\r
-          TempEntry = GetNextNode (FeatureList, CurrentEntry);\r
-          RemoveEntryList (CurrentEntry);\r
-          InsertHeadList (CheckEntry, CurrentEntry);\r
-          CurrentEntry = TempEntry;\r
-          Swapped = TRUE;\r
-          break;\r
-        }\r
-        CheckEntry = CheckEntry->ForwardLink;\r
+      Swapped = InsertToAfterEntry (FeatureList, CurrentEntry, CpuFeature->AfterFeatureBitMask);\r
+      if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
+        continue;\r
+      }\r
+    }\r
+\r
+    if (CpuFeature->CoreBeforeFeatureBitMask != NULL) {\r
+      Swapped = InsertToBeforeEntry (FeatureList, CurrentEntry, CpuFeature->CoreBeforeFeatureBitMask);\r
+      if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
+        continue;\r
       }\r
+    }\r
+\r
+    if (CpuFeature->CoreAfterFeatureBitMask != NULL) {\r
+      Swapped = InsertToAfterEntry (FeatureList, CurrentEntry, CpuFeature->CoreAfterFeatureBitMask);\r
       if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
         continue;\r
       }\r
     }\r
-    //\r
-    // No swap happened, check the next feature\r
-    //\r
+\r
+    if (CpuFeature->PackageBeforeFeatureBitMask != NULL) {\r
+      Swapped = InsertToBeforeEntry (FeatureList, CurrentEntry, CpuFeature->PackageBeforeFeatureBitMask);\r
+      if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
+        continue;\r
+      }\r
+    }\r
+\r
+    if (CpuFeature->PackageAfterFeatureBitMask != NULL) {\r
+      Swapped = InsertToAfterEntry (FeatureList, CurrentEntry, CpuFeature->PackageAfterFeatureBitMask);\r
+      if (Swapped) {\r
+        CurrentEntry = NextEntry;\r
+        continue;\r
+      }\r
+    }\r
+\r
     CurrentEntry = CurrentEntry->ForwardLink;\r
   }\r
 }\r
@@ -265,8 +563,8 @@ RegisterCpuFeatureWorker (
   CpuFeaturesData = GetCpuFeaturesData ();\r
   if (CpuFeaturesData->FeaturesCount == 0) {\r
     InitializeListHead (&CpuFeaturesData->FeatureList);\r
-    InitializeSpinLock (&CpuFeaturesData->MsrLock);\r
-    InitializeSpinLock (&CpuFeaturesData->MemoryMappedLock);\r
+    InitializeSpinLock (&CpuFeaturesData->CpuFlags.MemoryMappedLock);\r
+    InitializeSpinLock (&CpuFeaturesData->CpuFlags.ConsoleLogLock);\r
     CpuFeaturesData->BitMaskSize = (UINT32) BitMaskSize;\r
   }\r
   ASSERT (CpuFeaturesData->BitMaskSize == BitMaskSize);\r
@@ -328,6 +626,31 @@ RegisterCpuFeatureWorker (
       }\r
       CpuFeatureEntry->AfterFeatureBitMask = CpuFeature->AfterFeatureBitMask;\r
     }\r
+    if (CpuFeature->CoreBeforeFeatureBitMask != NULL) {\r
+      if (CpuFeatureEntry->CoreBeforeFeatureBitMask != NULL) {\r
+        FreePool (CpuFeatureEntry->CoreBeforeFeatureBitMask);\r
+      }\r
+      CpuFeatureEntry->CoreBeforeFeatureBitMask = CpuFeature->CoreBeforeFeatureBitMask;\r
+    }\r
+    if (CpuFeature->CoreAfterFeatureBitMask != NULL) {\r
+      if (CpuFeatureEntry->CoreAfterFeatureBitMask != NULL) {\r
+        FreePool (CpuFeatureEntry->CoreAfterFeatureBitMask);\r
+      }\r
+      CpuFeatureEntry->CoreAfterFeatureBitMask = CpuFeature->CoreAfterFeatureBitMask;\r
+    }\r
+    if (CpuFeature->PackageBeforeFeatureBitMask != NULL) {\r
+      if (CpuFeatureEntry->PackageBeforeFeatureBitMask != NULL) {\r
+        FreePool (CpuFeatureEntry->PackageBeforeFeatureBitMask);\r
+      }\r
+      CpuFeatureEntry->PackageBeforeFeatureBitMask = CpuFeature->PackageBeforeFeatureBitMask;\r
+    }\r
+    if (CpuFeature->PackageAfterFeatureBitMask != NULL) {\r
+      if (CpuFeatureEntry->PackageAfterFeatureBitMask != NULL) {\r
+        FreePool (CpuFeatureEntry->PackageAfterFeatureBitMask);\r
+      }\r
+      CpuFeatureEntry->PackageAfterFeatureBitMask = CpuFeature->PackageAfterFeatureBitMask;\r
+    }\r
+\r
     CpuFeatureEntry->BeforeAll = CpuFeature->BeforeAll;\r
     CpuFeatureEntry->AfterAll  = CpuFeature->AfterAll;\r
 \r
@@ -410,6 +733,8 @@ SetCpuFeaturesBitMask (
   @retval  RETURN_UNSUPPORTED       Registration of the CPU feature is not\r
                                     supported due to a circular dependency between\r
                                     BEFORE and AFTER features.\r
+  @retval  RETURN_NOT_READY         CPU feature PCD PcdCpuFeaturesUserConfiguration\r
+                                    not updated by Platform driver yet.\r
 \r
   @note This service could be called by BSP only.\r
 **/\r
@@ -431,12 +756,20 @@ RegisterCpuFeature (
   UINT8                      *FeatureMask;\r
   UINT8                      *BeforeFeatureBitMask;\r
   UINT8                      *AfterFeatureBitMask;\r
+  UINT8                      *CoreBeforeFeatureBitMask;\r
+  UINT8                      *CoreAfterFeatureBitMask;\r
+  UINT8                      *PackageBeforeFeatureBitMask;\r
+  UINT8                      *PackageAfterFeatureBitMask;\r
   BOOLEAN                    BeforeAll;\r
   BOOLEAN                    AfterAll;\r
 \r
-  FeatureMask          = NULL;\r
-  BeforeFeatureBitMask = NULL;\r
-  AfterFeatureBitMask  = NULL;\r
+  FeatureMask                 = NULL;\r
+  BeforeFeatureBitMask        = NULL;\r
+  AfterFeatureBitMask         = NULL;\r
+  CoreBeforeFeatureBitMask    = NULL;\r
+  CoreAfterFeatureBitMask     = NULL;\r
+  PackageBeforeFeatureBitMask = NULL;\r
+  PackageAfterFeatureBitMask  = NULL;\r
   BeforeAll            = FALSE;\r
   AfterAll             = FALSE;\r
 \r
@@ -449,6 +782,10 @@ RegisterCpuFeature (
                     != (CPU_FEATURE_BEFORE | CPU_FEATURE_AFTER));\r
     ASSERT ((Feature & (CPU_FEATURE_BEFORE_ALL | CPU_FEATURE_AFTER_ALL))\r
                     != (CPU_FEATURE_BEFORE_ALL | CPU_FEATURE_AFTER_ALL));\r
+    ASSERT ((Feature & (CPU_FEATURE_CORE_BEFORE | CPU_FEATURE_CORE_AFTER))\r
+                    != (CPU_FEATURE_CORE_BEFORE | CPU_FEATURE_CORE_AFTER));\r
+    ASSERT ((Feature & (CPU_FEATURE_PACKAGE_BEFORE | CPU_FEATURE_PACKAGE_AFTER))\r
+                    != (CPU_FEATURE_PACKAGE_BEFORE | CPU_FEATURE_PACKAGE_AFTER));\r
     if (Feature < CPU_FEATURE_BEFORE) {\r
       BeforeAll = ((Feature & CPU_FEATURE_BEFORE_ALL) != 0) ? TRUE : FALSE;\r
       AfterAll  = ((Feature & CPU_FEATURE_AFTER_ALL) != 0) ? TRUE : FALSE;\r
@@ -459,6 +796,14 @@ RegisterCpuFeature (
       SetCpuFeaturesBitMask (&BeforeFeatureBitMask, Feature & ~CPU_FEATURE_BEFORE, BitMaskSize);\r
     } else if ((Feature & CPU_FEATURE_AFTER) != 0) {\r
       SetCpuFeaturesBitMask (&AfterFeatureBitMask, Feature & ~CPU_FEATURE_AFTER, BitMaskSize);\r
+    } else if ((Feature & CPU_FEATURE_CORE_BEFORE) != 0) {\r
+      SetCpuFeaturesBitMask (&CoreBeforeFeatureBitMask, Feature & ~CPU_FEATURE_CORE_BEFORE, BitMaskSize);\r
+    } else if ((Feature & CPU_FEATURE_CORE_AFTER) != 0) {\r
+      SetCpuFeaturesBitMask (&CoreAfterFeatureBitMask, Feature & ~CPU_FEATURE_CORE_AFTER, BitMaskSize);\r
+    } else if ((Feature & CPU_FEATURE_PACKAGE_BEFORE) != 0) {\r
+      SetCpuFeaturesBitMask (&PackageBeforeFeatureBitMask, Feature & ~CPU_FEATURE_PACKAGE_BEFORE, BitMaskSize);\r
+    } else if ((Feature & CPU_FEATURE_PACKAGE_AFTER) != 0) {\r
+      SetCpuFeaturesBitMask (&PackageAfterFeatureBitMask, Feature & ~CPU_FEATURE_PACKAGE_AFTER, BitMaskSize);\r
     }\r
     Feature = VA_ARG (Marker, UINT32);\r
   }\r
@@ -466,15 +811,19 @@ RegisterCpuFeature (
 \r
   CpuFeature = AllocateZeroPool (sizeof (CPU_FEATURES_ENTRY));\r
   ASSERT (CpuFeature != NULL);\r
-  CpuFeature->Signature            = CPU_FEATURE_ENTRY_SIGNATURE;\r
-  CpuFeature->FeatureMask          = FeatureMask;\r
-  CpuFeature->BeforeFeatureBitMask = BeforeFeatureBitMask;\r
-  CpuFeature->AfterFeatureBitMask  = AfterFeatureBitMask;\r
-  CpuFeature->BeforeAll            = BeforeAll;\r
-  CpuFeature->AfterAll             = AfterAll;\r
-  CpuFeature->GetConfigDataFunc    = GetConfigDataFunc;\r
-  CpuFeature->SupportFunc          = SupportFunc;\r
-  CpuFeature->InitializeFunc       = InitializeFunc;\r
+  CpuFeature->Signature                   = CPU_FEATURE_ENTRY_SIGNATURE;\r
+  CpuFeature->FeatureMask                 = FeatureMask;\r
+  CpuFeature->BeforeFeatureBitMask        = BeforeFeatureBitMask;\r
+  CpuFeature->AfterFeatureBitMask         = AfterFeatureBitMask;\r
+  CpuFeature->CoreBeforeFeatureBitMask    = CoreBeforeFeatureBitMask;\r
+  CpuFeature->CoreAfterFeatureBitMask     = CoreAfterFeatureBitMask;\r
+  CpuFeature->PackageBeforeFeatureBitMask = PackageBeforeFeatureBitMask;\r
+  CpuFeature->PackageAfterFeatureBitMask  = PackageAfterFeatureBitMask;\r
+  CpuFeature->BeforeAll                   = BeforeAll;\r
+  CpuFeature->AfterAll                    = AfterAll;\r
+  CpuFeature->GetConfigDataFunc           = GetConfigDataFunc;\r
+  CpuFeature->SupportFunc                 = SupportFunc;\r
+  CpuFeature->InitializeFunc              = InitializeFunc;\r
   if (FeatureName != NULL) {\r
     CpuFeature->FeatureName          = AllocatePool (CPU_FEATURE_NAME_SIZE);\r
     ASSERT (CpuFeature->FeatureName != NULL);\r
@@ -489,13 +838,12 @@ RegisterCpuFeature (
 }\r
 \r
 /**\r
-  Allocates boot service data to save ACPI_CPU_DATA.\r
+  Return ACPI_CPU_DATA data.\r
 \r
-  @return  Pointer to allocated ACPI_CPU_DATA.\r
+  @return  Pointer to ACPI_CPU_DATA data.\r
 **/\r
-STATIC\r
 ACPI_CPU_DATA *\r
-AllocateAcpiCpuData (\r
+GetAcpiCpuData (\r
   VOID\r
   )\r
 {\r
@@ -508,9 +856,20 @@ AllocateAcpiCpuData (
   UINTN                                Index;\r
   EFI_PROCESSOR_INFORMATION            ProcessorInfoBuffer;\r
 \r
+  AcpiCpuData = (ACPI_CPU_DATA *) (UINTN) PcdGet64 (PcdCpuS3DataAddress);\r
+  if (AcpiCpuData != NULL) {\r
+    return AcpiCpuData;\r
+  }\r
+\r
   AcpiCpuData  = AllocatePages (EFI_SIZE_TO_PAGES (sizeof (ACPI_CPU_DATA)));\r
   ASSERT (AcpiCpuData != NULL);\r
 \r
+  //\r
+  // Set PcdCpuS3DataAddress to the base address of the ACPI_CPU_DATA structure\r
+  //\r
+  Status = PcdSet64S (PcdCpuS3DataAddress, (UINT64)(UINTN)AcpiCpuData);\r
+  ASSERT_EFI_ERROR (Status);\r
+\r
   GetNumberOfProcessor (&NumberOfCpus, &NumberOfEnabledProcessors);\r
   AcpiCpuData->NumberOfCpus = (UINT32)NumberOfCpus;\r
 \r
@@ -606,7 +965,6 @@ CpuRegisterTableWriteWorker (
   IN UINT64                  Value\r
   )\r
 {\r
-  EFI_STATUS               Status;\r
   CPU_FEATURES_DATA        *CpuFeaturesData;\r
   ACPI_CPU_DATA            *AcpiCpuData;\r
   CPU_REGISTER_TABLE       *RegisterTable;\r
@@ -614,17 +972,8 @@ CpuRegisterTableWriteWorker (
 \r
   CpuFeaturesData = GetCpuFeaturesData ();\r
   if (CpuFeaturesData->RegisterTable == NULL) {\r
-    AcpiCpuData = (ACPI_CPU_DATA *) (UINTN) PcdGet64 (PcdCpuS3DataAddress);\r
-    if (AcpiCpuData == NULL) {\r
-      AcpiCpuData = AllocateAcpiCpuData ();\r
-      ASSERT (AcpiCpuData != NULL);\r
-      //\r
-      // Set PcdCpuS3DataAddress to the base address of the ACPI_CPU_DATA structure\r
-      //\r
-      Status = PcdSet64S (PcdCpuS3DataAddress, (UINT64)(UINTN)AcpiCpuData);\r
-      ASSERT_EFI_ERROR (Status);\r
-    }\r
-    ASSERT (AcpiCpuData->RegisterTable != 0);\r
+    AcpiCpuData = GetAcpiCpuData ();\r
+    ASSERT ((AcpiCpuData != NULL) && (AcpiCpuData->RegisterTable != 0));\r
     CpuFeaturesData->RegisterTable = (CPU_REGISTER_TABLE *) (UINTN) AcpiCpuData->RegisterTable;\r
     CpuFeaturesData->PreSmmRegisterTable = (CPU_REGISTER_TABLE *) (UINTN) AcpiCpuData->PreSmmInitRegisterTable;\r
   }\r